text
stringlengths 5
1.04M
|
|---|
/*************************************************************************
* Copyright (C) [2019] by Cambricon, Inc. All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 "connector.hpp"
#include <atomic>
#include <vector>
#include "conveyor.hpp"
#include "cnstream_logging.hpp"
namespace cnstream {
Connector::Connector(const size_t conveyor_count, size_t conveyor_capacity) {
conveyor_capacity_ = conveyor_capacity;
conveyors_.reserve(conveyor_count);
fail_times_.reserve(conveyor_count);
for (size_t i = 0; i < conveyor_count; ++i) {
Conveyor* conveyor = new (std::nothrow) Conveyor(conveyor_capacity);
LOGF_IF(CORE, nullptr == conveyor) << "Connector::Connector() new Conveyor failed.";
conveyors_.push_back(conveyor);
}
}
Connector::~Connector() {
for (Conveyor* conveyor : conveyors_) {
delete conveyor;
}
}
const size_t Connector::GetConveyorCount() const {
return conveyors_.size();
}
Conveyor* Connector::GetConveyor(int conveyor_idx) const {
return GetConveyorByIdx(conveyor_idx);
}
size_t Connector::GetConveyorCapacity() const {
return conveyor_capacity_;
}
size_t Connector::GetConveyorSize(int conveyor_idx) const {
return GetConveyor(conveyor_idx)->GetBufferSize();
}
bool Connector::IsConveyorEmpty(int conveyor_idx) const {
return GetConveyor(conveyor_idx)->GetBufferSize() == 0;
}
bool Connector::IsConveyorFull(int conveyor_idx) const {
return GetConveyor(conveyor_idx)->GetBufferSize() >= conveyor_capacity_;
}
CNFrameInfoPtr Connector::PopDataBufferFromConveyor(int conveyor_idx) {
return GetConveyor(conveyor_idx)->PopDataBuffer();
}
bool Connector::PushDataBufferToConveyor(int conveyor_idx, CNFrameInfoPtr data) {
return GetConveyor(conveyor_idx)->PushDataBuffer(data);
}
uint64_t Connector::GetFailTime(int conveyor_idx) const {
return GetConveyor(conveyor_idx)->GetFailTime();
}
bool Connector::IsStopped() {
return stop_.load();
}
void Connector::Start() {
stop_.store(false);
}
void Connector::Stop() {
stop_.store(true);
}
Conveyor* Connector::GetConveyorByIdx(int idx) const {
LOGF_IF(CORE, idx < 0) << "Connector::GetConveyorByIdx() idx < 0.";
LOGF_IF(CORE, idx >= static_cast<int>(conveyors_.size())) << "Connector::GetConveyorByIdx() idx outpace conveyors size";
return conveyors_[idx];
}
void Connector::EmptyDataQueue() {
size_t conveyor_cnt = GetConveyorCount();
for (size_t conveyor_idx = 0; conveyor_idx < conveyor_cnt; ++conveyor_idx) {
GetConveyorByIdx(conveyor_idx)->PopAllDataBuffer();
}
}
} // namespace cnstream
|
/*
* Copyright © 2011 Mozilla Foundation
*
* This program is made available under an ISC-style license. See the
* accompanying file LICENSE for details.
*/
#undef NDEBUG
#include <AudioUnit/AudioUnit.h>
#include <TargetConditionals.h>
#include <assert.h>
#include <mach/mach_time.h>
#include <pthread.h>
#include <stdlib.h>
#if !TARGET_OS_IPHONE
#include <AvailabilityMacros.h>
#include <CoreAudio/AudioHardware.h>
#include <CoreAudio/HostTime.h>
#include <CoreFoundation/CoreFoundation.h>
#endif
#include "cubeb-internal.h"
#include "cubeb/cubeb.h"
#include "cubeb_mixer.h"
#include <AudioToolbox/AudioToolbox.h>
#include <CoreAudio/CoreAudioTypes.h>
#if !TARGET_OS_IPHONE
#include "cubeb_osx_run_loop.h"
#endif
#include "cubeb_resampler.h"
#include "cubeb_ring_array.h"
#include <algorithm>
#include <atomic>
#include <set>
#include <string>
#include <sys/time.h>
#include <vector>
using namespace std;
#if MAC_OS_X_VERSION_MIN_REQUIRED < 101000
typedef UInt32 AudioFormatFlags;
#endif
#define AU_OUT_BUS 0
#define AU_IN_BUS 1
const char * DISPATCH_QUEUE_LABEL = "org.mozilla.cubeb";
const char * PRIVATE_AGGREGATE_DEVICE_NAME = "CubebAggregateDevice";
#ifdef ALOGV
#undef ALOGV
#endif
#define ALOGV(msg, ...) \
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), \
^{ \
LOGV(msg, ##__VA_ARGS__); \
})
#ifdef ALOG
#undef ALOG
#endif
#define ALOG(msg, ...) \
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), \
^{ \
LOG(msg, ##__VA_ARGS__); \
})
/* Testing empirically, some headsets report a minimal latency that is very
* low, but this does not work in practice. Lie and say the minimum is 256
* frames. */
const uint32_t SAFE_MIN_LATENCY_FRAMES = 128;
const uint32_t SAFE_MAX_LATENCY_FRAMES = 512;
const AudioObjectPropertyAddress DEFAULT_INPUT_DEVICE_PROPERTY_ADDRESS = {
kAudioHardwarePropertyDefaultInputDevice, kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster};
const AudioObjectPropertyAddress DEFAULT_OUTPUT_DEVICE_PROPERTY_ADDRESS = {
kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster};
const AudioObjectPropertyAddress DEVICE_IS_ALIVE_PROPERTY_ADDRESS = {
kAudioDevicePropertyDeviceIsAlive, kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster};
const AudioObjectPropertyAddress DEVICES_PROPERTY_ADDRESS = {
kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster};
const AudioObjectPropertyAddress INPUT_DATA_SOURCE_PROPERTY_ADDRESS = {
kAudioDevicePropertyDataSource, kAudioDevicePropertyScopeInput,
kAudioObjectPropertyElementMaster};
const AudioObjectPropertyAddress OUTPUT_DATA_SOURCE_PROPERTY_ADDRESS = {
kAudioDevicePropertyDataSource, kAudioDevicePropertyScopeOutput,
kAudioObjectPropertyElementMaster};
typedef uint32_t device_flags_value;
enum device_flags {
DEV_UNKNOWN = 0x00, /* Unknown */
DEV_INPUT = 0x01, /* Record device like mic */
DEV_OUTPUT = 0x02, /* Playback device like speakers */
DEV_SYSTEM_DEFAULT = 0x04, /* System default device */
DEV_SELECTED_DEFAULT =
0x08, /* User selected to use the system default device */
};
void
audiounit_stream_stop_internal(cubeb_stream * stm);
static int
audiounit_stream_start_internal(cubeb_stream * stm);
static void
audiounit_close_stream(cubeb_stream * stm);
static int
audiounit_setup_stream(cubeb_stream * stm);
static vector<AudioObjectID>
audiounit_get_devices_of_type(cubeb_device_type devtype);
static UInt32
audiounit_get_device_presentation_latency(AudioObjectID devid,
AudioObjectPropertyScope scope);
#if !TARGET_OS_IPHONE
static AudioObjectID
audiounit_get_default_device_id(cubeb_device_type type);
static int
audiounit_uninstall_device_changed_callback(cubeb_stream * stm);
static int
audiounit_uninstall_system_changed_callback(cubeb_stream * stm);
static void
audiounit_reinit_stream_async(cubeb_stream * stm, device_flags_value flags);
#endif
extern cubeb_ops const audiounit_ops;
struct cubeb {
cubeb_ops const * ops = &audiounit_ops;
owned_critical_section mutex;
int active_streams = 0;
uint32_t global_latency_frames = 0;
cubeb_device_collection_changed_callback input_collection_changed_callback =
nullptr;
void * input_collection_changed_user_ptr = nullptr;
cubeb_device_collection_changed_callback output_collection_changed_callback =
nullptr;
void * output_collection_changed_user_ptr = nullptr;
// Store list of devices to detect changes
vector<AudioObjectID> input_device_array;
vector<AudioObjectID> output_device_array;
// The queue should be released when it’s no longer needed.
dispatch_queue_t serial_queue =
dispatch_queue_create(DISPATCH_QUEUE_LABEL, DISPATCH_QUEUE_SERIAL);
// Current used channel layout
atomic<cubeb_channel_layout> layout{CUBEB_LAYOUT_UNDEFINED};
uint32_t channels = 0;
};
static unique_ptr<AudioChannelLayout, decltype(&free)>
make_sized_audio_channel_layout(size_t sz)
{
assert(sz >= sizeof(AudioChannelLayout));
AudioChannelLayout * acl =
reinterpret_cast<AudioChannelLayout *>(calloc(1, sz));
assert(acl); // Assert the allocation works.
return unique_ptr<AudioChannelLayout, decltype(&free)>(acl, free);
}
enum class io_side {
INPUT,
OUTPUT,
};
static char const *
to_string(io_side side)
{
switch (side) {
case io_side::INPUT:
return "input";
case io_side::OUTPUT:
return "output";
}
}
struct device_info {
AudioDeviceID id = kAudioObjectUnknown;
device_flags_value flags = DEV_UNKNOWN;
};
struct property_listener {
AudioDeviceID device_id;
const AudioObjectPropertyAddress * property_address;
AudioObjectPropertyListenerProc callback;
cubeb_stream * stream;
property_listener(AudioDeviceID id,
const AudioObjectPropertyAddress * address,
AudioObjectPropertyListenerProc proc, cubeb_stream * stm)
: device_id(id), property_address(address), callback(proc), stream(stm)
{
}
};
struct cubeb_stream {
explicit cubeb_stream(cubeb * context);
/* Note: Must match cubeb_stream layout in cubeb.c. */
cubeb * context;
void * user_ptr = nullptr;
/**/
cubeb_data_callback data_callback = nullptr;
cubeb_state_callback state_callback = nullptr;
cubeb_device_changed_callback device_changed_callback = nullptr;
owned_critical_section device_changed_callback_lock;
/* Stream creation parameters */
cubeb_stream_params input_stream_params = {CUBEB_SAMPLE_FLOAT32NE, 0, 0,
CUBEB_LAYOUT_UNDEFINED,
CUBEB_STREAM_PREF_NONE};
cubeb_stream_params output_stream_params = {CUBEB_SAMPLE_FLOAT32NE, 0, 0,
CUBEB_LAYOUT_UNDEFINED,
CUBEB_STREAM_PREF_NONE};
device_info input_device;
device_info output_device;
/* Format descriptions */
AudioStreamBasicDescription input_desc;
AudioStreamBasicDescription output_desc;
/* I/O AudioUnits */
AudioUnit input_unit = nullptr;
AudioUnit output_unit = nullptr;
/* I/O device sample rate */
Float64 input_hw_rate = 0;
Float64 output_hw_rate = 0;
/* Expected I/O thread interleave,
* calculated from I/O hw rate. */
int expected_output_callbacks_in_a_row = 0;
owned_critical_section mutex;
// Hold the input samples in every input callback iteration.
// Only accessed on input/output callback thread and during initial configure.
unique_ptr<auto_array_wrapper> input_linear_buffer;
/* Frame counters */
atomic<uint64_t> frames_played{0};
uint64_t frames_queued = 0;
// How many frames got read from the input since the stream started (includes
// padded silence)
atomic<int64_t> frames_read{0};
// How many frames got written to the output device since the stream started
atomic<int64_t> frames_written{0};
atomic<bool> shutdown{true};
atomic<bool> draining{false};
atomic<bool> reinit_pending{false};
atomic<bool> destroy_pending{false};
/* Latency requested by the user. */
uint32_t latency_frames = 0;
atomic<uint32_t> current_latency_frames{0};
atomic<uint32_t> total_output_latency_frames{0};
unique_ptr<cubeb_resampler, decltype(&cubeb_resampler_destroy)> resampler;
/* This is true if a device change callback is currently running. */
atomic<bool> switching_device{false};
atomic<bool> buffer_size_change_state{false};
AudioDeviceID aggregate_device_id =
kAudioObjectUnknown; // the aggregate device id
AudioObjectID plugin_id =
kAudioObjectUnknown; // used to create aggregate device
/* Mixer interface */
unique_ptr<cubeb_mixer, decltype(&cubeb_mixer_destroy)> mixer;
/* Buffer where remixing/resampling will occur when upmixing is required */
/* Only accessed from callback thread */
unique_ptr<uint8_t[]> temp_buffer;
size_t temp_buffer_size = 0; // size in bytes.
/* Listeners indicating what system events are monitored. */
unique_ptr<property_listener> default_input_listener;
unique_ptr<property_listener> default_output_listener;
unique_ptr<property_listener> input_alive_listener;
unique_ptr<property_listener> input_source_listener;
unique_ptr<property_listener> output_source_listener;
};
bool
has_input(cubeb_stream * stm)
{
return stm->input_stream_params.rate != 0;
}
bool
has_output(cubeb_stream * stm)
{
return stm->output_stream_params.rate != 0;
}
cubeb_channel
channel_label_to_cubeb_channel(UInt32 label)
{
switch (label) {
case kAudioChannelLabel_Left:
return CHANNEL_FRONT_LEFT;
case kAudioChannelLabel_Right:
return CHANNEL_FRONT_RIGHT;
case kAudioChannelLabel_Center:
return CHANNEL_FRONT_CENTER;
case kAudioChannelLabel_LFEScreen:
return CHANNEL_LOW_FREQUENCY;
case kAudioChannelLabel_LeftSurround:
return CHANNEL_BACK_LEFT;
case kAudioChannelLabel_RightSurround:
return CHANNEL_BACK_RIGHT;
case kAudioChannelLabel_LeftCenter:
return CHANNEL_FRONT_LEFT_OF_CENTER;
case kAudioChannelLabel_RightCenter:
return CHANNEL_FRONT_RIGHT_OF_CENTER;
case kAudioChannelLabel_CenterSurround:
return CHANNEL_BACK_CENTER;
case kAudioChannelLabel_LeftSurroundDirect:
return CHANNEL_SIDE_LEFT;
case kAudioChannelLabel_RightSurroundDirect:
return CHANNEL_SIDE_RIGHT;
case kAudioChannelLabel_TopCenterSurround:
return CHANNEL_TOP_CENTER;
case kAudioChannelLabel_VerticalHeightLeft:
return CHANNEL_TOP_FRONT_LEFT;
case kAudioChannelLabel_VerticalHeightCenter:
return CHANNEL_TOP_FRONT_CENTER;
case kAudioChannelLabel_VerticalHeightRight:
return CHANNEL_TOP_FRONT_RIGHT;
case kAudioChannelLabel_TopBackLeft:
return CHANNEL_TOP_BACK_LEFT;
case kAudioChannelLabel_TopBackCenter:
return CHANNEL_TOP_BACK_CENTER;
case kAudioChannelLabel_TopBackRight:
return CHANNEL_TOP_BACK_RIGHT;
default:
return CHANNEL_UNKNOWN;
}
}
AudioChannelLabel
cubeb_channel_to_channel_label(cubeb_channel channel)
{
switch (channel) {
case CHANNEL_FRONT_LEFT:
return kAudioChannelLabel_Left;
case CHANNEL_FRONT_RIGHT:
return kAudioChannelLabel_Right;
case CHANNEL_FRONT_CENTER:
return kAudioChannelLabel_Center;
case CHANNEL_LOW_FREQUENCY:
return kAudioChannelLabel_LFEScreen;
case CHANNEL_BACK_LEFT:
return kAudioChannelLabel_LeftSurround;
case CHANNEL_BACK_RIGHT:
return kAudioChannelLabel_RightSurround;
case CHANNEL_FRONT_LEFT_OF_CENTER:
return kAudioChannelLabel_LeftCenter;
case CHANNEL_FRONT_RIGHT_OF_CENTER:
return kAudioChannelLabel_RightCenter;
case CHANNEL_BACK_CENTER:
return kAudioChannelLabel_CenterSurround;
case CHANNEL_SIDE_LEFT:
return kAudioChannelLabel_LeftSurroundDirect;
case CHANNEL_SIDE_RIGHT:
return kAudioChannelLabel_RightSurroundDirect;
case CHANNEL_TOP_CENTER:
return kAudioChannelLabel_TopCenterSurround;
case CHANNEL_TOP_FRONT_LEFT:
return kAudioChannelLabel_VerticalHeightLeft;
case CHANNEL_TOP_FRONT_CENTER:
return kAudioChannelLabel_VerticalHeightCenter;
case CHANNEL_TOP_FRONT_RIGHT:
return kAudioChannelLabel_VerticalHeightRight;
case CHANNEL_TOP_BACK_LEFT:
return kAudioChannelLabel_TopBackLeft;
case CHANNEL_TOP_BACK_CENTER:
return kAudioChannelLabel_TopBackCenter;
case CHANNEL_TOP_BACK_RIGHT:
return kAudioChannelLabel_TopBackRight;
default:
return kAudioChannelLabel_Unknown;
}
}
#if TARGET_OS_IPHONE
typedef UInt32 AudioDeviceID;
typedef UInt32 AudioObjectID;
#define AudioGetCurrentHostTime mach_absolute_time
#endif
uint64_t
ConvertHostTimeToNanos(uint64_t host_time)
{
static struct mach_timebase_info timebase_info;
static bool initialized = false;
if (!initialized) {
mach_timebase_info(&timebase_info);
initialized = true;
}
long double answer = host_time;
if (timebase_info.numer != timebase_info.denom) {
answer *= timebase_info.numer;
answer /= timebase_info.denom;
}
return (uint64_t)answer;
}
static void
audiounit_increment_active_streams(cubeb * ctx)
{
ctx->mutex.assert_current_thread_owns();
ctx->active_streams += 1;
}
static void
audiounit_decrement_active_streams(cubeb * ctx)
{
ctx->mutex.assert_current_thread_owns();
ctx->active_streams -= 1;
}
static int
audiounit_active_streams(cubeb * ctx)
{
ctx->mutex.assert_current_thread_owns();
return ctx->active_streams;
}
static void
audiounit_set_global_latency(cubeb * ctx, uint32_t latency_frames)
{
ctx->mutex.assert_current_thread_owns();
assert(audiounit_active_streams(ctx) == 1);
ctx->global_latency_frames = latency_frames;
}
static void
audiounit_make_silent(AudioBuffer * ioData)
{
assert(ioData);
assert(ioData->mData);
memset(ioData->mData, 0, ioData->mDataByteSize);
}
static OSStatus
audiounit_render_input(cubeb_stream * stm, AudioUnitRenderActionFlags * flags,
AudioTimeStamp const * tstamp, UInt32 bus,
UInt32 input_frames)
{
/* Create the AudioBufferList to store input. */
AudioBufferList input_buffer_list;
input_buffer_list.mBuffers[0].mDataByteSize =
stm->input_desc.mBytesPerFrame * input_frames;
input_buffer_list.mBuffers[0].mData = nullptr;
input_buffer_list.mBuffers[0].mNumberChannels =
stm->input_desc.mChannelsPerFrame;
input_buffer_list.mNumberBuffers = 1;
/* Render input samples */
OSStatus r = AudioUnitRender(stm->input_unit, flags, tstamp, bus,
input_frames, &input_buffer_list);
if (r != noErr) {
LOG("AudioUnitRender rv=%d", r);
if (r != kAudioUnitErr_CannotDoInCurrentContext) {
return r;
}
if (stm->output_unit) {
// kAudioUnitErr_CannotDoInCurrentContext is returned when using a BT
// headset and the profile is changed from A2DP to HFP/HSP. The previous
// output device is no longer valid and must be reset.
audiounit_reinit_stream_async(stm, DEV_INPUT | DEV_OUTPUT);
}
// For now state that no error occurred and feed silence, stream will be
// resumed once reinit has completed.
ALOGV("(%p) input: reinit pending feeding silence instead", stm);
stm->input_linear_buffer->push_silence(input_frames *
stm->input_desc.mChannelsPerFrame);
} else {
/* Copy input data in linear buffer. */
stm->input_linear_buffer->push(input_buffer_list.mBuffers[0].mData,
input_frames *
stm->input_desc.mChannelsPerFrame);
}
/* Advance input frame counter. */
assert(input_frames > 0);
stm->frames_read += input_frames;
ALOGV("(%p) input: buffers %u, size %u, channels %u, rendered frames %d, "
"total frames %lu.",
stm, (unsigned int)input_buffer_list.mNumberBuffers,
(unsigned int)input_buffer_list.mBuffers[0].mDataByteSize,
(unsigned int)input_buffer_list.mBuffers[0].mNumberChannels,
(unsigned int)input_frames,
stm->input_linear_buffer->length() / stm->input_desc.mChannelsPerFrame);
return noErr;
}
static OSStatus
audiounit_input_callback(void * user_ptr, AudioUnitRenderActionFlags * flags,
AudioTimeStamp const * tstamp, UInt32 bus,
UInt32 input_frames, AudioBufferList * /* bufs */)
{
cubeb_stream * stm = static_cast<cubeb_stream *>(user_ptr);
assert(stm->input_unit != NULL);
assert(AU_IN_BUS == bus);
if (stm->shutdown) {
ALOG("(%p) input shutdown", stm);
return noErr;
}
if (stm->draining) {
OSStatus r = AudioOutputUnitStop(stm->input_unit);
assert(r == 0);
// Only fire state callback in input-only stream. For duplex stream,
// the state callback will be fired in output callback.
if (stm->output_unit == NULL) {
stm->state_callback(stm, stm->user_ptr, CUBEB_STATE_DRAINED);
}
return noErr;
}
OSStatus r = audiounit_render_input(stm, flags, tstamp, bus, input_frames);
if (r != noErr) {
return r;
}
// Full Duplex. We'll call data_callback in the AudioUnit output callback.
if (stm->output_unit != NULL) {
return noErr;
}
/* Input only. Call the user callback through resampler.
Resampler will deliver input buffer in the correct rate. */
assert(input_frames <= stm->input_linear_buffer->length() /
stm->input_desc.mChannelsPerFrame);
long total_input_frames =
stm->input_linear_buffer->length() / stm->input_desc.mChannelsPerFrame;
long outframes = cubeb_resampler_fill(stm->resampler.get(),
stm->input_linear_buffer->data(),
&total_input_frames, NULL, 0);
stm->draining = outframes < total_input_frames;
// Reset input buffer
stm->input_linear_buffer->clear();
return noErr;
}
static void
audiounit_mix_output_buffer(cubeb_stream * stm, size_t output_frames,
void * input_buffer, size_t input_buffer_size,
void * output_buffer, size_t output_buffer_size)
{
assert(input_buffer_size >=
cubeb_sample_size(stm->output_stream_params.format) *
stm->output_stream_params.channels * output_frames);
assert(output_buffer_size >= stm->output_desc.mBytesPerFrame * output_frames);
int r = cubeb_mixer_mix(stm->mixer.get(), output_frames, input_buffer,
input_buffer_size, output_buffer, output_buffer_size);
if (r != 0) {
LOG("Remix error = %d", r);
}
}
// Return how many input frames (sampled at input_hw_rate) are needed to provide
// output_frames (sampled at output_stream_params.rate)
static int64_t
minimum_resampling_input_frames(cubeb_stream * stm, uint32_t output_frames)
{
if (stm->input_hw_rate == stm->output_stream_params.rate) {
// Fast path.
return output_frames;
}
return ceil(stm->input_hw_rate * output_frames /
stm->output_stream_params.rate);
}
static OSStatus
audiounit_output_callback(void * user_ptr,
AudioUnitRenderActionFlags * /* flags */,
AudioTimeStamp const * tstamp, UInt32 bus,
UInt32 output_frames, AudioBufferList * outBufferList)
{
assert(AU_OUT_BUS == bus);
assert(outBufferList->mNumberBuffers == 1);
cubeb_stream * stm = static_cast<cubeb_stream *>(user_ptr);
uint64_t now = ConvertHostTimeToNanos(mach_absolute_time());
uint64_t audio_output_time = ConvertHostTimeToNanos(tstamp->mHostTime);
uint64_t output_latency_ns = audio_output_time - now;
const int ns2s = 1e9;
// The total output latency is the timestamp difference + the stream latency +
// the hardware latency.
stm->total_output_latency_frames =
output_latency_ns * stm->output_hw_rate / ns2s +
stm->current_latency_frames;
ALOGV("(%p) output: buffers %u, size %u, channels %u, frames %u, total input "
"frames %lu.",
stm, (unsigned int)outBufferList->mNumberBuffers,
(unsigned int)outBufferList->mBuffers[0].mDataByteSize,
(unsigned int)outBufferList->mBuffers[0].mNumberChannels,
(unsigned int)output_frames,
has_input(stm) ? stm->input_linear_buffer->length() /
stm->input_desc.mChannelsPerFrame
: 0);
long input_frames = 0;
void *output_buffer = NULL, *input_buffer = NULL;
if (stm->shutdown) {
ALOG("(%p) output shutdown.", stm);
audiounit_make_silent(&outBufferList->mBuffers[0]);
return noErr;
}
if (stm->draining) {
OSStatus r = AudioOutputUnitStop(stm->output_unit);
assert(r == 0);
stm->state_callback(stm, stm->user_ptr, CUBEB_STATE_DRAINED);
audiounit_make_silent(&outBufferList->mBuffers[0]);
return noErr;
}
/* Get output buffer. */
if (stm->mixer) {
// If remixing needs to occur, we can't directly work in our final
// destination buffer as data may be overwritten or too small to start with.
size_t size_needed = output_frames * stm->output_stream_params.channels *
cubeb_sample_size(stm->output_stream_params.format);
if (stm->temp_buffer_size < size_needed) {
stm->temp_buffer.reset(new uint8_t[size_needed]);
stm->temp_buffer_size = size_needed;
}
output_buffer = stm->temp_buffer.get();
} else {
output_buffer = outBufferList->mBuffers[0].mData;
}
stm->frames_written += output_frames;
/* If Full duplex get also input buffer */
if (stm->input_unit != NULL) {
/* If the output callback came first and this is a duplex stream, we need to
* fill in some additional silence in the resampler.
* Otherwise, if we had more than expected callbacks in a row, or we're
* currently switching, we add some silence as well to compensate for the
* fact that we're lacking some input data. */
uint32_t input_frames_needed =
minimum_resampling_input_frames(stm, stm->frames_written);
long missing_frames = input_frames_needed - stm->frames_read;
if (missing_frames > 0) {
stm->input_linear_buffer->push_silence(missing_frames *
stm->input_desc.mChannelsPerFrame);
stm->frames_read = input_frames_needed;
ALOG("(%p) %s pushed %ld frames of input silence.", stm,
stm->frames_read == 0 ? "Input hasn't started,"
: stm->switching_device ? "Device switching,"
: "Drop out,",
missing_frames);
}
input_buffer = stm->input_linear_buffer->data();
// Number of input frames in the buffer. It will change to actually used
// frames inside fill
input_frames =
stm->input_linear_buffer->length() / stm->input_desc.mChannelsPerFrame;
}
/* Call user callback through resampler. */
long outframes = cubeb_resampler_fill(stm->resampler.get(), input_buffer,
input_buffer ? &input_frames : NULL,
output_buffer, output_frames);
if (input_buffer) {
// Pop from the buffer the frames used by the the resampler.
stm->input_linear_buffer->pop(input_frames *
stm->input_desc.mChannelsPerFrame);
}
if (outframes < 0 || outframes > output_frames) {
stm->shutdown = true;
OSStatus r = AudioOutputUnitStop(stm->output_unit);
assert(r == 0);
if (stm->input_unit) {
r = AudioOutputUnitStop(stm->input_unit);
assert(r == 0);
}
stm->state_callback(stm, stm->user_ptr, CUBEB_STATE_ERROR);
audiounit_make_silent(&outBufferList->mBuffers[0]);
return noErr;
}
stm->draining = (UInt32)outframes < output_frames;
stm->frames_played = stm->frames_queued;
stm->frames_queued += outframes;
/* Post process output samples. */
if (stm->draining) {
/* Clear missing frames (silence) */
size_t channels = stm->output_stream_params.channels;
size_t missing_samples = (output_frames - outframes) * channels;
size_t size_sample = cubeb_sample_size(stm->output_stream_params.format);
/* number of bytes that have been filled with valid audio by the callback.
*/
size_t audio_byte_count = outframes * channels * size_sample;
PodZero((uint8_t *)output_buffer + audio_byte_count,
missing_samples * size_sample);
}
/* Mixing */
if (stm->mixer) {
audiounit_mix_output_buffer(stm, output_frames, output_buffer,
stm->temp_buffer_size,
outBufferList->mBuffers[0].mData,
outBufferList->mBuffers[0].mDataByteSize);
}
return noErr;
}
extern "C" {
int
audiounit_init(cubeb ** context, char const * /* context_name */)
{
#if !TARGET_OS_IPHONE
cubeb_set_coreaudio_notification_runloop();
#endif
*context = new cubeb;
return CUBEB_OK;
}
}
static char const *
audiounit_get_backend_id(cubeb * /* ctx */)
{
return "audiounit";
}
#if !TARGET_OS_IPHONE
static int
audiounit_stream_get_volume(cubeb_stream * stm, float * volume);
static int
audiounit_stream_set_volume(cubeb_stream * stm, float volume);
static int
audiounit_set_device_info(cubeb_stream * stm, AudioDeviceID id, io_side side)
{
assert(stm);
device_info * info = nullptr;
cubeb_device_type type = CUBEB_DEVICE_TYPE_UNKNOWN;
if (side == io_side::INPUT) {
info = &stm->input_device;
type = CUBEB_DEVICE_TYPE_INPUT;
} else if (side == io_side::OUTPUT) {
info = &stm->output_device;
type = CUBEB_DEVICE_TYPE_OUTPUT;
}
memset(info, 0, sizeof(device_info));
info->id = id;
if (side == io_side::INPUT) {
info->flags |= DEV_INPUT;
} else if (side == io_side::OUTPUT) {
info->flags |= DEV_OUTPUT;
}
AudioDeviceID default_device_id = audiounit_get_default_device_id(type);
if (default_device_id == kAudioObjectUnknown) {
return CUBEB_ERROR;
}
if (id == kAudioObjectUnknown) {
info->id = default_device_id;
info->flags |= DEV_SELECTED_DEFAULT;
}
if (info->id == default_device_id) {
info->flags |= DEV_SYSTEM_DEFAULT;
}
assert(info->id);
assert(info->flags & DEV_INPUT && !(info->flags & DEV_OUTPUT) ||
!(info->flags & DEV_INPUT) && info->flags & DEV_OUTPUT);
return CUBEB_OK;
}
static int
audiounit_reinit_stream(cubeb_stream * stm, device_flags_value flags)
{
auto_lock context_lock(stm->context->mutex);
assert((flags & DEV_INPUT && stm->input_unit) ||
(flags & DEV_OUTPUT && stm->output_unit));
if (!stm->shutdown) {
audiounit_stream_stop_internal(stm);
}
int r = audiounit_uninstall_device_changed_callback(stm);
if (r != CUBEB_OK) {
LOG("(%p) Could not uninstall all device change listeners.", stm);
}
{
auto_lock lock(stm->mutex);
float volume = 0.0;
int vol_rv = CUBEB_ERROR;
if (stm->output_unit) {
vol_rv = audiounit_stream_get_volume(stm, &volume);
}
audiounit_close_stream(stm);
/* Reinit occurs in one of the following case:
* - When the device is not alive any more
* - When the default system device change.
* - The bluetooth device changed from A2DP to/from HFP/HSP profile
* We first attempt to re-use the same device id, should that fail we will
* default to the (potentially new) default device. */
AudioDeviceID input_device =
flags & DEV_INPUT ? stm->input_device.id : kAudioObjectUnknown;
if (flags & DEV_INPUT) {
r = audiounit_set_device_info(stm, input_device, io_side::INPUT);
if (r != CUBEB_OK) {
LOG("(%p) Set input device info failed. This can happen when last "
"media device is unplugged",
stm);
return CUBEB_ERROR;
}
}
/* Always use the default output on reinit. This is not correct in every
* case but it is sufficient for Firefox and prevent reinit from reporting
* failures. It will change soon when reinit mechanism will be updated. */
r = audiounit_set_device_info(stm, kAudioObjectUnknown, io_side::OUTPUT);
if (r != CUBEB_OK) {
LOG("(%p) Set output device info failed. This can happen when last media "
"device is unplugged",
stm);
return CUBEB_ERROR;
}
if (audiounit_setup_stream(stm) != CUBEB_OK) {
LOG("(%p) Stream reinit failed.", stm);
if (flags & DEV_INPUT && input_device != kAudioObjectUnknown) {
// Attempt to re-use the same device-id failed, so attempt again with
// default input device.
audiounit_close_stream(stm);
if (audiounit_set_device_info(stm, kAudioObjectUnknown,
io_side::INPUT) != CUBEB_OK ||
audiounit_setup_stream(stm) != CUBEB_OK) {
LOG("(%p) Second stream reinit failed.", stm);
return CUBEB_ERROR;
}
}
}
if (vol_rv == CUBEB_OK) {
audiounit_stream_set_volume(stm, volume);
}
// If the stream was running, start it again.
if (!stm->shutdown) {
r = audiounit_stream_start_internal(stm);
if (r != CUBEB_OK) {
return CUBEB_ERROR;
}
}
}
return CUBEB_OK;
}
static void
audiounit_reinit_stream_async(cubeb_stream * stm, device_flags_value flags)
{
if (std::atomic_exchange(&stm->reinit_pending, true)) {
// A reinit task is already pending, nothing more to do.
ALOG("(%p) re-init stream task already pending, cancelling request", stm);
return;
}
// Use a new thread, through the queue, to avoid deadlock when calling
// Get/SetProperties method from inside notify callback
dispatch_async(stm->context->serial_queue, ^() {
if (stm->destroy_pending) {
ALOG("(%p) stream pending destroy, cancelling reinit task", stm);
return;
}
if (audiounit_reinit_stream(stm, flags) != CUBEB_OK) {
if (audiounit_uninstall_system_changed_callback(stm) != CUBEB_OK) {
LOG("(%p) Could not uninstall system changed callback", stm);
}
stm->state_callback(stm, stm->user_ptr, CUBEB_STATE_ERROR);
LOG("(%p) Could not reopen the stream after switching.", stm);
}
stm->switching_device = false;
stm->reinit_pending = false;
});
}
static char const *
event_addr_to_string(AudioObjectPropertySelector selector)
{
switch (selector) {
case kAudioHardwarePropertyDefaultOutputDevice:
return "kAudioHardwarePropertyDefaultOutputDevice";
case kAudioHardwarePropertyDefaultInputDevice:
return "kAudioHardwarePropertyDefaultInputDevice";
case kAudioDevicePropertyDeviceIsAlive:
return "kAudioDevicePropertyDeviceIsAlive";
case kAudioDevicePropertyDataSource:
return "kAudioDevicePropertyDataSource";
default:
return "Unknown";
}
}
static OSStatus
audiounit_property_listener_callback(
AudioObjectID id, UInt32 address_count,
const AudioObjectPropertyAddress * addresses, void * user)
{
cubeb_stream * stm = (cubeb_stream *)user;
if (stm->switching_device) {
LOG("Switching is already taking place. Skip Event %s for id=%d",
event_addr_to_string(addresses[0].mSelector), id);
return noErr;
}
stm->switching_device = true;
LOG("(%p) Audio device changed, %u events.", stm,
(unsigned int)address_count);
for (UInt32 i = 0; i < address_count; i++) {
switch (addresses[i].mSelector) {
case kAudioHardwarePropertyDefaultOutputDevice: {
LOG("Event[%u] - mSelector == kAudioHardwarePropertyDefaultOutputDevice "
"for id=%d",
(unsigned int)i, id);
} break;
case kAudioHardwarePropertyDefaultInputDevice: {
LOG("Event[%u] - mSelector == kAudioHardwarePropertyDefaultInputDevice "
"for id=%d",
(unsigned int)i, id);
} break;
case kAudioDevicePropertyDeviceIsAlive: {
LOG("Event[%u] - mSelector == kAudioDevicePropertyDeviceIsAlive for "
"id=%d",
(unsigned int)i, id);
// If this is the default input device ignore the event,
// kAudioHardwarePropertyDefaultInputDevice will take care of the switch
if (stm->input_device.flags & DEV_SYSTEM_DEFAULT) {
LOG("It's the default input device, ignore the event");
stm->switching_device = false;
return noErr;
}
} break;
case kAudioDevicePropertyDataSource: {
LOG("Event[%u] - mSelector == kAudioDevicePropertyDataSource for id=%d",
(unsigned int)i, id);
} break;
default:
LOG("Event[%u] - mSelector == Unexpected Event id %d, return",
(unsigned int)i, addresses[i].mSelector);
stm->switching_device = false;
return noErr;
}
}
// Allow restart to choose the new default
device_flags_value switch_side = DEV_UNKNOWN;
if (has_input(stm)) {
switch_side |= DEV_INPUT;
}
if (has_output(stm)) {
switch_side |= DEV_OUTPUT;
}
for (UInt32 i = 0; i < address_count; i++) {
switch (addresses[i].mSelector) {
case kAudioHardwarePropertyDefaultOutputDevice:
case kAudioHardwarePropertyDefaultInputDevice:
case kAudioDevicePropertyDeviceIsAlive:
/* fall through */
case kAudioDevicePropertyDataSource: {
auto_lock dev_cb_lock(stm->device_changed_callback_lock);
if (stm->device_changed_callback) {
stm->device_changed_callback(stm->user_ptr);
}
break;
}
}
}
audiounit_reinit_stream_async(stm, switch_side);
return noErr;
}
OSStatus
audiounit_add_listener(const property_listener * listener)
{
assert(listener);
return AudioObjectAddPropertyListener(listener->device_id,
listener->property_address,
listener->callback, listener->stream);
}
OSStatus
audiounit_remove_listener(const property_listener * listener)
{
assert(listener);
return AudioObjectRemovePropertyListener(
listener->device_id, listener->property_address, listener->callback,
listener->stream);
}
static int
audiounit_install_device_changed_callback(cubeb_stream * stm)
{
OSStatus rv;
int r = CUBEB_OK;
if (stm->output_unit) {
/* This event will notify us when the data source on the same device
* changes, for example when the user plugs in a normal (non-usb) headset in
* the headphone jack. */
stm->output_source_listener.reset(new property_listener(
stm->output_device.id, &OUTPUT_DATA_SOURCE_PROPERTY_ADDRESS,
&audiounit_property_listener_callback, stm));
rv = audiounit_add_listener(stm->output_source_listener.get());
if (rv != noErr) {
stm->output_source_listener.reset();
LOG("AudioObjectAddPropertyListener/output/"
"kAudioDevicePropertyDataSource rv=%d, device id=%d",
rv, stm->output_device.id);
r = CUBEB_ERROR;
}
}
if (stm->input_unit) {
/* This event will notify us when the data source on the input device
* changes. */
stm->input_source_listener.reset(new property_listener(
stm->input_device.id, &INPUT_DATA_SOURCE_PROPERTY_ADDRESS,
&audiounit_property_listener_callback, stm));
rv = audiounit_add_listener(stm->input_source_listener.get());
if (rv != noErr) {
stm->input_source_listener.reset();
LOG("AudioObjectAddPropertyListener/input/kAudioDevicePropertyDataSource "
"rv=%d, device id=%d",
rv, stm->input_device.id);
r = CUBEB_ERROR;
}
/* Event to notify when the input is going away. */
stm->input_alive_listener.reset(new property_listener(
stm->input_device.id, &DEVICE_IS_ALIVE_PROPERTY_ADDRESS,
&audiounit_property_listener_callback, stm));
rv = audiounit_add_listener(stm->input_alive_listener.get());
if (rv != noErr) {
stm->input_alive_listener.reset();
LOG("AudioObjectAddPropertyListener/input/"
"kAudioDevicePropertyDeviceIsAlive rv=%d, device id =%d",
rv, stm->input_device.id);
r = CUBEB_ERROR;
}
}
return r;
}
static int
audiounit_install_system_changed_callback(cubeb_stream * stm)
{
OSStatus r;
if (stm->output_unit) {
/* This event will notify us when the default audio device changes,
* for example when the user plugs in a USB headset and the system chooses
* it automatically as the default, or when another device is chosen in the
* dropdown list. */
stm->default_output_listener.reset(new property_listener(
kAudioObjectSystemObject, &DEFAULT_OUTPUT_DEVICE_PROPERTY_ADDRESS,
&audiounit_property_listener_callback, stm));
r = audiounit_add_listener(stm->default_output_listener.get());
if (r != noErr) {
stm->default_output_listener.reset();
LOG("AudioObjectAddPropertyListener/output/"
"kAudioHardwarePropertyDefaultOutputDevice rv=%d",
r);
return CUBEB_ERROR;
}
}
if (stm->input_unit) {
/* This event will notify us when the default input device changes. */
stm->default_input_listener.reset(new property_listener(
kAudioObjectSystemObject, &DEFAULT_INPUT_DEVICE_PROPERTY_ADDRESS,
&audiounit_property_listener_callback, stm));
r = audiounit_add_listener(stm->default_input_listener.get());
if (r != noErr) {
stm->default_input_listener.reset();
LOG("AudioObjectAddPropertyListener/input/"
"kAudioHardwarePropertyDefaultInputDevice rv=%d",
r);
return CUBEB_ERROR;
}
}
return CUBEB_OK;
}
static int
audiounit_uninstall_device_changed_callback(cubeb_stream * stm)
{
OSStatus rv;
// Failing to uninstall listeners is not a fatal error.
int r = CUBEB_OK;
if (stm->output_source_listener) {
rv = audiounit_remove_listener(stm->output_source_listener.get());
if (rv != noErr) {
LOG("AudioObjectRemovePropertyListener/output/"
"kAudioDevicePropertyDataSource rv=%d, device id=%d",
rv, stm->output_device.id);
r = CUBEB_ERROR;
}
stm->output_source_listener.reset();
}
if (stm->input_source_listener) {
rv = audiounit_remove_listener(stm->input_source_listener.get());
if (rv != noErr) {
LOG("AudioObjectRemovePropertyListener/input/"
"kAudioDevicePropertyDataSource rv=%d, device id=%d",
rv, stm->input_device.id);
r = CUBEB_ERROR;
}
stm->input_source_listener.reset();
}
if (stm->input_alive_listener) {
rv = audiounit_remove_listener(stm->input_alive_listener.get());
if (rv != noErr) {
LOG("AudioObjectRemovePropertyListener/input/"
"kAudioDevicePropertyDeviceIsAlive rv=%d, device id=%d",
rv, stm->input_device.id);
r = CUBEB_ERROR;
}
stm->input_alive_listener.reset();
}
return r;
}
static int
audiounit_uninstall_system_changed_callback(cubeb_stream * stm)
{
OSStatus r;
if (stm->default_output_listener) {
r = audiounit_remove_listener(stm->default_output_listener.get());
if (r != noErr) {
return CUBEB_ERROR;
}
stm->default_output_listener.reset();
}
if (stm->default_input_listener) {
r = audiounit_remove_listener(stm->default_input_listener.get());
if (r != noErr) {
return CUBEB_ERROR;
}
stm->default_input_listener.reset();
}
return CUBEB_OK;
}
/* Get the acceptable buffer size (in frames) that this device can work with. */
static int
audiounit_get_acceptable_latency_range(AudioValueRange * latency_range)
{
UInt32 size;
OSStatus r;
AudioDeviceID output_device_id;
AudioObjectPropertyAddress output_device_buffer_size_range = {
kAudioDevicePropertyBufferFrameSizeRange, kAudioDevicePropertyScopeOutput,
kAudioObjectPropertyElementMaster};
output_device_id = audiounit_get_default_device_id(CUBEB_DEVICE_TYPE_OUTPUT);
if (output_device_id == kAudioObjectUnknown) {
LOG("Could not get default output device id.");
return CUBEB_ERROR;
}
/* Get the buffer size range this device supports */
size = sizeof(*latency_range);
r = AudioObjectGetPropertyData(output_device_id,
&output_device_buffer_size_range, 0, NULL,
&size, latency_range);
if (r != noErr) {
LOG("AudioObjectGetPropertyData/buffer size range rv=%d", r);
return CUBEB_ERROR;
}
return CUBEB_OK;
}
#endif /* !TARGET_OS_IPHONE */
static AudioObjectID
audiounit_get_default_device_id(cubeb_device_type type)
{
const AudioObjectPropertyAddress * adr;
if (type == CUBEB_DEVICE_TYPE_OUTPUT) {
adr = &DEFAULT_OUTPUT_DEVICE_PROPERTY_ADDRESS;
} else if (type == CUBEB_DEVICE_TYPE_INPUT) {
adr = &DEFAULT_INPUT_DEVICE_PROPERTY_ADDRESS;
} else {
return kAudioObjectUnknown;
}
AudioDeviceID devid;
UInt32 size = sizeof(AudioDeviceID);
if (AudioObjectGetPropertyData(kAudioObjectSystemObject, adr, 0, NULL, &size,
&devid) != noErr) {
return kAudioObjectUnknown;
}
return devid;
}
int
audiounit_get_max_channel_count(cubeb * ctx, uint32_t * max_channels)
{
#if TARGET_OS_IPHONE
// TODO: [[AVAudioSession sharedInstance] maximumOutputNumberOfChannels]
*max_channels = 2;
#else
UInt32 size;
OSStatus r;
AudioDeviceID output_device_id;
AudioStreamBasicDescription stream_format;
AudioObjectPropertyAddress stream_format_address = {
kAudioDevicePropertyStreamFormat, kAudioDevicePropertyScopeOutput,
kAudioObjectPropertyElementMaster};
assert(ctx && max_channels);
output_device_id = audiounit_get_default_device_id(CUBEB_DEVICE_TYPE_OUTPUT);
if (output_device_id == kAudioObjectUnknown) {
return CUBEB_ERROR;
}
size = sizeof(stream_format);
r = AudioObjectGetPropertyData(output_device_id, &stream_format_address, 0,
NULL, &size, &stream_format);
if (r != noErr) {
LOG("AudioObjectPropertyAddress/StreamFormat rv=%d", r);
return CUBEB_ERROR;
}
*max_channels = stream_format.mChannelsPerFrame;
#endif
return CUBEB_OK;
}
static int
audiounit_get_min_latency(cubeb * /* ctx */, cubeb_stream_params /* params */,
uint32_t * latency_frames)
{
#if TARGET_OS_IPHONE
// TODO: [[AVAudioSession sharedInstance] inputLatency]
return CUBEB_ERROR_NOT_SUPPORTED;
#else
AudioValueRange latency_range;
if (audiounit_get_acceptable_latency_range(&latency_range) != CUBEB_OK) {
LOG("Could not get acceptable latency range.");
return CUBEB_ERROR;
}
*latency_frames =
max<uint32_t>(latency_range.mMinimum, SAFE_MIN_LATENCY_FRAMES);
#endif
return CUBEB_OK;
}
static int
audiounit_get_preferred_sample_rate(cubeb * /* ctx */, uint32_t * rate)
{
#if TARGET_OS_IPHONE
// TODO
return CUBEB_ERROR_NOT_SUPPORTED;
#else
UInt32 size;
OSStatus r;
Float64 fsamplerate;
AudioDeviceID output_device_id;
AudioObjectPropertyAddress samplerate_address = {
kAudioDevicePropertyNominalSampleRate, kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster};
output_device_id = audiounit_get_default_device_id(CUBEB_DEVICE_TYPE_OUTPUT);
if (output_device_id == kAudioObjectUnknown) {
return CUBEB_ERROR;
}
size = sizeof(fsamplerate);
r = AudioObjectGetPropertyData(output_device_id, &samplerate_address, 0, NULL,
&size, &fsamplerate);
if (r != noErr) {
return CUBEB_ERROR;
}
*rate = static_cast<uint32_t>(fsamplerate);
#endif
return CUBEB_OK;
}
static cubeb_channel_layout
audiounit_convert_channel_layout(AudioChannelLayout * layout)
{
// When having one or two channel, force mono or stereo. Some devices (namely,
// Bose QC35, mark 1 and 2), expose a single channel mapped to the right for
// some reason.
if (layout->mNumberChannelDescriptions == 1) {
return CUBEB_LAYOUT_MONO;
} else if (layout->mNumberChannelDescriptions == 2) {
return CUBEB_LAYOUT_STEREO;
}
if (layout->mChannelLayoutTag !=
kAudioChannelLayoutTag_UseChannelDescriptions) {
// kAudioChannelLayoutTag_UseChannelBitmap
// kAudioChannelLayoutTag_Mono
// kAudioChannelLayoutTag_Stereo
// ....
LOG("Only handle UseChannelDescriptions for now.\n");
return CUBEB_LAYOUT_UNDEFINED;
}
cubeb_channel_layout cl = 0;
for (UInt32 i = 0; i < layout->mNumberChannelDescriptions; ++i) {
cubeb_channel cc = channel_label_to_cubeb_channel(
layout->mChannelDescriptions[i].mChannelLabel);
if (cc == CHANNEL_UNKNOWN) {
return CUBEB_LAYOUT_UNDEFINED;
}
cl |= cc;
}
return cl;
}
static cubeb_channel_layout
audiounit_get_preferred_channel_layout(AudioUnit output_unit)
{
OSStatus rv = noErr;
UInt32 size = 0;
rv = AudioUnitGetPropertyInfo(
output_unit, kAudioDevicePropertyPreferredChannelLayout,
kAudioUnitScope_Output, AU_OUT_BUS, &size, nullptr);
if (rv != noErr) {
LOG("AudioUnitGetPropertyInfo/kAudioDevicePropertyPreferredChannelLayout "
"rv=%d",
rv);
return CUBEB_LAYOUT_UNDEFINED;
}
assert(size > 0);
auto layout = make_sized_audio_channel_layout(size);
rv = AudioUnitGetProperty(
output_unit, kAudioDevicePropertyPreferredChannelLayout,
kAudioUnitScope_Output, AU_OUT_BUS, layout.get(), &size);
if (rv != noErr) {
LOG("AudioUnitGetProperty/kAudioDevicePropertyPreferredChannelLayout rv=%d",
rv);
return CUBEB_LAYOUT_UNDEFINED;
}
return audiounit_convert_channel_layout(layout.get());
}
static cubeb_channel_layout
audiounit_get_current_channel_layout(AudioUnit output_unit)
{
OSStatus rv = noErr;
UInt32 size = 0;
rv = AudioUnitGetPropertyInfo(
output_unit, kAudioUnitProperty_AudioChannelLayout,
kAudioUnitScope_Output, AU_OUT_BUS, &size, nullptr);
if (rv != noErr) {
LOG("AudioUnitGetPropertyInfo/kAudioUnitProperty_AudioChannelLayout rv=%d",
rv);
// This property isn't known before macOS 10.12, attempt another method.
return audiounit_get_preferred_channel_layout(output_unit);
}
assert(size > 0);
auto layout = make_sized_audio_channel_layout(size);
rv = AudioUnitGetProperty(output_unit, kAudioUnitProperty_AudioChannelLayout,
kAudioUnitScope_Output, AU_OUT_BUS, layout.get(),
&size);
if (rv != noErr) {
LOG("AudioUnitGetProperty/kAudioUnitProperty_AudioChannelLayout rv=%d", rv);
return CUBEB_LAYOUT_UNDEFINED;
}
return audiounit_convert_channel_layout(layout.get());
}
static int
audiounit_create_unit(AudioUnit * unit, device_info * device);
static OSStatus
audiounit_remove_device_listener(cubeb * context, cubeb_device_type devtype);
static void
audiounit_destroy(cubeb * ctx)
{
{
auto_lock lock(ctx->mutex);
// Disabling this assert for bug 1083664 -- we seem to leak a stream
// assert(ctx->active_streams == 0);
if (audiounit_active_streams(ctx) > 0) {
LOG("(%p) API misuse, %d streams active when context destroyed!", ctx,
audiounit_active_streams(ctx));
}
// Destroying a cubeb context with device collection callbacks registered
// is misuse of the API, assert then attempt to clean up.
assert(!ctx->input_collection_changed_callback &&
!ctx->input_collection_changed_user_ptr &&
!ctx->output_collection_changed_callback &&
!ctx->output_collection_changed_user_ptr);
/* Unregister the callback if necessary. */
if (ctx->input_collection_changed_callback) {
audiounit_remove_device_listener(ctx, CUBEB_DEVICE_TYPE_INPUT);
}
if (ctx->output_collection_changed_callback) {
audiounit_remove_device_listener(ctx, CUBEB_DEVICE_TYPE_OUTPUT);
}
}
dispatch_release(ctx->serial_queue);
delete ctx;
}
static void
audiounit_stream_destroy(cubeb_stream * stm);
static int
audio_stream_desc_init(AudioStreamBasicDescription * ss,
const cubeb_stream_params * stream_params)
{
switch (stream_params->format) {
case CUBEB_SAMPLE_S16LE:
ss->mBitsPerChannel = 16;
ss->mFormatFlags = kAudioFormatFlagIsSignedInteger;
break;
case CUBEB_SAMPLE_S16BE:
ss->mBitsPerChannel = 16;
ss->mFormatFlags =
kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsBigEndian;
break;
case CUBEB_SAMPLE_FLOAT32LE:
ss->mBitsPerChannel = 32;
ss->mFormatFlags = kAudioFormatFlagIsFloat;
break;
case CUBEB_SAMPLE_FLOAT32BE:
ss->mBitsPerChannel = 32;
ss->mFormatFlags = kAudioFormatFlagIsFloat | kAudioFormatFlagIsBigEndian;
break;
default:
return CUBEB_ERROR_INVALID_FORMAT;
}
ss->mFormatID = kAudioFormatLinearPCM;
ss->mFormatFlags |= kLinearPCMFormatFlagIsPacked;
ss->mSampleRate = stream_params->rate;
ss->mChannelsPerFrame = stream_params->channels;
ss->mBytesPerFrame = (ss->mBitsPerChannel / 8) * ss->mChannelsPerFrame;
ss->mFramesPerPacket = 1;
ss->mBytesPerPacket = ss->mBytesPerFrame * ss->mFramesPerPacket;
ss->mReserved = 0;
return CUBEB_OK;
}
void
audiounit_init_mixer(cubeb_stream * stm)
{
// We can't rely on macOS' AudioUnit to properly downmix (or upmix) the audio
// data, it silently drop the channels so we need to remix the
// audio data by ourselves to keep all the information.
stm->mixer.reset(cubeb_mixer_create(
stm->output_stream_params.format, stm->output_stream_params.channels,
stm->output_stream_params.layout, stm->context->channels,
stm->context->layout));
assert(stm->mixer);
}
static int
audiounit_set_channel_layout(AudioUnit unit, io_side side,
cubeb_channel_layout layout)
{
if (side != io_side::OUTPUT) {
return CUBEB_ERROR;
}
if (layout == CUBEB_LAYOUT_UNDEFINED) {
// We leave everything as-is...
return CUBEB_OK;
}
OSStatus r;
uint32_t nb_channels = cubeb_channel_layout_nb_channels(layout);
// We do not use CoreAudio standard layout for lack of documentation on what
// the actual channel orders are. So we set a custom layout.
size_t size = offsetof(AudioChannelLayout, mChannelDescriptions[nb_channels]);
auto au_layout = make_sized_audio_channel_layout(size);
au_layout->mChannelLayoutTag = kAudioChannelLayoutTag_UseChannelDescriptions;
au_layout->mNumberChannelDescriptions = nb_channels;
uint32_t channels = 0;
cubeb_channel_layout channelMap = layout;
for (uint32_t i = 0; channelMap != 0; ++i) {
XASSERT(channels < nb_channels);
uint32_t channel = (channelMap & 1) << i;
if (channel != 0) {
au_layout->mChannelDescriptions[channels].mChannelLabel =
cubeb_channel_to_channel_label(static_cast<cubeb_channel>(channel));
au_layout->mChannelDescriptions[channels].mChannelFlags =
kAudioChannelFlags_AllOff;
channels++;
}
channelMap = channelMap >> 1;
}
r = AudioUnitSetProperty(unit, kAudioUnitProperty_AudioChannelLayout,
kAudioUnitScope_Input, AU_OUT_BUS, au_layout.get(),
size);
if (r != noErr) {
LOG("AudioUnitSetProperty/%s/kAudioUnitProperty_AudioChannelLayout rv=%d",
to_string(side), r);
return CUBEB_ERROR;
}
return CUBEB_OK;
}
void
audiounit_layout_init(cubeb_stream * stm, io_side side)
{
// We currently don't support the input layout setting.
if (side == io_side::INPUT) {
return;
}
stm->context->layout = audiounit_get_current_channel_layout(stm->output_unit);
audiounit_set_channel_layout(stm->output_unit, io_side::OUTPUT,
stm->context->layout);
}
static vector<AudioObjectID>
audiounit_get_sub_devices(AudioDeviceID device_id)
{
vector<AudioDeviceID> sub_devices;
AudioObjectPropertyAddress property_address = {
kAudioAggregateDevicePropertyActiveSubDeviceList,
kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster};
UInt32 size = 0;
OSStatus rv = AudioObjectGetPropertyDataSize(device_id, &property_address, 0,
nullptr, &size);
if (rv != noErr) {
sub_devices.push_back(device_id);
return sub_devices;
}
uint32_t count = static_cast<uint32_t>(size / sizeof(AudioObjectID));
sub_devices.resize(count);
rv = AudioObjectGetPropertyData(device_id, &property_address, 0, nullptr,
&size, sub_devices.data());
if (rv != noErr) {
sub_devices.clear();
sub_devices.push_back(device_id);
} else {
LOG("Found %u sub-devices", count);
}
return sub_devices;
}
static int
audiounit_create_blank_aggregate_device(AudioObjectID * plugin_id,
AudioDeviceID * aggregate_device_id)
{
AudioObjectPropertyAddress address_plugin_bundle_id = {
kAudioHardwarePropertyPlugInForBundleID, kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster};
UInt32 size = 0;
OSStatus r = AudioObjectGetPropertyDataSize(
kAudioObjectSystemObject, &address_plugin_bundle_id, 0, NULL, &size);
if (r != noErr) {
LOG("AudioObjectGetPropertyDataSize/"
"kAudioHardwarePropertyPlugInForBundleID, rv=%d",
r);
return CUBEB_ERROR;
}
AudioValueTranslation translation_value;
CFStringRef in_bundle_ref = CFSTR("com.apple.audio.CoreAudio");
translation_value.mInputData = &in_bundle_ref;
translation_value.mInputDataSize = sizeof(in_bundle_ref);
translation_value.mOutputData = plugin_id;
translation_value.mOutputDataSize = sizeof(*plugin_id);
r = AudioObjectGetPropertyData(kAudioObjectSystemObject,
&address_plugin_bundle_id, 0, nullptr, &size,
&translation_value);
if (r != noErr) {
LOG("AudioObjectGetPropertyData/kAudioHardwarePropertyPlugInForBundleID, "
"rv=%d",
r);
return CUBEB_ERROR;
}
AudioObjectPropertyAddress create_aggregate_device_address = {
kAudioPlugInCreateAggregateDevice, kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster};
r = AudioObjectGetPropertyDataSize(
*plugin_id, &create_aggregate_device_address, 0, nullptr, &size);
if (r != noErr) {
LOG("AudioObjectGetPropertyDataSize/kAudioPlugInCreateAggregateDevice, "
"rv=%d",
r);
return CUBEB_ERROR;
}
CFMutableDictionaryRef aggregate_device_dict = CFDictionaryCreateMutable(
kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks);
struct timeval timestamp;
gettimeofday(×tamp, NULL);
long long int time_id = timestamp.tv_sec * 1000000LL + timestamp.tv_usec;
CFStringRef aggregate_device_name = CFStringCreateWithFormat(
NULL, NULL, CFSTR("%s_%llx"), PRIVATE_AGGREGATE_DEVICE_NAME, time_id);
CFDictionaryAddValue(aggregate_device_dict,
CFSTR(kAudioAggregateDeviceNameKey),
aggregate_device_name);
CFRelease(aggregate_device_name);
CFStringRef aggregate_device_UID =
CFStringCreateWithFormat(NULL, NULL, CFSTR("org.mozilla.%s_%llx"),
PRIVATE_AGGREGATE_DEVICE_NAME, time_id);
CFDictionaryAddValue(aggregate_device_dict,
CFSTR(kAudioAggregateDeviceUIDKey),
aggregate_device_UID);
CFRelease(aggregate_device_UID);
int private_value = 1;
CFNumberRef aggregate_device_private_key =
CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &private_value);
CFDictionaryAddValue(aggregate_device_dict,
CFSTR(kAudioAggregateDeviceIsPrivateKey),
aggregate_device_private_key);
CFRelease(aggregate_device_private_key);
int stacked_value = 0;
CFNumberRef aggregate_device_stacked_key =
CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &stacked_value);
CFDictionaryAddValue(aggregate_device_dict,
CFSTR(kAudioAggregateDeviceIsStackedKey),
aggregate_device_stacked_key);
CFRelease(aggregate_device_stacked_key);
r = AudioObjectGetPropertyData(*plugin_id, &create_aggregate_device_address,
sizeof(aggregate_device_dict),
&aggregate_device_dict, &size,
aggregate_device_id);
CFRelease(aggregate_device_dict);
if (r != noErr) {
LOG("AudioObjectGetPropertyData/kAudioPlugInCreateAggregateDevice, rv=%d",
r);
return CUBEB_ERROR;
}
LOG("New aggregate device %u", *aggregate_device_id);
return CUBEB_OK;
}
// The returned CFStringRef object needs to be released (via CFRelease)
// if it's not NULL, since the reference count of the returned CFStringRef
// object is increased.
static CFStringRef
get_device_name(AudioDeviceID id)
{
UInt32 size = sizeof(CFStringRef);
CFStringRef UIname = nullptr;
AudioObjectPropertyAddress address_uuid = {kAudioDevicePropertyDeviceUID,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster};
OSStatus err =
AudioObjectGetPropertyData(id, &address_uuid, 0, nullptr, &size, &UIname);
return (err == noErr) ? UIname : NULL;
}
static int
audiounit_set_aggregate_sub_device_list(AudioDeviceID aggregate_device_id,
AudioDeviceID input_device_id,
AudioDeviceID output_device_id)
{
LOG("Add devices input %u and output %u into aggregate device %u",
input_device_id, output_device_id, aggregate_device_id);
const vector<AudioDeviceID> output_sub_devices =
audiounit_get_sub_devices(output_device_id);
const vector<AudioDeviceID> input_sub_devices =
audiounit_get_sub_devices(input_device_id);
CFMutableArrayRef aggregate_sub_devices_array =
CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
/* The order of the items in the array is significant and is used to determine
the order of the streams of the AudioAggregateDevice. */
for (UInt32 i = 0; i < output_sub_devices.size(); i++) {
CFStringRef ref = get_device_name(output_sub_devices[i]);
if (ref == NULL) {
CFRelease(aggregate_sub_devices_array);
return CUBEB_ERROR;
}
CFArrayAppendValue(aggregate_sub_devices_array, ref);
CFRelease(ref);
}
for (UInt32 i = 0; i < input_sub_devices.size(); i++) {
CFStringRef ref = get_device_name(input_sub_devices[i]);
if (ref == NULL) {
CFRelease(aggregate_sub_devices_array);
return CUBEB_ERROR;
}
CFArrayAppendValue(aggregate_sub_devices_array, ref);
CFRelease(ref);
}
AudioObjectPropertyAddress aggregate_sub_device_list = {
kAudioAggregateDevicePropertyFullSubDeviceList,
kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster};
UInt32 size = sizeof(CFMutableArrayRef);
OSStatus rv = AudioObjectSetPropertyData(
aggregate_device_id, &aggregate_sub_device_list, 0, nullptr, size,
&aggregate_sub_devices_array);
CFRelease(aggregate_sub_devices_array);
if (rv != noErr) {
LOG("AudioObjectSetPropertyData/"
"kAudioAggregateDevicePropertyFullSubDeviceList, rv=%d",
rv);
return CUBEB_ERROR;
}
return CUBEB_OK;
}
static int
audiounit_set_master_aggregate_device(const AudioDeviceID aggregate_device_id)
{
assert(aggregate_device_id != kAudioObjectUnknown);
AudioObjectPropertyAddress master_aggregate_sub_device = {
kAudioAggregateDevicePropertyMasterSubDevice,
kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster};
// Master become the 1st output sub device
AudioDeviceID output_device_id =
audiounit_get_default_device_id(CUBEB_DEVICE_TYPE_OUTPUT);
const vector<AudioDeviceID> output_sub_devices =
audiounit_get_sub_devices(output_device_id);
CFStringRef master_sub_device = get_device_name(output_sub_devices[0]);
UInt32 size = sizeof(CFStringRef);
OSStatus rv = AudioObjectSetPropertyData(aggregate_device_id,
&master_aggregate_sub_device, 0,
NULL, size, &master_sub_device);
if (master_sub_device) {
CFRelease(master_sub_device);
}
if (rv != noErr) {
LOG("AudioObjectSetPropertyData/"
"kAudioAggregateDevicePropertyMasterSubDevice, rv=%d",
rv);
return CUBEB_ERROR;
}
return CUBEB_OK;
}
static int
audiounit_activate_clock_drift_compensation(
const AudioDeviceID aggregate_device_id)
{
assert(aggregate_device_id != kAudioObjectUnknown);
AudioObjectPropertyAddress address_owned = {
kAudioObjectPropertyOwnedObjects, kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster};
UInt32 qualifier_data_size = sizeof(AudioObjectID);
AudioClassID class_id = kAudioSubDeviceClassID;
void * qualifier_data = &class_id;
UInt32 size = 0;
OSStatus rv = AudioObjectGetPropertyDataSize(
aggregate_device_id, &address_owned, qualifier_data_size, qualifier_data,
&size);
if (rv != noErr) {
LOG("AudioObjectGetPropertyDataSize/kAudioObjectPropertyOwnedObjects, "
"rv=%d",
rv);
return CUBEB_ERROR;
}
UInt32 subdevices_num = 0;
subdevices_num = size / sizeof(AudioObjectID);
AudioObjectID sub_devices[subdevices_num];
size = sizeof(sub_devices);
rv = AudioObjectGetPropertyData(aggregate_device_id, &address_owned,
qualifier_data_size, qualifier_data, &size,
sub_devices);
if (rv != noErr) {
LOG("AudioObjectGetPropertyData/kAudioObjectPropertyOwnedObjects, rv=%d",
rv);
return CUBEB_ERROR;
}
AudioObjectPropertyAddress address_drift = {
kAudioSubDevicePropertyDriftCompensation, kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster};
// Start from the second device since the first is the master clock
for (UInt32 i = 1; i < subdevices_num; ++i) {
UInt32 drift_compensation_value = 1;
rv = AudioObjectSetPropertyData(sub_devices[i], &address_drift, 0, nullptr,
sizeof(UInt32), &drift_compensation_value);
if (rv != noErr) {
LOG("AudioObjectSetPropertyData/"
"kAudioSubDevicePropertyDriftCompensation, rv=%d",
rv);
return CUBEB_OK;
}
}
return CUBEB_OK;
}
static int
audiounit_destroy_aggregate_device(AudioObjectID plugin_id,
AudioDeviceID * aggregate_device_id);
static void
audiounit_get_available_samplerate(AudioObjectID devid,
AudioObjectPropertyScope scope,
uint32_t * min, uint32_t * max,
uint32_t * def);
static int
audiounit_create_device_from_hwdev(cubeb_device_info * dev_info,
AudioObjectID devid, cubeb_device_type type);
static void
audiounit_device_destroy(cubeb_device_info * device);
static void
audiounit_workaround_for_airpod(cubeb_stream * stm)
{
cubeb_device_info input_device_info;
audiounit_create_device_from_hwdev(&input_device_info, stm->input_device.id,
CUBEB_DEVICE_TYPE_INPUT);
cubeb_device_info output_device_info;
audiounit_create_device_from_hwdev(&output_device_info, stm->output_device.id,
CUBEB_DEVICE_TYPE_OUTPUT);
std::string input_name_str(input_device_info.friendly_name);
std::string output_name_str(output_device_info.friendly_name);
if (input_name_str.find("AirPods") != std::string::npos &&
output_name_str.find("AirPods") != std::string::npos) {
uint32_t input_min_rate = 0;
uint32_t input_max_rate = 0;
uint32_t input_nominal_rate = 0;
audiounit_get_available_samplerate(
stm->input_device.id, kAudioObjectPropertyScopeGlobal, &input_min_rate,
&input_max_rate, &input_nominal_rate);
LOG("(%p) Input device %u, name: %s, min: %u, max: %u, nominal rate: %u",
stm, stm->input_device.id, input_device_info.friendly_name,
input_min_rate, input_max_rate, input_nominal_rate);
uint32_t output_min_rate = 0;
uint32_t output_max_rate = 0;
uint32_t output_nominal_rate = 0;
audiounit_get_available_samplerate(
stm->output_device.id, kAudioObjectPropertyScopeGlobal,
&output_min_rate, &output_max_rate, &output_nominal_rate);
LOG("(%p) Output device %u, name: %s, min: %u, max: %u, nominal rate: %u",
stm, stm->output_device.id, output_device_info.friendly_name,
output_min_rate, output_max_rate, output_nominal_rate);
Float64 rate = input_nominal_rate;
AudioObjectPropertyAddress addr = {kAudioDevicePropertyNominalSampleRate,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster};
OSStatus rv = AudioObjectSetPropertyData(stm->aggregate_device_id, &addr, 0,
nullptr, sizeof(Float64), &rate);
if (rv != noErr) {
LOG("Non fatal error, "
"AudioObjectSetPropertyData/kAudioDevicePropertyNominalSampleRate, "
"rv=%d",
rv);
}
}
audiounit_device_destroy(&input_device_info);
audiounit_device_destroy(&output_device_info);
}
/*
* Aggregate Device is a virtual audio interface which utilizes inputs and
* outputs of one or more physical audio interfaces. It is possible to use the
* clock of one of the devices as a master clock for all the combined devices
* and enable drift compensation for the devices that are not designated clock
* master.
*
* Creating a new aggregate device programmatically requires [0][1]:
* 1. Locate the base plug-in ("com.apple.audio.CoreAudio")
* 2. Create a dictionary that describes the aggregate device
* (don't add sub-devices in that step, prone to fail [0])
* 3. Ask the base plug-in to create the aggregate device (blank)
* 4. Add the array of sub-devices.
* 5. Set the master device (1st output device in our case)
* 6. Enable drift compensation for the non-master devices
*
* [0] https://lists.apple.com/archives/coreaudio-api/2006/Apr/msg00092.html
* [1] https://lists.apple.com/archives/coreaudio-api/2005/Jul/msg00150.html
* [2] CoreAudio.framework/Headers/AudioHardware.h
* */
static int
audiounit_create_aggregate_device(cubeb_stream * stm)
{
int r = audiounit_create_blank_aggregate_device(&stm->plugin_id,
&stm->aggregate_device_id);
if (r != CUBEB_OK) {
LOG("(%p) Failed to create blank aggregate device", stm);
return CUBEB_ERROR;
}
r = audiounit_set_aggregate_sub_device_list(
stm->aggregate_device_id, stm->input_device.id, stm->output_device.id);
if (r != CUBEB_OK) {
LOG("(%p) Failed to set aggregate sub-device list", stm);
audiounit_destroy_aggregate_device(stm->plugin_id,
&stm->aggregate_device_id);
return CUBEB_ERROR;
}
r = audiounit_set_master_aggregate_device(stm->aggregate_device_id);
if (r != CUBEB_OK) {
LOG("(%p) Failed to set master sub-device for aggregate device", stm);
audiounit_destroy_aggregate_device(stm->plugin_id,
&stm->aggregate_device_id);
return CUBEB_ERROR;
}
r = audiounit_activate_clock_drift_compensation(stm->aggregate_device_id);
if (r != CUBEB_OK) {
LOG("(%p) Failed to activate clock drift compensation for aggregate device",
stm);
audiounit_destroy_aggregate_device(stm->plugin_id,
&stm->aggregate_device_id);
return CUBEB_ERROR;
}
audiounit_workaround_for_airpod(stm);
return CUBEB_OK;
}
static int
audiounit_destroy_aggregate_device(AudioObjectID plugin_id,
AudioDeviceID * aggregate_device_id)
{
assert(aggregate_device_id && *aggregate_device_id != kAudioDeviceUnknown &&
plugin_id != kAudioObjectUnknown);
AudioObjectPropertyAddress destroy_aggregate_device_addr = {
kAudioPlugInDestroyAggregateDevice, kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster};
UInt32 size;
OSStatus rv = AudioObjectGetPropertyDataSize(
plugin_id, &destroy_aggregate_device_addr, 0, NULL, &size);
if (rv != noErr) {
LOG("AudioObjectGetPropertyDataSize/kAudioPlugInDestroyAggregateDevice, "
"rv=%d",
rv);
return CUBEB_ERROR;
}
rv = AudioObjectGetPropertyData(plugin_id, &destroy_aggregate_device_addr, 0,
NULL, &size, aggregate_device_id);
if (rv != noErr) {
LOG("AudioObjectGetPropertyData/kAudioPlugInDestroyAggregateDevice, rv=%d",
rv);
return CUBEB_ERROR;
}
LOG("Destroyed aggregate device %d", *aggregate_device_id);
*aggregate_device_id = kAudioObjectUnknown;
return CUBEB_OK;
}
static int
audiounit_new_unit_instance(AudioUnit * unit, device_info * device)
{
AudioComponentDescription desc;
AudioComponent comp;
OSStatus rv;
desc.componentType = kAudioUnitType_Output;
#if TARGET_OS_IPHONE
desc.componentSubType = kAudioUnitSubType_RemoteIO;
#else
// Use the DefaultOutputUnit for output when no device is specified
// so we retain automatic output device switching when the default
// changes. Once we have complete support for device notifications
// and switching, we can use the AUHAL for everything.
if ((device->flags & DEV_SYSTEM_DEFAULT) && (device->flags & DEV_OUTPUT)) {
desc.componentSubType = kAudioUnitSubType_DefaultOutput;
} else {
desc.componentSubType = kAudioUnitSubType_HALOutput;
}
#endif
desc.componentManufacturer = kAudioUnitManufacturer_Apple;
desc.componentFlags = 0;
desc.componentFlagsMask = 0;
comp = AudioComponentFindNext(NULL, &desc);
if (comp == NULL) {
LOG("Could not find matching audio hardware.");
return CUBEB_ERROR;
}
rv = AudioComponentInstanceNew(comp, unit);
if (rv != noErr) {
LOG("AudioComponentInstanceNew rv=%d", rv);
return CUBEB_ERROR;
}
return CUBEB_OK;
}
enum enable_state {
DISABLE,
ENABLE,
};
static int
audiounit_enable_unit_scope(AudioUnit * unit, io_side side, enable_state state)
{
OSStatus rv;
UInt32 enable = state;
rv = AudioUnitSetProperty(*unit, kAudioOutputUnitProperty_EnableIO,
(side == io_side::INPUT) ? kAudioUnitScope_Input
: kAudioUnitScope_Output,
(side == io_side::INPUT) ? AU_IN_BUS : AU_OUT_BUS,
&enable, sizeof(UInt32));
if (rv != noErr) {
LOG("AudioUnitSetProperty/kAudioOutputUnitProperty_EnableIO rv=%d", rv);
return CUBEB_ERROR;
}
return CUBEB_OK;
}
static int
audiounit_create_unit(AudioUnit * unit, device_info * device)
{
assert(*unit == nullptr);
assert(device);
OSStatus rv;
int r;
r = audiounit_new_unit_instance(unit, device);
if (r != CUBEB_OK) {
return r;
}
assert(*unit);
if ((device->flags & DEV_SYSTEM_DEFAULT) && (device->flags & DEV_OUTPUT)) {
return CUBEB_OK;
}
if (device->flags & DEV_INPUT) {
r = audiounit_enable_unit_scope(unit, io_side::INPUT, ENABLE);
if (r != CUBEB_OK) {
LOG("Failed to enable audiounit input scope");
return r;
}
r = audiounit_enable_unit_scope(unit, io_side::OUTPUT, DISABLE);
if (r != CUBEB_OK) {
LOG("Failed to disable audiounit output scope");
return r;
}
} else if (device->flags & DEV_OUTPUT) {
r = audiounit_enable_unit_scope(unit, io_side::OUTPUT, ENABLE);
if (r != CUBEB_OK) {
LOG("Failed to enable audiounit output scope");
return r;
}
r = audiounit_enable_unit_scope(unit, io_side::INPUT, DISABLE);
if (r != CUBEB_OK) {
LOG("Failed to disable audiounit input scope");
return r;
}
} else {
assert(false);
}
rv = AudioUnitSetProperty(*unit, kAudioOutputUnitProperty_CurrentDevice,
kAudioUnitScope_Global, 0, &device->id,
sizeof(AudioDeviceID));
if (rv != noErr) {
LOG("AudioUnitSetProperty/kAudioOutputUnitProperty_CurrentDevice rv=%d",
rv);
return CUBEB_ERROR;
}
return CUBEB_OK;
}
static int
audiounit_init_input_linear_buffer(cubeb_stream * stream, uint32_t capacity)
{
uint32_t size =
capacity * stream->latency_frames * stream->input_desc.mChannelsPerFrame;
if (stream->input_desc.mFormatFlags & kAudioFormatFlagIsSignedInteger) {
stream->input_linear_buffer.reset(new auto_array_wrapper_impl<short>(size));
} else {
stream->input_linear_buffer.reset(new auto_array_wrapper_impl<float>(size));
}
assert(stream->input_linear_buffer->length() == 0);
return CUBEB_OK;
}
static uint32_t
audiounit_clamp_latency(cubeb_stream * stm, uint32_t latency_frames)
{
// For the 1st stream set anything within safe min-max
assert(audiounit_active_streams(stm->context) > 0);
if (audiounit_active_streams(stm->context) == 1) {
return max(min<uint32_t>(latency_frames, SAFE_MAX_LATENCY_FRAMES),
SAFE_MIN_LATENCY_FRAMES);
}
assert(stm->output_unit);
// If more than one stream operates in parallel
// allow only lower values of latency
int r;
UInt32 output_buffer_size = 0;
UInt32 size = sizeof(output_buffer_size);
if (stm->output_unit) {
r = AudioUnitGetProperty(
stm->output_unit, kAudioDevicePropertyBufferFrameSize,
kAudioUnitScope_Output, AU_OUT_BUS, &output_buffer_size, &size);
if (r != noErr) {
LOG("AudioUnitGetProperty/output/kAudioDevicePropertyBufferFrameSize "
"rv=%d",
r);
return 0;
}
output_buffer_size =
max(min<uint32_t>(output_buffer_size, SAFE_MAX_LATENCY_FRAMES),
SAFE_MIN_LATENCY_FRAMES);
}
UInt32 input_buffer_size = 0;
if (stm->input_unit) {
r = AudioUnitGetProperty(
stm->input_unit, kAudioDevicePropertyBufferFrameSize,
kAudioUnitScope_Input, AU_IN_BUS, &input_buffer_size, &size);
if (r != noErr) {
LOG("AudioUnitGetProperty/input/kAudioDevicePropertyBufferFrameSize "
"rv=%d",
r);
return 0;
}
input_buffer_size =
max(min<uint32_t>(input_buffer_size, SAFE_MAX_LATENCY_FRAMES),
SAFE_MIN_LATENCY_FRAMES);
}
// Every following active streams can only set smaller latency
UInt32 upper_latency_limit = 0;
if (input_buffer_size != 0 && output_buffer_size != 0) {
upper_latency_limit = min<uint32_t>(input_buffer_size, output_buffer_size);
} else if (input_buffer_size != 0) {
upper_latency_limit = input_buffer_size;
} else if (output_buffer_size != 0) {
upper_latency_limit = output_buffer_size;
} else {
upper_latency_limit = SAFE_MAX_LATENCY_FRAMES;
}
return max(min<uint32_t>(latency_frames, upper_latency_limit),
SAFE_MIN_LATENCY_FRAMES);
}
/*
* Change buffer size is prone to deadlock thus we change it
* following the steps:
* - register a listener for the buffer size property
* - change the property
* - wait until the listener is executed
* - property has changed, remove the listener
* */
static void
buffer_size_changed_callback(void * inClientData, AudioUnit inUnit,
AudioUnitPropertyID inPropertyID,
AudioUnitScope inScope, AudioUnitElement inElement)
{
cubeb_stream * stm = (cubeb_stream *)inClientData;
AudioUnit au = inUnit;
AudioUnitScope au_scope = kAudioUnitScope_Input;
AudioUnitElement au_element = inElement;
char const * au_type = "output";
if (AU_IN_BUS == inElement) {
au_scope = kAudioUnitScope_Output;
au_type = "input";
}
switch (inPropertyID) {
case kAudioDevicePropertyBufferFrameSize: {
if (inScope != au_scope) {
break;
}
UInt32 new_buffer_size;
UInt32 outSize = sizeof(UInt32);
OSStatus r =
AudioUnitGetProperty(au, kAudioDevicePropertyBufferFrameSize, au_scope,
au_element, &new_buffer_size, &outSize);
if (r != noErr) {
LOG("(%p) Event: kAudioDevicePropertyBufferFrameSize: Cannot get current "
"buffer size",
stm);
} else {
LOG("(%p) Event: kAudioDevicePropertyBufferFrameSize: New %s buffer size "
"= %d for scope %d",
stm, au_type, new_buffer_size, inScope);
}
stm->buffer_size_change_state = true;
break;
}
}
}
static int
audiounit_set_buffer_size(cubeb_stream * stm, uint32_t new_size_frames,
io_side side)
{
AudioUnit au = stm->output_unit;
AudioUnitScope au_scope = kAudioUnitScope_Input;
AudioUnitElement au_element = AU_OUT_BUS;
if (side == io_side::INPUT) {
au = stm->input_unit;
au_scope = kAudioUnitScope_Output;
au_element = AU_IN_BUS;
}
uint32_t buffer_frames = 0;
UInt32 size = sizeof(buffer_frames);
int r = AudioUnitGetProperty(au, kAudioDevicePropertyBufferFrameSize,
au_scope, au_element, &buffer_frames, &size);
if (r != noErr) {
LOG("AudioUnitGetProperty/%s/kAudioDevicePropertyBufferFrameSize rv=%d",
to_string(side), r);
return CUBEB_ERROR;
}
if (new_size_frames == buffer_frames) {
LOG("(%p) No need to update %s buffer size already %u frames", stm,
to_string(side), buffer_frames);
return CUBEB_OK;
}
r = AudioUnitAddPropertyListener(au, kAudioDevicePropertyBufferFrameSize,
buffer_size_changed_callback, stm);
if (r != noErr) {
LOG("AudioUnitAddPropertyListener/%s/kAudioDevicePropertyBufferFrameSize "
"rv=%d",
to_string(side), r);
return CUBEB_ERROR;
}
stm->buffer_size_change_state = false;
r = AudioUnitSetProperty(au, kAudioDevicePropertyBufferFrameSize, au_scope,
au_element, &new_size_frames,
sizeof(new_size_frames));
if (r != noErr) {
LOG("AudioUnitSetProperty/%s/kAudioDevicePropertyBufferFrameSize rv=%d",
to_string(side), r);
r = AudioUnitRemovePropertyListenerWithUserData(
au, kAudioDevicePropertyBufferFrameSize, buffer_size_changed_callback,
stm);
if (r != noErr) {
LOG("AudioUnitAddPropertyListener/%s/kAudioDevicePropertyBufferFrameSize "
"rv=%d",
to_string(side), r);
}
return CUBEB_ERROR;
}
int count = 0;
while (!stm->buffer_size_change_state && count++ < 30) {
struct timespec req, rem;
req.tv_sec = 0;
req.tv_nsec = 100000000L; // 0.1 sec
if (nanosleep(&req, &rem) < 0) {
LOG("(%p) Warning: nanosleep call failed or interrupted. Remaining time "
"%ld nano secs \n",
stm, rem.tv_nsec);
}
LOG("(%p) audiounit_set_buffer_size : wait count = %d", stm, count);
}
r = AudioUnitRemovePropertyListenerWithUserData(
au, kAudioDevicePropertyBufferFrameSize, buffer_size_changed_callback,
stm);
if (r != noErr) {
LOG("AudioUnitAddPropertyListener/%s/kAudioDevicePropertyBufferFrameSize "
"rv=%d",
to_string(side), r);
return CUBEB_ERROR;
}
if (!stm->buffer_size_change_state && count >= 30) {
LOG("(%p) Error, did not get buffer size change callback ...", stm);
return CUBEB_ERROR;
}
LOG("(%p) %s buffer size changed to %u frames.", stm, to_string(side),
new_size_frames);
return CUBEB_OK;
}
static int
audiounit_configure_input(cubeb_stream * stm)
{
assert(stm && stm->input_unit);
int r = 0;
UInt32 size;
AURenderCallbackStruct aurcbs_in;
LOG("(%p) Opening input side: rate %u, channels %u, format %d, latency in "
"frames %u.",
stm, stm->input_stream_params.rate, stm->input_stream_params.channels,
stm->input_stream_params.format, stm->latency_frames);
/* Get input device sample rate. */
AudioStreamBasicDescription input_hw_desc;
size = sizeof(AudioStreamBasicDescription);
r = AudioUnitGetProperty(stm->input_unit, kAudioUnitProperty_StreamFormat,
kAudioUnitScope_Input, AU_IN_BUS, &input_hw_desc,
&size);
if (r != noErr) {
LOG("AudioUnitGetProperty/input/kAudioUnitProperty_StreamFormat rv=%d", r);
return CUBEB_ERROR;
}
stm->input_hw_rate = input_hw_desc.mSampleRate;
LOG("(%p) Input device sampling rate: %.2f", stm, stm->input_hw_rate);
/* Set format description according to the input params. */
r = audio_stream_desc_init(&stm->input_desc, &stm->input_stream_params);
if (r != CUBEB_OK) {
LOG("(%p) Setting format description for input failed.", stm);
return r;
}
// Use latency to set buffer size
r = audiounit_set_buffer_size(stm, stm->latency_frames, io_side::INPUT);
if (r != CUBEB_OK) {
LOG("(%p) Error in change input buffer size.", stm);
return CUBEB_ERROR;
}
AudioStreamBasicDescription src_desc = stm->input_desc;
/* Input AudioUnit must be configured with device's sample rate.
we will resample inside input callback. */
src_desc.mSampleRate = stm->input_hw_rate;
r = AudioUnitSetProperty(stm->input_unit, kAudioUnitProperty_StreamFormat,
kAudioUnitScope_Output, AU_IN_BUS, &src_desc,
sizeof(AudioStreamBasicDescription));
if (r != noErr) {
LOG("AudioUnitSetProperty/input/kAudioUnitProperty_StreamFormat rv=%d", r);
return CUBEB_ERROR;
}
/* Frames per buffer in the input callback. */
r = AudioUnitSetProperty(
stm->input_unit, kAudioUnitProperty_MaximumFramesPerSlice,
kAudioUnitScope_Global, AU_IN_BUS, &stm->latency_frames, sizeof(UInt32));
if (r != noErr) {
LOG("AudioUnitSetProperty/input/kAudioUnitProperty_MaximumFramesPerSlice "
"rv=%d",
r);
return CUBEB_ERROR;
}
// Input only capacity
unsigned int array_capacity = 1;
if (has_output(stm)) {
// Full-duplex increase capacity
array_capacity = 8;
}
if (audiounit_init_input_linear_buffer(stm, array_capacity) != CUBEB_OK) {
return CUBEB_ERROR;
}
aurcbs_in.inputProc = audiounit_input_callback;
aurcbs_in.inputProcRefCon = stm;
r = AudioUnitSetProperty(
stm->input_unit, kAudioOutputUnitProperty_SetInputCallback,
kAudioUnitScope_Global, AU_OUT_BUS, &aurcbs_in, sizeof(aurcbs_in));
if (r != noErr) {
LOG("AudioUnitSetProperty/input/kAudioOutputUnitProperty_SetInputCallback "
"rv=%d",
r);
return CUBEB_ERROR;
}
stm->frames_read = 0;
LOG("(%p) Input audiounit init successfully.", stm);
return CUBEB_OK;
}
static int
audiounit_configure_output(cubeb_stream * stm)
{
assert(stm && stm->output_unit);
int r;
AURenderCallbackStruct aurcbs_out;
UInt32 size;
LOG("(%p) Opening output side: rate %u, channels %u, format %d, latency in "
"frames %u.",
stm, stm->output_stream_params.rate, stm->output_stream_params.channels,
stm->output_stream_params.format, stm->latency_frames);
r = audio_stream_desc_init(&stm->output_desc, &stm->output_stream_params);
if (r != CUBEB_OK) {
LOG("(%p) Could not initialize the audio stream description.", stm);
return r;
}
/* Get output device sample rate. */
AudioStreamBasicDescription output_hw_desc;
size = sizeof(AudioStreamBasicDescription);
memset(&output_hw_desc, 0, size);
r = AudioUnitGetProperty(stm->output_unit, kAudioUnitProperty_StreamFormat,
kAudioUnitScope_Output, AU_OUT_BUS, &output_hw_desc,
&size);
if (r != noErr) {
LOG("AudioUnitGetProperty/output/kAudioUnitProperty_StreamFormat rv=%d", r);
return CUBEB_ERROR;
}
stm->output_hw_rate = output_hw_desc.mSampleRate;
LOG("(%p) Output device sampling rate: %.2f", stm,
output_hw_desc.mSampleRate);
stm->context->channels = output_hw_desc.mChannelsPerFrame;
// Set the input layout to match the output device layout.
audiounit_layout_init(stm, io_side::OUTPUT);
if (stm->context->channels != stm->output_stream_params.channels ||
stm->context->layout != stm->output_stream_params.layout) {
LOG("Incompatible channel layouts detected, setting up remixer");
audiounit_init_mixer(stm);
// We will be remixing the data before it reaches the output device.
// We need to adjust the number of channels and other
// AudioStreamDescription details.
stm->output_desc.mChannelsPerFrame = stm->context->channels;
stm->output_desc.mBytesPerFrame = (stm->output_desc.mBitsPerChannel / 8) *
stm->output_desc.mChannelsPerFrame;
stm->output_desc.mBytesPerPacket =
stm->output_desc.mBytesPerFrame * stm->output_desc.mFramesPerPacket;
} else {
stm->mixer = nullptr;
}
r = AudioUnitSetProperty(stm->output_unit, kAudioUnitProperty_StreamFormat,
kAudioUnitScope_Input, AU_OUT_BUS, &stm->output_desc,
sizeof(AudioStreamBasicDescription));
if (r != noErr) {
LOG("AudioUnitSetProperty/output/kAudioUnitProperty_StreamFormat rv=%d", r);
return CUBEB_ERROR;
}
r = audiounit_set_buffer_size(stm, stm->latency_frames, io_side::OUTPUT);
if (r != CUBEB_OK) {
LOG("(%p) Error in change output buffer size.", stm);
return CUBEB_ERROR;
}
/* Frames per buffer in the input callback. */
r = AudioUnitSetProperty(
stm->output_unit, kAudioUnitProperty_MaximumFramesPerSlice,
kAudioUnitScope_Global, AU_OUT_BUS, &stm->latency_frames, sizeof(UInt32));
if (r != noErr) {
LOG("AudioUnitSetProperty/output/kAudioUnitProperty_MaximumFramesPerSlice "
"rv=%d",
r);
return CUBEB_ERROR;
}
aurcbs_out.inputProc = audiounit_output_callback;
aurcbs_out.inputProcRefCon = stm;
r = AudioUnitSetProperty(
stm->output_unit, kAudioUnitProperty_SetRenderCallback,
kAudioUnitScope_Global, AU_OUT_BUS, &aurcbs_out, sizeof(aurcbs_out));
if (r != noErr) {
LOG("AudioUnitSetProperty/output/kAudioUnitProperty_SetRenderCallback "
"rv=%d",
r);
return CUBEB_ERROR;
}
stm->frames_written = 0;
LOG("(%p) Output audiounit init successfully.", stm);
return CUBEB_OK;
}
static int
audiounit_setup_stream(cubeb_stream * stm)
{
stm->mutex.assert_current_thread_owns();
if ((stm->input_stream_params.prefs & CUBEB_STREAM_PREF_LOOPBACK) ||
(stm->output_stream_params.prefs & CUBEB_STREAM_PREF_LOOPBACK)) {
LOG("(%p) Loopback not supported for audiounit.", stm);
return CUBEB_ERROR_NOT_SUPPORTED;
}
int r = 0;
device_info in_dev_info = stm->input_device;
device_info out_dev_info = stm->output_device;
if (has_input(stm) && has_output(stm) &&
stm->input_device.id != stm->output_device.id) {
r = audiounit_create_aggregate_device(stm);
if (r != CUBEB_OK) {
stm->aggregate_device_id = kAudioObjectUnknown;
LOG("(%p) Create aggregate devices failed.", stm);
// !!!NOTE: It is not necessary to return here. If it does not
// return it will fallback to the old implementation. The intention
// is to investigate how often it fails. I plan to remove
// it after a couple of weeks.
return r;
} else {
in_dev_info.id = out_dev_info.id = stm->aggregate_device_id;
in_dev_info.flags = DEV_INPUT;
out_dev_info.flags = DEV_OUTPUT;
}
}
if (has_input(stm)) {
r = audiounit_create_unit(&stm->input_unit, &in_dev_info);
if (r != CUBEB_OK) {
LOG("(%p) AudioUnit creation for input failed.", stm);
return r;
}
}
if (has_output(stm)) {
r = audiounit_create_unit(&stm->output_unit, &out_dev_info);
if (r != CUBEB_OK) {
LOG("(%p) AudioUnit creation for output failed.", stm);
return r;
}
}
/* Latency cannot change if another stream is operating in parallel. In this
* case latency is set to the other stream value. */
if (audiounit_active_streams(stm->context) > 1) {
LOG("(%p) More than one active stream, use global latency.", stm);
stm->latency_frames = stm->context->global_latency_frames;
} else {
/* Silently clamp the latency down to the platform default, because we
* synthetize the clock from the callbacks, and we want the clock to update
* often. */
stm->latency_frames = audiounit_clamp_latency(stm, stm->latency_frames);
assert(stm->latency_frames); // Ugly error check
audiounit_set_global_latency(stm->context, stm->latency_frames);
}
/* Configure I/O stream */
if (has_input(stm)) {
r = audiounit_configure_input(stm);
if (r != CUBEB_OK) {
LOG("(%p) Configure audiounit input failed.", stm);
return r;
}
}
if (has_output(stm)) {
r = audiounit_configure_output(stm);
if (r != CUBEB_OK) {
LOG("(%p) Configure audiounit output failed.", stm);
return r;
}
}
// Setting the latency doesn't work well for USB headsets (eg. plantronics).
// Keep the default latency for now.
#if 0
buffer_size = latency;
/* Get the range of latency this particular device can work with, and clamp
* the requested latency to this acceptable range. */
#if !TARGET_OS_IPHONE
if (audiounit_get_acceptable_latency_range(&latency_range) != CUBEB_OK) {
return CUBEB_ERROR;
}
if (buffer_size < (unsigned int) latency_range.mMinimum) {
buffer_size = (unsigned int) latency_range.mMinimum;
} else if (buffer_size > (unsigned int) latency_range.mMaximum) {
buffer_size = (unsigned int) latency_range.mMaximum;
}
/**
* Get the default buffer size. If our latency request is below the default,
* set it. Otherwise, use the default latency.
**/
size = sizeof(default_buffer_size);
if (AudioUnitGetProperty(stm->output_unit, kAudioDevicePropertyBufferFrameSize,
kAudioUnitScope_Output, 0, &default_buffer_size, &size) != 0) {
return CUBEB_ERROR;
}
if (buffer_size < default_buffer_size) {
/* Set the maximum number of frame that the render callback will ask for,
* effectively setting the latency of the stream. This is process-wide. */
if (AudioUnitSetProperty(stm->output_unit, kAudioDevicePropertyBufferFrameSize,
kAudioUnitScope_Output, 0, &buffer_size, sizeof(buffer_size)) != 0) {
return CUBEB_ERROR;
}
}
#else // TARGET_OS_IPHONE
//TODO: [[AVAudioSession sharedInstance] inputLatency]
// http://stackoverflow.com/questions/13157523/kaudiodevicepropertybufferframesize-replacement-for-ios
#endif
#endif
/* We use a resampler because input AudioUnit operates
* reliable only in the capture device sample rate.
* Resampler will convert it to the user sample rate
* and deliver it to the callback. */
uint32_t target_sample_rate;
if (has_input(stm)) {
target_sample_rate = stm->input_stream_params.rate;
} else {
assert(has_output(stm));
target_sample_rate = stm->output_stream_params.rate;
}
cubeb_stream_params input_unconverted_params;
if (has_input(stm)) {
input_unconverted_params = stm->input_stream_params;
/* Use the rate of the input device. */
input_unconverted_params.rate = stm->input_hw_rate;
}
/* Create resampler. Output params are unchanged
* because we do not need conversion on the output. */
stm->resampler.reset(cubeb_resampler_create(
stm, has_input(stm) ? &input_unconverted_params : NULL,
has_output(stm) ? &stm->output_stream_params : NULL, target_sample_rate,
stm->data_callback, stm->user_ptr, CUBEB_RESAMPLER_QUALITY_DESKTOP));
if (!stm->resampler) {
LOG("(%p) Could not create resampler.", stm);
return CUBEB_ERROR;
}
if (stm->input_unit != NULL) {
r = AudioUnitInitialize(stm->input_unit);
if (r != noErr) {
LOG("AudioUnitInitialize/input rv=%d", r);
return CUBEB_ERROR;
}
}
if (stm->output_unit != NULL) {
r = AudioUnitInitialize(stm->output_unit);
if (r != noErr) {
LOG("AudioUnitInitialize/output rv=%d", r);
return CUBEB_ERROR;
}
stm->current_latency_frames = audiounit_get_device_presentation_latency(
stm->output_device.id, kAudioDevicePropertyScopeOutput);
Float64 unit_s;
UInt32 size = sizeof(unit_s);
if (AudioUnitGetProperty(stm->output_unit, kAudioUnitProperty_Latency,
kAudioUnitScope_Global, 0, &unit_s,
&size) == noErr) {
stm->current_latency_frames +=
static_cast<uint32_t>(unit_s * stm->output_desc.mSampleRate);
}
}
if (stm->input_unit && stm->output_unit) {
// According to the I/O hardware rate it is expected a specific pattern of
// callbacks for example is input is 44100 and output is 48000 we expected
// no more than 2 out callback in a row.
stm->expected_output_callbacks_in_a_row =
ceilf(stm->output_hw_rate / stm->input_hw_rate);
}
r = audiounit_install_device_changed_callback(stm);
if (r != CUBEB_OK) {
LOG("(%p) Could not install all device change callback.", stm);
}
return CUBEB_OK;
}
cubeb_stream::cubeb_stream(cubeb * context)
: context(context), resampler(nullptr, cubeb_resampler_destroy),
mixer(nullptr, cubeb_mixer_destroy)
{
PodZero(&input_desc, 1);
PodZero(&output_desc, 1);
}
static void
audiounit_stream_destroy_internal(cubeb_stream * stm);
static int
audiounit_stream_init(cubeb * context, cubeb_stream ** stream,
char const * /* stream_name */, cubeb_devid input_device,
cubeb_stream_params * input_stream_params,
cubeb_devid output_device,
cubeb_stream_params * output_stream_params,
unsigned int latency_frames,
cubeb_data_callback data_callback,
cubeb_state_callback state_callback, void * user_ptr)
{
assert(context);
auto_lock context_lock(context->mutex);
audiounit_increment_active_streams(context);
unique_ptr<cubeb_stream, decltype(&audiounit_stream_destroy)> stm(
new cubeb_stream(context), audiounit_stream_destroy_internal);
int r;
*stream = NULL;
assert(latency_frames > 0);
/* These could be different in the future if we have both
* full-duplex stream and different devices for input vs output. */
stm->data_callback = data_callback;
stm->state_callback = state_callback;
stm->user_ptr = user_ptr;
stm->latency_frames = latency_frames;
if ((input_device && !input_stream_params) ||
(output_device && !output_stream_params)) {
return CUBEB_ERROR_INVALID_PARAMETER;
}
if (input_stream_params) {
stm->input_stream_params = *input_stream_params;
r = audiounit_set_device_info(
stm.get(), reinterpret_cast<uintptr_t>(input_device), io_side::INPUT);
if (r != CUBEB_OK) {
LOG("(%p) Fail to set device info for input.", stm.get());
return r;
}
}
if (output_stream_params) {
stm->output_stream_params = *output_stream_params;
r = audiounit_set_device_info(
stm.get(), reinterpret_cast<uintptr_t>(output_device), io_side::OUTPUT);
if (r != CUBEB_OK) {
LOG("(%p) Fail to set device info for output.", stm.get());
return r;
}
}
{
// It's not critical to lock here, because no other thread has been started
// yet, but it allows to assert that the lock has been taken in
// `audiounit_setup_stream`.
auto_lock lock(stm->mutex);
r = audiounit_setup_stream(stm.get());
}
if (r != CUBEB_OK) {
LOG("(%p) Could not setup the audiounit stream.", stm.get());
return r;
}
r = audiounit_install_system_changed_callback(stm.get());
if (r != CUBEB_OK) {
LOG("(%p) Could not install the device change callback.", stm.get());
return r;
}
*stream = stm.release();
LOG("(%p) Cubeb stream init successful.", *stream);
return CUBEB_OK;
}
static void
audiounit_close_stream(cubeb_stream * stm)
{
stm->mutex.assert_current_thread_owns();
if (stm->input_unit) {
AudioUnitUninitialize(stm->input_unit);
AudioComponentInstanceDispose(stm->input_unit);
stm->input_unit = nullptr;
}
stm->input_linear_buffer.reset();
if (stm->output_unit) {
AudioUnitUninitialize(stm->output_unit);
AudioComponentInstanceDispose(stm->output_unit);
stm->output_unit = nullptr;
}
stm->resampler.reset();
stm->mixer.reset();
if (stm->aggregate_device_id != kAudioObjectUnknown) {
audiounit_destroy_aggregate_device(stm->plugin_id,
&stm->aggregate_device_id);
stm->aggregate_device_id = kAudioObjectUnknown;
}
}
static void
audiounit_stream_destroy_internal(cubeb_stream * stm)
{
stm->context->mutex.assert_current_thread_owns();
int r = audiounit_uninstall_system_changed_callback(stm);
if (r != CUBEB_OK) {
LOG("(%p) Could not uninstall the device changed callback", stm);
}
r = audiounit_uninstall_device_changed_callback(stm);
if (r != CUBEB_OK) {
LOG("(%p) Could not uninstall all device change listeners", stm);
}
auto_lock lock(stm->mutex);
audiounit_close_stream(stm);
assert(audiounit_active_streams(stm->context) >= 1);
audiounit_decrement_active_streams(stm->context);
}
static void
audiounit_stream_destroy(cubeb_stream * stm)
{
int r = audiounit_uninstall_system_changed_callback(stm);
if (r != CUBEB_OK) {
LOG("(%p) Could not uninstall the device changed callback", stm);
}
r = audiounit_uninstall_device_changed_callback(stm);
if (r != CUBEB_OK) {
LOG("(%p) Could not uninstall all device change listeners", stm);
}
if (!stm->shutdown.load()) {
auto_lock context_lock(stm->context->mutex);
audiounit_stream_stop_internal(stm);
stm->shutdown = true;
}
stm->destroy_pending = true;
// Execute close in serial queue to avoid collision
// with reinit when un/plug devices
dispatch_sync(stm->context->serial_queue, ^() {
auto_lock context_lock(stm->context->mutex);
audiounit_stream_destroy_internal(stm);
});
LOG("Cubeb stream (%p) destroyed successful.", stm);
delete stm;
}
static int
audiounit_stream_start_internal(cubeb_stream * stm)
{
OSStatus r;
if (stm->input_unit != NULL) {
r = AudioOutputUnitStart(stm->input_unit);
if (r != noErr) {
LOG("AudioOutputUnitStart (input) rv=%d", r);
return CUBEB_ERROR;
}
}
if (stm->output_unit != NULL) {
r = AudioOutputUnitStart(stm->output_unit);
if (r != noErr) {
LOG("AudioOutputUnitStart (output) rv=%d", r);
return CUBEB_ERROR;
}
}
return CUBEB_OK;
}
static int
audiounit_stream_start(cubeb_stream * stm)
{
auto_lock context_lock(stm->context->mutex);
stm->shutdown = false;
stm->draining = false;
int r = audiounit_stream_start_internal(stm);
if (r != CUBEB_OK) {
return r;
}
stm->state_callback(stm, stm->user_ptr, CUBEB_STATE_STARTED);
LOG("Cubeb stream (%p) started successfully.", stm);
return CUBEB_OK;
}
void
audiounit_stream_stop_internal(cubeb_stream * stm)
{
OSStatus r;
if (stm->input_unit != NULL) {
r = AudioOutputUnitStop(stm->input_unit);
assert(r == 0);
}
if (stm->output_unit != NULL) {
r = AudioOutputUnitStop(stm->output_unit);
assert(r == 0);
}
}
static int
audiounit_stream_stop(cubeb_stream * stm)
{
auto_lock context_lock(stm->context->mutex);
stm->shutdown = true;
audiounit_stream_stop_internal(stm);
stm->state_callback(stm, stm->user_ptr, CUBEB_STATE_STOPPED);
LOG("Cubeb stream (%p) stopped successfully.", stm);
return CUBEB_OK;
}
static int
audiounit_stream_get_position(cubeb_stream * stm, uint64_t * position)
{
assert(stm);
if (stm->current_latency_frames > stm->frames_played) {
*position = 0;
} else {
*position = stm->frames_played - stm->current_latency_frames;
}
return CUBEB_OK;
}
int
audiounit_stream_get_latency(cubeb_stream * stm, uint32_t * latency)
{
#if TARGET_OS_IPHONE
// TODO
return CUBEB_ERROR_NOT_SUPPORTED;
#else
*latency = stm->total_output_latency_frames;
return CUBEB_OK;
#endif
}
static int
audiounit_stream_get_volume(cubeb_stream * stm, float * volume)
{
assert(stm->output_unit);
OSStatus r = AudioUnitGetParameter(stm->output_unit, kHALOutputParam_Volume,
kAudioUnitScope_Global, 0, volume);
if (r != noErr) {
LOG("AudioUnitGetParameter/kHALOutputParam_Volume rv=%d", r);
return CUBEB_ERROR;
}
return CUBEB_OK;
}
static int
audiounit_stream_set_volume(cubeb_stream * stm, float volume)
{
assert(stm->output_unit);
OSStatus r;
r = AudioUnitSetParameter(stm->output_unit, kHALOutputParam_Volume,
kAudioUnitScope_Global, 0, volume, 0);
if (r != noErr) {
LOG("AudioUnitSetParameter/kHALOutputParam_Volume rv=%d", r);
return CUBEB_ERROR;
}
return CUBEB_OK;
}
unique_ptr<char[]>
convert_uint32_into_string(UInt32 data)
{
// Simply create an empty string if no data.
size_t size = data == 0 ? 0 : 4; // 4 bytes for uint32.
auto str = unique_ptr<char[]>{new char[size + 1]}; // + 1 for '\0'.
str[size] = '\0';
if (size < 4) {
return str;
}
// Reverse 0xWXYZ into 0xZYXW.
str[0] = (char)(data >> 24);
str[1] = (char)(data >> 16);
str[2] = (char)(data >> 8);
str[3] = (char)(data);
return str;
}
int
audiounit_get_default_device_datasource(cubeb_device_type type, UInt32 * data)
{
AudioDeviceID id = audiounit_get_default_device_id(type);
if (id == kAudioObjectUnknown) {
return CUBEB_ERROR;
}
UInt32 size = sizeof(*data);
/* This fails with some USB headsets (e.g., Plantronic .Audio 628). */
OSStatus r = AudioObjectGetPropertyData(
id,
type == CUBEB_DEVICE_TYPE_INPUT ? &INPUT_DATA_SOURCE_PROPERTY_ADDRESS
: &OUTPUT_DATA_SOURCE_PROPERTY_ADDRESS,
0, NULL, &size, data);
if (r != noErr) {
*data = 0;
}
return CUBEB_OK;
}
int
audiounit_get_default_device_name(cubeb_stream * stm,
cubeb_device * const device,
cubeb_device_type type)
{
assert(stm);
assert(device);
UInt32 data;
int r = audiounit_get_default_device_datasource(type, &data);
if (r != CUBEB_OK) {
return r;
}
char ** name = type == CUBEB_DEVICE_TYPE_INPUT ? &device->input_name
: &device->output_name;
*name = convert_uint32_into_string(data).release();
if (!strlen(*name)) { // empty string.
LOG("(%p) name of %s device is empty!", stm,
type == CUBEB_DEVICE_TYPE_INPUT ? "input" : "output");
}
return CUBEB_OK;
}
int
audiounit_stream_get_current_device(cubeb_stream * stm,
cubeb_device ** const device)
{
#if TARGET_OS_IPHONE
// TODO
return CUBEB_ERROR_NOT_SUPPORTED;
#else
*device = new cubeb_device;
if (!*device) {
return CUBEB_ERROR;
}
PodZero(*device, 1);
int r =
audiounit_get_default_device_name(stm, *device, CUBEB_DEVICE_TYPE_OUTPUT);
if (r != CUBEB_OK) {
return r;
}
r = audiounit_get_default_device_name(stm, *device, CUBEB_DEVICE_TYPE_INPUT);
if (r != CUBEB_OK) {
return r;
}
return CUBEB_OK;
#endif
}
int
audiounit_stream_device_destroy(cubeb_stream * /* stream */,
cubeb_device * device)
{
delete[] device->output_name;
delete[] device->input_name;
delete device;
return CUBEB_OK;
}
int
audiounit_stream_register_device_changed_callback(
cubeb_stream * stream,
cubeb_device_changed_callback device_changed_callback)
{
auto_lock dev_cb_lock(stream->device_changed_callback_lock);
/* Note: second register without unregister first causes 'nope' error.
* Current implementation requires unregister before register a new cb. */
assert(!device_changed_callback || !stream->device_changed_callback);
stream->device_changed_callback = device_changed_callback;
return CUBEB_OK;
}
static char *
audiounit_strref_to_cstr_utf8(CFStringRef strref)
{
CFIndex len, size;
char * ret;
if (strref == NULL) {
return NULL;
}
len = CFStringGetLength(strref);
// Add 1 to size to allow for '\0' termination character.
size = CFStringGetMaximumSizeForEncoding(len, kCFStringEncodingUTF8) + 1;
ret = new char[size];
if (!CFStringGetCString(strref, ret, size, kCFStringEncodingUTF8)) {
delete[] ret;
ret = NULL;
}
return ret;
}
static uint32_t
audiounit_get_channel_count(AudioObjectID devid, AudioObjectPropertyScope scope)
{
AudioObjectPropertyAddress adr = {0, scope,
kAudioObjectPropertyElementMaster};
UInt32 size = 0;
uint32_t i, ret = 0;
adr.mSelector = kAudioDevicePropertyStreamConfiguration;
if (AudioObjectGetPropertyDataSize(devid, &adr, 0, NULL, &size) == noErr &&
size > 0) {
AudioBufferList * list = static_cast<AudioBufferList *>(alloca(size));
if (AudioObjectGetPropertyData(devid, &adr, 0, NULL, &size, list) ==
noErr) {
for (i = 0; i < list->mNumberBuffers; i++)
ret += list->mBuffers[i].mNumberChannels;
}
}
return ret;
}
static void
audiounit_get_available_samplerate(AudioObjectID devid,
AudioObjectPropertyScope scope,
uint32_t * min, uint32_t * max,
uint32_t * def)
{
AudioObjectPropertyAddress adr = {0, scope,
kAudioObjectPropertyElementMaster};
adr.mSelector = kAudioDevicePropertyNominalSampleRate;
if (AudioObjectHasProperty(devid, &adr)) {
UInt32 size = sizeof(Float64);
Float64 fvalue = 0.0;
if (AudioObjectGetPropertyData(devid, &adr, 0, NULL, &size, &fvalue) ==
noErr) {
*def = fvalue;
}
}
adr.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
UInt32 size = 0;
AudioValueRange range;
if (AudioObjectHasProperty(devid, &adr) &&
AudioObjectGetPropertyDataSize(devid, &adr, 0, NULL, &size) == noErr) {
uint32_t count = size / sizeof(AudioValueRange);
vector<AudioValueRange> ranges(count);
range.mMinimum = 9999999999.0;
range.mMaximum = 0.0;
if (AudioObjectGetPropertyData(devid, &adr, 0, NULL, &size,
ranges.data()) == noErr) {
for (uint32_t i = 0; i < count; i++) {
if (ranges[i].mMaximum > range.mMaximum)
range.mMaximum = ranges[i].mMaximum;
if (ranges[i].mMinimum < range.mMinimum)
range.mMinimum = ranges[i].mMinimum;
}
}
*max = static_cast<uint32_t>(range.mMaximum);
*min = static_cast<uint32_t>(range.mMinimum);
} else {
*min = *max = 0;
}
}
static UInt32
audiounit_get_device_presentation_latency(AudioObjectID devid,
AudioObjectPropertyScope scope)
{
AudioObjectPropertyAddress adr = {0, scope,
kAudioObjectPropertyElementMaster};
UInt32 size, dev, stream = 0;
AudioStreamID sid[1];
adr.mSelector = kAudioDevicePropertyLatency;
size = sizeof(UInt32);
if (AudioObjectGetPropertyData(devid, &adr, 0, NULL, &size, &dev) != noErr) {
dev = 0;
}
adr.mSelector = kAudioDevicePropertyStreams;
size = sizeof(sid);
if (AudioObjectGetPropertyData(devid, &adr, 0, NULL, &size, sid) == noErr) {
adr.mSelector = kAudioStreamPropertyLatency;
size = sizeof(UInt32);
AudioObjectGetPropertyData(sid[0], &adr, 0, NULL, &size, &stream);
}
return dev + stream;
}
static int
audiounit_create_device_from_hwdev(cubeb_device_info * dev_info,
AudioObjectID devid, cubeb_device_type type)
{
AudioObjectPropertyAddress adr = {0, 0, kAudioObjectPropertyElementMaster};
UInt32 size;
if (type == CUBEB_DEVICE_TYPE_OUTPUT) {
adr.mScope = kAudioDevicePropertyScopeOutput;
} else if (type == CUBEB_DEVICE_TYPE_INPUT) {
adr.mScope = kAudioDevicePropertyScopeInput;
} else {
return CUBEB_ERROR;
}
UInt32 ch = audiounit_get_channel_count(devid, adr.mScope);
if (ch == 0) {
return CUBEB_ERROR;
}
PodZero(dev_info, 1);
CFStringRef device_id_str = nullptr;
size = sizeof(CFStringRef);
adr.mSelector = kAudioDevicePropertyDeviceUID;
OSStatus ret =
AudioObjectGetPropertyData(devid, &adr, 0, NULL, &size, &device_id_str);
if (ret == noErr && device_id_str != NULL) {
dev_info->device_id = audiounit_strref_to_cstr_utf8(device_id_str);
static_assert(sizeof(cubeb_devid) >= sizeof(decltype(devid)),
"cubeb_devid can't represent devid");
dev_info->devid = reinterpret_cast<cubeb_devid>(devid);
dev_info->group_id = dev_info->device_id;
CFRelease(device_id_str);
}
CFStringRef friendly_name_str = nullptr;
UInt32 ds;
size = sizeof(UInt32);
adr.mSelector = kAudioDevicePropertyDataSource;
ret = AudioObjectGetPropertyData(devid, &adr, 0, NULL, &size, &ds);
if (ret == noErr) {
AudioValueTranslation trl = {&ds, sizeof(ds), &friendly_name_str,
sizeof(CFStringRef)};
adr.mSelector = kAudioDevicePropertyDataSourceNameForIDCFString;
size = sizeof(AudioValueTranslation);
AudioObjectGetPropertyData(devid, &adr, 0, NULL, &size, &trl);
}
// If there is no datasource for this device, fall back to the
// device name.
if (!friendly_name_str) {
size = sizeof(CFStringRef);
adr.mSelector = kAudioObjectPropertyName;
AudioObjectGetPropertyData(devid, &adr, 0, NULL, &size, &friendly_name_str);
}
if (friendly_name_str) {
dev_info->friendly_name = audiounit_strref_to_cstr_utf8(friendly_name_str);
CFRelease(friendly_name_str);
} else {
// Couldn't get a datasource name nor a device name, return a
// valid string of length 0.
char * fallback_name = new char[1];
fallback_name[0] = '\0';
dev_info->friendly_name = fallback_name;
}
CFStringRef vendor_name_str = nullptr;
size = sizeof(CFStringRef);
adr.mSelector = kAudioObjectPropertyManufacturer;
ret =
AudioObjectGetPropertyData(devid, &adr, 0, NULL, &size, &vendor_name_str);
if (ret == noErr && vendor_name_str != NULL) {
dev_info->vendor_name = audiounit_strref_to_cstr_utf8(vendor_name_str);
CFRelease(vendor_name_str);
}
dev_info->type = type;
dev_info->state = CUBEB_DEVICE_STATE_ENABLED;
dev_info->preferred = (devid == audiounit_get_default_device_id(type))
? CUBEB_DEVICE_PREF_ALL
: CUBEB_DEVICE_PREF_NONE;
dev_info->max_channels = ch;
dev_info->format =
(cubeb_device_fmt)CUBEB_DEVICE_FMT_ALL; /* CoreAudio supports All! */
/* kAudioFormatFlagsAudioUnitCanonical is deprecated, prefer floating point */
dev_info->default_format = CUBEB_DEVICE_FMT_F32NE;
audiounit_get_available_samplerate(devid, adr.mScope, &dev_info->min_rate,
&dev_info->max_rate,
&dev_info->default_rate);
UInt32 latency = audiounit_get_device_presentation_latency(devid, adr.mScope);
AudioValueRange range;
adr.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
size = sizeof(AudioValueRange);
ret = AudioObjectGetPropertyData(devid, &adr, 0, NULL, &size, &range);
if (ret == noErr) {
dev_info->latency_lo = latency + range.mMinimum;
dev_info->latency_hi = latency + range.mMaximum;
} else {
dev_info->latency_lo =
10 * dev_info->default_rate / 1000; /* Default to 10ms */
dev_info->latency_hi =
100 * dev_info->default_rate / 1000; /* Default to 100ms */
}
return CUBEB_OK;
}
bool
is_aggregate_device(cubeb_device_info * device_info)
{
assert(device_info->friendly_name);
return !strncmp(device_info->friendly_name, PRIVATE_AGGREGATE_DEVICE_NAME,
strlen(PRIVATE_AGGREGATE_DEVICE_NAME));
}
static int
audiounit_enumerate_devices(cubeb * /* context */, cubeb_device_type type,
cubeb_device_collection * collection)
{
vector<AudioObjectID> input_devs;
vector<AudioObjectID> output_devs;
// Count number of input and output devices. This is not
// necessarily the same as the count of raw devices supported by the
// system since, for example, with Soundflower installed, some
// devices may report as being both input *and* output and cubeb
// separates those into two different devices.
if (type & CUBEB_DEVICE_TYPE_OUTPUT) {
output_devs = audiounit_get_devices_of_type(CUBEB_DEVICE_TYPE_OUTPUT);
}
if (type & CUBEB_DEVICE_TYPE_INPUT) {
input_devs = audiounit_get_devices_of_type(CUBEB_DEVICE_TYPE_INPUT);
}
auto devices = new cubeb_device_info[output_devs.size() + input_devs.size()];
collection->count = 0;
if (type & CUBEB_DEVICE_TYPE_OUTPUT) {
for (auto dev : output_devs) {
auto device = &devices[collection->count];
auto err = audiounit_create_device_from_hwdev(device, dev,
CUBEB_DEVICE_TYPE_OUTPUT);
if (err != CUBEB_OK || is_aggregate_device(device)) {
continue;
}
collection->count += 1;
}
}
if (type & CUBEB_DEVICE_TYPE_INPUT) {
for (auto dev : input_devs) {
auto device = &devices[collection->count];
auto err = audiounit_create_device_from_hwdev(device, dev,
CUBEB_DEVICE_TYPE_INPUT);
if (err != CUBEB_OK || is_aggregate_device(device)) {
continue;
}
collection->count += 1;
}
}
if (collection->count > 0) {
collection->device = devices;
} else {
delete[] devices;
collection->device = NULL;
}
return CUBEB_OK;
}
static void
audiounit_device_destroy(cubeb_device_info * device)
{
delete[] device->device_id;
delete[] device->friendly_name;
delete[] device->vendor_name;
}
static int
audiounit_device_collection_destroy(cubeb * /* context */,
cubeb_device_collection * collection)
{
for (size_t i = 0; i < collection->count; i++) {
audiounit_device_destroy(&collection->device[i]);
}
delete[] collection->device;
return CUBEB_OK;
}
static vector<AudioObjectID>
audiounit_get_devices_of_type(cubeb_device_type devtype)
{
UInt32 size = 0;
OSStatus ret = AudioObjectGetPropertyDataSize(
kAudioObjectSystemObject, &DEVICES_PROPERTY_ADDRESS, 0, NULL, &size);
if (ret != noErr) {
return vector<AudioObjectID>();
}
vector<AudioObjectID> devices(size / sizeof(AudioObjectID));
ret = AudioObjectGetPropertyData(kAudioObjectSystemObject,
&DEVICES_PROPERTY_ADDRESS, 0, NULL, &size,
devices.data());
if (ret != noErr) {
return vector<AudioObjectID>();
}
// Remove the aggregate device from the list of devices (if any).
for (auto it = devices.begin(); it != devices.end();) {
CFStringRef name = get_device_name(*it);
if (name && CFStringFind(name, CFSTR("CubebAggregateDevice"), 0).location !=
kCFNotFound) {
it = devices.erase(it);
} else {
it++;
}
if (name) {
CFRelease(name);
}
}
/* Expected sorted but did not find anything in the docs. */
sort(devices.begin(), devices.end(),
[](AudioObjectID a, AudioObjectID b) { return a < b; });
if (devtype == (CUBEB_DEVICE_TYPE_INPUT | CUBEB_DEVICE_TYPE_OUTPUT)) {
return devices;
}
AudioObjectPropertyScope scope = (devtype == CUBEB_DEVICE_TYPE_INPUT)
? kAudioDevicePropertyScopeInput
: kAudioDevicePropertyScopeOutput;
vector<AudioObjectID> devices_in_scope;
for (uint32_t i = 0; i < devices.size(); ++i) {
/* For device in the given scope channel must be > 0. */
if (audiounit_get_channel_count(devices[i], scope) > 0) {
devices_in_scope.push_back(devices[i]);
}
}
return devices_in_scope;
}
static OSStatus
audiounit_collection_changed_callback(
AudioObjectID /* inObjectID */, UInt32 /* inNumberAddresses */,
const AudioObjectPropertyAddress * /* inAddresses */, void * inClientData)
{
cubeb * context = static_cast<cubeb *>(inClientData);
// This can be called from inside an AudioUnit function, dispatch to another
// queue.
dispatch_async(context->serial_queue, ^() {
auto_lock lock(context->mutex);
if (!context->input_collection_changed_callback &&
!context->output_collection_changed_callback) {
/* Listener removed while waiting in mutex, abort. */
return;
}
if (context->input_collection_changed_callback) {
vector<AudioObjectID> devices =
audiounit_get_devices_of_type(CUBEB_DEVICE_TYPE_INPUT);
/* Elements in the vector expected sorted. */
if (context->input_device_array != devices) {
context->input_device_array = devices;
context->input_collection_changed_callback(
context, context->input_collection_changed_user_ptr);
}
}
if (context->output_collection_changed_callback) {
vector<AudioObjectID> devices =
audiounit_get_devices_of_type(CUBEB_DEVICE_TYPE_OUTPUT);
/* Elements in the vector expected sorted. */
if (context->output_device_array != devices) {
context->output_device_array = devices;
context->output_collection_changed_callback(
context, context->output_collection_changed_user_ptr);
}
}
});
return noErr;
}
static OSStatus
audiounit_add_device_listener(
cubeb * context, cubeb_device_type devtype,
cubeb_device_collection_changed_callback collection_changed_callback,
void * user_ptr)
{
context->mutex.assert_current_thread_owns();
assert(devtype & (CUBEB_DEVICE_TYPE_INPUT | CUBEB_DEVICE_TYPE_OUTPUT));
/* Note: second register without unregister first causes 'nope' error.
* Current implementation requires unregister before register a new cb. */
assert((devtype & CUBEB_DEVICE_TYPE_INPUT) &&
!context->input_collection_changed_callback ||
(devtype & CUBEB_DEVICE_TYPE_OUTPUT) &&
!context->output_collection_changed_callback);
if (!context->input_collection_changed_callback &&
!context->output_collection_changed_callback) {
OSStatus ret = AudioObjectAddPropertyListener(
kAudioObjectSystemObject, &DEVICES_PROPERTY_ADDRESS,
audiounit_collection_changed_callback, context);
if (ret != noErr) {
return ret;
}
}
if (devtype & CUBEB_DEVICE_TYPE_INPUT) {
/* Expected empty after unregister. */
assert(context->input_device_array.empty());
context->input_device_array =
audiounit_get_devices_of_type(CUBEB_DEVICE_TYPE_INPUT);
context->input_collection_changed_callback = collection_changed_callback;
context->input_collection_changed_user_ptr = user_ptr;
}
if (devtype & CUBEB_DEVICE_TYPE_OUTPUT) {
/* Expected empty after unregister. */
assert(context->output_device_array.empty());
context->output_device_array =
audiounit_get_devices_of_type(CUBEB_DEVICE_TYPE_OUTPUT);
context->output_collection_changed_callback = collection_changed_callback;
context->output_collection_changed_user_ptr = user_ptr;
}
return noErr;
}
static OSStatus
audiounit_remove_device_listener(cubeb * context, cubeb_device_type devtype)
{
context->mutex.assert_current_thread_owns();
if (devtype & CUBEB_DEVICE_TYPE_INPUT) {
context->input_collection_changed_callback = nullptr;
context->input_collection_changed_user_ptr = nullptr;
context->input_device_array.clear();
}
if (devtype & CUBEB_DEVICE_TYPE_OUTPUT) {
context->output_collection_changed_callback = nullptr;
context->output_collection_changed_user_ptr = nullptr;
context->output_device_array.clear();
}
if (context->input_collection_changed_callback ||
context->output_collection_changed_callback) {
return noErr;
}
/* Note: unregister a non registered cb is not a problem, not checking. */
return AudioObjectRemovePropertyListener(
kAudioObjectSystemObject, &DEVICES_PROPERTY_ADDRESS,
audiounit_collection_changed_callback, context);
}
int
audiounit_register_device_collection_changed(
cubeb * context, cubeb_device_type devtype,
cubeb_device_collection_changed_callback collection_changed_callback,
void * user_ptr)
{
if (devtype == CUBEB_DEVICE_TYPE_UNKNOWN) {
return CUBEB_ERROR_INVALID_PARAMETER;
}
OSStatus ret;
auto_lock lock(context->mutex);
if (collection_changed_callback) {
ret = audiounit_add_device_listener(context, devtype,
collection_changed_callback, user_ptr);
} else {
ret = audiounit_remove_device_listener(context, devtype);
}
return (ret == noErr) ? CUBEB_OK : CUBEB_ERROR;
}
cubeb_ops const audiounit_ops = {
/*.init =*/audiounit_init,
/*.get_backend_id =*/audiounit_get_backend_id,
/*.get_max_channel_count =*/audiounit_get_max_channel_count,
/*.get_min_latency =*/audiounit_get_min_latency,
/*.get_preferred_sample_rate =*/audiounit_get_preferred_sample_rate,
/*.enumerate_devices =*/audiounit_enumerate_devices,
/*.device_collection_destroy =*/audiounit_device_collection_destroy,
/*.destroy =*/audiounit_destroy,
/*.stream_init =*/audiounit_stream_init,
/*.stream_destroy =*/audiounit_stream_destroy,
/*.stream_start =*/audiounit_stream_start,
/*.stream_stop =*/audiounit_stream_stop,
/*.stream_get_position =*/audiounit_stream_get_position,
/*.stream_get_latency =*/audiounit_stream_get_latency,
/*.stream_get_input_latency =*/NULL,
/*.stream_set_volume =*/audiounit_stream_set_volume,
/*.stream_set_name =*/NULL,
/*.stream_get_current_device =*/audiounit_stream_get_current_device,
/*.stream_device_destroy =*/audiounit_stream_device_destroy,
/*.stream_register_device_changed_callback =*/
audiounit_stream_register_device_changed_callback,
/*.register_device_collection_changed =*/
audiounit_register_device_collection_changed};
|
// $Id$
/*
Copyright (c) 2007-2015, Trustees of The Leland Stanford Junior University
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
*/
// ----------------------------------------------------------------------
//
// SeparableOutputFirstAllocator: Separable Output-First Allocator
//
// ----------------------------------------------------------------------
#include "separable_output_first.hpp"
#include "booksim.hpp"
#include "arbiter.hpp"
#include <vector>
#include <iostream>
#include <cstring>
SeparableOutputFirstAllocator::
SeparableOutputFirstAllocator( Module* parent, const string& name, int inputs,
int outputs, const string& arb_type )
: SeparableAllocator( parent, name, inputs, outputs, arb_type )
{}
void SeparableOutputFirstAllocator::Allocate() {
set<int>::const_iterator port_iter = _out_occ.begin();
while(port_iter != _out_occ.end()) {
const int & output = *port_iter;
// add requests to the output arbiter
map<int, sRequest>::const_iterator req_iter = _out_req[output].begin();
while(req_iter != _out_req[output].end()) {
const sRequest & req = req_iter->second;
_output_arb[output]->AddRequest(req.port, req.label, req.out_pri);
++req_iter;
}
// Execute the output arbiter and propagate the grants to the
// input arbiters.
int label = -1;
const int input = _output_arb[output]->Arbitrate(&label, NULL);
assert(input > -1);
const sRequest & req = _in_req[input][output];
assert((req.port == output) && (req.label == label));
_input_arb[input]->AddRequest(req.port, req.label, req.in_pri);
++port_iter;
}
port_iter = _in_occ.begin();
while(port_iter != _in_occ.end()) {
const int & input = *port_iter;
// Execute the input arbiters.
const int output = _input_arb[input]->Arbitrate(NULL, NULL);
if(output > -1) {
assert((_inmatch[input] == -1) && (_outmatch[output] == -1));
_inmatch[input] = output;
_outmatch[output] = input;
_input_arb[input]->UpdateState() ;
_output_arb[output]->UpdateState() ;
}
++port_iter;
}
}
|
#include <bits/stdc++.h>
using namespace std;
using namespace __gnu_cxx;
typedef double db;
typedef long long ll;
typedef pair<db, db> pdd;
typedef pair<ll, ll> pll;
typedef pair<int, int> pii;
typedef unsigned long long ull;
#define F first
#define S second
#define pnl printf("\n")
#define sz(x) (int)x.size()
#define sf(x) scanf("%d",&x)
#define pf(x) printf("%d\n",x)
#define all(x) x.begin(),x.end()
#define rall(x) x.rbegin(),x.rend()
#define rep(i, n) for(int i = 0; i < n; ++i)
const db eps = 1e-9;
const db pi = acos(-1);
const int INF = 0x3f3f3f3f;
const ll LL_INF = 0x3f3f3f3f3f3f3f3f;
const int mod = 1000 * 1000 * 1000 + 7;
int n;
string str, v = "aeiouy";
bool isVowel(char c) {
return (v.find(c) != string::npos);
}
int main() {
while (scanf("%d", &n), n > 0) {
string ans;
int mx = -1;
for (int i = 0; i < n; ++i) {
cin >> str;
int cur = 0;
for (int j = 0; j < sz(str) - 1; ++j) {
if (isVowel(str[j]) && str[j] == str[j + 1])
++cur;
}
if (cur > mx)
mx = cur, ans = str;
}
cout << ans << endl;
}
return 0;
}
|
/*
*/
#include "inputdata.h"
json inputdata::all_data;
vector<string> inputdata::alphabet;
map<string, int> inputdata::r_alphabet;
int inputdata::num_attributes;
tail* tail::split(){
tail* t = new tail(sequence, index, 0);
t->split_from = this;
t->future_tail = future_tail;
t->past_tail = past_tail;
split_to = t;
return t;
};
void tail::undo_split(){
split_to = 0;
};
tail* tail::next(){
if(split_to == 0) return next_in_list;
if(next_in_list == 0) return 0;
return next_in_list->next();
};
tail* tail::future(){
if(split_to == 0) return future_tail;
return split_to->future();
};
tail::tail(int seq, int i, tail* pt){
sequence = seq;
index = i;
past_tail = pt;
if(past_tail != 0) past_tail->future_tail = this;
future_tail = 0;
next_in_list = 0;
split_from = 0;
};
inputdata::inputdata() {
node_number = 0;
}
void inputdata::read_json_file(istream &input_stream){
input_stream >> all_data;
};
void inputdata::read_abbadingo_file(istream &input_stream){
int num_sequences, alph_size;
input_stream >> num_sequences;
string tuple;
input_stream >> tuple;
std::stringstream lineStream;
lineStream.str(tuple);
string alph;
std::getline(lineStream,alph,':');
string attr;
std::getline(lineStream,attr);
alph_size = stoi(alph);
if(!attr.empty())
inputdata::num_attributes = stoi(attr);
else
inputdata::num_attributes = 0;
//cerr << "ATTR: " << attr << " " << inputdata::num_attributes << endl;
for(int line = 0; line < num_sequences; ++line){
read_abbadingo_sequence(input_stream, inputdata::num_attributes);
}
};
void inputdata::read_abbadingo_sequence(istream &input_stream, int num_attributes){
int type, length;
json sequence;
input_stream >> type;
input_stream >> length;
sequence["T"] = type;
sequence["L"] = length;
vector<int> symbols(length);
vector< vector<int> > values(num_attributes, vector<int>(length));
vector< string > datas(length);
bool has_data = false;
for(int index = 0; index < length; ++index){
string tuple;
input_stream >> tuple;
std::stringstream l1;
l1.str(tuple);
string temp_symbol;
std::getline(l1,temp_symbol,'/');
string data;
std::getline(l1,data);
if(!data.empty())
has_data = true;
std::stringstream l2;
l2.str(temp_symbol);
string symbol;
std::getline(l2,symbol,':');
string vals;
std::getline(l2,vals);
//cerr << symbol << " " << vals << endl;
if(r_alphabet.find(symbol) == r_alphabet.end()){
r_alphabet[symbol] = alphabet.size();
alphabet.push_back(symbol);
}
symbols[index] = r_alphabet[symbol];
datas[index] = data;
string val;
if(num_attributes != 0){
std::stringstream l3;
l3.str(vals);
for(int i = 0; i < num_attributes-1; ++i){
std::getline(l3,val,',');
cerr << val;
values[i][index] = stof(val);
}
std::getline(l3,val);
values[num_attributes-1][index] = stof(val);
}
}
sequence["S"] = symbols;
for(int i = 0; i < num_attributes; ++i){
sequence["V" + to_string(i)] = values[i];
}
if(has_data)
sequence["D"] = datas;
all_data.push_back(sequence);
};
void inputdata::add_data_to_apta(apta* the_apta){
for(int i = 0; i < all_data.size(); ++i){
add_sequence_to_apta(the_apta, i);
}
};
void inputdata::add_sequence_to_apta(apta* the_apta, int seq_nr){
json sequence = all_data[seq_nr];
int depth = 0;
apta_node* node = the_apta->root;
tail* ot = 0;
for(int index = 0; index < sequence["L"]; index++){
depth++;
tail* nt = new tail(seq_nr, index, ot);
int symbol = sequence["S"][index];
if(node->child(symbol) == 0){
apta_node* next_node = new apta_node(the_apta);
node->set_child(symbol, next_node);
next_node->source = node;
next_node->label = symbol;
next_node->depth = depth;
next_node->number = ++(this->node_number);
}
node->size = node->size + 1;
node->add_tail(nt);
node->data->read_from(seq_nr, index);
node = node->child(symbol);
node->data->read_to(seq_nr, index);
ot = nt;
}
node->type = sequence["T"];
node->size = node->size + 1;
};
const string inputdata::to_json_str() const{
ostringstream ostr;
ostr << all_data;
return ostr.str();
};
/*
const string inputdata::to_abbadingo_str() const{
ostringstream ostr;
ostr << num_sequences << " " << alph_size << ":" << num_attributes << "\n";
for(int line = 0; line < num_sequences; ++line) {
sequence* seq = sequences[line];
ostr << seq->type << " " << seq->length << " ";
for(int index = 0; index < seq->length; ++index){
ostr << inputdata::alphabet[seq->symbols[index]];
if(inputdata::num_attributes != 0){
ostr << inputdata::alphabet[seq->symbols[index]] << ":";
for(int val = 0; val < inputdata::num_attributes-1; ++val){
ostr << seq->values[index][val] << ",";
}
ostr << seq->values[index][inputdata::num_attributes-1] << " ";
}
if(!seq->data[index].empty()){
ostr << "/" << seq->data;
}
ostr << " ";
}
ostr << "\n";
}
return ostr.str();
};
*/
|
/*
* Copyright 2019 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 "rtc_base/synchronization/sequence_checker.h"
#if defined(WEBRTC_MAC)
#include <dispatch/dispatch.h>
#endif
#include "rtc_base/strings/string_builder.h"
namespace webrtc {
namespace {
// On Mac, returns the label of the current dispatch queue; elsewhere, return
// null.
__attribute__((no_instrument_function)) const void* GetSystemQueueRef() {
#if defined(WEBRTC_MAC)
return dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL);
#else
return nullptr;
#endif
}
} // namespace
std::string ExpectationToString(const webrtc::SequenceChecker* checker) {
#if RTC_DCHECK_IS_ON
return checker->ExpectationToString();
#endif
return std::string();
}
SequenceCheckerImpl::SequenceCheckerImpl()
: attached_(true),
valid_thread_(rtc::CurrentThreadRef()),
valid_queue_(TaskQueueBase::Current()),
valid_system_queue_(GetSystemQueueRef()) {}
SequenceCheckerImpl::~SequenceCheckerImpl() = default;
__attribute__((no_instrument_function)) bool SequenceCheckerImpl::IsCurrent() const {
const TaskQueueBase* const current_queue = TaskQueueBase::Current();
const rtc::PlatformThreadRef current_thread = rtc::CurrentThreadRef();
const void* const current_system_queue = GetSystemQueueRef();
MutexLock scoped_lock(&lock_);
if (!attached_) { // Previously detached.
attached_ = true;
valid_thread_ = current_thread;
valid_queue_ = current_queue;
valid_system_queue_ = current_system_queue;
return true;
}
if (valid_queue_ || current_queue) {
return valid_queue_ == current_queue;
}
if (valid_system_queue_ && valid_system_queue_ == current_system_queue) {
return true;
}
return rtc::IsThreadRefEqual(valid_thread_, current_thread);
}
void SequenceCheckerImpl::Detach() {
MutexLock scoped_lock(&lock_);
attached_ = false;
// We don't need to touch the other members here, they will be
// reset on the next call to IsCurrent().
}
#if RTC_DCHECK_IS_ON
std::string SequenceCheckerImpl::ExpectationToString() const {
const TaskQueueBase* const current_queue = TaskQueueBase::Current();
const rtc::PlatformThreadRef current_thread = rtc::CurrentThreadRef();
const void* const current_system_queue = GetSystemQueueRef();
MutexLock scoped_lock(&lock_);
if (!attached_)
return "Checker currently not attached.";
// The format of the string is meant to compliment the one we have inside of
// FatalLog() (checks.cc). Example:
//
// # Expected: TQ: 0x0 SysQ: 0x7fff69541330 Thread: 0x11dcf6dc0
// # Actual: TQ: 0x7fa8f0604190 SysQ: 0x7fa8f0604a30 Thread: 0x700006f1a000
// TaskQueue doesn't match
rtc::StringBuilder message;
message.AppendFormat(
"# Expected: TQ: %p SysQ: %p Thread: %p\n"
"# Actual: TQ: %p SysQ: %p Thread: %p\n",
valid_queue_, valid_system_queue_,
reinterpret_cast<const void*>(valid_thread_), current_queue,
current_system_queue, reinterpret_cast<const void*>(current_thread));
if ((valid_queue_ || current_queue) && valid_queue_ != current_queue) {
message << "TaskQueue doesn't match\n";
} else if (valid_system_queue_ &&
valid_system_queue_ != current_system_queue) {
message << "System queue doesn't match\n";
} else if (!rtc::IsThreadRefEqual(valid_thread_, current_thread)) {
message << "Threads don't match\n";
}
return message.Release();
}
#endif // RTC_DCHECK_IS_ON
} // namespace webrtc
|
/*
* Copyright (c) 2016, NVIDIA CORPORATION. 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 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.
*/
#include "NvV4l2ElementPlane.h"
#include "NvLogging.h"
#include <cstring>
#include <errno.h>
#include <libv4l2.h>
#include <sys/mman.h>
#include <sys/prctl.h>
#define CHECK_V4L2_RETURN(ret, str) \
if (ret < 0) { \
PLANE_SYS_ERROR_MSG(str << ": failed"); \
return -1; \
} else { \
PLANE_DEBUG_MSG(str << ": success"); \
return 0; \
}
using namespace std;
NvV4l2ElementPlane::NvV4l2ElementPlane(enum v4l2_buf_type buf_type, const char *device_name, int &fd, bool blocking,
NvElementProfiler &profiler)
: fd(fd), v4l2elem_profiler(profiler), comp_name(device_name) {
this->buf_type = buf_type;
this->blocking = blocking;
is_in_error = 0;
switch (buf_type) {
case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE:
plane_name = "Output Plane";
break;
case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:
plane_name = "Capture Plane";
break;
default:
ERROR_MSG("Unsupported v4l2_buf_type " << buf_type);
plane_name = "Unknown";
is_in_error = 1;
}
num_buffers = 0;
buffers = NULL;
n_planes = 0;
memset(&planefmts, 0, sizeof(planefmts));
num_queued_buffers = 0;
total_queued_buffers = 0;
total_dequeued_buffers = 0;
streamon = false;
pthread_mutex_init(&plane_lock, NULL);
pthread_cond_init(&plane_cond, NULL);
dqthread_running = false;
stop_dqthread = false;
dq_thread = 0;
callback = NULL;
memory_type = V4L2_MEMORY_MMAP;
dqThread_data = NULL;
}
NvV4l2ElementPlane::~NvV4l2ElementPlane() {
pthread_mutex_destroy(&plane_lock);
pthread_cond_destroy(&plane_cond);
}
NvBuffer *NvV4l2ElementPlane::getNthBuffer(uint32_t n) {
if (n >= num_buffers) {
PLANE_DEBUG_MSG("WARNING:Requested " << n << "th buffer out of " << num_buffers << "buffers. Returning NULL");
return NULL;
}
return buffers[n];
}
int NvV4l2ElementPlane::dqBuffer(struct v4l2_buffer &v4l2_buf, NvBuffer **buffer, NvBuffer **shared_buffer,
uint32_t num_retries) {
int ret;
v4l2_buf.type = buf_type;
v4l2_buf.memory = memory_type;
do {
ret = v4l2_ioctl(fd, VIDIOC_DQBUF, &v4l2_buf);
if (ret == 0) {
pthread_mutex_lock(&plane_lock);
if (buffer) *buffer = buffers[v4l2_buf.index];
if (shared_buffer && memory_type == V4L2_MEMORY_DMABUF) {
*shared_buffer = (NvBuffer *)buffers[v4l2_buf.index]->shared_buffer;
}
for (uint32_t i = 0; i < buffers[v4l2_buf.index]->n_planes; i++) {
buffers[v4l2_buf.index]->planes[i].bytesused = v4l2_buf.m.planes[i].bytesused;
}
if (buf_type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
v4l2elem_profiler.finishProcessing(0, false);
}
total_dequeued_buffers++;
num_queued_buffers--;
pthread_cond_broadcast(&plane_cond);
PLANE_DEBUG_MSG("DQed buffer " << v4l2_buf.index);
pthread_mutex_unlock(&plane_lock);
} else if (errno == EAGAIN) {
pthread_mutex_lock(&plane_lock);
if (!streamon) {
pthread_mutex_unlock(&plane_lock);
break;
}
pthread_mutex_unlock(&plane_lock);
if (num_retries-- == 0) {
PLANE_WARN_MSG("Error while DQing buffer: Resource temporarily unavailable");
break;
}
if (!blocking) {
usleep(1000);
}
} else {
is_in_error = 1;
PLANE_SYS_ERROR_MSG("Error while DQing buffer");
break;
}
} while (ret && !is_in_error);
return ret;
}
int NvV4l2ElementPlane::qBuffer(struct v4l2_buffer &v4l2_buf, NvBuffer *shared_buffer) {
int ret;
uint32_t i;
NvBuffer *buffer;
pthread_mutex_lock(&plane_lock);
buffer = buffers[v4l2_buf.index];
v4l2_buf.type = buf_type;
v4l2_buf.memory = memory_type;
v4l2_buf.length = n_planes;
switch (memory_type) {
case V4L2_MEMORY_USERPTR:
buffer->shared_buffer = shared_buffer;
for (i = 0; i < buffer->n_planes; i++) {
if (shared_buffer) {
v4l2_buf.m.planes[i].m.userptr = (unsigned long)shared_buffer->planes[i].data;
v4l2_buf.m.planes[i].bytesused = shared_buffer->planes[i].bytesused;
} else {
v4l2_buf.m.planes[i].m.userptr = (unsigned long)buffer->planes[i].data;
v4l2_buf.m.planes[i].bytesused = buffer->planes[i].bytesused;
}
}
break;
case V4L2_MEMORY_MMAP:
for (i = 0; i < buffer->n_planes; i++) {
v4l2_buf.m.planes[i].bytesused = buffer->planes[i].bytesused;
}
break;
case V4L2_MEMORY_DMABUF:
buffer->shared_buffer = shared_buffer;
if (shared_buffer) {
for (i = 0; i < buffer->n_planes; i++) {
v4l2_buf.m.planes[i].m.fd = shared_buffer->planes[i].fd;
v4l2_buf.m.planes[i].bytesused = shared_buffer->planes[i].bytesused;
}
}
break;
default:
return -1;
}
if (buf_type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE) {
v4l2elem_profiler.startProcessing();
}
ret = v4l2_ioctl(fd, VIDIOC_QBUF, &v4l2_buf);
if (ret) {
is_in_error = 1;
PLANE_SYS_ERROR_MSG("Error while Qing buffer");
} else {
PLANE_DEBUG_MSG("Qed buffer " << v4l2_buf.index);
pthread_cond_broadcast(&plane_cond);
total_queued_buffers++;
num_queued_buffers++;
}
pthread_mutex_unlock(&plane_lock);
return ret;
}
int NvV4l2ElementPlane::getFormat(struct v4l2_format &format) {
format.type = buf_type;
CHECK_V4L2_RETURN(v4l2_ioctl(fd, VIDIOC_G_FMT, &format), "Getting format");
}
int NvV4l2ElementPlane::setFormat(struct v4l2_format &format) {
int ret;
format.type = buf_type;
ret = v4l2_ioctl(fd, VIDIOC_S_FMT, &format);
if (ret) {
PLANE_SYS_ERROR_MSG("Error in VIDIOC_S_FMT");
is_in_error = 1;
} else {
PLANE_DEBUG_MSG("VIDIOC_S_FMT at capture plane successful");
n_planes = format.fmt.pix_mp.num_planes;
for (int j = 0; j < n_planes; j++) {
planefmts[j].stride = format.fmt.pix_mp.plane_fmt[j].bytesperline;
planefmts[j].sizeimage = format.fmt.pix_mp.plane_fmt[j].sizeimage;
}
}
return ret;
}
int NvV4l2ElementPlane::getCrop(struct v4l2_crop &crop) {
crop.type = buf_type;
CHECK_V4L2_RETURN(v4l2_ioctl(fd, VIDIOC_G_CROP, &crop), "Getting crop params");
}
int NvV4l2ElementPlane::setSelection(uint32_t target, uint32_t flags, struct v4l2_rect &rect) {
struct v4l2_selection select;
switch (buf_type) {
case V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE:
select.type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
break;
case V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE:
select.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
break;
default:
PLANE_ERROR_MSG("Unsupported v4l2_buf_type " << buf_type);
return -1;
}
select.target = target;
select.flags = flags;
select.r = rect;
CHECK_V4L2_RETURN(v4l2_ioctl(fd, VIDIOC_S_SELECTION, &select), "Setting selection");
}
void NvV4l2ElementPlane::setBufferPlaneFormat(int n_planes, NvBuffer::NvBufferPlaneFormat *planefmts) {
int i;
this->n_planes = n_planes;
for (i = 0; i < n_planes; i++) {
this->planefmts[i] = planefmts[i];
}
}
void NvV4l2ElementPlane::deinitPlane() {
setStreamStatus(false);
waitForDQThread(-1);
for (uint32_t i = 0; i < num_buffers; i++) {
switch (memory_type) {
case V4L2_MEMORY_USERPTR:
buffers[i]->deallocateMemory();
break;
case V4L2_MEMORY_MMAP:
buffers[i]->unmap();
break;
case V4L2_MEMORY_DMABUF:
break;
default:
return;
}
}
reqbufs(memory_type, 0);
PLANE_DEBUG_MSG("deinit successful");
}
int NvV4l2ElementPlane::reqbufs(enum v4l2_memory mem_type, uint32_t num) {
struct v4l2_requestbuffers reqbufs;
int ret;
memset(&reqbufs, 0, sizeof(struct v4l2_requestbuffers));
reqbufs.count = num;
reqbufs.type = buf_type;
switch (mem_type) {
case V4L2_MEMORY_USERPTR:
for (uint32_t i = 0; i < n_planes; i++) {
planefmts[i].stride = planefmts[i].width * planefmts[i].bytesperpixel;
planefmts[i].sizeimage = planefmts[i].width * planefmts[i].height;
}
break;
case V4L2_MEMORY_MMAP:
case V4L2_MEMORY_DMABUF:
break;
default:
PLANE_ERROR_MSG("Error in VIDIOC_REQBUFS:Unknown memory type " << mem_type);
return -1;
}
memory_type = mem_type;
reqbufs.memory = mem_type;
ret = v4l2_ioctl(fd, VIDIOC_REQBUFS, &reqbufs);
if (ret) {
PLANE_SYS_ERROR_MSG("Error in VIDIOC_REQBUFS at output plane");
is_in_error = 1;
} else {
if (reqbufs.count) {
buffers = new NvBuffer *[reqbufs.count];
for (uint32_t i = 0; i < reqbufs.count; i++) {
buffers[i] = new NvBuffer(buf_type, mem_type, n_planes, planefmts, i);
}
} else {
for (uint32_t i = 0; i < num_buffers; i++) {
delete buffers[i];
}
delete[] buffers;
buffers = NULL;
}
num_buffers = reqbufs.count;
PLANE_DEBUG_MSG("Reqbuf returned " << reqbufs.count << " buffers");
}
return ret;
}
int NvV4l2ElementPlane::setStreamStatus(bool status) {
int ret;
if (status == streamon) {
PLANE_DEBUG_MSG("Already in " << ((status) ? "STREAMON" : "STREAMOFF"));
return 0;
}
pthread_mutex_lock(&plane_lock);
if (status) {
ret = v4l2_ioctl(fd, VIDIOC_STREAMON, &buf_type);
} else {
ret = v4l2_ioctl(fd, VIDIOC_STREAMOFF, &buf_type);
}
if (ret) {
PLANE_SYS_ERROR_MSG("Error in " << ((status) ? "STREAMON" : "STREAMOFF"));
is_in_error = 1;
} else {
PLANE_DEBUG_MSG(((status) ? "STREAMON" : "STREAMOFF") << " successful");
streamon = status;
if (!streamon) {
num_queued_buffers = 0;
pthread_cond_broadcast(&plane_cond);
}
if (buf_type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE) {
if (status) {
v4l2elem_profiler.enableProfiling(false);
} else {
v4l2elem_profiler.disableProfiling();
}
}
}
pthread_mutex_unlock(&plane_lock);
return ret;
}
bool NvV4l2ElementPlane::getStreamStatus() { return streamon; }
int NvV4l2ElementPlane::setStreamParms(struct v4l2_streamparm &parm) {
int ret;
parm.type = buf_type;
ret = v4l2_ioctl(fd, VIDIOC_S_PARM, &parm);
if (ret == 0) {
PLANE_DEBUG_MSG("Successfully set stream parameters");
} else {
PLANE_SYS_ERROR_MSG("Error while setting stream parameters");
}
return ret;
}
int NvV4l2ElementPlane::queryBuffer(uint32_t i) {
struct v4l2_buffer v4l2_buf;
struct v4l2_plane planes[MAX_PLANES];
int ret;
memset(&v4l2_buf, 0, sizeof(struct v4l2_buffer));
memset(planes, 0, sizeof(planes));
v4l2_buf.index = i;
v4l2_buf.type = buf_type;
v4l2_buf.memory = memory_type;
v4l2_buf.m.planes = planes;
v4l2_buf.length = n_planes;
ret = v4l2_ioctl(fd, VIDIOC_QUERYBUF, &v4l2_buf);
if (ret) {
PLANE_SYS_ERROR_MSG("Error in QueryBuf for " << i << "th buffer");
is_in_error = 1;
} else {
PLANE_DEBUG_MSG("QueryBuf for " << i << "th buffer successful");
for (uint32_t j = 0; j < v4l2_buf.length; j++) {
buffers[i]->planes[j].length = v4l2_buf.m.planes[j].length;
buffers[i]->planes[j].mem_offset = v4l2_buf.m.planes[j].m.mem_offset;
}
}
return ret;
}
int NvV4l2ElementPlane::exportBuffer(uint32_t i) {
struct v4l2_exportbuffer expbuf;
memset(&expbuf, 0, sizeof(expbuf));
expbuf.type = buf_type;
expbuf.index = i;
for (int j = 0; j < n_planes; j++) {
expbuf.plane = j;
int ret = v4l2_ioctl(fd, VIDIOC_EXPBUF, &expbuf);
if (ret) {
PLANE_SYS_ERROR_MSG("Error in ExportBuf for Buffer " << i << ", Plane " << j);
is_in_error = 1;
return -1;
} else {
PLANE_DEBUG_MSG("ExportBuf successful for Buffer " << i << ", Plane " << j << ", fd = " << expbuf.fd);
buffers[i]->planes[j].fd = expbuf.fd;
}
}
return 0;
}
int NvV4l2ElementPlane::setupPlane(enum v4l2_memory mem_type, uint32_t num_buffers, bool map, bool allocate) {
uint32_t i;
if (reqbufs(mem_type, num_buffers)) {
goto error;
}
for (i = 0; i < this->num_buffers; i++) {
switch (mem_type) {
case V4L2_MEMORY_USERPTR:
if (allocate) {
if (buffers[i]->allocateMemory()) {
goto error;
}
}
break;
case V4L2_MEMORY_MMAP:
if (queryBuffer(i)) {
goto error;
}
if (exportBuffer(i)) {
goto error;
}
if (map) {
if (buffers[i]->map()) {
goto error;
}
}
break;
default:
continue;
}
}
return 0;
error:
PLANE_ERROR_MSG("Error during setup");
is_in_error = 1;
deinitPlane();
return -1;
}
int NvV4l2ElementPlane::waitAllBuffersQueued(uint32_t max_wait_ms) {
struct timespec timeToWait;
struct timeval now;
int return_val = 0;
gettimeofday(&now, NULL);
timeToWait.tv_nsec = (now.tv_usec + (max_wait_ms % 1000) * 1000L) * 1000L;
timeToWait.tv_sec = now.tv_sec + max_wait_ms / 1000 + timeToWait.tv_nsec / 1000000000L;
timeToWait.tv_nsec = timeToWait.tv_nsec % 1000000000L;
pthread_mutex_lock(&plane_lock);
while (num_queued_buffers < num_buffers) {
int ret = pthread_cond_timedwait(&plane_cond, &plane_lock, &timeToWait);
if (ret == ETIMEDOUT) {
return_val = -1;
break;
}
}
pthread_mutex_unlock(&plane_lock);
CHECK_V4L2_RETURN(return_val, "Waiting for all buffers to get queued");
}
int NvV4l2ElementPlane::waitAllBuffersDequeued(uint32_t max_wait_ms) {
struct timespec timeToWait;
struct timeval now;
int return_val = 0;
gettimeofday(&now, NULL);
timeToWait.tv_nsec = (now.tv_usec + (max_wait_ms % 1000) * 1000L) * 1000L;
timeToWait.tv_sec = now.tv_sec + max_wait_ms / 1000 + timeToWait.tv_nsec / 1000000000L;
timeToWait.tv_nsec = timeToWait.tv_nsec % 1000000000L;
pthread_mutex_lock(&plane_lock);
while (num_queued_buffers) {
int ret = pthread_cond_timedwait(&plane_cond, &plane_lock, &timeToWait);
if (ret == ETIMEDOUT) {
return_val = -1;
break;
}
}
pthread_mutex_unlock(&plane_lock);
CHECK_V4L2_RETURN(return_val, "Waiting for all buffers to get dequeued");
}
bool NvV4l2ElementPlane::setDQThreadCallback(dqThreadCallback callback) {
if (dqthread_running) return false;
this->callback = callback;
return true;
}
void *NvV4l2ElementPlane::dqThread(void *data) {
NvV4l2ElementPlane *plane = (NvV4l2ElementPlane *)data;
const char *comp_name = plane->comp_name;
const char *plane_name = plane->plane_name;
PLANE_DEBUG_MSG("Starting DQthread");
prctl(PR_SET_NAME, plane_name, 0, 0, 0);
plane->stop_dqthread = false;
while (!plane->stop_dqthread) {
struct v4l2_buffer v4l2_buf;
struct v4l2_plane planes[MAX_PLANES];
NvBuffer *buffer;
NvBuffer *shared_buffer;
bool ret;
memset(&v4l2_buf, 0, sizeof(v4l2_buf));
memset(planes, 0, sizeof(planes));
v4l2_buf.m.planes = planes;
v4l2_buf.length = plane->n_planes;
if (plane->dqBuffer(v4l2_buf, &buffer, &shared_buffer, -1) < 0) {
if (errno != EAGAIN) {
plane->is_in_error = 1;
}
if (errno != EAGAIN || plane->streamon) {
ret = plane->callback(NULL, NULL, NULL, plane->dqThread_data);
}
if (!plane->streamon) {
break;
}
} else {
ret = plane->callback(&v4l2_buf, buffer, shared_buffer, plane->dqThread_data);
}
if (!ret) {
break;
}
}
plane->stop_dqthread = false;
pthread_mutex_lock(&plane->plane_lock);
plane->dqthread_running = false;
pthread_cond_broadcast(&plane->plane_cond);
pthread_mutex_unlock(&plane->plane_lock);
PLANE_DEBUG_MSG("Exiting DQthread");
return NULL;
}
int NvV4l2ElementPlane::startDQThread(void *data) {
pthread_mutex_lock(&plane_lock);
if (dqthread_running) {
PLANE_DEBUG_MSG("DQ Thread already started");
pthread_mutex_unlock(&plane_lock);
return 0;
}
dqThread_data = data;
pthread_create(&dq_thread, NULL, dqThread, this);
dqthread_running = true;
pthread_mutex_unlock(&plane_lock);
PLANE_DEBUG_MSG("Started DQ Thread");
return 0;
}
int NvV4l2ElementPlane::stopDQThread() {
if (blocking) {
PLANE_WARN_MSG("Should not be called in blocking mode");
return 0;
}
stop_dqthread = true;
pthread_join(dq_thread, NULL);
dq_thread = 0;
PLANE_DEBUG_MSG("Stopped DQ Thread");
return 0;
}
int NvV4l2ElementPlane::waitForDQThread(uint32_t max_wait_ms) {
struct timespec timeToWait;
struct timeval now;
int return_val = 0;
int ret = 0;
gettimeofday(&now, NULL);
timeToWait.tv_nsec = (now.tv_usec + (max_wait_ms % 1000) * 1000L) * 1000L;
timeToWait.tv_sec = now.tv_sec + max_wait_ms / 1000 + timeToWait.tv_nsec / 1000000000L;
timeToWait.tv_nsec = timeToWait.tv_nsec % 1000000000L;
pthread_mutex_lock(&plane_lock);
while (dqthread_running) {
ret = pthread_cond_timedwait(&plane_cond, &plane_lock, &timeToWait);
if (ret == ETIMEDOUT) {
return_val = -1;
break;
}
}
pthread_mutex_unlock(&plane_lock);
if (ret == 0) {
pthread_join(dq_thread, NULL);
dq_thread = 0;
PLANE_DEBUG_MSG("Stopped DQ Thread");
} else {
PLANE_ERROR_MSG("Timed out waiting for dqthread");
}
return return_val;
}
|
/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "stdio.h"
#include "SkSLParser.h"
#include "SkSLToken.h"
#define register
#include "disable_flex_warnings.h"
#include "lex.sksl.c"
static_assert(YY_FLEX_MAJOR_VERSION * 10000 + YY_FLEX_MINOR_VERSION * 100 +
YY_FLEX_SUBMINOR_VERSION >= 20601,
"we require Flex 2.6.1 or better for security reasons");
#undef register
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "lex.layout.h"
#include "ast/SkSLASTBinaryExpression.h"
#include "ast/SkSLASTBlock.h"
#include "ast/SkSLASTBoolLiteral.h"
#include "ast/SkSLASTBreakStatement.h"
#include "ast/SkSLASTCallSuffix.h"
#include "ast/SkSLASTContinueStatement.h"
#include "ast/SkSLASTDiscardStatement.h"
#include "ast/SkSLASTDoStatement.h"
#include "ast/SkSLASTExpression.h"
#include "ast/SkSLASTExpressionStatement.h"
#include "ast/SkSLASTExtension.h"
#include "ast/SkSLASTFieldSuffix.h"
#include "ast/SkSLASTFloatLiteral.h"
#include "ast/SkSLASTForStatement.h"
#include "ast/SkSLASTFunction.h"
#include "ast/SkSLASTIdentifier.h"
#include "ast/SkSLASTIfStatement.h"
#include "ast/SkSLASTIndexSuffix.h"
#include "ast/SkSLASTInterfaceBlock.h"
#include "ast/SkSLASTIntLiteral.h"
#include "ast/SkSLASTModifiersDeclaration.h"
#include "ast/SkSLASTParameter.h"
#include "ast/SkSLASTPrecision.h"
#include "ast/SkSLASTPrefixExpression.h"
#include "ast/SkSLASTReturnStatement.h"
#include "ast/SkSLASTSection.h"
#include "ast/SkSLASTStatement.h"
#include "ast/SkSLASTSuffixExpression.h"
#include "ast/SkSLASTSwitchCase.h"
#include "ast/SkSLASTSwitchStatement.h"
#include "ast/SkSLASTTernaryExpression.h"
#include "ast/SkSLASTType.h"
#include "ast/SkSLASTVarDeclaration.h"
#include "ast/SkSLASTVarDeclarationStatement.h"
#include "ast/SkSLASTWhileStatement.h"
#include "ir/SkSLSymbolTable.h"
#include "ir/SkSLModifiers.h"
#include "ir/SkSLType.h"
namespace SkSL {
#define MAX_PARSE_DEPTH 50
class AutoDepth {
public:
AutoDepth(Parser* p)
: fParser(p) {
fParser->fDepth++;
}
~AutoDepth() {
fParser->fDepth--;
}
bool checkValid() {
if (fParser->fDepth > MAX_PARSE_DEPTH) {
fParser->error(fParser->peek().fPosition, String("exceeded max parse depth"));
return false;
}
return true;
}
private:
Parser* fParser;
};
Parser::Parser(String text, SymbolTable& types, ErrorReporter& errors)
: fPushback(Position(-1, -1), Token::INVALID_TOKEN, String())
, fTypes(types)
, fErrors(errors) {
sksllex_init(&fScanner);
layoutlex_init(&fLayoutScanner);
fBuffer = sksl_scan_string(text.c_str(), fScanner);
skslset_lineno(1, fScanner);
}
Parser::~Parser() {
sksl_delete_buffer(fBuffer, fScanner);
sksllex_destroy(fScanner);
layoutlex_destroy(fLayoutScanner);
}
/* (precision | directive | section | declaration)* END_OF_FILE */
std::vector<std::unique_ptr<ASTDeclaration>> Parser::file() {
std::vector<std::unique_ptr<ASTDeclaration>> result;
for (;;) {
switch (this->peek().fKind) {
case Token::END_OF_FILE:
return result;
case Token::PRECISION: {
std::unique_ptr<ASTDeclaration> precision = this->precision();
if (precision) {
result.push_back(std::move(precision));
}
break;
}
case Token::DIRECTIVE: {
std::unique_ptr<ASTDeclaration> decl = this->directive();
if (decl) {
result.push_back(std::move(decl));
}
break;
}
case Token::SECTION: {
std::unique_ptr<ASTDeclaration> section = this->section();
if (section) {
result.push_back(std::move(section));
}
break;
}
default: {
std::unique_ptr<ASTDeclaration> decl = this->declaration();
if (!decl) {
continue;
}
result.push_back(std::move(decl));
}
}
}
}
Token Parser::nextRawToken(bool needText) {
if (fPushback.fKind != Token::INVALID_TOKEN) {
Token result(std::move(fPushback));
fPushback.fKind = Token::INVALID_TOKEN;
fPushback.fText.clear();
return result;
}
Token::Kind kind = (Token::Kind) sksllex(fScanner);
if (!needText) {
switch (kind) {
case Token::Kind::DIRECTIVE: // fall through
case Token::Kind::IDENTIFIER: // fall through
case Token::Kind::INT_LITERAL: // fall through
case Token::Kind::FLOAT_LITERAL: // fall through
case Token::Kind::SECTION:
needText = true;
default:
break;
}
}
static String unavailable("<unavailable>");
return Token(Position(skslget_lineno(fScanner), -1), kind,
needText ? String(skslget_text(fScanner)) : unavailable);
}
Token Parser::nextToken() {
Token token;
do {
token = this->nextRawToken(false);
} while (token.fKind == Token::WHITESPACE);
return token;
}
void Parser::pushback(Token t) {
ASSERT(fPushback.fKind == Token::INVALID_TOKEN);
fPushback = std::move(t);
}
Token Parser::peek() {
if (fPushback.fKind == Token::INVALID_TOKEN) {
fPushback = this->nextToken();
}
return fPushback;
}
bool Parser::checkNext(Token::Kind kind, Token* result) {
if (fPushback.fKind != Token::INVALID_TOKEN && fPushback.fKind != kind) {
return false;
}
Token next = this->nextToken();
if (next.fKind == kind) {
if (result) {
*result = next;
}
return true;
}
this->pushback(std::move(next));
return false;
}
bool Parser::expect(Token::Kind kind, const char* expected, Token* result) {
Token next = this->nextToken();
if (next.fKind == kind) {
if (result) {
*result = std::move(next);
}
return true;
} else {
if (next.fText.size()) {
this->error(next.fPosition, "expected " + String(expected) + ", but found '" +
next.fText + "'");
} else {
this->error(next.fPosition, "parse error, recompile in debug mode for details");
}
return false;
}
}
void Parser::error(Position p, const char* msg) {
this->error(p, String(msg));
}
void Parser::error(Position p, String msg) {
fErrors.error(p, msg);
}
bool Parser::isType(const String& name) {
return nullptr != fTypes[name];
}
/* PRECISION (LOWP | MEDIUMP | HIGHP) type SEMICOLON */
std::unique_ptr<ASTDeclaration> Parser::precision() {
if (!this->expect(Token::PRECISION, "'precision'")) {
return nullptr;
}
Modifiers::Flag result;
Token p = this->nextToken();
switch (p.fKind) {
case Token::LOWP:
result = Modifiers::kLowp_Flag;
break;
case Token::MEDIUMP:
result = Modifiers::kMediump_Flag;
break;
case Token::HIGHP:
result = Modifiers::kHighp_Flag;
break;
default:
this->error(p.fPosition, "expected 'lowp', 'mediump', or 'highp', but found '" +
p.fText + "'");
return nullptr;
}
// FIXME handle the type
if (!this->type()) {
return nullptr;
}
this->expect(Token::SEMICOLON, "';'");
return std::unique_ptr<ASTDeclaration>(new ASTPrecision(p.fPosition, result));
}
/* DIRECTIVE(#version) INT_LITERAL ("es" | "compatibility")? |
DIRECTIVE(#extension) IDENTIFIER COLON IDENTIFIER */
std::unique_ptr<ASTDeclaration> Parser::directive() {
Token start;
if (!this->expect(Token::DIRECTIVE, "a directive", &start)) {
return nullptr;
}
if (start.fText == "#version") {
this->expect(Token::INT_LITERAL, "a version number");
Token next = this->peek();
if (next.fText == "es" || next.fText == "compatibility") {
this->nextToken();
}
// version is ignored for now; it will eventually become an error when we stop pretending
// to be GLSL
return nullptr;
} else if (start.fText == "#extension") {
Token name;
if (!this->expect(Token::IDENTIFIER, "an identifier", &name)) {
return nullptr;
}
if (!this->expect(Token::COLON, "':'")) {
return nullptr;
}
// FIXME: need to start paying attention to this token
if (!this->expect(Token::IDENTIFIER, "an identifier")) {
return nullptr;
}
return std::unique_ptr<ASTDeclaration>(new ASTExtension(start.fPosition,
std::move(name.fText)));
} else {
this->error(start.fPosition, "unsupported directive '" + start.fText + "'");
return nullptr;
}
}
/* SECTION LBRACE (LPAREN IDENTIFIER RPAREN)? <any sequence of tokens with balanced braces>
RBRACE */
std::unique_ptr<ASTDeclaration> Parser::section() {
Token start;
if (!this->expect(Token::SECTION, "a section token", &start)) {
return nullptr;
}
String argument;
if (this->peek().fKind == Token::LPAREN) {
this->nextToken();
Token argToken;
if (!this->expect(Token::IDENTIFIER, "an identifier", &argToken)) {
return nullptr;
}
argument = argToken.fText;
if (!this->expect(Token::RPAREN, "')'")) {
return nullptr;
}
}
if (!this->expect(Token::LBRACE, "'{'")) {
return nullptr;
}
String text;
int level = 1;
for (;;) {
Token next = this->nextRawToken(true);
switch (next.fKind) {
case Token::LBRACE:
++level;
break;
case Token::RBRACE:
--level;
break;
case Token::END_OF_FILE:
this->error(start.fPosition, "reached end of file while parsing section");
return nullptr;
default:
break;
}
if (!level) {
break;
}
text += next.fText;
}
return std::unique_ptr<ASTDeclaration>(new ASTSection(start.fPosition,
String(start.fText.c_str() + 1),
argument,
text));
}
/* modifiers (structVarDeclaration | type IDENTIFIER ((LPAREN parameter
(COMMA parameter)* RPAREN (block | SEMICOLON)) | SEMICOLON) | interfaceBlock) */
std::unique_ptr<ASTDeclaration> Parser::declaration() {
Modifiers modifiers = this->modifiers();
Token lookahead = this->peek();
if (lookahead.fKind == Token::IDENTIFIER && !this->isType(lookahead.fText)) {
// we have an identifier that's not a type, could be the start of an interface block
return this->interfaceBlock(modifiers);
}
if (lookahead.fKind == Token::STRUCT) {
return this->structVarDeclaration(modifiers);
}
if (lookahead.fKind == Token::SEMICOLON) {
this->nextToken();
return std::unique_ptr<ASTDeclaration>(new ASTModifiersDeclaration(modifiers));
}
std::unique_ptr<ASTType> type(this->type());
if (!type) {
return nullptr;
}
if (type->fKind == ASTType::kStruct_Kind && this->checkNext(Token::SEMICOLON)) {
return nullptr;
}
Token name;
if (!this->expect(Token::IDENTIFIER, "an identifier", &name)) {
return nullptr;
}
if (this->checkNext(Token::LPAREN)) {
std::vector<std::unique_ptr<ASTParameter>> parameters;
while (this->peek().fKind != Token::RPAREN) {
if (parameters.size() > 0) {
if (!this->expect(Token::COMMA, "','")) {
return nullptr;
}
}
std::unique_ptr<ASTParameter> parameter = this->parameter();
if (!parameter) {
return nullptr;
}
parameters.push_back(std::move(parameter));
}
this->nextToken();
std::unique_ptr<ASTBlock> body;
if (!this->checkNext(Token::SEMICOLON)) {
body = this->block();
if (!body) {
return nullptr;
}
}
return std::unique_ptr<ASTDeclaration>(new ASTFunction(name.fPosition,
modifiers,
std::move(type),
std::move(name.fText),
std::move(parameters),
std::move(body)));
} else {
return this->varDeclarationEnd(modifiers, std::move(type), std::move(name.fText));
}
}
/* modifiers type IDENTIFIER varDeclarationEnd */
std::unique_ptr<ASTVarDeclarations> Parser::varDeclarations() {
Modifiers modifiers = this->modifiers();
std::unique_ptr<ASTType> type(this->type());
if (!type) {
return nullptr;
}
Token name;
if (!this->expect(Token::IDENTIFIER, "an identifier", &name)) {
return nullptr;
}
return this->varDeclarationEnd(modifiers, std::move(type), std::move(name.fText));
}
/* STRUCT IDENTIFIER LBRACE varDeclaration* RBRACE */
std::unique_ptr<ASTType> Parser::structDeclaration() {
if (!this->expect(Token::STRUCT, "'struct'")) {
return nullptr;
}
Token name;
if (!this->expect(Token::IDENTIFIER, "an identifier", &name)) {
return nullptr;
}
if (!this->expect(Token::LBRACE, "'{'")) {
return nullptr;
}
std::vector<Type::Field> fields;
while (this->peek().fKind != Token::RBRACE) {
std::unique_ptr<ASTVarDeclarations> decl = this->varDeclarations();
if (!decl) {
return nullptr;
}
for (const auto& var : decl->fVars) {
auto type = (const Type*) fTypes[decl->fType->fName];
for (int i = (int) var.fSizes.size() - 1; i >= 0; i--) {
if (!var.fSizes[i] || var.fSizes[i]->fKind != ASTExpression::kInt_Kind) {
this->error(decl->fPosition, "array size in struct field must be a constant");
return nullptr;
}
uint64_t columns = ((ASTIntLiteral&) *var.fSizes[i]).fValue;
String name = type->name() + "[" + to_string(columns) + "]";
type = new Type(name, Type::kArray_Kind, *type, (int) columns);
fTypes.takeOwnership((Type*) type);
}
fields.push_back(Type::Field(decl->fModifiers, var.fName, type));
if (var.fValue) {
this->error(decl->fPosition, "initializers are not permitted on struct fields");
}
}
}
if (!this->expect(Token::RBRACE, "'}'")) {
return nullptr;
}
fTypes.add(name.fText, std::unique_ptr<Type>(new Type(name.fPosition, name.fText, fields)));
return std::unique_ptr<ASTType>(new ASTType(name.fPosition, name.fText,
ASTType::kStruct_Kind, std::vector<int>()));
}
/* structDeclaration ((IDENTIFIER varDeclarationEnd) | SEMICOLON) */
std::unique_ptr<ASTVarDeclarations> Parser::structVarDeclaration(Modifiers modifiers) {
std::unique_ptr<ASTType> type = this->structDeclaration();
if (!type) {
return nullptr;
}
Token name;
if (this->checkNext(Token::IDENTIFIER, &name)) {
std::unique_ptr<ASTVarDeclarations> result = this->varDeclarationEnd(modifiers,
std::move(type),
std::move(name.fText));
if (result) {
for (const auto& var : result->fVars) {
if (var.fValue) {
this->error(var.fValue->fPosition,
"struct variables cannot be initialized");
}
}
}
return result;
}
this->expect(Token::SEMICOLON, "';'");
return nullptr;
}
/* (LBRACKET expression? RBRACKET)* (EQ assignmentExpression)? (COMMA IDENTIFER
(LBRACKET expression? RBRACKET)* (EQ assignmentExpression)?)* SEMICOLON */
std::unique_ptr<ASTVarDeclarations> Parser::varDeclarationEnd(Modifiers mods,
std::unique_ptr<ASTType> type,
String name) {
std::vector<ASTVarDeclaration> vars;
std::vector<std::unique_ptr<ASTExpression>> currentVarSizes;
while (this->checkNext(Token::LBRACKET)) {
if (this->checkNext(Token::RBRACKET)) {
currentVarSizes.push_back(nullptr);
} else {
std::unique_ptr<ASTExpression> size(this->expression());
if (!size) {
return nullptr;
}
currentVarSizes.push_back(std::move(size));
if (!this->expect(Token::RBRACKET, "']'")) {
return nullptr;
}
}
}
std::unique_ptr<ASTExpression> value;
if (this->checkNext(Token::EQ)) {
value = this->assignmentExpression();
if (!value) {
return nullptr;
}
}
vars.emplace_back(std::move(name), std::move(currentVarSizes), std::move(value));
while (this->checkNext(Token::COMMA)) {
Token name;
if (!this->expect(Token::IDENTIFIER, "an identifier", &name)) {
return nullptr;
}
currentVarSizes.clear();
value.reset();
while (this->checkNext(Token::LBRACKET)) {
if (this->checkNext(Token::RBRACKET)) {
currentVarSizes.push_back(nullptr);
} else {
std::unique_ptr<ASTExpression> size(this->expression());
if (!size) {
return nullptr;
}
currentVarSizes.push_back(std::move(size));
if (!this->expect(Token::RBRACKET, "']'")) {
return nullptr;
}
}
}
if (this->checkNext(Token::EQ)) {
value = this->assignmentExpression();
if (!value) {
return nullptr;
}
}
vars.emplace_back(std::move(name.fText), std::move(currentVarSizes), std::move(value));
}
if (!this->expect(Token::SEMICOLON, "';'")) {
return nullptr;
}
return std::unique_ptr<ASTVarDeclarations>(new ASTVarDeclarations(std::move(mods),
std::move(type),
std::move(vars)));
}
/* modifiers type IDENTIFIER (LBRACKET INT_LITERAL RBRACKET)? */
std::unique_ptr<ASTParameter> Parser::parameter() {
Modifiers modifiers = this->modifiersWithDefaults(0);
std::unique_ptr<ASTType> type = this->type();
if (!type) {
return nullptr;
}
Token name;
if (!this->expect(Token::IDENTIFIER, "an identifier", &name)) {
return nullptr;
}
std::vector<int> sizes;
while (this->checkNext(Token::LBRACKET)) {
Token sizeToken;
if (!this->expect(Token::INT_LITERAL, "a positive integer", &sizeToken)) {
return nullptr;
}
sizes.push_back(SkSL::stoi(sizeToken.fText));
if (!this->expect(Token::RBRACKET, "']'")) {
return nullptr;
}
}
return std::unique_ptr<ASTParameter>(new ASTParameter(name.fPosition, modifiers,
std::move(type), name.fText,
std::move(sizes)));
}
/** (EQ INT_LITERAL)? */
int Parser::layoutInt() {
if (!this->expect(Token::EQ, "'='")) {
return -1;
}
Token resultToken;
if (this->expect(Token::INT_LITERAL, "a non-negative integer", &resultToken)) {
return SkSL::stoi(resultToken.fText);
}
return -1;
}
/** EQ <any sequence of tokens with balanced parentheses and no top-level comma> */
String Parser::layoutCode() {
if (!this->expect(Token::EQ, "'='")) {
return "";
}
Token start = this->nextRawToken(true);
this->pushback(start);
String code;
int level = 1;
bool done = false;
while (!done) {
Token next = this->nextRawToken(true);
switch (next.fKind) {
case Token::LPAREN:
++level;
break;
case Token::RPAREN:
--level;
break;
case Token::COMMA:
if (level == 1) {
done = true;
}
break;
case Token::END_OF_FILE:
this->error(start.fPosition, "reached end of file while parsing layout");
return nullptr;
default:
break;
}
if (!level) {
done = true;
}
if (done) {
this->pushback(std::move(next));
}
else {
code += next.fText;
}
}
return code;
}
/** (EQ IDENTIFIER('identity'))? */
Layout::Key Parser::layoutKey() {
if (this->peek().fKind == Token::EQ) {
this->expect(Token::EQ, "'='");
Token key;
if (this->expect(Token::IDENTIFIER, "an identifer", &key)) {
if (key.fText == "identity") {
return Layout::kIdentity_Key;
} else {
this->error(key.fPosition, "unsupported layout key");
}
}
}
return Layout::kKey_Key;
}
/* LAYOUT LPAREN IDENTIFIER (EQ INT_LITERAL)? (COMMA IDENTIFIER (EQ INT_LITERAL)?)* RPAREN */
Layout Parser::layout() {
int location = -1;
int offset = -1;
int binding = -1;
int index = -1;
int set = -1;
int builtin = -1;
int inputAttachmentIndex = -1;
bool originUpperLeft = false;
bool overrideCoverage = false;
bool blendSupportAllEquations = false;
Layout::Format format = Layout::Format::kUnspecified;
bool pushConstant = false;
Layout::Primitive primitive = Layout::kUnspecified_Primitive;
int maxVertices = -1;
int invocations = -1;
String when;
Layout::Key key = Layout::kNo_Key;
if (this->checkNext(Token::LAYOUT)) {
if (!this->expect(Token::LPAREN, "'('")) {
return Layout(location, offset, binding, index, set, builtin, inputAttachmentIndex,
originUpperLeft, overrideCoverage, blendSupportAllEquations, format,
pushConstant, primitive, maxVertices, invocations, when, key);
}
for (;;) {
Token t = this->nextToken();
YY_BUFFER_STATE buffer;
buffer = layout_scan_string(t.fText.c_str(), fLayoutScanner);
int token = layoutlex(fLayoutScanner);
layout_delete_buffer(buffer, fLayoutScanner);
if (token != Token::INVALID_TOKEN) {
switch (token) {
case Token::LOCATION:
location = this->layoutInt();
break;
case Token::OFFSET:
offset = this->layoutInt();
break;
case Token::BINDING:
binding = this->layoutInt();
break;
case Token::INDEX:
index = this->layoutInt();
break;
case Token::SET:
set = this->layoutInt();
break;
case Token::BUILTIN:
builtin = this->layoutInt();
break;
case Token::INPUT_ATTACHMENT_INDEX:
inputAttachmentIndex = this->layoutInt();
break;
case Token::ORIGIN_UPPER_LEFT:
originUpperLeft = true;
break;
case Token::OVERRIDE_COVERAGE:
overrideCoverage = true;
break;
case Token::BLEND_SUPPORT_ALL_EQUATIONS:
blendSupportAllEquations = true;
break;
case Token::PUSH_CONSTANT:
pushConstant = true;
break;
case Token::POINTS:
primitive = Layout::kPoints_Primitive;
break;
case Token::LINES:
primitive = Layout::kLines_Primitive;
break;
case Token::LINE_STRIP:
primitive = Layout::kLineStrip_Primitive;
break;
case Token::LINES_ADJACENCY:
primitive = Layout::kLinesAdjacency_Primitive;
break;
case Token::TRIANGLES:
primitive = Layout::kTriangles_Primitive;
break;
case Token::TRIANGLE_STRIP:
primitive = Layout::kTriangleStrip_Primitive;
break;
case Token::TRIANGLES_ADJACENCY:
primitive = Layout::kTrianglesAdjacency_Primitive;
break;
case Token::MAX_VERTICES:
maxVertices = this->layoutInt();
break;
case Token::INVOCATIONS:
invocations = this->layoutInt();
break;
case Token::WHEN:
when = this->layoutCode();
break;
case Token::KEY:
key = this->layoutKey();
break;
}
} else if (Layout::ReadFormat(t.fText, &format)) {
// AST::ReadFormat stored the result in 'format'.
} else {
this->error(t.fPosition, ("'" + t.fText +
"' is not a valid layout qualifier").c_str());
}
if (this->checkNext(Token::RPAREN)) {
break;
}
if (!this->expect(Token::COMMA, "','")) {
break;
}
}
}
return Layout(location, offset, binding, index, set, builtin, inputAttachmentIndex,
originUpperLeft, overrideCoverage, blendSupportAllEquations, format,
pushConstant, primitive, maxVertices, invocations, when, key);
}
/* layout? (UNIFORM | CONST | IN | OUT | INOUT | LOWP | MEDIUMP | HIGHP | FLAT | NOPERSPECTIVE |
READONLY | WRITEONLY | COHERENT | VOLATILE | RESTRICT | BUFFER)* */
Modifiers Parser::modifiers() {
Layout layout = this->layout();
int flags = 0;
for (;;) {
// TODO: handle duplicate / incompatible flags
switch (peek().fKind) {
case Token::UNIFORM:
this->nextToken();
flags |= Modifiers::kUniform_Flag;
break;
case Token::CONST:
this->nextToken();
flags |= Modifiers::kConst_Flag;
break;
case Token::IN:
this->nextToken();
flags |= Modifiers::kIn_Flag;
break;
case Token::OUT:
this->nextToken();
flags |= Modifiers::kOut_Flag;
break;
case Token::INOUT:
this->nextToken();
flags |= Modifiers::kIn_Flag;
flags |= Modifiers::kOut_Flag;
break;
case Token::LOWP:
this->nextToken();
flags |= Modifiers::kLowp_Flag;
break;
case Token::MEDIUMP:
this->nextToken();
flags |= Modifiers::kMediump_Flag;
break;
case Token::HIGHP:
this->nextToken();
flags |= Modifiers::kHighp_Flag;
break;
case Token::FLAT:
this->nextToken();
flags |= Modifiers::kFlat_Flag;
break;
case Token::NOPERSPECTIVE:
this->nextToken();
flags |= Modifiers::kNoPerspective_Flag;
break;
case Token::READONLY:
this->nextToken();
flags |= Modifiers::kReadOnly_Flag;
break;
case Token::WRITEONLY:
this->nextToken();
flags |= Modifiers::kWriteOnly_Flag;
break;
case Token::COHERENT:
this->nextToken();
flags |= Modifiers::kCoherent_Flag;
break;
case Token::VOLATILE:
this->nextToken();
flags |= Modifiers::kVolatile_Flag;
break;
case Token::RESTRICT:
this->nextToken();
flags |= Modifiers::kRestrict_Flag;
break;
case Token::BUFFER:
this->nextToken();
flags |= Modifiers::kBuffer_Flag;
break;
case Token::HASSIDEEFFECTS:
this->nextToken();
flags |= Modifiers::kHasSideEffects_Flag;
break;
default:
return Modifiers(layout, flags);
}
}
}
Modifiers Parser::modifiersWithDefaults(int defaultFlags) {
Modifiers result = this->modifiers();
if (!result.fFlags) {
return Modifiers(result.fLayout, defaultFlags);
}
return result;
}
/* ifStatement | forStatement | doStatement | whileStatement | block | expression */
std::unique_ptr<ASTStatement> Parser::statement() {
Token start = this->peek();
switch (start.fKind) {
case Token::IF: // fall through
case Token::STATIC_IF:
return this->ifStatement();
case Token::FOR:
return this->forStatement();
case Token::DO:
return this->doStatement();
case Token::WHILE:
return this->whileStatement();
case Token::SWITCH: // fall through
case Token::STATIC_SWITCH:
return this->switchStatement();
case Token::RETURN:
return this->returnStatement();
case Token::BREAK:
return this->breakStatement();
case Token::CONTINUE:
return this->continueStatement();
case Token::DISCARD:
return this->discardStatement();
case Token::LBRACE:
return this->block();
case Token::SEMICOLON:
this->nextToken();
return std::unique_ptr<ASTStatement>(new ASTBlock(start.fPosition,
std::vector<std::unique_ptr<ASTStatement>>()));
case Token::CONST: // fall through
case Token::HIGHP: // fall through
case Token::MEDIUMP: // fall through
case Token::LOWP: {
auto decl = this->varDeclarations();
if (!decl) {
return nullptr;
}
return std::unique_ptr<ASTStatement>(new ASTVarDeclarationStatement(std::move(decl)));
}
case Token::IDENTIFIER:
if (this->isType(start.fText)) {
auto decl = this->varDeclarations();
if (!decl) {
return nullptr;
}
return std::unique_ptr<ASTStatement>(new ASTVarDeclarationStatement(
std::move(decl)));
}
// fall through
default:
return this->expressionStatement();
}
}
/* IDENTIFIER(type) (LBRACKET intLiteral? RBRACKET)* */
std::unique_ptr<ASTType> Parser::type() {
Token type;
if (!this->expect(Token::IDENTIFIER, "a type", &type)) {
return nullptr;
}
if (!this->isType(type.fText)) {
this->error(type.fPosition, ("no type named '" + type.fText + "'").c_str());
return nullptr;
}
std::vector<int> sizes;
while (this->checkNext(Token::LBRACKET)) {
if (this->peek().fKind != Token::RBRACKET) {
int64_t i;
if (this->intLiteral(&i)) {
sizes.push_back(i);
} else {
return nullptr;
}
} else {
sizes.push_back(-1);
}
this->expect(Token::RBRACKET, "']'");
}
return std::unique_ptr<ASTType>(new ASTType(type.fPosition, std::move(type.fText),
ASTType::kIdentifier_Kind, sizes));
}
/* IDENTIFIER LBRACE varDeclaration* RBRACE (IDENTIFIER (LBRACKET expression? RBRACKET)*)? */
std::unique_ptr<ASTDeclaration> Parser::interfaceBlock(Modifiers mods) {
Token name;
if (!this->expect(Token::IDENTIFIER, "an identifier", &name)) {
return nullptr;
}
if (peek().fKind != Token::LBRACE) {
// we only get into interfaceBlock if we found a top-level identifier which was not a type.
// 99% of the time, the user was not actually intending to create an interface block, so
// it's better to report it as an unknown type
this->error(name.fPosition, "no type named '" + name.fText + "'");
return nullptr;
}
this->nextToken();
std::vector<std::unique_ptr<ASTVarDeclarations>> decls;
while (this->peek().fKind != Token::RBRACE) {
std::unique_ptr<ASTVarDeclarations> decl = this->varDeclarations();
if (!decl) {
return nullptr;
}
decls.push_back(std::move(decl));
}
this->nextToken();
std::vector<std::unique_ptr<ASTExpression>> sizes;
Token instanceName;
if (this->checkNext(Token::IDENTIFIER, &instanceName)) {
while (this->checkNext(Token::LBRACKET)) {
if (this->peek().fKind != Token::RBRACKET) {
std::unique_ptr<ASTExpression> size = this->expression();
if (!size) {
return nullptr;
}
sizes.push_back(std::move(size));
} else {
sizes.push_back(nullptr);
}
this->expect(Token::RBRACKET, "']'");
}
}
this->expect(Token::SEMICOLON, "';'");
return std::unique_ptr<ASTDeclaration>(new ASTInterfaceBlock(name.fPosition, mods,
std::move(name.fText),
std::move(decls),
std::move(instanceName.fText),
std::move(sizes)));
}
/* IF LPAREN expression RPAREN statement (ELSE statement)? */
std::unique_ptr<ASTIfStatement> Parser::ifStatement() {
Token start;
bool isStatic = this->checkNext(Token::STATIC_IF, &start);
if (!isStatic && !this->expect(Token::IF, "'if'", &start)) {
return nullptr;
}
if (!this->expect(Token::LPAREN, "'('")) {
return nullptr;
}
std::unique_ptr<ASTExpression> test(this->expression());
if (!test) {
return nullptr;
}
if (!this->expect(Token::RPAREN, "')'")) {
return nullptr;
}
std::unique_ptr<ASTStatement> ifTrue(this->statement());
if (!ifTrue) {
return nullptr;
}
std::unique_ptr<ASTStatement> ifFalse;
if (this->checkNext(Token::ELSE)) {
ifFalse = this->statement();
if (!ifFalse) {
return nullptr;
}
}
return std::unique_ptr<ASTIfStatement>(new ASTIfStatement(start.fPosition,
isStatic,
std::move(test),
std::move(ifTrue),
std::move(ifFalse)));
}
/* DO statement WHILE LPAREN expression RPAREN SEMICOLON */
std::unique_ptr<ASTDoStatement> Parser::doStatement() {
Token start;
if (!this->expect(Token::DO, "'do'", &start)) {
return nullptr;
}
std::unique_ptr<ASTStatement> statement(this->statement());
if (!statement) {
return nullptr;
}
if (!this->expect(Token::WHILE, "'while'")) {
return nullptr;
}
if (!this->expect(Token::LPAREN, "'('")) {
return nullptr;
}
std::unique_ptr<ASTExpression> test(this->expression());
if (!test) {
return nullptr;
}
if (!this->expect(Token::RPAREN, "')'")) {
return nullptr;
}
if (!this->expect(Token::SEMICOLON, "';'")) {
return nullptr;
}
return std::unique_ptr<ASTDoStatement>(new ASTDoStatement(start.fPosition,
std::move(statement),
std::move(test)));
}
/* WHILE LPAREN expression RPAREN STATEMENT */
std::unique_ptr<ASTWhileStatement> Parser::whileStatement() {
Token start;
if (!this->expect(Token::WHILE, "'while'", &start)) {
return nullptr;
}
if (!this->expect(Token::LPAREN, "'('")) {
return nullptr;
}
std::unique_ptr<ASTExpression> test(this->expression());
if (!test) {
return nullptr;
}
if (!this->expect(Token::RPAREN, "')'")) {
return nullptr;
}
std::unique_ptr<ASTStatement> statement(this->statement());
if (!statement) {
return nullptr;
}
return std::unique_ptr<ASTWhileStatement>(new ASTWhileStatement(start.fPosition,
std::move(test),
std::move(statement)));
}
/* CASE expression COLON statement* */
std::unique_ptr<ASTSwitchCase> Parser::switchCase() {
Token start;
if (!this->expect(Token::CASE, "'case'", &start)) {
return nullptr;
}
std::unique_ptr<ASTExpression> value = this->expression();
if (!value) {
return nullptr;
}
if (!this->expect(Token::COLON, "':'")) {
return nullptr;
}
std::vector<std::unique_ptr<ASTStatement>> statements;
while (this->peek().fKind != Token::RBRACE && this->peek().fKind != Token::CASE &&
this->peek().fKind != Token::DEFAULT) {
std::unique_ptr<ASTStatement> s = this->statement();
if (!s) {
return nullptr;
}
statements.push_back(std::move(s));
}
return std::unique_ptr<ASTSwitchCase>(new ASTSwitchCase(start.fPosition, std::move(value),
std::move(statements)));
}
/* SWITCH LPAREN expression RPAREN LBRACE switchCase* (DEFAULT COLON statement*)? RBRACE */
std::unique_ptr<ASTStatement> Parser::switchStatement() {
Token start;
bool isStatic = this->checkNext(Token::STATIC_SWITCH, &start);
if (!isStatic && !this->expect(Token::SWITCH, "'switch'", &start)) {
return nullptr;
}
if (!this->expect(Token::LPAREN, "'('")) {
return nullptr;
}
std::unique_ptr<ASTExpression> value(this->expression());
if (!value) {
return nullptr;
}
if (!this->expect(Token::RPAREN, "')'")) {
return nullptr;
}
if (!this->expect(Token::LBRACE, "'{'")) {
return nullptr;
}
std::vector<std::unique_ptr<ASTSwitchCase>> cases;
while (this->peek().fKind == Token::CASE) {
std::unique_ptr<ASTSwitchCase> c = this->switchCase();
if (!c) {
return nullptr;
}
cases.push_back(std::move(c));
}
// Requiring default: to be last (in defiance of C and GLSL) was a deliberate decision. Other
// parts of the compiler may rely upon this assumption.
if (this->peek().fKind == Token::DEFAULT) {
Token defaultStart;
ASSERT_RESULT(this->expect(Token::DEFAULT, "'default'", &defaultStart));
if (!this->expect(Token::COLON, "':'")) {
return nullptr;
}
std::vector<std::unique_ptr<ASTStatement>> statements;
while (this->peek().fKind != Token::RBRACE) {
std::unique_ptr<ASTStatement> s = this->statement();
if (!s) {
return nullptr;
}
statements.push_back(std::move(s));
}
cases.emplace_back(new ASTSwitchCase(defaultStart.fPosition, nullptr,
std::move(statements)));
}
if (!this->expect(Token::RBRACE, "'}'")) {
return nullptr;
}
return std::unique_ptr<ASTStatement>(new ASTSwitchStatement(start.fPosition,
isStatic,
std::move(value),
std::move(cases)));
}
/* FOR LPAREN (declaration | expression)? SEMICOLON expression? SEMICOLON expression? RPAREN
STATEMENT */
std::unique_ptr<ASTForStatement> Parser::forStatement() {
Token start;
if (!this->expect(Token::FOR, "'for'", &start)) {
return nullptr;
}
if (!this->expect(Token::LPAREN, "'('")) {
return nullptr;
}
std::unique_ptr<ASTStatement> initializer;
Token nextToken = this->peek();
switch (nextToken.fKind) {
case Token::SEMICOLON:
this->nextToken();
break;
case Token::CONST: {
std::unique_ptr<ASTVarDeclarations> vd = this->varDeclarations();
if (!vd) {
return nullptr;
}
initializer = std::unique_ptr<ASTStatement>(new ASTVarDeclarationStatement(
std::move(vd)));
break;
}
case Token::IDENTIFIER: {
if (this->isType(nextToken.fText)) {
std::unique_ptr<ASTVarDeclarations> vd = this->varDeclarations();
if (!vd) {
return nullptr;
}
initializer = std::unique_ptr<ASTStatement>(new ASTVarDeclarationStatement(
std::move(vd)));
break;
}
} // fall through
default:
initializer = this->expressionStatement();
}
std::unique_ptr<ASTExpression> test;
if (this->peek().fKind != Token::SEMICOLON) {
test = this->expression();
if (!test) {
return nullptr;
}
}
if (!this->expect(Token::SEMICOLON, "';'")) {
return nullptr;
}
std::unique_ptr<ASTExpression> next;
if (this->peek().fKind != Token::RPAREN) {
next = this->expression();
if (!next) {
return nullptr;
}
}
if (!this->expect(Token::RPAREN, "')'")) {
return nullptr;
}
std::unique_ptr<ASTStatement> statement(this->statement());
if (!statement) {
return nullptr;
}
return std::unique_ptr<ASTForStatement>(new ASTForStatement(start.fPosition,
std::move(initializer),
std::move(test), std::move(next),
std::move(statement)));
}
/* RETURN expression? SEMICOLON */
std::unique_ptr<ASTReturnStatement> Parser::returnStatement() {
Token start;
if (!this->expect(Token::RETURN, "'return'", &start)) {
return nullptr;
}
std::unique_ptr<ASTExpression> expression;
if (this->peek().fKind != Token::SEMICOLON) {
expression = this->expression();
if (!expression) {
return nullptr;
}
}
if (!this->expect(Token::SEMICOLON, "';'")) {
return nullptr;
}
return std::unique_ptr<ASTReturnStatement>(new ASTReturnStatement(start.fPosition,
std::move(expression)));
}
/* BREAK SEMICOLON */
std::unique_ptr<ASTBreakStatement> Parser::breakStatement() {
Token start;
if (!this->expect(Token::BREAK, "'break'", &start)) {
return nullptr;
}
if (!this->expect(Token::SEMICOLON, "';'")) {
return nullptr;
}
return std::unique_ptr<ASTBreakStatement>(new ASTBreakStatement(start.fPosition));
}
/* CONTINUE SEMICOLON */
std::unique_ptr<ASTContinueStatement> Parser::continueStatement() {
Token start;
if (!this->expect(Token::CONTINUE, "'continue'", &start)) {
return nullptr;
}
if (!this->expect(Token::SEMICOLON, "';'")) {
return nullptr;
}
return std::unique_ptr<ASTContinueStatement>(new ASTContinueStatement(start.fPosition));
}
/* DISCARD SEMICOLON */
std::unique_ptr<ASTDiscardStatement> Parser::discardStatement() {
Token start;
if (!this->expect(Token::DISCARD, "'continue'", &start)) {
return nullptr;
}
if (!this->expect(Token::SEMICOLON, "';'")) {
return nullptr;
}
return std::unique_ptr<ASTDiscardStatement>(new ASTDiscardStatement(start.fPosition));
}
/* LBRACE statement* RBRACE */
std::unique_ptr<ASTBlock> Parser::block() {
AutoDepth depth(this);
if (!depth.checkValid()) {
return nullptr;
}
Token start;
if (!this->expect(Token::LBRACE, "'{'", &start)) {
return nullptr;
}
std::vector<std::unique_ptr<ASTStatement>> statements;
for (;;) {
switch (this->peek().fKind) {
case Token::RBRACE:
this->nextToken();
return std::unique_ptr<ASTBlock>(new ASTBlock(start.fPosition,
std::move(statements)));
case Token::END_OF_FILE:
this->error(this->peek().fPosition, "expected '}', but found end of file");
return nullptr;
default: {
std::unique_ptr<ASTStatement> statement = this->statement();
if (!statement) {
return nullptr;
}
statements.push_back(std::move(statement));
}
}
}
}
/* expression SEMICOLON */
std::unique_ptr<ASTExpressionStatement> Parser::expressionStatement() {
std::unique_ptr<ASTExpression> expr = this->expression();
if (expr) {
if (this->expect(Token::SEMICOLON, "';'")) {
ASTExpressionStatement* result = new ASTExpressionStatement(std::move(expr));
return std::unique_ptr<ASTExpressionStatement>(result);
}
}
return nullptr;
}
/* assignmentExpression */
std::unique_ptr<ASTExpression> Parser::expression() {
AutoDepth depth(this);
if (!depth.checkValid()) {
return nullptr;
}
return this->commaExpression();
}
/* assignmentExpression (COMMA assignmentExpression)* */
std::unique_ptr<ASTExpression> Parser::commaExpression() {
std::unique_ptr<ASTExpression> result = this->assignmentExpression();
if (!result) {
return nullptr;
}
Token t;
while (this->checkNext(Token::COMMA, &t)) {
std::unique_ptr<ASTExpression> right = this->commaExpression();
if (!right) {
return nullptr;
}
result.reset(new ASTBinaryExpression(std::move(result), std::move(t), std::move(right)));
}
return result;
}
/* ternaryExpression ((EQEQ | STAREQ | SLASHEQ | PERCENTEQ | PLUSEQ | MINUSEQ | SHLEQ | SHREQ |
BITWISEANDEQ | BITWISEXOREQ | BITWISEOREQ | LOGICALANDEQ | LOGICALXOREQ | LOGICALOREQ)
assignmentExpression)*
*/
std::unique_ptr<ASTExpression> Parser::assignmentExpression() {
std::unique_ptr<ASTExpression> result = this->ternaryExpression();
if (!result) {
return nullptr;
}
for (;;) {
switch (this->peek().fKind) {
case Token::EQ: // fall through
case Token::STAREQ: // fall through
case Token::SLASHEQ: // fall through
case Token::PERCENTEQ: // fall through
case Token::PLUSEQ: // fall through
case Token::MINUSEQ: // fall through
case Token::SHLEQ: // fall through
case Token::SHREQ: // fall through
case Token::BITWISEANDEQ: // fall through
case Token::BITWISEXOREQ: // fall through
case Token::BITWISEOREQ: // fall through
case Token::LOGICALANDEQ: // fall through
case Token::LOGICALXOREQ: // fall through
case Token::LOGICALOREQ: {
Token t = this->nextToken();
std::unique_ptr<ASTExpression> right = this->assignmentExpression();
if (!right) {
return nullptr;
}
result = std::unique_ptr<ASTExpression>(new ASTBinaryExpression(std::move(result),
std::move(t),
std::move(right)));
}
default:
return result;
}
}
}
/* logicalOrExpression ('?' expression ':' assignmentExpression)? */
std::unique_ptr<ASTExpression> Parser::ternaryExpression() {
std::unique_ptr<ASTExpression> result = this->logicalOrExpression();
if (!result) {
return nullptr;
}
if (this->checkNext(Token::QUESTION)) {
std::unique_ptr<ASTExpression> trueExpr = this->expression();
if (!trueExpr) {
return nullptr;
}
if (this->expect(Token::COLON, "':'")) {
std::unique_ptr<ASTExpression> falseExpr = this->assignmentExpression();
return std::unique_ptr<ASTExpression>(new ASTTernaryExpression(std::move(result),
std::move(trueExpr),
std::move(falseExpr)));
}
return nullptr;
}
return result;
}
/* logicalXorExpression (LOGICALOR logicalXorExpression)* */
std::unique_ptr<ASTExpression> Parser::logicalOrExpression() {
std::unique_ptr<ASTExpression> result = this->logicalXorExpression();
if (!result) {
return nullptr;
}
Token t;
while (this->checkNext(Token::LOGICALOR, &t)) {
std::unique_ptr<ASTExpression> right = this->logicalXorExpression();
if (!right) {
return nullptr;
}
result.reset(new ASTBinaryExpression(std::move(result), std::move(t), std::move(right)));
}
return result;
}
/* logicalAndExpression (LOGICALXOR logicalAndExpression)* */
std::unique_ptr<ASTExpression> Parser::logicalXorExpression() {
std::unique_ptr<ASTExpression> result = this->logicalAndExpression();
if (!result) {
return nullptr;
}
Token t;
while (this->checkNext(Token::LOGICALXOR, &t)) {
std::unique_ptr<ASTExpression> right = this->logicalAndExpression();
if (!right) {
return nullptr;
}
result.reset(new ASTBinaryExpression(std::move(result), std::move(t), std::move(right)));
}
return result;
}
/* bitwiseOrExpression (LOGICALAND bitwiseOrExpression)* */
std::unique_ptr<ASTExpression> Parser::logicalAndExpression() {
std::unique_ptr<ASTExpression> result = this->bitwiseOrExpression();
if (!result) {
return nullptr;
}
Token t;
while (this->checkNext(Token::LOGICALAND, &t)) {
std::unique_ptr<ASTExpression> right = this->bitwiseOrExpression();
if (!right) {
return nullptr;
}
result.reset(new ASTBinaryExpression(std::move(result), std::move(t), std::move(right)));
}
return result;
}
/* bitwiseXorExpression (BITWISEOR bitwiseXorExpression)* */
std::unique_ptr<ASTExpression> Parser::bitwiseOrExpression() {
std::unique_ptr<ASTExpression> result = this->bitwiseXorExpression();
if (!result) {
return nullptr;
}
Token t;
while (this->checkNext(Token::BITWISEOR, &t)) {
std::unique_ptr<ASTExpression> right = this->bitwiseXorExpression();
if (!right) {
return nullptr;
}
result.reset(new ASTBinaryExpression(std::move(result), std::move(t), std::move(right)));
}
return result;
}
/* bitwiseAndExpression (BITWISEXOR bitwiseAndExpression)* */
std::unique_ptr<ASTExpression> Parser::bitwiseXorExpression() {
std::unique_ptr<ASTExpression> result = this->bitwiseAndExpression();
if (!result) {
return nullptr;
}
Token t;
while (this->checkNext(Token::BITWISEXOR, &t)) {
std::unique_ptr<ASTExpression> right = this->bitwiseAndExpression();
if (!right) {
return nullptr;
}
result.reset(new ASTBinaryExpression(std::move(result), std::move(t), std::move(right)));
}
return result;
}
/* equalityExpression (BITWISEAND equalityExpression)* */
std::unique_ptr<ASTExpression> Parser::bitwiseAndExpression() {
std::unique_ptr<ASTExpression> result = this->equalityExpression();
if (!result) {
return nullptr;
}
Token t;
while (this->checkNext(Token::BITWISEAND, &t)) {
std::unique_ptr<ASTExpression> right = this->equalityExpression();
if (!right) {
return nullptr;
}
result.reset(new ASTBinaryExpression(std::move(result), std::move(t), std::move(right)));
}
return result;
}
/* relationalExpression ((EQEQ | NEQ) relationalExpression)* */
std::unique_ptr<ASTExpression> Parser::equalityExpression() {
std::unique_ptr<ASTExpression> result = this->relationalExpression();
if (!result) {
return nullptr;
}
for (;;) {
switch (this->peek().fKind) {
case Token::EQEQ: // fall through
case Token::NEQ: {
Token t = this->nextToken();
std::unique_ptr<ASTExpression> right = this->relationalExpression();
if (!right) {
return nullptr;
}
result.reset(new ASTBinaryExpression(std::move(result), std::move(t), std::move(right)));
break;
}
default:
return result;
}
}
}
/* shiftExpression ((LT | GT | LTEQ | GTEQ) shiftExpression)* */
std::unique_ptr<ASTExpression> Parser::relationalExpression() {
std::unique_ptr<ASTExpression> result = this->shiftExpression();
if (!result) {
return nullptr;
}
for (;;) {
switch (this->peek().fKind) {
case Token::LT: // fall through
case Token::GT: // fall through
case Token::LTEQ: // fall through
case Token::GTEQ: {
Token t = this->nextToken();
std::unique_ptr<ASTExpression> right = this->shiftExpression();
if (!right) {
return nullptr;
}
result.reset(new ASTBinaryExpression(std::move(result), std::move(t),
std::move(right)));
break;
}
default:
return result;
}
}
}
/* additiveExpression ((SHL | SHR) additiveExpression)* */
std::unique_ptr<ASTExpression> Parser::shiftExpression() {
std::unique_ptr<ASTExpression> result = this->additiveExpression();
if (!result) {
return nullptr;
}
for (;;) {
switch (this->peek().fKind) {
case Token::SHL: // fall through
case Token::SHR: {
Token t = this->nextToken();
std::unique_ptr<ASTExpression> right = this->additiveExpression();
if (!right) {
return nullptr;
}
result.reset(new ASTBinaryExpression(std::move(result), std::move(t),
std::move(right)));
break;
}
default:
return result;
}
}
}
/* multiplicativeExpression ((PLUS | MINUS) multiplicativeExpression)* */
std::unique_ptr<ASTExpression> Parser::additiveExpression() {
std::unique_ptr<ASTExpression> result = this->multiplicativeExpression();
if (!result) {
return nullptr;
}
for (;;) {
switch (this->peek().fKind) {
case Token::PLUS: // fall through
case Token::MINUS: {
Token t = this->nextToken();
std::unique_ptr<ASTExpression> right = this->multiplicativeExpression();
if (!right) {
return nullptr;
}
result.reset(new ASTBinaryExpression(std::move(result), std::move(t),
std::move(right)));
break;
}
default:
return result;
}
}
}
/* unaryExpression ((STAR | SLASH | PERCENT) unaryExpression)* */
std::unique_ptr<ASTExpression> Parser::multiplicativeExpression() {
std::unique_ptr<ASTExpression> result = this->unaryExpression();
if (!result) {
return nullptr;
}
for (;;) {
switch (this->peek().fKind) {
case Token::STAR: // fall through
case Token::SLASH: // fall through
case Token::PERCENT: {
Token t = this->nextToken();
std::unique_ptr<ASTExpression> right = this->unaryExpression();
if (!right) {
return nullptr;
}
result.reset(new ASTBinaryExpression(std::move(result), std::move(t),
std::move(right)));
break;
}
default:
return result;
}
}
}
/* postfixExpression | (PLUS | MINUS | NOT | PLUSPLUS | MINUSMINUS) unaryExpression */
std::unique_ptr<ASTExpression> Parser::unaryExpression() {
switch (this->peek().fKind) {
case Token::PLUS: // fall through
case Token::MINUS: // fall through
case Token::LOGICALNOT: // fall through
case Token::BITWISENOT: // fall through
case Token::PLUSPLUS: // fall through
case Token::MINUSMINUS: {
Token t = this->nextToken();
std::unique_ptr<ASTExpression> expr = this->unaryExpression();
if (!expr) {
return nullptr;
}
return std::unique_ptr<ASTExpression>(new ASTPrefixExpression(std::move(t),
std::move(expr)));
}
default:
return this->postfixExpression();
}
}
/* term suffix* */
std::unique_ptr<ASTExpression> Parser::postfixExpression() {
std::unique_ptr<ASTExpression> result = this->term();
if (!result) {
return nullptr;
}
for (;;) {
switch (this->peek().fKind) {
case Token::LBRACKET: // fall through
case Token::DOT: // fall through
case Token::LPAREN: // fall through
case Token::PLUSPLUS: // fall through
case Token::MINUSMINUS: {
std::unique_ptr<ASTSuffix> s = this->suffix();
if (!s) {
return nullptr;
}
result.reset(new ASTSuffixExpression(std::move(result), std::move(s)));
break;
}
default:
return result;
}
}
}
/* LBRACKET expression? RBRACKET | DOT IDENTIFIER | LPAREN parameters RPAREN |
PLUSPLUS | MINUSMINUS */
std::unique_ptr<ASTSuffix> Parser::suffix() {
Token next = this->nextToken();
switch (next.fKind) {
case Token::LBRACKET: {
if (this->checkNext(Token::RBRACKET)) {
return std::unique_ptr<ASTSuffix>(new ASTIndexSuffix(next.fPosition));
}
std::unique_ptr<ASTExpression> e = this->expression();
if (!e) {
return nullptr;
}
this->expect(Token::RBRACKET, "']' to complete array access expression");
return std::unique_ptr<ASTSuffix>(new ASTIndexSuffix(std::move(e)));
}
case Token::DOT: {
Position pos = this->peek().fPosition;
String text;
if (this->identifier(&text)) {
return std::unique_ptr<ASTSuffix>(new ASTFieldSuffix(pos, std::move(text)));
}
return nullptr;
}
case Token::LPAREN: {
std::vector<std::unique_ptr<ASTExpression>> parameters;
if (this->peek().fKind != Token::RPAREN) {
for (;;) {
std::unique_ptr<ASTExpression> expr = this->assignmentExpression();
if (!expr) {
return nullptr;
}
parameters.push_back(std::move(expr));
if (!this->checkNext(Token::COMMA)) {
break;
}
}
}
this->expect(Token::RPAREN, "')' to complete function parameters");
return std::unique_ptr<ASTSuffix>(new ASTCallSuffix(next.fPosition,
std::move(parameters)));
}
case Token::PLUSPLUS:
return std::unique_ptr<ASTSuffix>(new ASTSuffix(next.fPosition,
ASTSuffix::kPostIncrement_Kind));
case Token::MINUSMINUS:
return std::unique_ptr<ASTSuffix>(new ASTSuffix(next.fPosition,
ASTSuffix::kPostDecrement_Kind));
default: {
this->error(next.fPosition, "expected expression suffix, but found '" + next.fText +
"'\n");
return nullptr;
}
}
}
/* IDENTIFIER | intLiteral | floatLiteral | boolLiteral | '(' expression ')' */
std::unique_ptr<ASTExpression> Parser::term() {
std::unique_ptr<ASTExpression> result;
Token t = this->peek();
switch (t.fKind) {
case Token::IDENTIFIER: {
String text;
if (this->identifier(&text)) {
result.reset(new ASTIdentifier(t.fPosition, std::move(text)));
}
break;
}
case Token::INT_LITERAL: {
int64_t i;
if (this->intLiteral(&i)) {
result.reset(new ASTIntLiteral(t.fPosition, i));
}
break;
}
case Token::FLOAT_LITERAL: {
double f;
if (this->floatLiteral(&f)) {
result.reset(new ASTFloatLiteral(t.fPosition, f));
}
break;
}
case Token::TRUE_LITERAL: // fall through
case Token::FALSE_LITERAL: {
bool b;
if (this->boolLiteral(&b)) {
result.reset(new ASTBoolLiteral(t.fPosition, b));
}
break;
}
case Token::LPAREN: {
this->nextToken();
result = this->expression();
if (result) {
this->expect(Token::RPAREN, "')' to complete expression");
}
break;
}
default:
this->nextToken();
this->error(t.fPosition, "expected expression, but found '" + t.fText + "'\n");
result = nullptr;
}
return result;
}
/* INT_LITERAL */
bool Parser::intLiteral(int64_t* dest) {
Token t;
if (this->expect(Token::INT_LITERAL, "integer literal", &t)) {
*dest = SkSL::stol(t.fText);
return true;
}
return false;
}
/* FLOAT_LITERAL */
bool Parser::floatLiteral(double* dest) {
Token t;
if (this->expect(Token::FLOAT_LITERAL, "float literal", &t)) {
*dest = SkSL::stod(t.fText);
return true;
}
return false;
}
/* TRUE_LITERAL | FALSE_LITERAL */
bool Parser::boolLiteral(bool* dest) {
Token t = this->nextToken();
switch (t.fKind) {
case Token::TRUE_LITERAL:
*dest = true;
return true;
case Token::FALSE_LITERAL:
*dest = false;
return true;
default:
this->error(t.fPosition, "expected 'true' or 'false', but found '" + t.fText + "'\n");
return false;
}
}
/* IDENTIFIER */
bool Parser::identifier(String* dest) {
Token t;
if (this->expect(Token::IDENTIFIER, "identifier", &t)) {
*dest = std::move(t.fText);
return true;
}
return false;
}
} // namespace
|
// -----------------------------------------------------------------------------------------------------
// Copyright (c) 2006-2020, Knut Reinert & Freie Universität Berlin
// Copyright (c) 2016-2020, Knut Reinert & MPI für molekulare Genetik
// This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License
// shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md
// -----------------------------------------------------------------------------------------------------
/*!\file
* \brief Provides various utility functions required only for output.
* \author Hannes Hauswedell <hannes.hauswedell AT fu-berlin.de>
*/
#pragma once
#include <seqan3/std/filesystem>
#include <iostream>
#include <string>
#include <tuple>
#ifdef SEQAN3_HAS_BZIP2
#include <seqan3/contrib/stream/bz2_ostream.hpp>
#endif
#ifdef SEQAN3_HAS_ZLIB
#include <seqan3/contrib/stream/bgzf_ostream.hpp>
#include <seqan3/contrib/stream/gz_ostream.hpp>
#endif
#include <seqan3/io/exception.hpp>
#include <seqan3/utility/detail/exposition_only_concept.hpp>
namespace seqan3::detail
{
/*!\brief Depending on the given filename/extension, create a compression stream or just forward the primary stream.
* \param[in] primary_stream The primary (uncompressed) stream for writing.
* \param[in,out] filename The associated filename; compression extensions will be stripped.
* \returns A pointer to the secondary stream with a default deleter or a nop-deleter.
* \throws seqan3::file_open_error If a compression-extension is used, but is not supported/available.
*/
template <builtin_character char_t>
inline auto make_secondary_ostream(std::basic_ostream<char_t> & primary_stream, std::filesystem::path & filename)
-> std::unique_ptr<std::basic_ostream<char_t>, std::function<void(std::basic_ostream<char_t>*)>>
{
// don't assume ownership
constexpr auto stream_deleter_noop = [] (std::basic_ostream<char_t> *) {};
// assume ownership
[[maybe_unused]] constexpr auto stream_deleter_default = [] (std::basic_ostream<char_t> * ptr) { delete ptr; };
std::string extension = filename.extension().string();
if (extension == ".gz")
{
#ifdef SEQAN3_HAS_ZLIB
filename.replace_extension("");
return {new contrib::basic_gz_ostream<char_t>{primary_stream}, stream_deleter_default};
#else
throw file_open_error{"Trying to write a gzipped file, but no ZLIB available."};
#endif
}
else if ((extension == ".bgzf") || (extension == ".bam"))
{
#ifdef SEQAN3_HAS_ZLIB
if (extension != ".bam") // remove extension except for bam
filename.replace_extension("");
return {new contrib::basic_bgzf_ostream<char_t>{primary_stream}, stream_deleter_default};
#else
throw file_open_error{"Trying to write a bgzf'ed file, but no ZLIB available."};
#endif
}
else if (extension == ".bz2")
{
#ifdef SEQAN3_HAS_BZIP2
filename.replace_extension("");
return {new contrib::basic_bz2_ostream<char_t>{primary_stream}, stream_deleter_default};
#else
throw file_open_error{"Trying to write a bzipped file, but no libbz2 available."};
#endif
}
else if (extension == ".zst")
{
throw file_open_error{"Trying to write a zst'ed file, but SeqAn does not yet support this."};
}
return {&primary_stream, stream_deleter_noop};
}
} // namespace seqan3::detail
|
#include "InlineDiff.h"
void InlineDiff::printAdd(const String& line, int leftLine, int rightLine)
{
if(line.empty()) {
printWrappedLine("<div class=\"mw-diff-inline-added mw-diff-empty-line\"><ins>", line, "</ins></div>\n");
} else {
printWrappedLine("<div class=\"mw-diff-inline-added\"><ins>", line, "</ins></div>\n");
}
}
void InlineDiff::printDelete(const String& line, int leftLine, int rightLine)
{
if(line.empty()) {
printWrappedLine("<div class=\"mw-diff-inline-deleted mw-diff-empty-line\"><del>", line, "</del></div>\n");
} else {
printWrappedLine("<div class=\"mw-diff-inline-deleted\"><del>", line, "</del></div>\n");
}
}
void InlineDiff::printWordDiff(const String& text1, const String& text2, int leftLine, int rightLine, bool printLeft, bool printRight, const String & srcAnchor, const String & dstAnchor, bool moveDirectionDownwards)
{
WordVector words1, words2;
TextUtil::explodeWords(text1, words1);
TextUtil::explodeWords(text2, words2);
WordDiff worddiff(words1, words2, MAX_WORD_LEVEL_DIFF_COMPLEXITY);
String word;
bool moved = printLeft != printRight,
isMoveSrc = moved && printLeft,
isMoveDest = moved && printRight;
if (moved) {
result += String("<div class=\"mw-diff-inline-moved mw-diff-inline-moved-") +
(printLeft ? "source" : "destination") + " mw-diff-inline-moved-" +
(moveDirectionDownwards ? "downwards" : "upwards") + "\">";
result += "<a name=\"" + srcAnchor + "\"></a>";
if (!moveDirectionDownwards) {
result += "<a class=\"mw-diff-movedpara-" +
String(printLeft ? "left" : "right") + "\" data-title-tag=\"" +
(printRight ? "new" : "old") + "\" href=\"#" + dstAnchor + "\">" + "▲" + "</a>";
}
} else {
result += "<div class=\"mw-diff-inline-changed\">";
}
for (unsigned i = 0; i < worddiff.size(); ++i) {
DiffOp<Word> & op = worddiff[i];
int n, j;
if (op.op == DiffOp<Word>::copy) {
n = op.from.size();
for (j=0; j<n; j++) {
op.from[j]->get_whole(word);
printHtmlEncodedText(word);
}
} else if (op.op == DiffOp<Word>::del) {
n = op.from.size();
if (!isMoveSrc)
result += "<del>";
for (j=0; j<n; j++) {
op.from[j]->get_whole(word);
printHtmlEncodedText(word);
}
if (!isMoveSrc)
result += "</del>";
} else if (op.op == DiffOp<Word>::add) {
if (isMoveSrc)
continue;
n = op.to.size();
result += "<ins>";
for (j=0; j<n; j++) {
op.to[j]->get_whole(word);
printHtmlEncodedText(word);
}
result += "</ins>";
} else if (op.op == DiffOp<Word>::change) {
n = op.from.size();
if (!isMoveSrc)
result += "<del>";
for (j=0; j<n; j++) {
op.from[j]->get_whole(word);
printHtmlEncodedText(word);
}
if (isMoveSrc)
continue;
result += "</del>";
n = op.to.size();
result += "<ins>";
for (j=0; j<n; j++) {
op.to[j]->get_whole(word);
printHtmlEncodedText(word);
}
result += "</ins>";
}
}
if (moved && moveDirectionDownwards) {
result += "<a class=\"mw-diff-movedpara-" +
String(printLeft ? "left" : "right") + "\" data-title-tag=\"" +
(printRight ? "new" : "old") + "\" href=\"#" + dstAnchor + "\">" + "▼" + "</a>";
}
result += "</div>\n";
}
void InlineDiff::printBlockHeader(int leftLine, int rightLine)
{
char buf[256]; // should be plenty
snprintf(buf, sizeof(buf),
"<div class=\"mw-diff-inline-header\"><!-- LINES %u,%u --></div>\n",
leftLine, rightLine);
result += buf;
}
void InlineDiff::printContext(const String & input, int leftLine, int rightLine)
{
printWrappedLine("<div class=\"mw-diff-inline-context\">", input, "</div>\n");
}
void InlineDiff::printWrappedLine(const char* pre, const String& line, const char* post)
{
result += pre;
if (line.empty()) {
result += " ";
} else {
printHtmlEncodedText(line);
}
result += post;
}
|
//
// Created by Ivan Shynkarenka on 28.05.2019
//
#include "server/asio/service.h"
#include "server/ws/ws_server.h"
#include "system/cpu.h"
#include "threads/thread.h"
#include "time/timestamp.h"
#include <atomic>
#include <iostream>
#include <thread>
#include <vector>
#include <OptionParser.h>
using namespace CppCommon;
using namespace CppServer::Asio;
using namespace CppServer::WS;
class MulticastSession : public WSSession
{
public:
using WSSession::WSSession;
protected:
void onError(int error, const std::string& category, const std::string& message) override
{
std::cout << "WebSocket session caught an error with code " << error << " and category '" << category << "': " << message << std::endl;
}
};
class MulticastServer : public WSServer
{
public:
using WSServer::WSServer;
protected:
std::shared_ptr<TCPSession> CreateSession(std::shared_ptr<TCPServer> server) override
{
return std::make_shared<MulticastSession>(std::dynamic_pointer_cast<WSServer>(server));
}
protected:
void onError(int error, const std::string& category, const std::string& message) override
{
std::cout << "WebSocket server caught an error with code " << error << " and category '" << category << "': " << message << std::endl;
}
};
int main(int argc, char** argv)
{
auto parser = optparse::OptionParser().version("1.0.0.0");
parser.add_option("-p", "--port").dest("port").action("store").type("int").set_default(8080).help("Server port. Default: %default");
parser.add_option("-t", "--threads").dest("threads").action("store").type("int").set_default(CPU::PhysicalCores()).help("Count of working threads. Default: %default");
parser.add_option("-m", "--messages").dest("messages").action("store").type("int").set_default(1000000).help("Rate of messages per second to send. Default: %default");
parser.add_option("-s", "--size").dest("size").action("store").type("int").set_default(32).help("Single message size. Default: %default");
optparse::Values options = parser.parse_args(argc, argv);
// Print help
if (options.get("help"))
{
parser.print_help();
return 0;
}
// Server port
int port = options.get("port");
int threads = options.get("threads");
int messages_rate = options.get("messages");
int message_size = options.get("size");
std::cout << "Server port: " << port << std::endl;
std::cout << "Working threads: " << threads << std::endl;
std::cout << "Messages rate: " << messages_rate << std::endl;
std::cout << "Message size: " << message_size << std::endl;
std::cout << std::endl;
// Create a new Asio service
auto service = std::make_shared<Service>(threads);
// Start the Asio service
std::cout << "Asio service starting...";
service->Start();
std::cout << "Done!" << std::endl;
// Create a new multicast server
auto server = std::make_shared<MulticastServer>(service, port);
// server->SetupNoDelay(true);
server->SetupReuseAddress(true);
server->SetupReusePort(true);
// Start the server
std::cout << "Server starting...";
server->Start();
std::cout << "Done!" << std::endl;
// Start the multicasting thread
std::atomic<bool> multicasting(true);
auto multicaster = std::thread([&server, &multicasting, messages_rate, message_size]()
{
// Prepare message to multicast
std::vector<uint8_t> message_to_send(message_size);
// Multicasting loop
while (multicasting)
{
auto start = UtcTimestamp();
for (int i = 0; i < messages_rate; ++i)
server->MulticastBinary(message_to_send.data(), message_to_send.size());
auto end = UtcTimestamp();
// Sleep for remaining time or yield
auto milliseconds = (end - start).milliseconds();
if (milliseconds < 1000)
Thread::Sleep(milliseconds);
else
Thread::Yield();
}
});
std::cout << "Press Enter to stop the server or '!' to restart the server..." << std::endl;
// Perform text input
std::string line;
while (getline(std::cin, line))
{
if (line.empty())
break;
// Restart the server
if (line == "!")
{
std::cout << "Server restarting...";
server->Restart();
std::cout << "Done!" << std::endl;
continue;
}
}
// Stop the multicasting thread
multicasting = false;
multicaster.join();
// Stop the server
std::cout << "Server stopping...";
server->Stop();
std::cout << "Done!" << std::endl;
// Stop the Asio service
std::cout << "Asio service stopping...";
service->Stop();
std::cout << "Done!" << std::endl;
return 0;
}
|
// Copyright (c) 2011-2013 The Bitcoin developers
// Copyright (c) 2017 The PIVX developers
// Copyright (c) 2017-2018 The Artax developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "notificator.h"
#include <QApplication>
#include <QByteArray>
#include <QIcon>
#include <QImageWriter>
#include <QMessageBox>
#include <QMetaType>
#include <QStyle>
#include <QSystemTrayIcon>
#include <QTemporaryFile>
#include <QVariant>
#ifdef USE_DBUS
#include <QtDBus>
#include <stdint.h>
#endif
// Include ApplicationServices.h after QtDbus to avoid redefinition of check().
// This affects at least OSX 10.6. See /usr/include/AssertMacros.h for details.
// Note: This could also be worked around using:
// #define __ASSERT_MACROS_DEFINE_VERSIONS_WITHOUT_UNDERSCORES 0
#ifdef Q_OS_MAC
#include "macnotificationhandler.h"
#include <ApplicationServices/ApplicationServices.h>
#endif
#ifdef USE_DBUS
// https://wiki.ubuntu.com/NotificationDevelopmentGuidelines recommends at least 128
const int FREEDESKTOP_NOTIFICATION_ICON_SIZE = 128;
#endif
Notificator::Notificator(const QString& programName, QSystemTrayIcon* trayicon, QWidget* parent) : QObject(parent),
parent(parent),
programName(programName),
mode(None),
trayIcon(trayicon)
#ifdef USE_DBUS
,
interface(0)
#endif
{
if (trayicon && trayicon->supportsMessages()) {
mode = QSystemTray;
}
#ifdef USE_DBUS
interface = new QDBusInterface("org.freedesktop.Notifications",
"/org/freedesktop/Notifications", "org.freedesktop.Notifications");
if (interface->isValid()) {
mode = Freedesktop;
}
#endif
#ifdef Q_OS_MAC
// check if users OS has support for NSUserNotification
if (MacNotificationHandler::instance()->hasUserNotificationCenterSupport()) {
mode = UserNotificationCenter;
}
#endif
}
Notificator::~Notificator()
{
#ifdef USE_DBUS
delete interface;
#endif
}
#ifdef USE_DBUS
// Loosely based on http://www.qtcentre.org/archive/index.php/t-25879.html
class FreedesktopImage
{
public:
FreedesktopImage() {}
FreedesktopImage(const QImage& img);
static int metaType();
// Image to variant that can be marshalled over DBus
static QVariant toVariant(const QImage& img);
private:
int width, height, stride;
bool hasAlpha;
int channels;
int bitsPerSample;
QByteArray image;
friend QDBusArgument& operator<<(QDBusArgument& a, const FreedesktopImage& i);
friend const QDBusArgument& operator>>(const QDBusArgument& a, FreedesktopImage& i);
};
Q_DECLARE_METATYPE(FreedesktopImage);
// Image configuration settings
const int CHANNELS = 4;
const int BYTES_PER_PIXEL = 4;
const int BITS_PER_SAMPLE = 8;
FreedesktopImage::FreedesktopImage(const QImage& img) : width(img.width()),
height(img.height()),
stride(img.width() * BYTES_PER_PIXEL),
hasAlpha(true),
channels(CHANNELS),
bitsPerSample(BITS_PER_SAMPLE)
{
// Convert 00xAARRGGBB to RGBA bytewise (endian-independent) format
QImage tmp = img.convertToFormat(QImage::Format_ARGB32);
const uint32_t* data = reinterpret_cast<const uint32_t*>(tmp.bits());
unsigned int num_pixels = width * height;
image.resize(num_pixels * BYTES_PER_PIXEL);
for (unsigned int ptr = 0; ptr < num_pixels; ++ptr) {
image[ptr * BYTES_PER_PIXEL + 0] = data[ptr] >> 16; // R
image[ptr * BYTES_PER_PIXEL + 1] = data[ptr] >> 8; // G
image[ptr * BYTES_PER_PIXEL + 2] = data[ptr]; // B
image[ptr * BYTES_PER_PIXEL + 3] = data[ptr] >> 24; // A
}
}
QDBusArgument& operator<<(QDBusArgument& a, const FreedesktopImage& i)
{
a.beginStructure();
a << i.width << i.height << i.stride << i.hasAlpha << i.bitsPerSample << i.channels << i.image;
a.endStructure();
return a;
}
const QDBusArgument& operator>>(const QDBusArgument& a, FreedesktopImage& i)
{
a.beginStructure();
a >> i.width >> i.height >> i.stride >> i.hasAlpha >> i.bitsPerSample >> i.channels >> i.image;
a.endStructure();
return a;
}
int FreedesktopImage::metaType()
{
return qDBusRegisterMetaType<FreedesktopImage>();
}
QVariant FreedesktopImage::toVariant(const QImage& img)
{
FreedesktopImage fimg(img);
return QVariant(FreedesktopImage::metaType(), &fimg);
}
void Notificator::notifyDBus(Class cls, const QString& title, const QString& text, const QIcon& icon, int millisTimeout)
{
Q_UNUSED(cls);
// Arguments for DBus call:
QList<QVariant> args;
// Program Name:
args.append(programName);
// Unique ID of this notification type:
args.append(0U);
// Application Icon, empty string
args.append(QString());
// Summary
args.append(title);
// Body
args.append(text);
// Actions (none, actions are deprecated)
QStringList actions;
args.append(actions);
// Hints
QVariantMap hints;
// If no icon specified, set icon based on class
QIcon tmpicon;
if (icon.isNull()) {
QStyle::StandardPixmap sicon = QStyle::SP_MessageBoxQuestion;
switch (cls) {
case Information:
sicon = QStyle::SP_MessageBoxInformation;
break;
case Warning:
sicon = QStyle::SP_MessageBoxWarning;
break;
case Critical:
sicon = QStyle::SP_MessageBoxCritical;
break;
default:
break;
}
tmpicon = QApplication::style()->standardIcon(sicon);
} else {
tmpicon = icon;
}
hints["icon_data"] = FreedesktopImage::toVariant(tmpicon.pixmap(FREEDESKTOP_NOTIFICATION_ICON_SIZE).toImage());
args.append(hints);
// Timeout (in msec)
args.append(millisTimeout);
// "Fire and forget"
interface->callWithArgumentList(QDBus::NoBlock, "Notify", args);
}
#endif
void Notificator::notifySystray(Class cls, const QString& title, const QString& text, const QIcon& icon, int millisTimeout)
{
Q_UNUSED(icon);
QSystemTrayIcon::MessageIcon sicon = QSystemTrayIcon::NoIcon;
switch (cls) // Set icon based on class
{
case Information:
sicon = QSystemTrayIcon::Information;
break;
case Warning:
sicon = QSystemTrayIcon::Warning;
break;
case Critical:
sicon = QSystemTrayIcon::Critical;
break;
}
trayIcon->showMessage(title, text, sicon, millisTimeout);
}
// Based on Qt's tray icon implementation
#ifdef Q_OS_MAC
void Notificator::notifyMacUserNotificationCenter(Class cls, const QString& title, const QString& text, const QIcon& icon)
{
// icon is not supported by the user notification center yet. OSX will use the app icon.
MacNotificationHandler::instance()->showNotification(title, text);
}
#endif
void Notificator::notify(Class cls, const QString& title, const QString& text, const QIcon& icon, int millisTimeout)
{
switch (mode) {
#ifdef USE_DBUS
case Freedesktop:
notifyDBus(cls, title, text, icon, millisTimeout);
break;
#endif
case QSystemTray:
notifySystray(cls, title, text, icon, millisTimeout);
break;
#ifdef Q_OS_MAC
case UserNotificationCenter:
notifyMacUserNotificationCenter(cls, title, text, icon);
break;
#endif
default:
if (cls == Critical) {
// Fall back to old fashioned pop-up dialog if critical and no other notification available
QMessageBox::critical(parent, title, text, QMessageBox::Ok, QMessageBox::Ok);
}
break;
}
}
|
/*******************************************************************************
* Copyright 2019 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#include "common_f32.hpp"
#include "jit_generator.hpp"
namespace mkldnn {
namespace impl {
namespace cpu {
jit_avx2_f32_copy_bn_kern::jit_avx2_f32_copy_bn_kern() :
jit_generator(nullptr, F32_COPY_KERNEL_CODE_SIZE) {
#ifndef _WIN32
#define M rdi
#define N rsi
#define A rdx
#define LDA rcx
#define ALPHA r8
#define B r9
#define I rax
#define A1 r10
#define A2 r8
#define LDA3 r11
#else
#define M rcx
#define N rdx
#define A r8
#define LDA r9
#define ALPHA rsi
#define B rdi
#define I rax
#define A1 rsi
#define A2 r10
#define LDA3 r11
#define ARG_ALPHA 40+stacksize+rsp
#define ARG_B 48+stacksize+rsp
#endif
inLocalLabel();
{
Xbyak::Label l118;
Xbyak::Label l15c;
Xbyak::Label l16c;
Xbyak::Label l18c;
Xbyak::Label l1cc;
Xbyak::Label l200;
Xbyak::Label l230;
Xbyak::Label l234;
Xbyak::Label l254;
Xbyak::Label l294;
Xbyak::Label l2c4;
Xbyak::Label l2e8;
Xbyak::Label l2ec;
Xbyak::Label l2f4;
Xbyak::Label l310;
Xbyak::Label l328;
Xbyak::Label l398;
Xbyak::Label l3ec;
Xbyak::Label l434;
Xbyak::Label l444;
Xbyak::Label l464;
Xbyak::Label l4ac;
Xbyak::Label l4e4;
Xbyak::Label l518;
Xbyak::Label l51c;
Xbyak::Label l53c;
Xbyak::Label l54;
Xbyak::Label l580;
Xbyak::Label l5b4;
Xbyak::Label l5dc;
Xbyak::Label l5e0;
Xbyak::Label l5e8;
Xbyak::Label l5f4;
Xbyak::Label l60c;
Xbyak::Label l67c;
Xbyak::Label l6c;
Xbyak::Label l6d0;
Xbyak::Label l718;
Xbyak::Label l728;
Xbyak::Label l748;
Xbyak::Label l790;
Xbyak::Label l7c8;
Xbyak::Label l7fc;
Xbyak::Label l800;
Xbyak::Label l820;
Xbyak::Label l864;
Xbyak::Label l898;
Xbyak::Label l8c0;
Xbyak::Label l8c4;
Xbyak::Label lcc;
preamble();
#ifdef _WIN32
auto stacksize = get_size_of_abi_save_regs();
mov(ALPHA, ptr[ARG_ALPHA]);
mov(B, ptr[ARG_B]);
#endif
mov(M, qword[M]);
mov(N, qword[N]);
mov(LDA, qword[LDA]);
sub(A, 0x0);
sub(B, -128);
shl(LDA, 0x2);
lea(LDA3, ptr[LDA+LDA*2]);
vbroadcastss(ymm6, dword[ALPHA]);
vpcmpeqb(xmm3, xmm3, xmm3);
vpsrld(xmm3, xmm3, 0x17);
vpslld(xmm3, xmm3, 0x19);
vpsrld(xmm3, xmm3, 0x2);
vpcmpeqb(xmm4, xmm4, xmm4);
vpslld(xmm4, xmm4, 0x1f);
vperm2f128(ymm4, ymm4, ymm4, 0x20);
vucomiss(xmm6, xmm3);
jne(l2f4, T_NEAR);
cmp(N, 0x4);
jl(l16c, T_NEAR);
align(4);
L(l54);
mov(A1, A);
mov(I, LDA);
imul(I, I, 0x4);
add(A, I);
mov(I, M);
sar(I, 0x2);
jle(lcc, T_NEAR);
align(4);
L(l6c);
vmovups(xmm0, xword[A1]);
vmovups(xmm1, xword[A1+LDA*1]);
vmovups(xmm2, xword[A1+LDA*2]);
vmovups(xmm3, xword[A1+LDA3*1]);
vunpcklps(xmm4, xmm0, xmm1);
vunpckhps(xmm5, xmm0, xmm1);
vunpcklps(xmm1, xmm2, xmm3);
vunpckhps(xmm3, xmm2, xmm3);
vunpcklpd(xmm0, xmm4, xmm1);
vunpckhpd(xmm1, xmm4, xmm1);
vunpcklpd(xmm2, xmm5, xmm3);
vunpckhpd(xmm3, xmm5, xmm3);
vmovups(xword[B-0x80], xmm0);
vmovups(xword[B-0x70], xmm1);
vmovups(xword[B-0x60], xmm2);
vmovups(xword[B-0x50], xmm3);
lea(A2, ptr[A1+LDA*4]);
sub(A1, -16);
sub(B, -64);
dec(I);
jg(l6c, T_NEAR);
align(4);
L(lcc);
test(M, 0x2);
jle(l118, T_NEAR);
vmovsd(xmm0, qword[A1]);
vmovsd(xmm1, qword[A1+LDA*1]);
vmovhps(xmm0, xmm0, qword[A1+LDA*2]);
vmovhps(xmm1, xmm1, qword[A1+LDA3*1]);
vunpcklps(xmm4, xmm0, xmm1);
vunpckhps(xmm1, xmm0, xmm1);
vunpcklpd(xmm0, xmm4, xmm1);
vunpckhpd(xmm1, xmm4, xmm1);
vmovups(xword[B-0x80], xmm0);
vmovups(xword[B-0x70], xmm1);
lea(A2, ptr[A1+LDA*4]);
sub(A1, -8);
sub(B, -32);
align(4);
L(l118);
test(M, 0x1);
jle(l15c, T_NEAR);
vmovss(xmm0, dword[A1]);
vmovss(xmm1, dword[A1+LDA*1]);
vunpcklps(xmm0, xmm0, xmm1);
vmovss(xmm2, dword[A1+LDA*2]);
vmovss(xmm3, dword[A1+LDA3*1]);
vunpcklps(xmm2, xmm2, xmm3);
vunpcklpd(xmm0, xmm0, xmm2);
vmovups(xword[B-0x80], xmm0);
lea(A2, ptr[A1+LDA*4]);
sub(A1, -4);
sub(B, -16);
align(4);
L(l15c);
sub(N, 0x4);
cmp(N, 0x4);
jge(l54, T_NEAR);
align(4);
L(l16c);
cmp(N, 0x2);
jl(l234, T_NEAR);
mov(A1, A);
mov(I, LDA);
imul(I, I, 0x2);
add(A, I);
mov(I, M);
sar(I, 0x2);
jle(l1cc, T_NEAR);
align(4);
L(l18c);
vmovups(xmm0, xword[A1]);
vmovups(xmm1, xword[A1+LDA*1]);
vunpcklps(xmm4, xmm0, xmm1);
vunpckhps(xmm1, xmm0, xmm1);
vmovaps(xmm0, xmm4);
vmovlps(qword[B-0x80], xmm0);
vmovhps(qword[B-0x78], xmm0);
vmovlps(qword[B-0x70], xmm1);
vmovhps(qword[B-0x68], xmm1);
lea(A2, ptr[A1+LDA*2]);
sub(A1, -16);
sub(B, -32);
dec(I);
jg(l18c, T_NEAR);
align(4);
L(l1cc);
test(M, 0x2);
jle(l200, T_NEAR);
vmovsd(xmm0, qword[A1]);
vmovsd(xmm1, qword[A1+LDA*1]);
vunpcklps(xmm0, xmm0, xmm1);
vmovlps(qword[B-0x80], xmm0);
vmovhps(qword[B-0x78], xmm0);
lea(A2, ptr[A1+LDA*2]);
sub(A1, -8);
sub(B, -16);
align(4);
L(l200);
test(M, 0x1);
jle(l230, T_NEAR);
vmovss(xmm0, dword[A1]);
vmovss(xmm1, dword[A1+LDA*1]);
vunpcklps(xmm0, xmm0, xmm1);
vmovlps(qword[B-0x80], xmm0);
lea(A2, ptr[A1+LDA*2]);
sub(A1, -4);
sub(B, -8);
align(4);
L(l230);
sub(N, 0x2);
align(4);
L(l234);
cmp(N, 0x1);
jl(l2ec, T_NEAR);
mov(A1, A);
mov(I, LDA);
imul(I, I, 0x1);
add(A, I);
mov(I, M);
sar(I, 0x2);
jle(l294, T_NEAR);
align(4);
L(l254);
vmovups(xmm0, xword[A1]);
vpshufd(xmm1, xmm0, 0x55);
vpshufd(xmm2, xmm0, 0xaa);
vpshufd(xmm3, xmm0, 0xff);
vmovss(dword[B-0x80], xmm0);
vmovss(dword[B-0x7c], xmm1);
vmovss(dword[B-0x78], xmm2);
vmovss(dword[B-0x74], xmm3);
lea(A2, ptr[A1+LDA*1]);
sub(A1, -16);
sub(B, -16);
dec(I);
jg(l254, T_NEAR);
align(4);
L(l294);
test(M, 0x2);
jle(l2c4, T_NEAR);
vmovsd(xmm0, qword[A1]);
vpshufd(xmm1, xmm0, 0x55);
vmovss(dword[B-0x80], xmm0);
vmovss(dword[B-0x7c], xmm1);
lea(A2, ptr[A1+LDA*1]);
sub(A1, -8);
sub(B, -8);
align(4);
L(l2c4);
test(M, 0x1);
jle(l2e8, T_NEAR);
vmovss(xmm0, dword[A1]);
vmovss(dword[B-0x80], xmm0);
lea(A2, ptr[A1+LDA*1]);
sub(A1, -4);
sub(B, -4);
align(4);
L(l2e8);
sub(N, 0x1);
align(4);
L(l2ec);
jmp(l8c4, T_NEAR);
align(4);
L(l2f4);
vxorps(xmm3, xmm3, xmm4);
vucomiss(xmm6, xmm3);
jne(l5e8, T_NEAR);
vmovaps(ymm6, ymm4);
cmp(N, 0x4);
jl(l444, T_NEAR);
align(4);
L(l310);
mov(A1, A);
mov(I, LDA);
imul(I, I, 0x4);
add(A, I);
mov(I, M);
sar(I, 0x2);
jle(l398, T_NEAR);
align(4);
L(l328);
vmovups(xmm0, xword[A1]);
vmovups(xmm1, xword[A1+LDA*1]);
vmovups(xmm2, xword[A1+LDA*2]);
vmovups(xmm3, xword[A1+LDA3*1]);
vunpcklps(xmm4, xmm0, xmm1);
vunpckhps(xmm5, xmm0, xmm1);
vunpcklps(xmm1, xmm2, xmm3);
vunpckhps(xmm3, xmm2, xmm3);
vunpcklpd(xmm0, xmm4, xmm1);
vunpckhpd(xmm1, xmm4, xmm1);
vunpcklpd(xmm2, xmm5, xmm3);
vunpckhpd(xmm3, xmm5, xmm3);
vxorps(xmm0, xmm6, xmm0);
vxorps(xmm1, xmm6, xmm1);
vxorps(xmm2, xmm6, xmm2);
vxorps(xmm3, xmm6, xmm3);
vmovups(xword[B-0x80], xmm0);
vmovups(xword[B-0x70], xmm1);
vmovups(xword[B-0x60], xmm2);
vmovups(xword[B-0x50], xmm3);
lea(A2, ptr[A1+LDA*4]);
sub(A1, -16);
sub(B, -64);
dec(I);
jg(l328, T_NEAR);
align(4);
L(l398);
test(M, 0x2);
jle(l3ec, T_NEAR);
vmovsd(xmm0, qword[A1]);
vmovsd(xmm1, qword[A1+LDA*1]);
vmovhps(xmm0, xmm0, qword[A1+LDA*2]);
vmovhps(xmm1, xmm1, qword[A1+LDA3*1]);
vunpcklps(xmm4, xmm0, xmm1);
vunpckhps(xmm1, xmm0, xmm1);
vunpcklpd(xmm0, xmm4, xmm1);
vunpckhpd(xmm1, xmm4, xmm1);
vxorps(xmm0, xmm6, xmm0);
vxorps(xmm1, xmm6, xmm1);
vmovups(xword[B-0x80], xmm0);
vmovups(xword[B-0x70], xmm1);
lea(A2, ptr[A1+LDA*4]);
sub(A1, -8);
sub(B, -32);
align(4);
L(l3ec);
test(M, 0x1);
jle(l434, T_NEAR);
vmovss(xmm0, dword[A1]);
vmovss(xmm1, dword[A1+LDA*1]);
vunpcklps(xmm0, xmm0, xmm1);
vmovss(xmm2, dword[A1+LDA*2]);
vmovss(xmm3, dword[A1+LDA3*1]);
vunpcklps(xmm2, xmm2, xmm3);
vunpcklpd(xmm0, xmm0, xmm2);
vxorps(xmm0, xmm6, xmm0);
vmovups(xword[B-0x80], xmm0);
lea(A2, ptr[A1+LDA*4]);
sub(A1, -4);
sub(B, -16);
align(4);
L(l434);
sub(N, 0x4);
cmp(N, 0x4);
jge(l310, T_NEAR);
align(4);
L(l444);
cmp(N, 0x2);
jl(l51c, T_NEAR);
mov(A1, A);
mov(I, LDA);
imul(I, I, 0x2);
add(A, I);
mov(I, M);
sar(I, 0x2);
jle(l4ac, T_NEAR);
align(4);
L(l464);
vmovups(xmm0, xword[A1]);
vmovups(xmm1, xword[A1+LDA*1]);
vunpcklps(xmm4, xmm0, xmm1);
vunpckhps(xmm1, xmm0, xmm1);
vmovaps(xmm0, xmm4);
vxorps(xmm0, xmm6, xmm0);
vxorps(xmm1, xmm6, xmm1);
vmovlps(qword[B-0x80], xmm0);
vmovhps(qword[B-0x78], xmm0);
vmovlps(qword[B-0x70], xmm1);
vmovhps(qword[B-0x68], xmm1);
lea(A2, ptr[A1+LDA*2]);
sub(A1, -16);
sub(B, -32);
dec(I);
jg(l464, T_NEAR);
align(4);
L(l4ac);
test(M, 0x2);
jle(l4e4, T_NEAR);
vmovsd(xmm0, qword[A1]);
vmovsd(xmm1, qword[A1+LDA*1]);
vunpcklps(xmm0, xmm0, xmm1);
vxorps(xmm0, xmm6, xmm0);
vmovlps(qword[B-0x80], xmm0);
vmovhps(qword[B-0x78], xmm0);
lea(A2, ptr[A1+LDA*2]);
sub(A1, -8);
sub(B, -16);
align(4);
L(l4e4);
test(M, 0x1);
jle(l518, T_NEAR);
vmovss(xmm0, dword[A1]);
vmovss(xmm1, dword[A1+LDA*1]);
vunpcklps(xmm0, xmm0, xmm1);
vxorps(xmm0, xmm6, xmm0);
vmovlps(qword[B-0x80], xmm0);
lea(A2, ptr[A1+LDA*2]);
sub(A1, -4);
sub(B, -8);
align(4);
L(l518);
sub(N, 0x2);
align(4);
L(l51c);
cmp(N, 0x1);
jl(l5e0, T_NEAR);
mov(A1, A);
mov(I, LDA);
imul(I, I, 0x1);
add(A, I);
mov(I, M);
sar(I, 0x2);
jle(l580, T_NEAR);
align(4);
L(l53c);
vmovups(xmm0, xword[A1]);
vxorps(xmm0, xmm6, xmm0);
vpshufd(xmm1, xmm0, 0x55);
vpshufd(xmm2, xmm0, 0xaa);
vpshufd(xmm3, xmm0, 0xff);
vmovss(dword[B-0x80], xmm0);
vmovss(dword[B-0x7c], xmm1);
vmovss(dword[B-0x78], xmm2);
vmovss(dword[B-0x74], xmm3);
lea(A2, ptr[A1+LDA*1]);
sub(A1, -16);
sub(B, -16);
dec(I);
jg(l53c, T_NEAR);
align(4);
L(l580);
test(M, 0x2);
jle(l5b4, T_NEAR);
vmovsd(xmm0, qword[A1]);
vxorps(xmm0, xmm6, xmm0);
vpshufd(xmm1, xmm0, 0x55);
vmovss(dword[B-0x80], xmm0);
vmovss(dword[B-0x7c], xmm1);
lea(A2, ptr[A1+LDA*1]);
sub(A1, -8);
sub(B, -8);
align(4);
L(l5b4);
test(M, 0x1);
jle(l5dc, T_NEAR);
vmovss(xmm0, dword[A1]);
vxorps(xmm0, xmm6, xmm0);
vmovss(dword[B-0x80], xmm0);
lea(A2, ptr[A1+LDA*1]);
sub(A1, -4);
sub(B, -4);
align(4);
L(l5dc);
sub(N, 0x1);
align(4);
L(l5e0);
jmp(l8c4, T_NEAR);
align(4);
L(l5e8);
cmp(N, 0x4);
jl(l728, T_NEAR);
align(4);
L(l5f4);
mov(A1, A);
mov(I, LDA);
imul(I, I, 0x4);
add(A, I);
mov(I, M);
sar(I, 0x2);
jle(l67c, T_NEAR);
align(4);
L(l60c);
vmovups(xmm0, xword[A1]);
vmovups(xmm1, xword[A1+LDA*1]);
vmovups(xmm2, xword[A1+LDA*2]);
vmovups(xmm3, xword[A1+LDA3*1]);
vunpcklps(xmm4, xmm0, xmm1);
vunpckhps(xmm5, xmm0, xmm1);
vunpcklps(xmm1, xmm2, xmm3);
vunpckhps(xmm3, xmm2, xmm3);
vunpcklpd(xmm0, xmm4, xmm1);
vunpckhpd(xmm1, xmm4, xmm1);
vunpcklpd(xmm2, xmm5, xmm3);
vunpckhpd(xmm3, xmm5, xmm3);
vmulps(xmm0, xmm6, xmm0);
vmulps(xmm1, xmm6, xmm1);
vmulps(xmm2, xmm6, xmm2);
vmulps(xmm3, xmm6, xmm3);
vmovups(xword[B-0x80], xmm0);
vmovups(xword[B-0x70], xmm1);
vmovups(xword[B-0x60], xmm2);
vmovups(xword[B-0x50], xmm3);
lea(A2, ptr[A1+LDA*4]);
sub(A1, -16);
sub(B, -64);
dec(I);
jg(l60c, T_NEAR);
align(4);
L(l67c);
test(M, 0x2);
jle(l6d0, T_NEAR);
vmovsd(xmm0, qword[A1]);
vmovsd(xmm1, qword[A1+LDA*1]);
vmovhps(xmm0, xmm0, qword[A1+LDA*2]);
vmovhps(xmm1, xmm1, qword[A1+LDA3*1]);
vunpcklps(xmm4, xmm0, xmm1);
vunpckhps(xmm1, xmm0, xmm1);
vunpcklpd(xmm0, xmm4, xmm1);
vunpckhpd(xmm1, xmm4, xmm1);
vmulps(xmm0, xmm6, xmm0);
vmulps(xmm1, xmm6, xmm1);
vmovups(xword[B-0x80], xmm0);
vmovups(xword[B-0x70], xmm1);
lea(A2, ptr[A1+LDA*4]);
sub(A1, -8);
sub(B, -32);
align(4);
L(l6d0);
test(M, 0x1);
jle(l718, T_NEAR);
vmovss(xmm0, dword[A1]);
vmovss(xmm1, dword[A1+LDA*1]);
vunpcklps(xmm0, xmm0, xmm1);
vmovss(xmm2, dword[A1+LDA*2]);
vmovss(xmm3, dword[A1+LDA3*1]);
vunpcklps(xmm2, xmm2, xmm3);
vunpcklpd(xmm0, xmm0, xmm2);
vmulps(xmm0, xmm6, xmm0);
vmovups(xword[B-0x80], xmm0);
lea(A2, ptr[A1+LDA*4]);
sub(A1, -4);
sub(B, -16);
align(4);
L(l718);
sub(N, 0x4);
cmp(N, 0x4);
jge(l5f4, T_NEAR);
align(4);
L(l728);
cmp(N, 0x2);
jl(l800, T_NEAR);
mov(A1, A);
mov(I, LDA);
imul(I, I, 0x2);
add(A, I);
mov(I, M);
sar(I, 0x2);
jle(l790, T_NEAR);
align(4);
L(l748);
vmovups(xmm0, xword[A1]);
vmovups(xmm1, xword[A1+LDA*1]);
vunpcklps(xmm4, xmm0, xmm1);
vunpckhps(xmm1, xmm0, xmm1);
vmovaps(xmm0, xmm4);
vmulps(xmm0, xmm6, xmm0);
vmulps(xmm1, xmm6, xmm1);
vmovlps(qword[B-0x80], xmm0);
vmovhps(qword[B-0x78], xmm0);
vmovlps(qword[B-0x70], xmm1);
vmovhps(qword[B-0x68], xmm1);
lea(A2, ptr[A1+LDA*2]);
sub(A1, -16);
sub(B, -32);
dec(I);
jg(l748, T_NEAR);
align(4);
L(l790);
test(M, 0x2);
jle(l7c8, T_NEAR);
vmovsd(xmm0, qword[A1]);
vmovsd(xmm1, qword[A1+LDA*1]);
vunpcklps(xmm0, xmm0, xmm1);
vmulps(xmm0, xmm6, xmm0);
vmovlps(qword[B-0x80], xmm0);
vmovhps(qword[B-0x78], xmm0);
lea(A2, ptr[A1+LDA*2]);
sub(A1, -8);
sub(B, -16);
align(4);
L(l7c8);
test(M, 0x1);
jle(l7fc, T_NEAR);
vmovss(xmm0, dword[A1]);
vmovss(xmm1, dword[A1+LDA*1]);
vunpcklps(xmm0, xmm0, xmm1);
vmulps(xmm0, xmm6, xmm0);
vmovlps(qword[B-0x80], xmm0);
lea(A2, ptr[A1+LDA*2]);
sub(A1, -4);
sub(B, -8);
align(4);
L(l7fc);
sub(N, 0x2);
align(4);
L(l800);
cmp(N, 0x1);
jl(l8c4, T_NEAR);
mov(A1, A);
mov(I, LDA);
imul(I, I, 0x1);
add(A, I);
mov(I, M);
sar(I, 0x2);
jle(l864, T_NEAR);
align(4);
L(l820);
vmovups(xmm0, xword[A1]);
vmulps(xmm0, xmm6, xmm0);
vpshufd(xmm1, xmm0, 0x55);
vpshufd(xmm2, xmm0, 0xaa);
vpshufd(xmm3, xmm0, 0xff);
vmovss(dword[B-0x80], xmm0);
vmovss(dword[B-0x7c], xmm1);
vmovss(dword[B-0x78], xmm2);
vmovss(dword[B-0x74], xmm3);
lea(A2, ptr[A1+LDA*1]);
sub(A1, -16);
sub(B, -16);
dec(I);
jg(l820, T_NEAR);
align(4);
L(l864);
test(M, 0x2);
jle(l898, T_NEAR);
vmovsd(xmm0, qword[A1]);
vmulps(xmm0, xmm6, xmm0);
vpshufd(xmm1, xmm0, 0x55);
vmovss(dword[B-0x80], xmm0);
vmovss(dword[B-0x7c], xmm1);
lea(A2, ptr[A1+LDA*1]);
sub(A1, -8);
sub(B, -8);
align(4);
L(l898);
test(M, 0x1);
jle(l8c0, T_NEAR);
vmovss(xmm0, dword[A1]);
vmulps(xmm0, xmm6, xmm0);
vmovss(dword[B-0x80], xmm0);
lea(A2, ptr[A1+LDA*1]);
sub(A1, -4);
sub(B, -4);
align(4);
L(l8c0);
sub(N, 0x1);
align(4);
L(l8c4);
postamble();
}
outLocalLabel();
#undef M
#undef N
#undef A
#undef LDA
#undef ALPHA
#undef B
#undef I
#undef A1
#undef A2
#undef LDA3
#ifdef _WIN32
#undef ARG_ALPHA
#undef ARG_B
#endif
}
}
}
}
|
//
// Created by john on 08/05/2021.
//
#include "listener.hpp"
//! stl
#include <algorithm>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include <vector>
//! boost
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/asio/dispatch.hpp>
#include <boost/asio/strand.hpp>
#include <boost/config.hpp>
//! local
#include "request.hpp"
namespace beast = boost::beast; // from <boost/beast.hpp>
namespace http = beast::http; // from <boost/beast/http.hpp>
namespace net = boost::asio; // from <boost/asio.hpp>
using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
namespace ott
{
namespace http
{
// Report a failure
listener::listener(net::io_context &ioc, tcp::endpoint endpoint) : ioc_(ioc), acceptor_(net::make_strand(ioc))
{
beast::error_code ec;
// Open the acceptor
acceptor_.open(endpoint.protocol(), ec);
if(ec)
{
fail(ec, "open");
return;
}
// Allow address reuse
acceptor_.set_option(net::socket_base::reuse_address(true), ec);
if(ec)
{
fail(ec, "set_option");
return;
}
// Bind to the server address
acceptor_.bind(endpoint, ec);
if(ec)
{
fail(ec, "bind");
return;
}
// Start listening for connections
acceptor_.listen(
net::socket_base::max_listen_connections, ec);
if(ec)
{
fail(ec, "listen");
return;
}
}
// Start accepting incoming connections
void listener::run()
{
std::cout << "start listener::run() " << std::endl;
do_accept();
std::cout << "end listener::run() " << std::endl;
}
void listener::do_accept()
{
std::cout << "start listener::do_accept() " << std::endl;
// The new connection gets its own strand
acceptor_.async_accept(
net::make_strand(ioc_),
beast::bind_front_handler(
&listener::on_accept,
shared_from_this()));
std::cout << "end listener::do_accept() " << std::endl;
}
void listener::on_accept(beast::error_code ec, tcp::socket socket)
{
std::cout << "start listener::on_accept() " << std::endl;
if(ec)
{
fail(ec, "accept");
}
else
{
// Create the session and run it
std::make_shared<HttpSession>(
std::move(socket))->run();
}
// Accept another connection
do_accept();
std::cout << "end listener::on_accept() " << std::endl;
}
}
}
|
/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "itkContourExtractor2DImageFilter.h"
#include "itkLabelToRGBImageFilter.h"
#include "itkLabelOverlayImageFilter.h"
#include "itkRGBPixel.h"
#include "itkQuadEdgeMesh.h"
#include "itkValuedRegionalMinimaImageFilter.h"
#include "itkValuedRegionalMaximaImageFilter.h"
#include "itkRegionalMaximaImageFilter.h"
#include "itkRegionalMinimaImageFilter.h"
#include "itkConformalFlatteningMeshFilter.h"
#include "itkVTKPolyDataReader.h"
#include "itkVTKPolyDataWriter.h"
#include "itkImageKernelOperator.h"
#include "itkHessianToObjectnessMeasureImageFilter.h"
#include "itkMultiScaleHessianBasedMeasureImageFilter.h"
int
itkReviewPrintTest(int, char *[])
{
using Input2DImageType = itk::Image<float, 2>;
using CharType = itk::Image<unsigned char, 2>;
using RGBPixelType = itk::RGBPixel<unsigned char>;
using RGBImageType = itk::Image<RGBPixelType, 2>;
using VectorType = itk::Vector<float, 2>;
using VectorImageType = itk::Image<VectorType, 2>;
using QuadEdgeMeshType = itk::QuadEdgeMesh<double, 3>;
using PixelType = unsigned short;
using MeshType = itk::Mesh<float, 3>;
using RealPixelType = itk::NumericTraits<PixelType>::RealType;
using HessianPixelType = itk::SymmetricSecondRankTensor<RealPixelType, 3>;
using HessianImageType = itk::Image<HessianPixelType, 3>;
using Input3DImageType = itk::Image<PixelType, 3>;
using OutputImageType = itk::Image<PixelType, 3>;
// Dummy variable just to force the full instantiation of the class
CharType::Pointer dummyImage = CharType::New();
VectorImageType::Pointer dummy2 = VectorImageType::New();
itk::ContourExtractor2DImageFilter<Input2DImageType>::Pointer ContourExtractor2DImageFilterObj =
itk::ContourExtractor2DImageFilter<Input2DImageType>::New();
std::cout << "-------------ContourExtractor2DImageFilter " << ContourExtractor2DImageFilterObj;
itk::LabelToRGBImageFilter<CharType, RGBImageType>::Pointer LabelToRGBImageFilterObj =
itk::LabelToRGBImageFilter<CharType, RGBImageType>::New();
std::cout << "-------------LabelToRGBImageFilter " << LabelToRGBImageFilterObj;
itk::LabelOverlayImageFilter<Input2DImageType, CharType, RGBImageType>::Pointer LabelOverlayImageFilterObj =
itk::LabelOverlayImageFilter<Input2DImageType, CharType, RGBImageType>::New();
std::cout << "-------------LabelOverlayImageFilter " << LabelOverlayImageFilterObj;
QuadEdgeMeshType::Pointer QuadEdgeMeshObj = QuadEdgeMeshType::New();
std::cout << "-------------QuadEdgeMesh " << QuadEdgeMeshObj;
itk::ValuedRegionalMaximaImageFilter<Input2DImageType, Input2DImageType>::Pointer ValuedRegionalMaximaImageFilterObj =
itk::ValuedRegionalMaximaImageFilter<Input2DImageType, Input2DImageType>::New();
std::cout << "-------------ValuedRegionalMaximaImageFilterObj " << ValuedRegionalMaximaImageFilterObj;
itk::ValuedRegionalMinimaImageFilter<Input2DImageType, Input2DImageType>::Pointer ValuedRegionalMinimaImageFilterObj =
itk::ValuedRegionalMinimaImageFilter<Input2DImageType, Input2DImageType>::New();
std::cout << "-------------ValuedRegionalMinimaImageFilterObj " << ValuedRegionalMinimaImageFilterObj;
itk::RegionalMaximaImageFilter<Input2DImageType, Input2DImageType>::Pointer RegionalMaximaImageFilterObj =
itk::RegionalMaximaImageFilter<Input2DImageType, Input2DImageType>::New();
std::cout << "-------------RegionalMaximaImageFilterObj " << RegionalMaximaImageFilterObj;
itk::RegionalMinimaImageFilter<Input2DImageType, Input2DImageType>::Pointer RegionalMinimaImageFilterObj =
itk::RegionalMinimaImageFilter<Input2DImageType, Input2DImageType>::New();
std::cout << "-------------RegionalMinimaImageFilterObj " << RegionalMinimaImageFilterObj;
itk::ConformalFlatteningMeshFilter<MeshType, MeshType>::Pointer ConformalFlatteningMeshFilterObj =
itk::ConformalFlatteningMeshFilter<MeshType, MeshType>::New();
std::cout << "--------------ConformalFlatteningMeshFilterObj " << ConformalFlatteningMeshFilterObj;
itk::VTKPolyDataReader<MeshType>::Pointer VTKPolyDataReaderObj = itk::VTKPolyDataReader<MeshType>::New();
std::cout << "--------------VTKPolyDataReaderObj " << VTKPolyDataReaderObj;
itk::VTKPolyDataWriter<MeshType>::Pointer VTKPolyDataWriterObj = itk::VTKPolyDataWriter<MeshType>::New();
std::cout << "--------------VTKPolyDataWriterObj " << VTKPolyDataWriterObj;
itk::ImageKernelOperator<float> kernelOperator;
std::cout << "--------------ImageKernelOperatorObj ";
kernelOperator.Print(std::cout);
itk::HessianToObjectnessMeasureImageFilter<HessianImageType, OutputImageType>::Pointer ObjectnessFilterObject =
itk::HessianToObjectnessMeasureImageFilter<HessianImageType, OutputImageType>::New();
std::cout << "---------------------------------ObjectnessFilterObject " << ObjectnessFilterObject;
itk::MultiScaleHessianBasedMeasureImageFilter<Input3DImageType, HessianImageType, OutputImageType>::Pointer
MultiScaleHessianFilter =
itk::MultiScaleHessianBasedMeasureImageFilter<Input3DImageType, HessianImageType, OutputImageType>::New();
return EXIT_SUCCESS;
}
|
/*
* 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 <thrift/lib/cpp/protocol/TJSONProtocol.h>
#include <math.h>
#include <thrift/lib/cpp/protocol/TBase64Utils.h>
#include <thrift/lib/cpp/transport/TTransportException.h>
#include <folly/Conv.h>
#include <folly/dynamic.h>
#include <folly/json.h>
using namespace apache::thrift::transport;
namespace apache { namespace thrift { namespace protocol {
// Static data
const uint8_t TJSONProtocol::kJSONObjectStart = '{';
const uint8_t TJSONProtocol::kJSONObjectEnd = '}';
const uint8_t TJSONProtocol::kJSONArrayStart = '[';
const uint8_t TJSONProtocol::kJSONArrayEnd = ']';
const uint8_t TJSONProtocol::kJSONPairSeparator = ':';
const uint8_t TJSONProtocol::kJSONElemSeparator = ',';
const uint8_t TJSONProtocol::kJSONBackslash = '\\';
const uint8_t TJSONProtocol::kJSONStringDelimiter = '"';
const uint8_t TJSONProtocol::kJSONZeroChar = '0';
const uint8_t TJSONProtocol::kJSONEscapeChar = 'u';
const uint8_t TJSONProtocol::kJSONSpace = ' ';
const uint8_t TJSONProtocol::kJSONNewline = '\n';
const uint8_t TJSONProtocol::kJSONTab = '\t';
const uint8_t TJSONProtocol::kJSONCarriageReturn = '\r';
const std::string TJSONProtocol::kJSONEscapePrefix("\\u00");
const std::string TJSONProtocol::kJSONTrue("true");
const std::string TJSONProtocol::kJSONFalse("false");
const uint32_t TJSONProtocol::kThriftVersion1 = 1;
const std::string TJSONProtocol::kThriftNan("NaN");
const std::string TJSONProtocol::kThriftNegativeNan("-NaN");
const std::string TJSONProtocol::kThriftInfinity("Infinity");
const std::string TJSONProtocol::kThriftNegativeInfinity("-Infinity");
const std::string TJSONProtocol::kTypeNameBool("tf");
const std::string TJSONProtocol::kTypeNameByte("i8");
const std::string TJSONProtocol::kTypeNameI16("i16");
const std::string TJSONProtocol::kTypeNameI32("i32");
const std::string TJSONProtocol::kTypeNameI64("i64");
const std::string TJSONProtocol::kTypeNameDouble("dbl");
const std::string TJSONProtocol::kTypeNameFloat("flt");
const std::string TJSONProtocol::kTypeNameStruct("rec");
const std::string TJSONProtocol::kTypeNameString("str");
const std::string TJSONProtocol::kTypeNameMap("map");
const std::string TJSONProtocol::kTypeNameList("lst");
const std::string TJSONProtocol::kTypeNameSet("set");
const std::string &TJSONProtocol::getTypeNameForTypeID(TType typeID) {
switch (typeID) {
case T_BOOL:
return kTypeNameBool;
case T_BYTE:
return kTypeNameByte;
case T_I16:
return kTypeNameI16;
case T_I32:
return kTypeNameI32;
case T_I64:
return kTypeNameI64;
case T_DOUBLE:
return kTypeNameDouble;
case T_FLOAT:
return kTypeNameFloat;
case T_STRING:
return kTypeNameString;
case T_STRUCT:
return kTypeNameStruct;
case T_MAP:
return kTypeNameMap;
case T_SET:
return kTypeNameSet;
case T_LIST:
return kTypeNameList;
default:
throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,
"Unrecognized type");
}
}
TType TJSONProtocol::getTypeIDForTypeName(const std::string &name) {
TType result = T_STOP; // Sentinel value
if (name.length() > 1) {
switch (name[0]) {
case 'd':
result = T_DOUBLE;
break;
case 'f':
result = T_FLOAT;
break;
case 'i':
switch (name[1]) {
case '8':
result = T_BYTE;
break;
case '1':
result = T_I16;
break;
case '3':
result = T_I32;
break;
case '6':
result = T_I64;
break;
}
break;
case 'l':
result = T_LIST;
break;
case 'm':
result = T_MAP;
break;
case 'r':
result = T_STRUCT;
break;
case 's':
if (name[1] == 't') {
result = T_STRING;
}
else if (name[1] == 'e') {
result = T_SET;
}
break;
case 't':
result = T_BOOL;
break;
}
}
if (result == T_STOP) {
throw TProtocolException(TProtocolException::NOT_IMPLEMENTED,
"Unrecognized type");
}
return result;
}
// This table describes the handling for the first 0x30 characters
// 0 : escape using "\u00xx" notation
// 1 : just output index
// <other> : escape using "\<other>" notation
static const uint8_t kJSONCharTable[0x30] = {
// 0 1 2 3 4 5 6 7 8 9 A B C D E F
0, 0, 0, 0, 0, 0, 0, 0,'b','t','n', 0,'f','r', 0, 0, // 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1
1, 1,'"', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 2
};
// This string's characters must match up with the elements in kEscapeCharVals.
// I don't have '/' on this list even though it appears on www.json.org --
// it is not in the RFC
const static std::string kEscapeChars("\"\\/bfnrt");
// The elements of this array must match up with the sequence of characters in
// kEscapeChars
const static uint8_t kEscapeCharVals[8] = {
'"', '\\', '/', '\b', '\f', '\n', '\r', '\t',
};
// Static helper functions
// Reads any whitespace characters
static uint32_t skipWhitespace(TJSONProtocol::LookaheadReader &reader) {
uint32_t result = 0;
while (reader.canPeek()) {
uint8_t ch = reader.peek();
if (ch != TJSONProtocol::kJSONSpace &&
ch != TJSONProtocol::kJSONNewline &&
ch != TJSONProtocol::kJSONTab &&
ch != TJSONProtocol::kJSONCarriageReturn) {
break;
}
reader.read();
++result;
}
return result;
}
// Read 1 character from the transport trans and verify that it is the
// expected character ch.
// Throw a protocol exception if it is not.
static uint32_t readSyntaxChar(TJSONProtocol::LookaheadReader &reader,
uint8_t ch) {
uint8_t ch2 = reader.read();
if (ch2 != ch) {
throw TProtocolException(TProtocolException::INVALID_DATA,
"Expected \'" + std::string((char *)&ch, 1) +
"\'; got \'" + std::string((char *)&ch2, 1) +
"\'.");
}
return 1;
}
// Reads a structural character (any of '[', ']', '{', '}', ',' and ':'),
// and any whitespace characters around it
static uint32_t readStructuralChar(TJSONProtocol::LookaheadReader &reader,
uint8_t ch) {
assert(ch == TJSONProtocol::kJSONObjectStart ||
ch == TJSONProtocol::kJSONObjectEnd ||
ch == TJSONProtocol::kJSONArrayStart ||
ch == TJSONProtocol::kJSONArrayEnd ||
ch == TJSONProtocol::kJSONPairSeparator ||
ch == TJSONProtocol::kJSONElemSeparator);
uint32_t result = 0;
result += skipWhitespace(reader);
result += readSyntaxChar(reader, ch);
result += skipWhitespace(reader);
return result;
}
// Return the integer value of a hex character ch.
// Throw a protocol exception if the character is not [0-9a-f].
static uint8_t hexVal(uint8_t ch) {
if ((ch >= '0') && (ch <= '9')) {
return ch - '0';
}
else if ((ch >= 'a') && (ch <= 'f')) {
return ch - 'a' + 10;
}
else {
throw TProtocolException(TProtocolException::INVALID_DATA,
"Expected hex val ([0-9a-f]); got \'"
+ std::string((char *)&ch, 1) + "\'.");
}
}
// Return the hex character representing the integer val. The value is masked
// to make sure it is in the correct range.
static uint8_t hexChar(uint8_t val) {
val &= 0x0F;
if (val < 10) {
return val + '0';
}
else {
return val - 10 + 'a';
}
}
// Return true if the character ch is in [-+0-9.Ee]; false otherwise
static bool isJSONNumeric(uint8_t ch) {
switch (ch) {
case '+':
case '-':
case '.':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'E':
case 'e':
return true;
}
return false;
}
/**
* Class to serve as base JSON context and as base class for other context
* implementations
*/
class TJSONContext {
public:
TJSONContext() {}
virtual ~TJSONContext() {}
/**
* Write context data to the transport. Default is to do nothing.
*/
virtual uint32_t write(TTransport& /*trans*/) {
return 0;
}
/**
* Read context data from the transport. Default is to do nothing.
*/
virtual uint32_t read(TJSONProtocol::LookaheadReader& /*reader*/) {
return 0;
}
/**
* Return true if numbers need to be escaped as strings in this context.
* Default behavior is to return false.
*/
virtual bool escapeNum() {
return false;
}
};
// Context class for object member key-value pairs
class JSONPairContext : public TJSONContext {
public:
JSONPairContext() :
first_(true),
colon_(true) {
}
uint32_t write(TTransport& trans) override {
if (first_) {
first_ = false;
colon_ = true;
return 0;
}
else {
trans.write(colon_ ? &TJSONProtocol::kJSONPairSeparator :
&TJSONProtocol::kJSONElemSeparator, 1);
colon_ = !colon_;
return 1;
}
}
uint32_t read(TJSONProtocol::LookaheadReader& reader) override {
if (first_) {
first_ = false;
colon_ = true;
return 0;
}
else {
uint8_t ch = (colon_ ? TJSONProtocol::kJSONPairSeparator :
TJSONProtocol::kJSONElemSeparator);
colon_ = !colon_;
return readStructuralChar(reader, ch);
}
}
// Numbers must be turned into strings if they are the key part of a pair
bool escapeNum() override { return colon_; }
private:
bool first_;
bool colon_;
};
// Context class for lists
class JSONListContext : public TJSONContext {
public:
JSONListContext() :
first_(true) {
}
uint32_t write(TTransport& trans) override {
if (first_) {
first_ = false;
return 0;
}
else {
trans.write(&TJSONProtocol::kJSONElemSeparator, 1);
return 1;
}
}
uint32_t read(TJSONProtocol::LookaheadReader& reader) override {
if (first_) {
first_ = false;
return 0;
}
else {
return readStructuralChar(reader, TJSONProtocol::kJSONElemSeparator);
}
}
private:
bool first_;
};
TJSONProtocol::TJSONProtocol(std::shared_ptr<TTransport> ptrans) :
TVirtualProtocol<TJSONProtocol>(ptrans),
trans_(ptrans.get()),
context_(new TJSONContext()),
allowDecodeUTF8_(false),
reader_(*ptrans) {
}
TJSONProtocol::TJSONProtocol(TTransport* ptrans) :
TVirtualProtocol<TJSONProtocol>(ptrans),
trans_(ptrans),
context_(new TJSONContext()),
allowDecodeUTF8_(false),
reader_(*ptrans) {
}
TJSONProtocol::~TJSONProtocol() {}
void TJSONProtocol::pushContext(std::shared_ptr<TJSONContext> c) {
contexts_.push(context_);
context_ = c;
}
void TJSONProtocol::popContext() {
context_ = contexts_.top();
contexts_.pop();
}
// Write the character ch as a JSON escape sequence ("\u00xx")
uint32_t TJSONProtocol::writeJSONEscapeChar(uint8_t ch) {
trans_->write((const uint8_t *)kJSONEscapePrefix.c_str(),
kJSONEscapePrefix.length());
uint8_t outCh = hexChar(ch >> 4);
trans_->write(&outCh, 1);
outCh = hexChar(ch);
trans_->write(&outCh, 1);
return 6;
}
// Write the character ch as part of a JSON string, escaping as appropriate.
uint32_t TJSONProtocol::writeJSONChar(uint8_t ch) {
if (ch >= 0x30) {
if (ch == kJSONBackslash) { // Only special character >= 0x30 is '\'
trans_->write(&kJSONBackslash, 1);
trans_->write(&kJSONBackslash, 1);
return 2;
}
else {
trans_->write(&ch, 1);
return 1;
}
}
else {
uint8_t outCh = kJSONCharTable[ch];
// Check if regular character, backslash escaped, or JSON escaped
if (outCh == 1) {
trans_->write(&ch, 1);
return 1;
}
else if (outCh > 1) {
trans_->write(&kJSONBackslash, 1);
trans_->write(&outCh, 1);
return 2;
}
else {
return writeJSONEscapeChar(ch);
}
}
}
// Write out the contents of the string str as a JSON string, escaping
// characters as appropriate.
uint32_t TJSONProtocol::writeJSONString(const std::string &str) {
uint32_t result = context_->write(*trans_);
result += 2; // For quotes
trans_->write(&kJSONStringDelimiter, 1);
std::string::const_iterator iter(str.begin());
std::string::const_iterator end(str.end());
while (iter != end) {
result += writeJSONChar(*iter++);
}
trans_->write(&kJSONStringDelimiter, 1);
return result;
}
// Write out the contents of the string as JSON string, base64-encoding
// the string's contents, and escaping as appropriate
uint32_t TJSONProtocol::writeJSONBase64(const std::string &str) {
uint32_t result = context_->write(*trans_);
result += 2; // For quotes
trans_->write(&kJSONStringDelimiter, 1);
uint8_t b[4];
const uint8_t *bytes = (const uint8_t *)str.c_str();
uint32_t len = str.length();
while (len >= 3) {
// Encode 3 bytes at a time
base64_encode(bytes, 3, b);
trans_->write(b, 4);
result += 4;
bytes += 3;
len -=3;
}
if (len) { // Handle remainder
base64_encode(bytes, len, b);
trans_->write(b, len + 1);
result += len + 1;
}
trans_->write(&kJSONStringDelimiter, 1);
return result;
}
// Convert the given integer type to a JSON number, or a string
// if the context requires it (eg: key in a map pair).
template <typename NumberType>
uint32_t TJSONProtocol::writeJSONInteger(NumberType num) {
uint32_t result = context_->write(*trans_);
auto val = folly::to<std::string>(num);
bool escapeNum = context_->escapeNum();
if (escapeNum) {
trans_->write(&kJSONStringDelimiter, 1);
result += 1;
}
trans_->write((const uint8_t *)val.c_str(), val.length());
result += val.length();
if (escapeNum) {
trans_->write(&kJSONStringDelimiter, 1);
result += 1;
}
return result;
}
// Convert the given boolean type to a true/false token
uint32_t TJSONProtocol::writeJSONBool(const bool value) {
uint32_t result = context_->write(*trans_);
result += 1;
bool escapeNum = context_->escapeNum();
if (escapeNum) {
trans_->write(&kJSONStringDelimiter, 1);
result += 1;
}
std::string boolVal = value ? "true" : "false";
std::string::const_iterator iter(boolVal.begin());
std::string::const_iterator end(boolVal.end());
while (iter != end) {
result += writeJSONChar(*iter++);
}
if (escapeNum) {
trans_->write(&kJSONStringDelimiter, 1);
result += 1;
}
return result;
}
// Convert the given double to a JSON string, which is either the number,
// "NaN" or "Infinity" or "-Infinity".
template <typename NumberType>
uint32_t TJSONProtocol::writeJSONDouble(NumberType num) {
uint32_t result = context_->write(*trans_);
std::string val;
bool special = true;
if (num == std::numeric_limits<NumberType>::infinity()) {
val = kThriftInfinity;
} else if (num == -std::numeric_limits<NumberType>::infinity()) {
val = kThriftNegativeInfinity;
} else if (std::isnan(num)) {
val = kThriftNan;
} else {
special = false;
val = folly::to<std::string>(num);
}
bool escapeNum = special || context_->escapeNum();
if (escapeNum) {
trans_->write(&kJSONStringDelimiter, 1);
result += 1;
}
trans_->write((const uint8_t *)val.c_str(), val.length());
result += val.length();
if (escapeNum) {
trans_->write(&kJSONStringDelimiter, 1);
result += 1;
}
return result;
}
uint32_t TJSONProtocol::writeJSONObjectStart() {
uint32_t result = context_->write(*trans_);
trans_->write(&kJSONObjectStart, 1);
pushContext(std::shared_ptr<TJSONContext>(new JSONPairContext()));
return result + 1;
}
uint32_t TJSONProtocol::writeJSONObjectEnd() {
popContext();
trans_->write(&kJSONObjectEnd, 1);
return 1;
}
uint32_t TJSONProtocol::writeJSONArrayStart() {
uint32_t result = context_->write(*trans_);
trans_->write(&kJSONArrayStart, 1);
pushContext(std::shared_ptr<TJSONContext>(new JSONListContext()));
return result + 1;
}
uint32_t TJSONProtocol::writeJSONArrayEnd() {
popContext();
trans_->write(&kJSONArrayEnd, 1);
return 1;
}
uint32_t TJSONProtocol::writeMessageBegin(const std::string& name,
const TMessageType messageType,
const int32_t seqid) {
uint32_t result = writeJSONArrayStart();
result += writeJSONInteger(kThriftVersion1);
result += writeJSONString(name);
result += writeJSONInteger(messageType);
result += writeJSONInteger(seqid);
return result;
}
uint32_t TJSONProtocol::writeMessageEnd() {
return writeJSONArrayEnd();
}
uint32_t TJSONProtocol::writeStructBegin(const char* /*name*/) {
return writeJSONObjectStart();
}
uint32_t TJSONProtocol::writeStructEnd() {
return writeJSONObjectEnd();
}
uint32_t TJSONProtocol::writeFieldBegin(const char* /*name*/,
const TType fieldType,
const int16_t fieldId) {
uint32_t result = writeJSONInteger(fieldId);
result += writeJSONObjectStart();
result += writeJSONString(getTypeNameForTypeID(fieldType));
return result;
}
uint32_t TJSONProtocol::writeFieldEnd() {
return writeJSONObjectEnd();
}
uint32_t TJSONProtocol::writeFieldStop() {
return 0;
}
uint32_t TJSONProtocol::writeMapBegin(const TType keyType,
const TType valType,
const uint32_t size) {
uint32_t result = writeJSONArrayStart();
result += writeJSONString(getTypeNameForTypeID(keyType));
result += writeJSONString(getTypeNameForTypeID(valType));
result += writeJSONInteger((int64_t)size);
result += writeJSONObjectStart();
return result;
}
uint32_t TJSONProtocol::writeMapEnd() {
return writeJSONObjectEnd() + writeJSONArrayEnd();
}
uint32_t TJSONProtocol::writeListBegin(const TType elemType,
const uint32_t size) {
uint32_t result = writeJSONArrayStart();
result += writeJSONString(getTypeNameForTypeID(elemType));
result += writeJSONInteger((int64_t)size);
return result;
}
uint32_t TJSONProtocol::writeListEnd() {
return writeJSONArrayEnd();
}
uint32_t TJSONProtocol::writeSetBegin(const TType elemType,
const uint32_t size) {
uint32_t result = writeJSONArrayStart();
result += writeJSONString(getTypeNameForTypeID(elemType));
result += writeJSONInteger((int64_t)size);
return result;
}
uint32_t TJSONProtocol::writeSetEnd() {
return writeJSONArrayEnd();
}
uint32_t TJSONProtocol::writeBool(const bool value) {
return writeJSONInteger(value);
}
uint32_t TJSONProtocol::writeByte(const int8_t byte) {
// writeByte() must be handled specially because folly::to sees
// int8_t as a text type instead of an integer type
return writeJSONInteger((int16_t)byte);
}
uint32_t TJSONProtocol::writeI16(const int16_t i16) {
return writeJSONInteger(i16);
}
uint32_t TJSONProtocol::writeI32(const int32_t i32) {
return writeJSONInteger(i32);
}
uint32_t TJSONProtocol::writeI64(const int64_t i64) {
return writeJSONInteger(i64);
}
uint32_t TJSONProtocol::writeDouble(const double dub) {
return writeJSONDouble(dub);
}
uint32_t TJSONProtocol::writeFloat(const float flt) {
return writeJSONDouble(flt);
}
uint32_t TJSONProtocol::writeString(const std::string& str) {
return writeJSONString(str);
}
uint32_t TJSONProtocol::writeBinary(const std::string& str) {
return writeJSONBase64(str);
}
/**
* Reading functions
*/
// Skips any whitespace characters
uint32_t TJSONProtocol::skipJSONWhitespace() {
return skipWhitespace(reader_);
}
// Whitespace characters is allowed before or after any
// structural characters
uint32_t TJSONProtocol::readJSONStructuralChar(uint8_t ch) {
return readStructuralChar(reader_, ch);
}
// Reads 1 byte and verifies that it matches ch.
uint32_t TJSONProtocol::readJSONSyntaxChar(uint8_t ch) {
return readSyntaxChar(reader_, ch);
}
// Decodes the four hex parts of a JSON escaped string character and returns
// the character via out. The first two characters must be "00".
uint32_t TJSONProtocol::readJSONEscapeChar(uint8_t *out) {
uint8_t b[2];
readJSONSyntaxChar(kJSONZeroChar);
readJSONSyntaxChar(kJSONZeroChar);
b[0] = reader_.read();
b[1] = reader_.read();
*out = (hexVal(b[0]) << 4) + hexVal(b[1]);
return 4;
}
// Decodes a JSON string, including unescaping, and returns the string via str
uint32_t TJSONProtocol::readJSONString(std::string &str, bool skipContext) {
uint32_t result = (skipContext ? 0 : context_->read(reader_));
result += readJSONSyntaxChar(kJSONStringDelimiter);
std::string json("\"");
uint8_t ch;
str.clear();
while (true) {
ch = reader_.read();
++result;
if (ch == kJSONStringDelimiter) {
break;
}
if (ch == kJSONBackslash) {
ch = reader_.read();
++result;
if (ch == kJSONEscapeChar) {
if (allowDecodeUTF8_) {
json += "\\u";
continue;
} else {
result += readJSONEscapeChar(&ch);
}
}
else {
size_t pos = kEscapeChars.find(ch);
if (pos == std::string::npos) {
throw TProtocolException(TProtocolException::INVALID_DATA,
"Expected control char, got '" +
std::string((const char *)&ch, 1) + "'.");
}
if (allowDecodeUTF8_) {
json += "\\";
json += kEscapeChars[pos];
continue;
} else {
ch = kEscapeCharVals[pos];
}
}
}
if (allowDecodeUTF8_) {
json += ch;
} else {
str += ch;
}
}
if (allowDecodeUTF8_) {
json += "\"";
folly::dynamic parsed = folly::parseJson(json);
str += parsed.getString();
}
return result;
}
// Reads a block of base64 characters, decoding it, and returns via str
uint32_t TJSONProtocol::readJSONBase64(std::string &str) {
std::string tmp;
uint32_t result = readJSONString(tmp);
uint8_t *b = (uint8_t *)tmp.c_str();
uint32_t len = tmp.length();
str.clear();
while (len >= 4) {
base64_decode(b, 4);
str.append((const char *)b, 3);
b += 4;
len -= 4;
}
// Don't decode if we hit the end or got a single leftover byte (invalid
// base64 but legal for skip of regular string type)
if (len > 1) {
base64_decode(b, len);
str.append((const char *)b, len - 1);
}
return result;
}
// Reads a sequence of characters, stopping at the first one that is not
// a valid JSON numeric character.
uint32_t TJSONProtocol::readJSONNumericChars(std::string &str) {
uint32_t result = 0;
str.clear();
while (reader_.canPeek()) {
uint8_t ch = reader_.peek();
if (!isJSONNumeric(ch)) {
break;
}
reader_.read();
str += ch;
++result;
}
return result;
}
uint32_t TJSONProtocol::readJSONBool(bool &value) {
uint32_t result = context_->read(reader_);
if (context_->escapeNum()) {
result += readJSONSyntaxChar(kJSONStringDelimiter);
}
uint8_t ch = reader_.read();
++result;
if (ch == kJSONTrue.at(0)) {
for (size_t i = 1; i < kJSONTrue.length(); ++i) {
result += readJSONSyntaxChar(kJSONTrue.at(i));
}
value = true;
} else if (ch == kJSONFalse.at(0)) {
for (size_t i = 1; i < kJSONFalse.length(); ++i) {
result += readJSONSyntaxChar(kJSONFalse.at(i));
}
value = false;
} else {
throw TProtocolException(TProtocolException::INVALID_DATA,
"Expected 't' or 'f'; got '" +
std::string((char *) &ch, 1) + "'.");
}
if (context_->escapeNum()) {
result += readJSONSyntaxChar(kJSONStringDelimiter);
}
return result;
}
// Reads a sequence of characters and assembles them into a number,
// returning them via num
template <typename NumberType>
uint32_t TJSONProtocol::readJSONInteger(NumberType &num) {
uint32_t result = context_->read(reader_);
if (context_->escapeNum()) {
result += readJSONSyntaxChar(kJSONStringDelimiter);
}
std::string str;
result += readJSONNumericChars(str);
try {
num = folly::to<NumberType>(str);
} catch (const std::exception& e) {
throw TProtocolException(TProtocolException::INVALID_DATA,
"Expected numeric value; got \"" + str +
"\"");
}
if (context_->escapeNum()) {
result += readJSONSyntaxChar(kJSONStringDelimiter);
}
return result;
}
// Reads a JSON number or string and interprets it as a double.
template <typename NumberType>
uint32_t TJSONProtocol::readJSONDouble(NumberType &num) {
uint32_t result = context_->read(reader_);
std::string str;
if (reader_.peek() == kJSONStringDelimiter) {
result += readJSONString(str, true);
// Check for NaN, Infinity and -Infinity
if (str == kThriftNan) {
num = HUGE_VAL/HUGE_VAL; // generates NaN
} else if (str == kThriftNegativeNan) {
num = -NAN;
}
else if (str == kThriftInfinity) {
num = HUGE_VAL;
}
else if (str == kThriftNegativeInfinity) {
num = -HUGE_VAL;
}
else {
if (!context_->escapeNum()) {
// Throw exception -- we should not be in a string in this case
throw TProtocolException(TProtocolException::INVALID_DATA,
"Numeric data unexpectedly quoted");
}
try {
num = folly::to<NumberType>(str);
} catch (const std::exception& e) {
throw TProtocolException(TProtocolException::INVALID_DATA,
"Expected numeric value; got \"" + str +
"\"");
}
}
}
else {
if (context_->escapeNum()) {
// This will throw - we should have had a quote if escapeNum == true
readJSONSyntaxChar(kJSONStringDelimiter);
}
result += readJSONNumericChars(str);
try {
num = folly::to<NumberType>(str);
} catch (const std::exception& e) {
throw TProtocolException(TProtocolException::INVALID_DATA,
"Expected numeric value; got \"" + str +
"\"");
}
}
return result;
}
uint32_t TJSONProtocol::readJSONObjectStart() {
uint32_t result = context_->read(reader_);
result += readJSONStructuralChar(kJSONObjectStart);
pushContext(std::shared_ptr<TJSONContext>(new JSONPairContext()));
return result;
}
uint32_t TJSONProtocol::readJSONObjectEnd() {
uint32_t result = readJSONStructuralChar(kJSONObjectEnd);
popContext();
return result;
}
uint32_t TJSONProtocol::readJSONArrayStart() {
uint32_t result = context_->read(reader_);
result += readJSONStructuralChar(kJSONArrayStart);
pushContext(std::shared_ptr<TJSONContext>(new JSONListContext()));
return result;
}
uint32_t TJSONProtocol::readJSONArrayEnd() {
uint32_t result = readJSONStructuralChar(kJSONArrayEnd);
popContext();
return result;
}
uint32_t TJSONProtocol::readMessageBegin(std::string& name,
TMessageType& messageType,
int32_t& seqid) {
uint32_t result = readJSONArrayStart();
uint64_t tmpVal = 0;
result += readJSONInteger(tmpVal);
if (tmpVal != kThriftVersion1) {
throw TProtocolException(TProtocolException::BAD_VERSION,
"Message contained bad version.");
}
result += readJSONString(name);
result += readJSONInteger(tmpVal);
messageType = (TMessageType)tmpVal;
result += readJSONInteger(tmpVal);
seqid = tmpVal;
return result;
}
uint32_t TJSONProtocol::readMessageEnd() {
return readJSONArrayEnd();
}
uint32_t TJSONProtocol::readStructBegin(std::string& /*name*/) {
return readJSONObjectStart();
}
uint32_t TJSONProtocol::readStructEnd() {
return readJSONObjectEnd();
}
uint32_t TJSONProtocol::readFieldBegin(std::string& /*name*/,
TType& fieldType,
int16_t& fieldId) {
uint32_t result = 0;
result += skipJSONWhitespace();
// Check if we hit the end of the list
uint8_t ch = reader_.peek();
if (ch == kJSONObjectEnd) {
fieldType = apache::thrift::protocol::T_STOP;
}
else {
uint64_t tmpVal = 0;
std::string tmpStr;
result += readJSONInteger(tmpVal);
fieldId = tmpVal;
result += readJSONObjectStart();
result += readJSONString(tmpStr);
fieldType = getTypeIDForTypeName(tmpStr);
}
return result;
}
uint32_t TJSONProtocol::readFieldEnd() {
return readJSONObjectEnd();
}
uint32_t TJSONProtocol::readMapBegin(TType& keyType,
TType& valType,
uint32_t& size,
bool& sizeUnknown) {
uint64_t tmpVal = 0;
std::string tmpStr;
uint32_t result = readJSONArrayStart();
result += readJSONString(tmpStr);
keyType = getTypeIDForTypeName(tmpStr);
result += readJSONString(tmpStr);
valType = getTypeIDForTypeName(tmpStr);
result += readJSONInteger(tmpVal);
size = tmpVal;
result += readJSONObjectStart();
sizeUnknown = false;
return result;
}
uint32_t TJSONProtocol::readMapEnd() {
return readJSONObjectEnd() + readJSONArrayEnd();
}
uint32_t TJSONProtocol::readListBegin(TType& elemType,
uint32_t& size,
bool& sizeUnknown) {
uint64_t tmpVal = 0;
std::string tmpStr;
uint32_t result = readJSONArrayStart();
result += readJSONString(tmpStr);
elemType = getTypeIDForTypeName(tmpStr);
result += readJSONInteger(tmpVal);
size = tmpVal;
sizeUnknown = false;
return result;
}
uint32_t TJSONProtocol::readListEnd() {
return readJSONArrayEnd();
}
uint32_t TJSONProtocol::readSetBegin(TType& elemType,
uint32_t& size,
bool& sizeUnknown) {
uint64_t tmpVal = 0;
std::string tmpStr;
uint32_t result = readJSONArrayStart();
result += readJSONString(tmpStr);
elemType = getTypeIDForTypeName(tmpStr);
result += readJSONInteger(tmpVal);
size = tmpVal;
sizeUnknown = false;
return result;
}
uint32_t TJSONProtocol::readSetEnd() {
return readJSONArrayEnd();
}
uint32_t TJSONProtocol::readBool(bool& value) {
return readJSONInteger(value);
}
// readByte() must be handled properly because folly::to sees int8_t
// as a text type instead of an integer type
uint32_t TJSONProtocol::readByte(int8_t& byte) {
int16_t tmp = (int16_t) byte;
uint32_t result = readJSONInteger(tmp);
if (tmp < -128 || tmp > 127) {
throw TProtocolException(TProtocolException::INVALID_DATA,
folly::to<std::string>("Expected numeric value; got \"", tmp, "\""));
}
byte = (int8_t)tmp;
return result;
}
uint32_t TJSONProtocol::readI16(int16_t& i16) {
return readJSONInteger(i16);
}
uint32_t TJSONProtocol::readI32(int32_t& i32) {
return readJSONInteger(i32);
}
uint32_t TJSONProtocol::readI64(int64_t& i64) {
return readJSONInteger(i64);
}
uint32_t TJSONProtocol::readDouble(double& dub) {
return readJSONDouble(dub);
}
uint32_t TJSONProtocol::readFloat(float& flt) {
return readJSONDouble(flt);
}
uint32_t TJSONProtocol::readString(std::string &str) {
return readJSONString(str);
}
uint32_t TJSONProtocol::readBinary(std::string &str) {
return readJSONBase64(str);
}
}}} // apache::thrift::protocol
|
/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkRecordDraw.h"
#include "SkImage.h"
#include "SkPatchUtils.h"
void SkRecordDraw(const SkRecord& record,
SkCanvas* canvas,
SkPicture const* const drawablePicts[],
SkDrawable* const drawables[],
int drawableCount,
const SkBBoxHierarchy* bbh,
SkPicture::AbortCallback* callback) {
SkAutoCanvasRestore saveRestore(canvas, true /*save now, restore at exit*/);
if (bbh) {
// Draw only ops that affect pixels in the canvas's current clip.
// The SkRecord and BBH were recorded in identity space. This canvas
// is not necessarily in that same space. getLocalClipBounds() returns us
// this canvas' clip bounds transformed back into identity space, which
// lets us query the BBH.
SkRect query = canvas->getLocalClipBounds();
SkTDArray<int> ops;
bbh->search(query, &ops);
SkRecords::Draw draw(canvas, drawablePicts, drawables, drawableCount);
for (int i = 0; i < ops.count(); i++) {
if (callback && callback->abort()) {
return;
}
// This visit call uses the SkRecords::Draw::operator() to call
// methods on the |canvas|, wrapped by methods defined with the
// DRAW() macro.
record.visit(ops[i], draw);
}
} else {
// Draw all ops.
SkRecords::Draw draw(canvas, drawablePicts, drawables, drawableCount);
for (int i = 0; i < record.count(); i++) {
if (callback && callback->abort()) {
return;
}
// This visit call uses the SkRecords::Draw::operator() to call
// methods on the |canvas|, wrapped by methods defined with the
// DRAW() macro.
record.visit(i, draw);
}
}
}
void SkRecordPartialDraw(const SkRecord& record, SkCanvas* canvas,
SkPicture const* const drawablePicts[], int drawableCount,
int start, int stop,
const SkMatrix& initialCTM) {
SkAutoCanvasRestore saveRestore(canvas, true /*save now, restore at exit*/);
stop = SkTMin(stop, record.count());
SkRecords::Draw draw(canvas, drawablePicts, nullptr, drawableCount, &initialCTM);
for (int i = start; i < stop; i++) {
record.visit(i, draw);
}
}
namespace SkRecords {
// NoOps draw nothing.
template <> void Draw::draw(const NoOp&) {}
#define DRAW(T, call) template <> void Draw::draw(const T& r) { fCanvas->call; }
DRAW(Flush, flush());
DRAW(Restore, restore());
DRAW(Save, save());
DRAW(SaveLayer, saveLayer(SkCanvas::SaveLayerRec(r.bounds,
r.paint,
r.backdrop.get(),
r.clipMask.get(),
r.clipMatrix,
r.saveLayerFlags)));
DRAW(SetMatrix, setMatrix(SkMatrix::Concat(fInitialCTM, r.matrix)));
DRAW(Concat, concat(r.matrix));
DRAW(Translate, translate(r.dx, r.dy));
DRAW(ClipPath, clipPath(r.path, r.opAA.op(), r.opAA.aa()));
DRAW(ClipRRect, clipRRect(r.rrect, r.opAA.op(), r.opAA.aa()));
DRAW(ClipRect, clipRect(r.rect, r.opAA.op(), r.opAA.aa()));
DRAW(ClipRegion, clipRegion(r.region, r.op));
DRAW(DrawArc, drawArc(r.oval, r.startAngle, r.sweepAngle, r.useCenter, r.paint));
DRAW(DrawDRRect, drawDRRect(r.outer, r.inner, r.paint));
DRAW(DrawImage, drawImage(r.image.get(), r.left, r.top, r.paint));
template <> void Draw::draw(const DrawImageLattice& r) {
SkCanvas::Lattice lattice;
lattice.fXCount = r.xCount;
lattice.fXDivs = r.xDivs;
lattice.fYCount = r.yCount;
lattice.fYDivs = r.yDivs;
lattice.fRectTypes = (0 == r.flagCount) ? nullptr : r.flags;
lattice.fColors = (0 == r.flagCount) ? nullptr : r.colors;
lattice.fBounds = &r.src;
fCanvas->drawImageLattice(r.image.get(), lattice, r.dst, r.paint);
}
DRAW(DrawImageRect, legacy_drawImageRect(r.image.get(), r.src, r.dst, r.paint, r.constraint));
DRAW(DrawImageNine, drawImageNine(r.image.get(), r.center, r.dst, r.paint));
DRAW(DrawOval, drawOval(r.oval, r.paint));
DRAW(DrawPaint, drawPaint(r.paint));
DRAW(DrawPath, drawPath(r.path, r.paint));
DRAW(DrawPatch, drawPatch(r.cubics, r.colors, r.texCoords, r.bmode, r.paint));
DRAW(DrawPicture, drawPicture(r.picture.get(), &r.matrix, r.paint));
DRAW(DrawPoints, drawPoints(r.mode, r.count, r.pts, r.paint));
DRAW(DrawPosText, drawPosText(r.text, r.byteLength, r.pos, r.paint));
DRAW(DrawPosTextH, drawPosTextH(r.text, r.byteLength, r.xpos, r.y, r.paint));
DRAW(DrawRRect, drawRRect(r.rrect, r.paint));
DRAW(DrawRect, drawRect(r.rect, r.paint));
DRAW(DrawRegion, drawRegion(r.region, r.paint));
DRAW(DrawText, drawText(r.text, r.byteLength, r.x, r.y, r.paint));
DRAW(DrawTextBlob, drawTextBlob(r.blob.get(), r.x, r.y, r.paint));
DRAW(DrawTextOnPath, drawTextOnPath(r.text, r.byteLength, r.path, &r.matrix, r.paint));
DRAW(DrawTextRSXform, drawTextRSXform(r.text, r.byteLength, r.xforms, r.cull, r.paint));
DRAW(DrawAtlas, drawAtlas(r.atlas.get(),
r.xforms, r.texs, r.colors, r.count, r.mode, r.cull, r.paint));
DRAW(DrawVertices, drawVertices(r.vertices, r.bmode, r.paint));
DRAW(DrawShadowRec, private_draw_shadow_rec(r.path, r.rec));
DRAW(DrawAnnotation, drawAnnotation(r.rect, r.key.c_str(), r.value.get()));
#undef DRAW
template <> void Draw::draw(const DrawDrawable& r) {
SkASSERT(r.index >= 0);
SkASSERT(r.index < fDrawableCount);
if (fDrawables) {
SkASSERT(nullptr == fDrawablePicts);
fCanvas->drawDrawable(fDrawables[r.index], r.matrix);
} else {
fCanvas->drawPicture(fDrawablePicts[r.index], r.matrix, nullptr);
}
}
// This is an SkRecord visitor that fills an SkBBoxHierarchy.
//
// The interesting part here is how to calculate bounds for ops which don't
// have intrinsic bounds. What is the bounds of a Save or a Translate?
//
// We answer this by thinking about a particular definition of bounds: if I
// don't execute this op, pixels in this rectangle might draw incorrectly. So
// the bounds of a Save, a Translate, a Restore, etc. are the union of the
// bounds of Draw* ops that they might have an effect on. For any given
// Save/Restore block, the bounds of the Save, the Restore, and any other
// non-drawing ("control") ops inside are exactly the union of the bounds of
// the drawing ops inside that block.
//
// To implement this, we keep a stack of active Save blocks. As we consume ops
// inside the Save/Restore block, drawing ops are unioned with the bounds of
// the block, and control ops are stashed away for later. When we finish the
// block with a Restore, our bounds are complete, and we go back and fill them
// in for all the control ops we stashed away.
class FillBounds : SkNoncopyable {
public:
FillBounds(const SkRect& cullRect, const SkRecord& record, SkRect bounds[])
: fNumRecords(record.count())
, fCullRect(cullRect)
, fBounds(bounds) {
fCTM = SkMatrix::I();
// We push an extra save block to track the bounds of any top-level control operations.
fSaveStack.push({ 0, Bounds::MakeEmpty(), nullptr, fCTM });
}
void cleanUp() {
// If we have any lingering unpaired Saves, simulate restores to make
// sure all ops in those Save blocks have their bounds calculated.
while (!fSaveStack.isEmpty()) {
this->popSaveBlock();
}
// Any control ops not part of any Save/Restore block draw everywhere.
while (!fControlIndices.isEmpty()) {
this->popControl(fCullRect);
}
}
void setCurrentOp(int currentOp) { fCurrentOp = currentOp; }
template <typename T> void operator()(const T& op) {
this->updateCTM(op);
this->trackBounds(op);
}
// In this file, SkRect are in local coordinates, Bounds are translated back to identity space.
typedef SkRect Bounds;
int currentOp() const { return fCurrentOp; }
const SkMatrix& ctm() const { return fCTM; }
const Bounds& getBounds(int index) const { return fBounds[index]; }
// Adjust rect for all paints that may affect its geometry, then map it to identity space.
Bounds adjustAndMap(SkRect rect, const SkPaint* paint) const {
// Inverted rectangles really confuse our BBHs.
rect.sort();
// Adjust the rect for its own paint.
if (!AdjustForPaint(paint, &rect)) {
// The paint could do anything to our bounds. The only safe answer is the cull.
return fCullRect;
}
// Adjust rect for all the paints from the SaveLayers we're inside.
if (!this->adjustForSaveLayerPaints(&rect)) {
// Same deal as above.
return fCullRect;
}
// Map the rect back to identity space.
fCTM.mapRect(&rect);
// Nothing can draw outside the cull rect.
if (!rect.intersect(fCullRect)) {
return Bounds::MakeEmpty();
}
return rect;
}
private:
struct SaveBounds {
int controlOps; // Number of control ops in this Save block, including the Save.
Bounds bounds; // Bounds of everything in the block.
const SkPaint* paint; // Unowned. If set, adjusts the bounds of all ops in this block.
SkMatrix ctm;
};
// Only Restore, SetMatrix, Concat, and Translate change the CTM.
template <typename T> void updateCTM(const T&) {}
void updateCTM(const Restore& op) { fCTM = op.matrix; }
void updateCTM(const SetMatrix& op) { fCTM = op.matrix; }
void updateCTM(const Concat& op) { fCTM.preConcat(op.matrix); }
void updateCTM(const Translate& op) { fCTM.preTranslate(op.dx, op.dy); }
// The bounds of these ops must be calculated when we hit the Restore
// from the bounds of the ops in the same Save block.
void trackBounds(const Save&) { this->pushSaveBlock(nullptr); }
void trackBounds(const SaveLayer& op) { this->pushSaveBlock(op.paint); }
void trackBounds(const Restore&) { fBounds[fCurrentOp] = this->popSaveBlock(); }
void trackBounds(const SetMatrix&) { this->pushControl(); }
void trackBounds(const Concat&) { this->pushControl(); }
void trackBounds(const Translate&) { this->pushControl(); }
void trackBounds(const ClipRect&) { this->pushControl(); }
void trackBounds(const ClipRRect&) { this->pushControl(); }
void trackBounds(const ClipPath&) { this->pushControl(); }
void trackBounds(const ClipRegion&) { this->pushControl(); }
// For all other ops, we can calculate and store the bounds directly now.
template <typename T> void trackBounds(const T& op) {
fBounds[fCurrentOp] = this->bounds(op);
this->updateSaveBounds(fBounds[fCurrentOp]);
}
void pushSaveBlock(const SkPaint* paint) {
// Starting a new Save block. Push a new entry to represent that.
SaveBounds sb;
sb.controlOps = 0;
// If the paint affects transparent black,
// the bound shouldn't be smaller than the cull.
sb.bounds =
PaintMayAffectTransparentBlack(paint) ? fCullRect : Bounds::MakeEmpty();
sb.paint = paint;
sb.ctm = this->fCTM;
fSaveStack.push(sb);
this->pushControl();
}
static bool PaintMayAffectTransparentBlack(const SkPaint* paint) {
if (paint) {
// FIXME: this is very conservative
if (paint->getImageFilter() || paint->getColorFilter()) {
return true;
}
// Unusual blendmodes require us to process a saved layer
// even with operations outisde the clip.
// For example, DstIn is used by masking layers.
// https://code.google.com/p/skia/issues/detail?id=1291
// https://crbug.com/401593
switch (paint->getBlendMode()) {
// For each of the following transfer modes, if the source
// alpha is zero (our transparent black), the resulting
// blended alpha is not necessarily equal to the original
// destination alpha.
case SkBlendMode::kClear:
case SkBlendMode::kSrc:
case SkBlendMode::kSrcIn:
case SkBlendMode::kDstIn:
case SkBlendMode::kSrcOut:
case SkBlendMode::kDstATop:
case SkBlendMode::kModulate:
return true;
break;
default:
break;
}
}
return false;
}
Bounds popSaveBlock() {
// We're done the Save block. Apply the block's bounds to all control ops inside it.
SaveBounds sb;
fSaveStack.pop(&sb);
while (sb.controlOps --> 0) {
this->popControl(sb.bounds);
}
// This whole Save block may be part another Save block.
this->updateSaveBounds(sb.bounds);
// If called from a real Restore (not a phony one for balance), it'll need the bounds.
return sb.bounds;
}
void pushControl() {
fControlIndices.push(fCurrentOp);
if (!fSaveStack.isEmpty()) {
fSaveStack.top().controlOps++;
}
}
void popControl(const Bounds& bounds) {
fBounds[fControlIndices.top()] = bounds;
fControlIndices.pop();
}
void updateSaveBounds(const Bounds& bounds) {
// If we're in a Save block, expand its bounds to cover these bounds too.
if (!fSaveStack.isEmpty()) {
fSaveStack.top().bounds.join(bounds);
}
}
Bounds bounds(const Flush&) const { return fCullRect; }
// FIXME: this method could use better bounds
Bounds bounds(const DrawText&) const { return fCullRect; }
Bounds bounds(const DrawPaint&) const { return fCullRect; }
Bounds bounds(const NoOp&) const { return Bounds::MakeEmpty(); } // NoOps don't draw.
Bounds bounds(const DrawRect& op) const { return this->adjustAndMap(op.rect, &op.paint); }
Bounds bounds(const DrawRegion& op) const {
SkRect rect = SkRect::Make(op.region.getBounds());
return this->adjustAndMap(rect, &op.paint);
}
Bounds bounds(const DrawOval& op) const { return this->adjustAndMap(op.oval, &op.paint); }
// Tighter arc bounds?
Bounds bounds(const DrawArc& op) const { return this->adjustAndMap(op.oval, &op.paint); }
Bounds bounds(const DrawRRect& op) const {
return this->adjustAndMap(op.rrect.rect(), &op.paint);
}
Bounds bounds(const DrawDRRect& op) const {
return this->adjustAndMap(op.outer.rect(), &op.paint);
}
Bounds bounds(const DrawImage& op) const {
const SkImage* image = op.image.get();
SkRect rect = SkRect::MakeXYWH(op.left, op.top, image->width(), image->height());
return this->adjustAndMap(rect, op.paint);
}
Bounds bounds(const DrawImageLattice& op) const {
return this->adjustAndMap(op.dst, op.paint);
}
Bounds bounds(const DrawImageRect& op) const {
return this->adjustAndMap(op.dst, op.paint);
}
Bounds bounds(const DrawImageNine& op) const {
return this->adjustAndMap(op.dst, op.paint);
}
Bounds bounds(const DrawPath& op) const {
return op.path.isInverseFillType() ? fCullRect
: this->adjustAndMap(op.path.getBounds(), &op.paint);
}
Bounds bounds(const DrawPoints& op) const {
SkRect dst;
dst.set(op.pts, op.count);
// Pad the bounding box a little to make sure hairline points' bounds aren't empty.
SkScalar stroke = SkMaxScalar(op.paint.getStrokeWidth(), 0.01f);
dst.outset(stroke/2, stroke/2);
return this->adjustAndMap(dst, &op.paint);
}
Bounds bounds(const DrawPatch& op) const {
SkRect dst;
dst.set(op.cubics, SkPatchUtils::kNumCtrlPts);
return this->adjustAndMap(dst, &op.paint);
}
Bounds bounds(const DrawVertices& op) const {
return this->adjustAndMap(op.vertices->bounds(), &op.paint);
}
Bounds bounds(const DrawAtlas& op) const {
if (op.cull) {
// TODO: <reed> can we pass nullptr for the paint? Isn't cull already "correct"
// for the paint (by the caller)?
return this->adjustAndMap(*op.cull, op.paint);
} else {
return fCullRect;
}
}
Bounds bounds(const DrawShadowRec& op) const {
SkRect bounds;
SkDrawShadowMetrics::GetLocalBounds(op.path, op.rec, fCTM, &bounds);
return this->adjustAndMap(bounds, nullptr);
}
Bounds bounds(const DrawPicture& op) const {
SkRect dst = op.picture->cullRect();
op.matrix.mapRect(&dst);
return this->adjustAndMap(dst, op.paint);
}
Bounds bounds(const DrawPosText& op) const {
const int N = op.paint.countText(op.text, op.byteLength);
if (N == 0) {
return Bounds::MakeEmpty();
}
SkRect dst;
dst.set(op.pos, N);
AdjustTextForFontMetrics(&dst, op.paint);
return this->adjustAndMap(dst, &op.paint);
}
Bounds bounds(const DrawPosTextH& op) const {
const int N = op.paint.countText(op.text, op.byteLength);
if (N == 0) {
return Bounds::MakeEmpty();
}
SkScalar left = op.xpos[0], right = op.xpos[0];
for (int i = 1; i < N; i++) {
left = SkMinScalar(left, op.xpos[i]);
right = SkMaxScalar(right, op.xpos[i]);
}
SkRect dst = { left, op.y, right, op.y };
AdjustTextForFontMetrics(&dst, op.paint);
return this->adjustAndMap(dst, &op.paint);
}
Bounds bounds(const DrawTextOnPath& op) const {
SkRect dst = op.path.getBounds();
// Pad all sides by the maximum padding in any direction we'd normally apply.
SkRect pad = { 0, 0, 0, 0};
AdjustTextForFontMetrics(&pad, op.paint);
// That maximum padding happens to always be the right pad today.
SkASSERT(pad.fLeft == -pad.fRight);
SkASSERT(pad.fTop == -pad.fBottom);
SkASSERT(pad.fRight > pad.fBottom);
dst.outset(pad.fRight, pad.fRight);
return this->adjustAndMap(dst, &op.paint);
}
Bounds bounds(const DrawTextRSXform& op) const {
if (op.cull) {
return this->adjustAndMap(*op.cull, nullptr);
} else {
return fCullRect;
}
}
Bounds bounds(const DrawTextBlob& op) const {
SkRect dst = op.blob->bounds();
dst.offset(op.x, op.y);
return this->adjustAndMap(dst, &op.paint);
}
Bounds bounds(const DrawDrawable& op) const {
return this->adjustAndMap(op.worstCaseBounds, nullptr);
}
Bounds bounds(const DrawAnnotation& op) const {
return this->adjustAndMap(op.rect, nullptr);
}
static void AdjustTextForFontMetrics(SkRect* rect, const SkPaint& paint) {
#ifdef SK_DEBUG
SkRect correct = *rect;
#endif
// crbug.com/373785 ~~> xPad = 4x yPad
// crbug.com/424824 ~~> bump yPad from 2x text size to 2.5x
const SkScalar yPad = 2.5f * paint.getTextSize(),
xPad = 4.0f * yPad;
rect->outset(xPad, yPad);
#ifdef SK_DEBUG
SkPaint::FontMetrics metrics;
paint.getFontMetrics(&metrics);
correct.fLeft += metrics.fXMin;
correct.fTop += metrics.fTop;
correct.fRight += metrics.fXMax;
correct.fBottom += metrics.fBottom;
// See skia:2862 for why we ignore small text sizes.
SkASSERTF(paint.getTextSize() < 0.001f || rect->contains(correct),
"%f %f %f %f vs. %f %f %f %f\n",
-xPad, -yPad, +xPad, +yPad,
metrics.fXMin, metrics.fTop, metrics.fXMax, metrics.fBottom);
#endif
}
// Returns true if rect was meaningfully adjusted for the effects of paint,
// false if the paint could affect the rect in unknown ways.
static bool AdjustForPaint(const SkPaint* paint, SkRect* rect) {
if (paint) {
if (paint->canComputeFastBounds()) {
*rect = paint->computeFastBounds(*rect, rect);
return true;
}
return false;
}
return true;
}
bool adjustForSaveLayerPaints(SkRect* rect, int savesToIgnore = 0) const {
for (int i = fSaveStack.count() - 1 - savesToIgnore; i >= 0; i--) {
SkMatrix inverse;
if (!fSaveStack[i].ctm.invert(&inverse)) {
return false;
}
inverse.mapRect(rect);
if (!AdjustForPaint(fSaveStack[i].paint, rect)) {
return false;
}
fSaveStack[i].ctm.mapRect(rect);
}
return true;
}
const int fNumRecords;
// We do not guarantee anything for operations outside of the cull rect
const SkRect fCullRect;
// Conservative identity-space bounds for each op in the SkRecord.
Bounds* fBounds;
// We walk fCurrentOp through the SkRecord,
// as we go using updateCTM() to maintain the exact CTM (fCTM).
int fCurrentOp;
SkMatrix fCTM;
// Used to track the bounds of Save/Restore blocks and the control ops inside them.
SkTDArray<SaveBounds> fSaveStack;
SkTDArray<int> fControlIndices;
};
} // namespace SkRecords
void SkRecordFillBounds(const SkRect& cullRect, const SkRecord& record, SkRect bounds[]) {
SkRecords::FillBounds visitor(cullRect, record, bounds);
for (int curOp = 0; curOp < record.count(); curOp++) {
visitor.setCurrentOp(curOp);
record.visit(curOp, visitor);
}
visitor.cleanUp();
}
|
/**
* @file UARTTX_Demo.cpp
*
* @author David Zemon
*
* @copyright
* The MIT License (MIT)<br>
* <br>Copyright (c) 2013 David Zemon<br>
* <br>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:<br>
* <br>The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.<br>
* <br>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.
*/
// Includes
#include <PropWare/PropWare.h>
#include <PropWare/gpio/simpleport.h>
#include <PropWare/serial/uart/uarttx.h>
#include <PropWare/hmi/output/printer.h>
using PropWare::UARTTX;
using PropWare::UART;
using PropWare::SimplePort;
using PropWare::Port;
using PropWare::Pin;
static void error (const PropWare::ErrorCode err);
static const int32_t BAUD_RATE = 115200;
static const int32_t DELAY = 200;
/**
* @example UARTTX_Demo.cpp
*
* Write "Hello world!" out via UART protocol
*
* @include PropWare_UARTTX/CMakeLists.txt
*/
int main () {
PropWare::ErrorCode err;
UARTTX uart;
// Create an easy-to-test number pattern - useful when testing with a logic
// analyzer
uint8_t numberPattern[] = {
0x01,
0x02,
0x03,
0x45,
0xe5,
0xaa,
0xff,
0x80,
0x00 }; // Make sure we have a null-terminator for puts
// Create the test string - useful when testing with a terminal
char string[] = "Hello world! This is my most favoritest sentence ever!!!\r\n";
// Typical RS232 settings (default settings for PropGCC serial comms)
uart.set_baud_rate(BAUD_RATE);
if ((err = uart.set_data_width(8)))
error(err);
if ((err = uart.set_stop_bit_width(1)))
error(err);
uart.set_parity(UART::Parity::NO_PARITY);
while (1) {
// Test the number pattern
uart.send_array((char *) numberPattern, sizeof(numberPattern));
waitcnt(DELAY * MILLISECOND + CNT);
// Test a basic string
uart.puts(string);
waitcnt(DELAY * MILLISECOND + CNT);
}
}
void error (const PropWare::ErrorCode err) {
SimplePort debugLEDs(Port::P16, 8, Pin::Dir::OUT);
while (1) {
debugLEDs.write((uint32_t) err);
waitcnt(100*MILLISECOND);
debugLEDs.write(0);
waitcnt(100*MILLISECOND);
}
}
|
// Copyright (c) 2012-2014 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 "clientversion.h"
#include "tinyformat.h"
#include <string>
/**
* Name of client reported in the 'version' message. Report the same name
* for both vivoinnovaonexgobyted and vivoinnovaonexgobyte-qt, to make it harder for attackers to
* target servers or GUI users specifically.
*/
const std::string CLIENT_NAME("Vivoinnovaonexgobyte Core");
/**
* Client version number
*/
#define CLIENT_VERSION_SUFFIX ""
/**
* The following part of the code determines the CLIENT_BUILD variable.
* Several mechanisms are used for this:
* * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
* generated by the build environment, possibly containing the output
* of git-describe in a macro called BUILD_DESC
* * secondly, if this is an exported version of the code, GIT_ARCHIVE will
* be defined (automatically using the export-subst git attribute), and
* GIT_COMMIT will contain the commit id.
* * then, three options exist for determining CLIENT_BUILD:
* * if BUILD_DESC is defined, use that literally (output of git-describe)
* * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
* * otherwise, use v[maj].[min].[rev].[build]-unk
* finally CLIENT_VERSION_SUFFIX is added
*/
//! First, include build.h if requested
#ifdef HAVE_BUILD_INFO
#include "build.h"
#endif
//! git will put "#define GIT_ARCHIVE 1" on the next line inside archives.
#define GIT_ARCHIVE 1
#ifdef GIT_ARCHIVE
#define GIT_COMMIT_ID "025f0901c43"
#define GIT_COMMIT_DATE "Tue, 5 Jul 2016 20:34:21 +0200"
#endif
#define BUILD_DESC_WITH_SUFFIX(maj, min, rev, build, suffix) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" DO_STRINGIZE(suffix)
#define BUILD_DESC_FROM_COMMIT(maj, min, rev, build, commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit
#define BUILD_DESC_FROM_UNKNOWN(maj, min, rev, build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
#ifdef BUILD_SUFFIX
#define BUILD_DESC BUILD_DESC_WITH_SUFFIX(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, BUILD_SUFFIX)
#elif defined(GIT_COMMIT_ID)
#define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
#else
#define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
#endif
#endif
#ifndef BUILD_DATE
#ifdef GIT_COMMIT_DATE
#define BUILD_DATE GIT_COMMIT_DATE
#else
#define BUILD_DATE __DATE__ ", " __TIME__
#endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
static std::string FormatVersion(int nVersion)
{
if (nVersion % 100 == 0)
return strprintf("%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100);
else
return strprintf("%d.%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100, nVersion % 100);
}
std::string FormatFullVersion()
{
return CLIENT_BUILD;
}
/**
* Format the subversion field according to BIP 14 spec (https://github.com/bitcoin/bips/blob/master/bip-0014.mediawiki)
*/
std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments)
{
std::ostringstream ss;
ss << "/";
ss << name << ":" << FormatVersion(nClientVersion);
if (!comments.empty())
{
std::vector<std::string>::const_iterator it(comments.begin());
ss << "(" << *it;
for(++it; it != comments.end(); ++it)
ss << "; " << *it;
ss << ")";
}
ss << "/";
return ss.str();
}
|
//
// 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.
#include "ApexDefs.h"
#include "Apex.h"
#include "ModuleDestructibleImpl.h"
#include "DestructiblePreviewImpl.h"
#include "DestructibleAssetImpl.h"
#include "DestructiblePreviewParam.h"
#include "RenderMeshAssetIntl.h"
namespace nvidia
{
namespace destructible
{
DestructiblePreviewImpl::DestructiblePreviewImpl(DestructiblePreview* _api, DestructibleAssetImpl& _asset, const NvParameterized::Interface* params) :
ApexPreview(),
m_asset(&_asset),
m_api(_api),
m_instancedChunkCount(0)
{
for (int meshN = 0; meshN < DestructibleActorMeshType::Count; ++meshN)
{
m_renderMeshActors[meshN] = NULL;
}
const DestructiblePreviewParam* destructiblePreviewParams = DYNAMIC_CAST(const DestructiblePreviewParam*)(params);
PX_ALLOCA(skinnedMaterialNames, const char*, destructiblePreviewParams->overrideSkinnedMaterialNames.arraySizes[0] > 0 ? destructiblePreviewParams->overrideSkinnedMaterialNames.arraySizes[0] : 1);
for (int i = 0; i < destructiblePreviewParams->overrideSkinnedMaterialNames.arraySizes[0]; ++i)
{
skinnedMaterialNames[i] = destructiblePreviewParams->overrideSkinnedMaterialNames.buf[i].buf;
}
PX_ASSERT(m_asset->getRenderMeshAsset());
RenderMeshActorDesc renderableMeshDesc;
renderableMeshDesc.visible = false;
renderableMeshDesc.indexBufferHint = RenderBufferHint::DYNAMIC;
renderableMeshDesc.keepVisibleBonesPacked = true;
renderableMeshDesc.overrideMaterials = destructiblePreviewParams->overrideSkinnedMaterialNames.arraySizes[0] > 0 ? (const char**)skinnedMaterialNames : NULL;
renderableMeshDesc.overrideMaterialCount = (uint32_t)destructiblePreviewParams->overrideSkinnedMaterialNames.arraySizes[0];
m_renderMeshActors[DestructibleActorMeshType::Skinned] = m_asset->getRenderMeshAsset()->createActor(renderableMeshDesc);
const uint32_t numParts = m_asset->getRenderMeshAsset()->getPartCount();
for (uint32_t i = 0; i < numParts; ++i)
{
m_renderMeshActors[DestructibleActorMeshType::Skinned]->setVisibility(false, (uint16_t)i);
}
m_renderMeshActors[DestructibleActorMeshType::Skinned]->updateBounds();
m_drawUnexpandedChunksStatically = destructiblePreviewParams->renderUnexplodedChunksStatically;
if (m_drawUnexpandedChunksStatically)
{
PX_ALLOCA(staticMaterialNames, const char*, destructiblePreviewParams->overrideStaticMaterialNames.arraySizes[0] > 0 ? destructiblePreviewParams->overrideStaticMaterialNames.arraySizes[0] : 1);
for (int i = 0; i < destructiblePreviewParams->overrideStaticMaterialNames.arraySizes[0]; ++i)
{
staticMaterialNames[i] = destructiblePreviewParams->overrideStaticMaterialNames.buf[i].buf;
}
// Create static render mesh
renderableMeshDesc.renderWithoutSkinning = true;
renderableMeshDesc.overrideMaterials = destructiblePreviewParams->overrideStaticMaterialNames.arraySizes[0] > 0 ? (const char**)staticMaterialNames : NULL;
renderableMeshDesc.overrideMaterialCount = (uint32_t)destructiblePreviewParams->overrideStaticMaterialNames.arraySizes[0];
m_renderMeshActors[DestructibleActorMeshType::Static] = m_asset->getRenderMeshAsset()->createActor(renderableMeshDesc);
for (uint32_t i = 0; i < numParts; ++i)
{
m_renderMeshActors[DestructibleActorMeshType::Static]->setVisibility(false, (uint16_t)i);
}
m_renderMeshActors[DestructibleActorMeshType::Static]->updateBounds();
}
// Instanced actors
physx::Array<uint16_t> tempPartToActorMap;
tempPartToActorMap.resize((uint32_t)m_asset->mParams->chunks.arraySizes[0], 0xFFFF);
m_instancedChunkActorMap.resize((uint32_t)m_asset->mParams->chunkInstanceInfo.arraySizes[0]);
for (int32_t i = 0; i < m_asset->mParams->chunkInstanceInfo.arraySizes[0]; ++i)
{
uint16_t partIndex = m_asset->mParams->chunkInstanceInfo.buf[i].partIndex;
if (tempPartToActorMap[partIndex] == 0xFFFF)
{
tempPartToActorMap[partIndex] = m_instancedChunkCount++;
}
m_instancedChunkActorMap[(uint32_t)i] = tempPartToActorMap[partIndex];
}
m_instancedActorVisiblePart.resize(m_instancedChunkCount);
for (int32_t i = 0; i < m_asset->mParams->chunks.arraySizes[0]; ++i)
{
DestructibleAssetParametersNS::Chunk_Type& chunk = m_asset->mParams->chunks.buf[i];
if ((chunk.flags & DestructibleAssetImpl::Instanced) != 0)
{
uint16_t partIndex = m_asset->mParams->chunkInstanceInfo.buf[chunk.meshPartIndex].partIndex;
m_instancedActorVisiblePart[m_instancedChunkActorMap[chunk.meshPartIndex]] = partIndex;
}
}
setChunkVisibility(0, true);
m_chunkDepth = destructiblePreviewParams->chunkDepth;
m_explodeAmount = destructiblePreviewParams->explodeAmount;
setPose(destructiblePreviewParams->globalPose);
m_userData = reinterpret_cast<void*>(destructiblePreviewParams->userData);
}
DestructiblePreviewImpl::~DestructiblePreviewImpl()
{
}
// called at the end of 'setPose' which allows for any module specific updates.
void DestructiblePreviewImpl::setPose(const PxMat44& pose)
{
ApexPreview::setPose(pose);
setExplodeView(m_chunkDepth, m_explodeAmount);
}
void DestructiblePreviewImpl::setExplodeView(uint32_t depth, float explode)
{
m_chunkDepth = PxClamp(depth, (uint32_t)0, m_asset->getDepthCount() - 1);
const float newExplodeAmount = PxMax(explode, 0.0f);
if (m_drawUnexpandedChunksStatically)
{
// Using a static mesh for unexploded chunks
if (m_explodeAmount == 0.0f && newExplodeAmount != 0.0f)
{
// Going from unexploded to exploded. Need to make the static mesh invisible.
if (m_renderMeshActors[DestructibleActorMeshType::Static] != NULL)
{
for (uint32_t i = 0; i < m_asset->getChunkCount(); ++i)
{
m_renderMeshActors[DestructibleActorMeshType::Static]->setVisibility(false, (uint16_t)i);
}
}
}
else if (m_explodeAmount != 0.0f && newExplodeAmount == 0.0f)
{
// Going from exploded to unexploded. Need to make the skinned mesh invisible.
if (m_renderMeshActors[DestructibleActorMeshType::Skinned] != NULL)
{
for (uint32_t i = 0; i < m_asset->getChunkCount(); ++i)
{
m_renderMeshActors[DestructibleActorMeshType::Skinned]->setVisibility(false, (uint16_t)i);
}
}
}
}
m_explodeAmount = newExplodeAmount;
for (uint32_t i = 0; i < m_instancedChunkRenderMeshActors.size(); ++i)
{
PX_ASSERT(i < m_chunkInstanceBufferData.size());
m_chunkInstanceBufferData[i].resize(0);
}
if (m_asset->getRenderMeshAsset() != NULL)
{
PxBounds3 bounds = m_asset->getRenderMeshAsset()->getBounds();
PxVec3 c = bounds.getCenter();
for (uint16_t i = 0; i < (uint16_t)m_asset->getChunkCount(); ++i)
{
setChunkVisibility(i, m_asset->mParams->chunks.buf[i].depth == m_chunkDepth);
}
DestructibleAssetParametersNS::Chunk_Type* sourceChunks = m_asset->mParams->chunks.buf;
mRenderBounds.setEmpty();
// Iterate over all visible chunks
const uint16_t* indexPtr = mVisibleChunks.usedIndices();
const uint16_t* indexPtrStop = indexPtr + mVisibleChunks.usedCount();
DestructibleAssetParametersNS::InstanceInfo_Type* instanceDataArray = m_asset->mParams->chunkInstanceInfo.buf;
while (indexPtr < indexPtrStop)
{
const uint16_t index = *indexPtr++;
if (index < m_asset->getChunkCount())
{
DestructibleAssetParametersNS::Chunk_Type& sourceChunk = sourceChunks[index];
PxMat44 pose = mPose;
if ((sourceChunk.flags & DestructibleAssetImpl::Instanced) == 0)
{
// Not instanced - only need to set skinned tms from chunks
if (!m_drawUnexpandedChunksStatically || m_explodeAmount != 0.0f)
{
PxBounds3 partBounds = m_asset->getRenderMeshAsset()->getBounds(sourceChunk.meshPartIndex);
PxVec3 partC = partBounds.getCenter();
pose.setPosition(pose.getPosition() + m_explodeAmount*pose.rotate(partC-c));
m_renderMeshActors[DestructibleActorMeshType::Skinned]->setTM(pose, sourceChunk.meshPartIndex);
}
}
else
{
// Instanced
PX_ASSERT(sourceChunk.meshPartIndex < m_asset->mParams->chunkInstanceInfo.arraySizes[0]);
DestructibleAssetImpl::ChunkInstanceBufferDataElement instanceDataElement;
DestructibleAssetParametersNS::InstanceInfo_Type& instanceData = instanceDataArray[sourceChunk.meshPartIndex];
const uint16_t instancedActorIndex = m_instancedChunkActorMap[sourceChunk.meshPartIndex];
physx::Array<DestructibleAssetImpl::ChunkInstanceBufferDataElement>& instanceBufferData = m_chunkInstanceBufferData[instancedActorIndex];
instanceDataElement.scaledRotation = PxMat33(pose.getBasis(0), pose.getBasis(1), pose.getBasis(2));
const PxVec3 globalOffset = instanceDataElement.scaledRotation*instanceData.chunkPositionOffset;
PxBounds3 partBounds = m_asset->getRenderMeshAsset()->getBounds(instanceData.partIndex);
partBounds.minimum += globalOffset;
partBounds.maximum += globalOffset;
PxVec3 partC = partBounds.getCenter();
instanceDataElement.translation = pose.getPosition() + globalOffset + m_explodeAmount*pose.rotate(partC-c);
instanceDataElement.uvOffset = instanceData.chunkUVOffset;
instanceDataElement.localOffset = instanceData.chunkPositionOffset;
instanceBufferData.pushBack(instanceDataElement);
// Transform bounds
PxVec3 center, extents;
center = partBounds.getCenter();
extents = partBounds.getExtents();
center = instanceDataElement.scaledRotation.transform(center) + instanceDataElement.translation;
extents = PxVec3(PxAbs(instanceDataElement.scaledRotation(0, 0) * extents.x) + PxAbs(instanceDataElement.scaledRotation(0, 1) * extents.y) + PxAbs(instanceDataElement.scaledRotation(0, 2) * extents.z),
PxAbs(instanceDataElement.scaledRotation(1, 0) * extents.x) + PxAbs(instanceDataElement.scaledRotation(1, 1) * extents.y) + PxAbs(instanceDataElement.scaledRotation(1, 2) * extents.z),
PxAbs(instanceDataElement.scaledRotation(2, 0) * extents.x) + PxAbs(instanceDataElement.scaledRotation(2, 1) * extents.y) + PxAbs(instanceDataElement.scaledRotation(2, 2) * extents.z));
mRenderBounds.include(PxBounds3::centerExtents(center, extents));
}
}
}
m_renderMeshActors[DestructibleActorMeshType::Skinned]->updateBounds();
mRenderBounds.include(m_renderMeshActors[DestructibleActorMeshType::Skinned]->getBounds());
// If a static mesh exists, set its (single) tm from the destructible's tm
if (m_renderMeshActors[DestructibleActorMeshType::Static] != NULL)
{
m_renderMeshActors[DestructibleActorMeshType::Static]->syncVisibility();
m_renderMeshActors[DestructibleActorMeshType::Static]->setTM(mPose);
m_renderMeshActors[DestructibleActorMeshType::Static]->updateBounds();
mRenderBounds.include(m_renderMeshActors[DestructibleActorMeshType::Static]->getBounds());
}
}
}
void DestructiblePreviewImpl::updateRenderResources(bool rewriteBuffers, void* userRenderData)
{
for (uint32_t i = 0; i < DestructibleActorMeshType::Count; ++i)
{
if (m_renderMeshActors[i] != NULL)
{
RenderMeshActorIntl* renderMeshActor = (RenderMeshActorIntl*)m_renderMeshActors[i];
renderMeshActor->updateRenderResources((i == DestructibleActorMeshType::Skinned), rewriteBuffers, userRenderData);
}
}
setInstancedChunkCount(m_instancedChunkCount);
for (uint32_t i = 0; i < m_instancedChunkRenderMeshActors.size(); ++i)
{
PX_ASSERT(i < m_chunkInstanceBufferData.size());
RenderMeshActorIntl* renderMeshActor = (RenderMeshActorIntl*)m_instancedChunkRenderMeshActors[i];
if (renderMeshActor != NULL)
{
physx::Array<DestructibleAssetImpl::ChunkInstanceBufferDataElement>& instanceBufferData = m_chunkInstanceBufferData[i];
const uint32_t instanceBufferSize = instanceBufferData.size();
if (instanceBufferSize > 0)
{
m_chunkInstanceBuffers[i]->writeBuffer(&instanceBufferData[0], 0, instanceBufferSize);
}
renderMeshActor->setInstanceBufferRange(0, instanceBufferSize);
renderMeshActor->updateRenderResources(false, rewriteBuffers, userRenderData);
}
}
}
void DestructiblePreviewImpl::dispatchRenderResources(UserRenderer& renderer)
{
for (uint32_t i = 0; i < DestructibleActorMeshType::Count; ++i)
{
if (m_renderMeshActors[i] != NULL)
{
m_renderMeshActors[i]->dispatchRenderResources(renderer);
}
}
for (uint32_t i = 0; i < m_instancedChunkRenderMeshActors.size(); ++i)
{
PX_ASSERT(i < m_chunkInstanceBufferData.size());
if (m_instancedChunkRenderMeshActors[i] != NULL)
{
if (m_chunkInstanceBufferData[i].size() > 0)
{
m_instancedChunkRenderMeshActors[i]->dispatchRenderResources(renderer);
}
}
}
}
void DestructiblePreviewImpl::release()
{
if (mInRelease)
{
return;
}
mInRelease = true;
destroy();
}
void DestructiblePreviewImpl::destroy()
{
ApexPreview::destroy();
for (uint32_t i = 0; i < DestructibleActorMeshType::Count; ++i)
{
if (m_renderMeshActors[i] != NULL)
{
m_renderMeshActors[i]->release();
}
}
setInstancedChunkCount(0);
}
void DestructiblePreviewImpl::setInstancedChunkCount(uint32_t count)
{
UserRenderResourceManager* rrm = GetInternalApexSDK()->getUserRenderResourceManager();
const uint32_t oldCount = m_instancedChunkRenderMeshActors.size();
for (uint32_t i = count; i < oldCount; ++i)
{
if (m_instancedChunkRenderMeshActors[i] != NULL)
{
m_instancedChunkRenderMeshActors[i]->release();
m_instancedChunkRenderMeshActors[i] = NULL;
}
if (m_chunkInstanceBuffers[i] != NULL)
{
rrm->releaseInstanceBuffer(*m_chunkInstanceBuffers[i]);
m_chunkInstanceBuffers[i] = NULL;
}
}
m_instancedChunkRenderMeshActors.resize(count);
m_chunkInstanceBuffers.resize(count);
m_chunkInstanceBufferData.resize(count);
for (uint32_t index = oldCount; index < count; ++index)
{
m_instancedChunkRenderMeshActors[index] = NULL;
m_chunkInstanceBuffers[index] = NULL;
m_chunkInstanceBufferData[index].reset();
// Find out how many potential instances there are
uint32_t maxInstanceCount = 0;
for (int32_t i = 0; i < m_asset->mParams->chunkInstanceInfo.arraySizes[0]; ++i)
{
if (m_asset->mParams->chunkInstanceInfo.buf[i].partIndex == m_instancedActorVisiblePart[index])
{
++maxInstanceCount;
}
}
// Create instance buffer
UserRenderInstanceBufferDesc instanceBufferDesc;
instanceBufferDesc.maxInstances = maxInstanceCount;
instanceBufferDesc.hint = RenderBufferHint::DYNAMIC;
instanceBufferDesc.semanticOffsets[RenderInstanceLayoutElement::POSITION_FLOAT3] = DestructibleAssetImpl::ChunkInstanceBufferDataElement::translationOffset();
instanceBufferDesc.semanticOffsets[RenderInstanceLayoutElement::ROTATION_SCALE_FLOAT3x3] = DestructibleAssetImpl::ChunkInstanceBufferDataElement::scaledRotationOffset();
instanceBufferDesc.semanticOffsets[RenderInstanceLayoutElement::UV_OFFSET_FLOAT2] = DestructibleAssetImpl::ChunkInstanceBufferDataElement::uvOffsetOffset();
instanceBufferDesc.semanticOffsets[RenderInstanceLayoutElement::LOCAL_OFFSET_FLOAT3] = DestructibleAssetImpl::ChunkInstanceBufferDataElement::localOffsetOffset();
instanceBufferDesc.stride = sizeof(DestructibleAssetImpl::ChunkInstanceBufferDataElement);
m_chunkInstanceBuffers[index] = rrm->createInstanceBuffer(instanceBufferDesc);
// Instance buffer data
m_chunkInstanceBufferData[index].reserve(maxInstanceCount);
m_chunkInstanceBufferData[index].resize(0);
// Create actor
if (m_asset->renderMeshAsset != NULL)
{
RenderMeshActorDesc renderableMeshDesc;
renderableMeshDesc.maxInstanceCount = maxInstanceCount;
renderableMeshDesc.renderWithoutSkinning = true;
renderableMeshDesc.visible = false;
m_instancedChunkRenderMeshActors[index] = m_asset->renderMeshAsset->createActor(renderableMeshDesc);
m_instancedChunkRenderMeshActors[index]->setInstanceBuffer(m_chunkInstanceBuffers[index]);
m_instancedChunkRenderMeshActors[index]->setVisibility(true, m_instancedActorVisiblePart[index]);
}
}
}
}
} // end namespace nvidia
|
#include "file.h"
#include <iostream>
#include <vector>
namespace aoc2017_day01 {
int part_1(std::string_view path) {
std::string input = file::readFileAsString(path);
char prev = input.back();
int sol = 0;
for (const auto& c : input) {
if (c == prev) {
sol += c - '0';
}
prev = c;
}
return sol;
}
int part_2(std::string_view path) {
std::string input = file::readFileAsString(path);
int sol = 0;
int extra = input.size() / 2;
int i = 0;
for (const auto& c : input) {
if (c == input[(extra + i) % input.size()]) {
sol += c - '0';
}
i++;
}
return sol;
}
}
#ifndef TESTING
int main() {
std::cout << "Part 1: " << aoc2017_day01::part_1("../2017/day01/input.in") << std::endl;
std::cout << "Part 2: " << aoc2017_day01::part_2("../2017/day01/input.in") << std::endl;
return 0;
}
#endif
|
/*
* task.cpp
*
* Copyright 2012-2019 German Aerospace Center (DLR) SC
*
* 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 <task.h>
#include <taskInput.h>
#include <taskGroup.h>
#include <scheduler.h>
// Need access to protected elements of scheduler and group. Protection is only valid for application code
class ProtectedSchedulerAccess : public Tasking::Scheduler
{
public:
using Tasking::Scheduler::getImpl;
};
class ProtectedInputAccess : public Tasking::Input
{
public:
using Tasking::Input::synchronizeEnd;
using Tasking::Input::synchronizeStart;
};
Tasking::Task::Task(Scheduler& scheduler, SchedulePolicy::ManagementData& policy, InputArray& inputArray,
TaskId taskId) :
m_taskId(taskId),
impl(scheduler, policy, *this, inputArray)
{
static TaskId autoId = 1u;
if (taskId == 0)
{
m_taskId = autoId;
++autoId;
}
}
//-------------------------------------
Tasking::Task::Task(Scheduler& scheduler, SchedulePolicy::ManagementData& policy, InputArray& inputArray,
const char* taskName) :
Task(scheduler, policy, inputArray, getTaskIdFromName(taskName))
{
}
//-------------------------------------
Tasking::Task::~Task(void)
{
}
//-------------------------------------
void
Tasking::Task::construct(void)
{
// Connect task to all inputs in the input array
impl.inputs.connectTask(impl);
}
//-------------------------------------
bool
Tasking::Task::configureInput(unsigned int key, Channel& channel)
{
return impl.inputs[key].associate(channel);
}
//-------------------------------------
bool
Tasking::Task::isValid(void) const
{
return impl.inputs.isValid();
}
//-------------------------------------
void
Tasking::Task::initialize(void)
{
// Nothing to do by default.
}
//-------------------------------------
void
Tasking::Task::reset(void)
{
impl.taskMutex.enter();
impl.m_state = TaskImpl::TASK_RESET;
impl.taskMutex.leave();
impl.inputs.reset();
impl.taskMutex.enter();
if ((impl.m_state == TaskImpl::TASK_PENDING) && impl.inputs.isActivated())
{
impl.m_state = TaskImpl::TASK_RUN;
static_cast<ProtectedSchedulerAccess&>(impl.associatedScheduler).getImpl().perform(impl);
}
else
{
impl.m_state = TaskImpl::TASK_WAIT;
}
impl.taskMutex.leave();
}
//-------------------------------------
Tasking::TaskId
Tasking::Task::getTaskId(void) const
{
return m_taskId;
}
//-------------------------------------
void
Tasking::Task::setTaskName(const char* newTaskName)
{
m_taskId = getTaskIdFromName(newTaskName);
}
//-------------------------------------
void
Tasking::Task::setTaskId(TaskId newTaskId)
{
m_taskId = newTaskId;
}
// ====================================
Tasking::TaskImpl::TaskImpl(Scheduler& scheduler, SchedulePolicy::ManagementData& policy, Task& task,
InputArray& inputArray) :
parent(task),
m_state(TASK_FINISH),
inputs(inputArray),
nextTaskAtScheduler(NULL),
associatedScheduler(scheduler),
policyData(&policy),
group(NULL)
{
static_cast<ProtectedSchedulerAccess&>(scheduler).getImpl().add(*this);
}
//-------------------------------------
void
Tasking::TaskImpl::activate(void)
{
taskMutex.enter();
// if the task is already PENDING, we should do nothing here; especially, not entering the monitor
if (m_state != TaskImpl::TASK_PENDING)
{
// Condition only true if a reset on this task is currently active.
// By the reset we are inside the monitor. Other tasks are outside of state task reset.
if (m_state == TaskImpl::TASK_RESET)
{
if (inputs.isActivated())
{
m_state = TaskImpl::TASK_PENDING;
}
}
else
{
// Not in state TASK_PENDING or TASK_RESET
if (m_state == TaskImpl::TASK_WAIT)
{
// Search if all inputs are active or activate if final input was triggered
if (inputs.isActivated())
{
// Initiate the execution
m_state = TaskImpl::TASK_RUN;
static_cast<ProtectedSchedulerAccess&>(associatedScheduler).getImpl().perform(*this);
}
}
}
}
taskMutex.leave();
}
//-------------------------------------
Tasking::TaskImpl&
Tasking::Task::joinTo(GroupImpl& group)
{
impl.group = &group;
return impl;
}
//-------------------------------------
void
Tasking::TaskImpl::finalizeExecution(void)
{
// If is part of no group, do a direct reset, else finalize the group.
if (group == NULL)
{
parent.reset();
}
else
{
// Possible running condition to activate when the state is changed.
taskMutex.enter();
m_state = TASK_FINISH;
taskMutex.leave();
group->finalizeExecution();
}
}
//-------------------------------------
void
Tasking::TaskImpl::synchronizeStart(void)
{
for (unsigned int i = 0; (i < inputs.size()); i++)
{
static_cast<ProtectedInputAccess&>(inputs[i]).synchronizeStart();
}
}
//-------------------------------------
void
Tasking::TaskImpl::synchronizeEnd(void)
{
for (unsigned int i = 0; (i < inputs.size()); i++)
{
static_cast<ProtectedInputAccess&>(inputs[i]).synchronizeEnd();
}
}
//-------------------------------------
bool
Tasking::TaskImpl::isExecuted(void) const
{
taskMutex.enter();
bool executionState = (m_state == TASK_FINISH);
taskMutex.leave();
return executionState;
}
|
#include "rpcconsole.h"
#include "ui_rpcconsole.h"
#include "clientmodel.h"
#include "bitcoinrpc.h"
#include "guiutil.h"
#include <QTime>
#include <QTimer>
#include <QThread>
#include <QTextEdit>
#include <QKeyEvent>
#include <QUrl>
#include <QScrollBar>
#include <openssl/crypto.h>
// TODO: make it possible to filter out categories (esp debug messages when implemented)
// TODO: receive errors and debug messages through ClientModel
const int CONSOLE_SCROLLBACK = 50;
const int CONSOLE_HISTORY = 50;
const QSize ICON_SIZE(24, 24);
const struct {
const char *url;
const char *source;
} ICON_MAPPING[] = {
{"cmd-request", ":/icons/tx_input"},
{"cmd-reply", ":/icons/tx_output"},
{"cmd-error", ":/icons/tx_output"},
{"misc", ":/icons/tx_inout"},
{NULL, NULL}
};
/* Object for executing console RPC commands in a separate thread.
*/
class RPCExecutor: public QObject
{
Q_OBJECT
public slots:
void start();
void request(const QString &command);
signals:
void reply(int category, const QString &command);
};
#include "rpcconsole.moc"
void RPCExecutor::start()
{
// Nothing to do
}
/**
* Split shell command line into a list of arguments. Aims to emulate \c bash and friends.
*
* - Arguments are delimited with whitespace
* - Extra whitespace at the beginning and end and between arguments will be ignored
* - Text can be "double" or 'single' quoted
* - The backslash \c \ is used as escape character
* - Outside quotes, any character can be escaped
* - Within double quotes, only escape \c " and backslashes before a \c " or another backslash
* - Within single quotes, no escaping is possible and no special interpretation takes place
*
* @param[out] args Parsed arguments will be appended to this list
* @param[in] strCommand Command line to split
*/
bool parseCommandLine(std::vector<std::string> &args, const std::string &strCommand)
{
enum CmdParseState
{
STATE_EATING_SPACES,
STATE_ARGUMENT,
STATE_SINGLEQUOTED,
STATE_DOUBLEQUOTED,
STATE_ESCAPE_OUTER,
STATE_ESCAPE_DOUBLEQUOTED
} state = STATE_EATING_SPACES;
std::string curarg;
foreach(char ch, strCommand)
{
switch(state)
{
case STATE_ARGUMENT: // In or after argument
case STATE_EATING_SPACES: // Handle runs of whitespace
switch(ch)
{
case '"': state = STATE_DOUBLEQUOTED; break;
case '\'': state = STATE_SINGLEQUOTED; break;
case '\\': state = STATE_ESCAPE_OUTER; break;
case ' ': case '\n': case '\t':
if(state == STATE_ARGUMENT) // Space ends argument
{
args.push_back(curarg);
curarg.clear();
}
state = STATE_EATING_SPACES;
break;
default: curarg += ch; state = STATE_ARGUMENT;
}
break;
case STATE_SINGLEQUOTED: // Single-quoted string
switch(ch)
{
case '\'': state = STATE_ARGUMENT; break;
default: curarg += ch;
}
break;
case STATE_DOUBLEQUOTED: // Double-quoted string
switch(ch)
{
case '"': state = STATE_ARGUMENT; break;
case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break;
default: curarg += ch;
}
break;
case STATE_ESCAPE_OUTER: // '\' outside quotes
curarg += ch; state = STATE_ARGUMENT;
break;
case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text
if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself
curarg += ch; state = STATE_DOUBLEQUOTED;
break;
}
}
switch(state) // final state
{
case STATE_EATING_SPACES:
return true;
case STATE_ARGUMENT:
args.push_back(curarg);
return true;
default: // ERROR to end in one of the other states
return false;
}
}
void RPCExecutor::request(const QString &command)
{
std::vector<std::string> args;
if(!parseCommandLine(args, command.toStdString()))
{
emit reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \""));
return;
}
if(args.empty())
return; // Nothing to do
try
{
std::string strPrint;
// Convert argument list to JSON objects in method-dependent way,
// and pass it along with the method name to the dispatcher.
json_spirit::Value result = tableRPC.execute(
args[0],
RPCConvertValues(args[0], std::vector<std::string>(args.begin() + 1, args.end())));
// Format result reply
if (result.type() == json_spirit::null_type)
strPrint = "";
else if (result.type() == json_spirit::str_type)
strPrint = result.get_str();
else
strPrint = write_string(result, true);
emit reply(RPCConsole::CMD_REPLY, QString::fromStdString(strPrint));
}
catch (json_spirit::Object& objError)
{
try // Nice formatting for standard-format error
{
int code = find_value(objError, "code").get_int();
std::string message = find_value(objError, "message").get_str();
emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")");
}
catch(std::runtime_error &) // raised when converting to invalid type, i.e. missing code or message
{ // Show raw JSON object
emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(write_string(json_spirit::Value(objError), false)));
}
}
catch (std::exception& e)
{
emit reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what()));
}
}
RPCConsole::RPCConsole(QWidget *parent) :
QDialog(parent),
ui(new Ui::RPCConsole),
historyPtr(0)
{
ui->setupUi(this);
#ifndef Q_OS_MAC
ui->openDebugLogfileButton->setIcon(QIcon(":/icons/export"));
ui->showCLOptionsButton->setIcon(QIcon(":/icons/options"));
#endif
// Install event filter for up and down arrow
ui->lineEdit->installEventFilter(this);
ui->messagesWidget->installEventFilter(this);
connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear()));
// set OpenSSL version label
ui->openSSLVersion->setText(SSLeay_version(SSLEAY_VERSION));
startExecutor();
clear();
}
RPCConsole::~RPCConsole()
{
emit stopExecutor();
delete ui;
}
bool RPCConsole::eventFilter(QObject* obj, QEvent *event)
{
if(event->type() == QEvent::KeyPress) // Special key handling
{
QKeyEvent *keyevt = static_cast<QKeyEvent*>(event);
int key = keyevt->key();
Qt::KeyboardModifiers mod = keyevt->modifiers();
switch(key)
{
case Qt::Key_Up: if(obj == ui->lineEdit) { browseHistory(-1); return true; } break;
case Qt::Key_Down: if(obj == ui->lineEdit) { browseHistory(1); return true; } break;
case Qt::Key_PageUp: /* pass paging keys to messages widget */
case Qt::Key_PageDown:
if(obj == ui->lineEdit)
{
QApplication::postEvent(ui->messagesWidget, new QKeyEvent(*keyevt));
return true;
}
break;
default:
// Typing in messages widget brings focus to line edit, and redirects key there
// Exclude most combinations and keys that emit no text, except paste shortcuts
if(obj == ui->messagesWidget && (
(!mod && !keyevt->text().isEmpty() && key != Qt::Key_Tab) ||
((mod & Qt::ControlModifier) && key == Qt::Key_V) ||
((mod & Qt::ShiftModifier) && key == Qt::Key_Insert)))
{
ui->lineEdit->setFocus();
QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt));
return true;
}
}
}
return QDialog::eventFilter(obj, event);
}
void RPCConsole::setClientModel(ClientModel *model)
{
this->clientModel = model;
if(model)
{
// Subscribe to information, replies, messages, errors
connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
connect(model, SIGNAL(numBlocksChanged(int,int)), this, SLOT(setNumBlocks(int,int)));
// Provide initial values
ui->clientVersion->setText(model->formatFullVersion());
ui->clientName->setText(model->clientName());
ui->buildDate->setText(model->formatBuildDate());
ui->startupTime->setText(model->formatClientStartupTime());
setNumConnections(model->getNumConnections());
ui->isTestNet->setChecked(model->isTestNet());
setNumBlocks(model->getNumBlocks(), model->getNumBlocksOfPeers());
}
}
static QString categoryClass(int category)
{
switch(category)
{
case RPCConsole::CMD_REQUEST: return "cmd-request"; break;
case RPCConsole::CMD_REPLY: return "cmd-reply"; break;
case RPCConsole::CMD_ERROR: return "cmd-error"; break;
default: return "misc";
}
}
void RPCConsole::clear()
{
ui->messagesWidget->clear();
ui->lineEdit->clear();
ui->lineEdit->setFocus();
// Add smoothly scaled icon images.
// (when using width/height on an img, Qt uses nearest instead of linear interpolation)
for(int i=0; ICON_MAPPING[i].url; ++i)
{
ui->messagesWidget->document()->addResource(
QTextDocument::ImageResource,
QUrl(ICON_MAPPING[i].url),
QImage(ICON_MAPPING[i].source).scaled(ICON_SIZE, Qt::IgnoreAspectRatio, Qt::SmoothTransformation));
}
// Set default style sheet
ui->messagesWidget->document()->setDefaultStyleSheet(
"table { }"
"td.time { color: #808080; padding-top: 3px; } "
"td.message { font-family: Monospace; font-size: 12px; } "
"td.cmd-request { color: #006060; } "
"td.cmd-error { color: red; } "
"b { color: #006060; } "
);
message(CMD_REPLY, (tr("Welcome to the VITAL RPC console.") + "<br>" +
tr("Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.") + "<br>" +
tr("Type <b>help</b> for an overview of available commands.")), true);
}
void RPCConsole::message(int category, const QString &message, bool html)
{
QTime time = QTime::currentTime();
QString timeString = time.toString();
QString out;
out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>";
out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>";
out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">";
if(html)
out += message;
else
out += GUIUtil::HtmlEscape(message, true);
out += "</td></tr></table>";
ui->messagesWidget->append(out);
}
void RPCConsole::setNumConnections(int count)
{
ui->numberOfConnections->setText(QString::number(count));
}
void RPCConsole::setNumBlocks(int count, int countOfPeers)
{
ui->numberOfBlocks->setText(QString::number(count));
ui->totalBlocks->setText(QString::number(countOfPeers));
if(clientModel)
{
// If there is no current number available display N/A instead of 0, which can't ever be true
ui->totalBlocks->setText(clientModel->getNumBlocksOfPeers() == 0 ? tr("N/A") : QString::number(clientModel->getNumBlocksOfPeers()));
ui->lastBlockTime->setText(clientModel->getLastBlockDate().toString());
}
}
void RPCConsole::on_lineEdit_returnPressed()
{
QString cmd = ui->lineEdit->text();
ui->lineEdit->clear();
if(!cmd.isEmpty())
{
message(CMD_REQUEST, cmd);
emit cmdRequest(cmd);
// Remove command, if already in history
history.removeOne(cmd);
// Append command to history
history.append(cmd);
// Enforce maximum history size
while(history.size() > CONSOLE_HISTORY)
history.removeFirst();
// Set pointer to end of history
historyPtr = history.size();
// Scroll console view to end
scrollToEnd();
}
}
void RPCConsole::browseHistory(int offset)
{
historyPtr += offset;
if(historyPtr < 0)
historyPtr = 0;
if(historyPtr > history.size())
historyPtr = history.size();
QString cmd;
if(historyPtr < history.size())
cmd = history.at(historyPtr);
ui->lineEdit->setText(cmd);
}
void RPCConsole::startExecutor()
{
QThread* thread = new QThread;
RPCExecutor *executor = new RPCExecutor();
executor->moveToThread(thread);
// Notify executor when thread started (in executor thread)
connect(thread, SIGNAL(started()), executor, SLOT(start()));
// Replies from executor object must go to this object
connect(executor, SIGNAL(reply(int,QString)), this, SLOT(message(int,QString)));
// Requests from this object must go to executor
connect(this, SIGNAL(cmdRequest(QString)), executor, SLOT(request(QString)));
// On stopExecutor signal
// - queue executor for deletion (in execution thread)
// - quit the Qt event loop in the execution thread
connect(this, SIGNAL(stopExecutor()), executor, SLOT(deleteLater()));
connect(this, SIGNAL(stopExecutor()), thread, SLOT(quit()));
// Queue the thread for deletion (in this thread) when it is finished
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
// Default implementation of QThread::run() simply spins up an event loop in the thread,
// which is what we want.
thread->start();
}
void RPCConsole::on_tabWidget_currentChanged(int index)
{
if(ui->tabWidget->widget(index) == ui->tab_console)
{
ui->lineEdit->setFocus();
}
}
void RPCConsole::on_openDebugLogfileButton_clicked()
{
GUIUtil::openDebugLogfile();
}
void RPCConsole::scrollToEnd()
{
QScrollBar *scrollbar = ui->messagesWidget->verticalScrollBar();
scrollbar->setValue(scrollbar->maximum());
}
void RPCConsole::on_showCLOptionsButton_clicked()
{
GUIUtil::HelpMessageBox help;
help.exec();
}
|
/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
/* If you are missing that file, acquire a complete release at teeworlds.com. */
#include <game/generated/protocol.h>
#include <game/server/gamecontext.h>
#include "pickup.h"
CPickup::CPickup(CGameWorld *pGameWorld, int Type, int SubType)
: CEntity(pGameWorld, CGameWorld::ENTTYPE_PICKUP)
{
m_Type = Type;
m_Subtype = SubType;
m_ProximityRadius = PickupPhysSize;
Reset();
GameWorld()->InsertEntity(this);
}
void CPickup::Reset()
{
if (g_pData->m_aPickups[m_Type].m_Spawndelay > 0)
m_SpawnTick = Server()->Tick() + Server()->TickSpeed() * g_pData->m_aPickups[m_Type].m_Spawndelay;
else
m_SpawnTick = -1;
}
void CPickup::Tick()
{
// wait for respawn
if(m_SpawnTick > 0)
{
if(Server()->Tick() > m_SpawnTick)
{
// respawn
m_SpawnTick = -1;
if(m_Type == POWERUP_WEAPON)
GameServer()->CreateSound(m_Pos, SOUND_WEAPON_SPAWN);
}
else
return;
}
// Check if a player intersected us
CCharacter *pChr = GameServer()->m_World.ClosestCharacter(m_Pos, 20.0f, 0);
if(pChr && pChr->IsAlive())
{
// player picked us up, is someone was hooking us, let them go
int RespawnTime = -1;
switch (m_Type)
{
case POWERUP_HEALTH:
if(pChr->IncreaseHealth(1))
{
GameServer()->CreateSound(m_Pos, SOUND_PICKUP_HEALTH);
RespawnTime = g_pData->m_aPickups[m_Type].m_Respawntime;
}
break;
case POWERUP_ARMOR:
if(pChr->IncreaseArmor(1))
{
GameServer()->CreateSound(m_Pos, SOUND_PICKUP_ARMOR);
RespawnTime = g_pData->m_aPickups[m_Type].m_Respawntime;
}
break;
case POWERUP_WEAPON:
if(m_Subtype >= 0 && m_Subtype < NUM_WEAPONS)
{
if(pChr->GiveWeapon(m_Subtype, 10))
{
RespawnTime = g_pData->m_aPickups[m_Type].m_Respawntime;
if(m_Subtype == WEAPON_GRENADE)
GameServer()->CreateSound(m_Pos, SOUND_PICKUP_GRENADE);
else if(m_Subtype == WEAPON_SHOTGUN)
GameServer()->CreateSound(m_Pos, SOUND_PICKUP_SHOTGUN);
else if(m_Subtype == WEAPON_RIFLE)
GameServer()->CreateSound(m_Pos, SOUND_PICKUP_SHOTGUN);
if(pChr->GetPlayer())
GameServer()->SendWeaponPickup(pChr->GetPlayer()->GetCID(), m_Subtype);
}
}
break;
case POWERUP_NINJA:
// activate ninja on target player
if (pChr->GiveNinja())
{
RespawnTime = g_pData->m_aPickups[m_Type].m_Respawntime;
// loop through all players, setting their emotes
CCharacter *pC = static_cast<CCharacter *>(GameServer()->m_World.FindFirst(CGameWorld::ENTTYPE_CHARACTER));
for(; pC; pC = (CCharacter *)pC->TypeNext())
{
if (pC != pChr)
pC->SetEmote(EMOTE_SURPRISE, Server()->Tick() + Server()->TickSpeed());
}
pChr->SetEmote(EMOTE_ANGRY, Server()->Tick() + 1200 * Server()->TickSpeed() / 1000);
break;
}
default:
break;
};
if(RespawnTime >= 0)
{
char aBuf[256];
str_format(aBuf, sizeof(aBuf), "pickup player='%d:%s' item=%d/%d",
pChr->GetPlayer()->GetCID(), Server()->ClientName(pChr->GetPlayer()->GetCID()), m_Type, m_Subtype);
GameServer()->Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf);
m_SpawnTick = Server()->Tick() + Server()->TickSpeed() * RespawnTime;
}
}
}
void CPickup::TickPaused()
{
if(m_SpawnTick != -1)
++m_SpawnTick;
}
void CPickup::Snap(int SnappingClient)
{
if(m_SpawnTick != -1 || NetworkClipped(SnappingClient))
return;
CNetObj_Pickup *pP = static_cast<CNetObj_Pickup *>(Server()->SnapNewItem(NETOBJTYPE_PICKUP, m_ID, sizeof(CNetObj_Pickup)));
if(!pP)
return;
pP->m_X = (int)m_Pos.x;
pP->m_Y = (int)m_Pos.y;
pP->m_Type = m_Type;
pP->m_Subtype = m_Subtype;
}
|
#include "vkg/base/base.hpp"
using namespace vkg;
auto main() -> int {
WindowConfig windowConfig{};
FeatureConfig featureConfig{};
Base app{windowConfig, featureConfig};
app.loop([&](double elapsed) {
});
return 0;
}
|
/*
* Copyright (c) 2011 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 "after_initialization_fixture.h"
class NetworkBeforeStreamingTest : public AfterInitializationFixture {
protected:
void SetUp() {
channel_ = voe_base_->CreateChannel();
}
void TearDown() {
voe_base_->DeleteChannel(channel_);
}
int channel_;
};
TEST_F(NetworkBeforeStreamingTest,
GetSourceInfoReturnsEmptyValuesForUnconfiguredChannel) {
char src_ip[32] = "0.0.0.0";
int src_rtp_port = 1234;
int src_rtcp_port = 1235;
EXPECT_EQ(0, voe_network_->GetSourceInfo(
channel_, src_rtp_port, src_rtcp_port, src_ip));
EXPECT_EQ(0, src_rtp_port);
EXPECT_EQ(0, src_rtcp_port);
EXPECT_STRCASEEQ("", src_ip);
}
TEST_F(NetworkBeforeStreamingTest,
GetSourceFilterReturnsEmptyValuesForUnconfiguredChannel) {
int filter_port = -1;
int filter_port_rtcp = -1;
char filter_ip[32] = "0.0.0.0";
EXPECT_EQ(0, voe_network_->GetSourceFilter(
channel_, filter_port, filter_port_rtcp, filter_ip));
EXPECT_EQ(0, filter_port);
EXPECT_EQ(0, filter_port_rtcp);
EXPECT_STRCASEEQ("", filter_ip);
}
TEST_F(NetworkBeforeStreamingTest, SetSourceFilterSucceeds) {
EXPECT_EQ(0, voe_network_->SetSourceFilter(channel_, 0));
}
|
//
// ogles_gpgpu project - GPGPU for mobile devices and embedded systems using OpenGL ES 2.0
//
// Author: Markus Konrad <post@mkonrad.net>, Winter 2014/2015
// http://www.mkonrad.net
//
// See LICENSE file in project repository root for the license.
//
#include "egl.h"
#include "../../common/common_includes.h"
using namespace ogles_gpgpu;
EGLConfig EGL::conf = NULL;
EGLSurface EGL::surface = EGL_NO_SURFACE;
EGLContext EGL::ctx = EGL_NO_CONTEXT;
EGLDisplay EGL::disp = EGL_NO_DISPLAY;
bool EGL::setup(int rSize, int gSize, int bSize, int aSize, int depthSize) {
// EGL config attributes
const EGLint confAttr[] = {
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, // use OpenGL ES 2.0, very important!
EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, // we will create a pixelbuffer surface
EGL_RED_SIZE, rSize,
EGL_GREEN_SIZE, gSize,
EGL_BLUE_SIZE, bSize,
EGL_ALPHA_SIZE, aSize,
EGL_DEPTH_SIZE, depthSize,
EGL_NONE
};
// EGL context attributes
const EGLint ctxAttr[] = {
EGL_CONTEXT_CLIENT_VERSION, 2, // use OpenGL ES 2.0, very important!
EGL_NONE
};
EGLint eglMajVers, eglMinVers;
EGLint numConfigs;
disp = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if (disp == EGL_NO_DISPLAY) {
OG_LOGERR("EGL", "eglGetDisplay failed: %d", eglGetError());
return false;
}
if (!eglInitialize(disp, &eglMajVers, &eglMinVers)) {
OG_LOGERR("EGL", "eglInitialize failed: %d", eglGetError());
return false;
}
OG_LOGINF("EGL", "EGL init with version %d.%d", eglMajVers, eglMinVers);
if (!eglChooseConfig(disp, confAttr, &conf, 1, &numConfigs)) { // choose the first config
OG_LOGERR("EGL", "eglChooseConfig failed: %d", eglGetError());
return false;
}
ctx = eglCreateContext(disp, conf, EGL_NO_CONTEXT, ctxAttr);
if (ctx == EGL_NO_CONTEXT) {
OG_LOGERR("EGL", "eglCreateContext failed: %d", eglGetError());
return false;
}
return true;
}
bool EGL::createPBufferSurface(int w, int h) {
assert(disp != EGL_NO_DISPLAY && conf != NULL && ctx != EGL_NO_CONTEXT);
assert(w > 0 && h > 0);
destroySurface();
// surface attributes
// the surface size is set to the input frame size
const EGLint surfaceAttr[] = {
EGL_WIDTH, w,
EGL_HEIGHT, h,
EGL_NONE
};
surface = eglCreatePbufferSurface(disp, conf, surfaceAttr); // create a pixelbuffer surface
if (surface == EGL_NO_SURFACE) {
OG_LOGERR("EGL", "eglCreatePbufferSurface failed: %d", eglGetError());
return false;
}
return true;
}
bool EGL::activate() {
assert(disp != EGL_NO_DISPLAY && conf != NULL && ctx != EGL_NO_CONTEXT && surface != EGL_NO_SURFACE);
if (!eglMakeCurrent(disp, surface, surface, ctx)) {
OG_LOGERR("EGL", "eglMakeCurrent failed: %d", eglGetError());
return false;
}
return true;
}
bool EGL::deactivate() {
if (!eglMakeCurrent(EGL_NO_DISPLAY, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)) {
OG_LOGERR("EGL", "eglMakeCurrent failed: %d", eglGetError());
return false;
}
return true;
}
void EGL::shutdown() {
deactivate();
destroySurface();
eglDestroyContext(disp, ctx);
eglTerminate(disp);
disp = EGL_NO_DISPLAY;
ctx = EGL_NO_CONTEXT;
}
void EGL::destroySurface() {
if (surface == EGL_NO_SURFACE) return;
eglDestroySurface(disp, surface);
surface = EGL_NO_SURFACE;
}
|
#include <assert.h>
#include "COP_VU.h"
#include "VUShared.h"
#include "../Log.h"
#include "../MIPS.h"
#include "../MemoryUtils.h"
#include "offsetof_def.h"
#include "Vpu.h"
#undef MAX
enum CTRL_REG
{
CTRL_REG_STATUS = 16,
CTRL_REG_MAC = 17,
CTRL_REG_CLIP = 18,
CTRL_REG_R = 20,
CTRL_REG_I = 21,
CTRL_REG_Q = 22,
CTRL_REG_TPC = 26,
CTRL_REG_CMSAR0 = 27,
CTRL_REG_FBRST = 28,
CTRL_REG_VPU_STAT = 29,
CTRL_REG_CMSAR1 = 31,
};
CCOP_VU::CCOP_VU(MIPS_REGSIZE nRegSize)
: CMIPSCoprocessor(nRegSize)
{
SetupReflectionTables();
}
void CCOP_VU::CompileInstruction(uint32 nAddress, CMipsJitter* codeGen, CMIPS* pCtx)
{
SetupQuickVariables(nAddress, codeGen, pCtx);
m_nDest = (uint8)((m_nOpcode >> 21) & 0x0F);
m_nFSF = ((m_nDest >> 0) & 0x03);
m_nFTF = ((m_nDest >> 2) & 0x03);
m_nFT = (uint8)((m_nOpcode >> 16) & 0x1F);
m_nFS = (uint8)((m_nOpcode >> 11) & 0x1F);
m_nFD = (uint8)((m_nOpcode >> 6) & 0x1F);
m_nBc = (uint8)((m_nOpcode >> 0) & 0x03);
m_nIT = m_nFT;
m_nIS = m_nFS;
m_nID = m_nFD;
m_nImm5 = m_nID;
m_nImm15 = (uint16)((m_nOpcode >> 6) & 0x7FFF);
switch((m_nOpcode >> 26) & 0x3F)
{
case 0x12:
//COP2
((this)->*(m_pOpCop2[(m_nOpcode >> 21) & 0x1F]))();
break;
case 0x36:
//LQC2
LQC2();
break;
case 0x3E:
//SQC2
SQC2();
break;
default:
Illegal();
break;
}
}
//////////////////////////////////////////////////
//General Instructions
//////////////////////////////////////////////////
//36
void CCOP_VU::LQC2()
{
if(m_nFT == 0) return;
ComputeMemAccessPageRef();
m_codeGen->PushCst(0);
m_codeGen->BeginIf(Jitter::CONDITION_NE);
{
ComputeMemAccessRef(0x10);
m_codeGen->MD_LoadFromRef();
m_codeGen->MD_PullRel(offsetof(CMIPS, m_State.nCOP2[m_nFT]));
}
m_codeGen->Else();
{
if(m_codeGen->GetCodeGen()->Has128BitsCallOperands())
{
ComputeMemAccessAddrNoXlat();
m_codeGen->PushCtx();
m_codeGen->PushIdx(1);
m_codeGen->Call(reinterpret_cast<void*>(&MemoryUtils_GetQuadProxy), 2, Jitter::CJitter::RETURN_VALUE_128);
m_codeGen->MD_PullRel(offsetof(CMIPS, m_State.nCOP2[m_nFT]));
m_codeGen->PullTop();
}
else
{
m_codeGen->Break();
}
}
m_codeGen->EndIf();
}
//3E
void CCOP_VU::SQC2()
{
ComputeMemAccessPageRef();
m_codeGen->PushCst(0);
m_codeGen->BeginIf(Jitter::CONDITION_NE);
{
ComputeMemAccessRef(0x10);
m_codeGen->MD_PushRel(offsetof(CMIPS, m_State.nCOP2[m_nFT]));
m_codeGen->MD_StoreAtRef();
}
m_codeGen->Else();
{
if(m_codeGen->GetCodeGen()->Has128BitsCallOperands())
{
ComputeMemAccessAddrNoXlat();
m_codeGen->PushCtx();
m_codeGen->MD_PushRel(offsetof(CMIPS, m_State.nCOP2[m_nFT]));
m_codeGen->PushIdx(2);
m_codeGen->Call(reinterpret_cast<void*>(&MemoryUtils_SetQuadProxy), 3, Jitter::CJitter::RETURN_VALUE_NONE);
m_codeGen->PullTop();
}
else
{
m_codeGen->Break();
}
}
m_codeGen->EndIf();
}
//////////////////////////////////////////////////
//COP2 Instructions
//////////////////////////////////////////////////
//01
void CCOP_VU::QMFC2()
{
if(m_nFT == 0) return;
for(unsigned int i = 0; i < 4; i++)
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nCOP2[m_nFS].nV[i]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nFT].nV[i]));
}
}
//02
void CCOP_VU::CFC2()
{
if(m_nFT == 0) return;
if(m_nFS < 16)
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nCOP2VI[m_nFS]));
m_codeGen->PushCst(0xFFFF);
m_codeGen->And();
}
else
{
switch(m_nFS)
{
case CTRL_REG_CLIP:
VUShared::CheckFlagPipeline(VUShared::g_pipeInfoClip, m_codeGen, VUShared::LATENCY_MAC);
m_codeGen->PushRel(offsetof(CMIPS, m_State.nCOP2CF));
break;
case CTRL_REG_STATUS:
VUShared::GetStatus(m_codeGen, offsetof(CMIPS, m_State.nCOP2T), VUShared::LATENCY_MAC);
m_codeGen->PushRel(offsetof(CMIPS, m_State.nCOP2T));
break;
case CTRL_REG_R:
m_codeGen->PushRel(offsetof(CMIPS, m_State.nCOP2R));
break;
case CTRL_REG_MAC:
VUShared::CheckFlagPipeline(VUShared::g_pipeInfoMac, m_codeGen, VUShared::LATENCY_MAC);
m_codeGen->PushRel(offsetof(CMIPS, m_State.nCOP2MF));
break;
case CTRL_REG_TPC:
m_codeGen->PushRel(offsetof(CMIPS, m_State.callMsAddr));
m_codeGen->Srl(3);
break;
case CTRL_REG_FBRST:
case CTRL_REG_VPU_STAT:
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[0].nV[0]));
break;
case CTRL_REG_I:
m_codeGen->PushRel(offsetof(CMIPS, m_State.nCOP2I));
break;
case CTRL_REG_Q:
m_codeGen->PushRel(offsetof(CMIPS, m_State.nCOP2Q));
break;
default:
assert(false);
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[0].nV[0]));
break;
}
}
m_codeGen->PushTop();
m_codeGen->SignExt();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nFT].nV[1]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nGPR[m_nFT].nV[0]));
}
//05
void CCOP_VU::QMTC2()
{
if(m_nFS == 0) return;
for(unsigned int i = 0; i < 4; i++)
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nFT].nV[i]));
m_codeGen->PullRel(offsetof(CMIPS, m_State.nCOP2[m_nFS].nV[i]));
}
}
//06
void CCOP_VU::CTC2()
{
if(m_nFS == 0)
{
//Moving stuff in VI0 register? (probably synchronizing with VU0 micro subroutine execution)
}
else if((m_nFS > 0) && (m_nFS < 16))
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nFT].nV[0]));
m_codeGen->PushCst(0xFFFF);
m_codeGen->And();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nCOP2VI[m_nFS]));
}
else
{
m_codeGen->PushRel(offsetof(CMIPS, m_State.nGPR[m_nFT].nV[0]));
switch(m_nFS)
{
case CTRL_REG_STATUS:
m_codeGen->PullTop();
VUShared::SetStatus(m_codeGen, offsetof(CMIPS, m_State.nGPR[m_nFT].nV[0]));
break;
case CTRL_REG_MAC:
//Read-only register
m_codeGen->PullTop();
break;
case CTRL_REG_CLIP:
m_codeGen->PushCst(0xFFFFFF);
m_codeGen->And();
m_codeGen->PushTop();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nCOP2CF));
VUShared::ResetFlagPipeline(VUShared::g_pipeInfoClip, m_codeGen);
break;
case CTRL_REG_R:
m_codeGen->PushCst(0x7FFFFF);
m_codeGen->And();
m_codeGen->PullRel(offsetof(CMIPS, m_State.nCOP2R));
break;
case CTRL_REG_I:
m_codeGen->PullRel(offsetof(CMIPS, m_State.nCOP2I));
break;
case CTRL_REG_Q:
m_codeGen->PullRel(VUShared::g_pipeInfoQ.heldValue);
VUShared::FlushPipeline(VUShared::g_pipeInfoQ, m_codeGen);
break;
case CTRL_REG_CMSAR0:
m_codeGen->PushCst(0xFFFF);
m_codeGen->And();
m_codeGen->PullRel(offsetof(CMIPS, m_State.cmsar0));
break;
case CTRL_REG_FBRST:
//Don't care
m_codeGen->PullTop();
break;
case CTRL_REG_CMSAR1:
{
m_codeGen->PushCst(0xFFFF);
m_codeGen->And();
uint32 valueCursor = m_codeGen->GetTopCursor();
//Push context
m_codeGen->PushCtx();
//Push value
m_codeGen->PushCursor(valueCursor);
//Compute Address
m_codeGen->PushCst(CVpu::VU_CMSAR1);
m_codeGen->Call(reinterpret_cast<void*>(&MemoryUtils_SetWordProxy), 3, false);
//Clear stack
assert(m_codeGen->GetTopCursor() == valueCursor);
m_codeGen->PullTop();
}
break;
default:
assert(false);
m_codeGen->PullTop();
break;
}
}
}
//08
void CCOP_VU::BC2()
{
//Not implemented
//We assume that this is used to check if VU0 is still running
//after VCALLMS* is used (used in .hack games)
//Also used in Kya: Dark Lineage
//For now, we just make it as if VU0 is not running
uint32 op = (m_nOpcode >> 16) & 0x03;
switch(op)
{
case 0x00:
//BC2F
//(running == false) -> Branch
m_codeGen->PushCst(0);
m_codeGen->PushCst(0);
Branch(Jitter::CONDITION_EQ);
break;
case 0x01:
//BC2T
//(running == false) -> Do not branch
break;
default:
Illegal();
break;
}
}
//10-1F
void CCOP_VU::V()
{
((this)->*(m_pOpVector[(m_nOpcode & 0x3F)]))();
}
//////////////////////////////////////////////////
//Vector Instructions
//////////////////////////////////////////////////
//00
//01
//02
//03
void CCOP_VU::VADDbc()
{
VUShared::ADDbc(m_codeGen, m_nDest, m_nFD, m_nFS, m_nFT, m_nBc, 0, 0);
}
//04
//05
//06
//07
void CCOP_VU::VSUBbc()
{
VUShared::SUBbc(m_codeGen, m_nDest, m_nFD, m_nFS, m_nFT, m_nBc, 0, 0);
}
//08
//09
//0A
//0B
void CCOP_VU::VMADDbc()
{
VUShared::MADDbc(m_codeGen, m_nDest, m_nFD, m_nFS, m_nFT, m_nBc, 0, 0);
}
//0C
//0D
//0E
//0F
void CCOP_VU::VMSUBbc()
{
VUShared::MSUBbc(m_codeGen, m_nDest, m_nFD, m_nFS, m_nFT, m_nBc, 0, 0);
}
//10
//11
//12
//13
void CCOP_VU::VMAXbc()
{
VUShared::MAXbc(m_codeGen, m_nDest, m_nFD, m_nFS, m_nFT, m_nBc);
}
//14
//15
//16
//17
void CCOP_VU::VMINIbc()
{
VUShared::MINIbc(m_codeGen, m_nDest, m_nFD, m_nFS, m_nFT, m_nBc);
}
//18
//19
//1A
//1B
void CCOP_VU::VMULbc()
{
VUShared::MULbc(m_codeGen, m_nDest, m_nFD, m_nFS, m_nFT, m_nBc, 0, 0);
}
//1C
void CCOP_VU::VMULq()
{
VUShared::MULq(m_codeGen, m_nDest, m_nFD, m_nFS, 0, 0);
}
//1D
void CCOP_VU::VMAXi()
{
VUShared::MAXi(m_codeGen, m_nDest, m_nFD, m_nFS);
}
//1E
void CCOP_VU::VMULi()
{
VUShared::MULi(m_codeGen, m_nDest, m_nFD, m_nFS, 0, 0);
}
//1F
void CCOP_VU::VMINIi()
{
VUShared::MINIi(m_codeGen, m_nDest, m_nFD, m_nFS);
}
//20
void CCOP_VU::VADDq()
{
VUShared::ADDq(m_codeGen, m_nDest, m_nFD, m_nFS, 0, 0);
}
//21
void CCOP_VU::VMADDq()
{
VUShared::MADDq(m_codeGen, m_nDest, m_nFD, m_nFS, 0, 0);
}
//22
void CCOP_VU::VADDi()
{
VUShared::ADDi(m_codeGen, m_nDest, m_nFD, m_nFS, 0, 0);
}
//23
void CCOP_VU::VMADDi()
{
VUShared::MADDi(m_codeGen, m_nDest, m_nFD, m_nFS, 0, 0);
}
//24
void CCOP_VU::VSUBq()
{
VUShared::SUBq(m_codeGen, m_nDest, m_nFD, m_nFS, 0, 0);
}
//25
void CCOP_VU::VMSUBq()
{
VUShared::MSUBq(m_codeGen, m_nDest, m_nFD, m_nFS, 0, 0);
}
//26
void CCOP_VU::VSUBi()
{
VUShared::SUBi(m_codeGen, m_nDest, m_nFD, m_nFS, 0, 0);
}
//27
void CCOP_VU::VMSUBi()
{
VUShared::MSUBi(m_codeGen, m_nDest, m_nFD, m_nFS, 0, 0);
}
//28
void CCOP_VU::VADD()
{
VUShared::ADD(m_codeGen, m_nDest, m_nFD, m_nFS, m_nFT, 0, 0);
}
//29
void CCOP_VU::VMADD()
{
VUShared::MADD(m_codeGen, m_nDest, m_nFD, m_nFS, m_nFT, 0, 0);
}
//2A
void CCOP_VU::VMUL()
{
VUShared::MUL(m_codeGen, m_nDest, m_nFD, m_nFS, m_nFT, 0, 0);
}
//2B
void CCOP_VU::VMAX()
{
VUShared::MAX(m_codeGen, m_nDest, m_nFD, m_nFS, m_nFT);
}
//2C
void CCOP_VU::VSUB()
{
VUShared::SUB(m_codeGen, m_nDest, m_nFD, m_nFS, m_nFT, 0, 0);
}
//2D
void CCOP_VU::VMSUB()
{
VUShared::MSUB(m_codeGen, m_nDest, m_nFD, m_nFS, m_nFT, 0, 0);
}
//2E
void CCOP_VU::VOPMSUB()
{
VUShared::OPMSUB(m_codeGen, m_nFD, m_nFS, m_nFT, 0, 0);
}
//2F
void CCOP_VU::VMINI()
{
VUShared::MINI(m_codeGen, m_nDest, m_nFD, m_nFS, m_nFT);
}
//30
void CCOP_VU::VIADD()
{
VUShared::IADD(m_codeGen, m_nID, m_nIS, m_nIT);
}
//31
void CCOP_VU::VISUB()
{
VUShared::ISUB(m_codeGen, m_nID, m_nIS, m_nIT);
}
//32
void CCOP_VU::VIADDI()
{
VUShared::IADDI(m_codeGen, m_nIT, m_nIS, m_nImm5);
}
//34
void CCOP_VU::VIAND()
{
VUShared::IAND(m_codeGen, m_nID, m_nIS, m_nIT);
}
//35
void CCOP_VU::VIOR()
{
VUShared::IOR(m_codeGen, m_nID, m_nIS, m_nIT);
}
//38
void CCOP_VU::VCALLMS()
{
m_codeGen->PushCst(1);
m_codeGen->PullRel(offsetof(CMIPS, m_State.callMsEnabled));
m_codeGen->PushCst(static_cast<uint32>(m_nImm15) * 8);
m_codeGen->PullRel(offsetof(CMIPS, m_State.callMsAddr));
m_codeGen->PushCst(MIPS_EXCEPTION_CALLMS);
m_codeGen->PullRel(offsetof(CMIPS, m_State.nHasException));
}
//39
void CCOP_VU::VCALLMSR()
{
m_codeGen->PushCst(1);
m_codeGen->PullRel(offsetof(CMIPS, m_State.callMsEnabled));
m_codeGen->PushRel(offsetof(CMIPS, m_State.cmsar0));
m_codeGen->Shl(3);
m_codeGen->PullRel(offsetof(CMIPS, m_State.callMsAddr));
m_codeGen->PushCst(MIPS_EXCEPTION_CALLMS);
m_codeGen->PullRel(offsetof(CMIPS, m_State.nHasException));
}
//3C
void CCOP_VU::VX0()
{
((this)->*(m_pOpVx0[(m_nOpcode >> 6) & 0x1F]))();
}
//3D
void CCOP_VU::VX1()
{
((this)->*(m_pOpVx1[(m_nOpcode >> 6) & 0x1F]))();
}
//3E
void CCOP_VU::VX2()
{
((this)->*(m_pOpVx2[(m_nOpcode >> 6) & 0x1F]))();
}
//3F
void CCOP_VU::VX3()
{
((this)->*(m_pOpVx3[(m_nOpcode >> 6) & 0x1F]))();
}
//////////////////////////////////////////////////
//Vx Common Instructions
//////////////////////////////////////////////////
//
void CCOP_VU::VADDAbc()
{
VUShared::ADDAbc(m_codeGen, m_nDest, m_nFS, m_nFT, m_nBc, 0, 0);
}
//
void CCOP_VU::VSUBAbc()
{
VUShared::SUBAbc(m_codeGen, m_nDest, m_nFS, m_nFT, m_nBc, 0, 0);
}
//
void CCOP_VU::VMADDAbc()
{
VUShared::MADDAbc(m_codeGen, m_nDest, m_nFS, m_nFT, m_nBc, 0, 0);
}
//
void CCOP_VU::VMSUBAbc()
{
VUShared::MSUBAbc(m_codeGen, m_nDest, m_nFS, m_nFT, m_nBc, 0, 0);
}
//
void CCOP_VU::VMULAbc()
{
VUShared::MULAbc(m_codeGen, m_nDest, m_nFS, m_nFT, m_nBc, 0, 0);
}
//////////////////////////////////////////////////
//V0 Instructions
//////////////////////////////////////////////////
//04
void CCOP_VU::VITOF0()
{
VUShared::ITOF0(m_codeGen, m_nDest, m_nFT, m_nFS);
}
//05
void CCOP_VU::VFTOI0()
{
VUShared::FTOI0(m_codeGen, m_nDest, m_nFT, m_nFS);
}
//07
void CCOP_VU::VMULAq()
{
VUShared::MULAq(m_codeGen, m_nDest, m_nFS, 0, 0);
}
//0A
void CCOP_VU::VADDA()
{
VUShared::ADDA(m_codeGen, m_nDest, m_nFS, m_nFT, 0, 0);
}
//0B
void CCOP_VU::VSUBA()
{
VUShared::SUBA(m_codeGen, m_nDest, m_nFS, m_nFT, 0, 0);
}
//0C
void CCOP_VU::VMOVE()
{
VUShared::MOVE(m_codeGen, m_nDest, m_nFT, m_nFS);
}
//0D
void CCOP_VU::VLQI()
{
VUShared::LQI(m_codeGen, m_nDest, m_nIT, m_nIS, m_vuMemAddressMask);
}
//0E
void CCOP_VU::VDIV()
{
VUShared::DIV(m_codeGen, m_nFS, m_nFSF, m_nFT, m_nFTF, 0);
VUShared::FlushPipeline(VUShared::g_pipeInfoQ, m_codeGen);
}
//0F
void CCOP_VU::VMTIR()
{
VUShared::MTIR(m_codeGen, m_nIT, m_nIS, m_nFSF);
}
//10
void CCOP_VU::VRNEXT()
{
VUShared::RNEXT(m_codeGen, m_nDest, m_nFT);
}
//////////////////////////////////////////////////
//V1 Instructions
//////////////////////////////////////////////////
//04
void CCOP_VU::VITOF4()
{
VUShared::ITOF4(m_codeGen, m_nDest, m_nFT, m_nFS);
}
//05
void CCOP_VU::VFTOI4()
{
VUShared::FTOI4(m_codeGen, m_nDest, m_nFT, m_nFS);
}
//07
void CCOP_VU::VABS()
{
VUShared::ABS(m_codeGen, m_nDest, m_nFT, m_nFS);
}
//08
void CCOP_VU::VMADDAq()
{
VUShared::MADDAq(m_codeGen, m_nDest, m_nFS, 0, 0);
}
//09
void CCOP_VU::VMSUBAq()
{
VUShared::MSUBAq(m_codeGen, m_nDest, m_nFS, 0, 0);
}
//0A
void CCOP_VU::VMADDA()
{
VUShared::MADDA(m_codeGen, m_nDest, m_nFS, m_nFT, 0, 0);
}
//0B
void CCOP_VU::VMSUBA()
{
VUShared::MSUBA(m_codeGen, m_nDest, m_nFS, m_nFT, 0, 0);
}
//0C
void CCOP_VU::VMR32()
{
VUShared::MR32(m_codeGen, m_nDest, m_nFT, m_nFS);
}
//0D
void CCOP_VU::VSQI()
{
VUShared::SQI(m_codeGen, m_nDest, m_nIS, m_nIT, m_vuMemAddressMask);
}
//0E
void CCOP_VU::VSQRT()
{
VUShared::SQRT(m_codeGen, m_nFT, m_nFTF, 0);
VUShared::FlushPipeline(VUShared::g_pipeInfoQ, m_codeGen);
}
//0F
void CCOP_VU::VMFIR()
{
VUShared::MFIR(m_codeGen, m_nDest, m_nIT, m_nIS);
}
//10
void CCOP_VU::VRGET()
{
VUShared::RGET(m_codeGen, m_nDest, m_nFT);
}
//////////////////////////////////////////////////
//V2 Instructions
//////////////////////////////////////////////////
//04
void CCOP_VU::VITOF12()
{
VUShared::ITOF12(m_codeGen, m_nDest, m_nFT, m_nFS);
}
//05
void CCOP_VU::VFTOI12()
{
VUShared::FTOI12(m_codeGen, m_nDest, m_nFT, m_nFS);
}
//07
void CCOP_VU::VMULAi()
{
VUShared::MULAi(m_codeGen, m_nDest, m_nFS, 0, 0);
}
//08
void CCOP_VU::VADDAi()
{
VUShared::ADDAi(m_codeGen, m_nDest, m_nFS, 0, 0);
}
//09
void CCOP_VU::VSUBAi()
{
VUShared::SUBAi(m_codeGen, m_nDest, m_nFS, 0, 0);
}
//0A
void CCOP_VU::VMULA()
{
VUShared::MULA(m_codeGen, m_nDest, m_nFS, m_nFT, 0, 0);
}
//0B
void CCOP_VU::VOPMULA()
{
VUShared::OPMULA(m_codeGen, m_nFS, m_nFT);
}
//0D
void CCOP_VU::VLQD()
{
VUShared::LQD(m_codeGen, m_nDest, m_nIT, m_nIS, m_vuMemAddressMask);
}
//0E
void CCOP_VU::VRSQRT()
{
VUShared::RSQRT(m_codeGen, m_nFS, m_nFSF, m_nFT, m_nFTF, 0);
VUShared::FlushPipeline(VUShared::g_pipeInfoQ, m_codeGen);
}
//0F
void CCOP_VU::VILWR()
{
VUShared::ILWR(m_codeGen, m_nDest, m_nIT, m_nIS, m_vuMemAddressMask);
}
//10
void CCOP_VU::VRINIT()
{
VUShared::RINIT(m_codeGen, m_nFS, m_nFSF);
}
//////////////////////////////////////////////////
//V3 Instructions
//////////////////////////////////////////////////
//04
void CCOP_VU::VITOF15()
{
VUShared::ITOF15(m_codeGen, m_nDest, m_nFT, m_nFS);
}
//05
void CCOP_VU::VFTOI15()
{
VUShared::FTOI15(m_codeGen, m_nDest, m_nFT, m_nFS);
}
//07
void CCOP_VU::VCLIP()
{
VUShared::CLIP(m_codeGen, m_nFS, m_nFT, 0);
}
//08
void CCOP_VU::VMADDAi()
{
VUShared::MADDAi(m_codeGen, m_nDest, m_nFS, 0, 0);
}
//09
void CCOP_VU::VMSUBAi()
{
VUShared::MSUBAi(m_codeGen, m_nDest, m_nFS, 0, 0);
}
//0B
void CCOP_VU::VNOP()
{
//Nothing to do
}
//0D
void CCOP_VU::VSQD()
{
VUShared::SQD(m_codeGen, m_nDest, m_nIS, m_nIT, m_vuMemAddressMask);
}
//0E
void CCOP_VU::VWAITQ()
{
VUShared::WAITQ(m_codeGen);
}
//0F
void CCOP_VU::VISWR()
{
VUShared::ISWR(m_codeGen, m_nDest, m_nIT, m_nIS, m_vuMemAddressMask);
}
//10
void CCOP_VU::VRXOR()
{
VUShared::RXOR(m_codeGen, m_nFS, m_nFSF);
}
//////////////////////////////////////////////////
//Opcode Tables
//////////////////////////////////////////////////
// clang-format off
CCOP_VU::InstructionFuncConstant CCOP_VU::m_pOpCop2[0x20] =
{
//0x00
&CCOP_VU::Illegal, &CCOP_VU::QMFC2, &CCOP_VU::CFC2, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::QMTC2, &CCOP_VU::CTC2, &CCOP_VU::Illegal,
//0x08
&CCOP_VU::BC2, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal,
//0x10
&CCOP_VU::V, &CCOP_VU::V, &CCOP_VU::V, &CCOP_VU::V, &CCOP_VU::V, &CCOP_VU::V, &CCOP_VU::V, &CCOP_VU::V,
//0x18
&CCOP_VU::V, &CCOP_VU::V, &CCOP_VU::V, &CCOP_VU::V, &CCOP_VU::V, &CCOP_VU::V, &CCOP_VU::V, &CCOP_VU::V,
};
CCOP_VU::InstructionFuncConstant CCOP_VU::m_pOpVector[0x40] =
{
//0x00
&CCOP_VU::VADDbc, &CCOP_VU::VADDbc, &CCOP_VU::VADDbc, &CCOP_VU::VADDbc, &CCOP_VU::VSUBbc, &CCOP_VU::VSUBbc, &CCOP_VU::VSUBbc, &CCOP_VU::VSUBbc,
//0x08
&CCOP_VU::VMADDbc, &CCOP_VU::VMADDbc, &CCOP_VU::VMADDbc, &CCOP_VU::VMADDbc, &CCOP_VU::VMSUBbc, &CCOP_VU::VMSUBbc, &CCOP_VU::VMSUBbc, &CCOP_VU::VMSUBbc,
//0x10
&CCOP_VU::VMAXbc, &CCOP_VU::VMAXbc, &CCOP_VU::VMAXbc, &CCOP_VU::VMAXbc, &CCOP_VU::VMINIbc, &CCOP_VU::VMINIbc, &CCOP_VU::VMINIbc, &CCOP_VU::VMINIbc,
//0x18
&CCOP_VU::VMULbc, &CCOP_VU::VMULbc, &CCOP_VU::VMULbc, &CCOP_VU::VMULbc, &CCOP_VU::VMULq, &CCOP_VU::VMAXi, &CCOP_VU::VMULi, &CCOP_VU::VMINIi,
//0x20
&CCOP_VU::VADDq, &CCOP_VU::VMADDq, &CCOP_VU::VADDi, &CCOP_VU::VMADDi, &CCOP_VU::VSUBq, &CCOP_VU::VMSUBq, &CCOP_VU::VSUBi, &CCOP_VU::VMSUBi,
//0x28
&CCOP_VU::VADD, &CCOP_VU::VMADD, &CCOP_VU::VMUL, &CCOP_VU::VMAX, &CCOP_VU::VSUB, &CCOP_VU::VMSUB, &CCOP_VU::VOPMSUB, &CCOP_VU::VMINI,
//0x30
&CCOP_VU::VIADD, &CCOP_VU::VISUB, &CCOP_VU::VIADDI, &CCOP_VU::Illegal, &CCOP_VU::VIAND, &CCOP_VU::VIOR, &CCOP_VU::Illegal, &CCOP_VU::Illegal,
//0x38
&CCOP_VU::VCALLMS, &CCOP_VU::VCALLMSR, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::VX0, &CCOP_VU::VX1, &CCOP_VU::VX2, &CCOP_VU::VX3,
};
CCOP_VU::InstructionFuncConstant CCOP_VU::m_pOpVx0[0x20] =
{
//0x00
&CCOP_VU::VADDAbc, &CCOP_VU::VSUBAbc, &CCOP_VU::VMADDAbc, &CCOP_VU::VMSUBAbc, &CCOP_VU::VITOF0, &CCOP_VU::VFTOI0, &CCOP_VU::VMULAbc, &CCOP_VU::VMULAq,
//0x08
&CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::VADDA, &CCOP_VU::VSUBA, &CCOP_VU::VMOVE, &CCOP_VU::VLQI, &CCOP_VU::VDIV, &CCOP_VU::VMTIR,
//0x10
&CCOP_VU::VRNEXT, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal,
//0x18
&CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal,
};
CCOP_VU::InstructionFuncConstant CCOP_VU::m_pOpVx1[0x20] =
{
//0x00
&CCOP_VU::VADDAbc, &CCOP_VU::VSUBAbc, &CCOP_VU::VMADDAbc, &CCOP_VU::VMSUBAbc, &CCOP_VU::VITOF4, &CCOP_VU::VFTOI4, &CCOP_VU::VMULAbc, &CCOP_VU::VABS,
//0x08
&CCOP_VU::VMADDAq, &CCOP_VU::VMSUBAq, &CCOP_VU::VMADDA, &CCOP_VU::VMSUBA, &CCOP_VU::VMR32, &CCOP_VU::VSQI, &CCOP_VU::VSQRT, &CCOP_VU::VMFIR,
//0x10
&CCOP_VU::VRGET, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal,
//0x18
&CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal,
};
CCOP_VU::InstructionFuncConstant CCOP_VU::m_pOpVx2[0x20] =
{
//0x00
&CCOP_VU::VADDAbc, &CCOP_VU::VSUBAbc, &CCOP_VU::VMADDAbc, &CCOP_VU::VMSUBAbc, &CCOP_VU::VITOF12, &CCOP_VU::VFTOI12, &CCOP_VU::VMULAbc, &CCOP_VU::VMULAi,
//0x08
&CCOP_VU::VADDAi, &CCOP_VU::VSUBAi, &CCOP_VU::VMULA, &CCOP_VU::VOPMULA, &CCOP_VU::Illegal, &CCOP_VU::VLQD, &CCOP_VU::VRSQRT, &CCOP_VU::VILWR,
//0x10
&CCOP_VU::VRINIT, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal,
//0x18
&CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal,
};
CCOP_VU::InstructionFuncConstant CCOP_VU::m_pOpVx3[0x20] =
{
//0x00
&CCOP_VU::VADDAbc, &CCOP_VU::VSUBAbc, &CCOP_VU::VMADDAbc, &CCOP_VU::VMSUBAbc, &CCOP_VU::VITOF15, &CCOP_VU::VFTOI15, &CCOP_VU::VMULAbc, &CCOP_VU::VCLIP,
//0x08
&CCOP_VU::VMADDAi, &CCOP_VU::VMSUBAi, &CCOP_VU::Illegal, &CCOP_VU::VNOP, &CCOP_VU::Illegal, &CCOP_VU::VSQD, &CCOP_VU::VWAITQ, &CCOP_VU::VISWR,
//0x10
&CCOP_VU::VRXOR, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal,
//0x18
&CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal, &CCOP_VU::Illegal,
};
// clang-format on
|
/*=============================================================================
Copyright (c) 2011-2019 Bolero MURAKAMI
https://github.com/bolero-MURAKAMI/Sprout
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 SPROUT_LIBS_ALGORITHM_TEST_MIN_ELEMENT_CPP
#define SPROUT_LIBS_ALGORITHM_TEST_MIN_ELEMENT_CPP
#include <sprout/algorithm/min_element.hpp>
#include <sprout/array.hpp>
#include <sprout/container.hpp>
#include <testspr/tools.hpp>
namespace testspr {
static void algorithm_min_element_test() {
using namespace sprout;
{
SPROUT_STATIC_CONSTEXPR auto arr1 = array<int, 10>{{6, 5, 7, 4, 8, 3, 9, 2, 10, 1}};
{
SPROUT_STATIC_CONSTEXPR auto result = sprout::min_element(
sprout::begin(arr1),
sprout::end(arr1)
);
TESTSPR_BOTH_ASSERT(result == sprout::begin(arr1) + 9);
}
{
SPROUT_STATIC_CONSTEXPR auto result = sprout::min_element(
sprout::begin(arr1),
sprout::begin(arr1) + 5
);
TESTSPR_BOTH_ASSERT(result == sprout::begin(arr1) + 3);
}
{
SPROUT_STATIC_CONSTEXPR auto result = sprout::min_element(
sprout::begin(arr1),
sprout::end(arr1),
testspr::less<int>()
);
TESTSPR_BOTH_ASSERT(result == sprout::begin(arr1) + 9);
}
{
SPROUT_STATIC_CONSTEXPR auto result = sprout::min_element(
sprout::begin(arr1),
sprout::begin(arr1) + 5,
testspr::less<int>()
);
TESTSPR_BOTH_ASSERT(result == sprout::begin(arr1) + 3);
}
{
SPROUT_STATIC_CONSTEXPR auto result = sprout::min_element(
testspr::reduce_forward(sprout::begin(arr1)),
testspr::reduce_forward(sprout::end(arr1))
).base();
TESTSPR_BOTH_ASSERT(result == sprout::begin(arr1) + 9);
}
{
SPROUT_STATIC_CONSTEXPR auto result = sprout::min_element(
testspr::reduce_forward(sprout::begin(arr1)),
testspr::reduce_forward(sprout::begin(arr1) + 5)
).base();
TESTSPR_BOTH_ASSERT(result == sprout::begin(arr1) + 3);
}
{
SPROUT_STATIC_CONSTEXPR auto result = sprout::min_element(
testspr::reduce_forward(sprout::begin(arr1)),
testspr::reduce_forward(sprout::end(arr1)),
testspr::less<int>()
).base();
TESTSPR_BOTH_ASSERT(result == sprout::begin(arr1) + 9);
}
{
SPROUT_STATIC_CONSTEXPR auto result = sprout::min_element(
testspr::reduce_forward(sprout::begin(arr1)),
testspr::reduce_forward(sprout::begin(arr1) + 5),
testspr::less<int>()
).base();
TESTSPR_BOTH_ASSERT(result == sprout::begin(arr1) + 3);
}
{
SPROUT_STATIC_CONSTEXPR auto result = sprout::min_element(
testspr::reduce_random_access(sprout::begin(arr1)),
testspr::reduce_random_access(sprout::end(arr1))
).base();
TESTSPR_BOTH_ASSERT(result == sprout::begin(arr1) + 9);
}
{
SPROUT_STATIC_CONSTEXPR auto result = sprout::min_element(
testspr::reduce_random_access(sprout::begin(arr1)),
testspr::reduce_random_access(sprout::begin(arr1) + 5)
).base();
TESTSPR_BOTH_ASSERT(result == sprout::begin(arr1) + 3);
}
{
SPROUT_STATIC_CONSTEXPR auto result = sprout::min_element(
testspr::reduce_random_access(sprout::begin(arr1)),
testspr::reduce_random_access(sprout::end(arr1)),
testspr::less<int>()
).base();
TESTSPR_BOTH_ASSERT(result == sprout::begin(arr1) + 9);
}
{
SPROUT_STATIC_CONSTEXPR auto result = sprout::min_element(
testspr::reduce_random_access(sprout::begin(arr1)),
testspr::reduce_random_access(sprout::begin(arr1) + 5),
testspr::less<int>()
).base();
TESTSPR_BOTH_ASSERT(result == sprout::begin(arr1) + 3);
}
}
}
} // namespace testspr
#ifndef TESTSPR_CPP_INCLUDE
# define TESTSPR_TEST_FUNCTION testspr::algorithm_min_element_test
# include <testspr/include_main.hpp>
#endif
#endif // #ifndef SPROUT_LIBS_ALGORITHM_TEST_MIN_ELEMENT_CPP
|
// Copyright (c) 2020-2021 The Eleccoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <qt/eleccoingui.h>
#include <qt/eleccoinunits.h>
#include <qt/clientmodel.h>
#include <qt/createwalletdialog.h>
#include <qt/guiconstants.h>
#include <qt/guiutil.h>
#include <qt/modaloverlay.h>
#include <qt/networkstyle.h>
#include <qt/notificator.h>
#include <qt/openuridialog.h>
#include <qt/optionsdialog.h>
#include <qt/optionsmodel.h>
#include <qt/platformstyle.h>
#include <qt/rpcconsole.h>
#include <qt/utilitydialog.h>
#ifdef ENABLE_WALLET
#include <qt/walletcontroller.h>
#include <qt/walletframe.h>
#include <qt/walletmodel.h>
#include <qt/walletview.h>
#endif // ENABLE_WALLET
#ifdef Q_OS_MAC
#include <qt/macdockiconhandler.h>
#endif
#include <functional>
#include <chain.h>
#include <chainparams.h>
#include <interfaces/handler.h>
#include <interfaces/node.h>
#include <node/ui_interface.h>
#include <util/system.h>
#include <util/translation.h>
#include <validation.h>
#include <QAction>
#include <QApplication>
#include <QComboBox>
#include <QCursor>
#include <QDateTime>
#include <QDragEnterEvent>
#include <QListWidget>
#include <QMenu>
#include <QMenuBar>
#include <QMessageBox>
#include <QMimeData>
#include <QProgressDialog>
#include <QScreen>
#include <QSettings>
#include <QShortcut>
#include <QStackedWidget>
#include <QStatusBar>
#include <QStyle>
#include <QSystemTrayIcon>
#include <QTimer>
#include <QToolBar>
#include <QUrlQuery>
#include <QVBoxLayout>
#include <QWindow>
const std::string EleccoinGUI::DEFAULT_UIPLATFORM =
#if defined(Q_OS_MAC)
"macosx"
#elif defined(Q_OS_WIN)
"windows"
#else
"other"
#endif
;
EleccoinGUI::EleccoinGUI(interfaces::Node& node, const PlatformStyle *_platformStyle, const NetworkStyle *networkStyle, QWidget *parent) :
QMainWindow(parent),
m_node(node),
trayIconMenu{new QMenu()},
platformStyle(_platformStyle),
m_network_style(networkStyle)
{
QSettings settings;
if (!restoreGeometry(settings.value("MainWindowGeometry").toByteArray())) {
// Restore failed (perhaps missing setting), center the window
move(QGuiApplication::primaryScreen()->availableGeometry().center() - frameGeometry().center());
}
setContextMenuPolicy(Qt::PreventContextMenu);
#ifdef ENABLE_WALLET
enableWallet = WalletModel::isWalletEnabled();
#endif // ENABLE_WALLET
QApplication::setWindowIcon(m_network_style->getTrayAndWindowIcon());
setWindowIcon(m_network_style->getTrayAndWindowIcon());
updateWindowTitle();
rpcConsole = new RPCConsole(node, _platformStyle, nullptr);
helpMessageDialog = new HelpMessageDialog(this, false);
#ifdef ENABLE_WALLET
if(enableWallet)
{
/** Create wallet frame and make it the central widget */
walletFrame = new WalletFrame(_platformStyle, this);
connect(walletFrame, &WalletFrame::createWalletButtonClicked, [this] {
auto activity = new CreateWalletActivity(getWalletController(), this);
connect(activity, &CreateWalletActivity::finished, activity, &QObject::deleteLater);
activity->create();
});
setCentralWidget(walletFrame);
} else
#endif // ENABLE_WALLET
{
/* When compiled without wallet or -disablewallet is provided,
* the central widget is the rpc console.
*/
setCentralWidget(rpcConsole);
Q_EMIT consoleShown(rpcConsole);
}
modalOverlay = new ModalOverlay(enableWallet, this->centralWidget());
// Accept D&D of URIs
setAcceptDrops(true);
// Create actions for the toolbar, menu bar and tray/dock icon
// Needs walletFrame to be initialized
createActions();
// Create application menu bar
createMenuBar();
// Create the toolbars
createToolBars();
// Create system tray icon and notification
if (QSystemTrayIcon::isSystemTrayAvailable()) {
createTrayIcon();
}
notificator = new Notificator(QApplication::applicationName(), trayIcon, this);
// Create status bar
statusBar();
// Disable size grip because it looks ugly and nobody needs it
statusBar()->setSizeGripEnabled(false);
// Status bar notification icons
QFrame *frameBlocks = new QFrame();
frameBlocks->setContentsMargins(0,0,0,0);
frameBlocks->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);
QHBoxLayout *frameBlocksLayout = new QHBoxLayout(frameBlocks);
frameBlocksLayout->setContentsMargins(3,0,3,0);
frameBlocksLayout->setSpacing(3);
unitDisplayControl = new UnitDisplayStatusBarControl(platformStyle);
labelWalletEncryptionIcon = new GUIUtil::ThemedLabel(platformStyle);
labelWalletHDStatusIcon = new GUIUtil::ThemedLabel(platformStyle);
labelProxyIcon = new GUIUtil::ClickableLabel(platformStyle);
connectionsControl = new GUIUtil::ClickableLabel(platformStyle);
labelBlocksIcon = new GUIUtil::ClickableLabel(platformStyle);
if(enableWallet)
{
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(unitDisplayControl);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelWalletEncryptionIcon);
frameBlocksLayout->addWidget(labelWalletHDStatusIcon);
}
frameBlocksLayout->addWidget(labelProxyIcon);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(connectionsControl);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelBlocksIcon);
frameBlocksLayout->addStretch();
// Progress bar and label for blocks download
progressBarLabel = new QLabel();
progressBarLabel->setVisible(false);
progressBar = new GUIUtil::ProgressBar();
progressBar->setAlignment(Qt::AlignCenter);
progressBar->setVisible(false);
// Override style sheet for progress bar for styles that have a segmented progress bar,
// as they make the text unreadable (workaround for issue #1071)
// See https://doc.qt.io/qt-5/gallery.html
QString curStyle = QApplication::style()->metaObject()->className();
if(curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle")
{
progressBar->setStyleSheet("QProgressBar { background-color: #e8e8e8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #FF8000, stop: 1 orange); border-radius: 7px; margin: 0px; }");
}
statusBar()->addWidget(progressBarLabel);
statusBar()->addWidget(progressBar);
statusBar()->addPermanentWidget(frameBlocks);
// Install event filter to be able to catch status tip events (QEvent::StatusTip)
this->installEventFilter(this);
// Initially wallet actions should be disabled
setWalletActionsEnabled(false);
// Subscribe to notifications from core
subscribeToCoreSignals();
connect(labelProxyIcon, &GUIUtil::ClickableLabel::clicked, [this] {
openOptionsDialogWithTab(OptionsDialog::TAB_NETWORK);
});
connect(labelBlocksIcon, &GUIUtil::ClickableLabel::clicked, this, &EleccoinGUI::showModalOverlay);
connect(progressBar, &GUIUtil::ClickableProgressBar::clicked, this, &EleccoinGUI::showModalOverlay);
#ifdef Q_OS_MAC
m_app_nap_inhibitor = new CAppNapInhibitor;
#endif
GUIUtil::handleCloseWindowShortcut(this);
}
EleccoinGUI::~EleccoinGUI()
{
// Unsubscribe from notifications from core
unsubscribeFromCoreSignals();
QSettings settings;
settings.setValue("MainWindowGeometry", saveGeometry());
if(trayIcon) // Hide tray icon, as deleting will let it linger until quit (on Ubuntu)
trayIcon->hide();
#ifdef Q_OS_MAC
delete m_app_nap_inhibitor;
delete appMenuBar;
MacDockIconHandler::cleanup();
#endif
delete rpcConsole;
}
void EleccoinGUI::createActions()
{
QActionGroup *tabGroup = new QActionGroup(this);
connect(modalOverlay, &ModalOverlay::triggered, tabGroup, &QActionGroup::setEnabled);
overviewAction = new QAction(platformStyle->SingleColorIcon(":/icons/overview"), tr("&Overview"), this);
overviewAction->setStatusTip(tr("Show general overview of wallet"));
overviewAction->setToolTip(overviewAction->statusTip());
overviewAction->setCheckable(true);
overviewAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_1));
tabGroup->addAction(overviewAction);
sendCoinsAction = new QAction(platformStyle->SingleColorIcon(":/icons/send"), tr("&Send"), this);
sendCoinsAction->setStatusTip(tr("Send coins to a Eleccoin address"));
sendCoinsAction->setToolTip(sendCoinsAction->statusTip());
sendCoinsAction->setCheckable(true);
sendCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_2));
tabGroup->addAction(sendCoinsAction);
sendCoinsMenuAction = new QAction(sendCoinsAction->text(), this);
sendCoinsMenuAction->setStatusTip(sendCoinsAction->statusTip());
sendCoinsMenuAction->setToolTip(sendCoinsMenuAction->statusTip());
receiveCoinsAction = new QAction(platformStyle->SingleColorIcon(":/icons/receiving_addresses"), tr("&Receive"), this);
receiveCoinsAction->setStatusTip(tr("Request payments (generates QR codes and eleccoin: URIs)"));
receiveCoinsAction->setToolTip(receiveCoinsAction->statusTip());
receiveCoinsAction->setCheckable(true);
receiveCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_3));
tabGroup->addAction(receiveCoinsAction);
receiveCoinsMenuAction = new QAction(receiveCoinsAction->text(), this);
receiveCoinsMenuAction->setStatusTip(receiveCoinsAction->statusTip());
receiveCoinsMenuAction->setToolTip(receiveCoinsMenuAction->statusTip());
historyAction = new QAction(platformStyle->SingleColorIcon(":/icons/history"), tr("&Transactions"), this);
historyAction->setStatusTip(tr("Browse transaction history"));
historyAction->setToolTip(historyAction->statusTip());
historyAction->setCheckable(true);
historyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_4));
tabGroup->addAction(historyAction);
#ifdef ENABLE_WALLET
// These showNormalIfMinimized are needed because Send Coins and Receive Coins
// can be triggered from the tray menu, and need to show the GUI to be useful.
connect(overviewAction, &QAction::triggered, [this]{ showNormalIfMinimized(); });
connect(overviewAction, &QAction::triggered, this, &EleccoinGUI::gotoOverviewPage);
connect(sendCoinsAction, &QAction::triggered, [this]{ showNormalIfMinimized(); });
connect(sendCoinsAction, &QAction::triggered, [this]{ gotoSendCoinsPage(); });
connect(sendCoinsMenuAction, &QAction::triggered, [this]{ showNormalIfMinimized(); });
connect(sendCoinsMenuAction, &QAction::triggered, [this]{ gotoSendCoinsPage(); });
connect(receiveCoinsAction, &QAction::triggered, [this]{ showNormalIfMinimized(); });
connect(receiveCoinsAction, &QAction::triggered, this, &EleccoinGUI::gotoReceiveCoinsPage);
connect(receiveCoinsMenuAction, &QAction::triggered, [this]{ showNormalIfMinimized(); });
connect(receiveCoinsMenuAction, &QAction::triggered, this, &EleccoinGUI::gotoReceiveCoinsPage);
connect(historyAction, &QAction::triggered, [this]{ showNormalIfMinimized(); });
connect(historyAction, &QAction::triggered, this, &EleccoinGUI::gotoHistoryPage);
#endif // ENABLE_WALLET
quitAction = new QAction(tr("E&xit"), this);
quitAction->setStatusTip(tr("Quit application"));
quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q));
quitAction->setMenuRole(QAction::QuitRole);
aboutAction = new QAction(tr("&About %1").arg(PACKAGE_NAME), this);
aboutAction->setStatusTip(tr("Show information about %1").arg(PACKAGE_NAME));
aboutAction->setMenuRole(QAction::AboutRole);
aboutAction->setEnabled(false);
aboutQtAction = new QAction(tr("About &Qt"), this);
aboutQtAction->setStatusTip(tr("Show information about Qt"));
aboutQtAction->setMenuRole(QAction::AboutQtRole);
optionsAction = new QAction(tr("&Options…"), this);
optionsAction->setStatusTip(tr("Modify configuration options for %1").arg(PACKAGE_NAME));
optionsAction->setMenuRole(QAction::PreferencesRole);
optionsAction->setEnabled(false);
toggleHideAction = new QAction(tr("&Show / Hide"), this);
toggleHideAction->setStatusTip(tr("Show or hide the main Window"));
encryptWalletAction = new QAction(tr("&Encrypt Wallet…"), this);
encryptWalletAction->setStatusTip(tr("Encrypt the private keys that belong to your wallet"));
encryptWalletAction->setCheckable(true);
backupWalletAction = new QAction(tr("&Backup Wallet…"), this);
backupWalletAction->setStatusTip(tr("Backup wallet to another location"));
changePassphraseAction = new QAction(tr("&Change Passphrase…"), this);
changePassphraseAction->setStatusTip(tr("Change the passphrase used for wallet encryption"));
signMessageAction = new QAction(tr("Sign &message…"), this);
signMessageAction->setStatusTip(tr("Sign messages with your Eleccoin addresses to prove you own them"));
verifyMessageAction = new QAction(tr("&Verify message…"), this);
verifyMessageAction->setStatusTip(tr("Verify messages to ensure they were signed with specified Eleccoin addresses"));
m_load_psbt_action = new QAction(tr("&Load PSBT from file…"), this);
m_load_psbt_action->setStatusTip(tr("Load Partially Signed Eleccoin Transaction"));
m_load_psbt_clipboard_action = new QAction(tr("Load PSBT from clipboard…"), this);
m_load_psbt_clipboard_action->setStatusTip(tr("Load Partially Signed Eleccoin Transaction from clipboard"));
openRPCConsoleAction = new QAction(tr("Node window"), this);
openRPCConsoleAction->setStatusTip(tr("Open node debugging and diagnostic console"));
// initially disable the debug window menu item
openRPCConsoleAction->setEnabled(false);
openRPCConsoleAction->setObjectName("openRPCConsoleAction");
usedSendingAddressesAction = new QAction(tr("&Sending addresses"), this);
usedSendingAddressesAction->setStatusTip(tr("Show the list of used sending addresses and labels"));
usedReceivingAddressesAction = new QAction(tr("&Receiving addresses"), this);
usedReceivingAddressesAction->setStatusTip(tr("Show the list of used receiving addresses and labels"));
openAction = new QAction(tr("Open &URI…"), this);
openAction->setStatusTip(tr("Open a eleccoin: URI"));
m_open_wallet_action = new QAction(tr("Open Wallet"), this);
m_open_wallet_action->setEnabled(false);
m_open_wallet_action->setStatusTip(tr("Open a wallet"));
m_open_wallet_menu = new QMenu(this);
m_close_wallet_action = new QAction(tr("Close Wallet…"), this);
m_close_wallet_action->setStatusTip(tr("Close wallet"));
m_create_wallet_action = new QAction(tr("Create Wallet…"), this);
m_create_wallet_action->setEnabled(false);
m_create_wallet_action->setStatusTip(tr("Create a new wallet"));
m_close_all_wallets_action = new QAction(tr("Close All Wallets…"), this);
m_close_all_wallets_action->setStatusTip(tr("Close all wallets"));
showHelpMessageAction = new QAction(tr("&Command-line options"), this);
showHelpMessageAction->setMenuRole(QAction::NoRole);
showHelpMessageAction->setStatusTip(tr("Show the %1 help message to get a list with possible Eleccoin command-line options").arg(PACKAGE_NAME));
m_mask_values_action = new QAction(tr("&Mask values"), this);
m_mask_values_action->setShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_M));
m_mask_values_action->setStatusTip(tr("Mask the values in the Overview tab"));
m_mask_values_action->setCheckable(true);
connect(quitAction, &QAction::triggered, qApp, QApplication::quit);
connect(aboutAction, &QAction::triggered, this, &EleccoinGUI::aboutClicked);
connect(aboutQtAction, &QAction::triggered, qApp, QApplication::aboutQt);
connect(optionsAction, &QAction::triggered, this, &EleccoinGUI::optionsClicked);
connect(toggleHideAction, &QAction::triggered, this, &EleccoinGUI::toggleHidden);
connect(showHelpMessageAction, &QAction::triggered, this, &EleccoinGUI::showHelpMessageClicked);
connect(openRPCConsoleAction, &QAction::triggered, this, &EleccoinGUI::showDebugWindow);
// prevents an open debug window from becoming stuck/unusable on client shutdown
connect(quitAction, &QAction::triggered, rpcConsole, &QWidget::hide);
#ifdef ENABLE_WALLET
if(walletFrame)
{
connect(encryptWalletAction, &QAction::triggered, walletFrame, &WalletFrame::encryptWallet);
connect(backupWalletAction, &QAction::triggered, walletFrame, &WalletFrame::backupWallet);
connect(changePassphraseAction, &QAction::triggered, walletFrame, &WalletFrame::changePassphrase);
connect(signMessageAction, &QAction::triggered, [this]{ showNormalIfMinimized(); });
connect(signMessageAction, &QAction::triggered, [this]{ gotoSignMessageTab(); });
connect(m_load_psbt_action, &QAction::triggered, [this]{ gotoLoadPSBT(); });
connect(m_load_psbt_clipboard_action, &QAction::triggered, [this]{ gotoLoadPSBT(true); });
connect(verifyMessageAction, &QAction::triggered, [this]{ showNormalIfMinimized(); });
connect(verifyMessageAction, &QAction::triggered, [this]{ gotoVerifyMessageTab(); });
connect(usedSendingAddressesAction, &QAction::triggered, walletFrame, &WalletFrame::usedSendingAddresses);
connect(usedReceivingAddressesAction, &QAction::triggered, walletFrame, &WalletFrame::usedReceivingAddresses);
connect(openAction, &QAction::triggered, this, &EleccoinGUI::openClicked);
connect(m_open_wallet_menu, &QMenu::aboutToShow, [this] {
m_open_wallet_menu->clear();
for (const std::pair<const std::string, bool>& i : m_wallet_controller->listWalletDir()) {
const std::string& path = i.first;
QString name = path.empty() ? QString("["+tr("default wallet")+"]") : QString::fromStdString(path);
// Menu items remove single &. Single & are shown when && is in
// the string, but only the first occurrence. So replace only
// the first & with &&.
name.replace(name.indexOf(QChar('&')), 1, QString("&&"));
QAction* action = m_open_wallet_menu->addAction(name);
if (i.second) {
// This wallet is already loaded
action->setEnabled(false);
continue;
}
connect(action, &QAction::triggered, [this, path] {
auto activity = new OpenWalletActivity(m_wallet_controller, this);
connect(activity, &OpenWalletActivity::opened, this, &EleccoinGUI::setCurrentWallet);
connect(activity, &OpenWalletActivity::finished, activity, &QObject::deleteLater);
activity->open(path);
});
}
if (m_open_wallet_menu->isEmpty()) {
QAction* action = m_open_wallet_menu->addAction(tr("No wallets available"));
action->setEnabled(false);
}
});
connect(m_close_wallet_action, &QAction::triggered, [this] {
m_wallet_controller->closeWallet(walletFrame->currentWalletModel(), this);
});
connect(m_create_wallet_action, &QAction::triggered, [this] {
auto activity = new CreateWalletActivity(m_wallet_controller, this);
connect(activity, &CreateWalletActivity::created, this, &EleccoinGUI::setCurrentWallet);
connect(activity, &CreateWalletActivity::finished, activity, &QObject::deleteLater);
activity->create();
});
connect(m_close_all_wallets_action, &QAction::triggered, [this] {
m_wallet_controller->closeAllWallets(this);
});
connect(m_mask_values_action, &QAction::toggled, this, &EleccoinGUI::setPrivacy);
}
#endif // ENABLE_WALLET
connect(new QShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_C), this), &QShortcut::activated, this, &EleccoinGUI::showDebugWindowActivateConsole);
connect(new QShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_D), this), &QShortcut::activated, this, &EleccoinGUI::showDebugWindow);
}
void EleccoinGUI::createMenuBar()
{
#ifdef Q_OS_MAC
// Create a decoupled menu bar on Mac which stays even if the window is closed
appMenuBar = new QMenuBar();
#else
// Get the main window's menu bar on other platforms
appMenuBar = menuBar();
#endif
// Configure the menus
QMenu *file = appMenuBar->addMenu(tr("&File"));
if(walletFrame)
{
file->addAction(m_create_wallet_action);
file->addAction(m_open_wallet_action);
file->addAction(m_close_wallet_action);
file->addAction(m_close_all_wallets_action);
file->addSeparator();
file->addAction(openAction);
file->addAction(backupWalletAction);
file->addAction(signMessageAction);
file->addAction(verifyMessageAction);
file->addAction(m_load_psbt_action);
file->addAction(m_load_psbt_clipboard_action);
file->addSeparator();
}
file->addAction(quitAction);
QMenu *settings = appMenuBar->addMenu(tr("&Settings"));
if(walletFrame)
{
settings->addAction(encryptWalletAction);
settings->addAction(changePassphraseAction);
settings->addSeparator();
settings->addAction(m_mask_values_action);
settings->addSeparator();
}
settings->addAction(optionsAction);
QMenu* window_menu = appMenuBar->addMenu(tr("&Window"));
QAction* minimize_action = window_menu->addAction(tr("Minimize"));
minimize_action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_M));
connect(minimize_action, &QAction::triggered, [] {
QApplication::activeWindow()->showMinimized();
});
connect(qApp, &QApplication::focusWindowChanged, [minimize_action] (QWindow* window) {
minimize_action->setEnabled(window != nullptr && (window->flags() & Qt::Dialog) != Qt::Dialog && window->windowState() != Qt::WindowMinimized);
});
#ifdef Q_OS_MAC
QAction* zoom_action = window_menu->addAction(tr("Zoom"));
connect(zoom_action, &QAction::triggered, [] {
QWindow* window = qApp->focusWindow();
if (window->windowState() != Qt::WindowMaximized) {
window->showMaximized();
} else {
window->showNormal();
}
});
connect(qApp, &QApplication::focusWindowChanged, [zoom_action] (QWindow* window) {
zoom_action->setEnabled(window != nullptr);
});
#endif
if (walletFrame) {
#ifdef Q_OS_MAC
window_menu->addSeparator();
QAction* main_window_action = window_menu->addAction(tr("Main Window"));
connect(main_window_action, &QAction::triggered, [this] {
GUIUtil::bringToFront(this);
});
#endif
window_menu->addSeparator();
window_menu->addAction(usedSendingAddressesAction);
window_menu->addAction(usedReceivingAddressesAction);
}
window_menu->addSeparator();
for (RPCConsole::TabTypes tab_type : rpcConsole->tabs()) {
QAction* tab_action = window_menu->addAction(rpcConsole->tabTitle(tab_type));
tab_action->setShortcut(rpcConsole->tabShortcut(tab_type));
connect(tab_action, &QAction::triggered, [this, tab_type] {
rpcConsole->setTabFocus(tab_type);
showDebugWindow();
});
}
QMenu *help = appMenuBar->addMenu(tr("&Help"));
help->addAction(showHelpMessageAction);
help->addSeparator();
help->addAction(aboutAction);
help->addAction(aboutQtAction);
}
void EleccoinGUI::createToolBars()
{
if(walletFrame)
{
QToolBar *toolbar = addToolBar(tr("Tabs toolbar"));
appToolBar = toolbar;
toolbar->setMovable(false);
toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
toolbar->addAction(overviewAction);
toolbar->addAction(sendCoinsAction);
toolbar->addAction(receiveCoinsAction);
toolbar->addAction(historyAction);
overviewAction->setChecked(true);
#ifdef ENABLE_WALLET
QWidget *spacer = new QWidget();
spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
toolbar->addWidget(spacer);
m_wallet_selector = new QComboBox();
m_wallet_selector->setSizeAdjustPolicy(QComboBox::AdjustToContents);
connect(m_wallet_selector, qOverload<int>(&QComboBox::currentIndexChanged), this, &EleccoinGUI::setCurrentWalletBySelectorIndex);
m_wallet_selector_label = new QLabel();
m_wallet_selector_label->setText(tr("Wallet:") + " ");
m_wallet_selector_label->setBuddy(m_wallet_selector);
m_wallet_selector_label_action = appToolBar->addWidget(m_wallet_selector_label);
m_wallet_selector_action = appToolBar->addWidget(m_wallet_selector);
m_wallet_selector_label_action->setVisible(false);
m_wallet_selector_action->setVisible(false);
#endif
}
}
void EleccoinGUI::setClientModel(ClientModel *_clientModel, interfaces::BlockAndHeaderTipInfo* tip_info)
{
this->clientModel = _clientModel;
if(_clientModel)
{
// Create system tray menu (or setup the dock menu) that late to prevent users from calling actions,
// while the client has not yet fully loaded
createTrayIconMenu();
// Keep up to date with client
setNetworkActive(m_node.getNetworkActive());
connect(connectionsControl, &GUIUtil::ClickableLabel::clicked, [this] {
GUIUtil::PopupMenu(m_network_context_menu, QCursor::pos());
});
connect(_clientModel, &ClientModel::numConnectionsChanged, this, &EleccoinGUI::setNumConnections);
connect(_clientModel, &ClientModel::networkActiveChanged, this, &EleccoinGUI::setNetworkActive);
modalOverlay->setKnownBestHeight(tip_info->header_height, QDateTime::fromTime_t(tip_info->header_time));
setNumBlocks(tip_info->block_height, QDateTime::fromTime_t(tip_info->block_time), tip_info->verification_progress, false, SynchronizationState::INIT_DOWNLOAD);
connect(_clientModel, &ClientModel::numBlocksChanged, this, &EleccoinGUI::setNumBlocks);
// Receive and report messages from client model
connect(_clientModel, &ClientModel::message, [this](const QString &title, const QString &message, unsigned int style){
this->message(title, message, style);
});
// Show progress dialog
connect(_clientModel, &ClientModel::showProgress, this, &EleccoinGUI::showProgress);
rpcConsole->setClientModel(_clientModel, tip_info->block_height, tip_info->block_time, tip_info->verification_progress);
updateProxyIcon();
#ifdef ENABLE_WALLET
if(walletFrame)
{
walletFrame->setClientModel(_clientModel);
}
#endif // ENABLE_WALLET
unitDisplayControl->setOptionsModel(_clientModel->getOptionsModel());
OptionsModel* optionsModel = _clientModel->getOptionsModel();
if (optionsModel && trayIcon) {
// be aware of the tray icon disable state change reported by the OptionsModel object.
connect(optionsModel, &OptionsModel::showTrayIconChanged, trayIcon, &QSystemTrayIcon::setVisible);
// initialize the disable state of the tray icon with the current value in the model.
trayIcon->setVisible(optionsModel->getShowTrayIcon());
}
} else {
// Disable possibility to show main window via action
toggleHideAction->setEnabled(false);
if(trayIconMenu)
{
// Disable context menu on tray icon
trayIconMenu->clear();
}
// Propagate cleared model to child objects
rpcConsole->setClientModel(nullptr);
#ifdef ENABLE_WALLET
if (walletFrame)
{
walletFrame->setClientModel(nullptr);
}
#endif // ENABLE_WALLET
unitDisplayControl->setOptionsModel(nullptr);
}
}
#ifdef ENABLE_WALLET
void EleccoinGUI::setWalletController(WalletController* wallet_controller)
{
assert(!m_wallet_controller);
assert(wallet_controller);
m_wallet_controller = wallet_controller;
m_create_wallet_action->setEnabled(true);
m_open_wallet_action->setEnabled(true);
m_open_wallet_action->setMenu(m_open_wallet_menu);
GUIUtil::ExceptionSafeConnect(wallet_controller, &WalletController::walletAdded, this, &EleccoinGUI::addWallet);
connect(wallet_controller, &WalletController::walletRemoved, this, &EleccoinGUI::removeWallet);
for (WalletModel* wallet_model : m_wallet_controller->getOpenWallets()) {
addWallet(wallet_model);
}
}
WalletController* EleccoinGUI::getWalletController()
{
return m_wallet_controller;
}
void EleccoinGUI::addWallet(WalletModel* walletModel)
{
if (!walletFrame) return;
WalletView* wallet_view = new WalletView(platformStyle, walletFrame);
if (!walletFrame->addWallet(walletModel, wallet_view)) return;
rpcConsole->addWallet(walletModel);
if (m_wallet_selector->count() == 0) {
setWalletActionsEnabled(true);
} else if (m_wallet_selector->count() == 1) {
m_wallet_selector_label_action->setVisible(true);
m_wallet_selector_action->setVisible(true);
}
connect(wallet_view, &WalletView::outOfSyncWarningClicked, this, &EleccoinGUI::showModalOverlay);
connect(wallet_view, &WalletView::transactionClicked, this, &EleccoinGUI::gotoHistoryPage);
connect(wallet_view, &WalletView::coinsSent, this, &EleccoinGUI::gotoHistoryPage);
connect(wallet_view, &WalletView::message, [this](const QString& title, const QString& message, unsigned int style) {
this->message(title, message, style);
});
connect(wallet_view, &WalletView::encryptionStatusChanged, this, &EleccoinGUI::updateWalletStatus);
connect(wallet_view, &WalletView::incomingTransaction, this, &EleccoinGUI::incomingTransaction);
connect(wallet_view, &WalletView::hdEnabledStatusChanged, this, &EleccoinGUI::updateWalletStatus);
connect(this, &EleccoinGUI::setPrivacy, wallet_view, &WalletView::setPrivacy);
wallet_view->setPrivacy(isPrivacyModeActivated());
const QString display_name = walletModel->getDisplayName();
m_wallet_selector->addItem(display_name, QVariant::fromValue(walletModel));
}
void EleccoinGUI::removeWallet(WalletModel* walletModel)
{
if (!walletFrame) return;
labelWalletHDStatusIcon->hide();
labelWalletEncryptionIcon->hide();
int index = m_wallet_selector->findData(QVariant::fromValue(walletModel));
m_wallet_selector->removeItem(index);
if (m_wallet_selector->count() == 0) {
setWalletActionsEnabled(false);
overviewAction->setChecked(true);
} else if (m_wallet_selector->count() == 1) {
m_wallet_selector_label_action->setVisible(false);
m_wallet_selector_action->setVisible(false);
}
rpcConsole->removeWallet(walletModel);
walletFrame->removeWallet(walletModel);
updateWindowTitle();
}
void EleccoinGUI::setCurrentWallet(WalletModel* wallet_model)
{
if (!walletFrame) return;
walletFrame->setCurrentWallet(wallet_model);
for (int index = 0; index < m_wallet_selector->count(); ++index) {
if (m_wallet_selector->itemData(index).value<WalletModel*>() == wallet_model) {
m_wallet_selector->setCurrentIndex(index);
break;
}
}
updateWindowTitle();
}
void EleccoinGUI::setCurrentWalletBySelectorIndex(int index)
{
WalletModel* wallet_model = m_wallet_selector->itemData(index).value<WalletModel*>();
if (wallet_model) setCurrentWallet(wallet_model);
}
void EleccoinGUI::removeAllWallets()
{
if(!walletFrame)
return;
setWalletActionsEnabled(false);
walletFrame->removeAllWallets();
}
#endif // ENABLE_WALLET
void EleccoinGUI::setWalletActionsEnabled(bool enabled)
{
overviewAction->setEnabled(enabled);
sendCoinsAction->setEnabled(enabled);
sendCoinsMenuAction->setEnabled(enabled);
receiveCoinsAction->setEnabled(enabled);
receiveCoinsMenuAction->setEnabled(enabled);
historyAction->setEnabled(enabled);
encryptWalletAction->setEnabled(enabled);
backupWalletAction->setEnabled(enabled);
changePassphraseAction->setEnabled(enabled);
signMessageAction->setEnabled(enabled);
verifyMessageAction->setEnabled(enabled);
usedSendingAddressesAction->setEnabled(enabled);
usedReceivingAddressesAction->setEnabled(enabled);
openAction->setEnabled(enabled);
m_close_wallet_action->setEnabled(enabled);
m_close_all_wallets_action->setEnabled(enabled);
}
void EleccoinGUI::createTrayIcon()
{
assert(QSystemTrayIcon::isSystemTrayAvailable());
#ifndef Q_OS_MAC
if (QSystemTrayIcon::isSystemTrayAvailable()) {
trayIcon = new QSystemTrayIcon(m_network_style->getTrayAndWindowIcon(), this);
QString toolTip = tr("%1 client").arg(PACKAGE_NAME) + " " + m_network_style->getTitleAddText();
trayIcon->setToolTip(toolTip);
}
#endif
}
void EleccoinGUI::createTrayIconMenu()
{
#ifndef Q_OS_MAC
// return if trayIcon is unset (only on non-macOSes)
if (!trayIcon)
return;
trayIcon->setContextMenu(trayIconMenu.get());
connect(trayIcon, &QSystemTrayIcon::activated, this, &EleccoinGUI::trayIconActivated);
#else
// Note: On macOS, the Dock icon is used to provide the tray's functionality.
MacDockIconHandler *dockIconHandler = MacDockIconHandler::instance();
connect(dockIconHandler, &MacDockIconHandler::dockIconClicked, this, &EleccoinGUI::macosDockIconActivated);
trayIconMenu->setAsDockMenu();
#endif
// Configuration of the tray icon (or Dock icon) menu
#ifndef Q_OS_MAC
// Note: On macOS, the Dock icon's menu already has Show / Hide action.
trayIconMenu->addAction(toggleHideAction);
trayIconMenu->addSeparator();
#endif
if (enableWallet) {
trayIconMenu->addAction(sendCoinsMenuAction);
trayIconMenu->addAction(receiveCoinsMenuAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(signMessageAction);
trayIconMenu->addAction(verifyMessageAction);
trayIconMenu->addSeparator();
}
trayIconMenu->addAction(optionsAction);
trayIconMenu->addAction(openRPCConsoleAction);
#ifndef Q_OS_MAC // This is built-in on macOS
trayIconMenu->addSeparator();
trayIconMenu->addAction(quitAction);
#endif
}
#ifndef Q_OS_MAC
void EleccoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
if(reason == QSystemTrayIcon::Trigger)
{
// Click on system tray icon triggers show/hide of the main window
toggleHidden();
}
}
#else
void EleccoinGUI::macosDockIconActivated()
{
show();
activateWindow();
}
#endif
void EleccoinGUI::optionsClicked()
{
openOptionsDialogWithTab(OptionsDialog::TAB_MAIN);
}
void EleccoinGUI::aboutClicked()
{
if(!clientModel)
return;
HelpMessageDialog dlg(this, true);
dlg.exec();
}
void EleccoinGUI::showDebugWindow()
{
GUIUtil::bringToFront(rpcConsole);
Q_EMIT consoleShown(rpcConsole);
}
void EleccoinGUI::showDebugWindowActivateConsole()
{
rpcConsole->setTabFocus(RPCConsole::TabTypes::CONSOLE);
showDebugWindow();
}
void EleccoinGUI::showHelpMessageClicked()
{
GUIUtil::bringToFront(helpMessageDialog);
}
#ifdef ENABLE_WALLET
void EleccoinGUI::openClicked()
{
OpenURIDialog dlg(this);
if(dlg.exec())
{
Q_EMIT receivedURI(dlg.getURI());
}
}
void EleccoinGUI::gotoOverviewPage()
{
overviewAction->setChecked(true);
if (walletFrame) walletFrame->gotoOverviewPage();
}
void EleccoinGUI::gotoHistoryPage()
{
historyAction->setChecked(true);
if (walletFrame) walletFrame->gotoHistoryPage();
}
void EleccoinGUI::gotoReceiveCoinsPage()
{
receiveCoinsAction->setChecked(true);
if (walletFrame) walletFrame->gotoReceiveCoinsPage();
}
void EleccoinGUI::gotoSendCoinsPage(QString addr)
{
sendCoinsAction->setChecked(true);
if (walletFrame) walletFrame->gotoSendCoinsPage(addr);
}
void EleccoinGUI::gotoSignMessageTab(QString addr)
{
if (walletFrame) walletFrame->gotoSignMessageTab(addr);
}
void EleccoinGUI::gotoVerifyMessageTab(QString addr)
{
if (walletFrame) walletFrame->gotoVerifyMessageTab(addr);
}
void EleccoinGUI::gotoLoadPSBT(bool from_clipboard)
{
if (walletFrame) walletFrame->gotoLoadPSBT(from_clipboard);
}
#endif // ENABLE_WALLET
void EleccoinGUI::updateNetworkState()
{
int count = clientModel->getNumConnections();
QString icon;
switch(count)
{
case 0: icon = ":/icons/connect_0"; break;
case 1: case 2: case 3: icon = ":/icons/connect_1"; break;
case 4: case 5: case 6: icon = ":/icons/connect_2"; break;
case 7: case 8: case 9: icon = ":/icons/connect_3"; break;
default: icon = ":/icons/connect_4"; break;
}
QString tooltip;
if (m_node.getNetworkActive()) {
//: A substring of the tooltip.
tooltip = tr("%n active connection(s) to Eleccoin network.", "", count);
} else {
//: A substring of the tooltip.
tooltip = tr("Network activity disabled.");
icon = ":/icons/network_disabled";
}
// Don't word-wrap this (fixed-width) tooltip
tooltip = QLatin1String("<nobr>") + tooltip + QLatin1String("<br>") +
//: A substring of the tooltip. "More actions" are available via the context menu.
tr("Click for more actions.") + QLatin1String("</nobr>");
connectionsControl->setToolTip(tooltip);
connectionsControl->setThemedPixmap(icon, STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE);
}
void EleccoinGUI::setNumConnections(int count)
{
updateNetworkState();
}
void EleccoinGUI::setNetworkActive(bool network_active)
{
updateNetworkState();
m_network_context_menu->clear();
m_network_context_menu->addAction(
//: A context menu item. The "Peers tab" is an element of the "Node window".
tr("Show Peers tab"),
[this] {
rpcConsole->setTabFocus(RPCConsole::TabTypes::PEERS);
showDebugWindow();
});
m_network_context_menu->addAction(
network_active ?
//: A context menu item.
tr("Disable network activity") :
//: A context menu item. The network activity was disabled previously.
tr("Enable network activity"),
[this, new_state = !network_active] { m_node.setNetworkActive(new_state); });
}
void EleccoinGUI::updateHeadersSyncProgressLabel()
{
int64_t headersTipTime = clientModel->getHeaderTipTime();
int headersTipHeight = clientModel->getHeaderTipHeight();
int estHeadersLeft = (GetTime() - headersTipTime) / Params().GetConsensus().nPowTargetSpacing;
if (estHeadersLeft > HEADER_HEIGHT_DELTA_SYNC)
progressBarLabel->setText(tr("Syncing Headers (%1%)…").arg(QString::number(100.0 / (headersTipHeight+estHeadersLeft)*headersTipHeight, 'f', 1)));
}
void EleccoinGUI::openOptionsDialogWithTab(OptionsDialog::Tab tab)
{
if (!clientModel || !clientModel->getOptionsModel())
return;
OptionsDialog dlg(this, enableWallet);
dlg.setCurrentTab(tab);
dlg.setModel(clientModel->getOptionsModel());
dlg.exec();
}
void EleccoinGUI::setNumBlocks(int count, const QDateTime& blockDate, double nVerificationProgress, bool header, SynchronizationState sync_state)
{
// Disabling macOS App Nap on initial sync, disk and reindex operations.
#ifdef Q_OS_MAC
if (sync_state == SynchronizationState::POST_INIT) {
m_app_nap_inhibitor->enableAppNap();
} else {
m_app_nap_inhibitor->disableAppNap();
}
#endif
if (modalOverlay)
{
if (header)
modalOverlay->setKnownBestHeight(count, blockDate);
else
modalOverlay->tipUpdate(count, blockDate, nVerificationProgress);
}
if (!clientModel)
return;
// Prevent orphan statusbar messages (e.g. hover Quit in main menu, wait until chain-sync starts -> garbled text)
statusBar()->clearMessage();
// Acquire current block source
enum BlockSource blockSource = clientModel->getBlockSource();
switch (blockSource) {
case BlockSource::NETWORK:
if (header) {
updateHeadersSyncProgressLabel();
return;
}
progressBarLabel->setText(tr("Synchronizing with network…"));
updateHeadersSyncProgressLabel();
break;
case BlockSource::DISK:
if (header) {
progressBarLabel->setText(tr("Indexing blocks on disk…"));
} else {
progressBarLabel->setText(tr("Processing blocks on disk…"));
}
break;
case BlockSource::REINDEX:
progressBarLabel->setText(tr("Reindexing blocks on disk…"));
break;
case BlockSource::NONE:
if (header) {
return;
}
progressBarLabel->setText(tr("Connecting to peers…"));
break;
}
QString tooltip;
QDateTime currentDate = QDateTime::currentDateTime();
qint64 secs = blockDate.secsTo(currentDate);
tooltip = tr("Processed %n block(s) of transaction history.", "", count);
// Set icon state: spinning if catching up, tick otherwise
if (secs < MAX_BLOCK_TIME_GAP) {
tooltip = tr("Up to date") + QString(".<br>") + tooltip;
labelBlocksIcon->setThemedPixmap(QStringLiteral(":/icons/synced"), STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE);
#ifdef ENABLE_WALLET
if(walletFrame)
{
walletFrame->showOutOfSyncWarning(false);
modalOverlay->showHide(true, true);
}
#endif // ENABLE_WALLET
progressBarLabel->setVisible(false);
progressBar->setVisible(false);
}
else
{
QString timeBehindText = GUIUtil::formatNiceTimeOffset(secs);
progressBarLabel->setVisible(true);
progressBar->setFormat(tr("%1 behind").arg(timeBehindText));
progressBar->setMaximum(1000000000);
progressBar->setValue(nVerificationProgress * 1000000000.0 + 0.5);
progressBar->setVisible(true);
tooltip = tr("Catching up…") + QString("<br>") + tooltip;
if(count != prevBlocks)
{
labelBlocksIcon->setThemedPixmap(
QString(":/animation/spinner-%1").arg(spinnerFrame, 3, 10, QChar('0')),
STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE);
spinnerFrame = (spinnerFrame + 1) % SPINNER_FRAMES;
}
prevBlocks = count;
#ifdef ENABLE_WALLET
if(walletFrame)
{
walletFrame->showOutOfSyncWarning(true);
modalOverlay->showHide();
}
#endif // ENABLE_WALLET
tooltip += QString("<br>");
tooltip += tr("Last received block was generated %1 ago.").arg(timeBehindText);
tooltip += QString("<br>");
tooltip += tr("Transactions after this will not yet be visible.");
}
// Don't word-wrap this (fixed-width) tooltip
tooltip = QString("<nobr>") + tooltip + QString("</nobr>");
labelBlocksIcon->setToolTip(tooltip);
progressBarLabel->setToolTip(tooltip);
progressBar->setToolTip(tooltip);
}
void EleccoinGUI::message(const QString& title, QString message, unsigned int style, bool* ret, const QString& detailed_message)
{
// Default title. On macOS, the window title is ignored (as required by the macOS Guidelines).
QString strTitle{PACKAGE_NAME};
// Default to information icon
int nMBoxIcon = QMessageBox::Information;
int nNotifyIcon = Notificator::Information;
QString msgType;
if (!title.isEmpty()) {
msgType = title;
} else {
switch (style) {
case CClientUIInterface::MSG_ERROR:
msgType = tr("Error");
message = tr("Error: %1").arg(message);
break;
case CClientUIInterface::MSG_WARNING:
msgType = tr("Warning");
message = tr("Warning: %1").arg(message);
break;
case CClientUIInterface::MSG_INFORMATION:
msgType = tr("Information");
// No need to prepend the prefix here.
break;
default:
break;
}
}
if (!msgType.isEmpty()) {
strTitle += " - " + msgType;
}
if (style & CClientUIInterface::ICON_ERROR) {
nMBoxIcon = QMessageBox::Critical;
nNotifyIcon = Notificator::Critical;
} else if (style & CClientUIInterface::ICON_WARNING) {
nMBoxIcon = QMessageBox::Warning;
nNotifyIcon = Notificator::Warning;
}
if (style & CClientUIInterface::MODAL) {
// Check for buttons, use OK as default, if none was supplied
QMessageBox::StandardButton buttons;
if (!(buttons = (QMessageBox::StandardButton)(style & CClientUIInterface::BTN_MASK)))
buttons = QMessageBox::Ok;
showNormalIfMinimized();
QMessageBox mBox(static_cast<QMessageBox::Icon>(nMBoxIcon), strTitle, message, buttons, this);
mBox.setTextFormat(Qt::PlainText);
mBox.setDetailedText(detailed_message);
int r = mBox.exec();
if (ret != nullptr)
*ret = r == QMessageBox::Ok;
} else {
notificator->notify(static_cast<Notificator::Class>(nNotifyIcon), strTitle, message);
}
}
void EleccoinGUI::changeEvent(QEvent *e)
{
if (e->type() == QEvent::PaletteChange) {
overviewAction->setIcon(platformStyle->SingleColorIcon(QStringLiteral(":/icons/overview")));
sendCoinsAction->setIcon(platformStyle->SingleColorIcon(QStringLiteral(":/icons/send")));
receiveCoinsAction->setIcon(platformStyle->SingleColorIcon(QStringLiteral(":/icons/receiving_addresses")));
historyAction->setIcon(platformStyle->SingleColorIcon(QStringLiteral(":/icons/history")));
}
QMainWindow::changeEvent(e);
#ifndef Q_OS_MAC // Ignored on Mac
if(e->type() == QEvent::WindowStateChange)
{
if(clientModel && clientModel->getOptionsModel() && clientModel->getOptionsModel()->getMinimizeToTray())
{
QWindowStateChangeEvent *wsevt = static_cast<QWindowStateChangeEvent*>(e);
if(!(wsevt->oldState() & Qt::WindowMinimized) && isMinimized())
{
QTimer::singleShot(0, this, &EleccoinGUI::hide);
e->ignore();
}
else if((wsevt->oldState() & Qt::WindowMinimized) && !isMinimized())
{
QTimer::singleShot(0, this, &EleccoinGUI::show);
e->ignore();
}
}
}
#endif
}
void EleccoinGUI::closeEvent(QCloseEvent *event)
{
#ifndef Q_OS_MAC // Ignored on Mac
if(clientModel && clientModel->getOptionsModel())
{
if(!clientModel->getOptionsModel()->getMinimizeOnClose())
{
// close rpcConsole in case it was open to make some space for the shutdown window
rpcConsole->close();
QApplication::quit();
}
else
{
QMainWindow::showMinimized();
event->ignore();
}
}
#else
QMainWindow::closeEvent(event);
#endif
}
void EleccoinGUI::showEvent(QShowEvent *event)
{
// enable the debug window when the main window shows up
openRPCConsoleAction->setEnabled(true);
aboutAction->setEnabled(true);
optionsAction->setEnabled(true);
}
#ifdef ENABLE_WALLET
void EleccoinGUI::incomingTransaction(const QString& date, int unit, const CAmount& amount, const QString& type, const QString& address, const QString& label, const QString& walletName)
{
// On new transaction, make an info balloon
QString msg = tr("Date: %1\n").arg(date) +
tr("Amount: %1\n").arg(EleccoinUnits::formatWithUnit(unit, amount, true));
if (m_node.walletClient().getWallets().size() > 1 && !walletName.isEmpty()) {
msg += tr("Wallet: %1\n").arg(walletName);
}
msg += tr("Type: %1\n").arg(type);
if (!label.isEmpty())
msg += tr("Label: %1\n").arg(label);
else if (!address.isEmpty())
msg += tr("Address: %1\n").arg(address);
message((amount)<0 ? tr("Sent transaction") : tr("Incoming transaction"),
msg, CClientUIInterface::MSG_INFORMATION);
}
#endif // ENABLE_WALLET
void EleccoinGUI::dragEnterEvent(QDragEnterEvent *event)
{
// Accept only URIs
if(event->mimeData()->hasUrls())
event->acceptProposedAction();
}
void EleccoinGUI::dropEvent(QDropEvent *event)
{
if(event->mimeData()->hasUrls())
{
for (const QUrl &uri : event->mimeData()->urls())
{
Q_EMIT receivedURI(uri.toString());
}
}
event->acceptProposedAction();
}
bool EleccoinGUI::eventFilter(QObject *object, QEvent *event)
{
// Catch status tip events
if (event->type() == QEvent::StatusTip)
{
// Prevent adding text from setStatusTip(), if we currently use the status bar for displaying other stuff
if (progressBarLabel->isVisible() || progressBar->isVisible())
return true;
}
return QMainWindow::eventFilter(object, event);
}
#ifdef ENABLE_WALLET
bool EleccoinGUI::handlePaymentRequest(const SendCoinsRecipient& recipient)
{
// URI has to be valid
if (walletFrame && walletFrame->handlePaymentRequest(recipient))
{
showNormalIfMinimized();
gotoSendCoinsPage();
return true;
}
return false;
}
void EleccoinGUI::setHDStatus(bool privkeyDisabled, int hdEnabled)
{
labelWalletHDStatusIcon->setThemedPixmap(privkeyDisabled ? QStringLiteral(":/icons/eye") : hdEnabled ? QStringLiteral(":/icons/hd_enabled") : QStringLiteral(":/icons/hd_disabled"), STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE);
labelWalletHDStatusIcon->setToolTip(privkeyDisabled ? tr("Private key <b>disabled</b>") : hdEnabled ? tr("HD key generation is <b>enabled</b>") : tr("HD key generation is <b>disabled</b>"));
labelWalletHDStatusIcon->show();
// eventually disable the QLabel to set its opacity to 50%
labelWalletHDStatusIcon->setEnabled(hdEnabled);
}
void EleccoinGUI::setEncryptionStatus(int status)
{
switch(status)
{
case WalletModel::Unencrypted:
labelWalletEncryptionIcon->hide();
encryptWalletAction->setChecked(false);
changePassphraseAction->setEnabled(false);
encryptWalletAction->setEnabled(true);
break;
case WalletModel::Unlocked:
labelWalletEncryptionIcon->show();
labelWalletEncryptionIcon->setThemedPixmap(QStringLiteral(":/icons/lock_open"), STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE);
labelWalletEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b>"));
encryptWalletAction->setChecked(true);
changePassphraseAction->setEnabled(true);
encryptWalletAction->setEnabled(false);
break;
case WalletModel::Locked:
labelWalletEncryptionIcon->show();
labelWalletEncryptionIcon->setThemedPixmap(QStringLiteral(":/icons/lock_closed"), STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE);
labelWalletEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>locked</b>"));
encryptWalletAction->setChecked(true);
changePassphraseAction->setEnabled(true);
encryptWalletAction->setEnabled(false);
break;
}
}
void EleccoinGUI::updateWalletStatus()
{
if (!walletFrame) {
return;
}
WalletView * const walletView = walletFrame->currentWalletView();
if (!walletView) {
return;
}
WalletModel * const walletModel = walletView->getWalletModel();
setEncryptionStatus(walletModel->getEncryptionStatus());
setHDStatus(walletModel->wallet().privateKeysDisabled(), walletModel->wallet().hdEnabled());
}
#endif // ENABLE_WALLET
void EleccoinGUI::updateProxyIcon()
{
std::string ip_port;
bool proxy_enabled = clientModel->getProxyInfo(ip_port);
if (proxy_enabled) {
if (!GUIUtil::HasPixmap(labelProxyIcon)) {
QString ip_port_q = QString::fromStdString(ip_port);
labelProxyIcon->setThemedPixmap((":/icons/proxy"), STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE);
labelProxyIcon->setToolTip(tr("Proxy is <b>enabled</b>: %1").arg(ip_port_q));
} else {
labelProxyIcon->show();
}
} else {
labelProxyIcon->hide();
}
}
void EleccoinGUI::updateWindowTitle()
{
QString window_title = PACKAGE_NAME;
#ifdef ENABLE_WALLET
if (walletFrame) {
WalletModel* const wallet_model = walletFrame->currentWalletModel();
if (wallet_model && !wallet_model->getWalletName().isEmpty()) {
window_title += " - " + wallet_model->getDisplayName();
}
}
#endif
if (!m_network_style->getTitleAddText().isEmpty()) {
window_title += " - " + m_network_style->getTitleAddText();
}
setWindowTitle(window_title);
}
void EleccoinGUI::showNormalIfMinimized(bool fToggleHidden)
{
if(!clientModel)
return;
if (!isHidden() && !isMinimized() && !GUIUtil::isObscured(this) && fToggleHidden) {
hide();
} else {
GUIUtil::bringToFront(this);
}
}
void EleccoinGUI::toggleHidden()
{
showNormalIfMinimized(true);
}
void EleccoinGUI::detectShutdown()
{
if (m_node.shutdownRequested())
{
if(rpcConsole)
rpcConsole->hide();
qApp->quit();
}
}
void EleccoinGUI::showProgress(const QString &title, int nProgress)
{
if (nProgress == 0) {
progressDialog = new QProgressDialog(title, QString(), 0, 100);
GUIUtil::PolishProgressDialog(progressDialog);
progressDialog->setWindowModality(Qt::ApplicationModal);
progressDialog->setAutoClose(false);
progressDialog->setValue(0);
} else if (nProgress == 100) {
if (progressDialog) {
progressDialog->close();
progressDialog->deleteLater();
progressDialog = nullptr;
}
} else if (progressDialog) {
progressDialog->setValue(nProgress);
}
}
void EleccoinGUI::showModalOverlay()
{
if (modalOverlay && (progressBar->isVisible() || modalOverlay->isLayerVisible()))
modalOverlay->toggleVisibility();
}
static bool ThreadSafeMessageBox(EleccoinGUI* gui, const bilingual_str& message, const std::string& caption, unsigned int style)
{
bool modal = (style & CClientUIInterface::MODAL);
// The SECURE flag has no effect in the Qt GUI.
// bool secure = (style & CClientUIInterface::SECURE);
style &= ~CClientUIInterface::SECURE;
bool ret = false;
QString detailed_message; // This is original message, in English, for googling and referencing.
if (message.original != message.translated) {
detailed_message = EleccoinGUI::tr("Original message:") + "\n" + QString::fromStdString(message.original);
}
// In case of modal message, use blocking connection to wait for user to click a button
bool invoked = QMetaObject::invokeMethod(gui, "message",
modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(caption)),
Q_ARG(QString, QString::fromStdString(message.translated)),
Q_ARG(unsigned int, style),
Q_ARG(bool*, &ret),
Q_ARG(QString, detailed_message));
assert(invoked);
return ret;
}
void EleccoinGUI::subscribeToCoreSignals()
{
// Connect signals to client
m_handler_message_box = m_node.handleMessageBox(std::bind(ThreadSafeMessageBox, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
m_handler_question = m_node.handleQuestion(std::bind(ThreadSafeMessageBox, this, std::placeholders::_1, std::placeholders::_3, std::placeholders::_4));
}
void EleccoinGUI::unsubscribeFromCoreSignals()
{
// Disconnect signals from client
m_handler_message_box->disconnect();
m_handler_question->disconnect();
}
bool EleccoinGUI::isPrivacyModeActivated() const
{
assert(m_mask_values_action);
return m_mask_values_action->isChecked();
}
UnitDisplayStatusBarControl::UnitDisplayStatusBarControl(const PlatformStyle *platformStyle)
: optionsModel(nullptr),
menu(nullptr),
m_platform_style{platformStyle}
{
createContextMenu();
setToolTip(tr("Unit to show amounts in. Click to select another unit."));
QList<EleccoinUnits::Unit> units = EleccoinUnits::availableUnits();
int max_width = 0;
const QFontMetrics fm(font());
for (const EleccoinUnits::Unit unit : units)
{
max_width = qMax(max_width, GUIUtil::TextWidth(fm, EleccoinUnits::longName(unit)));
}
setMinimumSize(max_width, 0);
setAlignment(Qt::AlignRight | Qt::AlignVCenter);
setStyleSheet(QString("QLabel { color : %1 }").arg(m_platform_style->SingleColor().name()));
}
/** So that it responds to button clicks */
void UnitDisplayStatusBarControl::mousePressEvent(QMouseEvent *event)
{
onDisplayUnitsClicked(event->pos());
}
void UnitDisplayStatusBarControl::changeEvent(QEvent* e)
{
if (e->type() == QEvent::PaletteChange) {
QString style = QString("QLabel { color : %1 }").arg(m_platform_style->SingleColor().name());
if (style != styleSheet()) {
setStyleSheet(style);
}
}
QLabel::changeEvent(e);
}
/** Creates context menu, its actions, and wires up all the relevant signals for mouse events. */
void UnitDisplayStatusBarControl::createContextMenu()
{
menu = new QMenu(this);
for (const EleccoinUnits::Unit u : EleccoinUnits::availableUnits()) {
menu->addAction(EleccoinUnits::longName(u))->setData(QVariant(u));
}
connect(menu, &QMenu::triggered, this, &UnitDisplayStatusBarControl::onMenuSelection);
}
/** Lets the control know about the Options Model (and its signals) */
void UnitDisplayStatusBarControl::setOptionsModel(OptionsModel *_optionsModel)
{
if (_optionsModel)
{
this->optionsModel = _optionsModel;
// be aware of a display unit change reported by the OptionsModel object.
connect(_optionsModel, &OptionsModel::displayUnitChanged, this, &UnitDisplayStatusBarControl::updateDisplayUnit);
// initialize the display units label with the current value in the model.
updateDisplayUnit(_optionsModel->getDisplayUnit());
}
}
/** When Display Units are changed on OptionsModel it will refresh the display text of the control on the status bar */
void UnitDisplayStatusBarControl::updateDisplayUnit(int newUnits)
{
setText(EleccoinUnits::longName(newUnits));
}
/** Shows context menu with Display Unit options by the mouse coordinates */
void UnitDisplayStatusBarControl::onDisplayUnitsClicked(const QPoint& point)
{
QPoint globalPos = mapToGlobal(point);
menu->exec(globalPos);
}
/** Tells underlying optionsModel to update its current display unit. */
void UnitDisplayStatusBarControl::onMenuSelection(QAction* action)
{
if (action)
{
optionsModel->setDisplayUnit(action->data());
}
}
|
/*
* PROGRAM: Client/Server Common Code
* MODULE: ClumpletReader.cpp
* DESCRIPTION: Secure handling of clumplet buffers
*
* The contents of this file are subject to the Initial
* Developer's Public License Version 1.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.ibphoenix.com/main.nfs?a=ibphoenix&page=ibp_idpl.
*
* Software distributed under the License is distributed AS IS,
* WITHOUT WARRANTY OF ANY KIND, either express or implied.
* See the License for the specific language governing rights
* and limitations under the License.
*
* The Original Code was created by Nickolay Samofatov
* for the Firebird Open Source RDBMS project.
*
* Copyright (c) 2004 Nickolay Samofatov <nickolay@broadviewsoftware.com>
* and all contributors signed below.
*
* All Rights Reserved.
* Contributor(s): ______________________________________.
*
*
*/
#include "firebird.h"
#include "../common/classes/ClumpletReader.h"
#include "../common/classes/MetaName.h"
#include "fb_exception.h"
#include "../jrd/ibase.h"
#include "firebird/Interface.h"
#ifdef DEBUG_CLUMPLETS
#include "../yvalve/gds_proto.h"
#include <ctype.h>
namespace Firebird {
class ClumpletDump : public ClumpletReader
{
public:
ClumpletDump(Kind k, const UCHAR* buffer, FB_SIZE_T buffLen)
: ClumpletReader(k, buffer, buffLen)
{ }
static string hexString(const UCHAR* b, FB_SIZE_T len)
{
string t1, t2;
for (; len > 0; --len, ++b)
{
if (isprint(*b))
t2 += *b;
else
{
t1.printf("<%02x>", *b);
t2 += t1;
}
}
return t2;
}
protected:
virtual void usage_mistake(const char* what) const
{
fatal_exception::raiseFmt("Internal error when using clumplet API: %s", what);
}
virtual void invalid_structure(const char* what, const int data) const
{
fatal_exception::raiseFmt("Invalid clumplet buffer structure: %s (%d)", what, data);
}
};
void ClumpletReader::dump() const
{
static int dmp = 0;
gds__log("*** DUMP ***");
if (dmp)
{
// Avoid infinite recursion during dump
gds__log("recursion");
return;
}
dmp++;
try {
ClumpletDump d(kind, getBuffer(), getBufferLength());
int t = (kind == SpbStart || kind == UnTagged || kind == WideUnTagged || kind == SpbResponse) ? -1 : d.getBufferTag();
gds__log("Tag=%d Offset=%d Length=%d Eof=%d\n", t, getCurOffset(), getBufferLength(), isEof());
for (d.rewind(); !(d.isEof()); d.moveNext())
{
gds__log("Clump %d at offset %d: %s", d.getClumpTag(), d.getCurOffset(),
ClumpletDump::hexString(d.getBytes(), d.getClumpLength()).c_str());
}
}
catch (const fatal_exception& x)
{
gds__log("Fatal exception during clumplet dump: %s", x.what());
FB_SIZE_T l = getBufferLength() - getCurOffset();
const UCHAR *p = getBuffer() + getCurOffset();
gds__log("Plain dump starting with offset %d: %s", getCurOffset(),
ClumpletDump::hexString(p, l).c_str());
}
dmp--;
}
}
#endif //DEBUG_CLUMPLETS
namespace Firebird {
ClumpletReader::ClumpletReader(Kind k, const UCHAR* buffer, FB_SIZE_T buffLen) :
kind(k), static_buffer(buffer), static_buffer_end(buffer + buffLen)
{
rewind(); // this will set cur_offset and spbState
}
ClumpletReader::ClumpletReader(MemoryPool& pool, Kind k, const UCHAR* buffer, FB_SIZE_T buffLen) :
AutoStorage(pool), kind(k), static_buffer(buffer), static_buffer_end(buffer + buffLen)
{
rewind(); // this will set cur_offset and spbState
}
ClumpletReader::ClumpletReader(MemoryPool& pool, const ClumpletReader& from) :
AutoStorage(pool), kind(from.kind),
static_buffer(from.getBuffer()), static_buffer_end(from.getBufferEnd())
{
rewind(); // this will set cur_offset and spbState
}
ClumpletReader::ClumpletReader(const ClumpletReader& from) :
AutoStorage(), kind(from.kind),
static_buffer(from.getBuffer()), static_buffer_end(from.getBufferEnd())
{
rewind(); // this will set cur_offset and spbState
}
ClumpletReader::ClumpletReader(MemoryPool& pool, const KindList* kl,
const UCHAR* buffer, FB_SIZE_T buffLen, FPTR_VOID raise) :
AutoStorage(pool), kind(kl->kind), static_buffer(buffer), static_buffer_end(buffer + buffLen)
{
create(kl, buffLen, raise);
}
ClumpletReader::ClumpletReader(const KindList* kl, const UCHAR* buffer, FB_SIZE_T buffLen, FPTR_VOID raise) :
kind(kl->kind), static_buffer(buffer), static_buffer_end(buffer + buffLen)
{
create(kl, buffLen, raise);
}
void ClumpletReader::create(const KindList* kl, FB_SIZE_T buffLen, FPTR_VOID raise)
{
cur_offset = 0;
if (buffLen)
{
while (kl->kind != EndOfList)
{
kind = kl->kind;
if (getBufferTag() == kl->tag)
{
break;
}
++kl;
}
if (kl->kind == EndOfList)
{
if (raise)
{
raise();
}
invalid_structure("Unknown tag value - missing in the list of possible");
}
}
rewind(); // this will set cur_offset and spbState
}
const UCHAR* ClumpletReader::getBuffer() const
{
return static_buffer;
}
const UCHAR* ClumpletReader::getBufferEnd() const
{
return static_buffer_end;
}
void ClumpletReader::usage_mistake(const char* what) const
{
#ifdef DEBUG_CLUMPLETS
dump();
#endif
fatal_exception::raiseFmt("Internal error when using clumplet API: %s", what);
}
void ClumpletReader::invalid_structure(const char* what, const int data) const
{
#ifdef DEBUG_CLUMPLETS
dump();
#endif
fatal_exception::raiseFmt("Invalid clumplet buffer structure: %s (%d)", what, data);
}
bool ClumpletReader::isTagged() const
{
switch (kind)
{
case Tpb:
case Tagged:
case WideTagged:
case SpbAttach:
return true;
}
return false;
}
UCHAR ClumpletReader::getBufferTag() const
{
const UCHAR* const buffer_end = getBufferEnd();
const UCHAR* buffer_start = getBuffer();
switch (kind)
{
case Tpb:
case Tagged:
case WideTagged:
if (buffer_end - buffer_start == 0)
{
invalid_structure("empty buffer");
return 0;
}
return buffer_start[0];
case SpbStart:
case UnTagged:
case WideUnTagged:
case SpbSendItems:
case SpbReceiveItems:
case SpbResponse:
usage_mistake("buffer is not tagged");
return 0;
case SpbAttach:
if (buffer_end - buffer_start == 0)
{
invalid_structure("empty buffer");
return 0;
}
switch (buffer_start[0])
{
case isc_spb_version1:
// This is old SPB format, it's almost like DPB -
// buffer's tag is the first byte.
return buffer_start[0];
case isc_spb_version:
// Buffer's tag is the second byte
if (buffer_end - buffer_start == 1)
{
invalid_structure("buffer too short", 1);
return 0;
}
return buffer_start[1];
case isc_spb_version3:
// This is wide SPB attach format - buffer's tag is the first byte.
return buffer_start[0];
default:
invalid_structure("spb in service attach should begin with isc_spb_version1 or isc_spb_version", buffer_start[0]);
return 0;
}
default:
fb_assert(false);
return 0;
}
}
ClumpletReader::ClumpletType ClumpletReader::getClumpletType(UCHAR tag) const
{
switch (kind)
{
case Tagged:
case UnTagged:
case SpbAttach:
return TraditionalDpb;
case WideTagged:
case WideUnTagged:
return Wide;
case Tpb:
switch (tag)
{
case isc_tpb_lock_write:
case isc_tpb_lock_read:
case isc_tpb_lock_timeout:
return TraditionalDpb;
}
return SingleTpb;
case SpbSendItems:
switch (tag)
{
case isc_info_svc_auth_block:
return Wide;
case isc_info_end:
case isc_info_truncated:
case isc_info_error:
case isc_info_data_not_ready:
case isc_info_length:
case isc_info_flag_end:
return SingleTpb;
}
return StringSpb;
case SpbReceiveItems:
return SingleTpb;
case SpbStart:
switch(tag)
{
case isc_spb_auth_block:
case isc_spb_trusted_auth:
case isc_spb_auth_plugin_name:
case isc_spb_auth_plugin_list:
return Wide;
}
switch (spbState)
{
case 0:
return SingleTpb;
case isc_action_svc_backup:
case isc_action_svc_restore:
switch (tag)
{
case isc_spb_bkp_file:
case isc_spb_dbname:
case isc_spb_res_fix_fss_data:
case isc_spb_res_fix_fss_metadata:
case isc_spb_bkp_stat:
case isc_spb_bkp_skip_data:
//case isc_spb_res_skip_data: // same value
return StringSpb;
case isc_spb_bkp_factor:
case isc_spb_bkp_length:
case isc_spb_res_length:
case isc_spb_res_buffers:
case isc_spb_res_page_size:
case isc_spb_options:
case isc_spb_verbint:
return IntSpb;
case isc_spb_verbose:
return SingleTpb;
case isc_spb_res_access_mode:
return ByteSpb;
}
invalid_structure("unknown parameter for backup/restore", tag);
break;
case isc_action_svc_repair:
switch (tag)
{
case isc_spb_dbname:
return StringSpb;
case isc_spb_options:
case isc_spb_rpr_commit_trans:
case isc_spb_rpr_rollback_trans:
case isc_spb_rpr_recover_two_phase:
return IntSpb;
case isc_spb_rpr_commit_trans_64:
case isc_spb_rpr_rollback_trans_64:
case isc_spb_rpr_recover_two_phase_64:
return BigIntSpb;
}
invalid_structure("unknown parameter for repair", tag);
break;
case isc_action_svc_add_user:
case isc_action_svc_delete_user:
case isc_action_svc_modify_user:
case isc_action_svc_display_user:
case isc_action_svc_display_user_adm:
case isc_action_svc_set_mapping:
case isc_action_svc_drop_mapping:
switch (tag)
{
case isc_spb_dbname:
case isc_spb_sql_role_name:
case isc_spb_sec_username:
case isc_spb_sec_password:
case isc_spb_sec_groupname:
case isc_spb_sec_firstname:
case isc_spb_sec_middlename:
case isc_spb_sec_lastname:
return StringSpb;
case isc_spb_sec_userid:
case isc_spb_sec_groupid:
case isc_spb_sec_admin:
return IntSpb;
}
invalid_structure("unknown parameter for security database operation", tag);
break;
case isc_action_svc_properties:
switch (tag)
{
case isc_spb_dbname:
return StringSpb;
case isc_spb_prp_page_buffers:
case isc_spb_prp_sweep_interval:
case isc_spb_prp_shutdown_db:
case isc_spb_prp_deny_new_attachments:
case isc_spb_prp_deny_new_transactions:
case isc_spb_prp_set_sql_dialect:
case isc_spb_options:
case isc_spb_prp_force_shutdown:
case isc_spb_prp_attachments_shutdown:
case isc_spb_prp_transactions_shutdown:
return IntSpb;
case isc_spb_prp_reserve_space:
case isc_spb_prp_write_mode:
case isc_spb_prp_access_mode:
case isc_spb_prp_shutdown_mode:
case isc_spb_prp_online_mode:
return ByteSpb;
}
invalid_structure("unknown parameter for setting database properties", tag);
break;
// case isc_action_svc_add_license:
// case isc_action_svc_remove_license:
case isc_action_svc_db_stats:
switch (tag)
{
case isc_spb_dbname:
case isc_spb_command_line:
case isc_spb_sts_table:
return StringSpb;
case isc_spb_options:
return IntSpb;
}
invalid_structure("unknown parameter for getting statistics", tag);
break;
case isc_action_svc_get_ib_log:
invalid_structure("unknown parameter for getting log", tag);
break;
case isc_action_svc_nbak:
case isc_action_svc_nrest:
switch (tag)
{
case isc_spb_nbk_file:
case isc_spb_nbk_direct:
case isc_spb_dbname:
case isc_spb_nbk_guid:
return StringSpb;
case isc_spb_nbk_level:
case isc_spb_options:
return IntSpb;
}
invalid_structure("unknown parameter for nbackup", tag);
break;
case isc_action_svc_trace_start:
case isc_action_svc_trace_stop:
case isc_action_svc_trace_suspend:
case isc_action_svc_trace_resume:
switch (tag)
{
case isc_spb_trc_cfg:
case isc_spb_trc_name:
return StringSpb;
case isc_spb_trc_id:
return IntSpb;
}
break;
case isc_action_svc_validate:
switch (tag)
{
case isc_spb_val_tab_incl:
case isc_spb_val_tab_excl:
case isc_spb_val_idx_incl:
case isc_spb_val_idx_excl:
case isc_spb_dbname:
return StringSpb;
case isc_spb_val_lock_timeout:
return IntSpb;
}
break;
}
invalid_structure("wrong spb state", spbState);
break;
case SpbResponse:
switch(tag)
{
case isc_info_svc_version:
case isc_spb_num_att:
case isc_spb_num_db:
case isc_spb_multi_tra_id:
case isc_spb_single_tra_id:
case isc_spb_tra_id:
case isc_info_svc_stdin:
case isc_info_svc_capabilities:
return IntSpb;
case isc_spb_multi_tra_id_64:
case isc_spb_single_tra_id_64:
case isc_spb_tra_id_64:
return BigIntSpb;
case isc_info_svc_server_version:
case isc_info_svc_implementation:
case isc_info_svc_get_env_msg:
case isc_info_svc_get_env:
case isc_info_svc_get_env_lock:
case isc_info_svc_user_dbpath:
case isc_spb_dbname:
case isc_spb_tra_host_site:
case isc_spb_tra_remote_site:
case isc_spb_tra_db_path:
case isc_info_svc_get_users:
case isc_info_svc_line:
case isc_info_svc_to_eof:
return StringSpb;
case isc_info_end:
case isc_info_svc_svr_db_info:
case isc_info_svc_limbo_trans:
case isc_info_flag_end:
case isc_info_truncated:
case isc_info_svc_timeout:
case isc_info_data_not_ready:
return SingleTpb;
case isc_spb_tra_state:
case isc_spb_tra_advise:
return ByteSpb;
}
invalid_structure("unrecognized service response tag", tag);
break;
}
invalid_structure("unknown clumplet kind", kind);
return SingleTpb;
}
void ClumpletReader::adjustSpbState()
{
switch (kind)
{
case SpbStart:
if (spbState == 0 && // Just started with service start block ...
getClumpletSize(true, true, true) == 1) // and this is action_XXX clumplet
{
spbState = getClumpTag();
}
break;
default:
break;
}
}
FB_SIZE_T ClumpletReader::getClumpletSize(bool wTag, bool wLength, bool wData) const
{
const UCHAR* clumplet = getBuffer() + cur_offset;
const UCHAR* const buffer_end = getBufferEnd();
// Check for EOF
if (clumplet >= buffer_end)
{
usage_mistake("read past EOF");
return 0;
}
FB_SIZE_T rc = wTag ? 1 : 0;
FB_SIZE_T lengthSize = 0;
FB_SIZE_T dataSize = 0;
ClumpletType t = getClumpletType(clumplet[0]);
switch (t)
{
// This form allows clumplets of virtually any size
case Wide:
// Check did we receive length component for clumplet
if (buffer_end - clumplet < 5)
{
invalid_structure("buffer end before end of clumplet - no length component", buffer_end - clumplet);
return rc;
}
lengthSize = 4;
dataSize = clumplet[4];
dataSize <<= 8;
dataSize += clumplet[3];
dataSize <<= 8;
dataSize += clumplet[2];
dataSize <<= 8;
dataSize += clumplet[1];
break;
// This is the most widely used form
case TraditionalDpb:
// Check did we receive length component for clumplet
if (buffer_end - clumplet < 2)
{
invalid_structure("buffer end before end of clumplet - no length component", buffer_end - clumplet);
return rc;
}
lengthSize = 1;
dataSize = clumplet[1];
break;
// Almost all TPB parameters are single bytes
case SingleTpb:
break;
// Used in SPB for long strings
case StringSpb:
// Check did we receive length component for clumplet
if (buffer_end - clumplet < 3)
{
invalid_structure("buffer end before end of clumplet - no length component", buffer_end - clumplet);
return rc;
}
lengthSize = 2;
dataSize = clumplet[2];
dataSize <<= 8;
dataSize += clumplet[1];
break;
// Used in SPB for 4-byte integers
case IntSpb:
dataSize = 4;
break;
// Used in SPB for 8-byte integers
case BigIntSpb:
dataSize = 8;
break;
// Used in SPB for single byte
case ByteSpb:
dataSize = 1;
break;
default:
invalid_structure("unknown clumplet type", t);
}
const FB_SIZE_T total = 1 + lengthSize + dataSize;
if (clumplet + total > buffer_end)
{
invalid_structure("buffer end before end of clumplet - clumplet too long", total);
FB_SIZE_T delta = total - (buffer_end - clumplet);
if (delta > dataSize)
dataSize = 0;
else
dataSize -= delta;
}
if (wLength) {
rc += lengthSize;
}
if (wData) {
rc += dataSize;
}
return rc;
}
void ClumpletReader::moveNext()
{
if (isEof())
return; // no need to raise useless exceptions
FB_SIZE_T cs = getClumpletSize(true, true, true);
adjustSpbState();
cur_offset += cs;
}
void ClumpletReader::rewind()
{
if (! getBuffer())
{
cur_offset = 0;
spbState = 0;
return;
}
switch (kind)
{
case UnTagged:
case WideUnTagged:
case SpbStart:
case SpbSendItems:
case SpbReceiveItems:
case SpbResponse:
cur_offset = 0;
break;
default:
if (kind == SpbAttach && getBufferLength() > 0 && getBuffer()[0] != isc_spb_version1)
cur_offset = 2;
else
cur_offset = 1;
}
spbState = 0;
}
bool ClumpletReader::find(UCHAR tag)
{
const FB_SIZE_T co = getCurOffset();
for (rewind(); !isEof(); moveNext())
{
if (tag == getClumpTag())
{
return true;
}
}
setCurOffset(co);
return false;
}
bool ClumpletReader::next(UCHAR tag)
{
if (!isEof())
{
const FB_SIZE_T co = getCurOffset();
if (tag == getClumpTag())
{
moveNext();
}
for (; !isEof(); moveNext())
{
if (tag == getClumpTag())
{
return true;
}
}
setCurOffset(co);
}
return false;
}
// Methods which work with currently selected clumplet
UCHAR ClumpletReader::getClumpTag() const
{
const UCHAR* clumplet = getBuffer() + cur_offset;
const UCHAR* const buffer_end = getBufferEnd();
// Check for EOF
if (clumplet >= buffer_end)
{
usage_mistake("read past EOF");
return 0;
}
return clumplet[0];
}
FB_SIZE_T ClumpletReader::getClumpLength() const
{
return getClumpletSize(false, false, true);
}
const UCHAR* ClumpletReader::getBytes() const
{
return getBuffer() + cur_offset + getClumpletSize(true, true, false);
}
SINT64 ClumpletReader::fromVaxInteger(const UCHAR* ptr, FB_SIZE_T length)
{
// We can't handle numbers bigger than int64. Some cases use length == 0.
fb_assert(ptr && length >= 0 && length < 9);
// This code is taken from gds__vax_integer
SINT64 value = 0;
int shift = 0;
while (length > 0)
{
--length;
value += ((SINT64) *ptr++) << shift;
shift += 8;
}
return value;
}
SLONG ClumpletReader::getInt() const
{
const FB_SIZE_T length = getClumpLength();
if (length > 4)
{
invalid_structure("length of integer exceeds 4 bytes", length);
return 0;
}
return fromVaxInteger(getBytes(), length);
}
double ClumpletReader::getDouble() const
{
const FB_SIZE_T length = getClumpLength();
if (length != sizeof(double))
{
invalid_structure("length of double must be equal 8 bytes", length);
return 0;
}
// based on XDR code
union {
double temp_double;
SLONG temp_long[2];
} temp;
fb_assert(sizeof(double) == sizeof(temp));
const UCHAR* ptr = getBytes();
temp.temp_long[FB_LONG_DOUBLE_FIRST] = fromVaxInteger(ptr, sizeof(SLONG));
temp.temp_long[FB_LONG_DOUBLE_SECOND] = fromVaxInteger(ptr + sizeof(SLONG), sizeof(SLONG));
return temp.temp_double;
}
ISC_TIMESTAMP ClumpletReader::getTimeStamp() const
{
ISC_TIMESTAMP value;
const FB_SIZE_T length = getClumpLength();
if (length != sizeof(ISC_TIMESTAMP))
{
invalid_structure("length of ISC_TIMESTAMP must be equal 8 bytes", length);
value.timestamp_date = 0;
value.timestamp_time = 0;
return value;
}
const UCHAR* ptr = getBytes();
value.timestamp_date = fromVaxInteger(ptr, sizeof(SLONG));
value.timestamp_time = fromVaxInteger(ptr + sizeof(SLONG), sizeof(SLONG));
return value;
}
SINT64 ClumpletReader::getBigInt() const
{
const FB_SIZE_T length = getClumpLength();
if (length > 8)
{
invalid_structure("length of BigInt exceeds 8 bytes", length);
return 0;
}
return fromVaxInteger(getBytes(), length);
}
AbstractString& ClumpletReader::getString(AbstractString& str) const
{
const UCHAR* ptr = getBytes();
const FB_SIZE_T length = getClumpLength();
str.assign(reinterpret_cast<const char*>(ptr), length);
str.recalculate_length();
if (str.length() + 1 < length)
{
invalid_structure("string length doesn't match with clumplet", str.length() + 1);
}
return str;
}
MetaName& ClumpletReader::getString(MetaName& str) const
{
const UCHAR* ptr = getBytes();
const FB_SIZE_T length = getClumpLength();
str.assign(reinterpret_cast<const char*>(ptr), length);
return str;
}
PathName& ClumpletReader::getPath(PathName& str) const
{
const UCHAR* ptr = getBytes();
const FB_SIZE_T length = getClumpLength();
str.assign(reinterpret_cast<const char*>(ptr), length);
str.recalculate_length();
if (str.length() + 1 < length)
{
invalid_structure("path length doesn't match with clumplet", str.length() + 1);
}
return str;
}
void ClumpletReader::getData(UCharBuffer& data) const
{
data.assign(getBytes(), getClumpLength());
}
bool ClumpletReader::getBoolean() const
{
const UCHAR* ptr = getBytes();
const FB_SIZE_T length = getClumpLength();
if (length > 1)
{
invalid_structure("length of boolean exceeds 1 byte", length);
return false;
}
return length && ptr[0];
}
ClumpletReader::SingleClumplet ClumpletReader::getClumplet() const
{
SingleClumplet rc;
rc.tag = getClumpTag();
rc.size = getClumpletSize(false, false, true);
rc.data = getBytes();
return rc;
}
const ClumpletReader::KindList ClumpletReader::dpbList[] = {
{ClumpletReader::Tagged, isc_dpb_version1},
{ClumpletReader::WideTagged, isc_dpb_version2},
{ClumpletReader::EndOfList, 0}
};
const ClumpletReader::KindList ClumpletReader::spbList[] = {
{ClumpletReader::SpbAttach, isc_spb_current_version},
{ClumpletReader::SpbAttach, isc_spb_version1},
{ClumpletReader::WideTagged, isc_spb_version3},
{ClumpletReader::EndOfList, 0}
};
AuthReader::AuthReader(const AuthBlock& authBlock)
: ClumpletReader(ClumpletReader::WideUnTagged, authBlock.begin(), authBlock.getCount())
{
rewind();
}
static inline void erase(NoCaseString& s)
{
s.erase();
}
static inline void set(NoCaseString& s, const ClumpletReader& rdr)
{
s.assign(rdr.getBytes(), rdr.getClumpLength());
}
bool AuthReader::getInfo(Info& info)
{
if (isEof())
{
return false;
}
erase(info.type);
erase(info.name);
erase(info.plugin);
erase(info.secDb);
erase(info.origPlug);
ClumpletReader internal(WideUnTagged, getBytes(), getClumpLength());
for (internal.rewind(); !internal.isEof(); internal.moveNext())
{
switch(internal.getClumpTag())
{
case AUTH_TYPE:
set(info.type, internal);
break;
case AUTH_NAME:
set(info.name, internal);
break;
case AUTH_PLUGIN:
set(info.plugin, internal);
break;
case AUTH_SECURE_DB:
set(info.secDb, internal);
break;
case AUTH_ORIG_PLUG:
set(info.origPlug, internal);
break;
default:
break;
}
}
return true;
}
#ifdef AUTH_BLOCK_DEBUG
void dumpAuthBlock(const char* text, ClumpletReader* pb, unsigned char param)
{
fprintf(stderr, "AuthBlock in %s:", text);
if (pb->find(param))
{
Firebird::AuthReader::AuthBlock tmp;
tmp.assign(pb->getBytes(), pb->getClumpLength());
Firebird::AuthReader rdr(tmp);
string name, plugin;
PathName secureDb;
bool x = false;
while (rdr.getInfo(&name, &plugin, &secureDb))
{
fprintf(stderr, " %s::%s::%s", name.c_str(), plugin.c_str(), secureDb.c_str());
x = true;
rdr.moveNext();
}
fprintf(stderr, "%s\n", x ? "" : " <empty>");
}
else
{
fprintf(stderr, " <missing>\n");
}
}
#endif
} // namespace
|
#include "ghpch.h"
#include "ParameterManager.h"
#include "game/parameter/ValueParameter.h"
#include "game/parameter/TextureParameter.h"
#include "core/SharedPointer.h"
#include "graphics/Textures.h"
namespace Ghurund {
const Ghurund::Core::Type& ParameterManager::GET_TYPE() {
static const auto CONSTRUCTOR = Constructor<ParameterManager>();
static const Ghurund::Core::Type TYPE = TypeBuilder<ParameterManager>(Ghurund::NAMESPACE_NAME, GH_STRINGIFY(ParameterManager))
.withConstructor(CONSTRUCTOR);
return TYPE;
}
ParameterManager::ParameterManager() {
float defaultFloat = 0;
::DirectX::XMFLOAT2 defaultFloat2 = {0,0};
::DirectX::XMFLOAT3 defaultFloat3 = {0,0,0};
::DirectX::XMMATRIX defaultMatrix = ::DirectX::XMMatrixIdentity();
SharedPointer<ValueParameter> viewportSize = ghnew ValueParameter(ParameterId::VIEWPORT_SIZE.ConstantName, ParameterType::FLOAT2, &defaultFloat2);
parameters.add(viewportSize);
::DirectX::XMFLOAT4 white(1, 1, 1, 1);
SharedPointer<ValueParameter> outlineColor = ghnew ValueParameter(ParameterId::OUTLINE_COLOR.ConstantName, ParameterType::COLOR, &white);
parameters.add(outlineColor);
::DirectX::XMFLOAT4 red(1, 0, 0, 1);
SharedPointer<ValueParameter> partyColor = ghnew ValueParameter(ParameterId::PARTY_COLOR.ConstantName, ParameterType::COLOR, &red);
parameters.add(partyColor);
SharedPointer<ValueParameter> random = ghnew ValueParameter(ParameterId::RANDOM.ConstantName, ParameterType::FLOAT, &defaultFloat);
parameters.add(random);
::DirectX::XMFLOAT4 gray(0.4f, 0.4f, 0.4f, 1);
SharedPointer<ValueParameter> ambientLight = ghnew ValueParameter(ParameterId::AMBIENT_LIGHT.ConstantName, ParameterType::COLOR, &gray);
parameters.add(ambientLight);
SharedPointer<ValueParameter> position = ghnew ValueParameter(ParameterId::POSITION.ConstantName, ParameterType::FLOAT3, &defaultFloat3);
parameters.add(position);
SharedPointer<ValueParameter> rotation = ghnew ValueParameter(ParameterId::ROTATION.ConstantName, ParameterType::FLOAT3, &defaultFloat3);
parameters.add(rotation);
SharedPointer<ValueParameter> scale = ghnew ValueParameter(ParameterId::SCALE.ConstantName, ParameterType::FLOAT3, &defaultFloat3);
parameters.add(scale);
SharedPointer<ValueParameter> cameraDirection = ghnew ValueParameter(ParameterId::CAMERA_DIRECTION.ConstantName, ParameterType::FLOAT3, &defaultFloat3);
parameters.add(cameraDirection);
SharedPointer<ValueParameter> cameraPosition = ghnew ValueParameter(ParameterId::CAMERA_POSITION.ConstantName, ParameterType::FLOAT3, &defaultFloat3);
parameters.add(cameraPosition);
SharedPointer<ValueParameter> cameraTarget = ghnew ValueParameter(ParameterId::CAMERA_TARGET.ConstantName, ParameterType::FLOAT3, &defaultFloat3);
parameters.add(cameraTarget);
SharedPointer<ValueParameter> cameraUp = ghnew ValueParameter(ParameterId::CAMERA_UP.ConstantName, ParameterType::FLOAT3, &defaultFloat3);
parameters.add(cameraUp);
SharedPointer<ValueParameter> cameraRight = ghnew ValueParameter(ParameterId::CAMERA_RIGHT.ConstantName, ParameterType::FLOAT3, &defaultFloat3);
parameters.add(cameraRight);
SharedPointer<ValueParameter> fov = ghnew ValueParameter(ParameterId::FOV.ConstantName, ParameterType::FLOAT, &defaultFloat);
parameters.add(fov);
SharedPointer<ValueParameter> zNear = ghnew ValueParameter(ParameterId::ZNEAR.ConstantName, ParameterType::FLOAT, &defaultFloat);
parameters.add(zNear);
SharedPointer<ValueParameter> zFar = ghnew ValueParameter(ParameterId::ZFAR.ConstantName, ParameterType::FLOAT, &defaultFloat);
parameters.add(zFar);
SharedPointer<ValueParameter> world = ghnew ValueParameter(ParameterId::WORLD.ConstantName, ParameterType::MATRIX, &defaultMatrix);
parameters.add(world);
SharedPointer<ValueParameter> worldIT = ghnew ValueParameter(ParameterId::WORLD_IT.ConstantName, ParameterType::MATRIX, &defaultMatrix);
parameters.add(worldIT);
SharedPointer<ValueParameter> view = ghnew ValueParameter(ParameterId::VIEW.ConstantName, ParameterType::MATRIX, &defaultMatrix);
parameters.add(view);
SharedPointer<ValueParameter> projection = ghnew ValueParameter(ParameterId::PROJECTION.ConstantName, ParameterType::MATRIX, &defaultMatrix);
parameters.add(projection);
SharedPointer<ValueParameter> viewProjection = ghnew ValueParameter(ParameterId::VIEW_PROJECTION.ConstantName, ParameterType::MATRIX, &defaultMatrix);
parameters.add(viewProjection);
SharedPointer<ValueParameter> viewProjectionInv = ghnew ValueParameter(ParameterId::VIEW_PROJECTION_INV.ConstantName, ParameterType::MATRIX, &defaultMatrix);
parameters.add(viewProjectionInv);
SharedPointer<TextureParameter> diffuseTextureParameter = ghnew TextureParameter(ParameterId::DIFFUSE_TEXTURE.ConstantName);
parameters.add(diffuseTextureParameter);
SharedPointer<TextureParameter> specularTextureParameter = ghnew TextureParameter(ParameterId::SPECULAR_TEXTURE.ConstantName);
parameters.add(specularTextureParameter);
SharedPointer<TextureParameter> normalTextureParameter = ghnew TextureParameter(ParameterId::NORMAL_TEXTURE.ConstantName);
parameters.add(normalTextureParameter);
}
void ParameterManager::initDefaultTextures(ResourceManager& manager, Graphics& graphics, CommandList& commandList) {
SharedPointer<Texture> diffuseTexture = Textures::makeDefaultDiffuse(graphics, commandList, manager);
TextureParameter* diffuseTextureParameter = (TextureParameter*)parameters[(size_t)ParameterId::DIFFUSE_TEXTURE.Value];
diffuseTextureParameter->Value = diffuseTexture;
SharedPointer<Texture> specularTexture = Textures::makeDefaultSpecular(graphics, commandList, manager);
TextureParameter* specularTextureParameter = (TextureParameter*)parameters[(size_t)ParameterId::SPECULAR_TEXTURE.Value];
specularTextureParameter->Value = specularTexture;
SharedPointer<Texture> normalTexture = Textures::makeDefaultNormal(graphics, commandList, manager);
TextureParameter* normalTextureParameter = (TextureParameter*)parameters[(size_t)ParameterId::NORMAL_TEXTURE.Value];
normalTextureParameter->Value = normalTexture;
}
}
|
// Copyright (C) 2020 THL A29 Limited, a Tencent company.
// All rights reserved.
// Licensed under the BSD 3-Clause License (the "License"); you may
// not use this file except in compliance with the License. You may
// obtain a copy of the License at
// https://opensource.org/licenses/BSD-3-Clause
// 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.
// See the AUTHORS file for names of contributors.
#include "bert_model.h"
#include <string>
#include <utility>
#include "cnpy.h"
#include "turbo_transformers/core/tensor_copy.h"
#include "turbo_transformers/layers/bert_attention.h"
#include "turbo_transformers/layers/bert_embedding.h"
#include "turbo_transformers/layers/bert_intermediate.h"
#include "turbo_transformers/layers/bert_output.h"
#include "turbo_transformers/layers/bert_pooler.h"
#include "turbo_transformers/layers/kernels/common.h"
#include "turbo_transformers/layers/prepare_bert_masks.h"
#include "turbo_transformers/layers/sequence_pool.h"
#include "turbo_transformers/loaders/npz_load.h"
using namespace turbo_transformers::loaders;
static std::unique_ptr<layers::BERTEmbedding> LoadEmbedding(NPZMapView npz,
DLDeviceType dev) {
NPZLoader params(std::move(npz), dev);
return std::unique_ptr<layers::BERTEmbedding>(new layers::BERTEmbedding(
params["word_embeddings.weight"], params["position_embeddings.weight"],
params["token_type_embeddings.weight"], params["LayerNorm.weight"],
params["LayerNorm.bias"]));
}
static std::unique_ptr<layers::BertPooler> LoadPooler(NPZMapView npz,
DLDeviceType dev) {
NPZLoader params(std::move(npz), dev);
return std::unique_ptr<layers::BertPooler>(
new layers::BertPooler(params["dense.weight"], params["dense.bias"]));
}
struct BERTLayer {
explicit BERTLayer(NPZLoader params, int64_t n_heads) {
// define layer network here
attention_.reset(new layers::BertAttention(
params["attention.qkv.weight"], params["attention.qkv.bias"],
params["attention.output.dense.weight"],
params["attention.output.dense.bias"],
params["attention.output.LayerNorm.weight"],
params["attention.output.LayerNorm.bias"], n_heads));
intermediate_.reset(
new layers::BertIntermediate(params["intermediate.dense.weight"],
params["intermediate.dense.bias"]));
output_.reset(new layers::BertOutput(
params["output.dense.weight"], params["output.dense.bias"],
params["output.LayerNorm.weight"], params["output.LayerNorm.bias"]));
}
void operator()(core::Tensor &hidden, core::Tensor &mask,
core::Tensor *attention_out, core::Tensor *intermediate_out,
core::Tensor *output) {
(*attention_)(hidden, mask, attention_out);
(*intermediate_)(*attention_out, intermediate_out);
(*output_)(*intermediate_out, *attention_out, output);
}
std::unique_ptr<layers::BertAttention> attention_;
std::unique_ptr<layers::BertIntermediate> intermediate_;
std::unique_ptr<layers::BertOutput> output_;
};
struct BertModel::Impl {
explicit Impl(const std::string &filename, DLDeviceType device_type,
size_t n_layers, int64_t n_heads)
: device_type_(device_type) {
auto npz = cnpy::npz_load(filename);
NPZMapView root("", &npz);
// HERE define your network model
embedding_ = LoadEmbedding(root.Sub("embeddings"), device_type);
for (size_t i = 0; i < n_layers; ++i) {
auto view = root.Sub("encoder.layer." + std::to_string(i));
NPZLoader params(view, device_type);
encoders_.emplace_back(std::move(params), n_heads);
}
if (root.IsExist("pooler")) {
pooler_ = LoadPooler(root.Sub("pooler"), device_type);
}
}
// preprocess helper function
template <typename T>
void PadTensor(const std::vector<std::vector<T>> &data_array, int64_t n,
int64_t m, T pad_val, DLDeviceType device_type,
core::Tensor *output_tensor) {
if (m == 0 || n == 0 || data_array.size() == 0) {
return;
}
core::Tensor cpu_tensor(nullptr);
T *tensor_data_ptr;
if (device_type == DLDeviceType::kDLGPU) {
tensor_data_ptr = cpu_tensor.Reshape<T>({n, m}, DLDeviceType::kDLCPU, 0);
output_tensor->Reshape<T>({n, m}, device_type, 0);
} else {
tensor_data_ptr = output_tensor->Reshape<T>({n, m}, device_type, 0);
}
for (int64_t i = 0; i < n; ++i, tensor_data_ptr += m) {
auto &line = data_array[i];
if (line.size() > 0) {
core::Copy(line.data(), line.size(), DLDeviceType::kDLCPU,
DLDeviceType::kDLCPU, tensor_data_ptr);
}
if (line.size() != static_cast<size_t>(m)) {
layers::kernels::common::Fill(tensor_data_ptr + line.size(),
static_cast<size_t>(m) - line.size(),
pad_val, DLDeviceType::kDLCPU);
}
}
if (device_type == DLDeviceType::kDLGPU) {
core::Copy<T>(cpu_tensor, *output_tensor);
}
}
// do inference
std::vector<float> operator()(
const std::vector<std::vector<int64_t>> &inputs,
const std::vector<std::vector<int64_t>> &poistion_ids,
const std::vector<std::vector<int64_t>> &segment_ids, PoolType pooling,
bool use_pooler) {
core::Tensor inputs_tensor{nullptr};
core::Tensor masks_tensor{nullptr};
core::Tensor gpuInputs_tensor{nullptr};
core::Tensor gpuMasks_tensor{nullptr};
int64_t max_seq_len =
std::accumulate(inputs.begin(), inputs.end(), 0,
[](size_t len, const std::vector<int64_t> &input_ids) {
return std::max(len, input_ids.size());
});
int64_t batch_size = inputs.size();
auto *iptr = inputs_tensor.Reshape<int64_t>(
{batch_size, max_seq_len}, DLDeviceType::kDLCPU, 0,
"PrepareBertMasks/seqids/Reshape");
auto *mptr = masks_tensor.Reshape<int64_t>(
{batch_size, max_seq_len}, DLDeviceType::kDLCPU, 0,
"PrepareBertMasks/attmask/Reshape");
for (size_t i = 0; i < inputs.size();
++i, iptr += max_seq_len, mptr += max_seq_len) {
auto &input = inputs[i];
// TODO(jiaruifang) Bert_Attention use mask value as 1 to indicate a valid
// position.
std::copy(input.begin(), input.end(), iptr);
std::fill(mptr, mptr + input.size(), 1);
if (input.size() != static_cast<size_t>(max_seq_len)) {
std::fill(iptr + input.size(), iptr + max_seq_len, 0);
std::fill(mptr + input.size(), mptr + max_seq_len, 0);
}
}
if (device_type_ == DLDeviceType::kDLGPU) {
gpuInputs_tensor.Reshape<int64_t>({batch_size, max_seq_len},
DLDeviceType::kDLGPU, 0,
"PrepareBertMasks/seqids/Reshape");
gpuMasks_tensor.Reshape<int64_t>({batch_size, max_seq_len},
DLDeviceType::kDLGPU, 0,
"PrepareBertMasks/attmask/Reshape");
core::Copy(inputs_tensor.data<int64_t>(), inputs_tensor.numel(),
DLDeviceType::kDLCPU, gpuInputs_tensor);
core::Copy(masks_tensor.data<int64_t>(), masks_tensor.numel(),
DLDeviceType::kDLCPU, gpuMasks_tensor);
}
auto &inputIds =
device_type_ == DLDeviceType::kDLCPU ? inputs_tensor : gpuInputs_tensor;
core::Tensor seqType(nullptr);
core::Tensor positionIds(nullptr);
core::Tensor extendedAttentionMask(nullptr);
if (poistion_ids.size() != 0) {
TT_ENFORCE_EQ(
poistion_ids.size(), static_cast<size_t>(batch_size),
"Position ids should have the same batch size as input ids");
PadTensor(poistion_ids, batch_size, max_seq_len, static_cast<int64_t>(0),
device_type_, &positionIds);
}
if (segment_ids.size() != 0) {
TT_ENFORCE_EQ(segment_ids.size(), static_cast<size_t>(batch_size),
"Segment ids should have the same batch size as input ids");
PadTensor(segment_ids, batch_size, max_seq_len, static_cast<int64_t>(0),
device_type_, &seqType);
}
layers::PrepareBertMasks()(
inputIds,
device_type_ == DLDeviceType::kDLCPU ? &masks_tensor : &gpuMasks_tensor,
&seqType, &positionIds, &extendedAttentionMask);
// start inference the BERT
core::Tensor hidden(nullptr);
(*embedding_)(inputIds, positionIds, seqType, &hidden);
core::Tensor attOut(nullptr);
core::Tensor intermediateOut(nullptr);
for (auto &layer : encoders_) {
layer(hidden, extendedAttentionMask, &attOut, &intermediateOut, &hidden);
}
std::vector<float> vec;
if (use_pooler) {
core::Tensor output(nullptr);
core::Tensor poolingOutput(nullptr);
layers::SequencePool(static_cast<layers::types::PoolType>(pooling))(
hidden, &poolingOutput);
(*pooler_)(poolingOutput, &output);
vec.resize(output.numel());
core::Copy(output, vec);
} else {
vec.resize(hidden.numel());
core::Copy(hidden, vec);
}
return vec;
}
std::unique_ptr<layers::BERTEmbedding> embedding_;
std::vector<BERTLayer> encoders_;
std::unique_ptr<layers::BertPooler> pooler_;
DLDeviceType device_type_;
};
BertModel::BertModel(const std::string &filename, DLDeviceType device_type,
size_t n_layers, int64_t n_heads)
: m_(new Impl(filename, device_type, n_layers, n_heads)) {}
std::vector<float> BertModel::operator()(
const std::vector<std::vector<int64_t>> &inputs,
const std::vector<std::vector<int64_t>> &poistion_ids,
const std::vector<std::vector<int64_t>> &segment_ids, PoolType pooling,
bool use_pooler) const {
return m_->operator()(inputs, poistion_ids, segment_ids, pooling, use_pooler);
}
BertModel::~BertModel() = default;
|
/*******************************************************************************
* Copyright 2016-2018 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
#ifndef MKLDNN_TEST_COMMON_HPP
#define MKLDNN_TEST_COMMON_HPP
#include <numeric>
#include <vector>
#include <cmath>
#include <stdint.h>
#include "gtest/gtest.h"
#if defined(_MSC_VER) && !defined(__clang__) && !defined(__INTEL_COMPILER)
#define collapse(x)
#endif
#include "mkldnn.hpp"
template <typename data_t> struct data_traits { };
template <> struct data_traits<float> {
static const auto data_type = mkldnn::memory::data_type::f32;
};
template <> struct data_traits<uint8_t> {
static const auto data_type = mkldnn::memory::data_type::u8;
};
template <> struct data_traits<int8_t> {
static const auto data_type = mkldnn::memory::data_type::s8;
};
template <> struct data_traits<int16_t> {
static const auto data_type = mkldnn::memory::data_type::s16;
};
template <> struct data_traits<int32_t> {
static const auto data_type = mkldnn::memory::data_type::s32;
};
template <typename T> inline void assert_eq(T a, T b);
template <> inline void assert_eq<float>(float a, float b) {
ASSERT_FLOAT_EQ(a, b);
}
template <typename data_t> inline data_t out_round(float x,
mkldnn_round_mode_t rmode = mkldnn_round_nearest)
{ return (data_t)(rmode == mkldnn_round_down ? floorf(x) : nearbyintf(x)); }
template <> inline float out_round<float>(float x, mkldnn_round_mode_t rmode)
{ (void)rmode; return x; }
inline int right_padding(int i, int o, int k, int p, int s, int d = 0) {
return (o - 1) * s + (k - 1) * (d + 1) - (p + i - 1);
}
template <typename data_t> struct acc_t { typedef data_t type; };
template<> struct acc_t<int8_t> { typedef int type; };
template<> struct acc_t<uint8_t> { typedef int type; };
inline size_t map_index(const mkldnn::memory::desc &md, size_t index,
bool with_padding = true) {
#if 1 || MKLDNN_JIT_TYPES > 0
using fmt = mkldnn::memory::format;
const fmt fwd_weights_g_qvnni = fmt::gOIhw8i16o2i;
const fmt fwd_weights_qvnni = fmt::OIhw8i16o2i;
const fmt bwd_weights_g_qvnni = fmt::gOIhw8o16i2o;
const fmt bwd_weights_qvnni = fmt::OIhw8o16i2o;
const fmt fwd_weights_g_vnni = fmt::gOIhw4i16o4i;
const fmt fwd_weights_vnni = fmt::OIhw4i16o4i;
const bool with_groups = (md.data.format == fwd_weights_g_qvnni)
|| (md.data.format == bwd_weights_g_qvnni)
|| (md.data.format == fwd_weights_g_vnni);
const bool qvnni = (md.data.format == fwd_weights_g_qvnni)
|| (md.data.format == bwd_weights_g_qvnni)
|| (md.data.format == fwd_weights_qvnni)
|| (md.data.format == bwd_weights_qvnni);
const bool vnni = (md.data.format == fwd_weights_g_vnni)
|| (md.data.format == fwd_weights_vnni);
const bool fwd_wei = (md.data.format == fwd_weights_g_qvnni)
|| (md.data.format == fwd_weights_qvnni)
|| (md.data.format == fwd_weights_g_vnni)
|| (md.data.format == fwd_weights_vnni);
const bool bwd_wei = (md.data.format == bwd_weights_g_qvnni)
|| (md.data.format == bwd_weights_qvnni);
#else
//const bool with_groups = false; // unused
//const bool qvnni = false;
//const bool vnni = false;
const bool fwd_wei = false;
const bool bwd_wei = false;
#endif
const int ndims = md.data.ndims;
const int *dims = md.data.dims;
const int *pdims = md.data.layout_desc.blocking.padding_dims;
const int *optd = md.data.layout_desc.blocking.offset_padding_to_data;
auto *strides_block = md.data.layout_desc.blocking.strides[0];
auto *strides_within_block = md.data.layout_desc.blocking.strides[1];
size_t ph_index = 0;
size_t oc_lb = 0, ic_sb = 0,
oc_sb = 0, ic_lb = 0;
for (int rd = 0; rd < ndims; ++rd) {
int d = ndims - rd - 1;
EXPECT_LE(dims[d], pdims[d]);
int cur_dim = with_padding ? pdims[d] : dims[d];
EXPECT_GT(cur_dim, 0);
int cur_block = md.data.layout_desc.blocking.block_dims[d];
size_t pos_d = /*static_cast<ssize_t>*/(index % cur_dim);
EXPECT_GE(optd[d], 0);
size_t cur_pos = optd[d] + pos_d;
size_t cur_pos_block = cur_pos / cur_block;
size_t cur_pos_within_block = cur_pos % cur_block;
#if 1 || MKLDNN_JIT_TYPES > 0
if (d == (with_groups + 0)) {
if (qvnni) { oc_lb = pos_d % 16; oc_sb = pos_d % 2; }
else if (vnni) { oc_lb = pos_d % 16; }
}
if (d == (with_groups + 1)) {
if (qvnni) { ic_sb = pos_d % 2; ic_lb = pos_d % 16; }
else if (vnni) { ic_sb = pos_d % 4; }
}
#endif
ph_index += cur_pos_block*strides_block[d];
ph_index += cur_pos_within_block*strides_within_block[d];
index /= cur_dim;
}
//int scale = (vnni) ? 3 : 1;
int scale = 1;
#if 1 || MKLDNN_JIT_TYPES > 0
if (vnni) scale = 3;
#endif
if (fwd_wei) {
//ph_index += -16 * ic_2 + oc_16 + ic_2;
ph_index += scale * oc_lb + ic_sb;
EXPECT_GE(ph_index, 16 * ic_sb);
ph_index -= 16 * ic_sb;
} else
if (bwd_wei) {
//ph_index += -16 * oc_2 + ic_16 + oc_2;
ph_index += ic_lb + oc_sb;
EXPECT_GE(ph_index, 16 * oc_sb);
ph_index -= 16 * oc_sb;
}
ph_index += md.data.layout_desc.blocking.offset_padding;
return ph_index;
}
#define MAX_NDIMS 12
// check_zero_tail - check on zero or set to zero padded memory
template <typename data_t>
void check_zero_tail(int set_zero_flag, mkldnn::memory &src) {
data_t *src_data = (data_t *)src.get_data_handle();
const mkldnn::memory::desc src_d = src.get_primitive_desc().desc();
const int ndims = src_d.data.ndims;
const int *dims = src_d.data.dims;
const int *pdims = src_d.data.layout_desc.blocking.padding_dims;
size_t idx[MAX_NDIMS] = {}, str[MAX_NDIMS] = {};
size_t nelems = 1;
int tail_flag = 0;
for (int i = 0; i < ndims; ++i) {
if (dims[ndims-i-1] != pdims[ndims-i-1]) tail_flag = 1;
nelems *= pdims[ndims-i-1];
idx[i] = 0;
str[i] = (i==0) ? 1 : str[i-1] * pdims[ndims-i];
}
if (tail_flag == 0) return;
for (size_t i = 0; i < nelems; ++i) {
size_t off = 0;
bool flag = 0;
for (int j = 0; j < ndims; ++j) {
off += idx[j] * str[j];
if (idx[j] >= (size_t)dims[ndims-j-1]) flag = 1;
}
if (flag == 1) {
size_t blk_off = map_index(src_d,off);
if (set_zero_flag) {
src_data[blk_off] = 0.0;
} else {
EXPECT_EQ(src_data[blk_off], 0.0) << " blk_off = " << blk_off
<< "off = " << off;
}
}
/*Update idx*/
for (int j = 0; j < ndims; ++j) {
idx[j] ++;
if (idx[j] < (size_t)pdims[ndims-j-1]) break;
idx[j] = 0;
}
}
}
inline mkldnn::memory::desc create_md(mkldnn::memory::dims dims,
mkldnn::memory::data_type data_type, mkldnn::memory::format fmt) {
using f = mkldnn::memory::format;
size_t ndims = 0;
switch (fmt) {
case f::x:
ndims = 1; break;
//---------------
case f::nc:
case f::oi:
case f::io:
ndims = 2; break;
case f::nchw:
case f::nhwc:
case f::chwn:
case f::nChw8c:
case f::nChw16c:
case f::oihw:
case f::hwio:
case f::OIhw8i8o:
case f::OIhw16i16o:
case f::OIhw8i16o2i:
case f::OIhw8o16i2o:
case f::OIhw4i16o4i:
case f::OIhw8o8i:
case f::OIhw16o16i:
case f::IOhw16o16i:
case f::Ohwi8o:
case f::Ohwi16o:
ndims = 4; break;
//---------------
case f::ncdhw:
case f::ndhwc:
case f::nCdhw8c:
case f::nCdhw16c:
case f::dhwio:
case f::oidhw:
case f::goihw:
case f::hwigo:
case f::OIdhw8i8o:
case f::OIdhw16i16o:
case f::OIdhw8o8i:
case f::OIdhw16o16i:
case f::gOhwi8o:
case f::Goihw8g:
case f::Goihw16g:
case f::gOIhw8i8o:
case f::gOIhw16i16o:
case f::gOIhw8i16o2i:
case f::gOIhw8o16i2o:
case f::gOIhw4i16o4i:
case f::gOIhw8o8i:
case f::gOIhw16o16i:
case f::gIOhw16o16i:
ndims = 5; break;
//---------------
case f::goidhw:
case f::gOIdhw8i8o:
case f::gOIdhw16i16o:
case f::gOIdhw8o8i:
case f::gOIdhw16o16i:
case f::gOdhwi16o:
ndims = 6; break;
//---------------
case f::format_undef:
ndims = 0; break;
case f::any:
return mkldnn::memory::desc(dims, data_type, fmt);
default: EXPECT_TRUE(false) << "test does not support format: " << int(fmt);
}
EXPECT_EQ(dims.size(), ndims) << "dims and format are inconsistent";
return mkldnn::memory::desc(dims, data_type, fmt);
}
template <typename data_t>
static inline data_t set_value(size_t index, data_t mean, data_t deviation,
double sparsity)
{
if (data_traits<data_t>::data_type == mkldnn::memory::data_type::f32) {
const size_t group_size = (size_t)(1. / sparsity);
const size_t group = index / group_size;
const size_t in_group = index % group_size;
const bool fill = in_group == ((group % 1637) % group_size);
return fill ? static_cast<data_t>(mean + deviation * sinf(float(index % 37)))
: data_t{0};
} else if (data_traits<data_t>::data_type == mkldnn::memory::data_type::s32
|| data_traits<data_t>::data_type == mkldnn::memory::data_type::s16
|| data_traits<data_t>::data_type == mkldnn::memory::data_type::s8) {
return data_t(rand() % 21 - 10);
} else if (data_traits<data_t>::data_type == mkldnn::memory::data_type::u8) {
return data_t(rand() % 17);
} else {
return data_t(0);
}
}
template <typename data_t>
static void fill_data(const size_t size, data_t *data, data_t mean,
data_t deviation, double sparsity = 1.)
{
OMP(parallel for schedule(static))//;
for (ptrdiff_t n = 0; n < (ptrdiff_t)size; n++) {
data[n] = set_value<data_t>(n, mean, deviation, sparsity);
}
}
template <typename data_t>
static void fill_data(const size_t size, data_t *data, double sparsity = 1.,
bool init_negs = false)
{
OMP(parallel for schedule(static))//;
for (ptrdiff_t n = 0; n < (ptrdiff_t)size; n++) {
data[n] = set_value<data_t>(n, data_t(1), data_t(2e-1), sparsity);
if (init_negs && n%4 == 0U)
data[n] = static_cast<data_t>(-data[n]); // weird for unsigned types!
}
}
template <typename data_t>
static void compare_data(mkldnn::memory& ref, mkldnn::memory& dst)
{
using data_type = mkldnn::memory::data_type;
ASSERT_TRUE(data_traits<data_t>::data_type == data_type::f32 ||
data_traits<data_t>::data_type == data_type::s32);
/* Note: size_t incompatible with MSVC++ */
auto ref_desc = ref.get_primitive_desc().desc();
auto dst_desc = dst.get_primitive_desc().desc();
ASSERT_TRUE(ref_desc.data.ndims == dst_desc.data.ndims);
auto ndims = ref_desc.data.ndims;
for (auto d = 0; d < ndims; ++d) {
ASSERT_TRUE(ref_desc.data.dims[d] == dst_desc.data.dims[d]);
}
auto dims = ref_desc.data.dims;
ptrdiff_t num = 1;
for (auto d = 0; d < ndims; ++d) {
num *= dims[d];
}
data_t *ref_data = (data_t *)ref.get_data_handle();
data_t *dst_data = (data_t *)dst.get_data_handle();
OMP(parallel for schedule(static))//;
for (ptrdiff_t i = 0; i < num; ++i) {
data_t ref = ref_data[map_index(ref_desc, i)];
data_t got = dst_data[map_index(dst_desc, i)];
if (data_traits<data_t>::data_type == data_type::f32) {
data_t diff = got - ref;
data_t e = (std::abs(ref) > (data_t)1e-4) ? diff / ref : diff;
EXPECT_NEAR(e, (data_t)0.0, (data_t)1e-4)
<< "Index: " << i << " Total: " << num;
} else {
EXPECT_EQ(ref, got) << "Index: " << i << " Total: " << num;
}
}
}
inline const char *query_impl_info(const_mkldnn_primitive_desc_t pd) {
const char *str;
mkldnn_primitive_desc_query(pd, mkldnn_query_impl_info_str, 0, &str);
return str;
};
mkldnn_status_t get_conv_impl_status(const_mkldnn_primitive_desc_t pd, const char *match_str){
const char* conv_str = query_impl_info(pd);
if( strstr(conv_str, match_str) != NULL)
return mkldnn_status_t::mkldnn_success;
return mkldnn_status_t::mkldnn_unimplemented;
};
struct test_convolution_sizes_t {
test_convolution_sizes_t(
int mb,
int ng,
int ic, int ih, int iw,
int oc, int oh, int ow,
int kh, int kw,
int padh, int padw,
int strh, int strw,
int dilh=0, int dilw=0
) :
mb(mb),
ng(ng),
ic(ic), ih(ih), iw(iw),
oc(oc), oh(oh), ow(ow),
kh(kh), kw(kw),
padh(padh), padw(padw),
strh(strh), strw(strw),
dilh(dilh), dilw(dilw) {}
int mb;
int ng;
int ic, ih, iw;
int oc, oh, ow;
int kh, kw;
int padh, padw;
int strh, strw;
int dilh, dilw;
};
struct test_convolution_attr_t {
struct scale_t {
enum policy_t { NONE = 0, COMMON };
bool is_def() const { return policy != NONE; }
scale_t (float s, policy_t p = NONE) :
scale(s) { policy = p; }
policy_t policy;
float scale;
};
void mkldnn_attr_recreate() {
mkl_attr = mkldnn::primitive_attr();
mkl_attr.set_int_output_round_mode(rmode);
if (oscale.is_def()) {
const int count = 1;
const int mask = 0;
std::vector<float> s(count, oscale.scale);
mkl_attr.set_output_scales(mask, s);
}
}
test_convolution_attr_t(mkldnn::round_mode rm, float s,
scale_t::policy_t p = scale_t::policy_t::NONE) :
rmode(rm), oscale(s, p), mkl_attr() {}
test_convolution_attr_t() :
rmode(mkldnn::round_mode::round_nearest),
oscale(1.0), mkl_attr() {}
mkldnn::round_mode rmode;
scale_t oscale;
mkldnn::primitive_attr mkl_attr;
};
struct test_convolution_formats_t {
mkldnn::memory::format src_format;
mkldnn::memory::format weights_format;
mkldnn::memory::format bias_format;
mkldnn::memory::format dst_format;
};
struct test_convolution_params_t {
const mkldnn::engine::kind engine_kind;
mkldnn::algorithm aalgorithm;
const float relu_negative_slope;
test_convolution_formats_t formats;
test_convolution_attr_t attr;
test_convolution_sizes_t sizes;
bool expect_to_fail;
mkldnn_status_t expected_status;
};
template<typename F> bool catch_expected_failures(const F &f,
bool expect_to_fail, mkldnn_status_t expected_status)
{
try {
f();
} catch (const mkldnn::error &e) {
// Rethrow the exception if it is not expected or the error status did
// not match.
if (!(expect_to_fail) || e.status != (expected_status)) {
// Ignore unimplemented
if (e.status == mkldnn_unimplemented)
return true;
else
throw e;
}
// Return normally if the failure is expected
if (expect_to_fail)
return true;
}
// Throw an exception if the failure is expected but did not happen
if (expect_to_fail)
throw std::exception();
return false;
}
#define TEST_MALLOC_OFFSET 8
char *test_malloc(size_t size) {
void *ptr;
const size_t align = 64;
const size_t padded_size = TEST_MALLOC_OFFSET + size;
#ifdef _WIN32
ptr = _aligned_malloc(padded_size, align);
int rc = ((ptr) ? 0 : errno);
#else
int rc = ::posix_memalign(&ptr, align, padded_size);
#endif /* _WIN32 */
return rc == 0 ? (char*)ptr + TEST_MALLOC_OFFSET: 0;
}
void test_free(char *ptr) {
char *base_ptr = ptr - TEST_MALLOC_OFFSET;
#ifdef _WIN32
_aligned_free(base_ptr);
#else
return ::free(base_ptr);
#endif /* _WIN32 */
}
#undef TEST_MALLOC_OFFSET
class test_memory {
public:
test_memory(const mkldnn::memory::desc &d, const mkldnn::engine &e) {
auto pd = mkldnn::memory::primitive_desc(d, e);
pd_size_ = pd.get_size();
data_.reset(test_malloc(pd_size_), test_free);
mem_.reset(new mkldnn::memory(pd, data_.get()));
}
size_t get_size() const { return pd_size_; }
mkldnn::memory &get() { return *mem_; }
private:
std::shared_ptr<mkldnn::memory> mem_;
std::shared_ptr<char> data_;
size_t pd_size_;
};
#endif
|
#include "vtkUnstructuredGrid.h"
#include "vtkUnstructuredGridReader.h"
#include "vtkUnstructuredGridWriter.h"
#include "vtkMimxMapOriginalCellAndPointIds.h"
int main(int argc, char * argv [])
{
//if( argc < 3 )
//{
// std::cerr << "vtkMimxMapOriginalCellAndPointIds "
// << " InputVtkUnstructuredGrid"
// << std::endl;
// return EXIT_FAILURE;
//}
vtkUnstructuredGridReader *reader1 = vtkUnstructuredGridReader::New();
//reader1->SetFileName(argv[1]);
reader1->SetFileName("D:/OpenSource/IAFEMESH/IaFeMesh/Testing/Data/FullMesh.vtk");
reader1->Update();
vtkUnstructuredGridReader *reader2 = vtkUnstructuredGridReader::New();
//reader2->SetFileName(argv[2]);
reader2->SetFileName("D:/OpenSource/IAFEMESH/IaFeMesh/Testing/Data/PartialMesh.vtk");
reader2->Update();
vtkMimxMapOriginalCellAndPointIds *MapOriginalCellAndPointIds =
vtkMimxMapOriginalCellAndPointIds::New();
MapOriginalCellAndPointIds->SetCompleteMesh(reader1->GetOutput());
MapOriginalCellAndPointIds->SetPartialMesh(reader2->GetOutput());
MapOriginalCellAndPointIds->Update();
vtkUnstructuredGridWriter *writer = vtkUnstructuredGridWriter::New();
writer->SetInput(reader2->GetOutput());
writer->SetFileName("PartialMeshWithIds.vtk");
writer->Write();
reader1->Delete();
reader2->Delete();
MapOriginalCellAndPointIds->Delete();
writer->Delete();
}
|
/**
* Copyright 2020 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ps/core/communicator/tcp_server.h"
#include <arpa/inet.h>
#include <event2/buffer.h>
#include <event2/buffer_compat.h>
#include <event2/bufferevent.h>
#include <event2/event.h>
#include <event2/listener.h>
#include <event2/util.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/socket.h>
#include <csignal>
#include <utility>
namespace mindspore {
namespace ps {
namespace core {
TcpConnection::~TcpConnection() { bufferevent_free(buffer_event_); }
void TcpConnection::InitConnection(const messageReceive &callback) { tcp_message_handler_.SetCallback(callback); }
void TcpConnection::OnReadHandler(const void *buffer, size_t num) {
MS_EXCEPTION_IF_NULL(buffer);
tcp_message_handler_.ReceiveMessage(buffer, num);
}
void TcpConnection::SendMessage(const void *buffer, size_t num) const {
MS_EXCEPTION_IF_NULL(buffer);
MS_EXCEPTION_IF_NULL(buffer_event_);
bufferevent_lock(buffer_event_);
if (bufferevent_write(buffer_event_, buffer, num) == -1) {
MS_LOG(ERROR) << "Write message to buffer event failed!";
}
bufferevent_unlock(buffer_event_);
}
const TcpServer *TcpConnection::GetServer() const { return server_; }
const evutil_socket_t &TcpConnection::GetFd() const { return fd_; }
void TcpConnection::set_callback(const Callback &callback) { callback_ = callback; }
bool TcpConnection::SendMessage(const std::shared_ptr<CommMessage> &message) const {
MS_EXCEPTION_IF_NULL(buffer_event_);
MS_EXCEPTION_IF_NULL(message);
bufferevent_lock(buffer_event_);
bool res = true;
size_t buf_size = message->ByteSizeLong();
if (bufferevent_write(buffer_event_, &buf_size, sizeof(buf_size)) == -1) {
MS_LOG(ERROR) << "Event buffer add header failed!";
res = false;
}
if (bufferevent_write(buffer_event_, message->SerializeAsString().data(), buf_size) == -1) {
MS_LOG(ERROR) << "Event buffer add protobuf data failed!";
res = false;
}
bufferevent_unlock(buffer_event_);
return res;
}
bool TcpConnection::SendMessage(const std::shared_ptr<MessageMeta> &meta, const Protos &protos, const void *data,
size_t size) const {
MS_EXCEPTION_IF_NULL(buffer_event_);
MS_EXCEPTION_IF_NULL(meta);
MS_EXCEPTION_IF_NULL(data);
bufferevent_lock(buffer_event_);
bool res = true;
MessageHeader header;
header.message_proto_ = protos;
header.message_meta_length_ = SizeToUint(meta->ByteSizeLong());
header.message_length_ = size + header.message_meta_length_;
if (bufferevent_write(buffer_event_, &header, sizeof(header)) == -1) {
MS_LOG(ERROR) << "Event buffer add header failed!";
res = false;
}
if (bufferevent_write(buffer_event_, meta->SerializeAsString().data(), meta->ByteSizeLong()) == -1) {
MS_LOG(ERROR) << "Event buffer add protobuf data failed!";
res = false;
}
if (bufferevent_write(buffer_event_, data, size) == -1) {
MS_LOG(ERROR) << "Event buffer add protobuf data failed!";
res = false;
}
int result = bufferevent_flush(buffer_event_, EV_READ | EV_WRITE, BEV_FLUSH);
if (result < 0) {
bufferevent_unlock(buffer_event_);
MS_LOG(EXCEPTION) << "Bufferevent flush failed!";
}
bufferevent_unlock(buffer_event_);
return res;
}
TcpServer::TcpServer(const std::string &address, std::uint16_t port, Configuration *const config)
: base_(nullptr),
signal_event_(nullptr),
listener_(nullptr),
server_address_(std::move(address)),
server_port_(port),
is_stop_(true),
config_(config),
max_connection_(0) {}
TcpServer::~TcpServer() {
if (signal_event_ != nullptr) {
event_free(signal_event_);
signal_event_ = nullptr;
}
if (listener_ != nullptr) {
evconnlistener_free(listener_);
listener_ = nullptr;
}
if (base_ != nullptr) {
event_base_free(base_);
base_ = nullptr;
}
}
void TcpServer::SetServerCallback(const OnConnected &client_conn, const OnDisconnected &client_disconn,
const OnAccepted &client_accept) {
this->client_connection_ = client_conn;
this->client_disconnection_ = client_disconn;
this->client_accept_ = client_accept;
}
void TcpServer::set_timer_once_callback(const OnTimerOnce &timer) { on_timer_once_callback_ = timer; }
void TcpServer::set_timer_callback(const OnTimer &timer) { on_timer_callback_ = timer; }
void TcpServer::Init() {
int result = evthread_use_pthreads();
if (result != 0) {
MS_LOG(EXCEPTION) << "Use event pthread failed!";
}
is_stop_ = false;
base_ = event_base_new();
MS_EXCEPTION_IF_NULL(base_);
if (!CommUtil::CheckIp(server_address_)) {
MS_LOG(EXCEPTION) << "The tcp server ip:" << server_address_ << " is illegal!";
}
MS_EXCEPTION_IF_NULL(config_);
max_connection_ = kConnectionNumDefault;
if (config_->Exists(kConnectionNum)) {
max_connection_ = config_->GetInt(kConnectionNum, 0);
}
MS_LOG(INFO) << "The max connection is:" << max_connection_;
struct sockaddr_in sin {};
if (memset_s(&sin, sizeof(sin), 0, sizeof(sin)) != EOK) {
MS_LOG(EXCEPTION) << "Initialize sockaddr_in failed!";
}
sin.sin_family = AF_INET;
sin.sin_port = htons(server_port_);
sin.sin_addr.s_addr = inet_addr(server_address_.c_str());
listener_ = evconnlistener_new_bind(base_, ListenerCallback, reinterpret_cast<void *>(this),
LEV_OPT_REUSEABLE | LEV_OPT_CLOSE_ON_FREE, -1,
reinterpret_cast<struct sockaddr *>(&sin), sizeof(sin));
if (listener_ == nullptr) {
MS_LOG(EXCEPTION) << "bind ip & port failed. please check.";
}
if (server_port_ == 0) {
struct sockaddr_in sin_bound {};
if (memset_s(&sin, sizeof(sin_bound), 0, sizeof(sin_bound)) != EOK) {
MS_LOG(EXCEPTION) << "Initialize sockaddr_in failed!";
}
socklen_t addr_len = sizeof(struct sockaddr_in);
if (getsockname(evconnlistener_get_fd(listener_), (struct sockaddr *)&sin_bound, &addr_len) != 0) {
MS_LOG(EXCEPTION) << "Get sock name failed!";
}
server_port_ = htons(sin_bound.sin_port);
}
signal_event_ = evsignal_new(base_, SIGINT, SignalCallback, reinterpret_cast<void *>(this));
MS_EXCEPTION_IF_NULL(signal_event_);
if (event_add(signal_event_, nullptr) < 0) {
MS_LOG(EXCEPTION) << "Cannot create signal event.";
}
}
void TcpServer::Start() {
MS_LOG(INFO) << "Start tcp server!";
MS_EXCEPTION_IF_NULL(base_);
int ret = event_base_dispatch(base_);
MSLOG_IF(INFO, ret == 0, NoExceptionType) << "Event base dispatch success!";
MSLOG_IF(mindspore::ERROR, ret == 1, NoExceptionType)
<< "Event base dispatch failed with no events pending or active!";
MSLOG_IF(mindspore::ERROR, ret == -1, NoExceptionType) << "Event base dispatch failed with error occurred!";
MSLOG_IF(mindspore::EXCEPTION, ret < -1, AbortedError) << "Event base dispatch with unexpected error code!";
}
void TcpServer::StartWithNoBlock() {
std::lock_guard<std::mutex> lock(connection_mutex_);
MS_LOG(INFO) << "Start tcp server with no block!";
MS_EXCEPTION_IF_NULL(base_);
int ret = event_base_loop(base_, EVLOOP_NONBLOCK);
MSLOG_IF(INFO, ret == 0, NoExceptionType) << "Event base loop success!";
MSLOG_IF(mindspore::ERROR, ret == 1, NoExceptionType) << "Event base loop failed with no events pending or active!";
MSLOG_IF(mindspore::ERROR, ret == -1, NoExceptionType) << "Event base loop failed with error occurred!";
MSLOG_IF(mindspore::EXCEPTION, ret < -1, AbortedError) << "Event base loop with unexpected error code!";
}
void TcpServer::Stop() {
MS_EXCEPTION_IF_NULL(base_);
std::lock_guard<std::mutex> lock(connection_mutex_);
MS_LOG(INFO) << "Stop tcp server!";
if (event_base_got_break(base_)) {
MS_LOG(DEBUG) << "The event base has stopped!";
is_stop_ = true;
return;
}
if (!is_stop_.load()) {
is_stop_ = true;
int ret = event_base_loopbreak(base_);
if (ret != 0) {
MS_LOG(ERROR) << "Event base loop break failed!";
}
}
}
void TcpServer::SendToAllClients(const char *data, size_t len) {
MS_EXCEPTION_IF_NULL(data);
std::lock_guard<std::mutex> lock(connection_mutex_);
for (auto it = connections_.begin(); it != connections_.end(); ++it) {
it->second->SendMessage(data, len);
}
}
void TcpServer::AddConnection(const evutil_socket_t &fd, std::shared_ptr<TcpConnection> connection) {
MS_EXCEPTION_IF_NULL(connection);
std::lock_guard<std::mutex> lock(connection_mutex_);
connections_.insert(std::make_pair(fd, connection));
}
void TcpServer::RemoveConnection(const evutil_socket_t &fd) {
std::lock_guard<std::mutex> lock(connection_mutex_);
connections_.erase(fd);
}
std::shared_ptr<TcpConnection> TcpServer::GetConnectionByFd(const evutil_socket_t &fd) { return connections_[fd]; }
void TcpServer::ListenerCallback(struct evconnlistener *, evutil_socket_t fd, struct sockaddr *sockaddr, int,
void *data) {
auto server = reinterpret_cast<class TcpServer *>(data);
MS_EXCEPTION_IF_NULL(server);
auto base = reinterpret_cast<struct event_base *>(server->base_);
MS_EXCEPTION_IF_NULL(base);
MS_EXCEPTION_IF_NULL(sockaddr);
if (server->ConnectionNum() >= server->max_connection_) {
MS_LOG(WARNING) << "The current connection num:" << server->ConnectionNum() << " is greater or equal to "
<< server->max_connection_;
return;
}
struct bufferevent *bev = nullptr;
if (!PSContext::instance()->enable_ssl()) {
MS_LOG(INFO) << "SSL is disable.";
bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE | BEV_OPT_THREADSAFE);
} else {
MS_LOG(INFO) << "Enable ssl support.";
SSL *ssl = SSL_new(SSLWrapper::GetInstance().GetSSLCtx());
MS_EXCEPTION_IF_NULL(ssl);
bev = bufferevent_openssl_socket_new(base, fd, ssl, BUFFEREVENT_SSL_ACCEPTING,
BEV_OPT_CLOSE_ON_FREE | BEV_OPT_THREADSAFE);
}
if (bev == nullptr) {
MS_LOG(ERROR) << "Error constructing buffer event!";
int ret = event_base_loopbreak(base);
if (ret != 0) {
MS_LOG(EXCEPTION) << "event base loop break failed!";
}
return;
}
std::shared_ptr<TcpConnection> conn = server->onCreateConnection(bev, fd);
MS_EXCEPTION_IF_NULL(conn);
SetTcpNoDelay(fd);
server->AddConnection(fd, conn);
conn->InitConnection(
[=](const std::shared_ptr<MessageMeta> &meta, const Protos &protos, const void *data, size_t size) {
OnServerReceiveMessage on_server_receive = server->GetServerReceive();
if (on_server_receive) {
on_server_receive(conn, meta, protos, data, size);
}
});
bufferevent_setcb(bev, TcpServer::ReadCallback, nullptr, TcpServer::EventCallback,
reinterpret_cast<void *>(conn.get()));
MS_LOG(INFO) << "A client is connected, fd is " << fd;
if (bufferevent_enable(bev, EV_READ | EV_WRITE) == -1) {
MS_LOG(EXCEPTION) << "Buffer event enable read and write failed!";
}
}
std::shared_ptr<TcpConnection> TcpServer::onCreateConnection(struct bufferevent *bev, const evutil_socket_t &fd) {
MS_EXCEPTION_IF_NULL(bev);
std::shared_ptr<TcpConnection> conn = nullptr;
if (client_accept_) {
conn = (client_accept_(*this));
} else {
conn = std::make_shared<TcpConnection>(bev, fd, this);
}
return conn;
}
OnServerReceiveMessage TcpServer::GetServerReceive() const { return message_callback_; }
void TcpServer::SignalCallback(evutil_socket_t, std::int16_t, void *data) {
MS_EXCEPTION_IF_NULL(data);
auto server = reinterpret_cast<class TcpServer *>(data);
struct event_base *base = server->base_;
MS_EXCEPTION_IF_NULL(base);
struct timeval delay = {0, 0};
MS_LOG(ERROR) << "Caught an interrupt signal; exiting cleanly in 0 seconds.";
if (event_base_loopexit(base, &delay) == -1) {
MS_LOG(ERROR) << "Event base loop exit failed.";
}
}
void TcpServer::ReadCallback(struct bufferevent *bev, void *connection) {
MS_EXCEPTION_IF_NULL(bev);
MS_EXCEPTION_IF_NULL(connection);
auto conn = static_cast<class TcpConnection *>(connection);
struct evbuffer *buf = bufferevent_get_input(bev);
MS_EXCEPTION_IF_NULL(buf);
char read_buffer[kMessageChunkLength];
while (EVBUFFER_LENGTH(buf) > 0) {
int read = evbuffer_remove(buf, &read_buffer, sizeof(read_buffer));
if (read == -1) {
MS_LOG(EXCEPTION) << "Can not drain data from the event buffer!";
}
conn->OnReadHandler(read_buffer, IntToSize(read));
}
}
void TcpServer::EventCallback(struct bufferevent *bev, std::int16_t events, void *data) {
MS_EXCEPTION_IF_NULL(bev);
MS_EXCEPTION_IF_NULL(data);
struct evbuffer *output = bufferevent_get_output(bev);
MS_EXCEPTION_IF_NULL(output);
auto conn = static_cast<class TcpConnection *>(data);
auto srv = const_cast<TcpServer *>(conn->GetServer());
MS_EXCEPTION_IF_NULL(srv);
if (events & BEV_EVENT_EOF) {
MS_LOG(INFO) << "Event buffer end of file, a client is disconnected from this server!";
// Notify about disconnection
if (srv->client_disconnection_) {
srv->client_disconnection_(*srv, *conn);
}
// Free connection structures
srv->RemoveConnection(conn->GetFd());
} else if (events & BEV_EVENT_ERROR) {
MS_LOG(WARNING) << "Connect to server error.";
if (PSContext::instance()->enable_ssl()) {
uint64_t err = bufferevent_get_openssl_error(bev);
MS_LOG(WARNING) << "The error number is:" << err;
MS_LOG(WARNING) << "Error message:" << ERR_reason_error_string(err)
<< ", the error lib:" << ERR_lib_error_string(err)
<< ", the error func:" << ERR_func_error_string(err);
}
// Free connection structures
srv->RemoveConnection(conn->GetFd());
// Notify about disconnection
if (srv->client_disconnection_) {
srv->client_disconnection_(*srv, *conn);
}
} else {
MS_LOG(WARNING) << "Unhandled event:" << events;
}
}
void TcpServer::TimerCallback(evutil_socket_t, int16_t, void *arg) {
MS_EXCEPTION_IF_NULL(arg);
auto tcp_server = reinterpret_cast<TcpServer *>(arg);
if (tcp_server->on_timer_callback_) {
tcp_server->on_timer_callback_();
}
}
void TcpServer::TimerOnceCallback(evutil_socket_t, int16_t, void *arg) {
MS_EXCEPTION_IF_NULL(arg);
auto tcp_server = reinterpret_cast<TcpServer *>(arg);
if (tcp_server->on_timer_once_callback_) {
tcp_server->on_timer_once_callback_(*tcp_server);
}
}
void TcpServer::SetTcpNoDelay(const evutil_socket_t &fd) {
const int one = 1;
int ret = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(int));
if (ret < 0) {
MS_LOG(EXCEPTION) << "Set socket no delay failed!";
}
}
bool TcpServer::SendMessage(const std::shared_ptr<TcpConnection> &conn, const std::shared_ptr<CommMessage> &message) {
MS_EXCEPTION_IF_NULL(conn);
MS_EXCEPTION_IF_NULL(message);
return conn->SendMessage(message);
}
bool TcpServer::SendMessage(const std::shared_ptr<TcpConnection> &conn, const std::shared_ptr<MessageMeta> &meta,
const Protos &protos, const void *data, size_t size) {
MS_EXCEPTION_IF_NULL(conn);
MS_EXCEPTION_IF_NULL(meta);
MS_EXCEPTION_IF_NULL(data);
return conn->SendMessage(meta, protos, data, size);
}
void TcpServer::SendMessage(const std::shared_ptr<CommMessage> &message) {
MS_EXCEPTION_IF_NULL(message);
std::lock_guard<std::mutex> lock(connection_mutex_);
for (auto it = connections_.begin(); it != connections_.end(); ++it) {
SendMessage(it->second, message);
}
}
uint16_t TcpServer::BoundPort() const { return server_port_; }
std::string TcpServer::BoundIp() const { return server_address_; }
int TcpServer::ConnectionNum() const { return SizeToInt(connections_.size()); }
const std::map<evutil_socket_t, std::shared_ptr<TcpConnection>> &TcpServer::Connections() const { return connections_; }
void TcpServer::SetMessageCallback(const OnServerReceiveMessage &cb) { message_callback_ = cb; }
} // namespace core
} // namespace ps
} // namespace mindspore
|
// { dg-do run { target c++14 } }
// Copyright (C) 2015-2017 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, 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 General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// 8.2.1 Class template shared_ptr [memory.smartptr.shared]
#include <experimental/memory>
#include <testsuite_hooks.h>
struct A { };
// C++14 §20.8.2.2.4
// swap
int
test01()
{
A * const a1 = new A[5];
A * const a2 = new A[5];
std::experimental::shared_ptr<A[5]> p1(a1);
std::experimental::shared_ptr<A[5]> p2(a2);
p1.swap(p2);
VERIFY( p1.get() == a2 );
VERIFY( p2.get() == a1 );
return 0;
}
int
main()
{
test01();
return 0;
}
|
// subtraction.cpp: test suite runner for subtraction on classic floats
//
// Copyright (C) 2017-2021 Stillwater Supercomputing, Inc.
//
// This file is part of the universal numbers project, which is released under an MIT Open Source license.
#include <universal/utility/directives.hpp>
// minimum set of include files to reflect source code dependencies
#define BLOCKTRIPLE_VERBOSE_OUTPUT
//#define BLOCKTRIPLE_TRACE_ADD
#include <universal/number/cfloat/cfloat.hpp>
#include <universal/verification/test_suite.hpp>
#include <universal/verification/cfloat_test_suite.hpp>
#include <universal/number/cfloat/table.hpp>
/*
Minimum number of operand bits for the adder = <abits>
to yield correctly rounded subtraction
number of exponent bits = <es>
nbits 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
1 - - - - - - - - - - - - - - - -
2 - - - - - - - - - - - - - - - -
3 2 - - - - - - - - - - - - - - -
4 3 3 - - - - - - - - - - - - - -
5 4 4 4 - - - - - - - - - - - - -
6 5 5 6 4 - - - - - - - - - - - -
7 6 6 8 6 4 - - - - - - - - - - -
8 7 7 10 8 6 4 - - - - - - - - - -
9 8 8 11 10 8 6 4 - - - - - - - - -
10 9 9 12 12 10 8 6 4 - - - - - - - -
11 10 10 13 14 12 10 8 6 4 - - - - - - -
12 11 11 14 16 14 12 10 8 6 4 - - - - - -
13 12 12 15 18 16 14 12 10 8 6 ? - - - - -
14 13 13 16 20 18 16 14 12 10 8 ? ? - - - -
15 14 14 17 22 20 18 16 14 12 10 ? ? ? - - -
16 15 15 18 24 22 20 18 16 14 12 ? ? ? ? - -
*/
// Regression testing guards: typically set by the cmake configuration, but MANUAL_TESTING is an override
#define MANUAL_TESTING 0
// REGRESSION_LEVEL_OVERRIDE is set by the cmake file to drive a specific regression intensity
// It is the responsibility of the regression test to organize the tests in a quartile progression.
//#undef REGRESSION_LEVEL_OVERRIDE
#ifndef REGRESSION_LEVEL_OVERRIDE
#undef REGRESSION_LEVEL_1
#undef REGRESSION_LEVEL_2
#undef REGRESSION_LEVEL_3
#undef REGRESSION_LEVEL_4
#define REGRESSION_LEVEL_1 1
#define REGRESSION_LEVEL_2 0
#define REGRESSION_LEVEL_3 0
#define REGRESSION_LEVEL_4 0
#endif
int main()
try {
using namespace sw::universal;
// cfloat encoding configuration for the test
constexpr bool hasSubnormals = true;
constexpr bool hasSupernormals = false;
constexpr bool isSaturating = false;
std::string test_suite = "classic cfloat subtraction validation with subnormals, normals, but no supernormals";
std::string test_tag = "cfloat_tff subtraction";
bool reportTestCases = false;
int nrOfFailedTestCases = 0;
std::cout << test_suite << '\n';
#if MANUAL_TESTING
{
float fa = 0.017578125;
// float fa = std::numeric_limits<float>::infinity();
// float fb = std::numeric_limits<float>::signaling_NaN();
// float fb = std::numeric_limits<float>::quiet_NaN();
float fb = 0.5f;
using Cfloat = cfloat < 8, 4, uint8_t, hasSubnormals, hasSupernormals, isSaturating >;
Cfloat a, b, c;
a.constexprClassParameters();
a = fa;
b = fb;
c = a - b;
std::cout << a << " - " << b << " = " << c << '\n';
std::cout << to_binary(a) << " + " << to_binary(b) << " = " << to_binary(c) << '\n';
TestCase< Cfloat, float>(TestCaseOperator::SUB, fa, fb);
}
{ // special cases of snan/qnan
constexpr float fa = std::numeric_limits<float>::quiet_NaN();
float fb = -fa;
std::cout << "fa = " << fa << " -fa = " << -fa << '\n';
std::cout << "fb = " << fb << " -fb = " << -fb << '\n';
std::cout << 0.0f << " - " << fa << " = " << (0.0f - fa) << '\n';
std::cout << 0.0f << " + " << fa << " = " << (0.0f + fa) << '\n';
std::cout << 0.0f << " - " << fb << " = " << (0.0f - fb) << '\n';
std::cout << fa << " - " << 0.0f << " = " << (fa - 0.0f) << '\n';
std::cout << fb << " - " << 0.0f << " = " << (fb - 0.0f) << '\n';
std::cout << fa << " - " << fa << " = " << (fa - fa) << '\n';
std::cout << fa << " - " << fb << " = " << (fa - fb) << '\n';
std::cout << fb << " - " << fa << " = " << (fb - fa) << '\n';
std::cout << fb << " - " << fb << " = " << (fb - fb) << '\n';
std::cout << to_binary(fa - fb) << '\n';
}
{ // special cases of +-inf
constexpr float fa = std::numeric_limits<float>::infinity();
float fb = -fa;
std::cout << fa << " - " << fa << " = " << (fa - fa) << '\n';
std::cout << fa << " - " << fb << " = " << (fa - fb) << '\n';
std::cout << fb << " - " << fa << " = " << (fb - fa) << '\n';
std::cout << fb << " - " << fb << " = " << (fb - fb) << '\n';
std::cout << to_binary(fa - fb) << '\n';
}
nrOfFailedTestCases += ReportTestResult(
VerifyCfloatSubtraction<
cfloat<4, 2, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(true),
"cfloat<4,2,uint8_t,t,f,f>",
"subtraction");
ReportTestSuiteResults(test_suite, nrOfFailedTestCases);
return EXIT_SUCCESS; // ignore failures
#else
#if REGRESSION_LEVEL_1
// nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<3, 1, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat< 3, 1,uint8_t,t,f,f>", "subtraction");
// nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<4, 1, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat< 4, 1,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<4, 2, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat< 4, 2,uint8_t,t,f,f>", "subtraction");
// nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<5, 1, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat< 5, 1,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<5, 2, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat< 5, 2,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<5, 3, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat< 5, 3,uint8_t,t,f,f>", "subtraction");
// nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<6, 1, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat< 6, 1,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<6, 2, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat< 6, 2,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<6, 3, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat< 6, 3,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<6, 4, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat< 6, 4,uint8_t,t,f,f>", "subtraction");
// nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<7, 1, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat< 7, 1,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<7, 2, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat< 7, 2,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<7, 3, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat< 7, 3,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<7, 4, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat< 7, 4,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<7, 5, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat< 7, 5,uint8_t,t,f,f>", "subtraction");
// nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<8, 1, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat< 8, 1,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<8, 2, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat< 8, 2,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<8, 3, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat< 8, 3,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<8, 4, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat< 8, 4,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<8, 5, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat< 8, 5,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<8, 6, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat< 8, 6,uint8_t,t,f,f>", "subtraction");
#endif
#if REGRESSION_LEVEL_2
// nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<9, 1, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat< 9, 1,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<9, 2, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat< 9, 2,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<9, 3, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat< 9, 3,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<9, 4, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat< 9, 4,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<9, 5, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat< 9, 5,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<9, 6, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat< 9, 6,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<9, 7, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat< 9, 7,uint8_t,t,f,f>", "subtraction");
// nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<10, 1, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<10, 1,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<10, 2, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<10, 2,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<10, 3, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<10, 3,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<10, 4, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<10, 4,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<10, 5, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<10, 5,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<10, 6, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<10, 6,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<10, 7, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<10, 7,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<10, 8, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<10, 8,uint8_t,t,f,f>", "subtraction");
// nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<11, 1, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<11, 1,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<11, 2, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<11, 2,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<11, 3, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<11, 3,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<11, 4, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<11, 4,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<11, 5, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<11, 5,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<11, 6, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<11, 6,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<11, 7, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<11, 7,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<11, 8, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<11, 8,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<11, 9, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<11, 9,uint8_t,t,f,f>", "subtraction");
#endif
#if REGRESSION_LEVEL_3
// nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<12, 1, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<12, 1,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<12, 2, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<12, 2,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<12, 3, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<12, 3,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<12, 4, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<12, 4,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<12, 5, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<12, 5,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<12, 6, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<12, 6,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<12, 7, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<12, 7,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<12, 8, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<12, 8,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<12, 9, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<12, 9,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<12,10, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<12,10,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<13, 3, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<13, 3,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<13, 4, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<13, 4,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<13, 5, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<13, 5,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<13, 6, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<13, 6,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<13, 7, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<13, 7,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<13, 8, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<13, 8,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<13, 9, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<13, 9,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<13, 10, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<13,10,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<13, 11, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<13,11,uint8_t,t,f,f>", "subtraction");
#endif
#if REGRESSION_LEVEL_4
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<14, 3, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<14, 3,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<14, 4, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<14, 4,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<14, 5, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<14, 5,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<14, 6, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<14, 6,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<14, 7, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<14, 7,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<14, 8, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<14, 8,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<14, 9, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<14, 9,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<14, 10, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<14,10,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<14, 11, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<14,11,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<15, 3, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<15, 3,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<15, 4, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<15, 4,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<15, 5, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<15, 5,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<15, 6, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<15, 6,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<15, 7, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<15, 7,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<15, 8, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<15, 8,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<15, 9, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<15, 9,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<15, 10, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<15,10,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<15, 11, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<15,11,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<16, 3, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<16, 3,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<16, 4, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<16, 4,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<16, 5, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<16, 5,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<16, 6, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<16, 6,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<16, 7, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<16, 7,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<16, 8, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<16, 8,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<16, 9, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<16, 9,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<16, 10, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<16,10,uint8_t,t,f,f>", "subtraction");
nrOfFailedTestCases += ReportTestResult(VerifyCfloatSubtraction< cfloat<16, 11, uint8_t, hasSubnormals, hasSupernormals, isSaturating> >(reportTestCases), "cfloat<16,11,uint8_t,t,f,f>", "subtraction");
#endif
ReportTestSuiteResults(test_suite, nrOfFailedTestCases);
return (nrOfFailedTestCases > 0 ? EXIT_FAILURE : EXIT_SUCCESS);
#endif // MANUAL_TESTING
}
catch (char const* msg) {
std::cerr << "Caught ad-hoc exception: " << msg << std::endl;
return EXIT_FAILURE;
}
catch (const sw::universal::universal_arithmetic_exception& err) {
std::cerr << "Caught unexpected universal arithmetic exception : " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (const sw::universal::universal_internal_exception& err) {
std::cerr << "Caught unexpected universal internal exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (const std::runtime_error& err) {
std::cerr << "Caught runtime exception: " << err.what() << std::endl;
return EXIT_FAILURE;
}
catch (...) {
std::cerr << "Caught unknown exception" << std::endl;
return EXIT_FAILURE;
}
|
// Copyright 2015 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/ash/login/signin/token_handle_fetcher.h"
#include <memory>
#include "base/bind.h"
#include "base/metrics/histogram_macros.h"
#include "chrome/browser/ash/login/signin/token_handle_util.h"
#include "chrome/browser/ash/profiles/profile_helper.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/identity_manager_factory.h"
#include "components/keyed_service/content/browser_context_keyed_service_shutdown_notifier_factory.h"
#include "components/signin/public/base/consent_level.h"
#include "components/signin/public/identity_manager/access_token_info.h"
#include "components/signin/public/identity_manager/identity_manager.h"
#include "components/signin/public/identity_manager/primary_account_access_token_fetcher.h"
#include "components/signin/public/identity_manager/scope_set.h"
#include "google_apis/gaia/gaia_constants.h"
#include "services/network/public/cpp/shared_url_loader_factory.h"
namespace ash {
namespace {
const int kMaxRetries = 3;
const char kAccessTokenFetchId[] = "token_handle_fetcher";
class TokenHandleFetcherShutdownNotifierFactory
: public BrowserContextKeyedServiceShutdownNotifierFactory {
public:
static TokenHandleFetcherShutdownNotifierFactory* GetInstance() {
return base::Singleton<TokenHandleFetcherShutdownNotifierFactory>::get();
}
TokenHandleFetcherShutdownNotifierFactory(
const TokenHandleFetcherShutdownNotifierFactory&) = delete;
TokenHandleFetcherShutdownNotifierFactory& operator=(
const TokenHandleFetcherShutdownNotifierFactory&) = delete;
private:
friend struct base::DefaultSingletonTraits<
TokenHandleFetcherShutdownNotifierFactory>;
TokenHandleFetcherShutdownNotifierFactory()
: BrowserContextKeyedServiceShutdownNotifierFactory(
"TokenHandleFetcher") {
DependsOn(IdentityManagerFactory::GetInstance());
}
~TokenHandleFetcherShutdownNotifierFactory() override {}
};
} // namespace
TokenHandleFetcher::TokenHandleFetcher(TokenHandleUtil* util,
const AccountId& account_id)
: token_handle_util_(util), account_id_(account_id) {}
TokenHandleFetcher::~TokenHandleFetcher() {}
void TokenHandleFetcher::BackfillToken(Profile* profile,
TokenFetchingCallback callback) {
profile_ = profile;
callback_ = std::move(callback);
identity_manager_ = IdentityManagerFactory::GetForProfile(profile);
// This class doesn't care about browser sync consent.
if (!identity_manager_->HasAccountWithRefreshToken(
identity_manager_->GetPrimaryAccountId(
signin::ConsentLevel::kSignin))) {
profile_shutdown_subscription_ =
TokenHandleFetcherShutdownNotifierFactory::GetInstance()
->Get(profile)
->Subscribe(
base::BindRepeating(&TokenHandleFetcher::OnProfileDestroyed,
base::Unretained(this)));
}
// Now we can request the token, knowing that it will be immediately requested
// if the refresh token is available, or that it will be requested once the
// refresh token is available for the primary account.
signin::ScopeSet scopes;
scopes.insert(GaiaConstants::kOAuth1LoginScope);
// We can use base::Unretained(this) below because `access_token_fetcher_` is
// owned by this object (thus destroyed when this object is destroyed) and
// PrimaryAccountAccessTokenFetcher guarantees that it doesn't invoke its
// callback after it is destroyed.
access_token_fetcher_ =
std::make_unique<signin::PrimaryAccountAccessTokenFetcher>(
kAccessTokenFetchId, identity_manager_, scopes,
base::BindOnce(&TokenHandleFetcher::OnAccessTokenFetchComplete,
base::Unretained(this)),
signin::PrimaryAccountAccessTokenFetcher::Mode::kWaitUntilAvailable,
signin::ConsentLevel::kSignin);
}
void TokenHandleFetcher::OnAccessTokenFetchComplete(
GoogleServiceAuthError error,
signin::AccessTokenInfo token_info) {
access_token_fetcher_.reset();
if (error.state() != GoogleServiceAuthError::NONE) {
LOG(ERROR) << "Could not get access token to backfill token handler"
<< error.ToString();
std::move(callback_).Run(account_id_, false);
return;
}
FillForAccessToken(token_info.token);
}
void TokenHandleFetcher::FillForNewUser(const std::string& access_token,
TokenFetchingCallback callback) {
profile_ = ProfileHelper::Get()->GetSigninProfile();
callback_ = std::move(callback);
FillForAccessToken(access_token);
}
void TokenHandleFetcher::FillForAccessToken(const std::string& access_token) {
if (!gaia_client_.get())
gaia_client_ = std::make_unique<gaia::GaiaOAuthClient>(
profile_->GetURLLoaderFactory());
tokeninfo_response_start_time_ = base::TimeTicks::Now();
gaia_client_->GetTokenInfo(access_token, kMaxRetries, this);
}
void TokenHandleFetcher::OnOAuthError() {
std::move(callback_).Run(account_id_, false);
}
void TokenHandleFetcher::OnNetworkError(int response_code) {
std::move(callback_).Run(account_id_, false);
}
void TokenHandleFetcher::OnGetTokenInfoResponse(
std::unique_ptr<base::DictionaryValue> token_info) {
bool success = false;
if (!token_info->FindKey("error")) {
std::string handle;
if (token_info->GetString("token_handle", &handle)) {
success = true;
token_handle_util_->StoreTokenHandle(account_id_, handle);
}
}
const base::TimeDelta duration =
base::TimeTicks::Now() - tokeninfo_response_start_time_;
UMA_HISTOGRAM_TIMES("Login.TokenObtainResponseTime", duration);
std::move(callback_).Run(account_id_, success);
}
void TokenHandleFetcher::OnProfileDestroyed() {
std::move(callback_).Run(account_id_, false);
}
} // namespace ash
|
/* Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is also distributed with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have included with MySQL.
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, version 2.0, for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
/*
Lock databases against read or write.
*/
#include <fcntl.h>
#include "storage/myisammrg/myrg_def.h"
#ifdef _WIN32
#include "storage/myisam/myisamdef.h"
#endif
int myrg_lock_database(MYRG_INFO *info, int lock_type) {
int error, new_error;
MYRG_TABLE *file;
error = 0;
for (file = info->open_tables; file != info->end_table; file++) {
#ifdef _WIN32
/*
Make sure this table is marked as owned by a merge table.
The semaphore is never released as long as table remains
in memory. This should be refactored into a more generic
approach (observer pattern)
*/
(file->table)->owned_by_merge = true;
#endif
if ((new_error = mi_lock_database(file->table, lock_type))) {
error = new_error;
if (lock_type != F_UNLCK) {
while (--file >= info->open_tables)
mi_lock_database(file->table, F_UNLCK);
break;
}
}
}
return (error);
}
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "wallet.h"
#include "walletdb.h"
#include "bitcoinrpc.h"
#include "init.h"
#include "base58.h"
using namespace json_spirit;
using namespace std;
int64 nWalletUnlockTime;
static CCriticalSection cs_nWalletUnlockTime;
extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry);
std::string HelpRequiringPassphrase()
{
return pwalletMain->IsCrypted()
? "\nrequires wallet passphrase to be set with walletpassphrase first"
: "";
}
void EnsureWalletIsUnlocked()
{
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
if (fWalletUnlockMintOnly)
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Wallet unlocked for block minting only.");
}
void WalletTxToJSON(const CWalletTx& wtx, Object& entry)
{
int confirms = wtx.GetDepthInMainChain();
entry.push_back(Pair("confirmations", confirms));
if (wtx.IsCoinBase() || wtx.IsCoinStake())
entry.push_back(Pair("generated", true));
if (confirms)
{
entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex()));
entry.push_back(Pair("blockindex", wtx.nIndex));
entry.push_back(Pair("blocktime", (boost::int64_t)(mapBlockIndex[wtx.hashBlock]->nTime)));
}
entry.push_back(Pair("txid", wtx.GetHash().GetHex()));
entry.push_back(Pair("time", (boost::int64_t)wtx.GetTxTime()));
entry.push_back(Pair("timereceived", (boost::int64_t)wtx.nTimeReceived));
BOOST_FOREACH(const PAIRTYPE(string,string)& item, wtx.mapValue)
entry.push_back(Pair(item.first, item.second));
}
string AccountFromValue(const Value& value)
{
string strAccount = value.get_str();
if (strAccount == "*")
throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name");
return strAccount;
}
Value getinfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getinfo\n"
"Returns an object containing various state info.");
proxyType proxy;
GetProxy(NET_IPV4, proxy);
Object obj;
obj.push_back(Pair("version", FormatFullVersion()));
obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION));
obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
obj.push_back(Pair("newmint", ValueFromAmount(pwalletMain->GetNewMint())));
obj.push_back(Pair("stake", ValueFromAmount(pwalletMain->GetStake())));
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("moneysupply", ValueFromAmount(pindexBest->nMoneySupply)));
obj.push_back(Pair("connections", (int)vNodes.size()));
obj.push_back(Pair("proxy", (proxy.first.IsValid() ? proxy.first.ToStringIPPort() : string())));
obj.push_back(Pair("ip", addrSeenByPeer.ToStringIP()));
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
obj.push_back(Pair("testnet", fTestNet));
obj.push_back(Pair("keypoololdest", (boost::int64_t)pwalletMain->GetOldestKeyPoolTime()));
obj.push_back(Pair("keypoolsize", pwalletMain->GetKeyPoolSize()));
obj.push_back(Pair("paytxfee", ValueFromAmount(nTransactionFee)));
if (pwalletMain->IsCrypted())
obj.push_back(Pair("unlocked_until", (boost::int64_t)nWalletUnlockTime / 1000));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
return obj;
}
Value getnewpubkey(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getnewpubkey [account]\n"
"Returns new public key for coinbase generation.");
// Parse the account first so we don't generate a key if there's an error
string strAccount;
if (params.size() > 0)
strAccount = AccountFromValue(params[0]);
if (!pwalletMain->IsLocked())
pwalletMain->TopUpKeyPool();
// Generate a new key that is added to wallet
CPubKey newKey;
if (!pwalletMain->GetKeyFromPool(newKey, false))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
CKeyID keyID = newKey.GetID();
pwalletMain->SetAddressBookName(keyID, strAccount);
vector<unsigned char> vchPubKey = newKey.Raw();
return HexStr(vchPubKey.begin(), vchPubKey.end());
}
Value getnewaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getnewaddress [account]\n"
"Returns a new UltraCoin address for receiving payments. "
"If [account] is specified (recommended), it is added to the address book "
"so payments received with the address will be credited to [account].");
// Parse the account first so we don't generate a key if there's an error
string strAccount;
if (params.size() > 0)
strAccount = AccountFromValue(params[0]);
if (!pwalletMain->IsLocked())
pwalletMain->TopUpKeyPool();
// Generate a new key that is added to wallet
CPubKey newKey;
if (!pwalletMain->GetKeyFromPool(newKey, false))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
CKeyID keyID = newKey.GetID();
pwalletMain->SetAddressBookName(keyID, strAccount);
return CBitcoinAddress(keyID).ToString();
}
CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
CAccount account;
walletdb.ReadAccount(strAccount, account);
bool bKeyUsed = false;
// Check if the current key has been used
if (account.vchPubKey.IsValid())
{
CScript scriptPubKey;
scriptPubKey.SetDestination(account.vchPubKey.GetID());
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin();
it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid();
++it)
{
const CWalletTx& wtx = (*it).second;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
bKeyUsed = true;
}
}
// Generate a new key
if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed)
{
if (!pwalletMain->GetKeyFromPool(account.vchPubKey, false))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
pwalletMain->SetAddressBookName(account.vchPubKey.GetID(), strAccount);
walletdb.WriteAccount(strAccount, account);
}
return CBitcoinAddress(account.vchPubKey.GetID());
}
Value getaccountaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccountaddress <account>\n"
"Returns the current UltraCoin address for receiving payments to this account.");
// Parse the account first so we don't generate a key if there's an error
string strAccount = AccountFromValue(params[0]);
Value ret;
ret = GetAccountAddress(strAccount).ToString();
return ret;
}
Value setaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"setaccount <ultracoinaddress> <account>\n"
"Sets the account associated with the given address.");
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid UltraCoin address");
string strAccount;
if (params.size() > 1)
strAccount = AccountFromValue(params[1]);
// Detect when changing the account of an address that is the 'unused current key' of another account:
if (pwalletMain->mapAddressBook.count(address.Get()))
{
string strOldAccount = pwalletMain->mapAddressBook[address.Get()];
if (address == GetAccountAddress(strOldAccount))
GetAccountAddress(strOldAccount, true);
}
pwalletMain->SetAddressBookName(address.Get(), strAccount);
return Value::null;
}
Value getaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccount <ultracoinaddress>\n"
"Returns the account associated with the given address.");
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid UltraCoin address");
string strAccount;
map<CTxDestination, string>::iterator mi = pwalletMain->mapAddressBook.find(address.Get());
if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.empty())
strAccount = (*mi).second;
return strAccount;
}
Value getaddressesbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaddressesbyaccount <account>\n"
"Returns the list of addresses for the given account.");
string strAccount = AccountFromValue(params[0]);
// Find all addresses that have the given account
Array ret;
BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
const string& strName = item.second;
if (strName == strAccount)
ret.push_back(address.ToString());
}
return ret;
}
Value sendtoaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendtoaddress <ultracoinaddress> <amount> [comment] [comment-to]\n"
"<amount> is a real and is rounded to the nearest 0.000001"
+ HelpRequiringPassphrase());
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid UltraCoin address");
// Amount
int64 nAmount = AmountFromValue(params[1]);
if (nAmount < MIN_TXOUT_AMOUNT)
throw JSONRPCError(-101, "Send amount too small");
// Wallet comments
CWalletTx wtx;
if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty())
wtx.mapValue["comment"] = params[2].get_str();
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["to"] = params[3].get_str();
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx);
if (strError != "")
throw JSONRPCError(RPC_WALLET_ERROR, strError);
return wtx.GetHash().GetHex();
}
Value listaddressgroupings(const Array& params, bool fHelp)
{
if (fHelp)
throw runtime_error(
"listaddressgroupings\n"
"Lists groups of addresses which have had their common ownership\n"
"made public by common use as inputs or as the resulting change\n"
"in past transactions");
Array jsonGroupings;
map<CTxDestination, int64> balances = pwalletMain->GetAddressBalances();
BOOST_FOREACH(set<CTxDestination> grouping, pwalletMain->GetAddressGroupings())
{
Array jsonGrouping;
BOOST_FOREACH(CTxDestination address, grouping)
{
Array addressInfo;
addressInfo.push_back(CBitcoinAddress(address).ToString());
addressInfo.push_back(ValueFromAmount(balances[address]));
{
LOCK(pwalletMain->cs_wallet);
if (pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get()) != pwalletMain->mapAddressBook.end())
addressInfo.push_back(pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get())->second);
}
jsonGrouping.push_back(addressInfo);
}
jsonGroupings.push_back(jsonGrouping);
}
return jsonGroupings;
}
Value signmessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"signmessage <ultracoinaddress> <message>\n"
"Sign a message with the private key of an address");
EnsureWalletIsUnlocked();
string strAddress = params[0].get_str();
string strMessage = params[1].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
CKey key;
if (!pwalletMain->GetKey(keyID, key))
throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available");
CDataStream ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
vector<unsigned char> vchSig;
if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
return EncodeBase64(&vchSig[0], vchSig.size());
}
Value verifymessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 3)
throw runtime_error(
"verifymessage <ultracoinaddress> <signature> <message>\n"
"Verify a signed message");
string strAddress = params[0].get_str();
string strSign = params[1].get_str();
string strMessage = params[2].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
bool fInvalid = false;
vector<unsigned char> vchSig = DecodeBase64(strSign.c_str(), &fInvalid);
if (fInvalid)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Malformed base64 encoding");
CDataStream ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
CKey key;
if (!key.SetCompactSignature(Hash(ss.begin(), ss.end()), vchSig))
return false;
return (key.GetPubKey().GetID() == keyID);
}
Value getreceivedbyaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaddress <ultracoinaddress> [minconf=1]\n"
"Returns the total amount received by <ultracoinaddress> in transactions with at least [minconf] confirmations.");
// Bitcoin address
CBitcoinAddress address = CBitcoinAddress(params[0].get_str());
CScript scriptPubKey;
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid UltraCoin address");
scriptPubKey.SetDestination(address.Get());
if (!IsMine(*pwalletMain,scriptPubKey))
return (double)0.0;
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Tally
int64 nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || wtx.IsCoinStake() || !wtx.IsFinal())
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
return ValueFromAmount(nAmount);
}
void GetAccountAddresses(string strAccount, set<CTxDestination>& setAddress)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& item, pwalletMain->mapAddressBook)
{
const CTxDestination& address = item.first;
const string& strName = item.second;
if (strName == strAccount)
setAddress.insert(address);
}
}
Value getreceivedbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaccount <account> [minconf=1]\n"
"Returns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.");
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Get the set of pub keys assigned to account
string strAccount = AccountFromValue(params[0]);
set<CTxDestination> setAddress;
GetAccountAddresses(strAccount, setAddress);
// Tally
int64 nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || wtx.IsCoinStake() || !wtx.IsFinal())
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address))
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
}
return (double)nAmount / (double)COIN;
}
int64 GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth)
{
int64 nBalance = 0;
// Tally wallet transactions
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!wtx.IsFinal())
continue;
int64 nGenerated, nReceived, nSent, nFee;
wtx.GetAccountAmounts(strAccount, nGenerated, nReceived, nSent, nFee);
if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth)
nBalance += nReceived;
nBalance += nGenerated - nSent - nFee;
}
// Tally internal accounting entries
nBalance += walletdb.GetAccountCreditDebit(strAccount);
return nBalance;
}
int64 GetAccountBalance(const string& strAccount, int nMinDepth)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
return GetAccountBalance(walletdb, strAccount, nMinDepth);
}
Value getbalance(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"getbalance [account] [minconf=1]\n"
"If [account] is not specified, returns the server's total available balance.\n"
"If [account] is specified, returns the balance in the account.");
if (params.size() == 0)
return ValueFromAmount(pwalletMain->GetBalance());
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
if (params[0].get_str() == "*") {
// Calculate total balance a different way from GetBalance()
// (GetBalance() sums up all unspent TxOuts)
// getbalance and getbalance '*' should always return the same number.
int64 nBalance = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (!wtx.IsFinal())
continue;
int64 allGeneratedImmature, allGeneratedMature, allFee;
allGeneratedImmature = allGeneratedMature = allFee = 0;
string strSentAccount;
list<pair<CTxDestination, int64> > listReceived;
list<pair<CTxDestination, int64> > listSent;
wtx.GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
if (wtx.GetDepthInMainChain() >= nMinDepth)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived)
nBalance += r.second;
}
BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listSent)
nBalance -= r.second;
nBalance -= allFee;
nBalance += allGeneratedMature;
}
return ValueFromAmount(nBalance);
}
string strAccount = AccountFromValue(params[0]);
int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
return ValueFromAmount(nBalance);
}
Value movecmd(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 5)
throw runtime_error(
"move <fromaccount> <toaccount> <amount> [minconf=1] [comment]\n"
"Move from one account in your wallet to another.");
string strFrom = AccountFromValue(params[0]);
string strTo = AccountFromValue(params[1]);
int64 nAmount = AmountFromValue(params[2]);
if (nAmount < MIN_TXOUT_AMOUNT)
throw JSONRPCError(-101, "Send amount too small");
if (params.size() > 3)
// unused parameter, used to be nMinDepth, keep type-checking it though
(void)params[3].get_int();
string strComment;
if (params.size() > 4)
strComment = params[4].get_str();
CWalletDB walletdb(pwalletMain->strWalletFile);
if (!walletdb.TxnBegin())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
int64 nNow = GetAdjustedTime();
// Debit
CAccountingEntry debit;
debit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
debit.strAccount = strFrom;
debit.nCreditDebit = -nAmount;
debit.nTime = nNow;
debit.strOtherAccount = strTo;
debit.strComment = strComment;
walletdb.WriteAccountingEntry(debit);
// Credit
CAccountingEntry credit;
credit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
credit.strAccount = strTo;
credit.nCreditDebit = nAmount;
credit.nTime = nNow;
credit.strOtherAccount = strFrom;
credit.strComment = strComment;
walletdb.WriteAccountingEntry(credit);
if (!walletdb.TxnCommit())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
return true;
}
Value sendfrom(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 6)
throw runtime_error(
"sendfrom <fromaccount> <toultracoinaddress> <amount> [minconf=1] [comment] [comment-to]\n"
"<amount> is a real and is rounded to the nearest 0.000001"
+ HelpRequiringPassphrase());
string strAccount = AccountFromValue(params[0]);
CBitcoinAddress address(params[1].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid UltraCoin address");
int64 nAmount = AmountFromValue(params[2]);
if (nAmount < MIN_TXOUT_AMOUNT)
throw JSONRPCError(-101, "Send amount too small");
int nMinDepth = 1;
if (params.size() > 3)
nMinDepth = params[3].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty())
wtx.mapValue["comment"] = params[4].get_str();
if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty())
wtx.mapValue["to"] = params[5].get_str();
EnsureWalletIsUnlocked();
// Check funds
int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
if (nAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
// Send
string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx);
if (strError != "")
throw JSONRPCError(RPC_WALLET_ERROR, strError);
return wtx.GetHash().GetHex();
}
Value sendmany(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendmany <fromaccount> {address:amount,...} [minconf=1] [comment]\n"
"amounts are double-precision floating point numbers"
+ HelpRequiringPassphrase());
string strAccount = AccountFromValue(params[0]);
Object sendTo = params[1].get_obj();
int nMinDepth = 1;
if (params.size() > 2)
nMinDepth = params[2].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty())
wtx.mapValue["comment"] = params[3].get_str();
set<CBitcoinAddress> setAddress;
vector<pair<CScript, int64> > vecSend;
int64 totalAmount = 0;
BOOST_FOREACH(const Pair& s, sendTo)
{
CBitcoinAddress address(s.name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid UltraCoin address: ")+s.name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_);
setAddress.insert(address);
CScript scriptPubKey;
scriptPubKey.SetDestination(address.Get());
int64 nAmount = AmountFromValue(s.value_);
if (nAmount < MIN_TXOUT_AMOUNT)
throw JSONRPCError(-101, "Send amount too small");
totalAmount += nAmount;
vecSend.push_back(make_pair(scriptPubKey, nAmount));
}
EnsureWalletIsUnlocked();
// Check funds
int64 nBalance = GetAccountBalance(strAccount, nMinDepth);
if (totalAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
// Send
CReserveKey keyChange(pwalletMain);
int64 nFeeRequired = 0;
bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired);
if (!fCreated)
{
if (totalAmount + nFeeRequired > pwalletMain->GetBalance())
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds");
throw JSONRPCError(RPC_WALLET_ERROR, "Transaction creation failed");
}
if (!pwalletMain->CommitTransaction(wtx, keyChange))
throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed");
return wtx.GetHash().GetHex();
}
Value addmultisigaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3)
{
string msg = "addmultisigaddress <nrequired> <'[\"key\",\"key\"]'> [account]\n"
"Add a nrequired-to-sign multisignature address to the wallet\"\n"
"each key is a UltraCoin address or hex-encoded public key\n"
"If [account] is specified, assign address to [account].";
throw runtime_error(msg);
}
int nRequired = params[0].get_int();
const Array& keys = params[1].get_array();
string strAccount;
if (params.size() > 2)
strAccount = AccountFromValue(params[2]);
// Gather public keys
if (nRequired < 1)
throw runtime_error("a multisignature address must require at least one key to redeem");
if ((int)keys.size() < nRequired)
throw runtime_error(
strprintf("not enough keys supplied "
"(got %" PRIszu " keys, but need at least %d to redeem)", keys.size(), nRequired));
std::vector<CKey> pubkeys;
pubkeys.resize(keys.size());
for (unsigned int i = 0; i < keys.size(); i++)
{
const std::string& ks = keys[i].get_str();
// Case 1: Bitcoin address and we have full public key:
CBitcoinAddress address(ks);
if (address.IsValid())
{
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw runtime_error(
strprintf("%s does not refer to a key",ks.c_str()));
CPubKey vchPubKey;
if (!pwalletMain->GetPubKey(keyID, vchPubKey))
throw runtime_error(
strprintf("no full public key for address %s",ks.c_str()));
if (!vchPubKey.IsValid() || !pubkeys[i].SetPubKey(vchPubKey))
throw runtime_error(" Invalid public key: "+ks);
}
// Case 2: hex public key
else if (IsHex(ks))
{
CPubKey vchPubKey(ParseHex(ks));
if (!vchPubKey.IsValid() || !pubkeys[i].SetPubKey(vchPubKey))
throw runtime_error(" Invalid public key: "+ks);
}
else
{
throw runtime_error(" Invalid public key: "+ks);
}
}
// Construct using pay-to-script-hash:
CScript inner;
inner.SetMultisig(nRequired, pubkeys);
CScriptID innerID = inner.GetID();
pwalletMain->AddCScript(inner);
pwalletMain->SetAddressBookName(innerID, strAccount);
return CBitcoinAddress(innerID).ToString();
}
struct tallyitem
{
int64 nAmount;
int nConf;
tallyitem()
{
nAmount = 0;
nConf = std::numeric_limits<int>::max();
}
};
Value ListReceived(const Array& params, bool fByAccounts)
{
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
// Whether to include empty accounts
bool fIncludeEmpty = false;
if (params.size() > 1)
fIncludeEmpty = params[1].get_bool();
// Tally
map<CBitcoinAddress, tallyitem> mapTally;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || wtx.IsCoinStake() || !wtx.IsFinal())
continue;
int nDepth = wtx.GetDepthInMainChain();
if (nDepth < nMinDepth)
continue;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address) || !IsMine(*pwalletMain, address))
continue;
tallyitem& item = mapTally[address];
item.nAmount += txout.nValue;
item.nConf = min(item.nConf, nDepth);
}
}
// Reply
Array ret;
map<string, tallyitem> mapAccountTally;
BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, pwalletMain->mapAddressBook)
{
const CBitcoinAddress& address = item.first;
const string& strAccount = item.second;
map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address);
if (it == mapTally.end() && !fIncludeEmpty)
continue;
int64 nAmount = 0;
int nConf = std::numeric_limits<int>::max();
if (it != mapTally.end())
{
nAmount = (*it).second.nAmount;
nConf = (*it).second.nConf;
}
if (fByAccounts)
{
tallyitem& item = mapAccountTally[strAccount];
item.nAmount += nAmount;
item.nConf = min(item.nConf, nConf);
}
else
{
Object obj;
obj.push_back(Pair("address", address.ToString()));
obj.push_back(Pair("account", strAccount));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
ret.push_back(obj);
}
}
if (fByAccounts)
{
for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it)
{
int64 nAmount = (*it).second.nAmount;
int nConf = (*it).second.nConf;
Object obj;
obj.push_back(Pair("account", (*it).first));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
ret.push_back(obj);
}
}
return ret;
}
Value listreceivedbyaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"listreceivedbyaddress [minconf=1] [includeempty=false]\n"
"[minconf] is the minimum number of confirmations before payments are included.\n"
"[includeempty] whether to include addresses that haven't received any payments.\n"
"Returns an array of objects containing:\n"
" \"address\" : receiving address\n"
" \"account\" : the account of the receiving address\n"
" \"amount\" : total amount received by the address\n"
" \"confirmations\" : number of confirmations of the most recent transaction included");
return ListReceived(params, false);
}
Value listreceivedbyaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"listreceivedbyaccount [minconf=1] [includeempty=false]\n"
"[minconf] is the minimum number of confirmations before payments are included.\n"
"[includeempty] whether to include accounts that haven't received any payments.\n"
"Returns an array of objects containing:\n"
" \"account\" : the account of the receiving addresses\n"
" \"amount\" : total amount received by addresses with this account\n"
" \"confirmations\" : number of confirmations of the most recent transaction included");
return ListReceived(params, true);
}
void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, Array& ret)
{
int64 nGeneratedImmature, nGeneratedMature, nFee;
string strSentAccount;
list<pair<CTxDestination, int64> > listReceived;
list<pair<CTxDestination, int64> > listSent;
wtx.GetAmounts(nGeneratedImmature, nGeneratedMature, listReceived, listSent, nFee, strSentAccount);
bool fAllAccounts = (strAccount == string("*"));
// Generated blocks assigned to account ""
if ((nGeneratedMature+nGeneratedImmature) != 0 && (fAllAccounts || strAccount == ""))
{
Object entry;
entry.push_back(Pair("account", string("")));
if (nGeneratedImmature)
{
entry.push_back(Pair("category", wtx.GetDepthInMainChain() ? "immature" : "orphan"));
entry.push_back(Pair("amount", ValueFromAmount(nGeneratedImmature)));
}
else
{
entry.push_back(Pair("category", "generate"));
entry.push_back(Pair("amount", ValueFromAmount(nGeneratedMature)));
}
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
// Sent
if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount))
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent)
{
Object entry;
entry.push_back(Pair("account", strSentAccount));
entry.push_back(Pair("address", CBitcoinAddress(s.first).ToString()));
entry.push_back(Pair("category", "send"));
entry.push_back(Pair("amount", ValueFromAmount(-s.second)));
entry.push_back(Pair("fee", ValueFromAmount(-nFee)));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
}
// Received
if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived)
{
string account;
if (pwalletMain->mapAddressBook.count(r.first))
account = pwalletMain->mapAddressBook[r.first];
if (fAllAccounts || (account == strAccount))
{
Object entry;
entry.push_back(Pair("account", account));
entry.push_back(Pair("address", CBitcoinAddress(r.first).ToString()));
if (wtx.IsCoinBase())
{
if (wtx.GetDepthInMainChain() < 1)
entry.push_back(Pair("category", "orphan"));
else if (wtx.GetBlocksToMaturity() > 0)
entry.push_back(Pair("category", "immature"));
else
entry.push_back(Pair("category", "generate"));
}
else
entry.push_back(Pair("category", "receive"));
entry.push_back(Pair("amount", ValueFromAmount(r.second)));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
}
}
}
void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, Array& ret)
{
bool fAllAccounts = (strAccount == string("*"));
if (fAllAccounts || acentry.strAccount == strAccount)
{
Object entry;
entry.push_back(Pair("account", acentry.strAccount));
entry.push_back(Pair("category", "move"));
entry.push_back(Pair("time", (boost::int64_t)acentry.nTime));
entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit)));
entry.push_back(Pair("otheraccount", acentry.strOtherAccount));
entry.push_back(Pair("comment", acentry.strComment));
ret.push_back(entry);
}
}
Value listtransactions(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"listtransactions [account] [count=10] [from=0]\n"
"Returns up to [count] most recent transactions skipping the first [from] transactions for account [account].");
string strAccount = "*";
if (params.size() > 0)
strAccount = params[0].get_str();
int nCount = 10;
if (params.size() > 1)
nCount = params[1].get_int();
int nFrom = 0;
if (params.size() > 2)
nFrom = params[2].get_int();
if (nCount < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count");
if (nFrom < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from");
Array ret;
std::list<CAccountingEntry> acentries;
CWallet::TxItems txOrdered = pwalletMain->OrderedTxItems(acentries, strAccount);
// iterate backwards until we have nCount items to return:
for (CWallet::TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
{
CWalletTx *const pwtx = (*it).second.first;
if (pwtx != 0)
ListTransactions(*pwtx, strAccount, 0, true, ret);
CAccountingEntry *const pacentry = (*it).second.second;
if (pacentry != 0)
AcentryToJSON(*pacentry, strAccount, ret);
if ((int)ret.size() >= (nCount+nFrom)) break;
}
// ret is newest to oldest
if (nFrom > (int)ret.size())
nFrom = ret.size();
if ((nFrom + nCount) > (int)ret.size())
nCount = ret.size() - nFrom;
Array::iterator first = ret.begin();
std::advance(first, nFrom);
Array::iterator last = ret.begin();
std::advance(last, nFrom+nCount);
if (last != ret.end()) ret.erase(last, ret.end());
if (first != ret.begin()) ret.erase(ret.begin(), first);
std::reverse(ret.begin(), ret.end()); // Return oldest to newest
return ret;
}
Value listaccounts(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"listaccounts [minconf=1]\n"
"Returns Object that has account names as keys, account balances as values.");
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
map<string, int64> mapAccountBalances;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, string)& entry, pwalletMain->mapAddressBook) {
if (IsMine(*pwalletMain, entry.first)) // This address belongs to me
mapAccountBalances[entry.second] = 0;
}
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it)
{
const CWalletTx& wtx = (*it).second;
int64 nGeneratedImmature, nGeneratedMature, nFee;
string strSentAccount;
list<pair<CTxDestination, int64> > listReceived;
list<pair<CTxDestination, int64> > listSent;
wtx.GetAmounts(nGeneratedImmature, nGeneratedMature, listReceived, listSent, nFee, strSentAccount);
mapAccountBalances[strSentAccount] -= nFee;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent)
mapAccountBalances[strSentAccount] -= s.second;
if (wtx.GetDepthInMainChain() >= nMinDepth)
{
mapAccountBalances[""] += nGeneratedMature;
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived)
if (pwalletMain->mapAddressBook.count(r.first))
mapAccountBalances[pwalletMain->mapAddressBook[r.first]] += r.second;
else
mapAccountBalances[""] += r.second;
}
}
list<CAccountingEntry> acentries;
CWalletDB(pwalletMain->strWalletFile).ListAccountCreditDebit("*", acentries);
BOOST_FOREACH(const CAccountingEntry& entry, acentries)
mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
Object ret;
BOOST_FOREACH(const PAIRTYPE(string, int64)& accountBalance, mapAccountBalances) {
ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
}
return ret;
}
Value listsinceblock(const Array& params, bool fHelp)
{
if (fHelp)
throw runtime_error(
"listsinceblock [blockhash] [target-confirmations]\n"
"Get all transactions in blocks since block [blockhash], or all transactions if omitted");
CBlockIndex *pindex = NULL;
int target_confirms = 1;
if (params.size() > 0)
{
uint256 blockId = 0;
blockId.SetHex(params[0].get_str());
pindex = CBlockLocator(blockId).GetBlockIndex();
}
if (params.size() > 1)
{
target_confirms = params[1].get_int();
if (target_confirms < 1)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
}
int depth = pindex ? (1 + nBestHeight - pindex->nHeight) : -1;
Array transactions;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++)
{
CWalletTx tx = (*it).second;
if (depth == -1 || tx.GetDepthInMainChain() < depth)
ListTransactions(tx, "*", 0, true, transactions);
}
uint256 lastblock;
if (target_confirms == 1)
{
lastblock = hashBestChain;
}
else
{
int target_height = pindexBest->nHeight + 1 - target_confirms;
CBlockIndex *block;
for (block = pindexBest;
block && block->nHeight > target_height;
block = block->pprev) { }
lastblock = block ? block->GetBlockHash() : 0;
}
Object ret;
ret.push_back(Pair("transactions", transactions));
ret.push_back(Pair("lastblock", lastblock.GetHex()));
return ret;
}
Value listlatesttx(const Array& params, bool fHelp)
{
if (fHelp)
throw runtime_error(
"listlatesttx [reserve=false]\n"
"Get latest transactions involving me. if [reserve] is set, transactions will be stored in memory, or transactions will be delete since every call");
bool reserve = false;
if (params.size() > 0)
{
reserve = params[0].get_bool();
}
Array transactions;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWalletFresh.begin(); it != pwalletMain->mapWalletFresh.end(); it++)
{
CWalletTx tx = (*it).second;
ListTransactions(tx, "*", 0, true, transactions);
}
if(!reserve){
pwalletMain->mapWalletFresh.clear();
}
uint256 lastblock = hashBestChain;
Object ret;
ret.push_back(Pair("transactions", transactions));
ret.push_back(Pair("lastblock", lastblock.GetHex()));
return ret;
}
Value gettransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"gettransaction <txid>\n"
"Get detailed information about <txid>");
uint256 hash;
hash.SetHex(params[0].get_str());
Object entry;
if (pwalletMain->mapWallet.count(hash))
{
const CWalletTx& wtx = pwalletMain->mapWallet[hash];
TxToJSON(wtx, 0, entry);
int64 nCredit = wtx.GetCredit();
int64 nDebit = wtx.GetDebit();
int64 nNet = nCredit - nDebit;
int64 nFee = (wtx.IsFromMe() ? wtx.GetValueOut() - nDebit : 0);
entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee)));
if (wtx.IsFromMe())
entry.push_back(Pair("fee", ValueFromAmount(nFee)));
WalletTxToJSON(wtx, entry);
Array details;
ListTransactions(pwalletMain->mapWallet[hash], "*", 0, false, details);
entry.push_back(Pair("details", details));
}
else
{
CTransaction tx;
uint256 hashBlock = 0;
if (GetTransaction(hash, tx, hashBlock))
{
entry.push_back(Pair("txid", hash.GetHex()));
TxToJSON(tx, 0, entry);
if (hashBlock == 0)
entry.push_back(Pair("confirmations", 0));
else
{
entry.push_back(Pair("blockhash", hashBlock.GetHex()));
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second)
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
{
entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight));
entry.push_back(Pair("txntime", (boost::int64_t)tx.nTime));
entry.push_back(Pair("time", (boost::int64_t)pindex->nTime));
}
else
entry.push_back(Pair("confirmations", 0));
}
}
}
else
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
}
return entry;
}
Value backupwallet(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"backupwallet <destination>\n"
"Safely copies wallet.dat to destination, which can be a directory or a path with filename.");
string strDest = params[0].get_str();
if (!BackupWallet(*pwalletMain, strDest))
throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!");
return Value::null;
}
Value keypoolrefill(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"keypoolrefill\n"
"Fills the keypool."
+ HelpRequiringPassphrase());
EnsureWalletIsUnlocked();
pwalletMain->TopUpKeyPool();
if (pwalletMain->GetKeyPoolSize() < GetArg("-keypool", 100))
throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool.");
return Value::null;
}
void ThreadTopUpKeyPool(void* parg)
{
// Make this thread recognisable as the key-topping-up thread
RenameThread("bitcoin-key-top");
pwalletMain->TopUpKeyPool();
}
void ThreadCleanWalletPassphrase(void* parg)
{
// Make this thread recognisable as the wallet relocking thread
RenameThread("bitcoin-lock-wa");
int64 nMyWakeTime = GetTimeMillis() + *((int64*)parg) * 1000;
ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime);
if (nWalletUnlockTime == 0)
{
nWalletUnlockTime = nMyWakeTime;
do
{
if (nWalletUnlockTime==0)
break;
int64 nToSleep = nWalletUnlockTime - GetTimeMillis();
if (nToSleep <= 0)
break;
LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime);
Sleep(nToSleep);
ENTER_CRITICAL_SECTION(cs_nWalletUnlockTime);
} while(1);
if (nWalletUnlockTime)
{
nWalletUnlockTime = 0;
pwalletMain->Lock();
}
}
else
{
if (nWalletUnlockTime < nMyWakeTime)
nWalletUnlockTime = nMyWakeTime;
}
LEAVE_CRITICAL_SECTION(cs_nWalletUnlockTime);
delete (int64*)parg;
}
Value walletpassphrase(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() < 2 || params.size() > 3))
throw runtime_error(
"walletpassphrase <passphrase> <timeout> [mintonly]\n"
"Stores the wallet decryption key in memory for <timeout> seconds.\n"
"mintonly is optional true/false allowing only block minting.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called.");
if (!pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_ALREADY_UNLOCKED, "Error: Wallet is already unlocked, use walletlock first if need to change unlock settings.");
// Note that the walletpassphrase is stored in params[0] which is not mlock()ed
SecureString strWalletPass;
strWalletPass.reserve(100);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() > 0)
{
if (!pwalletMain->Unlock(strWalletPass))
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
}
else
throw runtime_error(
"walletpassphrase <passphrase> <timeout>\n"
"Stores the wallet decryption key in memory for <timeout> seconds.");
NewThread(ThreadTopUpKeyPool, NULL);
int64* pnSleepTime = new int64(params[1].get_int64());
NewThread(ThreadCleanWalletPassphrase, pnSleepTime);
// if user OS account compromised prevent trivial sendmoney commands
if (params.size() > 2)
fWalletUnlockMintOnly = params[2].get_bool();
else
fWalletUnlockMintOnly = false;
return Value::null;
}
Value walletpassphrasechange(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
throw runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called.");
// TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strOldWalletPass;
strOldWalletPass.reserve(100);
strOldWalletPass = params[0].get_str().c_str();
SecureString strNewWalletPass;
strNewWalletPass.reserve(100);
strNewWalletPass = params[1].get_str().c_str();
if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1)
throw runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass))
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
return Value::null;
}
Value walletlock(const Array& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0))
throw runtime_error(
"walletlock\n"
"Removes the wallet encryption key from memory, locking the wallet.\n"
"After calling this method, you will need to call walletpassphrase again\n"
"before being able to call any methods which require the wallet to be unlocked.");
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called.");
{
LOCK(cs_nWalletUnlockTime);
pwalletMain->Lock();
nWalletUnlockTime = 0;
}
return Value::null;
}
Value encryptwallet(const Array& params, bool fHelp)
{
if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1))
throw runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (fHelp)
return true;
if (pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called.");
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strWalletPass;
strWalletPass.reserve(100);
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() < 1)
throw runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (!pwalletMain->EncryptWallet(strWalletPass))
throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet.");
// BDB seems to have a bad habit of writing old data into
// slack space in .dat files; that is bad if the old data is
// unencrypted private keys. So:
StartShutdown();
return "wallet encrypted; UltraCoin server stopping, restart to run with encrypted wallet. The keypool has been flushed, you need to make a new backup.";
}
class DescribeAddressVisitor : public boost::static_visitor<Object>
{
public:
Object operator()(const CNoDestination &dest) const { return Object(); }
Object operator()(const CKeyID &keyID) const {
Object obj;
CPubKey vchPubKey;
pwalletMain->GetPubKey(keyID, vchPubKey);
obj.push_back(Pair("isscript", false));
obj.push_back(Pair("pubkey", HexStr(vchPubKey.Raw())));
obj.push_back(Pair("iscompressed", vchPubKey.IsCompressed()));
return obj;
}
Object operator()(const CScriptID &scriptID) const {
Object obj;
obj.push_back(Pair("isscript", true));
CScript subscript;
pwalletMain->GetCScript(scriptID, subscript);
std::vector<CTxDestination> addresses;
txnouttype whichType;
int nRequired;
ExtractDestinations(subscript, whichType, addresses, nRequired);
obj.push_back(Pair("script", GetTxnOutputType(whichType)));
Array a;
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CBitcoinAddress(addr).ToString());
obj.push_back(Pair("addresses", a));
if (whichType == TX_MULTISIG)
obj.push_back(Pair("sigsrequired", nRequired));
return obj;
}
};
Value validateaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"validateaddress <ultracoinaddress>\n"
"Return information about <ultracoinaddress>.");
CBitcoinAddress address(params[0].get_str());
bool isValid = address.IsValid();
Object ret;
ret.push_back(Pair("isvalid", isValid));
if (isValid)
{
CTxDestination dest = address.Get();
string currentAddress = address.ToString();
ret.push_back(Pair("address", currentAddress));
bool fMine = IsMine(*pwalletMain, dest);
ret.push_back(Pair("ismine", fMine));
if (fMine) {
Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest);
ret.insert(ret.end(), detail.begin(), detail.end());
}
if (pwalletMain->mapAddressBook.count(dest))
ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest]));
}
return ret;
}
Value validatepubkey(const Array& params, bool fHelp)
{
if (fHelp || !params.size() || params.size() > 2)
throw runtime_error(
"validatepubkey <ultracoinpubkey>\n"
"Return information about <ultracoinpubkey>.");
std::vector<unsigned char> vchPubKey = ParseHex(params[0].get_str());
CPubKey pubKey(vchPubKey);
bool isValid = pubKey.IsValid();
bool isCompressed = pubKey.IsCompressed();
CKeyID keyID = pubKey.GetID();
CBitcoinAddress address;
address.Set(keyID);
Object ret;
ret.push_back(Pair("isvalid", isValid));
if (isValid)
{
CTxDestination dest = address.Get();
string currentAddress = address.ToString();
ret.push_back(Pair("address", currentAddress));
bool fMine = IsMine(*pwalletMain, dest);
ret.push_back(Pair("ismine", fMine));
ret.push_back(Pair("iscompressed", isCompressed));
if (fMine) {
Object detail = boost::apply_visitor(DescribeAddressVisitor(), dest);
ret.insert(ret.end(), detail.begin(), detail.end());
}
if (pwalletMain->mapAddressBook.count(dest))
ret.push_back(Pair("account", pwalletMain->mapAddressBook[dest]));
}
return ret;
}
// reserve balance from being staked for network protection
Value reservebalance(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"reservebalance [<reserve> [amount]]\n"
"<reserve> is true or false to turn balance reserve on or off.\n"
"<amount> is a real and rounded to cent.\n"
"Set reserve amount not participating in network protection.\n"
"If no parameters provided current setting is printed.\n");
if (params.size() > 0)
{
bool fReserve = params[0].get_bool();
if (fReserve)
{
if (params.size() == 1)
throw runtime_error("must provide amount to reserve balance.\n");
int64 nAmount = AmountFromValue(params[1]);
nAmount = (nAmount / MIN_TXOUT_AMOUNT) * MIN_TXOUT_AMOUNT; // round to cent
if (nAmount < 0)
throw runtime_error("amount cannot be negative.\n");
mapArgs["-reservebalance"] = FormatMoney(nAmount).c_str();
}
else
{
if (params.size() > 1)
throw runtime_error("cannot specify amount to turn off reserve.\n");
mapArgs["-reservebalance"] = "0";
}
}
Object result;
int64 nReserveBalance = 0;
if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
throw runtime_error("invalid reserve balance amount\n");
result.push_back(Pair("reserve", (nReserveBalance > 0)));
result.push_back(Pair("amount", ValueFromAmount(nReserveBalance)));
return result;
}
// check wallet integrity
Value checkwallet(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"checkwallet\n"
"Check wallet for integrity.\n");
int nMismatchSpent;
int64 nBalanceInQuestion;
pwalletMain->FixSpentCoins(nMismatchSpent, nBalanceInQuestion, true);
Object result;
if (nMismatchSpent == 0)
result.push_back(Pair("wallet check passed", true));
else
{
result.push_back(Pair("mismatched spent coins", nMismatchSpent));
result.push_back(Pair("amount in question", ValueFromAmount(nBalanceInQuestion)));
}
return result;
}
// repair wallet
Value repairwallet(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"repairwallet\n"
"Repair wallet if checkwallet reports any problem.\n");
int nMismatchSpent;
int64 nBalanceInQuestion;
pwalletMain->FixSpentCoins(nMismatchSpent, nBalanceInQuestion);
Object result;
if (nMismatchSpent == 0)
result.push_back(Pair("wallet check passed", true));
else
{
result.push_back(Pair("mismatched spent coins", nMismatchSpent));
result.push_back(Pair("amount affected by repair", ValueFromAmount(nBalanceInQuestion)));
}
return result;
}
// UltraCoin: resend unconfirmed wallet transactions
Value resendtx(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"resendtx\n"
"Re-send unconfirmed transactions.\n"
);
ResendWalletTransactions();
return Value::null;
}
// make a public-private key pair
Value makekeypair(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"makekeypair [prefix]\n"
"Make a public/private key pair.\n"
"[prefix] is optional preferred prefix for the public key.\n");
string strPrefix = "";
if (params.size() > 0)
strPrefix = params[0].get_str();
CKey key;
key.MakeNewKey(false);
CPrivKey vchPrivKey = key.GetPrivKey();
Object result;
result.push_back(Pair("PrivateKey", HexStr<CPrivKey::iterator>(vchPrivKey.begin(), vchPrivKey.end())));
result.push_back(Pair("PublicKey", HexStr(key.GetPubKey().Raw())));
return result;
}
|
/** \file
* \brief Implements front-end for LP solver
*
* \author Carsten Gutwenger
*
* \par License:
* This file is part of the Open Graph Drawing Framework (OGDF).
*
* \par
* Copyright (C)<br>
* See README.txt in the root directory of the OGDF installation for details.
*
* \par
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* Version 2 or 3 as published by the Free Software Foundation;
* see the file LICENSE.txt included in the packaging of this file
* for details.
*
* \par
* 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.
*
* \par
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
* \see http://www.gnu.org/copyleft/gpl.html
***************************************************************/
#include <ogdf/basic/basic.h>
#ifdef USE_COIN
#include <ogdf/internal/lpsolver/LPSolver_coin.h>
namespace ogdf {
LPSolver::LPSolver()
{
osi = CoinManager::createCorrectOsiSolverInterface();
}
double LPSolver::infinity() const
{
return osi->getInfinity();
}
bool LPSolver::checkFeasibility(
const Array<int> &matrixBegin, // matrixBegin[i] = begin of column i
const Array<int> &matrixCount, // matrixCount[i] = number of nonzeroes in column i
const Array<int> &matrixIndex, // matrixIndex[n] = index of matrixValue[n] in its column
const Array<double> &matrixValue, // matrixValue[n] = non-zero value in matrix
const Array<double> &rightHandSide, // right-hand side of LP constraints
const Array<char> &equationSense, // 'E' == 'G' >= 'L' <=
const Array<double> &lowerBound, // lower bound of x[i]
const Array<double> &upperBound, // upper bound of x[i]
const Array<double> &x // x-vector of optimal solution (if result is lpOptimal)
)
{
const int numRows = rightHandSide.size();
const int numCols = x.size();
double eps;
osi->getDblParam(OsiPrimalTolerance, eps);
for(int i = 0; i < numCols; ++i) {
if(x[i]+eps < lowerBound[i] || x[i]-eps > upperBound[i]) {
cerr << "column " << i << " out of range" << endl;
return false;
}
}
for(int i = 0; i < numRows; ++i) {
double leftHandSide = 0.0;
for(int c = 0; c < numCols; ++c) {
for(int j = matrixBegin[c]; j < matrixBegin[c]+matrixCount[c]; ++j)
if(matrixIndex[j] == i) {
leftHandSide += matrixValue[j] * x[c];
}
}
switch(equationSense[i]) {
case 'G':
if(leftHandSide+eps < rightHandSide[i]) {
cerr << "row " << i << " violated " << endl;
cerr << leftHandSide << " > " << rightHandSide[i] << endl;
return false;
}
break;
case 'L':
if(leftHandSide-eps > rightHandSide[i]) {
cerr << "row " << i << " violated " << endl;
cerr << leftHandSide << " < " << rightHandSide[i] << endl;
return false;
}
break;
case 'E':
if(leftHandSide+eps < rightHandSide[i] || leftHandSide-eps > rightHandSide[i]) {
cerr << "row " << i << " violated " << endl;
cerr << leftHandSide << " = " << rightHandSide[i] << endl;
return false;
}
break;
default:
cerr << "unexpected equation sense " << equationSense[i] << endl;
return false;
}
}
return true;
}
LPSolver::Status LPSolver::optimize(
OptimizationGoal goal, // goal of optimization (minimize or maximize)
Array<double> &obj, // objective function vector
Array<int> &matrixBegin, // matrixBegin[i] = begin of column i
Array<int> &matrixCount, // matrixCount[i] = number of nonzeroes in column i
Array<int> &matrixIndex, // matrixIndex[n] = index of matrixValue[n] in its column
Array<double> &matrixValue, // matrixValue[n] = non-zero value in matrix
Array<double> &rightHandSide, // right-hand side of LP constraints
Array<char> &equationSense, // 'E' == 'G' >= 'L' <=
Array<double> &lowerBound, // lower bound of x[i]
Array<double> &upperBound, // upper bound of x[i]
double &optimum, // optimum value of objective function (if result is lpOptimal)
Array<double> &x // x-vector of optimal solution (if result is lpOptimal)
)
{
if(osi->getNumCols()>0) { // get a fresh one if necessary
delete osi;
osi = CoinManager::createCorrectOsiSolverInterface();
}
const int numRows = rightHandSide.size();
const int numCols = obj.size();
#ifdef OGDF_DEBUG
const int numNonzeroes = matrixIndex.size();
#endif
// assert correctness of array boundaries
OGDF_ASSERT(obj .low() == 0);
OGDF_ASSERT(obj .size() == numCols);
OGDF_ASSERT(matrixBegin .low() == 0);
OGDF_ASSERT(matrixBegin .size() == numCols);
OGDF_ASSERT(matrixCount .low() == 0);
OGDF_ASSERT(matrixCount .size() == numCols);
OGDF_ASSERT(matrixIndex .low() == 0);
OGDF_ASSERT(matrixIndex .size() == numNonzeroes);
OGDF_ASSERT(matrixValue .low() == 0);
OGDF_ASSERT(matrixValue .size() == numNonzeroes);
OGDF_ASSERT(rightHandSide.low() == 0);
OGDF_ASSERT(rightHandSide.size() == numRows);
OGDF_ASSERT(equationSense.low() == 0);
OGDF_ASSERT(equationSense.size() == numRows);
OGDF_ASSERT(lowerBound .low() == 0);
OGDF_ASSERT(lowerBound .size() == numCols);
OGDF_ASSERT(upperBound .low() == 0);
OGDF_ASSERT(upperBound .size() == numCols);
OGDF_ASSERT(x .low() == 0);
OGDF_ASSERT(x .size() == numCols);
osi->setObjSense(goal==lpMinimize ? 1 : -1);
int i;
CoinPackedVector zero;
for(i = 0; i < numRows; ++i) {
osi->addRow(zero,equationSense[i],rightHandSide[i],0);
}
for(int colNo = 0; colNo < numCols; ++colNo) {
CoinPackedVector cpv;
for(i = matrixBegin[colNo]; i<matrixBegin[colNo]+matrixCount[colNo]; ++i) {
cpv.insert(matrixIndex[i],matrixValue[i]);
}
osi->addCol(cpv,lowerBound[colNo],upperBound[colNo],obj[colNo]);
}
osi->initialSolve();
Status status;
if(osi->isProvenOptimal()) {
optimum = osi->getObjValue();
const double* sol = osi->getColSolution();
for(i = numCols; i-->0;)
x[i]=sol[i];
status = lpOptimal;
OGDF_ASSERT_IF(dlExtendedChecking,
checkFeasibility(matrixBegin,matrixCount,matrixIndex,matrixValue,
rightHandSide,equationSense,lowerBound,upperBound,x));
} else if(osi->isProvenPrimalInfeasible())
status = lpInfeasible;
else if(osi->isProvenDualInfeasible())
status = lpUnbounded;
else
OGDF_THROW_PARAM(AlgorithmFailureException,afcNoSolutionFound);
return status;
}
} // end namespace ogdf
#endif
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2012 Litecoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "irc.h"
#include "db.h"
#include "net.h"
#include "init.h"
#include "strlcpy.h"
#include "addrman.h"
#include "ui_interface.h"
#ifdef WIN32
#include <string.h>
#endif
using namespace std;
using namespace boost;
static const int MAX_OUTBOUND_CONNECTIONS = 8;
void ThreadMessageHandler2(void* parg);
void ThreadSocketHandler2(void* parg);
void ThreadOpenConnections2(void* parg);
void ThreadOpenAddedConnections2(void* parg);
void ThreadDNSAddressSeed2(void* parg);
bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
struct LocalServiceInfo {
int nScore;
int nPort;
};
//
// Global state variables
//
bool fClient = false;
bool fDiscover = true;
uint64 nLocalServices = (fClient ? 0 : NODE_NETWORK);
static CCriticalSection cs_mapLocalHost;
static map<CNetAddr, LocalServiceInfo> mapLocalHost;
static bool vfReachable[NET_MAX] = {};
static bool vfLimited[NET_MAX] = {};
static CNode* pnodeLocalHost = NULL;
uint64 nLocalHostNonce = 0;
array<int, THREAD_MAX> vnThreadsRunning;
static std::vector<SOCKET> vhListenSocket;
CAddrMan addrman;
vector<CNode*> vNodes;
CCriticalSection cs_vNodes;
map<CInv, CDataStream> mapRelay;
deque<pair<int64, CInv> > vRelayExpiration;
CCriticalSection cs_mapRelay;
map<CInv, int64> mapAlreadyAskedFor;
static deque<string> vOneShots;
CCriticalSection cs_vOneShots;
set<CNetAddr> setservAddNodeAddresses;
CCriticalSection cs_setservAddNodeAddresses;
static CSemaphore *semOutbound = NULL;
void AddOneShot(string strDest)
{
LOCK(cs_vOneShots);
vOneShots.push_back(strDest);
}
unsigned short GetListenPort()
{
return (unsigned short)(GetArg("-port", GetDefaultPort()));
}
void CNode::PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd)
{
// Filter out duplicate requests
if (pindexBegin == pindexLastGetBlocksBegin && hashEnd == hashLastGetBlocksEnd)
return;
pindexLastGetBlocksBegin = pindexBegin;
hashLastGetBlocksEnd = hashEnd;
PushMessage("getblocks", CBlockLocator(pindexBegin), hashEnd);
}
// find 'best' local address for a particular peer
bool GetLocal(CService& addr, const CNetAddr *paddrPeer)
{
if (fNoListen)
return false;
int nBestScore = -1;
int nBestReachability = -1;
{
LOCK(cs_mapLocalHost);
for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++)
{
int nScore = (*it).second.nScore;
int nReachability = (*it).first.GetReachabilityFrom(paddrPeer);
if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore))
{
addr = CService((*it).first, (*it).second.nPort);
nBestReachability = nReachability;
nBestScore = nScore;
}
}
}
return nBestScore >= 0;
}
// get best local address for a particular peer as a CAddress
CAddress GetLocalAddress(const CNetAddr *paddrPeer)
{
CAddress ret(CService("0.0.0.0",0),0);
CService addr;
if (GetLocal(addr, paddrPeer))
{
ret = CAddress(addr);
ret.nServices = nLocalServices;
ret.nTime = GetAdjustedTime();
}
return ret;
}
bool RecvLine(SOCKET hSocket, string& strLine)
{
strLine = "";
loop
{
char c;
int nBytes = recv(hSocket, &c, 1, 0);
if (nBytes > 0)
{
if (c == '\n')
continue;
if (c == '\r')
return true;
strLine += c;
if (strLine.size() >= 9000)
return true;
}
else if (nBytes <= 0)
{
if (fShutdown)
return false;
if (nBytes < 0)
{
int nErr = WSAGetLastError();
if (nErr == WSAEMSGSIZE)
continue;
if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS)
{
Sleep(10);
continue;
}
}
if (!strLine.empty())
return true;
if (nBytes == 0)
{
// socket closed
printf("socket closed\n");
return false;
}
else
{
// socket error
int nErr = WSAGetLastError();
printf("recv failed: %d\n", nErr);
return false;
}
}
}
}
// used when scores of local addresses may have changed
// pushes better local address to peers
void static AdvertizeLocal()
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->fSuccessfullyConnected)
{
CAddress addrLocal = GetLocalAddress(&pnode->addr);
if (addrLocal.IsRoutable() && (CService)addrLocal != (CService)pnode->addrLocal)
{
pnode->PushAddress(addrLocal);
pnode->addrLocal = addrLocal;
}
}
}
}
void SetReachable(enum Network net, bool fFlag)
{
LOCK(cs_mapLocalHost);
vfReachable[net] = fFlag;
if (net == NET_IPV6 && fFlag)
vfReachable[NET_IPV4] = true;
}
// learn a new local address
bool AddLocal(const CService& addr, int nScore)
{
if (!addr.IsRoutable())
return false;
if (!fDiscover && nScore < LOCAL_MANUAL)
return false;
if (IsLimited(addr))
return false;
printf("AddLocal(%s,%i)\n", addr.ToString().c_str(), nScore);
{
LOCK(cs_mapLocalHost);
bool fAlready = mapLocalHost.count(addr) > 0;
LocalServiceInfo &info = mapLocalHost[addr];
if (!fAlready || nScore >= info.nScore) {
info.nScore = nScore;
info.nPort = addr.GetPort() + (fAlready ? 1 : 0);
}
SetReachable(addr.GetNetwork());
}
AdvertizeLocal();
return true;
}
bool AddLocal(const CNetAddr &addr, int nScore)
{
return AddLocal(CService(addr, GetListenPort()), nScore);
}
/** Make a particular network entirely off-limits (no automatic connects to it) */
void SetLimited(enum Network net, bool fLimited)
{
if (net == NET_UNROUTABLE)
return;
LOCK(cs_mapLocalHost);
vfLimited[net] = fLimited;
}
bool IsLimited(enum Network net)
{
LOCK(cs_mapLocalHost);
return vfLimited[net];
}
bool IsLimited(const CNetAddr &addr)
{
return IsLimited(addr.GetNetwork());
}
/** vote for a local address */
bool SeenLocal(const CService& addr)
{
{
LOCK(cs_mapLocalHost);
if (mapLocalHost.count(addr) == 0)
return false;
mapLocalHost[addr].nScore++;
}
AdvertizeLocal();
return true;
}
/** check whether a given address is potentially local */
bool IsLocal(const CService& addr)
{
LOCK(cs_mapLocalHost);
return mapLocalHost.count(addr) > 0;
}
/** check whether a given address is in a network we can probably connect to */
bool IsReachable(const CNetAddr& addr)
{
LOCK(cs_mapLocalHost);
enum Network net = addr.GetNetwork();
return vfReachable[net] && !vfLimited[net];
}
bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const char* pszKeyword, CNetAddr& ipRet)
{
SOCKET hSocket;
if (!ConnectSocket(addrConnect, hSocket))
return error("GetMyExternalIP() : connection to %s failed", addrConnect.ToString().c_str());
send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL);
string strLine;
while (RecvLine(hSocket, strLine))
{
if (strLine.empty()) // HTTP response is separated from headers by blank line
{
loop
{
if (!RecvLine(hSocket, strLine))
{
closesocket(hSocket);
return false;
}
if (pszKeyword == NULL)
break;
if (strLine.find(pszKeyword) != string::npos)
{
strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword));
break;
}
}
closesocket(hSocket);
if (strLine.find("<") != string::npos)
strLine = strLine.substr(0, strLine.find("<"));
strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r"));
while (strLine.size() > 0 && isspace(strLine[strLine.size()-1]))
strLine.resize(strLine.size()-1);
CService addr(strLine,0,true);
printf("GetMyExternalIP() received [%s] %s\n", strLine.c_str(), addr.ToString().c_str());
if (!addr.IsValid() || !addr.IsRoutable())
return false;
ipRet.SetIP(addr);
return true;
}
}
closesocket(hSocket);
return error("GetMyExternalIP() : connection closed");
}
// We now get our external IP from the IRC server first and only use this as a backup
bool GetMyExternalIP(CNetAddr& ipRet)
{
CService addrConnect;
const char* pszGet;
const char* pszKeyword;
for (int nLookup = 0; nLookup <= 1; nLookup++)
for (int nHost = 1; nHost <= 2; nHost++)
{
// We should be phasing out our use of sites like these. If we need
// replacements, we should ask for volunteers to put this simple
// php file on their webserver that prints the client IP:
// <?php echo $_SERVER["REMOTE_ADDR"]; ?>
if (nHost == 1)
{
addrConnect = CService("91.198.22.70",80); // checkip.dyndns.org
if (nLookup == 1)
{
CService addrIP("checkip.dyndns.org", 80, true);
if (addrIP.IsValid())
addrConnect = addrIP;
}
pszGet = "GET / HTTP/1.1\r\n"
"Host: checkip.dyndns.org\r\n"
"User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"
"Connection: close\r\n"
"\r\n";
pszKeyword = "Address:";
}
else if (nHost == 2)
{
addrConnect = CService("74.208.43.192", 80); // www.showmyip.com
if (nLookup == 1)
{
CService addrIP("www.showmyip.com", 80, true);
if (addrIP.IsValid())
addrConnect = addrIP;
}
pszGet = "GET /simple/ HTTP/1.1\r\n"
"Host: www.showmyip.com\r\n"
"User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"
"Connection: close\r\n"
"\r\n";
pszKeyword = NULL; // Returns just IP address
}
if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet))
return true;
}
return false;
}
void ThreadGetMyExternalIP(void* parg)
{
// Make this thread recognisable as the external IP detection thread
RenameThread("bitcoin-ext-ip");
CNetAddr addrLocalHost;
if (GetMyExternalIP(addrLocalHost))
{
printf("GetMyExternalIP() returned %s\n", addrLocalHost.ToStringIP().c_str());
AddLocal(addrLocalHost, LOCAL_HTTP);
}
}
void AddressCurrentlyConnected(const CService& addr)
{
addrman.Connected(addr);
}
CNode* FindNode(const CNetAddr& ip)
{
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if ((CNetAddr)pnode->addr == ip)
return (pnode);
}
return NULL;
}
CNode* FindNode(std::string addrName)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->addrName == addrName)
return (pnode);
return NULL;
}
CNode* FindNode(const CService& addr)
{
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if ((CService)pnode->addr == addr)
return (pnode);
}
return NULL;
}
CNode* ConnectNode(CAddress addrConnect, const char *pszDest, int64 nTimeout)
{
if (pszDest == NULL) {
if (IsLocal(addrConnect))
return NULL;
// Look for an existing connection
CNode* pnode = FindNode((CService)addrConnect);
if (pnode)
{
if (nTimeout != 0)
pnode->AddRef(nTimeout);
else
pnode->AddRef();
return pnode;
}
}
/// debug print
printf("trying connection %s lastseen=%.1fhrs\n",
pszDest ? pszDest : addrConnect.ToString().c_str(),
pszDest ? 0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0);
// Connect
SOCKET hSocket;
if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, GetDefaultPort()) : ConnectSocket(addrConnect, hSocket))
{
addrman.Attempt(addrConnect);
/// debug print
printf("connected %s\n", pszDest ? pszDest : addrConnect.ToString().c_str());
// Set to nonblocking
#ifdef WIN32
u_long nOne = 1;
if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR)
printf("ConnectSocket() : ioctlsocket nonblocking setting failed, error %d\n", WSAGetLastError());
#else
if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
printf("ConnectSocket() : fcntl nonblocking setting failed, error %d\n", errno);
#endif
// Add node
CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false);
if (nTimeout != 0)
pnode->AddRef(nTimeout);
else
pnode->AddRef();
{
LOCK(cs_vNodes);
vNodes.push_back(pnode);
}
pnode->nTimeConnected = GetTime();
return pnode;
}
else
{
return NULL;
}
}
void CNode::CloseSocketDisconnect()
{
fDisconnect = true;
if (hSocket != INVALID_SOCKET)
{
printf("disconnecting node %s\n", addrName.c_str());
closesocket(hSocket);
hSocket = INVALID_SOCKET;
vRecv.clear();
}
}
void CNode::Cleanup()
{
}
void CNode::PushVersion()
{
/// when NTP implemented, change to just nTime = GetAdjustedTime()
int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0",0)));
CAddress addrMe = GetLocalAddress(&addr);
RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
printf("send version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString().c_str(), addrYou.ToString().c_str(), addr.ToString().c_str());
PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe,
nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight);
}
std::map<CNetAddr, int64> CNode::setBanned;
CCriticalSection CNode::cs_setBanned;
void CNode::ClearBanned()
{
setBanned.clear();
}
bool CNode::IsBanned(CNetAddr ip)
{
bool fResult = false;
{
LOCK(cs_setBanned);
std::map<CNetAddr, int64>::iterator i = setBanned.find(ip);
if (i != setBanned.end())
{
int64 t = (*i).second;
if (GetTime() < t)
fResult = true;
}
}
return fResult;
}
bool CNode::Misbehaving(int howmuch)
{
if (addr.IsLocal())
{
printf("Warning: local node %s misbehaving\n", addrName.c_str());
return false;
}
nMisbehavior += howmuch;
if (nMisbehavior >= GetArg("-banscore", 100))
{
int64 banTime = GetTime()+GetArg("-bantime", 60*60*24); // Default 24-hour ban
{
LOCK(cs_setBanned);
if (setBanned[addr] < banTime)
setBanned[addr] = banTime;
}
CloseSocketDisconnect();
printf("Disconnected %s for misbehavior (score=%d)\n", addrName.c_str(), nMisbehavior);
return true;
}
return false;
}
#undef X
#define X(name) stats.name = name
void CNode::copyStats(CNodeStats &stats)
{
X(nServices);
X(nLastSend);
X(nLastRecv);
X(nTimeConnected);
X(addrName);
X(nVersion);
X(strSubVer);
X(fInbound);
X(nReleaseTime);
X(nStartingHeight);
X(nMisbehavior);
}
#undef X
void ThreadSocketHandler(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadSocketHandler(parg));
// Make this thread recognisable as the networking thread
RenameThread("bitcoin-net");
try
{
vnThreadsRunning[THREAD_SOCKETHANDLER]++;
ThreadSocketHandler2(parg);
vnThreadsRunning[THREAD_SOCKETHANDLER]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_SOCKETHANDLER]--;
PrintException(&e, "ThreadSocketHandler()");
} catch (...) {
vnThreadsRunning[THREAD_SOCKETHANDLER]--;
throw; // support pthread_cancel()
}
printf("ThreadSocketHandler exited\n");
}
void ThreadSocketHandler2(void* parg)
{
printf("ThreadSocketHandler started\n");
list<CNode*> vNodesDisconnected;
unsigned int nPrevNodeCount = 0;
loop
{
//
// Disconnect nodes
//
{
LOCK(cs_vNodes);
// Disconnect unused nodes
vector<CNode*> vNodesCopy = vNodes;
BOOST_FOREACH(CNode* pnode, vNodesCopy)
{
if (pnode->fDisconnect ||
(pnode->GetRefCount() <= 0 && pnode->vRecv.empty() && pnode->vSend.empty()))
{
// remove from vNodes
vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
// release outbound grant (if any)
pnode->grantOutbound.Release();
// close socket and cleanup
pnode->CloseSocketDisconnect();
pnode->Cleanup();
// hold in disconnected pool until all refs are released
pnode->nReleaseTime = max(pnode->nReleaseTime, GetTime() + 15 * 60);
if (pnode->fNetworkNode || pnode->fInbound)
pnode->Release();
vNodesDisconnected.push_back(pnode);
}
}
// Delete disconnected nodes
list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy)
{
// wait until threads are done using it
if (pnode->GetRefCount() <= 0)
{
bool fDelete = false;
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
{
TRY_LOCK(pnode->cs_vRecv, lockRecv);
if (lockRecv)
{
TRY_LOCK(pnode->cs_mapRequests, lockReq);
if (lockReq)
{
TRY_LOCK(pnode->cs_inventory, lockInv);
if (lockInv)
fDelete = true;
}
}
}
}
if (fDelete)
{
vNodesDisconnected.remove(pnode);
delete pnode;
}
}
}
}
if (vNodes.size() != nPrevNodeCount)
{
nPrevNodeCount = vNodes.size();
uiInterface.NotifyNumConnectionsChanged(vNodes.size());
}
//
// Find which sockets have data to receive
//
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 50000; // frequency to poll pnode->vSend
fd_set fdsetRecv;
fd_set fdsetSend;
fd_set fdsetError;
FD_ZERO(&fdsetRecv);
FD_ZERO(&fdsetSend);
FD_ZERO(&fdsetError);
SOCKET hSocketMax = 0;
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) {
FD_SET(hListenSocket, &fdsetRecv);
hSocketMax = max(hSocketMax, hListenSocket);
}
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->hSocket == INVALID_SOCKET)
continue;
FD_SET(pnode->hSocket, &fdsetRecv);
FD_SET(pnode->hSocket, &fdsetError);
hSocketMax = max(hSocketMax, pnode->hSocket);
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend && !pnode->vSend.empty())
FD_SET(pnode->hSocket, &fdsetSend);
}
}
}
vnThreadsRunning[THREAD_SOCKETHANDLER]--;
int nSelect = select(hSocketMax + 1, &fdsetRecv, &fdsetSend, &fdsetError, &timeout);
vnThreadsRunning[THREAD_SOCKETHANDLER]++;
if (fShutdown)
return;
if (nSelect == SOCKET_ERROR)
{
int nErr = WSAGetLastError();
if (hSocketMax != INVALID_SOCKET)
{
printf("socket select error %d\n", nErr);
for (unsigned int i = 0; i <= hSocketMax; i++)
FD_SET(i, &fdsetRecv);
}
FD_ZERO(&fdsetSend);
FD_ZERO(&fdsetError);
Sleep(timeout.tv_usec/1000);
}
//
// Accept new connections
//
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
if (hListenSocket != INVALID_SOCKET && FD_ISSET(hListenSocket, &fdsetRecv))
{
#ifdef USE_IPV6
struct sockaddr_storage sockaddr;
#else
struct sockaddr sockaddr;
#endif
socklen_t len = sizeof(sockaddr);
SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len);
CAddress addr;
int nInbound = 0;
if (hSocket != INVALID_SOCKET)
if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr))
printf("warning: unknown socket family\n");
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->fInbound)
nInbound++;
}
if (hSocket == INVALID_SOCKET)
{
if (WSAGetLastError() != WSAEWOULDBLOCK)
printf("socket error accept failed: %d\n", WSAGetLastError());
}
else if (nInbound >= GetArg("-maxconnections", 125) - MAX_OUTBOUND_CONNECTIONS)
{
{
LOCK(cs_setservAddNodeAddresses);
if (!setservAddNodeAddresses.count(addr))
closesocket(hSocket);
}
}
else if (CNode::IsBanned(addr))
{
printf("connection from %s dropped (banned)\n", addr.ToString().c_str());
closesocket(hSocket);
}
else
{
printf("accepted connection %s\n", addr.ToString().c_str());
CNode* pnode = new CNode(hSocket, addr, "", true);
pnode->AddRef();
{
LOCK(cs_vNodes);
vNodes.push_back(pnode);
}
}
}
//
// Service each socket
//
vector<CNode*> vNodesCopy;
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->AddRef();
}
BOOST_FOREACH(CNode* pnode, vNodesCopy)
{
if (fShutdown)
return;
//
// Receive
//
if (pnode->hSocket == INVALID_SOCKET)
continue;
if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError))
{
TRY_LOCK(pnode->cs_vRecv, lockRecv);
if (lockRecv)
{
CDataStream& vRecv = pnode->vRecv;
unsigned int nPos = vRecv.size();
if (nPos > ReceiveBufferSize()) {
if (!pnode->fDisconnect)
printf("socket recv flood control disconnect (%d bytes)\n", vRecv.size());
pnode->CloseSocketDisconnect();
}
else {
// typical socket buffer is 8K-64K
char pchBuf[0x10000];
int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
if (nBytes > 0)
{
vRecv.resize(nPos + nBytes);
memcpy(&vRecv[nPos], pchBuf, nBytes);
pnode->nLastRecv = GetTime();
}
else if (nBytes == 0)
{
// socket closed gracefully
if (!pnode->fDisconnect)
printf("socket closed\n");
pnode->CloseSocketDisconnect();
}
else if (nBytes < 0)
{
// error
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
{
if (!pnode->fDisconnect)
printf("socket recv error %d\n", nErr);
pnode->CloseSocketDisconnect();
}
}
}
}
}
//
// Send
//
if (pnode->hSocket == INVALID_SOCKET)
continue;
if (FD_ISSET(pnode->hSocket, &fdsetSend))
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
{
CDataStream& vSend = pnode->vSend;
if (!vSend.empty())
{
int nBytes = send(pnode->hSocket, &vSend[0], vSend.size(), MSG_NOSIGNAL | MSG_DONTWAIT);
if (nBytes > 0)
{
vSend.erase(vSend.begin(), vSend.begin() + nBytes);
pnode->nLastSend = GetTime();
}
else if (nBytes < 0)
{
// error
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
{
printf("socket send error %d\n", nErr);
pnode->CloseSocketDisconnect();
}
}
}
}
}
//
// Inactivity checking
//
if (pnode->vSend.empty())
pnode->nLastSendEmpty = GetTime();
if (GetTime() - pnode->nTimeConnected > 60)
{
if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)
{
printf("socket no message in first 60 seconds, %d %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0);
pnode->fDisconnect = true;
}
else if (GetTime() - pnode->nLastSend > 90*60 && GetTime() - pnode->nLastSendEmpty > 90*60)
{
printf("socket not sending\n");
pnode->fDisconnect = true;
}
else if (GetTime() - pnode->nLastRecv > 90*60)
{
printf("socket inactivity timeout\n");
pnode->fDisconnect = true;
}
}
}
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->Release();
}
Sleep(10);
}
}
// DNS seeds
// Each pair gives a source name and a seed name.
// The first name is used as information source for addrman.
// The second name should resolve to a list of seed addresses.
static const char *strDNSSeed[][2] = {
{"some website name", "somewebsite.org or ip x.x.x.x},
};
void ThreadDNSAddressSeed(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadDNSAddressSeed(parg));
// Make this thread recognisable as the DNS seeding thread
RenameThread("bitcoin-dnsseed");
try
{
vnThreadsRunning[THREAD_DNSSEED]++;
ThreadDNSAddressSeed2(parg);
vnThreadsRunning[THREAD_DNSSEED]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_DNSSEED]--;
PrintException(&e, "ThreadDNSAddressSeed()");
} catch (...) {
vnThreadsRunning[THREAD_DNSSEED]--;
throw; // support pthread_cancel()
}
printf("ThreadDNSAddressSeed exited\n");
}
void ThreadDNSAddressSeed2(void* parg)
{
printf("ThreadDNSAddressSeed started\n");
int found = 0;
if (!fTestNet)
{
printf("Loading addresses from DNS seeds (could take a while)\n");
for (unsigned int seed_idx = 0; seed_idx < ARRAYLEN(strDNSSeed); seed_idx++) {
if (GetNameProxy()) {
AddOneShot(strDNSSeed[seed_idx][1]);
} else {
vector<CNetAddr> vaddr;
vector<CAddress> vAdd;
if (LookupHost(strDNSSeed[seed_idx][1], vaddr))
{
BOOST_FOREACH(CNetAddr& ip, vaddr)
{
int nOneDay = 24*3600;
CAddress addr = CAddress(CService(ip, GetDefaultPort()));
addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old
vAdd.push_back(addr);
found++;
}
}
addrman.Add(vAdd, CNetAddr(strDNSSeed[seed_idx][0], true));
}
}
}
printf("%d addresses found from DNS seeds\n", found);
}
unsigned int pnSeed[] =
{
0x2EFDCB71, 0xCC1B3AD6, 0xADA77149,
};
void DumpAddresses()
{
int64 nStart = GetTimeMillis();
CAddrDB adb;
adb.Write(addrman);
printf("Flushed %d addresses to peers.dat %"PRI64d"ms\n",
addrman.size(), GetTimeMillis() - nStart);
}
void ThreadDumpAddress2(void* parg)
{
vnThreadsRunning[THREAD_DUMPADDRESS]++;
while (!fShutdown)
{
DumpAddresses();
vnThreadsRunning[THREAD_DUMPADDRESS]--;
Sleep(100000);
vnThreadsRunning[THREAD_DUMPADDRESS]++;
}
vnThreadsRunning[THREAD_DUMPADDRESS]--;
}
void ThreadDumpAddress(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadDumpAddress(parg));
// Make this thread recognisable as the address dumping thread
RenameThread("bitcoin-adrdump");
try
{
ThreadDumpAddress2(parg);
}
catch (std::exception& e) {
PrintException(&e, "ThreadDumpAddress()");
}
printf("ThreadDumpAddress exited\n");
}
void ThreadOpenConnections(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadOpenConnections(parg));
// Make this thread recognisable as the connection opening thread
RenameThread("bitcoin-opencon");
try
{
vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
ThreadOpenConnections2(parg);
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
PrintException(&e, "ThreadOpenConnections()");
} catch (...) {
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
PrintException(NULL, "ThreadOpenConnections()");
}
printf("ThreadOpenConnections exited\n");
}
void static ProcessOneShot()
{
string strDest;
{
LOCK(cs_vOneShots);
if (vOneShots.empty())
return;
strDest = vOneShots.front();
vOneShots.pop_front();
}
CAddress addr;
CSemaphoreGrant grant(*semOutbound, true);
if (grant) {
if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true))
AddOneShot(strDest);
}
}
void ThreadOpenConnections2(void* parg)
{
printf("ThreadOpenConnections started\n");
// Connect to specific addresses
if (mapArgs.count("-connect"))
{
for (int64 nLoop = 0;; nLoop++)
{
ProcessOneShot();
BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"])
{
CAddress addr;
OpenNetworkConnection(addr, NULL, strAddr.c_str());
for (int i = 0; i < 10 && i < nLoop; i++)
{
Sleep(500);
if (fShutdown)
return;
}
}
}
}
// Initiate network connections
int64 nStart = GetTime();
loop
{
ProcessOneShot();
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
Sleep(500);
vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
if (fShutdown)
return;
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
CSemaphoreGrant grant(*semOutbound);
vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
if (fShutdown)
return;
// Add seed nodes if IRC isn't working
if (addrman.size()==0 && (GetTime() - nStart > 60) && !fTestNet)
{
std::vector<CAddress> vAdd;
for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
{
// It'll only connect to one or two seed nodes because once it connects,
// it'll get a pile of addresses with newer timestamps.
// Seed nodes are given a random 'last seen time' of between one and two
// weeks ago.
const int64 nOneWeek = 7*24*60*60;
struct in_addr ip;
memcpy(&ip, &pnSeed[i], sizeof(ip));
CAddress addr(CService(ip, GetDefaultPort()));
addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek;
vAdd.push_back(addr);
}
addrman.Add(vAdd, CNetAddr("127.0.0.1"));
}
//
// Choose an address to connect to based on most recently seen
//
CAddress addrConnect;
// Only connect out to one peer per network group (/16 for IPv4).
// Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
int nOutbound = 0;
set<vector<unsigned char> > setConnected;
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes) {
if (!pnode->fInbound) {
setConnected.insert(pnode->addr.GetGroup());
nOutbound++;
}
}
}
int64 nANow = GetAdjustedTime();
int nTries = 0;
loop
{
// use an nUnkBias between 10 (no outgoing connections) and 90 (8 outgoing connections)
CAddress addr = addrman.Select(10 + min(nOutbound,8)*10);
// if we selected an invalid address, restart
if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
break;
nTries++;
if (IsLimited(addr))
continue;
// only consider very recently tried nodes after 30 failed attempts
if (nANow - addr.nLastTry < 600 && nTries < 30)
continue;
// do not allow non-default ports, unless after 50 invalid addresses selected already
if (addr.GetPort() != GetDefaultPort() && nTries < 50)
continue;
addrConnect = addr;
break;
}
if (addrConnect.IsValid())
OpenNetworkConnection(addrConnect, &grant);
}
}
void ThreadOpenAddedConnections(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadOpenAddedConnections(parg));
// Make this thread recognisable as the connection opening thread
RenameThread("bitcoin-opencon");
try
{
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
ThreadOpenAddedConnections2(parg);
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
PrintException(&e, "ThreadOpenAddedConnections()");
} catch (...) {
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
PrintException(NULL, "ThreadOpenAddedConnections()");
}
printf("ThreadOpenAddedConnections exited\n");
}
void ThreadOpenAddedConnections2(void* parg)
{
printf("ThreadOpenAddedConnections started\n");
if (mapArgs.count("-addnode") == 0)
return;
if (GetNameProxy()) {
while(!fShutdown) {
BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"]) {
CAddress addr;
CSemaphoreGrant grant(*semOutbound);
OpenNetworkConnection(addr, &grant, strAddNode.c_str());
Sleep(500);
}
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
Sleep(120000); // Retry every 2 minutes
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
}
return;
}
vector<vector<CService> > vservAddressesToAdd(0);
BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"])
{
vector<CService> vservNode(0);
if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0))
{
vservAddressesToAdd.push_back(vservNode);
{
LOCK(cs_setservAddNodeAddresses);
BOOST_FOREACH(CService& serv, vservNode)
setservAddNodeAddresses.insert(serv);
}
}
}
loop
{
vector<vector<CService> > vservConnectAddresses = vservAddressesToAdd;
// Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry
// (keeping in mind that addnode entries can have many IPs if fNameLookup)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
for (vector<vector<CService> >::iterator it = vservConnectAddresses.begin(); it != vservConnectAddresses.end(); it++)
BOOST_FOREACH(CService& addrNode, *(it))
if (pnode->addr == addrNode)
{
it = vservConnectAddresses.erase(it);
it--;
break;
}
}
BOOST_FOREACH(vector<CService>& vserv, vservConnectAddresses)
{
CSemaphoreGrant grant(*semOutbound);
OpenNetworkConnection(CAddress(*(vserv.begin())), &grant);
Sleep(500);
if (fShutdown)
return;
}
if (fShutdown)
return;
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
Sleep(120000); // Retry every 2 minutes
vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
if (fShutdown)
return;
}
}
// if succesful, this moves the passed grant to the constructed node
bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *strDest, bool fOneShot)
{
//
// Initiate outbound network connection
//
if (fShutdown)
return false;
if (!strDest)
if (IsLocal(addrConnect) ||
FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) ||
FindNode(addrConnect.ToStringIPPort().c_str()))
return false;
if (strDest && FindNode(strDest))
return false;
vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
CNode* pnode = ConnectNode(addrConnect, strDest);
vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
if (fShutdown)
return false;
if (!pnode)
return false;
if (grantOutbound)
grantOutbound->MoveTo(pnode->grantOutbound);
pnode->fNetworkNode = true;
if (fOneShot)
pnode->fOneShot = true;
return true;
}
void ThreadMessageHandler(void* parg)
{
IMPLEMENT_RANDOMIZE_STACK(ThreadMessageHandler(parg));
// Make this thread recognisable as the message handling thread
RenameThread("bitcoin-msghand");
try
{
vnThreadsRunning[THREAD_MESSAGEHANDLER]++;
ThreadMessageHandler2(parg);
vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
PrintException(&e, "ThreadMessageHandler()");
} catch (...) {
vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
PrintException(NULL, "ThreadMessageHandler()");
}
printf("ThreadMessageHandler exited\n");
}
void ThreadMessageHandler2(void* parg)
{
printf("ThreadMessageHandler started\n");
SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
while (!fShutdown)
{
vector<CNode*> vNodesCopy;
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->AddRef();
}
// Poll the connected nodes for messages
CNode* pnodeTrickle = NULL;
if (!vNodesCopy.empty())
pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];
BOOST_FOREACH(CNode* pnode, vNodesCopy)
{
// Receive messages
{
TRY_LOCK(pnode->cs_vRecv, lockRecv);
if (lockRecv)
ProcessMessages(pnode);
}
if (fShutdown)
return;
// Send messages
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
SendMessages(pnode, pnode == pnodeTrickle);
}
if (fShutdown)
return;
}
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodesCopy)
pnode->Release();
}
// Wait and allow messages to bunch up.
// Reduce vnThreadsRunning so StopNode has permission to exit while
// we're sleeping, but we must always check fShutdown after doing this.
vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
Sleep(100);
if (fRequestShutdown)
StartShutdown();
vnThreadsRunning[THREAD_MESSAGEHANDLER]++;
if (fShutdown)
return;
}
}
bool BindListenPort(const CService &addrBind, string& strError)
{
strError = "";
int nOne = 1;
#ifdef WIN32
// Initialize Windows Sockets
WSADATA wsadata;
int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
if (ret != NO_ERROR)
{
strError = strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret);
printf("%s\n", strError.c_str());
return false;
}
#endif
// Create socket for listening for incoming connections
#ifdef USE_IPV6
struct sockaddr_storage sockaddr;
#else
struct sockaddr sockaddr;
#endif
socklen_t len = sizeof(sockaddr);
if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
{
strError = strprintf("Error: bind address family for %s not supported", addrBind.ToString().c_str());
printf("%s\n", strError.c_str());
return false;
}
SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
if (hListenSocket == INVALID_SOCKET)
{
strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
#ifdef SO_NOSIGPIPE
// Different way of disabling SIGPIPE on BSD
setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
#endif
#ifndef WIN32
// Allow binding if the port is still in TIME_WAIT state after
// the program was closed and restarted. Not an issue on windows.
setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
#endif
#ifdef WIN32
// Set to nonblocking, incoming connections will also inherit this
if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR)
#else
if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
#endif
{
strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
#ifdef USE_IPV6
// some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
// and enable it by default or not. Try to enable it, if possible.
if (addrBind.IsIPv6()) {
#ifdef IPV6_V6ONLY
setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
#endif
#ifdef WIN32
int nProtLevel = 10 /* PROTECTION_LEVEL_UNRESTRICTED */;
int nParameterId = 23 /* IPV6_PROTECTION_LEVEl */;
// this call is allowed to fail
setsockopt(hListenSocket, IPPROTO_IPV6, nParameterId, (const char*)&nProtLevel, sizeof(int));
#endif
}
#endif
if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
{
int nErr = WSAGetLastError();
if (nErr == WSAEADDRINUSE)
strError = strprintf(_("Unable to bind to %s on this computer. SnowballCoin is probably already running."), addrBind.ToString().c_str());
else
strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %d, %s)"), addrBind.ToString().c_str(), nErr, strerror(nErr));
printf("%s\n", strError.c_str());
return false;
}
printf("Bound to %s\n", addrBind.ToString().c_str());
// Listen for incoming connections
if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
{
strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError());
printf("%s\n", strError.c_str());
return false;
}
vhListenSocket.push_back(hListenSocket);
if (addrBind.IsRoutable() && fDiscover)
AddLocal(addrBind, LOCAL_BIND);
return true;
}
void static Discover()
{
if (!fDiscover)
return;
#ifdef WIN32
// Get local host ip
char pszHostName[1000] = "";
if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
{
vector<CNetAddr> vaddr;
if (LookupHost(pszHostName, vaddr))
{
BOOST_FOREACH (const CNetAddr &addr, vaddr)
{
AddLocal(addr, LOCAL_IF);
}
}
}
#else
// Get local host ip
struct ifaddrs* myaddrs;
if (getifaddrs(&myaddrs) == 0)
{
for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next)
{
if (ifa->ifa_addr == NULL) continue;
if ((ifa->ifa_flags & IFF_UP) == 0) continue;
if (strcmp(ifa->ifa_name, "lo") == 0) continue;
if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
if (ifa->ifa_addr->sa_family == AF_INET)
{
struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
CNetAddr addr(s4->sin_addr);
if (AddLocal(addr, LOCAL_IF))
printf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
}
#ifdef USE_IPV6
else if (ifa->ifa_addr->sa_family == AF_INET6)
{
struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
CNetAddr addr(s6->sin6_addr);
if (AddLocal(addr, LOCAL_IF))
printf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
}
#endif
}
freeifaddrs(myaddrs);
}
#endif
CreateThread(ThreadGetMyExternalIP, NULL);
}
void StartNode(void* parg)
{
// Make this thread recognisable as the startup thread
RenameThread("bitcoin-start");
if (semOutbound == NULL) {
// initialize semaphore
int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, (int)GetArg("-maxconnections", 125));
semOutbound = new CSemaphore(nMaxOutbound);
}
if (pnodeLocalHost == NULL)
pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices));
Discover();
//
// Start threads
//
if (!GetBoolArg("-dnsseed", true))
printf("DNS seeding disabled\n");
else
if (!CreateThread(ThreadDNSAddressSeed, NULL))
printf("Error: CreateThread(ThreadDNSAddressSeed) failed\n");
// Get addresses from IRC and advertise ours
if (!CreateThread(ThreadIRCSeed, NULL))
printf("Error: CreateThread(ThreadIRCSeed) failed\n");
// Send and receive from sockets, accept connections
if (!CreateThread(ThreadSocketHandler, NULL))
printf("Error: CreateThread(ThreadSocketHandler) failed\n");
// Initiate outbound connections from -addnode
if (!CreateThread(ThreadOpenAddedConnections, NULL))
printf("Error: CreateThread(ThreadOpenAddedConnections) failed\n");
// Initiate outbound connections
if (!CreateThread(ThreadOpenConnections, NULL))
printf("Error: CreateThread(ThreadOpenConnections) failed\n");
// Process messages
if (!CreateThread(ThreadMessageHandler, NULL))
printf("Error: CreateThread(ThreadMessageHandler) failed\n");
// Dump network addresses
if (!CreateThread(ThreadDumpAddress, NULL))
printf("Error; CreateThread(ThreadDumpAddress) failed\n");
// Generate coins in the background
GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain);
}
bool StopNode()
{
printf("StopNode()\n");
fShutdown = true;
nTransactionsUpdated++;
int64 nStart = GetTime();
if (semOutbound)
for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++)
semOutbound->post();
do
{
int nThreadsRunning = 0;
for (int n = 0; n < THREAD_MAX; n++)
nThreadsRunning += vnThreadsRunning[n];
if (nThreadsRunning == 0)
break;
if (GetTime() - nStart > 20)
break;
Sleep(20);
} while(true);
if (vnThreadsRunning[THREAD_SOCKETHANDLER] > 0) printf("ThreadSocketHandler still running\n");
if (vnThreadsRunning[THREAD_OPENCONNECTIONS] > 0) printf("ThreadOpenConnections still running\n");
if (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0) printf("ThreadMessageHandler still running\n");
if (vnThreadsRunning[THREAD_MINER] > 0) printf("ThreadBitcoinMiner still running\n");
if (vnThreadsRunning[THREAD_RPCLISTENER] > 0) printf("ThreadRPCListener still running\n");
if (vnThreadsRunning[THREAD_RPCHANDLER] > 0) printf("ThreadsRPCServer still running\n");
if (vnThreadsRunning[THREAD_DNSSEED] > 0) printf("ThreadDNSAddressSeed still running\n");
if (vnThreadsRunning[THREAD_ADDEDCONNECTIONS] > 0) printf("ThreadOpenAddedConnections still running\n");
if (vnThreadsRunning[THREAD_DUMPADDRESS] > 0) printf("ThreadDumpAddresses still running\n");
while (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0 || vnThreadsRunning[THREAD_RPCHANDLER] > 0)
Sleep(20);
Sleep(50);
DumpAddresses();
return true;
}
class CNetCleanup
{
public:
CNetCleanup()
{
}
~CNetCleanup()
{
// Close sockets
BOOST_FOREACH(CNode* pnode, vNodes)
if (pnode->hSocket != INVALID_SOCKET)
closesocket(pnode->hSocket);
BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
if (hListenSocket != INVALID_SOCKET)
if (closesocket(hListenSocket) == SOCKET_ERROR)
printf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError());
#ifdef WIN32
// Shutdown Windows Sockets
WSACleanup();
#endif
}
}
instance_of_cnetcleanup;
|
#ifndef BOOST_ARCHIVE_DETAIL_ISERIALIZER_HPP
#define BOOST_ARCHIVE_DETAIL_ISERIALIZER_HPP
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#pragma inline_depth(511)
#pragma inline_recursion(on)
#endif
#if defined(__MWERKS__)
#pragma inline_depth(511)
#endif
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// iserializer.hpp: interface for serialization system.
// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com .
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for updates, documentation, and revision history.
#include <new> // for placement new
#include <memory> // for auto_ptr
#include <cstddef> // size_t, NULL
#include <boost/config.hpp>
#include <boost/detail/workaround.hpp>
#if defined(BOOST_NO_STDC_NAMESPACE)
namespace std{
using ::size_t;
} // namespace std
#endif
#include <boost/static_assert.hpp>
#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/identity.hpp>
#include <boost/mpl/greater_equal.hpp>
#include <boost/mpl/equal_to.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/detail/no_exceptions_support.hpp>
#ifndef BOOST_SERIALIZATION_DEFAULT_TYPE_INFO
#include <boost/serialization/extended_type_info_typeid.hpp>
#endif
#include <boost/serialization/throw_exception.hpp>
#include <boost/serialization/smart_cast.hpp>
#include <boost/serialization/static_warning.hpp>
#include <boost/type_traits/is_pointer.hpp>
#include <boost/type_traits/is_enum.hpp>
#include <boost/type_traits/is_const.hpp>
#include <boost/type_traits/remove_const.hpp>
#include <boost/type_traits/remove_extent.hpp>
#include <boost/type_traits/is_polymorphic.hpp>
#include <boost/serialization/assume_abstract.hpp>
#define DONT_USE_HAS_NEW_OPERATOR ( \
defined(__BORLANDC__) \
|| defined(__IBMCPP__) \
|| defined(BOOST_MSVC) && (BOOST_MSVC <= 1300) \
|| defined(__SUNPRO_CC) && (__SUNPRO_CC < 0x590) \
)
#if ! DONT_USE_HAS_NEW_OPERATOR
#include <boost/type_traits/has_new_operator.hpp>
#endif
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/version.hpp>
#include <boost/serialization/level.hpp>
#include <boost/serialization/tracking.hpp>
#include <boost/serialization/type_info_implementation.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/void_cast.hpp>
#include <boost/serialization/array.hpp>
#include <boost/serialization/collection_size_type.hpp>
#include <boost/serialization/singleton.hpp>
#include <boost/serialization/wrapper.hpp>
// the following is need only for dynamic cast of polymorphic pointers
#include <boost/archive/archive_exception.hpp>
#include <boost/archive/detail/basic_iarchive.hpp>
#include <boost/archive/detail/basic_iserializer.hpp>
#include <boost/archive/detail/basic_pointer_iserializer.hpp>
#include <boost/archive/detail/archive_serializer_map.hpp>
#include <boost/archive/detail/check.hpp>
namespace boost {
namespace serialization {
class extended_type_info;
} // namespace serialization
namespace archive {
// an accessor to permit friend access to archives. Needed because
// some compilers don't handle friend templates completely
class load_access {
public:
template<class Archive, class T>
static void load_primitive(Archive &ar, T &t){
ar.load(t);
}
};
namespace detail {
template<class Archive, class T>
class iserializer : public basic_iserializer
{
private:
virtual void destroy(/*const*/ void *address) const {
boost::serialization::access::destroy(static_cast<T *>(address));
}
protected:
// protected constructor since it's always created by singleton
explicit iserializer() :
basic_iserializer(
boost::serialization::singleton<
BOOST_DEDUCED_TYPENAME
boost::serialization::type_info_implementation<T>::type
>::get_const_instance()
)
{}
public:
virtual BOOST_DLLEXPORT void load_object_data(
basic_iarchive & ar,
void *x,
const unsigned int file_version
) const BOOST_USED;
virtual bool class_info() const {
return boost::serialization::implementation_level<T>::value
>= boost::serialization::object_class_info;
}
virtual bool tracking(const unsigned int /* flags */) const {
return boost::serialization::tracking_level<T>::value
== boost::serialization::track_always
|| ( boost::serialization::tracking_level<T>::value
== boost::serialization::track_selectively
&& serialized_as_pointer());
}
virtual unsigned int version() const {
return ::boost::serialization::version<T>::value;
}
virtual bool is_polymorphic() const {
return boost::is_polymorphic<T>::value;
}
virtual ~iserializer(){};
};
template<class Archive, class T>
BOOST_DLLEXPORT void iserializer<Archive, T>::load_object_data(
basic_iarchive & ar,
void *x,
const unsigned int file_version
) const {
// trap case where the program cannot handle the current version
if(file_version > version())
boost::serialization::throw_exception(
archive::archive_exception(
boost::archive::archive_exception::unsupported_class_version,
get_debug_info()
)
);
// make sure call is routed through the higest interface that might
// be specialized by the user.
boost::serialization::serialize_adl(
boost::serialization::smart_cast_reference<Archive &>(ar),
* static_cast<T *>(x),
file_version
);
}
template<class Archive, class T>
class pointer_iserializer :
public basic_pointer_iserializer
{
private:
virtual const basic_iserializer & get_basic_serializer() const {
return boost::serialization::singleton<
iserializer<Archive, T>
>::get_const_instance();
}
BOOST_DLLEXPORT virtual void load_object_ptr(
basic_iarchive & ar,
void * & x,
const unsigned int file_version
) const BOOST_USED;
protected:
// this should alway be a singleton so make the constructor protected
pointer_iserializer();
~pointer_iserializer();
};
// note trick to be sure that operator new is using class specific
// version if such exists. Due to Peter Dimov.
// note: the following fails if T has no default constructor.
// otherwise it would have been ideal
//struct heap_allocator : public T
//{
// T * invoke(){
// return ::new(sizeof(T));
// }
//}
template<class T>
struct heap_allocator
{
// boost::has_new_operator<T> doesn't work on these compilers
#if DONT_USE_HAS_NEW_OPERATOR
// This doesn't handle operator new overload for class T
static T * invoke(){
return static_cast<T *>(operator new(sizeof(T)));
}
#else
struct has_new_operator {
static T* invoke() {
return static_cast<T *>((T::operator new)(sizeof(T)));
}
};
struct doesnt_have_new_operator {
static T* invoke() {
return static_cast<T *>(operator new(sizeof(T)));
}
};
static T * invoke() {
typedef BOOST_DEDUCED_TYPENAME
mpl::eval_if<
boost::has_new_operator<T>,
mpl::identity<has_new_operator >,
mpl::identity<doesnt_have_new_operator >
>::type typex;
return typex::invoke();
}
#endif
};
// due to Martin Ecker
template <typename T>
class auto_ptr_with_deleter
{
public:
explicit auto_ptr_with_deleter(T* p) :
m_p(p)
{}
~auto_ptr_with_deleter(){
if (m_p)
boost::serialization::access::destroy(m_p);
}
T* get() const {
return m_p;
}
T* release() {
T* p = m_p;
m_p = NULL;
return p;
}
private:
T* m_p;
};
// note: BOOST_DLLEXPORT is so that code for polymorphic class
// serialized only through base class won't get optimized out
template<class Archive, class T>
BOOST_DLLEXPORT void pointer_iserializer<Archive, T>::load_object_ptr(
basic_iarchive & ar,
void * & x,
const unsigned int file_version
) const
{
Archive & ar_impl =
boost::serialization::smart_cast_reference<Archive &>(ar);
auto_ptr_with_deleter<T> ap(heap_allocator<T>::invoke());
if(NULL == ap.get())
boost::serialization::throw_exception(std::bad_alloc()) ;
T * t = ap.get();
x = t;
// catch exception during load_construct_data so that we don't
// automatically delete the t which is most likely not fully
// constructed
BOOST_TRY {
// this addresses an obscure situtation that occurs when
// load_constructor de-serializes something through a pointer.
ar.next_object_pointer(t);
boost::serialization::load_construct_data_adl<Archive, T>(
ar_impl,
t,
file_version
);
}
BOOST_CATCH(...){
ap.release();
BOOST_RETHROW;
}
BOOST_CATCH_END
ar_impl >> boost::serialization::make_nvp(NULL, * t);
ap.release();
}
template<class Archive, class T>
pointer_iserializer<Archive, T>::pointer_iserializer() :
basic_pointer_iserializer(
boost::serialization::singleton<
BOOST_DEDUCED_TYPENAME
boost::serialization::type_info_implementation<T>::type
>::get_const_instance()
)
{
boost::serialization::singleton<
iserializer<Archive, T>
>::get_mutable_instance().set_bpis(this);
archive_serializer_map<Archive>::insert(this);
}
template<class Archive, class T>
pointer_iserializer<Archive, T>::~pointer_iserializer(){
archive_serializer_map<Archive>::erase(this);
}
template<class Archive>
struct load_non_pointer_type {
// note this bounces the call right back to the archive
// with no runtime overhead
struct load_primitive {
template<class T>
static void invoke(Archive & ar, T & t){
load_access::load_primitive(ar, t);
}
};
// note this bounces the call right back to the archive
// with no runtime overhead
struct load_only {
template<class T>
static void invoke(Archive & ar, const T & t){
// short cut to user's serializer
// make sure call is routed through the higest interface that might
// be specialized by the user.
boost::serialization::serialize_adl(
ar,
const_cast<T &>(t),
boost::serialization::version<T>::value
);
}
};
// note this save class information including version
// and serialization level to the archive
struct load_standard {
template<class T>
static void invoke(Archive &ar, const T & t){
void * x = & const_cast<T &>(t);
ar.load_object(
x,
boost::serialization::singleton<
iserializer<Archive, T>
>::get_const_instance()
);
}
};
struct load_conditional {
template<class T>
static void invoke(Archive &ar, T &t){
//if(0 == (ar.get_flags() & no_tracking))
load_standard::invoke(ar, t);
//else
// load_only::invoke(ar, t);
}
};
template<class T>
static void invoke(Archive & ar, T &t){
typedef BOOST_DEDUCED_TYPENAME mpl::eval_if<
// if its primitive
mpl::equal_to<
boost::serialization::implementation_level<T>,
mpl::int_<boost::serialization::primitive_type>
>,
mpl::identity<load_primitive>,
// else
BOOST_DEDUCED_TYPENAME mpl::eval_if<
// class info / version
mpl::greater_equal<
boost::serialization::implementation_level<T>,
mpl::int_<boost::serialization::object_class_info>
>,
// do standard load
mpl::identity<load_standard>,
// else
BOOST_DEDUCED_TYPENAME mpl::eval_if<
// no tracking
mpl::equal_to<
boost::serialization::tracking_level<T>,
mpl::int_<boost::serialization::track_never>
>,
// do a fast load
mpl::identity<load_only>,
// else
// do a fast load only tracking is turned off
mpl::identity<load_conditional>
> > >::type typex;
check_object_versioning<T>();
check_object_level<T>();
typex::invoke(ar, t);
}
};
template<class Archive>
struct load_pointer_type {
struct abstract
{
template<class T>
static const basic_pointer_iserializer * register_type(Archive & /* ar */){
// it has? to be polymorphic
BOOST_STATIC_ASSERT(boost::is_polymorphic<T>::value);
return static_cast<basic_pointer_iserializer *>(NULL);
}
};
struct non_abstract
{
template<class T>
static const basic_pointer_iserializer * register_type(Archive & ar){
return ar.register_type(static_cast<T *>(NULL));
}
};
template<class T>
static const basic_pointer_iserializer * register_type(Archive &ar, T & /*t*/){
// there should never be any need to load an abstract polymorphic
// class pointer. Inhibiting code generation for this
// permits abstract base classes to be used - note: exception
// virtual serialize functions used for plug-ins
typedef BOOST_DEDUCED_TYPENAME
mpl::eval_if<
boost::serialization::is_abstract<const T>,
boost::mpl::identity<abstract>,
boost::mpl::identity<non_abstract>
>::type typex;
return typex::template register_type<T>(ar);
}
template<class T>
static T * pointer_tweak(
const boost::serialization::extended_type_info & eti,
void * t,
T &
) {
// tweak the pointer back to the base class
return static_cast<T *>(
boost::serialization::void_upcast(
eti,
boost::serialization::singleton<
BOOST_DEDUCED_TYPENAME
boost::serialization::type_info_implementation<T>::type
>::get_const_instance(),
t
)
);
}
template<class T>
static void load(Archive &ar, T & t){
check_pointer_level<T>();
check_pointer_tracking<T>();
}
template<class Tptr>
static void invoke(Archive & ar, Tptr & t){
load(ar, *t);
const basic_pointer_iserializer * bpis_ptr = register_type(ar, *t);
const basic_pointer_iserializer * newbpis_ptr = ar.load_pointer(
* reinterpret_cast<void **>(&t),
bpis_ptr
);
// if the pointer isn't that of the base class
if(newbpis_ptr != bpis_ptr){
t = pointer_tweak(newbpis_ptr->get_eti(), t, *t);
}
}
};
template<class Archive>
struct load_enum_type {
template<class T>
static void invoke(Archive &ar, T &t){
// convert integers to correct enum to load
int i;
ar >> boost::serialization::make_nvp(NULL, i);
t = static_cast<T>(i);
}
};
template<class Archive>
struct load_array_type {
template<class T>
static void invoke(Archive &ar, T &t){
typedef BOOST_DEDUCED_TYPENAME remove_extent<T>::type value_type;
// convert integers to correct enum to load
// determine number of elements in the array. Consider the
// fact that some machines will align elements on boundries
// other than characters.
std::size_t current_count = sizeof(t) / (
static_cast<char *>(static_cast<void *>(&t[1]))
- static_cast<char *>(static_cast<void *>(&t[0]))
);
boost::serialization::collection_size_type count;
ar >> BOOST_SERIALIZATION_NVP(count);
if(static_cast<std::size_t>(count) > current_count)
boost::serialization::throw_exception(
archive::archive_exception(
boost::archive::archive_exception::array_size_too_short
)
);
ar >> serialization::make_array(static_cast<value_type*>(&t[0]),count);
}
};
} // detail
template<class Archive, class T>
inline void load(Archive & ar, T &t){
// if this assertion trips. It means we're trying to load a
// const object with a compiler that doesn't have correct
// funtion template ordering. On other compilers, this is
// handled below.
detail::check_const_loading<T>();
typedef
BOOST_DEDUCED_TYPENAME mpl::eval_if<is_pointer<T>,
mpl::identity<detail::load_pointer_type<Archive> >
,//else
BOOST_DEDUCED_TYPENAME mpl::eval_if<is_array<T>,
mpl::identity<detail::load_array_type<Archive> >
,//else
BOOST_DEDUCED_TYPENAME mpl::eval_if<is_enum<T>,
mpl::identity<detail::load_enum_type<Archive> >
,//else
mpl::identity<detail::load_non_pointer_type<Archive> >
>
>
>::type typex;
typex::invoke(ar, t);
}
#if 0
// BORLAND
#if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x560))
// borland has a couple of problems
// a) if function is partially specialized - see below
// const paramters are transformed to non-const ones
// b) implementation of base_object can't be made to work
// correctly which results in all base_object s being const.
// So, strip off the const for borland. This breaks the trap
// for loading const objects - but I see no alternative
template<class Archive, class T>
inline void load(Archive &ar, const T & t){
load(ar, const_cast<T &>(t));
}
#endif
// let wrappers through.
#ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING
template<class Archive, class T>
inline void load_wrapper(Archive &ar, const T&t, mpl::true_){
boost::archive::load(ar, const_cast<T&>(t));
}
#if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x560))
template<class Archive, class T>
inline void load(Archive &ar, const T&t){
load_wrapper(ar,t,serialization::is_wrapper<T>());
}
#endif
#endif
#endif
} // namespace archive
} // namespace boost
#endif // BOOST_ARCHIVE_DETAIL_ISERIALIZER_HPP
|
// This file has been generated by Py++.
#include "boost/python.hpp"
#include "wrap_osg.h"
#include "wrap_referenced.h"
#include "geode.pypp.hpp"
namespace bp = boost::python;
struct Geode_wrapper : osg::Geode, bp::wrapper< osg::Geode > {
Geode_wrapper( )
: osg::Geode( )
, bp::wrapper< osg::Geode >(){
// null constructor
}
virtual void accept( ::osg::NodeVisitor & nv ) {
if( bp::override func_accept = this->get_override( "accept" ) )
func_accept( boost::ref(nv) );
else{
this->osg::Geode::accept( boost::ref(nv) );
}
}
void default_accept( ::osg::NodeVisitor & nv ) {
osg::Geode::accept( boost::ref(nv) );
}
virtual bool addDrawable( ::osg::Drawable * drawable ) {
if( bp::override func_addDrawable = this->get_override( "addDrawable" ) )
return func_addDrawable( boost::python::ptr(drawable) );
else{
return this->osg::Geode::addDrawable( boost::python::ptr(drawable) );
}
}
bool default_addDrawable( ::osg::Drawable * drawable ) {
return osg::Geode::addDrawable( boost::python::ptr(drawable) );
}
virtual ::osg::Geode * asGeode( ) {
if( bp::override func_asGeode = this->get_override( "asGeode" ) )
return func_asGeode( );
else{
return this->osg::Geode::asGeode( );
}
}
::osg::Geode * default_asGeode( ) {
return osg::Geode::asGeode( );
}
virtual ::osg::Geode const * asGeode( ) const {
if( bp::override func_asGeode = this->get_override( "asGeode" ) )
return func_asGeode( );
else{
return this->osg::Geode::asGeode( );
}
}
::osg::Geode const * default_asGeode( ) const {
return osg::Geode::asGeode( );
}
virtual char const * className( ) const {
if( bp::override func_className = this->get_override( "className" ) )
return func_className( );
else{
return this->osg::Geode::className( );
}
}
char const * default_className( ) const {
return osg::Geode::className( );
}
virtual ::osg::Object * clone( ::osg::CopyOp const & copyop ) const {
if( bp::override func_clone = this->get_override( "clone" ) )
return func_clone( boost::ref(copyop) );
else{
return this->osg::Geode::clone( boost::ref(copyop) );
}
}
::osg::Object * default_clone( ::osg::CopyOp const & copyop ) const {
return osg::Geode::clone( boost::ref(copyop) );
}
virtual ::osg::Object * cloneType( ) const {
if( bp::override func_cloneType = this->get_override( "cloneType" ) )
return func_cloneType( );
else{
return this->osg::Geode::cloneType( );
}
}
::osg::Object * default_cloneType( ) const {
return osg::Geode::cloneType( );
}
virtual ::osg::BoundingSphere computeBound( ) const {
if( bp::override func_computeBound = this->get_override( "computeBound" ) )
return func_computeBound( );
else{
return this->osg::Geode::computeBound( );
}
}
::osg::BoundingSphere default_computeBound( ) const {
return osg::Geode::computeBound( );
}
virtual bool isSameKindAs( ::osg::Object const * obj ) const {
if( bp::override func_isSameKindAs = this->get_override( "isSameKindAs" ) )
return func_isSameKindAs( boost::python::ptr(obj) );
else{
return this->osg::Geode::isSameKindAs( boost::python::ptr(obj) );
}
}
bool default_isSameKindAs( ::osg::Object const * obj ) const {
return osg::Geode::isSameKindAs( boost::python::ptr(obj) );
}
virtual char const * libraryName( ) const {
if( bp::override func_libraryName = this->get_override( "libraryName" ) )
return func_libraryName( );
else{
return this->osg::Geode::libraryName( );
}
}
char const * default_libraryName( ) const {
return osg::Geode::libraryName( );
}
virtual bool removeDrawable( ::osg::Drawable * drawable ) {
if( bp::override func_removeDrawable = this->get_override( "removeDrawable" ) )
return func_removeDrawable( boost::python::ptr(drawable) );
else{
return this->osg::Geode::removeDrawable( boost::python::ptr(drawable) );
}
}
bool default_removeDrawable( ::osg::Drawable * drawable ) {
return osg::Geode::removeDrawable( boost::python::ptr(drawable) );
}
virtual bool removeDrawables( unsigned int i, unsigned int numDrawablesToRemove=1 ) {
if( bp::override func_removeDrawables = this->get_override( "removeDrawables" ) )
return func_removeDrawables( i, numDrawablesToRemove );
else{
return this->osg::Geode::removeDrawables( i, numDrawablesToRemove );
}
}
bool default_removeDrawables( unsigned int i, unsigned int numDrawablesToRemove=1 ) {
return osg::Geode::removeDrawables( i, numDrawablesToRemove );
}
virtual bool replaceDrawable( ::osg::Drawable * origDraw, ::osg::Drawable * newDraw ) {
if( bp::override func_replaceDrawable = this->get_override( "replaceDrawable" ) )
return func_replaceDrawable( boost::python::ptr(origDraw), boost::python::ptr(newDraw) );
else{
return this->osg::Geode::replaceDrawable( boost::python::ptr(origDraw), boost::python::ptr(newDraw) );
}
}
bool default_replaceDrawable( ::osg::Drawable * origDraw, ::osg::Drawable * newDraw ) {
return osg::Geode::replaceDrawable( boost::python::ptr(origDraw), boost::python::ptr(newDraw) );
}
virtual void resizeGLObjectBuffers( unsigned int maxSize ) {
if( bp::override func_resizeGLObjectBuffers = this->get_override( "resizeGLObjectBuffers" ) )
func_resizeGLObjectBuffers( maxSize );
else{
this->osg::Geode::resizeGLObjectBuffers( maxSize );
}
}
void default_resizeGLObjectBuffers( unsigned int maxSize ) {
osg::Geode::resizeGLObjectBuffers( maxSize );
}
virtual bool setDrawable( unsigned int i, ::osg::Drawable * drawable ) {
if( bp::override func_setDrawable = this->get_override( "setDrawable" ) )
return func_setDrawable( i, boost::python::ptr(drawable) );
else{
return this->osg::Geode::setDrawable( i, boost::python::ptr(drawable) );
}
}
bool default_setDrawable( unsigned int i, ::osg::Drawable * drawable ) {
return osg::Geode::setDrawable( i, boost::python::ptr(drawable) );
}
virtual void setThreadSafeRefUnref( bool threadSafe ) {
if( bp::override func_setThreadSafeRefUnref = this->get_override( "setThreadSafeRefUnref" ) )
func_setThreadSafeRefUnref( threadSafe );
else{
this->osg::Geode::setThreadSafeRefUnref( threadSafe );
}
}
void default_setThreadSafeRefUnref( bool threadSafe ) {
osg::Geode::setThreadSafeRefUnref( threadSafe );
}
virtual ::osg::Camera * asCamera( ) {
if( bp::override func_asCamera = this->get_override( "asCamera" ) )
return func_asCamera( );
else{
return this->osg::Node::asCamera( );
}
}
::osg::Camera * default_asCamera( ) {
return osg::Node::asCamera( );
}
virtual ::osg::Camera const * asCamera( ) const {
if( bp::override func_asCamera = this->get_override( "asCamera" ) )
return func_asCamera( );
else{
return this->osg::Node::asCamera( );
}
}
::osg::Camera const * default_asCamera( ) const {
return osg::Node::asCamera( );
}
virtual ::osg::Group * asGroup( ) {
if( bp::override func_asGroup = this->get_override( "asGroup" ) )
return func_asGroup( );
else{
return this->osg::Node::asGroup( );
}
}
::osg::Group * default_asGroup( ) {
return osg::Node::asGroup( );
}
virtual ::osg::Group const * asGroup( ) const {
if( bp::override func_asGroup = this->get_override( "asGroup" ) )
return func_asGroup( );
else{
return this->osg::Node::asGroup( );
}
}
::osg::Group const * default_asGroup( ) const {
return osg::Node::asGroup( );
}
virtual ::osg::Switch * asSwitch( ) {
if( bp::override func_asSwitch = this->get_override( "asSwitch" ) )
return func_asSwitch( );
else{
return this->osg::Node::asSwitch( );
}
}
::osg::Switch * default_asSwitch( ) {
return osg::Node::asSwitch( );
}
virtual ::osg::Switch const * asSwitch( ) const {
if( bp::override func_asSwitch = this->get_override( "asSwitch" ) )
return func_asSwitch( );
else{
return this->osg::Node::asSwitch( );
}
}
::osg::Switch const * default_asSwitch( ) const {
return osg::Node::asSwitch( );
}
virtual ::osg::Transform * asTransform( ) {
if( bp::override func_asTransform = this->get_override( "asTransform" ) )
return func_asTransform( );
else{
return this->osg::Node::asTransform( );
}
}
::osg::Transform * default_asTransform( ) {
return osg::Node::asTransform( );
}
virtual ::osg::Transform const * asTransform( ) const {
if( bp::override func_asTransform = this->get_override( "asTransform" ) )
return func_asTransform( );
else{
return this->osg::Node::asTransform( );
}
}
::osg::Transform const * default_asTransform( ) const {
return osg::Node::asTransform( );
}
virtual void ascend( ::osg::NodeVisitor & nv ) {
if( bp::override func_ascend = this->get_override( "ascend" ) )
func_ascend( boost::ref(nv) );
else{
this->osg::Node::ascend( boost::ref(nv) );
}
}
void default_ascend( ::osg::NodeVisitor & nv ) {
osg::Node::ascend( boost::ref(nv) );
}
virtual void computeDataVariance( ) {
if( bp::override func_computeDataVariance = this->get_override( "computeDataVariance" ) )
func_computeDataVariance( );
else{
this->osg::Object::computeDataVariance( );
}
}
void default_computeDataVariance( ) {
osg::Object::computeDataVariance( );
}
virtual ::osg::Referenced * getUserData( ) {
if( bp::override func_getUserData = this->get_override( "getUserData" ) )
return func_getUserData( );
else{
return this->osg::Object::getUserData( );
}
}
::osg::Referenced * default_getUserData( ) {
return osg::Object::getUserData( );
}
virtual ::osg::Referenced const * getUserData( ) const {
if( bp::override func_getUserData = this->get_override( "getUserData" ) )
return func_getUserData( );
else{
return this->osg::Object::getUserData( );
}
}
::osg::Referenced const * default_getUserData( ) const {
return osg::Object::getUserData( );
}
virtual void setName( ::std::string const & name ) {
if( bp::override func_setName = this->get_override( "setName" ) )
func_setName( name );
else{
this->osg::Object::setName( name );
}
}
void default_setName( ::std::string const & name ) {
osg::Object::setName( name );
}
virtual void setUserData( ::osg::Referenced * obj ) {
if( bp::override func_setUserData = this->get_override( "setUserData" ) )
func_setUserData( boost::python::ptr(obj) );
else{
this->osg::Object::setUserData( boost::python::ptr(obj) );
}
}
void default_setUserData( ::osg::Referenced * obj ) {
osg::Object::setUserData( boost::python::ptr(obj) );
}
virtual void traverse( ::osg::NodeVisitor & arg0 ) {
if( bp::override func_traverse = this->get_override( "traverse" ) )
func_traverse( boost::ref(arg0) );
else{
this->osg::Node::traverse( boost::ref(arg0) );
}
}
void default_traverse( ::osg::NodeVisitor & arg0 ) {
osg::Node::traverse( boost::ref(arg0) );
}
};
void register_Geode_class(){
bp::class_< Geode_wrapper, bp::bases< osg::Node >, osg::ref_ptr< ::osg::Geode >, boost::noncopyable >( "Geode", "\n A Geode is a geometry node, that is, a leaf node on the scene graph\n that can have renderable things attached to it. In OSG, renderable things\n are represented by objects from the Drawable class, so a Geode is a\n Node whose purpose is grouping <tt>Drawable</tt>s.\n", bp::no_init )
.def( bp::init< >() )
.def(
"accept"
, (void ( ::osg::Geode::* )( ::osg::NodeVisitor & ))(&::osg::Geode::accept)
, (void ( Geode_wrapper::* )( ::osg::NodeVisitor & ))(&Geode_wrapper::default_accept)
, ( bp::arg("nv") ) )
.def(
"addDrawable"
, (bool ( ::osg::Geode::* )( ::osg::Drawable * ))(&::osg::Geode::addDrawable)
, (bool ( Geode_wrapper::* )( ::osg::Drawable * ))(&Geode_wrapper::default_addDrawable)
, ( bp::arg("drawable") ) )
.def(
"asGeode"
, (::osg::Geode * ( ::osg::Geode::* )( ))(&::osg::Geode::asGeode)
, (::osg::Geode * ( Geode_wrapper::* )( ))(&Geode_wrapper::default_asGeode)
, bp::return_internal_reference< >() )
.def(
"asGeode"
, (::osg::Geode const * ( ::osg::Geode::* )( )const)(&::osg::Geode::asGeode)
, (::osg::Geode const * ( Geode_wrapper::* )( )const)(&Geode_wrapper::default_asGeode)
, bp::return_internal_reference< >() )
.def(
"className"
, (char const * ( ::osg::Geode::* )( )const)(&::osg::Geode::className)
, (char const * ( Geode_wrapper::* )( )const)(&Geode_wrapper::default_className) )
.def(
"clone"
, (::osg::Object * ( ::osg::Geode::* )( ::osg::CopyOp const & )const)(&::osg::Geode::clone)
, (::osg::Object * ( Geode_wrapper::* )( ::osg::CopyOp const & )const)(&Geode_wrapper::default_clone)
, ( bp::arg("copyop") )
, bp::return_value_policy< bp::reference_existing_object >() )
.def(
"cloneType"
, (::osg::Object * ( ::osg::Geode::* )( )const)(&::osg::Geode::cloneType)
, (::osg::Object * ( Geode_wrapper::* )( )const)(&Geode_wrapper::default_cloneType)
, bp::return_value_policy< bp::reference_existing_object >() )
.def(
"compileDrawables"
, (void ( ::osg::Geode::* )( ::osg::RenderInfo & ))( &::osg::Geode::compileDrawables )
, ( bp::arg("renderInfo") )
, " Compile OpenGL Display List for each drawable." )
.def(
"computeBound"
, (::osg::BoundingSphere ( ::osg::Geode::* )( )const)(&::osg::Geode::computeBound)
, (::osg::BoundingSphere ( Geode_wrapper::* )( )const)(&Geode_wrapper::default_computeBound) )
.def(
"containsDrawable"
, (bool ( ::osg::Geode::* )( ::osg::Drawable const * )const)( &::osg::Geode::containsDrawable )
, ( bp::arg("gset") )
, " Return true if a given Drawable is contained within Geode." )
.def(
"getBoundingBox"
, (::osg::BoundingBox const & ( ::osg::Geode::* )( )const)( &::osg::Geode::getBoundingBox )
, bp::return_internal_reference< >()
, " Return the Geodes bounding box, which is the union of all the\n bounding boxes of the geodes drawables." )
.def(
"getDrawable"
, (::osg::Drawable * ( ::osg::Geode::* )( unsigned int ))( &::osg::Geode::getDrawable )
, ( bp::arg("i") )
, bp::return_internal_reference< >()
, " Return the Drawable at position i." )
.def(
"getDrawable"
, (::osg::Drawable const * ( ::osg::Geode::* )( unsigned int )const)( &::osg::Geode::getDrawable )
, ( bp::arg("i") )
, bp::return_internal_reference< >()
, " Return the Drawable at position i." )
.def(
"getDrawableIndex"
, (unsigned int ( ::osg::Geode::* )( ::osg::Drawable const * )const)( &::osg::Geode::getDrawableIndex )
, ( bp::arg("drawable") )
, " Get the index number of drawable.\n Return: A value between 0 and <tt>getNumDrawables()-1</tt> if\n drawable is found; if not found, then\n <tt>getNumDrawables()</tt> is returned." )
.def(
"getDrawableList"
, (::std::vector< osg::ref_ptr<osg::Drawable> > const & ( ::osg::Geode::* )( )const)( &::osg::Geode::getDrawableList )
, bp::return_internal_reference< >()
, " Get the list of drawables." )
.def(
"getNumDrawables"
, (unsigned int ( ::osg::Geode::* )( )const)( &::osg::Geode::getNumDrawables )
, " Return the number of <tt>Drawable</tt>s currently attached to the\n Geode." )
.def(
"isSameKindAs"
, (bool ( ::osg::Geode::* )( ::osg::Object const * )const)(&::osg::Geode::isSameKindAs)
, (bool ( Geode_wrapper::* )( ::osg::Object const * )const)(&Geode_wrapper::default_isSameKindAs)
, ( bp::arg("obj") ) )
.def(
"libraryName"
, (char const * ( ::osg::Geode::* )( )const)(&::osg::Geode::libraryName)
, (char const * ( Geode_wrapper::* )( )const)(&Geode_wrapper::default_libraryName) )
.def(
"removeDrawable"
, (bool ( ::osg::Geode::* )( ::osg::Drawable * ))(&::osg::Geode::removeDrawable)
, (bool ( Geode_wrapper::* )( ::osg::Drawable * ))(&Geode_wrapper::default_removeDrawable)
, ( bp::arg("drawable") ) )
.def(
"removeDrawables"
, (bool ( ::osg::Geode::* )( unsigned int,unsigned int ))(&::osg::Geode::removeDrawables)
, (bool ( Geode_wrapper::* )( unsigned int,unsigned int ))(&Geode_wrapper::default_removeDrawables)
, ( bp::arg("i"), bp::arg("numDrawablesToRemove")=(unsigned int)(1) ) )
.def(
"replaceDrawable"
, (bool ( ::osg::Geode::* )( ::osg::Drawable *,::osg::Drawable * ))(&::osg::Geode::replaceDrawable)
, (bool ( Geode_wrapper::* )( ::osg::Drawable *,::osg::Drawable * ))(&Geode_wrapper::default_replaceDrawable)
, ( bp::arg("origDraw"), bp::arg("newDraw") ) )
.def(
"resizeGLObjectBuffers"
, (void ( ::osg::Geode::* )( unsigned int ))(&::osg::Geode::resizeGLObjectBuffers)
, (void ( Geode_wrapper::* )( unsigned int ))(&Geode_wrapper::default_resizeGLObjectBuffers)
, ( bp::arg("maxSize") ) )
.def(
"setDrawable"
, (bool ( ::osg::Geode::* )( unsigned int,::osg::Drawable * ))(&::osg::Geode::setDrawable)
, (bool ( Geode_wrapper::* )( unsigned int,::osg::Drawable * ))(&Geode_wrapper::default_setDrawable)
, ( bp::arg("i"), bp::arg("drawable") ) )
.def(
"setThreadSafeRefUnref"
, (void ( ::osg::Geode::* )( bool ))(&::osg::Geode::setThreadSafeRefUnref)
, (void ( Geode_wrapper::* )( bool ))(&Geode_wrapper::default_setThreadSafeRefUnref)
, ( bp::arg("threadSafe") ) )
.def(
"asCamera"
, (::osg::Camera * ( ::osg::Node::* )( ))(&::osg::Node::asCamera)
, (::osg::Camera * ( Geode_wrapper::* )( ))(&Geode_wrapper::default_asCamera)
, bp::return_internal_reference< >() )
.def(
"asCamera"
, (::osg::Camera const * ( ::osg::Node::* )( )const)(&::osg::Node::asCamera)
, (::osg::Camera const * ( Geode_wrapper::* )( )const)(&Geode_wrapper::default_asCamera)
, bp::return_internal_reference< >() )
.def(
"asGroup"
, (::osg::Group * ( ::osg::Node::* )( ))(&::osg::Node::asGroup)
, (::osg::Group * ( Geode_wrapper::* )( ))(&Geode_wrapper::default_asGroup)
, bp::return_internal_reference< >() )
.def(
"asGroup"
, (::osg::Group const * ( ::osg::Node::* )( )const)(&::osg::Node::asGroup)
, (::osg::Group const * ( Geode_wrapper::* )( )const)(&Geode_wrapper::default_asGroup)
, bp::return_internal_reference< >() )
.def(
"asSwitch"
, (::osg::Switch * ( ::osg::Node::* )( ))(&::osg::Node::asSwitch)
, (::osg::Switch * ( Geode_wrapper::* )( ))(&Geode_wrapper::default_asSwitch)
, bp::return_internal_reference< >() )
.def(
"asSwitch"
, (::osg::Switch const * ( ::osg::Node::* )( )const)(&::osg::Node::asSwitch)
, (::osg::Switch const * ( Geode_wrapper::* )( )const)(&Geode_wrapper::default_asSwitch)
, bp::return_internal_reference< >() )
.def(
"asTransform"
, (::osg::Transform * ( ::osg::Node::* )( ))(&::osg::Node::asTransform)
, (::osg::Transform * ( Geode_wrapper::* )( ))(&Geode_wrapper::default_asTransform)
, bp::return_internal_reference< >() )
.def(
"asTransform"
, (::osg::Transform const * ( ::osg::Node::* )( )const)(&::osg::Node::asTransform)
, (::osg::Transform const * ( Geode_wrapper::* )( )const)(&Geode_wrapper::default_asTransform)
, bp::return_internal_reference< >() )
.def(
"ascend"
, (void ( ::osg::Node::* )( ::osg::NodeVisitor & ))(&::osg::Node::ascend)
, (void ( Geode_wrapper::* )( ::osg::NodeVisitor & ))(&Geode_wrapper::default_ascend)
, ( bp::arg("nv") ) )
.def(
"computeDataVariance"
, (void ( ::osg::Object::* )( ))(&::osg::Object::computeDataVariance)
, (void ( Geode_wrapper::* )( ))(&Geode_wrapper::default_computeDataVariance) )
.def(
"getUserData"
, (::osg::Referenced * ( ::osg::Object::* )( ))(&::osg::Object::getUserData)
, (::osg::Referenced * ( Geode_wrapper::* )( ))(&Geode_wrapper::default_getUserData)
, bp::return_internal_reference< >() )
.def(
"getUserData"
, (::osg::Referenced const * ( ::osg::Object::* )( )const)(&::osg::Object::getUserData)
, (::osg::Referenced const * ( Geode_wrapper::* )( )const)(&Geode_wrapper::default_getUserData)
, bp::return_internal_reference< >() )
.def(
"setName"
, (void ( ::osg::Object::* )( ::std::string const & ))(&::osg::Object::setName)
, (void ( Geode_wrapper::* )( ::std::string const & ))(&Geode_wrapper::default_setName)
, ( bp::arg("name") ) )
.def(
"setName"
, (void ( ::osg::Object::* )( char const * ))( &::osg::Object::setName )
, ( bp::arg("name") )
, " Set the name of object using a C style string." )
.def(
"setUserData"
, (void ( ::osg::Object::* )( ::osg::Referenced * ))(&::osg::Object::setUserData)
, (void ( Geode_wrapper::* )( ::osg::Referenced * ))(&Geode_wrapper::default_setUserData)
, ( bp::arg("obj") ) )
.def(
"traverse"
, (void ( ::osg::Node::* )( ::osg::NodeVisitor & ))(&::osg::Node::traverse)
, (void ( Geode_wrapper::* )( ::osg::NodeVisitor & ))(&Geode_wrapper::default_traverse)
, ( bp::arg("arg0") ) );
}
|
/*
* This file is part of the WebKit open source project.
*
* 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 "WebKitDOMHTMLDocument.h"
#include <WebCore/CSSImportRule.h>
#include "DOMObjectCache.h"
#include <WebCore/DOMException.h>
#include <WebCore/Document.h>
#include "GObjectEventListener.h"
#include <WebCore/JSMainThreadExecState.h>
#include "WebKitDOMEventPrivate.h"
#include "WebKitDOMEventTarget.h"
#include "WebKitDOMHTMLDocumentPrivate.h"
#include "WebKitDOMNodePrivate.h"
#include "WebKitDOMPrivate.h"
#include "ConvertToUTF8String.h"
#include <wtf/GetPtr.h>
#include <wtf/RefPtr.h>
G_GNUC_BEGIN_IGNORE_DEPRECATIONS;
namespace WebKit {
WebKitDOMHTMLDocument* kit(WebCore::HTMLDocument* obj)
{
return WEBKIT_DOM_HTML_DOCUMENT(kit(static_cast<WebCore::Node*>(obj)));
}
WebCore::HTMLDocument* core(WebKitDOMHTMLDocument* request)
{
return request ? static_cast<WebCore::HTMLDocument*>(WEBKIT_DOM_OBJECT(request)->coreObject) : 0;
}
WebKitDOMHTMLDocument* wrapHTMLDocument(WebCore::HTMLDocument* coreObject)
{
ASSERT(coreObject);
return WEBKIT_DOM_HTML_DOCUMENT(g_object_new(WEBKIT_DOM_TYPE_HTML_DOCUMENT, "core-object", coreObject, nullptr));
}
} // namespace WebKit
static gboolean webkit_dom_html_document_dispatch_event(WebKitDOMEventTarget* target, WebKitDOMEvent* event, GError** error)
{
WebCore::Event* coreEvent = WebKit::core(event);
if (!coreEvent)
return false;
WebCore::HTMLDocument* coreTarget = static_cast<WebCore::HTMLDocument*>(WEBKIT_DOM_OBJECT(target)->coreObject);
auto result = coreTarget->dispatchEventForBindings(*coreEvent);
if (result.hasException()) {
auto description = WebCore::DOMException::description(result.releaseException().code());
g_set_error_literal(error, g_quark_from_string("WEBKIT_DOM"), description.legacyCode, description.name);
return false;
}
return result.releaseReturnValue();
}
static gboolean webkit_dom_html_document_add_event_listener(WebKitDOMEventTarget* target, const char* eventName, GClosure* handler, gboolean useCapture)
{
WebCore::HTMLDocument* coreTarget = static_cast<WebCore::HTMLDocument*>(WEBKIT_DOM_OBJECT(target)->coreObject);
return WebKit::GObjectEventListener::addEventListener(G_OBJECT(target), coreTarget, eventName, handler, useCapture);
}
static gboolean webkit_dom_html_document_remove_event_listener(WebKitDOMEventTarget* target, const char* eventName, GClosure* handler, gboolean useCapture)
{
WebCore::HTMLDocument* coreTarget = static_cast<WebCore::HTMLDocument*>(WEBKIT_DOM_OBJECT(target)->coreObject);
return WebKit::GObjectEventListener::removeEventListener(G_OBJECT(target), coreTarget, eventName, handler, useCapture);
}
static void webkit_dom_html_document_dom_event_target_init(WebKitDOMEventTargetIface* iface)
{
iface->dispatch_event = webkit_dom_html_document_dispatch_event;
iface->add_event_listener = webkit_dom_html_document_add_event_listener;
iface->remove_event_listener = webkit_dom_html_document_remove_event_listener;
}
G_DEFINE_TYPE_WITH_CODE(WebKitDOMHTMLDocument, webkit_dom_html_document, WEBKIT_DOM_TYPE_DOCUMENT, G_IMPLEMENT_INTERFACE(WEBKIT_DOM_TYPE_EVENT_TARGET, webkit_dom_html_document_dom_event_target_init))
enum {
DOM_HTML_DOCUMENT_PROP_0,
DOM_HTML_DOCUMENT_PROP_WIDTH,
DOM_HTML_DOCUMENT_PROP_HEIGHT,
DOM_HTML_DOCUMENT_PROP_DIR,
DOM_HTML_DOCUMENT_PROP_BG_COLOR,
DOM_HTML_DOCUMENT_PROP_FG_COLOR,
DOM_HTML_DOCUMENT_PROP_ALINK_COLOR,
DOM_HTML_DOCUMENT_PROP_LINK_COLOR,
DOM_HTML_DOCUMENT_PROP_VLINK_COLOR,
};
static void webkit_dom_html_document_set_property(GObject* object, guint propertyId, const GValue* value, GParamSpec* pspec)
{
WebKitDOMHTMLDocument* self = WEBKIT_DOM_HTML_DOCUMENT(object);
switch (propertyId) {
case DOM_HTML_DOCUMENT_PROP_DIR:
webkit_dom_html_document_set_dir(self, g_value_get_string(value));
break;
case DOM_HTML_DOCUMENT_PROP_BG_COLOR:
webkit_dom_html_document_set_bg_color(self, g_value_get_string(value));
break;
case DOM_HTML_DOCUMENT_PROP_FG_COLOR:
webkit_dom_html_document_set_fg_color(self, g_value_get_string(value));
break;
case DOM_HTML_DOCUMENT_PROP_ALINK_COLOR:
webkit_dom_html_document_set_alink_color(self, g_value_get_string(value));
break;
case DOM_HTML_DOCUMENT_PROP_LINK_COLOR:
webkit_dom_html_document_set_link_color(self, g_value_get_string(value));
break;
case DOM_HTML_DOCUMENT_PROP_VLINK_COLOR:
webkit_dom_html_document_set_vlink_color(self, g_value_get_string(value));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propertyId, pspec);
break;
}
}
static void webkit_dom_html_document_get_property(GObject* object, guint propertyId, GValue* value, GParamSpec* pspec)
{
WebKitDOMHTMLDocument* self = WEBKIT_DOM_HTML_DOCUMENT(object);
switch (propertyId) {
case DOM_HTML_DOCUMENT_PROP_WIDTH:
g_value_set_long(value, webkit_dom_html_document_get_width(self));
break;
case DOM_HTML_DOCUMENT_PROP_HEIGHT:
g_value_set_long(value, webkit_dom_html_document_get_height(self));
break;
case DOM_HTML_DOCUMENT_PROP_DIR:
g_value_take_string(value, webkit_dom_html_document_get_dir(self));
break;
case DOM_HTML_DOCUMENT_PROP_BG_COLOR:
g_value_take_string(value, webkit_dom_html_document_get_bg_color(self));
break;
case DOM_HTML_DOCUMENT_PROP_FG_COLOR:
g_value_take_string(value, webkit_dom_html_document_get_fg_color(self));
break;
case DOM_HTML_DOCUMENT_PROP_ALINK_COLOR:
g_value_take_string(value, webkit_dom_html_document_get_alink_color(self));
break;
case DOM_HTML_DOCUMENT_PROP_LINK_COLOR:
g_value_take_string(value, webkit_dom_html_document_get_link_color(self));
break;
case DOM_HTML_DOCUMENT_PROP_VLINK_COLOR:
g_value_take_string(value, webkit_dom_html_document_get_vlink_color(self));
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propertyId, pspec);
break;
}
}
static void webkit_dom_html_document_class_init(WebKitDOMHTMLDocumentClass* requestClass)
{
GObjectClass* gobjectClass = G_OBJECT_CLASS(requestClass);
gobjectClass->set_property = webkit_dom_html_document_set_property;
gobjectClass->get_property = webkit_dom_html_document_get_property;
g_object_class_install_property(
gobjectClass,
DOM_HTML_DOCUMENT_PROP_WIDTH,
g_param_spec_long(
"width",
"HTMLDocument:width",
"read-only glong HTMLDocument:width",
G_MINLONG, G_MAXLONG, 0,
WEBKIT_PARAM_READABLE));
g_object_class_install_property(
gobjectClass,
DOM_HTML_DOCUMENT_PROP_HEIGHT,
g_param_spec_long(
"height",
"HTMLDocument:height",
"read-only glong HTMLDocument:height",
G_MINLONG, G_MAXLONG, 0,
WEBKIT_PARAM_READABLE));
g_object_class_install_property(
gobjectClass,
DOM_HTML_DOCUMENT_PROP_DIR,
g_param_spec_string(
"dir",
"HTMLDocument:dir",
"read-write gchar* HTMLDocument:dir",
"",
WEBKIT_PARAM_READWRITE));
g_object_class_install_property(
gobjectClass,
DOM_HTML_DOCUMENT_PROP_BG_COLOR,
g_param_spec_string(
"bg-color",
"HTMLDocument:bg-color",
"read-write gchar* HTMLDocument:bg-color",
"",
WEBKIT_PARAM_READWRITE));
g_object_class_install_property(
gobjectClass,
DOM_HTML_DOCUMENT_PROP_FG_COLOR,
g_param_spec_string(
"fg-color",
"HTMLDocument:fg-color",
"read-write gchar* HTMLDocument:fg-color",
"",
WEBKIT_PARAM_READWRITE));
g_object_class_install_property(
gobjectClass,
DOM_HTML_DOCUMENT_PROP_ALINK_COLOR,
g_param_spec_string(
"alink-color",
"HTMLDocument:alink-color",
"read-write gchar* HTMLDocument:alink-color",
"",
WEBKIT_PARAM_READWRITE));
g_object_class_install_property(
gobjectClass,
DOM_HTML_DOCUMENT_PROP_LINK_COLOR,
g_param_spec_string(
"link-color",
"HTMLDocument:link-color",
"read-write gchar* HTMLDocument:link-color",
"",
WEBKIT_PARAM_READWRITE));
g_object_class_install_property(
gobjectClass,
DOM_HTML_DOCUMENT_PROP_VLINK_COLOR,
g_param_spec_string(
"vlink-color",
"HTMLDocument:vlink-color",
"read-write gchar* HTMLDocument:vlink-color",
"",
WEBKIT_PARAM_READWRITE));
}
static void webkit_dom_html_document_init(WebKitDOMHTMLDocument* request)
{
UNUSED_PARAM(request);
}
void webkit_dom_html_document_close(WebKitDOMHTMLDocument* self)
{
WebCore::JSMainThreadNullState state;
g_return_if_fail(WEBKIT_DOM_IS_HTML_DOCUMENT(self));
WebCore::HTMLDocument* item = WebKit::core(self);
item->close();
}
void webkit_dom_html_document_clear(WebKitDOMHTMLDocument* self)
{
WebCore::JSMainThreadNullState state;
g_return_if_fail(WEBKIT_DOM_IS_HTML_DOCUMENT(self));
WebCore::HTMLDocument* item = WebKit::core(self);
item->clear();
}
void webkit_dom_html_document_capture_events(WebKitDOMHTMLDocument* self)
{
WebCore::JSMainThreadNullState state;
g_return_if_fail(WEBKIT_DOM_IS_HTML_DOCUMENT(self));
WebCore::HTMLDocument* item = WebKit::core(self);
item->captureEvents();
}
void webkit_dom_html_document_release_events(WebKitDOMHTMLDocument* self)
{
WebCore::JSMainThreadNullState state;
g_return_if_fail(WEBKIT_DOM_IS_HTML_DOCUMENT(self));
WebCore::HTMLDocument* item = WebKit::core(self);
item->releaseEvents();
}
glong webkit_dom_html_document_get_width(WebKitDOMHTMLDocument* self)
{
WebCore::JSMainThreadNullState state;
g_return_val_if_fail(WEBKIT_DOM_IS_HTML_DOCUMENT(self), 0);
WebCore::HTMLDocument* item = WebKit::core(self);
glong result = item->width();
return result;
}
glong webkit_dom_html_document_get_height(WebKitDOMHTMLDocument* self)
{
WebCore::JSMainThreadNullState state;
g_return_val_if_fail(WEBKIT_DOM_IS_HTML_DOCUMENT(self), 0);
WebCore::HTMLDocument* item = WebKit::core(self);
glong result = item->height();
return result;
}
gchar* webkit_dom_html_document_get_dir(WebKitDOMHTMLDocument* self)
{
WebCore::JSMainThreadNullState state;
g_return_val_if_fail(WEBKIT_DOM_IS_HTML_DOCUMENT(self), 0);
WebCore::HTMLDocument* item = WebKit::core(self);
gchar* result = convertToUTF8String(item->dir());
return result;
}
void webkit_dom_html_document_set_dir(WebKitDOMHTMLDocument* self, const gchar* value)
{
WebCore::JSMainThreadNullState state;
g_return_if_fail(WEBKIT_DOM_IS_HTML_DOCUMENT(self));
g_return_if_fail(value);
WebCore::HTMLDocument* item = WebKit::core(self);
WTF::String convertedValue = WTF::String::fromUTF8(value);
item->setDir(convertedValue);
}
gchar* webkit_dom_html_document_get_bg_color(WebKitDOMHTMLDocument* self)
{
WebCore::JSMainThreadNullState state;
g_return_val_if_fail(WEBKIT_DOM_IS_HTML_DOCUMENT(self), 0);
WebCore::HTMLDocument* item = WebKit::core(self);
gchar* result = convertToUTF8String(item->bgColor());
return result;
}
void webkit_dom_html_document_set_bg_color(WebKitDOMHTMLDocument* self, const gchar* value)
{
WebCore::JSMainThreadNullState state;
g_return_if_fail(WEBKIT_DOM_IS_HTML_DOCUMENT(self));
g_return_if_fail(value);
WebCore::HTMLDocument* item = WebKit::core(self);
WTF::String convertedValue = WTF::String::fromUTF8(value);
item->setBgColor(convertedValue);
}
gchar* webkit_dom_html_document_get_fg_color(WebKitDOMHTMLDocument* self)
{
WebCore::JSMainThreadNullState state;
g_return_val_if_fail(WEBKIT_DOM_IS_HTML_DOCUMENT(self), 0);
WebCore::HTMLDocument* item = WebKit::core(self);
gchar* result = convertToUTF8String(item->fgColor());
return result;
}
void webkit_dom_html_document_set_fg_color(WebKitDOMHTMLDocument* self, const gchar* value)
{
WebCore::JSMainThreadNullState state;
g_return_if_fail(WEBKIT_DOM_IS_HTML_DOCUMENT(self));
g_return_if_fail(value);
WebCore::HTMLDocument* item = WebKit::core(self);
WTF::String convertedValue = WTF::String::fromUTF8(value);
item->setFgColor(convertedValue);
}
gchar* webkit_dom_html_document_get_alink_color(WebKitDOMHTMLDocument* self)
{
WebCore::JSMainThreadNullState state;
g_return_val_if_fail(WEBKIT_DOM_IS_HTML_DOCUMENT(self), 0);
WebCore::HTMLDocument* item = WebKit::core(self);
gchar* result = convertToUTF8String(item->alinkColor());
return result;
}
void webkit_dom_html_document_set_alink_color(WebKitDOMHTMLDocument* self, const gchar* value)
{
WebCore::JSMainThreadNullState state;
g_return_if_fail(WEBKIT_DOM_IS_HTML_DOCUMENT(self));
g_return_if_fail(value);
WebCore::HTMLDocument* item = WebKit::core(self);
WTF::String convertedValue = WTF::String::fromUTF8(value);
item->setAlinkColor(convertedValue);
}
gchar* webkit_dom_html_document_get_link_color(WebKitDOMHTMLDocument* self)
{
WebCore::JSMainThreadNullState state;
g_return_val_if_fail(WEBKIT_DOM_IS_HTML_DOCUMENT(self), 0);
WebCore::HTMLDocument* item = WebKit::core(self);
gchar* result = convertToUTF8String(item->linkColorForBindings());
return result;
}
void webkit_dom_html_document_set_link_color(WebKitDOMHTMLDocument* self, const gchar* value)
{
WebCore::JSMainThreadNullState state;
g_return_if_fail(WEBKIT_DOM_IS_HTML_DOCUMENT(self));
g_return_if_fail(value);
WebCore::HTMLDocument* item = WebKit::core(self);
WTF::String convertedValue = WTF::String::fromUTF8(value);
item->setLinkColorForBindings(convertedValue);
}
gchar* webkit_dom_html_document_get_vlink_color(WebKitDOMHTMLDocument* self)
{
WebCore::JSMainThreadNullState state;
g_return_val_if_fail(WEBKIT_DOM_IS_HTML_DOCUMENT(self), 0);
WebCore::HTMLDocument* item = WebKit::core(self);
gchar* result = convertToUTF8String(item->vlinkColor());
return result;
}
void webkit_dom_html_document_set_vlink_color(WebKitDOMHTMLDocument* self, const gchar* value)
{
WebCore::JSMainThreadNullState state;
g_return_if_fail(WEBKIT_DOM_IS_HTML_DOCUMENT(self));
g_return_if_fail(value);
WebCore::HTMLDocument* item = WebKit::core(self);
WTF::String convertedValue = WTF::String::fromUTF8(value);
item->setVlinkColor(convertedValue);
}
G_GNUC_END_IGNORE_DEPRECATIONS;
|
#include "common/server.h"
#include <array>
using namespace std;
using namespace xynet;
inline constexpr static const uint16_t ECHO_PORT = 2007;
inline constexpr static const uint16_t ECHO_BUFFER_SIZE = 4096;
auto echo(socket_t peer_socket) -> task<>
{
array<byte, ECHO_BUFFER_SIZE> buf{};
try
{
for(;;)
{
auto recv_bytes = co_await peer_socket.recv_some(buf);
[[maybe_unused]]
auto sent_bytes = co_await peer_socket.send(span{buf.begin(), recv_bytes});
}
}catch(...){}
try
{
peer_socket.shutdown();
co_await peer_socket.close();
}catch(...){}
}
int main()
{
auto service = io_service{};
sync_wait(start_server(echo, service, ECHO_PORT));
}
|
// Copyright 2016 Open Source Robotics Foundation, 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 <functional>
#include <memory>
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"
using std::placeholders::_1;
class HelloworldSubscriber : public rclcpp::Node
{
public:
HelloworldSubscriber()
: Node("Helloworld_subscriber")
{
auto qos_profile = rclcpp::QoS(rclcpp::KeepLast(10));
helloworld_subscriber_ = this->create_subscription<std_msgs::msg::String>(
"helloworld",
qos_profile,
std::bind(&HelloworldSubscriber::subscribe_topic_message, this, _1));
}
private:
void subscribe_topic_message(const std_msgs::msg::String::SharedPtr msg) const
{
RCLCPP_INFO(this->get_logger(), "Received message: '%s'", msg->data.c_str());
}
rclcpp::Subscription<std_msgs::msg::String>::SharedPtr helloworld_subscriber_;
};
int main(int argc, char * argv[])
{
rclcpp::init(argc, argv);
auto node = std::make_shared<HelloworldSubscriber>();
rclcpp::spin(node);
rclcpp::shutdown();
return 0;
}
|
template<typename T, typename Comparator = std::less<T>>
struct SparseTable {
std::vector<std::vector<T>> u;
std::vector<int> lg;
Comparator cmp;
void build(const std::vector<T>& a) {
int n = a.size(), L = 1;
while ((1 << L) <= n) ++L;
std::vector<std::vector<T>>(n, std::vector<T>(L)).swap(u);
lg.resize(n + 1);
lg[0] = -1;
for (int i = 1; i < lg.size(); ++ i) lg[i] = lg[i >> 1] + 1;
for (int i = 0; i < n; ++ i) u[i][0] = a[i];
for (int j = 1; (1 << j) <= n; ++ j) {
for (int i = 0; i + (1 << j) <= n; ++ i) {
u[i][j] = select(u[i][j - 1], u[i + (1 << (j - 1))][j - 1]);
}
}
}
T ask(int a, int b) const { // [a, b]
if (a > b || a < 0 || b >= u.size()) throw;
int k = lg[b - a + 1];
return select(u[a][k], u[b - (1 << k) + 1][k]);
}
T select(const T& lhs, const T& rhs) const { return cmp(lhs, rhs) ? lhs : rhs; }
};
// SparseTable<int> st;
// SparseTable<int, std::greater<int>> st;
template<typename StringType = std::string>
struct SuffixArray {
public:
int n;
StringType str;
std::vector<int> sa, rank;
// lcp[i] means lcp(str[sa[i]..], str[sa[i + 1]..]).
std::vector<int> lcp;
SparseTable<int, std::less<int>> st;
// NOTE: Due to implementation issue, you should not use 0 in your charset.
// And you should image that s[n]=0.
explicit SuffixArray(const StringType& s) : n(s.size()), str(s), sa(n + 1), rank(n + 1) {
str.push_back(0);
if (n > 0) {
this->len = n;
int m = *std::max_element(str.begin(), str.end()) + 1;
std::vector<int> buffer((std::max(m, (n + 1) / 2) + 1) * 2);
this->buffer = &buffer[0];
using T = typename std::decay_t<decltype(str[0])>;
sa_is<T>(&str[0], &sa[0], n + 1, m);
}
for (int i = 0; i <= n; ++i) rank[sa[i]] = i;
lcp.resize(n, 0);
int h = 0;
for (int i = 0; i < n; ++i) {
int j = sa[rank[i] - 1];
if (h > 0) --h;
for (; j + h < n && i + h < n; ++h) {
if (str[j + h] != str[i + h]) break;
}
lcp[rank[i] - 1] = h;
}
}
// Not verified yet.
int compare(const StringType& lhs, int pos, int len, const StringType& rhs) const {
for (int i = pos; i < pos + len; ++i) {
if (i >= lhs.size()) {
return i - pos >= rhs.size() ? 0 : -1;
}
if (i - pos >= rhs.size()) {
return 1;
}
if (lhs[i] != rhs[i - pos]) {
return lhs[i] - rhs[i - pos];
}
}
return len < rhs.size() ? -1 : 0;
}
template <typename Compare> int binary_search(const StringType& t) const {
int lb = -1, ub = n + 1;
while (ub - lb > 1) {
int mid = (ub + lb) / 2;
if (Compare()(compare(str, sa[mid], t.size(), t), 0))
lb = mid;
else
ub = mid;
}
return ub;
}
// O(|t|logn).
bool contains(const StringType& t) const {
int lb = 0, ub = n;
while (ub - lb > 1) {
int mid = (lb + ub) / 2;
if (compare(str, sa[mid], t.size(), t) < 0)
lb = mid;
else
ub = mid;
}
return compare(str, sa[ub], t.size(), t) == 0;
}
void prepare_lcp_rmq() {
st.build(lcp);
}
// lcp(str[x..], str[y..])
int get_lcp(int x, int y) const {
if (x == y) return n - x;
if (rank[x] > rank[y]) std::swap(x, y);
return st.ask(rank[x], rank[y] - 1);
}
int lower_bound(const StringType& t) const { return binary_search<std::less<int>>(t); }
int upper_bound(const StringType& t) const { return binary_search<std::less_equal<int>>(t); }
private:
using SLTypes = std::vector<bool>;
int* buffer = nullptr;
int* freq = nullptr;
int* cur = nullptr;
int len = 0;
template<typename T>
void count_frequency(const T* s, int n, int m) {
memset(freq, 0, sizeof(int) * m);
for (int i = 0; i < n; ++i) ++freq[(int)s[i]];
for (int i = 1; i < m; ++i) freq[i] += freq[i - 1];
memcpy(cur, freq, sizeof(int) * m);
}
#define pushS(x) sa[--cur[(int)s[x]]] = x
#define pushL(x) sa[cur[(int)s[x]]++] = x
template<typename T>
void induce(const T* s, int* sa, int m, const SLTypes& t) {
const int n = t.size();
memcpy(cur + 1, freq, sizeof(int) * (m - 1));
for (int i = 0; i < n; ++i) {
int p = sa[i] - 1;
if (p >= 0 && t[p]) pushL(p);
}
memcpy(cur, freq, sizeof(int) * m);
for (int i = n - 1; i > 0; --i) {
int p = sa[i] - 1;
if (p >= 0 && !t[p]) pushS(p);
}
}
template<typename T>
void sa_is(const T* s, int* sa, int n, int m) {
SLTypes t(n); memset(sa, 0, sizeof(int) * n);
for (int i = n - 2; ~i; --i) {
t[i] = (s[i] == s[i + 1]) ? t[i + 1] : s[i] > s[i + 1];
}
freq = buffer, cur = buffer + m;
count_frequency(s, n, m);
for (int i = 1; i < n; ++i) if (t[i - 1] > t[i]) pushS(i);
induce(s, sa, m, t);
int n1 = 0, order = 0;
for (int i = 0, p; i < n; ++i) {
if ((p = sa[i]) && t[p - 1] > t[p]) sa[n1++] = p;
}
int* s1 = sa + n1;
memset(s1, -1, sizeof(int) * (n - n1));
s1[(sa[0] - 1) / 2] = order++;
for (int i = 1; i < n1; ++i) {
bool diff = true;
for (int x = sa[i - 1], y = sa[i]; ; ++x, ++y) {
if (s[x] != s[y] || t[x] != t[y]) break;
else if (t[x] > t[x + 1] && t[y] > t[y + 1]) {
diff = (s[x + 1] != s[y + 1]); break;
}
}
s1[(sa[i] - 1) / 2] = (order += diff) - 1;
}
for (int i = 0, x = 0; i < n - n1; ++i) {
if (~s1[i]) s1[x++] = s1[i];
}
if (order != n1) {
sa_is<int>(s1, sa, n1, order);
for (int i = 0; i < n1; ++i) s1[sa[i]] = i;
}
for (int i = 1, j = 0; i < n; ++i) {
if (t[i - 1] > t[i]) sa[s1[j++]] = -i;
}
memset(s1, 0, sizeof(int) * (n - n1));
freq = buffer, cur = buffer + m;
count_frequency(s, n, m);
for (int i = n1 - 1; ~i; --i) pushS(-sa[i]);
induce(s, sa, m, t);
}
#undef pushS
#undef pushL
};
|
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2015 Laurent Gomila (laurent@sfml-dev.org)
//
// 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.
//
////////////////////////////////////////////////////////////
#ifndef SFML_RENDERSTATES_HPP
#define SFML_RENDERSTATES_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Export.hpp>
#include <SFML/Graphics/BlendMode.hpp>
#include <SFML/Graphics/Transform.hpp>
namespace sf
{
class Shader;
class Texture;
////////////////////////////////////////////////////////////
/// \brief Define the states used for drawing to a RenderTarget
///
////////////////////////////////////////////////////////////
class SFML_GRAPHICS_API RenderStates
{
public:
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
/// Constructing a default set of render states is equivalent
/// to using sf::RenderStates::Default.
/// The default set defines:
/// \li the BlendAlpha blend mode
/// \li the identity transform
/// \li a null texture
/// \li a null shader
///
////////////////////////////////////////////////////////////
RenderStates();
////////////////////////////////////////////////////////////
/// \brief Construct a default set of render states with a custom blend mode
///
/// \param theBlendMode Blend mode to use
///
////////////////////////////////////////////////////////////
RenderStates(const BlendMode& theBlendMode);
////////////////////////////////////////////////////////////
/// \brief Construct a default set of render states with a custom transform
///
/// \param theTransform Transform to use
///
////////////////////////////////////////////////////////////
RenderStates(const Transform& theTransform);
////////////////////////////////////////////////////////////
/// \brief Construct a default set of render states with a custom texture
///
/// \param theTexture Texture to use
///
////////////////////////////////////////////////////////////
RenderStates(const Texture* theTexture);
////////////////////////////////////////////////////////////
/// \brief Construct a default set of render states with a custom shader
///
/// \param theShader Shader to use
///
////////////////////////////////////////////////////////////
RenderStates(const Shader* theShader);
////////////////////////////////////////////////////////////
/// \brief Construct a set of render states with all its attributes
///
/// \param theBlendMode Blend mode to use
/// \param theTransform Transform to use
/// \param theTexture Texture to use
/// \param theShader Shader to use
///
////////////////////////////////////////////////////////////
RenderStates(const BlendMode& theBlendMode, const Transform& theTransform,
const Texture* theTexture, const Shader* theShader);
////////////////////////////////////////////////////////////
// Static member data
////////////////////////////////////////////////////////////
static const RenderStates Default; ///< Special instance holding the default render states
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
BlendMode blendMode; ///< Blending mode
Transform transform; ///< Transform
const Texture* texture; ///< Texture
const Shader* shader; ///< Shader
};
} // namespace sf
#endif // SFML_RENDERSTATES_HPP
////////////////////////////////////////////////////////////
/// \class sf::RenderStates
/// \ingroup graphics
///
/// There are four global states that can be applied to
/// the drawn objects:
/// \li the blend mode: how pixels of the object are blended with the background
/// \li the transform: how the object is positioned/rotated/scaled
/// \li the texture: what image is mapped to the object
/// \li the shader: what custom effect is applied to the object
///
/// High-level objects such as sprites or text force some of
/// these states when they are drawn. For example, a sprite
/// will set its own texture, so that you don't have to care
/// about it when drawing the sprite.
///
/// The transform is a special case: sprites, texts and shapes
/// (and it's a good idea to do it with your own drawable classes
/// too) combine their transform with the one that is passed in the
/// RenderStates structure. So that you can use a "global" transform
/// on top of each object's transform.
///
/// Most objects, especially high-level drawables, can be drawn
/// directly without defining render states explicitly -- the
/// default set of states is ok in most cases.
/// \code
/// window.draw(sprite);
/// \endcode
///
/// If you want to use a single specific render state,
/// for example a shader, you can pass it directly to the Draw
/// function: sf::RenderStates has an implicit one-argument
/// constructor for each state.
/// \code
/// window.draw(sprite, shader);
/// \endcode
///
/// When you're inside the Draw function of a drawable
/// object (inherited from sf::Drawable), you can
/// either pass the render states unmodified, or change
/// some of them.
/// For example, a transformable object will combine the
/// current transform with its own transform. A sprite will
/// set its texture. Etc.
///
/// \see sf::RenderTarget, sf::Drawable
///
////////////////////////////////////////////////////////////
|
/****************************************************************************
** Copyright (c) 2021, Fougue Ltd. <http://www.fougue.pro>
** All rights reserved.
** See license at https://github.com/fougue/mayo/blob/master/LICENSE.txt
****************************************************************************/
#include "application.h"
#include "caf_utils.h"
#include "document.h"
#include <TDF_ChildIterator.hxx>
#include <TDF_TagSource.hxx>
#include <XCAFDoc_DocumentTool.hxx>
#include <set>
namespace Mayo {
Document::Document()
: QObject(nullptr),
TDocStd_Document(NameFormatBinary)
{
TDF_TagSource::Set(this->rootLabel());
}
void Document::initXCaf()
{
m_xcaf.setLabelMain(this->Main());
m_xcaf.setModelTree(m_modelTree);
}
const QString& Document::name() const
{
return m_name;
}
void Document::setName(const QString& name)
{
m_name = name;
emit this->nameChanged(name);
}
const FilePath& Document::filePath() const
{
return m_filePath;
}
void Document::setFilePath(const FilePath& fp)
{
m_filePath = fp;
}
const char* Document::toNameFormat(Document::Format format)
{
switch (format) {
case Format::Binary: return Document::NameFormatBinary;
case Format::Xml: return Document::NameFormatXml;
}
return nullptr;
}
const char Document::NameFormatBinary[] = "BinDocMayo";
const char Document::NameFormatXml[] = "XmlDocMayo";
const char Document::TypeName[] = "Mayo::Document";
bool Document::isXCafDocument() const
{
return XCAFDoc_DocumentTool::IsXCAFDocument(this);
}
TDF_Label Document::rootLabel() const
{
return this->GetData()->Root();
}
bool Document::isEntity(TreeNodeId nodeId)
{
return m_modelTree.nodeIsRoot(nodeId);
}
int Document::entityCount() const
{
return m_modelTree.roots().size();
}
TDF_Label Document::entityLabel(int index) const
{
return m_modelTree.nodeData(this->entityTreeNodeId(index));
}
TreeNodeId Document::entityTreeNodeId(int index) const
{
return m_modelTree.roots()[index];
}
DocumentTreeNode Document::entityTreeNode(int index) const
{
return { DocumentPtr(this), this->entityTreeNodeId(index) };
}
void Document::rebuildModelTree()
{
m_modelTree.clear();
const bool xcafIsNull = m_xcaf.isNull();
if (!xcafIsNull) {
for (const TDF_Label& label : m_xcaf.topLevelFreeShapes())
m_xcaf.deepBuildAssemblyTree(0, label);
}
constexpr bool allLevels = true;
for (TDF_ChildIterator it(this->rootLabel(), !allLevels); it.More(); it.Next()) {
const TDF_Label childLabel = it.Value();
if (!CafUtils::isNullOrEmpty(childLabel)
&& (xcafIsNull || childLabel != this->Main())) // Not XCAF Main label
{
m_modelTree.appendChild(0, childLabel);
}
}
}
DocumentPtr Document::findFrom(const TDF_Label& label)
{
return DocumentPtr::DownCast(TDocStd_Document::Get(label));
}
TDF_Label Document::newEntityLabel()
{
Handle_TDF_TagSource tagSrc = CafUtils::findAttribute<TDF_TagSource>(this->rootLabel());
Expects(!tagSrc.IsNull());
if (tagSrc->Get() == 0)
this->rootLabel().NewChild(); // Reserve label 0:1 for XCAF Main()
return this->rootLabel().NewChild();
}
void Document::addEntityTreeNode(const TDF_Label& label)
{
// Check if 'label' belongs to current document
if (Document::findFrom(label).get() != this)
return;
// Check if 'label' is not already there inside model tree
for (int i = 0; i < this->entityCount(); ++i) {
if (this->entityLabel(i) == label)
return;
}
// TODO Allow custom population of the model tree for the new entity
const TreeNodeId nodeId = m_xcaf.deepBuildAssemblyTree(0, label);
emit this->entityAdded(nodeId);
#if 0
// Remove 'label'
label.ForgetAllAttributes();
label.Nullify();
#endif
}
void Document::destroyEntity(TreeNodeId entityTreeNodeId)
{
Expects(this->modelTree().nodeIsRoot(entityTreeNodeId));
TDF_Label entityLabel = m_modelTree.nodeData(entityTreeNodeId);
if (CafUtils::isNullOrEmpty(entityLabel))
return;
emit this->entityAboutToBeDestroyed(entityTreeNodeId);
entityLabel.ForgetAllAttributes();
entityLabel.Nullify();
m_modelTree.removeRoot(entityTreeNodeId);
}
void Document::BeforeClose()
{
TDocStd_Document::BeforeClose();
Application::instance()->notifyDocumentAboutToClose(m_identifier);
}
void Document::ChangeStorageFormat(const TCollection_ExtendedString& newStorageFormat)
{
// TODO: check format
TDocStd_Document::ChangeStorageFormat(newStorageFormat);
}
} // namespace Mayo
|
/*
* Copyright (c) 2015-2017, Intel Corporation
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Intel Corporation nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/** \file
* \brief Shufti acceleration: compile code.
*/
#include "shufticompile.h"
#include "ue2common.h"
#include "util/charreach.h"
#include "util/container.h"
#include "util/flat_containers.h"
#include <array>
#include <cassert>
#include <cstring>
#include <map>
using namespace std;
namespace ue2 {
/** \brief Single-byte variant.
*
* Returns -1 if unable to construct masks, otherwise returns number of bits
* used in the mask.
*
* Note: always able to construct masks for 8 or fewer characters.
*/
int shuftiBuildMasks(const CharReach &c, u8 *lo, u8 *hi) {
/* Things could be packed much more optimally, but this should be able to
* handle any set of characters entirely in the lower half. */
assert(c.count() < 256);
assert(!c.none());
map<u8, CharReach> by_hi; /* hi nibble -> set of matching lo nibbles */
/* group matching characters by high nibble */
for (size_t i = c.find_first(); i != CharReach::npos; i = c.find_next(i)) {
u8 it_hi = i >> 4;
u8 it_lo = i & 0xf;
by_hi[it_hi].set(it_lo);
}
map<CharReach, CharReach> by_lo_set;
/* group all hi nibbles with a common set of lo nibbles together */
for (map<u8, CharReach>::const_iterator it = by_hi.begin();
it != by_hi.end(); ++it) {
by_lo_set[it->second].set(it->first);
}
if (by_lo_set.size() > 8) {
/* too many char classes on the dance floor */
assert(c.size() > 8);
return -1;
}
u8 bit_index = 0;
array<u8, 16> lo_a; lo_a.fill(0);
array<u8, 16> hi_a; hi_a.fill(0);
for (map<CharReach, CharReach>::const_iterator it = by_lo_set.begin();
it != by_lo_set.end(); ++it) {
const CharReach &lo_nibbles = it->first;
const CharReach &hi_nibbles = it->second;
/* set bits in low mask */
for (size_t j = lo_nibbles.find_first(); j != CharReach::npos;
j = lo_nibbles.find_next(j)) {
lo_a[j] |= (1 << bit_index);
}
/* set bits in high mask */
for (size_t j = hi_nibbles.find_first(); j != CharReach::npos;
j = hi_nibbles.find_next(j)) {
hi_a[j] |= (1 << bit_index);
}
bit_index++;
}
memcpy(lo, lo_a.data(), sizeof(m128));
memcpy(hi, hi_a.data(), sizeof(m128));
return bit_index;
}
static
array<u16, 4> or_array(array<u16, 4> a, const array<u16, 4> &b) {
a[0] |= b[0];
a[1] |= b[1];
a[2] |= b[2];
a[3] |= b[3];
return a;
}
#define MAX_BUCKETS 8
static
void set_buckets_from_mask(u16 nibble_mask, u32 bucket,
array<u8, 16> &byte_mask) {
assert(bucket < MAX_BUCKETS);
u32 mask = nibble_mask;
while (mask) {
u32 n = findAndClearLSB_32(&mask);
byte_mask[n] &= ~(1 << bucket);
}
}
bool shuftiBuildDoubleMasks(const CharReach &onechar,
const flat_set<pair<u8, u8>> &twochar,
u8 *lo1, u8 *hi1, u8 *lo2, u8 *hi2) {
DEBUG_PRINTF("unibytes %zu dibytes %zu\n", onechar.size(),
twochar.size());
array<u8, 16> lo1_a;
array<u8, 16> lo2_a;
array<u8, 16> hi1_a;
array<u8, 16> hi2_a;
lo1_a.fill(0xff);
lo2_a.fill(0xff);
hi1_a.fill(0xff);
hi2_a.fill(0xff);
// two-byte literals
vector<array<u16, 4>> nibble_masks;
for (const auto &p : twochar) {
DEBUG_PRINTF("%02hhx %02hhx\n", p.first, p.second);
u16 a_lo = 1U << (p.first & 0xf);
u16 a_hi = 1U << (p.first >> 4);
u16 b_lo = 1U << (p.second & 0xf);
u16 b_hi = 1U << (p.second >> 4);
nibble_masks.push_back({{a_lo, a_hi, b_lo, b_hi}});
}
// one-byte literals (second byte is a wildcard)
for (size_t it = onechar.find_first(); it != CharReach::npos;
it = onechar.find_next(it)) {
DEBUG_PRINTF("%02hhx\n", (u8)it);
u16 a_lo = 1U << (it & 0xf);
u16 a_hi = 1U << (it >> 4);
u16 wildcard = 0xffff;
nibble_masks.push_back({{a_lo, a_hi, wildcard, wildcard}});
}
// try to merge strings into shared buckets
for (u32 i = 0; i < 4; i++) {
map<array<u16, 4>, array<u16, 4>> new_masks;
for (const auto &a : nibble_masks) {
auto key = a;
key[i] = 0;
if (!contains(new_masks, key)) {
new_masks[key] = a;
} else {
new_masks[key] = or_array(new_masks[key], a);
}
}
nibble_masks.clear();
for (const auto &e : new_masks) {
nibble_masks.push_back(e.second);
}
}
if (nibble_masks.size() > MAX_BUCKETS) {
DEBUG_PRINTF("too many buckets needed (%zu)\n", nibble_masks.size());
return false;
}
u32 i = 0;
for (const auto &a : nibble_masks) {
set_buckets_from_mask(a[0], i, lo1_a);
set_buckets_from_mask(a[1], i, hi1_a);
set_buckets_from_mask(a[2], i, lo2_a);
set_buckets_from_mask(a[3], i, hi2_a);
i++;
}
memcpy(lo1, lo1_a.data(), sizeof(m128));
memcpy(lo2, lo2_a.data(), sizeof(m128));
memcpy(hi1, hi1_a.data(), sizeof(m128));
memcpy(hi2, hi2_a.data(), sizeof(m128));
return true;
}
#ifdef DUMP_SUPPORT
CharReach shufti2cr(const u8 *lo, const u8 *hi) {
CharReach cr;
for (u32 i = 0; i < 256; i++) {
if (lo[(u8)i & 0xf] & hi[(u8)i >> 4]) {
cr.set(i);
}
}
return cr;
}
#endif // DUMP_SUPPORT
} // namespace ue2
|
//
// MIT License
//
// Copyright 2019
//
// 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 JONES_DEBUGGER_COMMAND_PROMPT_HH
#define JONES_DEBUGGER_COMMAND_PROMPT_HH
#include <QCompleter>
#include <QKeyEvent>
#include <QStringListModel>
#include <QTextEdit>
#include <memory>
namespace Ui {
class CommandPrompt : public QTextEdit {
Q_OBJECT
public:
CommandPrompt(QWidget *parent = nullptr);
~CommandPrompt() override;
void setCompleter(std::unique_ptr<QCompleter> completer);
QCompleter *completer() const;
protected:
void keyPressEvent(QKeyEvent *event) override;
void focusInEvent(QFocusEvent *event) override;
private slots:
void insertCompletion(const QString &completion);
private:
void processAutoComplete(QKeyEvent *event);
void processCommand(QKeyEvent *event);
QString textUnderCursor() const;
private:
QStringListModel completerModel_;
std::unique_ptr<QCompleter> completer_;
};
} // namespace Ui
#endif // JONES_DEBUGGER_COMMAND_PROMPT_HH
|
// Copyright 2016 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 "content/browser/media/session/pepper_playback_observer.h"
#include <memory>
#include "base/command_line.h"
#include "base/metrics/histogram_macros.h"
#include "content/browser/media/session/media_session_impl.h"
#include "content/browser/media/session/pepper_player_delegate.h"
#include "content/common/frame_messages.h"
#include "ipc/ipc_message_macros.h"
#include "media/base/media_content_type.h"
#include "media/base/media_switches.h"
namespace content {
PepperPlaybackObserver::PepperPlaybackObserver(WebContents* contents)
: contents_(contents) {}
PepperPlaybackObserver::~PepperPlaybackObserver() {
// At this point WebContents is being destructed, so it's safe to
// call this. MediaSession may decide to send further IPC messages
// through PepperPlayerDelegates, which might be declined if the
// RenderViewHost has been destroyed.
for (auto it = players_played_sound_map_.begin();
it != players_played_sound_map_.end();) {
const PlayerId& id = (it++)->first;
PepperInstanceDeleted(id.first, id.second);
}
}
void PepperPlaybackObserver::RenderFrameDeleted(
RenderFrameHost* render_frame_host) {
std::vector<PlayerId> players_to_remove;
for (auto it = players_played_sound_map_.begin();
it != players_played_sound_map_.end();) {
const PlayerId& id = (it++)->first;
if (id.first == render_frame_host)
PepperInstanceDeleted(id.first, id.second);
}
}
void PepperPlaybackObserver::PepperInstanceCreated(
RenderFrameHost* render_frame_host, int32_t pp_instance) {
PlayerId id(render_frame_host, pp_instance);
players_played_sound_map_[id] = false;
}
void PepperPlaybackObserver::PepperInstanceDeleted(
RenderFrameHost* render_frame_host, int32_t pp_instance) {
PlayerId id(render_frame_host, pp_instance);
auto iter = players_played_sound_map_.find(id);
if (iter == players_played_sound_map_.end())
return;
players_played_sound_map_.erase(iter);
PepperStopsPlayback(render_frame_host, pp_instance);
}
void PepperPlaybackObserver::PepperStartsPlayback(
RenderFrameHost* render_frame_host, int32_t pp_instance) {
PlayerId id(render_frame_host, pp_instance);
players_played_sound_map_[id] = true;
if (players_map_.count(id))
return;
players_map_[id] =
std::make_unique<PepperPlayerDelegate>(render_frame_host, pp_instance);
MediaSessionImpl::Get(contents_)->AddPlayer(
players_map_[id].get(), PepperPlayerDelegate::kPlayerId,
base::FeatureList::IsEnabled(media::kAudioFocusDuckFlash)
? media::MediaContentType::Pepper
: media::MediaContentType::OneShot);
}
void PepperPlaybackObserver::PepperStopsPlayback(
RenderFrameHost* render_frame_host, int32_t pp_instance) {
PlayerId id(render_frame_host, pp_instance);
if (!players_map_.count(id))
return;
MediaSessionImpl::Get(contents_)->RemovePlayer(
players_map_[id].get(), PepperPlayerDelegate::kPlayerId);
players_map_.erase(id);
}
} // namespace content
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/supervised/supervised_user_creation_screen.h"
#include "ash/desktop_background/desktop_background_controller.h"
#include "ash/shelf/shelf.h"
#include "ash/shell.h"
#include "base/rand_util.h"
#include "base/values.h"
#include "chrome/browser/chromeos/camera_detector.h"
#include "chrome/browser/chromeos/login/error_screens_histogram_helper.h"
#include "chrome/browser/chromeos/login/existing_user_controller.h"
#include "chrome/browser/chromeos/login/screen_manager.h"
#include "chrome/browser/chromeos/login/screens/base_screen_delegate.h"
#include "chrome/browser/chromeos/login/screens/error_screen.h"
#include "chrome/browser/chromeos/login/screens/network_error.h"
#include "chrome/browser/chromeos/login/signin_specifics.h"
#include "chrome/browser/chromeos/login/supervised/supervised_user_authentication.h"
#include "chrome/browser/chromeos/login/supervised/supervised_user_creation_controller.h"
#include "chrome/browser/chromeos/login/supervised/supervised_user_creation_controller_new.h"
#include "chrome/browser/chromeos/login/supervised/supervised_user_creation_flow.h"
#include "chrome/browser/chromeos/login/users/avatar/user_image_manager.h"
#include "chrome/browser/chromeos/login/users/chrome_user_manager.h"
#include "chrome/browser/chromeos/login/users/supervised_user_manager.h"
#include "chrome/browser/chromeos/login/wizard_controller.h"
#include "chrome/browser/supervised_user/legacy/supervised_user_shared_settings_service.h"
#include "chrome/browser/supervised_user/legacy/supervised_user_shared_settings_service_factory.h"
#include "chrome/browser/supervised_user/legacy/supervised_user_sync_service.h"
#include "chrome/browser/supervised_user/legacy/supervised_user_sync_service_factory.h"
#include "chrome/browser/supervised_user/supervised_user_constants.h"
#include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h"
#include "chrome/grit/generated_resources.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/session_manager_client.h"
#include "chromeos/login/auth/key.h"
#include "chromeos/login/auth/user_context.h"
#include "chromeos/network/network_state.h"
#include "components/user_manager/user.h"
#include "components/user_manager/user_image/user_image.h"
#include "content/public/browser/browser_thread.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/image/image_skia.h"
namespace chromeos {
namespace {
// Key for (boolean) value that indicates that user already exists on device.
const char kUserExists[] = "exists";
// Key for value that indicates why user can not be imported.
const char kUserConflict[] = "conflict";
// User is already imported.
const char kUserConflictImported[] = "imported";
// There is another supervised user with same name.
const char kUserConflictName[] = "name";
const char kUserNeedPassword[] = "needPassword";
const char kAvatarURLKey[] = "avatarurl";
const char kRandomAvatarKey[] = "randomAvatar";
const char kNameOfIntroScreen[] = "intro";
const char kNameOfNewUserParametersScreen[] = "username";
void ConfigureErrorScreen(ErrorScreen* screen,
const NetworkState* network,
const NetworkPortalDetector::CaptivePortalStatus status) {
switch (status) {
case NetworkPortalDetector::CAPTIVE_PORTAL_STATUS_UNKNOWN:
case NetworkPortalDetector::CAPTIVE_PORTAL_STATUS_ONLINE:
NOTREACHED();
break;
case NetworkPortalDetector::CAPTIVE_PORTAL_STATUS_OFFLINE:
screen->SetErrorState(NetworkError::ERROR_STATE_OFFLINE, std::string());
break;
case NetworkPortalDetector::CAPTIVE_PORTAL_STATUS_PORTAL:
screen->SetErrorState(NetworkError::ERROR_STATE_PORTAL,
network ? network->name() : std::string());
screen->FixCaptivePortal();
break;
case NetworkPortalDetector::CAPTIVE_PORTAL_STATUS_PROXY_AUTH_REQUIRED:
screen->SetErrorState(NetworkError::ERROR_STATE_PROXY, std::string());
break;
default:
NOTREACHED();
break;
}
}
} // namespace
// static
SupervisedUserCreationScreen* SupervisedUserCreationScreen::Get(
ScreenManager* manager) {
return static_cast<SupervisedUserCreationScreen*>(
manager->GetScreen(WizardController::kSupervisedUserCreationScreenName));
}
SupervisedUserCreationScreen::SupervisedUserCreationScreen(
BaseScreenDelegate* base_screen_delegate,
SupervisedUserCreationScreenHandler* actor)
: BaseScreen(base_screen_delegate),
actor_(actor),
on_error_screen_(false),
manager_signin_in_progress_(false),
last_page_(kNameOfIntroScreen),
sync_service_(NULL),
apply_photo_after_decoding_(false),
selected_image_(0),
histogram_helper_(new ErrorScreensHistogramHelper("Supervised")),
weak_factory_(this) {
DCHECK(actor_);
if (actor_)
actor_->SetDelegate(this);
}
SupervisedUserCreationScreen::~SupervisedUserCreationScreen() {
CameraPresenceNotifier::GetInstance()->RemoveObserver(this);
if (sync_service_)
sync_service_->RemoveObserver(this);
if (actor_)
actor_->SetDelegate(NULL);
network_portal_detector::GetInstance()->RemoveObserver(this);
}
void SupervisedUserCreationScreen::PrepareToShow() {
if (actor_)
actor_->PrepareToShow();
}
void SupervisedUserCreationScreen::Show() {
CameraPresenceNotifier::GetInstance()->AddObserver(this);
if (actor_) {
actor_->Show();
// TODO(antrim) : temorary hack (until upcoming hackaton). Should be
// removed once we have screens reworked.
if (on_error_screen_)
actor_->ShowPage(last_page_);
else
actor_->ShowIntroPage();
}
if (!on_error_screen_)
network_portal_detector::GetInstance()->AddAndFireObserver(this);
on_error_screen_ = false;
histogram_helper_->OnScreenShow();
}
void SupervisedUserCreationScreen::OnPageSelected(const std::string& page) {
last_page_ = page;
}
void SupervisedUserCreationScreen::OnPortalDetectionCompleted(
const NetworkState* network,
const NetworkPortalDetector::CaptivePortalState& state) {
if (state.status == NetworkPortalDetector::CAPTIVE_PORTAL_STATUS_ONLINE) {
get_base_screen_delegate()->HideErrorScreen(this);
histogram_helper_->OnErrorHide();
} else if (state.status !=
NetworkPortalDetector::CAPTIVE_PORTAL_STATUS_UNKNOWN) {
on_error_screen_ = true;
ErrorScreen* screen = get_base_screen_delegate()->GetErrorScreen();
ConfigureErrorScreen(screen, network, state.status);
screen->SetUIState(NetworkError::UI_STATE_SUPERVISED);
get_base_screen_delegate()->ShowErrorScreen();
histogram_helper_->OnErrorShow(screen->GetErrorState());
}
}
void SupervisedUserCreationScreen::ShowManagerInconsistentStateErrorScreen() {
manager_signin_in_progress_ = false;
if (!actor_)
return;
actor_->ShowErrorPage(
l10n_util::GetStringUTF16(
IDS_CREATE_SUPERVISED_USER_MANAGER_INCONSISTENT_STATE_TITLE),
l10n_util::GetStringUTF16(
IDS_CREATE_SUPERVISED_USER_MANAGER_INCONSISTENT_STATE),
l10n_util::GetStringUTF16(
IDS_CREATE_SUPERVISED_USER_MANAGER_INCONSISTENT_STATE_BUTTON));
}
void SupervisedUserCreationScreen::ShowInitialScreen() {
if (actor_)
actor_->ShowIntroPage();
}
void SupervisedUserCreationScreen::Hide() {
CameraPresenceNotifier::GetInstance()->RemoveObserver(this);
if (actor_)
actor_->Hide();
if (!on_error_screen_)
network_portal_detector::GetInstance()->RemoveObserver(this);
}
std::string SupervisedUserCreationScreen::GetName() const {
return WizardController::kSupervisedUserCreationScreenName;
}
void SupervisedUserCreationScreen::AbortFlow() {
DBusThreadManager::Get()
->GetSessionManagerClient()
->NotifySupervisedUserCreationFinished();
controller_->CancelCreation();
}
void SupervisedUserCreationScreen::FinishFlow() {
DBusThreadManager::Get()
->GetSessionManagerClient()
->NotifySupervisedUserCreationFinished();
controller_->FinishCreation();
}
void SupervisedUserCreationScreen::HideFlow() {
Hide();
}
void SupervisedUserCreationScreen::AuthenticateManager(
const AccountId& manager_id,
const std::string& manager_password) {
if (manager_signin_in_progress_)
return;
manager_signin_in_progress_ = true;
UserFlow* flow = new SupervisedUserCreationFlow(manager_id);
ChromeUserManager::Get()->SetUserFlow(manager_id, flow);
// Make sure no two controllers exist at the same time.
controller_.reset();
controller_.reset(new SupervisedUserCreationControllerNew(this, manager_id));
UserContext user_context(manager_id);
user_context.SetKey(Key(manager_password));
ExistingUserController::current_controller()->Login(user_context,
SigninSpecifics());
}
void SupervisedUserCreationScreen::CreateSupervisedUser(
const base::string16& display_name,
const std::string& supervised_user_password) {
DCHECK(controller_.get());
int image;
if (selected_image_ == user_manager::User::USER_IMAGE_EXTERNAL)
// TODO(dzhioev): crbug/249660
image = SupervisedUserCreationController::kDummyAvatarIndex;
else
image = selected_image_;
controller_->StartCreation(display_name, supervised_user_password, image);
}
void SupervisedUserCreationScreen::ImportSupervisedUser(
const std::string& user_id) {
DCHECK(controller_.get());
DCHECK(existing_users_.get());
VLOG(1) << "Importing user " << user_id;
base::DictionaryValue* user_info;
if (!existing_users_->GetDictionary(user_id, &user_info)) {
LOG(ERROR) << "Can not import non-existing user " << user_id;
return;
}
base::string16 display_name;
std::string master_key;
std::string signature_key;
std::string encryption_key;
std::string avatar;
bool exists;
int avatar_index = SupervisedUserCreationController::kDummyAvatarIndex;
user_info->GetString(SupervisedUserSyncService::kName, &display_name);
user_info->GetString(SupervisedUserSyncService::kMasterKey, &master_key);
user_info->GetString(SupervisedUserSyncService::kPasswordSignatureKey,
&signature_key);
user_info->GetString(SupervisedUserSyncService::kPasswordEncryptionKey,
&encryption_key);
user_info->GetString(SupervisedUserSyncService::kChromeOsAvatar, &avatar);
user_info->GetBoolean(kUserExists, &exists);
// We should not get here with existing user selected, so just display error.
if (exists) {
actor_->ShowErrorPage(
l10n_util::GetStringUTF16(
IDS_CREATE_SUPERVISED_USER_GENERIC_ERROR_TITLE),
l10n_util::GetStringUTF16(
IDS_CREATE_SUPERVISED_USER_GENERIC_ERROR),
l10n_util::GetStringUTF16(
IDS_CREATE_SUPERVISED_USER_GENERIC_ERROR_BUTTON));
return;
}
SupervisedUserSyncService::GetAvatarIndex(avatar, &avatar_index);
const base::DictionaryValue* password_data = NULL;
SupervisedUserSharedSettingsService* shared_settings_service =
SupervisedUserSharedSettingsServiceFactory::GetForBrowserContext(
controller_->GetManagerProfile());
const base::Value* value = shared_settings_service->GetValue(
user_id, supervised_users::kChromeOSPasswordData);
bool password_right_here = value && value->GetAsDictionary(&password_data) &&
!password_data->empty();
if (password_right_here) {
controller_->StartImport(display_name,
avatar_index,
user_id,
master_key,
password_data,
encryption_key,
signature_key);
} else {
NOTREACHED() << " Oops, no password";
}
}
// TODO(antrim): Code duplication with previous method will be removed once
// password sync is implemented.
void SupervisedUserCreationScreen::ImportSupervisedUserWithPassword(
const std::string& user_id,
const std::string& password) {
DCHECK(controller_.get());
DCHECK(existing_users_.get());
VLOG(1) << "Importing user " << user_id;
base::DictionaryValue* user_info;
if (!existing_users_->GetDictionary(user_id, &user_info)) {
LOG(ERROR) << "Can not import non-existing user " << user_id;
return;
}
base::string16 display_name;
std::string master_key;
std::string avatar;
bool exists;
int avatar_index = SupervisedUserCreationController::kDummyAvatarIndex;
user_info->GetString(SupervisedUserSyncService::kName, &display_name);
user_info->GetString(SupervisedUserSyncService::kMasterKey, &master_key);
user_info->GetString(SupervisedUserSyncService::kChromeOsAvatar, &avatar);
user_info->GetBoolean(kUserExists, &exists);
// We should not get here with existing user selected, so just display error.
if (exists) {
actor_->ShowErrorPage(
l10n_util::GetStringUTF16(
IDS_CREATE_SUPERVISED_USER_GENERIC_ERROR_TITLE),
l10n_util::GetStringUTF16(
IDS_CREATE_SUPERVISED_USER_GENERIC_ERROR),
l10n_util::GetStringUTF16(
IDS_CREATE_SUPERVISED_USER_GENERIC_ERROR_BUTTON));
return;
}
SupervisedUserSyncService::GetAvatarIndex(avatar, &avatar_index);
controller_->StartImport(display_name,
password,
avatar_index,
user_id,
master_key);
}
void SupervisedUserCreationScreen::OnManagerLoginFailure() {
manager_signin_in_progress_ = false;
if (actor_)
actor_->ShowManagerPasswordError();
}
void SupervisedUserCreationScreen::OnManagerFullyAuthenticated(
Profile* manager_profile) {
DBusThreadManager::Get()
->GetSessionManagerClient()
->NotifySupervisedUserCreationStarted();
manager_signin_in_progress_ = false;
DCHECK(controller_.get());
// For manager user, move desktop to locked container so that windows created
// during the user image picker step are below it.
ash::Shell::GetInstance()->
desktop_background_controller()->MoveDesktopToLockedContainer();
ash::Shelf::ForPrimaryDisplay()->SetAlignment(
ash::ShelfAlignment::SHELF_ALIGNMENT_BOTTOM_LOCKED);
controller_->SetManagerProfile(manager_profile);
if (actor_)
actor_->ShowUsernamePage();
last_page_ = kNameOfNewUserParametersScreen;
CHECK(!sync_service_);
sync_service_ = SupervisedUserSyncServiceFactory::GetForProfile(
manager_profile);
sync_service_->AddObserver(this);
OnSupervisedUsersChanged();
}
void SupervisedUserCreationScreen::OnSupervisedUsersChanged() {
CHECK(sync_service_);
sync_service_->GetSupervisedUsersAsync(
base::Bind(&SupervisedUserCreationScreen::OnGetSupervisedUsers,
weak_factory_.GetWeakPtr()));
}
void SupervisedUserCreationScreen::OnManagerCryptohomeAuthenticated() {
if (actor_) {
actor_->ShowStatusMessage(true /* progress */, l10n_util::GetStringUTF16(
IDS_CREATE_SUPERVISED_USER_CREATION_AUTH_PROGRESS_MESSAGE));
}
}
void SupervisedUserCreationScreen::OnActorDestroyed(
SupervisedUserCreationScreenHandler* actor) {
if (actor_ == actor)
actor_ = NULL;
}
void SupervisedUserCreationScreen::OnCreationError(
SupervisedUserCreationController::ErrorCode code) {
LOG(ERROR) << "Supervised user creation failure, code: " << code;
base::string16 title;
base::string16 message;
base::string16 button;
// TODO(antrim) : find out which errors do we really have.
// We might reuse some error messages from ordinary user flow.
switch (code) {
case SupervisedUserCreationController::CRYPTOHOME_NO_MOUNT:
case SupervisedUserCreationController::CRYPTOHOME_FAILED_MOUNT:
case SupervisedUserCreationController::CRYPTOHOME_FAILED_TPM:
title = l10n_util::GetStringUTF16(
IDS_CREATE_SUPERVISED_USER_TPM_ERROR_TITLE);
message = l10n_util::GetStringUTF16(
IDS_CREATE_SUPERVISED_USER_TPM_ERROR);
button = l10n_util::GetStringUTF16(
IDS_CREATE_SUPERVISED_USER_TPM_ERROR_BUTTON);
break;
case SupervisedUserCreationController::CLOUD_SERVER_ERROR:
case SupervisedUserCreationController::TOKEN_WRITE_FAILED:
title = l10n_util::GetStringUTF16(
IDS_CREATE_SUPERVISED_USER_GENERIC_ERROR_TITLE);
message = l10n_util::GetStringUTF16(
IDS_CREATE_SUPERVISED_USER_GENERIC_ERROR);
button = l10n_util::GetStringUTF16(
IDS_CREATE_SUPERVISED_USER_GENERIC_ERROR_BUTTON);
break;
case SupervisedUserCreationController::NO_ERROR:
NOTREACHED();
}
if (actor_)
actor_->ShowErrorPage(title, message, button);
}
void SupervisedUserCreationScreen::OnCreationTimeout() {
if (actor_) {
actor_->ShowStatusMessage(false /* error */, l10n_util::GetStringUTF16(
IDS_CREATE_SUPERVISED_USER_CREATION_CREATION_TIMEOUT_MESSAGE));
}
}
void SupervisedUserCreationScreen::OnLongCreationWarning() {
if (actor_) {
actor_->ShowStatusMessage(true /* progress */, l10n_util::GetStringUTF16(
IDS_PROFILES_CREATE_SUPERVISED_JUST_SIGNED_IN));
}
}
bool SupervisedUserCreationScreen::FindUserByDisplayName(
const base::string16& display_name,
std::string *out_id) const {
if (!existing_users_.get())
return false;
for (base::DictionaryValue::Iterator it(*existing_users_.get());
!it.IsAtEnd(); it.Advance()) {
const base::DictionaryValue* user_info =
static_cast<const base::DictionaryValue*>(&it.value());
base::string16 user_display_name;
if (user_info->GetString(SupervisedUserSyncService::kName,
&user_display_name)) {
if (display_name == user_display_name) {
if (out_id)
*out_id = it.key();
return true;
}
}
}
return false;
}
// TODO(antrim) : this is an explicit code duplications with UserImageScreen.
// It should be removed by issue 251179.
void SupervisedUserCreationScreen::ApplyPicture() {
std::string user_id = controller_->GetSupervisedUserId();
UserImageManager* image_manager =
ChromeUserManager::Get()->GetUserImageManager(
AccountId::FromUserEmail(user_id));
switch (selected_image_) {
case user_manager::User::USER_IMAGE_EXTERNAL:
// Photo decoding may not have been finished yet.
if (user_photo_.isNull()) {
apply_photo_after_decoding_ = true;
return;
}
image_manager->SaveUserImage(
user_manager::UserImage::CreateAndEncode(user_photo_));
break;
case user_manager::User::USER_IMAGE_PROFILE:
NOTREACHED() << "Supervised users have no profile pictures";
break;
default:
DCHECK(selected_image_ >= 0 &&
selected_image_ < default_user_image::kDefaultImagesCount);
image_manager->SaveUserDefaultImageIndex(selected_image_);
break;
}
// Proceed to tutorial.
actor_->ShowTutorialPage();
}
void SupervisedUserCreationScreen::OnCreationSuccess() {
ApplyPicture();
}
void SupervisedUserCreationScreen::OnCameraPresenceCheckDone(
bool is_camera_present) {
if (actor_)
actor_->SetCameraPresent(is_camera_present);
}
void SupervisedUserCreationScreen::OnGetSupervisedUsers(
const base::DictionaryValue* users) {
// Copy for passing to WebUI, contains only id, name and avatar URL.
std::unique_ptr<base::ListValue> ui_users(new base::ListValue());
SupervisedUserManager* supervised_user_manager =
ChromeUserManager::Get()->GetSupervisedUserManager();
// Stored copy, contains all necessary information.
existing_users_.reset(new base::DictionaryValue());
for (base::DictionaryValue::Iterator it(*users); !it.IsAtEnd();
it.Advance()) {
// Copy that would be stored in this class.
base::DictionaryValue* local_copy =
static_cast<base::DictionaryValue*>(it.value().DeepCopy());
// Copy that would be passed to WebUI. It has some extra values for
// displaying, but does not contain sensitive data, such as master password.
base::DictionaryValue* ui_copy =
static_cast<base::DictionaryValue*>(new base::DictionaryValue());
int avatar_index = SupervisedUserCreationController::kDummyAvatarIndex;
std::string chromeos_avatar;
if (local_copy->GetString(SupervisedUserSyncService::kChromeOsAvatar,
&chromeos_avatar) &&
!chromeos_avatar.empty() &&
SupervisedUserSyncService::GetAvatarIndex(
chromeos_avatar, &avatar_index)) {
ui_copy->SetString(kAvatarURLKey,
default_user_image::GetDefaultImageUrl(avatar_index));
} else {
int i = base::RandInt(default_user_image::kFirstDefaultImageIndex,
default_user_image::kDefaultImagesCount - 1);
local_copy->SetString(
SupervisedUserSyncService::kChromeOsAvatar,
SupervisedUserSyncService::BuildAvatarString(i));
local_copy->SetBoolean(kRandomAvatarKey, true);
ui_copy->SetString(kAvatarURLKey,
default_user_image::GetDefaultImageUrl(i));
}
local_copy->SetBoolean(kUserExists, false);
ui_copy->SetBoolean(kUserExists, false);
base::string16 display_name;
local_copy->GetString(SupervisedUserSyncService::kName, &display_name);
if (supervised_user_manager->FindBySyncId(it.key())) {
local_copy->SetBoolean(kUserExists, true);
ui_copy->SetBoolean(kUserExists, true);
local_copy->SetString(kUserConflict, kUserConflictImported);
ui_copy->SetString(kUserConflict, kUserConflictImported);
} else if (supervised_user_manager->FindByDisplayName(display_name)) {
local_copy->SetBoolean(kUserExists, true);
ui_copy->SetBoolean(kUserExists, true);
local_copy->SetString(kUserConflict, kUserConflictName);
ui_copy->SetString(kUserConflict, kUserConflictName);
}
ui_copy->SetString(SupervisedUserSyncService::kName, display_name);
std::string signature_key;
bool has_password =
local_copy->GetString(SupervisedUserSyncService::kPasswordSignatureKey,
&signature_key) &&
!signature_key.empty();
ui_copy->SetBoolean(kUserNeedPassword, !has_password);
ui_copy->SetString("id", it.key());
existing_users_->Set(it.key(), local_copy);
ui_users->Append(ui_copy);
}
actor_->ShowExistingSupervisedUsers(ui_users.get());
}
void SupervisedUserCreationScreen::OnPhotoTaken(
const std::string& raw_data) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
user_photo_ = gfx::ImageSkia();
ImageDecoder::Cancel(this);
ImageDecoder::Start(this, raw_data);
}
void SupervisedUserCreationScreen::OnImageDecoded(
const SkBitmap& decoded_image) {
user_photo_ = gfx::ImageSkia::CreateFrom1xBitmap(decoded_image);
if (apply_photo_after_decoding_)
ApplyPicture();
}
void SupervisedUserCreationScreen::OnDecodeImageFailed() {
NOTREACHED() << "Failed to decode PNG image from WebUI";
}
void SupervisedUserCreationScreen::OnImageSelected(
const std::string& image_type,
const std::string& image_url) {
if (image_url.empty())
return;
int user_image_index = user_manager::User::USER_IMAGE_INVALID;
if (image_type == "default" &&
default_user_image::IsDefaultImageUrl(image_url, &user_image_index)) {
selected_image_ = user_image_index;
} else if (image_type == "camera") {
selected_image_ = user_manager::User::USER_IMAGE_EXTERNAL;
} else {
NOTREACHED() << "Unexpected image type: " << image_type;
}
}
void SupervisedUserCreationScreen::OnImageAccepted() {
}
} // namespace chromeos
|
//
// Copyright (c) 2016, Scientific Toolworks, Inc.
//
// This software is licensed under the MIT License. The LICENSE.md file
// describes the conditions under which this software may be distributed.
//
// Author: Bryan Williams
//
#include "ConfigDialog.h"
#include "AddRemoteDialog.h"
#include "BranchDelegate.h"
#include "BranchTableModel.h"
#include "DeleteBranchDialog.h"
#include "DiffPanel.h"
#include "NewBranchDialog.h"
#include "PluginsPanel.h"
#include "RemoteTableModel.h"
#include "SubmoduleDelegate.h"
#include "SubmoduleTableModel.h"
#include "app/Application.h"
#include "conf/Settings.h"
#include "git/Config.h"
#include "git/Reference.h"
#include "git/Submodule.h"
#include "index/Index.h"
#include "ui/BlameEditor.h"
#include "ui/EditorWindow.h"
#include "ui/Footer.h"
#include "ui/MainWindow.h"
#include "ui/RepoView.h"
#include <QAction>
#include <QCheckBox>
#include <QDialogButtonBox>
#include <QFormLayout>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QLabel>
#include <QLineEdit>
#include <QListView>
#include <QMessageBox>
#include <QPushButton>
#include <QShortcut>
#include <QSpinBox>
#include <QStackedWidget>
#include <QStringListModel>
#include <QTableView>
#include <QTextEdit>
#include <QToolBar>
#include <QUrl>
#include <QVBoxLayout>
#include <QtConcurrent>
namespace {
class StackedWidget : public QStackedWidget
{
public:
StackedWidget(QWidget *parent = nullptr)
: QStackedWidget(parent)
{}
QSize sizeHint() const override
{
return currentWidget()->sizeHint();
}
QSize minimumSizeHint() const override
{
return currentWidget()->minimumSizeHint();
}
};
class GeneralPanel : public QWidget
{
Q_OBJECT
public:
GeneralPanel(RepoView *view, QWidget *parent = nullptr)
: QWidget(parent), mRepo(view->repo())
{
mName = new QLineEdit(this);
mEmail = new QLineEdit(this);
mFetch = new QCheckBox(tr("Fetch every"), this);
mFetchMinutes = new QSpinBox(this);
connect(mFetch, &QCheckBox::toggled,
mFetchMinutes, &QSpinBox::setEnabled);
QHBoxLayout *fetchLayout = new QHBoxLayout;
fetchLayout->addWidget(mFetch);
fetchLayout->addWidget(mFetchMinutes);
fetchLayout->addWidget(new QLabel(tr("minutes"), this));
fetchLayout->addStretch();
mPushCommit = new QCheckBox(tr("Push after each commit"), this);
mPullUpdate = new QCheckBox(tr("Update submodules after pull"), this);
mAutoPrune = new QCheckBox(tr("Prune when fetching"), this);
QFormLayout *form = new QFormLayout(this);
form->addRow(tr("User name:"), mName);
form->addRow(tr("User email:"), mEmail);
form->addRow(tr("Automatic actions:"), fetchLayout);
form->addRow(QString(), mPushCommit);
form->addRow(QString(), mPullUpdate);
form->addRow(QString(), mAutoPrune);
init();
// Connect signals after initializing fields.
connect(mName, &QLineEdit::textChanged, [this](const QString &text) {
mRepo.config().setValue("user.name", text);
});
connect(mEmail, &QLineEdit::textChanged, [this](const QString &text) {
mRepo.config().setValue("user.email", text);
});
connect(mFetch, &QCheckBox::toggled, [this, view](bool checked) {
mRepo.appConfig().setValue("autofetch.enable", checked);
view->startFetchTimer();
});
using Signal = void (QSpinBox::*)(int);
auto signal = static_cast<Signal>(&QSpinBox::valueChanged);
connect(mFetchMinutes, signal, [this](int value) {
mRepo.appConfig().setValue("autofetch.minutes", value);
});
connect(mPushCommit, &QCheckBox::toggled, [this](bool checked) {
mRepo.appConfig().setValue("autopush.enable", checked);
});
connect(mPullUpdate, &QCheckBox::toggled, [this](bool checked) {
mRepo.appConfig().setValue("autoupdate.enable", checked);
});
connect(mAutoPrune, &QCheckBox::toggled, [this](bool checked) {
mRepo.appConfig().setValue("autoprune.enable", checked);
});
}
void init()
{
git::Config config = mRepo.config();
mName->setText(config.value<QString>("user.name"));
mEmail->setText(config.value<QString>("user.email"));
// Read defaults from global settings.
Settings *settings = Settings::instance();
settings->beginGroup("global");
settings->beginGroup("autofetch");
bool fetch = settings->value("enable").toBool();
int minutes = settings->value("minutes").toInt();
settings->endGroup();
bool push = settings->value("autopush/enable").toBool();
bool update = settings->value("autoupdate/enable").toBool();
bool prune = settings->value("autoprune/enable").toBool();
settings->endGroup();
git::Config app = mRepo.appConfig();
mFetch->setChecked(app.value<bool>("autofetch.enable", fetch));
mFetchMinutes->setValue(app.value<int>("autofetch.minutes", minutes));
mPushCommit->setChecked(app.value<bool>("autopush.enable", push));
mPullUpdate->setChecked(app.value<bool>("autoupdate.enable", update));
mAutoPrune->setChecked(app.value<bool>("autoprune.enable", prune));
}
private:
git::Repository mRepo;
QLineEdit *mName;
QLineEdit *mEmail;
QCheckBox *mFetch;
QSpinBox *mFetchMinutes;
QCheckBox *mPushCommit;
QCheckBox *mPullUpdate;
QCheckBox *mAutoPrune;
};
class RemotesPanel : public QWidget
{
Q_OBJECT
public:
RemotesPanel(const git::Repository &repo, QWidget *parent = nullptr)
: QWidget(parent), mRepo(repo)
{
QTableView *table = new QTableView(this);
table->verticalHeader()->setVisible(false);
table->horizontalHeader()->setStretchLastSection(true);
table->setEditTriggers(QAbstractItemView::SelectedClicked);
table->setSelectionBehavior(QAbstractItemView::SelectRows);
table->setSelectionMode(QAbstractItemView::ExtendedSelection);
table->setShowGrid(false);
table->setModel(new RemoteTableModel(this, repo));
Footer *footer = new Footer(table);
connect(footer, &Footer::plusClicked, this, [this] {
addRemote();
});
connect(footer, &Footer::minusClicked, this, [this, table] {
QModelIndexList indexes = table->selectionModel()->selectedRows();
foreach (const QModelIndex &index, indexes) {
QString name = index.data().toString();
QString title = tr("Delete Remote?");
QString text = tr("Are you sure you want to delete '%1'?");
QMessageBox msg(QMessageBox::Warning, title, text.arg(name),
QMessageBox::Cancel, this);
QPushButton *remove =
msg.addButton(tr("Delete"), QMessageBox::AcceptRole);
msg.exec();
if (msg.clickedButton() == remove)
mRepo.deleteRemote(name);
}
});
connect(table->selectionModel(), &QItemSelectionModel::selectionChanged,
[table, footer] {
QModelIndexList indexes = table->selectionModel()->selectedRows();
footer->setMinusEnabled(!indexes.isEmpty());
});
QVBoxLayout *layout = new QVBoxLayout(this);
layout->setSpacing(0);
layout->addWidget(table);
layout->addWidget(footer);
}
void addRemote(const QString &name = QString())
{
AddRemoteDialog *dialog = new AddRemoteDialog(name, this);
connect(dialog, &QDialog::accepted, this, [this, dialog] {
mRepo.addRemote(dialog->name(), dialog->url());
});
dialog->open();
}
private:
git::Repository mRepo;
};
class BranchesPanel : public QWidget
{
public:
BranchesPanel(const git::Repository &repo, QWidget *parent = nullptr)
: QWidget(parent)
{
mTable = new QTableView(this);
mTable->verticalHeader()->setVisible(false);
mTable->setEditTriggers(QAbstractItemView::SelectedClicked);
mTable->setSelectionBehavior(QAbstractItemView::SelectRows);
mTable->setSelectionMode(QAbstractItemView::ExtendedSelection);
mTable->setShowGrid(false);
mTable->setModel(new BranchTableModel(repo, this));
mTable->setItemDelegate(new BranchDelegate(repo, mTable));
// Set section resize mode after model is set.
mTable->horizontalHeader()->setSectionResizeMode(
BranchTableModel::Upstream, QHeaderView::Stretch);
Footer *footer = new Footer(mTable);
footer->setPlusEnabled(repo.head().isValid());
connect(footer, &Footer::plusClicked, [this, repo] {
NewBranchDialog *dialog = new NewBranchDialog(repo, git::Commit(), this);
connect(dialog, &QDialog::accepted, this, [this, repo, dialog] {
QString name = dialog->name();
git::Commit commit = dialog->target();
git::Branch branch = git::Repository(repo).createBranch(name, commit);
// Start tracking.
if (branch.isValid())
branch.setUpstream(dialog->upstream());
});
dialog->open();
});
connect(footer, &Footer::minusClicked, [this] {
// Get all selected branches before removing any.
QList<git::Branch> branches;
QModelIndexList indexes = mTable->selectionModel()->selectedRows();
foreach (const QModelIndex &index, indexes) {
QVariant var = index.data(BranchTableModel::BranchRole);
branches.append(var.value<git::Branch>());
}
// Remove them all.
foreach (git::Branch branch, branches) {
Q_ASSERT(!branch.isHead());
DeleteBranchDialog dialog(branch, this);
dialog.exec();
}
});
// Enable/disable minus button.
auto updateMinusButton = [this, footer] {
QModelIndexList indexes = mTable->selectionModel()->selectedRows();
bool enabled = !indexes.isEmpty();
foreach (const QModelIndex &index, indexes) {
QVariant var = index.data(BranchTableModel::BranchRole);
if (var.value<git::Branch>().isHead()) {
enabled = false;
break;
}
}
footer->setMinusEnabled(enabled);
};
connect(mTable->selectionModel(), &QItemSelectionModel::selectionChanged,
this, updateMinusButton);
connect(mTable->model(), &QAbstractItemModel::modelReset,
this, updateMinusButton);
QVBoxLayout *layout = new QVBoxLayout(this);
layout->setSpacing(0);
layout->addWidget(mTable);
layout->addWidget(footer);
}
void editBranch(const QString &name)
{
QAbstractItemModel *model = mTable->model();
for (int i = 0; i < model->rowCount(); ++i) {
QModelIndex index = model->index(i, BranchTableModel::Name);
if (index.data().toString() == name) {
mTable->edit(index);
return;
}
}
}
private:
QTableView *mTable;
};
class SubmodulesPanel : public QWidget
{
public:
SubmodulesPanel(RepoView *view, QWidget *parent = nullptr)
: QWidget(parent)
{
QTableView *table = new QTableView(this);
table->verticalHeader()->setVisible(false);
table->setEditTriggers(QAbstractItemView::SelectedClicked);
table->setSelectionBehavior(QAbstractItemView::SelectRows);
table->setSelectionMode(QAbstractItemView::ExtendedSelection);
table->setShowGrid(false);
table->setModel(new SubmoduleTableModel(view->repo(), this));
table->setItemDelegate(new SubmoduleDelegate(table));
// Set section resize mode after model is set.
table->horizontalHeader()->setSectionResizeMode(
SubmoduleTableModel::Name, QHeaderView::ResizeToContents);
table->horizontalHeader()->setSectionResizeMode(
SubmoduleTableModel::Url, QHeaderView::Stretch);
connect(table, &QTableView::doubleClicked, [view](const QModelIndex &index) {
QVariant var = index.data(SubmoduleTableModel::SubmoduleRole);
view->openSubmodule(var.value<git::Submodule>());
});
Footer *footer = new Footer(table);
footer->setPlusEnabled(false);
footer->setMinusEnabled(false);
QVBoxLayout *layout = new QVBoxLayout(this);
layout->setSpacing(0);
layout->addWidget(table);
layout->addWidget(footer);
}
};
class SearchPanel : public QWidget
{
Q_OBJECT
public:
SearchPanel(RepoView *view, QWidget *parent = nullptr)
: QWidget(parent)
{
using Signal = void (QSpinBox::*)(int);
auto signal = static_cast<Signal>(&QSpinBox::valueChanged);
git::Config config = view->repo().appConfig();
Q_ASSERT(config.isValid());
// enable
QCheckBox *enable = new QCheckBox(tr("Enable indexing"), this);
enable->setChecked(config.value<bool>("index.enable", true));
connect(enable, &QCheckBox::toggled, [view](bool checked) {
git::Config config = view->repo().appConfig();
config.setValue("index.enable", checked);
if (checked) {
view->startIndexing();
} else {
view->cancelIndexing();
}
});
// commit term limit
QSpinBox *terms = new QSpinBox(this);
QLabel *termsLabel = new QLabel(tr("terms"), this);
terms->setMinimum(100000);
terms->setMaximum(99999999);
terms->setSingleStep(100000);
terms->setValue(config.value<int>("index.termlimit", 1000000));
connect(terms, signal, [view](int value) {
view->repo().appConfig().setValue("index.termlimit", value);
});
QHBoxLayout *termsLayout = new QHBoxLayout;
termsLayout->addWidget(terms);
termsLayout->addWidget(termsLabel);
termsLayout->addStretch();
// diff context lines
QSpinBox *context = new QSpinBox(this);
QLabel *contextLabel = new QLabel(tr("lines"), this);
context->setValue(config.value<int>("index.contextlines", 3));
connect(context, signal, [view](int value) {
view->repo().appConfig().setValue("index.contextlines", value);
});
QHBoxLayout *contextLayout = new QHBoxLayout;
contextLayout->addWidget(context);
contextLayout->addWidget(contextLabel);
contextLayout->addStretch();
QFormLayout *form = new QFormLayout;
form->setContentsMargins(16,2,16,0);
form->setFormAlignment(Qt::AlignLeft | Qt::AlignTop);
form->addRow(tr("Limit commits to:"), termsLayout);
form->addRow(tr("Diff context:"), contextLayout);
// Collect a list of widgets to disable when indexing is disabled.
QList<QWidget *> widgets = {
terms, termsLabel, form->labelForField(termsLayout),
context, contextLabel, form->labelForField(contextLayout)
};
auto setWidgetsEnabled = [widgets](bool enabled) {
foreach (QWidget *widget, widgets)
widget->setEnabled(enabled);
};
connect(enable, &QCheckBox::toggled, setWidgetsEnabled);
setWidgetsEnabled(enable->isChecked());
// remove
QPushButton *remove = new QPushButton(tr("Remove Index"), this);
remove->setEnabled(view->index()->isValid());
connect(remove, &QPushButton::clicked, [view, remove] {
Index *index = view->index();
view->cancelIndexing();
index->remove();
remove->setEnabled(index->isValid());
});
QVBoxLayout *layout = new QVBoxLayout(this);
layout->setContentsMargins(24,24,24,24);
layout->addWidget(enable);
layout->addLayout(form);
layout->addWidget(remove, 0, Qt::AlignLeft);
layout->addStretch();
}
};
class LfsPanel : public QWidget
{
Q_OBJECT
public:
LfsPanel(RepoView *view, QWidget *parent = nullptr)
: QWidget(parent)
{
if (!view->repo().lfsIsInitialized()) {
QPushButton *button = new QPushButton(tr("Initialize LFS"), this);
connect(button, &QPushButton::clicked, [this, view] {
view->lfsInitialize();
window()->close();
});
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addSpacing(16);
layout->addWidget(button, 0, Qt::AlignCenter);
layout->addSpacing(12);
return;
}
Settings *settings = Settings::instance();
git::Repository repo = view->repo();
QListView *list = new QListView(this);
list->setEditTriggers(QAbstractItemView::NoEditTriggers);
list->setSelectionBehavior(QAbstractItemView::SelectRows);
list->setSelectionMode(QAbstractItemView::ExtendedSelection);
QStringListModel *model = new QStringListModel(QStringList(), this);
list->setModel(model);
QFutureWatcher<QStringList> *watcher = new QFutureWatcher<QStringList>(this);
connect(watcher, &QFutureWatcher<QStringList>::finished, [model, watcher] {
model->setStringList(watcher->result());
watcher->deleteLater();
});
watcher->setFuture(QtConcurrent::run(repo, &git::Repository::lfsTracked));
Footer *footer = new Footer(list);
connect(footer, &Footer::plusClicked, [this, repo, model] {
QDialog *dialog = new QDialog(this);
dialog->setAttribute(Qt::WA_DeleteOnClose);
QLabel *description = new QLabel(tr(
"Specify a glob pattern for tracking large files.\n"
"\n"
"Generally, large files are greater than 500kB, change frequently,\n"
"and do not compress well with git. This includes binary or video\n"
"files which are already highly compressed.\n"
"\n"
"Examples\n"
"*.png\n"
"*.[pP][nN][gG]\n"
"/images/*\n"
));
QFormLayout *form = new QFormLayout;
QLineEdit *pattern = new QLineEdit(dialog);
form->addRow(tr("Pattern:"), pattern);
QDialogButtonBox *buttons = new QDialogButtonBox();
buttons->addButton(QDialogButtonBox::Cancel);
QPushButton *track =
buttons->addButton(tr("Track"), QDialogButtonBox::AcceptRole);
track->setEnabled(false);
connect(buttons, &QDialogButtonBox::accepted, dialog, &QDialog::accept);
connect(buttons, &QDialogButtonBox::rejected, dialog, &QDialog::reject);
QVBoxLayout *layout = new QVBoxLayout(dialog);
layout->addWidget(description);
layout->addLayout(form);
layout->addWidget(buttons);
connect(pattern, &QLineEdit::textChanged, [track](const QString &text) {
track->setEnabled(!text.isEmpty());
});
connect(dialog, &QDialog::accepted, this, [pattern, repo, model] {
git::Repository tmp(repo);
tmp.lfsSetTracked(pattern->text(), true);
model->setStringList(tmp.lfsTracked());
});
dialog->open();
});
connect(footer, &Footer::minusClicked, [this, list, repo, model] {
git::Repository tmp(repo);
QModelIndexList indexes = list->selectionModel()->selectedRows();
foreach (const QModelIndex &index, indexes) {
QString text = index.data(Qt::DisplayRole).toString();
tmp.lfsSetTracked(text, false);
}
model->setStringList(tmp.lfsTracked());
});
// enable minus button
auto updateMinusButton = [list, footer] {
footer->setMinusEnabled(list->selectionModel()->hasSelection());
};
connect(list->selectionModel(), &QItemSelectionModel::selectionChanged,
this, updateMinusButton);
connect(list->model(), &QAbstractItemModel::modelReset,
this, updateMinusButton);
QVBoxLayout *tableLayout = new QVBoxLayout;
tableLayout->setSpacing(0);
tableLayout->addWidget(list);
tableLayout->addWidget(footer);
QMap<QString,QString> map;
foreach (const QString &string, repo.lfsEnvironment()) {
if (string.contains("=")) {
QString key = string.section('=', 0, 0);
QString value = string.section('=', 1);
map.insert(key, value);
}
}
// url
QLineEdit *urlLineEdit = new QLineEdit(
map.value("Endpoint").section(" ", 0, 0));
connect(urlLineEdit, &QLineEdit::textChanged,
[this, repo](const QString &text) {
repo.config().setValue("lfs.url", text);
});
// pruneoffsetdays
QSpinBox *pruneOffsetDays = new QSpinBox(this);
pruneOffsetDays->setValue(map.value("PruneOffsetDays").toInt());
auto signal = QOverload<int>::of(&QSpinBox::valueChanged);
connect(pruneOffsetDays, signal, [this, repo](int value) {
repo.config().setValue("lfs.pruneoffsetdays", value);
});
QHBoxLayout *pruneOffsetLayout = new QHBoxLayout;
pruneOffsetLayout->addWidget(pruneOffsetDays);
pruneOffsetLayout->addWidget(new QLabel(tr("days")));
pruneOffsetLayout->addStretch();
// fetchrecentalways
QCheckBox *fetchRecentAlways = new QCheckBox(
tr("Fetch LFS objects from all references for the past"), this);
bool fetchRecentEnabled = map.value("FetchRecentAlways").contains("true");
fetchRecentAlways->setChecked(fetchRecentEnabled);
connect(fetchRecentAlways, &QCheckBox::toggled,
[settings, repo](bool checked) {
repo.config().setValue("lfs.fetchrecentalways", checked);
});
// fetchrecentrefsdays
QSpinBox *fetchRecentRefsDays = new QSpinBox(this);
fetchRecentRefsDays->setValue(map.value("FetchRecentRefsDays").toInt());
fetchRecentRefsDays->setEnabled(fetchRecentEnabled);
connect(fetchRecentRefsDays, signal, [this, repo](int value) {
repo.config().setValue("lfs.fetchrecentrefsdays", value);
});
connect(fetchRecentAlways, &QCheckBox::toggled,
[fetchRecentRefsDays](bool checked) {
fetchRecentRefsDays->setEnabled(checked);
});
QHBoxLayout *refDaysLayout = new QHBoxLayout;
refDaysLayout->addWidget(fetchRecentRefsDays);
refDaysLayout->addWidget(new QLabel(tr("reference days or")));
refDaysLayout->addStretch();
// fetchrecentcommitsdays
QSpinBox *fetchRecentCommitsDays = new QSpinBox(this);
fetchRecentCommitsDays->setValue(map.value("FetchRecentCommitsDays").toInt());
fetchRecentCommitsDays->setEnabled(fetchRecentEnabled);
connect(fetchRecentCommitsDays, signal, [this, repo](int value) {
repo.config().setValue("lfs.fetchrecentcommitsdays", value);
});
connect(fetchRecentAlways, &QCheckBox::toggled,
[fetchRecentCommitsDays](bool checked) {
fetchRecentCommitsDays->setEnabled(checked);
});
QHBoxLayout *commitDaysLayout = new QHBoxLayout;
commitDaysLayout->addWidget(fetchRecentCommitsDays);
commitDaysLayout->addWidget(new QLabel(tr("commit days")));
commitDaysLayout->addStretch();
// lfs environment
QPushButton *environment = new QPushButton(tr("View Environment"));
connect(environment, &QAbstractButton::clicked, [this, view] {
git::Repository repo = view->repo();
QDialog *dialog = new QDialog();
dialog->setWindowTitle(tr("git-lfs env (read only)"));
QSize size(500, 500);
dialog->setFixedSize(size);
QTextEdit *textEdit = new QTextEdit(dialog);
textEdit->setFixedSize(size);
textEdit->setReadOnly(true);
foreach (const QString &string, repo.lfsEnvironment()) {
textEdit->append(string);
}
dialog->exec();
});
QPushButton *deinit = new QPushButton(tr("Deinitialize LFS"));
connect(deinit, &QAbstractButton::clicked, [this, view] {
QString title = tr("Deinitialize LFS?");
QString text =
tr("Are you sure you want uninstall LFS from this repository?");
QMessageBox msg(
QMessageBox::Warning, title, text, QMessageBox::Cancel, this);
QPushButton *agree =
msg.addButton(tr("Deinitialize"), QMessageBox::AcceptRole);
msg.exec();
if (msg.clickedButton() == agree)
view->lfsDeinitialize();
window()->close();
});
QFormLayout *form = new QFormLayout;
form->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);
form->addRow(tr("Server URL:"), urlLineEdit);
form->addRow(tr("Prune Offset:"), pruneOffsetLayout);
form->addRow(tr("Fetch Recent:"), fetchRecentAlways);
form->addRow(QString(), refDaysLayout);
form->addRow(QString(), commitDaysLayout);
form->addRow(tr("Advanced:"), environment);
form->addRow(QString(), deinit);
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addLayout(tableLayout);
layout->addLayout(form);
}
};
} // anon. namespace
ConfigDialog::ConfigDialog(RepoView *view, Index index)
: QDialog(view)
{
Application::track("ConfigDialog");
setMinimumWidth(500);
setAttribute(Qt::WA_DeleteOnClose);
setContextMenuPolicy(Qt::NoContextMenu);
QVBoxLayout *layout = new QVBoxLayout(this);
layout->setContentsMargins(0,0,0,0);
layout->setSpacing(0);
// Close on escape.
QShortcut *esc = new QShortcut(tr("Esc"), this);
connect(esc, &QShortcut::activated, this, &ConfigDialog::close);
// Create tool bar.
QToolBar *toolbar = new QToolBar(this);
toolbar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
toolbar->setMovable(false);
layout->addWidget(toolbar);
// Create central stack widget.
mStack = new StackedWidget(this);
connect(mStack, &StackedWidget::currentChanged,
this, &ConfigDialog::adjustSize);
layout->addWidget(mStack);
// Track actions in a group.
mActions = new QActionGroup(this);
connect(mActions, &QActionGroup::triggered, [this](QAction *action) {
mStack->setCurrentIndex(mActions->actions().indexOf(action));
setWindowTitle(action->text());
});
// Add project panel.
QAction *general = toolbar->addAction(QIcon(":/general.png"), tr("General"));
general->setActionGroup(mActions);
general->setCheckable(true);
GeneralPanel *generalPanel = new GeneralPanel(view, this);
mStack->addWidget(generalPanel);
// Add diff panel.
QAction *diff = toolbar->addAction(QIcon(":/diff.png"), tr("Diff"));
diff->setActionGroup(mActions);
diff->setCheckable(true);
DiffPanel *diffPanel = new DiffPanel(view->repo(), this);
mStack->addWidget(diffPanel);
// Add remotes panel.
QAction *remotes = toolbar->addAction(QIcon(":/remotes.png"), tr("Remotes"));
remotes->setActionGroup(mActions);
remotes->setCheckable(true);
mStack->addWidget(new RemotesPanel(view->repo(), this));
// Add branches panel.
QAction *branches =
toolbar->addAction(QIcon(":/branches.png"), tr("Branches"));
branches->setActionGroup(mActions);
branches->setCheckable(true);
mStack->addWidget(new BranchesPanel(view->repo(), this));
// Add submodules panel.
QAction *submodules =
toolbar->addAction(QIcon(":/submodules.png"), tr("Submodules"));
submodules->setActionGroup(mActions);
submodules->setCheckable(true);
mStack->addWidget(new SubmodulesPanel(view, this));
// Add search panel.
QAction *search = toolbar->addAction(QIcon(":/search.png"), tr("Search"));
search->setActionGroup(mActions);
search->setCheckable(true);
mStack->addWidget(new SearchPanel(view, this));
// Add plugins panel.
QAction *plugins = toolbar->addAction(QIcon(":/plugins.png"), tr("Plugins"));
plugins->setActionGroup(mActions);
plugins->setCheckable(true);
mStack->addWidget(new PluginsPanel(view->repo(), this));
// Add LFS panel.
QAction *lfs = toolbar->addAction(QIcon(":/lfs.png"), tr("LFS"));
lfs->setActionGroup(mActions);
lfs->setCheckable(true);
mStack->addWidget(new LfsPanel(view, this));
// Trigger the requested action.
mActions->actions().at(index)->trigger();
QDialogButtonBox *buttons = new QDialogButtonBox(QDialogButtonBox::Ok);
connect(buttons, &QDialogButtonBox::accepted, this, &QDialog::accept);
connect(buttons, &QDialogButtonBox::rejected, this, &QDialog::reject);
// Add edit button.
QPushButton *edit =
buttons->addButton(tr("Edit Config File..."), QDialogButtonBox::ResetRole);
connect(edit, &QPushButton::clicked, this, [this, view, generalPanel] {
QString file = view->repo().dir().filePath("config");
if (EditorWindow *window = view->openEditor(file))
connect(window->widget(), &BlameEditor::saved,
generalPanel, &GeneralPanel::init);
});
// FIXME: Adding the button box directly to the layout
// leaves weird margins at the sides of the dialog.
QVBoxLayout *buttonLayout = new QVBoxLayout;
buttonLayout->setContentsMargins(12,0,12,12);
buttonLayout->addWidget(buttons);
layout->addLayout(buttonLayout);
}
void ConfigDialog::addRemote(const QString &name)
{
mActions->actions().at(Remotes)->trigger();
static_cast<RemotesPanel *>(mStack->currentWidget())->addRemote(name);
}
void ConfigDialog::editBranch(const QString &name)
{
mActions->actions().at(Branches)->trigger();
static_cast<BranchesPanel *>(mStack->currentWidget())->editBranch(name);
}
void ConfigDialog::showEvent(QShowEvent *event)
{
QDialog::showEvent(event);
adjustSize();
}
#include "ConfigDialog.moc"
|
/************************************************************************//**
* @file DatabaseTestPluginsStaticLoader.cpp
* @author Sylvain Doremus
* @version 1.0
* @date 16/06/2014 12:04:46
*
*
* @brief Specialization of CStaticLibLoader for Database needed plugin
*
* @details Loads the static library of the Database needed plugin
*
***************************************************************************/
#include "DatabaseTestPch.h"
#include "DatabaseTestPluginsStaticLoader.h"
#include <DatabasePluginManager.h>
BEGIN_NAMESPACE_DATABASE_TEST
{
CPluginConfigBase::CPluginConfigBase( bool load )
: _load( load )
{
}
#if defined( STATIC_LIB )
template< typename PluginType >
CPluginConfig( bool load )
: CPluginConfigBase( load )
{
}
template< typename PluginType >
void CPluginConfig< PluginType >::Load()
{
if ( _load && !_plugin )
{
//!@remarks Create the plugin.
_plugin = new PluginType;
//!@remarks Register the plugin.
CPluginManager::Instance().InstallPlugin( _plugin );
}
}
template< typename PluginType >
void CPluginConfig< PluginType >::Unload()
{
if ( _plugin )
{
//!@remarks Unregister the plugin.
CPluginManager::Instance().UninstallPlugin( _plugin );
//!@remarks Delete the plugin.
delete _plugin;
_plugin = NULL;
}
}
#else
namespace
{
#if defined( _WIN32 )
static const String LIB_PREFIX;
static const String LIB_EXT = STR( ".dll" );
#else
static const String LIB_PREFIX = STR( "lib" );
static const String LIB_EXT = STR( ".so" );
#endif
#if defined( NDEBUG )
static const String LIB_SUFFIX;
#else
static const String LIB_SUFFIX = "d";
#endif
String GetLibName( const String & name )
{
return LIB_PREFIX + name + LIB_SUFFIX + LIB_EXT;
}
}
CPluginConfig::CPluginConfig( bool load, const String & path, const String & name )
: CPluginConfigBase( load )
, _path( path )
, _plugin( name )
{
}
void CPluginConfig::Load()
{
if ( _load )
{
CPluginManager::Instance().LoadPlugin( _path + GetLibName( _plugin ) );
}
}
void CPluginConfig::Unload()
{
if ( _load )
{
CPluginManager::Instance().UnloadPlugin( _path + GetLibName( _plugin ) );
}
}
#endif
CTestPluginsLoader::CTestPluginsLoader()
: _config()
{
}
CTestPluginsLoader::~CTestPluginsLoader()
{
}
void CTestPluginsLoader::Load( SPluginsConfig && config )
{
#if defined( TESTING_PLUGIN_MYSQL )
_config._mySql = std::move( config._mySql );
#endif
#if defined( TESTING_PLUGIN_SQLITE )
_config._sqlite = std::move( config._sqlite );
#endif
#if defined( TESTING_PLUGIN_ODBC )
_config._odbcMySql = std::move( config._odbcMySql );
_config._odbcMsSql = std::move( config._odbcMsSql );
#endif
#if defined( TESTING_PLUGIN_POSTGRE )
_config._postgreSql = std::move( config._postgreSql );
#endif
OnLoad();
}
void CTestPluginsLoader::Unload()
{
OnUnload();
}
void CTestPluginsLoader::OnLoad()
{
#if defined( TESTING_PLUGIN_MYSQL )
_config._mySql->Load();
#endif
#if defined( TESTING_PLUGIN_SQLITE )
_config._sqlite->Load();
#endif
#if defined( TESTING_PLUGIN_ODBC )
_config._odbcMySql->Load();
_config._odbcMsSql->Load();
#endif
#if defined( TESTING_PLUGIN_POSTGRE )
_config._postgreSql->Load();
#endif
}
void CTestPluginsLoader::OnUnload()
{
#if defined( TESTING_PLUGIN_MYSQL )
_config._mySql->Unload();
#endif
#if defined( TESTING_PLUGIN_SQLITE )
_config._sqlite->Unload();
#endif
#if defined( TESTING_PLUGIN_ODBC )
_config._odbcMySql->Unload();
_config._odbcMsSql->Unload();
#endif
#if defined( TESTING_PLUGIN_POSTGRE )
_config._postgreSql->Unload();
#endif
}
}
END_NAMESPACE_DATABASE_TEST
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: UnityEngine.MonoBehaviour
#include "UnityEngine/MonoBehaviour.hpp"
// Including type: DisconnectedReason
#include "GlobalNamespace/DisconnectedReason.hpp"
// Including type: TutorialScenesTransitionSetupDataSO
#include "GlobalNamespace/TutorialScenesTransitionSetupDataSO.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
// Forward declaring type: AppInitScenesTransitionSetupDataContainerSO
class AppInitScenesTransitionSetupDataContainerSO;
// Forward declaring type: StandardLevelScenesTransitionSetupDataSO
class StandardLevelScenesTransitionSetupDataSO;
// Forward declaring type: MultiplayerLevelScenesTransitionSetupDataSO
class MultiplayerLevelScenesTransitionSetupDataSO;
// Forward declaring type: MissionLevelScenesTransitionSetupDataSO
class MissionLevelScenesTransitionSetupDataSO;
// Forward declaring type: CreditsScenesTransitionSetupDataSO
class CreditsScenesTransitionSetupDataSO;
// Forward declaring type: BeatmapEditorScenesTransitionSetupDataSO
class BeatmapEditorScenesTransitionSetupDataSO;
// Forward declaring type: MainSettingsModelSO
class MainSettingsModelSO;
// Forward declaring type: GameScenesManager
class GameScenesManager;
// Forward declaring type: LevelCompletionResults
class LevelCompletionResults;
// Forward declaring type: MultiplayerResultsData
class MultiplayerResultsData;
// Forward declaring type: MissionCompletionResults
class MissionCompletionResults;
// Forward declaring type: IDifficultyBeatmap
class IDifficultyBeatmap;
// Forward declaring type: IPreviewBeatmapLevel
class IPreviewBeatmapLevel;
// Forward declaring type: OverrideEnvironmentSettings
class OverrideEnvironmentSettings;
// Forward declaring type: ColorScheme
class ColorScheme;
// Forward declaring type: GameplayModifiers
class GameplayModifiers;
// Forward declaring type: PlayerSpecificSettings
class PlayerSpecificSettings;
// Forward declaring type: PracticeSettings
class PracticeSettings;
// Forward declaring type: MissionObjective
class MissionObjective;
// Forward declaring type: BeatmapDifficulty
struct BeatmapDifficulty;
// Forward declaring type: BeatmapCharacteristicSO
class BeatmapCharacteristicSO;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Action`2<T1, T2>
template<typename T1, typename T2>
class Action_2;
// Forward declaring type: Action`1<T>
template<typename T>
class Action_1;
// Forward declaring type: Action
class Action;
}
// Forward declaring namespace: Zenject
namespace Zenject {
// Forward declaring type: DiContainer
class DiContainer;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Size: 0x88
#pragma pack(push, 1)
// Autogenerated type: MenuTransitionsHelper
class MenuTransitionsHelper : public UnityEngine::MonoBehaviour {
public:
// Nested type: GlobalNamespace::MenuTransitionsHelper::$$c
class $$c;
// Nested type: GlobalNamespace::MenuTransitionsHelper::$$c__DisplayClass23_0
class $$c__DisplayClass23_0;
// Nested type: GlobalNamespace::MenuTransitionsHelper::$$c__DisplayClass24_0
class $$c__DisplayClass24_0;
// Nested type: GlobalNamespace::MenuTransitionsHelper::$$c__DisplayClass25_0
class $$c__DisplayClass25_0;
// Nested type: GlobalNamespace::MenuTransitionsHelper::$$c__DisplayClass26_0
class $$c__DisplayClass26_0;
// Nested type: GlobalNamespace::MenuTransitionsHelper::$$c__DisplayClass27_0
class $$c__DisplayClass27_0;
// private AppInitScenesTransitionSetupDataContainerSO _appInitScenesTransitionSetupDataContainer
// Size: 0x8
// Offset: 0x18
GlobalNamespace::AppInitScenesTransitionSetupDataContainerSO* appInitScenesTransitionSetupDataContainer;
// Field size check
static_assert(sizeof(GlobalNamespace::AppInitScenesTransitionSetupDataContainerSO*) == 0x8);
// private StandardLevelScenesTransitionSetupDataSO _standardLevelScenesTransitionSetupData
// Size: 0x8
// Offset: 0x20
GlobalNamespace::StandardLevelScenesTransitionSetupDataSO* standardLevelScenesTransitionSetupData;
// Field size check
static_assert(sizeof(GlobalNamespace::StandardLevelScenesTransitionSetupDataSO*) == 0x8);
// private MultiplayerLevelScenesTransitionSetupDataSO _multiplayerLevelScenesTransitionSetupData
// Size: 0x8
// Offset: 0x28
GlobalNamespace::MultiplayerLevelScenesTransitionSetupDataSO* multiplayerLevelScenesTransitionSetupData;
// Field size check
static_assert(sizeof(GlobalNamespace::MultiplayerLevelScenesTransitionSetupDataSO*) == 0x8);
// private MissionLevelScenesTransitionSetupDataSO _missionLevelScenesTransitionSetupData
// Size: 0x8
// Offset: 0x30
GlobalNamespace::MissionLevelScenesTransitionSetupDataSO* missionLevelScenesTransitionSetupData;
// Field size check
static_assert(sizeof(GlobalNamespace::MissionLevelScenesTransitionSetupDataSO*) == 0x8);
// private TutorialScenesTransitionSetupDataSO _tutorialScenesTransitionSetupData
// Size: 0x8
// Offset: 0x38
GlobalNamespace::TutorialScenesTransitionSetupDataSO* tutorialScenesTransitionSetupData;
// Field size check
static_assert(sizeof(GlobalNamespace::TutorialScenesTransitionSetupDataSO*) == 0x8);
// private CreditsScenesTransitionSetupDataSO _creditsScenesTransitionSetupData
// Size: 0x8
// Offset: 0x40
GlobalNamespace::CreditsScenesTransitionSetupDataSO* creditsScenesTransitionSetupData;
// Field size check
static_assert(sizeof(GlobalNamespace::CreditsScenesTransitionSetupDataSO*) == 0x8);
// private BeatmapEditorScenesTransitionSetupDataSO _beatmapEditorScenesTransitionSetupData
// Size: 0x8
// Offset: 0x48
GlobalNamespace::BeatmapEditorScenesTransitionSetupDataSO* beatmapEditorScenesTransitionSetupData;
// Field size check
static_assert(sizeof(GlobalNamespace::BeatmapEditorScenesTransitionSetupDataSO*) == 0x8);
// private MainSettingsModelSO _mainSettingsModel
// Size: 0x8
// Offset: 0x50
GlobalNamespace::MainSettingsModelSO* mainSettingsModel;
// Field size check
static_assert(sizeof(GlobalNamespace::MainSettingsModelSO*) == 0x8);
// [InjectAttribute] Offset: 0xE29458
// private readonly GameScenesManager _gameScenesManager
// Size: 0x8
// Offset: 0x58
GlobalNamespace::GameScenesManager* gameScenesManager;
// Field size check
static_assert(sizeof(GlobalNamespace::GameScenesManager*) == 0x8);
// private System.Action`2<StandardLevelScenesTransitionSetupDataSO,LevelCompletionResults> _standardLevelFinishedCallback
// Size: 0x8
// Offset: 0x60
System::Action_2<GlobalNamespace::StandardLevelScenesTransitionSetupDataSO*, GlobalNamespace::LevelCompletionResults*>* standardLevelFinishedCallback;
// Field size check
static_assert(sizeof(System::Action_2<GlobalNamespace::StandardLevelScenesTransitionSetupDataSO*, GlobalNamespace::LevelCompletionResults*>*) == 0x8);
// private System.Action`2<MultiplayerLevelScenesTransitionSetupDataSO,MultiplayerResultsData> _multiplayerLevelFinishedCallback
// Size: 0x8
// Offset: 0x68
System::Action_2<GlobalNamespace::MultiplayerLevelScenesTransitionSetupDataSO*, GlobalNamespace::MultiplayerResultsData*>* multiplayerLevelFinishedCallback;
// Field size check
static_assert(sizeof(System::Action_2<GlobalNamespace::MultiplayerLevelScenesTransitionSetupDataSO*, GlobalNamespace::MultiplayerResultsData*>*) == 0x8);
// private System.Action`1<DisconnectedReason> _multiplayerDidDisconnectCallback
// Size: 0x8
// Offset: 0x70
System::Action_1<GlobalNamespace::DisconnectedReason>* multiplayerDidDisconnectCallback;
// Field size check
static_assert(sizeof(System::Action_1<GlobalNamespace::DisconnectedReason>*) == 0x8);
// private System.Action`2<MissionLevelScenesTransitionSetupDataSO,MissionCompletionResults> _missionLevelFinishedCallback
// Size: 0x8
// Offset: 0x78
System::Action_2<GlobalNamespace::MissionLevelScenesTransitionSetupDataSO*, GlobalNamespace::MissionCompletionResults*>* missionLevelFinishedCallback;
// Field size check
static_assert(sizeof(System::Action_2<GlobalNamespace::MissionLevelScenesTransitionSetupDataSO*, GlobalNamespace::MissionCompletionResults*>*) == 0x8);
// private System.Action _beatmapEditorFinishedCallback
// Size: 0x8
// Offset: 0x80
System::Action* beatmapEditorFinishedCallback;
// Field size check
static_assert(sizeof(System::Action*) == 0x8);
// Creating value type constructor for type: MenuTransitionsHelper
MenuTransitionsHelper(GlobalNamespace::AppInitScenesTransitionSetupDataContainerSO* appInitScenesTransitionSetupDataContainer_ = {}, GlobalNamespace::StandardLevelScenesTransitionSetupDataSO* standardLevelScenesTransitionSetupData_ = {}, GlobalNamespace::MultiplayerLevelScenesTransitionSetupDataSO* multiplayerLevelScenesTransitionSetupData_ = {}, GlobalNamespace::MissionLevelScenesTransitionSetupDataSO* missionLevelScenesTransitionSetupData_ = {}, GlobalNamespace::TutorialScenesTransitionSetupDataSO* tutorialScenesTransitionSetupData_ = {}, GlobalNamespace::CreditsScenesTransitionSetupDataSO* creditsScenesTransitionSetupData_ = {}, GlobalNamespace::BeatmapEditorScenesTransitionSetupDataSO* beatmapEditorScenesTransitionSetupData_ = {}, GlobalNamespace::MainSettingsModelSO* mainSettingsModel_ = {}, GlobalNamespace::GameScenesManager* gameScenesManager_ = {}, System::Action_2<GlobalNamespace::StandardLevelScenesTransitionSetupDataSO*, GlobalNamespace::LevelCompletionResults*>* standardLevelFinishedCallback_ = {}, System::Action_2<GlobalNamespace::MultiplayerLevelScenesTransitionSetupDataSO*, GlobalNamespace::MultiplayerResultsData*>* multiplayerLevelFinishedCallback_ = {}, System::Action_1<GlobalNamespace::DisconnectedReason>* multiplayerDidDisconnectCallback_ = {}, System::Action_2<GlobalNamespace::MissionLevelScenesTransitionSetupDataSO*, GlobalNamespace::MissionCompletionResults*>* missionLevelFinishedCallback_ = {}, System::Action* beatmapEditorFinishedCallback_ = {}) noexcept : appInitScenesTransitionSetupDataContainer{appInitScenesTransitionSetupDataContainer_}, standardLevelScenesTransitionSetupData{standardLevelScenesTransitionSetupData_}, multiplayerLevelScenesTransitionSetupData{multiplayerLevelScenesTransitionSetupData_}, missionLevelScenesTransitionSetupData{missionLevelScenesTransitionSetupData_}, tutorialScenesTransitionSetupData{tutorialScenesTransitionSetupData_}, creditsScenesTransitionSetupData{creditsScenesTransitionSetupData_}, beatmapEditorScenesTransitionSetupData{beatmapEditorScenesTransitionSetupData_}, mainSettingsModel{mainSettingsModel_}, gameScenesManager{gameScenesManager_}, standardLevelFinishedCallback{standardLevelFinishedCallback_}, multiplayerLevelFinishedCallback{multiplayerLevelFinishedCallback_}, multiplayerDidDisconnectCallback{multiplayerDidDisconnectCallback_}, missionLevelFinishedCallback{missionLevelFinishedCallback_}, beatmapEditorFinishedCallback{beatmapEditorFinishedCallback_} {}
// Deleting conversion operator: operator System::IntPtr
constexpr operator System::IntPtr() const noexcept = delete;
// public System.Void StartStandardLevel(System.String gameMode, IDifficultyBeatmap difficultyBeatmap, IPreviewBeatmapLevel previewBeatmapLevel, OverrideEnvironmentSettings overrideEnvironmentSettings, ColorScheme overrideColorScheme, GameplayModifiers gameplayModifiers, PlayerSpecificSettings playerSpecificSettings, PracticeSettings practiceSettings, System.String backButtonText, System.Boolean useTestNoteCutSoundEffects, System.Action beforeSceneSwitchCallback, System.Action`2<StandardLevelScenesTransitionSetupDataSO,LevelCompletionResults> levelFinishedCallback)
// Offset: 0x10DD160
void StartStandardLevel(::Il2CppString* gameMode, GlobalNamespace::IDifficultyBeatmap* difficultyBeatmap, GlobalNamespace::IPreviewBeatmapLevel* previewBeatmapLevel, GlobalNamespace::OverrideEnvironmentSettings* overrideEnvironmentSettings, GlobalNamespace::ColorScheme* overrideColorScheme, GlobalNamespace::GameplayModifiers* gameplayModifiers, GlobalNamespace::PlayerSpecificSettings* playerSpecificSettings, GlobalNamespace::PracticeSettings* practiceSettings, ::Il2CppString* backButtonText, bool useTestNoteCutSoundEffects, System::Action* beforeSceneSwitchCallback, System::Action_2<GlobalNamespace::StandardLevelScenesTransitionSetupDataSO*, GlobalNamespace::LevelCompletionResults*>* levelFinishedCallback);
// public System.Void StartStandardLevel(System.String gameMode, IDifficultyBeatmap difficultyBeatmap, IPreviewBeatmapLevel previewBeatmapLevel, OverrideEnvironmentSettings overrideEnvironmentSettings, ColorScheme overrideColorScheme, GameplayModifiers gameplayModifiers, PlayerSpecificSettings playerSpecificSettings, PracticeSettings practiceSettings, System.String backButtonText, System.Boolean useTestNoteCutSoundEffects, System.Action beforeSceneSwitchCallback, System.Action`1<Zenject.DiContainer> afterSceneSwitchCallback, System.Action`2<StandardLevelScenesTransitionSetupDataSO,LevelCompletionResults> levelFinishedCallback)
// Offset: 0x10DD19C
void StartStandardLevel(::Il2CppString* gameMode, GlobalNamespace::IDifficultyBeatmap* difficultyBeatmap, GlobalNamespace::IPreviewBeatmapLevel* previewBeatmapLevel, GlobalNamespace::OverrideEnvironmentSettings* overrideEnvironmentSettings, GlobalNamespace::ColorScheme* overrideColorScheme, GlobalNamespace::GameplayModifiers* gameplayModifiers, GlobalNamespace::PlayerSpecificSettings* playerSpecificSettings, GlobalNamespace::PracticeSettings* practiceSettings, ::Il2CppString* backButtonText, bool useTestNoteCutSoundEffects, System::Action* beforeSceneSwitchCallback, System::Action_1<Zenject::DiContainer*>* afterSceneSwitchCallback, System::Action_2<GlobalNamespace::StandardLevelScenesTransitionSetupDataSO*, GlobalNamespace::LevelCompletionResults*>* levelFinishedCallback);
// public System.Void StartMissionLevel(System.String missionId, IDifficultyBeatmap difficultyBeatmap, IPreviewBeatmapLevel previewBeatmapLevel, ColorScheme overrideColorScheme, GameplayModifiers gameplayModifiers, MissionObjective[] missionObjectives, PlayerSpecificSettings playerSpecificSettings, System.Action beforeSceneSwitchCallback, System.Action`2<MissionLevelScenesTransitionSetupDataSO,MissionCompletionResults> levelFinishedCallback)
// Offset: 0x10DD2FC
void StartMissionLevel(::Il2CppString* missionId, GlobalNamespace::IDifficultyBeatmap* difficultyBeatmap, GlobalNamespace::IPreviewBeatmapLevel* previewBeatmapLevel, GlobalNamespace::ColorScheme* overrideColorScheme, GlobalNamespace::GameplayModifiers* gameplayModifiers, ::Array<GlobalNamespace::MissionObjective*>* missionObjectives, GlobalNamespace::PlayerSpecificSettings* playerSpecificSettings, System::Action* beforeSceneSwitchCallback, System::Action_2<GlobalNamespace::MissionLevelScenesTransitionSetupDataSO*, GlobalNamespace::MissionCompletionResults*>* levelFinishedCallback);
// public System.Void StartMultiplayerLevel(System.String gameMode, IPreviewBeatmapLevel previewBeatmapLevel, BeatmapDifficulty beatmapDifficulty, BeatmapCharacteristicSO beatmapCharacteristic, IDifficultyBeatmap difficultyBeatmap, ColorScheme overrideColorScheme, GameplayModifiers gameplayModifiers, PlayerSpecificSettings playerSpecificSettings, PracticeSettings practiceSettings, System.String backButtonText, System.Boolean useTestNoteCutSoundEffects, System.Action beforeSceneSwitchCallback, System.Action`2<MultiplayerLevelScenesTransitionSetupDataSO,MultiplayerResultsData> levelFinishedCallback, System.Action`1<DisconnectedReason> didDisconnectCallback)
// Offset: 0x10DD46C
void StartMultiplayerLevel(::Il2CppString* gameMode, GlobalNamespace::IPreviewBeatmapLevel* previewBeatmapLevel, GlobalNamespace::BeatmapDifficulty beatmapDifficulty, GlobalNamespace::BeatmapCharacteristicSO* beatmapCharacteristic, GlobalNamespace::IDifficultyBeatmap* difficultyBeatmap, GlobalNamespace::ColorScheme* overrideColorScheme, GlobalNamespace::GameplayModifiers* gameplayModifiers, GlobalNamespace::PlayerSpecificSettings* playerSpecificSettings, GlobalNamespace::PracticeSettings* practiceSettings, ::Il2CppString* backButtonText, bool useTestNoteCutSoundEffects, System::Action* beforeSceneSwitchCallback, System::Action_2<GlobalNamespace::MultiplayerLevelScenesTransitionSetupDataSO*, GlobalNamespace::MultiplayerResultsData*>* levelFinishedCallback, System::Action_1<GlobalNamespace::DisconnectedReason>* didDisconnectCallback);
// private System.Void StartMultiplayerLevel(System.String gameMode, IPreviewBeatmapLevel previewBeatmapLevel, BeatmapDifficulty beatmapDifficulty, BeatmapCharacteristicSO beatmapCharacteristic, IDifficultyBeatmap difficultyBeatmap, ColorScheme overrideColorScheme, GameplayModifiers gameplayModifiers, PlayerSpecificSettings playerSpecificSettings, PracticeSettings practiceSettings, System.String backButtonText, System.Boolean useTestNoteCutSoundEffects, System.Action beforeSceneSwitchCallback, System.Action`1<Zenject.DiContainer> afterSceneSwitchCallback, System.Action`2<MultiplayerLevelScenesTransitionSetupDataSO,MultiplayerResultsData> levelFinishedCallback, System.Action`1<DisconnectedReason> didDisconnectCallback)
// Offset: 0x10DD4AC
void StartMultiplayerLevel(::Il2CppString* gameMode, GlobalNamespace::IPreviewBeatmapLevel* previewBeatmapLevel, GlobalNamespace::BeatmapDifficulty beatmapDifficulty, GlobalNamespace::BeatmapCharacteristicSO* beatmapCharacteristic, GlobalNamespace::IDifficultyBeatmap* difficultyBeatmap, GlobalNamespace::ColorScheme* overrideColorScheme, GlobalNamespace::GameplayModifiers* gameplayModifiers, GlobalNamespace::PlayerSpecificSettings* playerSpecificSettings, GlobalNamespace::PracticeSettings* practiceSettings, ::Il2CppString* backButtonText, bool useTestNoteCutSoundEffects, System::Action* beforeSceneSwitchCallback, System::Action_1<Zenject::DiContainer*>* afterSceneSwitchCallback, System::Action_2<GlobalNamespace::MultiplayerLevelScenesTransitionSetupDataSO*, GlobalNamespace::MultiplayerResultsData*>* levelFinishedCallback, System::Action_1<GlobalNamespace::DisconnectedReason>* didDisconnectCallback);
// public System.Void StartTutorial(System.Action beforeSceneSwitchCallback)
// Offset: 0x10D6710
void StartTutorial(System::Action* beforeSceneSwitchCallback);
// public System.Void ShowCredits()
// Offset: 0x10D6820
void ShowCredits();
// public System.Void StartBeatmapEditor(System.Action beatmapEditorFinishedCallback)
// Offset: 0x10D6404
void StartBeatmapEditor(System::Action* beatmapEditorFinishedCallback);
// public System.Void RestartGame(System.Action`1<Zenject.DiContainer> finishCallback)
// Offset: 0x10D6A60
void RestartGame(System::Action_1<Zenject::DiContainer*>* finishCallback);
// private System.Void HandleMainGameSceneDidFinish(StandardLevelScenesTransitionSetupDataSO standardLevelScenesTransitionSetupData, LevelCompletionResults levelCompletionResults)
// Offset: 0x10DD698
void HandleMainGameSceneDidFinish(GlobalNamespace::StandardLevelScenesTransitionSetupDataSO* standardLevelScenesTransitionSetupData, GlobalNamespace::LevelCompletionResults* levelCompletionResults);
// private System.Void HandleMultiplayerLevelDidFinish(MultiplayerLevelScenesTransitionSetupDataSO multiplayerLevelScenesTransitionSetupData, MultiplayerResultsData multiplayerResultsData)
// Offset: 0x10DD7CC
void HandleMultiplayerLevelDidFinish(GlobalNamespace::MultiplayerLevelScenesTransitionSetupDataSO* multiplayerLevelScenesTransitionSetupData, GlobalNamespace::MultiplayerResultsData* multiplayerResultsData);
// private System.Void HandleMultiplayerLevelDidDisconnect(MultiplayerLevelScenesTransitionSetupDataSO multiplayerLevelScenesTransitionSetupData, DisconnectedReason disconnectedReason)
// Offset: 0x10DD968
void HandleMultiplayerLevelDidDisconnect(GlobalNamespace::MultiplayerLevelScenesTransitionSetupDataSO* multiplayerLevelScenesTransitionSetupData, GlobalNamespace::DisconnectedReason disconnectedReason);
// private System.Void HandleMissionLevelSceneDidFinish(MissionLevelScenesTransitionSetupDataSO missionLevelScenesTransitionSetupData, MissionCompletionResults missionCompletionResults)
// Offset: 0x10DDAC4
void HandleMissionLevelSceneDidFinish(GlobalNamespace::MissionLevelScenesTransitionSetupDataSO* missionLevelScenesTransitionSetupData, GlobalNamespace::MissionCompletionResults* missionCompletionResults);
// private System.Void HandleTutorialSceneDidFinish(TutorialScenesTransitionSetupDataSO tutorialSceneTransitionSetupData, TutorialScenesTransitionSetupDataSO/TutorialEndStateType endState)
// Offset: 0x10DDBFC
void HandleTutorialSceneDidFinish(GlobalNamespace::TutorialScenesTransitionSetupDataSO* tutorialSceneTransitionSetupData, GlobalNamespace::TutorialScenesTransitionSetupDataSO::TutorialEndStateType endState);
// private System.Void HandleCreditsSceneDidFinish(CreditsScenesTransitionSetupDataSO creditsSceneTransitionSetupData)
// Offset: 0x10DDD24
void HandleCreditsSceneDidFinish(GlobalNamespace::CreditsScenesTransitionSetupDataSO* creditsSceneTransitionSetupData);
// private System.Void HandleBeatmapEditorSceneDidFinish(BeatmapEditorScenesTransitionSetupDataSO beatmapEditorScenesTransitionSetupData)
// Offset: 0x10DDDD8
void HandleBeatmapEditorSceneDidFinish(GlobalNamespace::BeatmapEditorScenesTransitionSetupDataSO* beatmapEditorScenesTransitionSetupData);
// private System.Void <HandleBeatmapEditorSceneDidFinish>b__29_0(Zenject.DiContainer container)
// Offset: 0x10DDEF4
void $HandleBeatmapEditorSceneDidFinish$b__29_0(Zenject::DiContainer* container);
// public System.Void .ctor()
// Offset: 0x10DDEEC
// Implemented from: UnityEngine.MonoBehaviour
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static MenuTransitionsHelper* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::MenuTransitionsHelper::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<MenuTransitionsHelper*, creationType>()));
}
}; // MenuTransitionsHelper
#pragma pack(pop)
static check_size<sizeof(MenuTransitionsHelper), 128 + sizeof(System::Action*)> __GlobalNamespace_MenuTransitionsHelperSizeCheck;
static_assert(sizeof(MenuTransitionsHelper) == 0x88);
}
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::MenuTransitionsHelper*, "", "MenuTransitionsHelper");
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int X, Y;
cin >> X >> Y;
int flag = 0;
for (int i = 0; i <= X; i++) {
if ((2 * i + 4 * (X - i)) == Y) {
flag = 1;
}
}
if (flag == 0) {
cout << "No" << endl;
} else {
cout << "Yes" << endl;
}
return 0;
}
|
// Copyright (c) 2011-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "overviewpage.h"
#include "ui_overviewpage.h"
#include "popbitunits.h"
#include "clientmodel.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "platformstyle.h"
#include "transactionfilterproxy.h"
#include "transactiontablemodel.h"
#include "walletmodel.h"
#include <QAbstractItemDelegate>
#include <QPainter>
#define DECORATION_SIZE 54
#define NUM_ITEMS 5
class TxViewDelegate : public QAbstractItemDelegate
{
Q_OBJECT
public:
TxViewDelegate(const PlatformStyle *platformStyle):
QAbstractItemDelegate(), unit(PopbitUnits::PBT),
platformStyle(platformStyle)
{
}
inline void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index ) const
{
painter->save();
QIcon icon = qvariant_cast<QIcon>(index.data(TransactionTableModel::RawDecorationRole));
QRect mainRect = option.rect;
QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE));
int xspace = DECORATION_SIZE + 8;
int ypad = 6;
int halfheight = (mainRect.height() - 2*ypad)/2;
QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad, mainRect.width() - xspace, halfheight);
QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, mainRect.width() - xspace, halfheight);
icon = platformStyle->SingleColorIcon(icon);
icon.paint(painter, decorationRect);
QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime();
QString address = index.data(Qt::DisplayRole).toString();
qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong();
bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool();
QVariant value = index.data(Qt::ForegroundRole);
QColor foreground = option.palette.color(QPalette::Text);
if(value.canConvert<QBrush>())
{
QBrush brush = qvariant_cast<QBrush>(value);
foreground = brush.color();
}
painter->setPen(foreground);
QRect boundingRect;
painter->drawText(addressRect, Qt::AlignLeft|Qt::AlignVCenter, address, &boundingRect);
if (index.data(TransactionTableModel::WatchonlyRole).toBool())
{
QIcon iconWatchonly = qvariant_cast<QIcon>(index.data(TransactionTableModel::WatchonlyDecorationRole));
QRect watchonlyRect(boundingRect.right() + 5, mainRect.top()+ypad+halfheight, 16, halfheight);
iconWatchonly.paint(painter, watchonlyRect);
}
if(amount < 0)
{
foreground = COLOR_NEGATIVE;
}
else if(!confirmed)
{
foreground = COLOR_UNCONFIRMED;
}
else
{
foreground = option.palette.color(QPalette::Text);
}
painter->setPen(foreground);
QString amountText = PopbitUnits::formatWithUnit(unit, amount, true, PopbitUnits::separatorAlways);
if(!confirmed)
{
amountText = QString("[") + amountText + QString("]");
}
painter->drawText(amountRect, Qt::AlignRight|Qt::AlignVCenter, amountText);
painter->setPen(option.palette.color(QPalette::Text));
painter->drawText(amountRect, Qt::AlignLeft|Qt::AlignVCenter, GUIUtil::dateTimeStr(date));
painter->restore();
}
inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
return QSize(DECORATION_SIZE, DECORATION_SIZE);
}
int unit;
const PlatformStyle *platformStyle;
};
#include "overviewpage.moc"
OverviewPage::OverviewPage(const PlatformStyle *platformStyle, QWidget *parent) :
QWidget(parent),
ui(new Ui::OverviewPage),
clientModel(0),
walletModel(0),
currentBalance(-1),
currentUnconfirmedBalance(-1),
currentImmatureBalance(-1),
currentWatchOnlyBalance(-1),
currentWatchUnconfBalance(-1),
currentWatchImmatureBalance(-1),
txdelegate(new TxViewDelegate(platformStyle)),
filter(0)
{
ui->setupUi(this);
// use a SingleColorIcon for the "out of sync warning" icon
QIcon icon = platformStyle->SingleColorIcon(":/icons/warning");
icon.addPixmap(icon.pixmap(QSize(64,64), QIcon::Normal), QIcon::Disabled); // also set the disabled icon because we are using a disabled QPushButton to work around missing HiDPI support of QLabel (https://bugreports.qt.io/browse/QTBUG-42503)
ui->labelTransactionsStatus->setIcon(icon);
ui->labelWalletStatus->setIcon(icon);
// Recent transactions
ui->listTransactions->setItemDelegate(txdelegate);
ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE));
ui->listTransactions->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2));
ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false);
connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex)));
// start with displaying the "out of sync" warnings
showOutOfSyncWarning(true);
}
void OverviewPage::handleTransactionClicked(const QModelIndex &index)
{
if(filter)
Q_EMIT transactionClicked(filter->mapToSource(index));
}
OverviewPage::~OverviewPage()
{
delete ui;
}
void OverviewPage::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance)
{
int unit = walletModel->getOptionsModel()->getDisplayUnit();
currentBalance = balance;
currentUnconfirmedBalance = unconfirmedBalance;
currentImmatureBalance = immatureBalance;
currentWatchOnlyBalance = watchOnlyBalance;
currentWatchUnconfBalance = watchUnconfBalance;
currentWatchImmatureBalance = watchImmatureBalance;
ui->labelBalance->setText(PopbitUnits::formatWithUnit(unit, balance, false, PopbitUnits::separatorAlways));
ui->labelUnconfirmed->setText(PopbitUnits::formatWithUnit(unit, unconfirmedBalance, false, PopbitUnits::separatorAlways));
ui->labelImmature->setText(PopbitUnits::formatWithUnit(unit, immatureBalance, false, PopbitUnits::separatorAlways));
ui->labelTotal->setText(PopbitUnits::formatWithUnit(unit, balance + unconfirmedBalance + immatureBalance, false, PopbitUnits::separatorAlways));
ui->labelWatchAvailable->setText(PopbitUnits::formatWithUnit(unit, watchOnlyBalance, false, PopbitUnits::separatorAlways));
ui->labelWatchPending->setText(PopbitUnits::formatWithUnit(unit, watchUnconfBalance, false, PopbitUnits::separatorAlways));
ui->labelWatchImmature->setText(PopbitUnits::formatWithUnit(unit, watchImmatureBalance, false, PopbitUnits::separatorAlways));
ui->labelWatchTotal->setText(PopbitUnits::formatWithUnit(unit, watchOnlyBalance + watchUnconfBalance + watchImmatureBalance, false, PopbitUnits::separatorAlways));
// only show immature (newly mined) balance if it's non-zero, so as not to complicate things
// for the non-mining users
bool showImmature = immatureBalance != 0;
bool showWatchOnlyImmature = watchImmatureBalance != 0;
// for symmetry reasons also show immature label when the watch-only one is shown
ui->labelImmature->setVisible(showImmature || showWatchOnlyImmature);
ui->labelImmatureText->setVisible(showImmature || showWatchOnlyImmature);
ui->labelWatchImmature->setVisible(showWatchOnlyImmature); // show watch-only immature balance
}
// show/hide watch-only labels
void OverviewPage::updateWatchOnlyLabels(bool showWatchOnly)
{
ui->labelSpendable->setVisible(showWatchOnly); // show spendable label (only when watch-only is active)
ui->labelWatchonly->setVisible(showWatchOnly); // show watch-only label
ui->lineWatchBalance->setVisible(showWatchOnly); // show watch-only balance separator line
ui->labelWatchAvailable->setVisible(showWatchOnly); // show watch-only available balance
ui->labelWatchPending->setVisible(showWatchOnly); // show watch-only pending balance
ui->labelWatchTotal->setVisible(showWatchOnly); // show watch-only total balance
if (!showWatchOnly)
ui->labelWatchImmature->hide();
}
void OverviewPage::setClientModel(ClientModel *model)
{
this->clientModel = model;
if(model)
{
// Show warning if this is a prerelease version
connect(model, SIGNAL(alertsChanged(QString)), this, SLOT(updateAlerts(QString)));
updateAlerts(model->getStatusBarWarnings());
}
}
void OverviewPage::setWalletModel(WalletModel *model)
{
this->walletModel = model;
if(model && model->getOptionsModel())
{
// Set up transaction list
filter = new TransactionFilterProxy();
filter->setSourceModel(model->getTransactionTableModel());
filter->setLimit(NUM_ITEMS);
filter->setDynamicSortFilter(true);
filter->setSortRole(Qt::EditRole);
filter->setShowInactive(false);
filter->sort(TransactionTableModel::Status, Qt::DescendingOrder);
ui->listTransactions->setModel(filter);
ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress);
// Keep up to date with wallet
setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance(),
model->getWatchBalance(), model->getWatchUnconfirmedBalance(), model->getWatchImmatureBalance());
connect(model, SIGNAL(balanceChanged(CAmount,CAmount,CAmount,CAmount,CAmount,CAmount)), this, SLOT(setBalance(CAmount,CAmount,CAmount,CAmount,CAmount,CAmount)));
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
updateWatchOnlyLabels(model->haveWatchOnly());
connect(model, SIGNAL(notifyWatchonlyChanged(bool)), this, SLOT(updateWatchOnlyLabels(bool)));
}
// update the display unit, to not use the default ("PBT")
updateDisplayUnit();
}
void OverviewPage::updateDisplayUnit()
{
if(walletModel && walletModel->getOptionsModel())
{
if(currentBalance != -1)
setBalance(currentBalance, currentUnconfirmedBalance, currentImmatureBalance,
currentWatchOnlyBalance, currentWatchUnconfBalance, currentWatchImmatureBalance);
// Update txdelegate->unit with the current unit
txdelegate->unit = walletModel->getOptionsModel()->getDisplayUnit();
ui->listTransactions->update();
}
}
void OverviewPage::updateAlerts(const QString &warnings)
{
this->ui->labelAlerts->setVisible(!warnings.isEmpty());
this->ui->labelAlerts->setText(warnings);
}
void OverviewPage::showOutOfSyncWarning(bool fShow)
{
ui->labelWalletStatus->setVisible(fShow);
ui->labelTransactionsStatus->setVisible(fShow);
}
|
//+--------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1991 - 1992
//
// File: dffuncs.cxx
//
// Contents: Private support functions for the DocFile code
//
// Methods: StartMS
// DeleteContents
//
// History: 11-Dec-91 DrewB Created
//
//---------------------------------------------------------------
#include <dfhead.cxx>
#pragma hdrstop
//+--------------------------------------------------------------
//
// Method: CDocFile::DeleteContents, public
//
// Synopsis: Deletes all entries in a DocFile recursing on entries
// with children
//
// Returns: Appropriate status code
//
// History: 25-Sep-91 DrewB Created
//
//---------------------------------------------------------------
SCODE CDocFile::DeleteContents(void)
{
SCODE sc;
olDebugOut((DEB_ITRACE, "In CDocFile::DeleteContents()\n"));
sc = _stgh.DestroyEntry(NULL);
olDebugOut((DEB_ITRACE, "Out CDocFile::DeleteContents\n"));
return sc;
}
//+--------------------------------------------------------------
//
// Method: CDocFile::ApplyChanges, public
//
// Synopsis: Applies a list of updates to a docfile
// Creates source entries in destination and links
// them to child instances in the given TL
//
// Arguments: [ulChanged] - List of changes
//
// Returns: Appropriate status code
//
// History: 12-Mar-92 DrewB Created
//
//---------------------------------------------------------------
SCODE CDocFile::ApplyChanges(CUpdateList &ulChanged)
{
SCODE sc = S_OK;
CUpdate *pud;
olDebugOut((DEB_ITRACE, "In CDocFile::ApplyChanges(%p)\n",
ulChanged.GetHead()));
for (pud = ulChanged.GetHead(); pud; pud = pud->GetNext())
{
if (pud->IsDelete())
olChk(DestroyEntry(pud->GetOriginalName(), FALSE));
else if (pud->IsRename())
olChk(RenameEntry(pud->GetOriginalName(),
pud->GetCurrentName()));
else
{
olAssert(pud->IsCreate());
olChk(CreateFromUpdate(pud, this, DF_WRITE));
}
}
olDebugOut((DEB_ITRACE, "Out CDocFile::ApplyChanges\n"));
// Fall through
EH_Err:
return sc;
}
//+--------------------------------------------------------------
//
// Member: CDocFile::CopyTo, public
//
// Synopsis: Copies the contents of one DocFile to another
//
// Arguments: [pdfTo] - Destination DocFile
// [dwFlags] - Control flags
// [snbExclude] - Partial instantiation list
//
// Returns: Appropriate status code
//
// History: 26-Sep-91 DrewB Created
//
//---------------------------------------------------------------
SCODE CDocFile::CopyTo(CDocFile *pdfTo,
DWORD dwFlags,
SNBW snbExclude)
{
CDfName dfnKey;
SIterBuffer ib;
PSStream *psstFrom = NULL, *psstTo = NULL;
CDocFile *pdfFromChild = NULL, *pdfToChild = NULL;
DFLUID dlLUID = DF_NOLUID;
SCODE sc;
olDebugOut((DEB_ITRACE, "In CDocFile::CopyTo:%p(%p, %lX, %p)\n", this,
pdfTo, dwFlags, snbExclude));
for (;;)
{
if (FAILED(FindGreaterEntry(&dfnKey, &ib, NULL)))
break;
dfnKey.Set(&ib.dfnName);
switch(REAL_STGTY(ib.type))
{
case STGTY_STORAGE:
// Embedded DocFile, create destination and recurse
olChkTo(EH_pwcsName, GetDocFile(&ib.dfnName, DF_READ, ib.type,
(PDocFile **)&pdfFromChild));
// Destination must be a direct docfile
olChkTo(EH_Get, CDocFile::Reserve(1, BP_TO_P(CDFBasis *, _pdfb)));
olChkTo(EH_Reserve, pdfTo->CreateDocFile(&ib.dfnName, DF_WRITE,
dlLUID, ib.type,
(PDocFile **)&pdfToChild));
if (dwFlags & CDF_EXACT)
pdfToChild->CopyTimesFrom(pdfFromChild);
CLSID clsid;
olChkTo(EH_Create, pdfFromChild->GetClass(&clsid));
olChkTo(EH_Create, pdfToChild->SetClass(clsid));
DWORD grfStateBits;
olChkTo(EH_Create, pdfFromChild->GetStateBits(&grfStateBits));
olChkTo(EH_Create, pdfToChild->SetStateBits(grfStateBits,
0xffffffff));
if ((dwFlags & CDF_ENTRIESONLY) == 0 &&
!(snbExclude && NameInSNB(&ib.dfnName, snbExclude) ==
S_OK))
olChkTo(EH_Create,
pdfFromChild->CopyTo(pdfToChild, dwFlags, NULL));
pdfFromChild->Release();
pdfToChild->Release();
break;
case STGTY_STREAM:
olChkTo(EH_pwcsName, GetStream(&ib.dfnName, DF_READ,
ib.type, &psstFrom));
// Destination must be a direct docfile
olChkTo(EH_Get,
CDirectStream::Reserve(1, BP_TO_P(CDFBasis *, _pdfb)));
olChkTo(EH_Reserve,
pdfTo->CreateStream(&ib.dfnName, DF_WRITE, dlLUID,
ib.type, &psstTo));
if ((dwFlags & CDF_ENTRIESONLY) == 0 &&
!(snbExclude && NameInSNB(&ib.dfnName, snbExclude) ==
S_OK))
olChkTo(EH_Create, CopySStreamToSStream(psstFrom, psstTo));
psstFrom->Release();
psstTo->Release();
break;
default:
olAssert(!aMsg("Unknown entry type in CDocFile::CopyTo"));
break;
}
}
olDebugOut((DEB_ITRACE, "Out CDocFile::CopyTo\n"));
return S_OK;
EH_Create:
if (REAL_STGTY(ib.type) == STGTY_STORAGE && pdfToChild)
pdfToChild->Release();
else if (REAL_STGTY(ib.type) == STGTY_STREAM && psstTo)
psstTo->Release();
olAssert(&ib.dfnName);
olVerSucc(pdfTo->DestroyEntry(&ib.dfnName, TRUE));
goto EH_Get;
EH_Reserve:
if (REAL_STGTY(ib.type) == STGTY_STORAGE)
CDocFile::Unreserve(1, BP_TO_P(CDFBasis *, _pdfb));
else if (REAL_STGTY(ib.type) == STGTY_STREAM)
CDirectStream::Unreserve(1, BP_TO_P(CDFBasis *, _pdfb));
EH_Get:
if (REAL_STGTY(ib.type) == STGTY_STORAGE && pdfFromChild)
pdfFromChild->Release();
else if (REAL_STGTY(ib.type) == STGTY_STREAM && psstFrom)
psstFrom->Release();
EH_pwcsName:
return sc;
}
|
#pragma once
#include <string>
#include "spdlog/spdlog.h"
struct options
{
std::string jsonFilename;
std::string outFilename;
spdlog::level::level_enum loggingLevel;
};
|
//
// detail/scheduler.hpp
// ~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2020 Christopher M. Kohlhoff (chris at kohlhoff dot 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)
//
#ifndef ASIO_DETAIL_SCHEDULER_HPP
#define ASIO_DETAIL_SCHEDULER_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "asio/detail/config.hpp"
#include "asio/error_code.hpp"
#include "asio/execution_context.hpp"
#include "asio/detail/atomic_count.hpp"
#include "asio/detail/conditionally_enabled_event.hpp"
#include "asio/detail/conditionally_enabled_mutex.hpp"
#include "asio/detail/op_queue.hpp"
#include "asio/detail/reactor_fwd.hpp"
#include "asio/detail/scheduler_operation.hpp"
#include "asio/detail/thread.hpp"
#include "asio/detail/thread_context.hpp"
#include "asio/detail/push_options.hpp"
namespace clmdep_asio {
namespace detail {
struct scheduler_thread_info;
class scheduler
: public execution_context_service_base<scheduler>,
public thread_context
{
public:
typedef scheduler_operation operation;
// Constructor. Specifies the number of concurrent threads that are likely to
// run the scheduler. If set to 1 certain optimisation are performed.
ASIO_DECL scheduler(clmdep_asio::execution_context& ctx,
int concurrency_hint = 0, bool own_thread = true);
// Destructor.
ASIO_DECL ~scheduler();
// Destroy all user-defined handler objects owned by the service.
ASIO_DECL void shutdown();
// Initialise the task, if required.
ASIO_DECL void init_task();
// Run the event loop until interrupted or no more work.
ASIO_DECL std::size_t run(clmdep_asio::error_code& ec);
// Run until interrupted or one operation is performed.
ASIO_DECL std::size_t run_one(clmdep_asio::error_code& ec);
// Run until timeout, interrupted, or one operation is performed.
ASIO_DECL std::size_t wait_one(
long usec, clmdep_asio::error_code& ec);
// Poll for operations without blocking.
ASIO_DECL std::size_t poll(clmdep_asio::error_code& ec);
// Poll for one operation without blocking.
ASIO_DECL std::size_t poll_one(clmdep_asio::error_code& ec);
// Interrupt the event processing loop.
ASIO_DECL void stop();
// Determine whether the scheduler is stopped.
ASIO_DECL bool stopped() const;
// Restart in preparation for a subsequent run invocation.
ASIO_DECL void restart();
// Notify that some work has started.
void work_started()
{
++outstanding_work_;
}
// Used to compensate for a forthcoming work_finished call. Must be called
// from within a scheduler-owned thread.
ASIO_DECL void compensating_work_started();
// Notify that some work has finished.
void work_finished()
{
if (--outstanding_work_ == 0)
stop();
}
// Return whether a handler can be dispatched immediately.
bool can_dispatch()
{
return thread_call_stack::contains(this) != 0;
}
// Request invocation of the given operation and return immediately. Assumes
// that work_started() has not yet been called for the operation.
ASIO_DECL void post_immediate_completion(
operation* op, bool is_continuation);
// Request invocation of the given operation and return immediately. Assumes
// that work_started() was previously called for the operation.
ASIO_DECL void post_deferred_completion(operation* op);
// Request invocation of the given operations and return immediately. Assumes
// that work_started() was previously called for each operation.
ASIO_DECL void post_deferred_completions(op_queue<operation>& ops);
// Enqueue the given operation following a failed attempt to dispatch the
// operation for immediate invocation.
ASIO_DECL void do_dispatch(operation* op);
// Process unfinished operations as part of a shutdownoperation. Assumes that
// work_started() was previously called for the operations.
ASIO_DECL void abandon_operations(op_queue<operation>& ops);
// Get the concurrency hint that was used to initialise the scheduler.
int concurrency_hint() const
{
return concurrency_hint_;
}
private:
// The mutex type used by this scheduler.
typedef conditionally_enabled_mutex mutex;
// The event type used by this scheduler.
typedef conditionally_enabled_event event;
// Structure containing thread-specific data.
typedef scheduler_thread_info thread_info;
// Run at most one operation. May block.
ASIO_DECL std::size_t do_run_one(mutex::scoped_lock& lock,
thread_info& this_thread, const clmdep_asio::error_code& ec);
// Run at most one operation with a timeout. May block.
ASIO_DECL std::size_t do_wait_one(mutex::scoped_lock& lock,
thread_info& this_thread, long usec, const clmdep_asio::error_code& ec);
// Poll for at most one operation.
ASIO_DECL std::size_t do_poll_one(mutex::scoped_lock& lock,
thread_info& this_thread, const clmdep_asio::error_code& ec);
// Stop the task and all idle threads.
ASIO_DECL void stop_all_threads(mutex::scoped_lock& lock);
// Wake a single idle thread, or the task, and always unlock the mutex.
ASIO_DECL void wake_one_thread_and_unlock(
mutex::scoped_lock& lock);
// Helper class to run the scheduler in its own thread.
class thread_function;
friend class thread_function;
// Helper class to perform task-related operations on block exit.
struct task_cleanup;
friend struct task_cleanup;
// Helper class to call work-related operations on block exit.
struct work_cleanup;
friend struct work_cleanup;
// Whether to optimise for single-threaded use cases.
const bool one_thread_;
// Mutex to protect access to internal data.
mutable mutex mutex_;
// Event to wake up blocked threads.
event wakeup_event_;
// The task to be run by this service.
reactor* task_;
// Operation object to represent the position of the task in the queue.
struct task_operation : operation
{
task_operation() : operation(0) {}
} task_operation_;
// Whether the task has been interrupted.
bool task_interrupted_;
// The count of unfinished work.
atomic_count outstanding_work_;
// The queue of handlers that are ready to be delivered.
op_queue<operation> op_queue_;
// Flag to indicate that the dispatcher has been stopped.
bool stopped_;
// Flag to indicate that the dispatcher has been shut down.
bool shutdown_;
// The concurrency hint used to initialise the scheduler.
const int concurrency_hint_;
// The thread that is running the scheduler.
clmdep_asio::detail::thread* thread_;
};
} // namespace detail
} // namespace clmdep_asio
#include "asio/detail/pop_options.hpp"
#if defined(ASIO_HEADER_ONLY)
# include "asio/detail/impl/scheduler.ipp"
#endif // defined(ASIO_HEADER_ONLY)
#endif // ASIO_DETAIL_SCHEDULER_HPP
|
// Copyright 2016 Etix Labs
//
// 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 <cachemanager.h>
#include <tasks/creds_attack.h>
namespace etix {
namespace cameradar {
static const std::string no_ids_warning_ =
"The ids.json files' default paths didn't match with the discovered "
"cameras. Either "
"they have custom ids, or your ids.json file does not contain enough "
"default routes. "
"Path dictionary attack is impossible without the credentials.";
// Tries to match the detected combination of Username / Password
// with the camera stream. Creates a resource in the DB upon
// valid discovery
bool
creds_attack::test_ids(const etix::cameradar::stream_model& stream,
const std::string& password,
const std::string& username) const {
bool found = false;
std::string path = stream.service_name + "://";
if (username != "" || password != "") { path += username + ":" + password + "@"; }
path += stream.address + ":" + std::to_string(stream.port) + stream.route;
LOG_INFO_("Testing ids : " + path, "creds_attack");
try {
if (curl_describe(path, true)) {
LOG_INFO_("[FOUND IDS] : " + path, "creds_attack");
found = true;
stream_model newstream{
stream.address, stream.port, username, password,
stream.route, stream.service_name, stream.product, stream.protocol,
stream.state, stream.path_found, true, stream.thumbnail_path
};
if ((*cache)->has_changed(stream)) return true;
(*cache)->update_stream(newstream);
} else {
stream_model newstream{ stream.address, stream.port, username,
password, stream.route, stream.service_name,
stream.product, stream.protocol, stream.state,
stream.path_found, false, stream.thumbnail_path };
if ((*cache)->has_changed(stream)) return true;
(*cache)->update_stream(newstream);
}
} catch (const std::runtime_error& e) {
LOG_DEBUG_("Ids already tested : " + std::string(e.what()), "creds_attack");
}
return found;
}
bool
ids_already_found(std::vector<stream_model> streams, stream_model stream) {
for (const auto& it : streams) {
if ((stream.address == it.address) && (stream.port == it.port) && it.ids_found) return true;
}
return false;
}
bool
creds_attack::attack_camera_creds(const stream_model& stream) const {
for (const auto& username : conf.usernames) {
if (signal_handler::instance().should_stop() != etix::cameradar::stop_priority::running)
break;
for (const auto& password : conf.passwords) {
if (signal_handler::instance().should_stop() != etix::cameradar::stop_priority::running)
break;
if ((*cache)->has_changed(stream)) return true;
if (test_ids(stream, password, username)) return true;
}
}
return false;
}
// Tries to discover the right IDs on all RTSP streams in DB
// Uses the ids.json file to try different combinations
bool
creds_attack::run() const {
std::vector<std::future<bool>> futures;
LOG_INFO_(
"Beginning attack of the credentials , it may "
"take a while.",
"creds_attack");
std::vector<etix::cameradar::stream_model> streams = (*cache)->get_streams();
LOG_DEBUG_("Found " + std::to_string(streams.size()) + " streams in the cache", "creds_attack");
size_t found = 0;
for (const auto& stream : streams) {
if (signal_handler::instance().should_stop() != etix::cameradar::stop_priority::running)
break;
if ((found < streams.size()) && ids_already_found(streams, stream)) {
LOG_INFO_(stream.address +
" : This camera's ids were already discovered in "
"the database. Skipping to "
"the next camera.",
"creds_attack");
++found;
} else {
futures.push_back(
std::async(std::launch::async, &creds_attack::attack_camera_creds, this, stream));
}
}
for (auto& fit : futures) {
if (fit.get()) { ++found; }
}
if (!found) {
LOG_WARN_(no_ids_warning_, "creds_attack");
return false;
} else
LOG_INFO_("Found " + std::to_string(found) + " ids for " + std::to_string(streams.size()) +
" cameras",
"creds_attack");
return true;
}
}
}
|
#include <fstream>
#include <iostream>
#include <iterator>
#include <regex>
#include <vector>
#include <omp.h>
class pargrep {
std::string dir_;
std::regex regexp_;
std::vector<std::string> results_;
public:
pargrep(std::string dir, std::string regexp)
: dir_(std::move(dir)), regexp_(regexp) {
}
void run() {
std::vector<std::string> files {
// TODO use actual files from the provided directory
"pargrep.cc",
"pargrep.cc",
"pargrep.cc",
"pargrep.cc"
};
#pragma omp parallel for
for (int i = 0; i < files.size(); ++i) {
do_one_file(files[i]);
}
std::copy(results_.begin(), results_.end(),
std::ostream_iterator<std::string>(std::cout, "\n"));
}
private:
void do_one_file(std::string const& filename) {
std::cout << omp_get_thread_num() << " " << filename << "\n";
std::string line;
std::ifstream ifs(filename.c_str());
while (std::getline(ifs, line)) {
if (std::regex_search(line, regexp_)) {
results_.push_back(filename + ": " + line);
}
}
}
};
void usage() {
std::cerr << "USAGE: pargrep <directory> <regexp>\n";
exit(1);
}
int main(int argc, char* argv[]) {
if (argc < 3) {
usage();
}
omp_set_num_threads(4);
pargrep grepper(argv[1], argv[2]);
grepper.run();
return 0;
}
|
#ifndef wali_wfa_TRANS_GUARD
#define wali_wfa_TRANS_GUARD 1
/*!
* @author Nicholas Kidd
*/
#include <iostream>
#include "wali/Common.hpp"
#include "wali/Printable.hpp"
#include "wali/Countable.hpp"
#include "wali/Markable.hpp"
#include "wali/SemElem.hpp"
#include "wali/KeyContainer.hpp"
#include "wali/wfa/ITrans.hpp"
// Disable
// warning C4250: 'wali::wfa::Trans' : inherits 'wali::Markable::wali::Markable::mark' via dominance
// for MSVC
#if defined(_MSC_VER)
# pragma warning(push)
# pragma warning(disable: 4250)
#endif
namespace wali
{
namespace wpds {
class Config;
}
namespace wfa
{
class WFA;
class Trans;
/*!
* @class Trans
*
* A Trans is a 4-tuple of from state, stack, to state, and Weight. It
* represents a transition in the WFA.
*
* Markable is to make a Trans able to be placed in a Worklist.
* Countable is for reference counting.
*
* @see Printable
* @see Countable
* @see Markable
* @see Worklist
* @see WFA
* @see sem_elem_t
* @see ref_ptr
*/
class Trans : public ITrans, public Markable
{
//
// Types
//
public:
friend class WFA;
static int numTrans;
//
// Methods
//
public:
/*!
* Construct an empty Trans
*/
Trans();
/*!
* @brief constructor
*
* This is used by WFA when addTrans is called.
*/
Trans( Key from,
Key stack,
Key to,
sem_elem_t se );
Trans( const Trans & t );
Trans( const ITrans & t );
Trans &operator =(const Trans &t);
Trans &operator =(const ITrans &t);
virtual ~Trans();
virtual Trans* copy() const;
virtual Trans* copy(Key f, Key s, Key t) const;
//
// getters (const)
//
/*! @return const Key of from state */
Key from() const throw() {
return kp.first;
}
/*! @return const Key of from state */
Key from_state() const throw() {
return kp.first;
}
/*! @return const Key of stack symbol */
Key stack() const throw() {
return kp.second;
}
/*! @return const Key of to state */
Key to() const throw() {
return toStateKey;
}
/*! @return const Key of to state */
Key to_state() const throw() {
return toStateKey;
}
/*! @return const sem_elem_t of Trans */
virtual const sem_elem_t weight() const throw() {
return se;
}
/*!
* @return const sem_elem_t delta of Trans
*
* delta is used in computing fixpoints
*/
const sem_elem_t getDelta() const throw() {
return delta;
}
ref_ptr<WorklistData> worklistData() const throw() {
return worklist_data;
}
//
// getters (non const)
//
/*! @return Key of from state */
Key from() throw() {
return kp.first;
}
/*! @return Key of from state */
Key from_state()throw() {
return kp.first;
}
/*! @return Key of stack symbol */
Key stack() throw() {
return kp.second;
}
/*! @return Key of to state */
Key to() throw() {
return toStateKey;
}
/*! @return Key of to state */
Key to_state() throw() {
return toStateKey;
}
/*! @return sem_elem_t of Trans */
virtual sem_elem_t weight() throw() {
return se;
}
/*!
* @return sem_elem_t delta of Trans
*
* delta is used in computing fixpoints
*/
sem_elem_t getDelta() throw() {
return delta;
}
//
// setters
//
/*!
* Set weight and delta of this Trans
* to be param [w].
*
* @param sem_elem_t for new weight and delta
*
* @return void
*/
virtual void setWeight( sem_elem_t w ) {
se = w;
delta = w;
}
/*!
* Set the delta value for the Trans.
*/
void setDelta( const sem_elem_t w ) {
delta = w;
}
/*!
* Sets the worklist data
*/
void setWorklistData( ref_ptr<WorklistData> wd ) {
worklist_data = wd;
}
/*!
* Sets the weight of the Trans to be param w.
* The Trans's status will be set to MODIFIED if
* param w != this->weight(). Delta is set accordingly.
*
* @param w the sem_elem_t for the new weight
*/
virtual void combineTrans( ITrans* tp );
/*!
* Return const referenct to this transitions KeyPair
*
* The KeyPair holds the from state and stack symbol.
*
* @see KeyPair
* @return const KeyPair reference
*/
const KeyPair & keypair() const throw()
{
return kp;
}
/*!
* @brief return true if the transition has been modified
*
* A Trans is considered modified if when its weight changes. This
* includes the initial creation of a Trans object. This follows
* from the fact that all Trans can be considered (abstractly)
* created with a weight of ZERO
*
* @return true if this transition has been modified
*/
bool modified() const throw()
{
return (status == MODIFIED);
}
/*!
* @return A null pointer.
*/
wpds::Config* getConfig() const;
/*!
* Set this Trans's Config to c.
* @return void
*/
void setConfig( wpds::Config* c );
/*!
* This is used by (E)WPDS::poststar
* during epsilon-transistion contraction.
* The base case is:
* this->weight()->extend(se)
*/
virtual sem_elem_t poststar_eps_closure( sem_elem_t se );
virtual TaggedWeight apply_post( TaggedWeight tw) const;
virtual TaggedWeight apply_pre( TaggedWeight tw) const;
virtual void applyWeightChanger( util::WeightChanger &wc);
protected:
KeyPair kp;
Key toStateKey;
mutable sem_elem_t se;
sem_elem_t delta;
ref_ptr<WorklistData> worklist_data;
protected: // vars used in Process and not relevant to Trans
status_t status;
/*!
* Used by *WPDS during pre and poststar. This is guaranteed
* to be NULL when not performing a reachability query.
*/
mutable wpds::Config *config;
};
} // namespace wfa
} // namespace wali
// Restore the warning state
#if defined(_MSC_VER)
# pragma warning(pop)
#endif
#endif // wali_wfa_TRANS_GUARD
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2018 The PIVX developers
// Copyright (c) 2018 The Crypto Dezire Cash developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "amount.h"
#include "base58.h"
#include "core_io.h"
#include "init.h"
#include "net.h"
#include "netbase.h"
#include "rpc/server.h"
#include "timedata.h"
#include "util.h"
#include "utilmoneystr.h"
#include "wallet.h"
#include "walletdb.h"
#include "zcdzcchain.h"
#include <stdint.h>
#include "libzerocoin/Coin.h"
#include "spork.h"
#include <boost/algorithm/string.hpp>
#include "primitives/deterministicmint.h"
#include <boost/assign/list_of.hpp>
#include <boost/thread/thread.hpp>
#include <univalue.h>
using namespace std;
using namespace boost;
using namespace boost::assign;
int64_t nWalletUnlockTime;
static CCriticalSection cs_nWalletUnlockTime;
std::string HelpRequiringPassphrase()
{
return pwalletMain && pwalletMain->IsCrypted() ? "\nRequires wallet passphrase to be set with walletpassphrase call." : "";
}
void EnsureWalletIsUnlocked(bool fAllowAnonOnly)
{
if (pwalletMain->IsLocked() || (!fAllowAnonOnly && pwalletMain->fWalletUnlockAnonymizeOnly))
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
}
void EnsureEnoughCryptoDezireCash(CAmount total)
{
CAmount nBalance = pwalletMain->GetBalance();
if (total > nBalance) {
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Error: Not enough funds in wallet or account");
}
}
void WalletTxToJSON(const CWalletTx& wtx, UniValue& entry)
{
int confirms = wtx.GetDepthInMainChain(false);
int confirmsTotal = GetIXConfirmations(wtx.GetHash()) + confirms;
entry.push_back(Pair("confirmations", confirmsTotal));
entry.push_back(Pair("bcconfirmations", confirms));
if (wtx.IsCoinBase() || wtx.IsCoinStake())
entry.push_back(Pair("generated", true));
if (confirms > 0) {
entry.push_back(Pair("blockhash", wtx.hashBlock.GetHex()));
entry.push_back(Pair("blockindex", wtx.nIndex));
entry.push_back(Pair("blocktime", mapBlockIndex[wtx.hashBlock]->GetBlockTime()));
}
uint256 hash = wtx.GetHash();
entry.push_back(Pair("txid", hash.GetHex()));
UniValue conflicts(UniValue::VARR);
BOOST_FOREACH (const uint256& conflict, wtx.GetConflicts())
conflicts.push_back(conflict.GetHex());
entry.push_back(Pair("walletconflicts", conflicts));
entry.push_back(Pair("time", wtx.GetTxTime()));
entry.push_back(Pair("timereceived", (int64_t)wtx.nTimeReceived));
BOOST_FOREACH (const PAIRTYPE(string, string) & item, wtx.mapValue)
entry.push_back(Pair(item.first, item.second));
}
string AccountFromValue(const UniValue& value)
{
string strAccount = value.get_str();
if (strAccount == "*")
throw JSONRPCError(RPC_WALLET_INVALID_ACCOUNT_NAME, "Invalid account name");
return strAccount;
}
UniValue getnewaddress(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getnewaddress ( \"account\" )\n"
"\nReturns a new Crypto Dezire Cash address for receiving payments.\n"
"If 'account' is specified (recommended), it is added to the address book \n"
"so payments received with the address will be credited to 'account'.\n"
"\nArguments:\n"
"1. \"account\" (string, optional) The account name for the address to be linked to. if not provided, the default account \"\" is used. It can also be set to the empty string \"\" to represent the default account. The account does not need to exist, it will be created if there is no account by the given name.\n"
"\nResult:\n"
"\"cryptodezirecashaddress\" (string) The new cryptodezirecash address\n"
"\nExamples:\n" +
HelpExampleCli("getnewaddress", "") + HelpExampleCli("getnewaddress", "\"\"") +
HelpExampleCli("getnewaddress", "\"myaccount\"") + HelpExampleRpc("getnewaddress", "\"myaccount\""));
LOCK2(cs_main, pwalletMain->cs_wallet);
// Parse the account first so we don't generate a key if there's an error
string strAccount;
if (params.size() > 0)
strAccount = AccountFromValue(params[0]);
if (!pwalletMain->IsLocked())
pwalletMain->TopUpKeyPool();
// Generate a new key that is added to wallet
CPubKey newKey;
if (!pwalletMain->GetKeyFromPool(newKey))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
CKeyID keyID = newKey.GetID();
pwalletMain->SetAddressBook(keyID, strAccount, "receive");
return CBitcoinAddress(keyID).ToString();
}
CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew = false)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
CAccount account;
walletdb.ReadAccount(strAccount, account);
bool bKeyUsed = false;
// Check if the current key has been used
if (account.vchPubKey.IsValid()) {
CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID());
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin();
it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid();
++it) {
const CWalletTx& wtx = (*it).second;
BOOST_FOREACH (const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
bKeyUsed = true;
}
}
// Generate a new key
if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed) {
if (!pwalletMain->GetKeyFromPool(account.vchPubKey))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
pwalletMain->SetAddressBook(account.vchPubKey.GetID(), strAccount, "receive");
walletdb.WriteAccount(strAccount, account);
}
return CBitcoinAddress(account.vchPubKey.GetID());
}
UniValue getaccountaddress(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccountaddress \"account\"\n"
"\nReturns the current Crypto Dezire Cash address for receiving payments to this account.\n"
"\nArguments:\n"
"1. \"account\" (string, required) The account name for the address. It can also be set to the empty string \"\" to represent the default account. The account does not need to exist, it will be created and a new address created if there is no account by the given name.\n"
"\nResult:\n"
"\"cryptodezirecashaddress\" (string) The account cryptodezirecash address\n"
"\nExamples:\n" +
HelpExampleCli("getaccountaddress", "") + HelpExampleCli("getaccountaddress", "\"\"") +
HelpExampleCli("getaccountaddress", "\"myaccount\"") + HelpExampleRpc("getaccountaddress", "\"myaccount\""));
LOCK2(cs_main, pwalletMain->cs_wallet);
// Parse the account first so we don't generate a key if there's an error
string strAccount = AccountFromValue(params[0]);
UniValue ret(UniValue::VSTR);
ret = GetAccountAddress(strAccount).ToString();
return ret;
}
UniValue getrawchangeaddress(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getrawchangeaddress\n"
"\nReturns a new Crypto Dezire Cash address, for receiving change.\n"
"This is for use with raw transactions, NOT normal use.\n"
"\nResult:\n"
"\"address\" (string) The address\n"
"\nExamples:\n" +
HelpExampleCli("getrawchangeaddress", "") + HelpExampleRpc("getrawchangeaddress", ""));
LOCK2(cs_main, pwalletMain->cs_wallet);
if (!pwalletMain->IsLocked())
pwalletMain->TopUpKeyPool();
CReserveKey reservekey(pwalletMain);
CPubKey vchPubKey;
if (!reservekey.GetReservedKey(vchPubKey))
throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
reservekey.KeepKey();
CKeyID keyID = vchPubKey.GetID();
return CBitcoinAddress(keyID).ToString();
}
UniValue setaccount(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"setaccount \"cryptodezirecashaddress\" \"account\"\n"
"\nSets the account associated with the given address.\n"
"\nArguments:\n"
"1. \"cryptodezirecashaddress\" (string, required) The cryptodezirecash address to be associated with an account.\n"
"2. \"account\" (string, required) The account to assign the address to.\n"
"\nExamples:\n" +
HelpExampleCli("setaccount", "\"Cf1QqABAiQ17aorbB2WTcWAr6HF6zQRLmV\" \"tabby\"") + HelpExampleRpc("setaccount", "\"Wf1QqABAiQ17aorbB2WTcWAr6HF6zQRLmV\", \"tabby\""));
LOCK2(cs_main, pwalletMain->cs_wallet);
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Crypto Dezire Cash address");
string strAccount;
if (params.size() > 1)
strAccount = AccountFromValue(params[1]);
// Only add the account if the address is yours.
if (IsMine(*pwalletMain, address.Get())) {
// Detect when changing the account of an address that is the 'unused current key' of another account:
if (pwalletMain->mapAddressBook.count(address.Get())) {
string strOldAccount = pwalletMain->mapAddressBook[address.Get()].name;
if (address == GetAccountAddress(strOldAccount))
GetAccountAddress(strOldAccount, true);
}
pwalletMain->SetAddressBook(address.Get(), strAccount, "receive");
} else
throw JSONRPCError(RPC_MISC_ERROR, "setaccount can only be used with own address");
return NullUniValue;
}
UniValue getaccount(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccount \"cryptodezirecashaddress\"\n"
"\nReturns the account associated with the given address.\n"
"\nArguments:\n"
"1. \"cryptodezirecashaddress\" (string, required) The cryptodezirecash address for account lookup.\n"
"\nResult:\n"
"\"accountname\" (string) the account address\n"
"\nExamples:\n" +
HelpExampleCli("getaccount", "\"Cf1QqABAiQ17aorbB2WTcWAr6HF6zQRLmV\"") + HelpExampleRpc("getaccount", "\"Wf1QqABAiQ17aorbB2WTcWAr6HF6zQRLmV\""));
LOCK2(cs_main, pwalletMain->cs_wallet);
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Crypto Dezire Cash address");
string strAccount;
map<CTxDestination, CAddressBookData>::iterator mi = pwalletMain->mapAddressBook.find(address.Get());
if (mi != pwalletMain->mapAddressBook.end() && !(*mi).second.name.empty())
strAccount = (*mi).second.name;
return strAccount;
}
UniValue getaddressesbyaccount(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaddressesbyaccount \"account\"\n"
"\nReturns the list of addresses for the given account.\n"
"\nArguments:\n"
"1. \"account\" (string, required) The account name.\n"
"\nResult:\n"
"[ (json array of string)\n"
" \"cryptodezirecashaddress\" (string) a cryptodezirecash address associated with the given account\n"
" ,...\n"
"]\n"
"\nExamples:\n" +
HelpExampleCli("getaddressesbyaccount", "\"tabby\"") + HelpExampleRpc("getaddressesbyaccount", "\"tabby\""));
LOCK2(cs_main, pwalletMain->cs_wallet);
string strAccount = AccountFromValue(params[0]);
// Find all addresses that have the given account
UniValue ret(UniValue::VARR);
BOOST_FOREACH (const PAIRTYPE(CBitcoinAddress, CAddressBookData) & item, pwalletMain->mapAddressBook) {
const CBitcoinAddress& address = item.first;
const string& strName = item.second.name;
if (strName == strAccount)
ret.push_back(address.ToString());
}
return ret;
}
void SendMoney(const CTxDestination& address, CAmount nValue, CWalletTx& wtxNew, bool fUseIX = false)
{
// Check amount
if (nValue <= 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid amount");
if (nValue > pwalletMain->GetBalance())
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds");
string strError;
if (pwalletMain->IsLocked()) {
strError = "Error: Wallet locked, unable to create transaction!";
LogPrintf("SendMoney() : %s", strError);
throw JSONRPCError(RPC_WALLET_ERROR, strError);
}
// Parse Crypto Dezire Cash address
CScript scriptPubKey = GetScriptForDestination(address);
// Create and send the transaction
CReserveKey reservekey(pwalletMain);
CAmount nFeeRequired;
if (!pwalletMain->CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired, strError, NULL, ALL_COINS, fUseIX, (CAmount)0)) {
if (nValue + nFeeRequired > pwalletMain->GetBalance())
strError = strprintf("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!", FormatMoney(nFeeRequired));
LogPrintf("SendMoney() : %s\n", strError);
throw JSONRPCError(RPC_WALLET_ERROR, strError);
}
if (!pwalletMain->CommitTransaction(wtxNew, reservekey, (!fUseIX ? "tx" : "ix")))
throw JSONRPCError(RPC_WALLET_ERROR, "Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.");
}
UniValue sendtoaddress(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendtoaddress \"cryptodezirecashaddress\" amount ( \"comment\" \"comment-to\" )\n"
"\nSend an amount to a given address. The amount is a real and is rounded to the nearest 0.00000001\n" +
HelpRequiringPassphrase() + "\n"
"\nArguments:\n"
"1. \"cryptodezirecashaddress\" (string, required) The cryptodezirecash address to send to.\n"
"2. \"amount\" (numeric, required) The amount in CDZC to send. eg 0.1\n"
"3. \"comment\" (string, optional) A comment used to store what the transaction is for. \n"
" This is not part of the transaction, just kept in your wallet.\n"
"4. \"comment-to\" (string, optional) A comment to store the name of the person or organization \n"
" to which you're sending the transaction. This is not part of the \n"
" transaction, just kept in your wallet.\n"
"\nResult:\n"
"\"transactionid\" (string) The transaction id.\n"
"\nExamples:\n" +
HelpExampleCli("sendtoaddress", "\"Cf1QqABAiQ17aorbB2WTcWAr6HF6zQRLmV\" 0.1") +
HelpExampleCli("sendtoaddress", "\"Cf1QqABAiQ17aorbB2WTcWAr6HF6zQRLmV\" 0.1 \"donation\" \"seans outpost\"") +
HelpExampleRpc("sendtoaddress", "\"Cf1QqABAiQ17aorbB2WTcWAr6HF6zQRLmV\", 0.1, \"donation\", \"seans outpost\""));
LOCK2(cs_main, pwalletMain->cs_wallet);
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Crypto Dezire Cash address");
// Amount
CAmount nAmount = AmountFromValue(params[1]);
// Wallet comments
CWalletTx wtx;
if (params.size() > 2 && !params[2].isNull() && !params[2].get_str().empty())
wtx.mapValue["comment"] = params[2].get_str();
if (params.size() > 3 && !params[3].isNull() && !params[3].get_str().empty())
wtx.mapValue["to"] = params[3].get_str();
EnsureWalletIsUnlocked();
SendMoney(address.Get(), nAmount, wtx);
return wtx.GetHash().GetHex();
}
UniValue sendtoaddressix(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendtoaddressix \"cryptodezirecashaddress\" amount ( \"comment\" \"comment-to\" )\n"
"\nSend an amount to a given address. The amount is a real and is rounded to the nearest 0.00000001\n" +
HelpRequiringPassphrase() + "\n"
"\nArguments:\n"
"1. \"cryptodezirecashaddress\" (string, required) The cryptodezirecash address to send to.\n"
"2. \"amount\" (numeric, required) The amount in CDZC to send. eg 0.1\n"
"3. \"comment\" (string, optional) A comment used to store what the transaction is for. \n"
" This is not part of the transaction, just kept in your wallet.\n"
"4. \"comment-to\" (string, optional) A comment to store the name of the person or organization \n"
" to which you're sending the transaction. This is not part of the \n"
" transaction, just kept in your wallet.\n"
"\nResult:\n"
"\"transactionid\" (string) The transaction id.\n"
"\nExamples:\n" +
HelpExampleCli("sendtoaddressix", "\"Cf1QqABAiQ17aorbB2WTcWAr6HF6zQRLmV\" 0.1") +
HelpExampleCli("sendtoaddressix", "\"Cf1QqABAiQ17aorbB2WTcWAr6HF6zQRLmV\" 0.1 \"donation\" \"seans outpost\"") +
HelpExampleRpc("sendtoaddressix", "\"Cf1QqABAiQ17aorbB2WTcWAr6HF6zQRLmV\", 0.1, \"donation\", \"seans outpost\""));
LOCK2(cs_main, pwalletMain->cs_wallet);
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Crypto Dezire Cash address");
// Amount
CAmount nAmount = AmountFromValue(params[1]);
// Wallet comments
CWalletTx wtx;
if (params.size() > 2 && !params[2].isNull() && !params[2].get_str().empty())
wtx.mapValue["comment"] = params[2].get_str();
if (params.size() > 3 && !params[3].isNull() && !params[3].get_str().empty())
wtx.mapValue["to"] = params[3].get_str();
EnsureWalletIsUnlocked();
SendMoney(address.Get(), nAmount, wtx, true);
return wtx.GetHash().GetHex();
}
UniValue listaddressgroupings(const UniValue& params, bool fHelp)
{
if (fHelp)
throw runtime_error(
"listaddressgroupings\n"
"\nLists groups of addresses which have had their common ownership\n"
"made public by common use as inputs or as the resulting change\n"
"in past transactions\n"
"\nResult:\n"
"[\n"
" [\n"
" [\n"
" \"cryptodezirecashaddress\", (string) The cryptodezirecash address\n"
" amount, (numeric) The amount in CDZC\n"
" \"account\" (string, optional) The account\n"
" ]\n"
" ,...\n"
" ]\n"
" ,...\n"
"]\n"
"\nExamples:\n" +
HelpExampleCli("listaddressgroupings", "") + HelpExampleRpc("listaddressgroupings", ""));
LOCK2(cs_main, pwalletMain->cs_wallet);
UniValue jsonGroupings(UniValue::VARR);
map<CTxDestination, CAmount> balances = pwalletMain->GetAddressBalances();
BOOST_FOREACH (set<CTxDestination> grouping, pwalletMain->GetAddressGroupings()) {
UniValue jsonGrouping(UniValue::VARR);
BOOST_FOREACH (CTxDestination address, grouping) {
UniValue addressInfo(UniValue::VARR);
addressInfo.push_back(CBitcoinAddress(address).ToString());
addressInfo.push_back(ValueFromAmount(balances[address]));
{
if (pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get()) != pwalletMain->mapAddressBook.end())
addressInfo.push_back(pwalletMain->mapAddressBook.find(CBitcoinAddress(address).Get())->second.name);
}
jsonGrouping.push_back(addressInfo);
}
jsonGroupings.push_back(jsonGrouping);
}
return jsonGroupings;
}
UniValue signmessage(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"signmessage \"cryptodezirecashaddress\" \"message\"\n"
"\nSign a message with the private key of an address" +
HelpRequiringPassphrase() + "\n"
"\nArguments:\n"
"1. \"cryptodezirecashaddress\" (string, required) The cryptodezirecash address to use for the private key.\n"
"2. \"message\" (string, required) The message to create a signature of.\n"
"\nResult:\n"
"\"signature\" (string) The signature of the message encoded in base 64\n"
"\nExamples:\n"
"\nUnlock the wallet for 30 seconds\n" +
HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") +
"\nCreate the signature\n" +
HelpExampleCli("signmessage", "\"Cf1QqABAiQ17aorbB2WTcWAr6HF6zQRLmV\" \"my message\"") +
"\nVerify the signature\n" +
HelpExampleCli("verifymessage", "\"Cf1QqABAiQ17aorbB2WTcWAr6HF6zQRLmV\" \"signature\" \"my message\"") +
"\nAs json rpc\n" +
HelpExampleRpc("signmessage", "\"Cf1QqABAiQ17aorbB2WTcWAr6HF6zQRLmV\", \"my message\""));
LOCK2(cs_main, pwalletMain->cs_wallet);
EnsureWalletIsUnlocked();
string strAddress = params[0].get_str();
string strMessage = params[1].get_str();
CBitcoinAddress addr(strAddress);
if (!addr.IsValid())
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
CKeyID keyID;
if (!addr.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
CKey key;
if (!pwalletMain->GetKey(keyID, key))
throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
vector<unsigned char> vchSig;
if (!key.SignCompact(ss.GetHash(), vchSig))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
return EncodeBase64(&vchSig[0], vchSig.size());
}
UniValue getreceivedbyaddress(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw std::runtime_error(
"getreceivedbyaddress \"cryptodezirecashaddress\" ( minconf )\n"
"\nReturns the total amount received by the given cryptodezirecashaddress in transactions with at least minconf confirmations.\n"
"\nArguments:\n"
"1. \"cryptodezirecashaddress\" (string, required) The cryptodezirecash address for transactions.\n"
"2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n"
"\nResult:\n"
"amount (numeric) The total amount in CDZC received at this address.\n"
"\nExamples:\n"
"\nThe amount from transactions with at least 1 confirmation\n" +
HelpExampleCli("getreceivedbyaddress", "\"Cf1QqABAiQ17aorbB2WTcWAr6HF6zQRLmV\"") +
"\nThe amount including unconfirmed transactions, zero confirmations\n" +
HelpExampleCli("getreceivedbyaddress", "\"Cf1QqABAiQ17aorbB2WTcWAr6HF6zQRLmV\" 0") +
"\nThe amount with at least 6 confirmation, very safe\n" +
HelpExampleCli("getreceivedbyaddress", "\"Cf1QqABAiQ17aorbB2WTcWAr6HF6zQRLmV\" 6") +
"\nAs a json rpc call\n" +
HelpExampleRpc("getreceivedbyaddress", "\"Cf1QqABAiQ17aorbB2WTcWAr6HF6zQRLmV\", 6"));
LOCK2(cs_main, pwalletMain->cs_wallet);
// cryptodezirecash address
CBitcoinAddress address = CBitcoinAddress(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Crypto Dezire Cash address");
CScript scriptPubKey = GetScriptForDestination(address.Get());
if (!IsMine(*pwalletMain, scriptPubKey))
throw JSONRPCError(RPC_WALLET_ERROR, "Address not found in wallet");
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Tally
CAmount nAmount = 0;
for (std::map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) {
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !IsFinalTx(wtx))
continue;
BOOST_FOREACH (const CTxOut& txout, wtx.vout)
if (txout.scriptPubKey == scriptPubKey)
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
return ValueFromAmount(nAmount);
}
UniValue getreceivedbyaccount(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaccount \"account\" ( minconf )\n"
"\nReturns the total amount received by addresses with <account> in transactions with at least [minconf] confirmations.\n"
"\nArguments:\n"
"1. \"account\" (string, required) The selected account, may be the default account using \"\".\n"
"2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n"
"\nResult:\n"
"amount (numeric) The total amount in CDZC received for this account.\n"
"\nExamples:\n"
"\nAmount received by the default account with at least 1 confirmation\n" +
HelpExampleCli("getreceivedbyaccount", "\"\"") +
"\nAmount received at the tabby account including unconfirmed amounts with zero confirmations\n" +
HelpExampleCli("getreceivedbyaccount", "\"tabby\" 0") +
"\nThe amount with at least 6 confirmation, very safe\n" +
HelpExampleCli("getreceivedbyaccount", "\"tabby\" 6") +
"\nAs a json rpc call\n" +
HelpExampleRpc("getreceivedbyaccount", "\"tabby\", 6"));
LOCK2(cs_main, pwalletMain->cs_wallet);
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
// Get the set of pub keys assigned to account
string strAccount = AccountFromValue(params[0]);
set<CTxDestination> setAddress = pwalletMain->GetAccountAddresses(strAccount);
// Tally
CAmount nAmount = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) {
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !IsFinalTx(wtx))
continue;
BOOST_FOREACH (const CTxOut& txout, wtx.vout) {
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwalletMain, address) && setAddress.count(address))
if (wtx.GetDepthInMainChain() >= nMinDepth)
nAmount += txout.nValue;
}
}
return (double)nAmount / (double)COIN;
}
CAmount GetAccountBalance(CWalletDB& walletdb, const string& strAccount, int nMinDepth, const isminefilter& filter)
{
CAmount nBalance = 0;
// Tally wallet transactions
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) {
const CWalletTx& wtx = (*it).second;
if (!IsFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < 0)
continue;
CAmount nReceived, nSent, nFee;
wtx.GetAccountAmounts(strAccount, nReceived, nSent, nFee, filter);
if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth)
nBalance += nReceived;
nBalance -= nSent + nFee;
}
// Tally internal accounting entries
nBalance += walletdb.GetAccountCreditDebit(strAccount);
return nBalance;
}
CAmount GetAccountBalance(const string& strAccount, int nMinDepth, const isminefilter& filter)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
return GetAccountBalance(walletdb, strAccount, nMinDepth, filter);
}
UniValue getbalance(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"getbalance ( \"account\" minconf includeWatchonly )\n"
"\nIf account is not specified, returns the server's total available balance (excluding zerocoins).\n"
"If account is specified, returns the balance in the account.\n"
"Note that the account \"\" is not the same as leaving the parameter out.\n"
"The server total may be different to the balance in the default \"\" account.\n"
"\nArguments:\n"
"1. \"account\" (string, optional) The selected account, or \"*\" for entire wallet. It may be the default account using \"\".\n"
"2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n"
"3. includeWatchonly (bool, optional, default=false) Also include balance in watchonly addresses (see 'importaddress')\n"
"\nResult:\n"
"amount (numeric) The total amount in CDZC received for this account.\n"
"\nExamples:\n"
"\nThe total amount in the server across all accounts\n" +
HelpExampleCli("getbalance", "") +
"\nThe total amount in the server across all accounts, with at least 5 confirmations\n" +
HelpExampleCli("getbalance", "\"*\" 6") +
"\nThe total amount in the default account with at least 1 confirmation\n" +
HelpExampleCli("getbalance", "\"\"") +
"\nThe total amount in the account named tabby with at least 6 confirmations\n" +
HelpExampleCli("getbalance", "\"tabby\" 6") +
"\nAs a json rpc call\n" +
HelpExampleRpc("getbalance", "\"tabby\", 6"));
LOCK2(cs_main, pwalletMain->cs_wallet);
if (params.size() == 0)
return ValueFromAmount(pwalletMain->GetBalance());
int nMinDepth = 1;
if (params.size() > 1)
nMinDepth = params[1].get_int();
isminefilter filter = ISMINE_SPENDABLE;
if (params.size() > 2)
if (params[2].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
if (params[0].get_str() == "*") {
// Calculate total balance a different way from GetBalance()
// (GetBalance() sums up all unspent TxOuts)
// getbalance and "getbalance * 1 true" should return the same number
CAmount nBalance = 0;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) {
const CWalletTx& wtx = (*it).second;
if (!IsFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < 0)
continue;
CAmount allFee;
string strSentAccount;
list<COutputEntry> listReceived;
list<COutputEntry> listSent;
wtx.GetAmounts(listReceived, listSent, allFee, strSentAccount, filter);
if (wtx.GetDepthInMainChain() >= nMinDepth) {
BOOST_FOREACH (const COutputEntry& r, listReceived)
nBalance += r.amount;
}
BOOST_FOREACH (const COutputEntry& s, listSent)
nBalance -= s.amount;
nBalance -= allFee;
}
return ValueFromAmount(nBalance);
}
string strAccount = AccountFromValue(params[0]);
CAmount nBalance = GetAccountBalance(strAccount, nMinDepth, filter);
return ValueFromAmount(nBalance);
}
UniValue getextendedbalance(const UniValue& params, bool fHelp)
{
if (fHelp || (params.size() > 0))
throw runtime_error(
"getextendedbalance\n"
"\nGet extended balance information.\n"
"\nResult:\n"
"{\n"
" \"blocks\": \"xxx\", (string) The current block height\n"
" \"balance\": \"xxx\", (string) The total CDZC balance\n"
" \"balance_locked\": \"xxx\", (string) The locked CDZC balance\n"
" \"balance_unlocked\": \"xxx\", (string) The unlocked CDZC balance\n"
" \"balance_unconfirmed\": \"xxx\", (string) The unconfirmed CDZC balance\n"
" \"balance_immature\": \"xxx\", (string) The immature CDZC balance\n"
" \"zerocoin_balance\": \"xxx\", (string) The total zCDZC balance\n"
" \"zerocoin_balance_mature\": \"xxx\", (string) The mature zCDZC balance\n"
" \"zerocoin_balance_immature\": \"xxx\", (string) The immature zCDZC balance\n"
" \"watchonly_balance\": \"xxx\", (string) The total watch-only CDZC balance\n"
" \"watchonly_balance_unconfirmed\": \"xxx\", (string) The unconfirmed watch-only CDZC balance\n"
" \"watchonly_balance_immature\": \"xxx\", (string) The immature watch-only CDZC balance\n"
" \"watchonly_balance_locked\": \"xxx\", (string) The locked watch-only CDZC balance\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getextendedbalance", "") + HelpExampleRpc("getextendedbalance", ""));
LOCK2(cs_main, pwalletMain->cs_wallet);
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("blocks", (int)chainActive.Height()));
obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
obj.push_back(Pair("balance_locked", ValueFromAmount(pwalletMain->GetLockedCoins())));
obj.push_back(Pair("balance_unlocked", ValueFromAmount(pwalletMain->GetUnlockedCoins())));
obj.push_back(Pair("balance_unconfirmed", ValueFromAmount(pwalletMain->GetUnconfirmedBalance())));
obj.push_back(Pair("balance_immature", ValueFromAmount(pwalletMain->GetImmatureBalance())));
obj.push_back(Pair("zerocoin_balance", ValueFromAmount(pwalletMain->GetZerocoinBalance(false))));
obj.push_back(Pair("zerocoin_balance_mature", ValueFromAmount(pwalletMain->GetZerocoinBalance(true))));
obj.push_back(Pair("zerocoin_balance_immature", ValueFromAmount(pwalletMain->GetImmatureZerocoinBalance())));
obj.push_back(Pair("watchonly_balance", ValueFromAmount(pwalletMain->GetWatchOnlyBalance())));
obj.push_back(Pair("watchonly_balance_unconfirmed", ValueFromAmount(pwalletMain->GetUnconfirmedWatchOnlyBalance())));
obj.push_back(Pair("watchonly_balance_immature", ValueFromAmount(pwalletMain->GetImmatureWatchOnlyBalance())));
obj.push_back(Pair("watchonly_balance_locked", ValueFromAmount(pwalletMain->GetLockedWatchOnlyBalance())));
return obj;
}
UniValue getunconfirmedbalance(const UniValue ¶ms, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"getunconfirmedbalance\n"
"Returns the server's total unconfirmed balance\n");
LOCK2(cs_main, pwalletMain->cs_wallet);
return ValueFromAmount(pwalletMain->GetUnconfirmedBalance());
}
UniValue movecmd(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 5)
throw std::runtime_error(
"move \"fromaccount\" \"toaccount\" amount ( minconf \"comment\" )\n"
"\nMove a specified amount from one account in your wallet to another.\n"
"\nArguments:\n"
"1. \"fromaccount\" (string, required) The name of the account to move funds from. May be the default account using \"\".\n"
"2. \"toaccount\" (string, required) The name of the account to move funds to. May be the default account using \"\".\n"
"3. amount (numeric, required) Quantity of CDZC to move between accounts.\n"
"4. minconf (numeric, optional, default=1) Only use funds with at least this many confirmations.\n"
"5. \"comment\" (string, optional) An optional comment, stored in the wallet only.\n"
"\nResult:\n"
"true|false (boolean) true if successful.\n"
"\nExamples:\n"
"\nMove 0.01 CDZC from the default account to the account named tabby\n" +
HelpExampleCli("move", "\"\" \"tabby\" 0.01") +
"\nMove 0.01 CDZC from timotei to akiko with a comment\n" +
HelpExampleCli("move", "\"timotei\" \"akiko\" 0.01 1 \"happy birthday!\"") +
"\nAs a json rpc call\n" +
HelpExampleRpc("move", "\"timotei\", \"akiko\", 0.01, 1, \"happy birthday!\""));
LOCK2(cs_main, pwalletMain->cs_wallet);
std::string strFrom = AccountFromValue(params[0]);
std::string strTo = AccountFromValue(params[1]);
CAmount nAmount = AmountFromValue(params[2]);
if (params.size() > 3)
// unused parameter, used to be nMinDepth, keep type-checking it though
(void)params[3].get_int();
std::string strComment;
if (params.size() > 4)
strComment = params[4].get_str();
CWalletDB walletdb(pwalletMain->strWalletFile);
if (!walletdb.TxnBegin())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
int64_t nNow = GetAdjustedTime();
// Debit
CAccountingEntry debit;
debit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
debit.strAccount = strFrom;
debit.nCreditDebit = -nAmount;
debit.nTime = nNow;
debit.strOtherAccount = strTo;
debit.strComment = strComment;
pwalletMain->AddAccountingEntry(debit, walletdb);
// Credit
CAccountingEntry credit;
credit.nOrderPos = pwalletMain->IncOrderPosNext(&walletdb);
credit.strAccount = strTo;
credit.nCreditDebit = nAmount;
credit.nTime = nNow;
credit.strOtherAccount = strFrom;
credit.strComment = strComment;
pwalletMain->AddAccountingEntry(credit, walletdb);
if (!walletdb.TxnCommit())
throw JSONRPCError(RPC_DATABASE_ERROR, "database error");
return true;
}
UniValue sendfrom(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 6)
throw runtime_error(
"sendfrom \"fromaccount\" \"tocryptodezirecashaddress\" amount ( minconf \"comment\" \"comment-to\" )\n"
"\nSent an amount from an account to a cryptodezirecash address.\n"
"The amount is a real and is rounded to the nearest 0.00000001." +
HelpRequiringPassphrase() + "\n"
"\nArguments:\n"
"1. \"fromaccount\" (string, required) The name of the account to send funds from. May be the default account using \"\".\n"
"2. \"tocryptodezirecashaddress\" (string, required) The cryptodezirecash address to send funds to.\n"
"3. amount (numeric, required) The amount in CDZC. (transaction fee is added on top).\n"
"4. minconf (numeric, optional, default=1) Only use funds with at least this many confirmations.\n"
"5. \"comment\" (string, optional) A comment used to store what the transaction is for. \n"
" This is not part of the transaction, just kept in your wallet.\n"
"6. \"comment-to\" (string, optional) An optional comment to store the name of the person or organization \n"
" to which you're sending the transaction. This is not part of the transaction, \n"
" it is just kept in your wallet.\n"
"\nResult:\n"
"\"transactionid\" (string) The transaction id.\n"
"\nExamples:\n"
"\nSend 0.01 CDZC from the default account to the address, must have at least 1 confirmation\n" +
HelpExampleCli("sendfrom", "\"\" \"Cf1QqABAiQ17aorbB2WTcWAr6HF6zQRLmV\" 0.01") +
"\nSend 0.01 from the tabby account to the given address, funds must have at least 6 confirmations\n" +
HelpExampleCli("sendfrom", "\"tabby\" \"Cf1QqABAiQ17aorbB2WTcWAr6HF6zQRLmV\" 0.01 6 \"donation\" \"seans outpost\"") +
"\nAs a json rpc call\n" +
HelpExampleRpc("sendfrom", "\"tabby\", \"Cf1QqABAiQ17aorbB2WTcWAr6HF6zQRLmV\", 0.01, 6, \"donation\", \"seans outpost\""));
LOCK2(cs_main, pwalletMain->cs_wallet);
string strAccount = AccountFromValue(params[0]);
CBitcoinAddress address(params[1].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Crypto Dezire Cash address");
CAmount nAmount = AmountFromValue(params[2]);
int nMinDepth = 1;
if (params.size() > 3)
nMinDepth = params[3].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 4 && !params[4].isNull() && !params[4].get_str().empty())
wtx.mapValue["comment"] = params[4].get_str();
if (params.size() > 5 && !params[5].isNull() && !params[5].get_str().empty())
wtx.mapValue["to"] = params[5].get_str();
EnsureWalletIsUnlocked();
// Check funds
CAmount nBalance = GetAccountBalance(strAccount, nMinDepth, ISMINE_SPENDABLE);
if (nAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
SendMoney(address.Get(), nAmount, wtx);
return wtx.GetHash().GetHex();
}
UniValue sendmany(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendmany \"fromaccount\" {\"address\":amount,...} ( minconf \"comment\" )\n"
"\nSend multiple times. Amounts are double-precision floating point numbers." +
HelpRequiringPassphrase() + "\n"
"\nArguments:\n"
"1. \"fromaccount\" (string, required) The account to send the funds from, can be \"\" for the default account\n"
"2. \"amounts\" (string, required) A json object with addresses and amounts\n"
" {\n"
" \"address\":amount (numeric) The cryptodezirecash address is the key, the numeric amount in CDZC is the value\n"
" ,...\n"
" }\n"
"3. minconf (numeric, optional, default=1) Only use the balance confirmed at least this many times.\n"
"4. \"comment\" (string, optional) A comment\n"
"\nResult:\n"
"\"transactionid\" (string) The transaction id for the send. Only 1 transaction is created regardless of \n"
" the number of addresses.\n"
"\nExamples:\n"
"\nSend two amounts to two different addresses:\n" +
HelpExampleCli("sendmany", "\"tabby\" \"{\\\"Wf1QqABAiQ17aorbB2WTcWAr6HF6zQRLmV\\\":0.01,\\\"WXUdjGuXGJEWb7YXkBn73Xkdzd6vkwazeo\\\":0.02}\"") +
"\nSend two amounts to two different addresses setting the confirmation and comment:\n" +
HelpExampleCli("sendmany", "\"tabby\" \"{\\\"Wf1QqABAiQ17aorbB2WTcWAr6HF6zQRLmV\\\":0.01,\\\"WXUdjGuXGJEWb7YXkBn73Xkdzd6vkwazeo\\\":0.02}\" 6 \"testing\"") +
"\nAs a json rpc call\n" +
HelpExampleRpc("sendmany", "\"tabby\", \"{\\\"Wf1QqABAiQ17aorbB2WTcWAr6HF6zQRLmV\\\":0.01,\\\"WXUdjGuXGJEWb7YXkBn73Xkdzd6vkwazeo\\\":0.02}\", 6, \"testing\""));
LOCK2(cs_main, pwalletMain->cs_wallet);
string strAccount = AccountFromValue(params[0]);
UniValue sendTo = params[1].get_obj();
int nMinDepth = 1;
if (params.size() > 2)
nMinDepth = params[2].get_int();
CWalletTx wtx;
wtx.strFromAccount = strAccount;
if (params.size() > 3 && !params[3].isNull() && !params[3].get_str().empty())
wtx.mapValue["comment"] = params[3].get_str();
set<CBitcoinAddress> setAddress;
vector<pair<CScript, CAmount> > vecSend;
CAmount totalAmount = 0;
vector<string> keys = sendTo.getKeys();
BOOST_FOREACH(const string& name_, keys) {
CBitcoinAddress address(name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Crypto Dezire Cash address: ")+name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+name_);
setAddress.insert(address);
CScript scriptPubKey = GetScriptForDestination(address.Get());
CAmount nAmount = AmountFromValue(sendTo[name_]);
totalAmount += nAmount;
vecSend.push_back(make_pair(scriptPubKey, nAmount));
}
EnsureWalletIsUnlocked();
// Check funds
CAmount nBalance = GetAccountBalance(strAccount, nMinDepth, ISMINE_SPENDABLE);
if (totalAmount > nBalance)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds");
// Send
CReserveKey keyChange(pwalletMain);
CAmount nFeeRequired = 0;
string strFailReason;
bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, strFailReason);
if (!fCreated)
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strFailReason);
if (!pwalletMain->CommitTransaction(wtx, keyChange))
throw JSONRPCError(RPC_WALLET_ERROR, "Transaction commit failed");
return wtx.GetHash().GetHex();
}
// Defined in rpc/misc.cpp
extern CScript _createmultisig_redeemScript(const UniValue& params);
UniValue addmultisigaddress(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3)
throw runtime_error(
"addmultisigaddress nrequired [\"key\",...] ( \"account\" )\n"
"\nAdd a nrequired-to-sign multisignature address to the wallet.\n"
"Each key is a Crypto Dezire Cash address or hex-encoded public key.\n"
"If 'account' is specified, assign address to that account.\n"
"\nArguments:\n"
"1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n"
"2. \"keysobject\" (string, required) A json array of cryptodezirecash addresses or hex-encoded public keys\n"
" [\n"
" \"address\" (string) cryptodezirecash address or hex-encoded public key\n"
" ...,\n"
" ]\n"
"3. \"account\" (string, optional) An account to assign the addresses to.\n"
"\nResult:\n"
"\"cryptodezirecashaddress\" (string) A cryptodezirecash address associated with the keys.\n"
"\nExamples:\n"
"\nAdd a multisig address from 2 addresses\n" +
HelpExampleCli("addmultisigaddress", "2 \"[\\\"Wf1QqABAiQ17aorbB2WTcWAr6HF6zQRLmV\\\",\\\"WXUdjGuXGJEWb7YXkBn73Xkdzd6vkwazeo\\\"]\"") +
"\nAs json rpc call\n" +
HelpExampleRpc("addmultisigaddress", "2, \"[\\\"Wf1QqABAiQ17aorbB2WTcWAr6HF6zQRLmV\\\",\\\"WXUdjGuXGJEWb7YXkBn73Xkdzd6vkwazeo\\\"]\""));
LOCK2(cs_main, pwalletMain->cs_wallet);
string strAccount;
if (params.size() > 2)
strAccount = AccountFromValue(params[2]);
// Construct using pay-to-script-hash:
CScript inner = _createmultisig_redeemScript(params);
CScriptID innerID(inner);
pwalletMain->AddCScript(inner);
pwalletMain->SetAddressBook(innerID, strAccount, "send");
return CBitcoinAddress(innerID).ToString();
}
struct tallyitem {
CAmount nAmount;
int nConf;
int nBCConf;
vector<uint256> txids;
bool fIsWatchonly;
tallyitem()
{
nAmount = 0;
nConf = std::numeric_limits<int>::max();
nBCConf = std::numeric_limits<int>::max();
fIsWatchonly = false;
}
};
UniValue ListReceived(const UniValue& params, bool fByAccounts)
{
// Minimum confirmations
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
// Whether to include empty accounts
bool fIncludeEmpty = false;
if (params.size() > 1)
fIncludeEmpty = params[1].get_bool();
isminefilter filter = ISMINE_SPENDABLE;
if (params.size() > 2)
if (params[2].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
// Tally
map<CBitcoinAddress, tallyitem> mapTally;
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) {
const CWalletTx& wtx = (*it).second;
if (wtx.IsCoinBase() || !IsFinalTx(wtx))
continue;
int nDepth = wtx.GetDepthInMainChain();
int nBCDepth = wtx.GetDepthInMainChain(false);
if (nDepth < nMinDepth)
continue;
BOOST_FOREACH (const CTxOut& txout, wtx.vout) {
CTxDestination address;
if (!ExtractDestination(txout.scriptPubKey, address))
continue;
isminefilter mine = IsMine(*pwalletMain, address);
if (!(mine & filter))
continue;
tallyitem& item = mapTally[address];
item.nAmount += txout.nValue;
item.nConf = min(item.nConf, nDepth);
item.nBCConf = min(item.nBCConf, nBCDepth);
item.txids.push_back(wtx.GetHash());
if (mine & ISMINE_WATCH_ONLY)
item.fIsWatchonly = true;
}
}
// Reply
UniValue ret(UniValue::VARR);
map<string, tallyitem> mapAccountTally;
BOOST_FOREACH (const PAIRTYPE(CBitcoinAddress, CAddressBookData) & item, pwalletMain->mapAddressBook) {
const CBitcoinAddress& address = item.first;
const string& strAccount = item.second.name;
map<CBitcoinAddress, tallyitem>::iterator it = mapTally.find(address);
if (it == mapTally.end() && !fIncludeEmpty)
continue;
CAmount nAmount = 0;
int nConf = std::numeric_limits<int>::max();
int nBCConf = std::numeric_limits<int>::max();
bool fIsWatchonly = false;
if (it != mapTally.end()) {
nAmount = (*it).second.nAmount;
nConf = (*it).second.nConf;
nBCConf = (*it).second.nBCConf;
fIsWatchonly = (*it).second.fIsWatchonly;
}
if (fByAccounts) {
tallyitem& item = mapAccountTally[strAccount];
item.nAmount += nAmount;
item.nConf = min(item.nConf, nConf);
item.nBCConf = min(item.nBCConf, nBCConf);
item.fIsWatchonly = fIsWatchonly;
} else {
UniValue obj(UniValue::VOBJ);
if (fIsWatchonly)
obj.push_back(Pair("involvesWatchonly", true));
obj.push_back(Pair("address", address.ToString()));
obj.push_back(Pair("account", strAccount));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
obj.push_back(Pair("bcconfirmations", (nBCConf == std::numeric_limits<int>::max() ? 0 : nBCConf)));
UniValue transactions(UniValue::VARR);
if (it != mapTally.end()) {
BOOST_FOREACH (const uint256& item, (*it).second.txids) {
transactions.push_back(item.GetHex());
}
}
obj.push_back(Pair("txids", transactions));
ret.push_back(obj);
}
}
if (fByAccounts) {
for (map<string, tallyitem>::iterator it = mapAccountTally.begin(); it != mapAccountTally.end(); ++it) {
CAmount nAmount = (*it).second.nAmount;
int nConf = (*it).second.nConf;
int nBCConf = (*it).second.nBCConf;
UniValue obj(UniValue::VOBJ);
if ((*it).second.fIsWatchonly)
obj.push_back(Pair("involvesWatchonly", true));
obj.push_back(Pair("account", (*it).first));
obj.push_back(Pair("amount", ValueFromAmount(nAmount)));
obj.push_back(Pair("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf)));
obj.push_back(Pair("bcconfirmations", (nBCConf == std::numeric_limits<int>::max() ? 0 : nBCConf)));
ret.push_back(obj);
}
}
return ret;
}
UniValue listreceivedbyaddress(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"listreceivedbyaddress ( minconf includeempty includeWatchonly)\n"
"\nList balances by receiving address.\n"
"\nArguments:\n"
"1. minconf (numeric, optional, default=1) The minimum number of confirmations before payments are included.\n"
"2. includeempty (numeric, optional, default=false) Whether to include addresses that haven't received any payments.\n"
"3. includeWatchonly (bool, optional, default=false) Whether to include watchonly addresses (see 'importaddress').\n"
"\nResult:\n"
"[\n"
" {\n"
" \"involvesWatchonly\" : \"true\", (bool) Only returned if imported addresses were involved in transaction\n"
" \"address\" : \"receivingaddress\", (string) The receiving address\n"
" \"account\" : \"accountname\", (string) The account of the receiving address. The default account is \"\".\n"
" \"amount\" : x.xxx, (numeric) The total amount in CDZC received by the address\n"
" \"confirmations\" : n (numeric) The number of confirmations of the most recent transaction included\n"
" \"bcconfirmations\" : n (numeric) The number of blockchain confirmations of the most recent transaction included\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n" +
HelpExampleCli("listreceivedbyaddress", "") + HelpExampleCli("listreceivedbyaddress", "6 true") + HelpExampleRpc("listreceivedbyaddress", "6, true, true"));
LOCK2(cs_main, pwalletMain->cs_wallet);
return ListReceived(params, false);
}
UniValue listreceivedbyaccount(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"listreceivedbyaccount ( minconf includeempty includeWatchonly)\n"
"\nList balances by account.\n"
"\nArguments:\n"
"1. minconf (numeric, optional, default=1) The minimum number of confirmations before payments are included.\n"
"2. includeempty (boolean, optional, default=false) Whether to include accounts that haven't received any payments.\n"
"3. includeWatchonly (bool, optional, default=false) Whether to include watchonly addresses (see 'importaddress').\n"
"\nResult:\n"
"[\n"
" {\n"
" \"involvesWatchonly\" : \"true\", (bool) Only returned if imported addresses were involved in transaction\n"
" \"account\" : \"accountname\", (string) The account name of the receiving account\n"
" \"amount\" : x.xxx, (numeric) The total amount received by addresses with this account\n"
" \"confirmations\" : n (numeric) The number of confirmations of the most recent transaction included\n"
" \"bcconfirmations\" : n (numeric) The number of blockchain confirmations of the most recent transaction included\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n" +
HelpExampleCli("listreceivedbyaccount", "") + HelpExampleCli("listreceivedbyaccount", "6 true") + HelpExampleRpc("listreceivedbyaccount", "6, true, true"));
LOCK2(cs_main, pwalletMain->cs_wallet);
return ListReceived(params, true);
}
static void MaybePushAddress(UniValue & entry, const CTxDestination &dest)
{
CBitcoinAddress addr;
if (addr.Set(dest))
entry.push_back(Pair("address", addr.ToString()));
}
void ListTransactions(const CWalletTx& wtx, const string& strAccount, int nMinDepth, bool fLong, UniValue& ret, const isminefilter& filter)
{
CAmount nFee;
string strSentAccount;
list<COutputEntry> listReceived;
list<COutputEntry> listSent;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount, filter);
bool fAllAccounts = (strAccount == string("*"));
bool involvesWatchonly = wtx.IsFromMe(ISMINE_WATCH_ONLY);
// Sent
if ((!listSent.empty() || nFee != 0) && (fAllAccounts || strAccount == strSentAccount)) {
BOOST_FOREACH (const COutputEntry& s, listSent) {
UniValue entry(UniValue::VOBJ);
if (involvesWatchonly || (::IsMine(*pwalletMain, s.destination) & ISMINE_WATCH_ONLY))
entry.push_back(Pair("involvesWatchonly", true));
entry.push_back(Pair("account", strSentAccount));
MaybePushAddress(entry, s.destination);
std::map<std::string, std::string>::const_iterator it = wtx.mapValue.find("DS");
entry.push_back(Pair("category", (it != wtx.mapValue.end() && it->second == "1") ? "darksent" : "send"));
entry.push_back(Pair("amount", ValueFromAmount(-s.amount)));
entry.push_back(Pair("vout", s.vout));
entry.push_back(Pair("fee", ValueFromAmount(-nFee)));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
}
// Received
if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth) {
BOOST_FOREACH (const COutputEntry& r, listReceived) {
string account;
if (pwalletMain->mapAddressBook.count(r.destination))
account = pwalletMain->mapAddressBook[r.destination].name;
if (fAllAccounts || (account == strAccount)) {
UniValue entry(UniValue::VOBJ);
if (involvesWatchonly || (::IsMine(*pwalletMain, r.destination) & ISMINE_WATCH_ONLY))
entry.push_back(Pair("involvesWatchonly", true));
entry.push_back(Pair("account", account));
MaybePushAddress(entry, r.destination);
if (wtx.IsCoinBase()) {
if (wtx.GetDepthInMainChain() < 1)
entry.push_back(Pair("category", "orphan"));
else if (wtx.GetBlocksToMaturity() > 0)
entry.push_back(Pair("category", "immature"));
else
entry.push_back(Pair("category", "generate"));
} else {
entry.push_back(Pair("category", "receive"));
}
entry.push_back(Pair("amount", ValueFromAmount(r.amount)));
entry.push_back(Pair("vout", r.vout));
if (fLong)
WalletTxToJSON(wtx, entry);
ret.push_back(entry);
}
}
}
}
void AcentryToJSON(const CAccountingEntry& acentry, const string& strAccount, UniValue& ret)
{
bool fAllAccounts = (strAccount == string("*"));
if (fAllAccounts || acentry.strAccount == strAccount) {
UniValue entry(UniValue::VOBJ);
entry.push_back(Pair("account", acentry.strAccount));
entry.push_back(Pair("category", "move"));
entry.push_back(Pair("time", acentry.nTime));
entry.push_back(Pair("amount", ValueFromAmount(acentry.nCreditDebit)));
entry.push_back(Pair("otheraccount", acentry.strOtherAccount));
entry.push_back(Pair("comment", acentry.strComment));
ret.push_back(entry);
}
}
UniValue listtransactions(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 4)
throw runtime_error(
"listtransactions ( \"account\" count from includeWatchonly)\n"
"\nReturns up to 'count' most recent transactions skipping the first 'from' transactions for account 'account'.\n"
"\nArguments:\n"
"1. \"account\" (string, optional) The account name. If not included, it will list all transactions for all accounts.\n"
" If \"\" is set, it will list transactions for the default account.\n"
"2. count (numeric, optional, default=10) The number of transactions to return\n"
"3. from (numeric, optional, default=0) The number of transactions to skip\n"
"4. includeWatchonly (bool, optional, default=false) Include transactions to watchonly addresses (see 'importaddress')\n"
"\nResult:\n"
"[\n"
" {\n"
" \"account\":\"accountname\", (string) The account name associated with the transaction. \n"
" It will be \"\" for the default account.\n"
" \"address\":\"cryptodezirecashaddress\", (string) The cryptodezirecash address of the transaction. Not present for \n"
" move transactions (category = move).\n"
" \"category\":\"send|receive|move\", (string) The transaction category. 'move' is a local (off blockchain)\n"
" transaction between accounts, and not associated with an address,\n"
" transaction id or block. 'send' and 'receive' transactions are \n"
" associated with an address, transaction id and block details\n"
" \"amount\": x.xxx, (numeric) The amount in CDZC. This is negative for the 'send' category, and for the\n"
" 'move' category for moves outbound. It is positive for the 'receive' category,\n"
" and for the 'move' category for inbound funds.\n"
" \"vout\" : n, (numeric) the vout value\n"
" \"fee\": x.xxx, (numeric) The amount of the fee in CDZC. This is negative and only available for the \n"
" 'send' category of transactions.\n"
" \"confirmations\": n, (numeric) The number of confirmations for the transaction. Available for 'send' and \n"
" 'receive' category of transactions.\n"
" \"bcconfirmations\": n, (numeric) The number of blockchain confirmations for the transaction. Available for 'send'\n"
" and 'receive' category of transactions.\n"
" \"blockhash\": \"hashvalue\", (string) The block hash containing the transaction. Available for 'send' and 'receive'\n"
" category of transactions.\n"
" \"blockindex\": n, (numeric) The block index containing the transaction. Available for 'send' and 'receive'\n"
" category of transactions.\n"
" \"txid\": \"transactionid\", (string) The transaction id. Available for 'send' and 'receive' category of transactions.\n"
" \"time\": xxx, (numeric) The transaction time in seconds since epoch (midnight Jan 1 1970 GMT).\n"
" \"timereceived\": xxx, (numeric) The time received in seconds since epoch (midnight Jan 1 1970 GMT). Available \n"
" for 'send' and 'receive' category of transactions.\n"
" \"comment\": \"...\", (string) If a comment is associated with the transaction.\n"
" \"otheraccount\": \"accountname\", (string) For the 'move' category of transactions, the account the funds came \n"
" from (for receiving funds, positive amounts), or went to (for sending funds,\n"
" negative amounts).\n"
" }\n"
"]\n"
"\nExamples:\n"
"\nList the most recent 10 transactions in the systems\n" +
HelpExampleCli("listtransactions", "") +
"\nList the most recent 10 transactions for the tabby account\n" +
HelpExampleCli("listtransactions", "\"tabby\"") +
"\nList transactions 100 to 120 from the tabby account\n" +
HelpExampleCli("listtransactions", "\"tabby\" 20 100") +
"\nAs a json rpc call\n" +
HelpExampleRpc("listtransactions", "\"tabby\", 20, 100"));
LOCK2(cs_main, pwalletMain->cs_wallet);
string strAccount = "*";
if (params.size() > 0)
strAccount = params[0].get_str();
int nCount = 10;
if (params.size() > 1)
nCount = params[1].get_int();
int nFrom = 0;
if (params.size() > 2)
nFrom = params[2].get_int();
isminefilter filter = ISMINE_SPENDABLE;
if (params.size() > 3)
if (params[3].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
if (nCount < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count");
if (nFrom < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from");
UniValue ret(UniValue::VARR);
const CWallet::TxItems & txOrdered = pwalletMain->wtxOrdered;
// iterate backwards until we have nCount items to return:
for (CWallet::TxItems::const_reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
CWalletTx* const pwtx = (*it).second.first;
if (pwtx != 0)
ListTransactions(*pwtx, strAccount, 0, true, ret, filter);
CAccountingEntry* const pacentry = (*it).second.second;
if (pacentry != 0)
AcentryToJSON(*pacentry, strAccount, ret);
if ((int)ret.size() >= (nCount + nFrom)) break;
}
// ret is newest to oldest
if (nFrom > (int)ret.size())
nFrom = ret.size();
if ((nFrom + nCount) > (int)ret.size())
nCount = ret.size() - nFrom;
vector<UniValue> arrTmp = ret.getValues();
vector<UniValue>::iterator first = arrTmp.begin();
std::advance(first, nFrom);
vector<UniValue>::iterator last = arrTmp.begin();
std::advance(last, nFrom+nCount);
if (last != arrTmp.end()) arrTmp.erase(last, arrTmp.end());
if (first != arrTmp.begin()) arrTmp.erase(arrTmp.begin(), first);
std::reverse(arrTmp.begin(), arrTmp.end()); // Return oldest to newest
ret.clear();
ret.setArray();
ret.push_backV(arrTmp);
return ret;
}
UniValue listaccounts(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"listaccounts ( minconf includeWatchonly)\n"
"\nReturns Object that has account names as keys, account balances as values.\n"
"\nArguments:\n"
"1. minconf (numeric, optional, default=1) Only include transactions with at least this many confirmations\n"
"2. includeWatchonly (bool, optional, default=false) Include balances in watchonly addresses (see 'importaddress')\n"
"\nResult:\n"
"{ (json object where keys are account names, and values are numeric balances\n"
" \"account\": x.xxx, (numeric) The property name is the account name, and the value is the total balance for the account.\n"
" ...\n"
"}\n"
"\nExamples:\n"
"\nList account balances where there at least 1 confirmation\n" +
HelpExampleCli("listaccounts", "") +
"\nList account balances including zero confirmation transactions\n" +
HelpExampleCli("listaccounts", "0") +
"\nList account balances for 6 or more confirmations\n" +
HelpExampleCli("listaccounts", "6") +
"\nAs json rpc call\n" +
HelpExampleRpc("listaccounts", "6"));
LOCK2(cs_main, pwalletMain->cs_wallet);
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
isminefilter includeWatchonly = ISMINE_SPENDABLE;
if (params.size() > 1)
if (params[1].get_bool())
includeWatchonly = includeWatchonly | ISMINE_WATCH_ONLY;
map<string, CAmount> mapAccountBalances;
BOOST_FOREACH (const PAIRTYPE(CTxDestination, CAddressBookData) & entry, pwalletMain->mapAddressBook) {
if (IsMine(*pwalletMain, entry.first) & includeWatchonly) // This address belongs to me
mapAccountBalances[entry.second.name] = 0;
}
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); ++it) {
const CWalletTx& wtx = (*it).second;
CAmount nFee;
string strSentAccount;
list<COutputEntry> listReceived;
list<COutputEntry> listSent;
int nDepth = wtx.GetDepthInMainChain();
if (wtx.GetBlocksToMaturity() > 0 || nDepth < 0)
continue;
wtx.GetAmounts(listReceived, listSent, nFee, strSentAccount, includeWatchonly);
mapAccountBalances[strSentAccount] -= nFee;
BOOST_FOREACH (const COutputEntry& s, listSent)
mapAccountBalances[strSentAccount] -= s.amount;
if (nDepth >= nMinDepth) {
BOOST_FOREACH (const COutputEntry& r, listReceived)
if (pwalletMain->mapAddressBook.count(r.destination))
mapAccountBalances[pwalletMain->mapAddressBook[r.destination].name] += r.amount;
else
mapAccountBalances[""] += r.amount;
}
}
const list<CAccountingEntry> & acentries = pwalletMain->laccentries;
BOOST_FOREACH (const CAccountingEntry& entry, acentries)
mapAccountBalances[entry.strAccount] += entry.nCreditDebit;
UniValue ret(UniValue::VOBJ);
BOOST_FOREACH (const PAIRTYPE(string, CAmount) & accountBalance, mapAccountBalances) {
ret.push_back(Pair(accountBalance.first, ValueFromAmount(accountBalance.second)));
}
return ret;
}
UniValue listsinceblock(const UniValue& params, bool fHelp)
{
if (fHelp)
throw runtime_error(
"listsinceblock ( \"blockhash\" target-confirmations includeWatchonly)\n"
"\nGet all transactions in blocks since block [blockhash], or all transactions if omitted\n"
"\nArguments:\n"
"1. \"blockhash\" (string, optional) The block hash to list transactions since\n"
"2. target-confirmations: (numeric, optional) The confirmations required, must be 1 or more\n"
"3. includeWatchonly: (bool, optional, default=false) Include transactions to watchonly addresses (see 'importaddress')"
"\nResult:\n"
"{\n"
" \"transactions\": [\n"
" \"account\":\"accountname\", (string) The account name associated with the transaction. Will be \"\" for the default account.\n"
" \"address\":\"cryptodezirecashaddress\", (string) The cryptodezirecash address of the transaction. Not present for move transactions (category = move).\n"
" \"category\":\"send|receive\", (string) The transaction category. 'send' has negative amounts, 'receive' has positive amounts.\n"
" \"amount\": x.xxx, (numeric) The amount in CDZC. This is negative for the 'send' category, and for the 'move' category for moves \n"
" outbound. It is positive for the 'receive' category, and for the 'move' category for inbound funds.\n"
" \"vout\" : n, (numeric) the vout value\n"
" \"fee\": x.xxx, (numeric) The amount of the fee in CDZC. This is negative and only available for the 'send' category of transactions.\n"
" \"confirmations\": n, (numeric) The number of confirmations for the transaction. Available for 'send' and 'receive' category of transactions.\n"
" \"bcconfirmations\" : n, (numeric) The number of blockchain confirmations for the transaction. Available for 'send' and 'receive' category of transactions.\n"
" \"blockhash\": \"hashvalue\", (string) The block hash containing the transaction. Available for 'send' and 'receive' category of transactions.\n"
" \"blockindex\": n, (numeric) The block index containing the transaction. Available for 'send' and 'receive' category of transactions.\n"
" \"blocktime\": xxx, (numeric) The block time in seconds since epoch (1 Jan 1970 GMT).\n"
" \"txid\": \"transactionid\", (string) The transaction id. Available for 'send' and 'receive' category of transactions.\n"
" \"time\": xxx, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT).\n"
" \"timereceived\": xxx, (numeric) The time received in seconds since epoch (Jan 1 1970 GMT). Available for 'send' and 'receive' category of transactions.\n"
" \"comment\": \"...\", (string) If a comment is associated with the transaction.\n"
" \"to\": \"...\", (string) If a comment to is associated with the transaction.\n"
" ],\n"
" \"lastblock\": \"lastblockhash\" (string) The hash of the last block\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("listsinceblock", "") +
HelpExampleCli("listsinceblock", "\"000000000000000bacf66f7497b7dc45ef753ee9a7d38571037cdb1a57f663ad\" 6") +
HelpExampleRpc("listsinceblock", "\"000000000000000bacf66f7497b7dc45ef753ee9a7d38571037cdb1a57f663ad\", 6"));
LOCK2(cs_main, pwalletMain->cs_wallet);
CBlockIndex* pindex = NULL;
int target_confirms = 1;
isminefilter filter = ISMINE_SPENDABLE;
if (params.size() > 0) {
uint256 blockId = 0;
blockId.SetHex(params[0].get_str());
BlockMap::iterator it = mapBlockIndex.find(blockId);
if (it != mapBlockIndex.end())
pindex = it->second;
}
if (params.size() > 1) {
target_confirms = params[1].get_int();
if (target_confirms < 1)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
}
if (params.size() > 2)
if (params[2].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
int depth = pindex ? (1 + chainActive.Height() - pindex->nHeight) : -1;
UniValue transactions(UniValue::VARR);
for (map<uint256, CWalletTx>::iterator it = pwalletMain->mapWallet.begin(); it != pwalletMain->mapWallet.end(); it++) {
CWalletTx tx = (*it).second;
if (depth == -1 || tx.GetDepthInMainChain(false) < depth)
ListTransactions(tx, "*", 0, true, transactions, filter);
}
CBlockIndex* pblockLast = chainActive[chainActive.Height() + 1 - target_confirms];
uint256 lastblock = pblockLast ? pblockLast->GetBlockHash() : 0;
UniValue ret(UniValue::VOBJ);
ret.push_back(Pair("transactions", transactions));
ret.push_back(Pair("lastblock", lastblock.GetHex()));
return ret;
}
UniValue gettransaction(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"gettransaction \"txid\" ( includeWatchonly )\n"
"\nGet detailed information about in-wallet transaction <txid>\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id\n"
"2. \"includeWatchonly\" (bool, optional, default=false) Whether to include watchonly addresses in balance calculation and details[]\n"
"\nResult:\n"
"{\n"
" \"amount\" : x.xxx, (numeric) The transaction amount in CDZC\n"
" \"confirmations\" : n, (numeric) The number of confirmations\n"
" \"bcconfirmations\" : n, (numeric) The number of blockchain confirmations\n"
" \"blockhash\" : \"hash\", (string) The block hash\n"
" \"blockindex\" : xx, (numeric) The block index\n"
" \"blocktime\" : ttt, (numeric) The time in seconds since epoch (1 Jan 1970 GMT)\n"
" \"txid\" : \"transactionid\", (string) The transaction id.\n"
" \"time\" : ttt, (numeric) The transaction time in seconds since epoch (1 Jan 1970 GMT)\n"
" \"timereceived\" : ttt, (numeric) The time received in seconds since epoch (1 Jan 1970 GMT)\n"
" \"details\" : [\n"
" {\n"
" \"account\" : \"accountname\", (string) The account name involved in the transaction, can be \"\" for the default account.\n"
" \"address\" : \"cryptodezirecashaddress\", (string) The cryptodezirecash address involved in the transaction\n"
" \"category\" : \"send|receive\", (string) The category, either 'send' or 'receive'\n"
" \"amount\" : x.xxx (numeric) The amount in CDZC\n"
" \"vout\" : n, (numeric) the vout value\n"
" }\n"
" ,...\n"
" ],\n"
" \"hex\" : \"data\" (string) Raw data for transaction\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"") +
HelpExampleCli("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\" true") +
HelpExampleRpc("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\""));
LOCK2(cs_main, pwalletMain->cs_wallet);
uint256 hash;
hash.SetHex(params[0].get_str());
isminefilter filter = ISMINE_SPENDABLE;
if (params.size() > 1)
if (params[1].get_bool())
filter = filter | ISMINE_WATCH_ONLY;
UniValue entry(UniValue::VOBJ);
if (!pwalletMain->mapWallet.count(hash))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id");
const CWalletTx& wtx = pwalletMain->mapWallet[hash];
CAmount nCredit = wtx.GetCredit(filter);
CAmount nDebit = wtx.GetDebit(filter);
CAmount nNet = nCredit - nDebit;
CAmount nFee = (wtx.IsFromMe(filter) ? wtx.GetValueOut() - nDebit : 0);
entry.push_back(Pair("amount", ValueFromAmount(nNet - nFee)));
if (wtx.IsFromMe(filter))
entry.push_back(Pair("fee", ValueFromAmount(nFee)));
WalletTxToJSON(wtx, entry);
UniValue details(UniValue::VARR);
ListTransactions(wtx, "*", 0, false, details, filter);
entry.push_back(Pair("details", details));
string strHex = EncodeHexTx(static_cast<CTransaction>(wtx));
entry.push_back(Pair("hex", strHex));
return entry;
}
UniValue backupwallet(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"backupwallet \"destination\"\n"
"\nSafely copies wallet.dat to destination, which can be a directory or a path with filename.\n"
"\nArguments:\n"
"1. \"destination\" (string) The destination directory or file\n"
"\nExamples:\n" +
HelpExampleCli("backupwallet", "\"backup.dat\"") + HelpExampleRpc("backupwallet", "\"backup.dat\""));
LOCK2(cs_main, pwalletMain->cs_wallet);
string strDest = params[0].get_str();
if (!BackupWallet(*pwalletMain, strDest))
throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!");
return NullUniValue;
}
UniValue keypoolrefill(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"keypoolrefill ( newsize )\n"
"\nFills the keypool." +
HelpRequiringPassphrase() + "\n"
"\nArguments\n"
"1. newsize (numeric, optional, default=100) The new keypool size\n"
"\nExamples:\n" +
HelpExampleCli("keypoolrefill", "") + HelpExampleRpc("keypoolrefill", ""));
LOCK2(cs_main, pwalletMain->cs_wallet);
// 0 is interpreted by TopUpKeyPool() as the default keypool size given by -keypool
unsigned int kpSize = 0;
if (params.size() > 0) {
if (params[0].get_int() < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected valid size.");
kpSize = (unsigned int)params[0].get_int();
}
EnsureWalletIsUnlocked();
pwalletMain->TopUpKeyPool(kpSize);
if (pwalletMain->GetKeyPoolSize() < kpSize)
throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool.");
return NullUniValue;
}
static void LockWallet(CWallet* pWallet)
{
LOCK(cs_nWalletUnlockTime);
nWalletUnlockTime = 0;
pWallet->fWalletUnlockAnonymizeOnly = false;
pWallet->Lock();
}
UniValue walletpassphrase(const UniValue& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() < 2 || params.size() > 3))
throw runtime_error(
"walletpassphrase \"passphrase\" timeout ( anonymizeonly )\n"
"\nStores the wallet decryption key in memory for 'timeout' seconds.\n"
"This is needed prior to performing transactions related to private keys such as sending CDZCs\n"
"\nArguments:\n"
"1. \"passphrase\" (string, required) The wallet passphrase\n"
"2. timeout (numeric, required) The time to keep the decryption key in seconds.\n"
"3. anonymizeonly (boolean, optional, default=false) If is true sending functions are disabled."
"\nNote:\n"
"Issuing the walletpassphrase command while the wallet is already unlocked will set a new unlock\n"
"time that overrides the old one. A timeout of \"0\" unlocks until the wallet is closed.\n"
"\nExamples:\n"
"\nUnlock the wallet for 60 seconds\n" +
HelpExampleCli("walletpassphrase", "\"my pass phrase\" 60") +
"\nUnlock the wallet for 60 seconds but allow anonymization, automint, and staking only\n" +
HelpExampleCli("walletpassphrase", "\"my pass phrase\" 60 true") +
"\nLock the wallet again (before 60 seconds)\n" +
HelpExampleCli("walletlock", "") +
"\nAs json rpc call\n" +
HelpExampleRpc("walletpassphrase", "\"my pass phrase\", 60"));
LOCK2(cs_main, pwalletMain->cs_wallet);
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called.");
// Note that the walletpassphrase is stored in params[0] which is not mlock()ed
SecureString strWalletPass;
strWalletPass.reserve(100);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
strWalletPass = params[0].get_str().c_str();
bool anonymizeOnly = false;
if (params.size() == 3)
anonymizeOnly = params[2].get_bool();
if (!pwalletMain->IsLocked() && pwalletMain->fWalletUnlockAnonymizeOnly && anonymizeOnly)
throw JSONRPCError(RPC_WALLET_ALREADY_UNLOCKED, "Error: Wallet is already unlocked.");
// Get the timeout
int64_t nSleepTime = params[1].get_int64();
// Timeout cannot be negative, otherwise it will relock immediately
if (nSleepTime < 0) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Timeout cannot be negative.");
}
// Clamp timeout
constexpr int64_t MAX_SLEEP_TIME = 100000000; // larger values trigger a macos/libevent bug?
if (nSleepTime > MAX_SLEEP_TIME) {
nSleepTime = MAX_SLEEP_TIME;
}
if (!pwalletMain->Unlock(strWalletPass, anonymizeOnly))
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
pwalletMain->TopUpKeyPool();
if (nSleepTime > 0) {
nWalletUnlockTime = GetTime () + nSleepTime;
RPCRunLater ("lockwallet", boost::bind (LockWallet, pwalletMain), nSleepTime);
}
return NullUniValue;
}
UniValue walletpassphrasechange(const UniValue& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 2))
throw runtime_error(
"walletpassphrasechange \"oldpassphrase\" \"newpassphrase\"\n"
"\nChanges the wallet passphrase from 'oldpassphrase' to 'newpassphrase'.\n"
"\nArguments:\n"
"1. \"oldpassphrase\" (string) The current passphrase\n"
"2. \"newpassphrase\" (string) The new passphrase\n"
"\nExamples:\n" +
HelpExampleCli("walletpassphrasechange", "\"old one\" \"new one\"") + HelpExampleRpc("walletpassphrasechange", "\"old one\", \"new one\""));
LOCK2(cs_main, pwalletMain->cs_wallet);
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called.");
// TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strOldWalletPass;
strOldWalletPass.reserve(100);
strOldWalletPass = params[0].get_str().c_str();
SecureString strNewWalletPass;
strNewWalletPass.reserve(100);
strNewWalletPass = params[1].get_str().c_str();
if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1)
throw runtime_error(
"walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
"Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
if (!pwalletMain->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass))
throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
return NullUniValue;
}
UniValue walletlock(const UniValue& params, bool fHelp)
{
if (pwalletMain->IsCrypted() && (fHelp || params.size() != 0))
throw runtime_error(
"walletlock\n"
"\nRemoves the wallet encryption key from memory, locking the wallet.\n"
"After calling this method, you will need to call walletpassphrase again\n"
"before being able to call any methods which require the wallet to be unlocked.\n"
"\nExamples:\n"
"\nSet the passphrase for 2 minutes to perform a transaction\n" +
HelpExampleCli("walletpassphrase", "\"my pass phrase\" 120") +
"\nPerform a send (requires passphrase set)\n" +
HelpExampleCli("sendtoaddress", "\"Wf1QqABAiQ17aorbB2WTcWAr6HF6zQRLmV\" 1.0") +
"\nClear the passphrase since we are done before 2 minutes is up\n" +
HelpExampleCli("walletlock", "") +
"\nAs json rpc call\n" +
HelpExampleRpc("walletlock", ""));
LOCK2(cs_main, pwalletMain->cs_wallet);
if (fHelp)
return true;
if (!pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called.");
{
LOCK(cs_nWalletUnlockTime);
pwalletMain->Lock();
nWalletUnlockTime = 0;
}
return NullUniValue;
}
UniValue encryptwallet(const UniValue& params, bool fHelp)
{
if (!pwalletMain->IsCrypted() && (fHelp || params.size() != 1))
throw runtime_error(
"encryptwallet \"passphrase\"\n"
"\nEncrypts the wallet with 'passphrase'. This is for first time encryption.\n"
"After this, any calls that interact with private keys such as sending or signing \n"
"will require the passphrase to be set prior the making these calls.\n"
"Use the walletpassphrase call for this, and then walletlock call.\n"
"If the wallet is already encrypted, use the walletpassphrasechange call.\n"
"Note that this will shutdown the server.\n"
"\nArguments:\n"
"1. \"passphrase\" (string) The pass phrase to encrypt the wallet with. It must be at least 1 character, but should be long.\n"
"\nExamples:\n"
"\nEncrypt you wallet\n" +
HelpExampleCli("encryptwallet", "\"my pass phrase\"") +
"\nNow set the passphrase to use the wallet, such as for signing or sending CDZCs\n" +
HelpExampleCli("walletpassphrase", "\"my pass phrase\"") +
"\nNow we can so something like sign\n" +
HelpExampleCli("signmessage", "\"cryptodezirecashaddress\" \"test message\"") +
"\nNow lock the wallet again by removing the passphrase\n" +
HelpExampleCli("walletlock", "") +
"\nAs a json rpc call\n" +
HelpExampleRpc("encryptwallet", "\"my pass phrase\""));
LOCK2(cs_main, pwalletMain->cs_wallet);
if (fHelp)
return true;
if (pwalletMain->IsCrypted())
throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called.");
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make params[0] mlock()'d to begin with.
SecureString strWalletPass;
strWalletPass.reserve(100);
strWalletPass = params[0].get_str().c_str();
if (strWalletPass.length() < 1)
throw runtime_error(
"encryptwallet <passphrase>\n"
"Encrypts the wallet with <passphrase>.");
if (!pwalletMain->EncryptWallet(strWalletPass))
throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet.");
// BDB seems to have a bad habit of writing old data into
// slack space in .dat files; that is bad if the old data is
// unencrypted private keys. So:
StartShutdown();
return "wallet encrypted; cryptodezirecash server stopping, restart to run with encrypted wallet. The keypool has been flushed, you need to make a new backup.";
}
UniValue lockunspent(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"lockunspent unlock [{\"txid\":\"txid\",\"vout\":n},...]\n"
"\nUpdates list of temporarily unspendable outputs.\n"
"Temporarily lock (unlock=false) or unlock (unlock=true) specified transaction outputs.\n"
"A locked transaction output will not be chosen by automatic coin selection, when spending CDZCs.\n"
"Locks are stored in memory only. Nodes start with zero locked outputs, and the locked output list\n"
"is always cleared (by virtue of process exit) when a node stops or fails.\n"
"Also see the listunspent call\n"
"\nArguments:\n"
"1. unlock (boolean, required) Whether to unlock (true) or lock (false) the specified transactions\n"
"2. \"transactions\" (string, required) A json array of objects. Each object the txid (string) vout (numeric)\n"
" [ (json array of json objects)\n"
" {\n"
" \"txid\":\"id\", (string) The transaction id\n"
" \"vout\": n (numeric) The output number\n"
" }\n"
" ,...\n"
" ]\n"
"\nResult:\n"
"true|false (boolean) Whether the command was successful or not\n"
"\nExamples:\n"
"\nList the unspent transactions\n" +
HelpExampleCli("listunspent", "") +
"\nLock an unspent transaction\n" +
HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
"\nList the locked transactions\n" +
HelpExampleCli("listlockunspent", "") +
"\nUnlock the transaction again\n" +
HelpExampleCli("lockunspent", "true \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
"\nAs a json rpc call\n" +
HelpExampleRpc("lockunspent", "false, \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\""));
LOCK2(cs_main, pwalletMain->cs_wallet);
if (params.size() == 1)
RPCTypeCheck(params, boost::assign::list_of(UniValue::VBOOL));
else
RPCTypeCheck(params, boost::assign::list_of(UniValue::VBOOL)(UniValue::VARR));
bool fUnlock = params[0].get_bool();
if (params.size() == 1) {
if (fUnlock)
pwalletMain->UnlockAllCoins();
return true;
}
UniValue outputs = params[1].get_array();
for (unsigned int idx = 0; idx < outputs.size(); idx++) {
const UniValue& output = outputs[idx];
if (!output.isObject())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected object");
const UniValue& o = output.get_obj();
RPCTypeCheckObj(o, boost::assign::map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM));
string txid = find_value(o, "txid").get_str();
if (!IsHex(txid))
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid");
int nOutput = find_value(o, "vout").get_int();
if (nOutput < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
COutPoint outpt(uint256(txid), nOutput);
if (fUnlock)
pwalletMain->UnlockCoin(outpt);
else
pwalletMain->LockCoin(outpt);
}
return true;
}
UniValue listlockunspent(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 0)
throw runtime_error(
"listlockunspent\n"
"\nReturns list of temporarily unspendable outputs.\n"
"See the lockunspent call to lock and unlock transactions for spending.\n"
"\nResult:\n"
"[\n"
" {\n"
" \"txid\" : \"transactionid\", (string) The transaction id locked\n"
" \"vout\" : n (numeric) The vout value\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n"
"\nList the unspent transactions\n" +
HelpExampleCli("listunspent", "") +
"\nLock an unspent transaction\n" +
HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
"\nList the locked transactions\n" +
HelpExampleCli("listlockunspent", "") +
"\nUnlock the transaction again\n" +
HelpExampleCli("lockunspent", "true \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
"\nAs a json rpc call\n" +
HelpExampleRpc("listlockunspent", ""));
LOCK2(cs_main, pwalletMain->cs_wallet);
vector<COutPoint> vOutpts;
pwalletMain->ListLockedCoins(vOutpts);
UniValue ret(UniValue::VARR);
BOOST_FOREACH (COutPoint& outpt, vOutpts) {
UniValue o(UniValue::VOBJ);
o.push_back(Pair("txid", outpt.hash.GetHex()));
o.push_back(Pair("vout", (int)outpt.n));
ret.push_back(o);
}
return ret;
}
UniValue settxfee(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 1)
throw runtime_error(
"settxfee amount\n"
"\nSet the transaction fee per kB.\n"
"\nArguments:\n"
"1. amount (numeric, required) The transaction fee in CDZC/kB rounded to the nearest 0.00000001\n"
"\nResult\n"
"true|false (boolean) Returns true if successful\n"
"\nExamples:\n" +
HelpExampleCli("settxfee", "0.00001") + HelpExampleRpc("settxfee", "0.00001"));
LOCK2(cs_main, pwalletMain->cs_wallet);
// Amount
CAmount nAmount = 0;
if (params[0].get_real() != 0.0)
nAmount = AmountFromValue(params[0]); // rejects 0.0 amounts
payTxFee = CFeeRate(nAmount, 1000);
return true;
}
UniValue getwalletinfo(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getwalletinfo\n"
"Returns an object containing various wallet state info.\n"
"\nResult:\n"
"{\n"
" \"walletversion\": xxxxx, (numeric) the wallet version\n"
" \"balance\": xxxxxxx, (numeric) the total CDZC balance of the wallet\n"
" \"txcount\": xxxxxxx, (numeric) the total number of transactions in the wallet\n"
" \"keypoololdest\": xxxxxx, (numeric) the timestamp (seconds since GMT epoch) of the oldest pre-generated key in the key pool\n"
" \"keypoolsize\": xxxx, (numeric) how many new keys are pre-generated\n"
" \"unlocked_until\": ttt, (numeric) the timestamp in seconds since epoch (midnight Jan 1 1970 GMT) that the wallet is unlocked for transfers, or 0 if the wallet is locked\n"
" \"paytxfee\": x.xxxx, (numeric) the transaction fee configuration, set in CDZC/kB\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("getwalletinfo", "") + HelpExampleRpc("getwalletinfo", ""));
LOCK2(cs_main, pwalletMain->cs_wallet);
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("walletversion", pwalletMain->GetVersion()));
obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
obj.push_back(Pair("txcount", (int)pwalletMain->mapWallet.size()));
obj.push_back(Pair("keypoololdest", pwalletMain->GetOldestKeyPoolTime()));
obj.push_back(Pair("keypoolsize", (int)pwalletMain->GetKeyPoolSize()));
if (pwalletMain->IsCrypted())
obj.push_back(Pair("unlocked_until", nWalletUnlockTime));
obj.push_back(Pair("paytxfee", ValueFromAmount(payTxFee.GetFeePerK())));
return obj;
}
// ppcoin: reserve balance from being staked for network protection
UniValue reservebalance(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"reservebalance ( reserve amount )\n"
"\nShow or set the reserve amount not participating in network protection\n"
"If no parameters provided current setting is printed.\n"
"\nArguments:\n"
"1. reserve (boolean, optional) is true or false to turn balance reserve on or off.\n"
"2. amount (numeric, optional) is a real and rounded to cent.\n"
"\nResult:\n"
"{\n"
" \"reserve\": true|false, (boolean) Status of the reserve balance\n"
" \"amount\": x.xxxx (numeric) Amount reserved\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("reservebalance", "true 5000") + HelpExampleRpc("reservebalance", "true 5000"));
if (params.size() > 0) {
bool fReserve = params[0].get_bool();
if (fReserve) {
if (params.size() == 1)
throw runtime_error("must provide amount to reserve balance.\n");
CAmount nAmount = AmountFromValue(params[1]);
nAmount = (nAmount / CENT) * CENT; // round to cent
if (nAmount < 0)
throw runtime_error("amount cannot be negative.\n");
nReserveBalance = nAmount;
} else {
if (params.size() > 1)
throw runtime_error("cannot specify amount to turn off reserve.\n");
nReserveBalance = 0;
}
}
UniValue result(UniValue::VOBJ);
result.push_back(Pair("reserve", (nReserveBalance > 0)));
result.push_back(Pair("amount", ValueFromAmount(nReserveBalance)));
return result;
}
// presstab HyperStake
UniValue setstakesplitthreshold(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"setstakesplitthreshold value\n"
"\nThis will set the output size of your stakes to never be below this number\n" +
HelpRequiringPassphrase() + "\n"
"\nArguments:\n"
"1. value (numeric, required) Threshold value between 1 and 999999\n"
"\nResult:\n"
"{\n"
" \"threshold\": n, (numeric) Threshold value set\n"
" \"saved\": true|false (boolean) 'true' if successfully saved to the wallet file\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("setstakesplitthreshold", "5000") + HelpExampleRpc("setstakesplitthreshold", "5000"));
EnsureWalletIsUnlocked();
uint64_t nStakeSplitThreshold = params[0].get_int();
if (nStakeSplitThreshold > 999999)
throw runtime_error("Value out of range, max allowed is 999999");
CWalletDB walletdb(pwalletMain->strWalletFile);
LOCK(pwalletMain->cs_wallet);
{
bool fFileBacked = pwalletMain->fFileBacked;
UniValue result(UniValue::VOBJ);
pwalletMain->nStakeSplitThreshold = nStakeSplitThreshold;
result.push_back(Pair("threshold", int(pwalletMain->nStakeSplitThreshold)));
if (fFileBacked) {
walletdb.WriteStakeSplitThreshold(nStakeSplitThreshold);
result.push_back(Pair("saved", "true"));
} else
result.push_back(Pair("saved", "false"));
return result;
}
}
// presstab HyperStake
UniValue getstakesplitthreshold(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getstakesplitthreshold\n"
"Returns the threshold for stake splitting\n"
"\nResult:\n"
"n (numeric) Threshold value\n"
"\nExamples:\n" +
HelpExampleCli("getstakesplitthreshold", "") + HelpExampleRpc("getstakesplitthreshold", ""));
return int(pwalletMain->nStakeSplitThreshold);
}
UniValue autocombinerewards(const UniValue& params, bool fHelp)
{
bool fEnable;
if (params.size() >= 1)
fEnable = params[0].get_bool();
if (fHelp || params.size() < 1 || (fEnable && params.size() != 2) || params.size() > 2)
throw runtime_error(
"autocombinerewards enable ( threshold )\n"
"\nWallet will automatically monitor for any coins with value below the threshold amount, and combine them if they reside with the same Crypto Dezire Cash address\n"
"When autocombinerewards runs it will create a transaction, and therefore will be subject to transaction fees.\n"
"\nArguments:\n"
"1. enable (boolean, required) Enable auto combine (true) or disable (false)\n"
"2. threshold (numeric, optional) Threshold amount (default: 0)\n"
"\nExamples:\n" +
HelpExampleCli("autocombinerewards", "true 500") + HelpExampleRpc("autocombinerewards", "true 500"));
CWalletDB walletdb(pwalletMain->strWalletFile);
CAmount nThreshold = 0;
if (fEnable)
nThreshold = params[1].get_int();
pwalletMain->fCombineDust = fEnable;
pwalletMain->nAutoCombineThreshold = nThreshold;
if (!walletdb.WriteAutoCombineSettings(fEnable, nThreshold))
throw runtime_error("Changed settings in wallet but failed to save to database\n");
return NullUniValue;
}
UniValue printMultiSend()
{
UniValue ret(UniValue::VARR);
UniValue act(UniValue::VOBJ);
act.push_back(Pair("MultiSendStake Activated?", pwalletMain->fMultiSendStake));
act.push_back(Pair("MultiSendMasternode Activated?", pwalletMain->fMultiSendMasternodeReward));
ret.push_back(act);
if (pwalletMain->vDisabledAddresses.size() >= 1) {
UniValue disAdd(UniValue::VOBJ);
for (unsigned int i = 0; i < pwalletMain->vDisabledAddresses.size(); i++) {
disAdd.push_back(Pair("Disabled From Sending", pwalletMain->vDisabledAddresses[i]));
}
ret.push_back(disAdd);
}
ret.push_back("MultiSend Addresses to Send To:");
UniValue vMS(UniValue::VOBJ);
for (unsigned int i = 0; i < pwalletMain->vMultiSend.size(); i++) {
vMS.push_back(Pair("Address " + std::to_string(i), pwalletMain->vMultiSend[i].first));
vMS.push_back(Pair("Percent", pwalletMain->vMultiSend[i].second));
}
ret.push_back(vMS);
return ret;
}
UniValue printAddresses()
{
std::vector<COutput> vCoins;
pwalletMain->AvailableCoins(vCoins);
std::map<std::string, double> mapAddresses;
BOOST_FOREACH (const COutput& out, vCoins) {
CTxDestination utxoAddress;
ExtractDestination(out.tx->vout[out.i].scriptPubKey, utxoAddress);
std::string strAdd = CBitcoinAddress(utxoAddress).ToString();
if (mapAddresses.find(strAdd) == mapAddresses.end()) //if strAdd is not already part of the map
mapAddresses[strAdd] = (double)out.tx->vout[out.i].nValue / (double)COIN;
else
mapAddresses[strAdd] += (double)out.tx->vout[out.i].nValue / (double)COIN;
}
UniValue ret(UniValue::VARR);
for (map<std::string, double>::const_iterator it = mapAddresses.begin(); it != mapAddresses.end(); ++it) {
UniValue obj(UniValue::VOBJ);
const std::string* strAdd = &(*it).first;
const double* nBalance = &(*it).second;
obj.push_back(Pair("Address ", *strAdd));
obj.push_back(Pair("Balance ", *nBalance));
ret.push_back(obj);
}
return ret;
}
unsigned int sumMultiSend()
{
unsigned int sum = 0;
for (unsigned int i = 0; i < pwalletMain->vMultiSend.size(); i++)
sum += pwalletMain->vMultiSend[i].second;
return sum;
}
UniValue multisend(const UniValue& params, bool fHelp)
{
CWalletDB walletdb(pwalletMain->strWalletFile);
bool fFileBacked;
//MultiSend Commands
if (params.size() == 1) {
string strCommand = params[0].get_str();
UniValue ret(UniValue::VOBJ);
if (strCommand == "print") {
return printMultiSend();
} else if (strCommand == "printaddress" || strCommand == "printaddresses") {
return printAddresses();
} else if (strCommand == "clear") {
LOCK(pwalletMain->cs_wallet);
{
bool erased = false;
if (pwalletMain->fFileBacked) {
if (walletdb.EraseMultiSend(pwalletMain->vMultiSend))
erased = true;
}
pwalletMain->vMultiSend.clear();
pwalletMain->setMultiSendDisabled();
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("Erased from database", erased));
obj.push_back(Pair("Erased from RAM", true));
return obj;
}
} else if (strCommand == "enablestake" || strCommand == "activatestake") {
if (pwalletMain->vMultiSend.size() < 1)
throw JSONRPCError(RPC_INVALID_REQUEST, "Unable to activate MultiSend, check MultiSend vector");
if (CBitcoinAddress(pwalletMain->vMultiSend[0].first).IsValid()) {
pwalletMain->fMultiSendStake = true;
if (!walletdb.WriteMSettings(true, pwalletMain->fMultiSendMasternodeReward, pwalletMain->nLastMultiSendHeight)) {
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("error", "MultiSend activated but writing settings to DB failed"));
UniValue arr(UniValue::VARR);
arr.push_back(obj);
arr.push_back(printMultiSend());
return arr;
} else
return printMultiSend();
}
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to activate MultiSend, check MultiSend vector");
} else if (strCommand == "enablemasternode" || strCommand == "activatemasternode") {
if (pwalletMain->vMultiSend.size() < 1)
throw JSONRPCError(RPC_INVALID_REQUEST, "Unable to activate MultiSend, check MultiSend vector");
if (CBitcoinAddress(pwalletMain->vMultiSend[0].first).IsValid()) {
pwalletMain->fMultiSendMasternodeReward = true;
if (!walletdb.WriteMSettings(pwalletMain->fMultiSendStake, true, pwalletMain->nLastMultiSendHeight)) {
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("error", "MultiSend activated but writing settings to DB failed"));
UniValue arr(UniValue::VARR);
arr.push_back(obj);
arr.push_back(printMultiSend());
return arr;
} else
return printMultiSend();
}
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Unable to activate MultiSend, check MultiSend vector");
} else if (strCommand == "disable" || strCommand == "deactivate") {
pwalletMain->setMultiSendDisabled();
if (!walletdb.WriteMSettings(false, false, pwalletMain->nLastMultiSendHeight))
throw JSONRPCError(RPC_DATABASE_ERROR, "MultiSend deactivated but writing settings to DB failed");
return printMultiSend();
} else if (strCommand == "enableall") {
if (!walletdb.EraseMSDisabledAddresses(pwalletMain->vDisabledAddresses))
return "failed to clear old vector from walletDB";
else {
pwalletMain->vDisabledAddresses.clear();
return printMultiSend();
}
}
}
if (params.size() == 2 && params[0].get_str() == "delete") {
int del = std::stoi(params[1].get_str().c_str());
if (!walletdb.EraseMultiSend(pwalletMain->vMultiSend))
throw JSONRPCError(RPC_DATABASE_ERROR, "failed to delete old MultiSend vector from database");
pwalletMain->vMultiSend.erase(pwalletMain->vMultiSend.begin() + del);
if (!walletdb.WriteMultiSend(pwalletMain->vMultiSend))
throw JSONRPCError(RPC_DATABASE_ERROR, "walletdb WriteMultiSend failed!");
return printMultiSend();
}
if (params.size() == 2 && params[0].get_str() == "disable") {
std::string disAddress = params[1].get_str();
if (!CBitcoinAddress(disAddress).IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "address you want to disable is not valid");
else {
pwalletMain->vDisabledAddresses.push_back(disAddress);
if (!walletdb.EraseMSDisabledAddresses(pwalletMain->vDisabledAddresses))
throw JSONRPCError(RPC_DATABASE_ERROR, "disabled address from sending, but failed to clear old vector from walletDB");
if (!walletdb.WriteMSDisabledAddresses(pwalletMain->vDisabledAddresses))
throw JSONRPCError(RPC_DATABASE_ERROR, "disabled address from sending, but failed to store it to walletDB");
else
return printMultiSend();
}
}
//if no commands are used
if (fHelp || params.size() != 2)
throw runtime_error(
"multisend <command>\n"
"****************************************************************\n"
"WHAT IS MULTISEND?\n"
"MultiSend allows a user to automatically send a percent of their stake reward to as many addresses as you would like\n"
"The MultiSend transaction is sent when the staked coins mature (100 confirmations)\n"
"****************************************************************\n"
"TO CREATE OR ADD TO THE MULTISEND VECTOR:\n"
"multisend <CRYPTODEZIRECASH Address> <percent>\n"
"This will add a new address to the MultiSend vector\n"
"Percent is a whole number 1 to 100.\n"
"****************************************************************\n"
"MULTISEND COMMANDS (usage: multisend <command>)\n"
" print - displays the current MultiSend vector \n"
" clear - deletes the current MultiSend vector \n"
" enablestake/activatestake - activates the current MultiSend vector to be activated on stake rewards\n"
" enablemasternode/activatemasternode - activates the current MultiSend vector to be activated on masternode rewards\n"
" disable/deactivate - disables the current MultiSend vector \n"
" delete <Address #> - deletes an address from the MultiSend vector \n"
" disable <address> - prevents a specific address from sending MultiSend transactions\n"
" enableall - enables all addresses to be eligible to send MultiSend transactions\n"
"****************************************************************\n");
//if the user is entering a new MultiSend item
string strAddress = params[0].get_str();
CBitcoinAddress address(strAddress);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid CDZC address");
if (std::stoi(params[1].get_str().c_str()) < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected valid percentage");
if (pwalletMain->IsLocked())
throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
unsigned int nPercent = (unsigned int) std::stoul(params[1].get_str().c_str());
LOCK(pwalletMain->cs_wallet);
{
fFileBacked = pwalletMain->fFileBacked;
//Error if 0 is entered
if (nPercent == 0) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Sending 0% of stake is not valid");
}
//MultiSend can only send 100% of your stake
if (nPercent + sumMultiSend() > 100)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Failed to add to MultiSend vector, the sum of your MultiSend is greater than 100%");
for (unsigned int i = 0; i < pwalletMain->vMultiSend.size(); i++) {
if (pwalletMain->vMultiSend[i].first == strAddress)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Failed to add to MultiSend vector, cannot use the same address twice");
}
if (fFileBacked)
walletdb.EraseMultiSend(pwalletMain->vMultiSend);
std::pair<std::string, int> newMultiSend;
newMultiSend.first = strAddress;
newMultiSend.second = nPercent;
pwalletMain->vMultiSend.push_back(newMultiSend);
if (fFileBacked) {
if (!walletdb.WriteMultiSend(pwalletMain->vMultiSend))
throw JSONRPCError(RPC_DATABASE_ERROR, "walletdb WriteMultiSend failed!");
}
}
return printMultiSend();
}
UniValue getzerocoinbalance(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getzerocoinbalance\n"
"\nReturn the wallet's total zCDZC balance.\n" +
HelpRequiringPassphrase() + "\n"
"\nResult:\n"
"amount (numeric) Total zCDZC balance.\n"
"\nExamples:\n" +
HelpExampleCli("getzerocoinbalance", "") + HelpExampleRpc("getzerocoinbalance", ""));
LOCK2(cs_main, pwalletMain->cs_wallet);
EnsureWalletIsUnlocked(true);
UniValue ret(UniValue::VOBJ);
ret.push_back(Pair("Total", ValueFromAmount(pwalletMain->GetZerocoinBalance(false))));
ret.push_back(Pair("Mature", ValueFromAmount(pwalletMain->GetZerocoinBalance(true))));
ret.push_back(Pair("Unconfirmed", ValueFromAmount(pwalletMain->GetUnconfirmedZerocoinBalance())));
ret.push_back(Pair("Immature", ValueFromAmount(pwalletMain->GetImmatureZerocoinBalance())));
return ret;
}
UniValue listmintedzerocoins(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"listmintedzerocoins (fVerbose) (fMatureOnly)\n"
"\nList all zCDZC mints in the wallet.\n" +
HelpRequiringPassphrase() + "\n"
"\nArguments:\n"
"1. fVerbose (boolean, optional, default=false) Output mints metadata.\n"
"2. fMatureOnly (boolean, optional, default=false) List only mature mints. (Set only if fVerbose is specified)\n"
"\nResult (with fVerbose=false):\n"
"[\n"
" \"xxx\" (string) Pubcoin in hex format.\n"
" ,...\n"
"]\n"
"\nResult (with fVerbose=true):\n"
"[\n"
" {\n"
" \"serial hash\": \"xxx\", (string) Mint serial hash in hex format.\n"
" \"version\": n, (numeric) Zerocoin version number.\n"
" \"zCDZC ID\": \"xxx\", (string) Pubcoin in hex format.\n"
" \"denomination\": n, (numeric) Coin denomination.\n"
" \"confirmations\": n (numeric) Number of confirmations.\n"
" }\n"
" ,..."
"]\n"
"\nExamples:\n" +
HelpExampleCli("listmintedzerocoins", "") + HelpExampleRpc("listmintedzerocoins", "") +
HelpExampleCli("listmintedzerocoins", "true") + HelpExampleRpc("listmintedzerocoins", "true") +
HelpExampleCli("listmintedzerocoins", "true true") + HelpExampleRpc("listmintedzerocoins", "true, true"));
bool fVerbose = (params.size() > 0) ? params[0].get_bool() : false;
bool fMatureOnly = (params.size() > 1) ? params[1].get_bool() : false;
LOCK2(cs_main, pwalletMain->cs_wallet);
EnsureWalletIsUnlocked(true);
CWalletDB walletdb(pwalletMain->strWalletFile);
set<CMintMeta> setMints = pwalletMain->zcdzcTracker->ListMints(true, fMatureOnly, true);
int nBestHeight = chainActive.Height();
UniValue jsonList(UniValue::VARR);
if (fVerbose) {
for (const CMintMeta& m : setMints) {
// Construct mint object
UniValue objMint(UniValue::VOBJ);
objMint.push_back(Pair("serial hash", m.hashSerial.GetHex())); // Serial hash
objMint.push_back(Pair("version", m.nVersion)); // Zerocoin version
objMint.push_back(Pair("zCDZC ID", m.hashPubcoin.GetHex())); // PubCoin
int denom = libzerocoin::ZerocoinDenominationToInt(m.denom);
objMint.push_back(Pair("denomination", denom)); // Denomination
int nConfirmations = (m.nHeight && nBestHeight > m.nHeight) ? nBestHeight - m.nHeight : 0;
objMint.push_back(Pair("confirmations", nConfirmations)); // Confirmations
// Push back mint object
jsonList.push_back(objMint);
}
} else {
for (const CMintMeta& m : setMints)
// Push back PubCoin
jsonList.push_back(m.hashPubcoin.GetHex());
}
return jsonList;
}
UniValue listzerocoinamounts(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"listzerocoinamounts\n"
"\nGet information about your zerocoin amounts.\n" +
HelpRequiringPassphrase() + "\n"
"\nResult:\n"
"[\n"
" {\n"
" \"denomination\": n, (numeric) Denomination Value.\n"
" \"mints\": n (numeric) Number of mints.\n"
" }\n"
" ,..."
"]\n"
"\nExamples:\n" +
HelpExampleCli("listzerocoinamounts", "") + HelpExampleRpc("listzerocoinamounts", ""));
LOCK2(cs_main, pwalletMain->cs_wallet);
EnsureWalletIsUnlocked(true);
CWalletDB walletdb(pwalletMain->strWalletFile);
set<CMintMeta> setMints = pwalletMain->zcdzcTracker->ListMints(true, true, true);
std::map<libzerocoin::CoinDenomination, CAmount> spread;
for (const auto& denom : libzerocoin::zerocoinDenomList)
spread.insert(std::pair<libzerocoin::CoinDenomination, CAmount>(denom, 0));
for (auto& meta : setMints) spread.at(meta.denom)++;
UniValue ret(UniValue::VARR);
for (const auto& m : libzerocoin::zerocoinDenomList) {
UniValue val(UniValue::VOBJ);
val.push_back(Pair("denomination", libzerocoin::ZerocoinDenominationToInt(m)));
val.push_back(Pair("mints", (int64_t)spread.at(m)));
ret.push_back(val);
}
return ret;
}
UniValue listspentzerocoins(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"listspentzerocoins\n"
"\nList all the spent zCDZC mints in the wallet.\n" +
HelpRequiringPassphrase() + "\n"
"\nResult:\n"
"[\n"
" \"xxx\" (string) Pubcoin in hex format.\n"
" ,...\n"
"]\n"
"\nExamples:\n" +
HelpExampleCli("listspentzerocoins", "") + HelpExampleRpc("listspentzerocoins", ""));
LOCK2(cs_main, pwalletMain->cs_wallet);
EnsureWalletIsUnlocked(true);
CWalletDB walletdb(pwalletMain->strWalletFile);
list<CBigNum> listPubCoin = walletdb.ListSpentCoinsSerial();
UniValue jsonList(UniValue::VARR);
for (const CBigNum& pubCoinItem : listPubCoin) {
jsonList.push_back(pubCoinItem.GetHex());
}
return jsonList;
}
UniValue mintzerocoin(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"mintzerocoin amount ( utxos )\n"
"\nMint the specified zCDZC amount\n" +
HelpRequiringPassphrase() + "\n"
"\nArguments:\n"
"1. amount (numeric, required) Enter an amount of Cdzc to convert to zCDZC\n"
"2. utxos (string, optional) A json array of objects.\n"
" Each object needs the txid (string) and vout (numeric)\n"
" [\n"
" {\n"
" \"txid\":\"txid\", (string) The transaction id\n"
" \"vout\": n (numeric) The output number\n"
" }\n"
" ,...\n"
" ]\n"
"\nResult:\n"
"[\n"
" {\n"
" \"txid\": \"xxx\", (string) Transaction ID.\n"
" \"value\": amount, (numeric) Minted amount.\n"
" \"pubcoin\": \"xxx\", (string) Pubcoin in hex format.\n"
" \"randomness\": \"xxx\", (string) Hex encoded randomness.\n"
" \"serial\": \"xxx\", (string) Serial in hex format.\n"
" \"time\": nnn (numeric) Time to mint this transaction.\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n"
"\nMint 50 from anywhere\n" +
HelpExampleCli("mintzerocoin", "50") +
"\nMint 13 from a specific output\n" +
HelpExampleCli("mintzerocoin", "13 \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
"\nAs a json rpc call\n" +
HelpExampleRpc("mintzerocoin", "13, \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\""));
LOCK2(cs_main, pwalletMain->cs_wallet);
if (params.size() == 1)
{
RPCTypeCheck(params, boost::assign::list_of(UniValue::VNUM));
} else
{
RPCTypeCheck(params, boost::assign::list_of(UniValue::VNUM)(UniValue::VARR));
}
int64_t nTime = GetTimeMillis();
if(GetAdjustedTime() > GetSporkValue(SPORK_16_ZEROCOIN_MAINTENANCE_MODE))
throw JSONRPCError(RPC_WALLET_ERROR, "zCDZC is currently disabled due to maintenance.");
EnsureWalletIsUnlocked(true);
CAmount nAmount = params[0].get_int() * COIN;
CWalletTx wtx;
vector<CDeterministicMint> vDMints;
string strError;
vector<COutPoint> vOutpts;
if (params.size() == 2)
{
UniValue outputs = params[1].get_array();
for (unsigned int idx = 0; idx < outputs.size(); idx++) {
const UniValue& output = outputs[idx];
if (!output.isObject())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected object");
const UniValue& o = output.get_obj();
RPCTypeCheckObj(o, boost::assign::map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM));
string txid = find_value(o, "txid").get_str();
if (!IsHex(txid))
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid");
int nOutput = find_value(o, "vout").get_int();
if (nOutput < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
COutPoint outpt(uint256(txid), nOutput);
vOutpts.push_back(outpt);
}
strError = pwalletMain->MintZerocoinFromOutPoint(nAmount, wtx, vDMints, vOutpts);
} else
{
strError = pwalletMain->MintZerocoin(nAmount, wtx, vDMints);
}
if (strError != "")
throw JSONRPCError(RPC_WALLET_ERROR, strError);
UniValue arrMints(UniValue::VARR);
for (CDeterministicMint dMint : vDMints) {
UniValue m(UniValue::VOBJ);
m.push_back(Pair("txid", wtx.GetHash().ToString()));
m.push_back(Pair("value", ValueFromAmount(libzerocoin::ZerocoinDenominationToAmount(dMint.GetDenomination()))));
m.push_back(Pair("pubcoinhash", dMint.GetPubcoinHash().GetHex()));
m.push_back(Pair("serialhash", dMint.GetSerialHash().GetHex()));
m.push_back(Pair("seedhash", dMint.GetSeedHash().GetHex()));
m.push_back(Pair("count", (int64_t)dMint.GetCount()));
m.push_back(Pair("time", GetTimeMillis() - nTime));
arrMints.push_back(m);
}
return arrMints;
}
UniValue spendzerocoin(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 5 || params.size() < 4)
throw runtime_error(
"spendzerocoin amount mintchange minimizechange securitylevel ( \"address\" )\n"
"\nSpend zCDZC to a CDZC address.\n" +
HelpRequiringPassphrase() + "\n"
"\nArguments:\n"
"1. amount (numeric, required) Amount to spend.\n"
"2. mintchange (boolean, required) Re-mint any leftover change.\n"
"3. minimizechange (boolean, required) Try to minimize the returning change [false]\n"
"4. securitylevel (numeric, required) Amount of checkpoints to add to the accumulator.\n"
" A checkpoint contains 10 blocks worth of zerocoinmints.\n"
" The more checkpoints that are added, the more untraceable the transaction.\n"
" Use [100] to add the maximum amount of checkpoints available.\n"
" Adding more checkpoints makes the minting process take longer\n"
"5. \"address\" (string, optional, default=change) Send to specified address or to a new change address.\n"
" If there is change then an address is required\n"
"\nResult:\n"
"{\n"
" \"txid\": \"xxx\", (string) Transaction hash.\n"
" \"bytes\": nnn, (numeric) Transaction size.\n"
" \"fee\": amount, (numeric) Transaction fee (if any).\n"
" \"spends\": [ (array) JSON array of input objects.\n"
" {\n"
" \"denomination\": nnn, (numeric) Denomination value.\n"
" \"pubcoin\": \"xxx\", (string) Pubcoin in hex format.\n"
" \"serial\": \"xxx\", (string) Serial number in hex format.\n"
" \"acc_checksum\": \"xxx\", (string) Accumulator checksum in hex format.\n"
" }\n"
" ,...\n"
" ],\n"
" \"outputs\": [ (array) JSON array of output objects.\n"
" {\n"
" \"value\": amount, (numeric) Value in CDZC.\n"
" \"address\": \"xxx\" (string) CDZC address or \"zerocoinmint\" for reminted change.\n"
" }\n"
" ,...\n"
" ]\n"
"}\n"
"\nExamples\n" +
HelpExampleCli("spendzerocoin", "5000 false true 100 \"Wf1QqABAiQ17aorbB2WTcWAr6HF6zQRLmV\"") +
HelpExampleRpc("spendzerocoin", "5000 false true 100 \"Wf1QqABAiQ17aorbB2WTcWAr6HF6zQRLmV\""));
LOCK2(cs_main, pwalletMain->cs_wallet);
if(GetAdjustedTime() > GetSporkValue(SPORK_16_ZEROCOIN_MAINTENANCE_MODE))
throw JSONRPCError(RPC_WALLET_ERROR, "zCDZC is currently disabled due to maintenance.");
EnsureWalletIsUnlocked();
CAmount nAmount = AmountFromValue(params[0]); // Spending amount
bool fMintChange = params[1].get_bool(); // Mint change to zCDZC
bool fMinimizeChange = params[2].get_bool(); // Minimize change
int nSecurityLevel = params[3].get_int(); // Security level
std::string address_str = params.size() > 4 ? params[4].get_str() : "";
vector<CZerocoinMint> vMintsSelected;
return DoZcdzcSpend(nAmount, fMintChange, fMinimizeChange, nSecurityLevel, vMintsSelected, address_str);
}
UniValue spendzerocoinmints(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"spendzerocoinmints mints_list (\"address\") \n"
"\nSpend zCDZC mints to a CDZC address.\n" +
HelpRequiringPassphrase() + "\n"
"\nArguments:\n"
"1. mints_list (string, required) A json array of zerocoin mints serial hashes\n"
"2. \"address\" (string, optional, default=change) Send to specified address or to a new change address.\n"
"\nResult:\n"
"{\n"
" \"txid\": \"xxx\", (string) Transaction hash.\n"
" \"bytes\": nnn, (numeric) Transaction size.\n"
" \"fee\": amount, (numeric) Transaction fee (if any).\n"
" \"spends\": [ (array) JSON array of input objects.\n"
" {\n"
" \"denomination\": nnn, (numeric) Denomination value.\n"
" \"pubcoin\": \"xxx\", (string) Pubcoin in hex format.\n"
" \"serial\": \"xxx\", (string) Serial number in hex format.\n"
" \"acc_checksum\": \"xxx\", (string) Accumulator checksum in hex format.\n"
" }\n"
" ,...\n"
" ],\n"
" \"outputs\": [ (array) JSON array of output objects.\n"
" {\n"
" \"value\": amount, (numeric) Value in CDZC.\n"
" \"address\": \"xxx\" (string) CDZC address or \"zerocoinmint\" for reminted change.\n"
" }\n"
" ,...\n"
" ]\n"
"}\n"
"\nExamples\n" +
HelpExampleCli("spendzerocoinmints", "'[\"0d8c16eee7737e3cc1e4e70dc006634182b175e039700931283b202715a0818f\", \"dfe585659e265e6a509d93effb906d3d2a0ac2fe3464b2c3b6d71a3ef34c8ad7\"]' \"DMJRSsuU9zfyrvxVaAEFQqK4MxZg6vgeS6\"") +
HelpExampleRpc("spendzerocoinmints", "[\"0d8c16eee7737e3cc1e4e70dc006634182b175e039700931283b202715a0818f\", \"dfe585659e265e6a509d93effb906d3d2a0ac2fe3464b2c3b6d71a3ef34c8ad7\"], \"DMJRSsuU9zfyrvxVaAEFQqK4MxZg6vgeS6\""));
LOCK2(cs_main, pwalletMain->cs_wallet);
if(GetAdjustedTime() > GetSporkValue(SPORK_16_ZEROCOIN_MAINTENANCE_MODE))
throw JSONRPCError(RPC_WALLET_ERROR, "zCDZC is currently disabled due to maintenance.");
std::string address_str = "";
if (params.size() > 1) {
RPCTypeCheck(params, boost::assign::list_of(UniValue::VARR)(UniValue::VSTR));
address_str = params[1].get_str();
} else
RPCTypeCheck(params, boost::assign::list_of(UniValue::VARR));
EnsureWalletIsUnlocked();
UniValue arrMints = params[0].get_array();
if (arrMints.size() == 0)
throw JSONRPCError(RPC_WALLET_ERROR, "No zerocoin selected");
if (arrMints.size() > 7)
throw JSONRPCError(RPC_WALLET_ERROR, "Too many mints included. Maximum zerocoins per spend: 7");
CAmount nAmount(0); // Spending amount
// fetch mints and update nAmount
vector<CZerocoinMint> vMintsSelected;
for(unsigned int i=0; i < arrMints.size(); i++) {
CZerocoinMint mint;
std::string serialHash = arrMints[i].get_str();
if (!IsHex(serialHash))
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex serial hash");
uint256 hashSerial(serialHash);
if (!pwalletMain->GetMint(hashSerial, mint)) {
std::string strErr = "Failed to fetch mint associated with serial hash " + serialHash;
throw JSONRPCError(RPC_WALLET_ERROR, strErr);
}
vMintsSelected.emplace_back(mint);
nAmount += mint.GetDenominationAsAmount();
}
return DoZcdzcSpend(nAmount, false, true, 100, vMintsSelected, address_str);
}
extern UniValue DoZcdzcSpend(const CAmount nAmount, bool fMintChange, bool fMinimizeChange, const int nSecurityLevel, vector<CZerocoinMint>& vMintsSelected, std::string address_str)
{
int64_t nTimeStart = GetTimeMillis();
CBitcoinAddress address = CBitcoinAddress(); // Optional sending address. Dummy initialization here.
CWalletTx wtx;
CZerocoinSpendReceipt receipt;
bool fSuccess;
if(address_str != "") { // Spend to supplied destination address
address = CBitcoinAddress(address_str);
if(!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Crypto Dezire Cash address");
fSuccess = pwalletMain->SpendZerocoin(nAmount, nSecurityLevel, wtx, receipt, vMintsSelected, fMintChange, fMinimizeChange, &address);
} else // Spend to newly generated local address
fSuccess = pwalletMain->SpendZerocoin(nAmount, nSecurityLevel, wtx, receipt, vMintsSelected, fMintChange, fMinimizeChange);
if (!fSuccess)
throw JSONRPCError(RPC_WALLET_ERROR, receipt.GetStatusMessage());
CAmount nValueIn = 0;
UniValue arrSpends(UniValue::VARR);
for (CZerocoinSpend spend : receipt.GetSpends()) {
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("denomination", spend.GetDenomination()));
obj.push_back(Pair("pubcoin", spend.GetPubCoin().GetHex()));
obj.push_back(Pair("serial", spend.GetSerial().GetHex()));
uint32_t nChecksum = spend.GetAccumulatorChecksum();
obj.push_back(Pair("acc_checksum", HexStr(BEGIN(nChecksum), END(nChecksum))));
arrSpends.push_back(obj);
nValueIn += libzerocoin::ZerocoinDenominationToAmount(spend.GetDenomination());
}
CAmount nValueOut = 0;
UniValue vout(UniValue::VARR);
for (unsigned int i = 0; i < wtx.vout.size(); i++) {
const CTxOut& txout = wtx.vout[i];
UniValue out(UniValue::VOBJ);
out.push_back(Pair("value", ValueFromAmount(txout.nValue)));
nValueOut += txout.nValue;
CTxDestination dest;
if(txout.scriptPubKey.IsZerocoinMint())
out.push_back(Pair("address", "zerocoinmint"));
else if(ExtractDestination(txout.scriptPubKey, dest))
out.push_back(Pair("address", CBitcoinAddress(dest).ToString()));
vout.push_back(out);
}
//construct JSON to return
UniValue ret(UniValue::VOBJ);
ret.push_back(Pair("txid", wtx.GetHash().ToString()));
ret.push_back(Pair("bytes", (int64_t)wtx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION)));
ret.push_back(Pair("fee", ValueFromAmount(nValueIn - nValueOut)));
ret.push_back(Pair("duration_millis", (GetTimeMillis() - nTimeStart)));
ret.push_back(Pair("spends", arrSpends));
ret.push_back(Pair("outputs", vout));
return ret;
}
UniValue resetmintzerocoin(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"resetmintzerocoin ( fullscan )\n"
"\nScan the blockchain for all of the zerocoins that are held in the wallet.dat.\n"
"Update any meta-data that is incorrect. Archive any mints that are not able to be found.\n" +
HelpRequiringPassphrase() + "\n"
"\nArguments:\n"
"1. fullscan (boolean, optional) Rescan each block of the blockchain.\n"
" WARNING - may take 30+ minutes!\n"
"\nResult:\n"
"{\n"
" \"updated\": [ (array) JSON array of updated mints.\n"
" \"xxx\" (string) Hex encoded mint.\n"
" ,...\n"
" ],\n"
" \"archived\": [ (array) JSON array of archived mints.\n"
" \"xxx\" (string) Hex encoded mint.\n"
" ,...\n"
" ]\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("resetmintzerocoin", "true") + HelpExampleRpc("resetmintzerocoin", "true"));
LOCK2(cs_main, pwalletMain->cs_wallet);
CWalletDB walletdb(pwalletMain->strWalletFile);
CzCDZCTracker* zcdzcTracker = pwalletMain->zcdzcTracker.get();
set<CMintMeta> setMints = zcdzcTracker->ListMints(false, false, true);
vector<CMintMeta> vMintsToFind(setMints.begin(), setMints.end());
vector<CMintMeta> vMintsMissing;
vector<CMintMeta> vMintsToUpdate;
// search all of our available data for these mints
FindMints(vMintsToFind, vMintsToUpdate, vMintsMissing);
// update the meta data of mints that were marked for updating
UniValue arrUpdated(UniValue::VARR);
for (CMintMeta meta : vMintsToUpdate) {
zcdzcTracker->UpdateState(meta);
arrUpdated.push_back(meta.hashPubcoin.GetHex());
}
// delete any mints that were unable to be located on the blockchain
UniValue arrDeleted(UniValue::VARR);
for (CMintMeta mint : vMintsMissing) {
zcdzcTracker->Archive(mint);
arrDeleted.push_back(mint.hashPubcoin.GetHex());
}
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("updated", arrUpdated));
obj.push_back(Pair("archived", arrDeleted));
return obj;
}
UniValue resetspentzerocoin(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"resetspentzerocoin\n"
"\nScan the blockchain for all of the zerocoins that are held in the wallet.dat.\n"
"Reset mints that are considered spent that did not make it into the blockchain.\n"
"\nResult:\n"
"{\n"
" \"restored\": [ (array) JSON array of restored objects.\n"
" {\n"
" \"serial\": \"xxx\" (string) Serial in hex format.\n"
" }\n"
" ,...\n"
" ]\n"
"}\n"
"\nExamples:\n" +
HelpExampleCli("resetspentzerocoin", "") + HelpExampleRpc("resetspentzerocoin", ""));
LOCK2(cs_main, pwalletMain->cs_wallet);
CWalletDB walletdb(pwalletMain->strWalletFile);
CzCDZCTracker* zcdzcTracker = pwalletMain->zcdzcTracker.get();
set<CMintMeta> setMints = zcdzcTracker->ListMints(false, false, false);
list<CZerocoinSpend> listSpends = walletdb.ListSpentCoins();
list<CZerocoinSpend> listUnconfirmedSpends;
for (CZerocoinSpend spend : listSpends) {
CTransaction tx;
uint256 hashBlock = 0;
if (!GetTransaction(spend.GetTxHash(), tx, hashBlock)) {
listUnconfirmedSpends.push_back(spend);
continue;
}
//no confirmations
if (hashBlock == 0)
listUnconfirmedSpends.push_back(spend);
}
UniValue objRet(UniValue::VOBJ);
UniValue arrRestored(UniValue::VARR);
for (CZerocoinSpend spend : listUnconfirmedSpends) {
for (auto& meta : setMints) {
if (meta.hashSerial == GetSerialHash(spend.GetSerial())) {
zcdzcTracker->SetPubcoinNotUsed(meta.hashPubcoin);
walletdb.EraseZerocoinSpendSerialEntry(spend.GetSerial());
RemoveSerialFromDB(spend.GetSerial());
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("serial", spend.GetSerial().GetHex()));
arrRestored.push_back(obj);
continue;
}
}
}
objRet.push_back(Pair("restored", arrRestored));
return objRet;
}
UniValue getarchivedzerocoin(const UniValue& params, bool fHelp)
{
if(fHelp || params.size() != 0)
throw runtime_error(
"getarchivedzerocoin\n"
"\nDisplay zerocoins that were archived because they were believed to be orphans.\n"
"Provides enough information to recover mint if it was incorrectly archived.\n" +
HelpRequiringPassphrase() + "\n"
"\nResult:\n"
"[\n"
" {\n"
" \"txid\": \"xxx\", (string) Transaction ID for archived mint.\n"
" \"denomination\": amount, (numeric) Denomination value.\n"
" \"serial\": \"xxx\", (string) Serial number in hex format.\n"
" \"randomness\": \"xxx\", (string) Hex encoded randomness.\n"
" \"pubcoin\": \"xxx\" (string) Pubcoin in hex format.\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n" +
HelpExampleCli("getarchivedzerocoin", "") + HelpExampleRpc("getarchivedzerocoin", ""));
LOCK2(cs_main, pwalletMain->cs_wallet);
EnsureWalletIsUnlocked();
CWalletDB walletdb(pwalletMain->strWalletFile);
list<CZerocoinMint> listMints = walletdb.ListArchivedZerocoins();
list<CDeterministicMint> listDMints = walletdb.ListArchivedDeterministicMints();
UniValue arrRet(UniValue::VARR);
for (const CZerocoinMint& mint : listMints) {
UniValue objMint(UniValue::VOBJ);
objMint.push_back(Pair("txid", mint.GetTxHash().GetHex()));
objMint.push_back(Pair("denomination", ValueFromAmount(mint.GetDenominationAsAmount())));
objMint.push_back(Pair("serial", mint.GetSerialNumber().GetHex()));
objMint.push_back(Pair("randomness", mint.GetRandomness().GetHex()));
objMint.push_back(Pair("pubcoin", mint.GetValue().GetHex()));
arrRet.push_back(objMint);
}
for (const CDeterministicMint& dMint : listDMints) {
UniValue objDMint(UniValue::VOBJ);
objDMint.push_back(Pair("txid", dMint.GetTxHash().GetHex()));
objDMint.push_back(Pair("denomination", ValueFromAmount(libzerocoin::ZerocoinDenominationToAmount(dMint.GetDenomination()))));
objDMint.push_back(Pair("serialhash", dMint.GetSerialHash().GetHex()));
objDMint.push_back(Pair("pubcoinhash", dMint.GetPubcoinHash().GetHex()));
objDMint.push_back(Pair("seedhash", dMint.GetSeedHash().GetHex()));
objDMint.push_back(Pair("count", (int64_t)dMint.GetCount()));
arrRet.push_back(objDMint);
}
return arrRet;
}
UniValue exportzerocoins(const UniValue& params, bool fHelp)
{
if(fHelp || params.empty() || params.size() > 2)
throw runtime_error(
"exportzerocoins include_spent ( denomination )\n"
"\nExports zerocoin mints that are held by this wallet.dat\n" +
HelpRequiringPassphrase() + "\n"
"\nArguments:\n"
"1. \"include_spent\" (bool, required) Include mints that have already been spent\n"
"2. \"denomination\" (integer, optional) Export a specific denomination of zCDZC\n"
"\nResult:\n"
"[ (array of json object)\n"
" {\n"
" \"d\": n, (numeric) the mint's zerocoin denomination \n"
" \"p\": \"pubcoin\", (string) The public coin\n"
" \"s\": \"serial\", (string) The secret serial number\n"
" \"r\": \"random\", (string) The secret random number\n"
" \"t\": \"txid\", (string) The txid that the coin was minted in\n"
" \"h\": n, (numeric) The height the tx was added to the blockchain\n"
" \"u\": used, (boolean) Whether the mint has been spent\n"
" \"v\": version, (numeric) The version of the zCDZC\n"
" \"k\": \"privkey\" (string) The zCDZC private key (V2+ zCDZC only)\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples:\n" +
HelpExampleCli("exportzerocoins", "false 5") + HelpExampleRpc("exportzerocoins", "false 5"));
LOCK2(cs_main, pwalletMain->cs_wallet);
EnsureWalletIsUnlocked();
CWalletDB walletdb(pwalletMain->strWalletFile);
bool fIncludeSpent = params[0].get_bool();
libzerocoin::CoinDenomination denomination = libzerocoin::ZQ_ERROR;
if (params.size() == 2)
denomination = libzerocoin::IntToZerocoinDenomination(params[1].get_int());
CzCDZCTracker* zcdzcTracker = pwalletMain->zcdzcTracker.get();
set<CMintMeta> setMints = zcdzcTracker->ListMints(!fIncludeSpent, false, false);
UniValue jsonList(UniValue::VARR);
for (const CMintMeta& meta : setMints) {
if (denomination != libzerocoin::ZQ_ERROR && denomination != meta.denom)
continue;
CZerocoinMint mint;
if (!pwalletMain->GetMint(meta.hashSerial, mint))
continue;
UniValue objMint(UniValue::VOBJ);
objMint.push_back(Pair("d", mint.GetDenomination()));
objMint.push_back(Pair("p", mint.GetValue().GetHex()));
objMint.push_back(Pair("s", mint.GetSerialNumber().GetHex()));
objMint.push_back(Pair("r", mint.GetRandomness().GetHex()));
objMint.push_back(Pair("t", mint.GetTxHash().GetHex()));
objMint.push_back(Pair("h", mint.GetHeight()));
objMint.push_back(Pair("u", mint.IsUsed()));
objMint.push_back(Pair("v", mint.GetVersion()));
if (mint.GetVersion() >= 2) {
CKey key;
key.SetPrivKey(mint.GetPrivKey(), true);
CBitcoinSecret cBitcoinSecret;
cBitcoinSecret.SetKey(key);
objMint.push_back(Pair("k", cBitcoinSecret.ToString()));
}
jsonList.push_back(objMint);
}
return jsonList;
}
UniValue importzerocoins(const UniValue& params, bool fHelp)
{
if(fHelp || params.size() == 0)
throw runtime_error(
"importzerocoins importdata \n"
"\n[{\"d\":denomination,\"p\":\"pubcoin_hex\",\"s\":\"serial_hex\",\"r\":\"randomness_hex\",\"t\":\"txid\",\"h\":height, \"u\":used},{\"d\":...}]\n"
"\nImport zerocoin mints.\n"
"Adds raw zerocoin mints to the wallet.dat\n"
"Note it is recommended to use the json export created from the exportzerocoins RPC call\n" +
HelpRequiringPassphrase() + "\n"
"\nArguments:\n"
"1. \"importdata\" (string, required) A json array of json objects containing zerocoin mints\n"
"\nResult:\n"
"{\n"
" \"added\": n, (numeric) The quantity of zerocoin mints that were added\n"
" \"value\": amount (numeric) The total zCDZC value of zerocoin mints that were added\n"
"}\n"
"\nExamples\n" +
HelpExampleCli("importzerocoins", "\'[{\"d\":100,\"p\":\"mypubcoin\",\"s\":\"myserial\",\"r\":\"randomness_hex\",\"t\":\"mytxid\",\"h\":104923, \"u\":false},{\"d\":5,...}]\'") +
HelpExampleRpc("importzerocoins", "[{\"d\":100,\"p\":\"mypubcoin\",\"s\":\"myserial\",\"r\":\"randomness_hex\",\"t\":\"mytxid\",\"h\":104923, \"u\":false},{\"d\":5,...}]"));
LOCK2(cs_main, pwalletMain->cs_wallet);
EnsureWalletIsUnlocked();
RPCTypeCheck(params, list_of(UniValue::VARR)(UniValue::VOBJ));
UniValue arrMints = params[0].get_array();
CWalletDB walletdb(pwalletMain->strWalletFile);
int count = 0;
CAmount nValue = 0;
for (unsigned int idx = 0; idx < arrMints.size(); idx++) {
const UniValue &val = arrMints[idx];
const UniValue &o = val.get_obj();
const UniValue& vDenom = find_value(o, "d");
if (!vDenom.isNum())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing d key");
int d = vDenom.get_int();
if (d < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, d must be positive");
libzerocoin::CoinDenomination denom = libzerocoin::IntToZerocoinDenomination(d);
CBigNum bnValue = 0;
bnValue.SetHex(find_value(o, "p").get_str());
CBigNum bnSerial = 0;
bnSerial.SetHex(find_value(o, "s").get_str());
CBigNum bnRandom = 0;
bnRandom.SetHex(find_value(o, "r").get_str());
uint256 txid(find_value(o, "t").get_str());
int nHeight = find_value(o, "h").get_int();
if (nHeight < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, h must be positive");
bool fUsed = find_value(o, "u").get_bool();
//Assume coin is version 1 unless it has the version actually set
uint8_t nVersion = 1;
const UniValue& vVersion = find_value(o, "v");
if (vVersion.isNum())
nVersion = static_cast<uint8_t>(vVersion.get_int());
//Set the privkey if applicable
CPrivKey privkey;
if (nVersion >= libzerocoin::PrivateCoin::PUBKEY_VERSION) {
std::string strPrivkey = find_value(o, "k").get_str();
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(strPrivkey);
CKey key = vchSecret.GetKey();
if (!key.IsValid() && fGood)
return JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "privkey is not valid");
privkey = key.GetPrivKey();
}
CZerocoinMint mint(denom, bnValue, bnRandom, bnSerial, fUsed, nVersion, &privkey);
mint.SetTxHash(txid);
mint.SetHeight(nHeight);
pwalletMain->zcdzcTracker->Add(mint, true);
count++;
nValue += libzerocoin::ZerocoinDenominationToAmount(denom);
}
UniValue ret(UniValue::VOBJ);
ret.push_back(Pair("added", count));
ret.push_back(Pair("value", ValueFromAmount(nValue)));
return ret;
}
UniValue reconsiderzerocoins(const UniValue& params, bool fHelp)
{
if(fHelp || !params.empty())
throw runtime_error(
"reconsiderzerocoins\n"
"\nCheck archived zCDZC list to see if any mints were added to the blockchain.\n" +
HelpRequiringPassphrase() + "\n"
"\nResult:\n"
"[\n"
" {\n"
" \"txid\" : \"xxx\", (string) the mint's zerocoin denomination \n"
" \"denomination\" : amount, (numeric) the mint's zerocoin denomination\n"
" \"pubcoin\" : \"xxx\", (string) The mint's public identifier\n"
" \"height\" : n (numeric) The height the tx was added to the blockchain\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples\n" +
HelpExampleCli("reconsiderzerocoins", "") + HelpExampleRpc("reconsiderzerocoins", ""));
LOCK2(cs_main, pwalletMain->cs_wallet);
EnsureWalletIsUnlocked(true);
list<CZerocoinMint> listMints;
list<CDeterministicMint> listDMints;
pwalletMain->ReconsiderZerocoins(listMints, listDMints);
UniValue arrRet(UniValue::VARR);
for (const CZerocoinMint& mint : listMints) {
UniValue objMint(UniValue::VOBJ);
objMint.push_back(Pair("txid", mint.GetTxHash().GetHex()));
objMint.push_back(Pair("denomination", ValueFromAmount(mint.GetDenominationAsAmount())));
objMint.push_back(Pair("pubcoin", mint.GetValue().GetHex()));
objMint.push_back(Pair("height", mint.GetHeight()));
arrRet.push_back(objMint);
}
for (const CDeterministicMint& dMint : listDMints) {
UniValue objMint(UniValue::VOBJ);
objMint.push_back(Pair("txid", dMint.GetTxHash().GetHex()));
objMint.push_back(Pair("denomination", FormatMoney(libzerocoin::ZerocoinDenominationToAmount(dMint.GetDenomination()))));
objMint.push_back(Pair("pubcoinhash", dMint.GetPubcoinHash().GetHex()));
objMint.push_back(Pair("height", dMint.GetHeight()));
arrRet.push_back(objMint);
}
return arrRet;
}
UniValue setzcdzcseed(const UniValue& params, bool fHelp)
{
if(fHelp || params.size() != 1)
throw runtime_error(
"setzcdzcseed \"seed\"\n"
"\nSet the wallet's deterministic zcdzc seed to a specific value.\n" +
HelpRequiringPassphrase() + "\n"
"\nArguments:\n"
"1. \"seed\" (string, required) The deterministic zcdzc seed.\n"
"\nResult\n"
"\"success\" : b, (boolean) Whether the seed was successfully set.\n"
"\nExamples\n" +
HelpExampleCli("setzcdzcseed", "63f793e7895dd30d99187b35fbfb314a5f91af0add9e0a4e5877036d1e392dd5") +
HelpExampleRpc("setzcdzcseed", "63f793e7895dd30d99187b35fbfb314a5f91af0add9e0a4e5877036d1e392dd5"));
EnsureWalletIsUnlocked();
uint256 seed;
seed.SetHex(params[0].get_str());
CzCDZCWallet* zwallet = pwalletMain->getZWallet();
bool fSuccess = zwallet->SetMasterSeed(seed, true);
if (fSuccess)
zwallet->SyncWithChain();
UniValue ret(UniValue::VOBJ);
ret.push_back(Pair("success", fSuccess));
return ret;
}
UniValue getzcdzcseed(const UniValue& params, bool fHelp)
{
if(fHelp || !params.empty())
throw runtime_error(
"getzcdzcseed\n"
"\nCheck archived zCDZC list to see if any mints were added to the blockchain.\n" +
HelpRequiringPassphrase() + "\n"
"\nResult\n"
"\"seed\" : s, (string) The deterministic zCDZC seed.\n"
"\nExamples\n" +
HelpExampleCli("getzcdzcseed", "") + HelpExampleRpc("getzcdzcseed", ""));
EnsureWalletIsUnlocked();
CzCDZCWallet* zwallet = pwalletMain->getZWallet();
uint256 seed = zwallet->GetMasterSeed();
UniValue ret(UniValue::VOBJ);
ret.push_back(Pair("seed", seed.GetHex()));
return ret;
}
UniValue generatemintlist(const UniValue& params, bool fHelp)
{
if(fHelp || params.size() != 2)
throw runtime_error(
"generatemintlist\n"
"\nShow mints that are derived from the deterministic zCDZC seed.\n" +
HelpRequiringPassphrase() + "\n"
"\nArguments\n"
"1. \"count\" : n, (numeric) Which sequential zCDZC to start with.\n"
"2. \"range\" : n, (numeric) How many zCDZC to generate.\n"
"\nResult:\n"
"[\n"
" {\n"
" \"count\": n, (numeric) Deterministic Count.\n"
" \"value\": \"xxx\", (string) Hex encoded pubcoin value.\n"
" \"randomness\": \"xxx\", (string) Hex encoded randomness.\n"
" \"serial\": \"xxx\" (string) Hex encoded Serial.\n"
" }\n"
" ,...\n"
"]\n"
"\nExamples\n" +
HelpExampleCli("generatemintlist", "1, 100") + HelpExampleRpc("generatemintlist", "1, 100"));
EnsureWalletIsUnlocked();
int nCount = params[0].get_int();
int nRange = params[1].get_int();
CzCDZCWallet* zwallet = pwalletMain->zwalletMain;
UniValue arrRet(UniValue::VARR);
for (int i = nCount; i < nCount + nRange; i++) {
libzerocoin::CoinDenomination denom = libzerocoin::CoinDenomination::ZQ_ONE;
libzerocoin::PrivateCoin coin(Params().Zerocoin_Params(false), denom, false);
CDeterministicMint dMint;
zwallet->GenerateMint(i, denom, coin, dMint);
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("count", i));
obj.push_back(Pair("value", coin.getPublicCoin().getValue().GetHex()));
obj.push_back(Pair("randomness", coin.getRandomness().GetHex()));
obj.push_back(Pair("serial", coin.getSerialNumber().GetHex()));
arrRet.push_back(obj);
}
return arrRet;
}
UniValue dzcdzcstate(const UniValue& params, bool fHelp) {
if (fHelp || params.size() != 0)
throw runtime_error(
"dzcdzcstate\n"
"\nThe current state of the mintpool of the deterministic zCDZC wallet.\n" +
HelpRequiringPassphrase() + "\n"
"\nExamples\n" +
HelpExampleCli("mintpoolstatus", "") + HelpExampleRpc("mintpoolstatus", ""));
CzCDZCWallet* zwallet = pwalletMain->zwalletMain;
UniValue obj(UniValue::VOBJ);
int nCount, nCountLastUsed;
zwallet->GetState(nCount, nCountLastUsed);
obj.push_back(Pair("dzcdzc_count", nCount));
obj.push_back(Pair("mintpool_count", nCountLastUsed));
return obj;
}
void static SearchThread(CzCDZCWallet* zwallet, int nCountStart, int nCountEnd)
{
LogPrintf("%s: start=%d end=%d\n", __func__, nCountStart, nCountEnd);
CWalletDB walletDB(pwalletMain->strWalletFile);
try {
uint256 seedMaster = zwallet->GetMasterSeed();
uint256 hashSeed = Hash(seedMaster.begin(), seedMaster.end());
for(int i = nCountStart; i < nCountEnd; i++) {
boost::this_thread::interruption_point();
CDataStream ss(SER_GETHASH, 0);
ss << seedMaster << i;
uint512 zerocoinSeed = Hash512(ss.begin(), ss.end());
CBigNum bnValue;
CBigNum bnSerial;
CBigNum bnRandomness;
CKey key;
zwallet->SeedToZCDZC(zerocoinSeed, bnValue, bnSerial, bnRandomness, key);
uint256 hashPubcoin = GetPubCoinHash(bnValue);
zwallet->AddToMintPool(make_pair(hashPubcoin, i), true);
walletDB.WriteMintPoolPair(hashSeed, hashPubcoin, i);
}
} catch (std::exception& e) {
LogPrintf("SearchThread() exception");
} catch (...) {
LogPrintf("SearchThread() exception");
}
}
UniValue searchdzcdzc(const UniValue& params, bool fHelp)
{
if(fHelp || params.size() != 3)
throw runtime_error(
"searchdzcdzc\n"
"\nMake an extended search for deterministically generated zCDZC that have not yet been recognized by the wallet.\n" +
HelpRequiringPassphrase() + "\n"
"\nArguments\n"
"1. \"count\" (numeric) Which sequential zCDZC to start with.\n"
"2. \"range\" (numeric) How many zCDZC to generate.\n"
"3. \"threads\" (numeric) How many threads should this operation consume.\n"
"\nExamples\n" +
HelpExampleCli("searchdzcdzc", "1, 100, 2") + HelpExampleRpc("searchdzcdzc", "1, 100, 2"));
EnsureWalletIsUnlocked();
int nCount = params[0].get_int();
if (nCount < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Count cannot be less than 0");
int nRange = params[1].get_int();
if (nRange < 1)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Range has to be at least 1");
int nThreads = params[2].get_int();
CzCDZCWallet* zwallet = pwalletMain->zwalletMain;
boost::thread_group* dzcdzcThreads = new boost::thread_group();
int nRangePerThread = nRange / nThreads;
int nPrevThreadEnd = nCount - 1;
for (int i = 0; i < nThreads; i++) {
int nStart = nPrevThreadEnd + 1;;
int nEnd = nStart + nRangePerThread;
nPrevThreadEnd = nEnd;
dzcdzcThreads->create_thread(boost::bind(&SearchThread, zwallet, nStart, nEnd));
}
dzcdzcThreads->join_all();
zwallet->RemoveMintsFromPool(pwalletMain->zcdzcTracker->GetSerialHashes());
zwallet->SyncWithChain(false);
//todo: better response
return "done";
}
|
#include "node.h"
#include "node_buffer.h"
#include "node_http_parser.h"
#include "base-object.h"
#include "base-object-inl.h"
#include "env.h"
#include "env-inl.h"
#include "util.h"
#include "util-inl.h"
#include "v8.h"
#include <stdlib.h> // free()
#include <string.h> // strdup()
#if defined(_MSC_VER)
#define strcasecmp _stricmp
#else
#include <strings.h> // strcasecmp()
#endif
// This is a binding to http_parser (https://github.com/joyent/http-parser)
// The goal is to decouple sockets from parsing for more javascript-level
// agility. A Buffer is read from a socket and passed to parser.execute().
// The parser then issues callbacks with slices of the data
// parser.onMessageBegin
// parser.onPath
// parser.onBody
// ...
// No copying is performed when slicing the buffer, only small reference
// allocations.
namespace node {
using v8::Array;
using v8::Boolean;
using v8::Context;
using v8::Exception;
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::Handle;
using v8::HandleScope;
using v8::Integer;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Uint32;
using v8::Undefined;
using v8::Value;
const uint32_t kOnHeaders = 0;
const uint32_t kOnHeadersComplete = 1;
const uint32_t kOnBody = 2;
const uint32_t kOnMessageComplete = 3;
#define HTTP_CB(name) \
static int name(http_parser* p_) { \
Parser* self = ContainerOf(&Parser::parser_, p_); \
return self->name##_(); \
} \
int name##_()
#define HTTP_DATA_CB(name) \
static int name(http_parser* p_, const char* at, size_t length) { \
Parser* self = ContainerOf(&Parser::parser_, p_); \
return self->name##_(at, length); \
} \
int name##_(const char* at, size_t length)
// helper class for the Parser
struct StringPtr {
StringPtr() {
on_heap_ = false;
Reset();
}
~StringPtr() {
Reset();
}
// If str_ does not point to a heap string yet, this function makes it do
// so. This is called at the end of each http_parser_execute() so as not
// to leak references. See issue #2438 and test-http-parser-bad-ref.js.
void Save() {
if (!on_heap_ && size_ > 0) {
char* s = new char[size_];
memcpy(s, str_, size_);
str_ = s;
on_heap_ = true;
}
}
void Reset() {
if (on_heap_) {
delete[] str_;
on_heap_ = false;
}
str_ = nullptr;
size_ = 0;
}
void Update(const char* str, size_t size) {
if (str_ == nullptr)
str_ = str;
else if (on_heap_ || str_ + size_ != str) {
// Non-consecutive input, make a copy on the heap.
// TODO(bnoordhuis) Use slab allocation, O(n) allocs is bad.
char* s = new char[size_ + size];
memcpy(s, str_, size_);
memcpy(s + size_, str, size);
if (on_heap_)
delete[] str_;
else
on_heap_ = true;
str_ = s;
}
size_ += size;
}
Local<String> ToString(Environment* env) const {
if (str_)
return OneByteString(env->isolate(), str_, size_);
else
return String::Empty(env->isolate());
}
const char* str_;
bool on_heap_;
size_t size_;
};
class Parser : public BaseObject {
public:
Parser(Environment* env, Local<Object> wrap, enum http_parser_type type)
: BaseObject(env, wrap),
current_buffer_len_(0),
current_buffer_data_(nullptr) {
Wrap(object(), this);
Init(type);
}
~Parser() override {
ClearWrap(object());
persistent().Reset();
}
HTTP_CB(on_message_begin) {
num_fields_ = num_values_ = 0;
url_.Reset();
status_message_.Reset();
return 0;
}
HTTP_DATA_CB(on_url) {
url_.Update(at, length);
return 0;
}
HTTP_DATA_CB(on_status) {
status_message_.Update(at, length);
return 0;
}
HTTP_DATA_CB(on_header_field) {
if (num_fields_ == num_values_) {
// start of new field name
num_fields_++;
if (num_fields_ == ARRAY_SIZE(fields_)) {
// ran out of space - flush to javascript land
Flush();
num_fields_ = 1;
num_values_ = 0;
}
fields_[num_fields_ - 1].Reset();
}
CHECK_LT(num_fields_, static_cast<int>(ARRAY_SIZE(fields_)));
CHECK_EQ(num_fields_, num_values_ + 1);
fields_[num_fields_ - 1].Update(at, length);
return 0;
}
HTTP_DATA_CB(on_header_value) {
if (num_values_ != num_fields_) {
// start of new header value
num_values_++;
values_[num_values_ - 1].Reset();
}
CHECK_LT(num_values_, static_cast<int>(ARRAY_SIZE(values_)));
CHECK_EQ(num_values_, num_fields_);
values_[num_values_ - 1].Update(at, length);
return 0;
}
HTTP_CB(on_headers_complete) {
// Arguments for the on-headers-complete javascript callback. This
// list needs to be kept in sync with the actual argument list for
// `parserOnHeadersComplete` in lib/_http_common.js.
enum on_headers_complete_arg_index {
A_VERSION_MAJOR = 0,
A_VERSION_MINOR,
A_HEADERS,
A_METHOD,
A_URL,
A_STATUS_CODE,
A_STATUS_MESSAGE,
A_UPGRADE,
A_SHOULD_KEEP_ALIVE,
A_MAX
};
Local<Value> argv[A_MAX];
Local<Object> obj = object();
Local<Value> cb = obj->Get(kOnHeadersComplete);
if (!cb->IsFunction())
return 0;
Local<Value> undefined = Undefined(env()->isolate());
for (size_t i = 0; i < ARRAY_SIZE(argv); i++)
argv[i] = undefined;
if (have_flushed_) {
// Slow case, flush remaining headers.
Flush();
} else {
// Fast case, pass headers and URL to JS land.
argv[A_HEADERS] = CreateHeaders();
if (parser_.type == HTTP_REQUEST)
argv[A_URL] = url_.ToString(env());
}
num_fields_ = 0;
num_values_ = 0;
// METHOD
if (parser_.type == HTTP_REQUEST) {
argv[A_METHOD] =
Uint32::NewFromUnsigned(env()->isolate(), parser_.method);
}
// STATUS
if (parser_.type == HTTP_RESPONSE) {
argv[A_STATUS_CODE] =
Integer::New(env()->isolate(), parser_.status_code);
argv[A_STATUS_MESSAGE] = status_message_.ToString(env());
}
// VERSION
argv[A_VERSION_MAJOR] = Integer::New(env()->isolate(), parser_.http_major);
argv[A_VERSION_MINOR] = Integer::New(env()->isolate(), parser_.http_minor);
argv[A_SHOULD_KEEP_ALIVE] =
Boolean::New(env()->isolate(), http_should_keep_alive(&parser_));
argv[A_UPGRADE] = Boolean::New(env()->isolate(), parser_.upgrade);
Local<Value> head_response =
cb.As<Function>()->Call(obj, ARRAY_SIZE(argv), argv);
if (head_response.IsEmpty()) {
got_exception_ = true;
return -1;
}
return head_response->IsTrue() ? 1 : 0;
}
HTTP_DATA_CB(on_body) {
HandleScope scope(env()->isolate());
Local<Object> obj = object();
Local<Value> cb = obj->Get(kOnBody);
if (!cb->IsFunction())
return 0;
Local<Value> argv[3] = {
current_buffer_,
Integer::NewFromUnsigned(env()->isolate(), at - current_buffer_data_),
Integer::NewFromUnsigned(env()->isolate(), length)
};
Local<Value> r = cb.As<Function>()->Call(obj, ARRAY_SIZE(argv), argv);
if (r.IsEmpty()) {
got_exception_ = true;
return -1;
}
return 0;
}
HTTP_CB(on_message_complete) {
HandleScope scope(env()->isolate());
if (num_fields_)
Flush(); // Flush trailing HTTP headers.
Local<Object> obj = object();
Local<Value> cb = obj->Get(kOnMessageComplete);
if (!cb->IsFunction())
return 0;
Local<Value> r = cb.As<Function>()->Call(obj, 0, nullptr);
if (r.IsEmpty()) {
got_exception_ = true;
return -1;
}
return 0;
}
static void New(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
http_parser_type type =
static_cast<http_parser_type>(args[0]->Int32Value());
CHECK(type == HTTP_REQUEST || type == HTTP_RESPONSE);
new Parser(env, args.This(), type);
}
static void Close(const FunctionCallbackInfo<Value>& args) {
Parser* parser = Unwrap<Parser>(args.Holder());
delete parser;
}
void Save() {
url_.Save();
status_message_.Save();
for (int i = 0; i < num_fields_; i++) {
fields_[i].Save();
}
for (int i = 0; i < num_values_; i++) {
values_[i].Save();
}
}
// var bytesParsed = parser->execute(buffer);
static void Execute(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
Parser* parser = Unwrap<Parser>(args.Holder());
CHECK(parser->current_buffer_.IsEmpty());
CHECK_EQ(parser->current_buffer_len_, 0);
CHECK_EQ(parser->current_buffer_data_, nullptr);
CHECK_EQ(Buffer::HasInstance(args[0]), true);
Local<Object> buffer_obj = args[0].As<Object>();
char* buffer_data = Buffer::Data(buffer_obj);
size_t buffer_len = Buffer::Length(buffer_obj);
// This is a hack to get the current_buffer to the callbacks with the least
// amount of overhead. Nothing else will run while http_parser_execute()
// runs, therefore this pointer can be set and used for the execution.
parser->current_buffer_ = buffer_obj;
parser->current_buffer_len_ = buffer_len;
parser->current_buffer_data_ = buffer_data;
parser->got_exception_ = false;
size_t nparsed =
http_parser_execute(&parser->parser_, &settings, buffer_data, buffer_len);
parser->Save();
// Unassign the 'buffer_' variable
parser->current_buffer_.Clear();
parser->current_buffer_len_ = 0;
parser->current_buffer_data_ = nullptr;
// If there was an exception in one of the callbacks
if (parser->got_exception_)
return;
Local<Integer> nparsed_obj = Integer::New(env->isolate(), nparsed);
// If there was a parse error in one of the callbacks
// TODO(bnoordhuis) What if there is an error on EOF?
if (!parser->parser_.upgrade && nparsed != buffer_len) {
enum http_errno err = HTTP_PARSER_ERRNO(&parser->parser_);
Local<Value> e = Exception::Error(env->parse_error_string());
Local<Object> obj = e->ToObject(env->isolate());
obj->Set(env->bytes_parsed_string(), nparsed_obj);
obj->Set(env->code_string(),
OneByteString(env->isolate(), http_errno_name(err)));
args.GetReturnValue().Set(e);
} else {
args.GetReturnValue().Set(nparsed_obj);
}
}
static void Finish(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
Parser* parser = Unwrap<Parser>(args.Holder());
CHECK(parser->current_buffer_.IsEmpty());
parser->got_exception_ = false;
int rv = http_parser_execute(&(parser->parser_), &settings, nullptr, 0);
if (parser->got_exception_)
return;
if (rv != 0) {
enum http_errno err = HTTP_PARSER_ERRNO(&parser->parser_);
Local<Value> e = env->parse_error_string();
Local<Object> obj = e->ToObject(env->isolate());
obj->Set(env->bytes_parsed_string(), Integer::New(env->isolate(), 0));
obj->Set(env->code_string(),
OneByteString(env->isolate(), http_errno_name(err)));
args.GetReturnValue().Set(e);
}
}
static void Reinitialize(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
http_parser_type type =
static_cast<http_parser_type>(args[0]->Int32Value());
CHECK(type == HTTP_REQUEST || type == HTTP_RESPONSE);
Parser* parser = Unwrap<Parser>(args.Holder());
// Should always be called from the same context.
CHECK_EQ(env, parser->env());
parser->Init(type);
}
template <bool should_pause>
static void Pause(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
Parser* parser = Unwrap<Parser>(args.Holder());
// Should always be called from the same context.
CHECK_EQ(env, parser->env());
http_parser_pause(&parser->parser_, should_pause);
}
private:
Local<Array> CreateHeaders() {
// num_values_ is either -1 or the entry # of the last header
// so num_values_ == 0 means there's a single header
Local<Array> headers = Array::New(env()->isolate(), 2 * num_values_);
for (int i = 0; i < num_values_; ++i) {
headers->Set(2 * i, fields_[i].ToString(env()));
headers->Set(2 * i + 1, values_[i].ToString(env()));
}
return headers;
}
// spill headers and request path to JS land
void Flush() {
HandleScope scope(env()->isolate());
Local<Object> obj = object();
Local<Value> cb = obj->Get(kOnHeaders);
if (!cb->IsFunction())
return;
Local<Value> argv[2] = {
CreateHeaders(),
url_.ToString(env())
};
Local<Value> r = cb.As<Function>()->Call(obj, ARRAY_SIZE(argv), argv);
if (r.IsEmpty())
got_exception_ = true;
url_.Reset();
have_flushed_ = true;
}
void Init(enum http_parser_type type) {
http_parser_init(&parser_, type);
url_.Reset();
status_message_.Reset();
num_fields_ = 0;
num_values_ = 0;
have_flushed_ = false;
got_exception_ = false;
}
http_parser parser_;
StringPtr fields_[32]; // header fields
StringPtr values_[32]; // header values
StringPtr url_;
StringPtr status_message_;
int num_fields_;
int num_values_;
bool have_flushed_;
bool got_exception_;
Local<Object> current_buffer_;
size_t current_buffer_len_;
char* current_buffer_data_;
static const struct http_parser_settings settings;
};
const struct http_parser_settings Parser::settings = {
Parser::on_message_begin,
Parser::on_url,
Parser::on_status,
Parser::on_header_field,
Parser::on_header_value,
Parser::on_headers_complete,
Parser::on_body,
Parser::on_message_complete
};
void InitHttpParser(Handle<Object> target,
Handle<Value> unused,
Handle<Context> context,
void* priv) {
Environment* env = Environment::GetCurrent(context);
Local<FunctionTemplate> t = env->NewFunctionTemplate(Parser::New);
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(FIXED_ONE_BYTE_STRING(env->isolate(), "HTTPParser"));
t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "REQUEST"),
Integer::New(env->isolate(), HTTP_REQUEST));
t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "RESPONSE"),
Integer::New(env->isolate(), HTTP_RESPONSE));
t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnHeaders"),
Integer::NewFromUnsigned(env->isolate(), kOnHeaders));
t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnHeadersComplete"),
Integer::NewFromUnsigned(env->isolate(), kOnHeadersComplete));
t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnBody"),
Integer::NewFromUnsigned(env->isolate(), kOnBody));
t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "kOnMessageComplete"),
Integer::NewFromUnsigned(env->isolate(), kOnMessageComplete));
Local<Array> methods = Array::New(env->isolate());
#define V(num, name, string) \
methods->Set(num, FIXED_ONE_BYTE_STRING(env->isolate(), #string));
HTTP_METHOD_MAP(V)
#undef V
t->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "methods"), methods);
env->SetProtoMethod(t, "close", Parser::Close);
env->SetProtoMethod(t, "execute", Parser::Execute);
env->SetProtoMethod(t, "finish", Parser::Finish);
env->SetProtoMethod(t, "reinitialize", Parser::Reinitialize);
env->SetProtoMethod(t, "pause", Parser::Pause<true>);
env->SetProtoMethod(t, "resume", Parser::Pause<false>);
target->Set(FIXED_ONE_BYTE_STRING(env->isolate(), "HTTPParser"),
t->GetFunction());
}
} // namespace node
NODE_MODULE_CONTEXT_AWARE_BUILTIN(http_parser, node::InitHttpParser)
|
// SPDX-License-Identifier: CC0-1.0
#include "gtest/gtest.h"
#include <experimental/expected.hpp>
#include <memory>
#include <tuple>
#include <vector>
using cxx20::expected;
using cxx20::unexpected;
namespace {
struct takes_init_and_variadic {
std::vector<int> v;
std::tuple<int, int> t;
template <class... Args>
takes_init_and_variadic(std::initializer_list<int> l, Args &&...args)
: v(l), t(std::forward<Args>(args)...) {}
};
} // namespace
TEST(EmplaceTest, Emplace) {
{
expected<std::unique_ptr<int>, int> e;
e.emplace(new int{42});
EXPECT_TRUE(e);
EXPECT_EQ(**e, 42);
}
{
expected<std::vector<int>, int> e;
e.emplace({0, 1});
EXPECT_TRUE(e);
EXPECT_EQ((*e)[0], 0);
EXPECT_EQ((*e)[1], 1);
}
{
expected<std::tuple<int, int>, int> e;
e.emplace(2, 3);
EXPECT_TRUE(e);
EXPECT_EQ(std::get<0>(*e), 2);
EXPECT_EQ(std::get<1>(*e), 3);
}
{
expected<takes_init_and_variadic, int> e = unexpected(0);
e.emplace({0, 1}, 2, 3);
EXPECT_TRUE(e);
EXPECT_EQ(e->v[0], 0);
EXPECT_EQ(e->v[1], 1);
EXPECT_EQ(std::get<0>(e->t), 2);
EXPECT_EQ(std::get<1>(e->t), 3);
}
}
|
#include "caffe2/utils/threadpool/ThreadPool.h"
#include "WorkersPool.h"
#include "caffe2/core/logging.h"
#include <cpuinfo.h>
C10_DEFINE_bool(
caffe2_threadpool_force_inline,
false,
"Force to always run jobs on the calling thread");
// Whether or not threadpool caps apply to Android
C10_DEFINE_int(caffe2_threadpool_android_cap, true, "");
// Whether or not threadpool caps apply to iOS and MacOS
C10_DEFINE_int(caffe2_threadpool_ios_cap, true, "");
C10_DEFINE_int(caffe2_threadpool_macos_cap, true, "");
C10_DEFINE_int(pthreadpool_size, 0, "Override the default thread pool size.");
namespace caffe2 {
size_t getDefaultNumThreads() {
CAFFE_ENFORCE(cpuinfo_initialize(), "cpuinfo initialization failed");
int numThreads = cpuinfo_get_processors_count();
bool applyCap = false;
#if defined(C10_ANDROID)
applyCap = FLAGS_caffe2_threadpool_android_cap;
#elif defined(C10_IOS)
applyCap = FLAGS_caffe2_threadpool_ios_cap;
#elif defined(TARGET_OS_MAC)
applyCap = FLAGS_caffe2_threadpool_macos_cap;
#endif
if (applyCap) {
switch (numThreads) {
#if defined(C10_ANDROID) && (CPUINFO_ARCH_ARM || CPUINFO_ARCH_ARM64)
case 4:
switch (cpuinfo_get_core(0)->midr & UINT32_C(0xFF00FFF0)) {
case UINT32_C(0x51002110): /* Snapdragon 820 Kryo Silver */
case UINT32_C(0x51002010): /* Snapdragon 821 Kryo Silver */
case UINT32_C(0x51002050): /* Snapdragon 820/821 Kryo Gold */
/* Kryo: 2+2 big.LITTLE */
numThreads = 2;
break;
default:
/* Anything else: assume homogeneous architecture */
numThreads = 4;
break;
}
break;
#endif
case 5:
/* 4+1 big.LITTLE */
numThreads = 4;
break;
case 6:
/* 2+4 big.LITTLE */
numThreads = 2;
break;
// NOLINTNEXTLINE(cppcoreguidelines-avoid-magic-numbers,bugprone-branch-clone)
case 8:
/* 4+4 big.LITTLE */
numThreads = 4;
break;
case 10:
/* 4+4+2 Min.Med.Max, running on Med cores */
numThreads = 4;
break;
default:
if (numThreads > 4) {
numThreads = numThreads / 2;
}
break;
}
}
if (FLAGS_pthreadpool_size) {
// Always give precedence to explicit setting.
numThreads = FLAGS_pthreadpool_size;
}
return numThreads;
}
// Default smallest amount of work that will be partitioned between
// multiple threads; the runtime value is configurable
constexpr size_t kDefaultMinWorkSize = 1;
size_t ThreadPool::defaultNumThreads_ = 0;
std::unique_ptr<ThreadPool> ThreadPool::defaultThreadPool() {
defaultNumThreads_ = getDefaultNumThreads();
LOG(INFO) << "Constructing thread pool with " << defaultNumThreads_
<< " threads";
return std::make_unique<ThreadPool>(defaultNumThreads_);
}
ThreadPool::ThreadPool(int numThreads)
: minWorkSize_(kDefaultMinWorkSize),
numThreads_(numThreads),
workersPool_(std::make_shared<WorkersPool>()) {}
// NOLINTNEXTLINE(modernize-use-equals-default)
ThreadPool::~ThreadPool() {}
int ThreadPool::getNumThreads() const {
return numThreads_;
}
// Sets the number of threads
// # of threads should not be bigger than the number of big cores
void ThreadPool::setNumThreads(size_t numThreads) {
if (defaultNumThreads_ == 0) {
defaultNumThreads_ = getDefaultNumThreads();
}
numThreads_ = std::min(numThreads, defaultNumThreads_);
}
// Sets the minimum work size (range) for which to invoke the
// threadpool; work sizes smaller than this will just be run on the
// main (calling) thread
void ThreadPool::setMinWorkSize(size_t size) {
std::lock_guard<std::mutex> guard(executionMutex_);
minWorkSize_ = size;
}
void ThreadPool::run(const std::function<void(int, size_t)>& fn, size_t range) {
const auto numThreads = numThreads_.load(std::memory_order_relaxed);
std::lock_guard<std::mutex> guard(executionMutex_);
// If there are no worker threads, or if the range is too small (too
// little work), just run locally
const bool runLocally = range < minWorkSize_ ||
FLAGS_caffe2_threadpool_force_inline || (numThreads == 0);
if (runLocally) {
// Work is small enough to just run locally; multithread overhead
// is too high
for (size_t i = 0; i < range; ++i) {
fn(0, i);
}
return;
}
struct FnTask : public Task {
// NOLINTNEXTLINE(modernize-use-equals-default,cppcoreguidelines-pro-type-member-init)
FnTask(){};
// NOLINTNEXTLINE(modernize-use-equals-default)
~FnTask() override{};
const std::function<void(int, size_t)>* fn_;
int idx_;
size_t start_;
size_t end_;
void Run() override {
for (auto i = start_; i < end_; ++i) {
(*fn_)(idx_, i);
}
}
};
CAFFE_ENFORCE_GE(numThreads_, 1);
const size_t unitsPerTask = (range + numThreads - 1) / numThreads;
tasks_.resize(numThreads);
for (size_t i = 0; i < numThreads; ++i) {
if (!tasks_[i]) {
// NOLINTNEXTLINE(modernize-make-shared)
tasks_[i].reset(new FnTask());
}
auto* task = (FnTask*)tasks_[i].get();
task->fn_ = &fn;
task->idx_ = i;
task->start_ = std::min<size_t>(range, i * unitsPerTask);
task->end_ = std::min<size_t>(range, (i + 1) * unitsPerTask);
if (task->start_ >= task->end_) {
tasks_.resize(i);
break;
}
CAFFE_ENFORCE_LE(task->start_, range);
CAFFE_ENFORCE_LE(task->end_, range);
}
CAFFE_ENFORCE_LE(tasks_.size(), numThreads);
CAFFE_ENFORCE_GE(tasks_.size(), 1);
workersPool_->Execute(tasks_);
}
void ThreadPool::withPool(const std::function<void(WorkersPool*)>& f) {
std::lock_guard<std::mutex> guard(executionMutex_);
f(workersPool_.get());
}
} // namespace caffe2
|
//
// Copyright (C) 2005-2010 Irene Ruengeler
// Copyright (C) 2009-2012 Thomas Dreibholz
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, see <http://www.gnu.org/licenses/>.
//
#include "inet/transportlayer/sctp/SCTP.h"
#include "inet/transportlayer/sctp/SCTPAssociation.h"
#include "inet/transportlayer/contract/sctp/SCTPCommand_m.h"
#include "inet/networklayer/common/IL3AddressType.h"
#include "inet/networklayer/contract/INetworkProtocolControlInfo.h"
#include "inet/networklayer/common/IPSocket.h"
#include "inet/common/ModuleAccess.h"
#ifdef WITH_IPv4
#include "inet/networklayer/ipv4/IPv4Datagram.h"
#endif // ifdef WITH_IPv4
#include "inet/transportlayer/contract/udp/UDPControlInfo_m.h"
#include "inet/transportlayer/contract/udp/UDPSocket.h"
namespace inet {
namespace sctp {
Define_Module(SCTP);
int32 SCTP::nextAssocId = 0;
void SCTP::printInfoAssocMap()
{
SCTPAssociation *assoc;
SockPair key;
EV_DETAIL << "Number of Assocs: " << sizeAssocMap << "\n";
if (sizeAssocMap > 0) {
for (SctpAssocMap::iterator i = sctpAssocMap.begin(); i != sctpAssocMap.end(); ++i) {
assoc = i->second;
key = i->first;
EV_DETAIL << "assocId: " << assoc->assocId << " assoc: " << assoc << " src: " << key.localAddr << " dst: " << key.remoteAddr << " lPort: " << key.localPort << " rPort: " << key.remotePort << "\n";
}
EV_DETAIL << "\n";
}
}
void SCTP::printVTagMap()
{
int32 assocId;
VTagPair key;
EV_DETAIL << "Number of Assocs: " << sctpVTagMap.size() << "\n";
if (sctpVTagMap.size() > 0) {
for (SctpVTagMap::iterator i = sctpVTagMap.begin(); i != sctpVTagMap.end(); ++i) {
assocId = i->first;
key = i->second;
EV_DETAIL << "assocId: " << assocId << " peerVTag: " << key.peerVTag
<< " localVTag: " << key.localVTag
<< " localPort: " << key.localPort << " rPort: " << key.remotePort << "\n";
}
EV_DETAIL << "\n";
}
}
void SCTP::bindPortForUDP()
{
EV_INFO << "Binding to UDP port " << SCTP_UDP_PORT << endl;
udpSocket.setOutputGate(gate("to_ip"));
udpSocket.bind(SCTP_UDP_PORT);
}
void SCTP::initialize(int stage)
{
cSimpleModule::initialize(stage);
if (stage == INITSTAGE_LOCAL) {
ift = getModuleFromPar<IInterfaceTable>(par("interfaceTableModule"), this);
rt = getModuleFromPar<IRoutingTable>(par("routingTableModule"), this);
this->auth = (bool)par("auth");
this->pktdrop = (bool)par("packetDrop");
this->sackNow = (bool)par("sackNow");
numPktDropReports = 0;
numPacketsReceived = 0;
numPacketsDropped = 0;
sizeAssocMap = 0;
nextEphemeralPort = (uint16)(intrand(10000) + 30000);
cModule *netw = simulation.getSystemModule();
if (netw->hasPar("testTimeout")) {
testTimeout = (simtime_t)netw->par("testTimeout");
}
}
else if (stage == INITSTAGE_TRANSPORT_LAYER) {
IPSocket socket(gate("to_ip"));
socket.registerProtocol(IP_PROT_SCTP);
}
else if (stage == INITSTAGE_TRANSPORT_LAYER_2) {
if (par("udpEncapsEnabled").boolValue()) {
bindPortForUDP();
}
}
}
SCTP::~SCTP()
{
EV_DEBUG << "delete SCTPMain\n";
if (!(sctpAppAssocMap.empty())) {
EV_DEBUG << "clear appConnMap ptr=" << &sctpAppAssocMap << "\n";
sctpAppAssocMap.clear();
}
if (!(assocStatMap.empty())) {
EV_DEBUG << "clear assocStatMap ptr=" << &assocStatMap << "\n";
assocStatMap.clear();
}
if (!(sctpVTagMap.empty())) {
sctpVTagMap.clear();
}
EV_DEBUG << "after clearing maps\n";
}
void SCTP::handleMessage(cMessage *msg)
{
L3Address destAddr;
L3Address srcAddr;
bool findListen = false;
bool bitError = false;
EV_DEBUG << "\n\nSCTPMain handleMessage at " << getFullPath() << "\n";
if (msg->isSelfMessage()) {
EV_DEBUG << "selfMessage\n";
SCTPAssociation *assoc = (SCTPAssociation *)msg->getContextPointer();
bool ret = assoc->processTimer(msg);
if (!ret)
removeAssociation(assoc);
}
else if (msg->arrivedOn("from_ip")) {
EV_INFO << "Message from IP\n";
printInfoAssocMap();
if (!dynamic_cast<SCTPMessage *>(msg)) {
EV_INFO << "no sctp message, delete it\n";
delete msg;
return;
}
SCTPMessage *sctpmsg = check_and_cast<SCTPMessage *>(msg);
numPacketsReceived++;
if (!pktdrop && (sctpmsg->hasBitError() || !(sctpmsg->getChecksumOk()))) {
EV_WARN << "Packet has bit-error. delete it\n";
bitError = true;
numPacketsDropped++;
delete msg;
return;
}
{
if (par("udpEncapsEnabled")) {
EV_DETAIL << "Size of SCTPMSG=" << sctpmsg->getByteLength() << "\n";
UDPDataIndication *ctrl = check_and_cast<UDPDataIndication *>(msg->removeControlInfo());
srcAddr = ctrl->getSrcAddr();
destAddr = ctrl->getDestAddr();
delete ctrl;
EV_INFO << "controlInfo srcAddr=" << srcAddr << " destAddr=" << destAddr << "\n";
EV_DETAIL << "VTag=" << sctpmsg->getTag() << "\n";
}
else {
INetworkProtocolControlInfo *controlInfo = check_and_cast<INetworkProtocolControlInfo *>(msg->removeControlInfo());
srcAddr = controlInfo->getSourceAddress();
destAddr = controlInfo->getDestinationAddress();
delete controlInfo;
EV_INFO << "controlInfo srcAddr=" << srcAddr << " destAddr=" << destAddr << "\n";
}
}
EV_INFO << "srcAddr=" << srcAddr << " destAddr=" << destAddr << "\n";
if (sctpmsg->getByteLength() > (SCTP_COMMON_HEADER)) {
if (((SCTPChunk *)(sctpmsg->getChunks(0)))->getChunkType() == INIT || ((SCTPChunk *)(sctpmsg->getChunks(0)))->getChunkType() == INIT_ACK)
findListen = true;
SCTPAssociation *assoc = findAssocForMessage(srcAddr, destAddr, sctpmsg->getSrcPort(), sctpmsg->getDestPort(), findListen);
if (!assoc && sctpAssocMap.size() > 0 && (((SCTPChunk *)(sctpmsg->getChunks(0)))->getChunkType() == ERRORTYPE
|| (sctpmsg->getChunksArraySize() > 1 &&
(((SCTPChunk *)(sctpmsg->getChunks(1)))->getChunkType() == ASCONF || ((SCTPChunk *)(sctpmsg->getChunks(1)))->getChunkType() == ASCONF_ACK))))
{
assoc = findAssocWithVTag(sctpmsg->getTag(), sctpmsg->getSrcPort(), sctpmsg->getDestPort());
}
if (!assoc) {
EV_INFO << "no assoc found msg=" << sctpmsg->getName() << "\n";
if (bitError) {
delete sctpmsg;
return;
}
if (((SCTPChunk *)(sctpmsg->getChunks(0)))->getChunkType() == SHUTDOWN_ACK)
sendShutdownCompleteFromMain(sctpmsg, destAddr, srcAddr);
else if (((SCTPChunk *)(sctpmsg->getChunks(0)))->getChunkType() != ABORT &&
((SCTPChunk *)(sctpmsg->getChunks(0)))->getChunkType() != SHUTDOWN_COMPLETE)
{
sendAbortFromMain(sctpmsg, destAddr, srcAddr);
}
delete sctpmsg;
}
else {
EV_INFO << "assoc " << assoc->assocId << "found\n";
bool ret = assoc->processSCTPMessage(sctpmsg, srcAddr, destAddr);
if (!ret) {
EV_DEBUG << "SCTPMain:: removeAssociation \n";
removeAssociation(assoc);
delete sctpmsg;
}
else {
delete sctpmsg;
}
}
}
else {
delete sctpmsg;
}
}
else { // must be from app
EV_DEBUG << "must be from app\n";
SCTPCommand *controlInfo = check_and_cast<SCTPCommand *>(msg->getControlInfo());
int32 appGateIndex;
if (controlInfo->getGate() != -1)
appGateIndex = controlInfo->getGate();
else
appGateIndex = msg->getArrivalGate()->getIndex();
int32 assocId = controlInfo->getAssocId();
EV_INFO << "msg arrived from app for assoc " << assocId << "\n";
SCTPAssociation *assoc = findAssocForApp(appGateIndex, assocId);
if (!assoc) {
EV_INFO << "no assoc found. msg=" << msg->getName() << " number of assocs = " << assocList.size() << "\n";
if (strcmp(msg->getName(), "PassiveOPEN") == 0 || strcmp(msg->getName(), "Associate") == 0) {
if (assocList.size() > 0) {
assoc = NULL;
SCTPOpenCommand *open = check_and_cast<SCTPOpenCommand *>(controlInfo);
EV_INFO << "Looking for assoc with remoteAddr=" << open->getRemoteAddr() << ", remotePort=" << open->getRemotePort() << ", localPort=" << open->getLocalPort() << "\n";
for (std::list<SCTPAssociation *>::iterator iter = assocList.begin(); iter != assocList.end(); iter++) {
EV_DETAIL << "remoteAddr=" << (*iter)->remoteAddr << ", remotePort=" << (*iter)->remotePort << ", localPort=" << (*iter)->localPort << "\n";
if ((*iter)->remoteAddr == open->getRemoteAddr() && (*iter)->localPort == open->getLocalPort() && (*iter)->remotePort == open->getRemotePort()) {
assoc = (*iter);
break;
}
}
}
if (assocList.size() == 0 || assoc == NULL) {
assoc = new SCTPAssociation(this, appGateIndex, assocId, rt, ift);
AppAssocKey key;
key.appGateIndex = appGateIndex;
key.assocId = assocId;
sctpAppAssocMap[key] = assoc;
EV_INFO << "SCTP association created for appGateIndex " << appGateIndex << " and assoc " << assocId << "\n";
bool ret = assoc->processAppCommand(PK(msg));
if (!ret) {
removeAssociation(assoc);
}
}
}
}
else {
EV_INFO << "assoc found\n";
bool ret = assoc->processAppCommand(PK(msg));
if (!ret)
removeAssociation(assoc);
}
delete msg;
}
if (ev.isGUI())
updateDisplayString();
}
void SCTP::sendAbortFromMain(SCTPMessage *sctpmsg, L3Address srcAddr, L3Address destAddr)
{
SCTPMessage *msg = new SCTPMessage();
EV_DEBUG << "\n\nSCTPMain:sendABORT \n";
msg->setSrcPort(sctpmsg->getDestPort());
msg->setDestPort(sctpmsg->getSrcPort());
msg->setBitLength(SCTP_COMMON_HEADER * 8);
msg->setChecksumOk(true);
SCTPAbortChunk *abortChunk = new SCTPAbortChunk("ABORT");
abortChunk->setChunkType(ABORT);
if (sctpmsg->getChunksArraySize() > 0 && ((SCTPChunk *)(sctpmsg->getChunks(0)))->getChunkType() == INIT) {
SCTPInitChunk *initChunk = check_and_cast<SCTPInitChunk *>(sctpmsg->getChunks(0));
abortChunk->setT_Bit(0);
msg->setTag(initChunk->getInitTag());
}
else {
abortChunk->setT_Bit(1);
msg->setTag(sctpmsg->getTag());
}
abortChunk->setBitLength(SCTP_ABORT_CHUNK_LENGTH * 8);
msg->addChunk(abortChunk);
if ((bool)par("udpEncapsEnabled")) {
EV_DETAIL << "VTag=" << msg->getTag() << "\n";
udpSocket.sendTo(msg, destAddr, SCTP_UDP_PORT);
}
else {
INetworkProtocolControlInfo *controlInfo = destAddr.getAddressType()->createNetworkProtocolControlInfo();
controlInfo->setTransportProtocol(IP_PROT_SCTP);
controlInfo->setSourceAddress(srcAddr);
controlInfo->setDestinationAddress(destAddr);
msg->setControlInfo(check_and_cast<cObject *>(controlInfo));
send(msg, "to_ip");
}
}
void SCTP::sendShutdownCompleteFromMain(SCTPMessage *sctpmsg, L3Address srcAddr, L3Address destAddr)
{
SCTPMessage *msg = new SCTPMessage();
EV_DEBUG << "\n\nSCTP:sendShutdownCompleteFromMain \n";
msg->setSrcPort(sctpmsg->getDestPort());
msg->setDestPort(sctpmsg->getSrcPort());
msg->setBitLength(SCTP_COMMON_HEADER * 8);
msg->setChecksumOk(true);
SCTPShutdownCompleteChunk *scChunk = new SCTPShutdownCompleteChunk("SHUTDOWN_COMPLETE");
scChunk->setChunkType(SHUTDOWN_COMPLETE);
scChunk->setTBit(1);
msg->setTag(sctpmsg->getTag());
scChunk->setBitLength(SCTP_SHUTDOWN_ACK_LENGTH * 8);
msg->addChunk(scChunk);
INetworkProtocolControlInfo *controlInfo = destAddr.getAddressType()->createNetworkProtocolControlInfo();
controlInfo->setTransportProtocol(IP_PROT_SCTP);
controlInfo->setSourceAddress(srcAddr);
controlInfo->setDestinationAddress(destAddr);
msg->setControlInfo(check_and_cast<cObject *>(controlInfo));
send(msg, "to_ip");
}
void SCTP::updateDisplayString()
{
#if 0
if (ev.disable_tracing) {
// in express mode, we don't bother to update the display
// (std::map's iteration is not very fast if map is large)
getDisplayString().setTagArg("t", 0, "");
return;
}
//char buf[40];
//sprintf(buf,"%d conns", sctpAppConnMap.size());
//displayString().setTagArg("t",0,buf);
int32 numCLOSED = 0, numLISTEN = 0, numSYN_SENT = 0, numSYN_RCVD = 0,
numESTABLISHED = 0, numCLOSE_WAIT = 0, numLAST_ACK = 0, numFIN_WAIT_1 = 0,
numFIN_WAIT_2 = 0, numCLOSING = 0, numTIME_WAIT = 0;
for (SctpAppConnMap::iterator i = sctpAppConnMap.begin(); i != sctpAppConnMap.end(); ++i) {
int32 state = (*i).second->getFsmState();
switch (state) {
// case SCTP_S_INIT: numINIT++; break;
case SCTP_S_CLOSED:
numCLOSED++;
break;
case SCTP_S_COOKIE_WAIT:
numLISTEN++;
break;
case SCTP_S_COOKIE_ECHOED:
numSYN_SENT++;
break;
case SCTP_S_ESTABLISHED:
numESTABLISHED++;
break;
case SCTP_S_SHUTDOWN_PENDING:
numCLOSE_WAIT++;
break;
case SCTP_S_SHUTDOWN_SENT:
numLAST_ACK++;
break;
case SCTP_S_SHUTDOWN_RECEIVED:
numFIN_WAIT_1++;
break;
case SCTP_S_SHUTDOWN_ACK_SENT:
numFIN_WAIT_2++;
break;
}
}
char buf2[300];
buf2[0] = '\0';
if (numCLOSED > 0)
sprintf(buf2 + strlen(buf2), "closed:%d ", numCLOSED);
if (numLISTEN > 0)
sprintf(buf2 + strlen(buf2), "listen:%d ", numLISTEN);
if (numSYN_SENT > 0)
sprintf(buf2 + strlen(buf2), "syn_sent:%d ", numSYN_SENT);
if (numSYN_RCVD > 0)
sprintf(buf2 + strlen(buf2), "syn_rcvd:%d ", numSYN_RCVD);
if (numESTABLISHED > 0)
sprintf(buf2 + strlen(buf2), "estab:%d ", numESTABLISHED);
if (numCLOSE_WAIT > 0)
sprintf(buf2 + strlen(buf2), "close_wait:%d ", numCLOSE_WAIT);
if (numLAST_ACK > 0)
sprintf(buf2 + strlen(buf2), "last_ack:%d ", numLAST_ACK);
if (numFIN_WAIT_1 > 0)
sprintf(buf2 + strlen(buf2), "fin_wait_1:%d ", numFIN_WAIT_1);
if (numFIN_WAIT_2 > 0)
sprintf(buf2 + strlen(buf2), "fin_wait_2:%d ", numFIN_WAIT_2);
if (numCLOSING > 0)
sprintf(buf2 + strlen(buf2), "closing:%d ", numCLOSING);
if (numTIME_WAIT > 0)
sprintf(buf2 + strlen(buf2), "time_wait:%d ", numTIME_WAIT);
getDisplayString().setTagArg("t", 0, buf2);
#endif // if 0
}
SCTPAssociation *SCTP::findAssocWithVTag(uint32 peerVTag, uint32 remotePort, uint32 localPort)
{
printVTagMap();
EV_DEBUG << "findAssocWithVTag: peerVTag=" << peerVTag << " srcPort=" << remotePort << " destPort=" << localPort << "\n";
printInfoAssocMap();
// try with fully qualified SockPair
for (SctpVTagMap::iterator i = sctpVTagMap.begin(); i != sctpVTagMap.end(); i++) {
if ((i->second.peerVTag == peerVTag && i->second.localPort == localPort
&& i->second.remotePort == remotePort)
|| (i->second.localVTag == peerVTag && i->second.localPort == localPort
&& i->second.remotePort == remotePort))
return getAssoc(i->first);
}
return NULL;
}
SCTPAssociation *SCTP::findAssocForMessage(L3Address srcAddr, L3Address destAddr, uint32 srcPort, uint32 destPort, bool findListen)
{
SockPair key;
key.localAddr = destAddr;
key.remoteAddr = srcAddr;
key.localPort = destPort;
key.remotePort = srcPort;
SockPair save = key;
EV_DEBUG << "findAssocForMessage: srcAddr=" << destAddr << " destAddr=" << srcAddr << " srcPort=" << destPort << " destPort=" << srcPort << "\n";
printInfoAssocMap();
// try with fully qualified SockPair
SctpAssocMap::iterator i;
i = sctpAssocMap.find(key);
if (i != sctpAssocMap.end())
return i->second;
// try with localAddr missing (only localPort specified in passive/active open)
key.localAddr = L3Address();
i = sctpAssocMap.find(key);
if (i != sctpAssocMap.end()) {
// try with localAddr missing (only localPort specified in passive/active open)
return i->second;
}
if (findListen == true) {
// try fully qualified local socket + blank remote socket (for incoming SYN)
key = save;
key.remoteAddr = L3Address();
key.remotePort = 0;
i = sctpAssocMap.find(key);
if (i != sctpAssocMap.end()) {
// try fully qualified local socket + blank remote socket
return i->second;
}
// try with blank remote socket, and localAddr missing (for incoming SYN)
key.localAddr = L3Address();
i = sctpAssocMap.find(key);
if (i != sctpAssocMap.end()) {
// try with blank remote socket, and localAddr missing
return i->second;
}
}
// given up
EV_INFO << "giving up on trying to find assoc for localAddr=" << srcAddr << " remoteAddr=" << destAddr << " localPort=" << srcPort << " remotePort=" << destPort << "\n";
return NULL;
}
SCTPAssociation *SCTP::findAssocForApp(int32 appGateIndex, int32 assocId)
{
AppAssocKey key;
key.appGateIndex = appGateIndex;
key.assocId = assocId;
EV_INFO << "findAssoc for appGateIndex " << appGateIndex << " and assoc " << assocId << "\n";
SctpAppAssocMap::iterator i = sctpAppAssocMap.find(key);
return (i == sctpAppAssocMap.end()) ? NULL : i->second;
}
uint16 SCTP::getEphemeralPort()
{
if (nextEphemeralPort == 5000)
throw cRuntimeError("Ephemeral port range 1024..4999 exhausted (email SCTP model "
"author that he should implement reuse of ephemeral ports!!!)");
return nextEphemeralPort++;
}
void SCTP::updateSockPair(SCTPAssociation *assoc, L3Address localAddr, L3Address remoteAddr, int32 localPort, int32 remotePort)
{
SockPair key;
EV_INFO << "updateSockPair: localAddr: " << localAddr << " remoteAddr=" << remoteAddr << " localPort=" << localPort << " remotePort=" << remotePort << "\n";
key.localAddr = (assoc->localAddr = localAddr);
key.remoteAddr = (assoc->remoteAddr = remoteAddr);
key.localPort = assoc->localPort = localPort;
key.remotePort = assoc->remotePort = remotePort;
for (SctpAssocMap::iterator i = sctpAssocMap.begin(); i != sctpAssocMap.end(); i++) {
if (i->second == assoc) {
sctpAssocMap.erase(i);
break;
}
}
EV_INFO << "updateSockPair assoc=" << assoc << " localAddr=" << key.localAddr << " remoteAddr=" << key.remoteAddr << " localPort=" << key.localPort << " remotePort=" << remotePort << "\n";
sctpAssocMap[key] = assoc;
sizeAssocMap = sctpAssocMap.size();
EV_DEBUG << "assoc inserted in sctpAssocMap\n";
printInfoAssocMap();
}
void SCTP::addLocalAddress(SCTPAssociation *assoc, L3Address address)
{
SockPair key;
key.localAddr = assoc->localAddr;
key.remoteAddr = assoc->remoteAddr;
key.localPort = assoc->localPort;
key.remotePort = assoc->remotePort;
SctpAssocMap::iterator i = sctpAssocMap.find(key);
if (i != sctpAssocMap.end()) {
ASSERT(i->second == assoc);
if (key.localAddr.isUnspecified()) {
sctpAssocMap.erase(i);
sizeAssocMap--;
}
}
else
EV_INFO << "no actual sockPair found\n";
key.localAddr = address;
sctpAssocMap[key] = assoc;
sizeAssocMap = sctpAssocMap.size();
EV_INFO << "addLocalAddress " << address << " number of connections now=" << sizeAssocMap << "\n";
printInfoAssocMap();
}
void SCTP::addLocalAddressToAllRemoteAddresses(SCTPAssociation *assoc, L3Address address, std::vector<L3Address> remAddresses)
{
SockPair key;
for (AddressVector::iterator i = remAddresses.begin(); i != remAddresses.end(); ++i) {
//EV_DEBUG<<"remote address="<<(*i)<<"\n";
key.localAddr = assoc->localAddr;
key.remoteAddr = (*i);
key.localPort = assoc->localPort;
key.remotePort = assoc->remotePort;
SctpAssocMap::iterator j = sctpAssocMap.find(key);
if (j != sctpAssocMap.end()) {
ASSERT(j->second == assoc);
if (key.localAddr.isUnspecified()) {
sctpAssocMap.erase(j);
sizeAssocMap--;
}
}
else
EV_INFO << "no actual sockPair found\n";
key.localAddr = address;
sctpAssocMap[key] = assoc;
sizeAssocMap++;
EV_DEBUG << "number of connections=" << sctpAssocMap.size() << "\n";
printInfoAssocMap();
}
}
void SCTP::removeLocalAddressFromAllRemoteAddresses(SCTPAssociation *assoc, L3Address address, std::vector<L3Address> remAddresses)
{
SockPair key;
for (AddressVector::iterator i = remAddresses.begin(); i != remAddresses.end(); ++i) {
key.localAddr = address;
key.remoteAddr = (*i);
key.localPort = assoc->localPort;
key.remotePort = assoc->remotePort;
SctpAssocMap::iterator j = sctpAssocMap.find(key);
if (j != sctpAssocMap.end()) {
ASSERT(j->second == assoc);
sctpAssocMap.erase(j);
sizeAssocMap--;
}
else
EV_INFO << "no actual sockPair found\n";
printInfoAssocMap();
}
}
void SCTP::removeRemoteAddressFromAllAssociations(SCTPAssociation *assoc, L3Address address, std::vector<L3Address> locAddresses)
{
SockPair key;
for (AddressVector::iterator i = locAddresses.begin(); i != locAddresses.end(); i++) {
key.localAddr = (*i);
key.remoteAddr = address;
key.localPort = assoc->localPort;
key.remotePort = assoc->remotePort;
SctpAssocMap::iterator j = sctpAssocMap.find(key);
if (j != sctpAssocMap.end()) {
ASSERT(j->second == assoc);
sctpAssocMap.erase(j);
sizeAssocMap--;
}
else
EV_INFO << "no actual sockPair found\n";
printInfoAssocMap();
}
}
bool SCTP::addRemoteAddress(SCTPAssociation *assoc, L3Address localAddress, L3Address remoteAddress)
{
EV_INFO << "Add remote Address: " << remoteAddress << " to local Address " << localAddress << "\n";
SockPair key;
key.localAddr = localAddress;
key.remoteAddr = remoteAddress;
key.localPort = assoc->localPort;
key.remotePort = assoc->remotePort;
SctpAssocMap::iterator i = sctpAssocMap.find(key);
if (i != sctpAssocMap.end()) {
ASSERT(i->second == assoc);
return false;
}
else {
sctpAssocMap[key] = assoc;
sizeAssocMap++;
}
printInfoAssocMap();
return true;
}
void SCTP::addForkedAssociation(SCTPAssociation *assoc, SCTPAssociation *newAssoc, L3Address localAddr, L3Address remoteAddr, int32 localPort, int32 remotePort)
{
SockPair keyAssoc;
EV_INFO << "addForkedConnection assocId=" << assoc->assocId << " newId=" << newAssoc->assocId << "\n";
for (SctpAssocMap::iterator j = sctpAssocMap.begin(); j != sctpAssocMap.end(); ++j)
if (assoc->assocId == j->second->assocId)
keyAssoc = j->first;
// update assoc's socket pair, and register newAssoc (which'll keep LISTENing)
updateSockPair(assoc, localAddr, remoteAddr, localPort, remotePort);
updateSockPair(newAssoc, keyAssoc.localAddr, keyAssoc.remoteAddr, keyAssoc.localPort, keyAssoc.remotePort);
// assoc will get a new assocId...
AppAssocKey key;
key.appGateIndex = assoc->appGateIndex;
key.assocId = assoc->assocId;
sctpAppAssocMap.erase(key);
key.assocId = assoc->assocId = getNewAssocId();
sctpAppAssocMap[key] = assoc;
// ...and newAssoc will live on with the old assocId
key.appGateIndex = newAssoc->appGateIndex;
key.assocId = newAssoc->assocId;
sctpAppAssocMap[key] = newAssoc;
sizeAssocMap = sctpAssocMap.size();
printInfoAssocMap();
}
void SCTP::removeAssociation(SCTPAssociation *assoc)
{
bool ok = false;
bool find = false;
const int32 id = assoc->assocId;
EV_INFO << "Deleting SCTP connection " << assoc << " id= " << id << endl;
printInfoAssocMap();
if (sizeAssocMap > 0) {
AssocStatMap::iterator assocStatMapIterator = assocStatMap.find(assoc->assocId);
if (assocStatMapIterator != assocStatMap.end()) {
assocStatMapIterator->second.stop = simulation.getSimTime();
assocStatMapIterator->second.lifeTime = assocStatMapIterator->second.stop - assocStatMapIterator->second.start;
assocStatMapIterator->second.throughput = assocStatMapIterator->second.ackedBytes * 8 / assocStatMapIterator->second.lifeTime.dbl();
}
while (!ok) {
if (sizeAssocMap == 0) {
ok = true;
}
else {
for (SctpAssocMap::iterator sctpAssocMapIterator = sctpAssocMap.begin();
sctpAssocMapIterator != sctpAssocMap.end(); sctpAssocMapIterator++)
{
if (sctpAssocMapIterator->second != NULL) {
SCTPAssociation *myAssoc = sctpAssocMapIterator->second;
if (myAssoc->assocId == assoc->assocId) {
if (myAssoc->T1_InitTimer) {
myAssoc->stopTimer(myAssoc->T1_InitTimer);
}
if (myAssoc->T2_ShutdownTimer) {
myAssoc->stopTimer(myAssoc->T2_ShutdownTimer);
}
if (myAssoc->T5_ShutdownGuardTimer) {
myAssoc->stopTimer(myAssoc->T5_ShutdownGuardTimer);
}
if (myAssoc->SackTimer) {
myAssoc->stopTimer(myAssoc->SackTimer);
}
if (myAssoc->StartAddIP) {
myAssoc->stopTimer(myAssoc->StartAddIP);
}
sctpAssocMap.erase(sctpAssocMapIterator);
sizeAssocMap--;
find = true;
break;
}
}
}
}
if (!find) {
ok = true;
}
else {
find = false;
}
}
}
// Write statistics
char str[128];
for (SCTPAssociation::SCTPPathMap::iterator pathMapIterator = assoc->sctpPathMap.begin();
pathMapIterator != assoc->sctpPathMap.end(); pathMapIterator++)
{
const SCTPPathVariables *path = pathMapIterator->second;
snprintf((char *)&str, sizeof(str), "Number of Fast Retransmissions %d:%s",
assoc->assocId, path->remoteAddress.str().c_str());
recordScalar(str, path->numberOfFastRetransmissions);
snprintf((char *)&str, sizeof(str), "Number of Timer-Based Retransmissions %d:%s",
assoc->assocId, path->remoteAddress.str().c_str());
recordScalar(str, path->numberOfTimerBasedRetransmissions);
snprintf((char *)&str, sizeof(str), "Number of Heartbeats Sent %d:%s",
assoc->assocId, path->remoteAddress.str().c_str());
recordScalar(str, path->numberOfHeartbeatsSent);
snprintf((char *)&str, sizeof(str), "Number of Heartbeats Received %d:%s",
assoc->assocId, path->remoteAddress.str().c_str());
recordScalar(str, path->numberOfHeartbeatsRcvd);
snprintf((char *)&str, sizeof(str), "Number of Heartbeat ACKs Sent %d:%s",
assoc->assocId, path->remoteAddress.str().c_str());
recordScalar(str, path->numberOfHeartbeatAcksSent);
snprintf((char *)&str, sizeof(str), "Number of Heartbeat ACKs Received %d:%s",
assoc->assocId, path->remoteAddress.str().c_str());
recordScalar(str, path->numberOfHeartbeatAcksRcvd);
snprintf((char *)&str, sizeof(str), "Number of Duplicates %d:%s",
assoc->assocId, path->remoteAddress.str().c_str());
recordScalar(str, path->numberOfDuplicates);
snprintf((char *)&str, sizeof(str), "Number of Bytes received from %d:%s",
assoc->assocId, path->remoteAddress.str().c_str());
recordScalar(str, path->numberOfBytesReceived);
}
for (uint16 i = 0; i < assoc->inboundStreams; i++) {
snprintf((char *)&str, sizeof(str), "Bytes received on stream %d of assoc %d",
i, assoc->assocId);
recordScalar(str, assoc->getState()->streamThroughput[i]);
}
recordScalar("Blocking TSNs Moved", assoc->state->blockingTSNsMoved);
assoc->removePath();
assoc->deleteStreams();
// Chunks may be in the transmission and retransmission queues simultaneously.
// Remove entry from transmission queue if it is already in the retransmission queue.
for (SCTPQueue::PayloadQueue::iterator i = assoc->getRetransmissionQueue()->payloadQueue.begin();
i != assoc->getRetransmissionQueue()->payloadQueue.end(); i++)
{
SCTPQueue::PayloadQueue::iterator j = assoc->getTransmissionQueue()->payloadQueue.find(i->second->tsn);
if (j != assoc->getTransmissionQueue()->payloadQueue.end()) {
assoc->getTransmissionQueue()->payloadQueue.erase(j);
}
}
// Now, both queues can be safely deleted.
delete assoc->getRetransmissionQueue();
delete assoc->getTransmissionQueue();
AppAssocKey key;
key.appGateIndex = assoc->appGateIndex;
key.assocId = assoc->assocId;
sctpAppAssocMap.erase(key);
assocList.remove(assoc);
delete assoc;
}
SCTPAssociation *SCTP::getAssoc(int32 assocId)
{
for (SctpAppAssocMap::iterator i = sctpAppAssocMap.begin(); i != sctpAppAssocMap.end(); i++) {
if (i->first.assocId == assocId)
return i->second;
}
return NULL;
}
void SCTP::finish()
{
SctpAssocMap::iterator assocMapIterator = sctpAssocMap.begin();
while (assocMapIterator != sctpAssocMap.end()) {
removeAssociation(assocMapIterator->second);
assocMapIterator = sctpAssocMap.begin();
}
EV_INFO << getFullPath() << ": finishing SCTP with "
<< sctpAssocMap.size() << " connections open." << endl;
for (AssocStatMap::const_iterator iterator = assocStatMap.begin();
iterator != assocStatMap.end(); iterator++)
{
const SCTP::AssocStat& assoc = iterator->second;
EV_DETAIL << "Association " << assoc.assocId << ": started at " << assoc.start
<< " and finished at " << assoc.stop << " --> lifetime: " << assoc.lifeTime << endl;
EV_DETAIL << "Association " << assoc.assocId << ": sent bytes=" << assoc.sentBytes
<< ", acked bytes=" << assoc.ackedBytes << ", throughput=" << assoc.throughput << " bit/s" << endl;
EV_DETAIL << "Association " << assoc.assocId << ": transmitted Bytes="
<< assoc.transmittedBytes << ", retransmitted Bytes=" << assoc.transmittedBytes - assoc.ackedBytes << endl;
EV_DETAIL << "Association " << assoc.assocId << ": number of Fast RTX="
<< assoc.numFastRtx << ", number of Timer-Based RTX=" << assoc.numT3Rtx
<< ", path failures=" << assoc.numPathFailures << ", ForwardTsns=" << assoc.numForwardTsn << endl;
EV_DETAIL << "AllMessages=" << numPacketsReceived << " BadMessages=" << numPacketsDropped << endl;
recordScalar("Association Lifetime", assoc.lifeTime);
recordScalar("Acked Bytes", assoc.ackedBytes);
recordScalar("Throughput [bit/s]", assoc.throughput);
recordScalar("Transmitted Bytes", assoc.transmittedBytes);
recordScalar("Fast RTX", assoc.numFastRtx);
recordScalar("Timer-Based RTX", assoc.numT3Rtx);
recordScalar("Duplicate Acks", assoc.numDups);
recordScalar("Packets Received", numPacketsReceived);
recordScalar("Packets Dropped", numPacketsDropped);
recordScalar("Sum of R Gap Ranges", assoc.sumRGapRanges);
recordScalar("Sum of NR Gap Ranges", assoc.sumNRGapRanges);
recordScalar("Overfull SACKs", assoc.numOverfullSACKs);
recordScalar("Drops Because New TSN Greater Than Highest TSN", assoc.numDropsBecauseNewTSNGreaterThanHighestTSN);
recordScalar("Drops Because No Room In Buffer", assoc.numDropsBecauseNoRoomInBuffer);
recordScalar("Chunks Reneged", assoc.numChunksReneged);
recordScalar("sackPeriod", (simtime_t)par("sackPeriod"));
recordScalar("Number of AUTH chunks sent", assoc.numAuthChunksSent);
recordScalar("Number of AUTH chunks accepted", assoc.numAuthChunksAccepted);
recordScalar("Number of AUTH chunks rejected", assoc.numAuthChunksRejected);
recordScalar("Number of StreamReset requests sent", assoc.numResetRequestsSent);
recordScalar("Number of StreamReset requests performed", assoc.numResetRequestsPerformed);
if ((double)par("fairStart") > 0) {
recordScalar("fair acked bytes", assoc.fairAckedBytes);
recordScalar("fair start time", assoc.fairStart);
recordScalar("fair stop time", assoc.fairStop);
recordScalar("fair lifetime", assoc.fairLifeTime);
recordScalar("fair throughput", assoc.fairThroughput);
}
recordScalar("Number of PacketDrop Reports", numPktDropReports);
if (assoc.numEndToEndMessages > 0 && (assoc.cumEndToEndDelay / assoc.numEndToEndMessages) > 0) {
uint32 msgnum = assoc.numEndToEndMessages - assoc.startEndToEndDelay;
if (assoc.stopEndToEndDelay > 0)
msgnum -= (assoc.numEndToEndMessages - assoc.stopEndToEndDelay);
recordScalar("Average End to End Delay", assoc.cumEndToEndDelay / msgnum);
}
recordScalar("RTXMethod", (double)par("RTXMethod"));
}
}
} // namespace sctp
} // namespace inet
|
// Copyright 2018 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/chromeos/cryptauth/gcm_device_info_provider_impl.h"
#include "base/linux_util.h"
#include "base/no_destructor.h"
#include "base/sys_info.h"
#include "base/version.h"
#include "chrome/browser/chrome_content_browser_client.h"
#include "chrome/browser/chromeos/cryptauth/cryptauth_device_id_provider_impl.h"
#include "components/cryptauth/cryptauth_enrollment_utils.h"
#include "components/version_info/version_info.h"
namespace chromeos {
// static
const GcmDeviceInfoProviderImpl* GcmDeviceInfoProviderImpl::GetInstance() {
static const base::NoDestructor<GcmDeviceInfoProviderImpl> provider;
return provider.get();
}
const cryptauth::GcmDeviceInfo& GcmDeviceInfoProviderImpl::GetGcmDeviceInfo()
const {
static const base::NoDestructor<cryptauth::GcmDeviceInfo> gcm_device_info([] {
static const google::protobuf::int64 kSoftwareVersionCode =
cryptauth::HashStringToInt64(version_info::GetLastChange());
cryptauth::GcmDeviceInfo gcm_device_info;
gcm_device_info.set_long_device_id(
cryptauth::CryptAuthDeviceIdProviderImpl::GetInstance()->GetDeviceId());
gcm_device_info.set_device_type(cryptauth::CHROME);
gcm_device_info.set_device_software_version(
version_info::GetVersionNumber());
gcm_device_info.set_device_software_version_code(kSoftwareVersionCode);
gcm_device_info.set_locale(
ChromeContentBrowserClient().GetApplicationLocale());
gcm_device_info.set_device_model(base::SysInfo::GetLsbReleaseBoard());
gcm_device_info.set_device_os_version(base::GetLinuxDistro());
// The Chrome OS version tracks the Chrome version, so fill in the same
// value as |device_kSoftwareVersionCode|.
gcm_device_info.set_device_os_version_code(kSoftwareVersionCode);
// |device_display_diagonal_mils| is unused because it only applies to
// phones/tablets, but it must be set due to server API verification.
gcm_device_info.set_device_display_diagonal_mils(0);
// Set all supported features.
gcm_device_info.add_supported_software_features(
cryptauth::SoftwareFeature::BETTER_TOGETHER_CLIENT);
gcm_device_info.add_supported_software_features(
cryptauth::SoftwareFeature::EASY_UNLOCK_CLIENT);
gcm_device_info.add_supported_software_features(
cryptauth::SoftwareFeature::MAGIC_TETHER_CLIENT);
gcm_device_info.add_supported_software_features(
cryptauth::SoftwareFeature::SMS_CONNECT_CLIENT);
return gcm_device_info;
}());
return *gcm_device_info;
}
GcmDeviceInfoProviderImpl::GcmDeviceInfoProviderImpl() = default;
} // namespace chromeos
|
#include "util/tc_docker.h"
#include "util/tc_http.h"
#include "util/tc_http_async.h"
#include "util/tc_base64.h"
#include "util/tc_json.h"
namespace tars
{
//
//class AsyncHttpCallback : public TC_HttpAsync::RequestCallback
//{
//public:
// AsyncHttpCallback()//std::mutex &m, std::condition_variable &cond ): _m(m), _cond(cond)
// {
// }
//
// virtual void onSucc(TC_HttpResponse& stHttpResponse)
// {
//// LOG_CONSOLE_DEBUG << stHttpResponse.getContent() << endl;
// _succ = true;
// _rsp = stHttpResponse;
// }
//
// virtual void onFailed(FAILED_CODE ret, const string& info)
// {
//// LOG_CONSOLE_DEBUG << ret << ":" << info << endl;
//
// _errMessage = info;
// std::unique_lock<std::mutex> lock(_m);
// _terminate = true;
// _cond.notify_one();
// }
//
// virtual void onClose()
// {
//// LOG_CONSOLE_DEBUG << _rsp.getContent() << endl;
//
// std::unique_lock<std::mutex> lock(_m);
// _terminate = true;
// _cond.notify_one();
// }
//
// void wait()
// {
// std::unique_lock<std::mutex> lock(_m);
//
// if (_terminate)
// {
// return;
// }
// _cond.wait(lock);
// }
//
//public:
// std::mutex _m;
// std::condition_variable _cond;
//
// bool _succ = false;
// bool _terminate = false;
// string _errMessage;
// TC_HttpResponse _rsp;
//};
//
// bool TC_Docker::createHttpRequest(TC_HttpRequest &request)
// {
// TC_HttpAsync ast;
// ast.setTimeout(_requestTimeout);
// ast.start();
//
// AsyncHttpCallback* callback = new AsyncHttpCallback();
//
// TC_HttpAsync::RequestCallbackPtr p(callback);
//
// request.setHeader("X-Registry-Auth", this->_authenticationStr);
// if (!request.hasHeader("Content-Type"))
// {
// request.setHeader("Content-Type", "application/tar");
// }
//
// request.setHost("localhost");
//// LOG_CONSOLE_DEBUG << request.encode() << endl;
//
// ast.doAsyncRequest(request, p);
//
// callback->wait();
// ast.waitForAllDone();
//
//// LOG_CONSOLE_DEBUG << callback->_rsp.encode() << endl;
//
// _responseMessage = TC_Common::trimright(callback->_rsp.getContent());
//
// if (callback->_succ && (callback->_rsp.getStatus() >= 200 && callback->_rsp.getStatus() < 300))
// {
// return true;
// }
// else
// {
// if (!callback->_rsp.getContent().empty())
// {
// _errMessage = TC_Common::trimright(callback->_rsp.getContent());
// }
// else if(!callback->_errMessage.empty())
// {
// _errMessage = "{ \"message\": \"" + callback->_errMessage + "\"}";
// }
// else
// {
// _errMessage = "{ \"message\": \"" + callback->_rsp.getAbout() + "\"}";
// }
//
// return false;
// }
// }
void TC_Docker::setDockerUnixLocal(const string& unixSocket)
{
_dockerUrl = TC_Common::replace(unixSocket, FILE_SEP, "$") + ":0";
}
bool TC_Docker::createHttpRequest(TC_HttpRequest& request)
{
request.setHeader("X-Registry-Auth", this->_authenticationStr);
if (!request.hasHeader("Content-Type"))
{
request.setHeader("Content-Type", "application/tar");
}
request.setHost("localhost");
TC_HttpResponse response;
int ret = request.doRequest(response, this->_requestTimeout);
if(ret != 0)
{
_errMessage = "http request docker error, ret:" + TC_Common::tostr(ret);
return false;
}
_responseMessage = TC_Common::trimright(response.getContent());
if ( response.getStatus() >= 200 && response.getStatus() < 300)
{
return true;
}
else
{
if (!response.getContent().empty())
{
_errMessage = TC_Common::trimright(response.getContent());
}
else
{
_errMessage = "{ \"message\": \"" + response.getAbout() + "\"}";
}
return false;
}
}
void TC_Docker::setAuthentication(const string& useName, const string& password, const string& serverAddress)
{
_authentication.useName = useName;
_authentication.password = password;
_authentication.serverAddress = serverAddress;
JsonValueObjPtr obj = new JsonValueObj();
obj->value["username"] = new JsonValueString(useName);
obj->value["password"] = new JsonValueString(password);
obj->value["serveraddress"] = new JsonValueString(serverAddress);
_authenticationStr = TC_Base64::encode(TC_Json::writeValue(obj));
}
bool TC_Docker::login(const string& useName, const string& password, const string& serverAddress)
{
JsonValueObjPtr obj = new JsonValueObj();
obj->value["username"] = new JsonValueString(useName);
obj->value["password"] = new JsonValueString(password);
obj->value["serveraddress"] = new JsonValueString(serverAddress);
TC_HttpRequest request;
request.setPostRequest(_dockerUrl + "/" + _dockerApiVersion + "/auth", TC_Json::writeValue(obj));
bool flag = createHttpRequest(request);
if (flag)
{
JsonValueObjPtr result = JsonValueObjPtr::dynamicCast(TC_Json::getValue(getResponseMessage()));
auto it = result->value.find("Status");
if (it != result->value.end())
{
JsonValueStringPtr v = JsonValueStringPtr::dynamicCast(it->second);
if (v && v->value == "Login Succeeded")
{
return true;
}
}
else
{
this->_errMessage = JsonValueStringPtr::dynamicCast(result->value["message"])->value;
}
}
return false;
}
bool TC_Docker::pull(const string& image)
{
TC_HttpRequest request;
request.setPostRequest(_dockerUrl + "/" + _dockerApiVersion + "/images/create?fromImage=" + image,
_authenticationStr);
return createHttpRequest(request);
}
bool TC_Docker::create(const string& name,
const string& image,
const vector<string>& entrypoint,
const vector<string>& commands,
const vector<string>& envs,
const map<string, string>& mounts,
const map<string, pair<string, int>>& ports,
const string& restartPolicy,
int maximumRetryCount,
const string& networkMode,
const string& ipcMode,
bool autoRemove,
bool privileged)
{
TC_HttpRequest request;
JsonValueObjPtr obj = new JsonValueObj();
obj->value["Image"] = new JsonValueString(image);
if (!entrypoint.empty())
{
JsonValueArrayPtr ePtr = new JsonValueArray();
obj->value["Entrypoint"] = ePtr;
for (auto& e: entrypoint)
{
ePtr->value.push_back(new JsonValueString(e));
}
}
if (!commands.empty())
{
JsonValueArrayPtr cmd = new JsonValueArray();
obj->value["Cmd"] = cmd;
for (auto& c: commands)
{
cmd->value.push_back(new JsonValueString(c));
}
}
if (!envs.empty())
{
JsonValueArrayPtr env = new JsonValueArray();
obj->value["Env"] = env;
for (auto& e: envs)
{
env->value.push_back(new JsonValueString(e));
}
}
JsonValueObjPtr hostConfig = new JsonValueObj();
obj->value["HostConfig"] = hostConfig;
hostConfig->value["NetworkMode"] = new JsonValueString(networkMode);
if (!ports.empty())
{
JsonValueObjPtr espec = new JsonValueObj();
obj->value["ExposedPorts"] = espec;
JsonValueObjPtr portBindings = new JsonValueObj();
hostConfig->value["PortBindings"] = portBindings;
for (auto e: ports)
{
espec->value[e.first] = new JsonValueObj();
JsonValueArrayPtr hostPort = new JsonValueArray();
JsonValueObjPtr hObj = new JsonValueObj();
hObj->value["HostIp"] = new JsonValueString(e.second.first);
hObj->value["HostPort"] = new JsonValueString(TC_Common::tostr(e.second.second));
hostPort->push_back(hObj);
portBindings->value[e.first] = hostPort;
}
}
if (!mounts.empty())
{
JsonValueArrayPtr Mounts = new JsonValueArray();
hostConfig->value["Mounts"] = Mounts;
for (auto e: mounts)
{
JsonValueObjPtr mObj = new JsonValueObj();
mObj->value["Source"] = new JsonValueString(e.first);
mObj->value["Target"] = new JsonValueString(e.second);
mObj->value["Type"] = new JsonValueString("bind");
Mounts->push_back(mObj);
}
}
if (!restartPolicy.empty())
{
JsonValueObjPtr rObj = new JsonValueObj();
rObj->value["RestartPolicy"] = new JsonValueString(restartPolicy);
rObj->value["maximumRetryCount"] = new JsonValueNum((int64_t)maximumRetryCount, true);
hostConfig->value["RestartPolicy"] = rObj;
}
// JsonValueArrayPtr shell = new JsonValueArray();
// shell->value.push_back(new JsonValueString("bash"));
// shell->value.push_back(new JsonValueString("bash"));
// shell->value.push_back(new JsonValueString("bash"));
// hostConfig->value["Shell"] = shell;
hostConfig->value["WorkingDir"] = new JsonValueString("/");
hostConfig->value["AutoRemove"] = new JsonValueBoolean(autoRemove);
hostConfig->value["Privileged"] = new JsonValueBoolean(privileged);
string json = TC_Json::writeValue(obj);
request.setPostRequest(_dockerUrl + "/" + _dockerApiVersion + "/containers/create?name=" + name, json);
request.setHeader("Content-Type", "application/json");
return createHttpRequest(request);
}
bool TC_Docker::exec(const string& name, const vector<string>& commands, const vector<string>& envs, bool privileged)
{
TC_HttpRequest request;
JsonValueObjPtr obj = new JsonValueObj();
if (!commands.empty())
{
JsonValueArrayPtr cmd = new JsonValueArray();
obj->value["Cmd"] = cmd;
for (auto& c: commands)
{
cmd->value.push_back(new JsonValueString(c));
}
}
if (!envs.empty())
{
JsonValueArrayPtr env = new JsonValueArray();
obj->value["Env"] = env;
for (auto& e: envs)
{
env->value.push_back(new JsonValueString(e));
}
}
obj->value["WorkingDir"] = new JsonValueString("/");
obj->value["Privileged"] = new JsonValueBoolean(privileged);
string json = TC_Json::writeValue(obj);
request.setPostRequest(_dockerUrl + "/" + _dockerApiVersion + "/containers/" + name + "/exec", json);
request.setHeader("Content-Type", "application/json");
return createHttpRequest(request);
}
bool TC_Docker::start(const string& containerId)
{
TC_HttpRequest request;
request.setPostRequest(_dockerUrl + "/" + _dockerApiVersion + "/containers/" + containerId + "/start", "");
return createHttpRequest(request);
}
bool TC_Docker::stop(const string& containerId, size_t waitSeconds)
{
TC_HttpRequest request;
request.setPostRequest(_dockerUrl + "/" + _dockerApiVersion + "/containers/" + containerId + "/stop?t=" +
TC_Common::tostr(waitSeconds), "");
return createHttpRequest(request);
}
bool TC_Docker::remove(const string& containerId, bool force)
{
TC_HttpRequest request;
request.setDeleteRequest(_dockerUrl + "/" + _dockerApiVersion + "/containers/" + containerId + "?force=" +
string(force ? "true" : "false"), "");
return createHttpRequest(request);
}
bool TC_Docker::inspectContainer(const string& containerId)
{
TC_HttpRequest request;
request.setGetRequest(_dockerUrl + "/" + _dockerApiVersion + "/containers/" + containerId + "/json");
return createHttpRequest(request);
}
bool TC_Docker::inspectImage(const string& imageId)
{
TC_HttpRequest request;
request.setGetRequest(_dockerUrl + "/" + _dockerApiVersion + "/images/" + imageId + "/json");
return createHttpRequest(request);
}
}
|
// Copyright 2012 the V8 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.
#include "src/ast/scopes.h"
#include <set>
#include "src/ast/ast.h"
#include "src/base/logging.h"
#include "src/base/optional.h"
#include "src/builtins/accessors.h"
#include "src/common/message-template.h"
#include "src/heap/off-thread-factory-inl.h"
#include "src/init/bootstrapper.h"
#include "src/logging/counters.h"
#include "src/objects/module-inl.h"
#include "src/objects/objects-inl.h"
#include "src/objects/scope-info.h"
#include "src/parsing/parse-info.h"
#include "src/parsing/parser.h"
#include "src/parsing/preparse-data.h"
#include "src/zone/zone-list-inl.h"
namespace v8 {
namespace internal {
// ----------------------------------------------------------------------------
// Implementation of LocalsMap
//
// Note: We are storing the handle locations as key values in the hash map.
// When inserting a new variable via Declare(), we rely on the fact that
// the handle location remains alive for the duration of that variable
// use. Because a Variable holding a handle with the same location exists
// this is ensured.
VariableMap::VariableMap(Zone* zone)
: ZoneHashMap(8, ZoneAllocationPolicy(zone)) {}
Variable* VariableMap::Declare(Zone* zone, Scope* scope,
const AstRawString* name, VariableMode mode,
VariableKind kind,
InitializationFlag initialization_flag,
MaybeAssignedFlag maybe_assigned_flag,
IsStaticFlag is_static_flag, bool* was_added) {
// AstRawStrings are unambiguous, i.e., the same string is always represented
// by the same AstRawString*.
// FIXME(marja): fix the type of Lookup.
Entry* p =
ZoneHashMap::LookupOrInsert(const_cast<AstRawString*>(name), name->Hash(),
ZoneAllocationPolicy(zone));
*was_added = p->value == nullptr;
if (*was_added) {
// The variable has not been declared yet -> insert it.
DCHECK_EQ(name, p->key);
Variable* variable =
new (zone) Variable(scope, name, mode, kind, initialization_flag,
maybe_assigned_flag, is_static_flag);
p->value = variable;
}
return reinterpret_cast<Variable*>(p->value);
}
void VariableMap::Remove(Variable* var) {
const AstRawString* name = var->raw_name();
ZoneHashMap::Remove(const_cast<AstRawString*>(name), name->Hash());
}
void VariableMap::Add(Zone* zone, Variable* var) {
const AstRawString* name = var->raw_name();
Entry* p =
ZoneHashMap::LookupOrInsert(const_cast<AstRawString*>(name), name->Hash(),
ZoneAllocationPolicy(zone));
DCHECK_NULL(p->value);
DCHECK_EQ(name, p->key);
p->value = var;
}
Variable* VariableMap::Lookup(const AstRawString* name) {
Entry* p = ZoneHashMap::Lookup(const_cast<AstRawString*>(name), name->Hash());
if (p != nullptr) {
DCHECK(reinterpret_cast<const AstRawString*>(p->key) == name);
DCHECK_NOT_NULL(p->value);
return reinterpret_cast<Variable*>(p->value);
}
return nullptr;
}
// ----------------------------------------------------------------------------
// Implementation of Scope
Scope::Scope(Zone* zone)
: zone_(zone),
outer_scope_(nullptr),
variables_(zone),
scope_type_(SCRIPT_SCOPE) {
SetDefaults();
}
Scope::Scope(Zone* zone, Scope* outer_scope, ScopeType scope_type)
: zone_(zone),
outer_scope_(outer_scope),
variables_(zone),
scope_type_(scope_type) {
DCHECK_NE(SCRIPT_SCOPE, scope_type);
SetDefaults();
set_language_mode(outer_scope->language_mode());
private_name_lookup_skips_outer_class_ =
outer_scope->is_class_scope() &&
outer_scope->AsClassScope()->IsParsingHeritage();
outer_scope_->AddInnerScope(this);
}
DeclarationScope::DeclarationScope(Zone* zone,
AstValueFactory* ast_value_factory,
REPLMode repl_mode)
: Scope(zone),
function_kind_(repl_mode == REPLMode::kYes ? kAsyncFunction
: kNormalFunction),
params_(4, zone) {
DCHECK_EQ(scope_type_, SCRIPT_SCOPE);
SetDefaults();
is_repl_mode_scope_ = repl_mode == REPLMode::kYes;
receiver_ = DeclareDynamicGlobal(ast_value_factory->this_string(),
THIS_VARIABLE, this);
}
DeclarationScope::DeclarationScope(Zone* zone, Scope* outer_scope,
ScopeType scope_type,
FunctionKind function_kind)
: Scope(zone, outer_scope, scope_type),
function_kind_(function_kind),
params_(4, zone) {
DCHECK_NE(scope_type, SCRIPT_SCOPE);
SetDefaults();
}
ModuleScope::ModuleScope(DeclarationScope* script_scope,
AstValueFactory* avfactory)
: DeclarationScope(avfactory->zone(), script_scope, MODULE_SCOPE, kModule),
module_descriptor_(new (avfactory->zone())
SourceTextModuleDescriptor(avfactory->zone())) {
set_language_mode(LanguageMode::kStrict);
DeclareThis(avfactory);
}
ModuleScope::ModuleScope(Isolate* isolate, Handle<ScopeInfo> scope_info,
AstValueFactory* avfactory)
: DeclarationScope(avfactory->zone(), MODULE_SCOPE, scope_info),
module_descriptor_(nullptr) {
set_language_mode(LanguageMode::kStrict);
}
ClassScope::ClassScope(Zone* zone, Scope* outer_scope, bool is_anonymous)
: Scope(zone, outer_scope, CLASS_SCOPE),
rare_data_and_is_parsing_heritage_(nullptr),
is_anonymous_class_(is_anonymous) {
set_language_mode(LanguageMode::kStrict);
}
ClassScope::ClassScope(Isolate* isolate, Zone* zone,
AstValueFactory* ast_value_factory,
Handle<ScopeInfo> scope_info)
: Scope(zone, CLASS_SCOPE, scope_info),
rare_data_and_is_parsing_heritage_(nullptr) {
set_language_mode(LanguageMode::kStrict);
if (scope_info->HasClassBrand()) {
Variable* brand =
LookupInScopeInfo(ast_value_factory->dot_brand_string(), this);
DCHECK_NOT_NULL(brand);
EnsureRareData()->brand = brand;
}
// If the class variable is context-allocated and its index is
// saved for deserialization, deserialize it.
if (scope_info->HasSavedClassVariableIndex()) {
int index = scope_info->SavedClassVariableContextLocalIndex();
DCHECK_GE(index, 0);
DCHECK_LT(index, scope_info->ContextLocalCount());
String name = scope_info->ContextLocalName(index);
DCHECK_EQ(scope_info->ContextLocalMode(index), VariableMode::kConst);
DCHECK_EQ(scope_info->ContextLocalInitFlag(index),
InitializationFlag::kNeedsInitialization);
DCHECK_EQ(scope_info->ContextLocalMaybeAssignedFlag(index),
MaybeAssignedFlag::kMaybeAssigned);
Variable* var = DeclareClassVariable(
ast_value_factory, ast_value_factory->GetString(handle(name, isolate)),
kNoSourcePosition);
var->AllocateTo(VariableLocation::CONTEXT,
Context::MIN_CONTEXT_SLOTS + index);
}
}
Scope::Scope(Zone* zone, ScopeType scope_type, Handle<ScopeInfo> scope_info)
: zone_(zone),
outer_scope_(nullptr),
variables_(zone),
scope_info_(scope_info),
scope_type_(scope_type) {
DCHECK(!scope_info.is_null());
SetDefaults();
#ifdef DEBUG
already_resolved_ = true;
#endif
set_language_mode(scope_info->language_mode());
DCHECK_EQ(ContextHeaderLength(), num_heap_slots_);
private_name_lookup_skips_outer_class_ =
scope_info->PrivateNameLookupSkipsOuterClass();
// We don't really need to use the preparsed scope data; this is just to
// shorten the recursion in SetMustUsePreparseData.
must_use_preparsed_scope_data_ = true;
}
DeclarationScope::DeclarationScope(Zone* zone, ScopeType scope_type,
Handle<ScopeInfo> scope_info)
: Scope(zone, scope_type, scope_info),
function_kind_(scope_info->function_kind()),
params_(0, zone) {
DCHECK_NE(scope_type, SCRIPT_SCOPE);
SetDefaults();
if (scope_info->SloppyEvalCanExtendVars()) {
DCHECK(!is_eval_scope());
sloppy_eval_can_extend_vars_ = true;
}
}
Scope::Scope(Zone* zone, const AstRawString* catch_variable_name,
MaybeAssignedFlag maybe_assigned, Handle<ScopeInfo> scope_info)
: zone_(zone),
outer_scope_(nullptr),
variables_(zone),
scope_info_(scope_info),
scope_type_(CATCH_SCOPE) {
SetDefaults();
#ifdef DEBUG
already_resolved_ = true;
#endif
// Cache the catch variable, even though it's also available via the
// scope_info, as the parser expects that a catch scope always has the catch
// variable as first and only variable.
bool was_added;
Variable* variable =
Declare(zone, catch_variable_name, VariableMode::kVar, NORMAL_VARIABLE,
kCreatedInitialized, maybe_assigned, &was_added);
DCHECK(was_added);
AllocateHeapSlot(variable);
}
void DeclarationScope::SetDefaults() {
is_declaration_scope_ = true;
has_simple_parameters_ = true;
is_asm_module_ = false;
force_eager_compilation_ = false;
has_arguments_parameter_ = false;
scope_uses_super_property_ = false;
has_checked_syntax_ = false;
has_this_reference_ = false;
has_this_declaration_ =
(is_function_scope() && !is_arrow_scope()) || is_module_scope();
needs_private_name_context_chain_recalc_ = false;
has_rest_ = false;
receiver_ = nullptr;
new_target_ = nullptr;
function_ = nullptr;
arguments_ = nullptr;
rare_data_ = nullptr;
should_eager_compile_ = false;
was_lazily_parsed_ = false;
is_skipped_function_ = false;
preparse_data_builder_ = nullptr;
#ifdef DEBUG
DeclarationScope* outer_declaration_scope =
outer_scope_ ? outer_scope_->GetDeclarationScope() : nullptr;
is_being_lazily_parsed_ =
outer_declaration_scope ? outer_declaration_scope->is_being_lazily_parsed_
: false;
#endif
}
void Scope::SetDefaults() {
#ifdef DEBUG
scope_name_ = nullptr;
already_resolved_ = false;
needs_migration_ = false;
#endif
inner_scope_ = nullptr;
sibling_ = nullptr;
unresolved_list_.Clear();
start_position_ = kNoSourcePosition;
end_position_ = kNoSourcePosition;
calls_eval_ = false;
sloppy_eval_can_extend_vars_ = false;
scope_nonlinear_ = false;
is_hidden_ = false;
is_debug_evaluate_scope_ = false;
inner_scope_calls_eval_ = false;
force_context_allocation_for_parameters_ = false;
is_declaration_scope_ = false;
private_name_lookup_skips_outer_class_ = false;
must_use_preparsed_scope_data_ = false;
is_repl_mode_scope_ = false;
deserialized_scope_uses_external_cache_ = false;
num_stack_slots_ = 0;
num_heap_slots_ = ContextHeaderLength();
set_language_mode(LanguageMode::kSloppy);
}
bool Scope::HasSimpleParameters() {
DeclarationScope* scope = GetClosureScope();
return !scope->is_function_scope() || scope->has_simple_parameters();
}
void DeclarationScope::set_should_eager_compile() {
should_eager_compile_ = !was_lazily_parsed_;
}
void DeclarationScope::set_is_asm_module() { is_asm_module_ = true; }
bool Scope::IsAsmModule() const {
return is_function_scope() && AsDeclarationScope()->is_asm_module();
}
bool Scope::ContainsAsmModule() const {
if (IsAsmModule()) return true;
// Check inner scopes recursively
for (Scope* scope = inner_scope_; scope != nullptr; scope = scope->sibling_) {
// Don't check inner functions which won't be eagerly compiled.
if (!scope->is_function_scope() ||
scope->AsDeclarationScope()->ShouldEagerCompile()) {
if (scope->ContainsAsmModule()) return true;
}
}
return false;
}
Scope* Scope::DeserializeScopeChain(Isolate* isolate, Zone* zone,
ScopeInfo scope_info,
DeclarationScope* script_scope,
AstValueFactory* ast_value_factory,
DeserializationMode deserialization_mode) {
// Reconstruct the outer scope chain from a closure's context chain.
Scope* current_scope = nullptr;
Scope* innermost_scope = nullptr;
Scope* outer_scope = nullptr;
bool cache_scope_found = false;
while (!scope_info.is_null()) {
if (scope_info.scope_type() == WITH_SCOPE) {
if (scope_info.IsDebugEvaluateScope()) {
outer_scope = new (zone)
DeclarationScope(zone, FUNCTION_SCOPE, handle(scope_info, isolate));
outer_scope->set_is_debug_evaluate_scope();
} else {
// For scope analysis, debug-evaluate is equivalent to a with scope.
outer_scope =
new (zone) Scope(zone, WITH_SCOPE, handle(scope_info, isolate));
}
} else if (scope_info.scope_type() == SCRIPT_SCOPE) {
// If we reach a script scope, it's the outermost scope. Install the
// scope info of this script context onto the existing script scope to
// avoid nesting script scopes.
if (deserialization_mode == DeserializationMode::kIncludingVariables) {
script_scope->SetScriptScopeInfo(handle(scope_info, isolate));
}
if (scope_info.IsReplModeScope()) script_scope->set_is_repl_mode_scope();
DCHECK(!scope_info.HasOuterScopeInfo());
break;
} else if (scope_info.scope_type() == FUNCTION_SCOPE) {
outer_scope = new (zone)
DeclarationScope(zone, FUNCTION_SCOPE, handle(scope_info, isolate));
if (scope_info.IsAsmModule()) {
outer_scope->AsDeclarationScope()->set_is_asm_module();
}
} else if (scope_info.scope_type() == EVAL_SCOPE) {
outer_scope = new (zone)
DeclarationScope(zone, EVAL_SCOPE, handle(scope_info, isolate));
} else if (scope_info.scope_type() == CLASS_SCOPE) {
outer_scope = new (zone) ClassScope(isolate, zone, ast_value_factory,
handle(scope_info, isolate));
} else if (scope_info.scope_type() == BLOCK_SCOPE) {
if (scope_info.is_declaration_scope()) {
outer_scope = new (zone)
DeclarationScope(zone, BLOCK_SCOPE, handle(scope_info, isolate));
} else {
outer_scope =
new (zone) Scope(zone, BLOCK_SCOPE, handle(scope_info, isolate));
}
} else if (scope_info.scope_type() == MODULE_SCOPE) {
outer_scope = new (zone)
ModuleScope(isolate, handle(scope_info, isolate), ast_value_factory);
} else {
DCHECK_EQ(scope_info.scope_type(), CATCH_SCOPE);
DCHECK_EQ(scope_info.ContextLocalCount(), 1);
DCHECK_EQ(scope_info.ContextLocalMode(0), VariableMode::kVar);
DCHECK_EQ(scope_info.ContextLocalInitFlag(0), kCreatedInitialized);
String name = scope_info.ContextLocalName(0);
MaybeAssignedFlag maybe_assigned =
scope_info.ContextLocalMaybeAssignedFlag(0);
outer_scope = new (zone)
Scope(zone, ast_value_factory->GetString(handle(name, isolate)),
maybe_assigned, handle(scope_info, isolate));
}
if (deserialization_mode == DeserializationMode::kScopesOnly) {
outer_scope->scope_info_ = Handle<ScopeInfo>::null();
}
if (cache_scope_found) {
outer_scope->set_deserialized_scope_uses_external_cache();
} else {
DCHECK(!cache_scope_found);
cache_scope_found =
outer_scope->is_declaration_scope() && !outer_scope->is_eval_scope();
}
if (current_scope != nullptr) {
outer_scope->AddInnerScope(current_scope);
}
current_scope = outer_scope;
if (innermost_scope == nullptr) innermost_scope = current_scope;
scope_info = scope_info.HasOuterScopeInfo() ? scope_info.OuterScopeInfo()
: ScopeInfo();
}
if (deserialization_mode == DeserializationMode::kIncludingVariables &&
script_scope->scope_info_.is_null()) {
script_scope->SetScriptScopeInfo(
ReadOnlyRoots(isolate).global_this_binding_scope_info_handle());
}
if (innermost_scope == nullptr) return script_scope;
script_scope->AddInnerScope(current_scope);
return innermost_scope;
}
DeclarationScope* Scope::AsDeclarationScope() {
DCHECK(is_declaration_scope());
return static_cast<DeclarationScope*>(this);
}
const DeclarationScope* Scope::AsDeclarationScope() const {
DCHECK(is_declaration_scope());
return static_cast<const DeclarationScope*>(this);
}
ModuleScope* Scope::AsModuleScope() {
DCHECK(is_module_scope());
return static_cast<ModuleScope*>(this);
}
const ModuleScope* Scope::AsModuleScope() const {
DCHECK(is_module_scope());
return static_cast<const ModuleScope*>(this);
}
ClassScope* Scope::AsClassScope() {
DCHECK(is_class_scope());
return static_cast<ClassScope*>(this);
}
const ClassScope* Scope::AsClassScope() const {
DCHECK(is_class_scope());
return static_cast<const ClassScope*>(this);
}
void DeclarationScope::DeclareSloppyBlockFunction(
SloppyBlockFunctionStatement* sloppy_block_function) {
sloppy_block_functions_.Add(sloppy_block_function);
}
void DeclarationScope::HoistSloppyBlockFunctions(AstNodeFactory* factory) {
DCHECK(is_sloppy(language_mode()));
DCHECK(is_function_scope() || is_eval_scope() || is_script_scope() ||
(is_block_scope() && outer_scope()->is_function_scope()));
DCHECK(HasSimpleParameters() || is_block_scope() || is_being_lazily_parsed_);
DCHECK_EQ(factory == nullptr, is_being_lazily_parsed_);
if (sloppy_block_functions_.is_empty()) return;
// In case of complex parameters the current scope is the body scope and the
// parameters are stored in the outer scope.
Scope* parameter_scope = HasSimpleParameters() ? this : outer_scope_;
DCHECK(parameter_scope->is_function_scope() || is_eval_scope() ||
is_script_scope());
DeclarationScope* decl_scope = GetNonEvalDeclarationScope();
Scope* outer_scope = decl_scope->outer_scope();
// For each variable which is used as a function declaration in a sloppy
// block,
for (SloppyBlockFunctionStatement* sloppy_block_function :
sloppy_block_functions_) {
const AstRawString* name = sloppy_block_function->name();
// If the variable wouldn't conflict with a lexical declaration
// or parameter,
// Check if there's a conflict with a parameter.
Variable* maybe_parameter = parameter_scope->LookupLocal(name);
if (maybe_parameter != nullptr && maybe_parameter->is_parameter()) {
continue;
}
// Check if there's a conflict with a lexical declaration
Scope* query_scope = sloppy_block_function->scope()->outer_scope();
Variable* var = nullptr;
bool should_hoist = true;
// It is not sufficient to just do a Lookup on query_scope: for
// example, that does not prevent hoisting of the function in
// `{ let e; try {} catch (e) { function e(){} } }`
//
// Don't use a generic cache scope, as the cache scope would be the outer
// scope and we terminate the iteration there anyway.
do {
var = query_scope->LookupInScopeOrScopeInfo(name, query_scope);
if (var != nullptr && IsLexicalVariableMode(var->mode())) {
should_hoist = false;
break;
}
query_scope = query_scope->outer_scope();
} while (query_scope != outer_scope);
if (!should_hoist) continue;
if (factory) {
DCHECK(!is_being_lazily_parsed_);
int pos = sloppy_block_function->position();
bool ok = true;
bool was_added;
auto declaration = factory->NewVariableDeclaration(pos);
// Based on the preceding checks, it doesn't matter what we pass as
// sloppy_mode_block_scope_function_redefinition.
Variable* var = DeclareVariable(
declaration, name, pos, VariableMode::kVar, NORMAL_VARIABLE,
Variable::DefaultInitializationFlag(VariableMode::kVar), &was_added,
nullptr, &ok);
DCHECK(ok);
VariableProxy* source =
factory->NewVariableProxy(sloppy_block_function->var());
VariableProxy* target = factory->NewVariableProxy(var);
Assignment* assignment = factory->NewAssignment(
sloppy_block_function->init(), target, source, pos);
assignment->set_lookup_hoisting_mode(LookupHoistingMode::kLegacySloppy);
Statement* statement = factory->NewExpressionStatement(assignment, pos);
sloppy_block_function->set_statement(statement);
} else {
DCHECK(is_being_lazily_parsed_);
bool was_added;
Variable* var = DeclareVariableName(name, VariableMode::kVar, &was_added);
if (sloppy_block_function->init() == Token::ASSIGN) {
var->SetMaybeAssigned();
}
}
}
}
bool DeclarationScope::Analyze(ParseInfo* info) {
RuntimeCallTimerScope runtimeTimer(
info->runtime_call_stats(), RuntimeCallCounterId::kCompileScopeAnalysis,
RuntimeCallStats::kThreadSpecific);
DCHECK_NOT_NULL(info->literal());
DeclarationScope* scope = info->literal()->scope();
base::Optional<AllowHandleDereference> allow_deref;
if (!info->maybe_outer_scope_info().is_null()) {
// Allow dereferences to the scope info if there is one.
allow_deref.emplace();
}
if (scope->is_eval_scope() && is_sloppy(scope->language_mode())) {
AstNodeFactory factory(info->ast_value_factory(), info->zone());
scope->HoistSloppyBlockFunctions(&factory);
}
// We are compiling one of four cases:
// 1) top-level code,
// 2) a function/eval/module on the top-level
// 3) a function/eval in a scope that was already resolved.
DCHECK(scope->is_script_scope() || scope->outer_scope()->is_script_scope() ||
scope->outer_scope()->already_resolved_);
// The outer scope is never lazy.
scope->set_should_eager_compile();
if (scope->must_use_preparsed_scope_data_) {
DCHECK_EQ(scope->scope_type_, ScopeType::FUNCTION_SCOPE);
allow_deref.emplace();
info->consumed_preparse_data()->RestoreScopeAllocationData(
scope, info->ast_value_factory());
}
if (!scope->AllocateVariables(info)) return false;
scope->GetScriptScope()->RewriteReplGlobalVariables();
#ifdef DEBUG
if (FLAG_print_scopes) {
PrintF("Global scope:\n");
scope->Print();
}
scope->CheckScopePositions();
scope->CheckZones();
#endif
return true;
}
void DeclarationScope::DeclareThis(AstValueFactory* ast_value_factory) {
DCHECK(has_this_declaration());
bool derived_constructor = IsDerivedConstructor(function_kind_);
receiver_ = new (zone())
Variable(this, ast_value_factory->this_string(),
derived_constructor ? VariableMode::kConst : VariableMode::kVar,
THIS_VARIABLE,
derived_constructor ? kNeedsInitialization : kCreatedInitialized,
kNotAssigned);
}
void DeclarationScope::DeclareArguments(AstValueFactory* ast_value_factory) {
DCHECK(is_function_scope());
DCHECK(!is_arrow_scope());
// Declare 'arguments' variable which exists in all non arrow functions. Note
// that it might never be accessed, in which case it won't be allocated during
// variable allocation.
bool was_added;
arguments_ =
Declare(zone(), ast_value_factory->arguments_string(), VariableMode::kVar,
NORMAL_VARIABLE, kCreatedInitialized, kNotAssigned, &was_added);
if (!was_added && IsLexicalVariableMode(arguments_->mode())) {
// Check if there's lexically declared variable named arguments to avoid
// redeclaration. See ES#sec-functiondeclarationinstantiation, step 20.
arguments_ = nullptr;
}
}
void DeclarationScope::DeclareDefaultFunctionVariables(
AstValueFactory* ast_value_factory) {
DCHECK(is_function_scope());
DCHECK(!is_arrow_scope());
DeclareThis(ast_value_factory);
bool was_added;
new_target_ = Declare(zone(), ast_value_factory->new_target_string(),
VariableMode::kConst, NORMAL_VARIABLE,
kCreatedInitialized, kNotAssigned, &was_added);
DCHECK(was_added);
if (IsConciseMethod(function_kind_) || IsClassConstructor(function_kind_) ||
IsAccessorFunction(function_kind_)) {
EnsureRareData()->this_function = Declare(
zone(), ast_value_factory->this_function_string(), VariableMode::kConst,
NORMAL_VARIABLE, kCreatedInitialized, kNotAssigned, &was_added);
DCHECK(was_added);
}
}
Variable* DeclarationScope::DeclareFunctionVar(const AstRawString* name,
Scope* cache) {
DCHECK(is_function_scope());
DCHECK_NULL(function_);
if (cache == nullptr) cache = this;
DCHECK(this->IsOuterScopeOf(cache));
DCHECK_NULL(cache->variables_.Lookup(name));
VariableKind kind = is_sloppy(language_mode()) ? SLOPPY_FUNCTION_NAME_VARIABLE
: NORMAL_VARIABLE;
function_ = new (zone())
Variable(this, name, VariableMode::kConst, kind, kCreatedInitialized);
if (sloppy_eval_can_extend_vars()) {
cache->NonLocal(name, VariableMode::kDynamic);
} else {
cache->variables_.Add(zone(), function_);
}
return function_;
}
Variable* DeclarationScope::DeclareGeneratorObjectVar(
const AstRawString* name) {
DCHECK(is_function_scope() || is_module_scope() || is_repl_mode_scope());
DCHECK_NULL(generator_object_var());
Variable* result = EnsureRareData()->generator_object =
NewTemporary(name, kNotAssigned);
result->set_is_used();
return result;
}
Scope* Scope::FinalizeBlockScope() {
DCHECK(is_block_scope());
#ifdef DEBUG
DCHECK_NE(sibling_, this);
#endif
if (variables_.occupancy() > 0 ||
(is_declaration_scope() &&
AsDeclarationScope()->sloppy_eval_can_extend_vars())) {
return this;
}
DCHECK(!is_class_scope());
// Remove this scope from outer scope.
outer_scope()->RemoveInnerScope(this);
// Reparent inner scopes.
if (inner_scope_ != nullptr) {
Scope* scope = inner_scope_;
scope->outer_scope_ = outer_scope();
while (scope->sibling_ != nullptr) {
scope = scope->sibling_;
scope->outer_scope_ = outer_scope();
}
scope->sibling_ = outer_scope()->inner_scope_;
outer_scope()->inner_scope_ = inner_scope_;
inner_scope_ = nullptr;
}
// Move unresolved variables
if (!unresolved_list_.is_empty()) {
outer_scope()->unresolved_list_.Prepend(std::move(unresolved_list_));
unresolved_list_.Clear();
}
if (inner_scope_calls_eval_) outer_scope()->inner_scope_calls_eval_ = true;
// No need to propagate sloppy_eval_can_extend_vars_, since if it was relevant
// to this scope we would have had to bail out at the top.
DCHECK(!is_declaration_scope() ||
!AsDeclarationScope()->sloppy_eval_can_extend_vars());
// This block does not need a context.
num_heap_slots_ = 0;
// Mark scope as removed by making it its own sibling.
#ifdef DEBUG
sibling_ = this;
#endif
return nullptr;
}
void DeclarationScope::AddLocal(Variable* var) {
DCHECK(!already_resolved_);
// Temporaries are only placed in ClosureScopes.
DCHECK_EQ(GetClosureScope(), this);
locals_.Add(var);
}
void Scope::Snapshot::Reparent(DeclarationScope* new_parent) {
DCHECK(!IsCleared());
DCHECK_EQ(new_parent, outer_scope_and_calls_eval_.GetPointer()->inner_scope_);
DCHECK_EQ(new_parent->outer_scope_, outer_scope_and_calls_eval_.GetPointer());
DCHECK_EQ(new_parent, new_parent->GetClosureScope());
DCHECK_NULL(new_parent->inner_scope_);
DCHECK(new_parent->unresolved_list_.is_empty());
Scope* inner_scope = new_parent->sibling_;
if (inner_scope != top_inner_scope_) {
for (; inner_scope->sibling() != top_inner_scope_;
inner_scope = inner_scope->sibling()) {
inner_scope->outer_scope_ = new_parent;
if (inner_scope->inner_scope_calls_eval_) {
new_parent->inner_scope_calls_eval_ = true;
}
DCHECK_NE(inner_scope, new_parent);
}
inner_scope->outer_scope_ = new_parent;
if (inner_scope->inner_scope_calls_eval_) {
new_parent->inner_scope_calls_eval_ = true;
}
new_parent->inner_scope_ = new_parent->sibling_;
inner_scope->sibling_ = nullptr;
// Reset the sibling rather than the inner_scope_ since we
// want to keep new_parent there.
new_parent->sibling_ = top_inner_scope_;
}
Scope* outer_scope_ = outer_scope_and_calls_eval_.GetPointer();
new_parent->unresolved_list_.MoveTail(&outer_scope_->unresolved_list_,
top_unresolved_);
// Move temporaries allocated for complex parameter initializers.
DeclarationScope* outer_closure = outer_scope_->GetClosureScope();
for (auto it = top_local_; it != outer_closure->locals()->end(); ++it) {
Variable* local = *it;
DCHECK_EQ(VariableMode::kTemporary, local->mode());
DCHECK_EQ(local->scope(), local->scope()->GetClosureScope());
DCHECK_NE(local->scope(), new_parent);
local->set_scope(new_parent);
}
new_parent->locals_.MoveTail(outer_closure->locals(), top_local_);
outer_closure->locals_.Rewind(top_local_);
// Move eval calls since Snapshot's creation into new_parent.
if (outer_scope_and_calls_eval_->calls_eval_) {
new_parent->RecordDeclarationScopeEvalCall();
new_parent->inner_scope_calls_eval_ = true;
}
// We are in the arrow function case. The calls eval we may have recorded
// is intended for the inner scope and we should simply restore the
// original "calls eval" flag of the outer scope.
RestoreEvalFlag();
Clear();
}
void Scope::ReplaceOuterScope(Scope* outer) {
DCHECK_NOT_NULL(outer);
DCHECK_NOT_NULL(outer_scope_);
DCHECK(!already_resolved_);
outer_scope_->RemoveInnerScope(this);
outer->AddInnerScope(this);
outer_scope_ = outer;
}
Variable* Scope::LookupInScopeInfo(const AstRawString* name, Scope* cache) {
DCHECK(!scope_info_.is_null());
DCHECK(this->IsOuterScopeOf(cache));
DCHECK(!cache->deserialized_scope_uses_external_cache());
// The case where where the cache can be another scope is when the cache scope
// is the last scope that doesn't use an external cache.
DCHECK_IMPLIES(
cache != this,
cache->outer_scope()->deserialized_scope_uses_external_cache());
DCHECK_NULL(cache->variables_.Lookup(name));
DisallowHeapAllocation no_gc;
String name_handle = *name->string().get_handle();
ScopeInfo scope_info = *scope_info_.get_handle();
// The Scope is backed up by ScopeInfo. This means it cannot operate in a
// heap-independent mode, and all strings must be internalized immediately. So
// it's ok to get the Handle<String> here.
bool found = false;
VariableLocation location;
int index;
VariableMode mode;
InitializationFlag init_flag;
MaybeAssignedFlag maybe_assigned_flag;
IsStaticFlag is_static_flag;
{
location = VariableLocation::CONTEXT;
index =
ScopeInfo::ContextSlotIndex(scope_info, name_handle, &mode, &init_flag,
&maybe_assigned_flag, &is_static_flag);
found = index >= 0;
}
if (!found && is_module_scope()) {
location = VariableLocation::MODULE;
index = scope_info.ModuleIndex(name_handle, &mode, &init_flag,
&maybe_assigned_flag);
found = index != 0;
}
if (!found) {
index = scope_info.FunctionContextSlotIndex(name_handle);
if (index < 0) return nullptr; // Nowhere found.
Variable* var = AsDeclarationScope()->DeclareFunctionVar(name, cache);
DCHECK_EQ(VariableMode::kConst, var->mode());
var->AllocateTo(VariableLocation::CONTEXT, index);
return cache->variables_.Lookup(name);
}
if (!is_module_scope()) {
DCHECK_NE(index, scope_info.ReceiverContextSlotIndex());
}
bool was_added;
Variable* var = cache->variables_.Declare(
zone(), this, name, mode, NORMAL_VARIABLE, init_flag, maybe_assigned_flag,
IsStaticFlag::kNotStatic, &was_added);
DCHECK(was_added);
var->AllocateTo(location, index);
return var;
}
Variable* DeclarationScope::DeclareParameter(const AstRawString* name,
VariableMode mode,
bool is_optional, bool is_rest,
AstValueFactory* ast_value_factory,
int position) {
DCHECK(!already_resolved_);
DCHECK(is_function_scope() || is_module_scope());
DCHECK(!has_rest_);
DCHECK(!is_optional || !is_rest);
DCHECK(!is_being_lazily_parsed_);
DCHECK(!was_lazily_parsed_);
Variable* var;
if (mode == VariableMode::kTemporary) {
var = NewTemporary(name);
} else {
var = LookupLocal(name);
DCHECK_EQ(mode, VariableMode::kVar);
DCHECK(var->is_parameter());
}
has_rest_ = is_rest;
var->set_initializer_position(position);
params_.Add(var, zone());
if (!is_rest) ++num_parameters_;
if (name == ast_value_factory->arguments_string()) {
has_arguments_parameter_ = true;
}
// Params are automatically marked as used to make sure that the debugger and
// function.arguments sees them.
// TODO(verwaest): Reevaluate whether we always need to do this, since
// strict-mode function.arguments does not make the arguments available.
var->set_is_used();
return var;
}
void DeclarationScope::RecordParameter(bool is_rest) {
DCHECK(!already_resolved_);
DCHECK(is_function_scope() || is_module_scope());
DCHECK(is_being_lazily_parsed_);
DCHECK(!has_rest_);
has_rest_ = is_rest;
if (!is_rest) ++num_parameters_;
}
Variable* Scope::DeclareLocal(const AstRawString* name, VariableMode mode,
VariableKind kind, bool* was_added,
InitializationFlag init_flag) {
DCHECK(!already_resolved_);
// Private methods should be declared with ClassScope::DeclarePrivateName()
DCHECK(!IsPrivateMethodOrAccessorVariableMode(mode));
// This function handles VariableMode::kVar, VariableMode::kLet, and
// VariableMode::kConst modes. VariableMode::kDynamic variables are
// introduced during variable allocation, and VariableMode::kTemporary
// variables are allocated via NewTemporary().
DCHECK(IsDeclaredVariableMode(mode));
DCHECK_IMPLIES(GetDeclarationScope()->is_being_lazily_parsed(),
mode == VariableMode::kVar || mode == VariableMode::kLet ||
mode == VariableMode::kConst);
DCHECK(!GetDeclarationScope()->was_lazily_parsed());
Variable* var =
Declare(zone(), name, mode, kind, init_flag, kNotAssigned, was_added);
// Pessimistically assume that top-level variables will be assigned and used.
//
// Top-level variables in a script can be accessed by other scripts or even
// become global properties. While this does not apply to top-level variables
// in a module (assuming they are not exported), we must still mark these as
// assigned because they might be accessed by a lazily parsed top-level
// function, which, for efficiency, we preparse without variable tracking.
if (is_script_scope() || is_module_scope()) {
if (mode != VariableMode::kConst) var->SetMaybeAssigned();
var->set_is_used();
}
return var;
}
Variable* Scope::DeclareVariable(
Declaration* declaration, const AstRawString* name, int pos,
VariableMode mode, VariableKind kind, InitializationFlag init,
bool* was_added, bool* sloppy_mode_block_scope_function_redefinition,
bool* ok) {
// Private methods should be declared with ClassScope::DeclarePrivateName()
DCHECK(!IsPrivateMethodOrAccessorVariableMode(mode));
DCHECK(IsDeclaredVariableMode(mode));
DCHECK(!already_resolved_);
DCHECK(!GetDeclarationScope()->is_being_lazily_parsed());
DCHECK(!GetDeclarationScope()->was_lazily_parsed());
if (mode == VariableMode::kVar && !is_declaration_scope()) {
return GetDeclarationScope()->DeclareVariable(
declaration, name, pos, mode, kind, init, was_added,
sloppy_mode_block_scope_function_redefinition, ok);
}
DCHECK(!is_catch_scope());
DCHECK(!is_with_scope());
DCHECK(is_declaration_scope() ||
(IsLexicalVariableMode(mode) && is_block_scope()));
DCHECK_NOT_NULL(name);
Variable* var = LookupLocal(name);
// Declare the variable in the declaration scope.
*was_added = var == nullptr;
if (V8_LIKELY(*was_added)) {
if (V8_UNLIKELY(is_eval_scope() && is_sloppy(language_mode()) &&
mode == VariableMode::kVar)) {
// In a var binding in a sloppy direct eval, pollute the enclosing scope
// with this new binding by doing the following:
// The proxy is bound to a lookup variable to force a dynamic declaration
// using the DeclareEvalVar or DeclareEvalFunction runtime functions.
DCHECK_EQ(NORMAL_VARIABLE, kind);
var = NonLocal(name, VariableMode::kDynamic);
// Mark the var as used in case anyone outside the eval wants to use it.
var->set_is_used();
} else {
// Declare the name.
var = DeclareLocal(name, mode, kind, was_added, init);
DCHECK(*was_added);
}
} else {
var->SetMaybeAssigned();
if (V8_UNLIKELY(IsLexicalVariableMode(mode) ||
IsLexicalVariableMode(var->mode()))) {
// The name was declared in this scope before; check for conflicting
// re-declarations. We have a conflict if either of the declarations is
// not a var (in script scope, we also have to ignore legacy const for
// compatibility). There is similar code in runtime.cc in the Declare
// functions. The function CheckConflictingVarDeclarations checks for
// var and let bindings from different scopes whereas this is a check
// for conflicting declarations within the same scope. This check also
// covers the special case
//
// function () { let x; { var x; } }
//
// because the var declaration is hoisted to the function scope where
// 'x' is already bound.
//
// In harmony we treat re-declarations as early errors. See ES5 16 for a
// definition of early errors.
//
// Allow duplicate function decls for web compat, see bug 4693.
*ok = var->is_sloppy_block_function() &&
kind == SLOPPY_BLOCK_FUNCTION_VARIABLE;
*sloppy_mode_block_scope_function_redefinition = *ok;
}
}
DCHECK_NOT_NULL(var);
// We add a declaration node for every declaration. The compiler
// will only generate code if necessary. In particular, declarations
// for inner local variables that do not represent functions won't
// result in any generated code.
//
// This will lead to multiple declaration nodes for the
// same variable if it is declared several times. This is not a
// semantic issue, but it may be a performance issue since it may
// lead to repeated DeclareEvalVar or DeclareEvalFunction calls.
decls_.Add(declaration);
declaration->set_var(var);
return var;
}
Variable* Scope::DeclareVariableName(const AstRawString* name,
VariableMode mode, bool* was_added,
VariableKind kind) {
DCHECK(IsDeclaredVariableMode(mode));
DCHECK(!already_resolved_);
DCHECK(GetDeclarationScope()->is_being_lazily_parsed());
// Private methods should be declared with ClassScope::DeclarePrivateName()
DCHECK(!IsPrivateMethodOrAccessorVariableMode(mode));
if (mode == VariableMode::kVar && !is_declaration_scope()) {
return GetDeclarationScope()->DeclareVariableName(name, mode, was_added,
kind);
}
DCHECK(!is_with_scope());
DCHECK(!is_eval_scope());
DCHECK(is_declaration_scope() || IsLexicalVariableMode(mode));
DCHECK(scope_info_.is_null());
// Declare the variable in the declaration scope.
Variable* var = DeclareLocal(name, mode, kind, was_added);
if (!*was_added) {
if (IsLexicalVariableMode(mode) || IsLexicalVariableMode(var->mode())) {
if (!var->is_sloppy_block_function() ||
kind != SLOPPY_BLOCK_FUNCTION_VARIABLE) {
// Duplicate functions are allowed in the sloppy mode, but if this is
// not a function declaration, it's an error. This is an error PreParser
// hasn't previously detected.
return nullptr;
}
// Sloppy block function redefinition.
}
var->SetMaybeAssigned();
}
var->set_is_used();
return var;
}
Variable* Scope::DeclareCatchVariableName(const AstRawString* name) {
DCHECK(!already_resolved_);
DCHECK(is_catch_scope());
DCHECK(scope_info_.is_null());
bool was_added;
Variable* result = Declare(zone(), name, VariableMode::kVar, NORMAL_VARIABLE,
kCreatedInitialized, kNotAssigned, &was_added);
DCHECK(was_added);
return result;
}
void Scope::AddUnresolved(VariableProxy* proxy) {
DCHECK(!already_resolved_);
DCHECK(!proxy->is_resolved());
unresolved_list_.Add(proxy);
}
Variable* DeclarationScope::DeclareDynamicGlobal(const AstRawString* name,
VariableKind kind,
Scope* cache) {
DCHECK(is_script_scope());
bool was_added;
return cache->variables_.Declare(
zone(), this, name, VariableMode::kDynamicGlobal, kind,
kCreatedInitialized, kNotAssigned, IsStaticFlag::kNotStatic, &was_added);
// TODO(neis): Mark variable as maybe-assigned?
}
bool Scope::RemoveUnresolved(VariableProxy* var) {
return unresolved_list_.Remove(var);
}
void Scope::DeleteUnresolved(VariableProxy* var) {
DCHECK(unresolved_list_.Contains(var));
var->mark_removed_from_unresolved();
}
Variable* Scope::NewTemporary(const AstRawString* name) {
return NewTemporary(name, kMaybeAssigned);
}
Variable* Scope::NewTemporary(const AstRawString* name,
MaybeAssignedFlag maybe_assigned) {
DeclarationScope* scope = GetClosureScope();
Variable* var = new (zone()) Variable(scope, name, VariableMode::kTemporary,
NORMAL_VARIABLE, kCreatedInitialized);
scope->AddLocal(var);
if (maybe_assigned == kMaybeAssigned) var->SetMaybeAssigned();
return var;
}
Declaration* DeclarationScope::CheckConflictingVarDeclarations() {
if (has_checked_syntax_) return nullptr;
for (Declaration* decl : decls_) {
// Lexical vs lexical conflicts within the same scope have already been
// captured in Parser::Declare. The only conflicts we still need to check
// are lexical vs nested var.
if (decl->IsVariableDeclaration() &&
decl->AsVariableDeclaration()->AsNested() != nullptr) {
Scope* current = decl->AsVariableDeclaration()->AsNested()->scope();
DCHECK(decl->var()->mode() == VariableMode::kVar ||
decl->var()->mode() == VariableMode::kDynamic);
// Iterate through all scopes until the declaration scope.
do {
// There is a conflict if there exists a non-VAR binding.
if (current->is_catch_scope()) {
current = current->outer_scope();
continue;
}
Variable* other_var = current->LookupLocal(decl->var()->raw_name());
if (other_var != nullptr) {
DCHECK(IsLexicalVariableMode(other_var->mode()));
return decl;
}
current = current->outer_scope();
} while (current != this);
}
}
if (V8_LIKELY(!is_eval_scope())) return nullptr;
if (!is_sloppy(language_mode())) return nullptr;
// Var declarations in sloppy eval are hoisted to the first non-eval
// declaration scope. Check for conflicts between the eval scope that
// declaration scope.
Scope* end = outer_scope()->GetNonEvalDeclarationScope()->outer_scope();
for (Declaration* decl : decls_) {
if (IsLexicalVariableMode(decl->var()->mode())) continue;
Scope* current = outer_scope_;
// Iterate through all scopes until and including the declaration scope.
do {
// There is a conflict if there exists a non-VAR binding up to the
// declaration scope in which this sloppy-eval runs.
//
// Use the current scope as the cache, since the general cache would be
// the end scope.
Variable* other_var =
current->LookupInScopeOrScopeInfo(decl->var()->raw_name(), current);
if (other_var != nullptr && !current->is_catch_scope()) {
// If this is a VAR, then we know that it doesn't conflict with
// anything, so we can't conflict with anything either. The one
// exception is the binding variable in catch scopes, which is handled
// by the if above.
if (!IsLexicalVariableMode(other_var->mode())) break;
return decl;
}
current = current->outer_scope();
} while (current != end);
}
return nullptr;
}
const AstRawString* Scope::FindVariableDeclaredIn(Scope* scope,
VariableMode mode_limit) {
const VariableMap& variables = scope->variables_;
for (ZoneHashMap::Entry* p = variables.Start(); p != nullptr;
p = variables.Next(p)) {
const AstRawString* name = static_cast<const AstRawString*>(p->key);
Variable* var = LookupLocal(name);
if (var != nullptr && var->mode() <= mode_limit) return name;
}
return nullptr;
}
void DeclarationScope::DeserializeReceiver(AstValueFactory* ast_value_factory) {
if (is_script_scope()) {
DCHECK_NOT_NULL(receiver_);
return;
}
DCHECK(has_this_declaration());
DeclareThis(ast_value_factory);
if (is_debug_evaluate_scope()) {
receiver_->AllocateTo(VariableLocation::LOOKUP, -1);
} else {
receiver_->AllocateTo(VariableLocation::CONTEXT,
scope_info_.get_handle()->ReceiverContextSlotIndex());
}
}
bool DeclarationScope::AllocateVariables(ParseInfo* info) {
// Module variables must be allocated before variable resolution
// to ensure that UpdateNeedsHoleCheck() can detect import variables.
if (is_module_scope()) AsModuleScope()->AllocateModuleVariables();
PrivateNameScopeIterator private_name_scope_iter(this);
if (!private_name_scope_iter.Done() &&
!private_name_scope_iter.GetScope()->ResolvePrivateNames(info)) {
DCHECK(info->pending_error_handler()->has_pending_error());
return false;
}
if (!ResolveVariablesRecursively(info)) {
DCHECK(info->pending_error_handler()->has_pending_error());
return false;
}
// Don't allocate variables of preparsed scopes.
if (!was_lazily_parsed()) AllocateVariablesRecursively();
return true;
}
bool Scope::HasThisReference() const {
if (is_declaration_scope() && AsDeclarationScope()->has_this_reference()) {
return true;
}
for (Scope* scope = inner_scope_; scope != nullptr; scope = scope->sibling_) {
if (!scope->is_declaration_scope() ||
!scope->AsDeclarationScope()->has_this_declaration()) {
if (scope->HasThisReference()) return true;
}
}
return false;
}
bool Scope::AllowsLazyParsingWithoutUnresolvedVariables(
const Scope* outer) const {
// If none of the outer scopes need to decide whether to context allocate
// specific variables, we can preparse inner functions without unresolved
// variables. Otherwise we need to find unresolved variables to force context
// allocation of the matching declarations. We can stop at the outer scope for
// the parse, since context allocation of those variables is already
// guaranteed to be correct.
for (const Scope* s = this; s != outer; s = s->outer_scope_) {
// Eval forces context allocation on all outer scopes, so we don't need to
// look at those scopes. Sloppy eval makes top-level non-lexical variables
// dynamic, whereas strict-mode requires context allocation.
if (s->is_eval_scope()) return is_sloppy(s->language_mode());
// Catch scopes force context allocation of all variables.
if (s->is_catch_scope()) continue;
// With scopes do not introduce variables that need allocation.
if (s->is_with_scope()) continue;
DCHECK(s->is_module_scope() || s->is_block_scope() ||
s->is_function_scope());
return false;
}
return true;
}
bool DeclarationScope::AllowsLazyCompilation() const {
// Functions which force eager compilation and class member initializer
// functions are not lazily compilable.
return !force_eager_compilation_ &&
!IsClassMembersInitializerFunction(function_kind());
}
int Scope::ContextChainLength(Scope* scope) const {
int n = 0;
for (const Scope* s = this; s != scope; s = s->outer_scope_) {
DCHECK_NOT_NULL(s); // scope must be in the scope chain
if (s->NeedsContext()) n++;
}
return n;
}
int Scope::ContextChainLengthUntilOutermostSloppyEval() const {
int result = 0;
int length = 0;
for (const Scope* s = this; s != nullptr; s = s->outer_scope()) {
if (!s->NeedsContext()) continue;
length++;
if (s->is_declaration_scope() &&
s->AsDeclarationScope()->sloppy_eval_can_extend_vars()) {
result = length;
}
}
return result;
}
DeclarationScope* Scope::GetDeclarationScope() {
Scope* scope = this;
while (!scope->is_declaration_scope()) {
scope = scope->outer_scope();
}
return scope->AsDeclarationScope();
}
DeclarationScope* Scope::GetNonEvalDeclarationScope() {
Scope* scope = this;
while (!scope->is_declaration_scope() || scope->is_eval_scope()) {
scope = scope->outer_scope();
}
return scope->AsDeclarationScope();
}
const DeclarationScope* Scope::GetClosureScope() const {
const Scope* scope = this;
while (!scope->is_declaration_scope() || scope->is_block_scope()) {
scope = scope->outer_scope();
}
return scope->AsDeclarationScope();
}
DeclarationScope* Scope::GetClosureScope() {
Scope* scope = this;
while (!scope->is_declaration_scope() || scope->is_block_scope()) {
scope = scope->outer_scope();
}
return scope->AsDeclarationScope();
}
bool Scope::NeedsScopeInfo() const {
DCHECK(!already_resolved_);
DCHECK(GetClosureScope()->ShouldEagerCompile());
// The debugger expects all functions to have scope infos.
// TODO(jochen|yangguo): Remove this requirement.
if (is_function_scope()) return true;
return NeedsContext();
}
bool Scope::ShouldBanArguments() {
return GetReceiverScope()->should_ban_arguments();
}
DeclarationScope* Scope::GetReceiverScope() {
Scope* scope = this;
while (!scope->is_declaration_scope() ||
(!scope->is_script_scope() &&
!scope->AsDeclarationScope()->has_this_declaration())) {
scope = scope->outer_scope();
}
return scope->AsDeclarationScope();
}
DeclarationScope* Scope::GetScriptScope() {
Scope* scope = this;
while (!scope->is_script_scope()) {
scope = scope->outer_scope();
}
return scope->AsDeclarationScope();
}
Scope* Scope::GetOuterScopeWithContext() {
Scope* scope = outer_scope_;
while (scope && !scope->NeedsContext()) {
scope = scope->outer_scope();
}
return scope;
}
namespace {
bool WasLazilyParsed(Scope* scope) {
return scope->is_declaration_scope() &&
scope->AsDeclarationScope()->was_lazily_parsed();
}
} // namespace
template <typename FunctionType>
void Scope::ForEach(FunctionType callback) {
Scope* scope = this;
while (true) {
Iteration iteration = callback(scope);
// Try to descend into inner scopes first.
if ((iteration == Iteration::kDescend) && scope->inner_scope_ != nullptr) {
scope = scope->inner_scope_;
} else {
// Find the next outer scope with a sibling.
while (scope->sibling_ == nullptr) {
if (scope == this) return;
scope = scope->outer_scope_;
}
if (scope == this) return;
scope = scope->sibling_;
}
}
}
bool Scope::IsOuterScopeOf(Scope* other) const {
Scope* scope = other;
while (scope) {
if (scope == this) return true;
scope = scope->outer_scope();
}
return false;
}
void Scope::CollectNonLocals(DeclarationScope* max_outer_scope,
Isolate* isolate, ParseInfo* info,
Handle<StringSet>* non_locals) {
this->ForEach([max_outer_scope, isolate, info, non_locals](Scope* scope) {
// Module variables must be allocated before variable resolution
// to ensure that UpdateNeedsHoleCheck() can detect import variables.
if (scope->is_module_scope()) {
scope->AsModuleScope()->AllocateModuleVariables();
}
// Lazy parsed declaration scopes are already partially analyzed. If there
// are unresolved references remaining, they just need to be resolved in
// outer scopes.
Scope* lookup = WasLazilyParsed(scope) ? scope->outer_scope() : scope;
for (VariableProxy* proxy : scope->unresolved_list_) {
DCHECK(!proxy->is_resolved());
Variable* var =
Lookup<kParsedScope>(proxy, lookup, max_outer_scope->outer_scope());
if (var == nullptr) {
*non_locals = StringSet::Add(isolate, *non_locals, proxy->name());
} else {
// In this case we need to leave scopes in a way that they can be
// allocated. If we resolved variables from lazy parsed scopes, we need
// to context allocate the var.
scope->ResolveTo(info, proxy, var);
if (!var->is_dynamic() && lookup != scope)
var->ForceContextAllocation();
}
}
// Clear unresolved_list_ as it's in an inconsistent state.
scope->unresolved_list_.Clear();
return Iteration::kDescend;
});
}
void Scope::AnalyzePartially(DeclarationScope* max_outer_scope,
AstNodeFactory* ast_node_factory,
UnresolvedList* new_unresolved_list,
bool maybe_in_arrowhead) {
this->ForEach([max_outer_scope, ast_node_factory, new_unresolved_list,
maybe_in_arrowhead](Scope* scope) {
DCHECK_IMPLIES(scope->is_declaration_scope(),
!scope->AsDeclarationScope()->was_lazily_parsed());
for (VariableProxy* proxy = scope->unresolved_list_.first();
proxy != nullptr; proxy = proxy->next_unresolved()) {
if (proxy->is_removed_from_unresolved()) continue;
DCHECK(!proxy->is_resolved());
Variable* var =
Lookup<kParsedScope>(proxy, scope, max_outer_scope->outer_scope());
if (var == nullptr) {
// Don't copy unresolved references to the script scope, unless it's a
// reference to a private name or method. In that case keep it so we
// can fail later.
if (!max_outer_scope->outer_scope()->is_script_scope() ||
maybe_in_arrowhead) {
VariableProxy* copy = ast_node_factory->CopyVariableProxy(proxy);
new_unresolved_list->Add(copy);
}
} else {
var->set_is_used();
if (proxy->is_assigned()) var->SetMaybeAssigned();
}
}
// Clear unresolved_list_ as it's in an inconsistent state.
scope->unresolved_list_.Clear();
return Iteration::kDescend;
});
}
Handle<StringSet> DeclarationScope::CollectNonLocals(
Isolate* isolate, ParseInfo* info, Handle<StringSet> non_locals) {
Scope::CollectNonLocals(this, isolate, info, &non_locals);
return non_locals;
}
void DeclarationScope::ResetAfterPreparsing(AstValueFactory* ast_value_factory,
bool aborted) {
DCHECK(is_function_scope());
// Reset all non-trivial members.
params_.Clear();
decls_.Clear();
locals_.Clear();
inner_scope_ = nullptr;
unresolved_list_.Clear();
sloppy_block_functions_.Clear();
rare_data_ = nullptr;
has_rest_ = false;
function_ = nullptr;
DCHECK_NE(zone_, ast_value_factory->zone());
zone_->ReleaseMemory();
if (aborted) {
// Prepare scope for use in the outer zone.
zone_ = ast_value_factory->zone();
variables_.Reset(ZoneAllocationPolicy(zone_));
if (!IsArrowFunction(function_kind_)) {
has_simple_parameters_ = true;
DeclareDefaultFunctionVariables(ast_value_factory);
}
} else {
// Make sure this scope isn't used for allocation anymore.
zone_ = nullptr;
variables_.Invalidate();
}
#ifdef DEBUG
needs_migration_ = false;
is_being_lazily_parsed_ = false;
#endif
was_lazily_parsed_ = !aborted;
}
bool Scope::IsSkippableFunctionScope() {
// Lazy non-arrow function scopes are skippable. Lazy functions are exactly
// those Scopes which have their own PreparseDataBuilder object. This
// logic ensures that the scope allocation data is consistent with the
// skippable function data (both agree on where the lazy function boundaries
// are).
if (!is_function_scope()) return false;
DeclarationScope* declaration_scope = AsDeclarationScope();
return !declaration_scope->is_arrow_scope() &&
declaration_scope->preparse_data_builder() != nullptr;
}
void Scope::SavePreparseData(Parser* parser) {
this->ForEach([parser](Scope* scope) {
if (scope->IsSkippableFunctionScope()) {
scope->AsDeclarationScope()->SavePreparseDataForDeclarationScope(parser);
}
return Iteration::kDescend;
});
}
void DeclarationScope::SavePreparseDataForDeclarationScope(Parser* parser) {
if (preparse_data_builder_ == nullptr) return;
preparse_data_builder_->SaveScopeAllocationData(this, parser);
}
void DeclarationScope::AnalyzePartially(Parser* parser,
AstNodeFactory* ast_node_factory,
bool maybe_in_arrowhead) {
DCHECK(!force_eager_compilation_);
UnresolvedList new_unresolved_list;
if (!IsArrowFunction(function_kind_) &&
(!outer_scope_->is_script_scope() || maybe_in_arrowhead ||
(preparse_data_builder_ != nullptr &&
preparse_data_builder_->HasInnerFunctions()))) {
// Try to resolve unresolved variables for this Scope and migrate those
// which cannot be resolved inside. It doesn't make sense to try to resolve
// them in the outer Scopes here, because they are incomplete.
Scope::AnalyzePartially(this, ast_node_factory, &new_unresolved_list,
maybe_in_arrowhead);
// Migrate function_ to the right Zone.
if (function_ != nullptr) {
function_ = ast_node_factory->CopyVariable(function_);
}
SavePreparseData(parser);
}
#ifdef DEBUG
if (FLAG_print_scopes) {
PrintF("Inner function scope:\n");
Print();
}
#endif
ResetAfterPreparsing(ast_node_factory->ast_value_factory(), false);
unresolved_list_ = std::move(new_unresolved_list);
}
void DeclarationScope::RewriteReplGlobalVariables() {
DCHECK(is_script_scope());
if (!is_repl_mode_scope()) return;
for (VariableMap::Entry* p = variables_.Start(); p != nullptr;
p = variables_.Next(p)) {
Variable* var = reinterpret_cast<Variable*>(p->value);
var->RewriteLocationForRepl();
}
}
#ifdef DEBUG
namespace {
const char* Header(ScopeType scope_type, FunctionKind function_kind,
bool is_declaration_scope) {
switch (scope_type) {
case EVAL_SCOPE: return "eval";
// TODO(adamk): Should we print concise method scopes specially?
case FUNCTION_SCOPE:
if (IsGeneratorFunction(function_kind)) return "function*";
if (IsAsyncFunction(function_kind)) return "async function";
if (IsArrowFunction(function_kind)) return "arrow";
return "function";
case MODULE_SCOPE: return "module";
case SCRIPT_SCOPE: return "global";
case CATCH_SCOPE: return "catch";
case BLOCK_SCOPE: return is_declaration_scope ? "varblock" : "block";
case CLASS_SCOPE:
return "class";
case WITH_SCOPE: return "with";
}
UNREACHABLE();
}
void Indent(int n, const char* str) { PrintF("%*s%s", n, "", str); }
void PrintName(const AstRawString* name) {
PrintF("%.*s", name->length(), name->raw_data());
}
void PrintLocation(Variable* var) {
switch (var->location()) {
case VariableLocation::UNALLOCATED:
break;
case VariableLocation::PARAMETER:
PrintF("parameter[%d]", var->index());
break;
case VariableLocation::LOCAL:
PrintF("local[%d]", var->index());
break;
case VariableLocation::CONTEXT:
PrintF("context[%d]", var->index());
break;
case VariableLocation::LOOKUP:
PrintF("lookup");
break;
case VariableLocation::MODULE:
PrintF("module");
break;
case VariableLocation::REPL_GLOBAL:
PrintF("repl global[%d]", var->index());
break;
}
}
void PrintVar(int indent, Variable* var) {
Indent(indent, VariableMode2String(var->mode()));
PrintF(" ");
if (var->raw_name()->IsEmpty())
PrintF(".%p", reinterpret_cast<void*>(var));
else
PrintName(var->raw_name());
PrintF("; // (%p) ", reinterpret_cast<void*>(var));
PrintLocation(var);
bool comma = !var->IsUnallocated();
if (var->has_forced_context_allocation()) {
if (comma) PrintF(", ");
PrintF("forced context allocation");
comma = true;
}
if (var->maybe_assigned() == kNotAssigned) {
if (comma) PrintF(", ");
PrintF("never assigned");
comma = true;
}
if (var->initialization_flag() == kNeedsInitialization &&
!var->binding_needs_init()) {
if (comma) PrintF(", ");
PrintF("hole initialization elided");
}
PrintF("\n");
}
void PrintMap(int indent, const char* label, VariableMap* map, bool locals,
Variable* function_var) {
bool printed_label = false;
for (VariableMap::Entry* p = map->Start(); p != nullptr; p = map->Next(p)) {
Variable* var = reinterpret_cast<Variable*>(p->value);
if (var == function_var) continue;
bool local = !IsDynamicVariableMode(var->mode());
if ((locals ? local : !local) &&
(var->is_used() || !var->IsUnallocated())) {
if (!printed_label) {
Indent(indent, label);
printed_label = true;
}
PrintVar(indent, var);
}
}
}
} // anonymous namespace
void DeclarationScope::PrintParameters() {
PrintF(" (");
for (int i = 0; i < params_.length(); i++) {
if (i > 0) PrintF(", ");
const AstRawString* name = params_[i]->raw_name();
if (name->IsEmpty()) {
PrintF(".%p", reinterpret_cast<void*>(params_[i]));
} else {
PrintName(name);
}
}
PrintF(")");
}
void Scope::Print(int n) {
int n0 = (n > 0 ? n : 0);
int n1 = n0 + 2; // indentation
// Print header.
FunctionKind function_kind = is_function_scope()
? AsDeclarationScope()->function_kind()
: kNormalFunction;
Indent(n0, Header(scope_type_, function_kind, is_declaration_scope()));
if (scope_name_ != nullptr && !scope_name_->IsEmpty()) {
PrintF(" ");
PrintName(scope_name_);
}
// Print parameters, if any.
Variable* function = nullptr;
if (is_function_scope()) {
AsDeclarationScope()->PrintParameters();
function = AsDeclarationScope()->function_var();
}
PrintF(" { // (%p) (%d, %d)\n", reinterpret_cast<void*>(this),
start_position(), end_position());
if (is_hidden()) {
Indent(n1, "// is hidden\n");
}
// Function name, if any (named function literals, only).
if (function != nullptr) {
Indent(n1, "// (local) function name: ");
PrintName(function->raw_name());
PrintF("\n");
}
// Scope info.
if (is_strict(language_mode())) {
Indent(n1, "// strict mode scope\n");
}
if (IsAsmModule()) Indent(n1, "// scope is an asm module\n");
if (is_declaration_scope() &&
AsDeclarationScope()->sloppy_eval_can_extend_vars()) {
Indent(n1, "// scope calls sloppy 'eval'\n");
}
if (is_declaration_scope() && AsDeclarationScope()->NeedsHomeObject()) {
Indent(n1, "// scope needs home object\n");
}
if (private_name_lookup_skips_outer_class()) {
Indent(n1, "// scope skips outer class for #-names\n");
}
if (inner_scope_calls_eval_) Indent(n1, "// inner scope calls 'eval'\n");
if (is_declaration_scope()) {
DeclarationScope* scope = AsDeclarationScope();
if (scope->was_lazily_parsed()) Indent(n1, "// lazily parsed\n");
if (scope->ShouldEagerCompile()) Indent(n1, "// will be compiled\n");
if (scope->needs_private_name_context_chain_recalc()) {
Indent(n1, "// needs #-name context chain recalc\n");
}
}
if (num_stack_slots_ > 0) {
Indent(n1, "// ");
PrintF("%d stack slots\n", num_stack_slots_);
}
if (num_heap_slots_ > 0) {
Indent(n1, "// ");
PrintF("%d heap slots\n", num_heap_slots_);
}
// Print locals.
if (function != nullptr) {
Indent(n1, "// function var:\n");
PrintVar(n1, function);
}
// Print temporaries.
{
bool printed_header = false;
for (Variable* local : locals_) {
if (local->mode() != VariableMode::kTemporary) continue;
if (!printed_header) {
printed_header = true;
Indent(n1, "// temporary vars:\n");
}
PrintVar(n1, local);
}
}
if (variables_.occupancy() > 0) {
PrintMap(n1, "// local vars:\n", &variables_, true, function);
PrintMap(n1, "// dynamic vars:\n", &variables_, false, function);
}
if (is_class_scope()) {
ClassScope* class_scope = AsClassScope();
if (class_scope->GetRareData() != nullptr) {
PrintMap(n1, "// private name vars:\n",
&(class_scope->GetRareData()->private_name_map), true, function);
Variable* brand = class_scope->brand();
if (brand != nullptr) {
Indent(n1, "// brand var:\n");
PrintVar(n1, brand);
}
}
if (class_scope->class_variable() != nullptr) {
Indent(n1, "// class var");
PrintF("%s%s:\n",
class_scope->class_variable()->is_used() ? ", used" : ", unused",
class_scope->should_save_class_variable_index()
? ", index saved"
: ", index not saved");
PrintVar(n1, class_scope->class_variable());
}
}
// Print inner scopes (disable by providing negative n).
if (n >= 0) {
for (Scope* scope = inner_scope_; scope != nullptr;
scope = scope->sibling_) {
PrintF("\n");
scope->Print(n1);
}
}
Indent(n0, "}\n");
}
void Scope::CheckScopePositions() {
this->ForEach([](Scope* scope) {
// Visible leaf scopes must have real positions.
if (!scope->is_hidden() && scope->inner_scope_ == nullptr) {
DCHECK_NE(kNoSourcePosition, scope->start_position());
DCHECK_NE(kNoSourcePosition, scope->end_position());
}
return Iteration::kDescend;
});
}
void Scope::CheckZones() {
DCHECK(!needs_migration_);
this->ForEach([](Scope* scope) {
if (WasLazilyParsed(scope)) {
DCHECK_NULL(scope->zone());
DCHECK_NULL(scope->inner_scope_);
return Iteration::kContinue;
}
return Iteration::kDescend;
});
}
#endif // DEBUG
Variable* Scope::NonLocal(const AstRawString* name, VariableMode mode) {
// Declare a new non-local.
DCHECK(IsDynamicVariableMode(mode));
bool was_added;
Variable* var = variables_.Declare(zone(), this, name, mode, NORMAL_VARIABLE,
kCreatedInitialized, kNotAssigned,
IsStaticFlag::kNotStatic, &was_added);
// Allocate it by giving it a dynamic lookup.
var->AllocateTo(VariableLocation::LOOKUP, -1);
return var;
}
// static
template <Scope::ScopeLookupMode mode>
Variable* Scope::Lookup(VariableProxy* proxy, Scope* scope,
Scope* outer_scope_end, Scope* cache_scope,
bool force_context_allocation) {
// If we have already passed the cache scope in earlier recursions, we should
// first quickly check if the current scope uses the cache scope before
// continuing.
if (mode == kDeserializedScope &&
scope->deserialized_scope_uses_external_cache()) {
Variable* var = cache_scope->variables_.Lookup(proxy->raw_name());
if (var != nullptr) return var;
}
while (true) {
DCHECK_IMPLIES(mode == kParsedScope, !scope->is_debug_evaluate_scope_);
// Short-cut: whenever we find a debug-evaluate scope, just look everything
// up dynamically. Debug-evaluate doesn't properly create scope info for the
// lookups it does. It may not have a valid 'this' declaration, and anything
// accessed through debug-evaluate might invalidly resolve to
// stack-allocated variables.
// TODO(yangguo): Remove once debug-evaluate creates proper ScopeInfo for
// the scopes in which it's evaluating.
if (mode == kDeserializedScope &&
V8_UNLIKELY(scope->is_debug_evaluate_scope_)) {
DCHECK(scope->deserialized_scope_uses_external_cache() ||
scope == cache_scope);
return cache_scope->NonLocal(proxy->raw_name(), VariableMode::kDynamic);
}
// Try to find the variable in this scope.
Variable* var;
if (mode == kParsedScope) {
var = scope->LookupLocal(proxy->raw_name());
} else {
DCHECK_EQ(mode, kDeserializedScope);
bool external_cache = scope->deserialized_scope_uses_external_cache();
if (!external_cache) {
// Check the cache on each deserialized scope, up to the main cache
// scope when we get to it (we may still have deserialized scopes
// in-between the initial and cache scopes so we can't just check the
// cache before the loop).
Variable* var = scope->variables_.Lookup(proxy->raw_name());
if (var != nullptr) return var;
}
var = scope->LookupInScopeInfo(proxy->raw_name(),
external_cache ? cache_scope : scope);
}
// We found a variable and we are done. (Even if there is an 'eval' in this
// scope which introduces the same variable again, the resulting variable
// remains the same.)
//
// For sloppy eval though, we skip dynamic variable to avoid resolving to a
// variable when the variable and proxy are in the same eval execution. The
// variable is not available on subsequent lazy executions of functions in
// the eval, so this avoids inner functions from looking up different
// variables during eager and lazy compilation.
//
// TODO(leszeks): Maybe we want to restrict this to e.g. lookups of a proxy
// living in a different scope to the current one, or some other
// optimisation.
if (var != nullptr &&
!(scope->is_eval_scope() && var->mode() == VariableMode::kDynamic)) {
if (mode == kParsedScope && force_context_allocation &&
!var->is_dynamic()) {
var->ForceContextAllocation();
}
return var;
}
if (scope->outer_scope_ == outer_scope_end) break;
DCHECK(!scope->is_script_scope());
if (V8_UNLIKELY(scope->is_with_scope())) {
return LookupWith(proxy, scope, outer_scope_end, cache_scope,
force_context_allocation);
}
if (V8_UNLIKELY(
scope->is_declaration_scope() &&
scope->AsDeclarationScope()->sloppy_eval_can_extend_vars())) {
return LookupSloppyEval(proxy, scope, outer_scope_end, cache_scope,
force_context_allocation);
}
force_context_allocation |= scope->is_function_scope();
scope = scope->outer_scope_;
// TODO(verwaest): Separate through AnalyzePartially.
if (mode == kParsedScope && !scope->scope_info_.is_null()) {
DCHECK_NULL(cache_scope);
Scope* cache_scope = scope->GetNonEvalDeclarationScope();
return Lookup<kDeserializedScope>(proxy, scope, outer_scope_end,
cache_scope);
}
}
// We may just be trying to find all free variables. In that case, don't
// declare them in the outer scope.
// TODO(marja): Separate Lookup for preparsed scopes better.
if (mode == kParsedScope && !scope->is_script_scope()) {
return nullptr;
}
// No binding has been found. Declare a variable on the global object.
return scope->AsDeclarationScope()->DeclareDynamicGlobal(
proxy->raw_name(), NORMAL_VARIABLE,
mode == kDeserializedScope ? cache_scope : scope);
}
template Variable* Scope::Lookup<Scope::kParsedScope>(
VariableProxy* proxy, Scope* scope, Scope* outer_scope_end,
Scope* cache_scope, bool force_context_allocation);
template Variable* Scope::Lookup<Scope::kDeserializedScope>(
VariableProxy* proxy, Scope* scope, Scope* outer_scope_end,
Scope* cache_scope, bool force_context_allocation);
Variable* Scope::LookupWith(VariableProxy* proxy, Scope* scope,
Scope* outer_scope_end, Scope* cache_scope,
bool force_context_allocation) {
DCHECK(scope->is_with_scope());
Variable* var =
scope->outer_scope_->scope_info_.is_null()
? Lookup<kParsedScope>(proxy, scope->outer_scope_, outer_scope_end,
nullptr, force_context_allocation)
: Lookup<kDeserializedScope>(proxy, scope->outer_scope_,
outer_scope_end, cache_scope);
if (var == nullptr) return var;
// The current scope is a with scope, so the variable binding can not be
// statically resolved. However, note that it was necessary to do a lookup
// in the outer scope anyway, because if a binding exists in an outer
// scope, the associated variable has to be marked as potentially being
// accessed from inside of an inner with scope (the property may not be in
// the 'with' object).
if (!var->is_dynamic() && var->IsUnallocated()) {
DCHECK(!scope->already_resolved_);
var->set_is_used();
var->ForceContextAllocation();
if (proxy->is_assigned()) var->SetMaybeAssigned();
}
Scope* target_scope;
if (scope->deserialized_scope_uses_external_cache()) {
DCHECK_NOT_NULL(cache_scope);
cache_scope->variables_.Remove(var);
target_scope = cache_scope;
} else {
target_scope = scope;
}
Variable* dynamic =
target_scope->NonLocal(proxy->raw_name(), VariableMode::kDynamic);
dynamic->set_local_if_not_shadowed(var);
return dynamic;
}
Variable* Scope::LookupSloppyEval(VariableProxy* proxy, Scope* scope,
Scope* outer_scope_end, Scope* cache_scope,
bool force_context_allocation) {
DCHECK(scope->is_declaration_scope() &&
scope->AsDeclarationScope()->sloppy_eval_can_extend_vars());
// If we're compiling eval, it's possible that the outer scope is the first
// ScopeInfo-backed scope. We use the next declaration scope as the cache for
// this case, to avoid complexity around sloppy block function hoisting and
// conflict detection through catch scopes in the eval.
Scope* entry_cache = cache_scope == nullptr
? scope->outer_scope()->GetNonEvalDeclarationScope()
: cache_scope;
Variable* var =
scope->outer_scope_->scope_info_.is_null()
? Lookup<kParsedScope>(proxy, scope->outer_scope_, outer_scope_end,
nullptr, force_context_allocation)
: Lookup<kDeserializedScope>(proxy, scope->outer_scope_,
outer_scope_end, entry_cache);
if (var == nullptr) return var;
// We may not want to use the cache scope, change it back to the given scope
// if necessary.
if (!scope->deserialized_scope_uses_external_cache()) {
// For a deserialized scope, we'll be replacing the cache_scope.
DCHECK_IMPLIES(!scope->scope_info_.is_null(), cache_scope != nullptr);
cache_scope = scope;
}
// A variable binding may have been found in an outer scope, but the current
// scope makes a sloppy 'eval' call, so the found variable may not be the
// correct one (the 'eval' may introduce a binding with the same name). In
// that case, change the lookup result to reflect this situation. Only
// scopes that can host var bindings (declaration scopes) need be considered
// here (this excludes block and catch scopes), and variable lookups at
// script scope are always dynamic.
if (var->IsGlobalObjectProperty()) {
Scope* target = cache_scope == nullptr ? scope : cache_scope;
var = target->NonLocal(proxy->raw_name(), VariableMode::kDynamicGlobal);
}
if (var->is_dynamic()) return var;
Variable* invalidated = var;
if (cache_scope != nullptr) cache_scope->variables_.Remove(invalidated);
Scope* target = cache_scope == nullptr ? scope : cache_scope;
var = target->NonLocal(proxy->raw_name(), VariableMode::kDynamicLocal);
var->set_local_if_not_shadowed(invalidated);
return var;
}
void Scope::ResolveVariable(ParseInfo* info, VariableProxy* proxy) {
DCHECK(info->script_scope()->is_script_scope());
DCHECK(!proxy->is_resolved());
Variable* var = Lookup<kParsedScope>(proxy, this, nullptr);
DCHECK_NOT_NULL(var);
ResolveTo(info, proxy, var);
}
namespace {
void SetNeedsHoleCheck(Variable* var, VariableProxy* proxy) {
proxy->set_needs_hole_check();
var->ForceHoleInitialization();
}
void UpdateNeedsHoleCheck(Variable* var, VariableProxy* proxy, Scope* scope) {
if (var->mode() == VariableMode::kDynamicLocal) {
// Dynamically introduced variables never need a hole check (since they're
// VariableMode::kVar bindings, either from var or function declarations),
// but the variable they shadow might need a hole check, which we want to do
// if we decide that no shadowing variable was dynamically introoduced.
DCHECK_EQ(kCreatedInitialized, var->initialization_flag());
return UpdateNeedsHoleCheck(var->local_if_not_shadowed(), proxy, scope);
}
if (var->initialization_flag() == kCreatedInitialized) return;
// It's impossible to eliminate module import hole checks here, because it's
// unknown at compilation time whether the binding referred to in the
// exporting module itself requires hole checks.
if (var->location() == VariableLocation::MODULE && !var->IsExport()) {
return SetNeedsHoleCheck(var, proxy);
}
// Check if the binding really needs an initialization check. The check
// can be skipped in the following situation: we have a VariableMode::kLet or
// VariableMode::kConst binding, both the Variable and the VariableProxy have
// the same declaration scope (i.e. they are both in global code, in the same
// function or in the same eval code), the VariableProxy is in the source
// physically located after the initializer of the variable, and that the
// initializer cannot be skipped due to a nonlinear scope.
//
// The condition on the closure scopes is a conservative check for
// nested functions that access a binding and are called before the
// binding is initialized:
// function() { f(); let x = 1; function f() { x = 2; } }
//
// The check cannot be skipped on non-linear scopes, namely switch
// scopes, to ensure tests are done in cases like the following:
// switch (1) { case 0: let x = 2; case 1: f(x); }
// The scope of the variable needs to be checked, in case the use is
// in a sub-block which may be linear.
if (var->scope()->GetClosureScope() != scope->GetClosureScope()) {
return SetNeedsHoleCheck(var, proxy);
}
// We should always have valid source positions.
DCHECK_NE(var->initializer_position(), kNoSourcePosition);
DCHECK_NE(proxy->position(), kNoSourcePosition);
if (var->scope()->is_nonlinear() ||
var->initializer_position() >= proxy->position()) {
return SetNeedsHoleCheck(var, proxy);
}
}
} // anonymous namespace
void Scope::ResolveTo(ParseInfo* info, VariableProxy* proxy, Variable* var) {
DCHECK_NOT_NULL(var);
UpdateNeedsHoleCheck(var, proxy, this);
proxy->BindTo(var);
}
void Scope::ResolvePreparsedVariable(VariableProxy* proxy, Scope* scope,
Scope* end) {
// Resolve the variable in all parsed scopes to force context allocation.
for (; scope != end; scope = scope->outer_scope_) {
Variable* var = scope->LookupLocal(proxy->raw_name());
if (var != nullptr) {
var->set_is_used();
if (!var->is_dynamic()) {
var->ForceContextAllocation();
if (proxy->is_assigned()) var->SetMaybeAssigned();
return;
}
}
}
}
bool Scope::ResolveVariablesRecursively(ParseInfo* info) {
DCHECK(info->script_scope()->is_script_scope());
// Lazy parsed declaration scopes are already partially analyzed. If there are
// unresolved references remaining, they just need to be resolved in outer
// scopes.
if (WasLazilyParsed(this)) {
DCHECK_EQ(variables_.occupancy(), 0);
Scope* end = info->scope();
// Resolve in all parsed scopes except for the script scope.
if (!end->is_script_scope()) end = end->outer_scope();
for (VariableProxy* proxy : unresolved_list_) {
ResolvePreparsedVariable(proxy, outer_scope(), end);
}
} else {
// Resolve unresolved variables for this scope.
for (VariableProxy* proxy : unresolved_list_) {
ResolveVariable(info, proxy);
}
// Resolve unresolved variables for inner scopes.
for (Scope* scope = inner_scope_; scope != nullptr;
scope = scope->sibling_) {
if (!scope->ResolveVariablesRecursively(info)) return false;
}
}
return true;
}
bool Scope::MustAllocate(Variable* var) {
DCHECK(var->location() != VariableLocation::MODULE);
// Give var a read/write use if there is a chance it might be accessed
// via an eval() call. This is only possible if the variable has a
// visible name.
if (!var->raw_name()->IsEmpty() &&
(inner_scope_calls_eval_ || is_catch_scope() || is_script_scope())) {
var->set_is_used();
if (inner_scope_calls_eval_ && !var->is_this()) var->SetMaybeAssigned();
}
DCHECK(!var->has_forced_context_allocation() || var->is_used());
// Global variables do not need to be allocated.
return !var->IsGlobalObjectProperty() && var->is_used();
}
bool Scope::MustAllocateInContext(Variable* var) {
// If var is accessed from an inner scope, or if there is a possibility
// that it might be accessed from the current or an inner scope (through
// an eval() call or a runtime with lookup), it must be allocated in the
// context.
//
// Temporary variables are always stack-allocated. Catch-bound variables are
// always context-allocated.
VariableMode mode = var->mode();
if (mode == VariableMode::kTemporary) return false;
if (is_catch_scope()) return true;
if (is_script_scope() || is_eval_scope()) {
if (IsLexicalVariableMode(mode)) {
return true;
}
}
return var->has_forced_context_allocation() || inner_scope_calls_eval_;
}
void Scope::AllocateStackSlot(Variable* var) {
if (is_block_scope()) {
outer_scope()->GetDeclarationScope()->AllocateStackSlot(var);
} else {
var->AllocateTo(VariableLocation::LOCAL, num_stack_slots_++);
}
}
void Scope::AllocateHeapSlot(Variable* var) {
var->AllocateTo(VariableLocation::CONTEXT, num_heap_slots_++);
}
void DeclarationScope::AllocateParameterLocals() {
DCHECK(is_function_scope());
bool has_mapped_arguments = false;
if (arguments_ != nullptr) {
DCHECK(!is_arrow_scope());
if (MustAllocate(arguments_) && !has_arguments_parameter_) {
// 'arguments' is used and does not refer to a function
// parameter of the same name. If the arguments object
// aliases formal parameters, we conservatively allocate
// them specially in the loop below.
has_mapped_arguments =
GetArgumentsType() == CreateArgumentsType::kMappedArguments;
} else {
// 'arguments' is unused. Tell the code generator that it does not need to
// allocate the arguments object by nulling out arguments_.
arguments_ = nullptr;
}
}
// The same parameter may occur multiple times in the parameters_ list.
// If it does, and if it is not copied into the context object, it must
// receive the highest parameter index for that parameter; thus iteration
// order is relevant!
for (int i = num_parameters() - 1; i >= 0; --i) {
Variable* var = params_[i];
DCHECK_NOT_NULL(var);
DCHECK(!has_rest_ || var != rest_parameter());
DCHECK_EQ(this, var->scope());
if (has_mapped_arguments) {
var->set_is_used();
var->SetMaybeAssigned();
var->ForceContextAllocation();
}
AllocateParameter(var, i);
}
}
void DeclarationScope::AllocateParameter(Variable* var, int index) {
if (!MustAllocate(var)) return;
if (has_forced_context_allocation_for_parameters() ||
MustAllocateInContext(var)) {
DCHECK(var->IsUnallocated() || var->IsContextSlot());
if (var->IsUnallocated()) AllocateHeapSlot(var);
} else {
DCHECK(var->IsUnallocated() || var->IsParameter());
if (var->IsUnallocated()) {
var->AllocateTo(VariableLocation::PARAMETER, index);
}
}
}
void DeclarationScope::AllocateReceiver() {
if (!has_this_declaration()) return;
DCHECK_NOT_NULL(receiver());
DCHECK_EQ(receiver()->scope(), this);
AllocateParameter(receiver(), -1);
}
void Scope::AllocateNonParameterLocal(Variable* var) {
DCHECK_EQ(var->scope(), this);
if (var->IsUnallocated() && MustAllocate(var)) {
if (MustAllocateInContext(var)) {
AllocateHeapSlot(var);
DCHECK_IMPLIES(is_catch_scope(),
var->index() == Context::THROWN_OBJECT_INDEX);
} else {
AllocateStackSlot(var);
}
}
}
void Scope::AllocateNonParameterLocalsAndDeclaredGlobals() {
if (is_declaration_scope() && AsDeclarationScope()->is_arrow_scope()) {
// In arrow functions, allocate non-temporaries first and then all the
// temporaries to make the local variable ordering stable when reparsing to
// collect source positions.
for (Variable* local : locals_) {
if (local->mode() != VariableMode::kTemporary)
AllocateNonParameterLocal(local);
}
for (Variable* local : locals_) {
if (local->mode() == VariableMode::kTemporary)
AllocateNonParameterLocal(local);
}
} else {
for (Variable* local : locals_) {
AllocateNonParameterLocal(local);
}
}
if (is_declaration_scope()) {
AsDeclarationScope()->AllocateLocals();
}
}
void DeclarationScope::AllocateLocals() {
// For now, function_ must be allocated at the very end. If it gets
// allocated in the context, it must be the last slot in the context,
// because of the current ScopeInfo implementation (see
// ScopeInfo::ScopeInfo(FunctionScope* scope) constructor).
if (function_ != nullptr && MustAllocate(function_)) {
AllocateNonParameterLocal(function_);
} else {
function_ = nullptr;
}
DCHECK(!has_rest_ || !MustAllocate(rest_parameter()) ||
!rest_parameter()->IsUnallocated());
if (new_target_ != nullptr && !MustAllocate(new_target_)) {
new_target_ = nullptr;
}
NullifyRareVariableIf(RareVariable::kThisFunction,
[=](Variable* var) { return !MustAllocate(var); });
}
void ModuleScope::AllocateModuleVariables() {
for (const auto& it : module()->regular_imports()) {
Variable* var = LookupLocal(it.first);
var->AllocateTo(VariableLocation::MODULE, it.second->cell_index);
DCHECK(!var->IsExport());
}
for (const auto& it : module()->regular_exports()) {
Variable* var = LookupLocal(it.first);
var->AllocateTo(VariableLocation::MODULE, it.second->cell_index);
DCHECK(var->IsExport());
}
}
void Scope::AllocateVariablesRecursively() {
this->ForEach([](Scope* scope) -> Iteration {
DCHECK(!scope->already_resolved_);
if (WasLazilyParsed(scope)) return Iteration::kContinue;
DCHECK_EQ(scope->ContextHeaderLength(), scope->num_heap_slots_);
// Allocate variables for this scope.
// Parameters must be allocated first, if any.
if (scope->is_declaration_scope()) {
if (scope->is_function_scope()) {
scope->AsDeclarationScope()->AllocateParameterLocals();
}
scope->AsDeclarationScope()->AllocateReceiver();
}
scope->AllocateNonParameterLocalsAndDeclaredGlobals();
// Force allocation of a context for this scope if necessary. For a 'with'
// scope and for a function scope that makes an 'eval' call we need a
// context, even if no local variables were statically allocated in the
// scope. Likewise for modules and function scopes representing asm.js
// modules. Also force a context, if the scope is stricter than the outer
// scope.
bool must_have_context =
scope->is_with_scope() || scope->is_module_scope() ||
scope->IsAsmModule() || scope->ForceContextForLanguageMode() ||
(scope->is_function_scope() &&
scope->AsDeclarationScope()->sloppy_eval_can_extend_vars()) ||
(scope->is_block_scope() && scope->is_declaration_scope() &&
scope->AsDeclarationScope()->sloppy_eval_can_extend_vars());
// If we didn't allocate any locals in the local context, then we only
// need the minimal number of slots if we must have a context.
if (scope->num_heap_slots_ == scope->ContextHeaderLength() &&
!must_have_context) {
scope->num_heap_slots_ = 0;
}
// Allocation done.
DCHECK(scope->num_heap_slots_ == 0 ||
scope->num_heap_slots_ >= scope->ContextHeaderLength());
return Iteration::kDescend;
});
}
template <typename Isolate>
void Scope::AllocateScopeInfosRecursively(
Isolate* isolate, MaybeHandleFor<Isolate, ScopeInfo> outer_scope) {
DCHECK(scope_info_.is_null());
MaybeHandleFor<Isolate, ScopeInfo> next_outer_scope = outer_scope;
if (NeedsScopeInfo()) {
scope_info_ = ScopeInfo::Create(isolate, zone(), this, outer_scope);
// The ScopeInfo chain should mirror the context chain, so we only link to
// the next outer scope that needs a context.
if (NeedsContext()) next_outer_scope = scope_info_;
}
// Allocate ScopeInfos for inner scopes.
for (Scope* scope = inner_scope_; scope != nullptr; scope = scope->sibling_) {
if (!scope->is_function_scope() ||
scope->AsDeclarationScope()->ShouldEagerCompile()) {
scope->AllocateScopeInfosRecursively(isolate, next_outer_scope);
}
}
}
template EXPORT_TEMPLATE_DEFINE(V8_EXPORT_PRIVATE) void Scope::
AllocateScopeInfosRecursively<Isolate>(Isolate* isolate,
MaybeHandle<ScopeInfo> outer_scope);
template EXPORT_TEMPLATE_DEFINE(V8_EXPORT_PRIVATE) void Scope::
AllocateScopeInfosRecursively<OffThreadIsolate>(
OffThreadIsolate* isolate, OffThreadHandle<ScopeInfo> outer_scope);
void DeclarationScope::RecalcPrivateNameContextChain() {
// The outermost scope in a class heritage expression is marked to skip the
// class scope during private name resolution. It is possible, however, that
// either the class scope won't require a Context and ScopeInfo, or the
// outermost scope in the heritage position won't. Simply copying the bit from
// full parse into the ScopeInfo will break lazy compilation. In the former
// case the scope that is marked to skip its outer scope will incorrectly skip
// a different class scope than the one we intended to skip. In the latter
// case variables resolved through an inner scope will incorrectly check the
// class scope since we lost the skip bit from the outermost heritage scope.
//
// This method fixes both cases by, in outermost to innermost order, copying
// the value of the skip bit from outer scopes that don't require a Context.
DCHECK(needs_private_name_context_chain_recalc_);
this->ForEach([](Scope* scope) {
Scope* outer = scope->outer_scope();
if (!outer) return Iteration::kDescend;
if (!outer->NeedsContext()) {
scope->private_name_lookup_skips_outer_class_ =
outer->private_name_lookup_skips_outer_class();
}
if (!scope->is_function_scope() ||
scope->AsDeclarationScope()->ShouldEagerCompile()) {
return Iteration::kDescend;
}
return Iteration::kContinue;
});
}
void DeclarationScope::RecordNeedsPrivateNameContextChainRecalc() {
DCHECK_EQ(GetClosureScope(), this);
DeclarationScope* scope;
for (scope = this; scope != nullptr;
scope = scope->outer_scope() != nullptr
? scope->outer_scope()->GetClosureScope()
: nullptr) {
if (scope->needs_private_name_context_chain_recalc_) return;
scope->needs_private_name_context_chain_recalc_ = true;
}
}
// static
template <typename Isolate>
void DeclarationScope::AllocateScopeInfos(ParseInfo* info, Isolate* isolate) {
DeclarationScope* scope = info->literal()->scope();
// No one else should have allocated a scope info for this scope yet.
DCHECK(scope->scope_info_.is_null());
MaybeHandleFor<Isolate, ScopeInfo> outer_scope;
if (scope->outer_scope_ != nullptr) {
DCHECK((std::is_same<Isolate, v8::internal::Isolate>::value));
outer_scope = scope->outer_scope_->scope_info_;
}
if (scope->needs_private_name_context_chain_recalc()) {
scope->RecalcPrivateNameContextChain();
}
scope->AllocateScopeInfosRecursively(isolate, outer_scope);
// The debugger expects all shared function infos to contain a scope info.
// Since the top-most scope will end up in a shared function info, make sure
// it has one, even if it doesn't need a scope info.
// TODO(jochen|yangguo): Remove this requirement.
if (scope->scope_info_.is_null()) {
scope->scope_info_ =
ScopeInfo::Create(isolate, scope->zone(), scope, outer_scope);
}
// Ensuring that the outer script scope has a scope info avoids having
// special case for native contexts vs other contexts.
if (info->script_scope() && info->script_scope()->scope_info_.is_null()) {
info->script_scope()->scope_info_ = isolate->factory()->empty_scope_info();
}
}
template V8_EXPORT_PRIVATE void DeclarationScope::AllocateScopeInfos<Isolate>(
ParseInfo* info, Isolate* isolate);
template V8_EXPORT_PRIVATE void DeclarationScope::AllocateScopeInfos<
OffThreadIsolate>(ParseInfo* info, OffThreadIsolate* isolate);
int Scope::ContextLocalCount() const {
if (num_heap_slots() == 0) return 0;
Variable* function =
is_function_scope() ? AsDeclarationScope()->function_var() : nullptr;
bool is_function_var_in_context =
function != nullptr && function->IsContextSlot();
return num_heap_slots() - ContextHeaderLength() -
(is_function_var_in_context ? 1 : 0);
}
bool IsComplementaryAccessorPair(VariableMode a, VariableMode b) {
switch (a) {
case VariableMode::kPrivateGetterOnly:
return b == VariableMode::kPrivateSetterOnly;
case VariableMode::kPrivateSetterOnly:
return b == VariableMode::kPrivateGetterOnly;
default:
return false;
}
}
Variable* ClassScope::DeclarePrivateName(const AstRawString* name,
VariableMode mode,
IsStaticFlag is_static_flag,
bool* was_added) {
Variable* result = EnsureRareData()->private_name_map.Declare(
zone(), this, name, mode, NORMAL_VARIABLE,
InitializationFlag::kNeedsInitialization,
MaybeAssignedFlag::kMaybeAssigned, is_static_flag, was_added);
if (*was_added) {
locals_.Add(result);
has_static_private_methods_ |=
(result->is_static() &&
IsPrivateMethodOrAccessorVariableMode(result->mode()));
} else if (IsComplementaryAccessorPair(result->mode(), mode) &&
result->is_static_flag() == is_static_flag) {
*was_added = true;
result->set_mode(VariableMode::kPrivateGetterAndSetter);
}
result->ForceContextAllocation();
return result;
}
Variable* ClassScope::LookupLocalPrivateName(const AstRawString* name) {
RareData* rare_data = GetRareData();
if (rare_data == nullptr) {
return nullptr;
}
return rare_data->private_name_map.Lookup(name);
}
UnresolvedList::Iterator ClassScope::GetUnresolvedPrivateNameTail() {
RareData* rare_data = GetRareData();
if (rare_data == nullptr) {
return UnresolvedList::Iterator();
}
return rare_data->unresolved_private_names.end();
}
void ClassScope::ResetUnresolvedPrivateNameTail(UnresolvedList::Iterator tail) {
RareData* rare_data = GetRareData();
if (rare_data == nullptr ||
rare_data->unresolved_private_names.end() == tail) {
return;
}
bool tail_is_empty = tail == UnresolvedList::Iterator();
if (tail_is_empty) {
// If the saved tail is empty, the list used to be empty, so clear it.
rare_data->unresolved_private_names.Clear();
} else {
rare_data->unresolved_private_names.Rewind(tail);
}
}
void ClassScope::MigrateUnresolvedPrivateNameTail(
AstNodeFactory* ast_node_factory, UnresolvedList::Iterator tail) {
RareData* rare_data = GetRareData();
if (rare_data == nullptr ||
rare_data->unresolved_private_names.end() == tail) {
return;
}
UnresolvedList migrated_names;
// If the saved tail is empty, the list used to be empty, so we should
// migrate everything after the head.
bool tail_is_empty = tail == UnresolvedList::Iterator();
UnresolvedList::Iterator it =
tail_is_empty ? rare_data->unresolved_private_names.begin() : tail;
for (; it != rare_data->unresolved_private_names.end(); ++it) {
VariableProxy* proxy = *it;
VariableProxy* copy = ast_node_factory->CopyVariableProxy(proxy);
migrated_names.Add(copy);
}
// Replace with the migrated copies.
if (tail_is_empty) {
rare_data->unresolved_private_names.Clear();
} else {
rare_data->unresolved_private_names.Rewind(tail);
}
rare_data->unresolved_private_names.Append(std::move(migrated_names));
}
Variable* ClassScope::LookupPrivateNameInScopeInfo(const AstRawString* name) {
DCHECK(!scope_info_.is_null());
DCHECK_NULL(LookupLocalPrivateName(name));
DisallowHeapAllocation no_gc;
String name_handle = *name->string().get_handle();
VariableMode mode;
InitializationFlag init_flag;
MaybeAssignedFlag maybe_assigned_flag;
IsStaticFlag is_static_flag;
int index = ScopeInfo::ContextSlotIndex(
*scope_info_.get_handle(), name_handle, &mode, &init_flag,
&maybe_assigned_flag, &is_static_flag);
if (index < 0) {
return nullptr;
}
DCHECK(IsConstVariableMode(mode));
DCHECK_EQ(init_flag, InitializationFlag::kNeedsInitialization);
DCHECK_EQ(maybe_assigned_flag, MaybeAssignedFlag::kMaybeAssigned);
// Add the found private name to the map to speed up subsequent
// lookups for the same name.
bool was_added;
Variable* var = DeclarePrivateName(name, mode, is_static_flag, &was_added);
DCHECK(was_added);
var->AllocateTo(VariableLocation::CONTEXT, index);
return var;
}
Variable* ClassScope::LookupPrivateName(VariableProxy* proxy) {
DCHECK(!proxy->is_resolved());
for (PrivateNameScopeIterator scope_iter(this); !scope_iter.Done();
scope_iter.Next()) {
ClassScope* scope = scope_iter.GetScope();
// Try finding it in the private name map first, if it can't be found,
// try the deseralized scope info.
Variable* var = scope->LookupLocalPrivateName(proxy->raw_name());
if (var == nullptr && !scope->scope_info_.is_null()) {
var = scope->LookupPrivateNameInScopeInfo(proxy->raw_name());
}
if (var != nullptr) {
return var;
}
}
return nullptr;
}
bool ClassScope::ResolvePrivateNames(ParseInfo* info) {
RareData* rare_data = GetRareData();
if (rare_data == nullptr || rare_data->unresolved_private_names.is_empty()) {
return true;
}
UnresolvedList& list = rare_data->unresolved_private_names;
for (VariableProxy* proxy : list) {
Variable* var = LookupPrivateName(proxy);
if (var == nullptr) {
// It's only possible to fail to resolve private names here if
// this is at the top level or the private name is accessed through eval.
DCHECK(info->is_eval() || outer_scope_->is_script_scope());
Scanner::Location loc = proxy->location();
info->pending_error_handler()->ReportMessageAt(
loc.beg_pos, loc.end_pos,
MessageTemplate::kInvalidPrivateFieldResolution, proxy->raw_name());
return false;
} else {
proxy->BindTo(var);
}
}
// By now all unresolved private names should be resolved so
// clear the list.
list.Clear();
return true;
}
VariableProxy* ClassScope::ResolvePrivateNamesPartially() {
RareData* rare_data = GetRareData();
if (rare_data == nullptr || rare_data->unresolved_private_names.is_empty()) {
return nullptr;
}
PrivateNameScopeIterator private_name_scope_iter(this);
private_name_scope_iter.Next();
UnresolvedList& unresolved = rare_data->unresolved_private_names;
bool has_private_names = rare_data->private_name_map.capacity() > 0;
// If the class itself does not have private names, nor does it have
// an outer private name scope, then we are certain any private name access
// inside cannot be resolved.
if (!has_private_names && private_name_scope_iter.Done() &&
!unresolved.is_empty()) {
return unresolved.first();
}
for (VariableProxy* proxy = unresolved.first(); proxy != nullptr;) {
DCHECK(proxy->IsPrivateName());
VariableProxy* next = proxy->next_unresolved();
unresolved.Remove(proxy);
Variable* var = nullptr;
// If we can find private name in the current class scope, we can bind
// them immediately because it's going to shadow any outer private names.
if (has_private_names) {
var = LookupLocalPrivateName(proxy->raw_name());
if (var != nullptr) {
var->set_is_used();
proxy->BindTo(var);
// If the variable being accessed is a static private method, we need to
// save the class variable in the context to check that the receiver is
// the class during runtime.
has_explicit_static_private_methods_access_ |=
(var->is_static() &&
IsPrivateMethodOrAccessorVariableMode(var->mode()));
}
}
// If the current scope does not have declared private names,
// try looking from the outer class scope later.
if (var == nullptr) {
// There's no outer private name scope so we are certain that the variable
// cannot be resolved later.
if (private_name_scope_iter.Done()) {
return proxy;
}
// The private name may be found later in the outer private name scope, so
// push it to the outer sopce.
private_name_scope_iter.AddUnresolvedPrivateName(proxy);
}
proxy = next;
}
DCHECK(unresolved.is_empty());
return nullptr;
}
Variable* ClassScope::DeclareBrandVariable(AstValueFactory* ast_value_factory,
IsStaticFlag is_static_flag,
int class_token_pos) {
DCHECK_IMPLIES(GetRareData() != nullptr, GetRareData()->brand == nullptr);
bool was_added;
Variable* brand = Declare(zone(), ast_value_factory->dot_brand_string(),
VariableMode::kConst, NORMAL_VARIABLE,
InitializationFlag::kNeedsInitialization,
MaybeAssignedFlag::kMaybeAssigned, &was_added);
DCHECK(was_added);
brand->set_is_static_flag(is_static_flag);
brand->ForceContextAllocation();
brand->set_is_used();
EnsureRareData()->brand = brand;
brand->set_initializer_position(class_token_pos);
return brand;
}
Variable* ClassScope::DeclareClassVariable(AstValueFactory* ast_value_factory,
const AstRawString* name,
int class_token_pos) {
DCHECK_NULL(class_variable_);
bool was_added;
class_variable_ =
Declare(zone(), name == nullptr ? ast_value_factory->dot_string() : name,
VariableMode::kConst, NORMAL_VARIABLE,
InitializationFlag::kNeedsInitialization,
MaybeAssignedFlag::kMaybeAssigned, &was_added);
DCHECK(was_added);
class_variable_->set_initializer_position(class_token_pos);
return class_variable_;
}
PrivateNameScopeIterator::PrivateNameScopeIterator(Scope* start)
: start_scope_(start), current_scope_(start) {
if (!start->is_class_scope() || start->AsClassScope()->IsParsingHeritage()) {
Next();
}
}
void PrivateNameScopeIterator::Next() {
DCHECK(!Done());
Scope* inner = current_scope_;
Scope* scope = inner->outer_scope();
while (scope != nullptr) {
if (scope->is_class_scope()) {
if (!inner->private_name_lookup_skips_outer_class()) {
current_scope_ = scope;
return;
}
skipped_any_scopes_ = true;
}
inner = scope;
scope = scope->outer_scope();
}
current_scope_ = nullptr;
}
void PrivateNameScopeIterator::AddUnresolvedPrivateName(VariableProxy* proxy) {
// During a reparse, current_scope_->already_resolved_ may be true here,
// because the class scope is deserialized while the function scope inside may
// be new.
DCHECK(!proxy->is_resolved());
DCHECK(proxy->IsPrivateName());
GetScope()->EnsureRareData()->unresolved_private_names.Add(proxy);
// Any closure scope that contain uses of private names that skips over a
// class scope due to heritage expressions need private name context chain
// recalculation, since not all scopes require a Context or ScopeInfo. See
// comment in DeclarationScope::RecalcPrivateNameContextChain.
if (V8_UNLIKELY(skipped_any_scopes_)) {
start_scope_->GetClosureScope()->RecordNeedsPrivateNameContextChainRecalc();
}
}
} // namespace internal
} // namespace v8
|
/*
Copyright 2020 The OneFlow 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 "oneflow/core/graph/boxing/slice_boxing_sub_task_graph_builder.h"
#include "oneflow/core/register/tensor_slice_view.h"
#include "oneflow/core/common/balanced_splitter.h"
#include "oneflow/core/graph/slice_boxing_task_node.h"
#include "oneflow/core/graph/boxing/sub_task_graph_builder_util.h"
#include "oneflow/core/job/parallel_distribution_util.h"
#include "oneflow/core/common/id_util.h"
#include "oneflow/core/graph/id_serialization.h"
#include "oneflow/core/device/cpu_stream_index.h"
#ifdef WITH_CUDA
#include "oneflow/core/device/cuda_stream_index.h"
#endif
namespace oneflow {
namespace {
void GroupParallelIdByMachine(const ParallelDesc& pd,
HashMap<int64_t, std::vector<int64_t>>* machine_id2parallel_ids) {
FOR_RANGE(int64_t, parallel_id, 0, pd.parallel_num()) {
int64_t machine_id = CHECK_JUST(pd.MachineId4ParallelId(parallel_id));
(*machine_id2parallel_ids)[machine_id].push_back(parallel_id);
}
}
bool ContainsEmptySlice(const std::vector<TensorSliceView>& slices) {
return std::any_of(slices.cbegin(), slices.cend(),
[](const TensorSliceView& slice) { return slice.IsEmpty(); });
}
bool IsCopyContiguous(const TensorSliceView& src, const TensorSliceView& dst) {
CHECK_EQ(src.range_vec().size(), dst.range_vec().size());
FOR_RANGE(int64_t, i, 1, src.range_vec().size()) {
if (src.range_vec().at(i) != dst.range_vec().at(i)) { return false; }
}
return true;
}
bool IsSameDevice(const ParallelDesc& in_pd, const ParallelDesc& out_pd,
const int64_t in_parallel_id, const int64_t out_parallel_id) {
return in_pd.device_type() == out_pd.device_type()
&& CHECK_JUST(in_pd.DeviceId4ParallelId(in_parallel_id))
== CHECK_JUST(out_pd.DeviceId4ParallelId(out_parallel_id));
}
} // namespace
Maybe<SubTskGphBuilderStatus> SliceBoxingSubTskGphBuilder::Build(
SubTskGphBuilderCtx* ctx, const std::vector<TaskNode*>& sorted_in_tasks,
std::vector<TaskNode*>* sorted_out_tasks,
std::vector<std::vector<TaskNode*>>* sorted_ctrl_tasks, const ParallelDesc& in_parallel_desc,
const ParallelDesc& out_parallel_desc, const LogicalBlobId& lbi,
const BlobDesc& logical_blob_desc, const cfg::SbpParallel& in_sbp_parallel,
const cfg::SbpParallel& out_sbp_parallel, const Shape& time_shape) const {
if (SubTskGphBuilderUtil::BlobHasDynamicShape(logical_blob_desc)) {
return Error::BoxingNotSupportedError();
}
if (!SubTskGphBuilderUtil::IsDeviceTypeCPUOrGPU(in_parallel_desc)) {
return Error::BoxingNotSupportedError();
}
if (!SubTskGphBuilderUtil::IsDeviceTypeCPUOrGPU(out_parallel_desc)) {
return Error::BoxingNotSupportedError();
}
if (SubTskGphBuilderUtil::HasEmptySliceIfSplit(in_parallel_desc.parallel_num(), in_sbp_parallel,
logical_blob_desc)) {
return Error::BoxingNotSupportedError();
}
if (SubTskGphBuilderUtil::HasEmptySliceIfSplit(out_parallel_desc.parallel_num(), out_sbp_parallel,
logical_blob_desc)) {
return Error::BoxingNotSupportedError();
}
if (!(SubTskGphBuilderUtil::IsBoxingS2B(in_sbp_parallel, out_sbp_parallel)
|| SubTskGphBuilderUtil::IsBoxingS2S(in_sbp_parallel, out_sbp_parallel)
|| SubTskGphBuilderUtil::IsBoxingP2S(in_sbp_parallel, out_sbp_parallel)
|| SubTskGphBuilderUtil::IsBoxingP2B(in_sbp_parallel, out_sbp_parallel)
|| SubTskGphBuilderUtil::IsBoxingB2S(in_sbp_parallel, out_sbp_parallel))) {
return Error::BoxingNotSupportedError();
}
const auto GetBoxingGpuThrdId = [](int64_t machine_id, int64_t dev_id,
CudaWorkType work_type) -> int64_t {
int64_t thrd_id = -1;
#ifdef WITH_CUDA
DeviceId device_id{static_cast<DeviceId::rank_t>(machine_id), DeviceType::kGPU,
static_cast<DeviceId::device_index_t>(dev_id)};
auto* generator = dynamic_cast<CudaStreamIndexGenerator*>(
Global<IDMgr>::Get()->GetStreamIndexGeneratorManager()->GetGenerator(device_id));
CHECK_NOTNULL(generator);
StreamId::stream_index_t stream_index = 0;
if (work_type == CudaWorkType::kCopyH2D) {
stream_index = generator->GenerateH2DStreamIndex();
} else if (work_type == CudaWorkType::kCopyD2H) {
stream_index = generator->GenerateD2HStreamIndex();
} else if (work_type == CudaWorkType::kMix) {
stream_index = generator->GenerateMixStreamIndex();
} else {
UNIMPLEMENTED();
}
thrd_id = SerializeStreamIdToInt64(StreamId{device_id, stream_index});
#else
UNIMPLEMENTED();
#endif
return thrd_id;
};
const auto NewEdge = [&ctx]() -> TaskEdge* { return ctx->task_graph()->NewEdge(); };
const auto CreateBoxingNode121 = [&ctx, &lbi, &GetBoxingGpuThrdId](
const ParallelDesc& pd, const int64_t parallel_id,
const TensorSliceView& slice,
SliceBoxingTaskMode mode) -> SliceBoxingTaskNode* {
SliceBoxingTaskNode* node = ctx->task_graph()->NewNode<SliceBoxingTaskNode>();
const int64_t machine_id = CHECK_JUST(pd.MachineId4ParallelId(parallel_id));
int64_t thrd_id = -1;
if (pd.device_type() == DeviceType::kCPU) {
thrd_id = Global<IDMgr>::Get()->PickCpuThrdIdEvenly(machine_id);
} else if (pd.device_type() == DeviceType::kGPU) {
#ifdef WITH_CUDA
int64_t dev_id = CHECK_JUST(pd.DeviceId4ParallelId(parallel_id));
thrd_id = GetBoxingGpuThrdId(machine_id, dev_id, CudaWorkType::kCopyH2D);
#else
UNIMPLEMENTED();
#endif
} else {
UNIMPLEMENTED();
}
node->Init(lbi, slice, mode, machine_id, thrd_id);
return node;
};
const auto CreateBoxingNodeToHost =
[&ctx, &lbi, &GetBoxingGpuThrdId, &NewEdge](
TaskNode* src_node, const TensorSliceView& src_slice,
const TensorSliceView& dst_slice) -> SliceBoxingTaskNode* {
SliceBoxingTaskNode* dst_node = ctx->task_graph()->NewNode<SliceBoxingTaskNode>();
int64_t thrd_id = -1;
if (src_node->device_type() == DeviceType::kCPU) {
thrd_id = Global<IDMgr>::Get()->PickCpuThrdIdEvenly(src_node->machine_id());
} else if (src_node->device_type() == DeviceType::kGPU) {
#ifdef WITH_CUDA
thrd_id =
GetBoxingGpuThrdId(src_node->machine_id(), src_node->GpuPhyId(), CudaWorkType::kCopyD2H);
#else
UNIMPLEMENTED();
#endif
} else {
UNIMPLEMENTED();
}
dst_node->Init(lbi, dst_slice, kSliceBoxingTaskModeCopy, src_node->machine_id(), thrd_id,
GetNodeCPUMemZoneId(src_node->machine_id()));
dst_node->ConnectToSrcNodeWithSlice(src_node, NewEdge(), src_slice);
return dst_node;
};
const auto BuildSubTaskGphS2B =
[&ctx, &CreateBoxingNode121, &NewEdge, &lbi](
const ParallelDesc& in_pd, const ParallelDesc& out_pd, const cfg::SbpParallel& in_sbp,
const cfg::SbpParallel& out_sbp, const BlobDesc& blob_desc,
const std::vector<TaskNode*>& in_nodes, std::vector<TaskNode*>* out_nodes) {
CHECK(SubTskGphBuilderUtil::IsBoxingS2B(in_sbp, out_sbp));
const std::vector<TensorSliceView> in_slices =
GetTensorSliceView(in_pd.parallel_num(), in_sbp, blob_desc);
CHECK(!ContainsEmptySlice(in_slices));
const TensorSliceView out_slice = GetBroadcastTensorSliceView(blob_desc);
FOR_RANGE(int64_t, out_id, 0, out_pd.parallel_num()) {
SliceBoxingTaskNode* out_node =
CreateBoxingNode121(out_pd, out_id, out_slice, kSliceBoxingTaskModeCopy);
FOR_RANGE(int64_t, in_id, 0, in_pd.parallel_num()) {
const TensorSliceView& in_slice = in_slices.at(in_id);
TaskNode* in_node = in_nodes.at(in_id);
if (SubTskGphBuilderUtil::IsOnSameGPU(in_node, out_node)) {
out_node->ConnectToSrcNodeWithSlice(in_node, NewEdge(), in_slice);
} else {
TaskNode* proxy_node = ctx->task_graph()->GetProxyNode(
in_node, lbi, GetNodeCPUMemZoneId(out_node->machine_id()));
out_node->ConnectToSrcNodeWithSlice(proxy_node, NewEdge(), in_slice);
}
}
out_nodes->push_back(out_node);
}
};
const auto BuildSubTaskGphS2S = [&ctx, &lbi, &CreateBoxingNode121, &CreateBoxingNodeToHost,
&GetBoxingGpuThrdId, &NewEdge](
const ParallelDesc& in_pd, const ParallelDesc& out_pd,
const cfg::SbpParallel& in_sbp,
const cfg::SbpParallel& out_sbp, const BlobDesc& blob_desc,
const std::vector<TaskNode*>& in_nodes,
std::vector<TaskNode*>* out_nodes) {
CHECK(SubTskGphBuilderUtil::IsBoxingS2S(in_sbp, out_sbp));
const std::vector<TensorSliceView> in_slices =
GetTensorSliceView(in_pd.parallel_num(), in_sbp, blob_desc);
CHECK(!ContainsEmptySlice(in_slices));
const std::vector<TensorSliceView> out_slices =
GetTensorSliceView(out_pd.parallel_num(), out_sbp, blob_desc);
CHECK(!ContainsEmptySlice(out_slices));
HashMap<int64_t, std::vector<int64_t>> machine_id2in_parallel_ids;
GroupParallelIdByMachine(in_pd, &machine_id2in_parallel_ids);
FOR_RANGE(int64_t, out_id, 0, out_pd.parallel_num()) {
const TensorSliceView& out_slice = out_slices.at(out_id);
SliceBoxingTaskNode* out_node =
CreateBoxingNode121(out_pd, out_id, out_slice, kSliceBoxingTaskModeCopy);
for (const auto& pair : machine_id2in_parallel_ids) {
const int64_t in_machine_id = pair.first;
const std::vector<int64_t>& in_parallel_ids = pair.second;
if (out_node->machine_id() == in_machine_id) {
for (const int64_t in_id : in_parallel_ids) {
const TensorSliceView& in_slice = in_slices.at(in_id);
const TensorSliceView& intersection = out_slice.Intersect(in_slice);
if (intersection.IsEmpty()) { continue; }
TaskNode* in_node = in_nodes.at(in_id);
if (in_pd.device_type() == DeviceType::kGPU
&& out_pd.device_type() == DeviceType::kCPU) {
SliceBoxingTaskNode* copy_to_host =
CreateBoxingNodeToHost(in_node, in_slice, intersection);
out_node->ConnectToSrcNodeWithSlice(copy_to_host, NewEdge(), intersection);
} else if (in_pd.device_type() == DeviceType::kCPU
&& out_pd.device_type() == DeviceType::kCPU) {
out_node->ConnectToSrcNodeWithSlice(in_node, NewEdge(), in_slice);
} else {
bool in_contiguous = IsCopyContiguous(in_slice, intersection);
bool out_contiguous = IsCopyContiguous(intersection, out_slice);
if (IsSameDevice(in_pd, out_pd, in_id, out_id) || (in_contiguous && out_contiguous)) {
out_node->ConnectToSrcNodeWithSlice(in_node, NewEdge(), in_slice);
} else if (in_contiguous && !out_contiguous) {
SliceBoxingTaskNode* copy_to_out_continuous =
CreateBoxingNode121(out_pd, out_id, intersection, kSliceBoxingTaskModeCopy);
copy_to_out_continuous->ConnectToSrcNodeWithSlice(in_node, NewEdge(), in_slice);
out_node->ConnectToSrcNodeWithSlice(copy_to_out_continuous, NewEdge(),
intersection);
} else if (!in_contiguous && out_contiguous) {
SliceBoxingTaskNode* in_copy_to_continuous =
CreateBoxingNode121(in_pd, in_id, intersection, kSliceBoxingTaskModeCopy);
in_copy_to_continuous->ConnectToSrcNodeWithSlice(in_node, NewEdge(), in_slice);
out_node->ConnectToSrcNodeWithSlice(in_copy_to_continuous, NewEdge(), intersection);
} else {
SliceBoxingTaskNode* in_copy_to_continuous =
CreateBoxingNode121(in_pd, in_id, intersection, kSliceBoxingTaskModeCopy);
in_copy_to_continuous->ConnectToSrcNodeWithSlice(in_node, NewEdge(), in_slice);
SliceBoxingTaskNode* copy_to_out_continuous =
CreateBoxingNode121(out_pd, out_id, intersection, kSliceBoxingTaskModeCopy);
copy_to_out_continuous->ConnectToSrcNodeWithSlice(in_copy_to_continuous, NewEdge(),
intersection);
out_node->ConnectToSrcNodeWithSlice(copy_to_out_continuous, NewEdge(),
intersection);
}
}
}
} else {
HashMap<int64_t, TensorSliceView> in_id2intersection;
std::vector<TensorSliceView> non_empty_intersections;
for (const int64_t in_id : in_parallel_ids) {
const TensorSliceView& intersection = out_slice.Intersect(in_slices.at(in_id));
in_id2intersection[in_id] = intersection;
if (!intersection.IsEmpty()) { non_empty_intersections.push_back(intersection); }
}
if (non_empty_intersections.empty()) { continue; }
const TensorSliceView concat_slice =
TensorSliceView::Concatenate(non_empty_intersections, in_sbp.split_parallel().axis());
SliceBoxingTaskNode* local_concat_node =
ctx->task_graph()->NewNode<SliceBoxingTaskNode>();
int64_t local_concat_thrd_id = -1;
if (in_pd.device_type() == DeviceType::kCPU) {
local_concat_thrd_id = Global<IDMgr>::Get()->PickCpuThrdIdEvenly(in_machine_id);
} else if (in_pd.device_type() == DeviceType::kGPU) {
#ifdef WITH_CUDA
TaskNode* node = in_nodes.at(in_parallel_ids.at(out_id % in_parallel_ids.size()));
local_concat_thrd_id =
GetBoxingGpuThrdId(node->machine_id(), node->GpuPhyId(), CudaWorkType::kCopyD2H);
#else
UNIMPLEMENTED();
#endif
}
local_concat_node->Init(lbi, concat_slice, kSliceBoxingTaskModeCopy, in_machine_id,
local_concat_thrd_id, GetNodeCPUMemZoneId(in_machine_id));
for (const int64_t in_id : in_parallel_ids) {
if (!in_id2intersection.at(in_id).IsEmpty()) {
local_concat_node->ConnectToSrcNodeWithSlice(in_nodes.at(in_id), NewEdge(),
in_slices.at(in_id));
}
}
TaskNode* local_add_proxy_node = ctx->task_graph()->GetProxyNode(
local_concat_node, lbi, GetNodeCPUMemZoneId(out_node->machine_id()));
out_node->ConnectToSrcNodeWithSlice(local_add_proxy_node, NewEdge(), concat_slice);
}
}
out_nodes->push_back(out_node);
}
};
const auto BuildSubTaskGphP2S =
[&ctx, &lbi, &CreateBoxingNode121, &CreateBoxingNodeToHost, &GetBoxingGpuThrdId, &NewEdge](
const ParallelDesc& in_pd, const ParallelDesc& out_pd, const cfg::SbpParallel& in_sbp,
const cfg::SbpParallel& out_sbp, const BlobDesc& blob_desc,
const std::vector<TaskNode*>& in_nodes, std::vector<TaskNode*>* out_nodes) {
CHECK(SubTskGphBuilderUtil::IsBoxingP2S(in_sbp, out_sbp));
const TensorSliceView in_slice = GetBroadcastTensorSliceView(blob_desc);
const std::vector<TensorSliceView> out_slices =
GetTensorSliceView(out_pd.parallel_num(), out_sbp, blob_desc);
CHECK(!ContainsEmptySlice(out_slices));
HashMap<int64_t, std::vector<int64_t>> machine_id2in_parallel_ids;
GroupParallelIdByMachine(in_pd, &machine_id2in_parallel_ids);
FOR_RANGE(int64_t, out_id, 0, out_pd.parallel_num()) {
const TensorSliceView& out_slice = out_slices.at(out_id);
SliceBoxingTaskNode* out_node =
CreateBoxingNode121(out_pd, out_id, out_slice, kSliceBoxingTaskModeAdd);
for (const auto& pair : machine_id2in_parallel_ids) {
const int64_t in_machine_id = pair.first;
const std::vector<int64_t>& in_parallel_ids = pair.second;
if (out_node->machine_id() == in_machine_id) {
for (const int64_t in_id : in_parallel_ids) {
TaskNode* in_node = in_nodes.at(in_id);
if (SubTskGphBuilderUtil::IsOnSameGPU(in_node, out_node)) {
out_node->ConnectToSrcNodeWithSlice(in_node, NewEdge(), in_slice);
} else if (in_pd.device_type() == DeviceType::kGPU) {
SliceBoxingTaskNode* copy_to_host =
CreateBoxingNodeToHost(in_node, in_slice, out_slice);
out_node->ConnectToSrcNodeWithSlice(copy_to_host, NewEdge(), out_slice);
} else {
out_node->ConnectToSrcNodeWithSlice(in_node, NewEdge(), in_slice);
}
}
} else {
auto* local_add_node = ctx->task_graph()->NewNode<SliceBoxingTaskNode>();
int64_t local_add_thrd_id = -1;
if (in_pd.device_type() == DeviceType::kCPU) {
local_add_thrd_id = Global<IDMgr>::Get()->PickCpuThrdIdEvenly(in_machine_id);
} else if (in_pd.device_type() == DeviceType::kGPU) {
#ifdef WITH_CUDA
TaskNode* node = in_nodes.at(in_parallel_ids.at(out_id % in_parallel_ids.size()));
local_add_thrd_id = GetBoxingGpuThrdId(node->machine_id(), node->GpuPhyId(),
CudaWorkType::kCopyD2H);
#else
UNIMPLEMENTED();
#endif
}
local_add_node->Init(lbi, out_slice, kSliceBoxingTaskModeAdd, in_machine_id,
local_add_thrd_id, GetNodeCPUMemZoneId(in_machine_id));
for (const int64_t in_id : in_parallel_ids) {
local_add_node->ConnectToSrcNodeWithSlice(in_nodes.at(in_id), NewEdge(), in_slice);
}
TaskNode* local_add_proxy_node = ctx->task_graph()->GetProxyNode(
local_add_node, lbi, GetNodeCPUMemZoneId(out_node->machine_id()));
out_node->ConnectToSrcNodeWithSlice(local_add_proxy_node, NewEdge(), out_slice);
}
}
out_nodes->push_back(out_node);
}
};
const auto BuildSubTaskGphP2B = [&ctx, &lbi, &GetBoxingGpuThrdId, &NewEdge](
const ParallelDesc& in_pd, const ParallelDesc& out_pd,
const cfg::SbpParallel& in_sbp,
const cfg::SbpParallel& out_sbp, const BlobDesc& blob_desc,
const std::vector<TaskNode*>& in_nodes,
std::vector<TaskNode*>* out_nodes) {
CHECK(SubTskGphBuilderUtil::IsBoxingP2B(in_sbp, out_sbp));
const TensorSliceView slice = GetBroadcastTensorSliceView(blob_desc);
HashMap<int64_t, std::vector<int64_t>> machine_id2in_parallel_ids;
HashMap<int64_t, std::vector<int64_t>> machine_id2out_parallel_ids;
GroupParallelIdByMachine(in_pd, &machine_id2in_parallel_ids);
GroupParallelIdByMachine(out_pd, &machine_id2out_parallel_ids);
std::vector<TaskNode*> out_box_nodes;
for (const auto& machine_id7in_parallel_ids : machine_id2in_parallel_ids) {
const int64_t in_machine_id = machine_id7in_parallel_ids.first;
const std::vector<int64_t>& in_ids_on_machine = machine_id7in_parallel_ids.second;
if (in_ids_on_machine.size() == 1) {
out_box_nodes.push_back(in_nodes.at(in_ids_on_machine.front()));
} else {
auto* local_add_node = ctx->task_graph()->NewNode<SliceBoxingTaskNode>();
int64_t local_add_thrd_id = -1;
if (in_pd.device_type() == DeviceType::kCPU) {
local_add_thrd_id = Global<IDMgr>::Get()->PickCpuThrdIdEvenly(in_machine_id);
} else if (in_pd.device_type() == DeviceType::kGPU) {
#ifdef WITH_CUDA
TaskNode* node = in_nodes.at(in_ids_on_machine.front());
local_add_thrd_id =
GetBoxingGpuThrdId(node->machine_id(), node->GpuPhyId(), CudaWorkType::kCopyH2D);
#else
UNIMPLEMENTED();
#endif
}
local_add_node->Init(lbi, slice, kSliceBoxingTaskModeAdd, in_machine_id, local_add_thrd_id);
FOR_RANGE(int64_t, i, 0, in_ids_on_machine.size()) {
local_add_node->ConnectToSrcNodeWithSlice(in_nodes.at(in_ids_on_machine.at(i)), NewEdge(),
slice);
}
out_box_nodes.push_back(local_add_node);
}
}
out_nodes->resize(out_pd.parallel_num());
for (const auto& machine_id7out_parallel_ids : machine_id2out_parallel_ids) {
const int64_t out_machine_id = machine_id7out_parallel_ids.first;
TaskNode* in_box_node = nullptr;
if (out_box_nodes.size() == 1) {
in_box_node = ctx->task_graph()->GetProxyNode(
out_box_nodes.front(), lbi, GetNodeCPUMemZoneId(machine_id7out_parallel_ids.first));
} else {
auto* add_node = ctx->task_graph()->NewNode<SliceBoxingTaskNode>();
add_node->Init(lbi, slice, kSliceBoxingTaskModeAdd, machine_id7out_parallel_ids.first,
Global<IDMgr>::Get()->PickCpuThrdIdEvenly(machine_id7out_parallel_ids.first),
GetNodeCPUMemZoneId(machine_id7out_parallel_ids.first));
for (TaskNode* out_box_node : out_box_nodes) {
TaskNode* out_boxing_node_proxy = ctx->task_graph()->GetProxyNode(
out_box_node, lbi, GetNodeCPUMemZoneId(out_machine_id));
add_node->ConnectToSrcNodeWithSlice(out_boxing_node_proxy, NewEdge(), slice);
}
in_box_node = add_node;
}
for (const int64_t out_id : machine_id7out_parallel_ids.second) {
if (out_pd.device_type() == DeviceType::kCPU) {
(*out_nodes)[out_id] = ctx->task_graph()->GetProxyNode(
in_box_node, lbi, GetNodeCPUMemZoneId(out_machine_id));
} else if (out_pd.device_type() == DeviceType::kGPU) {
int64_t dev_id = CHECK_JUST(out_pd.DeviceId4ParallelId(out_id));
(*out_nodes)[out_id] = ctx->task_graph()->GetProxyNode(
in_box_node, lbi,
MemZoneId{static_cast<MemZoneId::node_index_t>(out_machine_id), DeviceType::kGPU,
static_cast<MemZoneId::device_index_t>(dev_id)});
} else {
UNIMPLEMENTED();
}
}
}
};
const auto BuildSubTaskGphB2S =
[&ctx, &lbi, &CreateBoxingNode121, &CreateBoxingNodeToHost, &GetBoxingGpuThrdId, &NewEdge](
const ParallelDesc& in_pd, const ParallelDesc& out_pd, const cfg::SbpParallel& in_sbp,
const cfg::SbpParallel& out_sbp, const BlobDesc& blob_desc,
const std::vector<TaskNode*>& in_nodes, std::vector<TaskNode*>* out_nodes) {
CHECK(SubTskGphBuilderUtil::IsBoxingB2S(in_sbp, out_sbp));
const TensorSliceView in_slice = GetBroadcastTensorSliceView(blob_desc);
const std::vector<TensorSliceView> out_slices =
GetTensorSliceView(out_pd.parallel_num(), out_sbp, blob_desc);
CHECK(!ContainsEmptySlice(out_slices));
FOR_RANGE(int64_t, out_id, 0, out_pd.parallel_num()) {
const TensorSliceView& out_slice = out_slices.at(out_id);
const int64_t nearest_idx =
SubTskGphBuilderUtil::FindNearestSrcParallelId(in_pd, out_pd, out_id);
TaskNode* in_node = in_nodes.at(nearest_idx);
SliceBoxingTaskNode* slice_node =
CreateBoxingNode121(in_pd, nearest_idx, out_slice, kSliceBoxingTaskModeCopy);
slice_node->ConnectToSrcNodeWithSlice(in_node, NewEdge(), in_slice);
TaskNode* out_node = ctx->task_graph()->GetProxyNode(slice_node, lbi, out_pd, out_id);
out_nodes->push_back(out_node);
}
};
std::string comment;
if (SubTskGphBuilderUtil::IsBoxingS2B(in_sbp_parallel, out_sbp_parallel)) {
BuildSubTaskGphS2B(in_parallel_desc, out_parallel_desc, in_sbp_parallel, out_sbp_parallel,
logical_blob_desc, sorted_in_tasks, sorted_out_tasks);
comment = "BuildSubTaskGphS2B";
} else if (SubTskGphBuilderUtil::IsBoxingS2S(in_sbp_parallel, out_sbp_parallel)) {
BuildSubTaskGphS2S(in_parallel_desc, out_parallel_desc, in_sbp_parallel, out_sbp_parallel,
logical_blob_desc, sorted_in_tasks, sorted_out_tasks);
comment = "BuildSubTaskGphS2S";
} else if (SubTskGphBuilderUtil::IsBoxingP2S(in_sbp_parallel, out_sbp_parallel)) {
BuildSubTaskGphP2S(in_parallel_desc, out_parallel_desc, in_sbp_parallel, out_sbp_parallel,
logical_blob_desc, sorted_in_tasks, sorted_out_tasks);
comment = "BuildSubTaskGphP2S";
} else if (SubTskGphBuilderUtil::IsBoxingP2B(in_sbp_parallel, out_sbp_parallel)) {
if (logical_blob_desc.shape().elem_cnt() < out_parallel_desc.parallel_num()) {
BuildSubTaskGphP2B(in_parallel_desc, out_parallel_desc, in_sbp_parallel, out_sbp_parallel,
logical_blob_desc, sorted_in_tasks, sorted_out_tasks);
comment = "BuildSubTaskGphP2B";
} else {
BlobDesc flat_blob_desc(logical_blob_desc.data_type());
flat_blob_desc.mut_shape() = Shape({logical_blob_desc.shape().elem_cnt()});
std::vector<TaskNode*> middle_nodes;
cfg::SbpParallel middle_sbp;
middle_sbp.mutable_split_parallel()->set_axis(0);
BuildSubTaskGphP2S(in_parallel_desc, out_parallel_desc, in_sbp_parallel, middle_sbp,
flat_blob_desc, sorted_in_tasks, &middle_nodes);
BuildSubTaskGphS2B(out_parallel_desc, out_parallel_desc, middle_sbp, out_sbp_parallel,
flat_blob_desc, middle_nodes, sorted_out_tasks);
comment = "BuildSubTaskGphP2S->BuildSubTaskGphS2B";
for (TaskNode* out_node : *sorted_out_tasks) {
auto* slice_boxing_node = dynamic_cast<SliceBoxingTaskNode*>(out_node);
CHECK_NOTNULL(slice_boxing_node);
slice_boxing_node->SetOutShape(logical_blob_desc.shape());
}
}
} else if (SubTskGphBuilderUtil::IsBoxingB2S(in_sbp_parallel, out_sbp_parallel)) {
BuildSubTaskGphB2S(in_parallel_desc, out_parallel_desc, in_sbp_parallel, out_sbp_parallel,
logical_blob_desc, sorted_in_tasks, sorted_out_tasks);
comment = "BuildSubTaskGphB2S";
} else {
UNIMPLEMENTED();
}
return TRY(BuildSubTskGphBuilderStatus("SliceBoxingSubTskGphBuilder", comment));
}
} // namespace oneflow
|
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <QtWidgets/qgraphicsanchorlayout.h>
#include <private/qgraphicsanchorlayout_p.h>
#include <QtWidgets/qgraphicswidget.h>
#include <QtWidgets/qgraphicsproxywidget.h>
#include <QtWidgets/qgraphicsview.h>
#include <QtWidgets/qstylefactory.h>
#include <QtWidgets/qproxystyle.h>
class tst_QGraphicsAnchorLayout : public QObject {
Q_OBJECT
public:
tst_QGraphicsAnchorLayout() : QObject() {
hasSimplification = qgetenv("QT_ANCHORLAYOUT_NO_SIMPLIFICATION").isEmpty();
}
private:
bool hasSimplification;
private slots:
void simple();
void simple_center();
void simple_semifloat();
void layoutDirection();
void diagonal();
void parallel();
void parallel2();
void snake();
void snakeOppositeDirections();
void fairDistribution();
void fairDistributionOppositeDirections();
void proportionalPreferred();
void example();
void setSpacing();
void styleDefaults();
void hardComplexS60();
void stability();
void delete_anchor();
void conflicts();
void sizePolicy();
void floatConflict();
void infiniteMaxSizes();
void simplifiableUnfeasible();
void simplificationVsOrder();
void parallelSimplificationOfCenter();
void simplificationVsRedundance();
void spacingPersistency();
void snakeParallelWithLayout();
void parallelToHalfLayout();
void globalSpacing();
void graphicsAnchorHandling();
void invalidHierarchyCheck();
};
class RectWidget : public QGraphicsWidget
{
public:
RectWidget(QGraphicsItem *parent = 0) : QGraphicsWidget(parent){}
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
painter->drawRoundRect(rect());
painter->drawLine(rect().topLeft(), rect().bottomRight());
painter->drawLine(rect().bottomLeft(), rect().topRight());
}
};
static QGraphicsWidget *createItem(const QSizeF &minimum = QSizeF(100.0, 100.0),
const QSizeF &preferred = QSize(150.0, 100.0),
const QSizeF &maximum = QSizeF(200.0, 100.0),
const QString &name = QString())
{
QGraphicsWidget *w = new RectWidget;
w->setMinimumSize(minimum);
w->setPreferredSize(preferred);
w->setMaximumSize(maximum);
w->setData(0, name);
return w;
}
static void setAnchor(QGraphicsAnchorLayout *l,
QGraphicsLayoutItem *firstItem,
Qt::AnchorPoint firstEdge,
QGraphicsLayoutItem *secondItem,
Qt::AnchorPoint secondEdge,
qreal spacing = 0)
{
QGraphicsAnchor *anchor = l->addAnchor(firstItem, firstEdge, secondItem, secondEdge);
anchor->setSpacing(spacing);
}
static bool checkReverseDirection(QGraphicsWidget *widget)
{
QGraphicsLayout *layout = widget->layout();
qreal left, top, right, bottom;
layout->getContentsMargins(&left, &top, &right, &bottom);
widget->setLayoutDirection(Qt::LeftToRight);
QApplication::processEvents();
QMap<QGraphicsLayoutItem *, QRectF> geometries;
for (int i = 0; i < layout->count(); ++i) {
QGraphicsLayoutItem *item = layout->itemAt(i);
geometries.insert(item, item->geometry());
}
widget->setLayoutDirection(Qt::RightToLeft);
QApplication::processEvents();
const QRectF layoutGeometry = layout->geometry().adjusted(+right, +top, -left, -bottom);
for (int i = 0; i < layout->count(); ++i) {
QGraphicsLayoutItem *item = layout->itemAt(i);
const QRectF rightToLeftGeometry = item->geometry();
const QRectF leftToRightGeometry = geometries.value(item);
QRectF expectedGeometry = leftToRightGeometry;
expectedGeometry.moveRight(layoutGeometry.right() - leftToRightGeometry.left());
if (expectedGeometry != rightToLeftGeometry) {
qDebug() << "layout->geometry():" << layoutGeometry
<< "expected:" << expectedGeometry
<< "actual:" << rightToLeftGeometry;
return false;
}
}
return true;
}
static bool layoutHasConflict(QGraphicsAnchorLayout *l)
{
return QGraphicsAnchorLayoutPrivate::get(l)->hasConflicts();
}
static bool usedSimplex(QGraphicsAnchorLayout *l, Qt::Orientation o)
{
QGraphicsAnchorLayoutPrivate::Orientation oo = (o == Qt::Horizontal) ?
QGraphicsAnchorLayoutPrivate::Horizontal :
QGraphicsAnchorLayoutPrivate::Vertical;
return QGraphicsAnchorLayoutPrivate::get(l)->lastCalculationUsedSimplex[oo];
}
void tst_QGraphicsAnchorLayout::simple()
{
QGraphicsWidget *w1 = createItem();
QGraphicsWidget *w2 = createItem();
QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout;
l->setContentsMargins(0, 0, 0, 0);
// Horizontal
l->addAnchor(l, Qt::AnchorLeft, w1, Qt::AnchorLeft);
l->addAnchor(w1, Qt::AnchorRight, w2, Qt::AnchorLeft);
l->addAnchor(w2, Qt::AnchorRight, l, Qt::AnchorRight);
// Vertical
l->addAnchors(l, w1, Qt::Vertical);
l->addAnchors(l, w2, Qt::Vertical);
QCOMPARE(l->count(), 2);
QGraphicsWidget p;
p.setLayout(l);
p.adjustSize();
if (hasSimplification) {
QVERIFY(!usedSimplex(l, Qt::Horizontal));
QVERIFY(!usedSimplex(l, Qt::Vertical));
}
}
void tst_QGraphicsAnchorLayout::simple_center()
{
QSizeF minSize(10, 10);
QSizeF pref(50, 10);
QSizeF maxSize(100, 10);
QGraphicsWidget *a = createItem(minSize, pref, maxSize, "a");
QGraphicsWidget *b = createItem(minSize, pref, maxSize, "b");
QGraphicsWidget *c = createItem(minSize, pref, maxSize, "c");
QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout;
l->setContentsMargins(0, 0, 0, 0);
// horizontal
setAnchor(l, l, Qt::AnchorLeft, a, Qt::AnchorLeft, 0);
setAnchor(l, a, Qt::AnchorRight, b, Qt::AnchorLeft, 0);
setAnchor(l, b, Qt::AnchorRight, l, Qt::AnchorRight, 0);
setAnchor(l, a, Qt::AnchorHorizontalCenter, c, Qt::AnchorLeft, 0);
setAnchor(l, c, Qt::AnchorRight, b, Qt::AnchorHorizontalCenter, 0);
// vertical
setAnchor(l, l, Qt::AnchorTop, a, Qt::AnchorTop, 0);
setAnchor(l, l, Qt::AnchorTop, b, Qt::AnchorTop, 0);
setAnchor(l, a, Qt::AnchorBottom, c, Qt::AnchorTop, 0);
setAnchor(l, b, Qt::AnchorBottom, c, Qt::AnchorTop, 0);
setAnchor(l, c, Qt::AnchorBottom, l, Qt::AnchorBottom, 0);
QCOMPARE(l->count(), 3);
QGraphicsWidget *p = new QGraphicsWidget(0, Qt::Window);
p->setLayout(l);
QSizeF layoutMinimumSize = l->effectiveSizeHint(Qt::MinimumSize);
QCOMPARE(layoutMinimumSize, QSizeF(20, 20));
QSizeF layoutMaximumSize = l->effectiveSizeHint(Qt::MaximumSize);
QCOMPARE(layoutMaximumSize, QSizeF(200, 20));
if (hasSimplification) {
QVERIFY(usedSimplex(l, Qt::Horizontal));
QVERIFY(!usedSimplex(l, Qt::Vertical));
}
delete p;
}
void tst_QGraphicsAnchorLayout::simple_semifloat()
{
// Useful for testing simplification between A_left and B_left.
// Unfortunately the only way to really test that now is to manually inspect the
// simplified graph.
QSizeF minSize(10, 10);
QSizeF pref(50, 10);
QSizeF maxSize(100, 10);
QGraphicsWidget *A = createItem(minSize, pref, maxSize, "A");
QGraphicsWidget *B = createItem(minSize, pref, maxSize, "B");
QGraphicsWidget *a = createItem(minSize, pref, maxSize, "a");
QGraphicsWidget *b = createItem(minSize, pref, maxSize, "b");
QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout;
l->setContentsMargins(0, 0, 0, 0);
// horizontal
setAnchor(l, l, Qt::AnchorLeft, A, Qt::AnchorLeft, 0);
setAnchor(l, A, Qt::AnchorRight, B, Qt::AnchorLeft, 0);
setAnchor(l, B, Qt::AnchorRight, l, Qt::AnchorRight, 0);
setAnchor(l, A, Qt::AnchorLeft, a, Qt::AnchorLeft, 0);
setAnchor(l, B, Qt::AnchorLeft, b, Qt::AnchorLeft, 0);
// vertical
setAnchor(l, l, Qt::AnchorTop, A, Qt::AnchorTop, 0);
setAnchor(l, l, Qt::AnchorTop, B, Qt::AnchorTop, 0);
setAnchor(l, A, Qt::AnchorBottom, a, Qt::AnchorTop, 0);
setAnchor(l, B, Qt::AnchorBottom, b, Qt::AnchorTop, 0);
setAnchor(l, a, Qt::AnchorBottom, l, Qt::AnchorBottom, 0);
setAnchor(l, b, Qt::AnchorBottom, l, Qt::AnchorBottom, 0);
QCOMPARE(l->count(), 4);
QGraphicsWidget *p = new QGraphicsWidget(0, Qt::Window);
p->setLayout(l);
QSizeF layoutMinimumSize = l->effectiveSizeHint(Qt::MinimumSize);
QCOMPARE(layoutMinimumSize, QSizeF(20, 20));
QCOMPARE(l->effectiveSizeHint(Qt::PreferredSize), QSizeF(100, 20));
QSizeF layoutMaximumSize = l->effectiveSizeHint(Qt::MaximumSize);
QCOMPARE(layoutMaximumSize, QSizeF(200, 20));
delete p;
}
void tst_QGraphicsAnchorLayout::layoutDirection()
{
QSizeF minSize(10, 10);
QSizeF pref(50, 10);
QSizeF maxSize(100, 10);
QGraphicsWidget *a = createItem(minSize, pref, maxSize, "a");
QGraphicsWidget *b = createItem(minSize, pref, maxSize, "b");
QGraphicsWidget *c = createItem(minSize, pref, QSizeF(100, 20), "c");
a->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
b->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
c->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout;
l->setContentsMargins(0, 5, 10, 15);
// horizontal
setAnchor(l, l, Qt::AnchorLeft, a, Qt::AnchorLeft, 0);
setAnchor(l, a, Qt::AnchorRight, b, Qt::AnchorLeft, 0);
setAnchor(l, b, Qt::AnchorRight, l, Qt::AnchorRight, 0);
setAnchor(l, a, Qt::AnchorHorizontalCenter, c, Qt::AnchorLeft, 0);
setAnchor(l, c, Qt::AnchorRight, b, Qt::AnchorHorizontalCenter, 0);
// vertical
setAnchor(l, l, Qt::AnchorTop, a, Qt::AnchorTop, 0);
setAnchor(l, l, Qt::AnchorTop, b, Qt::AnchorTop, 0);
setAnchor(l, a, Qt::AnchorBottom, c, Qt::AnchorTop, 0);
setAnchor(l, b, Qt::AnchorBottom, c, Qt::AnchorTop, 0);
setAnchor(l, c, Qt::AnchorBottom, l, Qt::AnchorBottom, 0);
QCOMPARE(l->count(), 3);
QGraphicsWidget *p = new QGraphicsWidget(0, Qt::Window);
p->setLayoutDirection(Qt::LeftToRight);
p->setLayout(l);
QGraphicsScene scene;
QGraphicsView *view = new QGraphicsView(&scene);
scene.addItem(p);
p->show();
view->show();
QVERIFY(p->layout());
QCOMPARE(checkReverseDirection(p), true);
if (hasSimplification) {
QVERIFY(usedSimplex(l, Qt::Horizontal));
QVERIFY(!usedSimplex(l, Qt::Vertical));
}
delete p;
delete view;
}
void tst_QGraphicsAnchorLayout::diagonal()
{
QSizeF minSize(10, 100);
QSizeF pref(70, 100);
QSizeF maxSize(100, 100);
QGraphicsWidget *a = createItem(minSize, pref, maxSize, "A");
QGraphicsWidget *b = createItem(minSize, pref, maxSize, "B");
QGraphicsWidget *c = createItem(minSize, pref, maxSize, "C");
QGraphicsWidget *d = createItem(minSize, pref, maxSize, "D");
QGraphicsWidget *e = createItem(minSize, pref, maxSize, "E");
QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout;
l->setContentsMargins(0, 0, 0, 0);
l->setSpacing(0);
// vertical
l->addAnchor(a, Qt::AnchorTop, l, Qt::AnchorTop);
l->addAnchor(b, Qt::AnchorTop, l, Qt::AnchorTop);
l->addAnchor(c, Qt::AnchorTop, a, Qt::AnchorBottom);
l->addAnchor(c, Qt::AnchorTop, b, Qt::AnchorBottom);
l->addAnchor(c, Qt::AnchorBottom, d, Qt::AnchorTop);
l->addAnchor(c, Qt::AnchorBottom, e, Qt::AnchorTop);
l->addAnchor(d, Qt::AnchorBottom, l, Qt::AnchorBottom);
l->addAnchor(e, Qt::AnchorBottom, l, Qt::AnchorBottom);
// horizontal
l->addAnchor(l, Qt::AnchorLeft, a, Qt::AnchorLeft);
l->addAnchor(l, Qt::AnchorLeft, d, Qt::AnchorLeft);
l->addAnchor(a, Qt::AnchorRight, b, Qt::AnchorLeft);
l->addAnchor(a, Qt::AnchorRight, c, Qt::AnchorLeft);
l->addAnchor(c, Qt::AnchorRight, e, Qt::AnchorLeft);
l->addAnchor(b, Qt::AnchorRight, l, Qt::AnchorRight);
l->addAnchor(e, Qt::AnchorRight, l, Qt::AnchorRight);
l->addAnchor(d, Qt::AnchorRight, e, Qt::AnchorLeft);
QCOMPARE(l->count(), 5);
QGraphicsWidget p;
p.setLayout(l);
QSizeF layoutMinimumSize = l->effectiveSizeHint(Qt::MinimumSize);
QSizeF layoutMaximumSize = l->effectiveSizeHint(Qt::MaximumSize);
QSizeF layoutPreferredSize = l->effectiveSizeHint(Qt::PreferredSize);
QCOMPARE(layoutMinimumSize, QSizeF(30.0, 300.0));
QCOMPARE(layoutPreferredSize, QSizeF(170.0, 300.0));
QCOMPARE(layoutMaximumSize, QSizeF(190.0, 300.0));
p.resize(layoutMinimumSize);
QCOMPARE(a->geometry(), QRectF(0.0, 0.0, 10.0, 100.0));
QCOMPARE(b->geometry(), QRectF(10.0, 0.0, 20.0, 100.0));
QCOMPARE(c->geometry(), QRectF(10.0, 100.0, 10.0, 100.0));
QCOMPARE(d->geometry(), QRectF(0.0, 200.0, 20.0, 100.0));
QCOMPARE(e->geometry(), QRectF(20.0, 200.0, 10.0, 100.0));
QCOMPARE(p.size(), layoutMinimumSize);
p.resize(layoutPreferredSize);
QCOMPARE(a->geometry(), QRectF(0.0, 0.0, 70.0, 100.0));
QCOMPARE(b->geometry(), QRectF(70.0, 0.0, 100.0, 100.0));
QCOMPARE(c->geometry(), QRectF(70.0, 100.0, 30.0, 100.0));
QCOMPARE(d->geometry(), QRectF(0.0, 200.0, 100.0, 100.0));
QCOMPARE(e->geometry(), QRectF(100.0, 200.0, 70.0, 100.0));
QCOMPARE(p.size(), layoutPreferredSize);
p.resize(layoutMaximumSize);
QCOMPARE(a->geometry(), QRectF(0.0, 0.0, 90.0, 100.0));
QCOMPARE(b->geometry(), QRectF(90.0, 0.0, 100.0, 100.0));
QCOMPARE(c->geometry(), QRectF(90.0, 100.0, 10.0, 100.0));
QCOMPARE(d->geometry(), QRectF(0.0, 200.0, 100.0, 100.0));
QCOMPARE(e->geometry(), QRectF(100.0, 200.0, 90.0, 100.0));
QCOMPARE(p.size(), layoutMaximumSize);
QSizeF testA(175.0, 300.0);
p.resize(testA);
QCOMPARE(a->geometry(), QRectF(0.0, 0.0, 75.0, 100.0));
QCOMPARE(b->geometry(), QRectF(75.0, 0.0, 100.0, 100.0));
QCOMPARE(c->geometry(), QRectF(75.0, 100.0, 25.0, 100.0));
QCOMPARE(d->geometry(), QRectF(0.0, 200.0, 100.0, 100.0));
QCOMPARE(e->geometry(), QRectF(100.0, 200.0, 75.0, 100.0));
QCOMPARE(p.size(), testA);
if (hasSimplification) {
QVERIFY(usedSimplex(l, Qt::Horizontal));
QVERIFY(!usedSimplex(l, Qt::Vertical));
}
QVERIFY(p.layout());
QCOMPARE(checkReverseDirection(&p), true);
c->setMinimumWidth(300);
QVERIFY(layoutHasConflict(l));
}
void tst_QGraphicsAnchorLayout::parallel()
{
QGraphicsWidget *a = createItem(QSizeF(100, 100),
QSizeF(150, 100),
QSizeF(200, 100), "A");
QGraphicsWidget *b = createItem(QSizeF(100, 100),
QSizeF(150, 100),
QSizeF(300, 100), "B");
QGraphicsWidget *c = createItem(QSizeF(100, 100),
QSizeF(200, 100),
QSizeF(350, 100), "C");
QGraphicsWidget *d = createItem(QSizeF(100, 100),
QSizeF(170, 100),
QSizeF(200, 100), "D");
QGraphicsWidget *e = createItem(QSizeF(150, 100),
QSizeF(150, 100),
QSizeF(200, 100), "E");
QGraphicsWidget *f = createItem(QSizeF(100, 100),
QSizeF(150, 100),
QSizeF(200, 100), "F");
QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout;
l->setContentsMargins(0, 0, 0, 0);
l->setSpacing(0);
l->addAnchor(l, Qt::AnchorTop, a, Qt::AnchorTop);
l->addAnchor(a, Qt::AnchorBottom, b, Qt::AnchorTop);
l->addAnchor(b, Qt::AnchorBottom, c, Qt::AnchorTop);
l->addAnchor(c, Qt::AnchorBottom, d, Qt::AnchorTop);
l->addAnchor(d, Qt::AnchorBottom, e, Qt::AnchorTop);
l->addAnchor(e, Qt::AnchorBottom, f, Qt::AnchorTop);
l->addAnchor(f, Qt::AnchorBottom, l, Qt::AnchorBottom);
l->addAnchor(l, Qt::AnchorLeft, a, Qt::AnchorLeft);
l->addAnchor(a, Qt::AnchorRight, b, Qt::AnchorLeft);
l->addAnchor(a, Qt::AnchorRight, c, Qt::AnchorLeft);
l->addAnchor(b, Qt::AnchorRight, d, Qt::AnchorLeft);
l->addAnchor(b, Qt::AnchorRight, e, Qt::AnchorLeft);
l->addAnchor(c, Qt::AnchorRight, f, Qt::AnchorLeft);
l->addAnchor(d, Qt::AnchorRight, f, Qt::AnchorLeft);
l->addAnchor(e, Qt::AnchorRight, f, Qt::AnchorLeft);
l->addAnchor(f, Qt::AnchorRight, l, Qt::AnchorRight);
QCOMPARE(l->count(), 6);
QGraphicsWidget p;
p.setLayout(l);
QSizeF layoutMinimumSize = l->effectiveSizeHint(Qt::MinimumSize);
QSizeF layoutPreferredSize = l->effectiveSizeHint(Qt::PreferredSize);
QSizeF layoutMaximumSize = l->effectiveSizeHint(Qt::MaximumSize);
QCOMPARE(layoutMinimumSize, QSizeF(450, 600));
QCOMPARE(layoutPreferredSize, QSizeF(620, 600));
QCOMPARE(layoutMaximumSize, QSizeF(750, 600));
p.resize(layoutMinimumSize);
QCOMPARE(a->geometry(), QRectF(0, 0, 100, 100));
QCOMPARE(b->geometry(), QRectF(100, 100, 100, 100));
QCOMPARE(c->geometry(), QRectF(100, 200, 250, 100));
QCOMPARE(d->geometry(), QRectF(200, 300, 150, 100));
QCOMPARE(e->geometry(), QRectF(200, 400, 150, 100));
QCOMPARE(f->geometry(), QRectF(350, 500, 100, 100));
QCOMPARE(p.size(), layoutMinimumSize);
if (!hasSimplification)
return;
p.resize(layoutPreferredSize);
QCOMPARE(a->geometry(), QRectF(0, 0, 150, 100));
QCOMPARE(b->geometry(), QRectF(150, 100, 150, 100));
QCOMPARE(c->geometry(), QRectF(150, 200, 320, 100));
QCOMPARE(d->geometry(), QRectF(300, 300, 170, 100));
QCOMPARE(e->geometry(), QRectF(300, 400, 170, 100));
QCOMPARE(f->geometry(), QRectF(470, 500, 150, 100));
QCOMPARE(p.size(), layoutPreferredSize);
// Maximum size depends on simplification / fair distribution
// Without that, test may or may not pass, depending on the
// solution found by the solver at runtime.
p.resize(layoutMaximumSize);
QCOMPARE(a->geometry(), QRectF(0, 0, 200, 100));
QCOMPARE(b->geometry(), QRectF(200, 100, 175, 100));
QCOMPARE(c->geometry(), QRectF(200, 200, 350, 100));
QCOMPARE(d->geometry(), QRectF(375, 300, 175, 100));
QCOMPARE(e->geometry(), QRectF(375, 400, 175, 100));
QCOMPARE(f->geometry(), QRectF(550, 500, 200, 100));
QCOMPARE(p.size(), layoutMaximumSize);
QVERIFY(!usedSimplex(l, Qt::Horizontal));
QVERIFY(!usedSimplex(l, Qt::Vertical));
}
void tst_QGraphicsAnchorLayout::parallel2()
{
QGraphicsWidget *a = createItem(QSizeF(70.0, 100.0),
QSizeF(100.0, 100.0),
QSizeF(200.0, 100.0), "A");
QGraphicsWidget *b = createItem(QSizeF(100.0, 100.0),
QSizeF(150.0, 100.0),
QSizeF(190.0, 100.0), "B");
QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout;
l->setContentsMargins(0, 0, 0, 0);
l->setSpacing(0);
l->addAnchor(l, Qt::AnchorTop, a, Qt::AnchorTop);
l->addAnchor(a, Qt::AnchorBottom, b, Qt::AnchorTop);
l->addAnchor(b, Qt::AnchorBottom, l, Qt::AnchorBottom);
l->addAnchors(l, a, Qt::Horizontal);
l->addAnchor(l, Qt::AnchorLeft, b, Qt::AnchorLeft);
l->addAnchor(b, Qt::AnchorRight, a, Qt::AnchorRight);
QCOMPARE(l->count(), 2);
QGraphicsWidget p;
p.setLayout(l);
QSizeF layoutMinimumSize = l->effectiveSizeHint(Qt::MinimumSize);
QSizeF layoutPreferredSize = l->effectiveSizeHint(Qt::PreferredSize);
QSizeF layoutMaximumSize = l->effectiveSizeHint(Qt::MaximumSize);
QCOMPARE(layoutMinimumSize, QSizeF(100.0, 200.0));
QCOMPARE(layoutPreferredSize, QSizeF(150.0, 200.0));
QCOMPARE(layoutMaximumSize, QSizeF(190.0, 200.0));
p.resize(layoutMinimumSize);
QCOMPARE(p.size(), layoutMinimumSize);
p.resize(layoutPreferredSize);
QCOMPARE(p.size(), layoutPreferredSize);
p.resize(layoutMaximumSize);
QCOMPARE(p.size(), layoutMaximumSize);
if (hasSimplification) {
QVERIFY(!usedSimplex(l, Qt::Horizontal));
QVERIFY(!usedSimplex(l, Qt::Vertical));
}
}
void tst_QGraphicsAnchorLayout::snake()
{
QGraphicsWidget *a = createItem(QSizeF(50.0, 100.0),
QSizeF(70.0, 100.0),
QSizeF(100.0, 100.0), "A");
QGraphicsWidget *b = createItem(QSizeF(10.0, 100.0),
QSizeF(20.0, 100.0),
QSizeF(40.0, 100.0), "B");
QGraphicsWidget *c = createItem(QSizeF(50.0, 100.0),
QSizeF(70.0, 100.0),
QSizeF(100.0, 100.0), "C");
QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout;
l->setContentsMargins(0, 0, 0, 0);
l->setSpacing(0);
l->addAnchor(l, Qt::AnchorTop, a, Qt::AnchorTop);
l->addAnchor(a, Qt::AnchorBottom, b, Qt::AnchorTop);
l->addAnchor(b, Qt::AnchorBottom, c, Qt::AnchorTop);
l->addAnchor(c, Qt::AnchorBottom, l, Qt::AnchorBottom);
l->addAnchor(l, Qt::AnchorLeft, a, Qt::AnchorLeft);
l->addAnchor(a, Qt::AnchorRight, b, Qt::AnchorRight);
l->addAnchor(b, Qt::AnchorLeft, c, Qt::AnchorLeft);
l->addAnchor(c, Qt::AnchorRight, l, Qt::AnchorRight);
QCOMPARE(l->count(), 3);
QGraphicsWidget p;
p.setLayout(l);
QSizeF layoutMinimumSize = l->effectiveSizeHint(Qt::MinimumSize);
QSizeF layoutMaximumSize = l->effectiveSizeHint(Qt::MaximumSize);
QSizeF layoutPreferredSize = l->effectiveSizeHint(Qt::PreferredSize);
QCOMPARE(layoutMinimumSize, QSizeF(60.0, 300.0));
QCOMPARE(layoutPreferredSize, QSizeF(120.0, 300.0));
QCOMPARE(layoutMaximumSize, QSizeF(190.0, 300.0));
p.resize(layoutMinimumSize);
QCOMPARE(a->geometry(), QRectF(0.0, 0.0, 50.0, 100.0));
QCOMPARE(b->geometry(), QRectF(10.0, 100.0, 40.0, 100.0));
QCOMPARE(c->geometry(), QRectF(10.0, 200.0, 50.0, 100.0));
QCOMPARE(p.size(), layoutMinimumSize);
p.resize(layoutPreferredSize);
QCOMPARE(a->geometry(), QRectF(0.0, 0.0, 70.0, 100.0));
QCOMPARE(b->geometry(), QRectF(50.0, 100.0, 20.0, 100.0));
QCOMPARE(c->geometry(), QRectF(50.0, 200.0, 70.0, 100.0));
QCOMPARE(p.size(), layoutPreferredSize);
p.resize(layoutMaximumSize);
QCOMPARE(a->geometry(), QRectF(0.0, 0.0, 100.0, 100.0));
QCOMPARE(b->geometry(), QRectF(90.0, 100.0, 10.0, 100.0));
QCOMPARE(c->geometry(), QRectF(90.0, 200.0, 100.0, 100.0));
QCOMPARE(p.size(), layoutMaximumSize);
QVERIFY(!layoutHasConflict(l));
// Test QSizePolicy::ExpandFlag, it shouldn't change the extreme
// points of the layout...
b->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
QSizeF newLayoutMinimumSize = l->effectiveSizeHint(Qt::MinimumSize);
QSizeF newLayoutMaximumSize = l->effectiveSizeHint(Qt::MaximumSize);
QSizeF newLayoutPreferredSize = l->effectiveSizeHint(Qt::PreferredSize);
QCOMPARE(layoutMinimumSize, newLayoutMinimumSize);
QCOMPARE(layoutMaximumSize, newLayoutMaximumSize);
QCOMPARE(layoutPreferredSize, newLayoutPreferredSize);
}
void tst_QGraphicsAnchorLayout::snakeOppositeDirections()
{
QGraphicsWidget *a = createItem(QSizeF(50.0, 100.0),
QSizeF(70.0, 100.0),
QSizeF(100.0, 100.0), "A");
QGraphicsWidget *b = createItem(QSizeF(10.0, 100.0),
QSizeF(20.0, 100.0),
QSizeF(40.0, 100.0), "B");
QGraphicsWidget *c = createItem(QSizeF(50.0, 100.0),
QSizeF(70.0, 100.0),
QSizeF(100.0, 100.0), "C");
QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout;
l->setContentsMargins(0, 0, 0, 0);
l->setSpacing(0);
l->addAnchor(l, Qt::AnchorTop, a, Qt::AnchorTop);
l->addAnchor(a, Qt::AnchorBottom, b, Qt::AnchorTop);
l->addAnchor(b, Qt::AnchorBottom, c, Qt::AnchorTop);
l->addAnchor(c, Qt::AnchorBottom, l, Qt::AnchorBottom);
l->addAnchor(l, Qt::AnchorLeft, a, Qt::AnchorLeft);
// Both a and c are 'pointing' to b
l->addAnchor(a, Qt::AnchorRight, b, Qt::AnchorRight);
l->addAnchor(c, Qt::AnchorLeft, b, Qt::AnchorLeft);
l->addAnchor(c, Qt::AnchorRight, l, Qt::AnchorRight);
QCOMPARE(l->count(), 3);
QGraphicsWidget p;
p.setLayout(l);
QSizeF layoutMinimumSize = l->effectiveSizeHint(Qt::MinimumSize);
QSizeF layoutMaximumSize = l->effectiveSizeHint(Qt::MaximumSize);
QSizeF layoutPreferredSize = l->effectiveSizeHint(Qt::PreferredSize);
QCOMPARE(layoutMinimumSize, QSizeF(60.0, 300.0));
QCOMPARE(layoutPreferredSize, QSizeF(120.0, 300.0));
QCOMPARE(layoutMaximumSize, QSizeF(190.0, 300.0));
p.resize(layoutMinimumSize);
QCOMPARE(a->geometry(), QRectF(0.0, 0.0, 50.0, 100.0));
QCOMPARE(b->geometry(), QRectF(10.0, 100.0, 40.0, 100.0));
QCOMPARE(c->geometry(), QRectF(10.0, 200.0, 50.0, 100.0));
QCOMPARE(p.size(), layoutMinimumSize);
p.resize(layoutPreferredSize);
QCOMPARE(a->geometry(), QRectF(0.0, 0.0, 70.0, 100.0));
QCOMPARE(b->geometry(), QRectF(50.0, 100.0, 20.0, 100.0));
QCOMPARE(c->geometry(), QRectF(50.0, 200.0, 70.0, 100.0));
QCOMPARE(p.size(), layoutPreferredSize);
p.resize(layoutMaximumSize);
QCOMPARE(a->geometry(), QRectF(0.0, 0.0, 100.0, 100.0));
QCOMPARE(b->geometry(), QRectF(90.0, 100.0, 10.0, 100.0));
QCOMPARE(c->geometry(), QRectF(90.0, 200.0, 100.0, 100.0));
QCOMPARE(p.size(), layoutMaximumSize);
QVERIFY(p.layout());
QCOMPARE(checkReverseDirection(&p), true);
}
void tst_QGraphicsAnchorLayout::fairDistribution()
{
QGraphicsWidget *a = createItem(QSizeF(10.0, 100.0),
QSizeF(50.0, 100.0),
QSizeF(100.0, 100.0), "A");
QGraphicsWidget *b = createItem(QSizeF(10.0, 100.0),
QSizeF(50.0, 100.0),
QSizeF(100.0, 100.0), "B");
QGraphicsWidget *c = createItem(QSizeF(10.0, 100.0),
QSizeF(50.0, 100.0),
QSizeF(100.0, 100.0), "C");
QGraphicsWidget *d = createItem(QSizeF(60.0, 100.0),
QSizeF(165.0, 100.0),
QSizeF(600.0, 100.0), "D");
QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout;
l->setContentsMargins(0, 0, 0, 0);
l->setSpacing(0);
l->addAnchor(l, Qt::AnchorTop, a, Qt::AnchorTop);
l->addAnchor(a, Qt::AnchorBottom, b, Qt::AnchorTop);
l->addAnchor(b, Qt::AnchorBottom, c, Qt::AnchorTop);
l->addAnchor(c, Qt::AnchorBottom, d, Qt::AnchorTop);
l->addAnchor(d, Qt::AnchorBottom, l, Qt::AnchorBottom);
l->addAnchor(l, Qt::AnchorLeft, a, Qt::AnchorLeft);
l->addAnchor(a, Qt::AnchorRight, b, Qt::AnchorLeft);
l->addAnchor(b, Qt::AnchorRight, c, Qt::AnchorLeft);
l->addAnchor(c, Qt::AnchorRight, l, Qt::AnchorRight);
l->addAnchor(l, Qt::AnchorLeft, d, Qt::AnchorLeft);
l->addAnchor(d, Qt::AnchorRight, l, Qt::AnchorRight);
QCOMPARE(l->count(), 4);
QGraphicsWidget p;
p.setLayout(l);
QSizeF layoutMinimumSize = l->effectiveSizeHint(Qt::MinimumSize);
QSizeF layoutMaximumSize = l->effectiveSizeHint(Qt::MaximumSize);
QSizeF layoutPreferredSize = l->effectiveSizeHint(Qt::PreferredSize);
QCOMPARE(layoutMinimumSize, QSizeF(60.0, 400.0));
QCOMPARE(layoutPreferredSize, QSizeF(165.0, 400.0));
QCOMPARE(layoutMaximumSize, QSizeF(300.0, 400.0));
p.resize(layoutMinimumSize);
if (!hasSimplification)
QEXPECT_FAIL("", "Without simplification there is no fair distribution.", Abort);
QCOMPARE(a->geometry(), QRectF(0.0, 0.0, 20.0, 100.0));
QCOMPARE(b->geometry(), QRectF(20.0, 100.0, 20.0, 100.0));
QCOMPARE(c->geometry(), QRectF(40.0, 200.0, 20.0, 100.0));
QCOMPARE(d->geometry(), QRectF(0.0, 300.0, 60.0, 100.0));
QCOMPARE(p.size(), layoutMinimumSize);
p.resize(layoutPreferredSize);
QCOMPARE(a->geometry(), QRectF(0.0, 0.0, 55.0, 100.0));
QCOMPARE(b->geometry(), QRectF(55.0, 100.0, 55.0, 100.0));
QCOMPARE(c->geometry(), QRectF(110.0, 200.0, 55.0, 100.0));
QCOMPARE(d->geometry(), QRectF(0.0, 300.0, 165.0, 100.0));
QCOMPARE(p.size(), layoutPreferredSize);
p.resize(layoutMaximumSize);
QCOMPARE(a->geometry(), QRectF(0.0, 0.0, 100.0, 100.0));
QCOMPARE(b->geometry(), QRectF(100.0, 100.0, 100.0, 100.0));
QCOMPARE(c->geometry(), QRectF(200.0, 200.0, 100.0, 100.0));
QCOMPARE(d->geometry(), QRectF(0.0, 300.0, 300.0, 100.0));
QCOMPARE(p.size(), layoutMaximumSize);
if (hasSimplification) {
QVERIFY(!usedSimplex(l, Qt::Horizontal));
QVERIFY(!usedSimplex(l, Qt::Vertical));
}
}
void tst_QGraphicsAnchorLayout::fairDistributionOppositeDirections()
{
QGraphicsWidget *a = createItem(QSizeF(10.0, 100.0),
QSizeF(50.0, 100.0),
QSizeF(100.0, 100.0), "A");
QGraphicsWidget *b = createItem(QSizeF(10.0, 100.0),
QSizeF(50.0, 100.0),
QSizeF(100.0, 100.0), "B");
QGraphicsWidget *c = createItem(QSizeF(10.0, 100.0),
QSizeF(50.0, 100.0),
QSizeF(100.0, 100.0), "C");
QGraphicsWidget *d = createItem(QSizeF(10.0, 100.0),
QSizeF(50.0, 100.0),
QSizeF(100.0, 100.0), "D");
QGraphicsWidget *e = createItem(QSizeF(60.0, 100.0),
QSizeF(220.0, 100.0),
QSizeF(600.0, 100.0), "E");
QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout;
l->setContentsMargins(0, 0, 0, 0);
l->setSpacing(0);
l->addAnchor(l, Qt::AnchorTop, a, Qt::AnchorTop);
l->addAnchor(a, Qt::AnchorBottom, b, Qt::AnchorTop);
l->addAnchor(b, Qt::AnchorBottom, c, Qt::AnchorTop);
l->addAnchor(c, Qt::AnchorBottom, d, Qt::AnchorTop);
l->addAnchor(d, Qt::AnchorBottom, e, Qt::AnchorTop);
l->addAnchor(e, Qt::AnchorBottom, l, Qt::AnchorBottom);
l->addAnchor(a, Qt::AnchorLeft, l, Qt::AnchorLeft);
l->addAnchor(b, Qt::AnchorLeft, a, Qt::AnchorRight);
l->addAnchor(c, Qt::AnchorLeft, b, Qt::AnchorRight);
l->addAnchor(d, Qt::AnchorLeft, c, Qt::AnchorRight);
l->addAnchor(d, Qt::AnchorRight, l, Qt::AnchorRight);
l->addAnchors(l, e, Qt::Horizontal);
QCOMPARE(l->count(), 5);
QGraphicsWidget p;
p.setLayout(l);
QSizeF layoutMinimumSize = l->effectiveSizeHint(Qt::MinimumSize);
QSizeF layoutMaximumSize = l->effectiveSizeHint(Qt::MaximumSize);
QSizeF layoutPreferredSize = l->effectiveSizeHint(Qt::PreferredSize);
QCOMPARE(layoutMinimumSize, QSizeF(60.0, 500.0));
QCOMPARE(layoutPreferredSize, QSizeF(220.0, 500.0));
QCOMPARE(layoutMaximumSize, QSizeF(400.0, 500.0));
if (!hasSimplification)
return;
p.resize(layoutMinimumSize);
QCOMPARE(a->size(), b->size());
QCOMPARE(a->size(), c->size());
QCOMPARE(a->size(), d->size());
QCOMPARE(e->size().width(), 4 * a->size().width());
QCOMPARE(p.size(), layoutMinimumSize);
p.resize(layoutPreferredSize);
QCOMPARE(a->size(), b->size());
QCOMPARE(a->size(), c->size());
QCOMPARE(a->size(), d->size());
QCOMPARE(e->size().width(), 4 * a->size().width());
QCOMPARE(p.size(), layoutPreferredSize);
p.resize(layoutMaximumSize);
QCOMPARE(a->size(), b->size());
QCOMPARE(a->size(), c->size());
QCOMPARE(a->size(), d->size());
QCOMPARE(e->size().width(), 4 * a->size().width());
QCOMPARE(p.size(), layoutMaximumSize);
QVERIFY(!usedSimplex(l, Qt::Horizontal));
QVERIFY(!usedSimplex(l, Qt::Vertical));
}
void tst_QGraphicsAnchorLayout::proportionalPreferred()
{
QSizeF minSize(0, 100);
QGraphicsWidget *a = createItem(minSize, QSizeF(10, 100), QSizeF(20, 100), "A");
QGraphicsWidget *b = createItem(minSize, QSizeF(20, 100), QSizeF(30, 100), "B");
QGraphicsWidget *c = createItem(minSize, QSizeF(14, 100), QSizeF(20, 100), "C");
QGraphicsWidget *d = createItem(minSize, QSizeF(10, 100), QSizeF(20, 100), "D");
QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout;
l->setContentsMargins(0, 0, 0, 0);
l->setSpacing(0);
l->addAnchor(l, Qt::AnchorTop, a, Qt::AnchorTop);
l->addAnchor(a, Qt::AnchorBottom, b, Qt::AnchorTop);
l->addAnchor(b, Qt::AnchorBottom, c, Qt::AnchorTop);
l->addAnchor(c, Qt::AnchorBottom, d, Qt::AnchorTop);
l->addAnchor(d, Qt::AnchorBottom, l, Qt::AnchorBottom);
l->addAnchor(l, Qt::AnchorLeft, a, Qt::AnchorLeft);
l->addAnchor(l, Qt::AnchorLeft, b, Qt::AnchorLeft);
l->addAnchor(a, Qt::AnchorRight, c, Qt::AnchorLeft);
l->addAnchor(a, Qt::AnchorRight, d, Qt::AnchorLeft);
l->addAnchor(b, Qt::AnchorRight, l, Qt::AnchorRight);
l->addAnchor(c, Qt::AnchorRight, l, Qt::AnchorRight);
l->addAnchor(d, Qt::AnchorRight, l, Qt::AnchorRight);
QCOMPARE(l->count(), 4);
QGraphicsWidget p;
p.setLayout(l);
QSizeF layoutMinimumSize = l->effectiveSizeHint(Qt::MinimumSize);
QSizeF layoutPreferredSize = l->effectiveSizeHint(Qt::PreferredSize);
QSizeF layoutMaximumSize = l->effectiveSizeHint(Qt::MaximumSize);
QCOMPARE(layoutMinimumSize, QSizeF(0, 400));
QCOMPARE(layoutPreferredSize, QSizeF(24, 400));
QCOMPARE(layoutMaximumSize, QSizeF(30, 400));
p.resize(layoutMinimumSize);
QCOMPARE(p.size(), layoutMinimumSize);
p.resize(layoutPreferredSize);
QCOMPARE(c->size().width(), d->size().width());
QCOMPARE(p.size(), layoutPreferredSize);
p.resize(layoutMaximumSize);
QCOMPARE(p.size(), layoutMaximumSize);
p.resize(QSizeF(12, 400));
// Proportionality between size given and preferred size, this
// should be respected in this graph for (a) and (b)|(c).
qreal factor = 12.0 / 24.0;
QCOMPARE(c->size().width(), d->size().width());
QCOMPARE(a->size().width(), 10 * factor);
QCOMPARE(c->size().width(), 14 * factor);
QCOMPARE(p.size(), QSizeF(12, 400));
if (hasSimplification) {
QVERIFY(!usedSimplex(l, Qt::Horizontal));
QVERIFY(!usedSimplex(l, Qt::Vertical));
}
}
void tst_QGraphicsAnchorLayout::example()
{
QSizeF minSize(30, 100);
QSizeF pref(210, 100);
QSizeF maxSize(300, 100);
QGraphicsWidget *a = createItem(minSize, pref, maxSize, "A");
QGraphicsWidget *b = createItem(minSize, pref, maxSize, "B");
QGraphicsWidget *c = createItem(minSize, pref, maxSize, "C");
QGraphicsWidget *d = createItem(minSize, pref, maxSize, "D");
QGraphicsWidget *e = createItem(minSize, pref, maxSize, "E");
QGraphicsWidget *f = createItem(QSizeF(30, 50), QSizeF(150, 50), maxSize, "F");
QGraphicsWidget *g = createItem(QSizeF(30, 50), QSizeF(30, 100), maxSize, "G");
QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout;
l->setContentsMargins(0, 0, 0, 0);
l->setSpacing(0);
// vertical
l->addAnchor(a, Qt::AnchorTop, l, Qt::AnchorTop);
l->addAnchor(b, Qt::AnchorTop, l, Qt::AnchorTop);
l->addAnchor(c, Qt::AnchorTop, a, Qt::AnchorBottom);
l->addAnchor(c, Qt::AnchorTop, b, Qt::AnchorBottom);
l->addAnchor(c, Qt::AnchorBottom, d, Qt::AnchorTop);
l->addAnchor(c, Qt::AnchorBottom, e, Qt::AnchorTop);
l->addAnchor(d, Qt::AnchorBottom, l, Qt::AnchorBottom);
l->addAnchor(e, Qt::AnchorBottom, l, Qt::AnchorBottom);
l->addAnchor(c, Qt::AnchorTop, f, Qt::AnchorTop);
l->addAnchor(c, Qt::AnchorVerticalCenter, f, Qt::AnchorBottom);
l->addAnchor(f, Qt::AnchorBottom, g, Qt::AnchorTop);
l->addAnchor(c, Qt::AnchorBottom, g, Qt::AnchorBottom);
// horizontal
l->addAnchor(l, Qt::AnchorLeft, a, Qt::AnchorLeft);
l->addAnchor(l, Qt::AnchorLeft, d, Qt::AnchorLeft);
l->addAnchor(a, Qt::AnchorRight, b, Qt::AnchorLeft);
l->addAnchor(a, Qt::AnchorRight, c, Qt::AnchorLeft);
l->addAnchor(c, Qt::AnchorRight, e, Qt::AnchorLeft);
l->addAnchor(b, Qt::AnchorRight, l, Qt::AnchorRight);
l->addAnchor(e, Qt::AnchorRight, l, Qt::AnchorRight);
l->addAnchor(d, Qt::AnchorRight, e, Qt::AnchorLeft);
l->addAnchor(l, Qt::AnchorLeft, f, Qt::AnchorLeft);
l->addAnchor(l, Qt::AnchorLeft, g, Qt::AnchorLeft);
l->addAnchor(f, Qt::AnchorRight, g, Qt::AnchorRight);
QCOMPARE(l->count(), 7);
QGraphicsWidget p;
p.setLayout(l);
QSizeF layoutMinimumSize = l->effectiveSizeHint(Qt::MinimumSize);
QSizeF layoutMaximumSize = l->effectiveSizeHint(Qt::MaximumSize);
QSizeF layoutPreferredSize = l->effectiveSizeHint(Qt::PreferredSize);
QCOMPARE(layoutMinimumSize, QSizeF(90.0, 300.0));
QCOMPARE(layoutPreferredSize, QSizeF(510.0, 300.0));
QCOMPARE(layoutMaximumSize, QSizeF(570.0, 300.0));
p.resize(layoutMinimumSize);
QCOMPARE(p.size(), layoutMinimumSize);
QCOMPARE(a->size(), e->size());
QCOMPARE(b->size(), d->size());
QCOMPARE(f->size(), g->size());
p.resize(layoutPreferredSize);
QCOMPARE(p.size(), layoutPreferredSize);
QCOMPARE(a->size(), e->size());
QCOMPARE(b->size(), d->size());
QCOMPARE(f->size(), g->size());
p.resize(layoutMaximumSize);
QCOMPARE(p.size(), layoutMaximumSize);
QCOMPARE(a->size(), e->size());
QCOMPARE(b->size(), d->size());
QCOMPARE(f->size(), g->size());
if (hasSimplification) {
QVERIFY(usedSimplex(l, Qt::Horizontal));
QVERIFY(usedSimplex(l, Qt::Vertical));
}
}
void tst_QGraphicsAnchorLayout::setSpacing()
{
QSizeF minSize(10, 10);
QSizeF pref(20, 20);
QSizeF maxSize(50, 50);
QGraphicsWidget *a = createItem(minSize, pref, maxSize);
QGraphicsWidget *b = createItem(minSize, pref, maxSize);
QGraphicsWidget *c = createItem(minSize, pref, maxSize);
QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout;
l->addCornerAnchors(l, Qt::TopLeftCorner, a, Qt::TopLeftCorner);
l->addCornerAnchors(b, Qt::TopRightCorner, l, Qt::TopRightCorner);
l->addAnchor(a, Qt::AnchorRight, b, Qt::AnchorLeft);
l->addAnchors(l, c, Qt::Horizontal);
l->addAnchor(a, Qt::AnchorBottom, c, Qt::AnchorTop);
l->addAnchor(c, Qt::AnchorBottom, l, Qt::AnchorBottom);
QGraphicsWidget *p = new QGraphicsWidget(0, Qt::Window);
p->setLayout(l);
l->setSpacing(1);
// don't let the style influence the test.
l->setContentsMargins(0, 0, 0, 0);
QGraphicsScene scene;
scene.addItem(p);
QGraphicsView *view = new QGraphicsView(&scene);
view->show();
p->show();
QApplication::processEvents();
#ifdef Q_OS_MAC
QTest::qWait(200);
#endif
// 21x21
QCOMPARE(p->size(), QSizeF(41, 41));
QCOMPARE(a->geometry(), QRectF(0, 0, 20, 20));
QCOMPARE(b->geometry(), QRectF(21, 0, 20, 20));
QCOMPARE(c->geometry(), QRectF(0, 21, 41, 20));
l->setHorizontalSpacing(4);
QApplication::processEvents();
p->adjustSize();
QCOMPARE(a->geometry(), QRectF(0, 0, 20, 20));
QCOMPARE(b->geometry(), QRectF(24, 0, 20, 20));
QCOMPARE(c->geometry(), QRectF(0, 21, 44, 20));
l->setVerticalSpacing(0);
QApplication::processEvents();
p->adjustSize();
QCOMPARE(a->geometry(), QRectF(0, 0, 20, 20));
QCOMPARE(b->geometry(), QRectF(24, 0, 20, 20));
QCOMPARE(c->geometry(), QRectF(0, 20, 44, 20));
delete p;
delete view;
}
class CustomLayoutStyle : public QProxyStyle
{
Q_OBJECT
public:
CustomLayoutStyle() : QProxyStyle(QStyleFactory::create("windows"))
{
hspacing = 5;
vspacing = 10;
}
virtual int pixelMetric(PixelMetric metric, const QStyleOption * option = 0,
const QWidget * widget = 0 ) const;
int hspacing;
int vspacing;
int layoutSpacing(QSizePolicy::ControlType control1,
QSizePolicy::ControlType control2,
Qt::Orientation orientation,
const QStyleOption *option = 0,
const QWidget *widget = 0) const;
};
#define CT1(c) CT2(c, c)
#define CT2(c1, c2) ((uint)c1 << 16) | (uint)c2
int CustomLayoutStyle::layoutSpacing(QSizePolicy::ControlType control1,
QSizePolicy::ControlType control2,
Qt::Orientation orientation,
const QStyleOption * /*option = 0*/,
const QWidget * /*widget = 0*/) const
{
if (orientation == Qt::Horizontal) {
switch (CT2(control1, control2)) {
case CT1(QSizePolicy::PushButton):
return 2;
break;
}
return 5;
} else {
switch (CT2(control1, control2)) {
case CT1(QSizePolicy::RadioButton):
return 2;
break;
}
return 10;
}
}
int CustomLayoutStyle::pixelMetric(PixelMetric metric, const QStyleOption * option /*= 0*/,
const QWidget * widget /*= 0*/ ) const
{
switch (metric) {
case PM_LayoutLeftMargin:
return 0;
break;
case PM_LayoutTopMargin:
return 3;
break;
case PM_LayoutRightMargin:
return 6;
break;
case PM_LayoutBottomMargin:
return 9;
break;
case PM_LayoutHorizontalSpacing:
return hspacing;
case PM_LayoutVerticalSpacing:
return vspacing;
break;
default:
break;
}
return QProxyStyle::pixelMetric(metric, option, widget);
}
void tst_QGraphicsAnchorLayout::styleDefaults()
{
QSizeF minSize (10, 10);
QSizeF pref(20, 20);
QSizeF maxSize (50, 50);
/*
create this layout, where a,b have controlType QSizePolicy::RadioButton
c,d have controlType QSizePolicy::PushButton:
+-------+
|a |
| b |
| c |
| d|
+-------+
*/
QGraphicsScene scene;
QGraphicsWidget *a = createItem(minSize, pref, maxSize);
QSizePolicy spRadioButton = a->sizePolicy();
spRadioButton.setControlType(QSizePolicy::RadioButton);
a->setSizePolicy(spRadioButton);
QGraphicsWidget *b = createItem(minSize, pref, maxSize);
b->setSizePolicy(spRadioButton);
QGraphicsWidget *c = createItem(minSize, pref, maxSize);
QSizePolicy spPushButton = c->sizePolicy();
spPushButton.setControlType(QSizePolicy::PushButton);
c->setSizePolicy(spPushButton);
QGraphicsWidget *d = createItem(minSize, pref, maxSize);
d->setSizePolicy(spPushButton);
QGraphicsWidget *window = new QGraphicsWidget(0, Qt::Window);
// Test layoutSpacing
CustomLayoutStyle *style = new CustomLayoutStyle;
style->hspacing = -1;
style->vspacing = -1;
window->setStyle(style);
QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout;
l->addCornerAnchors(l, Qt::TopLeftCorner, a, Qt::TopLeftCorner);
l->addCornerAnchors(a, Qt::BottomRightCorner, b, Qt::TopLeftCorner);
l->addCornerAnchors(b, Qt::BottomRightCorner, c, Qt::TopLeftCorner);
l->addCornerAnchors(c, Qt::BottomRightCorner, d, Qt::TopLeftCorner);
l->addCornerAnchors(d, Qt::BottomRightCorner, l, Qt::BottomRightCorner);
window->setLayout(l);
scene.addItem(window);
window->show();
QGraphicsView view(&scene);
view.resize(200, 200);
view.show();
window->adjustSize();
QCOMPARE(a->geometry(), QRectF(0, 3, 20, 20)); //radio
QCOMPARE(b->geometry(), QRectF(25, 25, 20, 20)); //radio
QCOMPARE(c->geometry(), QRectF(50, 55, 20, 20)); //push
QCOMPARE(d->geometry(), QRectF(72, 85, 20, 20)); //push
QCOMPARE(l->geometry(), QRectF(0, 0, 98, 114));
// Test pixelMetric(PM_Layout{Horizontal|Vertical}Spacing
window->setStyle(0);
style->hspacing = 1;
style->vspacing = 2;
window->setStyle(style);
window->adjustSize();
QCOMPARE(a->geometry(), QRectF(0, 3, 20, 20));
QCOMPARE(b->geometry(), QRectF(21, 25, 20, 20));
QCOMPARE(c->geometry(), QRectF(42, 47, 20, 20));
QCOMPARE(d->geometry(), QRectF(63, 69, 20, 20));
QCOMPARE(l->geometry(), QRectF(0, 0, 89, 98));
window->setStyle(0);
delete style;
}
/*!
Taken from "hard" complex case, found at
https://cwiki.nokia.com/S60QTUI/AnchorLayoutComplexCases
This layout has a special property, since it has two possible solutions for its minimum size.
For instance, when it is in its minimum size - the layout have two possible solutions:
1. c.width == 10, e.width == 10 and g.width == 10
(all others have width 0)
2. d.width == 10 and g.width == 10
(all others have width 0)
It also has several solutions for preferred size.
*/
static QGraphicsAnchorLayout *createAmbiguousS60Layout()
{
QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout;
l->setContentsMargins(0, 0, 0, 0);
l->setSpacing(0);
QSizeF minSize(0, 10);
QSizeF pref(50, 10);
QSizeF maxSize(100, 10);
QGraphicsWidget *a = createItem(minSize, pref, maxSize, "a");
QGraphicsWidget *b = createItem(minSize, pref, maxSize, "b");
QGraphicsWidget *c = createItem(minSize, pref, maxSize, "c");
QGraphicsWidget *d = createItem(minSize, pref, maxSize, "d");
QGraphicsWidget *e = createItem(minSize, pref, maxSize, "e");
QGraphicsWidget *f = createItem(minSize, pref, maxSize, "f");
QGraphicsWidget *g = createItem(minSize, pref, maxSize, "g");
//<!-- Trunk -->
setAnchor(l, l, Qt::AnchorLeft, a, Qt::AnchorLeft, 10);
setAnchor(l, a, Qt::AnchorRight, b, Qt::AnchorLeft, 10);
setAnchor(l, b, Qt::AnchorRight, c, Qt::AnchorLeft, 10);
setAnchor(l, c, Qt::AnchorRight, d, Qt::AnchorLeft, 10);
setAnchor(l, d, Qt::AnchorRight, l, Qt::AnchorRight, 10);
//<!-- Above trunk -->
setAnchor(l, b, Qt::AnchorLeft, e, Qt::AnchorLeft, 10);
setAnchor(l, e, Qt::AnchorRight, d, Qt::AnchorLeft, 10);
//<!-- Below trunk -->
setAnchor(l, a, Qt::AnchorHorizontalCenter, g, Qt::AnchorLeft, 10);
setAnchor(l, g, Qt::AnchorRight, f, Qt::AnchorHorizontalCenter, 10);
setAnchor(l, c, Qt::AnchorLeft, f, Qt::AnchorLeft, 10);
setAnchor(l, f, Qt::AnchorRight, d, Qt::AnchorRight, 10);
//<!-- vertical is simpler -->
setAnchor(l, l, Qt::AnchorTop, e, Qt::AnchorTop, 0);
setAnchor(l, e, Qt::AnchorBottom, a, Qt::AnchorTop, 0);
setAnchor(l, e, Qt::AnchorBottom, b, Qt::AnchorTop, 0);
setAnchor(l, e, Qt::AnchorBottom, c, Qt::AnchorTop, 0);
setAnchor(l, e, Qt::AnchorBottom, d, Qt::AnchorTop, 0);
setAnchor(l, a, Qt::AnchorBottom, f, Qt::AnchorTop, 0);
setAnchor(l, a, Qt::AnchorBottom, b, Qt::AnchorBottom, 0);
setAnchor(l, a, Qt::AnchorBottom, c, Qt::AnchorBottom, 0);
setAnchor(l, a, Qt::AnchorBottom, d, Qt::AnchorBottom, 0);
setAnchor(l, f, Qt::AnchorBottom, g, Qt::AnchorTop, 0);
setAnchor(l, g, Qt::AnchorBottom, l, Qt::AnchorBottom, 0);
return l;
}
void tst_QGraphicsAnchorLayout::hardComplexS60()
{
QGraphicsAnchorLayout *l = createAmbiguousS60Layout();
QCOMPARE(l->count(), 7);
QGraphicsWidget *p = new QGraphicsWidget(0, Qt::Window);
p->setLayout(l);
QSizeF layoutMinimumSize = l->effectiveSizeHint(Qt::MinimumSize);
QCOMPARE(layoutMinimumSize, QSizeF(60, 40));
// expected preferred might be wrong, (haven't manually verified it)
QSizeF layoutPreferredSize = l->effectiveSizeHint(Qt::PreferredSize);
QCOMPARE(layoutPreferredSize, QSizeF(220, 40));
QSizeF layoutMaximumSize = l->effectiveSizeHint(Qt::MaximumSize);
QCOMPARE(layoutMaximumSize, QSizeF(240, 40));
delete p;
}
static inline QByteArray msgStability(const QRectF &actual, const QRectF &expected, int pass, int item)
{
QString result;
QDebug(&result)
<< "The layout has several solutions, but which solution it picks is not stable ("
<< actual << "!=" << expected << ", iteration" << pass << ", item" << item << ')';
return result.toLocal8Bit();
}
void tst_QGraphicsAnchorLayout::stability()
{
QVector<QRectF> geometries;
geometries.resize(7);
QGraphicsWidget p(0, Qt::Window);
// it usually fails after 3-4 iterations
for (int pass = 0; pass < 20; ++pass) {
// In case we need to "scramble" the heap allocator to provoke this bug.
//static const int primes[] = {2, 3, 5, 13, 89, 233, 1597, 28657, 514229}; // fibo primes
//const int primeCount = sizeof(primes)/sizeof(int);
//int alloc = primes[pass % primeCount] + pass;
//void *mem = malloc(alloc);
//free(mem);
QGraphicsAnchorLayout *l = createAmbiguousS60Layout();
p.setLayout(l);
QSizeF layoutMinimumSize = l->effectiveSizeHint(Qt::MinimumSize);
l->setGeometry(QRectF(QPointF(0,0), layoutMinimumSize));
QApplication::processEvents();
for (int i = l->count() - 1; i >=0; --i) {
const QRectF actualGeom = l->itemAt(i)->geometry();
if (pass != 0) {
if (actualGeom != geometries[i])
QEXPECT_FAIL("", msgStability(actualGeom, geometries[i], pass, i).constData(), Abort);
QCOMPARE(actualGeom, geometries[i]);
}
geometries[i] = actualGeom;
}
p.setLayout(0); // uninstalls and deletes the layout
QApplication::processEvents();
}
}
void tst_QGraphicsAnchorLayout::delete_anchor()
{
QGraphicsScene scene;
QSizeF minSize(0, 0);
QSizeF prefSize(50, 50);
QSizeF maxSize(100, 100);
QGraphicsWidget *w1 = createItem(minSize, prefSize, maxSize, "w1");
QGraphicsWidget *w2 = createItem(minSize, prefSize, maxSize, "w2");
QGraphicsWidget *w3 = createItem(minSize, prefSize, maxSize, "w3");
QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout;
l->setSpacing(0);
l->setContentsMargins(0, 0, 0, 0);
// Horizontal
l->addAnchor(l, Qt::AnchorLeft, w1, Qt::AnchorLeft);
l->addAnchor(w1, Qt::AnchorRight, w2, Qt::AnchorLeft);
l->addAnchor(w2, Qt::AnchorRight, l, Qt::AnchorRight);
l->addAnchor(w1, Qt::AnchorRight, w3, Qt::AnchorLeft);
l->addAnchor(w3, Qt::AnchorRight, l, Qt::AnchorRight);
// Vertical
l->addAnchors(l, w1, Qt::Vertical);
l->addAnchors(l, w2, Qt::Vertical);
l->addAnchors(l, w3, Qt::Vertical);
QGraphicsAnchor *anchor = l->anchor(w3, Qt::AnchorRight, l, Qt::AnchorRight);
anchor->setSpacing(10);
QGraphicsWidget *p = new QGraphicsWidget;
p->setLayout(l);
QCOMPARE(l->count(), 3);
scene.addItem(p);
QGraphicsView *view = new QGraphicsView(&scene);
QApplication::processEvents();
// Should now be simplified
QCOMPARE(l->effectiveSizeHint(Qt::PreferredSize).width(), qreal(110));
QGraphicsAnchor *anchor1 = l->anchor(w3, Qt::AnchorRight, l, Qt::AnchorRight);
QVERIFY(anchor1);
QGraphicsAnchor *anchor2 = l->anchor(w3, Qt::AnchorRight, l, Qt::AnchorRight);
QVERIFY(anchor2);
QGraphicsAnchor *anchor3 = l->anchor(l, Qt::AnchorRight, w3, Qt::AnchorRight);
QVERIFY(anchor3);
QGraphicsAnchor *anchor4 = l->anchor(l, Qt::AnchorRight, w3, Qt::AnchorRight);
QVERIFY(anchor4);
// should all be the same object
QCOMPARE(anchor1, anchor2);
QCOMPARE(anchor2, anchor3);
QCOMPARE(anchor3, anchor4);
// check if removal works
delete anchor1;
QApplication::processEvents();
// it should also change the preferred size of the layout
QCOMPARE(l->effectiveSizeHint(Qt::PreferredSize).width(), qreal(100));
delete p;
delete view;
}
void tst_QGraphicsAnchorLayout::sizePolicy()
{
QGraphicsScene scene;
QSizeF minSize(0, 0);
QSizeF prefSize(50, 50);
QSizeF maxSize(100, 100);
QGraphicsWidget *w1 = createItem(minSize, prefSize, maxSize, "w1");
QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout;
l->setSpacing(0);
l->setContentsMargins(0, 0, 0, 0);
// horizontal and vertical
l->addAnchors(l, w1);
QGraphicsWidget *p = new QGraphicsWidget;
p->setLayout(l);
scene.addItem(p);
QGraphicsView *view = new QGraphicsView(&scene);
// QSizePolicy::Minimum
w1->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
QApplication::processEvents();
w1->adjustSize();
QCOMPARE(l->effectiveSizeHint(Qt::MinimumSize), QSizeF(50, 50));
QCOMPARE(l->effectiveSizeHint(Qt::PreferredSize), QSizeF(50, 50));
QCOMPARE(l->effectiveSizeHint(Qt::MaximumSize), QSizeF(100, 100));
// QSizePolicy::Maximum
w1->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);
QApplication::processEvents();
w1->adjustSize();
QCOMPARE(l->effectiveSizeHint(Qt::MinimumSize), QSizeF(0, 0));
QCOMPARE(l->effectiveSizeHint(Qt::PreferredSize), QSizeF(50, 50));
QCOMPARE(l->effectiveSizeHint(Qt::MaximumSize), QSizeF(50, 50));
// QSizePolicy::Fixed
w1->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
QApplication::processEvents();
w1->adjustSize();
QCOMPARE(l->effectiveSizeHint(Qt::MinimumSize), QSizeF(50, 50));
QCOMPARE(l->effectiveSizeHint(Qt::PreferredSize), QSizeF(50, 50));
QCOMPARE(l->effectiveSizeHint(Qt::MaximumSize), QSizeF(50, 50));
// QSizePolicy::Preferred
w1->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
QApplication::processEvents();
w1->adjustSize();
QCOMPARE(l->effectiveSizeHint(Qt::MinimumSize), QSizeF(0, 0));
QCOMPARE(l->effectiveSizeHint(Qt::PreferredSize), QSizeF(50, 50));
QCOMPARE(l->effectiveSizeHint(Qt::MaximumSize), QSizeF(100, 100));
// QSizePolicy::Ignored
w1->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
QApplication::processEvents();
w1->adjustSize();
QCOMPARE(l->effectiveSizeHint(Qt::MinimumSize), QSizeF(0, 0));
QCOMPARE(l->effectiveSizeHint(Qt::PreferredSize), QSizeF(0, 0));
QCOMPARE(l->effectiveSizeHint(Qt::MaximumSize), QSizeF(100, 100));
// Anchor size policies
w1->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
QGraphicsAnchor *anchor = l->anchor(l, Qt::AnchorLeft, w1, Qt::AnchorLeft);
anchor->setSpacing(10);
// QSizePolicy::Minimum
anchor->setSizePolicy(QSizePolicy::Minimum);
QApplication::processEvents();
QCOMPARE(l->effectiveSizeHint(Qt::MinimumSize), QSizeF(60, 50));
QCOMPARE(l->effectiveSizeHint(Qt::PreferredSize), QSizeF(60, 50));
// The layout has a maximum size of QWIDGETSIZE_MAX, so the result won't exceed that value.
QCOMPARE(l->effectiveSizeHint(Qt::MaximumSize), QSizeF(QWIDGETSIZE_MAX, 50));
// QSizePolicy::Preferred
anchor->setSizePolicy(QSizePolicy::Preferred);
QApplication::processEvents();
QCOMPARE(l->effectiveSizeHint(Qt::MinimumSize), QSizeF(50, 50));
QCOMPARE(l->effectiveSizeHint(Qt::PreferredSize), QSizeF(60, 50));
// The layout has a maximum size of QWIDGETSIZE_MAX, so the result won't exceed that value.
QCOMPARE(l->effectiveSizeHint(Qt::MaximumSize), QSizeF(QWIDGETSIZE_MAX, 50));
// QSizePolicy::Maximum
anchor->setSizePolicy(QSizePolicy::Maximum);
QApplication::processEvents();
QCOMPARE(l->effectiveSizeHint(Qt::MinimumSize), QSizeF(50, 50));
QCOMPARE(l->effectiveSizeHint(Qt::PreferredSize), QSizeF(60, 50));
QCOMPARE(l->effectiveSizeHint(Qt::MaximumSize), QSizeF(60, 50));
// QSizePolicy::Ignored
anchor->setSizePolicy(QSizePolicy::Ignored);
QApplication::processEvents();
QCOMPARE(l->effectiveSizeHint(Qt::MinimumSize), QSizeF(50, 50));
QCOMPARE(l->effectiveSizeHint(Qt::PreferredSize), QSizeF(50, 50));
QCOMPARE(l->effectiveSizeHint(Qt::MaximumSize), QSizeF(QWIDGETSIZE_MAX, 50));
if (hasSimplification) {
QVERIFY(!usedSimplex(l, Qt::Horizontal));
QVERIFY(!usedSimplex(l, Qt::Vertical));
}
delete p;
delete view;
}
/*!
\internal
Uses private API. (We have decided to pull hasConflicts() out of the API). However, it also
tests some tight conditions (almost-in-conflict) that we really want to test.
*/
void tst_QGraphicsAnchorLayout::conflicts()
{
QGraphicsWidget *a = createItem(QSizeF(80,10), QSizeF(90,10), QSizeF(100,10), "a");
QGraphicsWidget *b = createItem(QSizeF(10,10), QSizeF(20,10), QSizeF(30,10), "b");
QGraphicsWidget *c = createItem(QSizeF(10,10), QSizeF(20,10), QSizeF(30,10), "c");
QGraphicsAnchorLayout *l;
QGraphicsWidget *p = new QGraphicsWidget(0, Qt::Window);
l = new QGraphicsAnchorLayout;
l->setContentsMargins(0, 0, 0, 0);
// with the following setup, 'a' cannot be larger than 30 we will first have a Simplex conflict
// horizontal
setAnchor(l, l, Qt::AnchorLeft, b, Qt::AnchorLeft);
setAnchor(l, b, Qt::AnchorRight, c, Qt::AnchorLeft);
setAnchor(l, c, Qt::AnchorRight, l, Qt::AnchorRight);
setAnchor(l, b, Qt::AnchorHorizontalCenter, a, Qt::AnchorLeft);
setAnchor(l, a, Qt::AnchorRight, c, Qt::AnchorHorizontalCenter);
// vertical
setAnchor(l, l, Qt::AnchorTop, a, Qt::AnchorTop);
setAnchor(l, a, Qt::AnchorBottom, b, Qt::AnchorTop);
setAnchor(l, a, Qt::AnchorBottom, c, Qt::AnchorTop);
setAnchor(l, b, Qt::AnchorBottom, l, Qt::AnchorBottom);
setAnchor(l, c, Qt::AnchorBottom, l, Qt::AnchorBottom);
p->setLayout(l);
QCOMPARE(layoutHasConflict(l), true);
a->setMinimumSize(QSizeF(29,10));
QCOMPARE(layoutHasConflict(l), false);
a->setMinimumSize(QSizeF(30,10));
QCOMPARE(layoutHasConflict(l), false);
delete p;
}
void tst_QGraphicsAnchorLayout::floatConflict()
{
QGraphicsWidget *a = createItem(QSizeF(80,10), QSizeF(90,10), QSizeF(100,10), "a");
QGraphicsWidget *b = createItem(QSizeF(80,10), QSizeF(90,10), QSizeF(100,10), "b");
QGraphicsAnchorLayout *l;
QGraphicsWidget *p = new QGraphicsWidget(0, Qt::Window);
l = new QGraphicsAnchorLayout;
l->setContentsMargins(0, 0, 0, 0);
p->setLayout(l);
// horizontal
// with this anchor we have two floating items
setAnchor(l, a, Qt::AnchorRight, b, Qt::AnchorLeft);
// Just checking if the layout is handling well the removal of floating items
delete l->anchor(a, Qt::AnchorRight, b, Qt::AnchorLeft);
QCOMPARE(l->count(), 0);
QCOMPARE(layoutHasConflict(l), false);
// setting back the same anchor
setAnchor(l, a, Qt::AnchorRight, b, Qt::AnchorLeft);
// We don't support floating items but they should be counted as if they are in the layout
QCOMPARE(l->count(), 2);
// Although, we have an invalid situation
QCOMPARE(layoutHasConflict(l), true);
// Semi-floats are supported
setAnchor(l, a, Qt::AnchorLeft, l, Qt::AnchorLeft);
QCOMPARE(l->count(), 2);
// Vertically the layout has floating items. Therefore, we have a conflict
QCOMPARE(layoutHasConflict(l), true);
// No more floating items
setAnchor(l, b, Qt::AnchorRight, l, Qt::AnchorRight);
setAnchor(l, a, Qt::AnchorTop, l, Qt::AnchorTop);
setAnchor(l, a, Qt::AnchorBottom, l, Qt::AnchorBottom);
setAnchor(l, b, Qt::AnchorTop, l, Qt::AnchorTop);
setAnchor(l, b, Qt::AnchorBottom, l, Qt::AnchorBottom);
QCOMPARE(layoutHasConflict(l), false);
delete p;
}
void tst_QGraphicsAnchorLayout::infiniteMaxSizes()
{
if (sizeof(qreal) <= 4)
QSKIP("qreal has too little precision, result will be wrong");
QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout;
l->setContentsMargins(0, 0, 0, 0);
l->setSpacing(0);
QSizeF minSize(10, 10);
QSizeF pref(50, 10);
QSizeF maxSize(QWIDGETSIZE_MAX, 10);
QGraphicsWidget *a = createItem(minSize, pref, maxSize, "a");
QGraphicsWidget *b = createItem(minSize, pref, maxSize, "b");
QGraphicsWidget *c = createItem(minSize, pref, maxSize, "c");
QGraphicsWidget *d = createItem(minSize, pref, maxSize, "d");
QGraphicsWidget *e = createItem(minSize, pref, maxSize, "e");
//<!-- Trunk -->
setAnchor(l, l, Qt::AnchorLeft, a, Qt::AnchorLeft, 0);
setAnchor(l, a, Qt::AnchorRight, b, Qt::AnchorLeft, 0);
setAnchor(l, b, Qt::AnchorRight, c, Qt::AnchorLeft, 0);
setAnchor(l, c, Qt::AnchorRight, d, Qt::AnchorLeft, 0);
setAnchor(l, d, Qt::AnchorRight, l, Qt::AnchorRight, 0);
setAnchor(l, b, Qt::AnchorHorizontalCenter, e, Qt::AnchorLeft, 0);
setAnchor(l, e, Qt::AnchorRight, c, Qt::AnchorHorizontalCenter, 0);
QGraphicsWidget p;
p.setLayout(l);
QCOMPARE(int(p.effectiveSizeHint(Qt::MaximumSize).width()),
QWIDGETSIZE_MAX);
p.resize(200, 10);
QCOMPARE(a->geometry(), QRectF(0, 0, 50, 10));
QCOMPARE(b->geometry(), QRectF(50, 0, 50, 10));
QCOMPARE(c->geometry(), QRectF(100, 0, 50, 10));
QCOMPARE(d->geometry(), QRectF(150, 0, 50, 10));
p.resize(1000, 10);
QCOMPARE(a->geometry(), QRectF(0, 0, 250, 10));
QCOMPARE(b->geometry(), QRectF(250, 0, 250, 10));
QCOMPARE(c->geometry(), QRectF(500, 0, 250, 10));
QCOMPARE(d->geometry(), QRectF(750, 0, 250, 10));
p.resize(40000, 10);
QCOMPARE(a->geometry(), QRectF(0, 0, 10000, 10));
QCOMPARE(b->geometry(), QRectF(10000, 0, 10000, 10));
QCOMPARE(c->geometry(), QRectF(20000, 0, 10000, 10));
QCOMPARE(d->geometry(), QRectF(30000, 0, 10000, 10));
}
void tst_QGraphicsAnchorLayout::simplifiableUnfeasible()
{
QGraphicsWidget *a = createItem(QSizeF(70.0, 100.0),
QSizeF(100.0, 100.0),
QSizeF(100.0, 100.0), "A");
QGraphicsWidget *b = createItem(QSizeF(110.0, 100.0),
QSizeF(150.0, 100.0),
QSizeF(190.0, 100.0), "B");
QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout;
l->setContentsMargins(0, 0, 0, 0);
l->setSpacing(0);
l->addAnchor(l, Qt::AnchorTop, a, Qt::AnchorTop);
l->addAnchor(a, Qt::AnchorBottom, b, Qt::AnchorTop);
l->addAnchor(b, Qt::AnchorBottom, l, Qt::AnchorBottom);
l->addAnchors(l, a, Qt::Horizontal);
l->addAnchor(l, Qt::AnchorLeft, b, Qt::AnchorLeft);
l->addAnchor(b, Qt::AnchorRight, a, Qt::AnchorRight);
QCOMPARE(l->count(), 2);
QGraphicsWidget p;
p.setLayout(l);
l->invalidate();
QVERIFY(layoutHasConflict(l));
if (hasSimplification)
QVERIFY(!usedSimplex(l, Qt::Horizontal));
// Now we make it valid
b->setMinimumWidth(100);
l->invalidate();
QVERIFY(!layoutHasConflict(l));
if (hasSimplification)
QVERIFY(!usedSimplex(l, Qt::Horizontal));
// And make it invalid again
a->setPreferredWidth(70);
a->setMaximumWidth(70);
l->invalidate();
QVERIFY(layoutHasConflict(l));
if (hasSimplification)
QVERIFY(!usedSimplex(l, Qt::Horizontal));
}
/*
Test whether the anchor direction can prevent it from
being simplificated
*/
void tst_QGraphicsAnchorLayout::simplificationVsOrder()
{
QSizeF minSize(10, 10);
QSizeF pref(20, 10);
QSizeF maxSize(50, 10);
QGraphicsWidget *a = createItem(minSize, pref, maxSize, "A");
QGraphicsWidget *b = createItem(minSize, pref, maxSize, "B");
QGraphicsWidget *c = createItem(minSize, pref, maxSize, "C");
QGraphicsWidget frame;
QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout(&frame);
// Bulk anchors
l->addAnchor(l, Qt::AnchorLeft, a, Qt::AnchorLeft);
l->addAnchor(a, Qt::AnchorRight, b, Qt::AnchorLeft);
l->addAnchor(b, Qt::AnchorLeft, c, Qt::AnchorLeft);
l->addAnchor(c, Qt::AnchorRight, l, Qt::AnchorRight);
// Problematic anchor, direction b->c
QGraphicsAnchor *anchor = l->addAnchor(b, Qt::AnchorRight, c, Qt::AnchorRight);
anchor->setSpacing(5);
l->effectiveSizeHint(Qt::MinimumSize);
if (hasSimplification) {
QCOMPARE(usedSimplex(l, Qt::Horizontal), false);
QCOMPARE(usedSimplex(l, Qt::Vertical), false);
}
// Problematic anchor, direction c->b
delete anchor;
anchor = l->addAnchor(c, Qt::AnchorRight, b, Qt::AnchorRight);
anchor->setSpacing(5);
l->effectiveSizeHint(Qt::MinimumSize);
if (hasSimplification) {
QCOMPARE(usedSimplex(l, Qt::Horizontal), false);
QCOMPARE(usedSimplex(l, Qt::Vertical), false);
}
}
void tst_QGraphicsAnchorLayout::parallelSimplificationOfCenter()
{
QSizeF minSize(10, 10);
QSizeF pref(20, 10);
QSizeF maxSize(50, 10);
QGraphicsWidget *a = createItem(minSize, pref, maxSize, "A");
QGraphicsWidget *b = createItem(minSize, pref, maxSize, "B");
QGraphicsWidget parent;
QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout(&parent);
l->setContentsMargins(0, 0, 0, 0);
l->addAnchor(l, Qt::AnchorLeft, a, Qt::AnchorLeft);
l->addAnchor(l, Qt::AnchorRight, a, Qt::AnchorRight);
l->addAnchor(a, Qt::AnchorHorizontalCenter, b, Qt::AnchorLeft);
l->addAnchor(b, Qt::AnchorRight, a, Qt::AnchorRight);
parent.resize(l->effectiveSizeHint(Qt::PreferredSize));
QCOMPARE(a->geometry(), QRectF(0, 0, 40, 10));
QCOMPARE(b->geometry(), QRectF(20, 0, 20, 10));
}
/*
Test whether redundance of anchors (in this case by using addCornerAnchors), will
prevent simplification to take place when it should.
*/
void tst_QGraphicsAnchorLayout::simplificationVsRedundance()
{
QSizeF minSize(10, 10);
QSizeF pref(20, 10);
QSizeF maxSize(50, 30);
QGraphicsWidget *a = createItem(minSize, pref, maxSize, "A");
QGraphicsWidget *b = createItem(minSize, pref, maxSize, "B");
QGraphicsWidget *c = createItem(minSize, pref, maxSize, "C");
QGraphicsWidget frame;
QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout(&frame);
l->addCornerAnchors(a, Qt::TopLeftCorner, l, Qt::TopLeftCorner);
l->addCornerAnchors(a, Qt::BottomLeftCorner, l, Qt::BottomLeftCorner);
l->addCornerAnchors(b, Qt::TopLeftCorner, a, Qt::TopRightCorner);
l->addCornerAnchors(b, Qt::TopRightCorner, l, Qt::TopRightCorner);
l->addCornerAnchors(c, Qt::TopLeftCorner, b, Qt::BottomLeftCorner);
l->addCornerAnchors(c, Qt::BottomLeftCorner, a, Qt::BottomRightCorner);
l->addCornerAnchors(c, Qt::TopRightCorner, b, Qt::BottomRightCorner);
l->addCornerAnchors(c, Qt::BottomRightCorner, l, Qt::BottomRightCorner);
l->effectiveSizeHint(Qt::MinimumSize);
QCOMPARE(layoutHasConflict(l), false);
if (!hasSimplification)
QEXPECT_FAIL("", "Test depends on simplification.", Abort);
QCOMPARE(usedSimplex(l, Qt::Horizontal), false);
QCOMPARE(usedSimplex(l, Qt::Vertical), false);
}
/*
Avoid regression where the saved prefSize would be lost. This was
solved by saving the original spacing in the QGraphicsAnchorPrivate class
*/
void tst_QGraphicsAnchorLayout::spacingPersistency()
{
QGraphicsWidget w;
QGraphicsWidget *a = createItem();
QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout(&w);
l->addAnchors(l, a, Qt::Horizontal);
QGraphicsAnchor *anchor = l->anchor(l, Qt::AnchorLeft, a, Qt::AnchorLeft);
anchor->setSpacing(-30);
QCOMPARE(anchor->spacing(), -30.0);
anchor->setSpacing(30);
QCOMPARE(anchor->spacing(), 30.0);
anchor->setSizePolicy(QSizePolicy::Ignored);
w.effectiveSizeHint(Qt::PreferredSize);
QCOMPARE(anchor->spacing(), 30.0);
}
/*
Test whether a correct preferred size is set when a "snake" sequence is in parallel with the
layout or half of the layout. The tricky thing here is that all items on the snake should
keep their preferred sizes.
*/
void tst_QGraphicsAnchorLayout::snakeParallelWithLayout()
{
QSizeF minSize(10, 20);
QSizeF pref(50, 20);
QSizeF maxSize(100, 20);
QGraphicsWidget *a = createItem(maxSize, maxSize, maxSize, "A");
QGraphicsWidget *b = createItem(minSize, pref, maxSize, "B");
QGraphicsWidget *c = createItem(maxSize, maxSize, maxSize, "C");
QGraphicsWidget parent;
QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout(&parent);
l->setContentsMargins(0, 0, 0, 0);
l->setSpacing(0);
// First we'll do the case in parallel with the entire layout...
l->addAnchor(l, Qt::AnchorLeft, a, Qt::AnchorLeft);
l->addAnchor(a, Qt::AnchorRight, b, Qt::AnchorRight);
l->addAnchor(b, Qt::AnchorLeft, c, Qt::AnchorLeft);
l->addAnchor(c, Qt::AnchorRight, l, Qt::AnchorRight);
l->addAnchor(l, Qt::AnchorTop, a, Qt::AnchorTop);
l->addAnchor(a, Qt::AnchorBottom, b, Qt::AnchorTop);
l->addAnchor(b, Qt::AnchorBottom, c, Qt::AnchorTop);
l->addAnchor(c, Qt::AnchorBottom, l, Qt::AnchorBottom);
parent.resize(l->effectiveSizeHint(Qt::PreferredSize));
// Note that A and C are fixed in the maximum size
QCOMPARE(l->geometry(), QRectF(QPointF(0, 0), QSizeF(150, 60)));
QCOMPARE(a->geometry(), QRectF(QPointF(0, 0), maxSize));
QCOMPARE(b->geometry(), QRectF(QPointF(50, 20), pref));
QCOMPARE(c->geometry(), QRectF(QPointF(50, 40), maxSize));
// Then, we change the "snake" to be in parallel with half of the layout
delete l->anchor(c, Qt::AnchorRight, l, Qt::AnchorRight);
l->addAnchor(c, Qt::AnchorRight, l, Qt::AnchorHorizontalCenter);
parent.resize(l->effectiveSizeHint(Qt::PreferredSize));
QCOMPARE(l->geometry(), QRectF(QPointF(0, 0), QSizeF(300, 60)));
QCOMPARE(a->geometry(), QRectF(QPointF(0, 0), maxSize));
QCOMPARE(b->geometry(), QRectF(QPointF(50, 20), pref));
QCOMPARE(c->geometry(), QRectF(QPointF(50, 40), maxSize));
}
/*
Avoid regression where the sizeHint constraints would not be
created for a parallel anchor that included the first layout half
*/
void tst_QGraphicsAnchorLayout::parallelToHalfLayout()
{
QGraphicsWidget *a = createItem();
QGraphicsWidget w;
QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout(&w);
l->setContentsMargins(10, 10, 10, 10);
l->addAnchors(l, a, Qt::Vertical);
QGraphicsAnchor *anchor;
anchor = l->addAnchor(l, Qt::AnchorLeft, a, Qt::AnchorLeft);
anchor->setSpacing(5);
anchor = l->addAnchor(l, Qt::AnchorHorizontalCenter, a, Qt::AnchorRight);
anchor->setSpacing(-5);
const QSizeF minimumSizeHint = w.effectiveSizeHint(Qt::MinimumSize);
const QSizeF preferredSizeHint = w.effectiveSizeHint(Qt::PreferredSize);
const QSizeF maximumSizeHint = w.effectiveSizeHint(Qt::MaximumSize);
const QSizeF overhead = QSizeF(10 + 5 + 5, 10) * 2;
QCOMPARE(minimumSizeHint, QSizeF(200, 100) + overhead);
QCOMPARE(preferredSizeHint, QSizeF(300, 100) + overhead);
QCOMPARE(maximumSizeHint, QSizeF(400, 100) + overhead);
}
void tst_QGraphicsAnchorLayout::globalSpacing()
{
QGraphicsWidget *a = createItem();
QGraphicsWidget *b = createItem();
QGraphicsWidget w;
QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout(&w);
l->addCornerAnchors(l, Qt::TopLeftCorner, a, Qt::TopLeftCorner);
l->addCornerAnchors(a, Qt::BottomRightCorner, b, Qt::TopLeftCorner);
l->addCornerAnchors(b, Qt::BottomRightCorner, l, Qt::BottomRightCorner);
w.resize(w.effectiveSizeHint(Qt::PreferredSize));
qreal vSpacing = b->geometry().top() - a->geometry().bottom();
qreal hSpacing = b->geometry().left() - a->geometry().right();
// Set spacings manually
l->setVerticalSpacing(vSpacing + 10);
l->setHorizontalSpacing(hSpacing + 5);
w.resize(w.effectiveSizeHint(Qt::PreferredSize));
qreal newVSpacing = b->geometry().top() - a->geometry().bottom();
qreal newHSpacing = b->geometry().left() - a->geometry().right();
QCOMPARE(newVSpacing, vSpacing + 10);
QCOMPARE(newHSpacing, hSpacing + 5);
// Set a negative spacing. This will unset the previous spacing and
// bring back the widget-defined spacing.
l->setSpacing(-1);
w.resize(w.effectiveSizeHint(Qt::PreferredSize));
newVSpacing = b->geometry().top() - a->geometry().bottom();
newHSpacing = b->geometry().left() - a->geometry().right();
QCOMPARE(newVSpacing, vSpacing);
QCOMPARE(newHSpacing, hSpacing);
}
void tst_QGraphicsAnchorLayout::graphicsAnchorHandling()
{
QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout();
QGraphicsWidget *a = createItem();
l->addAnchors(l, a);
QGraphicsAnchor *layoutAnchor = l->anchor(l, Qt::AnchorTop, l, Qt::AnchorBottom);
QGraphicsAnchor *itemAnchor = l->anchor(a, Qt::AnchorTop, a, Qt::AnchorBottom);
QGraphicsAnchor *invalidAnchor = l->anchor(a, Qt::AnchorTop, l, Qt::AnchorBottom);
// Ensure none of these anchors are accessible.
QVERIFY(!layoutAnchor);
QVERIFY(!itemAnchor);
QVERIFY(!invalidAnchor);
// Hook the anchors to a QObject
QObject object;
QGraphicsAnchor *userAnchor = l->anchor(l, Qt::AnchorTop, a, Qt::AnchorTop);
userAnchor->setParent(&object);
userAnchor = l->anchor(l, Qt::AnchorBottom, a, Qt::AnchorBottom);
userAnchor->setParent(&object);
userAnchor = l->anchor(l, Qt::AnchorRight, a, Qt::AnchorRight);
userAnchor->setParent(&object);
userAnchor = l->anchor(l, Qt::AnchorLeft, a, Qt::AnchorLeft);
userAnchor->setParent(&object);
QCOMPARE(object.children().size(), 4);
// Delete layout, this will cause all anchors to be deleted internally.
// We expect the public QGraphicsAnchor instances to be deleted too.
delete l;
QCOMPARE(object.children().size(), 0);
delete a;
}
void tst_QGraphicsAnchorLayout::invalidHierarchyCheck()
{
QGraphicsWidget window(0, Qt::Window);
QGraphicsAnchorLayout *l = new QGraphicsAnchorLayout;
window.setLayout(l);
QCOMPARE(l->count(), 0);
QTest::ignoreMessage(QtWarningMsg, "QGraphicsAnchorLayout::addAnchor(): "
"You cannot add the parent of the layout to the layout.");
QVERIFY(!l->addAnchor(l, Qt::AnchorLeft, &window, Qt::AnchorLeft));
QTest::ignoreMessage(QtWarningMsg, "QGraphicsAnchorLayout::addAnchor(): "
"You cannot add the parent of the layout to the layout.");
l->addAnchors(l, &window);
QTest::ignoreMessage(QtWarningMsg, "QGraphicsAnchorLayout::addAnchor(): "
"You cannot add the parent of the layout to the layout.");
l->addCornerAnchors(l, Qt::TopLeftCorner, &window, Qt::TopLeftCorner);
QCOMPARE(l->count(), 0);
}
QTEST_MAIN(tst_QGraphicsAnchorLayout)
#include "tst_qgraphicsanchorlayout.moc"
|
//-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2022 Ryo Suzuki
// Copyright (c) 2016-2022 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# include <Siv3D/Window.hpp>
# include <Siv3D/Utility.hpp>
# include <Siv3D/Error.hpp>
# include <Siv3D/Monitor.hpp>
# include <Siv3D/Scene.hpp>
# include <Siv3D/WindowState.hpp>
# include <Siv3D/Window/IWindow.hpp>
# include <Siv3D/Common/Siv3DEngine.hpp>
namespace s3d
{
namespace Window
{
void SetTitle(const String& title)
{
SIV3D_ENGINE(Window)->setWindowTitle(title);
}
const String& GetTitle() noexcept
{
return SIV3D_ENGINE(Window)->getWindowTitle();
}
const WindowState& GetState() noexcept
{
return SIV3D_ENGINE(Window)->getState();
}
void SetStyle(const WindowStyle style)
{
SIV3D_ENGINE(Window)->setStyle(style);
}
void SetPos(const Point pos)
{
SIV3D_ENGINE(Window)->setPos(pos);
}
void Centering()
{
SIV3D_ENGINE(Window)->show();
try
{
const MonitorInfo currentMonitor = System::GetCurrentMonitor();
const Rect workArea = System::GetCurrentMonitor().workArea;
const Rect windowBounds = SIV3D_ENGINE(Window)->getState().bounds;
const Point pos = (workArea.pos + (workArea.size - windowBounds.size) / 2);
SetPos(pos);
}
catch (const Error&) {}
}
void Maximize()
{
SIV3D_ENGINE(Window)->maximize();
}
void Restore()
{
SIV3D_ENGINE(Window)->restore();
}
void Minimize()
{
SIV3D_ENGINE(Window)->minimize();
}
bool ResizeVirtual(const Size size, const s3d::Centering centering)
{
if ((not InRange(size.x, 1, 8192))
|| (not InRange(size.y, 1, 8192)))
{
throw Error(U"Window::ResizeVirtual(): width and height must be in the range [1, 8192]");
}
if (not SIV3D_ENGINE(Window)->resizeByVirtualSize(size))
{
return false;
}
if (const auto resizeMode = Scene::GetResizeMode();
resizeMode == ResizeMode::Actual)
{
Scene::Resize(SIV3D_ENGINE(Window)->getState().frameBufferSize);
}
else if (resizeMode == ResizeMode::Virtual)
{
Scene::Resize(size);
}
if (centering)
{
Centering();
}
return true;
}
bool ResizeActual(const Size size, const s3d::Centering centering)
{
if ((not InRange(size.x, 1, 8192))
|| (not InRange(size.y, 1, 8192)))
{
throw Error(U"Window::ResizeActual(): width and height must be in the range [1, 8192]");
}
if (not SIV3D_ENGINE(Window)->resizeByFrameBufferSize(size))
{
return false;
}
if (const auto resizeMode = Scene::GetResizeMode();
resizeMode == ResizeMode::Actual)
{
Scene::Resize(SIV3D_ENGINE(Window)->getState().frameBufferSize);
}
else if (resizeMode == ResizeMode::Virtual)
{
Scene::Resize(size);
}
if (centering)
{
Centering();
}
return true;
}
void SetMinimumFrameBufferSize(const Size size)
{
SIV3D_ENGINE(Window)->setMinimumFrameBufferSize(size);
}
void SetFullscreen(const bool fullscreen, const size_t monitorIndex)
{
SIV3D_ENGINE(Window)->setFullscreen(fullscreen, monitorIndex);
}
void SetToggleFullscreenEnabled(const bool enabled)
{
SIV3D_ENGINE(Window)->setToggleFullscreenEnabled(enabled);
}
bool IsToggleFullscreenEnabled()
{
return SIV3D_ENGINE(Window)->isToggleFullscreenEnabled();
}
}
# if SIV3D_PLATFORM(WINDOWS)
namespace Platform::Windows::Window
{
void* GetHWND()
{
return SIV3D_ENGINE(Window)->getHandle();
}
}
# endif
}
|
//pure
struct down_sgn {
int operator () (LT x) const {
return sgn(x);
}
};
struct up_sgn {
int operator () (LT x) const {
return -sgn(x);
}
};
template <class XSGN>
struct HalfConvexHull {
#define xsgn XSGN()
struct CMPX {
bool operator () (const VEC& a, const VEC& b) {
return xsgn(a.x - b.x) < 0;
}
};
typedef set<VEC, CMPX> SE;
SE s;
typedef typename SE::iterator IT;
IT it;
//The convex mustn't be degenerate
//0: out
//1: on
//2: in
int relation(const VEC& p) {
it = s.lower_bound(p);
if (it == s.end()) return 0;
if (it == s.begin()) {
if (xsgn(p.x - it->x) < 0) return 0;
else return xsgn(p.y - it->y) + 1;
}
auto bef = it;
--bef;
return sgn((*it - *bef) ^ (p - *bef)) + 1;
}
IT Pre(IT it) {
return it == s.begin() ? s.end() : --it;
}
void Insert(const VEC& p) {
if (relation(p)) return;
bool del = false;
if (it != s.end() && it->x == p.x) {
s.erase(it);
}
it = s.insert(p).first;
auto pre = Pre(it);
auto nxt(it);
++nxt;
if (pre != s.end()) {
for (auto j = Pre(pre); j != s.end() && ((*pre - p) ^ (*j - p)) >= 0; pre = j, j = Pre(j)) {
s.erase(pre);
}
}
if (nxt != s.end()) {
auto j = nxt;
for (++j; j != s.end() && ((*j - p) ^ (*nxt - p)) >= 0; nxt = j, ++j) {
s.erase(nxt);
}
}
}
};
struct ConvexHull {
HalfConvexHull<down_sgn> down;
HalfConvexHull<up_sgn> up;
int relation(const VEC& p) {
int r = down.relation(p);
if (r != 2) return r;
return up.relation(p);
}
void Insert(const VEC& p) {
down.Insert(p);
up.Insert(p);
}
};
//area2
template <class XSGN>
struct HalfConvexHull {
#define xsgn XSGN()
struct CMPX {
bool operator () (const VEC& a, const VEC& b) {
return xsgn(a.x - b.x) < 0;
}
};
typedef set<VEC, CMPX> SE;
SE s;
typedef typename SE::iterator IT;
LT area2; //to (0, 0)
IT it;
HalfConvexHull() : area2(0) {}
//The convex mustn't be degenerate
//0: out
//1: on
//2: in
int relation(const VEC& p) {
it = s.lower_bound(p);
if (it == s.end()) return 0;
if (it == s.begin()) {
if (xsgn(p.x - it->x) < 0) return 0;
else return xsgn(p.y - it->y) + 1;
}
auto bef = it;
--bef;
return sgn((*it - *bef) ^ (p - *bef)) + 1;
}
IT Pre(IT it) {
return it == s.begin() ? s.end() : --it;
}
void Insert(const VEC& p) {
if (relation(p)) return;
bool del = false;
VEC d;
if (it != s.end() && it->x == p.x) {
d = *it;
del = true;
s.erase(it);
}
it = s.insert(p).first;
auto pre = Pre(it);
auto nxt(it);
++nxt;
if (pre != s.end()) {
if (del) {
area2 -= *pre ^ d;
} else if (nxt != s.end()) {
area2 -= *pre ^ *nxt;
}
area2 += *pre ^ p;
for (auto j = Pre(pre); j != s.end() && ((*pre - p) ^ (*j - p)) >= 0; pre = j, j = Pre(j)) {
area2 += (*j ^ p) - (*j ^ *pre) - (*pre ^ p);
s.erase(pre);
}
}
if (nxt != s.end()) {
if (del) {
area2 -= d ^ *nxt;
}
area2 += p ^ *nxt;
auto j = nxt;
for (++j; j != s.end() && ((*j - p) ^ (*nxt - p)) >= 0; nxt = j, ++j) {
area2 += (p ^ *j) - (p ^ *nxt) - (*nxt ^ *j);
s.erase(nxt);
}
}
}
};
struct ConvexHull {
HalfConvexHull<down_sgn> down;
HalfConvexHull<up_sgn> up;
void Insert(const VEC& p) {
down.Insert(p);
up.Insert(p);
}
LT area2() const {
if (down.s.empty()) return 0;
return (*up.s.rbegin() ^ *down.s.begin()) + down.area2 +
(*down.s.rbegin() ^ *up.s.begin()) + up.area2;
}
};
//SPLAY set
template <class XSGN>
struct HalfConvexHull {
#define xsgn XSGN()
struct CMPX {
bool operator () (const VEC& a, const VEC& b) const {
return xsgn(a.x - b.x) < 0;
}
};
SPLAY<VEC, CMPX> s;
void Init() {
s.Init();
}
int Pre(int it) {
return s.PreOrNxt(it, false);
}
int Nxt(int it) {
return s.PreOrNxt(it, true);
}
int it;
//The convex mustn't be degenerate
//0: out
//1: on
//2: in
int relation(const VEC& p) {
it = s.lower_bound(p, true);
if (it == s.end()) return 0;
if (it == s.begin()) {
if (xsgn(p.x - s.keys[it].x) < 0) return 0;
else return xsgn(p.y - s.keys[it].y) + 1;
}
int bef = Pre(it);
return sgn((s.keys[it] - s.keys[bef]) ^ (p - s.keys[bef])) + 1;
}
void Insert(const VEC& p) {
if (relation(p)) return;
if (it && s.keys[it].x == p.x) {
s.erase(it);
}
s.Insert(p);
it = s.root; //The new node
auto pre = Pre(it), nxt = Nxt(it);
if (pre) {
for (auto j = Pre(pre); j && ((s.keys[pre] - p) ^ (s.keys[j] - p)) >= 0; pre = j, j = Pre(j)) {
s.erase(pre);
}
}
if (nxt) {
for (auto j = Nxt(nxt); j && ((s.keys[j] - p) ^ (s.keys[nxt] - p)) >= 0; nxt = j, j = Nxt(j)) {
s.erase(nxt);
}
}
}
};
struct ConvexHull {
HalfConvexHull<down_sgn> down;
HalfConvexHull<up_sgn> up;
void Init() {
down.Init();
up.Init();
}
int relation(const VEC& p) {
int r = down.relation(p);
if (r != 2) return r;
return up.relation(p);
}
void Insert(const VEC& p) {
down.Insert(p);
up.Insert(p);
}
};
|
/*
Copyright (c) 2010-2017 Maximus5
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 authors 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.
*/
#include <windows.h>
#include "../common/pluginA.hpp"
#include "../common/plugin_helper.h"
#include "ConEmuLn.h"
//#define SHOW_DEBUG_EVENTS
extern bool gbSetStartupInfoOk;
// minimal(?) FAR version 1.71 alpha 4 build 2470
int WINAPI _export GetMinFarVersion(void)
{
// Однако, FAR2 до сборки 748 не понимал две версии плагина в одном файле
BOOL bFar2=FALSE;
if (!LoadFarVersion())
bFar2 = TRUE;
else
bFar2 = gFarVersion.dwVerMajor>=2;
if (bFar2)
{
return MAKEFARVERSION(2,0,748);
}
return MAKEFARVERSION(1,71,2470);
}
struct PluginStartupInfo *InfoA = NULL;
struct FarStandardFunctions *FSFA = NULL;
static wchar_t* gszRootKeyA = NULL;
#if defined(__GNUC__)
#ifdef __cplusplus
extern "C" {
#endif
void WINAPI SetStartupInfo(const struct PluginStartupInfo *aInfo);
#ifdef __cplusplus
};
#endif
#endif
void WINAPI _export SetStartupInfo(const struct PluginStartupInfo *aInfo)
{
gbSetStartupInfoOk = true;
//LoadFarVersion - уже вызван в GetStartupInfo
INIT_FAR_PSI(::InfoA, ::FSFA, aInfo);
DWORD nFarVer = 0;
if (InfoA->AdvControl(InfoA->ModuleNumber, ACTL_GETFARVERSION, &nFarVer))
{
if (HIBYTE(LOWORD(nFarVer)) == 1)
{
gFarVersion.dwBuild = HIWORD(nFarVer);
gFarVersion.dwVerMajor = (HIBYTE(LOWORD(nFarVer)));
gFarVersion.dwVerMinor = (LOBYTE(LOWORD(nFarVer)));
}
else
{
_ASSERTE(HIBYTE(HIWORD(nFarVer)) == 1);
}
}
int nLen = lstrlenA(InfoA->RootKey)+16;
if (gszRootKeyA) free(gszRootKeyA);
gszRootKeyA = (wchar_t*)calloc(nLen,2);
MultiByteToWideChar(CP_OEMCP,0,InfoA->RootKey,-1,gszRootKeyA,nLen);
WCHAR* pszSlash = gszRootKeyA+lstrlenW(gszRootKeyA)-1;
if (*pszSlash != L'\\') *(++pszSlash) = L'\\';
lstrcpyW(pszSlash+1, L"ConEmuLn\\");
StartPlugin(FALSE);
}
void WINAPI _export GetPluginInfo(struct PluginInfo *pi)
{
_ASSERTE(pi->StructSize==0);
pi->StructSize = sizeof(struct PluginInfo);
//_ASSERTE(pi->StructSize>0 && (pi->StructSize >= sizeof(*pi)));
static char *szMenu[1], szMenu1[255];
szMenu[0]=szMenu1;
lstrcpynA(szMenu1, InfoA->GetMsg(InfoA->ModuleNumber,CEPluginName), 240);
_ASSERTE(pi->StructSize == sizeof(struct PluginInfo));
pi->Flags = (gbBackgroundEnabled?PF_PRELOAD:0) | PF_EDITOR | PF_VIEWER;
//pi->DiskMenuStrings = NULL;
//pi->DiskMenuNumbers = 0;
pi->PluginMenuStrings = szMenu;
pi->PluginMenuStringsNumber = 1;
pi->PluginConfigStrings = szMenu;
pi->PluginConfigStringsNumber = 1;
pi->CommandPrefix = NULL;
pi->Reserved = 0;
}
void WINAPI _export ExitFAR(void)
{
ExitPlugin();
if (InfoA)
{
free(InfoA);
InfoA = NULL;
}
if (FSFA)
{
free(FSFA);
FSFA = NULL;
}
if (gszRootKeyA)
{
free(gszRootKeyA);
gszRootKeyA = NULL;
}
}
static char *GetMsg(int MsgId)
{
return((char*)InfoA->GetMsg(InfoA->ModuleNumber, MsgId));
}
#undef FAR_UNICODE
#include "Configure.h"
int WINAPI Configure(int ItemNumber)
{
if (!InfoA)
return false;
return ConfigureProc(ItemNumber);
}
HANDLE WINAPI _export OpenPlugin(int OpenFrom,INT_PTR Item)
{
if (InfoA == NULL)
return INVALID_HANDLE_VALUE;
Configure(0);
return INVALID_HANDLE_VALUE;
}
void SettingsLoadA()
{
SettingsLoadReg(gszRootKeyA);
}
void SettingsSaveA()
{
SettingsSaveReg(gszRootKeyA);
}
|
// This file is a part of Julia. License is MIT: https://julialang.org/license
#define DEBUG_TYPE "alloc_opt"
#undef DEBUG
#include "llvm-version.h"
#include <llvm-c/Core.h>
#include <llvm-c/Types.h>
#include <llvm/ADT/SmallSet.h>
#include <llvm/ADT/SmallVector.h>
#include <llvm/ADT/SetVector.h>
#include <llvm/IR/Value.h>
#include <llvm/IR/CFG.h>
#include <llvm/IR/LegacyPassManager.h>
#include <llvm/IR/Dominators.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/IntrinsicInst.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Operator.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/Pass.h>
#include <llvm/Support/Debug.h>
#include <llvm/Transforms/Utils/PromoteMemToReg.h>
#include <llvm/InitializePasses.h>
#include "codegen_shared.h"
#include "julia.h"
#include "julia_internal.h"
#include "llvm-pass-helpers.h"
#include <map>
#include <set>
#include "julia_assert.h"
using namespace llvm;
namespace {
static void removeGCPreserve(CallInst *call, Instruction *val)
{
auto replace = Constant::getNullValue(val->getType());
call->replaceUsesOfWith(val, replace);
for (auto &arg: call->arg_operands()) {
if (!isa<Constant>(arg.get())) {
return;
}
}
while (!call->use_empty()) {
auto end = cast<Instruction>(*call->user_begin());
// gc_preserve_end returns void.
assert(end->use_empty());
end->eraseFromParent();
}
call->eraseFromParent();
}
static bool hasObjref(Type *ty)
{
if (auto ptrty = dyn_cast<PointerType>(ty))
return ptrty->getAddressSpace() == AddressSpace::Tracked;
if (isa<ArrayType>(ty) || isa<VectorType>(ty))
return hasObjref(GetElementPtrInst::getTypeAtIndex(ty, (uint64_t)0));
if (auto structty = dyn_cast<StructType>(ty)) {
for (auto elty: structty->elements()) {
if (hasObjref(elty)) {
return true;
}
}
}
return false;
}
/**
* Promote `julia.gc_alloc_obj` which do not have escaping root to a alloca.
* Uses that are not considered to escape the object (i.e. heap address) includes,
*
* * load
* * `pointer_from_objref`
* * Any real llvm intrinsics
* * gc preserve intrinsics
* * `ccall` gcroot array (`jl_roots` operand bundle)
* * store (as address)
* * addrspacecast, bitcast, getelementptr
*
* The results of these cast instructions will be scanned recursively.
*
* All other uses are considered to escape conservatively.
*/
/**
* TODO:
* * Return twice
* * Handle phi node.
* * Look through `pointer_from_objref`.
* * Handle jl_box*
*/
struct AllocOpt : public FunctionPass, public JuliaPassContext {
static char ID;
AllocOpt()
: FunctionPass(ID)
{
llvm::initializeDominatorTreeWrapperPassPass(*PassRegistry::getPassRegistry());
}
const DataLayout *DL;
Function *lifetime_start;
Function *lifetime_end;
Type *T_int64;
private:
bool doInitialization(Module &m) override;
bool runOnFunction(Function &F) override;
void getAnalysisUsage(AnalysisUsage &AU) const override
{
FunctionPass::getAnalysisUsage(AU);
AU.addRequired<DominatorTreeWrapperPass>();
AU.addPreserved<DominatorTreeWrapperPass>();
AU.setPreservesCFG();
}
};
struct Optimizer {
Optimizer(Function &F, AllocOpt &pass)
: F(F),
pass(pass)
{}
void initialize();
void optimizeAll();
bool finalize();
private:
bool isSafepoint(Instruction *inst);
Instruction *getFirstSafepoint(BasicBlock *bb);
ssize_t getGCAllocSize(Instruction *I);
void pushInstruction(Instruction *I);
void insertLifetimeEnd(Value *ptr, Constant *sz, Instruction *insert);
// insert llvm.lifetime.* calls for `ptr` with size `sz` based on the use of `orig`.
void insertLifetime(Value *ptr, Constant *sz, Instruction *orig);
void checkInst(Instruction *I);
void replaceIntrinsicUseWith(IntrinsicInst *call, Intrinsic::ID ID,
Instruction *orig_i, Instruction *new_i);
void removeAlloc(CallInst *orig_inst);
void moveToStack(CallInst *orig_inst, size_t sz, bool has_ref);
void splitOnStack(CallInst *orig_inst);
void optimizeTag(CallInst *orig_inst);
Function &F;
AllocOpt &pass;
DominatorTree *_DT = nullptr;
DominatorTree &getDomTree()
{
if (!_DT)
_DT = &pass.getAnalysis<DominatorTreeWrapperPass>().getDomTree();
return *_DT;
}
struct CheckInst {
struct Frame {
Instruction *parent;
uint32_t offset;
Instruction::use_iterator use_it;
Instruction::use_iterator use_end;
};
typedef SmallVector<Frame,4> Stack;
};
struct Lifetime {
struct Frame {
BasicBlock *bb;
pred_iterator p_cur;
pred_iterator p_end;
Frame(BasicBlock *bb)
: bb(bb),
p_cur(pred_begin(bb)),
p_end(pred_end(bb))
{}
};
typedef SmallVector<Frame,4> Stack;
};
struct ReplaceUses {
struct Frame {
Instruction *orig_i;
union {
Instruction *new_i;
uint32_t offset;
};
Frame(Instruction *orig_i, Instruction *new_i)
: orig_i(orig_i),
new_i(new_i)
{}
Frame(Instruction *orig_i, uint32_t offset)
: orig_i(orig_i),
offset(offset)
{}
};
typedef SmallVector<Frame,4> Stack;
};
struct MemOp {
Instruction *inst;
unsigned opno;
uint32_t offset = 0;
uint32_t size = 0;
bool isobjref:1;
bool isaggr:1;
MemOp(Instruction *inst, unsigned opno)
: inst(inst),
opno(opno),
isobjref(false),
isaggr(false)
{}
};
struct Field {
uint32_t size;
bool hasobjref:1;
bool hasaggr:1;
bool multiloc:1;
bool hasload:1;
Type *elty;
SmallVector<MemOp,4> accesses;
Field(uint32_t size, Type *elty)
: size(size),
hasobjref(false),
hasaggr(false),
multiloc(false),
hasload(false),
elty(elty)
{
}
};
struct AllocUseInfo {
SmallSet<Instruction*,16> uses;
SmallSet<CallInst*,4> preserves;
std::map<uint32_t,Field> memops;
// Completely unknown use
bool escaped:1;
// Address is leaked to functions that doesn't care where the object is allocated.
bool addrescaped:1;
// There are reader of the memory
bool hasload:1;
// There are uses in gc_preserve intrinsics or ccall roots
bool haspreserve:1;
// There are objects fields being loaded
bool refload:1;
// There are objects fields being stored
bool refstore:1;
// There are typeof call
// This can be optimized without optimizing out the allocation itself
bool hastypeof:1;
// There are store/load/memset on this object with offset or size (or value for memset)
// that cannot be statically computed.
// This is a weaker form of `addrescaped` since `hasload` can still be used
// to see if the memory is actually being used
bool hasunknownmem:1;
void reset()
{
escaped = false;
addrescaped = false;
hasload = false;
haspreserve = false;
refload = false;
refstore = false;
hastypeof = false;
hasunknownmem = false;
uses.clear();
preserves.clear();
memops.clear();
}
void dump();
bool addMemOp(Instruction *inst, unsigned opno, uint32_t offset, Type *elty,
bool isstore, const DataLayout &DL);
std::pair<const uint32_t,Field> &getField(uint32_t offset, uint32_t size, Type *elty);
std::map<uint32_t,Field>::iterator findLowerField(uint32_t offset)
{
// Find the last field that starts no higher than `offset`.
auto it = memops.upper_bound(offset);
if (it != memops.begin())
return --it;
return memops.end();
}
};
SetVector<std::pair<CallInst*,size_t>> worklist;
SmallVector<CallInst*,6> removed;
AllocUseInfo use_info;
CheckInst::Stack check_stack;
Lifetime::Stack lifetime_stack;
ReplaceUses::Stack replace_stack;
std::map<BasicBlock*, llvm::WeakVH> first_safepoint;
};
void Optimizer::pushInstruction(Instruction *I)
{
ssize_t sz = getGCAllocSize(I);
if (sz != -1) {
worklist.insert(std::make_pair(cast<CallInst>(I), sz));
}
}
void Optimizer::initialize()
{
for (auto &bb: F) {
for (auto &I: bb) {
pushInstruction(&I);
}
}
}
void Optimizer::optimizeAll()
{
while (!worklist.empty()) {
auto item = worklist.pop_back_val();
auto orig = item.first;
size_t sz = item.second;
checkInst(orig);
if (use_info.escaped) {
if (use_info.hastypeof)
optimizeTag(orig);
continue;
}
if (!use_info.addrescaped && !use_info.hasload && (!use_info.haspreserve ||
!use_info.refstore)) {
// No one took the address, no one reads anything and there's no meaningful
// preserve of fields (either no preserve/ccall or no object reference fields)
// We can just delete all the uses.
removeAlloc(orig);
continue;
}
bool has_ref = false;
bool has_refaggr = false;
for (auto memop: use_info.memops) {
auto &field = memop.second;
if (field.hasobjref) {
has_ref = true;
// This can be relaxed a little based on hasload
// TODO: add support for hasaggr load/store
if (field.hasaggr || field.multiloc || field.size != sizeof(void*)) {
has_refaggr = true;
break;
}
}
}
if (!use_info.hasunknownmem && !use_info.addrescaped && !has_refaggr) {
// No one actually care about the memory layout of this object, split it.
splitOnStack(orig);
continue;
}
if (has_refaggr) {
if (use_info.hastypeof)
optimizeTag(orig);
continue;
}
// The object has no fields with mix reference access
moveToStack(orig, sz, has_ref);
}
}
bool Optimizer::finalize()
{
if (removed.empty())
return false;
for (auto inst: removed)
inst->eraseFromParent();
return true;
}
bool Optimizer::isSafepoint(Instruction *inst)
{
auto call = dyn_cast<CallInst>(inst);
if (!call)
return false;
if (isa<IntrinsicInst>(call))
return false;
if (auto callee = call->getCalledFunction()) {
// Known functions emitted in codegen that are not safepoints
if (callee == pass.pointer_from_objref_func || callee->getName() == "memcmp") {
return false;
}
}
return true;
}
Instruction *Optimizer::getFirstSafepoint(BasicBlock *bb)
{
auto it = first_safepoint.find(bb);
if (it != first_safepoint.end()) {
Value *Val = it->second;
if (Val)
return cast<Instruction>(Val);
}
Instruction *first = nullptr;
for (auto &I: *bb) {
if (isSafepoint(&I)) {
first = &I;
break;
}
}
first_safepoint[bb] = first;
return first;
}
ssize_t Optimizer::getGCAllocSize(Instruction *I)
{
auto call = dyn_cast<CallInst>(I);
if (!call)
return -1;
if (call->getCalledOperand() != pass.alloc_obj_func)
return -1;
assert(call->getNumArgOperands() == 3);
size_t sz = (size_t)cast<ConstantInt>(call->getArgOperand(1))->getZExtValue();
if (sz < IntegerType::MAX_INT_BITS / 8 && sz < INT32_MAX)
return sz;
return -1;
}
std::pair<const uint32_t,Optimizer::Field>&
Optimizer::AllocUseInfo::getField(uint32_t offset, uint32_t size, Type *elty)
{
auto it = findLowerField(offset);
auto end = memops.end();
auto lb = end; // first overlap
auto ub = end; // last overlap
if (it != end) {
// The slot found contains the current location
if (it->first + it->second.size >= offset + size) {
if (it->second.elty != elty)
it->second.elty = nullptr;
assert(it->second.elty == nullptr || (it->first == offset && it->second.size == size));
return *it;
}
if (it->first + it->second.size > offset) {
lb = it;
ub = it;
}
}
else {
it = memops.begin();
}
// Now find the last slot that overlaps with the current memory location.
// Also set `lb` if we didn't find any above.
for (; it != end && it->first < offset + size; ++it) {
if (lb == end)
lb = it;
ub = it;
}
// no overlap found just create a new one.
if (lb == end)
return *memops.emplace(offset, Field(size, elty)).first;
// We find overlapping but not containing slot we need to merge slot/create new one
uint32_t new_offset = std::min(offset, lb->first);
uint32_t new_addrub = std::max(offset + uint32_t(size), ub->first + ub->second.size);
uint32_t new_size = new_addrub - new_offset;
Field field(new_size, nullptr);
field.multiloc = true;
++ub;
for (it = lb; it != ub; ++it) {
field.hasobjref |= it->second.hasobjref;
field.hasload |= it->second.hasload;
field.hasaggr |= it->second.hasaggr;
field.accesses.append(it->second.accesses.begin(), it->second.accesses.end());
}
memops.erase(lb, ub);
return *memops.emplace(new_offset, std::move(field)).first;
}
bool Optimizer::AllocUseInfo::addMemOp(Instruction *inst, unsigned opno, uint32_t offset,
Type *elty, bool isstore, const DataLayout &DL)
{
MemOp memop(inst, opno);
memop.offset = offset;
uint64_t size = DL.getTypeStoreSize(elty);
if (size >= UINT32_MAX - offset)
return false;
memop.size = size;
memop.isaggr = isa<StructType>(elty) || isa<ArrayType>(elty) || isa<VectorType>(elty);
memop.isobjref = hasObjref(elty);
auto &field = getField(offset, size, elty);
if (field.second.hasobjref != memop.isobjref)
field.second.multiloc = true; // can't split this field, since it contains a mix of references and bits
if (!isstore)
field.second.hasload = true;
if (memop.isobjref) {
if (isstore) {
refstore = true;
}
else {
refload = true;
}
if (memop.isaggr)
field.second.hasaggr = true;
field.second.hasobjref = true;
}
else if (memop.isaggr) {
field.second.hasaggr = true;
}
field.second.accesses.push_back(memop);
return true;
}
JL_USED_FUNC void Optimizer::AllocUseInfo::dump()
{
jl_safe_printf("escaped: %d\n", escaped);
jl_safe_printf("addrescaped: %d\n", addrescaped);
jl_safe_printf("hasload: %d\n", hasload);
jl_safe_printf("haspreserve: %d\n", haspreserve);
jl_safe_printf("refload: %d\n", refload);
jl_safe_printf("refstore: %d\n", refstore);
jl_safe_printf("hasunknownmem: %d\n", hasunknownmem);
jl_safe_printf("Uses: %d\n", (unsigned)uses.size());
for (auto inst: uses)
llvm_dump(inst);
if (!preserves.empty()) {
jl_safe_printf("Preserves: %d\n", (unsigned)preserves.size());
for (auto inst: preserves) {
llvm_dump(inst);
}
}
if (!memops.empty()) {
jl_safe_printf("Memops: %d\n", (unsigned)memops.size());
for (auto &field: memops) {
jl_safe_printf(" Field %d @ %d\n", field.second.size, field.first);
jl_safe_printf(" Accesses:\n");
for (auto memop: field.second.accesses) {
jl_safe_printf(" ");
llvm_dump(memop.inst);
}
}
}
}
void Optimizer::checkInst(Instruction *I)
{
use_info.reset();
if (I->use_empty())
return;
CheckInst::Frame cur{I, 0, I->use_begin(), I->use_end()};
check_stack.clear();
// Recursion
auto push_inst = [&] (Instruction *inst) {
if (cur.use_it != cur.use_end)
check_stack.push_back(cur);
cur.parent = inst;
cur.use_it = inst->use_begin();
cur.use_end = inst->use_end();
};
auto check_inst = [&] (Instruction *inst, Use *use) {
if (isa<LoadInst>(inst)) {
use_info.hasload = true;
if (cur.offset == UINT32_MAX || !use_info.addMemOp(inst, 0, cur.offset,
inst->getType(),
false, *pass.DL))
use_info.hasunknownmem = true;
return true;
}
if (auto call = dyn_cast<CallInst>(inst)) {
// TODO handle `memcmp`
// None of the intrinsics should care if the memory is stack or heap allocated.
auto callee = call->getCalledOperand();
if (auto II = dyn_cast<IntrinsicInst>(call)) {
if (auto id = II->getIntrinsicID()) {
if (id == Intrinsic::memset) {
assert(call->getNumArgOperands() == 4);
if (cur.offset == UINT32_MAX ||
!isa<ConstantInt>(call->getArgOperand(2)) ||
!isa<ConstantInt>(call->getArgOperand(1)) ||
(cast<ConstantInt>(call->getArgOperand(2))->getLimitedValue() >=
UINT32_MAX - cur.offset))
use_info.hasunknownmem = true;
return true;
}
if (id == Intrinsic::lifetime_start || id == Intrinsic::lifetime_end ||
isa<DbgInfoIntrinsic>(II))
return true;
use_info.addrescaped = true;
return true;
}
if (pass.gc_preserve_begin_func == callee) {
for (auto user: call->users())
use_info.uses.insert(cast<Instruction>(user));
use_info.preserves.insert(call);
use_info.haspreserve = true;
return true;
}
}
if (pass.pointer_from_objref_func == callee) {
use_info.addrescaped = true;
return true;
}
if (pass.typeof_func == callee) {
use_info.hastypeof = true;
assert(use->get() == I);
return true;
}
if (pass.write_barrier_func == callee)
return true;
auto opno = use->getOperandNo();
// Uses in `jl_roots` operand bundle are not counted as escaping, everything else is.
if (!call->isBundleOperand(opno) ||
call->getOperandBundleForOperand(opno).getTagName() != "jl_roots") {
use_info.escaped = true;
return false;
}
use_info.haspreserve = true;
return true;
}
if (auto store = dyn_cast<StoreInst>(inst)) {
// Only store value count
if (use->getOperandNo() != StoreInst::getPointerOperandIndex()) {
use_info.escaped = true;
return false;
}
auto storev = store->getValueOperand();
if (cur.offset == UINT32_MAX || !use_info.addMemOp(inst, use->getOperandNo(),
cur.offset, storev->getType(),
true, *pass.DL))
use_info.hasunknownmem = true;
return true;
}
if (isa<AtomicCmpXchgInst>(inst) || isa<AtomicRMWInst>(inst)) {
// Only store value count
if (use->getOperandNo() != isa<AtomicCmpXchgInst>(inst) ? AtomicCmpXchgInst::getPointerOperandIndex() : AtomicRMWInst::getPointerOperandIndex()) {
use_info.escaped = true;
return false;
}
use_info.hasload = true;
auto storev = isa<AtomicCmpXchgInst>(inst) ? cast<AtomicCmpXchgInst>(inst)->getNewValOperand() : cast<AtomicRMWInst>(inst)->getValOperand();
if (cur.offset == UINT32_MAX || !use_info.addMemOp(inst, use->getOperandNo(),
cur.offset, storev->getType(),
true, *pass.DL))
use_info.hasunknownmem = true;
use_info.refload = true;
return true;
}
if (isa<AddrSpaceCastInst>(inst) || isa<BitCastInst>(inst)) {
push_inst(inst);
return true;
}
if (auto gep = dyn_cast<GetElementPtrInst>(inst)) {
uint64_t next_offset = cur.offset;
if (cur.offset != UINT32_MAX) {
APInt apoffset(sizeof(void*) * 8, cur.offset, true);
if (!gep->accumulateConstantOffset(*pass.DL, apoffset) || apoffset.isNegative()) {
next_offset = UINT32_MAX;
}
else {
next_offset = apoffset.getLimitedValue();
if (next_offset > UINT32_MAX) {
next_offset = UINT32_MAX;
}
}
}
push_inst(inst);
cur.offset = (uint32_t)next_offset;
return true;
}
use_info.escaped = true;
return false;
};
while (true) {
assert(cur.use_it != cur.use_end);
auto use = &*cur.use_it;
auto inst = dyn_cast<Instruction>(use->getUser());
++cur.use_it;
if (!inst) {
use_info.escaped = true;
return;
}
if (!check_inst(inst, use))
return;
use_info.uses.insert(inst);
if (cur.use_it == cur.use_end) {
if (check_stack.empty())
return;
cur = check_stack.back();
check_stack.pop_back();
}
}
}
void Optimizer::insertLifetimeEnd(Value *ptr, Constant *sz, Instruction *insert)
{
BasicBlock::iterator it(insert);
BasicBlock::iterator begin(insert->getParent()->begin());
// Makes sure that the end is inserted before nearby start.
// We insert start before the allocation call, if it is the first safepoint we find for
// another instruction, it's better if we insert the end before the start instead of the
// allocation so that the two allocations do not have overlapping lifetime.
while (it != begin) {
--it;
if (auto II = dyn_cast<IntrinsicInst>(&*it)) {
if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
II->getIntrinsicID() == Intrinsic::lifetime_end) {
insert = II;
continue;
}
}
break;
}
CallInst::Create(pass.lifetime_end, {sz, ptr}, "", insert);
}
void Optimizer::insertLifetime(Value *ptr, Constant *sz, Instruction *orig)
{
CallInst::Create(pass.lifetime_start, {sz, ptr}, "", orig);
BasicBlock *def_bb = orig->getParent();
std::set<BasicBlock*> bbs{def_bb};
auto &DT = getDomTree();
// Collect all BB where the allocation is live
for (auto use: use_info.uses) {
auto bb = use->getParent();
if (!bbs.insert(bb).second)
continue;
assert(lifetime_stack.empty());
Lifetime::Frame cur{bb};
while (true) {
assert(cur.p_cur != cur.p_end);
auto pred = *cur.p_cur;
++cur.p_cur;
if (bbs.insert(pred).second) {
if (cur.p_cur != cur.p_end)
lifetime_stack.push_back(cur);
cur = Lifetime::Frame(pred);
}
if (cur.p_cur == cur.p_end) {
if (lifetime_stack.empty())
break;
cur = lifetime_stack.back();
lifetime_stack.pop_back();
}
}
}
#ifndef JL_NDEBUG
for (auto bb: bbs) {
if (bb == def_bb)
continue;
if (DT.dominates(orig, bb))
continue;
auto F = bb->getParent();
llvm_dump(F);
llvm_dump(orig);
jl_safe_printf("Does not dominate BB:\n");
llvm_dump(bb);
abort();
}
#endif
// Record extra BBs that contain invisible uses.
SmallSet<BasicBlock*, 8> extra_use;
SmallVector<DomTreeNodeBase<BasicBlock>*, 8> dominated;
for (auto preserve: use_info.preserves) {
for (auto RN = DT.getNode(preserve->getParent()); RN;
RN = dominated.empty() ? nullptr : dominated.pop_back_val()) {
for (auto N: *RN) {
auto bb = N->getBlock();
if (extra_use.count(bb))
continue;
bool ended = false;
for (auto end: preserve->users()) {
auto end_bb = cast<Instruction>(end)->getParent();
auto end_node = DT.getNode(end_bb);
if (end_bb == bb || (end_node && DT.dominates(end_node, N))) {
ended = true;
break;
}
}
if (ended)
continue;
bbs.insert(bb);
extra_use.insert(bb);
dominated.push_back(N);
}
}
assert(dominated.empty());
}
// For each BB, find the first instruction(s) where the allocation is possibly dead.
// If all successors are live, then there isn't one.
// If all successors are dead, then it's the first instruction after the last use
// within the BB.
// If some successors are live and others are dead, it's the first instruction in
// the successors that are dead.
std::vector<Instruction*> first_dead;
for (auto bb: bbs) {
bool has_use = false;
for (auto succ: successors(bb)) {
// def_bb is the only bb in bbs that's not dominated by orig
if (succ != def_bb && bbs.count(succ)) {
has_use = true;
break;
}
}
if (has_use) {
for (auto succ: successors(bb)) {
if (!bbs.count(succ)) {
first_dead.push_back(&*succ->begin());
}
}
}
else if (extra_use.count(bb)) {
first_dead.push_back(bb->getTerminator());
}
else {
for (auto it = bb->rbegin(), end = bb->rend(); it != end; ++it) {
if (use_info.uses.count(&*it)) {
--it;
first_dead.push_back(&*it);
break;
}
}
}
}
bbs.clear();
// There can/need only be one lifetime.end for each allocation in each bb, use bbs
// to record that.
// Iterate through the first dead and find the first safepoint following each of them.
while (!first_dead.empty()) {
auto I = first_dead.back();
first_dead.pop_back();
auto bb = I->getParent();
if (!bbs.insert(bb).second)
continue;
if (I == &*bb->begin()) {
// There's no use in or after this bb. If this bb is not dominated by
// the def then it has to be dead on entering this bb.
// Otherwise, there could be use that we don't track
// before hitting the next safepoint.
if (!DT.dominates(orig, bb)) {
insertLifetimeEnd(ptr, sz, &*bb->getFirstInsertionPt());
continue;
}
else if (auto insert = getFirstSafepoint(bb)) {
insertLifetimeEnd(ptr, sz, insert);
continue;
}
}
else {
assert(bb == def_bb || DT.dominates(orig, I));
BasicBlock::iterator it(I);
BasicBlock::iterator end = bb->end();
bool safepoint_found = false;
for (; it != end; ++it) {
auto insert = &*it;
if (isSafepoint(insert)) {
insertLifetimeEnd(ptr, sz, insert);
safepoint_found = true;
break;
}
}
if (safepoint_found) {
continue;
}
}
for (auto succ: successors(bb)) {
first_dead.push_back(&*succ->begin());
}
}
}
void Optimizer::replaceIntrinsicUseWith(IntrinsicInst *call, Intrinsic::ID ID,
Instruction *orig_i, Instruction *new_i)
{
auto nargs = call->getNumArgOperands();
SmallVector<Value*, 8> args(nargs);
SmallVector<Type*, 8> argTys(nargs);
for (unsigned i = 0; i < nargs; i++) {
auto arg = call->getArgOperand(i);
args[i] = arg == orig_i ? new_i : arg;
argTys[i] = args[i]->getType();
}
auto oldfType = call->getFunctionType();
auto newfType = FunctionType::get(
oldfType->getReturnType(),
makeArrayRef(argTys).slice(0, oldfType->getNumParams()),
oldfType->isVarArg());
// Accumulate an array of overloaded types for the given intrinsic
// and compute the new name mangling schema
SmallVector<Type*, 4> overloadTys;
{
SmallVector<Intrinsic::IITDescriptor, 8> Table;
getIntrinsicInfoTableEntries(ID, Table);
ArrayRef<Intrinsic::IITDescriptor> TableRef = Table;
auto res = Intrinsic::matchIntrinsicSignature(newfType, TableRef, overloadTys);
assert(res == Intrinsic::MatchIntrinsicTypes_Match);
(void)res;
bool matchvararg = Intrinsic::matchIntrinsicVarArg(newfType->isVarArg(), TableRef);
assert(!matchvararg);
(void)matchvararg;
}
auto newF = Intrinsic::getDeclaration(call->getModule(), ID, overloadTys);
assert(newF->getFunctionType() == newfType);
newF->setCallingConv(call->getCallingConv());
auto newCall = CallInst::Create(newF, args, "", call);
newCall->setTailCallKind(call->getTailCallKind());
auto old_attrs = call->getAttributes();
newCall->setAttributes(AttributeList::get(pass.getLLVMContext(), old_attrs.getFnAttributes(),
old_attrs.getRetAttributes(), {}));
newCall->setDebugLoc(call->getDebugLoc());
call->replaceAllUsesWith(newCall);
call->eraseFromParent();
}
// This function should not erase any safepoint so that the lifetime marker can find and cache
// all the original safepoints.
void Optimizer::moveToStack(CallInst *orig_inst, size_t sz, bool has_ref)
{
auto tag = orig_inst->getArgOperand(2);
removed.push_back(orig_inst);
// The allocation does not escape or get used in a phi node so none of the derived
// SSA from it are live when we run the allocation again.
// It is now safe to promote the allocation to an entry block alloca.
size_t align = 1;
// TODO: This is overly conservative. May want to instead pass this as a
// parameter to the allocation function directly.
if (sz > 1)
align = MinAlign(JL_SMALL_BYTE_ALIGNMENT, NextPowerOf2(sz));
// No debug info for prolog instructions
IRBuilder<> prolog_builder(&F.getEntryBlock().front());
AllocaInst *buff;
Instruction *ptr;
if (sz == 0) {
buff = prolog_builder.CreateAlloca(pass.T_int8, ConstantInt::get(pass.T_int64, 0));
ptr = buff;
}
else if (has_ref) {
// Allocate with the correct type so that the GC frame lowering pass will
// treat this as a non-mem2reg'd alloca
// The ccall root and GC preserve handling below makes sure that
// the alloca isn't optimized out.
buff = prolog_builder.CreateAlloca(pass.T_prjlvalue);
buff->setAlignment(Align(align));
ptr = cast<Instruction>(prolog_builder.CreateBitCast(buff, pass.T_pint8));
}
else {
Type *buffty;
if (pass.DL->isLegalInteger(sz * 8))
buffty = Type::getIntNTy(pass.getLLVMContext(), sz * 8);
else
buffty = ArrayType::get(Type::getInt8Ty(pass.getLLVMContext()), sz);
buff = prolog_builder.CreateAlloca(buffty);
buff->setAlignment(Align(align));
ptr = cast<Instruction>(prolog_builder.CreateBitCast(buff, pass.T_pint8));
}
insertLifetime(ptr, ConstantInt::get(pass.T_int64, sz), orig_inst);
auto new_inst = cast<Instruction>(prolog_builder.CreateBitCast(ptr, pass.T_pjlvalue));
new_inst->takeName(orig_inst);
auto simple_replace = [&] (Instruction *orig_i, Instruction *new_i) {
if (orig_i->user_empty()) {
if (orig_i != orig_inst)
orig_i->eraseFromParent();
return true;
}
Type *orig_t = orig_i->getType();
Type *new_t = new_i->getType();
if (orig_t == new_t) {
orig_i->replaceAllUsesWith(new_i);
if (orig_i != orig_inst)
orig_i->eraseFromParent();
return true;
}
return false;
};
if (simple_replace(orig_inst, new_inst))
return;
assert(replace_stack.empty());
ReplaceUses::Frame cur{orig_inst, new_inst};
auto finish_cur = [&] () {
assert(cur.orig_i->user_empty());
if (cur.orig_i != orig_inst) {
cur.orig_i->eraseFromParent();
}
};
auto push_frame = [&] (Instruction *orig_i, Instruction *new_i) {
if (simple_replace(orig_i, new_i))
return;
replace_stack.push_back(cur);
cur = {orig_i, new_i};
};
// Both `orig_i` and `new_i` should be pointer of the same type
// but possibly different address spaces. `new_i` is always in addrspace 0.
auto replace_inst = [&] (Instruction *user) {
Instruction *orig_i = cur.orig_i;
Instruction *new_i = cur.new_i;
if (isa<LoadInst>(user) || isa<StoreInst>(user)) {
user->replaceUsesOfWith(orig_i, new_i);
}
else if (auto call = dyn_cast<CallInst>(user)) {
auto callee = call->getCalledOperand();
if (pass.pointer_from_objref_func == callee) {
call->replaceAllUsesWith(new_i);
call->eraseFromParent();
return;
}
if (pass.typeof_func == callee) {
call->replaceAllUsesWith(tag);
call->eraseFromParent();
return;
}
// Also remove the preserve intrinsics so that it can be better optimized.
if (pass.gc_preserve_begin_func == callee) {
if (has_ref) {
call->replaceUsesOfWith(orig_i, buff);
}
else {
removeGCPreserve(call, orig_i);
}
return;
}
if (pass.write_barrier_func == callee) {
call->eraseFromParent();
return;
}
if (auto intrinsic = dyn_cast<IntrinsicInst>(call)) {
if (Intrinsic::ID ID = intrinsic->getIntrinsicID()) {
replaceIntrinsicUseWith(intrinsic, ID, orig_i, new_i);
return;
}
}
// remove from operand bundle
Value *replace = has_ref ? (Value*)buff : Constant::getNullValue(orig_i->getType());
user->replaceUsesOfWith(orig_i, replace);
}
else if (isa<AddrSpaceCastInst>(user) || isa<BitCastInst>(user)) {
auto cast_t = PointerType::get(cast<PointerType>(user->getType())->getElementType(),
0);
auto replace_i = new_i;
Type *new_t = new_i->getType();
if (cast_t != new_t) {
replace_i = new BitCastInst(replace_i, cast_t, "", user);
replace_i->setDebugLoc(user->getDebugLoc());
replace_i->takeName(user);
}
push_frame(user, replace_i);
}
else if (auto gep = dyn_cast<GetElementPtrInst>(user)) {
SmallVector<Value *, 4> IdxOperands(gep->idx_begin(), gep->idx_end());
auto new_gep = GetElementPtrInst::Create(gep->getSourceElementType(),
new_i, IdxOperands,
gep->getName(), gep);
new_gep->setIsInBounds(gep->isInBounds());
new_gep->takeName(gep);
new_gep->copyMetadata(*gep);
push_frame(gep, new_gep);
}
else {
abort();
}
};
while (true) {
replace_inst(cast<Instruction>(*cur.orig_i->user_begin()));
while (cur.orig_i->use_empty()) {
finish_cur();
if (replace_stack.empty())
return;
cur = replace_stack.back();
replace_stack.pop_back();
}
}
}
// This function should not erase any safepoint so that the lifetime marker can find and cache
// all the original safepoints.
void Optimizer::removeAlloc(CallInst *orig_inst)
{
auto tag = orig_inst->getArgOperand(2);
removed.push_back(orig_inst);
auto simple_remove = [&] (Instruction *orig_i) {
if (orig_i->user_empty()) {
if (orig_i != orig_inst)
orig_i->eraseFromParent();
return true;
}
return false;
};
if (simple_remove(orig_inst))
return;
assert(replace_stack.empty());
ReplaceUses::Frame cur{orig_inst, nullptr};
auto finish_cur = [&] () {
assert(cur.orig_i->user_empty());
if (cur.orig_i != orig_inst) {
cur.orig_i->eraseFromParent();
}
};
auto push_frame = [&] (Instruction *orig_i) {
if (simple_remove(orig_i))
return;
replace_stack.push_back(cur);
cur = {orig_i, nullptr};
};
auto remove_inst = [&] (Instruction *user) {
Instruction *orig_i = cur.orig_i;
if (auto store = dyn_cast<StoreInst>(user)) {
// All stores are known to be dead.
// The stored value might be an gc pointer in which case deleting the object
// might open more optimization opportunities.
if (auto stored_inst = dyn_cast<Instruction>(store->getValueOperand()))
pushInstruction(stored_inst);
user->eraseFromParent();
return;
}
else if (auto call = dyn_cast<CallInst>(user)) {
auto callee = call->getCalledOperand();
if (pass.gc_preserve_begin_func == callee) {
removeGCPreserve(call, orig_i);
return;
}
if (pass.typeof_func == callee) {
call->replaceAllUsesWith(tag);
call->eraseFromParent();
return;
}
if (pass.write_barrier_func == callee) {
call->eraseFromParent();
return;
}
if (auto II = dyn_cast<IntrinsicInst>(call)) {
auto id = II->getIntrinsicID();
if (id == Intrinsic::memset || id == Intrinsic::lifetime_start ||
id == Intrinsic::lifetime_end || isa<DbgInfoIntrinsic>(II)) {
call->eraseFromParent();
return;
}
}
// remove from operand bundle
user->replaceUsesOfWith(orig_i, Constant::getNullValue(orig_i->getType()));
}
else if (isa<AddrSpaceCastInst>(user) || isa<BitCastInst>(user) ||
isa<GetElementPtrInst>(user)) {
push_frame(user);
}
else {
abort();
}
};
while (true) {
remove_inst(cast<Instruction>(*cur.orig_i->user_begin()));
while (cur.orig_i->use_empty()) {
finish_cur();
if (replace_stack.empty())
return;
cur = replace_stack.back();
replace_stack.pop_back();
}
}
}
// Unable to optimize out the allocation, do store to load forwarding on the tag instead.
void Optimizer::optimizeTag(CallInst *orig_inst)
{
auto tag = orig_inst->getArgOperand(2);
// `julia.typeof` is only legal on the original pointer, no need to scan recursively
size_t last_deleted = removed.size();
for (auto user: orig_inst->users()) {
if (auto call = dyn_cast<CallInst>(user)) {
auto callee = call->getCalledOperand();
if (pass.typeof_func == callee) {
call->replaceAllUsesWith(tag);
// Push to the removed instructions to trigger `finalize` to
// return the correct result.
// Also so that we don't have to worry about iterator invalidation...
removed.push_back(call);
}
}
}
while (last_deleted < removed.size())
removed[last_deleted++]->replaceUsesOfWith(orig_inst, UndefValue::get(orig_inst->getType()));
}
void Optimizer::splitOnStack(CallInst *orig_inst)
{
auto tag = orig_inst->getArgOperand(2);
removed.push_back(orig_inst);
IRBuilder<> prolog_builder(&F.getEntryBlock().front());
struct SplitSlot {
AllocaInst *slot;
bool isref;
uint32_t offset;
uint32_t size;
};
SmallVector<SplitSlot,8> slots;
for (auto memop: use_info.memops) {
auto offset = memop.first;
auto &field = memop.second;
// If the field has no reader and is not a object reference field that we
// need to preserve at some point, there's no need to allocate the field.
if (!field.hasload && (!field.hasobjref || !use_info.haspreserve))
continue;
SplitSlot slot{nullptr, field.hasobjref, offset, field.size};
Type *allocty;
if (field.hasobjref) {
allocty = pass.T_prjlvalue;
}
else if (field.elty && !field.multiloc) {
allocty = field.elty;
}
else if (pass.DL->isLegalInteger(field.size * 8)) {
allocty = Type::getIntNTy(pass.getLLVMContext(), field.size * 8);
} else {
allocty = ArrayType::get(Type::getInt8Ty(pass.getLLVMContext()), field.size);
}
slot.slot = prolog_builder.CreateAlloca(allocty);
insertLifetime(prolog_builder.CreateBitCast(slot.slot, pass.T_pint8),
ConstantInt::get(pass.T_int64, field.size), orig_inst);
slots.push_back(std::move(slot));
}
const auto nslots = slots.size();
auto find_slot = [&] (uint32_t offset) {
if (offset == 0)
return 0u;
unsigned lb = 0;
unsigned ub = slots.size();
while (lb + 1 < ub) {
unsigned mid = (lb + ub) / 2;
if (slots[mid].offset <= offset) {
lb = mid;
}
else {
ub = mid;
}
}
return lb;
};
auto simple_replace = [&] (Instruction *orig_i) {
if (orig_i->user_empty()) {
if (orig_i != orig_inst)
orig_i->eraseFromParent();
return true;
}
return false;
};
if (simple_replace(orig_inst))
return;
assert(replace_stack.empty());
ReplaceUses::Frame cur{orig_inst, uint32_t(0)};
auto finish_cur = [&] () {
assert(cur.orig_i->user_empty());
if (cur.orig_i != orig_inst) {
cur.orig_i->eraseFromParent();
}
};
auto push_frame = [&] (Instruction *orig_i, uint32_t offset) {
if (simple_replace(orig_i))
return;
replace_stack.push_back(cur);
cur = {orig_i, offset};
};
auto slot_gep = [&] (SplitSlot &slot, uint32_t offset, Type *elty, IRBuilder<> &builder) {
assert(slot.offset <= offset);
offset -= slot.offset;
auto size = pass.DL->getTypeAllocSize(elty);
Value *addr;
if (offset % size == 0) {
addr = builder.CreateBitCast(slot.slot, elty->getPointerTo());
if (offset != 0) {
addr = builder.CreateConstInBoundsGEP1_32(elty, addr, offset / size);
}
}
else {
addr = builder.CreateBitCast(slot.slot, pass.T_pint8);
addr = builder.CreateConstInBoundsGEP1_32(pass.T_int8, addr, offset);
addr = builder.CreateBitCast(addr, elty->getPointerTo());
}
return addr;
};
auto replace_inst = [&] (Use *use) {
Instruction *user = cast<Instruction>(use->getUser());
Instruction *orig_i = cur.orig_i;
uint32_t offset = cur.offset;
if (auto load = dyn_cast<LoadInst>(user)) {
auto slot_idx = find_slot(offset);
auto &slot = slots[slot_idx];
assert(slot.offset <= offset && slot.offset + slot.size >= offset);
IRBuilder<> builder(load);
Value *val;
Type *load_ty = load->getType();
LoadInst *newload;
if (slot.isref) {
assert(slot.offset == offset);
newload = builder.CreateLoad(pass.T_prjlvalue, slot.slot);
// Assume the addrspace is correct.
val = builder.CreateBitCast(newload, load_ty);
}
else {
newload = builder.CreateLoad(load_ty, slot_gep(slot, offset, load_ty, builder));
val = newload;
}
// TODO: should we use `load->clone()`, or manually copy any other metadata?
newload->setAlignment(load->getAlign());
// since we're moving heap-to-stack, it is safe to downgrade the atomic level to NotAtomic
newload->setOrdering(AtomicOrdering::NotAtomic);
load->replaceAllUsesWith(val);
load->eraseFromParent();
return;
}
else if (auto store = dyn_cast<StoreInst>(user)) {
if (auto stored_inst = dyn_cast<Instruction>(store->getValueOperand()))
pushInstruction(stored_inst);
auto slot_idx = find_slot(offset);
auto &slot = slots[slot_idx];
if (slot.offset > offset || slot.offset + slot.size <= offset) {
store->eraseFromParent();
return;
}
IRBuilder<> builder(store);
auto store_val = store->getValueOperand();
auto store_ty = store_val->getType();
StoreInst *newstore;
if (slot.isref) {
assert(slot.offset == offset);
if (!isa<PointerType>(store_ty)) {
store_val = builder.CreateBitCast(store_val, pass.T_size);
store_val = builder.CreateIntToPtr(store_val, pass.T_pjlvalue);
store_ty = pass.T_pjlvalue;
}
else {
store_ty = cast<PointerType>(pass.T_pjlvalue)->getElementType()
->getPointerTo(cast<PointerType>(store_ty)->getAddressSpace());
store_val = builder.CreateBitCast(store_val, store_ty);
}
if (cast<PointerType>(store_ty)->getAddressSpace() != AddressSpace::Tracked)
store_val = builder.CreateAddrSpaceCast(store_val, pass.T_prjlvalue);
newstore = builder.CreateStore(store_val, slot.slot);
}
else {
newstore = builder.CreateStore(store_val, slot_gep(slot, offset, store_ty, builder));
}
// TODO: should we use `store->clone()`, or manually copy any other metadata?
newstore->setAlignment(store->getAlign());
// since we're moving heap-to-stack, it is safe to downgrade the atomic level to NotAtomic
newstore->setOrdering(AtomicOrdering::NotAtomic);
store->eraseFromParent();
return;
}
else if (isa<AtomicCmpXchgInst>(user) || isa<AtomicRMWInst>(user)) {
auto slot_idx = find_slot(offset);
auto &slot = slots[slot_idx];
assert(slot.offset <= offset && slot.offset + slot.size >= offset);
IRBuilder<> builder(user);
Value *newptr;
if (slot.isref) {
assert(slot.offset == offset);
newptr = slot.slot;
}
else {
Value *Val = isa<AtomicCmpXchgInst>(user) ? cast<AtomicCmpXchgInst>(user)->getNewValOperand() : cast<AtomicRMWInst>(user)->getValOperand();
newptr = slot_gep(slot, offset, Val->getType(), builder);
}
*use = newptr;
}
else if (auto call = dyn_cast<CallInst>(user)) {
auto callee = call->getCalledOperand();
assert(callee); // makes it clear for clang analyser that `callee` is not NULL
if (auto intrinsic = dyn_cast<IntrinsicInst>(call)) {
if (Intrinsic::ID id = intrinsic->getIntrinsicID()) {
if (id == Intrinsic::memset) {
IRBuilder<> builder(call);
auto val_arg = cast<ConstantInt>(call->getArgOperand(1));
auto size_arg = cast<ConstantInt>(call->getArgOperand(2));
uint8_t val = val_arg->getLimitedValue();
uint32_t size = size_arg->getLimitedValue();
for (unsigned idx = find_slot(offset); idx < nslots; idx++) {
auto &slot = slots[idx];
if (slot.offset + slot.size <= offset || slot.offset >= offset + size)
break;
if (slot.isref) {
assert(slot.offset >= offset &&
slot.offset + slot.size <= offset + size);
Constant *ptr;
if (val == 0) {
ptr = Constant::getNullValue(pass.T_prjlvalue);
}
else {
uint64_t intval;
memset(&intval, val, 8);
Constant *val = ConstantInt::get(pass.T_size, intval);
val = ConstantExpr::getIntToPtr(val, pass.T_pjlvalue);
ptr = ConstantExpr::getAddrSpaceCast(val, pass.T_prjlvalue);
}
StoreInst *store = builder.CreateAlignedStore(ptr, slot.slot, Align(sizeof(void*)));
store->setOrdering(AtomicOrdering::NotAtomic);
continue;
}
auto ptr8 = builder.CreateBitCast(slot.slot, pass.T_pint8);
if (offset > slot.offset)
ptr8 = builder.CreateConstInBoundsGEP1_32(pass.T_int8, ptr8,
offset - slot.offset);
auto sub_size = std::min(slot.offset + slot.size, offset + size) -
std::max(offset, slot.offset);
// TODO: alignment computation
builder.CreateMemSet(ptr8, val_arg, sub_size, MaybeAlign(0));
}
call->eraseFromParent();
return;
}
call->eraseFromParent();
return;
}
}
if (pass.typeof_func == callee) {
call->replaceAllUsesWith(tag);
call->eraseFromParent();
return;
}
if (pass.write_barrier_func == callee) {
call->eraseFromParent();
return;
}
if (pass.gc_preserve_begin_func == callee) {
SmallVector<Value*,8> operands;
for (auto &arg: call->arg_operands()) {
if (arg.get() == orig_i || isa<Constant>(arg.get()))
continue;
operands.push_back(arg.get());
}
IRBuilder<> builder(call);
for (auto &slot: slots) {
if (!slot.isref)
continue;
LoadInst *ref = builder.CreateAlignedLoad(pass.T_prjlvalue, slot.slot, Align(sizeof(void*)));
// since we're moving heap-to-stack, it is safe to downgrade the atomic level to NotAtomic
ref->setOrdering(AtomicOrdering::NotAtomic);
operands.push_back(ref);
}
auto new_call = builder.CreateCall(pass.gc_preserve_begin_func, operands);
new_call->takeName(call);
new_call->setAttributes(call->getAttributes());
call->replaceAllUsesWith(new_call);
call->eraseFromParent();
return;
}
// remove from operand bundle
assert(call->isBundleOperand(use->getOperandNo()));
assert(call->getOperandBundleForOperand(use->getOperandNo()).getTagName() ==
"jl_roots");
SmallVector<OperandBundleDef,2> bundles;
call->getOperandBundlesAsDefs(bundles);
for (auto &bundle: bundles) {
if (bundle.getTag() != "jl_roots")
continue;
std::vector<Value*> operands;
for (auto op: bundle.inputs()) {
if (op == orig_i || isa<Constant>(op))
continue;
operands.push_back(op);
}
IRBuilder<> builder(call);
for (auto &slot: slots) {
if (!slot.isref)
continue;
LoadInst *ref = builder.CreateAlignedLoad(pass.T_prjlvalue, slot.slot, Align(sizeof(void*)));
// since we're moving heap-to-stack, it is safe to downgrade the atomic level to NotAtomic
ref->setOrdering(AtomicOrdering::NotAtomic);
operands.push_back(ref);
}
bundle = OperandBundleDef("jl_roots", std::move(operands));
break;
}
auto new_call = CallInst::Create(call, bundles, call);
new_call->takeName(call);
call->replaceAllUsesWith(new_call);
call->eraseFromParent();
return;
}
else if (isa<AddrSpaceCastInst>(user) || isa<BitCastInst>(user)) {
push_frame(user, offset);
}
else if (auto gep = dyn_cast<GetElementPtrInst>(user)) {
APInt apoffset(sizeof(void*) * 8, offset, true);
gep->accumulateConstantOffset(*pass.DL, apoffset);
push_frame(gep, apoffset.getLimitedValue());
}
else {
abort();
}
};
while (true) {
replace_inst(&*cur.orig_i->use_begin());
while (cur.orig_i->use_empty()) {
finish_cur();
if (replace_stack.empty())
goto cleanup;
cur = replace_stack.back();
replace_stack.pop_back();
}
}
cleanup:
for (auto &slot: slots) {
if (!slot.isref)
continue;
PromoteMemToReg({slot.slot}, getDomTree());
}
}
bool AllocOpt::doInitialization(Module &M)
{
initAll(M);
if (!alloc_obj_func)
return false;
DL = &M.getDataLayout();
T_int64 = Type::getInt64Ty(getLLVMContext());
lifetime_start = Intrinsic::getDeclaration(&M, Intrinsic::lifetime_start, { T_pint8 });
lifetime_end = Intrinsic::getDeclaration(&M, Intrinsic::lifetime_end, { T_pint8 });
return true;
}
bool AllocOpt::runOnFunction(Function &F)
{
if (!alloc_obj_func)
return false;
Optimizer optimizer(F, *this);
optimizer.initialize();
optimizer.optimizeAll();
return optimizer.finalize();
}
char AllocOpt::ID = 0;
static RegisterPass<AllocOpt> X("AllocOpt", "Promote heap allocation to stack",
false /* Only looks at CFG */,
false /* Analysis Pass */);
}
Pass *createAllocOptPass()
{
return new AllocOpt();
}
extern "C" JL_DLLEXPORT void LLVMExtraAddAllocOptPass(LLVMPassManagerRef PM)
{
unwrap(PM)->add(createAllocOptPass());
}
|
/*
* BidirectionalBFS.hpp
*
* Created on: 14.06.2019
* Author: Eugenio Angriman <angrimae@hu-berlin.de>
*/
#ifndef NETWORKIT_DISTANCE_BIDIRECTIONAL_BFS_HPP_
#define NETWORKIT_DISTANCE_BIDIRECTIONAL_BFS_HPP_
#include <queue>
#include <networkit/distance/STSP.hpp>
namespace NetworKit {
/*
* @ingroup distance
* Implements a bidirectional breadth-first search on a graph from two given source and target
* nodes. Explores the graph from both the source and target nodes until the two explorations meet.
*/
class BidirectionalBFS final : public STSP {
public:
// Inherit the constructors of STSP.
using STSP::STSP;
/*
* Perform a bidirectional BFS from the given source and target nodes.
*/
void run() override;
/*
* Returns the distance (i.e., number of hops) from the source to the target node.
*
* @return count Number of hops from the source to the target node.
*/
count getHops() {
assureFinished();
return stDist;
}
edgeweight getDistance() const override {
assureFinished();
return static_cast<edgeweight>(stDist);
}
private:
count stDist;
std::vector<uint8_t> visited;
uint8_t ts = 0;
static constexpr uint8_t ballMask = uint8_t(1) << 7;
std::queue<node> sQueue, sQueueNext, tQueue, tQueueNext;
};
} // namespace NetworKit
#endif // NETWORKIT_DISTANCE_BIDIRECTIONAL_BFS_HPP_
|
#include "cApp.h"
wxIMPLEMENT_APP(cApp);
cApp::cApp() {
}
cApp::~cApp() {
}
bool cApp::OnInit() {
m_frame1 = new cMain();
m_frame1->Show();
return true;
}
|
/*
Copyright (C) 2013 Jolla Ltd.
Contact: Thomas Perl <thomas.perl@jollamobile.com>
All rights reserved.
You may use this file under the terms of BSD license as follows:
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 Jolla Ltd 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 HOLDERS 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.
*/
#ifdef QT_QML_DEBUG
#include <QtQuick>
#endif
#include <QtQuick>
#include <sailfishapp.h>
#include "thumbnailprovider.h"
#include "settings.h"
#include "filelist.h"
#include "fileengine.h"
#include "covermodel.h"
int main(int argc, char *argv[])
{
// SailfishApp::main() will display "qml/template.qml", if you need more
// control over initialization, you can use:
//
// - SailfishApp::application(int, char *[]) to get the QGuiApplication *
// - SailfishApp::createView() to get a new QQuickView * instance
// - SailfishApp::pathTo(QString) to get a QUrl to a resource file
//
// To display the view, call "show()" (will show fullscreen on device).
qRegisterMetaType<QList<FileInfoEntry*> >();
QGuiApplication *app = SailfishApp::application(argc, argv);
QQuickView *view = SailfishApp::createView();
// Add image providers and C++ classes
view->engine()->addImageProvider(QLatin1String("thumbnail"), new ThumbnailProvider);
FileEngine fileEngine;
view->engine()->rootContext()->setContextProperty("engine", &fileEngine);
view->engine()->rootContext()->setContextProperty("fileList", fileEngine.fileList);
view->engine()->rootContext()->setContextProperty("fileInfo", fileEngine.fileInfo);
view->engine()->rootContext()->setContextProperty("fileProcess", fileEngine.fileProcess);
view->engine()->rootContext()->setContextProperty("clipboard", fileEngine.clipboard);
view->engine()->rootContext()->setContextProperty("settings", fileEngine.settings);
view->engine()->rootContext()->setContextProperty("coverModel", fileEngine.coverModel);
// Show the application
view->setSource(SailfishApp::pathTo("qml/Filetug.qml"));
view->show();
return app->exec();
}
|
/*
pbrt source code is Copyright(c) 1998-2016
Matt Pharr, Greg Humphreys, and Wenzel Jakob.
This file is part of pbrt.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// core/scene.cpp*
#include "scene.h"
#include "stats.h"
namespace pbrt {
STAT_COUNTER("Intersections/Regular ray intersection tests",
nIntersectionTests);
STAT_COUNTER("Intersections/Shadow ray intersection tests", nShadowTests);
// Scene Method Definitions
bool Scene::Intersect(const Ray &ray, SurfaceInteraction *isect) const {
++nIntersectionTests;
DCHECK_NE(ray.d, Vector3f(0,0,0));
//////////////////////
// PrISE-3D Updates //
//////////////////////
// get intersection information
bool results = aggregate->Intersect(ray, isect);
ray.nn = isect->n;
ray.p = isect->p;
ray.u = isect->uv.x;
ray.v = isect->uv.y;
// return results;
return results;
//////////////////////////
// End PrISE-3D Updates //
//////////////////////////
}
bool Scene::IntersectP(const Ray &ray) const {
++nShadowTests;
DCHECK_NE(ray.d, Vector3f(0,0,0));
return aggregate->IntersectP(ray);
}
bool Scene::IntersectTr(Ray ray, Sampler &sampler, SurfaceInteraction *isect,
Spectrum *Tr) const {
*Tr = Spectrum(1.f);
while (true) {
bool hitSurface = Intersect(ray, isect);
// Accumulate beam transmittance for ray segment
if (ray.medium) *Tr *= ray.medium->Tr(ray, sampler);
// Initialize next ray segment or terminate transmittance computation
if (!hitSurface) return false;
if (isect->primitive->GetMaterial() != nullptr) return true;
ray = isect->SpawnRay(ray.d);
}
}
} // namespace pbrt
|
// Problem: https://leetcode.com/problems/search-insert-position/
//
// Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
//
// You may assume no duplicates in the array.
//
// Example 1:
// Input: [1,3,5,6], 5
// Output: 2
//
// Example 2:
// Input: [1,3,5,6], 2
// Output: 1
//
// Example 3:
// Input: [1,3,5,6], 7
// Output: 4
//
// Example 4:
// Input: [1,3,5,6], 0
// Output: 0
class Solution {
public:
int searchInsert(vector<int>& A, int target) {
int n = A.size();
if(n < 1) {
return 0;
}
int low = 0;
int high = n-1;
int mid;
int pos;
while(low <= high) {
mid = low + (high-low)/2;
if(A[mid] == target) {
return mid;
} else if(A[mid] > target) {
high = mid - 1;
pos = mid;
} else {
low = mid + 1;
pos = mid + 1;
}
}
return pos;
}
};
|
//*****************************************************************************
// Copyright 2017-2021 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#include <algorithm>
#include <cctype>
#include <functional>
#include <locale>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
#include "dict_attribute_visitor.hpp"
#include "ngraph/check.hpp"
#include "ngraph/except.hpp"
#include "ngraph/node.hpp"
#include "ngraph/op/util/op_types.hpp"
#include "ngraph/opsets/opset.hpp"
#include "node_factory.hpp"
#include "tensor_iterator_builder.hpp"
namespace py = pybind11;
namespace
{
class NodeFactory
{
public:
NodeFactory() {}
NodeFactory(const std::string& opset_name)
: m_opset{get_opset(opset_name)}
{
}
std::shared_ptr<ngraph::Node> create(const std::string op_type_name,
const ngraph::OutputVector& arguments,
const py::dict& attributes = py::dict())
{
std::shared_ptr<ngraph::Node> op_node =
std::shared_ptr<ngraph::Node>(m_opset.create(op_type_name));
NGRAPH_CHECK(op_node != nullptr, "Couldn't create operator: ", op_type_name);
NGRAPH_CHECK(!ngraph::op::is_constant(op_node),
"Currently NodeFactory doesn't support Constant node: ",
op_type_name);
if (op_type_name == "TensorIterator")
{
// XXX: How to differentiate opsets?
return util::TensorIteratorBuilder(as_node_vector(arguments), attributes)
.configure(std::static_pointer_cast<ngraph::op::TensorIterator>(op_node));
}
util::DictAttributeDeserializer visitor(attributes);
op_node->set_arguments(arguments);
op_node->visit_attributes(visitor);
op_node->constructor_validate_and_infer_types();
return op_node;
}
private:
const ngraph::OpSet& get_opset(std::string opset_ver)
{
std::locale loc;
std::transform(opset_ver.begin(), opset_ver.end(), opset_ver.begin(), [&loc](char c) {
return std::tolower(c, loc);
});
using OpsetFunction = std::function<const ngraph::OpSet&()>;
static const std::map<std::string, OpsetFunction> s_opsets{
{"opset1", OpsetFunction(ngraph::get_opset1)},
{"opset2", OpsetFunction(ngraph::get_opset2)},
{"opset3", OpsetFunction(ngraph::get_opset3)},
{"opset4", OpsetFunction(ngraph::get_opset4)},
{"opset5", OpsetFunction(ngraph::get_opset5)},
{"opset6", OpsetFunction(ngraph::get_opset6)},
};
auto it = s_opsets.find(opset_ver);
if (it == s_opsets.end())
{
throw ngraph::ngraph_error("Unsupported opset version requested.");
}
return it->second();
}
const ngraph::OpSet& m_opset{ngraph::get_opset6()};
};
}
void regclass_pyngraph_NodeFactory(py::module m)
{
py::class_<NodeFactory> node_factory(m, "NodeFactory");
node_factory.doc() = "NodeFactory creates nGraph nodes";
node_factory.def(py::init());
node_factory.def(py::init<std::string>());
node_factory.def("create", &NodeFactory::create);
node_factory.def("__repr__", [](const NodeFactory& self) { return "<NodeFactory>"; });
}
|
#include <catch.hpp>
#include <algorithm>
#include <atomic>
#include <thread>
#include <vector>
#include "iris/Agent.hpp"
#include "iris/Parameters.hpp"
#include "iris/Types.hpp"
#include "iris/Threading.hpp"
#include "iris/Utils.hpp"
typedef std::vector<iris::AgentID> IdVector;
TEST_CASE("Verify that std::iota works as expected.")
{
SECTION("Test simple range [a, b).")
{
const auto a = 5;
const auto b = 15;
auto vec = IdVector{};
auto expected = IdVector{5, 6, 7, 8, 9, 10, 11, 12, 13, 14};
vec.resize(b - a);
CHECK(vec.capacity() == 10);
std::iota(vec.begin(), vec.end(), a);
CHECK(vec == expected);
}
}
TEST_CASE("Verify spread algorithm works correctly.")
{
SECTION("Test incorrect range causes an exception.")
{
using namespace iris;
using namespace iris::types;
using namespace std;
const auto behavior = Uint32List{};
std::atomic<uint32> completion = {0};
auto params = Parameters();
std::atomic<uint64> time = {0};
auto worker = ThreadWorker(completion, time);
CHECK_THROWS(worker.initialize(NULL, 3, 2, params, behavior));
CHECK_THROWS(worker.initialize(NULL, 4, 4, params, behavior));
}
SECTION("Test that range is calculated correctly.")
{
using namespace iris;
using namespace iris::types;
const auto totalAgents = 100;
const auto numThreads = 3;
auto result = IdVector{};
const auto expected = IdVector{0, 33, 33, 66, 66, 100};
const auto spread = static_cast<uint32>(totalAgents / numThreads);
CHECK(spread == 33);
for(uint32 i = 0; i < numThreads; i++)
{
const auto lowerBound = static_cast<AgentID>(spread * i);
auto upperBound = static_cast<AgentID>(spread * (i + 1));
if(i >= (numThreads - 1))
{
upperBound = totalAgents;
}
result.push_back(lowerBound);
result.push_back(upperBound);
}
CHECK(result == expected);
}
}
TEST_CASE("Verify that the signal framework works correctly.")
{
SECTION("Check that the atomic-reference idiom works as expected.")
{
using namespace iris::types;
using namespace iris::util;
using namespace std;
atomic<uint32> counter = {0};
atomic<bool> running = {true};
atomic<bool> signal = {false};
const auto duration = std::chrono::nanoseconds(1000);
const auto lambda =
[&counter, duration, &running, &signal](){
while(running)
{
spin(signal, true, duration);
counter = counter + 1;
signal = false;
}
};
thread worker = thread(lambda);
// First round.
CHECK(counter == 0);
CHECK(running == true);
CHECK(signal == false);
// Fire.
signal = true;
spin(signal, false, duration);
// Second round.
CHECK(counter == 1);
CHECK(running == true);
CHECK(signal == false);
// Fire
signal = true;
spin(signal, false, duration);
CHECK(counter == 2);
CHECK(running == true);
CHECK(signal == false);
// Main library does not have this problem.
running = false;
signal = true;
// Clean up.
worker.join();
}
}
TEST_CASE("Verify that ThreadWorkers store and access external values"
" correctly.")
{
using namespace iris;
using namespace iris::types;
using namespace std;
atomic<uint32> complete;
atomic<uint64> time = {1};
Agent* agents = new Agent[3];
ThreadWorker worker(complete, time);
BehaviorList behavList = {2, 3, 2};
Parameters params;
// Set up the parameters.
params.m_lambda = 0.12;
params.m_n = 10000;
params.m_outConnections = 15;
params.m_powerPercent = 0;
params.m_qIn = 3;
params.m_qOut = 2;
params.m_resist = 0.5;
params.m_resistMax = 0.95;
params.m_resistMin = 0.05;
params.m_steps = 2000;
params.m_prob = 0.8;
params.m_recip = 1.0;
SECTION("Ensure behaviors and parameters are copied correctly.")
{
worker.initialize(agents, static_cast<AgentID>(0),
static_cast<AgentID>(3),params,
behavList);
const auto resultBehav = worker.getBehaviorList();
const auto resultParams = worker.getParameters();
CHECK(resultBehav == behavList);
CHECK(resultParams.m_lambda == params.m_lambda);
CHECK(resultParams.m_n == params.m_n);
CHECK(resultParams.m_outConnections == params.m_outConnections);
CHECK(resultParams.m_powerPercent == Approx(params.m_powerPercent));
CHECK(resultParams.m_qIn == params.m_qIn);
CHECK(resultParams.m_qOut == params.m_qOut);
CHECK(resultParams.m_resist == Approx(params.m_resist));
CHECK(resultParams.m_resistMax == Approx(params.m_resistMax));
CHECK(resultParams.m_resistMin == Approx(params.m_resistMin));
CHECK(resultParams.m_steps == params.m_steps);
CHECK(resultParams.m_prob == Approx(params.m_prob));
CHECK(resultParams.m_recip == Approx(params.m_recip));
}
delete[] agents;
}
|
/*
* Copyright (C) 2018-2022 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "shared/source/indirect_heap/indirect_heap.h"
#include "shared/source/memory_manager/memory_manager.h"
#include "shared/test/common/test_macros/test.h"
#include "opencl/source/event/event.h"
#include "opencl/test/unit_test/command_queue/command_queue_fixture.h"
#include "opencl/test/unit_test/fixtures/cl_device_fixture.h"
#include "opencl/test/unit_test/mocks/mock_context.h"
using namespace NEO;
struct OOMSetting {
bool oomCS;
bool oomISH;
};
static OOMSetting oomSettings[] = {
{true, false},
{false, true},
{true, true}};
struct OOMCommandQueueTest : public ClDeviceFixture,
public CommandQueueFixture,
public ::testing::TestWithParam<OOMSetting> {
using CommandQueueFixture::SetUp;
OOMCommandQueueTest() {
}
void SetUp() override {
ClDeviceFixture::SetUp();
context = new MockContext(pClDevice);
CommandQueueFixture::SetUp(context, pClDevice, 0);
const auto &oomSetting = GetParam();
auto oomSize = 10u;
if (oomSetting.oomCS) {
auto &cs = pCmdQ->getCS(oomSize);
// CommandStream may be larger than requested so grab what wasnt requested
cs.getSpace(cs.getAvailableSpace() - oomSize);
ASSERT_EQ(oomSize, cs.getAvailableSpace());
}
if (oomSetting.oomISH) {
auto &ish = pCmdQ->getIndirectHeap(IndirectHeap::Type::DYNAMIC_STATE, oomSize);
// IndirectHeap may be larger than requested so grab what wasnt requested
ish.getSpace(ish.getAvailableSpace() - oomSize);
ASSERT_EQ(oomSize, ish.getAvailableSpace());
}
}
void TearDown() override {
CommandQueueFixture::TearDown();
context->release();
ClDeviceFixture::TearDown();
}
MockContext *context;
};
HWTEST_P(OOMCommandQueueTest, WhenFinishingThenMaxAvailableSpaceIsNotExceeded) {
auto &commandStream = pCmdQ->getCS(1024);
auto &indirectHeap = pCmdQ->getIndirectHeap(IndirectHeap::Type::DYNAMIC_STATE, 10);
auto usedBeforeCS = commandStream.getUsed();
auto usedBeforeISH = indirectHeap.getUsed();
auto retVal = pCmdQ->finish();
auto usedAfterCS = commandStream.getUsed();
auto usedAfterISH = indirectHeap.getUsed();
EXPECT_LE(usedAfterCS - usedBeforeCS, commandStream.getMaxAvailableSpace());
EXPECT_LE(usedAfterISH - usedBeforeISH, indirectHeap.getMaxAvailableSpace());
EXPECT_EQ(CL_SUCCESS, retVal);
}
HWTEST_P(OOMCommandQueueTest, WhenEnqueingMarkerThenMaxAvailableSpaceIsNotExceeded) {
auto &commandStream = pCmdQ->getCS(1024);
auto &indirectHeap = pCmdQ->getIndirectHeap(IndirectHeap::Type::DYNAMIC_STATE, 10);
auto usedBeforeCS = commandStream.getUsed();
auto usedBeforeISH = indirectHeap.getUsed();
Event event1(pCmdQ, CL_COMMAND_NDRANGE_KERNEL, 5, 15);
cl_event eventBeingWaitedOn = &event1;
cl_event eventReturned = nullptr;
auto retVal = pCmdQ->enqueueMarkerWithWaitList(
1,
&eventBeingWaitedOn,
&eventReturned);
EXPECT_EQ(CL_SUCCESS, retVal);
auto usedAfterCS = commandStream.getUsed();
auto usedAfterISH = indirectHeap.getUsed();
EXPECT_LE(usedAfterCS - usedBeforeCS, commandStream.getMaxAvailableSpace());
EXPECT_LE(usedAfterISH - usedBeforeISH, indirectHeap.getMaxAvailableSpace());
delete (Event *)eventReturned;
}
HWTEST_P(OOMCommandQueueTest, WhenEnqueingBarrierThenMaxAvailableSpaceIsNotExceeded) {
auto &commandStream = pCmdQ->getCS(1024);
auto &indirectHeap = pCmdQ->getIndirectHeap(IndirectHeap::Type::DYNAMIC_STATE, 10);
auto usedBeforeCS = commandStream.getUsed();
auto usedBeforeISH = indirectHeap.getUsed();
Event event1(pCmdQ, CL_COMMAND_NDRANGE_KERNEL, 5, 15);
cl_event eventBeingWaitedOn = &event1;
cl_event eventReturned = nullptr;
auto retVal = pCmdQ->enqueueBarrierWithWaitList(
1,
&eventBeingWaitedOn,
&eventReturned);
EXPECT_EQ(CL_SUCCESS, retVal);
auto usedAfterCS = commandStream.getUsed();
auto usedAfterISH = indirectHeap.getUsed();
EXPECT_LE(usedAfterCS - usedBeforeCS, commandStream.getMaxAvailableSpace());
EXPECT_LE(usedAfterISH - usedBeforeISH, indirectHeap.getMaxAvailableSpace());
delete (Event *)eventReturned;
}
INSTANTIATE_TEST_CASE_P(
OOM,
OOMCommandQueueTest,
testing::ValuesIn(oomSettings));
|
/*-----------------------------------------------------------------------
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 "ShotPointLineFeature.h"
#include "../resqml2/SeismicLineSetFeature.h"
using namespace std;
using namespace RESQML2_NS;
using namespace gsoap_eml2_3;
const char* ShotPointLineFeature::XML_TAG = "ShotPointLineFeature";
unsigned int ShotPointLineFeature::getTraceCount() const
{
auto labels = getTraceLabels();
return labels.empty()
? -1
: labels.size();
}
|
//===- InterleavedLoadCombine.cpp - Combine Interleaved Loads ---*- 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
//
//===----------------------------------------------------------------------===//
//
// \file
//
// This file defines the interleaved-load-combine pass. The pass searches for
// ShuffleVectorInstruction that execute interleaving loads. If a matching
// pattern is found, it adds a combined load and further instructions in a
// pattern that is detectable by InterleavedAccesPass. The old instructions are
// left dead to be removed later. The pass is specifically designed to be
// executed just before InterleavedAccesPass to find any left-over instances
// that are not detected within former passes.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/MemoryLocation.h"
#include "llvm/Analysis/MemorySSA.h"
#include "llvm/Analysis/MemorySSAUpdater.h"
#include "llvm/Analysis/OptimizationRemarkEmitter.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/TargetLowering.h"
#include "llvm/CodeGen/TargetPassConfig.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Module.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetMachine.h"
#include <algorithm>
#include <cassert>
#include <list>
using namespace llvm;
#define DEBUG_TYPE "interleaved-load-combine"
namespace {
/// Statistic counter
STATISTIC(NumInterleavedLoadCombine, "Number of combined loads");
/// Option to disable the pass
static cl::opt<bool> DisableInterleavedLoadCombine(
"disable-" DEBUG_TYPE, cl::init(false), cl::Hidden,
cl::desc("Disable combining of interleaved loads"));
struct VectorInfo;
struct InterleavedLoadCombineImpl {
public:
InterleavedLoadCombineImpl(Function &F, DominatorTree &DT, MemorySSA &MSSA,
TargetMachine &TM)
: F(F), DT(DT), MSSA(MSSA),
TLI(*TM.getSubtargetImpl(F)->getTargetLowering()),
TTI(TM.getTargetTransformInfo(F)) {}
/// Scan the function for interleaved load candidates and execute the
/// replacement if applicable.
bool run();
private:
/// Function this pass is working on
Function &F;
/// Dominator Tree Analysis
DominatorTree &DT;
/// Memory Alias Analyses
MemorySSA &MSSA;
/// Target Lowering Information
const TargetLowering &TLI;
/// Target Transform Information
const TargetTransformInfo TTI;
/// Find the instruction in sets LIs that dominates all others, return nullptr
/// if there is none.
LoadInst *findFirstLoad(const std::set<LoadInst *> &LIs);
/// Replace interleaved load candidates. It does additional
/// analyses if this makes sense. Returns true on success and false
/// of nothing has been changed.
bool combine(std::list<VectorInfo> &InterleavedLoad,
OptimizationRemarkEmitter &ORE);
/// Given a set of VectorInfo containing candidates for a given interleave
/// factor, find a set that represents a 'factor' interleaved load.
bool findPattern(std::list<VectorInfo> &Candidates,
std::list<VectorInfo> &InterleavedLoad, unsigned Factor,
const DataLayout &DL);
}; // InterleavedLoadCombine
/// First Order Polynomial on an n-Bit Integer Value
///
/// Polynomial(Value) = Value * B + A + E*2^(n-e)
///
/// A and B are the coefficients. E*2^(n-e) is an error within 'e' most
/// significant bits. It is introduced if an exact computation cannot be proven
/// (e.q. division by 2).
///
/// As part of this optimization multiple loads will be combined. It necessary
/// to prove that loads are within some relative offset to each other. This
/// class is used to prove relative offsets of values loaded from memory.
///
/// Representing an integer in this form is sound since addition in two's
/// complement is associative (trivial) and multiplication distributes over the
/// addition (see Proof(1) in Polynomial::mul). Further, both operations
/// commute.
//
// Example:
// declare @fn(i64 %IDX, <4 x float>* %PTR) {
// %Pa1 = add i64 %IDX, 2
// %Pa2 = lshr i64 %Pa1, 1
// %Pa3 = getelementptr inbounds <4 x float>, <4 x float>* %PTR, i64 %Pa2
// %Va = load <4 x float>, <4 x float>* %Pa3
//
// %Pb1 = add i64 %IDX, 4
// %Pb2 = lshr i64 %Pb1, 1
// %Pb3 = getelementptr inbounds <4 x float>, <4 x float>* %PTR, i64 %Pb2
// %Vb = load <4 x float>, <4 x float>* %Pb3
// ... }
//
// The goal is to prove that two loads load consecutive addresses.
//
// In this case the polynomials are constructed by the following
// steps.
//
// The number tag #e specifies the error bits.
//
// Pa_0 = %IDX #0
// Pa_1 = %IDX + 2 #0 | add 2
// Pa_2 = %IDX/2 + 1 #1 | lshr 1
// Pa_3 = %IDX/2 + 1 #1 | GEP, step signext to i64
// Pa_4 = (%IDX/2)*16 + 16 #0 | GEP, multiply index by sizeof(4) for floats
// Pa_5 = (%IDX/2)*16 + 16 #0 | GEP, add offset of leading components
//
// Pb_0 = %IDX #0
// Pb_1 = %IDX + 4 #0 | add 2
// Pb_2 = %IDX/2 + 2 #1 | lshr 1
// Pb_3 = %IDX/2 + 2 #1 | GEP, step signext to i64
// Pb_4 = (%IDX/2)*16 + 32 #0 | GEP, multiply index by sizeof(4) for floats
// Pb_5 = (%IDX/2)*16 + 16 #0 | GEP, add offset of leading components
//
// Pb_5 - Pa_5 = 16 #0 | subtract to get the offset
//
// Remark: %PTR is not maintained within this class. So in this instance the
// offset of 16 can only be assumed if the pointers are equal.
//
class Polynomial {
/// Operations on B
enum BOps {
LShr,
Mul,
SExt,
Trunc,
};
/// Number of Error Bits e
unsigned ErrorMSBs;
/// Value
Value *V;
/// Coefficient B
SmallVector<std::pair<BOps, APInt>, 4> B;
/// Coefficient A
APInt A;
public:
Polynomial(Value *V) : ErrorMSBs((unsigned)-1), V(V), B(), A() {
IntegerType *Ty = dyn_cast<IntegerType>(V->getType());
if (Ty) {
ErrorMSBs = 0;
this->V = V;
A = APInt(Ty->getBitWidth(), 0);
}
}
Polynomial(const APInt &A, unsigned ErrorMSBs = 0)
: ErrorMSBs(ErrorMSBs), V(NULL), B(), A(A) {}
Polynomial(unsigned BitWidth, uint64_t A, unsigned ErrorMSBs = 0)
: ErrorMSBs(ErrorMSBs), V(NULL), B(), A(BitWidth, A) {}
Polynomial() : ErrorMSBs((unsigned)-1), V(NULL), B(), A() {}
/// Increment and clamp the number of undefined bits.
void incErrorMSBs(unsigned amt) {
if (ErrorMSBs == (unsigned)-1)
return;
ErrorMSBs += amt;
if (ErrorMSBs > A.getBitWidth())
ErrorMSBs = A.getBitWidth();
}
/// Decrement and clamp the number of undefined bits.
void decErrorMSBs(unsigned amt) {
if (ErrorMSBs == (unsigned)-1)
return;
if (ErrorMSBs > amt)
ErrorMSBs -= amt;
else
ErrorMSBs = 0;
}
/// Apply an add on the polynomial
Polynomial &add(const APInt &C) {
// Note: Addition is associative in two's complement even when in case of
// signed overflow.
//
// Error bits can only propagate into higher significant bits. As these are
// already regarded as undefined, there is no change.
//
// Theorem: Adding a constant to a polynomial does not change the error
// term.
//
// Proof:
//
// Since the addition is associative and commutes:
//
// (B + A + E*2^(n-e)) + C = B + (A + C) + E*2^(n-e)
// [qed]
if (C.getBitWidth() != A.getBitWidth()) {
ErrorMSBs = (unsigned)-1;
return *this;
}
A += C;
return *this;
}
/// Apply a multiplication onto the polynomial.
Polynomial &mul(const APInt &C) {
// Note: Multiplication distributes over the addition
//
// Theorem: Multiplication distributes over the addition
//
// Proof(1):
//
// (B+A)*C =-
// = (B + A) + (B + A) + .. {C Times}
// addition is associative and commutes, hence
// = B + B + .. {C Times} .. + A + A + .. {C times}
// = B*C + A*C
// (see (function add) for signed values and overflows)
// [qed]
//
// Theorem: If C has c trailing zeros, errors bits in A or B are shifted out
// to the left.
//
// Proof(2):
//
// Let B' and A' be the n-Bit inputs with some unknown errors EA,
// EB at e leading bits. B' and A' can be written down as:
//
// B' = B + 2^(n-e)*EB
// A' = A + 2^(n-e)*EA
//
// Let C' be an input with c trailing zero bits. C' can be written as
//
// C' = C*2^c
//
// Therefore we can compute the result by using distributivity and
// commutativity.
//
// (B'*C' + A'*C') = [B + 2^(n-e)*EB] * C' + [A + 2^(n-e)*EA] * C' =
// = [B + 2^(n-e)*EB + A + 2^(n-e)*EA] * C' =
// = (B'+A') * C' =
// = [B + 2^(n-e)*EB + A + 2^(n-e)*EA] * C' =
// = [B + A + 2^(n-e)*EB + 2^(n-e)*EA] * C' =
// = (B + A) * C' + [2^(n-e)*EB + 2^(n-e)*EA)] * C' =
// = (B + A) * C' + [2^(n-e)*EB + 2^(n-e)*EA)] * C*2^c =
// = (B + A) * C' + C*(EB + EA)*2^(n-e)*2^c =
//
// Let EC be the final error with EC = C*(EB + EA)
//
// = (B + A)*C' + EC*2^(n-e)*2^c =
// = (B + A)*C' + EC*2^(n-(e-c))
//
// Since EC is multiplied by 2^(n-(e-c)) the resulting error contains c
// less error bits than the input. c bits are shifted out to the left.
// [qed]
if (C.getBitWidth() != A.getBitWidth()) {
ErrorMSBs = (unsigned)-1;
return *this;
}
// Multiplying by one is a no-op.
if (C.isOneValue()) {
return *this;
}
// Multiplying by zero removes the coefficient B and defines all bits.
if (C.isNullValue()) {
ErrorMSBs = 0;
deleteB();
}
// See Proof(2): Trailing zero bits indicate a left shift. This removes
// leading bits from the result even if they are undefined.
decErrorMSBs(C.countTrailingZeros());
A *= C;
pushBOperation(Mul, C);
return *this;
}
/// Apply a logical shift right on the polynomial
Polynomial &lshr(const APInt &C) {
// Theorem(1): (B + A + E*2^(n-e)) >> 1 => (B >> 1) + (A >> 1) + E'*2^(n-e')
// where
// e' = e + 1,
// E is a e-bit number,
// E' is a e'-bit number,
// holds under the following precondition:
// pre(1): A % 2 = 0
// pre(2): e < n, (see Theorem(2) for the trivial case with e=n)
// where >> expresses a logical shift to the right, with adding zeros.
//
// We need to show that for every, E there is a E'
//
// B = b_h * 2^(n-1) + b_m * 2 + b_l
// A = a_h * 2^(n-1) + a_m * 2 (pre(1))
//
// where a_h, b_h, b_l are single bits, and a_m, b_m are (n-2) bit numbers
//
// Let X = (B + A + E*2^(n-e)) >> 1
// Let Y = (B >> 1) + (A >> 1) + E*2^(n-e) >> 1
//
// X = [B + A + E*2^(n-e)] >> 1 =
// = [ b_h * 2^(n-1) + b_m * 2 + b_l +
// + a_h * 2^(n-1) + a_m * 2 +
// + E * 2^(n-e) ] >> 1 =
//
// The sum is built by putting the overflow of [a_m + b+n] into the term
// 2^(n-1). As there are no more bits beyond 2^(n-1) the overflow within
// this bit is discarded. This is expressed by % 2.
//
// The bit in position 0 cannot overflow into the term (b_m + a_m).
//
// = [ ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-1) +
// + ((b_m + a_m) % 2^(n-2)) * 2 +
// + b_l + E * 2^(n-e) ] >> 1 =
//
// The shift is computed by dividing the terms by 2 and by cutting off
// b_l.
//
// = ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-2) +
// + ((b_m + a_m) % 2^(n-2)) +
// + E * 2^(n-(e+1)) =
//
// by the definition in the Theorem e+1 = e'
//
// = ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-2) +
// + ((b_m + a_m) % 2^(n-2)) +
// + E * 2^(n-e') =
//
// Compute Y by applying distributivity first
//
// Y = (B >> 1) + (A >> 1) + E*2^(n-e') =
// = (b_h * 2^(n-1) + b_m * 2 + b_l) >> 1 +
// + (a_h * 2^(n-1) + a_m * 2) >> 1 +
// + E * 2^(n-e) >> 1 =
//
// Again, the shift is computed by dividing the terms by 2 and by cutting
// off b_l.
//
// = b_h * 2^(n-2) + b_m +
// + a_h * 2^(n-2) + a_m +
// + E * 2^(n-(e+1)) =
//
// Again, the sum is built by putting the overflow of [a_m + b+n] into
// the term 2^(n-1). But this time there is room for a second bit in the
// term 2^(n-2) we add this bit to a new term and denote it o_h in a
// second step.
//
// = ([b_h + a_h + (b_m + a_m) >> (n-2)] >> 1) * 2^(n-1) +
// + ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-2) +
// + ((b_m + a_m) % 2^(n-2)) +
// + E * 2^(n-(e+1)) =
//
// Let o_h = [b_h + a_h + (b_m + a_m) >> (n-2)] >> 1
// Further replace e+1 by e'.
//
// = o_h * 2^(n-1) +
// + ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-2) +
// + ((b_m + a_m) % 2^(n-2)) +
// + E * 2^(n-e') =
//
// Move o_h into the error term and construct E'. To ensure that there is
// no 2^x with negative x, this step requires pre(2) (e < n).
//
// = ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-2) +
// + ((b_m + a_m) % 2^(n-2)) +
// + o_h * 2^(e'-1) * 2^(n-e') + | pre(2), move 2^(e'-1)
// | out of the old exponent
// + E * 2^(n-e') =
// = ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-2) +
// + ((b_m + a_m) % 2^(n-2)) +
// + [o_h * 2^(e'-1) + E] * 2^(n-e') + | move 2^(e'-1) out of
// | the old exponent
//
// Let E' = o_h * 2^(e'-1) + E
//
// = ([b_h + a_h + (b_m + a_m) >> (n-2)] % 2) * 2^(n-2) +
// + ((b_m + a_m) % 2^(n-2)) +
// + E' * 2^(n-e')
//
// Because X and Y are distinct only in there error terms and E' can be
// constructed as shown the theorem holds.
// [qed]
//
// For completeness in case of the case e=n it is also required to show that
// distributivity can be applied.
//
// In this case Theorem(1) transforms to (the pre-condition on A can also be
// dropped)
//
// Theorem(2): (B + A + E) >> 1 => (B >> 1) + (A >> 1) + E'
// where
// A, B, E, E' are two's complement numbers with the same bit
// width
//
// Let A + B + E = X
// Let (B >> 1) + (A >> 1) = Y
//
// Therefore we need to show that for every X and Y there is an E' which
// makes the equation
//
// X = Y + E'
//
// hold. This is trivially the case for E' = X - Y.
//
// [qed]
//
// Remark: Distributing lshr with and arbitrary number n can be expressed as
// ((((B + A) lshr 1) lshr 1) ... ) {n times}.
// This construction induces n additional error bits at the left.
if (C.getBitWidth() != A.getBitWidth()) {
ErrorMSBs = (unsigned)-1;
return *this;
}
if (C.isNullValue())
return *this;
// Test if the result will be zero
unsigned shiftAmt = C.getZExtValue();
if (shiftAmt >= C.getBitWidth())
return mul(APInt(C.getBitWidth(), 0));
// The proof that shiftAmt LSBs are zero for at least one summand is only
// possible for the constant number.
//
// If this can be proven add shiftAmt to the error counter
// `ErrorMSBs`. Otherwise set all bits as undefined.
if (A.countTrailingZeros() < shiftAmt)
ErrorMSBs = A.getBitWidth();
else
incErrorMSBs(shiftAmt);
// Apply the operation.
pushBOperation(LShr, C);
A = A.lshr(shiftAmt);
return *this;
}
/// Apply a sign-extend or truncate operation on the polynomial.
Polynomial &sextOrTrunc(unsigned n) {
if (n < A.getBitWidth()) {
// Truncate: Clearly undefined Bits on the MSB side are removed
// if there are any.
decErrorMSBs(A.getBitWidth() - n);
A = A.trunc(n);
pushBOperation(Trunc, APInt(sizeof(n) * 8, n));
}
if (n > A.getBitWidth()) {
// Extend: Clearly extending first and adding later is different
// to adding first and extending later in all extended bits.
incErrorMSBs(n - A.getBitWidth());
A = A.sext(n);
pushBOperation(SExt, APInt(sizeof(n) * 8, n));
}
return *this;
}
/// Test if there is a coefficient B.
bool isFirstOrder() const { return V != nullptr; }
/// Test coefficient B of two Polynomials are equal.
bool isCompatibleTo(const Polynomial &o) const {
// The polynomial use different bit width.
if (A.getBitWidth() != o.A.getBitWidth())
return false;
// If neither Polynomial has the Coefficient B.
if (!isFirstOrder() && !o.isFirstOrder())
return true;
// The index variable is different.
if (V != o.V)
return false;
// Check the operations.
if (B.size() != o.B.size())
return false;
auto ob = o.B.begin();
for (auto &b : B) {
if (b != *ob)
return false;
ob++;
}
return true;
}
/// Subtract two polynomials, return an undefined polynomial if
/// subtraction is not possible.
Polynomial operator-(const Polynomial &o) const {
// Return an undefined polynomial if incompatible.
if (!isCompatibleTo(o))
return Polynomial();
// If the polynomials are compatible (meaning they have the same
// coefficient on B), B is eliminated. Thus a polynomial solely
// containing A is returned
return Polynomial(A - o.A, std::max(ErrorMSBs, o.ErrorMSBs));
}
/// Subtract a constant from a polynomial,
Polynomial operator-(uint64_t C) const {
Polynomial Result(*this);
Result.A -= C;
return Result;
}
/// Add a constant to a polynomial,
Polynomial operator+(uint64_t C) const {
Polynomial Result(*this);
Result.A += C;
return Result;
}
/// Returns true if it can be proven that two Polynomials are equal.
bool isProvenEqualTo(const Polynomial &o) {
// Subtract both polynomials and test if it is fully defined and zero.
Polynomial r = *this - o;
return (r.ErrorMSBs == 0) && (!r.isFirstOrder()) && (r.A.isNullValue());
}
/// Print the polynomial into a stream.
void print(raw_ostream &OS) const {
OS << "[{#ErrBits:" << ErrorMSBs << "} ";
if (V) {
for (auto b : B)
OS << "(";
OS << "(" << *V << ") ";
for (auto b : B) {
switch (b.first) {
case LShr:
OS << "LShr ";
break;
case Mul:
OS << "Mul ";
break;
case SExt:
OS << "SExt ";
break;
case Trunc:
OS << "Trunc ";
break;
}
OS << b.second << ") ";
}
}
OS << "+ " << A << "]";
}
private:
void deleteB() {
V = nullptr;
B.clear();
}
void pushBOperation(const BOps Op, const APInt &C) {
if (isFirstOrder()) {
B.push_back(std::make_pair(Op, C));
return;
}
}
};
#ifndef NDEBUG
static raw_ostream &operator<<(raw_ostream &OS, const Polynomial &S) {
S.print(OS);
return OS;
}
#endif
/// VectorInfo stores abstract the following information for each vector
/// element:
///
/// 1) The the memory address loaded into the element as Polynomial
/// 2) a set of load instruction necessary to construct the vector,
/// 3) a set of all other instructions that are necessary to create the vector and
/// 4) a pointer value that can be used as relative base for all elements.
struct VectorInfo {
private:
VectorInfo(const VectorInfo &c) : VTy(c.VTy) {
llvm_unreachable(
"Copying VectorInfo is neither implemented nor necessary,");
}
public:
/// Information of a Vector Element
struct ElementInfo {
/// Offset Polynomial.
Polynomial Ofs;
/// The Load Instruction used to Load the entry. LI is null if the pointer
/// of the load instruction does not point on to the entry
LoadInst *LI;
ElementInfo(Polynomial Offset = Polynomial(), LoadInst *LI = nullptr)
: Ofs(Offset), LI(LI) {}
};
/// Basic-block the load instructions are within
BasicBlock *BB;
/// Pointer value of all participation load instructions
Value *PV;
/// Participating load instructions
std::set<LoadInst *> LIs;
/// Participating instructions
std::set<Instruction *> Is;
/// Final shuffle-vector instruction
ShuffleVectorInst *SVI;
/// Information of the offset for each vector element
ElementInfo *EI;
/// Vector Type
FixedVectorType *const VTy;
VectorInfo(FixedVectorType *VTy)
: BB(nullptr), PV(nullptr), LIs(), Is(), SVI(nullptr), VTy(VTy) {
EI = new ElementInfo[VTy->getNumElements()];
}
virtual ~VectorInfo() { delete[] EI; }
unsigned getDimension() const { return VTy->getNumElements(); }
/// Test if the VectorInfo can be part of an interleaved load with the
/// specified factor.
///
/// \param Factor of the interleave
/// \param DL Targets Datalayout
///
/// \returns true if this is possible and false if not
bool isInterleaved(unsigned Factor, const DataLayout &DL) const {
unsigned Size = DL.getTypeAllocSize(VTy->getElementType());
for (unsigned i = 1; i < getDimension(); i++) {
if (!EI[i].Ofs.isProvenEqualTo(EI[0].Ofs + i * Factor * Size)) {
return false;
}
}
return true;
}
/// Recursively computes the vector information stored in V.
///
/// This function delegates the work to specialized implementations
///
/// \param V Value to operate on
/// \param Result Result of the computation
///
/// \returns false if no sensible information can be gathered.
static bool compute(Value *V, VectorInfo &Result, const DataLayout &DL) {
ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V);
if (SVI)
return computeFromSVI(SVI, Result, DL);
LoadInst *LI = dyn_cast<LoadInst>(V);
if (LI)
return computeFromLI(LI, Result, DL);
BitCastInst *BCI = dyn_cast<BitCastInst>(V);
if (BCI)
return computeFromBCI(BCI, Result, DL);
return false;
}
/// BitCastInst specialization to compute the vector information.
///
/// \param BCI BitCastInst to operate on
/// \param Result Result of the computation
///
/// \returns false if no sensible information can be gathered.
static bool computeFromBCI(BitCastInst *BCI, VectorInfo &Result,
const DataLayout &DL) {
Instruction *Op = dyn_cast<Instruction>(BCI->getOperand(0));
if (!Op)
return false;
FixedVectorType *VTy = dyn_cast<FixedVectorType>(Op->getType());
if (!VTy)
return false;
// We can only cast from large to smaller vectors
if (Result.VTy->getNumElements() % VTy->getNumElements())
return false;
unsigned Factor = Result.VTy->getNumElements() / VTy->getNumElements();
unsigned NewSize = DL.getTypeAllocSize(Result.VTy->getElementType());
unsigned OldSize = DL.getTypeAllocSize(VTy->getElementType());
if (NewSize * Factor != OldSize)
return false;
VectorInfo Old(VTy);
if (!compute(Op, Old, DL))
return false;
for (unsigned i = 0; i < Result.VTy->getNumElements(); i += Factor) {
for (unsigned j = 0; j < Factor; j++) {
Result.EI[i + j] =
ElementInfo(Old.EI[i / Factor].Ofs + j * NewSize,
j == 0 ? Old.EI[i / Factor].LI : nullptr);
}
}
Result.BB = Old.BB;
Result.PV = Old.PV;
Result.LIs.insert(Old.LIs.begin(), Old.LIs.end());
Result.Is.insert(Old.Is.begin(), Old.Is.end());
Result.Is.insert(BCI);
Result.SVI = nullptr;
return true;
}
/// ShuffleVectorInst specialization to compute vector information.
///
/// \param SVI ShuffleVectorInst to operate on
/// \param Result Result of the computation
///
/// Compute the left and the right side vector information and merge them by
/// applying the shuffle operation. This function also ensures that the left
/// and right side have compatible loads. This means that all loads are with
/// in the same basic block and are based on the same pointer.
///
/// \returns false if no sensible information can be gathered.
static bool computeFromSVI(ShuffleVectorInst *SVI, VectorInfo &Result,
const DataLayout &DL) {
FixedVectorType *ArgTy =
cast<FixedVectorType>(SVI->getOperand(0)->getType());
// Compute the left hand vector information.
VectorInfo LHS(ArgTy);
if (!compute(SVI->getOperand(0), LHS, DL))
LHS.BB = nullptr;
// Compute the right hand vector information.
VectorInfo RHS(ArgTy);
if (!compute(SVI->getOperand(1), RHS, DL))
RHS.BB = nullptr;
// Neither operand produced sensible results?
if (!LHS.BB && !RHS.BB)
return false;
// Only RHS produced sensible results?
else if (!LHS.BB) {
Result.BB = RHS.BB;
Result.PV = RHS.PV;
}
// Only LHS produced sensible results?
else if (!RHS.BB) {
Result.BB = LHS.BB;
Result.PV = LHS.PV;
}
// Both operands produced sensible results?
else if ((LHS.BB == RHS.BB) && (LHS.PV == RHS.PV)) {
Result.BB = LHS.BB;
Result.PV = LHS.PV;
}
// Both operands produced sensible results but they are incompatible.
else {
return false;
}
// Merge and apply the operation on the offset information.
if (LHS.BB) {
Result.LIs.insert(LHS.LIs.begin(), LHS.LIs.end());
Result.Is.insert(LHS.Is.begin(), LHS.Is.end());
}
if (RHS.BB) {
Result.LIs.insert(RHS.LIs.begin(), RHS.LIs.end());
Result.Is.insert(RHS.Is.begin(), RHS.Is.end());
}
Result.Is.insert(SVI);
Result.SVI = SVI;
int j = 0;
for (int i : SVI->getShuffleMask()) {
assert((i < 2 * (signed)ArgTy->getNumElements()) &&
"Invalid ShuffleVectorInst (index out of bounds)");
if (i < 0)
Result.EI[j] = ElementInfo();
else if (i < (signed)ArgTy->getNumElements()) {
if (LHS.BB)
Result.EI[j] = LHS.EI[i];
else
Result.EI[j] = ElementInfo();
} else {
if (RHS.BB)
Result.EI[j] = RHS.EI[i - ArgTy->getNumElements()];
else
Result.EI[j] = ElementInfo();
}
j++;
}
return true;
}
/// LoadInst specialization to compute vector information.
///
/// This function also acts as abort condition to the recursion.
///
/// \param LI LoadInst to operate on
/// \param Result Result of the computation
///
/// \returns false if no sensible information can be gathered.
static bool computeFromLI(LoadInst *LI, VectorInfo &Result,
const DataLayout &DL) {
Value *BasePtr;
Polynomial Offset;
if (LI->isVolatile())
return false;
if (LI->isAtomic())
return false;
// Get the base polynomial
computePolynomialFromPointer(*LI->getPointerOperand(), Offset, BasePtr, DL);
Result.BB = LI->getParent();
Result.PV = BasePtr;
Result.LIs.insert(LI);
Result.Is.insert(LI);
for (unsigned i = 0; i < Result.getDimension(); i++) {
Value *Idx[2] = {
ConstantInt::get(Type::getInt32Ty(LI->getContext()), 0),
ConstantInt::get(Type::getInt32Ty(LI->getContext()), i),
};
int64_t Ofs = DL.getIndexedOffsetInType(Result.VTy, makeArrayRef(Idx, 2));
Result.EI[i] = ElementInfo(Offset + Ofs, i == 0 ? LI : nullptr);
}
return true;
}
/// Recursively compute polynomial of a value.
///
/// \param BO Input binary operation
/// \param Result Result polynomial
static void computePolynomialBinOp(BinaryOperator &BO, Polynomial &Result) {
Value *LHS = BO.getOperand(0);
Value *RHS = BO.getOperand(1);
// Find the RHS Constant if any
ConstantInt *C = dyn_cast<ConstantInt>(RHS);
if ((!C) && BO.isCommutative()) {
C = dyn_cast<ConstantInt>(LHS);
if (C)
std::swap(LHS, RHS);
}
switch (BO.getOpcode()) {
case Instruction::Add:
if (!C)
break;
computePolynomial(*LHS, Result);
Result.add(C->getValue());
return;
case Instruction::LShr:
if (!C)
break;
computePolynomial(*LHS, Result);
Result.lshr(C->getValue());
return;
default:
break;
}
Result = Polynomial(&BO);
}
/// Recursively compute polynomial of a value
///
/// \param V input value
/// \param Result result polynomial
static void computePolynomial(Value &V, Polynomial &Result) {
if (auto *BO = dyn_cast<BinaryOperator>(&V))
computePolynomialBinOp(*BO, Result);
else
Result = Polynomial(&V);
}
/// Compute the Polynomial representation of a Pointer type.
///
/// \param Ptr input pointer value
/// \param Result result polynomial
/// \param BasePtr pointer the polynomial is based on
/// \param DL Datalayout of the target machine
static void computePolynomialFromPointer(Value &Ptr, Polynomial &Result,
Value *&BasePtr,
const DataLayout &DL) {
// Not a pointer type? Return an undefined polynomial
PointerType *PtrTy = dyn_cast<PointerType>(Ptr.getType());
if (!PtrTy) {
Result = Polynomial();
BasePtr = nullptr;
return;
}
unsigned PointerBits =
DL.getIndexSizeInBits(PtrTy->getPointerAddressSpace());
/// Skip pointer casts. Return Zero polynomial otherwise
if (isa<CastInst>(&Ptr)) {
CastInst &CI = *cast<CastInst>(&Ptr);
switch (CI.getOpcode()) {
case Instruction::BitCast:
computePolynomialFromPointer(*CI.getOperand(0), Result, BasePtr, DL);
break;
default:
BasePtr = &Ptr;
Polynomial(PointerBits, 0);
break;
}
}
/// Resolve GetElementPtrInst.
else if (isa<GetElementPtrInst>(&Ptr)) {
GetElementPtrInst &GEP = *cast<GetElementPtrInst>(&Ptr);
APInt BaseOffset(PointerBits, 0);
// Check if we can compute the Offset with accumulateConstantOffset
if (GEP.accumulateConstantOffset(DL, BaseOffset)) {
Result = Polynomial(BaseOffset);
BasePtr = GEP.getPointerOperand();
return;
} else {
// Otherwise we allow that the last index operand of the GEP is
// non-constant.
unsigned idxOperand, e;
SmallVector<Value *, 4> Indices;
for (idxOperand = 1, e = GEP.getNumOperands(); idxOperand < e;
idxOperand++) {
ConstantInt *IDX = dyn_cast<ConstantInt>(GEP.getOperand(idxOperand));
if (!IDX)
break;
Indices.push_back(IDX);
}
// It must also be the last operand.
if (idxOperand + 1 != e) {
Result = Polynomial();
BasePtr = nullptr;
return;
}
// Compute the polynomial of the index operand.
computePolynomial(*GEP.getOperand(idxOperand), Result);
// Compute base offset from zero based index, excluding the last
// variable operand.
BaseOffset =
DL.getIndexedOffsetInType(GEP.getSourceElementType(), Indices);
// Apply the operations of GEP to the polynomial.
unsigned ResultSize = DL.getTypeAllocSize(GEP.getResultElementType());
Result.sextOrTrunc(PointerBits);
Result.mul(APInt(PointerBits, ResultSize));
Result.add(BaseOffset);
BasePtr = GEP.getPointerOperand();
}
}
// All other instructions are handled by using the value as base pointer and
// a zero polynomial.
else {
BasePtr = &Ptr;
Polynomial(DL.getIndexSizeInBits(PtrTy->getPointerAddressSpace()), 0);
}
}
#ifndef NDEBUG
void print(raw_ostream &OS) const {
if (PV)
OS << *PV;
else
OS << "(none)";
OS << " + ";
for (unsigned i = 0; i < getDimension(); i++)
OS << ((i == 0) ? "[" : ", ") << EI[i].Ofs;
OS << "]";
}
#endif
};
} // anonymous namespace
bool InterleavedLoadCombineImpl::findPattern(
std::list<VectorInfo> &Candidates, std::list<VectorInfo> &InterleavedLoad,
unsigned Factor, const DataLayout &DL) {
for (auto C0 = Candidates.begin(), E0 = Candidates.end(); C0 != E0; ++C0) {
unsigned i;
// Try to find an interleaved load using the front of Worklist as first line
unsigned Size = DL.getTypeAllocSize(C0->VTy->getElementType());
// List containing iterators pointing to the VectorInfos of the candidates
std::vector<std::list<VectorInfo>::iterator> Res(Factor, Candidates.end());
for (auto C = Candidates.begin(), E = Candidates.end(); C != E; C++) {
if (C->VTy != C0->VTy)
continue;
if (C->BB != C0->BB)
continue;
if (C->PV != C0->PV)
continue;
// Check the current value matches any of factor - 1 remaining lines
for (i = 1; i < Factor; i++) {
if (C->EI[0].Ofs.isProvenEqualTo(C0->EI[0].Ofs + i * Size)) {
Res[i] = C;
}
}
for (i = 1; i < Factor; i++) {
if (Res[i] == Candidates.end())
break;
}
if (i == Factor) {
Res[0] = C0;
break;
}
}
if (Res[0] != Candidates.end()) {
// Move the result into the output
for (unsigned i = 0; i < Factor; i++) {
InterleavedLoad.splice(InterleavedLoad.end(), Candidates, Res[i]);
}
return true;
}
}
return false;
}
LoadInst *
InterleavedLoadCombineImpl::findFirstLoad(const std::set<LoadInst *> &LIs) {
assert(!LIs.empty() && "No load instructions given.");
// All LIs are within the same BB. Select the first for a reference.
BasicBlock *BB = (*LIs.begin())->getParent();
BasicBlock::iterator FLI =
std::find_if(BB->begin(), BB->end(), [&LIs](Instruction &I) -> bool {
return is_contained(LIs, &I);
});
assert(FLI != BB->end());
return cast<LoadInst>(FLI);
}
bool InterleavedLoadCombineImpl::combine(std::list<VectorInfo> &InterleavedLoad,
OptimizationRemarkEmitter &ORE) {
LLVM_DEBUG(dbgs() << "Checking interleaved load\n");
// The insertion point is the LoadInst which loads the first values. The
// following tests are used to proof that the combined load can be inserted
// just before InsertionPoint.
LoadInst *InsertionPoint = InterleavedLoad.front().EI[0].LI;
// Test if the offset is computed
if (!InsertionPoint)
return false;
std::set<LoadInst *> LIs;
std::set<Instruction *> Is;
std::set<Instruction *> SVIs;
unsigned InterleavedCost;
unsigned InstructionCost = 0;
// Get the interleave factor
unsigned Factor = InterleavedLoad.size();
// Merge all input sets used in analysis
for (auto &VI : InterleavedLoad) {
// Generate a set of all load instructions to be combined
LIs.insert(VI.LIs.begin(), VI.LIs.end());
// Generate a set of all instructions taking part in load
// interleaved. This list excludes the instructions necessary for the
// polynomial construction.
Is.insert(VI.Is.begin(), VI.Is.end());
// Generate the set of the final ShuffleVectorInst.
SVIs.insert(VI.SVI);
}
// There is nothing to combine.
if (LIs.size() < 2)
return false;
// Test if all participating instruction will be dead after the
// transformation. If intermediate results are used, no performance gain can
// be expected. Also sum the cost of the Instructions beeing left dead.
for (auto &I : Is) {
// Compute the old cost
InstructionCost +=
TTI.getInstructionCost(I, TargetTransformInfo::TCK_Latency);
// The final SVIs are allowed not to be dead, all uses will be replaced
if (SVIs.find(I) != SVIs.end())
continue;
// If there are users outside the set to be eliminated, we abort the
// transformation. No gain can be expected.
for (auto *U : I->users()) {
if (Is.find(dyn_cast<Instruction>(U)) == Is.end())
return false;
}
}
// We know that all LoadInst are within the same BB. This guarantees that
// either everything or nothing is loaded.
LoadInst *First = findFirstLoad(LIs);
// To be safe that the loads can be combined, iterate over all loads and test
// that the corresponding defining access dominates first LI. This guarantees
// that there are no aliasing stores in between the loads.
auto FMA = MSSA.getMemoryAccess(First);
for (auto LI : LIs) {
auto MADef = MSSA.getMemoryAccess(LI)->getDefiningAccess();
if (!MSSA.dominates(MADef, FMA))
return false;
}
assert(!LIs.empty() && "There are no LoadInst to combine");
// It is necessary that insertion point dominates all final ShuffleVectorInst.
for (auto &VI : InterleavedLoad) {
if (!DT.dominates(InsertionPoint, VI.SVI))
return false;
}
// All checks are done. Add instructions detectable by InterleavedAccessPass
// The old instruction will are left dead.
IRBuilder<> Builder(InsertionPoint);
Type *ETy = InterleavedLoad.front().SVI->getType()->getElementType();
unsigned ElementsPerSVI =
cast<FixedVectorType>(InterleavedLoad.front().SVI->getType())
->getNumElements();
FixedVectorType *ILTy = FixedVectorType::get(ETy, Factor * ElementsPerSVI);
SmallVector<unsigned, 4> Indices;
for (unsigned i = 0; i < Factor; i++)
Indices.push_back(i);
InterleavedCost = TTI.getInterleavedMemoryOpCost(
Instruction::Load, ILTy, Factor, Indices, InsertionPoint->getAlign(),
InsertionPoint->getPointerAddressSpace());
if (InterleavedCost >= InstructionCost) {
return false;
}
// Create a pointer cast for the wide load.
auto CI = Builder.CreatePointerCast(InsertionPoint->getOperand(0),
ILTy->getPointerTo(),
"interleaved.wide.ptrcast");
// Create the wide load and update the MemorySSA.
auto LI = Builder.CreateAlignedLoad(ILTy, CI, InsertionPoint->getAlign(),
"interleaved.wide.load");
auto MSSAU = MemorySSAUpdater(&MSSA);
MemoryUse *MSSALoad = cast<MemoryUse>(MSSAU.createMemoryAccessBefore(
LI, nullptr, MSSA.getMemoryAccess(InsertionPoint)));
MSSAU.insertUse(MSSALoad);
// Create the final SVIs and replace all uses.
int i = 0;
for (auto &VI : InterleavedLoad) {
SmallVector<int, 4> Mask;
for (unsigned j = 0; j < ElementsPerSVI; j++)
Mask.push_back(i + j * Factor);
Builder.SetInsertPoint(VI.SVI);
auto SVI = Builder.CreateShuffleVector(LI, UndefValue::get(LI->getType()),
Mask, "interleaved.shuffle");
VI.SVI->replaceAllUsesWith(SVI);
i++;
}
NumInterleavedLoadCombine++;
ORE.emit([&]() {
return OptimizationRemark(DEBUG_TYPE, "Combined Interleaved Load", LI)
<< "Load interleaved combined with factor "
<< ore::NV("Factor", Factor);
});
return true;
}
bool InterleavedLoadCombineImpl::run() {
OptimizationRemarkEmitter ORE(&F);
bool changed = false;
unsigned MaxFactor = TLI.getMaxSupportedInterleaveFactor();
auto &DL = F.getParent()->getDataLayout();
// Start with the highest factor to avoid combining and recombining.
for (unsigned Factor = MaxFactor; Factor >= 2; Factor--) {
std::list<VectorInfo> Candidates;
for (BasicBlock &BB : F) {
for (Instruction &I : BB) {
if (auto SVI = dyn_cast<ShuffleVectorInst>(&I)) {
// We don't support scalable vectors in this pass.
if (isa<ScalableVectorType>(SVI->getType()))
continue;
Candidates.emplace_back(cast<FixedVectorType>(SVI->getType()));
if (!VectorInfo::computeFromSVI(SVI, Candidates.back(), DL)) {
Candidates.pop_back();
continue;
}
if (!Candidates.back().isInterleaved(Factor, DL)) {
Candidates.pop_back();
}
}
}
}
std::list<VectorInfo> InterleavedLoad;
while (findPattern(Candidates, InterleavedLoad, Factor, DL)) {
if (combine(InterleavedLoad, ORE)) {
changed = true;
} else {
// Remove the first element of the Interleaved Load but put the others
// back on the list and continue searching
Candidates.splice(Candidates.begin(), InterleavedLoad,
std::next(InterleavedLoad.begin()),
InterleavedLoad.end());
}
InterleavedLoad.clear();
}
}
return changed;
}
namespace {
/// This pass combines interleaved loads into a pattern detectable by
/// InterleavedAccessPass.
struct InterleavedLoadCombine : public FunctionPass {
static char ID;
InterleavedLoadCombine() : FunctionPass(ID) {
initializeInterleavedLoadCombinePass(*PassRegistry::getPassRegistry());
}
StringRef getPassName() const override {
return "Interleaved Load Combine Pass";
}
bool runOnFunction(Function &F) override {
if (DisableInterleavedLoadCombine)
return false;
auto *TPC = getAnalysisIfAvailable<TargetPassConfig>();
if (!TPC)
return false;
LLVM_DEBUG(dbgs() << "*** " << getPassName() << ": " << F.getName()
<< "\n");
return InterleavedLoadCombineImpl(
F, getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
getAnalysis<MemorySSAWrapperPass>().getMSSA(),
TPC->getTM<TargetMachine>())
.run();
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.addRequired<MemorySSAWrapperPass>();
AU.addRequired<DominatorTreeWrapperPass>();
FunctionPass::getAnalysisUsage(AU);
}
private:
};
} // anonymous namespace
char InterleavedLoadCombine::ID = 0;
INITIALIZE_PASS_BEGIN(
InterleavedLoadCombine, DEBUG_TYPE,
"Combine interleaved loads into wide loads and shufflevector instructions",
false, false)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
INITIALIZE_PASS_END(
InterleavedLoadCombine, DEBUG_TYPE,
"Combine interleaved loads into wide loads and shufflevector instructions",
false, false)
FunctionPass *
llvm::createInterleavedLoadCombinePass() {
auto P = new InterleavedLoadCombine();
return P;
}
|
#include<bits/stdc++.h>
using namespace std;
int m, s[200010], dp[200010];
int main()
{
scanf("%d", &m);
for (int i = 1; i <= m; ++i)
dp[i] = 1e9;
int tmp = ceil(sqrt(sqrt(m)) + 1);
for (int i = 1; i <= tmp; ++i)
s[i] = pow(i, 4);
for (int i = 1; i <= tmp; ++i)
for (int j = s[i]; j <= m; ++j)
dp[j] = min(dp[j], dp[j - s[i]] + 1);
printf("%d\n", dp[m]);
return 0;
}
|
// stack using 2 queues
# include <bits/stdc++.h>
using namespace std;
int l1=0,l2=0;
int size=10;
int q1[10],q2[10];
int frontA=0,frontB=0,rearA=-1,rearB=-1;
bool notEmpty(int i)
{
if(i==1)
{
if(frontA>rearA)
return false;
else
return true;
}
else
if(frontB>rearB)
return false;
else
return true;
}
void enqueue(int i,int element)
{
if(i==1)
{
q1[++rearA%size]=element;
}
else
{
q2[++rearB%size]=element;
}
}
int dequeue(int i)
{
if(i==1)
{
return q1[frontA++%size];
}
else
return q2[frontB++%size];
}
void push(int k){
if(rearA-frontA<size)
{
if(rearA==-1)
enqueue(1,k);
else
{
while(notEmpty(1))
{
enqueue(2,dequeue(1));
}
enqueue(1,k);
while(notEmpty(2))
{
enqueue(1,dequeue(2));
}
}
}
else
printf("The queue is full\n");
}
void pop(){
if(!notEmpty(1))
printf("The stack is empty\n");
else
{
dequeue(1);
}
}
void display()
{
int i;
for(i=frontA;i<=rearA;i++)
{
printf("%d-->",q1[i]);
}
printf("end\n");
}
int main()
{
int i,j=0,k,l;
do{
printf("Choose\n1)Push 2) Pop 3) display 4) exit\n");
scanf("%d",&i);
switch(i)
{
case 1: printf("Enter the element\n");
scanf("%d",&k);
push(k);
break;
case 2: pop();
break;
case 3: display();
break;
case 4: j=1;
break;
default: printf("Wrong choice\n");
}
}while(j==0);
return 0;
}
|
/*
* Copyright 2021 Assured Information Security, 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.
*/
#pragma once
#include <introvirt/core/memory/guest_ptr.hh>
#include <introvirt/windows/libraries/ws2_32/types/SOCKADDR_IN.hh>
#include <algorithm>
#include <arpa/inet.h>
namespace introvirt {
namespace windows {
namespace ws2_32 {
namespace structs {
struct _SOCKADDR_IN {
uint16_t sa_family;
union {
struct {
uint16_t sin_port;
uint8_t sin_addr[4];
};
uint8_t sa_data[14];
};
};
}; // namespace structs
class SOCKADDR_IN_IMPL final : public SOCKADDR_IN {
public:
uint16_t sa_family() const override { return ptr_->sa_family; }
void sa_family(uint16_t sa_family) override { ptr_->sa_family = sa_family; }
uint16_t sin_port() const override { return ntohs(ptr_->sin_port); }
void sin_port(uint16_t sin_port) override { ptr_->sin_port = htons(sin_port); }
guest_ptr<const uint8_t[]> sin_addr() const override { return sin_addr_; }
guest_ptr<uint8_t[]> sin_addr() override { return sin_addr_; }
guest_ptr<const char[]> sa_data() const override { return sa_data_; }
guest_ptr<char[]> sa_data() override { return sa_data_; }
// Helper functions
/**
* @brief Get the IP address as a string
*/
std::string inet_ntoa() const override {
static char ip[32];
snprintf(ip, sizeof(ip), "%d.%d.%d.%d", ptr_->sin_addr[0], ptr_->sin_addr[1],
ptr_->sin_addr[2], ptr_->sin_addr[3]);
return std::string(ip);
}
SOCKADDR_IN_IMPL(const guest_ptr<void>& ptr)
: ptr_(ptr),
sin_addr_(ptr + offsetof(_SOCKADDR_IN, sin_addr), sizeof(_SOCKADDR_IN::sin_addr)),
sa_data_(ptr + offsetof(_SOCKADDR_IN, sa_data), sizeof(_SOCKADDR_IN::sa_data)) {}
private:
using _SOCKADDR_IN = structs::_SOCKADDR_IN;
guest_ptr<_SOCKADDR_IN> ptr_;
guest_ptr<uint8_t[]> sin_addr_;
guest_ptr<char[]> sa_data_;
};
} // namespace ws2_32
} // namespace windows
} // namespace introvirt
|
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main()
{
int A[100][100],i,j,suma=0,sumb=0,N;
scanf("%d",&N);
for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
{
scanf("%d",&A[i][j]);
if(i==j)
suma+=A[i][j];
if(j==(N-i-1))
sumb+=A[i][j];
}
}
printf("%d",abs(suma-sumb));
return 0;
}
|
//=================================================================================================
/*!
// \file src/mathtest/dmatreduce/total/DDa.cpp
// \brief Source file for the DDa dense matrix total reduction operation math test
//
// Copyright (C) 2012-2018 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/DiagonalMatrix.h>
#include <blaze/math/DynamicMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/dmatreduce/total/OperationTest.h>
#include <blazetest/system/MathTest.h>
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'DDa'..." << std::endl;
using blazetest::mathtest::TypeA;
try
{
// Matrix type definitions
using DDa = blaze::DiagonalMatrix< blaze::DynamicMatrix<TypeA> >;
// Creator type definitions
using CDDa = blazetest::Creator<DDa>;
// Running tests with small matrices
for( size_t i=0UL; i<=9UL; ++i ) {
RUN_DMATREDUCE_TOTAL_OPERATION_TEST( CDDa( i ) );
}
// Running tests with large matrices
RUN_DMATREDUCE_TOTAL_OPERATION_TEST( CDDa( 67UL ) );
RUN_DMATREDUCE_TOTAL_OPERATION_TEST( CDDa( 128UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense matrix total reduction operation:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
|
#include "header/keyaction.h"
KeyAction::KeyAction()
{
connect(&typeStringTimer, &QTimer::timeout, this, &KeyAction::execAndAdvanceTyping);
}
void KeyAction::execute()
{
if ((type == Type::String && text.isEmpty()) || (type != Type::String && key.isEmpty()))
{
return;
}
switch (type) {
case Type::Press:
for (QString mod : modifiers) keyHandler.hold(mod);
keyHandler.press(key);
for (QString mod : modifiers) keyHandler.release(mod);
break;
case Type::Hold:
keyHandler.hold(key);
break;
case Type::Release:
keyHandler.release(key);
break;
case Type::String:
typeString(text, typeStringDelay);
break;
}
}
void KeyAction::setKey(QString key)
{
this->key = key;
}
void KeyAction::setText(QString text)
{
this->text = text;
}
void KeyAction::setModifiers(QStringList mods)
{
this->modifiers = mods;
}
void KeyAction::setType(KeyAction::Type type)
{
this->type = type;
}
QString KeyAction::getString()
{
QString prefix;
QString modsJoined = modifiers.join("+");
QString mod = (modifiers.isEmpty() ? "" : "[" + modsJoined + "] ");
QString k = "\"" + key + "\"";
switch (type) {
case Type::Press:
prefix = "Press: ";
break;
case Type::Hold:
prefix = "Hold: ";
break;
case Type::Release:
prefix = "Release: ";
break;
case Type::String:
prefix = "Type: ";
mod = "";
QString trunc = text.left(12);
if (trunc.size() < text.size()) trunc += "...";
k = "\"" + trunc + "\"";
break;
}
return key.isEmpty() ? "None" : prefix + mod + k;
}
void KeyAction::typeString(QString string, int delay)
{
typeStringTimer.stop();
typeStringIndex = 0;
typeStringChars.clear();
for (QChar ch : string) {
// Get vkey from char
WORD wvk = VkKeyScan(ch.unicode());
BYTE VKey = LOBYTE(wvk);
// Does this char require shift? (high-order byte 0x01 = Either SHIFT key is pressed.)
bool holdShift = HIBYTE(wvk) & 0x01 ? true : false;
typeStringChars.push_back(QPair<BYTE, bool>(VKey, holdShift));
}
typeStringTimer.start(delay);
}
void KeyAction::execAndAdvanceTyping()
{
if (typeStringIndex < typeStringChars.size())
{
QPair<BYTE, bool> v = typeStringChars[typeStringIndex];
if (v.second) keyHandler.hold("Shift");
keyHandler.press(v.first);
if (v.second) keyHandler.release("Shift");
typeStringIndex++;
}
else
{
typeStringTimer.stop();
}
}
|
/**
* @file
* @brief Terrain related functions.
**/
#include "AppHdr.h"
#include "terrain.h"
#include <algorithm>
#include <functional>
#include <sstream>
#include "areas.h"
#include "attack.h"
#include "branch.h"
#include "cloud.h"
#include "coord.h"
#include "coordit.h"
#include "dgn-event.h"
#include "dgn-overview.h"
#include "directn.h"
#include "dungeon.h"
#include "env.h"
#include "fight.h"
#include "feature.h"
#include "fprop.h"
#include "god-abil.h"
#include "item-prop.h"
#include "items.h"
#include "level-state-type.h"
#include "libutil.h"
#include "mapmark.h"
#include "message.h"
#include "mon-behv.h"
#include "mon-place.h"
#include "mon-poly.h"
#include "mon-util.h"
#include "ouch.h"
#include "player.h"
#include "random.h"
#include "religion.h"
#include "species.h"
#include "spl-transloc.h"
#include "state.h"
#include "stringutil.h"
#include "tileview.h"
#include "transform.h"
#include "traps.h"
#include "travel.h"
#include "viewchar.h"
#include "view.h"
static bool _revert_terrain_to_floor(coord_def pos);
actor* actor_at(const coord_def& c)
{
if (!in_bounds(c))
return nullptr;
if (c == you.pos())
return &you;
return monster_at(c);
}
/** Can a malign gateway be placed on this feature?
*/
bool feat_is_malign_gateway_suitable(dungeon_feature_type feat)
{
return feat == DNGN_FLOOR || feat == DNGN_SHALLOW_WATER;
}
/** Is this feature a type of wall?
*/
bool feat_is_wall(dungeon_feature_type feat)
{
return get_feature_def(feat).flags & FFT_WALL;
}
/** Is this feature one of the main stone downstairs of a level?
*/
bool feat_is_stone_stair_down(dungeon_feature_type feat)
{
return feat == DNGN_STONE_STAIRS_DOWN_I
|| feat == DNGN_STONE_STAIRS_DOWN_II
|| feat == DNGN_STONE_STAIRS_DOWN_III;
}
/** Is this feature one of the main stone upstairs of a level?
*/
bool feat_is_stone_stair_up(dungeon_feature_type feat)
{
return feat == DNGN_STONE_STAIRS_UP_I
|| feat == DNGN_STONE_STAIRS_UP_II
|| feat == DNGN_STONE_STAIRS_UP_III;
}
/** Is this feature one of the main stone stairs of a level?
*/
bool feat_is_stone_stair(dungeon_feature_type feat)
{
return feat_is_stone_stair_up(feat) || feat_is_stone_stair_down(feat);
}
/** Is it possible to call this feature a staircase? (purely cosmetic)
*/
bool feat_is_staircase(dungeon_feature_type feat)
{
if (feat_is_stone_stair(feat))
return true;
// All branch entries/exits are staircases, except for Zot and Vaults entry.
if (feat == DNGN_ENTER_VAULTS
|| feat == DNGN_EXIT_VAULTS
|| feat == DNGN_ENTER_ZOT
|| feat == DNGN_EXIT_ZOT)
{
return false;
}
return feat_is_branch_entrance(feat)
|| feat_is_branch_exit(feat)
|| feat == DNGN_ABYSSAL_STAIR;
}
/**
* Define a memoized function from dungeon_feature_type to bool.
* This macro should be followed by the non-memoized version of the
* function body: see feat_is_branch_entrance below for an example.
*
* @param funcname The name of the function to define.
* @param paramname The name under which the function's single parameter,
* of type dungeon_feature_type, is visible in the function body.
*/
#define FEATFN_MEMOIZED(funcname, paramname) \
static bool _raw_ ## funcname (dungeon_feature_type); \
bool funcname (dungeon_feature_type feat) \
{ \
static int cached[NUM_FEATURES+1] = { 0 }; \
if (!cached[feat]) cached[feat] = _raw_ ## funcname (feat) ? 1 : -1; \
return cached[feat] > 0; \
} \
static bool _raw_ ## funcname (dungeon_feature_type paramname)
/** Is this feature a branch entrance that should show up on ^O?
*/
FEATFN_MEMOIZED(feat_is_branch_entrance, feat)
{
if (feat == DNGN_ENTER_HELL)
return false;
for (branch_iterator it; it; ++it)
{
if (it->entry_stairs == feat
&& is_connected_branch(it->id))
{
return true;
}
}
return false;
}
/** Counterpart to feat_is_branch_entrance.
*/
FEATFN_MEMOIZED(feat_is_branch_exit, feat)
{
if (feat == DNGN_ENTER_HELL || feat == DNGN_EXIT_HELL)
return false;
for (branch_iterator it; it; ++it)
{
if (it->exit_stairs == feat
&& is_connected_branch(it->id))
{
return true;
}
}
return false;
}
/** Is this feature an entrance to a portal branch?
*/
FEATFN_MEMOIZED(feat_is_portal_entrance, feat)
{
// These are have different rules from normal connected branches, but they
// also have different rules from "portal vaults," and are more similar to
// real branches in some respects.
if (feat == DNGN_ENTER_ABYSS || feat == DNGN_ENTER_PANDEMONIUM)
return false;
for (branch_iterator it; it; ++it)
{
if (it->entry_stairs == feat
&& !is_connected_branch(it->id))
{
return true;
}
}
#if TAG_MAJOR_VERSION == 34
if (feat == DNGN_ENTER_PORTAL_VAULT)
return true;
#endif
return false;
}
/** Counterpart to feat_is_portal_entrance.
*/
FEATFN_MEMOIZED(feat_is_portal_exit, feat)
{
if (feat == DNGN_EXIT_ABYSS || feat == DNGN_EXIT_PANDEMONIUM)
return false;
for (branch_iterator it; it; ++it)
{
if (it->exit_stairs == feat
&& !is_connected_branch(it->id))
{
return true;
}
}
#if TAG_MAJOR_VERSION == 34
if (feat == DNGN_EXIT_PORTAL_VAULT)
return true;
#endif
return false;
}
/** Is this feature a kind of portal?
*/
bool feat_is_portal(dungeon_feature_type feat)
{
return feat == DNGN_MALIGN_GATEWAY
|| feat_is_portal_entrance(feat)
|| feat_is_portal_exit(feat);
}
/** Is this feature a kind of level exit?
*/
bool feat_is_stair(dungeon_feature_type gridc)
{
return feat_is_travelable_stair(gridc) || feat_is_gate(gridc);
}
/** Is this feature a level exit stair with a consistent endpoint?
*/
bool feat_is_travelable_stair(dungeon_feature_type feat)
{
return feat_is_stone_stair(feat)
|| feat_is_escape_hatch(feat)
|| feat_is_branch_entrance(feat)
|| feat_is_branch_exit(feat)
|| feat == DNGN_ENTER_HELL
|| feat == DNGN_EXIT_HELL;
}
/** Is this feature an escape hatch?
*/
bool feat_is_escape_hatch(dungeon_feature_type feat)
{
return feat == DNGN_ESCAPE_HATCH_DOWN
|| feat == DNGN_ESCAPE_HATCH_UP;
}
/** Is this feature a gate?
* XXX: Why does this matter??
*/
bool feat_is_gate(dungeon_feature_type feat)
{
if (feat_is_portal_entrance(feat)
|| feat_is_portal_exit(feat))
{
return true;
}
switch (feat)
{
case DNGN_ENTER_ABYSS:
case DNGN_EXIT_THROUGH_ABYSS:
case DNGN_EXIT_ABYSS:
case DNGN_ABYSSAL_STAIR:
case DNGN_ENTER_PANDEMONIUM:
case DNGN_EXIT_PANDEMONIUM:
case DNGN_TRANSIT_PANDEMONIUM:
case DNGN_ENTER_VAULTS:
case DNGN_EXIT_VAULTS:
case DNGN_ENTER_ZOT:
case DNGN_EXIT_ZOT:
case DNGN_ENTER_HELL:
case DNGN_EXIT_HELL:
case DNGN_ENTER_DIS:
case DNGN_ENTER_GEHENNA:
case DNGN_ENTER_COCYTUS:
case DNGN_ENTER_TARTARUS:
return true;
default:
return false;
}
}
/** What command do you use to traverse this feature?
*
* @param feat the feature.
* @returns CMD_GO_UPSTAIRS if it's a stair up, CMD_GO_DOWNSTAIRS if it's a
* stair down, and CMD_NO_CMD if it can't be used to move.
*/
command_type feat_stair_direction(dungeon_feature_type feat)
{
if (feat_is_portal_entrance(feat)
|| feat_is_branch_entrance(feat))
{
return CMD_GO_DOWNSTAIRS;
}
if (feat_is_portal_exit(feat)
|| feat_is_branch_exit(feat))
{
return CMD_GO_UPSTAIRS;
}
if (feat_is_altar(feat))
return CMD_GO_UPSTAIRS; // arbitrary; consistent with shops
switch (feat)
{
case DNGN_ENTER_HELL:
return player_in_hell() ? CMD_GO_UPSTAIRS : CMD_GO_DOWNSTAIRS;
case DNGN_STONE_STAIRS_UP_I:
case DNGN_STONE_STAIRS_UP_II:
case DNGN_STONE_STAIRS_UP_III:
case DNGN_ESCAPE_HATCH_UP:
case DNGN_ENTER_SHOP:
case DNGN_EXIT_HELL:
return CMD_GO_UPSTAIRS;
case DNGN_STONE_STAIRS_DOWN_I:
case DNGN_STONE_STAIRS_DOWN_II:
case DNGN_STONE_STAIRS_DOWN_III:
case DNGN_ESCAPE_HATCH_DOWN:
case DNGN_ENTER_ABYSS:
case DNGN_EXIT_THROUGH_ABYSS:
case DNGN_EXIT_ABYSS:
case DNGN_ABYSSAL_STAIR:
case DNGN_ENTER_PANDEMONIUM:
case DNGN_EXIT_PANDEMONIUM:
case DNGN_TRANSIT_PANDEMONIUM:
case DNGN_TRANSPORTER:
return CMD_GO_DOWNSTAIRS;
default:
return CMD_NO_CMD;
}
}
/** Can you normally see through this feature?
*/
bool feat_is_opaque(dungeon_feature_type feat)
{
return get_feature_def(feat).flags & FFT_OPAQUE;
}
/** Can you move into this feature in normal play?
*/
bool feat_is_solid(dungeon_feature_type feat)
{
return get_feature_def(feat).flags & FFT_SOLID;
}
/** Can you wall jump against this feature? (Wu Jian)?
*/
bool feat_can_wall_jump_against(dungeon_feature_type feat)
{
return feat_is_wall(feat)
|| feat == DNGN_GRATE
|| feat_is_closed_door(feat)
|| feat_is_tree(feat)
|| feat_is_statuelike(feat);
}
/** Can you move into this cell in normal play?
*/
bool cell_is_solid(const coord_def &c)
{
return feat_is_solid(grd(c));
}
/** Can a human stand on this feature without flying?
*/
bool feat_has_solid_floor(dungeon_feature_type feat)
{
return !feat_is_solid(feat) && feat != DNGN_DEEP_WATER
&& feat != DNGN_LAVA;
}
/** Is there enough dry floor on this feature to stand without penalty?
*/
bool feat_has_dry_floor(dungeon_feature_type feat)
{
return feat_has_solid_floor(feat) && !feat_is_water(feat);
}
/** Is this feature a variety of door?
*/
bool feat_is_door(dungeon_feature_type feat)
{
return feat_is_closed_door(feat) || feat_is_open_door(feat);
}
/** Is this feature a variety of closed door?
*/
bool feat_is_closed_door(dungeon_feature_type feat)
{
return feat == DNGN_CLOSED_DOOR
|| feat == DNGN_CLOSED_CLEAR_DOOR
|| feat_is_runed(feat)
|| feat == DNGN_SEALED_DOOR
|| feat == DNGN_SEALED_CLEAR_DOOR;
}
/** Is this feature a variety of open door?
*/
bool feat_is_open_door(dungeon_feature_type feat)
{
return feat == DNGN_OPEN_DOOR || feat == DNGN_OPEN_CLEAR_DOOR;
}
/** Has this feature been sealed by a vault warden?
*/
bool feat_is_sealed(dungeon_feature_type feat)
{
return feat == DNGN_SEALED_STAIRS_DOWN
|| feat == DNGN_SEALED_STAIRS_UP
|| feat == DNGN_SEALED_DOOR
|| feat == DNGN_SEALED_CLEAR_DOOR;
}
/** Is this feature a type of runed door?
*/
bool feat_is_runed(dungeon_feature_type feat)
{
return feat == DNGN_RUNED_DOOR || feat == DNGN_RUNED_CLEAR_DOOR;
}
/** Is the original feature at this position runed, as in a runed door?
*/
bool cell_is_runed(const coord_def &p)
{
// the orig_terrain call will check the actual terrain if there's no change
return feat_is_runed(orig_terrain(p));
}
/** Is this feature a type of statue, i.e., granite or an idol?
*/
bool feat_is_statuelike(dungeon_feature_type feat)
{
return feat == DNGN_ORCISH_IDOL || feat == DNGN_GRANITE_STATUE;
}
/** Is this feature permanent, unalterable rock?
*/
bool feat_is_permarock(dungeon_feature_type feat)
{
return feat == DNGN_PERMAROCK_WALL || feat == DNGN_CLEAR_PERMAROCK_WALL;
}
/** Is this feature an open expanse used only as a map border?
*/
bool feat_is_endless(dungeon_feature_type feat)
{
return feat == DNGN_OPEN_SEA || feat == DNGN_LAVA_SEA
|| feat == DNGN_ENDLESS_SALT;
}
/** Can this feature be dug?
*/
bool feat_is_diggable(dungeon_feature_type feat)
{
return feat == DNGN_ROCK_WALL || feat == DNGN_CLEAR_ROCK_WALL
|| feat == DNGN_SLIMY_WALL || feat == DNGN_GRATE
|| feat == DNGN_ORCISH_IDOL || feat == DNGN_GRANITE_STATUE;
}
/** Is this feature a type of trap?
*
* @param feat the feature.
* @returns true if it's a trap.
*/
bool feat_is_trap(dungeon_feature_type feat)
{
if (!is_valid_feature_type(feat))
return false; // ???
return get_feature_def(feat).flags & FFT_TRAP;
}
/** Is this feature a type of water, with the concomitant dangers/bonuss?
*/
bool feat_is_water(dungeon_feature_type feat)
{
return feat == DNGN_SHALLOW_WATER
|| feat == DNGN_DEEP_WATER
|| feat == DNGN_OPEN_SEA
|| feat == DNGN_TOXIC_BOG;
}
/** Does this feature have enough water to keep water-only monsters alive in it?
*/
bool feat_is_watery(dungeon_feature_type feat)
{
return feat_is_water(feat) || feat == DNGN_FOUNTAIN_BLUE;
}
/** Is this feature a kind of lava?
*/
bool feat_is_lava(dungeon_feature_type feat)
{
return feat == DNGN_LAVA || feat == DNGN_LAVA_SEA;
}
static const pair<god_type, dungeon_feature_type> _god_altars[] =
{
{ GOD_ZIN, DNGN_ALTAR_ZIN },
{ GOD_SHINING_ONE, DNGN_ALTAR_SHINING_ONE },
{ GOD_KIKUBAAQUDGHA, DNGN_ALTAR_KIKUBAAQUDGHA },
{ GOD_YREDELEMNUL, DNGN_ALTAR_YREDELEMNUL },
{ GOD_XOM, DNGN_ALTAR_XOM },
{ GOD_VEHUMET, DNGN_ALTAR_VEHUMET },
{ GOD_OKAWARU, DNGN_ALTAR_OKAWARU },
{ GOD_MAKHLEB, DNGN_ALTAR_MAKHLEB },
{ GOD_SIF_MUNA, DNGN_ALTAR_SIF_MUNA },
{ GOD_TROG, DNGN_ALTAR_TROG },
{ GOD_NEMELEX_XOBEH, DNGN_ALTAR_NEMELEX_XOBEH },
{ GOD_ELYVILON, DNGN_ALTAR_ELYVILON },
{ GOD_LUGONU, DNGN_ALTAR_LUGONU },
{ GOD_BEOGH, DNGN_ALTAR_BEOGH },
{ GOD_JIYVA, DNGN_ALTAR_JIYVA },
{ GOD_FEDHAS, DNGN_ALTAR_FEDHAS },
{ GOD_CHEIBRIADOS, DNGN_ALTAR_CHEIBRIADOS },
{ GOD_ASHENZARI, DNGN_ALTAR_ASHENZARI },
{ GOD_DITHMENOS, DNGN_ALTAR_DITHMENOS },
{ GOD_GOZAG, DNGN_ALTAR_GOZAG },
{ GOD_QAZLAL, DNGN_ALTAR_QAZLAL },
{ GOD_RU, DNGN_ALTAR_RU },
#if TAG_MAJOR_VERSION == 34
{ GOD_PAKELLAS, DNGN_ALTAR_PAKELLAS },
#endif
{ GOD_USKAYAW, DNGN_ALTAR_USKAYAW },
{ GOD_HEPLIAKLQANA, DNGN_ALTAR_HEPLIAKLQANA },
{ GOD_WU_JIAN, DNGN_ALTAR_WU_JIAN },
{ GOD_ECUMENICAL, DNGN_ALTAR_ECUMENICAL },
{ GOD_ANADORATH, DNGN_ALTAR_ANADORATH },
};
COMPILE_CHECK(ARRAYSZ(_god_altars) == NUM_GODS );
/** Whose altar is this feature?
*
* @param feat the feature.
* @returns GOD_NO_GOD if not an altar, otherwise the god_type of the god.
*/
god_type feat_altar_god(dungeon_feature_type feat)
{
for (const auto &altar : _god_altars)
if (altar.second == feat)
return altar.first;
return GOD_NO_GOD;
}
/** What feature is the altar of this god?
*
* @param god the god.
* @returns DNGN_FLOOR for an invalid god, the god's altar otherwise.
*/
dungeon_feature_type altar_for_god(god_type god)
{
for (const auto &altar : _god_altars)
if (altar.first == god)
return altar.second;
return DNGN_FLOOR;
}
/** Is this feature an altar to any god?
*/
bool feat_is_altar(dungeon_feature_type grid)
{
return feat_altar_god(grid) != GOD_NO_GOD;
}
/** Is this feature an altar to the player's god?
*
* @param feat the feature.
* @returns true if the player has a god and this is its altar.
*/
bool feat_is_player_altar(dungeon_feature_type grid)
{
return !you_worship(GOD_NO_GOD) && you_worship(feat_altar_god(grid));
}
/** Is this feature a tree?
*/
bool feat_is_tree(dungeon_feature_type feat)
{
return feat == DNGN_TREE;
}
/** Is this feature made of metal?
*/
bool feat_is_metal(dungeon_feature_type feat)
{
return feat == DNGN_METAL_WALL || feat == DNGN_GRATE;
}
/** Is this feature ambivalent about whether we're going up or down?
*/
bool feat_is_bidirectional_portal(dungeon_feature_type feat)
{
return get_feature_dchar(feat) == DCHAR_ARCH
&& feat_stair_direction(feat) != CMD_NO_CMD
&& feat != DNGN_ENTER_ZOT
&& feat != DNGN_EXIT_ZOT
&& feat != DNGN_ENTER_VAULTS
&& feat != DNGN_EXIT_VAULTS
&& feat != DNGN_EXIT_HELL
&& feat != DNGN_ENTER_HELL;
}
/** Is this feature a type of fountain?
*/
bool feat_is_fountain(dungeon_feature_type feat)
{
return feat == DNGN_FOUNTAIN_BLUE
|| feat == DNGN_FOUNTAIN_SPARKLING
|| feat == DNGN_FOUNTAIN_BLOOD
|| feat == DNGN_DRY_FOUNTAIN;
}
/** Is this feature non-solid enough that you can reach past it?
*/
bool feat_is_reachable_past(dungeon_feature_type feat)
{
return !feat_is_opaque(feat)
&& !feat_is_wall(feat)
&& !feat_is_closed_door(feat)
&& feat != DNGN_GRATE;
}
/** Is this feature important to the game?
*
* @param feat the feature.
* @returns true for altars, stairs/portals, and malign gateways (???).
*/
bool feat_is_critical(dungeon_feature_type feat)
{
return feat_stair_direction(feat) != CMD_NO_CMD
|| feat_altar_god(feat) != GOD_NO_GOD
|| feat == DNGN_TRANSPORTER_LANDING
|| feat == DNGN_MALIGN_GATEWAY;
}
/** Can you use this feature for a map border?
*/
bool feat_is_valid_border(dungeon_feature_type feat)
{
return feat_is_wall(feat)
|| feat_is_tree(feat)
|| feat == DNGN_OPEN_SEA
|| feat == DNGN_LAVA_SEA
|| feat == DNGN_ENDLESS_SALT;
}
/** Can this feature be a mimic?
*
* @param feat the feature
* @param strict if true, disallow features for which being a mimic would be bad in
normal generation; vaults can still use such mimics.
* @returns whether this could make a valid mimic type.
*/
bool feat_is_mimicable(dungeon_feature_type feat, bool strict)
{
if (!strict && feat != DNGN_FLOOR && feat != DNGN_SHALLOW_WATER
&& feat != DNGN_DEEP_WATER)
{
return true;
}
if (feat == DNGN_ENTER_ZIGGURAT)
return false;
if (feat_is_portal_entrance(feat))
return true;
if (feat == DNGN_ENTER_SHOP)
return true;
return false;
}
/** Can creatures on this feature be shafted?
*
* @param feat The feature in question.
* @returns Whether creatures standing on this feature can be shafted (by
* magical effects, Formicid digging, etc).
*/
bool feat_is_shaftable(dungeon_feature_type feat)
{
return feat_has_dry_floor(feat)
&& !feat_is_stair(feat)
&& !feat_is_portal(feat);
}
int count_neighbours_with_func(const coord_def& c, bool (*checker)(dungeon_feature_type))
{
int count = 0;
for (adjacent_iterator ai(c); ai; ++ai)
{
if (checker(grd(*ai)))
count++;
}
return count;
}
// For internal use by find_connected_identical only.
static void _find_connected_identical(const coord_def &d,
dungeon_feature_type ft,
set<coord_def>& out,
bool known_only)
{
if (grd(d) != ft || (known_only && !env.map_knowledge(d).known()))
return;
string prop = env.markers.property_at(d, MAT_ANY, "connected_exclude");
if (!prop.empty())
{
// Don't treat this square as connected to anything. Ignore it.
// Continue the search in other directions.
return;
}
if (out.insert(d).second)
{
_find_connected_identical(coord_def(d.x+1, d.y), ft, out, known_only);
_find_connected_identical(coord_def(d.x-1, d.y), ft, out, known_only);
_find_connected_identical(coord_def(d.x, d.y+1), ft, out, known_only);
_find_connected_identical(coord_def(d.x, d.y-1), ft, out, known_only);
}
}
// Find all connected cells containing ft, starting at d.
void find_connected_identical(const coord_def &d, set<coord_def>& out, bool known_only)
{
string prop = env.markers.property_at(d, MAT_ANY, "connected_exclude");
if (!prop.empty())
out.insert(d);
else
_find_connected_identical(d, grd(d), out, known_only);
}
void get_door_description(int door_size, const char** adjective, const char** noun)
{
const char* descriptions[] =
{
"miniscule " , "buggy door",
"" , "door",
"large " , "door",
"" , "gate",
"huge " , "gate",
};
int max_idx = static_cast<int>(ARRAYSZ(descriptions) - 2);
const unsigned int idx = min(door_size*2, max_idx);
*adjective = descriptions[idx];
*noun = descriptions[idx+1];
}
coord_def get_random_stair()
{
vector<coord_def> st;
for (rectangle_iterator ri(1); ri; ++ri)
{
const dungeon_feature_type feat = grd(*ri);
if (feat_is_travelable_stair(feat) && !feat_is_escape_hatch(feat)
&& feat != DNGN_EXIT_DUNGEON
&& feat != DNGN_EXIT_HELL)
{
st.push_back(*ri);
}
}
if (st.empty())
return coord_def(); // sanity check: shouldn't happen
return st[random2(st.size())];
}
static unique_ptr<map_mask_boolean> _slime_wall_precomputed_neighbour_mask;
static void _precompute_slime_wall_neighbours()
{
map_mask_boolean &mask(*_slime_wall_precomputed_neighbour_mask);
for (rectangle_iterator ri(1); ri; ++ri)
{
if (grd(*ri) == DNGN_SLIMY_WALL)
{
for (adjacent_iterator ai(*ri); ai; ++ai)
mask(*ai) = true;
}
}
}
unwind_slime_wall_precomputer::unwind_slime_wall_precomputer(bool docompute)
: did_compute_mask(false)
{
if (!(env.level_state & LSTATE_SLIMY_WALL))
return;
if (docompute && !_slime_wall_precomputed_neighbour_mask)
{
did_compute_mask = true;
_slime_wall_precomputed_neighbour_mask.reset(
new map_mask_boolean(false));
_precompute_slime_wall_neighbours();
}
}
unwind_slime_wall_precomputer::~unwind_slime_wall_precomputer()
{
if (did_compute_mask)
_slime_wall_precomputed_neighbour_mask.reset(nullptr);
}
bool slime_wall_neighbour(const coord_def& c)
{
if (!(env.level_state & LSTATE_SLIMY_WALL))
return false;
if (_slime_wall_precomputed_neighbour_mask)
return (*_slime_wall_precomputed_neighbour_mask)(c);
// Not using count_adjacent_slime_walls because the early return might
// be relevant for performance here. TODO: profile it and find out.
for (adjacent_iterator ai(c); ai; ++ai)
if (env.grid(*ai) == DNGN_SLIMY_WALL)
return true;
return false;
}
int count_adjacent_slime_walls(const coord_def &pos)
{
int count = 0;
for (adjacent_iterator ai(pos); ai; ++ai)
if (env.grid(*ai) == DNGN_SLIMY_WALL)
count++;
return count;
}
void slime_wall_damage(actor* act, int delay)
{
ASSERT(act);
if (actor_slime_wall_immune(act))
return;
const int walls = count_adjacent_slime_walls(act->pos());
if (!walls)
return;
const int strength = div_rand_round(3 * walls * delay, BASELINE_DELAY);
if (act->is_player())
{
you.splash_with_acid(nullptr, strength, false,
(walls > 1) ? "The walls burn you!"
: "The wall burns you!");
}
else
{
monster* mon = act->as_monster();
const int dam = resist_adjust_damage(mon, BEAM_ACID,
roll_dice(2, strength));
if (dam > 0 && you.can_see(*mon))
{
mprf((walls > 1) ? "The walls burn %s!" : "The wall burns %s!",
mon->name(DESC_THE).c_str());
}
mon->hurt(nullptr, dam, BEAM_ACID);
}
}
int count_adjacent_icy_walls(const coord_def &pos)
{
int count = 0;
for (adjacent_iterator ai(pos); ai; ++ai)
if (is_icecovered(*ai))
count++;
return count;
}
void feat_splash_noise(dungeon_feature_type feat)
{
if (crawl_state.generating_level)
return;
switch (feat)
{
case DNGN_SHALLOW_WATER:
case DNGN_DEEP_WATER:
mprf(MSGCH_SOUND, "You hear a splash.");
return;
case DNGN_LAVA:
mprf(MSGCH_SOUND, "You hear a sizzling splash.");
return;
default:
return;
}
}
/** Does this feature destroy any items that fall into it?
*/
bool feat_destroys_items(dungeon_feature_type feat)
{
return feat == DNGN_LAVA;
}
/** Does this feature make items that fall into it permanently inaccessible?
*/
bool feat_eliminates_items(dungeon_feature_type feat)
{
return feat_destroys_items(feat)
|| feat == DNGN_DEEP_WATER && !species_likes_water(you.species);
}
static coord_def _dgn_find_nearest_square(
const coord_def &pos,
function<bool (const coord_def &)> acceptable,
function<bool (const coord_def &)> traversable = nullptr)
{
memset(travel_point_distance, 0, sizeof(travel_distance_grid_t));
vector<coord_def> points[2];
int iter = 0;
points[iter].push_back(pos);
while (!points[iter].empty())
{
// Iterate each layer of BFS in random order to avoid bias.
shuffle_array(points[iter]);
for (const auto &p : points[iter])
{
if (p != pos && acceptable(p))
return p;
travel_point_distance[p.x][p.y] = 1;
for (int yi = -1; yi <= 1; ++yi)
for (int xi = -1; xi <= 1; ++xi)
{
if (!xi && !yi)
continue;
const coord_def np = p + coord_def(xi, yi);
if (!in_bounds(np) || travel_point_distance[np.x][np.y])
continue;
if (traversable && !traversable(np))
continue;
points[!iter].push_back(np);
}
}
points[iter].clear();
iter = !iter;
}
return coord_def(0, 0); // Not found.
}
static bool _item_safe_square(const coord_def &pos)
{
const dungeon_feature_type feat = grd(pos);
return feat_is_traversable(feat) && !feat_destroys_items(feat);
}
static bool _item_traversable_square(const coord_def &pos)
{
return !cell_is_solid(pos);
}
// Moves an item on the floor to the nearest adjacent floor-space.
static bool _dgn_shift_item(const coord_def &pos, item_def &item)
{
// First try to avoid pushing things through solid features...
coord_def np = _dgn_find_nearest_square(pos, _item_safe_square,
_item_traversable_square);
// ... but if we have to, so be it.
if (!in_bounds(np) || np == pos)
np = _dgn_find_nearest_square(pos, _item_safe_square);
if (in_bounds(np) && np != pos)
{
int index = item.index();
move_item_to_grid(&index, np);
return true;
}
return false;
}
static bool _is_feature_shift_target(const coord_def &pos)
{
return grd(pos) == DNGN_FLOOR && !dungeon_events.has_listeners_at(pos)
&& !actor_at(pos);
}
// Moves everything at src to dst. This is not a swap operation: src will be
// left with the same feature it started with, and should be overwritten with
// something new. Assumes there are no actors in the destination square.
//
// Things that are moved:
// 1. Dungeon terrain (set to DNGN_UNSEEN)
// 2. Actors (including the player)
// 3. Items
// 4. Clouds
// 5. Terrain properties
// 6. Terrain colours
// 7. Vault (map) mask
// 8. Vault id mask
// 9. Map markers, dungeon listeners, shopping list
//10. Player's knowledge
void dgn_move_entities_at(coord_def src, coord_def dst,
bool move_player,
bool move_monster,
bool move_items)
{
if (!in_bounds(dst) || !in_bounds(src) || src == dst)
return;
move_notable_thing(src, dst);
dungeon_feature_type dfeat = grd(src);
if (dfeat == DNGN_ENTER_SHOP)
{
ASSERT(shop_at(src));
env.shop[dst] = env.shop[src];
env.shop[dst].pos = dst;
env.shop.erase(src);
grd(src) = DNGN_FLOOR;
}
else if (feat_is_trap(dfeat))
{
ASSERT(trap_at(src));
env.trap[dst] = env.trap[src];
env.trap[dst].pos = dst;
env.trap.erase(src);
grd(src) = DNGN_FLOOR;
}
grd(dst) = dfeat;
if (move_monster || move_player)
ASSERT(!actor_at(dst));
if (move_monster)
{
if (monster* mon = monster_at(src))
{
mon->moveto(dst);
if (mon->type == MONS_ELDRITCH_TENTACLE)
{
if (mon->props.exists("base_position"))
{
coord_def delta = dst - src;
coord_def base_pos = mon->props["base_position"].get_coord();
base_pos += delta;
mon->props["base_position"].get_coord() = base_pos;
}
}
mgrd(dst) = mgrd(src);
mgrd(src) = NON_MONSTER;
}
}
if (move_player && you.pos() == src)
you.shiftto(dst);
if (move_items)
move_item_stack_to_grid(src, dst);
if (cell_is_solid(dst))
{
delete_cloud(src);
delete_cloud(dst); // in case there was already a clear there
}
else
move_cloud(src, dst);
// Move terrain colours and properties.
env.pgrid(dst) = env.pgrid(src);
env.grid_colours(dst) = env.grid_colours(src);
#ifdef USE_TILE
env.tile_bk_fg(dst) = env.tile_bk_fg(src);
env.tile_bk_bg(dst) = env.tile_bk_bg(src);
env.tile_bk_cloud(dst) = env.tile_bk_cloud(src);
#endif
env.tile_flv(dst) = env.tile_flv(src);
// Move vault masks.
env.level_map_mask(dst) = env.level_map_mask(src);
env.level_map_ids(dst) = env.level_map_ids(src);
// Move markers, dungeon listeners and shopping list.
env.markers.move(src, dst);
dungeon_events.move_listeners(src, dst);
shopping_list.move_things(src, dst);
// Move player's knowledge.
env.map_knowledge(dst) = env.map_knowledge(src);
env.map_seen.set(dst, env.map_seen(src));
StashTrack.move_stash(src, dst);
}
static bool _dgn_shift_feature(const coord_def &pos)
{
const dungeon_feature_type dfeat = grd(pos);
if (!feat_is_critical(dfeat) && !env.markers.find(pos, MAT_ANY))
return false;
const coord_def dest =
_dgn_find_nearest_square(pos, _is_feature_shift_target);
dgn_move_entities_at(pos, dest, false, false, false);
return true;
}
static void _dgn_check_terrain_items(const coord_def &pos, bool preserve_items)
{
const dungeon_feature_type feat = grd(pos);
int item = igrd(pos);
while (item != NON_ITEM)
{
const int curr = item;
item = mitm[item].link;
if (!feat_is_solid(feat) && !feat_destroys_items(feat))
continue;
// Game-critical item.
if (preserve_items || mitm[curr].is_critical())
_dgn_shift_item(pos, mitm[curr]);
else
{
feat_splash_noise(feat);
item_was_destroyed(mitm[curr]);
destroy_item(curr);
}
}
}
static void _dgn_check_terrain_monsters(const coord_def &pos)
{
if (monster* m = monster_at(pos))
m->apply_location_effects(pos);
}
// Clear blood or off of terrain that shouldn't have it. Also clear of blood if
// a bloody wall has been dug out and replaced by a floor, or if a bloody floor
// has been replaced by a wall.
static void _dgn_check_terrain_covering(const coord_def &pos,
dungeon_feature_type old_feat,
dungeon_feature_type new_feat)
{
if (!testbits(env.pgrid(pos), FPROP_BLOODY))
return;
if (new_feat == DNGN_UNSEEN)
{
// Caller has already changed the grid, and old_feat is actually
// the new feat.
if (old_feat != DNGN_FLOOR && !feat_is_solid(old_feat))
env.pgrid(pos) &= ~(FPROP_BLOODY);
}
else
{
if (feat_is_solid(old_feat) != feat_is_solid(new_feat)
|| feat_is_water(new_feat) || new_feat == DNGN_LAVA
|| feat_is_critical(new_feat))
{
env.pgrid(pos) &= ~(FPROP_BLOODY);
}
}
}
static void _dgn_check_terrain_player(const coord_def pos)
{
if (crawl_state.generating_level || !crawl_state.need_save)
return; // don't reference player if they don't currently exist
if (pos != you.pos())
return;
if (you.can_pass_through(pos))
move_player_to_grid(pos, false);
else
you_teleport_now();
}
/**
* Change a given feature to a new type, cleaning up associated issues
* (monsters/items in walls, blood on water, etc) in the process.
*
* @param pos The location to be changed.
* @param nfeat The feature to be changed to.
* @param preserve_features Whether to shunt the old feature to a nearby loc.
* @param preserve_items Whether to shunt items to a nearby loc, if they
* can't stay in this one.
* @param temporary Whether the terrain change is only temporary & so
* shouldn't affect branch/travel knowledge.
* @param wizmode Whether this is a wizmode terrain change,
* & shouldn't check whether the player can actually
* exist in the new feature.
*/
void dungeon_terrain_changed(const coord_def &pos,
dungeon_feature_type nfeat,
bool preserve_features,
bool preserve_items,
bool temporary,
bool wizmode)
{
if (grd(pos) == nfeat)
return;
if (feat_is_wall(nfeat) && monster_at(pos))
return;
if (feat_is_trap(nfeat) && env.trap.find(pos) == env.trap.end())
{
// TODO: create a trap_def in env for this case?
mprf(MSGCH_ERROR,
"Attempting to change terrain to a trap without a corresponding"
" trap_def!");
nfeat = DNGN_FLOOR;
}
_dgn_check_terrain_covering(pos, grd(pos), nfeat);
if (nfeat != DNGN_UNSEEN)
{
if (preserve_features)
_dgn_shift_feature(pos);
if (!temporary)
unnotice_feature(level_pos(level_id::current(), pos));
grd(pos) = nfeat;
// Reset feature tile
env.tile_flv(pos).feat = 0;
env.tile_flv(pos).feat_idx = 0;
if (is_notable_terrain(nfeat) && you.see_cell(pos))
seen_notable_thing(nfeat, pos);
// Don't destroy a trap which was just placed.
if (!feat_is_trap(nfeat))
destroy_trap(pos);
}
_dgn_check_terrain_items(pos, preserve_items);
_dgn_check_terrain_monsters(pos);
if (!wizmode)
_dgn_check_terrain_player(pos);
if (!temporary && feature_mimic_at(pos))
env.level_map_mask(pos) &= ~MMT_MIMIC;
set_terrain_changed(pos);
// Deal with doors being created by changing features.
tile_init_flavour(pos);
}
static void _announce_swap_real(coord_def orig_pos, coord_def dest_pos)
{
const dungeon_feature_type orig_feat = grd(dest_pos);
const string orig_name =
feature_description_at(dest_pos, false,
you.see_cell(orig_pos) ? DESC_THE : DESC_A);
string prep = feat_preposition(orig_feat, false);
string orig_actor, dest_actor;
if (orig_pos == you.pos())
orig_actor = "you";
else if (const monster* m = monster_at(orig_pos))
{
if (you.can_see(*m))
orig_actor = m->name(DESC_THE);
}
if (dest_pos == you.pos())
dest_actor = "you";
else if (const monster* m = monster_at(dest_pos))
{
if (you.can_see(*m))
dest_actor = m->name(DESC_THE);
}
ostringstream str;
str << orig_name << " ";
if (you.see_cell(orig_pos) && !you.see_cell(dest_pos))
{
str << "suddenly disappears";
if (!orig_actor.empty())
str << " from " << prep << " " << orig_actor;
}
else if (!you.see_cell(orig_pos) && you.see_cell(dest_pos))
{
str << "suddenly appears";
if (!dest_actor.empty())
str << " " << prep << " " << dest_actor;
}
else
{
str << "moves";
if (!orig_actor.empty())
str << " from " << prep << " " << orig_actor;
if (!dest_actor.empty())
str << " to " << prep << " " << dest_actor;
}
str << "!";
mpr(str.str());
}
static void _announce_swap(coord_def pos1, coord_def pos2)
{
if (!you.see_cell(pos1) && !you.see_cell(pos2))
return;
const dungeon_feature_type feat1 = grd(pos1);
const dungeon_feature_type feat2 = grd(pos2);
if (feat1 == feat2)
return;
const bool notable_seen1 = is_notable_terrain(feat1) && you.see_cell(pos1);
const bool notable_seen2 = is_notable_terrain(feat2) && you.see_cell(pos2);
if (notable_seen1 && notable_seen2)
{
_announce_swap_real(pos1, pos2);
_announce_swap_real(pos2, pos1);
}
else if (notable_seen1)
_announce_swap_real(pos2, pos1);
else if (notable_seen2)
_announce_swap_real(pos1, pos2);
else if (you.see_cell(pos2))
_announce_swap_real(pos1, pos2);
else
_announce_swap_real(pos2, pos1);
}
bool swap_features(const coord_def &pos1, const coord_def &pos2,
bool swap_everything, bool announce)
{
ASSERT_IN_BOUNDS(pos1);
ASSERT_IN_BOUNDS(pos2);
ASSERT(pos1 != pos2);
if (is_sanctuary(pos1) || is_sanctuary(pos2))
return false;
const dungeon_feature_type feat1 = grd(pos1);
const dungeon_feature_type feat2 = grd(pos2);
if (is_notable_terrain(feat1) && !you.see_cell(pos1)
&& env.map_knowledge(pos1).known())
{
return false;
}
if (is_notable_terrain(feat2) && !you.see_cell(pos2)
&& env.map_knowledge(pos2).known())
{
return false;
}
const unsigned short col1 = env.grid_colours(pos1);
const unsigned short col2 = env.grid_colours(pos2);
const terrain_property_t prop1 = env.pgrid(pos1);
const terrain_property_t prop2 = env.pgrid(pos2);
trap_def* trap1 = trap_at(pos1);
trap_def* trap2 = trap_at(pos2);
shop_struct* shop1 = shop_at(pos1);
shop_struct* shop2 = shop_at(pos2);
// Find a temporary holding place for pos1 stuff to be moved to
// before pos2 is moved to pos1.
coord_def temp(-1, -1);
for (int x = X_BOUND_1 + 1; x < X_BOUND_2; x++)
{
for (int y = Y_BOUND_1 + 1; y < Y_BOUND_2; y++)
{
coord_def pos(x, y);
if (pos == pos1 || pos == pos2)
continue;
if (!env.markers.find(pos, MAT_ANY)
&& !is_notable_terrain(grd(pos))
&& !cloud_at(pos))
{
temp = pos;
break;
}
}
if (in_bounds(temp))
break;
}
if (!in_bounds(temp))
{
mprf(MSGCH_ERROR, "swap_features(): No boring squares on level?");
return false;
}
// OK, now we guarantee the move.
(void) move_notable_thing(pos1, temp);
env.markers.move(pos1, temp);
dungeon_events.move_listeners(pos1, temp);
grd(pos1) = DNGN_UNSEEN;
env.pgrid(pos1) = terrain_property_t{};
(void) move_notable_thing(pos2, pos1);
env.markers.move(pos2, pos1);
dungeon_events.move_listeners(pos2, pos1);
env.pgrid(pos1) = prop2;
env.pgrid(pos2) = prop1;
(void) move_notable_thing(temp, pos2);
env.markers.move(temp, pos2);
dungeon_events.move_listeners(temp, pos2);
// Swap features and colours.
grd(pos2) = feat1;
grd(pos1) = feat2;
env.grid_colours(pos1) = col2;
env.grid_colours(pos2) = col1;
// Swap traps.
if (trap1 && !trap2)
{
env.trap[pos2] = env.trap[pos1];
env.trap[pos2].pos = pos2;
env.trap.erase(pos1);
}
else if (!trap1 && trap2)
{
env.trap[pos1] = env.trap[pos2];
env.trap[pos1].pos = pos1;
env.trap.erase(pos2);
}
else if (trap1 && trap2)
{
trap_def tmp = env.trap[pos1];
env.trap[pos1] = env.trap[pos2];
env.trap[pos2] = tmp;
env.trap[pos1].pos = pos1;
env.trap[pos2].pos = pos2;
}
// Swap shops.
if (shop1 && !shop2)
{
env.shop[pos2] = env.shop[pos1];
env.shop[pos2].pos = pos2;
env.shop.erase(pos1);
}
else if (!shop1 && shop2)
{
env.shop[pos1] = env.shop[pos2];
env.shop[pos1].pos = pos1;
env.shop.erase(pos2);
}
else if (shop1 && shop2)
{
shop_struct tmp = env.shop[pos1];
env.shop[pos1] = env.shop[pos2];
env.shop[pos2] = tmp;
env.shop[pos1].pos = pos1;
env.shop[pos2].pos = pos2;
}
if (!swap_everything)
{
_dgn_check_terrain_items(pos1, false);
_dgn_check_terrain_monsters(pos1);
_dgn_check_terrain_player(pos1);
set_terrain_changed(pos1);
_dgn_check_terrain_items(pos2, false);
_dgn_check_terrain_monsters(pos2);
_dgn_check_terrain_player(pos2);
set_terrain_changed(pos2);
if (announce)
_announce_swap(pos1, pos2);
return true;
}
// Swap items.
for (stack_iterator si(pos1); si; ++si)
si->pos = pos1;
for (stack_iterator si(pos2); si; ++si)
si->pos = pos2;
// Swap monsters.
// Note that trapping nets, etc., move together
// with the monster/player, so don't clear them.
const int m1 = mgrd(pos1);
const int m2 = mgrd(pos2);
mgrd(pos1) = m2;
mgrd(pos2) = m1;
if (monster_at(pos1))
{
menv[mgrd(pos1)].set_position(pos1);
menv[mgrd(pos1)].clear_invalid_constrictions();
}
if (monster_at(pos2))
{
menv[mgrd(pos2)].set_position(pos2);
menv[mgrd(pos2)].clear_invalid_constrictions();
}
swap_clouds(pos1, pos2);
if (pos1 == you.pos())
{
you.set_position(pos2);
you.clear_invalid_constrictions();
viewwindow();
update_screen();
}
else if (pos2 == you.pos())
{
you.set_position(pos1);
you.clear_invalid_constrictions();
viewwindow();
update_screen();
}
set_terrain_changed(pos1);
set_terrain_changed(pos2);
if (announce)
_announce_swap(pos1, pos2);
return true;
}
static bool _ok_dest_cell(const actor* orig_actor,
const dungeon_feature_type orig_feat,
const coord_def dest_pos)
{
const dungeon_feature_type dest_feat = grd(dest_pos);
if (orig_feat == dest_feat)
return false;
if (is_notable_terrain(dest_feat))
return false;
if (trap_at(dest_pos))
return false;
actor* dest_actor = actor_at(dest_pos);
if (orig_actor && !orig_actor->is_habitable_feat(dest_feat))
return false;
if (dest_actor && !dest_actor->is_habitable_feat(orig_feat))
return false;
return true;
}
bool slide_feature_over(const coord_def &src, coord_def preferred_dest,
bool announce)
{
ASSERT_IN_BOUNDS(src);
const dungeon_feature_type orig_feat = grd(src);
const actor* orig_actor = actor_at(src);
if (in_bounds(preferred_dest)
&& _ok_dest_cell(orig_actor, orig_feat, preferred_dest))
{
ASSERT(preferred_dest != src);
}
else
{
int squares = 0;
for (adjacent_iterator ai(src); ai; ++ai)
{
if (_ok_dest_cell(orig_actor, orig_feat, *ai)
&& one_chance_in(++squares))
{
preferred_dest = *ai;
}
}
}
if (!in_bounds(preferred_dest))
return false;
ASSERT(preferred_dest != src);
return swap_features(src, preferred_dest, false, announce);
}
/**
* Apply harmful environmental effects from the current tile terrain to the
* player.
*
* @param entry The terrain type in question.
*/
void fall_into_a_pool(dungeon_feature_type terrain)
{
if (terrain == DNGN_DEEP_WATER)
{
if (you.can_water_walk() || form_likes_water())
return;
if (species_likes_water(you.species) && !you.transform_uncancellable)
{
emergency_untransform();
return;
}
}
mprf("You fall into the %s!",
(terrain == DNGN_LAVA) ? "lava" :
(terrain == DNGN_DEEP_WATER) ? "water"
: "programming rift");
// included in default force_more_message
enable_emergency_flight();
}
typedef map<string, dungeon_feature_type> feat_desc_map;
static feat_desc_map feat_desc_cache;
void init_feat_desc_cache()
{
for (int i = 0; i < NUM_FEATURES; i++)
{
dungeon_feature_type feat = static_cast<dungeon_feature_type>(i);
string desc = feature_description(feat);
lowercase(desc);
if (!feat_desc_cache.count(desc))
feat_desc_cache[desc] = feat;
}
}
dungeon_feature_type feat_by_desc(string desc)
{
lowercase(desc);
#if TAG_MAJOR_VERSION == 34
// hard-coded because all the dry fountain variants match this description,
// and they have a lower enum value, so the first is incorrectly returned
if (desc == "a dry fountain")
return DNGN_DRY_FOUNTAIN;
#endif
return lookup(feat_desc_cache, desc, DNGN_UNSEEN);
}
// If active is true, the player is just stepping onto the feature, with the
// message: "<feature> slides away as you move <prep> it!"
// Else, the actor is already on the feature:
// "<feature> moves from <prep origin> to <prep destination>!"
string feat_preposition(dungeon_feature_type feat, bool active, const actor* who)
{
const bool airborne = !who || who->airborne();
const command_type dir = feat_stair_direction(feat);
if (dir == CMD_NO_CMD)
{
if (feat == DNGN_STONE_ARCH)
return "beside";
else if (feat_is_solid(feat)) // Passwall?
{
if (active)
return "inside";
else
return "around";
}
else if (!airborne)
{
if (feat == DNGN_LAVA || feat_is_water(feat))
{
if (active)
return "into";
else
return "around";
}
else
{
if (active)
return "onto";
else
return "under";
}
}
}
if (dir == CMD_GO_UPSTAIRS && feat_is_escape_hatch(feat))
{
if (active)
return "under";
else
return "above";
}
if (airborne)
{
if (active)
return "over";
else
return "beneath";
}
if (dir == CMD_GO_DOWNSTAIRS
&& (feat_is_staircase(feat) || feat_is_escape_hatch(feat)))
{
if (active)
return "onto";
else
return "beneath";
}
else
return "beside";
}
string stair_climb_verb(dungeon_feature_type feat)
{
ASSERT(feat_stair_direction(feat) != CMD_NO_CMD);
if (feat_is_staircase(feat))
return "climb";
else if (feat_is_escape_hatch(feat))
return "use";
else
return "pass through";
}
/** Find the feature with this name.
*
* @param name The name (not the user-visible one) to be matched.
* @returns DNGN_UNSEEN if name is "", DNGN_FLOOR if the name is for a
* dead/forbidden god, and the first entry in the enum with a
* matching name otherwise.
*/
dungeon_feature_type dungeon_feature_by_name(const string &name)
{
if (name.empty())
return DNGN_UNSEEN;
for (unsigned i = 0; i < NUM_FEATURES; ++i)
{
dungeon_feature_type feat = static_cast<dungeon_feature_type>(i);
if (!is_valid_feature_type(feat))
continue;
if (get_feature_def(feat).vaultname == name)
{
if (feat_is_altar(feat)
&& is_unavailable_god(feat_altar_god(feat)))
{
return DNGN_FLOOR;
}
return feat;
}
}
return DNGN_UNSEEN;
}
/** Find feature names that contain this name.
*
* @param name The string to be matched.
* @returns a list of matching names.
*/
vector<string> dungeon_feature_matches(const string &name)
{
vector<string> matches;
if (name.empty())
return matches;
for (unsigned i = 0; i < NUM_FEATURES; ++i)
{
dungeon_feature_type feat = static_cast<dungeon_feature_type>(i);
if (!is_valid_feature_type(feat))
continue;
const char *featname = get_feature_def(feat).vaultname;
if (strstr(featname, name.c_str()))
matches.emplace_back(featname);
}
return matches;
}
/** Get the lua/wizmode name for a feature.
*
* @param rfeat The feature type to be found.
* @returns nullptr if rfeat is not defined, the vaultname of the corresponding
* feature_def otherwise.
*/
const char *dungeon_feature_name(dungeon_feature_type rfeat)
{
if (!is_valid_feature_type(rfeat))
return nullptr;
return get_feature_def(rfeat).vaultname;
}
void destroy_wall(const coord_def& p)
{
if (!in_bounds(p))
return;
// Blood does not transfer onto floor.
if (is_bloodcovered(p))
env.pgrid(p) &= ~(FPROP_BLOODY);
_revert_terrain_to_floor(p);
env.level_map_mask(p) |= MMT_TURNED_TO_FLOOR;
}
const char* feat_type_name(dungeon_feature_type feat)
{
if (feat_is_door(feat))
return "door";
if (feat_is_wall(feat))
return "wall";
if (feat == DNGN_GRATE)
return "grate";
if (feat_is_tree(feat))
return "tree";
if (feat_is_statuelike(feat))
return "statue";
if (feat_is_water(feat))
return "water";
if (feat_is_lava(feat))
return "lava";
if (feat_is_altar(feat))
return "altar";
if (feat_is_trap(feat))
return "trap";
if (feat_is_escape_hatch(feat))
return "escape hatch";
if (feat_is_portal(feat) || feat_is_gate(feat))
return "portal";
if (feat_is_travelable_stair(feat))
return "staircase";
if (feat == DNGN_ENTER_SHOP || feat == DNGN_ABANDONED_SHOP)
return "shop";
if (feat_is_fountain(feat))
return "fountain";
if (feat == DNGN_UNSEEN)
return "unknown terrain";
return "floor";
}
void set_terrain_changed(const coord_def p)
{
if (cell_is_solid(p))
delete_cloud(p);
if (grd(p) == DNGN_SLIMY_WALL)
env.level_state |= LSTATE_SLIMY_WALL;
else if (grd(p) == DNGN_OPEN_DOOR)
{
// Restore colour from door-change markers
for (map_marker *marker : env.markers.get_markers_at(p))
{
if (marker->get_type() == MAT_TERRAIN_CHANGE)
{
map_terrain_change_marker* tmarker =
dynamic_cast<map_terrain_change_marker*>(marker);
if (tmarker->change_type == TERRAIN_CHANGE_DOOR_SEAL
&& tmarker->colour != BLACK)
{
// Restore the unsealed colour.
dgn_set_grid_colour_at(p, tmarker->colour);
break;
}
}
}
}
env.map_knowledge(p).flags |= MAP_CHANGED_FLAG;
dungeon_events.fire_position_event(DET_FEAT_CHANGE, p);
los_terrain_changed(p);
}
/**
* Does this cell count for exploration piety?
*
* Don't count: endless map borders, deep water, lava, and cells explicitly
* marked. (player_view_update_at in view.cc updates the flags)
*/
bool cell_triggers_conduct(const coord_def p)
{
return !(feat_is_endless(grd(p))
|| grd(p) == DNGN_LAVA
|| grd(p) == DNGN_DEEP_WATER
|| env.pgrid(p) & FPROP_SEEN_OR_NOEXP);
}
bool is_boring_terrain(dungeon_feature_type feat)
{
if (!is_notable_terrain(feat))
return true;
// Altars in the temple are boring.
if (feat_is_altar(feat) && player_in_branch(BRANCH_TEMPLE))
return true;
// Only note the first entrance to the Abyss/Pan/Hell
// which is found.
if ((feat == DNGN_ENTER_ABYSS || feat == DNGN_ENTER_PANDEMONIUM
|| feat == DNGN_ENTER_HELL)
&& overview_knows_num_portals(feat) > 1)
{
return true;
}
return false;
}
dungeon_feature_type orig_terrain(coord_def pos)
{
const map_marker *mark = env.markers.find(pos, MAT_TERRAIN_CHANGE);
if (!mark)
return grd(pos);
const map_terrain_change_marker *terch
= dynamic_cast<const map_terrain_change_marker *>(mark);
ASSERTM(terch, "%s has incorrect class", mark->debug_describe().c_str());
return terch->old_feature;
}
void temp_change_terrain(coord_def pos, dungeon_feature_type newfeat, int dur,
terrain_change_type type, const monster* mon)
{
dungeon_feature_type old_feat = grd(pos);
for (map_marker *marker : env.markers.get_markers_at(pos))
{
if (marker->get_type() == MAT_TERRAIN_CHANGE)
{
map_terrain_change_marker* tmarker =
dynamic_cast<map_terrain_change_marker*>(marker);
// If change type matches, just modify old one; no need to add new one
if (tmarker->change_type == type)
{
if (tmarker->new_feature == newfeat)
{
if (tmarker->duration < dur)
{
tmarker->duration = dur;
if (mon)
tmarker->mon_num = mon->mid;
}
}
else
{
tmarker->new_feature = newfeat;
tmarker->duration = dur;
if (mon)
tmarker->mon_num = mon->mid;
}
// ensure that terrain change happens. Sometimes a terrain
// change marker can get stuck; this allows re-doing such
// cases. Also probably needed by the else case above.
dungeon_terrain_changed(pos, newfeat, false, true, true);
return;
}
else
old_feat = tmarker->old_feature;
}
}
// If we are trying to change terrain into what it already is, don't actually
// add another marker (unless the current terrain is due to some OTHER marker)
if (grd(pos) == newfeat && newfeat == old_feat)
return;
int col = env.grid_colours(pos);
map_terrain_change_marker *marker =
new map_terrain_change_marker(pos, old_feat, newfeat, dur, type,
mon ? mon->mid : 0, col);
env.markers.add(marker);
env.markers.clear_need_activate();
dungeon_terrain_changed(pos, newfeat, false, true, true);
}
/// What terrain type do destroyed feats become, in the current branch?
static dungeon_feature_type _destroyed_feat_type()
{
return player_in_branch(BRANCH_SWAMP) ?
DNGN_SHALLOW_WATER :
DNGN_FLOOR;
}
static bool _revert_terrain_to_floor(coord_def pos)
{
dungeon_feature_type newfeat = _destroyed_feat_type();
for (map_marker *marker : env.markers.get_markers_at(pos))
{
if (marker->get_type() == MAT_TERRAIN_CHANGE)
{
map_terrain_change_marker* tmarker =
dynamic_cast<map_terrain_change_marker*>(marker);
// Don't revert sealed doors to normal doors if we're trying to
// remove the door altogether
// Same for destroyed trees
if ((tmarker->change_type == TERRAIN_CHANGE_DOOR_SEAL
|| tmarker->change_type == TERRAIN_CHANGE_FORESTED)
&& newfeat == _destroyed_feat_type())
{
env.markers.remove(tmarker);
}
else
{
newfeat = tmarker->old_feature;
if (tmarker->new_feature == grd(pos))
env.markers.remove(tmarker);
}
}
}
if (grd(pos) == DNGN_RUNED_DOOR && newfeat != DNGN_RUNED_DOOR
|| grd(pos) == DNGN_RUNED_CLEAR_DOOR
&& newfeat != DNGN_RUNED_CLEAR_DOOR)
{
explored_tracked_feature(grd(pos));
}
grd(pos) = newfeat;
set_terrain_changed(pos);
tile_clear_flavour(pos);
tile_init_flavour(pos);
return true;
}
bool revert_terrain_change(coord_def pos, terrain_change_type ctype)
{
dungeon_feature_type newfeat = DNGN_UNSEEN;
int colour = BLACK;
for (map_marker *marker : env.markers.get_markers_at(pos))
{
if (marker->get_type() == MAT_TERRAIN_CHANGE)
{
map_terrain_change_marker* tmarker =
dynamic_cast<map_terrain_change_marker*>(marker);
if (tmarker->change_type == ctype)
{
if (tmarker->colour != BLACK)
colour = tmarker->colour;
if (!newfeat)
newfeat = tmarker->old_feature;
env.markers.remove(tmarker);
}
else
{
// If we had an old colour, give it to the other marker.
if (colour != BLACK)
tmarker->colour = colour;
colour = BLACK;
newfeat = tmarker->new_feature;
}
}
}
// Don't revert opened sealed doors.
if (feat_is_door(newfeat) && grd(pos) == DNGN_OPEN_DOOR)
newfeat = DNGN_UNSEEN;
if (newfeat != DNGN_UNSEEN)
{
if (ctype == TERRAIN_CHANGE_BOG)
env.map_knowledge(pos).set_feature(newfeat, colour);
dungeon_terrain_changed(pos, newfeat, false, true);
env.grid_colours(pos) = colour;
return true;
}
else
return false;
}
bool is_temp_terrain(coord_def pos)
{
for (map_marker *marker : env.markers.get_markers_at(pos))
if (marker->get_type() == MAT_TERRAIN_CHANGE)
return true;
return false;
}
bool plant_forbidden_at(const coord_def &p, bool connectivity_only)
{
// .... Prevent this arrangement by never placing a plant in a way that
// #P## locally disconnects two adjacent cells. We scan clockwise around
// ##.# p looking for maximal contiguous sequences of traversable cells.
// #?## If we find more than one (and they don't join up cyclically),
// reject the configuration so the plant doesn't disconnect floor.
//
// ... We do reject many non-problematic cases, such as this one; dpeg
// #P# suggests doing a connectivity check in ruination after placing
// ... plants, and removing cut-point plants then.
// First traversable index, last consecutive traversable index, and
// the next traversable index after last+1.
int first = -1, last = -1, next = -1;
int passable = 0;
for (int i = 0; i < 8; i++)
{
coord_def q = p + Compass[i];
if (feat_is_traversable(grd(q), true))
{
++passable;
if (first < 0)
first = i;
else if (last >= 0 && next < 0)
{
// Found a maybe-disconnected traversable cell. This is only
// acceptable if it might connect up at the end.
if (first == 0)
next = i;
else
return true;
}
}
else
{
if (first >= 0 && last < 0)
last = i - 1;
else if (next >= 0)
return true;
}
}
// ?#. Forbid this arrangement when the ? squares are walls.
// #P# If multiple plants conspire to do something similar, that's
// ##? fine: we just want to avoid the most common occurrences.
// This would be an info leak (that at least one ? is not a wall)
// were it not for the previous check.
return passable <= 1 && !connectivity_only;
}
/*
* Find an adjacent space to displace a stack of items or a creature.
*
* @param pos the starting position to displace from.
* @param push_actor true if the goal is to move an actor, false if items
* @param excluded any spots to rule out a priori. Used for e.g. imprison and
* for multi-space doors.
*
* @return a (possibly empty) vector of positions where displacement is
* possible. If `push_actor` is true but there is no
* actor at the position, will return an empty list.
*/
vector<coord_def> get_push_spaces(const coord_def& pos, bool push_actor,
const vector<coord_def>* excluded)
{
vector<coord_def> results;
actor *act = nullptr;
if (push_actor)
{
act = actor_at(pos);
if (!act || act->is_stationary())
return results;
}
dungeon_feature_type starting_feat = grd(pos);
vector<coord_def> bad_spots; // used for items
for (adjacent_iterator ai(pos); ai; ++ai)
{
dungeon_feature_type feat = grd(*ai);
// Make sure the spot wasn't already vetoed. This is used e.g. for
// imprison, to pre-exclude all the spots where a wall will be.
if (excluded && find(begin(*excluded), end(*excluded), *ai)
!= end(*excluded))
{
continue;
}
// can never push to a solid space
if (feat_is_solid(feat))
continue;
// Extra checks if we're moving a monster instead of an item
if (push_actor)
{
// these should get deep water and lava for cases where they matter
if (actor_at(*ai)
|| !act->can_pass_through(*ai)
|| !act->is_habitable(*ai))
{
continue;
}
results.push_back(*ai);
}
else
{
if (feat_has_solid_floor(feat))
results.push_back(*ai);
else if (starting_feat == DNGN_DEEP_WATER
&& feat == DNGN_DEEP_WATER)
{
// Dispreferentially allow pushing items from deep water to
// deep water. Without this, zin imprison fails over deep
// water if there are items, even if the player can't see
// them.
bad_spots.push_back(*ai);
}
// otherwise, can't position an item on this spot
}
}
if (!results.empty())
return results;
return bad_spots;
}
bool has_push_spaces(const coord_def& pos, bool push_actor,
const vector<coord_def>* excluded)
{
return !get_push_spaces(pos, push_actor, excluded).empty();
}
/**
* Push items from `pos`, splashing them around whatever available spaces
* there are.
* @param pos the source position.
* @param excluded positions that are a priori unavailable.
*
* @return true if any items moved, false otherwise. (Will return false if there
* were no items.)
*/
bool push_items_from(const coord_def& pos, const vector<coord_def>* excluded)
{
vector<coord_def> targets = get_push_spaces(pos, false, excluded);
bool result = false;
if (targets.empty())
return false;
// TODO: splashing is flavorful, but how annoying is it in practice?
while (igrd(pos) != NON_ITEM)
result |= move_top_item(pos, targets[random2(targets.size())]);
return result;
}
/**
* Push an actor from `pos` to some available space, if possible.
*
* @param pos the source position.
* @param excluded excluded positions that are a priori unavailable.
* @param random whether to chose the position randomly, or deterministically.
* (Useful for systematically moving a bunch of actors at once, when you
* need to worry about domino effects.)
*
* @return the new coordinates for the actor.
*/
coord_def push_actor_from(const coord_def& pos,
const vector<coord_def>* excluded, bool random)
{
actor* act = actor_at(pos);
if (!act)
return coord_def(0,0);
vector<coord_def> targets = get_push_spaces(pos, true, excluded);
if (targets.empty())
return coord_def(0,0);
const coord_def newpos = random ? targets[random2(targets.size())]
: targets.front();
ASSERT(!newpos.origin());
act->move_to_pos(newpos);
// The new position of the monster is now an additional veto spot for
// monsters.
return newpos;
}
/** Close any door at the given position. Handles the grid change, but does not
* mark terrain or do any event handling.
*
* @param dest The location of the door.
*/
void dgn_close_door(const coord_def &dest)
{
if (!feat_is_open_door(grd(dest)))
return;
if (grd(dest) == DNGN_OPEN_CLEAR_DOOR)
grd(dest) = DNGN_CLOSED_CLEAR_DOOR;
else
grd(dest) = DNGN_CLOSED_DOOR;
}
/** Open any door at the given position. Handles the grid change, but does not
* mark terrain or do any event handling.
*
* @param dest The location of the door.
*/
void dgn_open_door(const coord_def &dest)
{
if (!feat_is_closed_door(grd(dest)))
return;
if (grd(dest) == DNGN_CLOSED_CLEAR_DOOR
|| grd(dest) == DNGN_RUNED_CLEAR_DOOR)
{
grd(dest) = DNGN_OPEN_CLEAR_DOOR;
}
else
grd(dest) = DNGN_OPEN_DOOR;
}
void ice_wall_damage(monster &mons, int delay)
{
if (!you.duration[DUR_FROZEN_RAMPARTS]
|| !you.see_cell_no_trans(mons.pos())
|| mons_aligned(&you, &mons))
{
return;
}
const int walls = count_adjacent_icy_walls(mons.pos());
if (!walls)
return;
const int pow = calc_spell_power(SPELL_FROZEN_RAMPARTS, true);
const int orig_dam = div_rand_round(
delay * roll_dice(1, 2 + div_rand_round(pow, 5)), BASELINE_DELAY);
bolt beam;
beam.flavour = BEAM_COLD;
beam.thrower = KILL_YOU;
int dam = mons_adjust_flavoured(&mons, beam, orig_dam);
mprf("The wall freezes %s%s%s",
you.can_see(mons) ? mons.name(DESC_THE).c_str() : "something",
dam ? "" : " but do no damage",
attack_strength_punctuation(dam).c_str());
if (dam > 0)
{
mons.hurt(&you, dam, BEAM_COLD);
if (mons.alive())
{
behaviour_event(&mons, ME_WHACK, &you);
mons.expose_to_element(BEAM_COLD, orig_dam);
}
}
}
|
/*
Copyright (c) 2017 TOSHIBA Digital Solutions Corporation
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*!
@file
@brief Implementation of Exception and Trace
*/
#include "gs_error.h"
#include "util/container.h"
GSExceptionRegenerator::GSExceptionRegenerator(
UTIL_EXCEPTION_CONSTRUCTOR_ARGS_LIST) throw()
: fileNameLiteral_(fileNameLiteral),
functionNameLiteral_(functionNameLiteral),
critical_(false) {
util::Exception cause;
util::Exception::DuplicatedLiteralFlags filteredFlags;
const util::Exception::DuplicatedLiteralFlags baseFlags =
util::Exception::LITERAL_ALL_DUPLICATED;
NamedErrorCode filteredCode;
const char8_t *extraMessage = NULL;
if (causeInHandling != NULL) {
NamedErrorCode causeCode;
bool userOrSystemThrown = false;
bool unexpectedType = false;
try {
throw;
}
catch (const UserException &e) {
cause = e;
userOrSystemThrown = true;
causeCode = selectErrorCode(e.getNamedErrorCode(),
GS_EXCEPTION_NAMED_CODE(GS_ERROR_CM_INTERNAL_ERROR));
filteredFlags = e.inheritLiteralFlags(baseFlags) | literalFlags;
}
catch (const SystemException &e) {
cause = e;
critical_ = true;
userOrSystemThrown = true;
causeCode = selectErrorCode(e.getNamedErrorCode(),
GS_EXCEPTION_NAMED_CODE(GS_ERROR_CM_INTERNAL_ERROR));
filteredFlags = e.inheritLiteralFlags(baseFlags) | literalFlags;
}
catch (const util::PlatformException &e) {
cause = e;
causeCode = GS_EXCEPTION_NAMED_CODE(GS_ERROR_CM_PLATFORM_ERROR);
filteredFlags = e.inheritLiteralFlags(baseFlags) | literalFlags;
}
catch (const util::UtilityException &e) {
cause = e;
switch (e.getErrorCode()) {
case util::UtilityException::CODE_NO_MEMORY:
causeCode = GS_EXCEPTION_NAMED_CODE(GS_ERROR_CM_NO_MEMORY);
break;
case util::UtilityException::CODE_MEMORY_LIMIT_EXCEEDED:
causeCode =
GS_EXCEPTION_NAMED_CODE(GS_ERROR_CM_MEMORY_LIMIT_EXCEEDED);
break;
case util::UtilityException::CODE_SIZE_LIMIT_EXCEEDED:
causeCode =
GS_EXCEPTION_NAMED_CODE(GS_ERROR_CM_SIZE_LIMIT_EXCEEDED);
break;
default:
causeCode = GS_EXCEPTION_NAMED_CODE(GS_ERROR_CM_INTERNAL_ERROR);
extraMessage = "Internal error by unexpected utility problem";
break;
}
filteredFlags = literalFlags;
}
catch (const util::Exception &e) {
cause = e;
if (e.getErrorCode() == 0) {
critical_ = true;
unexpectedType = true;
causeCode = GS_EXCEPTION_NAMED_CODE(GS_ERROR_CM_INTERNAL_ERROR);
filteredFlags = literalFlags;
}
else {
causeCode = e.getNamedErrorCode();
filteredFlags = e.inheritLiteralFlags(baseFlags) | literalFlags;
}
}
catch (const std::bad_alloc &) {
causeCode = GS_EXCEPTION_NAMED_CODE(GS_ERROR_CM_NO_MEMORY);
filteredFlags = literalFlags;
}
catch (...) {
critical_ = true;
unexpectedType = true;
causeCode = GS_EXCEPTION_NAMED_CODE(GS_ERROR_CM_INTERNAL_ERROR);
filteredFlags = literalFlags;
}
filteredCode = selectErrorCode(namedErrorCode, causeCode);
if (userOrSystemThrown &&
causeCode.getCode() == GS_ERROR_CM_INTERNAL_ERROR &&
cause.getErrorCode() == GS_ERROR_DEFAULT) {
extraMessage = "Internal error by empty error code";
}
else if (unexpectedType) {
extraMessage = "Internal error by unexpected exception type";
}
}
else {
filteredCode = namedErrorCode;
filteredFlags = literalFlags;
}
filteredCode = selectErrorCode(
filteredCode, GS_EXCEPTION_NAMED_CODE(GS_ERROR_CM_INTERNAL_ERROR));
typedef util::NormalOStringStream StrStream;
typedef util::Exception::NoThrowString<StrStream::allocator_type> SafeStr;
StrStream baseStream;
baseStream << cause.getField(util::Exception::FIELD_MESSAGE);
SafeStr baseStr(baseStream);
const char8_t *strPtr = baseStr.get();
const char8_t *baseMessage =
(message != NULL && strlen(message) > 0)
? message
: (strPtr == NULL || strlen(strPtr) > 0 ? strPtr : NULL);
if (baseMessage != NULL && !namedErrorCode.isEmpty()) {
extraMessage = NULL;
}
StrStream messageStream;
if (extraMessage == NULL) {
if (baseMessage != NULL) {
messageStream << baseMessage;
}
}
else {
messageStream << extraMessage;
if (baseMessage != NULL) {
messageStream << " (reason=" << baseMessage << ")";
}
}
base_ = util::Exception(filteredCode, SafeStr(messageStream).get(), NULL,
NULL, lineNumber, causeInHandling, typeNameLiteral, stackTraceMode,
filteredFlags);
}
void GSExceptionRegenerator::generate(
util::Exception &dest, const char8_t *typeName) const throw() {
util::Exception cause;
try {
cause.assign(base_, 1);
throw cause;
}
catch (...) {
dest = util::Exception(base_.getNamedErrorCode(),
UTIL_EXCEPTION_CREATE_MESSAGE_CHARS(base_.getField(
util::Exception::FIELD_MESSAGE)),
fileNameLiteral_, functionNameLiteral_, base_.getLineNumber(),
&cause, typeName, util::Exception::STACK_TRACE_NONE,
base_.inheritLiteralFlags());
}
}
GSExceptionRegenerator::NamedErrorCode
GSExceptionRegenerator::getNamedErrorCode() const throw() {
return base_.getNamedErrorCode();
}
/*!
@brief Formats data by field type
*/
void GSExceptionRegenerator::formatField(
std::ostream &stream, util::Exception::FieldType fieldType) const throw() {
base_.formatField(stream, fieldType);
}
bool GSExceptionRegenerator::getCause(util::Exception &dest) const throw() {
if (base_.getMaxDepth() > 0) {
dest.assign(base_, 1);
return true;
}
return false;
}
const GSExceptionRegenerator::NamedErrorCode &
GSExceptionRegenerator::selectErrorCode(
const NamedErrorCode &primary, const NamedErrorCode &secondary) throw() {
return (primary.isEmpty() ? secondary : primary);
}
GSTraceFormatter::GSTraceFormatter(const char8_t *secretHexKey) :
secret_(true), traceLocationVisible_(false)
{
util::NormalIStringStream iss(secretHexKey);
util::NormalOStringStream oss;
util::HexConverter::decode(oss, iss);
std::string keyStr = oss.str();
secretKey_.reserve(keyStr.size());
for (std::string::iterator it = keyStr.begin(); it != keyStr.end(); ++it) {
secretKey_.push_back(static_cast<uint8_t>(*it));
}
if (secretKey_.empty()) {
GS_THROW_SYSTEM_ERROR(GS_ERROR_CM_INTERNAL_ERROR, "Empty secret key");
}
}
GSTraceFormatter::~GSTraceFormatter() {}
void GSTraceFormatter::setSecret(bool secret) {
secret_ = secret;
}
void GSTraceFormatter::setTraceLocationVisible(bool visible) {
traceLocationVisible_ = visible;
}
/*!
@brief Formats error message
*/
void GSTraceFormatter::format(std::ostream &stream, util::TraceRecord &record) {
util::Exception cause;
GSExceptionRegenerator regenerator(record.namedErrorCode_, record.message_,
NULL, NULL, 0, record.causeInHandling_, NULL,
util::Exception::STACK_TRACE_NONE);
if (regenerator.getCause(cause)) {
record.cause_ = &cause;
if (record.namedErrorCode_.isEmpty()) {
record.namedErrorCode_ = regenerator.getNamedErrorCode();
}
}
u8string message;
try {
util::NormalOStringStream oss;
regenerator.formatField(oss, util::Exception::FIELD_MESSAGE);
message = oss.str();
record.message_ = message.c_str();
}
catch (std::bad_alloc &) {
record.message_ =
"(Failed to format error message by not enough memory)";
}
catch (...) {
record.message_ = "(Failed to format error message by unknown error)";
}
Base::format(stream, record);
}
void GSTraceFormatter::formatFiltered(
std::ostream &stream, const util::TraceRecord &record) {
const bool codeAndSymbolCombined = true;
stream << record.dateTime_ << " ";
if (record.hostName_ != NULL) {
stream << record.hostName_ << " ";
}
stream << util::Thread::getSelfId() << " ";
formatLevel(stream, record);
if (!codeAndSymbolCombined) {
formatMainErrorCode(stream, record, false, " ");
}
if (record.tracerName_ != NULL) {
stream << " " << record.tracerName_;
}
if (codeAndSymbolCombined) {
if (formatMainErrorCode(stream, record, false, " [")) {
formatMainErrorCode(stream, record, true, ":");
stream << "]";
}
}
else {
formatMainErrorCode(stream, record, true, " ");
}
if (record.message_ != NULL && *record.message_ != '\0') {
stream << (codeAndSymbolCombined ? " " : " : ") << record.message_;
}
if (record.cause_ != NULL) {
stream << " <";
if (secret_) {
util::NormalOStringStream oss;
formatMainLocation(oss, record, "");
formatCause(oss, record, " ");
util::NormalIStringStream iss(obfuscate(oss.str()));
util::Base64Converter::encode(stream, iss);
}
else {
formatMainLocation(stream, record, "");
formatCause(stream, record, " ");
}
stream << ">";
}
}
u8string GSTraceFormatter::obfuscate(const u8string &src) {
assert(!secretKey_.empty());
u8string dest = src;
for (u8string::iterator it = dest.begin(); it != dest.end(); ++it) {
*it = static_cast<char8_t>(*it ^ static_cast<char8_t>(
secretKey_[(it - dest.begin()) % secretKey_.size()]));
}
return dest;
}
InterruptionChecker::InterruptionChecker() :
flags_(0),
handler_(NULL) {
}
void InterruptionChecker::setCheckHandler(CheckHandler *handler) {
handler_ = handler;
const int32_t flag = (1 << INTERRUPTION_HANDLER);
if (handler == NULL) {
flags_ &= ~flag;
}
else {
flags_ |= flag;
}
}
void InterruptionChecker::setInterruption(InterruptionType type) {
flags_ |= (1 << type);
}
void InterruptionChecker::clearInterruption() {
flags_ &= (1 << INTERRUPTION_HANDLER);
}
bool InterruptionChecker::checkFlags(int32_t flags) {
if ((flags & (1 << INTERRUPTION_CANCEL)) != 0) {
errorCanceled();
}
else if ((flags & (1 << INTERRUPTION_SUSPEND)) != 0) {
return true;
}
return false;
}
void InterruptionChecker::errorCanceled() {
GS_THROW_USER_ERROR(GS_ERROR_CM_CANCELED, "");
}
bool InterruptionChecker::checkInternal() {
const int32_t flags = flags_;
if (flags != 0) {
if (handler_ != NULL) {
return (*handler_)(*this, flags);
}
return checkFlags(flags);
}
return false;
}
InterruptionChecker::CheckHandler::~CheckHandler() {
}
|
/*
* Copyright 2008 Search Solution Corporation
* Copyright 2016 CUBRID Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/*
* test_memory_alloc_helper.hpp - helper classes and function for test memory alloc
*/
#ifndef _TEST_MEMORY_ALLOC_HELPER_HPP_
#define _TEST_MEMORY_ALLOC_HELPER_HPP_
#include "test_string_collection.hpp"
#include "memory_private_allocator.hpp"
#include "thread_entry.hpp"
/* this hack */
#ifdef strlen
#undef strlen
#endif /* strlen */
#include <iostream>
#include <thread>
namespace test_memalloc
{
/************************************************************************/
/* helpers */
/************************************************************************/
const size_t SIZE_64 = 64;
const size_t SIZE_ONE_K = 1024;
const size_t SIZE_16_K = 16 * 1024;
const size_t SIZE_1_M = 1024 * 1024;
const size_t SIZE_100_M = SIZE_1_M * 100;
/* thread entry wrapper */
class custom_thread_entry
{
public:
custom_thread_entry ();
~custom_thread_entry ();
THREAD_ENTRY *get_thread_entry ();
void check_resource_leaks (void);
private:
void start_resource_tracking (void);
THREAD_ENTRY m_thread_entry;
int m_rc_track_id;
};
/* Mallocator - allocator concept to be used with malloc/free
*/
template <typename T>
class mallocator
{
public:
T *allocate (size_t size)
{
return (T *) malloc (size * sizeof (T));
}
void deallocate (T *pointer, size_t UNUSED (size))
{
free (pointer);
}
size_t max_size (void) const
{
return 0x7FFFFFFF;
}
private:
};
template <class T, class U>
bool
operator== (const mallocator<T> &, const mallocator<U> &)
{
return true;
}
template <class T, class U>
bool
operator!= (const mallocator<T> &, const mallocator<U> &)
{
return false;
}
/* allocators */
typedef enum test_allocator_type
{
PRIVATE,
STANDARD,
MALLOC,
COUNT
} test_allocator_type;
const test_common::string_collection &get_allocator_names (void);
/* Generic functions to allocate an allocator with thread entry argument. */
template <typename T>
void
init_allocator (custom_thread_entry &cte, std::allocator<T> *&alloc, test_allocator_type &type_out)
{
alloc = new std::allocator<T> ();
type_out = test_allocator_type::STANDARD;
}
template <typename T>
void
init_allocator (custom_thread_entry &cte, mallocator<T> *&alloc, test_allocator_type &type_out)
{
alloc = new mallocator<T> ();
type_out = test_allocator_type::MALLOC;
}
template <typename T>
void
init_allocator (custom_thread_entry &cte, cubmem::private_allocator<T> *&alloc, test_allocator_type &type_out)
{
alloc = new cubmem::private_allocator<T> (cte.get_thread_entry ());
type_out = test_allocator_type::PRIVATE;
}
/* run test and wrap with formatted text */
template <typename Func, typename ... Args>
void
run_test (int &global_err, Func &&f, Args &&... args)
{
std::cout << std::endl;
std::cout << " starting test - " << std::endl;;
int err = f (std::forward<Args> (args)...);
if (err == 0)
{
std::cout << " test successful" << std::endl;
}
else
{
std::cout << " test failed" << std::endl;
global_err = global_err != 0 ? global_err : err;
}
}
/* run test on multiple thread and wrap with formatted text */
template <typename Func, typename ... Args>
void
run_parallel (Func &&f, Args &&... args)
{
unsigned int worker_count = std::thread::hardware_concurrency ();
worker_count = worker_count != 0 ? worker_count : 24;
std::cout << std::endl;
std::cout << " starting test with " << worker_count << " concurrent threads - " << std::endl;;
std::thread *workers = new std::thread [worker_count];
for (unsigned int i = 0; i < worker_count; i++)
{
workers[i] = std::thread (std::forward<Func> (f), std::forward<Args> (args)...);
}
for (unsigned int i = 0; i < worker_count; i++)
{
workers[i].join ();
}
std::cout << " finished test with " << worker_count << " concurrent threads - " << std::endl;;
std::cout << std::endl;
}
} // namespace test_memalloc
#endif // !_TEST_MEMORY_ALLOC_HELPER_HPP_
|
#pragma once
#include "tria/fs.hpp"
#include <exception>
#include <string>
#include <string_view>
namespace tria::log::err {
/*
* Exception that is thrown when an error occurs while creating a log file.
*/
class LogFileErr final : public std::exception {
public:
LogFileErr() = delete;
LogFileErr(const fs::path& path, std::string_view msg) :
m_path{path},
m_innerMsg{msg},
m_msg{std::string{"Failed to create log file: "} + std::string{msg} + ": " +
m_path.string()} {}
[[nodiscard]] auto what() const noexcept -> const char* override { return m_msg.c_str(); }
[[nodiscard]] auto getInnerMsg() const noexcept -> const std::string_view { return m_innerMsg; }
[[nodiscard]] auto getPath() const noexcept -> const fs::path& { return m_path; }
private:
fs::path m_path;
std::string m_innerMsg;
std::string m_msg;
};
} // namespace tria::log::err
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.