text
stringlengths 54
60.6k
|
|---|
<commit_before>/*
* Copyright © 2013 Intel Corporation
*
* 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 (including the next
* paragraph) 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.
*/
/** @file brw_dead_control_flow.cpp
*
* This file implements the dead control flow elimination optimization pass.
*/
#include "brw_shader.h"
#include "brw_cfg.h"
/* Look for and eliminate dead control flow:
*
* - if/endif
* - else in else/endif
* - then in if/else/endif
*/
bool
dead_control_flow_eliminate(backend_shader *s)
{
bool progress = false;
foreach_block_safe (block, s->cfg) {
bblock_t *prev_block = block->prev();
backend_instruction *const inst = block->start();
backend_instruction *const prev_inst = prev_block->end();
/* ENDIF instructions, by definition, can only be found at the start of
* basic blocks.
*/
if (inst->opcode == BRW_OPCODE_ENDIF &&
prev_inst->opcode == BRW_OPCODE_ELSE) {
bblock_t *const else_block = prev_block;
backend_instruction *const else_inst = prev_inst;
else_inst->remove(else_block);
progress = true;
} else if (inst->opcode == BRW_OPCODE_ENDIF &&
prev_inst->opcode == BRW_OPCODE_IF) {
bblock_t *const endif_block = block;
bblock_t *const if_block = prev_block;
backend_instruction *const endif_inst = inst;
backend_instruction *const if_inst = prev_inst;
bblock_t *earlier_block = NULL, *later_block = NULL;
if (if_block->start_ip == if_block->end_ip) {
earlier_block = if_block->prev();
} else {
earlier_block = if_block;
}
if_inst->remove(if_block);
if (endif_block->start_ip == endif_block->end_ip) {
later_block = endif_block->next();
} else {
later_block = endif_block;
}
endif_inst->remove(endif_block);
assert((earlier_block == NULL) == (later_block == NULL));
if (earlier_block && earlier_block->can_combine_with(later_block)) {
earlier_block->combine_with(later_block);
/* If ENDIF was in its own block, then we've now deleted it and
* merged the two surrounding blocks, the latter of which the
* __next block pointer was pointing to.
*/
if (endif_block != later_block) {
__next = earlier_block->next();
}
}
progress = true;
} else if (inst->opcode == BRW_OPCODE_ELSE &&
prev_inst->opcode == BRW_OPCODE_IF) {
bblock_t *const else_block = block;
backend_instruction *const if_inst = prev_inst;
backend_instruction *const else_inst = inst;
/* Since the else-branch is becoming the new then-branch, the
* condition has to be inverted.
*/
if_inst->predicate_inverse = !if_inst->predicate_inverse;
else_inst->remove(else_block);
progress = true;
}
}
if (progress)
s->invalidate_live_intervals();
return progress;
}
<commit_msg>i965: Fix invalid pointer read in dead_control_flow_eliminate().<commit_after>/*
* Copyright © 2013 Intel Corporation
*
* 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 (including the next
* paragraph) 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.
*/
/** @file brw_dead_control_flow.cpp
*
* This file implements the dead control flow elimination optimization pass.
*/
#include "brw_shader.h"
#include "brw_cfg.h"
/* Look for and eliminate dead control flow:
*
* - if/endif
* - else in else/endif
* - then in if/else/endif
*/
bool
dead_control_flow_eliminate(backend_shader *s)
{
bool progress = false;
foreach_block_safe (block, s->cfg) {
bblock_t *prev_block = block->prev();
if (!prev_block)
continue;
backend_instruction *const inst = block->start();
backend_instruction *const prev_inst = prev_block->end();
/* ENDIF instructions, by definition, can only be found at the start of
* basic blocks.
*/
if (inst->opcode == BRW_OPCODE_ENDIF &&
prev_inst->opcode == BRW_OPCODE_ELSE) {
bblock_t *const else_block = prev_block;
backend_instruction *const else_inst = prev_inst;
else_inst->remove(else_block);
progress = true;
} else if (inst->opcode == BRW_OPCODE_ENDIF &&
prev_inst->opcode == BRW_OPCODE_IF) {
bblock_t *const endif_block = block;
bblock_t *const if_block = prev_block;
backend_instruction *const endif_inst = inst;
backend_instruction *const if_inst = prev_inst;
bblock_t *earlier_block = NULL, *later_block = NULL;
if (if_block->start_ip == if_block->end_ip) {
earlier_block = if_block->prev();
} else {
earlier_block = if_block;
}
if_inst->remove(if_block);
if (endif_block->start_ip == endif_block->end_ip) {
later_block = endif_block->next();
} else {
later_block = endif_block;
}
endif_inst->remove(endif_block);
assert((earlier_block == NULL) == (later_block == NULL));
if (earlier_block && earlier_block->can_combine_with(later_block)) {
earlier_block->combine_with(later_block);
/* If ENDIF was in its own block, then we've now deleted it and
* merged the two surrounding blocks, the latter of which the
* __next block pointer was pointing to.
*/
if (endif_block != later_block) {
__next = earlier_block->next();
}
}
progress = true;
} else if (inst->opcode == BRW_OPCODE_ELSE &&
prev_inst->opcode == BRW_OPCODE_IF) {
bblock_t *const else_block = block;
backend_instruction *const if_inst = prev_inst;
backend_instruction *const else_inst = inst;
/* Since the else-branch is becoming the new then-branch, the
* condition has to be inverted.
*/
if_inst->predicate_inverse = !if_inst->predicate_inverse;
else_inst->remove(else_block);
progress = true;
}
}
if (progress)
s->invalidate_live_intervals();
return progress;
}
<|endoftext|>
|
<commit_before>/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2014 Klaus Post
Copyright (C) 2014-2015 Pedro Côrte-Real
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "decoders/RafDecoder.h"
#include "common/Common.h" // for uint32, ushort16
#include "common/Point.h" // for iPoint2D, iRecta...
#include "decoders/RawDecoder.h" // for RawDecoderThread
#include "decoders/RawDecoderException.h" // for RawDecoderExcept...
#include "decompressors/FujiDecompressor.h" // for FujiDecompressor
#include "decompressors/UncompressedDecompressor.h" // for UncompressedDeco...
#include "io/Buffer.h" // for Buffer
#include "io/ByteStream.h" // for ByteStream
#include "io/Endianness.h" // for getHostEndianness
#include "metadata/BlackArea.h" // for BlackArea
#include "metadata/Camera.h" // for Camera, Hints
#include "metadata/CameraMetaData.h" // for CameraMetaData
#include "metadata/CameraSensorInfo.h" // for CameraSensorInfo
#include "metadata/ColorFilterArray.h" // for ColorFilterArray
#include "tiff/TiffEntry.h" // for TiffEntry
#include "tiff/TiffIFD.h" // for TiffRootIFD, Tif...
#include "tiff/TiffTag.h" // for TiffTag::FUJIOLDWB
#include <cassert> // for assert
#include <cstdio> // for size_t
#include <cstring> // for memcmp
#include <memory> // for unique_ptr, allo...
#include <string> // for string
#include <vector> // for vector
namespace rawspeed {
bool RafDecoder::isRAF(const Buffer* input) {
static const char magic[] = "FUJIFILMCCD-RAW ";
static const size_t magic_size = sizeof(magic) - 1; // excluding \0
const unsigned char* data = input->getData(0, magic_size);
return 0 == memcmp(&data[0], magic, magic_size);
}
bool RafDecoder::isAppropriateDecoder(const TiffRootIFD* rootIFD,
const Buffer* file) {
const auto id = rootIFD->getID();
const std::string& make = id.make;
// FIXME: magic
return make == "FUJIFILM";
}
RawImage RafDecoder::decodeRawInternal() {
auto raw = mRootIFD->getIFDWithTag(FUJI_STRIPOFFSETS);
uint32 height = 0;
uint32 width = 0;
if (raw->hasEntry(FUJI_RAWIMAGEFULLHEIGHT)) {
height = raw->getEntry(FUJI_RAWIMAGEFULLHEIGHT)->getU32();
width = raw->getEntry(FUJI_RAWIMAGEFULLWIDTH)->getU32();
} else if (raw->hasEntry(IMAGEWIDTH)) {
TiffEntry *e = raw->getEntry(IMAGEWIDTH);
height = e->getU16(0);
width = e->getU16(1);
} else
ThrowRDE("Unable to locate image size");
if (height < 1 || width < 1)
ThrowRDE("Bad image dimensions");
if (raw->hasEntry(FUJI_LAYOUT)) {
TiffEntry *e = raw->getEntry(FUJI_LAYOUT);
alt_layout = !(e->getByte(0) >> 7);
}
TiffEntry *offsets = raw->getEntry(FUJI_STRIPOFFSETS);
TiffEntry *counts = raw->getEntry(FUJI_STRIPBYTECOUNTS);
if (offsets->count != 1 || counts->count != 1)
ThrowRDE("Multiple Strips found: %u %u", offsets->count, counts->count);
ByteStream input(offsets->getRootIfdData());
input = input.getSubStream(offsets->getU32(), counts->getU32());
if (isCompressed()) {
mRaw->metadata.mode = "compressed";
mRaw->dim = iPoint2D(width, height);
FujiDecompressor _f(input, mRaw);
f = &_f;
const iPoint2D hDim(f->header.raw_width, f->header.raw_height);
if (mRaw->dim != hDim)
ThrowRDE("RAF header specifies different dimensions!");
mRaw->createData();
_f.fuji_compressed_load_raw();
startTasks(getThreadCount());
f = nullptr;
return mRaw;
}
// x-trans sensors report 14bpp, but data isn't packed
// thus, unless someone has any better ideas, let's autodetect it.
int bps;
// Some fuji SuperCCD cameras include a second raw image next to the first one
// that is identical but darker to the first. The two combined can produce
// a higher dynamic range image. Right now we're ignoring it.
bool double_width;
assert(!isCompressed());
if (8UL * counts->getU32() >= 2UL * 16UL * width * height) {
bps = 16;
double_width = true;
} else if (8UL * counts->getU32() >= 2UL * 14UL * width * height) {
bps = 14;
double_width = true;
} else if (8UL * counts->getU32() >= 2UL * 12UL * width * height) {
bps = 12;
double_width = true;
} else if (8UL * counts->getU32() >= 16UL * width * height) {
bps = 16;
double_width = false;
} else if (8UL * counts->getU32() >= 14UL * width * height) {
bps = 14;
double_width = false;
} else if (8UL * counts->getU32() >= 12UL * width * height) {
bps = 12;
double_width = false;
} else {
ThrowRDE("Can not detect bitdepth. StripByteCounts = %u, width = %u, "
"height = %u",
counts->getU32(), width, height);
}
double_width = hints.has("double_width_unpacked");
const uint32 real_width = double_width ? 2U * width : width;
mRaw->dim = iPoint2D(real_width, height);
mRaw->createData();
UncompressedDecompressor u(input, mRaw);
if (double_width) {
u.decodeRawUnpacked<16, little>(width * 2, height);
} else if (input.isInNativeByteOrder() == (getHostEndianness() == big)) {
u.decodeRawUnpacked<16, big>(width, height);
} else {
iPoint2D pos(0, 0);
if (hints.has("jpeg32_bitorder")) {
u.readUncompressedRaw(mRaw->dim, pos, width * bps / 8, bps,
BitOrder_MSB32);
} else {
u.readUncompressedRaw(mRaw->dim, pos, width * bps / 8, bps, BitOrder_LSB);
}
}
return mRaw;
}
void RafDecoder::decodeThreaded(RawDecoderThread* t) {
assert(f);
const auto nThreads = getThreadCount();
assert(t->taskNo >= 0 && t->taskNo < nThreads);
const auto slicesPerThread =
(f->header.blocks_in_row + nThreads - 1) / nThreads;
assert(slicesPerThread * nThreads >= f->header.blocks_in_row);
const auto startSlice = slicesPerThread * t->taskNo;
const auto endSlice = startSlice + slicesPerThread;
f->fuji_decode_loop(startSlice, endSlice);
}
void RafDecoder::checkSupportInternal(const CameraMetaData* meta) {
if (!this->checkCameraSupported(meta, mRootIFD->getID(), ""))
ThrowRDE("Unknown camera. Will not guess.");
if (isCompressed()) {
mRaw->metadata.mode = "compressed";
auto id = mRootIFD->getID();
const Camera* cam = meta->getCamera(id.make, id.model, mRaw->metadata.mode);
if (!cam)
ThrowRDE("Couldn't find camera %s %s", id.make.c_str(), id.model.c_str());
mRaw->cfa = cam->cfa;
}
}
void RafDecoder::decodeMetaDataInternal(const CameraMetaData* meta) {
int iso = 0;
if (mRootIFD->hasEntryRecursive(ISOSPEEDRATINGS))
iso = mRootIFD->getEntryRecursive(ISOSPEEDRATINGS)->getU32();
mRaw->metadata.isoSpeed = iso;
// This is where we'd normally call setMetaData but since we may still need
// to rotate the image for SuperCCD cameras we do everything ourselves
auto id = mRootIFD->getID();
const Camera* cam = meta->getCamera(id.make, id.model, mRaw->metadata.mode);
if (!cam)
ThrowRDE("Couldn't find camera");
assert(cam != nullptr);
iPoint2D new_size(mRaw->dim);
iPoint2D crop_offset = iPoint2D(0,0);
if (applyCrop) {
new_size = cam->cropSize;
crop_offset = cam->cropPos;
bool double_width = hints.has("double_width_unpacked");
// If crop size is negative, use relative cropping
if (new_size.x <= 0)
new_size.x = mRaw->dim.x / (double_width ? 2 : 1) - cam->cropPos.x + new_size.x;
else
new_size.x /= (double_width ? 2 : 1);
if (new_size.y <= 0)
new_size.y = mRaw->dim.y - cam->cropPos.y + new_size.y;
}
bool rotate = hints.has("fuji_rotate");
rotate = rotate && fujiRotate;
// Rotate 45 degrees - could be multithreaded.
if (rotate && !this->uncorrectedRawValues) {
// Calculate the 45 degree rotated size;
uint32 rotatedsize;
uint32 rotationPos;
if (alt_layout) {
rotatedsize = new_size.y+new_size.x/2;
rotationPos = new_size.x/2 - 1;
}
else {
rotatedsize = new_size.x+new_size.y/2;
rotationPos = new_size.x - 1;
}
iPoint2D final_size(rotatedsize, rotatedsize-1);
RawImage rotated = RawImage::create(final_size, TYPE_USHORT16, 1);
rotated->clearArea(iRectangle2D(iPoint2D(0,0), rotated->dim));
rotated->metadata = mRaw->metadata;
rotated->metadata.fujiRotationPos = rotationPos;
int dest_pitch = static_cast<int>(rotated->pitch) / 2;
auto* dst = reinterpret_cast<ushort16*>(rotated->getData(0, 0));
for (int y = 0; y < new_size.y; y++) {
auto* src = reinterpret_cast<ushort16*>(
mRaw->getData(crop_offset.x, crop_offset.y + y));
for (int x = 0; x < new_size.x; x++) {
int h;
int w;
if (alt_layout) { // Swapped x and y
h = rotatedsize - (new_size.y + 1 - y + (x >> 1));
w = ((x+1) >> 1) + y;
} else {
h = new_size.x - 1 - x + (y >> 1);
w = ((y+1) >> 1) + x;
}
if (h < rotated->dim.y && w < rotated->dim.x)
dst[w + h * dest_pitch] = src[x];
else
ThrowRDE("Trying to write out of bounds");
}
}
mRaw = rotated;
} else if (applyCrop) {
mRaw->subFrame(iRectangle2D(crop_offset, new_size));
}
const CameraSensorInfo *sensor = cam->getSensorInfo(iso);
mRaw->blackLevel = sensor->mBlackLevel;
// at least the (bayer sensor) X100 comes with a tag like this:
if (mRootIFD->hasEntryRecursive(FUJI_BLACKLEVEL)) {
TiffEntry* sep_black = mRootIFD->getEntryRecursive(FUJI_BLACKLEVEL);
if (sep_black->count == 4)
{
for(int k=0;k<4;k++)
mRaw->blackLevelSeparate[k] = sep_black->getU32(k);
} else if (sep_black->count == 36) {
for (int& k : mRaw->blackLevelSeparate)
k = 0;
for (int y = 0; y < 6; y++) {
for (int x = 0; x < 6; x++)
mRaw->blackLevelSeparate[2 * (y % 2) + (x % 2)] +=
sep_black->getU32(6 * y + x);
}
for (int& k : mRaw->blackLevelSeparate)
k /= 9;
}
}
mRaw->whitePoint = sensor->mWhiteLevel;
mRaw->blackAreas = cam->blackAreas;
mRaw->cfa = cam->cfa;
mRaw->metadata.canonical_make = cam->canonical_make;
mRaw->metadata.canonical_model = cam->canonical_model;
mRaw->metadata.canonical_alias = cam->canonical_alias;
mRaw->metadata.canonical_id = cam->canonical_id;
mRaw->metadata.make = id.make;
mRaw->metadata.model = id.model;
if (mRootIFD->hasEntryRecursive(FUJI_WB_GRBLEVELS)) {
TiffEntry *wb = mRootIFD->getEntryRecursive(FUJI_WB_GRBLEVELS);
if (wb->count == 3) {
mRaw->metadata.wbCoeffs[0] = wb->getFloat(1);
mRaw->metadata.wbCoeffs[1] = wb->getFloat(0);
mRaw->metadata.wbCoeffs[2] = wb->getFloat(2);
}
} else if (mRootIFD->hasEntryRecursive(FUJIOLDWB)) {
TiffEntry *wb = mRootIFD->getEntryRecursive(FUJIOLDWB);
if (wb->count == 8) {
mRaw->metadata.wbCoeffs[0] = wb->getFloat(1);
mRaw->metadata.wbCoeffs[1] = wb->getFloat(0);
mRaw->metadata.wbCoeffs[2] = wb->getFloat(3);
}
}
}
int RafDecoder::isCompressed() {
auto raw = mRootIFD->getIFDWithTag(FUJI_STRIPOFFSETS);
uint32 height = 0;
uint32 width = 0;
if (raw->hasEntry(FUJI_RAWIMAGEFULLHEIGHT)) {
height = raw->getEntry(FUJI_RAWIMAGEFULLHEIGHT)->getU32();
width = raw->getEntry(FUJI_RAWIMAGEFULLWIDTH)->getU32();
} else if (raw->hasEntry(IMAGEWIDTH)) {
TiffEntry* e = raw->getEntry(IMAGEWIDTH);
height = e->getU16(0);
width = e->getU16(1);
} else
ThrowRDE("Unable to locate image size");
uint32 count = raw->getEntry(FUJI_STRIPBYTECOUNTS)->getU32();
return count * 8 / (width * height) < 10;
}
} // namespace rawspeed
<commit_msg>RafDecoder::decodeThreaded(): fixup taskNo assert.<commit_after>/*
RawSpeed - RAW file decoder.
Copyright (C) 2009-2014 Klaus Post
Copyright (C) 2014-2015 Pedro Côrte-Real
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "decoders/RafDecoder.h"
#include "common/Common.h" // for uint32, ushort16
#include "common/Point.h" // for iPoint2D, iRecta...
#include "decoders/RawDecoder.h" // for RawDecoderThread
#include "decoders/RawDecoderException.h" // for RawDecoderExcept...
#include "decompressors/FujiDecompressor.h" // for FujiDecompressor
#include "decompressors/UncompressedDecompressor.h" // for UncompressedDeco...
#include "io/Buffer.h" // for Buffer
#include "io/ByteStream.h" // for ByteStream
#include "io/Endianness.h" // for getHostEndianness
#include "metadata/BlackArea.h" // for BlackArea
#include "metadata/Camera.h" // for Camera, Hints
#include "metadata/CameraMetaData.h" // for CameraMetaData
#include "metadata/CameraSensorInfo.h" // for CameraSensorInfo
#include "metadata/ColorFilterArray.h" // for ColorFilterArray
#include "tiff/TiffEntry.h" // for TiffEntry
#include "tiff/TiffIFD.h" // for TiffRootIFD, Tif...
#include "tiff/TiffTag.h" // for TiffTag::FUJIOLDWB
#include <cassert> // for assert
#include <cstdio> // for size_t
#include <cstring> // for memcmp
#include <memory> // for unique_ptr, allo...
#include <string> // for string
#include <vector> // for vector
namespace rawspeed {
bool RafDecoder::isRAF(const Buffer* input) {
static const char magic[] = "FUJIFILMCCD-RAW ";
static const size_t magic_size = sizeof(magic) - 1; // excluding \0
const unsigned char* data = input->getData(0, magic_size);
return 0 == memcmp(&data[0], magic, magic_size);
}
bool RafDecoder::isAppropriateDecoder(const TiffRootIFD* rootIFD,
const Buffer* file) {
const auto id = rootIFD->getID();
const std::string& make = id.make;
// FIXME: magic
return make == "FUJIFILM";
}
RawImage RafDecoder::decodeRawInternal() {
auto raw = mRootIFD->getIFDWithTag(FUJI_STRIPOFFSETS);
uint32 height = 0;
uint32 width = 0;
if (raw->hasEntry(FUJI_RAWIMAGEFULLHEIGHT)) {
height = raw->getEntry(FUJI_RAWIMAGEFULLHEIGHT)->getU32();
width = raw->getEntry(FUJI_RAWIMAGEFULLWIDTH)->getU32();
} else if (raw->hasEntry(IMAGEWIDTH)) {
TiffEntry *e = raw->getEntry(IMAGEWIDTH);
height = e->getU16(0);
width = e->getU16(1);
} else
ThrowRDE("Unable to locate image size");
if (height < 1 || width < 1)
ThrowRDE("Bad image dimensions");
if (raw->hasEntry(FUJI_LAYOUT)) {
TiffEntry *e = raw->getEntry(FUJI_LAYOUT);
alt_layout = !(e->getByte(0) >> 7);
}
TiffEntry *offsets = raw->getEntry(FUJI_STRIPOFFSETS);
TiffEntry *counts = raw->getEntry(FUJI_STRIPBYTECOUNTS);
if (offsets->count != 1 || counts->count != 1)
ThrowRDE("Multiple Strips found: %u %u", offsets->count, counts->count);
ByteStream input(offsets->getRootIfdData());
input = input.getSubStream(offsets->getU32(), counts->getU32());
if (isCompressed()) {
mRaw->metadata.mode = "compressed";
mRaw->dim = iPoint2D(width, height);
FujiDecompressor _f(input, mRaw);
f = &_f;
const iPoint2D hDim(f->header.raw_width, f->header.raw_height);
if (mRaw->dim != hDim)
ThrowRDE("RAF header specifies different dimensions!");
mRaw->createData();
_f.fuji_compressed_load_raw();
startTasks(getThreadCount());
f = nullptr;
return mRaw;
}
// x-trans sensors report 14bpp, but data isn't packed
// thus, unless someone has any better ideas, let's autodetect it.
int bps;
// Some fuji SuperCCD cameras include a second raw image next to the first one
// that is identical but darker to the first. The two combined can produce
// a higher dynamic range image. Right now we're ignoring it.
bool double_width;
assert(!isCompressed());
if (8UL * counts->getU32() >= 2UL * 16UL * width * height) {
bps = 16;
double_width = true;
} else if (8UL * counts->getU32() >= 2UL * 14UL * width * height) {
bps = 14;
double_width = true;
} else if (8UL * counts->getU32() >= 2UL * 12UL * width * height) {
bps = 12;
double_width = true;
} else if (8UL * counts->getU32() >= 16UL * width * height) {
bps = 16;
double_width = false;
} else if (8UL * counts->getU32() >= 14UL * width * height) {
bps = 14;
double_width = false;
} else if (8UL * counts->getU32() >= 12UL * width * height) {
bps = 12;
double_width = false;
} else {
ThrowRDE("Can not detect bitdepth. StripByteCounts = %u, width = %u, "
"height = %u",
counts->getU32(), width, height);
}
double_width = hints.has("double_width_unpacked");
const uint32 real_width = double_width ? 2U * width : width;
mRaw->dim = iPoint2D(real_width, height);
mRaw->createData();
UncompressedDecompressor u(input, mRaw);
if (double_width) {
u.decodeRawUnpacked<16, little>(width * 2, height);
} else if (input.isInNativeByteOrder() == (getHostEndianness() == big)) {
u.decodeRawUnpacked<16, big>(width, height);
} else {
iPoint2D pos(0, 0);
if (hints.has("jpeg32_bitorder")) {
u.readUncompressedRaw(mRaw->dim, pos, width * bps / 8, bps,
BitOrder_MSB32);
} else {
u.readUncompressedRaw(mRaw->dim, pos, width * bps / 8, bps, BitOrder_LSB);
}
}
return mRaw;
}
void RafDecoder::decodeThreaded(RawDecoderThread* t) {
assert(f);
const auto nThreads = getThreadCount();
assert(t->taskNo < nThreads);
const auto slicesPerThread =
(f->header.blocks_in_row + nThreads - 1) / nThreads;
assert(slicesPerThread * nThreads >= f->header.blocks_in_row);
const auto startSlice = slicesPerThread * t->taskNo;
const auto endSlice = startSlice + slicesPerThread;
f->fuji_decode_loop(startSlice, endSlice);
}
void RafDecoder::checkSupportInternal(const CameraMetaData* meta) {
if (!this->checkCameraSupported(meta, mRootIFD->getID(), ""))
ThrowRDE("Unknown camera. Will not guess.");
if (isCompressed()) {
mRaw->metadata.mode = "compressed";
auto id = mRootIFD->getID();
const Camera* cam = meta->getCamera(id.make, id.model, mRaw->metadata.mode);
if (!cam)
ThrowRDE("Couldn't find camera %s %s", id.make.c_str(), id.model.c_str());
mRaw->cfa = cam->cfa;
}
}
void RafDecoder::decodeMetaDataInternal(const CameraMetaData* meta) {
int iso = 0;
if (mRootIFD->hasEntryRecursive(ISOSPEEDRATINGS))
iso = mRootIFD->getEntryRecursive(ISOSPEEDRATINGS)->getU32();
mRaw->metadata.isoSpeed = iso;
// This is where we'd normally call setMetaData but since we may still need
// to rotate the image for SuperCCD cameras we do everything ourselves
auto id = mRootIFD->getID();
const Camera* cam = meta->getCamera(id.make, id.model, mRaw->metadata.mode);
if (!cam)
ThrowRDE("Couldn't find camera");
assert(cam != nullptr);
iPoint2D new_size(mRaw->dim);
iPoint2D crop_offset = iPoint2D(0,0);
if (applyCrop) {
new_size = cam->cropSize;
crop_offset = cam->cropPos;
bool double_width = hints.has("double_width_unpacked");
// If crop size is negative, use relative cropping
if (new_size.x <= 0)
new_size.x = mRaw->dim.x / (double_width ? 2 : 1) - cam->cropPos.x + new_size.x;
else
new_size.x /= (double_width ? 2 : 1);
if (new_size.y <= 0)
new_size.y = mRaw->dim.y - cam->cropPos.y + new_size.y;
}
bool rotate = hints.has("fuji_rotate");
rotate = rotate && fujiRotate;
// Rotate 45 degrees - could be multithreaded.
if (rotate && !this->uncorrectedRawValues) {
// Calculate the 45 degree rotated size;
uint32 rotatedsize;
uint32 rotationPos;
if (alt_layout) {
rotatedsize = new_size.y+new_size.x/2;
rotationPos = new_size.x/2 - 1;
}
else {
rotatedsize = new_size.x+new_size.y/2;
rotationPos = new_size.x - 1;
}
iPoint2D final_size(rotatedsize, rotatedsize-1);
RawImage rotated = RawImage::create(final_size, TYPE_USHORT16, 1);
rotated->clearArea(iRectangle2D(iPoint2D(0,0), rotated->dim));
rotated->metadata = mRaw->metadata;
rotated->metadata.fujiRotationPos = rotationPos;
int dest_pitch = static_cast<int>(rotated->pitch) / 2;
auto* dst = reinterpret_cast<ushort16*>(rotated->getData(0, 0));
for (int y = 0; y < new_size.y; y++) {
auto* src = reinterpret_cast<ushort16*>(
mRaw->getData(crop_offset.x, crop_offset.y + y));
for (int x = 0; x < new_size.x; x++) {
int h;
int w;
if (alt_layout) { // Swapped x and y
h = rotatedsize - (new_size.y + 1 - y + (x >> 1));
w = ((x+1) >> 1) + y;
} else {
h = new_size.x - 1 - x + (y >> 1);
w = ((y+1) >> 1) + x;
}
if (h < rotated->dim.y && w < rotated->dim.x)
dst[w + h * dest_pitch] = src[x];
else
ThrowRDE("Trying to write out of bounds");
}
}
mRaw = rotated;
} else if (applyCrop) {
mRaw->subFrame(iRectangle2D(crop_offset, new_size));
}
const CameraSensorInfo *sensor = cam->getSensorInfo(iso);
mRaw->blackLevel = sensor->mBlackLevel;
// at least the (bayer sensor) X100 comes with a tag like this:
if (mRootIFD->hasEntryRecursive(FUJI_BLACKLEVEL)) {
TiffEntry* sep_black = mRootIFD->getEntryRecursive(FUJI_BLACKLEVEL);
if (sep_black->count == 4)
{
for(int k=0;k<4;k++)
mRaw->blackLevelSeparate[k] = sep_black->getU32(k);
} else if (sep_black->count == 36) {
for (int& k : mRaw->blackLevelSeparate)
k = 0;
for (int y = 0; y < 6; y++) {
for (int x = 0; x < 6; x++)
mRaw->blackLevelSeparate[2 * (y % 2) + (x % 2)] +=
sep_black->getU32(6 * y + x);
}
for (int& k : mRaw->blackLevelSeparate)
k /= 9;
}
}
mRaw->whitePoint = sensor->mWhiteLevel;
mRaw->blackAreas = cam->blackAreas;
mRaw->cfa = cam->cfa;
mRaw->metadata.canonical_make = cam->canonical_make;
mRaw->metadata.canonical_model = cam->canonical_model;
mRaw->metadata.canonical_alias = cam->canonical_alias;
mRaw->metadata.canonical_id = cam->canonical_id;
mRaw->metadata.make = id.make;
mRaw->metadata.model = id.model;
if (mRootIFD->hasEntryRecursive(FUJI_WB_GRBLEVELS)) {
TiffEntry *wb = mRootIFD->getEntryRecursive(FUJI_WB_GRBLEVELS);
if (wb->count == 3) {
mRaw->metadata.wbCoeffs[0] = wb->getFloat(1);
mRaw->metadata.wbCoeffs[1] = wb->getFloat(0);
mRaw->metadata.wbCoeffs[2] = wb->getFloat(2);
}
} else if (mRootIFD->hasEntryRecursive(FUJIOLDWB)) {
TiffEntry *wb = mRootIFD->getEntryRecursive(FUJIOLDWB);
if (wb->count == 8) {
mRaw->metadata.wbCoeffs[0] = wb->getFloat(1);
mRaw->metadata.wbCoeffs[1] = wb->getFloat(0);
mRaw->metadata.wbCoeffs[2] = wb->getFloat(3);
}
}
}
int RafDecoder::isCompressed() {
auto raw = mRootIFD->getIFDWithTag(FUJI_STRIPOFFSETS);
uint32 height = 0;
uint32 width = 0;
if (raw->hasEntry(FUJI_RAWIMAGEFULLHEIGHT)) {
height = raw->getEntry(FUJI_RAWIMAGEFULLHEIGHT)->getU32();
width = raw->getEntry(FUJI_RAWIMAGEFULLWIDTH)->getU32();
} else if (raw->hasEntry(IMAGEWIDTH)) {
TiffEntry* e = raw->getEntry(IMAGEWIDTH);
height = e->getU16(0);
width = e->getU16(1);
} else
ThrowRDE("Unable to locate image size");
uint32 count = raw->getEntry(FUJI_STRIPBYTECOUNTS)->getU32();
return count * 8 / (width * height) < 10;
}
} // namespace rawspeed
<|endoftext|>
|
<commit_before>#include "a_lane.h"
namespace a {
///! laneInstance
laneInstance::laneInstance(lane *parent)
: m_parent(parent)
{
m_flags |= kProtected;
}
void laneInstance::getAudio(float *buffer, size_t samples) {
int handle = m_parent->m_channelHandle;
if (handle == 0)
return;
audio *owner = m_parent->m_owner;
if (owner->m_scratchNeeded != m_scratch.size())
m_scratch.resize(owner->m_scratchNeeded);
owner->mixLane(buffer, samples, &m_scratch[0], handle);
}
bool laneInstance::hasEnded() const {
return false;
}
laneInstance::~laneInstance() {
audio *owner = m_parent->m_owner;
for (size_t i = 0; i < owner->m_voices.size(); i++) {
if (owner->m_voices[i] && owner->m_voices[i]->m_laneHandle == m_parent->m_channelHandle)
owner->stopVoice(i);
}
}
///! lane
lane::lane()
: m_channelHandle(0)
, m_instance(nullptr)
{
}
laneInstance *lane::create() {
if (m_channelHandle) {
m_owner->stopVoice(m_owner->getVoiceFromHandle(m_channelHandle));
m_channelHandle = 0;
m_instance = nullptr;
}
return m_instance = new laneInstance(this);
}
int lane::play(source &sound, float volume, float pan, bool paused) {
if (!m_instance || !m_owner)
return 0;
if (m_channelHandle == 0) {
// find channel the lane is playing on
for (size_t i = 0; m_channelHandle == 0 && i < m_owner->m_voices.size(); i++)
if (m_owner->m_voices[i] == m_instance)
m_channelHandle = m_owner->getHandleFromVoice(i);
// could not find channel
if (m_channelHandle == 0)
return 0;
}
return m_owner->play(sound, volume, pan, paused, m_channelHandle);
}
}
<commit_msg>Mixing lanes are supposed to be stereo<commit_after>#include "a_lane.h"
namespace a {
///! laneInstance
laneInstance::laneInstance(lane *parent)
: m_parent(parent)
{
m_flags |= kProtected;
}
void laneInstance::getAudio(float *buffer, size_t samples) {
int handle = m_parent->m_channelHandle;
if (handle == 0)
return;
audio *owner = m_parent->m_owner;
if (owner->m_scratchNeeded != m_scratch.size())
m_scratch.resize(owner->m_scratchNeeded);
owner->mixLane(buffer, samples, &m_scratch[0], handle);
}
bool laneInstance::hasEnded() const {
return false;
}
laneInstance::~laneInstance() {
audio *owner = m_parent->m_owner;
for (size_t i = 0; i < owner->m_voices.size(); i++) {
if (owner->m_voices[i] && owner->m_voices[i]->m_laneHandle == m_parent->m_channelHandle)
owner->stopVoice(i);
}
}
///! lane
lane::lane()
: m_channelHandle(0)
, m_instance(nullptr)
{
m_channels = 2;
}
laneInstance *lane::create() {
if (m_channelHandle) {
m_owner->stopVoice(m_owner->getVoiceFromHandle(m_channelHandle));
m_channelHandle = 0;
m_instance = nullptr;
}
return m_instance = new laneInstance(this);
}
int lane::play(source &sound, float volume, float pan, bool paused) {
if (!m_instance || !m_owner)
return 0;
if (m_channelHandle == 0) {
// find channel the lane is playing on
for (size_t i = 0; m_channelHandle == 0 && i < m_owner->m_voices.size(); i++)
if (m_owner->m_voices[i] == m_instance)
m_channelHandle = m_owner->getHandleFromVoice(i);
// could not find channel
if (m_channelHandle == 0)
return 0;
}
return m_owner->play(sound, volume, pan, paused, m_channelHandle);
}
}
<|endoftext|>
|
<commit_before>#include "config.h"
#include "matmul.decl.h"
#include "logger.h"
#include "messages.h"
#include "timer.h"
#include <getopt.h>
#ifdef VERIFY_MULTIPLY
#include "index.h"
#endif
void matmulInit()
{
DEBUG("on PE %d, turning manual LB on\n", CkMyPe());
//TurnManualLBOn();
}
class Main : public CBase_Main
{
public:
Main (CkArgMsg *msg)
{
int N = 1;
int blocksize = 1;
int c;
const char *short_options = "hN:b:";
const option long_options[] = {
{ "help", no_argument, NULL, 0 },
{ "N", required_argument, NULL, 'N' },
{ "block", required_argument, NULL, 'b' }
};
while((c = getopt_long(msg->argc, msg->argv, short_options,
long_options, NULL)) != -1)
{
switch(c)
{
case 'h':
CkPrintf("Usage:\n");
CkPrintf("{ -h | --help } This help\n");
CkPrintf("{ -N | --N } N Create NxN matrix (default: %d)\n", N);
CkPrintf("{ -b | --block } B Create BxB dense blocks at leaf "
"nodes (default: %d)\n", blocksize);
CkExit();
break;
case 'N':
N = strtol(optarg, NULL, 10);
break;
case 'b':
blocksize = strtol(optarg, NULL, 10);
break;
default:
CkExit();
break;
}
}
CkPrintf("running on %d PEs\n", CkNumPes());
DEBUG("calling run on this proxy\n");
thisProxy.run(N, blocksize);
}
void run (int N, int blocksize)
{
CProxy_Matrix A = CProxy_Matrix::ckNew(N, blocksize);
CProxy_Matrix C = CProxy_Matrix::ckNew(N, blocksize);
DEBUG("generating random matrix\n");
A.random(CkCallbackResumeThread());
#ifdef VERIFY_MULTIPLY
DenseMatrixMsg *ADense = A.getDense();
#endif
DEBUG("setting C to zero\n");
C.zero(CkCallbackResumeThread());
#ifdef DEBUG_OUTPUT
A.print(CkCallbackResumeThread());
#endif
Timer t("multiplying C = A*A");
C.multiply(A, A, CkCallbackResumeThread());
t.stop();
CkPrintf(t.to_str());
#ifdef DEBUG_OUTPUT
C.print(CkCallbackResumeThread());
#endif
#ifdef VERIFY_MULTIPLY
DenseMatrixMsg *CDense = C.getDense();
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++)
{
double CExact = 0;
for(int k = 0; k < N; k++)
{
CExact += ADense->A[BLOCK_INDEX(i, k, 0, 0, N)]
*ADense->A[BLOCK_INDEX(k, j, 0, 0, N)];
}
if(fabs(CExact-CDense->A[BLOCK_INDEX(i, j, 0, 0, N)]) > VERIFY_TOLERANCE)
{
ABORT("result mismatch (abs. tolerance = %e), "
"C(%d,%d): %e vs. %e\n", VERIFY_TOLERANCE, i, j,
CExact, CDense->A[BLOCK_INDEX(i, j, 0, 0, N)]);
}
}
}
CkPrintf("result verified\n");
delete ADense;
delete CDense;
#endif
DEBUG("done\n");
CkExit();
}
};
#include "matmul.def.h"
<commit_msg>Checkpoint.<commit_after>#include "config.h"
#include "matmul.decl.h"
#include "logger.h"
#include "messages.h"
#include "timer.h"
#include <getopt.h>
#ifdef VERIFY_MULTIPLY
#include "index.h"
#endif
void matmulInit()
{
//DEBUG("on PE %d, turning manual LB on\n", CkMyPe());
//TurnManualLBOn();
}
class Main : public CBase_Main
{
public:
Main (CkArgMsg *msg)
{
int N = 1;
int blocksize = 1;
int c;
const char *short_options = "hN:b:";
const option long_options[] = {
{ "help", no_argument, NULL, 0 },
{ "N", required_argument, NULL, 'N' },
{ "block", required_argument, NULL, 'b' }
};
while((c = getopt_long(msg->argc, msg->argv, short_options,
long_options, NULL)) != -1)
{
switch(c)
{
case 'h':
CkPrintf("Usage:\n");
CkPrintf("{ -h | --help } This help\n");
CkPrintf("{ -N | --N } N Create NxN matrix (default: %d)\n", N);
CkPrintf("{ -b | --block } B Create BxB dense blocks at leaf "
"nodes (default: %d)\n", blocksize);
CkExit();
break;
case 'N':
N = strtol(optarg, NULL, 10);
break;
case 'b':
blocksize = strtol(optarg, NULL, 10);
break;
default:
CkExit();
break;
}
}
CkPrintf("running on %d PEs\n", CkNumPes());
DEBUG("calling run on this proxy\n");
thisProxy.run(N, blocksize);
}
void run (int N, int blocksize)
{
CProxy_Matrix A = CProxy_Matrix::ckNew(N, blocksize);
CProxy_Matrix C = CProxy_Matrix::ckNew(N, blocksize);
DEBUG("generating random matrix\n");
A.random(CkCallbackResumeThread());
#ifdef VERIFY_MULTIPLY
DenseMatrixMsg *ADense = A.getDense();
#endif
DEBUG("setting C to zero\n");
C.zero(CkCallbackResumeThread());
#ifdef DEBUG_OUTPUT
A.print(CkCallbackResumeThread());
#endif
Timer t("multiplying C = A*A");
C.multiply(A, A, CkCallbackResumeThread());
t.stop();
CkPrintf(t.to_str());
#ifdef DEBUG_OUTPUT
C.print(CkCallbackResumeThread());
#endif
#ifdef VERIFY_MULTIPLY
DenseMatrixMsg *CDense = C.getDense();
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++)
{
double CExact = 0;
for(int k = 0; k < N; k++)
{
CExact += ADense->A[BLOCK_INDEX(i, k, 0, 0, N)]
*ADense->A[BLOCK_INDEX(k, j, 0, 0, N)];
}
if(fabs(CExact-CDense->A[BLOCK_INDEX(i, j, 0, 0, N)]) > VERIFY_TOLERANCE)
{
ABORT("result mismatch (abs. tolerance = %e), "
"C(%d,%d): %e vs. %e\n", VERIFY_TOLERANCE, i, j,
CExact, CDense->A[BLOCK_INDEX(i, j, 0, 0, N)]);
}
}
}
CkPrintf("result verified\n");
delete ADense;
delete CDense;
#endif
DEBUG("done\n");
CkExit();
}
};
#include "matmul.def.h"
<|endoftext|>
|
<commit_before>//
// PROJECT: Aspia Remote Desktop
// FILE: ui/file_manager_panel.cc
// LICENSE: Mozilla Public License Version 2.0
// PROGRAMMERS: Dmitry Chapyshev (dmitry@aspia.ru)
//
#include "ui/file_manager_panel.h"
#include "ui/file_manager_helpers.h"
#include "ui/status_code.h"
#include "base/strings/string_util.h"
#include "base/strings/unicode.h"
#include "base/version_helpers.h"
#include "base/logging.h"
#include <uxtheme.h>
namespace aspia {
namespace fs = std::experimental::filesystem;
static_assert(UiFileList::kInvalidObjectIndex == UiDriveList::kInvalidObjectIndex,
"Values must be equal");
UiFileManagerPanel::UiFileManagerPanel(PanelType panel_type,
std::shared_ptr<FileRequestSenderProxy> sender) :
toolbar_(panel_type == PanelType::LOCAL ?
UiFileToolBar::Type::LOCAL : UiFileToolBar::Type::REMOTE),
panel_type_(panel_type),
sender_(sender)
{
// Nothing
}
LPARAM UiFileManagerPanel::OnCreate(UINT message, WPARAM wparam, LPARAM lparam, BOOL& handled)
{
HFONT default_font = AtlGetStockFont(DEFAULT_GUI_FONT);
CString panel_name;
if (panel_type_ == PanelType::LOCAL)
panel_name.LoadStringW(IDS_FT_LOCAL_COMPUTER);
else
panel_name.LoadStringW(IDS_FT_REMOTE_COMPUTER);
CRect title_rect(0, 0, 200, 20);
title_.Create(*this, title_rect, panel_name, WS_CHILD | WS_VISIBLE | SS_OWNERDRAW);
title_.SetFont(default_font);
drive_list_.CreateDriveList(*this, kDriveListControl);
toolbar_.CreateFileToolBar(*this);
file_list_.CreateFileList(*this, kFileListControl);
CRect status_rect(0, 0, 200, 20);
status_.Create(*this, status_rect, nullptr,
WS_CHILD | WS_VISIBLE | SS_OWNERDRAW);
status_.SetFont(default_font);
sender_->SendDriveListRequest(This());
return 0;
}
LRESULT UiFileManagerPanel::OnDestroy(UINT message, WPARAM wparam, LPARAM lparam, BOOL& handled)
{
drive_list_.DestroyWindow();
file_list_.DestroyWindow();
toolbar_.DestroyWindow();
title_.DestroyWindow();
status_.DestroyWindow();
return 0;
}
LRESULT UiFileManagerPanel::OnSize(UINT message, WPARAM wparam, LPARAM lparam, BOOL& handled)
{
HDWP dwp = BeginDeferWindowPos(5);
if (dwp)
{
CSize size(lparam);
toolbar_.AutoSize();
CRect drive_rect;
drive_list_.GetWindowRect(drive_rect);
CRect toolbar_rect;
toolbar_.GetWindowRect(toolbar_rect);
CRect title_rect;
title_.GetWindowRect(title_rect);
CRect status_rect;
status_.GetWindowRect(status_rect);
title_.DeferWindowPos(dwp, nullptr,
0,
0,
size.cx,
title_rect.Height(),
SWP_NOACTIVATE | SWP_NOZORDER);
drive_list_.DeferWindowPos(dwp, nullptr,
0,
title_rect.Height(),
size.cx,
drive_rect.Height(),
SWP_NOACTIVATE | SWP_NOZORDER);
toolbar_.DeferWindowPos(dwp, nullptr,
0,
title_rect.Height() + drive_rect.Height(),
size.cx,
toolbar_rect.Height(),
SWP_NOACTIVATE | SWP_NOZORDER);
int list_y = title_rect.Height() + toolbar_rect.Height() + drive_rect.Height();
int list_height = size.cy - list_y - status_rect.Height();
file_list_.DeferWindowPos(dwp, nullptr,
0,
list_y,
size.cx,
list_height,
SWP_NOACTIVATE | SWP_NOZORDER);
status_.DeferWindowPos(dwp, nullptr,
0,
list_y + list_height,
size.cx,
status_rect.Height(),
SWP_NOACTIVATE | SWP_NOZORDER);
EndDeferWindowPos(dwp);
}
return 0;
}
LRESULT UiFileManagerPanel::OnDrawItem(UINT message, WPARAM wparam, LPARAM lparam, BOOL& handled)
{
LPDRAWITEMSTRUCT dis = reinterpret_cast<LPDRAWITEMSTRUCT>(lparam);
if (dis->hwndItem == title_ || dis->hwndItem == status_)
{
int saved_dc = SaveDC(dis->hDC);
if (saved_dc)
{
// Transparent background.
SetBkMode(dis->hDC, TRANSPARENT);
HBRUSH background_brush = GetSysColorBrush(COLOR_WINDOW);
FillRect(dis->hDC, &dis->rcItem, background_brush);
WCHAR label[256] = { 0 };
::GetWindowTextW(dis->hwndItem, label, _countof(label));
if (label[0])
{
SetTextColor(dis->hDC, GetSysColor(COLOR_WINDOWTEXT));
DrawTextW(dis->hDC,
label,
wcslen(label),
&dis->rcItem,
DT_VCENTER | DT_SINGLELINE);
}
RestoreDC(dis->hDC, saved_dc);
}
}
return 0;
}
LRESULT UiFileManagerPanel::OnDriveChange(WORD code, WORD ctrl_id, HWND ctrl, BOOL& handled)
{
int object_index = drive_list_.SelectedObject();
if (object_index == UiDriveList::kInvalidObjectIndex)
return 0;
MoveToDrive(object_index);
return 0;
}
LRESULT UiFileManagerPanel::OnListDoubleClock(int ctrl_id, LPNMHDR hdr, BOOL& handled)
{
int object_index = file_list_.GetObjectUnderMousePointer();
if (!file_list_.HasDirectoryList())
{
MoveToDrive(object_index);
return 0;
}
if (!file_list_.IsValidObjectIndex(object_index))
return 0;
const proto::FileList::Item& item = file_list_.Object(object_index);
if (file_list_.IsDirectoryObject(object_index))
{
FilePath path(drive_list_.CurrentPath());
path.append(file_list_.ObjectName(object_index));
sender_->SendFileListRequest(This(), path);
}
return 0;
}
LRESULT UiFileManagerPanel::OnFolderUp(WORD code, WORD ctrl_id, HWND ctrl, BOOL& handled)
{
FilePath path = drive_list_.CurrentPath();
if (!path.has_parent_path() || path.parent_path() == path.root_name())
{
MoveToDrive(UiDriveList::kComputerObjectIndex);
}
else
{
sender_->SendFileListRequest(This(), path.parent_path());
}
return 0;
}
LRESULT UiFileManagerPanel::OnFolderAdd(WORD code, WORD ctrl_id, HWND ctrl, BOOL& handled)
{
file_list_.AddDirectory();
return 0;
}
LRESULT UiFileManagerPanel::OnRefresh(WORD code, WORD ctrl_id, HWND ctrl, BOOL& handled)
{
sender_->SendDriveListRequest(This());
if (file_list_.HasDirectoryList())
{
sender_->SendFileListRequest(This(), drive_list_.CurrentPath());
}
return 0;
}
LRESULT UiFileManagerPanel::OnRemove(WORD code, WORD ctrl_id, HWND ctrl, BOOL& handled)
{
if (!file_list_.HasDirectoryList())
return 0;
UINT selected_count = file_list_.GetSelectedCount();
if (!selected_count)
return 0;
CString title;
title.LoadStringW(IDS_CONFIRMATION);
CString message;
message.Format(IDS_FT_DELETE_CONFORM, selected_count);
if (MessageBoxW(message, title, MB_YESNO | MB_ICONQUESTION) == IDYES)
{
for (UiFileList::Iterator iter(file_list_, UiFileList::Iterator::SELECTED);
!iter.IsAtEnd();
iter.Advance())
{
proto::FileList::Item* object = iter.Object();
if (!object)
continue;
FilePath path = drive_list_.CurrentPath();
path.append(fs::u8path(object->name()));
sender_->SendRemoveRequest(This(), path);
}
}
return 0;
}
void UiFileManagerPanel::MoveToDrive(int object_index)
{
drive_list_.SelectObject(object_index);
if (object_index == UiDriveList::kComputerObjectIndex)
{
toolbar_.EnableButton(ID_FOLDER_ADD, FALSE);
toolbar_.EnableButton(ID_FOLDER_UP, FALSE);
toolbar_.EnableButton(ID_DELETE, FALSE);
toolbar_.EnableButton(ID_SEND, FALSE);
toolbar_.EnableButton(ID_HOME, FALSE);
file_list_.Read(drive_list_.DriveList());
drive_list_.SetCurrentPath(drive_list_.CurrentPath());
}
else
{
sender_->SendFileListRequest(This(), drive_list_.ObjectPath(object_index));
}
}
LRESULT UiFileManagerPanel::OnListEndLabelEdit(int ctrl_id, LPNMHDR hdr, BOOL& handled)
{
LPNMLVDISPINFOW disp_info = reinterpret_cast<LPNMLVDISPINFOW>(hdr);
if (!file_list_.HasDirectoryList())
return 0;
int object_index = disp_info->item.lParam;
// New folder.
if (object_index == UiFileList::kNewFolderObjectIndex)
{
CEdit edit(file_list_.GetEditControl());
WCHAR buffer[MAX_PATH] = { 0 };
edit.GetWindowTextW(buffer, _countof(buffer));
FilePath path = drive_list_.CurrentPath();
path.append(buffer);
sender_->SendCreateDirectoryRequest(This(), path);
}
else // Rename exists item.
{
DCHECK(file_list_.IsValidObjectIndex(object_index));
// User canceled rename.
if (!disp_info->item.pszText)
return 0;
FilePath old_name = drive_list_.CurrentPath();
old_name.append(file_list_.ObjectName(object_index));
FilePath new_name = drive_list_.CurrentPath();
new_name.append(disp_info->item.pszText);
sender_->SendRenameRequest(This(), old_name, new_name);
}
return 0;
}
LRESULT UiFileManagerPanel::OnListItemChanged(int ctrl_id, LPNMHDR hdr, BOOL& handled)
{
UINT count = file_list_.GetSelectedCount();
if (file_list_.HasDirectoryList())
{
bool enable = (count != 0);
toolbar_.EnableButton(ID_DELETE, enable);
toolbar_.EnableButton(ID_SEND, enable);
}
CString status;
status.Format(IDS_FT_SELECTED_OBJECT_COUNT, count);
status_.SetWindowTextW(status);
return 0;
}
LRESULT UiFileManagerPanel::OnSend(WORD code, WORD ctrl_id, HWND ctrl, BOOL& handled)
{
if (!file_list_.HasDirectoryList())
return 0;
return 0;
}
LRESULT UiFileManagerPanel::OnDriveEndEdit(int ctrl_id, LPNMHDR hdr, BOOL& handled)
{
PNMCBEENDEDITW end_edit = reinterpret_cast<PNMCBEENDEDITW>(hdr);
if (end_edit->fChanged && end_edit->iWhy == CBENF_RETURN && end_edit->szText)
{
sender_->SendFileListRequest(This(), FilePath(end_edit->szText));
}
return 0;
}
LRESULT UiFileManagerPanel::OnHome(WORD code, WORD ctrl_id, HWND ctrl, BOOL& handled)
{
MoveToDrive(UiDriveList::kComputerObjectIndex);
return 0;
}
void UiFileManagerPanel::OnDriveListRequestReply(std::unique_ptr<proto::DriveList> drive_list)
{
drive_list_.Read(std::move(drive_list));
if (!file_list_.HasDirectoryList())
{
MoveToDrive(UiDriveList::kComputerObjectIndex);
}
}
void UiFileManagerPanel::OnDriveListRequestFailure(proto::RequestStatus status)
{
CString status_string = RequestStatusCodeToString(status);
CString message;
message.Format(IDS_FT_OP_BROWSE_DRIVES_ERROR, status_string.GetBuffer(0));
MessageBoxW(message, nullptr, MB_ICONWARNING | MB_OK);
}
void UiFileManagerPanel::OnFileListRequestReply(const FilePath& path,
std::unique_ptr<proto::FileList> file_list)
{
toolbar_.EnableButton(ID_FOLDER_ADD, TRUE);
toolbar_.EnableButton(ID_FOLDER_UP, TRUE);
toolbar_.EnableButton(ID_HOME, TRUE);
file_list_.Read(std::move(file_list));
drive_list_.SetCurrentPath(path);
}
void UiFileManagerPanel::OnFileListRequestFailure(const FilePath& path,
proto::RequestStatus status)
{
CString status_string = RequestStatusCodeToString(status);
CString message;
message.Format(IDS_FT_BROWSE_FOLDERS_ERROR, path.c_str(), status_string.GetBuffer(0));
MessageBoxW(message, nullptr, MB_ICONWARNING | MB_OK);
}
void UiFileManagerPanel::OnDirectorySizeRequestReply(const FilePath& path,
uint64_t size)
{
// TODO
}
void UiFileManagerPanel::OnDirectorySizeRequestFailure(const FilePath& path,
proto::RequestStatus status)
{
// TODO
}
void UiFileManagerPanel::OnCreateDirectoryRequestReply(const FilePath& path,
proto::RequestStatus status)
{
sender_->SendFileListRequest(This(), drive_list_.CurrentPath());
if (status != proto::RequestStatus::REQUEST_STATUS_SUCCESS)
{
CString status_string = RequestStatusCodeToString(status);
CString message;
message.Format(IDS_FT_OP_CREATE_FOLDER_ERROR, path.c_str(), status_string);
MessageBoxW(message, nullptr, MB_ICONWARNING | MB_OK);
}
}
void UiFileManagerPanel::OnRemoveRequestReply(const FilePath& path,
proto::RequestStatus status)
{
sender_->SendFileListRequest(This(), drive_list_.CurrentPath());
if (status != proto::RequestStatus::REQUEST_STATUS_SUCCESS)
{
CString status_string = RequestStatusCodeToString(status);
CString message;
message.Format(IDS_FT_OP_REMOVE_ERROR, path.c_str(), status_string);
MessageBoxW(message, nullptr, MB_ICONWARNING | MB_OK);
}
}
void UiFileManagerPanel::OnRenameRequestReply(const FilePath& old_name,
const FilePath& new_name,
proto::RequestStatus status)
{
sender_->SendFileListRequest(This(), drive_list_.CurrentPath());
if (status != proto::RequestStatus::REQUEST_STATUS_SUCCESS)
{
CString status_string = RequestStatusCodeToString(status);
CString message;
message.Format(IDS_FT_OP_RENAME_ERROR,
old_name.c_str(),
new_name.c_str(),
status_string);
MessageBoxW(message, nullptr, MB_ICONWARNING | MB_OK);
}
}
} // namespace aspia
<commit_msg>- Correct path setting for the Computer object<commit_after>//
// PROJECT: Aspia Remote Desktop
// FILE: ui/file_manager_panel.cc
// LICENSE: Mozilla Public License Version 2.0
// PROGRAMMERS: Dmitry Chapyshev (dmitry@aspia.ru)
//
#include "ui/file_manager_panel.h"
#include "ui/file_manager_helpers.h"
#include "ui/status_code.h"
#include "base/strings/string_util.h"
#include "base/strings/unicode.h"
#include "base/version_helpers.h"
#include "base/logging.h"
#include <uxtheme.h>
namespace aspia {
namespace fs = std::experimental::filesystem;
static_assert(UiFileList::kInvalidObjectIndex == UiDriveList::kInvalidObjectIndex,
"Values must be equal");
UiFileManagerPanel::UiFileManagerPanel(PanelType panel_type,
std::shared_ptr<FileRequestSenderProxy> sender) :
toolbar_(panel_type == PanelType::LOCAL ?
UiFileToolBar::Type::LOCAL : UiFileToolBar::Type::REMOTE),
panel_type_(panel_type),
sender_(sender)
{
// Nothing
}
LPARAM UiFileManagerPanel::OnCreate(UINT message, WPARAM wparam, LPARAM lparam, BOOL& handled)
{
HFONT default_font = AtlGetStockFont(DEFAULT_GUI_FONT);
CString panel_name;
if (panel_type_ == PanelType::LOCAL)
panel_name.LoadStringW(IDS_FT_LOCAL_COMPUTER);
else
panel_name.LoadStringW(IDS_FT_REMOTE_COMPUTER);
CRect title_rect(0, 0, 200, 20);
title_.Create(*this, title_rect, panel_name, WS_CHILD | WS_VISIBLE | SS_OWNERDRAW);
title_.SetFont(default_font);
drive_list_.CreateDriveList(*this, kDriveListControl);
toolbar_.CreateFileToolBar(*this);
file_list_.CreateFileList(*this, kFileListControl);
CRect status_rect(0, 0, 200, 20);
status_.Create(*this, status_rect, nullptr,
WS_CHILD | WS_VISIBLE | SS_OWNERDRAW);
status_.SetFont(default_font);
sender_->SendDriveListRequest(This());
return 0;
}
LRESULT UiFileManagerPanel::OnDestroy(UINT message, WPARAM wparam, LPARAM lparam, BOOL& handled)
{
drive_list_.DestroyWindow();
file_list_.DestroyWindow();
toolbar_.DestroyWindow();
title_.DestroyWindow();
status_.DestroyWindow();
return 0;
}
LRESULT UiFileManagerPanel::OnSize(UINT message, WPARAM wparam, LPARAM lparam, BOOL& handled)
{
HDWP dwp = BeginDeferWindowPos(5);
if (dwp)
{
CSize size(lparam);
toolbar_.AutoSize();
CRect drive_rect;
drive_list_.GetWindowRect(drive_rect);
CRect toolbar_rect;
toolbar_.GetWindowRect(toolbar_rect);
CRect title_rect;
title_.GetWindowRect(title_rect);
CRect status_rect;
status_.GetWindowRect(status_rect);
title_.DeferWindowPos(dwp, nullptr,
0,
0,
size.cx,
title_rect.Height(),
SWP_NOACTIVATE | SWP_NOZORDER);
drive_list_.DeferWindowPos(dwp, nullptr,
0,
title_rect.Height(),
size.cx,
drive_rect.Height(),
SWP_NOACTIVATE | SWP_NOZORDER);
toolbar_.DeferWindowPos(dwp, nullptr,
0,
title_rect.Height() + drive_rect.Height(),
size.cx,
toolbar_rect.Height(),
SWP_NOACTIVATE | SWP_NOZORDER);
int list_y = title_rect.Height() + toolbar_rect.Height() + drive_rect.Height();
int list_height = size.cy - list_y - status_rect.Height();
file_list_.DeferWindowPos(dwp, nullptr,
0,
list_y,
size.cx,
list_height,
SWP_NOACTIVATE | SWP_NOZORDER);
status_.DeferWindowPos(dwp, nullptr,
0,
list_y + list_height,
size.cx,
status_rect.Height(),
SWP_NOACTIVATE | SWP_NOZORDER);
EndDeferWindowPos(dwp);
}
return 0;
}
LRESULT UiFileManagerPanel::OnDrawItem(UINT message, WPARAM wparam, LPARAM lparam, BOOL& handled)
{
LPDRAWITEMSTRUCT dis = reinterpret_cast<LPDRAWITEMSTRUCT>(lparam);
if (dis->hwndItem == title_ || dis->hwndItem == status_)
{
int saved_dc = SaveDC(dis->hDC);
if (saved_dc)
{
// Transparent background.
SetBkMode(dis->hDC, TRANSPARENT);
HBRUSH background_brush = GetSysColorBrush(COLOR_WINDOW);
FillRect(dis->hDC, &dis->rcItem, background_brush);
WCHAR label[256] = { 0 };
::GetWindowTextW(dis->hwndItem, label, _countof(label));
if (label[0])
{
SetTextColor(dis->hDC, GetSysColor(COLOR_WINDOWTEXT));
DrawTextW(dis->hDC,
label,
wcslen(label),
&dis->rcItem,
DT_VCENTER | DT_SINGLELINE);
}
RestoreDC(dis->hDC, saved_dc);
}
}
return 0;
}
LRESULT UiFileManagerPanel::OnDriveChange(WORD code, WORD ctrl_id, HWND ctrl, BOOL& handled)
{
int object_index = drive_list_.SelectedObject();
if (object_index == UiDriveList::kInvalidObjectIndex)
return 0;
MoveToDrive(object_index);
return 0;
}
LRESULT UiFileManagerPanel::OnListDoubleClock(int ctrl_id, LPNMHDR hdr, BOOL& handled)
{
int object_index = file_list_.GetObjectUnderMousePointer();
if (!file_list_.HasDirectoryList())
{
MoveToDrive(object_index);
return 0;
}
if (!file_list_.IsValidObjectIndex(object_index))
return 0;
const proto::FileList::Item& item = file_list_.Object(object_index);
if (file_list_.IsDirectoryObject(object_index))
{
FilePath path(drive_list_.CurrentPath());
path.append(file_list_.ObjectName(object_index));
sender_->SendFileListRequest(This(), path);
}
return 0;
}
LRESULT UiFileManagerPanel::OnFolderUp(WORD code, WORD ctrl_id, HWND ctrl, BOOL& handled)
{
FilePath path = drive_list_.CurrentPath();
if (!path.has_parent_path() || path.parent_path() == path.root_name())
{
MoveToDrive(UiDriveList::kComputerObjectIndex);
}
else
{
sender_->SendFileListRequest(This(), path.parent_path());
}
return 0;
}
LRESULT UiFileManagerPanel::OnFolderAdd(WORD code, WORD ctrl_id, HWND ctrl, BOOL& handled)
{
file_list_.AddDirectory();
return 0;
}
LRESULT UiFileManagerPanel::OnRefresh(WORD code, WORD ctrl_id, HWND ctrl, BOOL& handled)
{
sender_->SendDriveListRequest(This());
if (file_list_.HasDirectoryList())
{
sender_->SendFileListRequest(This(), drive_list_.CurrentPath());
}
return 0;
}
LRESULT UiFileManagerPanel::OnRemove(WORD code, WORD ctrl_id, HWND ctrl, BOOL& handled)
{
if (!file_list_.HasDirectoryList())
return 0;
UINT selected_count = file_list_.GetSelectedCount();
if (!selected_count)
return 0;
CString title;
title.LoadStringW(IDS_CONFIRMATION);
CString message;
message.Format(IDS_FT_DELETE_CONFORM, selected_count);
if (MessageBoxW(message, title, MB_YESNO | MB_ICONQUESTION) == IDYES)
{
for (UiFileList::Iterator iter(file_list_, UiFileList::Iterator::SELECTED);
!iter.IsAtEnd();
iter.Advance())
{
proto::FileList::Item* object = iter.Object();
if (!object)
continue;
FilePath path = drive_list_.CurrentPath();
path.append(fs::u8path(object->name()));
sender_->SendRemoveRequest(This(), path);
}
}
return 0;
}
void UiFileManagerPanel::MoveToDrive(int object_index)
{
drive_list_.SelectObject(object_index);
if (object_index == UiDriveList::kComputerObjectIndex)
{
toolbar_.EnableButton(ID_FOLDER_ADD, FALSE);
toolbar_.EnableButton(ID_FOLDER_UP, FALSE);
toolbar_.EnableButton(ID_DELETE, FALSE);
toolbar_.EnableButton(ID_SEND, FALSE);
toolbar_.EnableButton(ID_HOME, FALSE);
file_list_.Read(drive_list_.DriveList());
drive_list_.SetCurrentPath(FilePath());
}
else
{
sender_->SendFileListRequest(This(), drive_list_.ObjectPath(object_index));
}
}
LRESULT UiFileManagerPanel::OnListEndLabelEdit(int ctrl_id, LPNMHDR hdr, BOOL& handled)
{
LPNMLVDISPINFOW disp_info = reinterpret_cast<LPNMLVDISPINFOW>(hdr);
if (!file_list_.HasDirectoryList())
return 0;
int object_index = disp_info->item.lParam;
// New folder.
if (object_index == UiFileList::kNewFolderObjectIndex)
{
CEdit edit(file_list_.GetEditControl());
WCHAR buffer[MAX_PATH] = { 0 };
edit.GetWindowTextW(buffer, _countof(buffer));
FilePath path = drive_list_.CurrentPath();
path.append(buffer);
sender_->SendCreateDirectoryRequest(This(), path);
}
else // Rename exists item.
{
DCHECK(file_list_.IsValidObjectIndex(object_index));
// User canceled rename.
if (!disp_info->item.pszText)
return 0;
FilePath old_name = drive_list_.CurrentPath();
old_name.append(file_list_.ObjectName(object_index));
FilePath new_name = drive_list_.CurrentPath();
new_name.append(disp_info->item.pszText);
sender_->SendRenameRequest(This(), old_name, new_name);
}
return 0;
}
LRESULT UiFileManagerPanel::OnListItemChanged(int ctrl_id, LPNMHDR hdr, BOOL& handled)
{
UINT count = file_list_.GetSelectedCount();
if (file_list_.HasDirectoryList())
{
bool enable = (count != 0);
toolbar_.EnableButton(ID_DELETE, enable);
toolbar_.EnableButton(ID_SEND, enable);
}
CString status;
status.Format(IDS_FT_SELECTED_OBJECT_COUNT, count);
status_.SetWindowTextW(status);
return 0;
}
LRESULT UiFileManagerPanel::OnSend(WORD code, WORD ctrl_id, HWND ctrl, BOOL& handled)
{
if (!file_list_.HasDirectoryList())
return 0;
return 0;
}
LRESULT UiFileManagerPanel::OnDriveEndEdit(int ctrl_id, LPNMHDR hdr, BOOL& handled)
{
PNMCBEENDEDITW end_edit = reinterpret_cast<PNMCBEENDEDITW>(hdr);
if (end_edit->fChanged && end_edit->iWhy == CBENF_RETURN && end_edit->szText)
{
sender_->SendFileListRequest(This(), FilePath(end_edit->szText));
}
return 0;
}
LRESULT UiFileManagerPanel::OnHome(WORD code, WORD ctrl_id, HWND ctrl, BOOL& handled)
{
MoveToDrive(UiDriveList::kComputerObjectIndex);
return 0;
}
void UiFileManagerPanel::OnDriveListRequestReply(std::unique_ptr<proto::DriveList> drive_list)
{
drive_list_.Read(std::move(drive_list));
if (!file_list_.HasDirectoryList())
{
MoveToDrive(UiDriveList::kComputerObjectIndex);
}
}
void UiFileManagerPanel::OnDriveListRequestFailure(proto::RequestStatus status)
{
CString status_string = RequestStatusCodeToString(status);
CString message;
message.Format(IDS_FT_OP_BROWSE_DRIVES_ERROR, status_string.GetBuffer(0));
MessageBoxW(message, nullptr, MB_ICONWARNING | MB_OK);
}
void UiFileManagerPanel::OnFileListRequestReply(const FilePath& path,
std::unique_ptr<proto::FileList> file_list)
{
toolbar_.EnableButton(ID_FOLDER_ADD, TRUE);
toolbar_.EnableButton(ID_FOLDER_UP, TRUE);
toolbar_.EnableButton(ID_HOME, TRUE);
file_list_.Read(std::move(file_list));
drive_list_.SetCurrentPath(path);
}
void UiFileManagerPanel::OnFileListRequestFailure(const FilePath& path,
proto::RequestStatus status)
{
CString status_string = RequestStatusCodeToString(status);
CString message;
message.Format(IDS_FT_BROWSE_FOLDERS_ERROR, path.c_str(), status_string.GetBuffer(0));
MessageBoxW(message, nullptr, MB_ICONWARNING | MB_OK);
}
void UiFileManagerPanel::OnDirectorySizeRequestReply(const FilePath& path,
uint64_t size)
{
// TODO
}
void UiFileManagerPanel::OnDirectorySizeRequestFailure(const FilePath& path,
proto::RequestStatus status)
{
// TODO
}
void UiFileManagerPanel::OnCreateDirectoryRequestReply(const FilePath& path,
proto::RequestStatus status)
{
sender_->SendFileListRequest(This(), drive_list_.CurrentPath());
if (status != proto::RequestStatus::REQUEST_STATUS_SUCCESS)
{
CString status_string = RequestStatusCodeToString(status);
CString message;
message.Format(IDS_FT_OP_CREATE_FOLDER_ERROR, path.c_str(), status_string);
MessageBoxW(message, nullptr, MB_ICONWARNING | MB_OK);
}
}
void UiFileManagerPanel::OnRemoveRequestReply(const FilePath& path,
proto::RequestStatus status)
{
sender_->SendFileListRequest(This(), drive_list_.CurrentPath());
if (status != proto::RequestStatus::REQUEST_STATUS_SUCCESS)
{
CString status_string = RequestStatusCodeToString(status);
CString message;
message.Format(IDS_FT_OP_REMOVE_ERROR, path.c_str(), status_string);
MessageBoxW(message, nullptr, MB_ICONWARNING | MB_OK);
}
}
void UiFileManagerPanel::OnRenameRequestReply(const FilePath& old_name,
const FilePath& new_name,
proto::RequestStatus status)
{
sender_->SendFileListRequest(This(), drive_list_.CurrentPath());
if (status != proto::RequestStatus::REQUEST_STATUS_SUCCESS)
{
CString status_string = RequestStatusCodeToString(status);
CString message;
message.Format(IDS_FT_OP_RENAME_ERROR,
old_name.c_str(),
new_name.c_str(),
status_string);
MessageBoxW(message, nullptr, MB_ICONWARNING | MB_OK);
}
}
} // namespace aspia
<|endoftext|>
|
<commit_before>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "google/cloud/grpc_utils/completion_queue.h"
#include "google/cloud/future.h"
#include "google/cloud/testing_util/assert_ok.h"
#include <google/bigtable/admin/v2/bigtable_table_admin.grpc.pb.h>
#include <google/bigtable/v2/bigtable.grpc.pb.h>
#include <gmock/gmock.h>
#include <chrono>
#include <memory>
#include <thread>
namespace google {
namespace cloud {
namespace grpc_utils {
inline namespace GOOGLE_CLOUD_CPP_GRPC_UTILS_NS {
namespace {
class MockCompletionQueue : public internal::CompletionQueueImpl {
public:
using internal::CompletionQueueImpl::SimulateCompletion;
};
namespace btadmin = ::google::bigtable::admin::v2;
namespace btproto = ::google::bigtable::v2;
using ::testing::_;
using ::testing::Invoke;
class MockClient {
public:
MOCK_METHOD3(
AsyncGetTable,
std::unique_ptr<grpc::ClientAsyncResponseReaderInterface<btadmin::Table>>(
grpc::ClientContext*, btadmin::GetTableRequest const&,
grpc::CompletionQueue* cq));
MOCK_METHOD3(AsyncReadRows,
std::unique_ptr<::grpc::ClientAsyncReaderInterface<
btproto::ReadRowsResponse>>(grpc::ClientContext*,
btproto::ReadRowsRequest const&,
grpc::CompletionQueue* cq));
};
class MockTableReader
: public grpc::ClientAsyncResponseReaderInterface<btadmin::Table> {
public:
MOCK_METHOD0(StartCall, void());
MOCK_METHOD1(ReadInitialMetadata, void(void*));
MOCK_METHOD3(Finish, void(btadmin::Table*, grpc::Status*, void*));
};
class MockRowReader
: public grpc::ClientAsyncReaderInterface<btproto::ReadRowsResponse> {
public:
MOCK_METHOD1(StartCall, void(void*));
MOCK_METHOD1(ReadInitialMetadata, void(void*));
MOCK_METHOD2(Read, void(btproto::ReadRowsResponse*, void*));
MOCK_METHOD2(Finish, void(grpc::Status*, void*));
};
/// @test Verify that the basic functionality in a CompletionQueue works.
TEST(CompletionQueueTest, TimerSmokeTest) {
CompletionQueue cq;
std::thread t([&cq] { cq.Run(); });
using ms = std::chrono::milliseconds;
promise<void> wait_for_sleep;
cq.MakeRelativeTimer(ms(2))
.then([&wait_for_sleep](
future<StatusOr<std::chrono::system_clock::time_point>>) {
wait_for_sleep.set_value();
})
.get();
auto f = wait_for_sleep.get_future();
EXPECT_EQ(std::future_status::ready, f.wait_for(ms(0)));
cq.Shutdown();
t.join();
}
TEST(CompletionQueueTest, MockSmokeTest) {
auto mock = std::make_shared<MockCompletionQueue>();
CompletionQueue cq(mock);
using ms = std::chrono::milliseconds;
promise<void> wait_for_sleep;
cq.MakeRelativeTimer(ms(20000)).then(
[&wait_for_sleep](
future<StatusOr<std::chrono::system_clock::time_point>>) {
wait_for_sleep.set_value();
});
mock->SimulateCompletion(/*ok=*/true);
auto f = wait_for_sleep.get_future();
EXPECT_EQ(std::future_status::ready, f.wait_for(ms(0)));
cq.Shutdown();
}
TEST(CompletionQueueTest, ShutdownWithPending) {
using ms = std::chrono::milliseconds;
future<void> timer;
{
CompletionQueue cq;
std::thread runner([&cq] { cq.Run(); });
timer = cq.MakeRelativeTimer(ms(20)).then(
[](future<StatusOr<std::chrono::system_clock::time_point>> result) {
// Timer still runs to completion after `Shutdown`.
EXPECT_STATUS_OK(result.get().status());
});
EXPECT_EQ(std::future_status::timeout, timer.wait_for(ms(0)));
cq.Shutdown();
EXPECT_EQ(std::future_status::timeout, timer.wait_for(ms(0)));
runner.join();
}
EXPECT_EQ(std::future_status::ready, timer.wait_for(ms(0)));
}
TEST(CompletionQueueTest, CanCancelAllEvents) {
using ms = std::chrono::milliseconds;
CompletionQueue cq;
promise<void> done;
std::thread runner([&cq, &done] {
cq.Run();
done.set_value();
});
for (int i = 0; i < 3; ++i) {
cq.MakeRelativeTimer(ms(20000)).then(
[](future<StatusOr<std::chrono::system_clock::time_point>> result) {
// Cancelled timers return CANCELLED status.
EXPECT_EQ(StatusCode::kCancelled, result.get().status().code());
});
}
auto f = done.get_future();
EXPECT_EQ(std::future_status::timeout, f.wait_for(ms(1)));
cq.Shutdown();
EXPECT_EQ(std::future_status::timeout, f.wait_for(ms(1)));
cq.CancelAll();
EXPECT_EQ(std::future_status::ready, f.wait_for(ms(100)));
runner.join();
}
TEST(CompletionQueueTest, MakeUnaryRpc) {
using ms = std::chrono::milliseconds;
auto mock_cq = std::make_shared<MockCompletionQueue>();
CompletionQueue cq(mock_cq);
auto mock_reader = google::cloud::internal::make_unique<MockTableReader>();
EXPECT_CALL(*mock_reader, Finish(_, _, _))
.WillOnce([](btadmin::Table* table, grpc::Status* status, void*) {
table->set_name("test-table-name");
*status = grpc::Status::OK;
});
MockClient mock_client;
EXPECT_CALL(mock_client, AsyncGetTable(_, _, _))
.WillOnce([&mock_reader](grpc::ClientContext*,
btadmin::GetTableRequest const& request,
grpc::CompletionQueue*) {
EXPECT_EQ("test-table-name", request.name());
// This looks like a double delete, but it is not because
// std::unique_ptr<grpc::ClientAsyncResponseReaderInterface<T>> is
// specialized to not delete. :shrug:
return std::unique_ptr<
grpc::ClientAsyncResponseReaderInterface<btadmin::Table>>(
mock_reader.get());
});
std::thread runner([&cq] { cq.Run(); });
btadmin::GetTableRequest request;
request.set_name("test-table-name");
future<void> done =
cq.MakeUnaryRpc(
[&mock_client](grpc::ClientContext* context,
btadmin::GetTableRequest const& request,
grpc::CompletionQueue* cq) {
return mock_client.AsyncGetTable(context, request, cq);
},
request,
google::cloud::internal::make_unique<grpc::ClientContext>())
.then([](future<StatusOr<btadmin::Table>> f) {
auto table = f.get();
ASSERT_STATUS_OK(table);
EXPECT_EQ("test-table-name", table->name());
});
mock_cq->SimulateCompletion(true);
EXPECT_EQ(std::future_status::ready, done.wait_for(ms(0)));
cq.Shutdown();
runner.join();
}
TEST(CompletionQueueTest, MakeStreamingReadRpc) {
auto mock_cq = std::make_shared<MockCompletionQueue>();
CompletionQueue cq(mock_cq);
auto mock_reader = google::cloud::internal::make_unique<MockRowReader>();
EXPECT_CALL(*mock_reader, StartCall(_)).Times(1);
EXPECT_CALL(*mock_reader, Read(_, _)).Times(2);
EXPECT_CALL(*mock_reader, Finish(_, _)).Times(1);
MockClient mock_client;
EXPECT_CALL(mock_client, AsyncReadRows(_, _, _))
.WillOnce([&mock_reader](grpc::ClientContext*,
btproto::ReadRowsRequest const& request,
grpc::CompletionQueue*) {
EXPECT_EQ("test-table-name", request.table_name());
return std::unique_ptr<
grpc::ClientAsyncReaderInterface<btproto::ReadRowsResponse>>(
mock_reader.release());
});
std::thread runner([&cq] { cq.Run(); });
btproto::ReadRowsRequest request;
request.set_table_name("test-table-name");
int on_read_counter = 0;
int on_finish_counter = 0;
(void)cq.MakeStreamingReadRpc(
[&mock_client](grpc::ClientContext* context,
btproto::ReadRowsRequest const& request,
grpc::CompletionQueue* cq) {
return mock_client.AsyncReadRows(context, request, cq);
},
request, google::cloud::internal::make_unique<grpc::ClientContext>(),
[&on_read_counter](btproto::ReadRowsResponse const&) {
++on_read_counter;
return make_ready_future(true);
},
[&on_finish_counter](Status const&) { ++on_finish_counter; });
// Simulate the OnStart() completion
mock_cq->SimulateCompletion(true);
// Simulate the first Read() completion
mock_cq->SimulateCompletion(true);
EXPECT_EQ(1, on_read_counter);
EXPECT_EQ(0, on_finish_counter);
// Simulate a Read() returning false
mock_cq->SimulateCompletion(false);
EXPECT_EQ(1, on_read_counter);
EXPECT_EQ(0, on_finish_counter);
// Simulate the Finish() call completing asynchronously
mock_cq->SimulateCompletion(false);
EXPECT_EQ(1, on_read_counter);
EXPECT_EQ(1, on_finish_counter);
cq.Shutdown();
runner.join();
}
TEST(CompletionQueueTest, RunAsync) {
using ms = std::chrono::milliseconds;
CompletionQueue cq;
std::thread runner([&cq] { cq.Run(); });
std::promise<void> done_promise;
cq.RunAsync([&done_promise](CompletionQueue&) { done_promise.set_value(); });
auto done = done_promise.get_future();
EXPECT_EQ(std::future_status::ready, done.wait_for(ms(10)));
done.get();
cq.Shutdown();
runner.join();
}
} // namespace
} // namespace GOOGLE_CLOUD_CPP_GRPC_UTILS_NS
} // namespace grpc_utils
} // namespace cloud
} // namespace google
<commit_msg>fix: make test not flaky (googleapis/google-cloud-cpp-common#143)<commit_after>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "google/cloud/grpc_utils/completion_queue.h"
#include "google/cloud/future.h"
#include "google/cloud/testing_util/assert_ok.h"
#include <google/bigtable/admin/v2/bigtable_table_admin.grpc.pb.h>
#include <google/bigtable/v2/bigtable.grpc.pb.h>
#include <gmock/gmock.h>
#include <chrono>
#include <memory>
#include <thread>
namespace google {
namespace cloud {
namespace grpc_utils {
inline namespace GOOGLE_CLOUD_CPP_GRPC_UTILS_NS {
namespace {
class MockCompletionQueue : public internal::CompletionQueueImpl {
public:
using internal::CompletionQueueImpl::SimulateCompletion;
};
namespace btadmin = ::google::bigtable::admin::v2;
namespace btproto = ::google::bigtable::v2;
using ::testing::_;
using ::testing::Invoke;
class MockClient {
public:
MOCK_METHOD3(
AsyncGetTable,
std::unique_ptr<grpc::ClientAsyncResponseReaderInterface<btadmin::Table>>(
grpc::ClientContext*, btadmin::GetTableRequest const&,
grpc::CompletionQueue* cq));
MOCK_METHOD3(AsyncReadRows,
std::unique_ptr<::grpc::ClientAsyncReaderInterface<
btproto::ReadRowsResponse>>(grpc::ClientContext*,
btproto::ReadRowsRequest const&,
grpc::CompletionQueue* cq));
};
class MockTableReader
: public grpc::ClientAsyncResponseReaderInterface<btadmin::Table> {
public:
MOCK_METHOD0(StartCall, void());
MOCK_METHOD1(ReadInitialMetadata, void(void*));
MOCK_METHOD3(Finish, void(btadmin::Table*, grpc::Status*, void*));
};
class MockRowReader
: public grpc::ClientAsyncReaderInterface<btproto::ReadRowsResponse> {
public:
MOCK_METHOD1(StartCall, void(void*));
MOCK_METHOD1(ReadInitialMetadata, void(void*));
MOCK_METHOD2(Read, void(btproto::ReadRowsResponse*, void*));
MOCK_METHOD2(Finish, void(grpc::Status*, void*));
};
/// @test Verify that the basic functionality in a CompletionQueue works.
TEST(CompletionQueueTest, TimerSmokeTest) {
CompletionQueue cq;
std::thread t([&cq] { cq.Run(); });
using ms = std::chrono::milliseconds;
promise<void> wait_for_sleep;
cq.MakeRelativeTimer(ms(2))
.then([&wait_for_sleep](
future<StatusOr<std::chrono::system_clock::time_point>>) {
wait_for_sleep.set_value();
})
.get();
auto f = wait_for_sleep.get_future();
EXPECT_EQ(std::future_status::ready, f.wait_for(ms(0)));
cq.Shutdown();
t.join();
}
TEST(CompletionQueueTest, MockSmokeTest) {
auto mock = std::make_shared<MockCompletionQueue>();
CompletionQueue cq(mock);
using ms = std::chrono::milliseconds;
promise<void> wait_for_sleep;
cq.MakeRelativeTimer(ms(20000)).then(
[&wait_for_sleep](
future<StatusOr<std::chrono::system_clock::time_point>>) {
wait_for_sleep.set_value();
});
mock->SimulateCompletion(/*ok=*/true);
auto f = wait_for_sleep.get_future();
EXPECT_EQ(std::future_status::ready, f.wait_for(ms(0)));
cq.Shutdown();
}
TEST(CompletionQueueTest, ShutdownWithPending) {
using ms = std::chrono::milliseconds;
future<void> timer;
{
CompletionQueue cq;
std::thread runner([&cq] { cq.Run(); });
timer = cq.MakeRelativeTimer(ms(20)).then(
[](future<StatusOr<std::chrono::system_clock::time_point>> result) {
// Timer still runs to completion after `Shutdown`.
EXPECT_STATUS_OK(result.get().status());
});
EXPECT_EQ(std::future_status::timeout, timer.wait_for(ms(0)));
cq.Shutdown();
EXPECT_EQ(std::future_status::timeout, timer.wait_for(ms(0)));
runner.join();
}
EXPECT_EQ(std::future_status::ready, timer.wait_for(ms(0)));
}
TEST(CompletionQueueTest, CanCancelAllEvents) {
using ms = std::chrono::milliseconds;
CompletionQueue cq;
promise<void> done;
std::thread runner([&cq, &done] {
cq.Run();
done.set_value();
});
for (int i = 0; i < 3; ++i) {
cq.MakeRelativeTimer(ms(20000)).then(
[](future<StatusOr<std::chrono::system_clock::time_point>> result) {
// Cancelled timers return CANCELLED status.
EXPECT_EQ(StatusCode::kCancelled, result.get().status().code());
});
}
auto f = done.get_future();
EXPECT_EQ(std::future_status::timeout, f.wait_for(ms(1)));
cq.Shutdown();
EXPECT_EQ(std::future_status::timeout, f.wait_for(ms(1)));
cq.CancelAll();
EXPECT_EQ(std::future_status::ready, f.wait_for(ms(100)));
runner.join();
}
TEST(CompletionQueueTest, MakeUnaryRpc) {
using ms = std::chrono::milliseconds;
auto mock_cq = std::make_shared<MockCompletionQueue>();
CompletionQueue cq(mock_cq);
auto mock_reader = google::cloud::internal::make_unique<MockTableReader>();
EXPECT_CALL(*mock_reader, Finish(_, _, _))
.WillOnce([](btadmin::Table* table, grpc::Status* status, void*) {
table->set_name("test-table-name");
*status = grpc::Status::OK;
});
MockClient mock_client;
EXPECT_CALL(mock_client, AsyncGetTable(_, _, _))
.WillOnce([&mock_reader](grpc::ClientContext*,
btadmin::GetTableRequest const& request,
grpc::CompletionQueue*) {
EXPECT_EQ("test-table-name", request.name());
// This looks like a double delete, but it is not because
// std::unique_ptr<grpc::ClientAsyncResponseReaderInterface<T>> is
// specialized to not delete. :shrug:
return std::unique_ptr<
grpc::ClientAsyncResponseReaderInterface<btadmin::Table>>(
mock_reader.get());
});
std::thread runner([&cq] { cq.Run(); });
btadmin::GetTableRequest request;
request.set_name("test-table-name");
future<void> done =
cq.MakeUnaryRpc(
[&mock_client](grpc::ClientContext* context,
btadmin::GetTableRequest const& request,
grpc::CompletionQueue* cq) {
return mock_client.AsyncGetTable(context, request, cq);
},
request,
google::cloud::internal::make_unique<grpc::ClientContext>())
.then([](future<StatusOr<btadmin::Table>> f) {
auto table = f.get();
ASSERT_STATUS_OK(table);
EXPECT_EQ("test-table-name", table->name());
});
mock_cq->SimulateCompletion(true);
EXPECT_EQ(std::future_status::ready, done.wait_for(ms(0)));
cq.Shutdown();
runner.join();
}
TEST(CompletionQueueTest, MakeStreamingReadRpc) {
auto mock_cq = std::make_shared<MockCompletionQueue>();
CompletionQueue cq(mock_cq);
auto mock_reader = google::cloud::internal::make_unique<MockRowReader>();
EXPECT_CALL(*mock_reader, StartCall(_)).Times(1);
EXPECT_CALL(*mock_reader, Read(_, _)).Times(2);
EXPECT_CALL(*mock_reader, Finish(_, _)).Times(1);
MockClient mock_client;
EXPECT_CALL(mock_client, AsyncReadRows(_, _, _))
.WillOnce([&mock_reader](grpc::ClientContext*,
btproto::ReadRowsRequest const& request,
grpc::CompletionQueue*) {
EXPECT_EQ("test-table-name", request.table_name());
return std::unique_ptr<
grpc::ClientAsyncReaderInterface<btproto::ReadRowsResponse>>(
mock_reader.release());
});
std::thread runner([&cq] { cq.Run(); });
btproto::ReadRowsRequest request;
request.set_table_name("test-table-name");
int on_read_counter = 0;
int on_finish_counter = 0;
(void)cq.MakeStreamingReadRpc(
[&mock_client](grpc::ClientContext* context,
btproto::ReadRowsRequest const& request,
grpc::CompletionQueue* cq) {
return mock_client.AsyncReadRows(context, request, cq);
},
request, google::cloud::internal::make_unique<grpc::ClientContext>(),
[&on_read_counter](btproto::ReadRowsResponse const&) {
++on_read_counter;
return make_ready_future(true);
},
[&on_finish_counter](Status const&) { ++on_finish_counter; });
// Simulate the OnStart() completion
mock_cq->SimulateCompletion(true);
// Simulate the first Read() completion
mock_cq->SimulateCompletion(true);
EXPECT_EQ(1, on_read_counter);
EXPECT_EQ(0, on_finish_counter);
// Simulate a Read() returning false
mock_cq->SimulateCompletion(false);
EXPECT_EQ(1, on_read_counter);
EXPECT_EQ(0, on_finish_counter);
// Simulate the Finish() call completing asynchronously
mock_cq->SimulateCompletion(false);
EXPECT_EQ(1, on_read_counter);
EXPECT_EQ(1, on_finish_counter);
cq.Shutdown();
runner.join();
}
TEST(CompletionQueueTest, RunAsync) {
CompletionQueue cq;
std::thread runner([&cq] { cq.Run(); });
std::promise<void> done_promise;
cq.RunAsync([&done_promise](CompletionQueue&) { done_promise.set_value(); });
auto done = done_promise.get_future();
done.get();
cq.Shutdown();
runner.join();
}
} // namespace
} // namespace GOOGLE_CLOUD_CPP_GRPC_UTILS_NS
} // namespace grpc_utils
} // namespace cloud
} // namespace google
<|endoftext|>
|
<commit_before>#include <QDir>
#include <QApplication>
#include "mainwindow.h"
#include "parameter.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QFont font = QApplication::font();
if (font.defaultFamily() == QLatin1String("SimSun")) {
font.setFamily(QLatin1String("Microsoft YaHei"));
QApplication::setFont(font);
}
Parameter::exe = QApplication::applicationDirPath();
#ifdef Q_OS_DARWIN
if (Parameter::exe.endsWith(QLatin1String(".app/Contents/MacOS"))) {
QDir exe(Parameter::exe);
exe.cdUp();
exe.cdUp();
exe.cdUp();
Parameter::exe = exe.absolutePath();
}
#endif
QDir home = QDir::home();
#ifdef Q_OS_WIN32
home.cd(QLatin1String("Documents"));
#endif
home.mkdir(QLatin1String("RTM-GWAS"));
home.cd(QLatin1String("RTM-GWAS"));
Parameter::work = home.absolutePath();
Parameter::open = Parameter::work;
QDir::setCurrent(Parameter::work);
MainWindow w;
w.show();
return a.exec();
}
<commit_msg>Change to font.family<commit_after>#include <QDir>
#include <QApplication>
#include "mainwindow.h"
#include "parameter.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QFont font = QApplication::font();
if (font.family() == QLatin1String("SimSun")) {
font.setFamily(QLatin1String("Microsoft YaHei"));
QApplication::setFont(font);
}
Parameter::exe = QApplication::applicationDirPath();
#ifdef Q_OS_DARWIN
if (Parameter::exe.endsWith(QLatin1String(".app/Contents/MacOS"))) {
QDir exe(Parameter::exe);
exe.cdUp();
exe.cdUp();
exe.cdUp();
Parameter::exe = exe.absolutePath();
}
#endif
QDir home = QDir::home();
#ifdef Q_OS_WIN32
home.cd(QLatin1String("Documents"));
#endif
home.mkdir(QLatin1String("RTM-GWAS"));
home.cd(QLatin1String("RTM-GWAS"));
Parameter::work = home.absolutePath();
Parameter::open = Parameter::work;
QDir::setCurrent(Parameter::work);
MainWindow w;
w.show();
return a.exec();
}
<|endoftext|>
|
<commit_before>// bbldc_basicisdaactualactual.cpp -*-C++-*-
#include <bbldc_basicisdaactualactual.h>
#include <bsls_ident.h>
BSLS_IDENT_RCSID(bbldc_basicisdaactualactual_cpp,"$Id$ $CSID$")
#include <bdlt_serialdateimputil.h>
#include <bsls_assert.h>
namespace BloombergLP {
namespace bbldc {
// ----------------------------
// struct BasicIsdaActualActual
// ----------------------------
// CLASS METHODS
double BasicIsdaActualActual::yearsDiff(const bdlt::Date& beginDate,
const bdlt::Date& endDate)
{
const int beginYear = beginDate.year();
const int endYear = endDate.year();
const int daysInBeginYear =
365 + bdlt::SerialDateImpUtil::isLeapYear(beginYear);
const int daysInEndYear =
365 + bdlt::SerialDateImpUtil::isLeapYear(endYear);
const int yDiff = endYear - beginYear - 1;
const int beginYearDayDiff = bdlt::Date(beginYear + 1, 1, 1) - beginDate;
const int endYearDayDiff = endDate - bdlt::Date(endYear, 1, 1);
double result = (yDiff * daysInBeginYear * daysInEndYear
+ beginYearDayDiff * daysInEndYear
+ endYearDayDiff * daysInBeginYear)
/ static_cast<double>(daysInBeginYear * daysInEndYear);
return result;
}
} // close package namespace
} // close enterprise namespace
// ----------------------------------------------------------------------------
// Copyright 2017 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
<commit_msg>Jeff's comments #3<commit_after>// bbldc_basicisdaactualactual.cpp -*-C++-*-
#include <bbldc_basicisdaactualactual.h>
#include <bsls_ident.h>
BSLS_IDENT_RCSID(bbldc_basicisdaactualactual_cpp,"$Id$ $CSID$")
#include <bdlt_serialdateimputil.h>
#include <bsls_assert.h>
namespace BloombergLP {
namespace bbldc {
// ----------------------------
// struct BasicIsdaActualActual
// ----------------------------
// CLASS METHODS
double BasicIsdaActualActual::yearsDiff(const bdlt::Date& beginDate,
const bdlt::Date& endDate)
{
const int beginYear = beginDate.year();
const int endYear = endDate.year();
const int daysInBeginYear =
365 + bdlt::SerialDateImpUtil::isLeapYear(beginYear);
const int daysInEndYear =
365 + bdlt::SerialDateImpUtil::isLeapYear(endYear);
const int yDiff = endYear - beginYear - 1;
const int beginYearDayDiff = bdlt::Date(beginYear + 1, 1, 1) - beginDate;
const int endYearDayDiff = endDate - bdlt::Date(endYear, 1, 1);
const int numerator = yDiff * daysInBeginYear * daysInEndYear
+ beginYearDayDiff * daysInEndYear
+ endYearDayDiff * daysInBeginYear;
const int denominator = daysInBeginYear * daysInEndYear;
return numerator / static_cast<double>(daysInBeginYear * daysInEndYear);
}
} // close package namespace
} // close enterprise namespace
// ----------------------------------------------------------------------------
// Copyright 2017 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
<|endoftext|>
|
<commit_before>#ifndef BUW_COLOR_HPP
#define BUW_COLOR_HPP
#include <iostream>
struct Color
{
Color(float red, float green, float blue) : r_(red), g_(green), b_(blue) {}
float r_;
float g_;
float b_;
friend std::ostream& operator<<(std::ostream& os, Color const& c)
{
os << "(" << c.r_ << "," << c.g_ << "," << c.b_ << ")\n";
return os;
}
Color& operator+=(Color const& other)
{
r_ += other.r_;
g_ += other.g_;
b_ += other.b_;
return *this;
}
Color& operator-=(Color const& other)
{
r_ -= other.r_;
g_ -= other.g_;
b_ -= other.b_;
return *this;
}
friend Color operator+(Color const& a, Color const& b)
{
auto tmp(a);
tmp += b;
return tmp;
}
friend Color operator-(Color const& a, Color const& b)
{
auto tmp(a);
tmp -= b;
return tmp;
}
};
#endif //#define BUW_COLOR_HPP
<commit_msg>Rename members.<commit_after>#ifndef BUW_COLOR_HPP
#define BUW_COLOR_HPP
#include <iostream>
struct Color
{
Color(float red, float green, float blue) : r(red), g(green), b(blue) {}
float r;
float g;
float b;
friend std::ostream& operator<<(std::ostream& os, Color const& c)
{
os << "(" << c.r << "," << c.g << "," << c.b << ")\n";
return os;
}
Color& operator+=(Color const& other)
{
r += other.r;
g += other.g;
b += other.b;
return *this;
}
Color& operator-=(Color const& other)
{
r -= other.r;
g -= other.g;
b -= other.b;
return *this;
}
friend Color operator+(Color const& a, Color const& b)
{
auto tmp(a);
tmp += b;
return tmp;
}
friend Color operator-(Color const& a, Color const& b)
{
auto tmp(a);
tmp -= b;
return tmp;
}
};
#endif //#define BUW_COLOR_HPP
<|endoftext|>
|
<commit_before>/*
* InterColComm.cpp
*
* Created on: Aug 28, 2008
* Author: rasmussn
*/
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "InterColComm.hpp"
#include "HyPerCol.hpp"
namespace PV {
InterColComm::InterColComm(int* argc, char*** argv) : Communicator(argc, argv)
{
numPublishers = 0;
publisherArraySize = INITIAL_PUBLISHER_ARRAY_SIZE;
publishers = (Publisher **) malloc( publisherArraySize * sizeof(Publisher *) );
for (int i = 0; i < publisherArraySize; i++) {
publishers[i] = NULL;
}
}
InterColComm::~InterColComm()
{
clearPublishers();
free(publishers); publishers = NULL;
}
int InterColComm::addPublisher(HyPerLayer* pub, int numItems, int numLevels)
{
int pubId = pub->getLayerId();
if( pubId >= publisherArraySize) {
int status = resizePublishersArray(pubId+1);
assert(status == EXIT_SUCCESS);
}
#ifdef PV_USE_OPENCL
bool copydstoreflag=pub->getCopyDataStoreFlag();
publishers[pubId] = new Publisher(pubId, pub->getParent(), numItems, pub->getCLayer()->loc, numLevels, copydstoreflag);
#else
publishers[pubId] = new Publisher(pubId, pub->getParent(), numItems, pub->clayer->loc, numLevels);
#endif
numPublishers += 1;
return pubId;
}
int InterColComm::clearPublishers() {
for (int i=0; i<numPublishers; i++) {
delete publishers[i]; publishers[i] = NULL;
}
numPublishers = 0;
return PV_SUCCESS;
}
int InterColComm::resizePublishersArray(int newSize) {
/* If newSize is greater than the existing size publisherArraySize,
* create a new array of size newSize, and copy over the existing
* publishers. publisherArraySize is updated, to equal newSize.
* If newSize <= publisherArraySize, do nothing
* Returns EXIT_SUCCESS if resizing was successful
* (or not needed; i.e. if newSize<=publisherArraySize)
* Returns EXIT_FAILURE if unable to allocate a new array; in this
* (unlikely) case, publishers and publisherArraySize are unchanged.
*/
if( newSize > publisherArraySize ) {
Publisher ** newPublishers = (Publisher **) malloc( newSize * sizeof(Publisher *) );
if( newPublishers == NULL) return EXIT_FAILURE;
for( int k=0; k< publisherArraySize; k++ ) {
newPublishers[k] = publishers[k];
}
for( int k=publisherArraySize; k<newSize; k++) {
newPublishers[k] = NULL;
}
free(publishers);
publishers = newPublishers;
publisherArraySize = newSize;
}
return EXIT_SUCCESS;
}
int InterColComm::subscribe(HyPerConn* conn)
{
int pubId = conn->preSynapticLayer()->getLayerId();
assert( pubId < publisherArraySize && pubId >= 0);
return publishers[pubId]->subscribe(conn);
}
int InterColComm::publish(HyPerLayer* pub, PVLayerCube* cube)
{
int pubId = pub->getLayerId();
return publishers[pubId]->publish(pub, neighbors, numNeighbors, borders, numBorders, cube);
}
int InterColComm::exchangeBorders(int pubId, const PVLayerLoc * loc, int delay/*default=0*/) {
int status = publishers[pubId]->exchangeBorders(neighbors, numNeighbors, loc, delay);
return status;
}
/**
* wait until all outstanding published messages have arrived
*/
int InterColComm::wait(int pubId)
{
return publishers[pubId]->wait();
}
#ifdef OBSOLETE // Marked obsolete July 25, 2013. recvSynapticInput is now called by recvAllSynapticInput, called by HyPerCol, so deliver andtriggerReceive aren't needed.
/**
* deliver all outstanding published messages
*/
int InterColComm::deliver(HyPerCol* hc, int pubId)
{
#ifdef DEBUG_OUTPUT
printf("[%d]: InterColComm::deliver: pubId=%d\n", commRank(), pubId); fflush(stdout);
#endif // DEBUG_OUTPUT
return publishers[pubId]->deliver(hc, numNeighbors, numBorders);
}
#endif // OBSOLETE
#ifdef PV_USE_OPENCL
Publisher::Publisher(int pubId, HyPerCol * hc, int numItems, PVLayerLoc loc, int numLevels, bool copydstoreflag)
#else
Publisher::Publisher(int pubId, HyPerCol * hc, int numItems, PVLayerLoc loc, int numLevels)
#endif
{
size_t dataSize = numItems * sizeof(float);
this->pubId = pubId;
this->comm = hc->icCommunicator();
this->numSubscribers = 0;
cube.data = NULL;
cube.loc = loc;
cube.numItems = numItems;
// not really inplace but ok as is only used to deliver
// to provide cube information for data from store
cube.size = dataSize + sizeof(PVLayerCube);
const int numBuffers = 1;
#ifdef PV_USE_OPENCL
store = new DataStore(hc, numBuffers, dataSize, numLevels, copydstoreflag);
#else
store = new DataStore(hc, numBuffers, dataSize, numLevels);
#endif
//DONE: check for memory leak here, method flagged by valgrind
this->neighborDatatypes = Communicator::newDatatypes(&loc);
this->subscriberArraySize = INITIAL_SUBSCRIBER_ARRAY_SIZE;
this->connection = (HyPerConn **) malloc( subscriberArraySize * sizeof(HyPerConn *) );
assert(this->connection);
for (int i = 0; i < subscriberArraySize; i++) {
this->connection[i] = NULL;
}
numRequests = 0;
}
Publisher::~Publisher()
{
delete store;
Communicator::freeDatatypes(neighborDatatypes); neighborDatatypes = NULL;
free(connection);
}
int Publisher::publish(HyPerLayer* pub,
int neighbors[], int numNeighbors,
int borders[], int numBorders,
PVLayerCube* cube, int delay/*default=0*/)
{
//
// Everyone publishes border region to neighbors even if no subscribers.
// This means that everyone should wait as well.
//
size_t dataSize = cube->numItems * sizeof(pvdata_t);
assert(dataSize == store->size());
pvdata_t * sendBuf = cube->data;
pvdata_t * recvBuf = recvBuffer(LOCAL); // only LOCAL buffer, neighbors copy into LOCAL extended buffer
if (pub->getLastUpdateTime() >= pub->getParent()->simulationTime()) {
// copy entire layer and let neighbors overwrite
// TODO - have layers use the data store directly then no need for extra copy
//Only memcopy if layer needs an update
memcpy(recvBuf, sendBuf, dataSize);
exchangeBorders(neighbors, numNeighbors, &cube->loc, 0);
}
return PV_SUCCESS;
}
int Publisher::exchangeBorders(int neighbors[], int numNeighbors, const PVLayerLoc * loc, int delay/*default 0*/) {
// Code duplication with Communicator::exchange. Consolidate?
int status = PV_SUCCESS;
#ifdef PV_USE_MPI
int icRank = comm->commRank();
MPI_Comm mpiComm = comm->communicator();
// don't send interior
assert(numRequests == 0);
for (int n = 1; n < NUM_NEIGHBORHOOD; n++) {
if (neighbors[n] == icRank) continue; // don't send interior to self
pvdata_t * recvBuf = recvBuffer(LOCAL, delay) + comm->recvOffset(n, loc);
// sendBuf = cube->data + Communicator::sendOffset(n, &cube->loc);
pvdata_t * sendBuf = recvBuffer(LOCAL, delay) + comm->sendOffset(n, loc);
#ifdef DEBUG_OUTPUT
size_t recvOff = comm->recvOffset(n, &cube.loc);
size_t sendOff = comm->sendOffset(n, &cube.loc);
if( cube.loc.nb > 0 ) {
fprintf(stderr, "[%2d]: recv,send to %d, n=%d, delay=%d, recvOffset==%ld, sendOffset==%ld, numitems=%d, send[0]==%f\n", comm->commRank(), neighbors[n], n, delay, recvOff, sendOff, cube.numItems, sendBuf[0]);
}
else {
fprintf(stderr, "[%2d]: recv,send to %d, n=%d, delay=%d, recvOffset==%ld, sendOffset==%ld, numitems=%d\n", comm->commRank(), neighbors[n], n, delay, recvOff, sendOff, cube.numItems);
}
fflush(stdout);
#endif //DEBUG_OUTPUT
MPI_Irecv(recvBuf, 1, neighborDatatypes[n], neighbors[n], comm->getTag(n), mpiComm,
&requests[numRequests++]);
int status = MPI_Send( sendBuf, 1, neighborDatatypes[n], neighbors[n], comm->getTag(n), mpiComm);
assert(status==0);
}
assert(numRequests == comm->numberOfNeighbors() - 1);
#endif // PV_USE_MPI
return status;
}
/**
* wait until all outstanding published messages have arrived
*/
int Publisher::wait()
{
#ifdef PV_USE_MPI
# ifdef DEBUG_OUTPUT
fprintf(stderr, "[%2d]: waiting for data, num_requests==%d\n", comm->commRank(), numRemote); fflush(stdout);
# endif // DEBUG_OUTPUT
if (numRequests != 0) {
MPI_Waitall(numRequests, requests, MPI_STATUSES_IGNORE);
numRequests = 0;
}
#endif // PV_USE_MPI
return 0;
}
#ifdef OBSOLETE // Marked obsolete July 25, 2013. recvSynapticInput is now called by recvAllSynapticInput, called by HyPerCol, so deliver andtriggerReceive aren't needed.
/**
* deliver published messages
*/
int Publisher::deliver(HyPerCol* hc, int numNeighbors, int numBorders)
{
//
// Waiting for data to arrive has been separated from delivery.
// This method now assumes that wait has already been called
// and that the data have all arrived from remote neighbors.
//
#ifdef PV_USE_OPENCL
// TODO - send border data to device
#endif // PV_USE_OPENCL
for (int ic = 0; ic < numSubscribers; ic++) {
HyPerConn* conn = connection[ic];
// int delay = conn->getDelay(0);
// if (delay > 0) {
// cube.data = recvBuffer(LOCAL, delay);
// }
// else {
// cube.data = recvBuffer(LOCAL);
// }
#ifdef DEBUG_OUTPUT
printf("[%d]: Publisher::deliver: buf=%p\n", comm->commRank(), cube.data);
fflush(stdout);
#endif // DEBUG_OUTPUT
//I'm moving this to below. Now that layers will decide based on a Params
//flag whether that layer is GPU accelerated, the layers will tell
//connections whether to use GPU acceleration and the connections
//will then decide how to handle deliver
//#ifdef PV_USE_OPENCL
// conn->deliverOpenCL(this);
//#else
// conn->deliver(this, &cube, LOCAL);
//#endif // PV_USE_OPENCL
conn->deliver(this, &cube, LOCAL);
}
return 0;
}
#endif // OBSOLETE
int Publisher::readData(int delay) {
if (delay > 0) {
cube.data = recvBuffer(LOCAL, delay);
}
else {
cube.data = recvBuffer(LOCAL);
}
return 0;
}
int Publisher::subscribe(HyPerConn* conn)
{
assert(numSubscribers <= subscriberArraySize);
if( numSubscribers == subscriberArraySize ) {
subscriberArraySize += RESIZE_ARRAY_INCR;
HyPerConn ** newConnection = (HyPerConn **) malloc( subscriberArraySize * sizeof(HyPerConn *) );
assert(newConnection);
for( int k=0; k<numSubscribers; k++ ) {
newConnection[k] = connection[k];
}
free(connection);
connection = newConnection;
}
connection[numSubscribers] = conn;
numSubscribers += 1;
return 0;
}
} // end namespace PV
<commit_msg>Changing EXIT_SUCCESS to PV_SUCCESS when not exiting<commit_after>/*
* InterColComm.cpp
*
* Created on: Aug 28, 2008
* Author: rasmussn
*/
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "InterColComm.hpp"
#include "HyPerCol.hpp"
namespace PV {
InterColComm::InterColComm(int* argc, char*** argv) : Communicator(argc, argv)
{
numPublishers = 0;
publisherArraySize = INITIAL_PUBLISHER_ARRAY_SIZE;
publishers = (Publisher **) malloc( publisherArraySize * sizeof(Publisher *) );
for (int i = 0; i < publisherArraySize; i++) {
publishers[i] = NULL;
}
}
InterColComm::~InterColComm()
{
clearPublishers();
free(publishers); publishers = NULL;
}
int InterColComm::addPublisher(HyPerLayer* pub, int numItems, int numLevels)
{
int pubId = pub->getLayerId();
if( pubId >= publisherArraySize) {
int status = resizePublishersArray(pubId+1);
assert(status == EXIT_SUCCESS);
}
#ifdef PV_USE_OPENCL
bool copydstoreflag=pub->getCopyDataStoreFlag();
publishers[pubId] = new Publisher(pubId, pub->getParent(), numItems, pub->getCLayer()->loc, numLevels, copydstoreflag);
#else
publishers[pubId] = new Publisher(pubId, pub->getParent(), numItems, pub->clayer->loc, numLevels);
#endif
numPublishers += 1;
return pubId;
}
int InterColComm::clearPublishers() {
for (int i=0; i<numPublishers; i++) {
delete publishers[i]; publishers[i] = NULL;
}
numPublishers = 0;
return PV_SUCCESS;
}
int InterColComm::resizePublishersArray(int newSize) {
/* If newSize is greater than the existing size publisherArraySize,
* create a new array of size newSize, and copy over the existing
* publishers. publisherArraySize is updated, to equal newSize.
* If newSize <= publisherArraySize, do nothing
* Returns PV_SUCCESS if resizing was successful
* (or not needed; i.e. if newSize<=publisherArraySize)
* Returns PV_FAILURE if unable to allocate a new array; in this
* (unlikely) case, publishers and publisherArraySize are unchanged.
*/
if( newSize > publisherArraySize ) {
Publisher ** newPublishers = (Publisher **) malloc( newSize * sizeof(Publisher *) );
if( newPublishers == NULL) return PV_FAILURE;
for( int k=0; k< publisherArraySize; k++ ) {
newPublishers[k] = publishers[k];
}
for( int k=publisherArraySize; k<newSize; k++) {
newPublishers[k] = NULL;
}
free(publishers);
publishers = newPublishers;
publisherArraySize = newSize;
}
return PV_SUCCESS;
}
int InterColComm::subscribe(HyPerConn* conn)
{
int pubId = conn->preSynapticLayer()->getLayerId();
assert( pubId < publisherArraySize && pubId >= 0);
return publishers[pubId]->subscribe(conn);
}
int InterColComm::publish(HyPerLayer* pub, PVLayerCube* cube)
{
int pubId = pub->getLayerId();
return publishers[pubId]->publish(pub, neighbors, numNeighbors, borders, numBorders, cube);
}
int InterColComm::exchangeBorders(int pubId, const PVLayerLoc * loc, int delay/*default=0*/) {
int status = publishers[pubId]->exchangeBorders(neighbors, numNeighbors, loc, delay);
return status;
}
/**
* wait until all outstanding published messages have arrived
*/
int InterColComm::wait(int pubId)
{
return publishers[pubId]->wait();
}
#ifdef OBSOLETE // Marked obsolete July 25, 2013. recvSynapticInput is now called by recvAllSynapticInput, called by HyPerCol, so deliver andtriggerReceive aren't needed.
/**
* deliver all outstanding published messages
*/
int InterColComm::deliver(HyPerCol* hc, int pubId)
{
#ifdef DEBUG_OUTPUT
printf("[%d]: InterColComm::deliver: pubId=%d\n", commRank(), pubId); fflush(stdout);
#endif // DEBUG_OUTPUT
return publishers[pubId]->deliver(hc, numNeighbors, numBorders);
}
#endif // OBSOLETE
#ifdef PV_USE_OPENCL
Publisher::Publisher(int pubId, HyPerCol * hc, int numItems, PVLayerLoc loc, int numLevels, bool copydstoreflag)
#else
Publisher::Publisher(int pubId, HyPerCol * hc, int numItems, PVLayerLoc loc, int numLevels)
#endif
{
size_t dataSize = numItems * sizeof(float);
this->pubId = pubId;
this->comm = hc->icCommunicator();
this->numSubscribers = 0;
cube.data = NULL;
cube.loc = loc;
cube.numItems = numItems;
// not really inplace but ok as is only used to deliver
// to provide cube information for data from store
cube.size = dataSize + sizeof(PVLayerCube);
const int numBuffers = 1;
#ifdef PV_USE_OPENCL
store = new DataStore(hc, numBuffers, dataSize, numLevels, copydstoreflag);
#else
store = new DataStore(hc, numBuffers, dataSize, numLevels);
#endif
//DONE: check for memory leak here, method flagged by valgrind
this->neighborDatatypes = Communicator::newDatatypes(&loc);
this->subscriberArraySize = INITIAL_SUBSCRIBER_ARRAY_SIZE;
this->connection = (HyPerConn **) malloc( subscriberArraySize * sizeof(HyPerConn *) );
assert(this->connection);
for (int i = 0; i < subscriberArraySize; i++) {
this->connection[i] = NULL;
}
numRequests = 0;
}
Publisher::~Publisher()
{
delete store;
Communicator::freeDatatypes(neighborDatatypes); neighborDatatypes = NULL;
free(connection);
}
int Publisher::publish(HyPerLayer* pub,
int neighbors[], int numNeighbors,
int borders[], int numBorders,
PVLayerCube* cube, int delay/*default=0*/)
{
//
// Everyone publishes border region to neighbors even if no subscribers.
// This means that everyone should wait as well.
//
size_t dataSize = cube->numItems * sizeof(pvdata_t);
assert(dataSize == store->size());
pvdata_t * sendBuf = cube->data;
pvdata_t * recvBuf = recvBuffer(LOCAL); // only LOCAL buffer, neighbors copy into LOCAL extended buffer
if (pub->getLastUpdateTime() >= pub->getParent()->simulationTime()) {
// copy entire layer and let neighbors overwrite
// TODO - have layers use the data store directly then no need for extra copy
//Only memcopy if layer needs an update
memcpy(recvBuf, sendBuf, dataSize);
exchangeBorders(neighbors, numNeighbors, &cube->loc, 0);
}
return PV_SUCCESS;
}
int Publisher::exchangeBorders(int neighbors[], int numNeighbors, const PVLayerLoc * loc, int delay/*default 0*/) {
// Code duplication with Communicator::exchange. Consolidate?
int status = PV_SUCCESS;
#ifdef PV_USE_MPI
int icRank = comm->commRank();
MPI_Comm mpiComm = comm->communicator();
// don't send interior
assert(numRequests == 0);
for (int n = 1; n < NUM_NEIGHBORHOOD; n++) {
if (neighbors[n] == icRank) continue; // don't send interior to self
pvdata_t * recvBuf = recvBuffer(LOCAL, delay) + comm->recvOffset(n, loc);
// sendBuf = cube->data + Communicator::sendOffset(n, &cube->loc);
pvdata_t * sendBuf = recvBuffer(LOCAL, delay) + comm->sendOffset(n, loc);
#ifdef DEBUG_OUTPUT
size_t recvOff = comm->recvOffset(n, &cube.loc);
size_t sendOff = comm->sendOffset(n, &cube.loc);
if( cube.loc.nb > 0 ) {
fprintf(stderr, "[%2d]: recv,send to %d, n=%d, delay=%d, recvOffset==%ld, sendOffset==%ld, numitems=%d, send[0]==%f\n", comm->commRank(), neighbors[n], n, delay, recvOff, sendOff, cube.numItems, sendBuf[0]);
}
else {
fprintf(stderr, "[%2d]: recv,send to %d, n=%d, delay=%d, recvOffset==%ld, sendOffset==%ld, numitems=%d\n", comm->commRank(), neighbors[n], n, delay, recvOff, sendOff, cube.numItems);
}
fflush(stdout);
#endif //DEBUG_OUTPUT
MPI_Irecv(recvBuf, 1, neighborDatatypes[n], neighbors[n], comm->getTag(n), mpiComm,
&requests[numRequests++]);
int status = MPI_Send( sendBuf, 1, neighborDatatypes[n], neighbors[n], comm->getTag(n), mpiComm);
assert(status==0);
}
assert(numRequests == comm->numberOfNeighbors() - 1);
#endif // PV_USE_MPI
return status;
}
/**
* wait until all outstanding published messages have arrived
*/
int Publisher::wait()
{
#ifdef PV_USE_MPI
# ifdef DEBUG_OUTPUT
fprintf(stderr, "[%2d]: waiting for data, num_requests==%d\n", comm->commRank(), numRemote); fflush(stdout);
# endif // DEBUG_OUTPUT
if (numRequests != 0) {
MPI_Waitall(numRequests, requests, MPI_STATUSES_IGNORE);
numRequests = 0;
}
#endif // PV_USE_MPI
return 0;
}
#ifdef OBSOLETE // Marked obsolete July 25, 2013. recvSynapticInput is now called by recvAllSynapticInput, called by HyPerCol, so deliver andtriggerReceive aren't needed.
/**
* deliver published messages
*/
int Publisher::deliver(HyPerCol* hc, int numNeighbors, int numBorders)
{
//
// Waiting for data to arrive has been separated from delivery.
// This method now assumes that wait has already been called
// and that the data have all arrived from remote neighbors.
//
#ifdef PV_USE_OPENCL
// TODO - send border data to device
#endif // PV_USE_OPENCL
for (int ic = 0; ic < numSubscribers; ic++) {
HyPerConn* conn = connection[ic];
// int delay = conn->getDelay(0);
// if (delay > 0) {
// cube.data = recvBuffer(LOCAL, delay);
// }
// else {
// cube.data = recvBuffer(LOCAL);
// }
#ifdef DEBUG_OUTPUT
printf("[%d]: Publisher::deliver: buf=%p\n", comm->commRank(), cube.data);
fflush(stdout);
#endif // DEBUG_OUTPUT
//I'm moving this to below. Now that layers will decide based on a Params
//flag whether that layer is GPU accelerated, the layers will tell
//connections whether to use GPU acceleration and the connections
//will then decide how to handle deliver
//#ifdef PV_USE_OPENCL
// conn->deliverOpenCL(this);
//#else
// conn->deliver(this, &cube, LOCAL);
//#endif // PV_USE_OPENCL
conn->deliver(this, &cube, LOCAL);
}
return 0;
}
#endif // OBSOLETE
int Publisher::readData(int delay) {
if (delay > 0) {
cube.data = recvBuffer(LOCAL, delay);
}
else {
cube.data = recvBuffer(LOCAL);
}
return 0;
}
int Publisher::subscribe(HyPerConn* conn)
{
assert(numSubscribers <= subscriberArraySize);
if( numSubscribers == subscriberArraySize ) {
subscriberArraySize += RESIZE_ARRAY_INCR;
HyPerConn ** newConnection = (HyPerConn **) malloc( subscriberArraySize * sizeof(HyPerConn *) );
assert(newConnection);
for( int k=0; k<numSubscribers; k++ ) {
newConnection[k] = connection[k];
}
free(connection);
connection = newConnection;
}
connection[numSubscribers] = conn;
numSubscribers += 1;
return 0;
}
} // end namespace PV
<|endoftext|>
|
<commit_before>#pragma once
#include <thread>
#include <poll.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
namespace nix {
class MonitorFdHup
{
private:
std::thread thread;
public:
MonitorFdHup(int fd)
{
thread = std::thread([&]() {
/* Wait indefinitely until a POLLHUP occurs. */
struct pollfd fds[1];
fds[0].fd = fd;
fds[0].events = 0;
if (poll(fds, 1, -1) == -1) {
if (errno != EINTR) abort(); // can't happen
return; // destructor is asking us to exit
}
/* We got POLLHUP, so send an INT signal to the main thread. */
kill(getpid(), SIGINT);
});
};
~MonitorFdHup()
{
pthread_kill(thread.native_handle(), SIGINT);
thread.join();
}
};
}
<commit_msg>Add some assertions<commit_after>#pragma once
#include <thread>
#include <atomic>
#include <poll.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
namespace nix {
class MonitorFdHup
{
private:
std::thread thread;
std::atomic_bool quit;
public:
MonitorFdHup(int fd)
{
quit = false;
thread = std::thread([&]() {
/* Wait indefinitely until a POLLHUP occurs. */
struct pollfd fds[1];
fds[0].fd = fd;
fds[0].events = 0;
if (poll(fds, 1, -1) == -1) {
if (errno != EINTR) abort(); // can't happen
assert(quit);
return; // destructor is asking us to exit
}
assert(fds[0].revents & POLLHUP);
/* We got POLLHUP, so send an INT signal to the main thread. */
kill(getpid(), SIGINT);
});
};
~MonitorFdHup()
{
quit = true;
pthread_kill(thread.native_handle(), SIGINT);
thread.join();
}
};
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include <winsock2.h>
#include <ws2tcpip.h>
#include <mswsock.h>
#include "bin/builtin.h"
#include "bin/eventhandler.h"
#include "bin/socket.h"
bool Socket::Initialize() {
int err;
WSADATA winsock_data;
WORD version_requested = MAKEWORD(1, 0);
err = WSAStartup(version_requested, &winsock_data);
if (err != 0) {
fprintf(stderr, "Unable to initialize Winsock: %d\n", WSAGetLastError());
}
return err == 0;
}
intptr_t Socket::Available(intptr_t fd) {
ClientSocket* client_socket = reinterpret_cast<ClientSocket*>(fd);
return client_socket->Available();
}
intptr_t Socket::Read(intptr_t fd, void* buffer, intptr_t num_bytes) {
Handle* handle = reinterpret_cast<Handle*>(fd);
return handle->Read(buffer, num_bytes);
}
intptr_t Socket::Write(intptr_t fd, const void* buffer, intptr_t num_bytes) {
Handle* handle = reinterpret_cast<Handle*>(fd);
return handle->Write(buffer, num_bytes);
}
intptr_t Socket::GetPort(intptr_t fd) {
ASSERT(reinterpret_cast<Handle*>(fd)->is_socket());
SocketHandle* socket_handle = reinterpret_cast<SocketHandle*>(fd);
struct sockaddr_in socket_address;
socklen_t size = sizeof(socket_address);
if (getsockname(socket_handle->socket(),
reinterpret_cast<struct sockaddr *>(&socket_address),
&size)) {
fprintf(stderr, "Error getsockname: %s\n", strerror(errno));
return 0;
}
return ntohs(socket_address.sin_port);
}
bool Socket::GetRemotePeer(intptr_t fd, char *host, intptr_t *port) {
ASSERT(DART_INET_ADDRSTRLEN >= INET_ADDRSTRLEN);
ASSERT(reinterpret_cast<Handle*>(fd)->is_socket());
SocketHandle* socket_handle = reinterpret_cast<SocketHandle*>(fd);
struct sockaddr_in socket_address;
socklen_t size = sizeof(socket_address);
if (getpeername(socket_handle->socket(),
reinterpret_cast<struct sockaddr *>(&socket_address),
&size)) {
fprintf(stderr, "Error getpeername: %s\n", strerror(errno));
return false;
}
if (inet_ntop(socket_address.sin_family,
reinterpret_cast<const void *>(&socket_address.sin_addr),
host,
INET_ADDRSTRLEN) == NULL) {
fprintf(stderr, "Error inet_ntop: %s\n", strerror(errno));
return false;
}
*port = ntohs(socket_address.sin_port);
return true;
intptr_t Socket::CreateConnect(const char* host, const intptr_t port) {
SOCKET s = socket(AF_INET, SOCK_STREAM, 0);
if (s == INVALID_SOCKET) {
return -1;
}
linger l;
l.l_onoff = 1;
l.l_linger = 10;
int status = setsockopt(s,
SOL_SOCKET,
SO_LINGER,
reinterpret_cast<char*>(&l),
sizeof(l));
if (status != NO_ERROR) {
FATAL("Failed setting SO_LINGER on socket");
}
// Perform a name lookup for an IPv4 address.
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
struct addrinfo* result = NULL;
status = getaddrinfo(host, 0, &hints, &result);
if (status != NO_ERROR) {
return -1;
}
// Copy IPv4 address and set the port.
struct sockaddr_in server_address;
memcpy(&server_address,
reinterpret_cast<sockaddr_in *>(result->ai_addr),
sizeof(server_address));
server_address.sin_port = htons(port);
freeaddrinfo(result); // Free data allocated by getaddrinfo.
status = connect(
s,
reinterpret_cast<struct sockaddr*>(&server_address),
sizeof(server_address));
if (status == SOCKET_ERROR) {
DWORD rc = WSAGetLastError();
closesocket(s);
SetLastError(rc);
return -1;
}
ClientSocket* client_socket = new ClientSocket(s);
return reinterpret_cast<intptr_t>(client_socket);
}
void Socket::GetError(intptr_t fd, OSError* os_error) {
Handle* handle = reinterpret_cast<Handle*>(fd);
os_error->SetCodeAndMessage(OSError::kSystem, handle->last_error());
}
intptr_t Socket::GetStdioHandle(int num) {
HANDLE handle;
switch (num) {
case 0:
handle = GetStdHandle(STD_INPUT_HANDLE);
break;
case 1:
handle = GetStdHandle(STD_OUTPUT_HANDLE);
break;
case 2:
handle = GetStdHandle(STD_ERROR_HANDLE);
break;
default: UNREACHABLE();
}
if (handle == INVALID_HANDLE_VALUE) {
return -1;
}
FileHandle* file_handle = new FileHandle(handle);
if (file_handle == NULL) return -1;
file_handle->MarkDoesNotSupportOverlappedIO();
return reinterpret_cast<intptr_t>(file_handle);
}
intptr_t ServerSocket::Accept(intptr_t fd) {
ListenSocket* listen_socket = reinterpret_cast<ListenSocket*>(fd);
ClientSocket* client_socket = listen_socket->Accept();
if (client_socket != NULL) {
return reinterpret_cast<intptr_t>(client_socket);
} else {
return -1;
}
}
const char* Socket::LookupIPv4Address(char* host, OSError** os_error) {
// Perform a name lookup for an IPv4 address.
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
struct addrinfo* info = NULL;
int status = getaddrinfo(host, 0, &hints, &info);
if (status != 0) {
ASSERT(*os_error == NULL);
*os_error = new OSError(status,
gai_strerror(status),
OSError::kGetAddressInfo);
return NULL;
}
// Convert the address into IPv4 dotted decimal notation.
char* buffer = reinterpret_cast<char*>(malloc(INET_ADDRSTRLEN));
sockaddr_in *sockaddr = reinterpret_cast<sockaddr_in *>(info->ai_addr);
const char* result = inet_ntop(AF_INET,
reinterpret_cast<void *>(&sockaddr->sin_addr),
buffer,
INET_ADDRSTRLEN);
if (result == NULL) {
free(buffer);
return NULL;
}
ASSERT(result == buffer);
return buffer;
}
intptr_t ServerSocket::CreateBindListen(const char* host,
intptr_t port,
intptr_t backlog) {
SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s == INVALID_SOCKET) {
return -1;
}
BOOL optval = true;
int status = setsockopt(s,
SOL_SOCKET,
SO_REUSEADDR,
reinterpret_cast<const char*>(&optval),
sizeof(optval));
if (status == SOCKET_ERROR) {
DWORD rc = WSAGetLastError();
closesocket(s);
SetLastError(rc);
return -1;
}
sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(host);
addr.sin_port = htons(port);
status = bind(s,
reinterpret_cast<struct sockaddr *>(&addr),
sizeof(addr));
if (status == SOCKET_ERROR) {
DWORD rc = WSAGetLastError();
closesocket(s);
SetLastError(rc);
return -1;
}
status = listen(s, backlog);
if (status == SOCKET_ERROR) {
DWORD rc = WSAGetLastError();
closesocket(s);
SetLastError(rc);
return -1;
}
ListenSocket* listen_socket = new ListenSocket(s);
return reinterpret_cast<intptr_t>(listen_socket);
}
<commit_msg>Speculative fix for the windows compilation failure. Review URL: https://chromiumcodereview.appspot.com//10032030<commit_after>// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include <winsock2.h>
#include <ws2tcpip.h>
#include <mswsock.h>
#include "bin/builtin.h"
#include "bin/eventhandler.h"
#include "bin/socket.h"
bool Socket::Initialize() {
int err;
WSADATA winsock_data;
WORD version_requested = MAKEWORD(1, 0);
err = WSAStartup(version_requested, &winsock_data);
if (err != 0) {
fprintf(stderr, "Unable to initialize Winsock: %d\n", WSAGetLastError());
}
return err == 0;
}
intptr_t Socket::Available(intptr_t fd) {
ClientSocket* client_socket = reinterpret_cast<ClientSocket*>(fd);
return client_socket->Available();
}
intptr_t Socket::Read(intptr_t fd, void* buffer, intptr_t num_bytes) {
Handle* handle = reinterpret_cast<Handle*>(fd);
return handle->Read(buffer, num_bytes);
}
intptr_t Socket::Write(intptr_t fd, const void* buffer, intptr_t num_bytes) {
Handle* handle = reinterpret_cast<Handle*>(fd);
return handle->Write(buffer, num_bytes);
}
intptr_t Socket::GetPort(intptr_t fd) {
ASSERT(reinterpret_cast<Handle*>(fd)->is_socket());
SocketHandle* socket_handle = reinterpret_cast<SocketHandle*>(fd);
struct sockaddr_in socket_address;
socklen_t size = sizeof(socket_address);
if (getsockname(socket_handle->socket(),
reinterpret_cast<struct sockaddr *>(&socket_address),
&size)) {
fprintf(stderr, "Error getsockname: %s\n", strerror(errno));
return 0;
}
return ntohs(socket_address.sin_port);
}
bool Socket::GetRemotePeer(intptr_t fd, char *host, intptr_t *port) {
ASSERT(DART_INET_ADDRSTRLEN >= INET_ADDRSTRLEN);
ASSERT(reinterpret_cast<Handle*>(fd)->is_socket());
SocketHandle* socket_handle = reinterpret_cast<SocketHandle*>(fd);
struct sockaddr_in socket_address;
socklen_t size = sizeof(socket_address);
if (getpeername(socket_handle->socket(),
reinterpret_cast<struct sockaddr *>(&socket_address),
&size)) {
fprintf(stderr, "Error getpeername: %s\n", strerror(errno));
return false;
}
if (inet_ntop(socket_address.sin_family,
reinterpret_cast<void *>(&socket_address.sin_addr),
host,
INET_ADDRSTRLEN) == NULL) {
fprintf(stderr, "Error inet_ntop: %s\n", strerror(errno));
return false;
}
*port = ntohs(socket_address.sin_port);
return true;
}
intptr_t Socket::CreateConnect(const char* host, const intptr_t port) {
SOCKET s = socket(AF_INET, SOCK_STREAM, 0);
if (s == INVALID_SOCKET) {
return -1;
}
linger l;
l.l_onoff = 1;
l.l_linger = 10;
int status = setsockopt(s,
SOL_SOCKET,
SO_LINGER,
reinterpret_cast<char*>(&l),
sizeof(l));
if (status != NO_ERROR) {
FATAL("Failed setting SO_LINGER on socket");
}
// Perform a name lookup for an IPv4 address.
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
struct addrinfo* result = NULL;
status = getaddrinfo(host, 0, &hints, &result);
if (status != NO_ERROR) {
return -1;
}
// Copy IPv4 address and set the port.
struct sockaddr_in server_address;
memcpy(&server_address,
reinterpret_cast<sockaddr_in *>(result->ai_addr),
sizeof(server_address));
server_address.sin_port = htons(port);
freeaddrinfo(result); // Free data allocated by getaddrinfo.
status = connect(
s,
reinterpret_cast<struct sockaddr*>(&server_address),
sizeof(server_address));
if (status == SOCKET_ERROR) {
DWORD rc = WSAGetLastError();
closesocket(s);
SetLastError(rc);
return -1;
}
ClientSocket* client_socket = new ClientSocket(s);
return reinterpret_cast<intptr_t>(client_socket);
}
void Socket::GetError(intptr_t fd, OSError* os_error) {
Handle* handle = reinterpret_cast<Handle*>(fd);
os_error->SetCodeAndMessage(OSError::kSystem, handle->last_error());
}
intptr_t Socket::GetStdioHandle(int num) {
HANDLE handle;
switch (num) {
case 0:
handle = GetStdHandle(STD_INPUT_HANDLE);
break;
case 1:
handle = GetStdHandle(STD_OUTPUT_HANDLE);
break;
case 2:
handle = GetStdHandle(STD_ERROR_HANDLE);
break;
default: UNREACHABLE();
}
if (handle == INVALID_HANDLE_VALUE) {
return -1;
}
FileHandle* file_handle = new FileHandle(handle);
if (file_handle == NULL) return -1;
file_handle->MarkDoesNotSupportOverlappedIO();
return reinterpret_cast<intptr_t>(file_handle);
}
intptr_t ServerSocket::Accept(intptr_t fd) {
ListenSocket* listen_socket = reinterpret_cast<ListenSocket*>(fd);
ClientSocket* client_socket = listen_socket->Accept();
if (client_socket != NULL) {
return reinterpret_cast<intptr_t>(client_socket);
} else {
return -1;
}
}
const char* Socket::LookupIPv4Address(char* host, OSError** os_error) {
// Perform a name lookup for an IPv4 address.
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
struct addrinfo* info = NULL;
int status = getaddrinfo(host, 0, &hints, &info);
if (status != 0) {
ASSERT(*os_error == NULL);
*os_error = new OSError(status,
gai_strerror(status),
OSError::kGetAddressInfo);
return NULL;
}
// Convert the address into IPv4 dotted decimal notation.
char* buffer = reinterpret_cast<char*>(malloc(INET_ADDRSTRLEN));
sockaddr_in *sockaddr = reinterpret_cast<sockaddr_in *>(info->ai_addr);
const char* result = inet_ntop(AF_INET,
reinterpret_cast<void *>(&sockaddr->sin_addr),
buffer,
INET_ADDRSTRLEN);
if (result == NULL) {
free(buffer);
return NULL;
}
ASSERT(result == buffer);
return buffer;
}
intptr_t ServerSocket::CreateBindListen(const char* host,
intptr_t port,
intptr_t backlog) {
SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s == INVALID_SOCKET) {
return -1;
}
BOOL optval = true;
int status = setsockopt(s,
SOL_SOCKET,
SO_REUSEADDR,
reinterpret_cast<const char*>(&optval),
sizeof(optval));
if (status == SOCKET_ERROR) {
DWORD rc = WSAGetLastError();
closesocket(s);
SetLastError(rc);
return -1;
}
sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(host);
addr.sin_port = htons(port);
status = bind(s,
reinterpret_cast<struct sockaddr *>(&addr),
sizeof(addr));
if (status == SOCKET_ERROR) {
DWORD rc = WSAGetLastError();
closesocket(s);
SetLastError(rc);
return -1;
}
status = listen(s, backlog);
if (status == SOCKET_ERROR) {
DWORD rc = WSAGetLastError();
closesocket(s);
SetLastError(rc);
return -1;
}
ListenSocket* listen_socket = new ListenSocket(s);
return reinterpret_cast<intptr_t>(listen_socket);
}
<|endoftext|>
|
<commit_before>#include <light.hpp>
Light::Light() :
light_position_{ glm::vec3{0.0,0.0,0.0} },
intensity_{ Color{0.0,0.0,0.0} } {}
Light::Light(glm::vec3 pos) :
light_position_{ pos },
intensity_{ Color{0.0,0.0,0.0} } {}
Light::Light(Color intensity) :
light_position_{ glm::vec3{0.0,0.0,0.0} },
intensity_{ intensity } {}
Light::Light(glm::vec3 pos, Color intensity) :
light_position_{ pos },
intensity_{ intensity } {}
Light::~Light(){}
<commit_msg>added getter<commit_after>#include <light.hpp>
Light::Light() :
light_position_{ glm::vec3{0.0,0.0,0.0} },
intensity_{ Color{0.0,0.0,0.0} } {}
Light::Light(glm::vec3 pos) :
light_position_{ pos },
intensity_{ Color{0.0,0.0,0.0} } {}
Light::Light(Color intensity) :
light_position_{ glm::vec3{0.0,0.0,0.0} },
intensity_{ intensity } {}
Light::Light(glm::vec3 pos, Color intensity) :
light_position_{ pos },
intensity_{ intensity } {}
Light::~Light(){}
glm::vec3 Light::get_position() const {
return light_position_;
}
Color Light::get_intensity() const {
return intensity_;
}
<|endoftext|>
|
<commit_before>//
// CameraRenderer.cpp
// G3MiOSSDK
//
// Created by Agustín Trujillo Pino on 30/07/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#include <iostream>
#include "CameraRenderer.h"
#include "IGL.hpp"
//const Planet* CameraRenderer::_planet;
//const ILogger* CameraRenderer::_logger;
//IGL* CameraRenderer::gl;
//Camera CameraRenderer::_camera0(NULL, 0, 0);
//Camera* CameraRenderer::_camera = NULL;
Gesture CameraRenderer::_currentGesture = None;
<commit_msg>removed static reference to Camera in CameraRenderer<commit_after>//
// CameraRenderer.cpp
// G3MiOSSDK
//
// Created by Agustín Trujillo Pino on 30/07/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#include <iostream>
#include "CameraRenderer.h"
#include "IGL.hpp"
Gesture CameraRenderer::_currentGesture = None;
<|endoftext|>
|
<commit_before>/*----------------------------------------------------------------------------------*\
| |
| rcb_generator.hpp |
| |
| Copyright (c) 2016 Richard Cookman |
| |
| 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. |
| |
\*----------------------------------------------------------------------------------*/
#pragma once
namespace rcbg {
template<typename U>
inline bool get_bit(U val, unsigned pos) {
return val & ((U)1 << pos);
}
template<typename U>
inline U set_bit(U val, unsigned pos, bool to) {
return (val & ~((U)1 << pos)) | ((U)to << pos);
}
//the random cycle bit generator - random number generator
template<typename T,
unsigned int bit_pos_left = ((sizeof(T) * 8) / 3) + 1,
unsigned int bit_pos_start = bit_pos_left * 2>
class rcb_generator {
private:
T val;
T last;
T cnt = 1;
//only first two flags used (1 << 1) is "left" (1 << 0) is start
char flags = 0;
inline static T shift_transform(T val, int i, bool& start_bit) {
val ^= (T)start_bit << i;
start_bit ^= get_bit(val, i);
return val;
}
static T generate(T val, bool left, bool start_bit) {
if(left)
for(int i = 0; i < (int)(sizeof(T) * 8); ++i)
val = shift_transform(val, i, start_bit);
else
for(int i = (sizeof(T) * 8) - 1; i > -1; --i)
val = shift_transform(val, i, start_bit);
return val;
}
T generate(T inval) {
//set the flags left and start bit
bool left = (get_bit(val, bit_pos_left) ^ get_bit(flags, 1) ^ true);
bool start_bit = (get_bit(val, bit_pos_start) ^ get_bit(flags, 0) ^ true);
flags = set_bit(flags, 1, left);
flags = set_bit(flags, 0, start_bit);
return last = generate(inval, left, start_bit) ^ inval ^ ~last;
}
public:
rcb_generator(T rnd) : val(rnd + 10), last(~(rnd - 10)) {}
inline T rand() {
T tmp_cnt = cnt++;
if(cnt == 0) ++cnt;
return val = (((val = generate(val)) << 1) * (generate(tmp_cnt) << 1)) ^ generate(val);
}
};
}
<commit_msg>optional automatic reseed, scalable internal count variable, C++ version only<commit_after>/*----------------------------------------------------------------------------------*\
| |
| rcb_generator.hpp |
| |
| Copyright (c) 2016 Richard Cookman |
| |
| 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. |
| |
\*----------------------------------------------------------------------------------*/
#pragma once
namespace rcbg {
template<typename U>
inline bool get_bit(U val, unsigned pos) {
return val & ((U)1 << pos);
}
template<typename U>
inline U set_bit(U val, unsigned pos, bool to) {
return (val & ~((U)1 << pos)) | ((U)to << pos);
}
template<unsigned int N>
struct rcb_generator_count {
private:
uint8_t dat[N];
public:
rcb_generator_count() {
//init to zero
for(unsigned i = 0; i < N; ++i)
dat[i] = 0;
}
bool increment() {
//increment this
for(unsigned i = 0; i < N; ++i) {
if(dat[i] == std::numeric_limits<uint8_t>::max())
dat[i] = 0;
else {
++dat[i];
return true;
}
}
return false;
}
bool good() const {
//have we gone around the whole set of numbers
for(unsigned i = 0; i < N; ++i)
if(dat[i] != std::numeric_limits<uint8_t>::max())
return true;
return false;
}
template<typename T>
operator T() const {
//get the value of this
T rtn = 0;
unsigned j = 0;
for(unsigned i = 0; i < N; ++i) {
rtn ^= ((T)dat[i]) << (8 * j);
++j;
if(j == sizeof(T))
j = 0;
}
return rtn;
}
};
//the random cycle bit generator - random number generator
template<typename T,
unsigned int CntN = sizeof(T),
unsigned int bit_pos_left = ((sizeof(T) * 8) / 3) + 1,
unsigned int bit_pos_start = bit_pos_left * 2>
class rcb_generator {
private:
T val;
T last;
rcb_generator_count<CntN> cnt;
//only first two flags used (1 << 1) is "left" (1 << 0) is start
char flags;
inline static T shift_transform(T val, int i, bool& start_bit) {
val ^= (T)start_bit << i;
start_bit ^= get_bit(val, i);
return val;
}
static T generate(T val, bool left, bool start_bit) {
if(left)
for(int i = 0; i < (int)(sizeof(T) * 8); ++i)
val = shift_transform(val, i, start_bit);
else
for(int i = (sizeof(T) * 8) - 1; i > -1; --i)
val = shift_transform(val, i, start_bit);
return val;
}
T generate(T inval) {
//set the flags left and start bit
bool left = (get_bit(val, bit_pos_left) ^ get_bit(flags, 1) ^ true);
bool start_bit = (get_bit(val, bit_pos_start) ^ get_bit(flags, 0) ^ true);
flags = set_bit(flags, 1, left);
flags = set_bit(flags, 0, start_bit);
return last = generate(inval, left, start_bit) ^ inval ^ ~last;
}
T generate_outer(T tmp_cnt) {
return val = (((val = generate(val)) << 1) * (generate(tmp_cnt) << 1)) ^ generate(val);
}
void seed(T rnd, T offset, bool reseed) {
flags = 0;
val = rnd + offset;
last = ~(rnd - offset);
set_bit(flags, 2, reseed);
}
public:
rcb_generator(T rnd, bool reseed = false) {
seed(rnd, 10, reseed);
}
T rand() {
bool gd = cnt.increment();
T tmp_cnt = cnt;
if(tmp_cnt == 0) ++tmp_cnt;
T rtn = generate_outer(tmp_cnt);
if(!gd && reseeds())
seed(generate_outer(++tmp_cnt), generate_outer(++tmp_cnt) / 2, true);
return rtn;
}
bool good() {
return cnt.good();
}
bool reseeds() const {
return get_bit(flags, 2);
}
};
}
<|endoftext|>
|
<commit_before>//=====================================================================//
/*! @file
@brief RX24T LCD サンプル @n
・(インジケーター)P00(4) ピンに赤色LED(VF:1.9V)を吸い込みで接続する
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2017 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/cmt_io.hpp"
#include "common/sci_io.hpp"
#include "common/fixed_fifo.hpp"
#include "common/format.hpp"
#include "common/rspi_io.hpp"
// LCD を選択する
// #define LCD_ST7565
// #define LCD_UC1701
#define LCD_R61505
#if defined(LCD_ST7565)
#include "chip/ST7565.hpp"
#include "graphics/monograph.hpp"
#define LCD_SPI
#define LCD_MONO
#elif defined(LCD_UC1701)
#include "chip/UC1701.hpp"
#include "graphics/monograph.hpp"
#define LCD_SPI
#define LCD_MONO
#elif defined(LCD_R61505)
#include "chip/R61505.hpp"
#include "chip/bus_rw.hpp"
#include "../RAYTRACER_sample/raytracer.hpp"
#define LCD_BUS
#endif
namespace {
// 外部 10MHz クリスタル
typedef device::system_io<10000000> SYSTEM_IO;
// LED インジケーター
typedef device::PORT<device::PORT0, device::bitpos::B0> LED;
typedef device::cmt_io<device::CMT0> CMT;
CMT cmt_;
typedef utils::fixed_fifo<char, 128> buffer;
device::sci_io<device::SCI1, buffer, buffer> sci_;
#if defined(LCD_SPI)
typedef device::PORT<device::PORT6, device::bitpos::B1> LCD_SEL; ///< LCD 選択信号
typedef device::PORT<device::PORT6, device::bitpos::B2> LCD_A0; ///< LCD レジスター選択
// SPI 定義(RSPI0)
typedef device::rspi_io<device::RSPI0> SPI;
SPI spi_;
#endif
#if defined(LCD_ST7565)
static const char* LCD_NAME = { "ST7565" };
chip::ST7565<SPI, LCD_SEL, LCD_A0> lcd_(spi_);
#elif defined(LCD_UC1701)
static const char* LCD_NAME = { "UC1701" };
chip::UC1701<SPI, LCD_SEL, LCD_A0> lcd_(spi_);
#elif defined(LCD_R61505)
static const char* LCD_NAME = { "R61505" };
typedef device::PORT<device::PORT5, device::bitpos::B2> RS;
typedef device::PORT<device::PORT5, device::bitpos::B4> RD;
typedef device::PORT<device::PORT5, device::bitpos::B3> WR;
typedef device::PORT<device::PORT5, device::bitpos::B1> CS;
typedef device::PORT_BYTE<device::PORT4> DATA;
typedef device::bus_rw8<CS, RS, RD, WR, DATA> BUS;
BUS bus_;
typedef device::PORT<device::PORT5, device::bitpos::B0> RES;
typedef chip::R61505<BUS, RES> LCD;
LCD lcd_;
#endif
#if defined(LCD_MONO)
// モノクロ・グラフィックス
graphics::kfont_null kfont_;
graphics::monograph<128, 64> bitmap_(kfont_);
uint8_t v_ = 91;
uint8_t m_ = 123;
uint8_t rand_()
{
v_ += v_ << 2;
++v_;
uint8_t n = 0;
if(m_ & 0x02) n = 1;
if(m_ & 0x40) n ^= 1;
m_ += m_;
if(n == 0) ++m_;
return v_ ^ m_;
}
#endif
}
extern "C" {
#if defined(LCD_R61505)
void draw_pixel(int x, int y, int r, int g, int b)
{
volatile uint16_t c = (static_cast<uint16_t>(r & 0xf8) << 8)
| (static_cast<uint16_t>(g & 0xfc) << 3)
| (static_cast<uint16_t>(b) >> 3);
lcd_.plot(x, y, c);
}
void draw_text(int x, int y, const char* t)
{
// render_.fill_box(x, y, strlen(t) * 8, 16, render_.get_back_color());
// render_.draw_text(x, y, t);
}
uint32_t millis(void)
{
return cmt_.get_counter() * 10;
}
#endif
void sci_putch(char ch)
{
sci_.putch(ch);
}
char sci_getch()
{
return sci_.getch();
}
}
int main(int argc, char** argv);
int main(int argc, char** argv)
{
SYSTEM_IO::setup_system_clock();
// タイマー設定(100Hz)
{
uint8_t cmt_irq_level = 4;
cmt_.start(100, cmt_irq_level);
}
// SCI 設定
{
uint8_t sci_level = 2;
sci_.start(115200, sci_level);
}
utils::format("RX24T LCD %s sample\n") % LCD_NAME;
#ifdef LCD_SPI
// RSPI 開始
{
uint32_t clk = 8000000;
if(!spi_.start(clk, SPI::PHASE::TYPE4, SPI::DLEN::W8)) {
utils::format("RSPI speed fail...\n");
}
}
#endif
#ifdef LCD_MONO
// LCD 開始
{
lcd_.start(0x00);
bitmap_.clear(0);
uint16_t x = rand_() & 127;
uint16_t y = rand_() & 63;
uint16_t xx;
uint16_t yy;
uint8_t nn = 0;
uint8_t loop = 0;
}
#endif
#if defined(LCD_R61505)
// TFT/BUS 開始
{
if(!lcd_.start()) {
utils::format("R61505 not start\n");
} else {
lcd_.fill_box(0, 0, 320, 240, 0x0000);
doRaytrace(1, 320, 240);
}
}
#endif
LED::DIR = 1;
uint32_t cnt = 0;
while(1) {
cmt_.sync();
#ifdef LCD_MONO
if(nn >= 4) {
lcd_.copy(bitmap_.fb(), bitmap_.page_num());
nn = 0;
}
++nn;
if(loop >= 20) {
loop = 0;
bitmap_.clear(0);
bitmap_.frame(0, 0, 128, 64, 1);
}
xx = rand_() & 127;
yy = rand_() & 63;
bitmap_.line(x, y, xx, yy, 1);
x = xx;
y = yy;
++loop;
#endif
if(sci_.recv_length()) {
auto ch = sci_.getch();
sci_.putch(ch);
}
++cnt;
if(cnt >= 30) {
cnt = 0;
}
LED::P = (cnt < 10) ? 0 : 1;
}
}
<commit_msg>update: R61505 manage<commit_after>//=====================================================================//
/*! @file
@brief RX24T LCD サンプル @n
・(インジケーター)P00(4) ピンに赤色LED(VF:1.9V)を吸い込みで接続する
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2017 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/cmt_io.hpp"
#include "common/sci_io.hpp"
#include "common/fixed_fifo.hpp"
#include "common/format.hpp"
#include "common/rspi_io.hpp"
// LCD を選択する
// #define LCD_ST7565
// #define LCD_UC1701
#define LCD_R61505
#if defined(LCD_ST7565)
#include "chip/ST7565.hpp"
#include "graphics/monograph.hpp"
#define LCD_SPI
#define LCD_MONO
#elif defined(LCD_UC1701)
#include "chip/UC1701.hpp"
#include "graphics/monograph.hpp"
#define LCD_SPI
#define LCD_MONO
#elif defined(LCD_R61505)
#include "chip/R61505.hpp"
#include "chip/bus_rw.hpp"
#include "../RAYTRACER_sample/raytracer.hpp"
#define LCD_BUS
#endif
namespace {
// 外部 10MHz クリスタル
typedef device::system_io<10000000> SYSTEM_IO;
// LED インジケーター
typedef device::PORT<device::PORT0, device::bitpos::B0> LED;
typedef device::cmt_io<device::CMT0> CMT;
CMT cmt_;
typedef utils::fixed_fifo<char, 128> buffer;
device::sci_io<device::SCI1, buffer, buffer> sci_;
#if defined(LCD_SPI)
typedef device::PORT<device::PORT6, device::bitpos::B1> LCD_SEL; ///< LCD 選択信号
typedef device::PORT<device::PORT6, device::bitpos::B2> LCD_A0; ///< LCD レジスター選択
// SPI 定義(RSPI0)
typedef device::rspi_io<device::RSPI0> SPI;
SPI spi_;
#endif
#if defined(LCD_ST7565)
static const char* LCD_NAME = { "ST7565" };
chip::ST7565<SPI, LCD_SEL, LCD_A0> lcd_(spi_);
#elif defined(LCD_UC1701)
static const char* LCD_NAME = { "UC1701" };
chip::UC1701<SPI, LCD_SEL, LCD_A0> lcd_(spi_);
#elif defined(LCD_R61505)
static const char* LCD_NAME = { "R61505" };
// LCD connection connector
// DB0, DB1, DB2, DB3, GND, DB4, DB5, DB6, DB7
// RST, /CS, RS , /WR, /RD, GND, GND, 3.3, 3.3
typedef device::PORT<device::PORT5, device::bitpos::B2> RS;
typedef device::PORT<device::PORT5, device::bitpos::B4> RD;
typedef device::PORT<device::PORT5, device::bitpos::B3> WR;
typedef device::PORT<device::PORT5, device::bitpos::B1> CS;
typedef device::PORT_BYTE<device::PORT4> DATA;
typedef device::bus_rw8<CS, RS, RD, WR, DATA> BUS;
BUS bus_;
typedef device::PORT<device::PORT5, device::bitpos::B0> RES;
typedef chip::R61505<BUS, RES> LCD;
LCD lcd_;
#endif
#if defined(LCD_MONO)
// モノクロ・グラフィックス
graphics::kfont_null kfont_;
graphics::monograph<128, 64> bitmap_(kfont_);
uint8_t v_ = 91;
uint8_t m_ = 123;
uint8_t rand_()
{
v_ += v_ << 2;
++v_;
uint8_t n = 0;
if(m_ & 0x02) n = 1;
if(m_ & 0x40) n ^= 1;
m_ += m_;
if(n == 0) ++m_;
return v_ ^ m_;
}
#endif
}
extern "C" {
#if defined(LCD_R61505)
void draw_pixel(int x, int y, int r, int g, int b)
{
volatile uint16_t c = (static_cast<uint16_t>(r & 0xf8) << 8)
| (static_cast<uint16_t>(g & 0xfc) << 3)
| (static_cast<uint16_t>(b) >> 3);
lcd_.plot(x, y, c);
}
void draw_text(int x, int y, const char* t)
{
// render_.fill_box(x, y, strlen(t) * 8, 16, render_.get_back_color());
// render_.draw_text(x, y, t);
}
uint32_t millis(void)
{
return cmt_.get_counter() * 10;
}
#endif
void sci_putch(char ch)
{
sci_.putch(ch);
}
char sci_getch()
{
return sci_.getch();
}
}
int main(int argc, char** argv);
int main(int argc, char** argv)
{
SYSTEM_IO::setup_system_clock();
// タイマー設定(100Hz)
{
uint8_t cmt_irq_level = 4;
cmt_.start(100, cmt_irq_level);
}
// SCI 設定
{
uint8_t sci_level = 2;
sci_.start(115200, sci_level);
}
utils::format("RX24T LCD %s sample\n") % LCD_NAME;
#ifdef LCD_SPI
// RSPI 開始
{
uint32_t clk = 8000000;
if(!spi_.start(clk, SPI::PHASE::TYPE4, SPI::DLEN::W8)) {
utils::format("RSPI speed fail...\n");
}
}
#endif
#ifdef LCD_MONO
// LCD 開始
{
lcd_.start(0x00);
bitmap_.clear(0);
uint16_t x = rand_() & 127;
uint16_t y = rand_() & 63;
uint16_t xx;
uint16_t yy;
uint8_t nn = 0;
uint8_t loop = 0;
}
#endif
#if defined(LCD_R61505)
// TFT/BUS 開始
{
if(!lcd_.start()) {
utils::format("R61505 not start\n");
} else {
lcd_.fill_box(0, 0, 320, 240, 0x0000);
doRaytrace(1, 320, 240);
}
}
#endif
LED::DIR = 1;
uint32_t cnt = 0;
while(1) {
cmt_.sync();
#ifdef LCD_MONO
if(nn >= 4) {
lcd_.copy(bitmap_.fb(), bitmap_.page_num());
nn = 0;
}
++nn;
if(loop >= 20) {
loop = 0;
bitmap_.clear(0);
bitmap_.frame(0, 0, 128, 64, 1);
}
xx = rand_() & 127;
yy = rand_() & 63;
bitmap_.line(x, y, xx, yy, 1);
x = xx;
y = yy;
++loop;
#endif
if(sci_.recv_length()) {
auto ch = sci_.getch();
sci_.putch(ch);
}
++cnt;
if(cnt >= 30) {
cnt = 0;
}
LED::P = (cnt < 10) ? 0 : 1;
}
}
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <math.h>
#include "bio++.H"
#include "meryl.H"
#include "merStream.H"
#include <unordered_map>
#include <vector>
#include <set>
using namespace std;
#define MAX_HASH 0xffffffffffffffff
int
main(int argc, char **argv) {
// parse args
merylArgs *args = new merylArgs(argc, argv);
// set up streams for reading kmers and sequences
seqStream *seqstr = new seqStream(args->inputFile);
args->numBasesActual = 0;
for (u32bit i=0; i<seqstr->numberOfSequences(); i++)
args->numBasesActual += seqstr->lengthOf(i);
merStream *M = new merStream(new kMerBuilder(args->merSize, args->merComp), seqstr, true, true);
args->numMersActual = M->approximateNumberOfMers() + 1;
if (args->memoryLimit) {
args->mersPerBatch = estimateNumMersInMemorySize(args->merSize, args->memoryLimit, args->positionsEnabled, args->beVerbose);
if (args->mersPerBatch > args->numMersActual)
args->mersPerBatch = args->numMersActual;
args->segmentLimit = (u64bit)ceil((double)args->numMersActual / (double)args->mersPerBatch);
if (args->beVerbose)
fprintf(stderr, "Have a memory limit: mersPerBatch="u64bitFMT" segmentLimit="u64bitFMT"\n", args->mersPerBatch, args->segmentLimit);
} else if (args->segmentLimit) {
args->mersPerBatch = (u64bit)ceil((double)args->numMersActual / (double)args->segmentLimit);
if (args->beVerbose)
fprintf(stderr, "Have a segment limit: mersPerBatch="u64bitFMT" segmentLimit="u64bitFMT"\n", args->mersPerBatch, args->segmentLimit);
} else {
args->mersPerBatch = args->numMersActual;
args->segmentLimit = 1;
if (args->beVerbose)
fprintf(stderr, "Have NO LIMITS!: mersPerBatch="u64bitFMT" segmentLimit="u64bitFMT"\n", args->mersPerBatch, args->segmentLimit);
}
// store an array of the minium hash value for each sequence. Corresponds to min for each hash table
unordered_map<u64bit, u64bit *> storedHash;
// store an array of minum values to sequences for each hash table
unordered_map<u64bit, vector<u64bit>* >* minToSequence = new unordered_map<u64bit, vector<u64bit> *>[args->numHashes + 1];
// store an array of positions of the minimum kmer values
unordered_map<u64bit, int >* minToPosition = new unordered_map<u64bit, int>[args->numHashes + 1];
args->basesPerBatch = (u64bit)ceil((double)args->numBasesActual / (double)args->segmentLimit);
args->bucketPointerWidth = logBaseTwo64(args->basesPerBatch + 1);
args->numBuckets_log2 = 16; //optimalNumberOfBuckets(args->merSize, args->basesPerBatch, args->positionsEnabled);
args->numBuckets = (u64bitONE << args->numBuckets_log2);
args->merDataWidth = args->merSize * 2 - args->numBuckets_log2;
args->salt_log2 = logBaseTwo64(args->numHashes * 10);
const kMer *currMer = 0L;
bool isFwd = true;
// the kmers of sequences, read once and reused for all hash tables
unordered_map<u64bit, vector<kMer> *> seqs;
// length of sequences loaded
unordered_map<u64bit, u32bit> seqLens;
// orientation of the kmers from sequences
unordered_map<u64bit, vector<bool> *> ori;
// read evey input kmer and store whether it was forward or reverse, the kmer, and the length of the sequence
while (M->nextMer()) {
if (M->theFMer() <= M->theRMer()) {
currMer = &(M->theFMer());
isFwd = true;
} else {
currMer = &(M->theRMer());
isFwd = false;
}
if (seqs.find(M->theSequenceNumber()) == seqs.end()) {
seqs.insert(pair<u64bit, vector<kMer>*>(M->theSequenceNumber(), new vector<kMer>()));
ori.insert(pair<u64bit, vector<bool>*>(M->theSequenceNumber(), new vector<bool>()));
}
seqs.find(M->theSequenceNumber())->second->push_back(*currMer);
seqLens.erase(M->theSequenceNumber());
seqLens.insert(pair<u64bit, u32bit>(M->theSequenceNumber(), M->thePositionInSequence()+args->merSize));
ori.find(M->theSequenceNumber())->second->push_back(isFwd);
}
for (u32bit i = 0; i < args->numHashes; i++) {
u32bit processed = 0;
args->salt = i * 10;
//fprintf(stderr, "Starting hash %d with min %llu\n", i, minHash);
for (u32bit s = 0; s < seqs.size(); s++) {
vector<kMer> *mers = seqs.find(s)->second;
vector<bool> *oris = ori.find(s)->second;
u64bit minHash = MAX_HASH-1;
int minPos = 0;
int currPos = 0;
u64bit lastSeq = s;
if (processed % 10000 == 0) { fprintf(stderr, "Done with %d sequences %d/%d hashes\n", processed, i+1, args->numHashes); }
processed++;
for (vector<kMer>::iterator mer = mers->begin(); mer != mers->end(); ++mer) {
u64bit key = args->hash(*mer);
if (key < minHash) {
minHash = key;
minPos = (oris->at(currPos) == true ? currPos : -1*currPos);
//fprintf(stderr, "For sequence %llu hash %llu stored min %llu at position %d\n", s, i, minHash, minPos);
}
currPos++;
}
//fprintf(stderr, "For sequence %llu hash %d min value is %llu\n", lastSeq, i, minHash);
if (storedHash.find(lastSeq) == storedHash.end()) {
storedHash.insert(pair<u64bit, u64bit *>(lastSeq, new u64bit[args->numHashes+1]));
}
storedHash.find(lastSeq)->second[i] = minHash;
if (minToSequence[i].find(minHash) == minToSequence[i].end()) {
minToSequence[i].insert(pair<u64bit, vector<u64bit> *>(minHash, new vector<u64bit>()));
}
minToSequence[i].find(minHash)->second->push_back(lastSeq);
minToPosition[i].insert(pair<u64bit, int>(lastSeq, minPos));
}
}
seqs.clear();
ori.clear();
// now that we have the hash constructed, go through all sequences to recompute their min and score their matches
for (unordered_map<u64bit, u64bit* >::iterator iter = storedHash.begin();
iter != storedHash.end();
++iter) {
unordered_map<u64bit, u64bit> counts;
int aLen = seqLens.find(iter->first)->second;
for (u32bit i = 0; i < args->numHashes; i++) {
//fprintf(stderr, "For sequence %llu hash %d min value stored is %llu\n", iter->first, i, iter->second[i]);
vector<u64bit>* sameMin = minToSequence[i].find(iter->second[i])->second;
for (vector<u64bit>::iterator mins = sameMin->begin(); mins != sameMin->end(); ++mins) {
if (counts.find(*mins) == counts.end()) { counts.insert(pair<u64bit, u64bit>(*mins, 0)); }
counts[*mins] = counts[*mins] + 1;
//fprintf(stderr, "Hash %d sequences %llu and %llu share minimum\n", i, iter->first, *mins);
}
}
for (unordered_map<u64bit, u64bit* >::iterator c = storedHash.begin();
c != storedHash.end() && c->first < iter->first;
++c) {
double score = 0;
int bLen = seqLens.find(c->first)->second;
if (counts.find(c->first) != counts.end()) {
score = (double)counts[c->first] / args->numHashes * 100;
// adjust for different lengths
int minLen = (aLen < bLen ? aLen : bLen);
int maxLen = (aLen > bLen ? aLen : bLen);
double ratio = (double)minLen/maxLen;
score /= ratio;
}
//fprintf(stderr, "For sequence %llu versus sequence %llu the count is %.2f\n", iter->first, c->first, score);
if (score >= args->threshold) {
// figure out intersecting regions
int aStart = 0;
int aEnd = 0;
int aFwd = 0;
int aRev = 0;
int bStart = 0;
int bEnd = 0;
int bFwd = 0;
int bRev = 0;
u64bit* aHashes = storedHash.find(iter->first)->second;
u64bit* bHashes = storedHash.find(c->first)->second;
set<u64bit> aPositions;
set<u64bit> bPositions;
for (u32bit i = 0; i < args->numHashes; i++) {
if (aHashes[i] != bHashes[i]) { continue; }
int aPos = minToPosition[i].find(iter->first)->second;
(aPos < 0 ? aRev++: aFwd++);
aPos = abs(aPos);
int bPos = minToPosition[i].find(c->first)->second;
(bPos < 0 ? bRev++ : bFwd++);
bPos = abs(bPos);
aPositions.insert(aPos);
bPositions.insert(bPos);
}
set<u64bit>::iterator bIter=bPositions.begin();
for (set<u64bit>::iterator aIter = aPositions.begin(); aIter != aPositions.end() && bIter != bPositions.end(); ++bIter, ++aIter) {
int aPos = *aIter;
int bPos = *bIter;
//fprintf(stderr, "Comparsing sequence %llu versus %llu. Position in first is %d second %d\n", iter->first, c->first, aPos, bPos);
if (aStart != 0 && aStart > aPos && aPos - aStart > args->maxSkip) { continue; }
if (aStart != 0 && aEnd < (aPos+args->merSize) && aPos+args->merSize - aEnd > args->maxSkip) { continue; }
if (bStart != 0 && bStart > bPos && bPos - bStart > args->maxSkip) { continue; }
if (bStart != 0 && bEnd < (bPos+args->merSize) && bPos+args->merSize - bEnd > args->maxSkip) { continue; }
if (aStart == 0 || aStart > aPos) aStart = aPos;
if (aEnd < aPos+args->merSize) aEnd = aPos+args->merSize;
if (bStart == 0 || bStart > bPos) bStart = bPos;
if (bEnd < bPos+args->merSize) bEnd = bPos+args->merSize;
}
bool aOri = (aFwd > aRev ? true : false);
bool bOri = (bFwd > bRev ? true : false);
fprintf(stderr, "For sequence %llu (%d-%d) %d versus sequence %llu (%d-%d) %d the count is %.2f\n", iter->first, (aOri ? aStart : aEnd), (aOri ? aEnd : aStart), aLen, c->first, (bOri ? bStart : bEnd), (bOri ? bEnd : bStart), bLen, score);
/*
seq_pair p;
u32bit cnt = 0;
p.alen = seqstr->lengthOf(iter->first);
p.a = new char[p.alen + 1];
seqstr->setRange(seqstr->startOf(iter->first), seqstr->startOf(iter->first)+p.alen);
while (!seqstr->eof()) {
p.a[cnt] = seqstr->get();
cnt++;
}
cnt = 0;
p.blen = seqstr->lengthOf(c->first);
p.b = new char[p.blen + 1];
seqstr->setRange(seqstr->startOf(c->first), seqstr->startOf(c->first)+p.blen);
while (!seqstr->eof()) {
p.b[cnt] = seqstr->get();
cnt++;
}
seq_pair_t result = smith_waterman(&p, true);
fprintf(stderr, "%s\n%s\n", result->a, result->b);
*/
}
}
}
delete M;
delete args;
return(0);
}
<commit_msg>Cleanup <commit_after><|endoftext|>
|
<commit_before>#include <iostream>
#include "SimpleHttpRequest.h"
using namespace std;
int main() {
int r;
uv_loop = uv_default_loop();
map<string, string> options;
map<string, string> headers;
options["hostname"] = "192.168.10.9";
options["port"] = "10509";
options["path"] = "/archive";
options["method"] = "GET";
headers["content-type"] = "application/json";
SimpleHttpRequest request(options, headers, uv_loop);
request.on("error", [](){
cerr << endl << "on error" << endl;
}).on("response", [&request](){
for (const auto &kv : request.responseHeaders)
cout << kv.first << " : " << kv.second << endl;
cout << request.responseBody.str().c_str();
}).end();
// options["method"] = "POST";
// headers["content-type"] = "application/json";
// SimpleHttpRequest request(options, headers, uv_loop);
// request.on("error", [](){
// cout << endl << "on error" << endl;
// });
// request.on("response", [](){
// cout << endl << "on response" << endl;
// });
// request.write("{\"archive\":3}");
// request.end();
return uv_run(uv_loop, UV_RUN_DEFAULT);
}
<commit_msg>more examples<commit_after>#include <iostream>
#include "SimpleHttpRequest.h"
using namespace std;
int main() {
int r;
uv_loop = uv_default_loop();
#if 1
// request.get(url)
SimpleHttpRequest request(uv_loop);
request.get("http://192.168.10.9:10509/archive")
.on("error", [](){
cerr << endl << "on error" << endl;
}).on("response", [&request](){
cout << request.responseBody.str();
}).end();
#endif
#if 0
// request(options) GET
map<string, string> options;
options["hostname"] = "192.168.10.9";
options["port"] = "10509";
options["path"] = "/archive";
options["method"] = "GET";
SimpleHttpRequest request(options, uv_loop);
request.setHeader("content-type","application/json")
.on("error", [](){
cerr << endl << "on error" << endl;
}).on("response", [&request](){
for (const auto &kv : request.responseHeaders)
cout << kv.first << " : " << kv.second << endl;
cout << request.responseBody.str().c_str();
}).end();
#endif
#if 0
// request.post(url, body) POST
string body = "{\"archive\":3}";
SimpleHttpRequest request(uv_loop);
request.setHeader("content-type","application/json")
.post("http://192.168.10.9:10509/archive", body)
.on("error", [](){
cout << endl << "on error" << endl;
})
.on("response", [&request](){
cout << endl << request.statusCode << endl;
cout << request.responseBody.str() << endl;
})
.end();
#endif
#if 0
// request(options, headers) POST
map<string, string> options;
map<string, string> headers;
options["hostname"] = "192.168.10.9";
options["port"] = "10509";
options["path"] = "/archive";
options["method"] = "POST";
headers["content-type"] = "application/json";
SimpleHttpRequest request(options, headers, uv_loop);
request.on("error", [](){
cout << endl << "on error" << endl;
});
request.on("response", [&request](){
cout << endl << request.statusCode << endl;
cout << request.responseBody.str() << endl;
});
request.write("{\"archive\":3}");
request.end();
#endif
return uv_run(uv_loop, UV_RUN_DEFAULT);
}
<|endoftext|>
|
<commit_before>#include <easyqrpng/easyqrpngpp.h>
#include <iostream>
int main(int argc, char* argv[])
{
easyqrpng p;
p.setTargetWidth(500);
if (p.encode("Encode me in a test"))
{
std::cout << "ENCODE ERROR: " << p.errorMessage() << std::endl;
return 0;
}
if (p.save("test.png"))
{
std::cout << "SAVE ERROR: " << p.errorMessage() << std::endl;
return 1;
}
std::cout << "OK" << std::endl;
return 0;
}<commit_msg>* Better error checking in sample<commit_after>#include <easyqrpng/easyqrpngpp.h>
#include <iostream>
int main(int argc, char* argv[])
{
easyqrpng p;
p.setTargetWidth(500);
if (p.encode("Encode me in a test")!=EASYQRPNGERR_OK)
{
std::cout << "ENCODE ERROR: " << p.errorMessage() << std::endl;
return 0;
}
if (p.save("test.png")!=EASYQRPNGERR_OK)
{
std::cout << "SAVE ERROR: " << p.errorMessage() << std::endl;
return 1;
}
std::cout << "OK" << std::endl;
return 0;
}<|endoftext|>
|
<commit_before>#include "catch.hpp"
#include "inputfile.hpp"
using namespace groho;
TEST_CASE("Missing input file parsing", "[InputFile]")
{
auto lines = load_input_file("non-existent.txt");
REQUIRE(!lines);
}
TEST_CASE("Input file parsing", "[InputFile]")
{
auto lines = load_input_file("../examples/001.basics/scn.groho.txt");
REQUIRE((*lines).size() == 17);
REQUIRE((*lines)[0].key == "start");
REQUIRE((*lines)[7].key == "2050.01.01:0.5");
REQUIRE((*lines)[8].key == "plan");
REQUIRE((*lines)[10].key == "2050.01.02:0.5");
REQUIRE((*lines)[11].key == "2050.01.03:0.5");
REQUIRE((*lines)[12].key == "2050.01.04:0.5");
REQUIRE((*lines)[14].status.code == ParseStatus::ERROR);
}
TEST_CASE("String split on white space", "[StringSplit]")
{
auto split = split_string(" The quick brown fox ");
REQUIRE(split.at(0) == "The");
REQUIRE(split.at(3) == "fox");
REQUIRE(split.size() == 4);
}
TEST_CASE("String split on comma", "[StringSplit]")
{
auto split = split_string(
"Mercury BC, 2.2031780000000021E+04, 0", ",");
REQUIRE(split.at(0) == "Mercury BC");
REQUIRE(split.at(1) == "2.2031780000000021E+04");
REQUIRE(split.at(2) == "0");
}
<commit_msg>Update tests to match changed scenario file<commit_after>#include "catch.hpp"
#include "inputfile.hpp"
using namespace groho;
TEST_CASE("Missing input file parsing", "[InputFile]")
{
auto lines = load_input_file("non-existent.txt");
REQUIRE(!lines);
}
TEST_CASE("Input file parsing", "[InputFile]")
{
auto lines = load_input_file("../examples/001.basics/scn.groho.txt");
REQUIRE((*lines).size() == 18);
REQUIRE((*lines)[0].key == "start");
REQUIRE((*lines)[7].key == "2050.01.01:0.5");
REQUIRE((*lines)[9].key == "plan");
REQUIRE((*lines)[12].key == "2050.01.03:0.5");
REQUIRE((*lines)[15].status.code == ParseStatus::ERROR);
}
TEST_CASE("String split on white space", "[StringSplit]")
{
auto split = split_string(" The quick brown fox ");
REQUIRE(split.at(0) == "The");
REQUIRE(split.at(3) == "fox");
REQUIRE(split.size() == 4);
}
TEST_CASE("String split on comma", "[StringSplit]")
{
auto split = split_string(
"Mercury BC, 2.2031780000000021E+04, 0", ",");
REQUIRE(split.at(0) == "Mercury BC");
REQUIRE(split.at(1) == "2.2031780000000021E+04");
REQUIRE(split.at(2) == "0");
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: namedvaluecollection.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-09-17 17:12:43 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_comphelper.hxx"
#ifndef COMPHELPER_NAMEDVALUECOLLECTION_HXX
#include <comphelper/namedvaluecollection.hxx>
#endif
/** === begin UNO includes === **/
#ifndef _COM_SUN_STAR_BEANS_NAMEDVALUE_HPP_
#include <com/sun/star/beans/NamedValue.hpp>
#endif
/** === end UNO includes === **/
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#include <hash_map>
//........................................................................
namespace comphelper
{
//........................................................................
/** === begin UNO using === **/
using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::beans::PropertyValue;
using ::com::sun::star::beans::NamedValue;
using ::com::sun::star::uno::Type;
using ::com::sun::star::uno::cpp_acquire;
using ::com::sun::star::uno::cpp_release;
using ::com::sun::star::uno::cpp_queryInterface;
/** === end UNO using === **/
//====================================================================
//= NamedValueCollection_Impl
//====================================================================
typedef ::std::hash_map< ::rtl::OUString, Any, ::rtl::OUStringHash > NamedValueRepository;
struct NamedValueCollection_Impl
{
NamedValueRepository aValues;
};
//====================================================================
//= NamedValueCollection
//====================================================================
//--------------------------------------------------------------------
NamedValueCollection::NamedValueCollection()
:m_pImpl( new NamedValueCollection_Impl )
{
}
//--------------------------------------------------------------------
NamedValueCollection::NamedValueCollection( const Sequence< Any >& _rArguments )
:m_pImpl( new NamedValueCollection_Impl )
{
impl_assign( _rArguments );
}
//--------------------------------------------------------------------
NamedValueCollection::NamedValueCollection( const Sequence< PropertyValue >& _rArguments )
:m_pImpl( new NamedValueCollection_Impl )
{
impl_assign( _rArguments );
}
//--------------------------------------------------------------------
NamedValueCollection::~NamedValueCollection()
{
}
//--------------------------------------------------------------------
void NamedValueCollection::impl_assign( const Sequence< Any >& _rArguments )
{
{
NamedValueRepository empty;
m_pImpl->aValues.swap( empty );
}
PropertyValue aPropertyValue;
NamedValue aNamedValue;
const Any* pArgument = _rArguments.getConstArray();
const Any* pArgumentEnd = _rArguments.getConstArray() + _rArguments.getLength();
for ( ; pArgument != pArgumentEnd; ++pArgument )
{
if ( *pArgument >>= aPropertyValue )
m_pImpl->aValues[ aPropertyValue.Name ] = aPropertyValue.Value;
else if ( *pArgument >>= aNamedValue )
m_pImpl->aValues[ aNamedValue.Name ] = aNamedValue.Value;
else
OSL_ENSURE( !pArgument->hasValue(), "NamedValueCollection::NamedValueCollection: encountered a value which I cannot handle!" );
}
}
//--------------------------------------------------------------------
void NamedValueCollection::impl_assign( const Sequence< PropertyValue >& _rArguments )
{
{
NamedValueRepository empty;
m_pImpl->aValues.swap( empty );
}
const PropertyValue* pArgument = _rArguments.getConstArray();
const PropertyValue* pArgumentEnd = _rArguments.getConstArray() + _rArguments.getLength();
for ( ; pArgument != pArgumentEnd; ++pArgument )
m_pImpl->aValues[ pArgument->Name ] = pArgument->Value;
}
//--------------------------------------------------------------------
bool NamedValueCollection::getIfExists_ensureType( const ::rtl::OUString& _rValueName, void* _pValueLocation, const Type& _rExpectedValueType ) const
{
NamedValueRepository::const_iterator pos = m_pImpl->aValues.find( _rValueName );
if ( pos != m_pImpl->aValues.end() )
{
return uno_type_assignData(
_pValueLocation, _rExpectedValueType.getTypeLibType(),
const_cast< void* >( pos->second.getValue() ), pos->second.getValueType().getTypeLibType(),
reinterpret_cast< uno_QueryInterfaceFunc >( cpp_queryInterface ),
reinterpret_cast< uno_AcquireFunc >( cpp_acquire ),
reinterpret_cast< uno_ReleaseFunc >( cpp_release )
);
}
return true;
}
//--------------------------------------------------------------------
const Any& NamedValueCollection::impl_get( const ::rtl::OUString& _rValueName ) const
{
NamedValueRepository::const_iterator pos = m_pImpl->aValues.find( _rValueName );
if ( pos != m_pImpl->aValues.end() )
return pos->second;
static Any aEmptyDefault;
return aEmptyDefault;
}
//........................................................................
} // namespace comphelper
//........................................................................
<commit_msg>INTEGRATION: CWS dba22a (1.4.34); FILE MERGED 2006/11/22 09:32:46 fs 1.4.34.1: allow construction from NamedValues<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: namedvaluecollection.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2006-12-01 17:32:40 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_comphelper.hxx"
#ifndef COMPHELPER_NAMEDVALUECOLLECTION_HXX
#include <comphelper/namedvaluecollection.hxx>
#endif
/** === begin UNO includes === **/
#ifndef _COM_SUN_STAR_BEANS_NAMEDVALUE_HPP_
#include <com/sun/star/beans/NamedValue.hpp>
#endif
/** === end UNO includes === **/
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#include <hash_map>
//........................................................................
namespace comphelper
{
//........................................................................
/** === begin UNO using === **/
using ::com::sun::star::uno::Any;
using ::com::sun::star::uno::Sequence;
using ::com::sun::star::beans::PropertyValue;
using ::com::sun::star::beans::NamedValue;
using ::com::sun::star::uno::Type;
using ::com::sun::star::uno::cpp_acquire;
using ::com::sun::star::uno::cpp_release;
using ::com::sun::star::uno::cpp_queryInterface;
using ::com::sun::star::beans::NamedValue;
/** === end UNO using === **/
//====================================================================
//= NamedValueCollection_Impl
//====================================================================
typedef ::std::hash_map< ::rtl::OUString, Any, ::rtl::OUStringHash > NamedValueRepository;
struct NamedValueCollection_Impl
{
NamedValueRepository aValues;
};
//====================================================================
//= NamedValueCollection
//====================================================================
//--------------------------------------------------------------------
NamedValueCollection::NamedValueCollection()
:m_pImpl( new NamedValueCollection_Impl )
{
}
//--------------------------------------------------------------------
NamedValueCollection::NamedValueCollection( const Sequence< Any >& _rArguments )
:m_pImpl( new NamedValueCollection_Impl )
{
impl_assign( _rArguments );
}
//--------------------------------------------------------------------
NamedValueCollection::NamedValueCollection( const Sequence< PropertyValue >& _rArguments )
:m_pImpl( new NamedValueCollection_Impl )
{
impl_assign( _rArguments );
}
//--------------------------------------------------------------------
NamedValueCollection::NamedValueCollection( const Sequence< NamedValue >& _rArguments )
:m_pImpl( new NamedValueCollection_Impl )
{
impl_assign( _rArguments );
}
//--------------------------------------------------------------------
NamedValueCollection::~NamedValueCollection()
{
}
//--------------------------------------------------------------------
void NamedValueCollection::impl_assign( const Sequence< Any >& _rArguments )
{
{
NamedValueRepository empty;
m_pImpl->aValues.swap( empty );
}
PropertyValue aPropertyValue;
NamedValue aNamedValue;
const Any* pArgument = _rArguments.getConstArray();
const Any* pArgumentEnd = _rArguments.getConstArray() + _rArguments.getLength();
for ( ; pArgument != pArgumentEnd; ++pArgument )
{
if ( *pArgument >>= aPropertyValue )
m_pImpl->aValues[ aPropertyValue.Name ] = aPropertyValue.Value;
else if ( *pArgument >>= aNamedValue )
m_pImpl->aValues[ aNamedValue.Name ] = aNamedValue.Value;
else
OSL_ENSURE( !pArgument->hasValue(), "NamedValueCollection::impl_assign: encountered a value which I cannot handle!" );
}
}
//--------------------------------------------------------------------
void NamedValueCollection::impl_assign( const Sequence< PropertyValue >& _rArguments )
{
{
NamedValueRepository empty;
m_pImpl->aValues.swap( empty );
}
const PropertyValue* pArgument = _rArguments.getConstArray();
const PropertyValue* pArgumentEnd = _rArguments.getConstArray() + _rArguments.getLength();
for ( ; pArgument != pArgumentEnd; ++pArgument )
m_pImpl->aValues[ pArgument->Name ] = pArgument->Value;
}
//--------------------------------------------------------------------
void NamedValueCollection::impl_assign( const Sequence< NamedValue >& _rArguments )
{
{
NamedValueRepository empty;
m_pImpl->aValues.swap( empty );
}
const NamedValue* pArgument = _rArguments.getConstArray();
const NamedValue* pArgumentEnd = _rArguments.getConstArray() + _rArguments.getLength();
for ( ; pArgument != pArgumentEnd; ++pArgument )
m_pImpl->aValues[ pArgument->Name ] = pArgument->Value;
}
//--------------------------------------------------------------------
bool NamedValueCollection::getIfExists_ensureType( const ::rtl::OUString& _rValueName, void* _pValueLocation, const Type& _rExpectedValueType ) const
{
NamedValueRepository::const_iterator pos = m_pImpl->aValues.find( _rValueName );
if ( pos != m_pImpl->aValues.end() )
{
return uno_type_assignData(
_pValueLocation, _rExpectedValueType.getTypeLibType(),
const_cast< void* >( pos->second.getValue() ), pos->second.getValueType().getTypeLibType(),
reinterpret_cast< uno_QueryInterfaceFunc >( cpp_queryInterface ),
reinterpret_cast< uno_AcquireFunc >( cpp_acquire ),
reinterpret_cast< uno_ReleaseFunc >( cpp_release )
);
}
return true;
}
//--------------------------------------------------------------------
const Any& NamedValueCollection::impl_get( const ::rtl::OUString& _rValueName ) const
{
NamedValueRepository::const_iterator pos = m_pImpl->aValues.find( _rValueName );
if ( pos != m_pImpl->aValues.end() )
return pos->second;
static Any aEmptyDefault;
return aEmptyDefault;
}
//........................................................................
} // namespace comphelper
//........................................................................
<|endoftext|>
|
<commit_before>/*=========================================================================
*
* 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.
*
*=========================================================================*/
#ifndef itkBlockMatchingDisplacementPipeline_hxx
#define itkBlockMatchingDisplacementPipeline_hxx
#include "itkBlockMatchingDisplacementPipeline.h"
namespace itk
{
namespace BlockMatching
{
template< typename TFixedPixel, typename TMovingPixel,
typename TMetricPixel, typename TCoordRep,
unsigned int VImageDimension >
DisplacementPipeline< TFixedPixel, TMovingPixel, TMetricPixel, TCoordRep, VImageDimension >
::DisplacementPipeline():
m_LevelRegistrationMethodTextProgressBar( false ),
m_Direction( 0 ),
m_MaximumAbsStrainAllowed( 0.075 ),
m_BlockOverlap( 0.75 ),
m_ScaleBlockByStrain( true ),
m_RegularizationMaximumNumberOfIterations( 2 )
{
this->SetNumberOfRequiredInputs( 2 );
m_FixedResampler = FixedResamplerType::New();
m_MovingResampler = MovingResamplerType::New();
m_FixedResamplerInterpolator = FixedResamplerInterpolatorType::New();
m_MovingResamplerInterpolator = MovingResamplerInterpolatorType::New();
m_FixedResampler->SetInterpolator( m_FixedResamplerInterpolator );
m_MovingResampler->SetInterpolator( m_MovingResamplerInterpolator );
m_BlockRadiusCalculator = BlockRadiusCalculatorType::New();
m_SearchRegionImageSource = SearchRegionImageSourceType::New();
m_LevelRegistrationMethod = LevelRegistrationMethodType::New();
m_RegistrationObserver = TextProgressBarCommand::New();
m_ParabolicInterpolator = ParabolicInterpolatorType::New();
m_MaximumPixelInterpolator = MaximumPixelDisplacementCalculatorType::New();
m_FinalInterpolator = FinalInterpolatorType::New();
// Optimizing interpolator specific stuff
m_SubsampleInterpolator = SubsampleInterpolatorType::New();
m_FinalInterpolator->SetInterpolator( m_SubsampleInterpolator );
m_SubsampleOptimizer = SubsampleOptimizerType::New();
typename SubsampleOptimizerType::ParametersType simplexDelta( ImageDimension );
simplexDelta.Fill( 0.3 );
m_SubsampleOptimizer->AutomaticInitialSimplexOff();
m_SubsampleOptimizer->SetInitialSimplexDelta( simplexDelta );
m_SubsampleOptimizer->SetMaximumNumberOfIterations( 250 );
m_SubsampleOptimizer->SetParametersConvergenceTolerance( 1.0e-5 );
m_SubsampleOptimizer->SetFunctionConvergenceTolerance( 10.0 );
m_FinalInterpolator->SetOptimizer( m_SubsampleOptimizer );
m_StrainWindower = StrainWindowDisplacementCalculatorType::New();
m_StrainWindower->SetMaximumIterations( 2 );
m_StrainWindower->SetDisplacementCalculator( m_ParabolicInterpolator );
m_StrainWindowStrainFilter = StrainWindowStrainFilterType::New();
m_HigherOrderAccurateGradientFilter = HigherOrderAccurateGradientFilterType::New();
m_HigherOrderAccurateGradientFilter->SetOrderOfAccuracy( 2 );
m_LinearLeastSquaresGradientFilter = LinearLeastSquaresGradientFilterType::New();
m_LinearLeastSquaresGradientFilter->SetRadius( 2 );
m_StrainWindowStrainFilter->SetGradientFilter( m_HigherOrderAccurateGradientFilter );
m_StrainWindower->SetStrainImageFilter( m_StrainWindowStrainFilter.GetPointer() );
m_MetricImageFilter = MetricImageFilterType::New();
m_BlockTransformMetricImageFilter = BlockTransformMetricImageFilterType::New();
m_BlockTransformMetricImageFilter->SetMetricImageFilter( m_MetricImageFilter );
m_BlockTransformCommand = BlockTransformCommandType::New();
m_BlockTransformCommand->SetBlockAffineTransformMetricImageFilter( m_BlockTransformMetricImageFilter );
m_StrainWindower->AddObserver( itk::EndEvent(), m_BlockTransformCommand );
m_Regularizer = DisplacmentRegularizerType::New();
m_Regularizer->SetMetricLowerBound( -1.0 );
m_Regularizer->SetDisplacementCalculator( m_StrainWindower );
m_MultiResolutionRegistrationMethod = RegistrationMethodType::New();
m_MultiResolutionRegistrationMethod->SetBlockRadiusCalculator( m_BlockRadiusCalculator );
m_MultiResolutionRegistrationMethod->SetSearchRegionImageSource( m_SearchRegionImageSource );
m_MultiResolutionRegistrationMethod->SetImageRegistrationMethod( m_LevelRegistrationMethod );
m_DisplacementCalculatorCommand = DisplacementCalculatorCommandType::New();
m_DisplacementCalculatorCommand->SetLevel0ToNMinus1DisplacementCalculator( m_StrainWindower );
m_DisplacementCalculatorCommand->SetLevelNDisplacementCalculator( m_FinalInterpolator );
m_DisplacementCalculatorCommand->SetRegularizer( m_Regularizer );
m_UpsamplingRatio[0] = 2.0;
m_UpsamplingRatio[1] = 2.0;
m_TopBlockRadius[0] = 15;
m_TopBlockRadius[1] = 10;
m_BottomBlockRadius[0] = 12;
m_BottomBlockRadius[1] = 7;
m_SearchRegionTopFactor[0] = 2.2;
m_SearchRegionTopFactor[1] = 1.4;
m_SearchRegionBottomFactor[0] = 1.1;
m_SearchRegionBottomFactor[1] = 1.1;
m_RegularizationStrainSigma[0] = 0.075;
m_RegularizationStrainSigma[1] = 0.15;
}
template< typename TFixedPixel, class TMovingPixel,
typename TMetricPixel, class TCoordRep,
unsigned int VImageDimension >
void
DisplacementPipeline< TFixedPixel, TMovingPixel, TMetricPixel, TCoordRep, VImageDimension >
::GenerateOutputInformation()
{
this->SetupPipeline();
m_MultiResolutionRegistrationMethod->UpdateOutputInformation();
DisplacementImageType* output = this->GetOutput( 0 );
if( !output )
{
return;
}
output->CopyInformation( m_MultiResolutionRegistrationMethod->GetOutput( 0 ) );
}
template< typename TFixedPixel, typename TMovingPixel,
typename TMetricPixel, typename TCoordRep,
unsigned int VImageDimension >
void
DisplacementPipeline< TFixedPixel, TMovingPixel, TMetricPixel, TCoordRep, VImageDimension >
::SetupPipeline()
{
typename FixedImageType::Pointer fixed = const_cast< FixedImageType * >(
static_cast< const FixedImageType * >( this->GetInput( 0 )));
typename MovingImageType::Pointer moving = const_cast< MovingImageType * >(
static_cast< const MovingImageType * >( this->GetInput( 1 )));
if( fixed.GetPointer() == nullptr )
{
itkExceptionMacro(<< "Fixed image image pointer is nullptr." );
}
if( moving.GetPointer() == nullptr )
{
itkExceptionMacro(<< "Moving image image pointer is nullptr." );
}
fixed->UpdateOutputInformation();
moving->UpdateOutputInformation();
// Upsampling.
m_FixedResampler->SetInput( fixed );
m_FixedResampler->SetOutputOrigin( fixed->GetOrigin() );
m_FixedResampler->SetOutputDirection( fixed->GetDirection() );
m_FixedResampler->SetOutputStartIndex( fixed->GetLargestPossibleRegion().GetIndex() );
typename FixedImageType::SizeType size;
typename FixedImageType::SpacingType spacing;
size[0] = static_cast< typename FixedImageType::SizeType::SizeValueType >( fixed->GetLargestPossibleRegion().GetSize()[0] * m_UpsamplingRatio[0] );
size[1] = static_cast< typename FixedImageType::SizeType::SizeValueType >( fixed->GetLargestPossibleRegion().GetSize()[1] * m_UpsamplingRatio[1] );
spacing[0] = fixed->GetSpacing()[0] / m_UpsamplingRatio[0];
spacing[1] = fixed->GetSpacing()[1] / m_UpsamplingRatio[1];
m_FixedResampler->SetOutputSpacing( spacing );
m_FixedResampler->SetSize( size );
m_MovingResampler->SetInput( moving );
m_MovingResampler->SetOutputOrigin( moving->GetOrigin() );
m_MovingResampler->SetOutputDirection( moving->GetDirection() );
m_MovingResampler->SetOutputStartIndex( moving->GetLargestPossibleRegion().GetIndex() );
size[0] = static_cast< typename MovingImageType::SizeType::SizeValueType >( moving->GetLargestPossibleRegion().GetSize()[0] * m_UpsamplingRatio[0] );
size[1] = static_cast< typename MovingImageType::SizeType::SizeValueType >( moving->GetLargestPossibleRegion().GetSize()[1] * m_UpsamplingRatio[1] );
spacing[0] = moving->GetSpacing()[0] / m_UpsamplingRatio[0];
spacing[1] = moving->GetSpacing()[1] / m_UpsamplingRatio[1];
m_MovingResampler->SetOutputSpacing( spacing );
m_MovingResampler->SetSize( size );
// Block Radius Calculator
RadiusType minBlockRadius;
RadiusType maxBlockRadius;
minBlockRadius[0] = m_BottomBlockRadius[0];
minBlockRadius[1] = m_BottomBlockRadius[1];
maxBlockRadius[0] = m_TopBlockRadius[0];
maxBlockRadius[1] = m_TopBlockRadius[1];
m_BlockRadiusCalculator->SetMinRadius( minBlockRadius );
m_BlockRadiusCalculator->SetMaxRadius( maxBlockRadius );
// Search Region Image Source
m_SearchRegionImageSource->SetMaxFactor( m_SearchRegionTopFactor );
m_SearchRegionImageSource->SetMinFactor( m_SearchRegionBottomFactor );
typename SearchRegionImageSourceType::PyramidScheduleType pyramidSchedule( 3, ImageDimension );
if( m_Direction == 1 )
{
pyramidSchedule( 0, 0 ) = 2;
pyramidSchedule( 0, 1 ) = 3;
pyramidSchedule( 1, 0 ) = 1;
pyramidSchedule( 1, 1 ) = 2;
pyramidSchedule( 2, 0 ) = 1;
pyramidSchedule( 2, 1 ) = 1;
}
else
{
pyramidSchedule( 0, 0 ) = 3;
pyramidSchedule( 0, 1 ) = 2;
pyramidSchedule( 1, 0 ) = 2;
pyramidSchedule( 1, 1 ) = 1;
pyramidSchedule( 2, 0 ) = 1;
pyramidSchedule( 2, 1 ) = 1;
}
m_SearchRegionImageSource->SetPyramidSchedule( pyramidSchedule );
m_SearchRegionImageSource->SetOverlapSchedule( m_BlockOverlap );
// The registration method.
m_LevelRegistrationMethod->RemoveAllObservers();
if( m_LevelRegistrationMethodTextProgressBar )
{
m_LevelRegistrationMethod->AddObserver( itk::ProgressEvent(), m_RegistrationObserver );
}
// Filter out peak hopping.
typedef typename StrainWindowDisplacementCalculatorType::StrainTensorType StrainTensorType;
StrainTensorType maxStrain;
maxStrain.Fill( m_MaximumAbsStrainAllowed );
m_StrainWindower->SetMaximumAbsStrain( maxStrain );
// Scale the fixed block by the strain at higher levels.
// Initialize to nullptr because there is initially no previous strain at the top level of the pyramid.
m_BlockTransformMetricImageFilter->SetStrainImage( nullptr );
if( m_ScaleBlockByStrain )
{
m_LevelRegistrationMethod->SetMetricImageFilter( m_BlockTransformMetricImageFilter );
}
else
{
m_LevelRegistrationMethod->SetMetricImageFilter( m_MetricImageFilter );
}
// Perform regularization.
m_Regularizer->SetStrainSigma( m_RegularizationStrainSigma );
m_Regularizer->SetMaximumIterations( m_RegularizationMaximumNumberOfIterations );
// @todo re-enable the ability to use this point examination code.
// typedef itk::DisplacementRegularizationIterationCommand<
// DisplacmentRegularizerType >
// RegularizerCommandType;
// RegularizerCommandType::Pointer regularizerObserver =
// RegularizerCommandType::New();
// regularizerObserver->SetOutputFilePrefix( args.outputPrefix );
// MetricImageType::PointType targetPoint;
// targetPoint[0] = args.targetPointAxial;
// targetPoint[1] = args.targetPointLateral;
// regularizerObserver->SetTargetPoint( targetPoint );
// typedef itk::DisplacementRegularizationIterationCommand<
// DisplacmentRegularizerType >
// RegularizerCommandType;
// RegularizerCommandType::Pointer regularizerObserver =
// RegularizerCommandType::New();
// regularizerObserver->SetOutputFilePrefix( args.outputPrefix );
// MetricImageType::PointType targetPoint;
// targetPoint[0] = args.targetPointAxial;
// targetPoint[1] = args.targetPointLateral;
// regularizerObserver->SetTargetPoint( targetPoint );
// regularizerObserver->SetRegularizer( regularizer );
// regularizerObserver->SetTruthFile( args.truthImage );
// regularizer->AddObserver( itk::IterationEvent(), regularizerObserver );
// regularizer->SetMeanChangeThreshold( 1.0e-25 );
// regularizer->SetDisplacementCalculator( interpolator );
if( m_UpsamplingRatio[0] == 1.0 && m_UpsamplingRatio[1] == 1.0 )
{
m_MultiResolutionRegistrationMethod->SetFixedImage( fixed );
m_MultiResolutionRegistrationMethod->SetMovingImage( moving );
}
else
{
m_MultiResolutionRegistrationMethod->SetFixedImage( m_FixedResampler->GetOutput() );
m_MultiResolutionRegistrationMethod->SetMovingImage( m_MovingResampler->GetOutput() );
}
m_MultiResolutionRegistrationMethod->SetSchedules( pyramidSchedule, pyramidSchedule );
}
template< typename TFixedPixel, typename TMovingPixel,
typename TMetricPixel, typename TCoordRep,
unsigned int VImageDimension >
void
DisplacementPipeline< TFixedPixel, TMovingPixel, TMetricPixel, TCoordRep, VImageDimension >
::GenerateData()
{
this->AllocateOutputs();
// Set the displacement calculator and regularizer iterations at every level.
m_MultiResolutionRegistrationMethod->GetImageRegistrationMethod()->SetMetricImageToDisplacementCalculator( m_Regularizer );
//if ( args.maximumIterations == 0 )
//{
//displacementCalculatorCommand->SetLevel0ToNMinus1RegularizerIterations( 0 );
//}
//else
//{
m_DisplacementCalculatorCommand->SetLevel0ToNMinus1RegularizerIterations( 3 );
//}
m_DisplacementCalculatorCommand->SetLevelNRegularizerIterations( m_RegularizationMaximumNumberOfIterations );
m_DisplacementCalculatorCommand->SetMultiResolutionMethod( m_MultiResolutionRegistrationMethod );
m_MultiResolutionRegistrationMethod->AddObserver( itk::IterationEvent(), m_DisplacementCalculatorCommand );
m_MultiResolutionRegistrationMethod->GraftOutput( this->GetOutput() );
m_MultiResolutionRegistrationMethod->Update();
this->GraftOutput( m_MultiResolutionRegistrationMethod->GetOutput() );
}
} // end namespace BlockMatching
} // end namespace itk
#endif
<commit_msg>ENH: Remove 0 to n-1 mult-resolution displacement regularizations<commit_after>/*=========================================================================
*
* 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.
*
*=========================================================================*/
#ifndef itkBlockMatchingDisplacementPipeline_hxx
#define itkBlockMatchingDisplacementPipeline_hxx
#include "itkBlockMatchingDisplacementPipeline.h"
namespace itk
{
namespace BlockMatching
{
template< typename TFixedPixel, typename TMovingPixel,
typename TMetricPixel, typename TCoordRep,
unsigned int VImageDimension >
DisplacementPipeline< TFixedPixel, TMovingPixel, TMetricPixel, TCoordRep, VImageDimension >
::DisplacementPipeline():
m_LevelRegistrationMethodTextProgressBar( false ),
m_Direction( 0 ),
m_MaximumAbsStrainAllowed( 0.075 ),
m_BlockOverlap( 0.75 ),
m_ScaleBlockByStrain( true ),
m_RegularizationMaximumNumberOfIterations( 2 )
{
this->SetNumberOfRequiredInputs( 2 );
m_FixedResampler = FixedResamplerType::New();
m_MovingResampler = MovingResamplerType::New();
m_FixedResamplerInterpolator = FixedResamplerInterpolatorType::New();
m_MovingResamplerInterpolator = MovingResamplerInterpolatorType::New();
m_FixedResampler->SetInterpolator( m_FixedResamplerInterpolator );
m_MovingResampler->SetInterpolator( m_MovingResamplerInterpolator );
m_BlockRadiusCalculator = BlockRadiusCalculatorType::New();
m_SearchRegionImageSource = SearchRegionImageSourceType::New();
m_LevelRegistrationMethod = LevelRegistrationMethodType::New();
m_RegistrationObserver = TextProgressBarCommand::New();
m_ParabolicInterpolator = ParabolicInterpolatorType::New();
m_MaximumPixelInterpolator = MaximumPixelDisplacementCalculatorType::New();
m_FinalInterpolator = FinalInterpolatorType::New();
// Optimizing interpolator specific stuff
m_SubsampleInterpolator = SubsampleInterpolatorType::New();
m_FinalInterpolator->SetInterpolator( m_SubsampleInterpolator );
m_SubsampleOptimizer = SubsampleOptimizerType::New();
typename SubsampleOptimizerType::ParametersType simplexDelta( ImageDimension );
simplexDelta.Fill( 0.3 );
m_SubsampleOptimizer->AutomaticInitialSimplexOff();
m_SubsampleOptimizer->SetInitialSimplexDelta( simplexDelta );
m_SubsampleOptimizer->SetMaximumNumberOfIterations( 250 );
m_SubsampleOptimizer->SetParametersConvergenceTolerance( 1.0e-5 );
m_SubsampleOptimizer->SetFunctionConvergenceTolerance( 10.0 );
m_FinalInterpolator->SetOptimizer( m_SubsampleOptimizer );
m_StrainWindower = StrainWindowDisplacementCalculatorType::New();
m_StrainWindower->SetMaximumIterations( 2 );
m_StrainWindower->SetDisplacementCalculator( m_ParabolicInterpolator );
m_StrainWindowStrainFilter = StrainWindowStrainFilterType::New();
m_HigherOrderAccurateGradientFilter = HigherOrderAccurateGradientFilterType::New();
m_HigherOrderAccurateGradientFilter->SetOrderOfAccuracy( 2 );
m_LinearLeastSquaresGradientFilter = LinearLeastSquaresGradientFilterType::New();
m_LinearLeastSquaresGradientFilter->SetRadius( 2 );
m_StrainWindowStrainFilter->SetGradientFilter( m_HigherOrderAccurateGradientFilter );
m_StrainWindower->SetStrainImageFilter( m_StrainWindowStrainFilter.GetPointer() );
m_MetricImageFilter = MetricImageFilterType::New();
m_BlockTransformMetricImageFilter = BlockTransformMetricImageFilterType::New();
m_BlockTransformMetricImageFilter->SetMetricImageFilter( m_MetricImageFilter );
m_BlockTransformCommand = BlockTransformCommandType::New();
m_BlockTransformCommand->SetBlockAffineTransformMetricImageFilter( m_BlockTransformMetricImageFilter );
m_StrainWindower->AddObserver( itk::EndEvent(), m_BlockTransformCommand );
m_Regularizer = DisplacmentRegularizerType::New();
m_Regularizer->SetMetricLowerBound( -1.0 );
m_Regularizer->SetDisplacementCalculator( m_StrainWindower );
m_MultiResolutionRegistrationMethod = RegistrationMethodType::New();
m_MultiResolutionRegistrationMethod->SetBlockRadiusCalculator( m_BlockRadiusCalculator );
m_MultiResolutionRegistrationMethod->SetSearchRegionImageSource( m_SearchRegionImageSource );
m_MultiResolutionRegistrationMethod->SetImageRegistrationMethod( m_LevelRegistrationMethod );
m_DisplacementCalculatorCommand = DisplacementCalculatorCommandType::New();
m_DisplacementCalculatorCommand->SetLevel0ToNMinus1DisplacementCalculator( m_StrainWindower );
m_DisplacementCalculatorCommand->SetLevelNDisplacementCalculator( m_FinalInterpolator );
m_DisplacementCalculatorCommand->SetRegularizer( m_Regularizer );
m_UpsamplingRatio[0] = 2.0;
m_UpsamplingRatio[1] = 2.0;
m_TopBlockRadius[0] = 15;
m_TopBlockRadius[1] = 10;
m_BottomBlockRadius[0] = 12;
m_BottomBlockRadius[1] = 7;
m_SearchRegionTopFactor[0] = 2.2;
m_SearchRegionTopFactor[1] = 1.4;
m_SearchRegionBottomFactor[0] = 1.1;
m_SearchRegionBottomFactor[1] = 1.1;
m_RegularizationStrainSigma[0] = 0.075;
m_RegularizationStrainSigma[1] = 0.15;
}
template< typename TFixedPixel, class TMovingPixel,
typename TMetricPixel, class TCoordRep,
unsigned int VImageDimension >
void
DisplacementPipeline< TFixedPixel, TMovingPixel, TMetricPixel, TCoordRep, VImageDimension >
::GenerateOutputInformation()
{
this->SetupPipeline();
m_MultiResolutionRegistrationMethod->UpdateOutputInformation();
DisplacementImageType* output = this->GetOutput( 0 );
if( !output )
{
return;
}
output->CopyInformation( m_MultiResolutionRegistrationMethod->GetOutput( 0 ) );
}
template< typename TFixedPixel, typename TMovingPixel,
typename TMetricPixel, typename TCoordRep,
unsigned int VImageDimension >
void
DisplacementPipeline< TFixedPixel, TMovingPixel, TMetricPixel, TCoordRep, VImageDimension >
::SetupPipeline()
{
typename FixedImageType::Pointer fixed = const_cast< FixedImageType * >(
static_cast< const FixedImageType * >( this->GetInput( 0 )));
typename MovingImageType::Pointer moving = const_cast< MovingImageType * >(
static_cast< const MovingImageType * >( this->GetInput( 1 )));
if( fixed.GetPointer() == nullptr )
{
itkExceptionMacro(<< "Fixed image image pointer is nullptr." );
}
if( moving.GetPointer() == nullptr )
{
itkExceptionMacro(<< "Moving image image pointer is nullptr." );
}
fixed->UpdateOutputInformation();
moving->UpdateOutputInformation();
// Upsampling.
m_FixedResampler->SetInput( fixed );
m_FixedResampler->SetOutputOrigin( fixed->GetOrigin() );
m_FixedResampler->SetOutputDirection( fixed->GetDirection() );
m_FixedResampler->SetOutputStartIndex( fixed->GetLargestPossibleRegion().GetIndex() );
typename FixedImageType::SizeType size;
typename FixedImageType::SpacingType spacing;
size[0] = static_cast< typename FixedImageType::SizeType::SizeValueType >( fixed->GetLargestPossibleRegion().GetSize()[0] * m_UpsamplingRatio[0] );
size[1] = static_cast< typename FixedImageType::SizeType::SizeValueType >( fixed->GetLargestPossibleRegion().GetSize()[1] * m_UpsamplingRatio[1] );
spacing[0] = fixed->GetSpacing()[0] / m_UpsamplingRatio[0];
spacing[1] = fixed->GetSpacing()[1] / m_UpsamplingRatio[1];
m_FixedResampler->SetOutputSpacing( spacing );
m_FixedResampler->SetSize( size );
m_MovingResampler->SetInput( moving );
m_MovingResampler->SetOutputOrigin( moving->GetOrigin() );
m_MovingResampler->SetOutputDirection( moving->GetDirection() );
m_MovingResampler->SetOutputStartIndex( moving->GetLargestPossibleRegion().GetIndex() );
size[0] = static_cast< typename MovingImageType::SizeType::SizeValueType >( moving->GetLargestPossibleRegion().GetSize()[0] * m_UpsamplingRatio[0] );
size[1] = static_cast< typename MovingImageType::SizeType::SizeValueType >( moving->GetLargestPossibleRegion().GetSize()[1] * m_UpsamplingRatio[1] );
spacing[0] = moving->GetSpacing()[0] / m_UpsamplingRatio[0];
spacing[1] = moving->GetSpacing()[1] / m_UpsamplingRatio[1];
m_MovingResampler->SetOutputSpacing( spacing );
m_MovingResampler->SetSize( size );
// Block Radius Calculator
RadiusType minBlockRadius;
RadiusType maxBlockRadius;
minBlockRadius[0] = m_BottomBlockRadius[0];
minBlockRadius[1] = m_BottomBlockRadius[1];
maxBlockRadius[0] = m_TopBlockRadius[0];
maxBlockRadius[1] = m_TopBlockRadius[1];
m_BlockRadiusCalculator->SetMinRadius( minBlockRadius );
m_BlockRadiusCalculator->SetMaxRadius( maxBlockRadius );
// Search Region Image Source
m_SearchRegionImageSource->SetMaxFactor( m_SearchRegionTopFactor );
m_SearchRegionImageSource->SetMinFactor( m_SearchRegionBottomFactor );
typename SearchRegionImageSourceType::PyramidScheduleType pyramidSchedule( 3, ImageDimension );
if( m_Direction == 1 )
{
pyramidSchedule( 0, 0 ) = 2;
pyramidSchedule( 0, 1 ) = 3;
pyramidSchedule( 1, 0 ) = 1;
pyramidSchedule( 1, 1 ) = 2;
pyramidSchedule( 2, 0 ) = 1;
pyramidSchedule( 2, 1 ) = 1;
}
else
{
pyramidSchedule( 0, 0 ) = 3;
pyramidSchedule( 0, 1 ) = 2;
pyramidSchedule( 1, 0 ) = 2;
pyramidSchedule( 1, 1 ) = 1;
pyramidSchedule( 2, 0 ) = 1;
pyramidSchedule( 2, 1 ) = 1;
}
m_SearchRegionImageSource->SetPyramidSchedule( pyramidSchedule );
m_SearchRegionImageSource->SetOverlapSchedule( m_BlockOverlap );
// The registration method.
m_LevelRegistrationMethod->RemoveAllObservers();
if( m_LevelRegistrationMethodTextProgressBar )
{
m_LevelRegistrationMethod->AddObserver( itk::ProgressEvent(), m_RegistrationObserver );
}
// Filter out peak hopping.
typedef typename StrainWindowDisplacementCalculatorType::StrainTensorType StrainTensorType;
StrainTensorType maxStrain;
maxStrain.Fill( m_MaximumAbsStrainAllowed );
m_StrainWindower->SetMaximumAbsStrain( maxStrain );
// Scale the fixed block by the strain at higher levels.
// Initialize to nullptr because there is initially no previous strain at the top level of the pyramid.
m_BlockTransformMetricImageFilter->SetStrainImage( nullptr );
if( m_ScaleBlockByStrain )
{
m_LevelRegistrationMethod->SetMetricImageFilter( m_BlockTransformMetricImageFilter );
}
else
{
m_LevelRegistrationMethod->SetMetricImageFilter( m_MetricImageFilter );
}
// Perform regularization.
m_Regularizer->SetStrainSigma( m_RegularizationStrainSigma );
m_Regularizer->SetMaximumIterations( m_RegularizationMaximumNumberOfIterations );
// @todo re-enable the ability to use this point examination code.
// typedef itk::DisplacementRegularizationIterationCommand<
// DisplacmentRegularizerType >
// RegularizerCommandType;
// RegularizerCommandType::Pointer regularizerObserver =
// RegularizerCommandType::New();
// regularizerObserver->SetOutputFilePrefix( args.outputPrefix );
// MetricImageType::PointType targetPoint;
// targetPoint[0] = args.targetPointAxial;
// targetPoint[1] = args.targetPointLateral;
// regularizerObserver->SetTargetPoint( targetPoint );
// typedef itk::DisplacementRegularizationIterationCommand<
// DisplacmentRegularizerType >
// RegularizerCommandType;
// RegularizerCommandType::Pointer regularizerObserver =
// RegularizerCommandType::New();
// regularizerObserver->SetOutputFilePrefix( args.outputPrefix );
// MetricImageType::PointType targetPoint;
// targetPoint[0] = args.targetPointAxial;
// targetPoint[1] = args.targetPointLateral;
// regularizerObserver->SetTargetPoint( targetPoint );
// regularizerObserver->SetRegularizer( regularizer );
// regularizerObserver->SetTruthFile( args.truthImage );
// regularizer->AddObserver( itk::IterationEvent(), regularizerObserver );
// regularizer->SetMeanChangeThreshold( 1.0e-25 );
// regularizer->SetDisplacementCalculator( interpolator );
if( m_UpsamplingRatio[0] == 1.0 && m_UpsamplingRatio[1] == 1.0 )
{
m_MultiResolutionRegistrationMethod->SetFixedImage( fixed );
m_MultiResolutionRegistrationMethod->SetMovingImage( moving );
}
else
{
m_MultiResolutionRegistrationMethod->SetFixedImage( m_FixedResampler->GetOutput() );
m_MultiResolutionRegistrationMethod->SetMovingImage( m_MovingResampler->GetOutput() );
}
m_MultiResolutionRegistrationMethod->SetSchedules( pyramidSchedule, pyramidSchedule );
}
template< typename TFixedPixel, typename TMovingPixel,
typename TMetricPixel, typename TCoordRep,
unsigned int VImageDimension >
void
DisplacementPipeline< TFixedPixel, TMovingPixel, TMetricPixel, TCoordRep, VImageDimension >
::GenerateData()
{
this->AllocateOutputs();
// Set the displacement calculator and regularizer iterations at every level.
m_MultiResolutionRegistrationMethod->GetImageRegistrationMethod()->SetMetricImageToDisplacementCalculator( m_Regularizer );
m_DisplacementCalculatorCommand->SetLevel0ToNMinus1RegularizerIterations( 0 );
m_DisplacementCalculatorCommand->SetLevelNRegularizerIterations( m_RegularizationMaximumNumberOfIterations );
m_DisplacementCalculatorCommand->SetMultiResolutionMethod( m_MultiResolutionRegistrationMethod );
m_MultiResolutionRegistrationMethod->AddObserver( itk::IterationEvent(), m_DisplacementCalculatorCommand );
m_MultiResolutionRegistrationMethod->GraftOutput( this->GetOutput() );
m_MultiResolutionRegistrationMethod->Update();
this->GraftOutput( m_MultiResolutionRegistrationMethod->GetOutput() );
}
} // end namespace BlockMatching
} // end namespace itk
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2009, 2010, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
/// \file urbi/uobject.hxx
#ifndef URBI_UOBJECT_HXX
# define URBI_UOBJECT_HXX
namespace urbi
{
/*----------.
| UObject. |
`----------*/
inline
int
UObject::update()
{
return 0;
}
inline
int
UObject::voidfun()
{
return 0;
}
inline
void
UObject::clean()
{
assert(impl_);
impl_->clean();
}
inline
void
UObject::USetUpdate(ufloat period)
{
assert(impl_);
impl_->setUpdate(period);
}
inline
void
UObject::USync(UVar &v)
{
v.keepSynchronized();
}
inline
bool
UObject::removeTimer(TimerHandle h)
{
return impl_->removeTimer(h);
}
inline
impl::UObjectImpl*
UObject::impl_get()
{
return impl_;
}
inline
libport::ThreadPool::rTaskLock
UObject::getTaskLock(LockMode m, const std::string& what)
{
typedef libport::ThreadPool::rTaskLock rTaskLock;
typedef libport::ThreadPool::TaskLock TaskLock;
// Static in inlined functions are per-module.
static rTaskLock module_lock(new TaskLock);
switch(m)
{
case LOCK_NONE:
return 0;
break;
case LOCK_FUNCTION:
{
rTaskLock& res = taskLocks_[what];
if (!res)
res = new TaskLock;
return res;
}
break;
case LOCK_INSTANCE:
return taskLock_;
break;
case LOCK_CLASS:
return getClassTaskLock();
break;
case LOCK_MODULE:
return module_lock;
break;
}
// Unreachable
assert(false);
}
inline UObject*
uvalue_caster<UObject*>::operator()(UValue& v)
{
if (v.type != DATA_STRING)
return 0;
return getUObject(*v.stringValue);
}
template<typename T> struct
uvalue_caster<T*> {
T* operator()(UValue& v)
{
UObject* res = uvalue_caster<UObject*>()(v);
return dynamic_cast<T*>(res);
}
};
}
#endif // !URBI_UOBJECT_HXX
<commit_msg>Pacify (incorrect) missing return value warning.<commit_after>/*
* Copyright (C) 2009, 2010, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
/// \file urbi/uobject.hxx
#ifndef URBI_UOBJECT_HXX
# define URBI_UOBJECT_HXX
namespace urbi
{
/*----------.
| UObject. |
`----------*/
inline
int
UObject::update()
{
return 0;
}
inline
int
UObject::voidfun()
{
return 0;
}
inline
void
UObject::clean()
{
assert(impl_);
impl_->clean();
}
inline
void
UObject::USetUpdate(ufloat period)
{
assert(impl_);
impl_->setUpdate(period);
}
inline
void
UObject::USync(UVar &v)
{
v.keepSynchronized();
}
inline
bool
UObject::removeTimer(TimerHandle h)
{
return impl_->removeTimer(h);
}
inline
impl::UObjectImpl*
UObject::impl_get()
{
return impl_;
}
inline
libport::ThreadPool::rTaskLock
UObject::getTaskLock(LockMode m, const std::string& what)
{
typedef libport::ThreadPool::rTaskLock rTaskLock;
typedef libport::ThreadPool::TaskLock TaskLock;
// Static in inlined functions are per-module.
static rTaskLock module_lock(new TaskLock);
switch(m)
{
case LOCK_NONE:
return 0;
break;
case LOCK_FUNCTION:
{
rTaskLock& res = taskLocks_[what];
if (!res)
res = new TaskLock;
return res;
}
break;
case LOCK_INSTANCE:
return taskLock_;
break;
case LOCK_CLASS:
return getClassTaskLock();
break;
case LOCK_MODULE:
return module_lock;
break;
}
return 0;
}
inline UObject*
uvalue_caster<UObject*>::operator()(UValue& v)
{
if (v.type != DATA_STRING)
return 0;
return getUObject(*v.stringValue);
}
template<typename T> struct
uvalue_caster<T*> {
T* operator()(UValue& v)
{
UObject* res = uvalue_caster<UObject*>()(v);
return dynamic_cast<T*>(res);
}
};
}
#endif // !URBI_UOBJECT_HXX
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2009, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#include <sys/stat.h>
#include <cassert>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <libport/config.h>
#include <libport/foreach.hh>
#include <urbi/urbi-root.hh>
#include <libport/config.h>
#if defined WIN32
# define APPLE_LINUX_WINDOWS(Apple, Linux, Windows) Windows
#elif defined __APPLE__
# define APPLE_LINUX_WINDOWS(Apple, Linux, Windows) Apple
#else
# define APPLE_LINUX_WINDOWS(Apple, Linux, Windows) Linux
#endif
/*--------.
| Helpers |
`--------*/
static std::string
xgetenv(const std::string& var, const std::string& val = "")
{
const char* res = getenv(var.c_str());
return res ? std::string(res) : val;
}
// static void
// xsetenv(const std::string& var, const std::string& val, int force)
// {
// #ifdef WIN32
// if (force || xgetenv(var).empty())
// _putenv(strdup((var + "=" + val).c_str()));
// #else
// setenv(var.c_str(), val.c_str(), force);
// #endif
// }
/*------------.
| Reporting. |
`------------*/
static bool
debug()
{
static bool res = xgetenv("GD_LEVEL") == "DUMP";
return res;
}
# define URBI_ROOT_ECHO(S) \
std::cerr << S << std::endl \
# define URBI_ROOT_DEBUG(Self, S) \
do { \
if (debug()) \
URBI_ROOT_ECHO(Self << ": " << S); \
} while (0) \
# define URBI_ROOT_FATAL(Self, N, S) \
do { \
URBI_ROOT_ECHO(Self << ": " << S); \
exit(N); \
} while (0)
/*-----------------.
| File constants. |
`-----------------*/
static const std::string libext =
APPLE_LINUX_WINDOWS(".dylib", ".so", ".dll");
static const std::string separator =
APPLE_LINUX_WINDOWS("/", "/", "\\");
static const std::string libdir =
APPLE_LINUX_WINDOWS("lib", "lib", "bin");
static const std::string libuobjects_dir =
std::string("gostai/core/") + LIBPORT_URBI_HOST;
/// Join path components.
std::string
operator/(const std::string& lhs, const std::string& rhs)
{
return (lhs.empty() ? rhs
: rhs.empty() ? lhs
: lhs + separator + rhs);
}
/*-------------------------------------.
| Crapy dynamic portability routines. |
`-------------------------------------*/
#ifdef WIN32
#define RTLD_LAZY 0
#define RTLD_NOW 0
#define RTLD_GLOBAL 0
static RTLD_HANDLE
dlopen(const char* name, int)
{
RTLD_HANDLE res = LoadLibrary(name);
if (res)
{
char buf[BUFSIZ];
GetModuleFileName(res, buf, sizeof buf - 1);
buf[sizeof buf - 1] = 0;
}
return res;
}
static void*
dlsym(RTLD_HANDLE module, const char* name)
{
return GetProcAddress(module, name);
}
static const char*
dlerror(DWORD err = GetLastError())
{
static char buf[1024];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
0, err, 0,
(LPTSTR)buf, sizeof buf,
0);
return buf;
}
#else
# include <dlfcn.h>
#endif
typedef std::vector<std::string> strings_type;
static strings_type
split(std::string lib)
{
strings_type res;
size_t pos;
while ((pos = lib.find(':')) != lib.npos)
{
std::string s = lib.substr(0, pos);
lib = lib.substr(pos + 1, lib.npos);
#ifdef WIN32
// In case we split "c:\foo" into "c" and "\foo", glue them
// together again.
if (s[0] == '\\'
&& !res.empty()
&& res.back().length() == 1)
res.back() += ':' + s;
else
#endif
res.push_back(s);
}
if (!lib.empty())
res.push_back(lib);
return res;
}
/// \a path does not include the extension.
static RTLD_HANDLE
xdlopen(const std::string& self, std::string path,
int flags = RTLD_GLOBAL)
{
path += libext;
URBI_ROOT_DEBUG(self, "loading library: " << path);
RTLD_HANDLE res = dlopen(path.c_str(), flags);
if (!res)
URBI_ROOT_FATAL(self, 1,
"cannot open library: " << path << ": " << dlerror());
return res;
}
static
std::string
resolve_symlinks(const std::string& logname, const std::string& s)
{
#if defined WIN32
return s;
#else
char path[BUFSIZ];
strncpy(path, s.c_str(), BUFSIZ);
path[BUFSIZ - 1] = 0;
while (readlink(path, path, BUFSIZ) != -1)
URBI_ROOT_DEBUG(logname, "unrolling symbolic link: " << path);
return path;
#endif
}
/*-----------.
| UrbiRoot. |
`-----------*/
UrbiRoot::UrbiRoot(const std::string& program, bool static_build)
: program_(program)
, root_()
, handle_libjpeg_(0)
, handle_libport_(0)
, handle_libsched_(0)
, handle_liburbi_(0)
, handle_libuobject_(0)
{
// Find our directory.
std::string uroot = xgetenv("URBI_ROOT");
if (!uroot.empty())
{
URBI_ROOT_DEBUG(program_,
"URBI_ROOT is set, forcing root directory: " << root_);
root_ = uroot;
}
else
{
URBI_ROOT_DEBUG(program_, "guessing Urbi root: invoked as: " << program_);
// Handle the chained symlinks case.
std::string argv0 = resolve_symlinks(program_, program);
#ifdef WIN32
size_t pos = argv0.find_last_of("/\\");
#else
size_t pos = argv0.rfind('/');
#endif
if (pos == std::string::npos)
{
URBI_ROOT_DEBUG(program_,
"invoked from the path, looking for ourselves in PATH");
strings_type path = split(xgetenv("PATH"));
foreach (const std::string& dir, path)
{
struct stat stats;
std::string file = dir / argv0;
if (stat(file.c_str(), &stats) == 0)
{
URBI_ROOT_DEBUG(program_, "found: " << file);
root_ = dir / "..";
URBI_ROOT_DEBUG(program_, "root directory is: " << root_);
break;
}
URBI_ROOT_DEBUG(program_, "not found: " << file);
}
}
else
{
root_ = argv0.substr(0, pos) / "..";
URBI_ROOT_DEBUG(program_,
"invoked with a path, setting root to parent directory: "
<< root_);
}
}
if (root_.empty())
URBI_ROOT_FATAL(program_, 3,
"Unable to find Urbi SDK installation location. "
"Please set URBI_ROOT.");
// const std::string urbi_path = root_ / "share" / "gostai";
// xsetenv("URBI_PATH", xgetenv("URBI_PATH") + ":" + urbi_path, true);
// URBI_ROOT_DEBUG("append to URBI_PATH: " << urbi_path);
if (!static_build)
{
handle_libjpeg_ = library_load("jpeg");
handle_libport_ = library_load("port");
handle_libsched_ = library_load("sched");
handle_libserialize_ = library_load("serialize");
handle_liburbi_ = library_load("urbi");
}
}
RTLD_HANDLE
UrbiRoot::library_load(const std::string& base)
{
std::string envvar = "URBI_ROOT_LIB" + base;
foreach (char& s, envvar)
s = toupper(s);
return
xdlopen(program_,
xgetenv(envvar,
root(libdir / "lib" + base)));
}
std::string
UrbiRoot::root(const std::string& path) const
{
return root_ / path;
}
std::string
UrbiRoot::core_path(const std::string& path) const
{
return root(libuobjects_dir / path);
}
std::string
UrbiRoot::uobjects_path(const std::string& path) const
{
return core_path("uobjects" / path);
}
std::string
UrbiRoot::share_path(const std::string& path) const
{
return root("share/gostai" / path);
}
void
UrbiRoot::load_plugin()
{
URBI_ROOT_DEBUG(program_, "loading plugin UObject implementation");
handle_libuobject_ = xdlopen(program_, core_path("engine/libuobject"));
}
/// Location of Urbi remote libuobject
void
UrbiRoot::load_remote()
{
URBI_ROOT_DEBUG(program_, "loading remote UObject implementation");
handle_libuobject_ = xdlopen(program_, core_path("remote/libuobject"));
}
void
UrbiRoot::load_custom(const std::string& path_)
{
std::string path = path_ / "libuobject";
URBI_ROOT_DEBUG(program_, "loading custom UObject implementation: " << path);
handle_libuobject_ = xdlopen(program_, path);
}
typedef int(*urbi_launch_type)(int, const char*[], UrbiRoot&);
int
UrbiRoot::urbi_launch(int argc, const char** argv)
{
URBI_ROOT_DEBUG(program_, "loading symbol urbi_launch from liburbi-launch");
// Reinterpret-cast fails with gcc3 arm
urbi_launch_type f = (urbi_launch_type)(dlsym(handle_liburbi_, "urbi_launch"));
if (!f)
URBI_ROOT_FATAL(program_, 2,
"cannot locate urbi_launch symbol: " << dlerror());
return f(argc, argv, *this);
}
int
UrbiRoot::urbi_launch(int argc, char** argv)
{
return urbi_launch(argc, const_cast<const char**>(argv));
}
typedef int(*urbi_main_type)(const std::vector<std::string>& args,
UrbiRoot& root,
bool block, bool errors);
int
UrbiRoot::urbi_main(const std::vector<std::string>& args,
bool block, bool errors)
{
URBI_ROOT_DEBUG(program_, "loading symbol urbi_main_args from libuobject");
// Reinterpret-cast fails with gcc3 arm
urbi_main_type f =
(urbi_main_type)(dlsym(handle_libuobject_, "urbi_main_args"));
if (!f)
URBI_ROOT_FATAL(program_, 2,
"cannot locate urbi_launch symbol: " << dlerror());
return f(args, *this, block, errors);
}
<commit_msg>urbi-root: don't use / in paths.<commit_after>/*
* Copyright (C) 2009, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
#include <sys/stat.h>
#include <cassert>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <libport/config.h>
#include <libport/foreach.hh>
#include <urbi/urbi-root.hh>
#include <libport/config.h>
#if defined WIN32
# define APPLE_LINUX_WINDOWS(Apple, Linux, Windows) Windows
#elif defined __APPLE__
# define APPLE_LINUX_WINDOWS(Apple, Linux, Windows) Apple
#else
# define APPLE_LINUX_WINDOWS(Apple, Linux, Windows) Linux
#endif
/*--------.
| Helpers |
`--------*/
static std::string
xgetenv(const std::string& var, const std::string& val = "")
{
const char* res = getenv(var.c_str());
return res ? std::string(res) : val;
}
// static void
// xsetenv(const std::string& var, const std::string& val, int force)
// {
// #ifdef WIN32
// if (force || xgetenv(var).empty())
// _putenv(strdup((var + "=" + val).c_str()));
// #else
// setenv(var.c_str(), val.c_str(), force);
// #endif
// }
/*------------.
| Reporting. |
`------------*/
static bool
debug()
{
static bool res = xgetenv("GD_LEVEL") == "DUMP";
return res;
}
# define URBI_ROOT_ECHO(S) \
std::cerr << S << std::endl \
# define URBI_ROOT_DEBUG(Self, S) \
do { \
if (debug()) \
URBI_ROOT_ECHO(Self << ": " << S); \
} while (0) \
# define URBI_ROOT_FATAL(Self, N, S) \
do { \
URBI_ROOT_ECHO(Self << ": " << S); \
exit(N); \
} while (0)
/*-----------------.
| File constants. |
`-----------------*/
static const std::string libext =
APPLE_LINUX_WINDOWS(".dylib", ".so", ".dll");
static const std::string separator =
APPLE_LINUX_WINDOWS("/", "/", "\\");
static const std::string libdir =
APPLE_LINUX_WINDOWS("lib", "lib", "bin");
/// Join path components.
std::string
operator/(const std::string& lhs, const std::string& rhs)
{
return (lhs.empty() ? rhs
: rhs.empty() ? lhs
: lhs + separator + rhs);
}
/*-------------------------------------.
| Crapy dynamic portability routines. |
`-------------------------------------*/
#ifdef WIN32
#define RTLD_LAZY 0
#define RTLD_NOW 0
#define RTLD_GLOBAL 0
static RTLD_HANDLE
dlopen(const char* name, int)
{
RTLD_HANDLE res = LoadLibrary(name);
if (res)
{
char buf[BUFSIZ];
GetModuleFileName(res, buf, sizeof buf - 1);
buf[sizeof buf - 1] = 0;
}
return res;
}
static void*
dlsym(RTLD_HANDLE module, const char* name)
{
return GetProcAddress(module, name);
}
static const char*
dlerror(DWORD err = GetLastError())
{
static char buf[1024];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
0, err, 0,
(LPTSTR)buf, sizeof buf,
0);
return buf;
}
#else
# include <dlfcn.h>
#endif
typedef std::vector<std::string> strings_type;
static strings_type
split(std::string lib)
{
strings_type res;
size_t pos;
while ((pos = lib.find(':')) != lib.npos)
{
std::string s = lib.substr(0, pos);
lib = lib.substr(pos + 1, lib.npos);
#ifdef WIN32
// In case we split "c:\foo" into "c" and "\foo", glue them
// together again.
if (s[0] == '\\'
&& !res.empty()
&& res.back().length() == 1)
res.back() += ':' + s;
else
#endif
res.push_back(s);
}
if (!lib.empty())
res.push_back(lib);
return res;
}
/// \a path does not include the extension.
static RTLD_HANDLE
xdlopen(const std::string& self, std::string path,
int flags = RTLD_GLOBAL)
{
path += libext;
URBI_ROOT_DEBUG(self, "loading library: " << path);
RTLD_HANDLE res = dlopen(path.c_str(), flags);
if (!res)
URBI_ROOT_FATAL(self, 1,
"cannot open library: " << path << ": " << dlerror());
return res;
}
static
std::string
resolve_symlinks(const std::string& logname, const std::string& s)
{
#if defined WIN32
return s;
#else
char path[BUFSIZ];
strncpy(path, s.c_str(), BUFSIZ);
path[BUFSIZ - 1] = 0;
while (readlink(path, path, BUFSIZ) != -1)
URBI_ROOT_DEBUG(logname, "unrolling symbolic link: " << path);
return path;
#endif
}
/*-----------.
| UrbiRoot. |
`-----------*/
UrbiRoot::UrbiRoot(const std::string& program, bool static_build)
: program_(program)
, root_()
, handle_libjpeg_(0)
, handle_libport_(0)
, handle_libsched_(0)
, handle_liburbi_(0)
, handle_libuobject_(0)
{
// Find our directory.
std::string uroot = xgetenv("URBI_ROOT");
if (!uroot.empty())
{
URBI_ROOT_DEBUG(program_,
"URBI_ROOT is set, forcing root directory: " << root_);
root_ = uroot;
}
else
{
URBI_ROOT_DEBUG(program_, "guessing Urbi root: invoked as: " << program_);
// Handle the chained symlinks case.
std::string argv0 = resolve_symlinks(program_, program);
#ifdef WIN32
size_t pos = argv0.find_last_of("/\\");
#else
size_t pos = argv0.rfind('/');
#endif
if (pos == std::string::npos)
{
URBI_ROOT_DEBUG(program_,
"invoked from the path, looking for ourselves in PATH");
strings_type path = split(xgetenv("PATH"));
foreach (const std::string& dir, path)
{
struct stat stats;
std::string file = dir / argv0;
if (stat(file.c_str(), &stats) == 0)
{
URBI_ROOT_DEBUG(program_, "found: " << file);
root_ = dir / "..";
URBI_ROOT_DEBUG(program_, "root directory is: " << root_);
break;
}
URBI_ROOT_DEBUG(program_, "not found: " << file);
}
}
else
{
root_ = argv0.substr(0, pos) / "..";
URBI_ROOT_DEBUG(program_,
"invoked with a path, setting root to parent directory: "
<< root_);
}
}
if (root_.empty())
URBI_ROOT_FATAL(program_, 3,
"Unable to find Urbi SDK installation location. "
"Please set URBI_ROOT.");
// const std::string urbi_path = root_ / "share" / "gostai";
// xsetenv("URBI_PATH", xgetenv("URBI_PATH") + ":" + urbi_path, true);
// URBI_ROOT_DEBUG("append to URBI_PATH: " << urbi_path);
if (!static_build)
{
handle_libjpeg_ = library_load("jpeg");
handle_libport_ = library_load("port");
handle_libsched_ = library_load("sched");
handle_libserialize_ = library_load("serialize");
handle_liburbi_ = library_load("urbi");
}
}
RTLD_HANDLE
UrbiRoot::library_load(const std::string& base)
{
std::string envvar = "URBI_ROOT_LIB" + base;
foreach (char& s, envvar)
s = toupper(s);
return
xdlopen(program_,
xgetenv(envvar,
root(libdir / "lib" + base)));
}
std::string
UrbiRoot::root(const std::string& path) const
{
return root_ / path;
}
std::string
UrbiRoot::core_path(const std::string& path) const
{
return root_ / "gostai" / "core" / LIBPORT_URBI_HOST / path;
}
std::string
UrbiRoot::uobjects_path(const std::string& path) const
{
return core_path("uobjects" / path);
}
std::string
UrbiRoot::share_path(const std::string& path) const
{
return root_ / "share" / "gostai" / path;
}
void
UrbiRoot::load_plugin()
{
URBI_ROOT_DEBUG(program_, "loading plugin UObject implementation");
handle_libuobject_ = xdlopen(program_,
core_path() / "engine" / "libuobject");
}
/// Location of Urbi remote libuobject
void
UrbiRoot::load_remote()
{
URBI_ROOT_DEBUG(program_, "loading remote UObject implementation");
handle_libuobject_ = xdlopen(program_,
core_path() / "remote" / "libuobject");
}
void
UrbiRoot::load_custom(const std::string& path_)
{
std::string path = path_ / "libuobject";
URBI_ROOT_DEBUG(program_, "loading custom UObject implementation: " << path);
handle_libuobject_ = xdlopen(program_, path);
}
typedef int(*urbi_launch_type)(int, const char*[], UrbiRoot&);
int
UrbiRoot::urbi_launch(int argc, const char** argv)
{
URBI_ROOT_DEBUG(program_, "loading symbol urbi_launch from liburbi-launch");
// Reinterpret-cast fails with gcc3 arm
urbi_launch_type f = (urbi_launch_type)(dlsym(handle_liburbi_, "urbi_launch"));
if (!f)
URBI_ROOT_FATAL(program_, 2,
"cannot locate urbi_launch symbol: " << dlerror());
return f(argc, argv, *this);
}
int
UrbiRoot::urbi_launch(int argc, char** argv)
{
return urbi_launch(argc, const_cast<const char**>(argv));
}
typedef int(*urbi_main_type)(const std::vector<std::string>& args,
UrbiRoot& root,
bool block, bool errors);
int
UrbiRoot::urbi_main(const std::vector<std::string>& args,
bool block, bool errors)
{
URBI_ROOT_DEBUG(program_, "loading symbol urbi_main_args from libuobject");
// Reinterpret-cast fails with gcc3 arm
urbi_main_type f =
(urbi_main_type)(dlsym(handle_libuobject_, "urbi_main_args"));
if (!f)
URBI_ROOT_FATAL(program_, 2,
"cannot locate urbi_launch symbol: " << dlerror());
return f(args, *this, block, errors);
}
<|endoftext|>
|
<commit_before>/*
* Copyright Andrey Semashev 2007 - 2013.
* 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)
*/
#include <boost/config/abi_prefix.hpp>
#if !defined(BOOST_LOG_ENABLE_WARNINGS)
#if defined(_MSC_VER)
#pragma warning(push, 3)
// 'm_A' : class 'A' needs to have dll-interface to be used by clients of class 'B'
#pragma warning(disable: 4251)
// non dll-interface class 'A' used as base for dll-interface class 'B'
#pragma warning(disable: 4275)
// switch statement contains 'default' but no 'case' labels
#pragma warning(disable: 4065)
// 'this' : used in base member initializer list
#pragma warning(disable: 4355)
// 'int' : forcing value to bool 'true' or 'false' (performance warning)
#pragma warning(disable: 4800)
// unreferenced formal parameter
#pragma warning(disable: 4100)
// conditional expression is constant
#pragma warning(disable: 4127)
// default constructor could not be generated
#pragma warning(disable: 4510)
// copy constructor could not be generated
#pragma warning(disable: 4511)
// assignment operator could not be generated
#pragma warning(disable: 4512)
// struct 'A' can never be instantiated - user defined constructor required
#pragma warning(disable: 4610)
// function marked as __forceinline not inlined
#pragma warning(disable: 4714)
#elif defined(__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__) >= 406
#pragma GCC diagnostic push
// 'var' defined but not used
#pragma GCC diagnostic ignored "-Wunused-variable"
// unused parameter 'arg'
#pragma GCC diagnostic ignored "-Wunused-parameter"
// missing initializer for member var
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
#if (__GNUC__ * 100 + __GNUC_MINOR__) >= 407
// typedef ‘foo’ locally defined but not used
#pragma GCC diagnostic ignored "-Wunused-local-typedefs"
#endif
#endif
#endif // !defined(BOOST_LOG_ENABLE_WARNINGS)
<commit_msg>Disabled warning suppression pragmas for Intel compiler since it doesn't support them.<commit_after>/*
* Copyright Andrey Semashev 2007 - 2013.
* 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)
*/
#include <boost/config/abi_prefix.hpp>
#if !defined(BOOST_LOG_ENABLE_WARNINGS)
#if defined(_MSC_VER)
#pragma warning(push, 3)
// 'm_A' : class 'A' needs to have dll-interface to be used by clients of class 'B'
#pragma warning(disable: 4251)
// non dll-interface class 'A' used as base for dll-interface class 'B'
#pragma warning(disable: 4275)
// switch statement contains 'default' but no 'case' labels
#pragma warning(disable: 4065)
// 'this' : used in base member initializer list
#pragma warning(disable: 4355)
// 'int' : forcing value to bool 'true' or 'false' (performance warning)
#pragma warning(disable: 4800)
// unreferenced formal parameter
#pragma warning(disable: 4100)
// conditional expression is constant
#pragma warning(disable: 4127)
// default constructor could not be generated
#pragma warning(disable: 4510)
// copy constructor could not be generated
#pragma warning(disable: 4511)
// assignment operator could not be generated
#pragma warning(disable: 4512)
// struct 'A' can never be instantiated - user defined constructor required
#pragma warning(disable: 4610)
// function marked as __forceinline not inlined
#pragma warning(disable: 4714)
#elif defined(__GNUC__) && !(defined(__INTEL_COMPILER) || defined(__ICL) || defined(__ICC) || defined(__ECC)) \
&& (__GNUC__ * 100 + __GNUC_MINOR__) >= 406
#pragma GCC diagnostic push
// 'var' defined but not used
#pragma GCC diagnostic ignored "-Wunused-variable"
// unused parameter 'arg'
#pragma GCC diagnostic ignored "-Wunused-parameter"
// missing initializer for member var
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
#if (__GNUC__ * 100 + __GNUC_MINOR__) >= 407
// typedef ‘foo’ locally defined but not used
#pragma GCC diagnostic ignored "-Wunused-local-typedefs"
#endif
#endif
#endif // !defined(BOOST_LOG_ENABLE_WARNINGS)
<|endoftext|>
|
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* Razor - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2012 Razor team
* Authors:
* Kuzma Shapran <kuzma.shapran@gmail.com>
* Luís Pereira <luis.artur.pereira@gmail.com>
*
* This program or library is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*
* END_COMMON_COPYRIGHT_HEADER */
#include "calendar_utils.h"
#include "config.h"
#include <QtCore/QtGlobal>
#if QT_VERSION < 0x040800
#ifdef CAN_USE_BOOST
#include <boost/locale/date_time.hpp>
Qt::DayOfWeek firstDayOfWeek(void)
{
return (boost::locale::calendar().first_day_of_week() + 6) % 7;
}
#else // use C
#ifdef HAVE__NL_TIME_FIRST_WEEKDAY
#include <langinfo.h>
#include <QtCore/QDebug>
#endif
Qt::DayOfWeek firstDayOfWeek(void)
{
#ifdef HAVE__NL_TIME_FIRST_WEEKDAY
int firstWeekDay;
int weekFirstDay = 0;
int weekStart;
long weekFirstDayLong;
firstWeekDay = nl_langinfo(_NL_TIME_FIRST_WEEKDAY)[0];
weekFirstDayLong = (long) nl_langinfo(_NL_TIME_WEEK_1STDAY);
if (weekFirstDayLong == 19971130L) // Sunday
{
weekFirstDay = 0;
}
else if (weekFirstDayLong == 19971201L) // Monday
{
weekFirstDay = 1;
}
else
{
qDebug() << Q_FUNC_INFO <<
"nl_langinfo(_NL_TIME_WEEK_1STDAY) returned an unknown value.";
}
weekStart = (weekFirstDay + firstWeekDay - 1) % 7;
if (weekStart == 0)
{
return Qt::Sunday;
}
else
{
return static_cast<Qt::DayOfWeek>(weekStart);
}
#else
return Qt::Sunday;
#endif // HAVE__NL_TIME_FIRST_WEEKDAY
}
#endif
#else // use Qt >= 4.8
Qt::DayOfWeek firstDayOfWeek(void)
{
return QLocale::system().firstDayOfWeek();
}
#endif
<commit_msg>plugin-clock: Add documentation to firstDayOfWeek()<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* Razor - a lightweight, Qt based, desktop toolset
* http://razor-qt.org
*
* Copyright: 2012 Razor team
* Authors:
* Kuzma Shapran <kuzma.shapran@gmail.com>
* Luís Pereira <luis.artur.pereira@gmail.com>
*
* This program or library is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*
* END_COMMON_COPYRIGHT_HEADER */
#include "calendar_utils.h"
#include "config.h"
#include <QtCore/QtGlobal>
#if QT_VERSION < 0x040800
#ifdef CAN_USE_BOOST
#include <boost/locale/date_time.hpp>
Qt::DayOfWeek firstDayOfWeek(void)
{
return (boost::locale::calendar().first_day_of_week() + 6) % 7;
}
#else // use C
#ifdef HAVE__NL_TIME_FIRST_WEEKDAY
#include <langinfo.h>
#include <QtCore/QDebug>
#endif
Qt::DayOfWeek firstDayOfWeek(void)
{
#ifdef HAVE__NL_TIME_FIRST_WEEKDAY
int firstWeekDay;
int weekFirstDay = 0;
int weekStart;
long weekFirstDayLong;
// firstWeekDay: Specifies the offset of the first day-of-week in the day
// weekFirstDay: Some date that corresponds to the beginning of a week.
// Specifies the base of the day list. It is (in glibc) either
// 19971130 (Sunday) or 19971201 (Monday)
firstWeekDay = nl_langinfo(_NL_TIME_FIRST_WEEKDAY)[0];
weekFirstDayLong = (long) nl_langinfo(_NL_TIME_WEEK_1STDAY);
if (weekFirstDayLong == 19971130L) // Sunday
{
weekFirstDay = 0;
}
else if (weekFirstDayLong == 19971201L) // Monday
{
weekFirstDay = 1;
}
else
{
qDebug() << Q_FUNC_INFO <<
"nl_langinfo(_NL_TIME_WEEK_1STDAY) returned an unknown value.";
}
weekStart = (weekFirstDay + firstWeekDay - 1) % 7;
if (weekStart == 0)
{
return Qt::Sunday;
}
else
{
return static_cast<Qt::DayOfWeek>(weekStart);
}
#else
return Qt::Sunday;
#endif // HAVE__NL_TIME_FIRST_WEEKDAY
}
#endif
#else // use Qt >= 4.8
Qt::DayOfWeek firstDayOfWeek(void)
{
return QLocale::system().firstDayOfWeek();
}
#endif
<|endoftext|>
|
<commit_before>//===--- LiveRangeEdit.cpp - Basic tools for editing a register live range --===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// The LiveRangeEdit class represents changes done to a virtual register when it
// is spilled or split.
//===----------------------------------------------------------------------===//
#include "LiveRangeEdit.h"
#include "VirtRegMap.h"
#include "llvm/CodeGen/LiveIntervalAnalysis.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/Target/TargetInstrInfo.h"
using namespace llvm;
int LiveRangeEdit::assignStackSlot(VirtRegMap &vrm) {
int ss = vrm.getStackSlot(getReg());
if (ss != VirtRegMap::NO_STACK_SLOT)
return ss;
return vrm.assignVirt2StackSlot(getReg());
}
LiveInterval &LiveRangeEdit::create(MachineRegisterInfo &mri,
LiveIntervals &lis,
VirtRegMap &vrm) {
const TargetRegisterClass *RC = mri.getRegClass(parent_.reg);
unsigned VReg = mri.createVirtualRegister(RC);
vrm.grow();
// Immediately assign to the same stack slot as parent.
vrm.assignVirt2StackSlot(VReg, assignStackSlot(vrm));
LiveInterval &li = lis.getOrCreateInterval(VReg);
newRegs_.push_back(&li);
return li;
}
void LiveRangeEdit::scanRemattable(LiveIntervals &lis,
const TargetInstrInfo &tii,
AliasAnalysis *aa) {
for (LiveInterval::vni_iterator I = parent_.vni_begin(),
E = parent_.vni_end(); I != E; ++I) {
VNInfo *VNI = *I;
if (VNI->isUnused())
continue;
MachineInstr *DefMI = lis.getInstructionFromIndex(VNI->def);
if (!DefMI)
continue;
if (tii.isTriviallyReMaterializable(DefMI, aa))
remattable_.insert(VNI);
}
scannedRemattable_ = true;
}
bool LiveRangeEdit::anyRematerializable(LiveIntervals &lis,
const TargetInstrInfo &tii,
AliasAnalysis *aa) {
if (!scannedRemattable_)
scanRemattable(lis, tii, aa);
return !remattable_.empty();
}
/// allUsesAvailableAt - Return true if all registers used by OrigMI at
/// OrigIdx are also available with the same value at UseIdx.
bool LiveRangeEdit::allUsesAvailableAt(const MachineInstr *OrigMI,
SlotIndex OrigIdx,
SlotIndex UseIdx,
LiveIntervals &lis) {
OrigIdx = OrigIdx.getUseIndex();
UseIdx = UseIdx.getUseIndex();
for (unsigned i = 0, e = OrigMI->getNumOperands(); i != e; ++i) {
const MachineOperand &MO = OrigMI->getOperand(i);
if (!MO.isReg() || !MO.getReg() || MO.getReg() == getReg())
continue;
// Reserved registers are OK.
if (MO.isUndef() || !lis.hasInterval(MO.getReg()))
continue;
// We don't want to move any defs.
if (MO.isDef())
return false;
// We cannot depend on virtual registers in uselessRegs_.
for (unsigned ui = 0, ue = uselessRegs_.size(); ui != ue; ++ui)
if (uselessRegs_[ui]->reg == MO.getReg())
return false;
LiveInterval &li = lis.getInterval(MO.getReg());
const VNInfo *OVNI = li.getVNInfoAt(OrigIdx);
if (!OVNI)
continue;
if (OVNI != li.getVNInfoAt(UseIdx))
return false;
}
return true;
}
LiveRangeEdit::Remat LiveRangeEdit::canRematerializeAt(VNInfo *ParentVNI,
SlotIndex UseIdx,
bool cheapAsAMove,
LiveIntervals &lis) {
assert(scannedRemattable_ && "Call anyRematerializable first");
Remat RM = { 0, 0 };
// We could remat an undefined value as IMPLICIT_DEF, but all that should have
// been taken care of earlier.
if (!(RM.ParentVNI = parent_.getVNInfoAt(UseIdx)))
return RM;
// Use scanRemattable info.
if (!remattable_.count(RM.ParentVNI))
return RM;
// No defining instruction.
MachineInstr *OrigMI = lis.getInstructionFromIndex(RM.ParentVNI->def);
assert(OrigMI && "Defining instruction for remattable value disappeared");
// If only cheap remats were requested, bail out early.
if (cheapAsAMove && !OrigMI->getDesc().isAsCheapAsAMove())
return RM;
// Verify that all used registers are available with the same values.
if (!allUsesAvailableAt(OrigMI, RM.ParentVNI->def, UseIdx, lis))
return RM;
RM.OrigMI = OrigMI;
return RM;
}
SlotIndex LiveRangeEdit::rematerializeAt(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
unsigned DestReg,
const Remat &RM,
LiveIntervals &lis,
const TargetInstrInfo &tii,
const TargetRegisterInfo &tri) {
assert(RM.OrigMI && "Invalid remat");
tii.reMaterialize(MBB, MI, DestReg, 0, RM.OrigMI, tri);
return lis.InsertMachineInstrInMaps(--MI).getDefIndex();
}
<commit_msg>Remember to keep track of rematted values.<commit_after>//===--- LiveRangeEdit.cpp - Basic tools for editing a register live range --===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// The LiveRangeEdit class represents changes done to a virtual register when it
// is spilled or split.
//===----------------------------------------------------------------------===//
#include "LiveRangeEdit.h"
#include "VirtRegMap.h"
#include "llvm/CodeGen/LiveIntervalAnalysis.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/Target/TargetInstrInfo.h"
using namespace llvm;
int LiveRangeEdit::assignStackSlot(VirtRegMap &vrm) {
int ss = vrm.getStackSlot(getReg());
if (ss != VirtRegMap::NO_STACK_SLOT)
return ss;
return vrm.assignVirt2StackSlot(getReg());
}
LiveInterval &LiveRangeEdit::create(MachineRegisterInfo &mri,
LiveIntervals &lis,
VirtRegMap &vrm) {
const TargetRegisterClass *RC = mri.getRegClass(parent_.reg);
unsigned VReg = mri.createVirtualRegister(RC);
vrm.grow();
// Immediately assign to the same stack slot as parent.
vrm.assignVirt2StackSlot(VReg, assignStackSlot(vrm));
LiveInterval &li = lis.getOrCreateInterval(VReg);
newRegs_.push_back(&li);
return li;
}
void LiveRangeEdit::scanRemattable(LiveIntervals &lis,
const TargetInstrInfo &tii,
AliasAnalysis *aa) {
for (LiveInterval::vni_iterator I = parent_.vni_begin(),
E = parent_.vni_end(); I != E; ++I) {
VNInfo *VNI = *I;
if (VNI->isUnused())
continue;
MachineInstr *DefMI = lis.getInstructionFromIndex(VNI->def);
if (!DefMI)
continue;
if (tii.isTriviallyReMaterializable(DefMI, aa))
remattable_.insert(VNI);
}
scannedRemattable_ = true;
}
bool LiveRangeEdit::anyRematerializable(LiveIntervals &lis,
const TargetInstrInfo &tii,
AliasAnalysis *aa) {
if (!scannedRemattable_)
scanRemattable(lis, tii, aa);
return !remattable_.empty();
}
/// allUsesAvailableAt - Return true if all registers used by OrigMI at
/// OrigIdx are also available with the same value at UseIdx.
bool LiveRangeEdit::allUsesAvailableAt(const MachineInstr *OrigMI,
SlotIndex OrigIdx,
SlotIndex UseIdx,
LiveIntervals &lis) {
OrigIdx = OrigIdx.getUseIndex();
UseIdx = UseIdx.getUseIndex();
for (unsigned i = 0, e = OrigMI->getNumOperands(); i != e; ++i) {
const MachineOperand &MO = OrigMI->getOperand(i);
if (!MO.isReg() || !MO.getReg() || MO.getReg() == getReg())
continue;
// Reserved registers are OK.
if (MO.isUndef() || !lis.hasInterval(MO.getReg()))
continue;
// We don't want to move any defs.
if (MO.isDef())
return false;
// We cannot depend on virtual registers in uselessRegs_.
for (unsigned ui = 0, ue = uselessRegs_.size(); ui != ue; ++ui)
if (uselessRegs_[ui]->reg == MO.getReg())
return false;
LiveInterval &li = lis.getInterval(MO.getReg());
const VNInfo *OVNI = li.getVNInfoAt(OrigIdx);
if (!OVNI)
continue;
if (OVNI != li.getVNInfoAt(UseIdx))
return false;
}
return true;
}
LiveRangeEdit::Remat LiveRangeEdit::canRematerializeAt(VNInfo *ParentVNI,
SlotIndex UseIdx,
bool cheapAsAMove,
LiveIntervals &lis) {
assert(scannedRemattable_ && "Call anyRematerializable first");
Remat RM = { 0, 0 };
// We could remat an undefined value as IMPLICIT_DEF, but all that should have
// been taken care of earlier.
if (!(RM.ParentVNI = parent_.getVNInfoAt(UseIdx)))
return RM;
// Use scanRemattable info.
if (!remattable_.count(RM.ParentVNI))
return RM;
// No defining instruction.
MachineInstr *OrigMI = lis.getInstructionFromIndex(RM.ParentVNI->def);
assert(OrigMI && "Defining instruction for remattable value disappeared");
// If only cheap remats were requested, bail out early.
if (cheapAsAMove && !OrigMI->getDesc().isAsCheapAsAMove())
return RM;
// Verify that all used registers are available with the same values.
if (!allUsesAvailableAt(OrigMI, RM.ParentVNI->def, UseIdx, lis))
return RM;
RM.OrigMI = OrigMI;
return RM;
}
SlotIndex LiveRangeEdit::rematerializeAt(MachineBasicBlock &MBB,
MachineBasicBlock::iterator MI,
unsigned DestReg,
const Remat &RM,
LiveIntervals &lis,
const TargetInstrInfo &tii,
const TargetRegisterInfo &tri) {
assert(RM.OrigMI && "Invalid remat");
tii.reMaterialize(MBB, MI, DestReg, 0, RM.OrigMI, tri);
rematted_.insert(RM.ParentVNI);
return lis.InsertMachineInstrInMaps(--MI).getDefIndex();
}
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
/*!
* \file sgd_context.hpp
* \brief Stochastic Gradient Descent (SGD) context Implementation.
*/
#pragma once
#include "etl/etl.hpp"
#include "dll/layer_traits.hpp"
#include "dll/dbn_traits.hpp"
namespace dll {
/*!
* \copydoc sgd_context
*/
template <typename DBN, typename Layer>
struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_dense_layer() && !layer_traits<Layer>::is_dynamic()>> {
using layer_t = Layer;
using weight = typename layer_t::weight;
static constexpr const auto num_visible = layer_t::num_visible;
static constexpr const auto num_hidden = layer_t::num_hidden;
static constexpr const auto batch_size = DBN::batch_size;
etl::fast_matrix<weight, num_visible, num_hidden> w_grad;
etl::fast_matrix<weight, num_hidden> b_grad;
etl::fast_matrix<weight, num_visible, num_hidden> w_inc;
etl::fast_matrix<weight, num_hidden> b_inc;
etl::fast_matrix<weight, batch_size, num_hidden> output;
etl::fast_matrix<weight, batch_size, num_hidden> errors;
sgd_context()
: w_inc(0.0), b_inc(0.0), output(0.0), errors(0.0) {}
};
/*!
* \copydoc sgd_context
*/
template <typename DBN, typename Layer>
struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_dense_layer() && layer_traits<Layer>::is_dynamic()>> {
using layer_t = Layer;
using weight = typename layer_t::weight;
static constexpr const auto batch_size = DBN::batch_size;
etl::dyn_matrix<weight, 2> w_grad;
etl::dyn_matrix<weight, 1> b_grad;
etl::dyn_matrix<weight, 2> w_inc;
etl::dyn_matrix<weight, 1> b_inc;
etl::dyn_matrix<weight, 2> output;
etl::dyn_matrix<weight, 2> errors;
sgd_context(std::size_t num_visible, std::size_t num_hidden)
: w_grad(num_visible, num_hidden), b_grad(num_hidden),
w_inc(num_visible, num_hidden, 0.0), b_inc(num_hidden, 0.0),
output(batch_size, num_hidden, 0.0), errors(batch_size, num_hidden, 0.0) {}
};
/*!
* \copydoc sgd_context
*/
template <typename DBN, typename Layer>
struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_convolutional_layer() && !layer_traits<Layer>::is_dynamic()>> {
using layer_t = Layer;
using weight = typename layer_t::weight;
static_assert(!layer_traits<layer_t>::has_probabilistic_max_pooling(), "Probabilistic Max Pooling is not supported in backpropagation");
static constexpr const std::size_t NV1 = layer_t::NV1;
static constexpr const std::size_t NV2 = layer_t::NV2;
static constexpr const std::size_t NH1 = layer_t::NH1;
static constexpr const std::size_t NH2 = layer_t::NH2;
static constexpr const std::size_t NW1 = layer_t::NW1;
static constexpr const std::size_t NW2 = layer_t::NW2;
static constexpr const std::size_t NC = layer_t::NC;
static constexpr const std::size_t K = layer_t::K;
static constexpr const auto batch_size = DBN::batch_size;
etl::fast_matrix<weight, K, NC, NW1, NW2> w_grad;
etl::fast_matrix<weight, K> b_grad;
etl::fast_matrix<weight, K, NC, NW1, NW2> w_inc;
etl::fast_matrix<weight, K> b_inc;
etl::fast_matrix<weight, batch_size, K, NH1, NH2> output;
etl::fast_matrix<weight, batch_size, K, NH1, NH2> errors;
sgd_context()
: w_inc(0.0), b_inc(0.0), output(0.0), errors(0.0) {}
};
/*!
* \copydoc sgd_context
*/
template <typename DBN, typename Layer>
struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_convolutional_layer() && layer_traits<Layer>::is_dynamic()>> {
using layer_t = Layer;
using weight = typename layer_t::weight;
static_assert(!layer_traits<layer_t>::has_probabilistic_max_pooling(), "Probabilistic Max Pooling is not supported in backpropagation");
static constexpr const auto batch_size = DBN::batch_size;
etl::dyn_matrix<weight, 4> w_grad;
etl::dyn_matrix<weight, 1> b_grad;
etl::dyn_matrix<weight, 4> w_inc;
etl::dyn_matrix<weight, 1> b_inc;
etl::dyn_matrix<weight, 4> output;
etl::dyn_matrix<weight, 4> errors;
sgd_context(size_t nc, size_t nv1, size_t nv2, size_t k, size_t nh1, size_t nh2)
: w_grad(k, nc, nv1 - nh1 + 1, nv2 - nh2 + 1), b_grad(k),
w_inc(k, nc, nv1 - nh1 + 1, nv2 - nh2 + 1), b_inc(k),
output(batch_size, k, nh1, nh2), errors(batch_size, k, nh1, nh2) {}
};
/*!
* \copydoc sgd_context
*/
template <typename DBN, typename Layer>
struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_pooling_layer() && !layer_traits<Layer>::is_dynamic()>> {
using layer_t = Layer;
using weight = typename layer_t::weight;
static constexpr const std::size_t I1 = layer_t::I1;
static constexpr const std::size_t I2 = layer_t::I2;
static constexpr const std::size_t I3 = layer_t::I3;
static constexpr const std::size_t O1 = layer_t::O1;
static constexpr const std::size_t O2 = layer_t::O2;
static constexpr const std::size_t O3 = layer_t::O3;
static constexpr const auto batch_size = DBN::batch_size;
etl::fast_matrix<weight, batch_size, I1, I2, I3> input;
etl::fast_matrix<weight, batch_size, O1, O2, O3> output;
etl::fast_matrix<weight, batch_size, O1, O2, O3> errors;
};
/*!
* \copydoc sgd_context
*/
template <typename DBN, typename Layer>
struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_pooling_layer() && layer_traits<Layer>::is_dynamic()>> {
using layer_t = Layer;
using weight = typename layer_t::weight;
static constexpr const auto batch_size = DBN::batch_size;
etl::dyn_matrix<weight, 4> input;
etl::dyn_matrix<weight, 4> output;
etl::dyn_matrix<weight, 4> errors;
sgd_context(size_t i1, size_t i2, size_t i3, size_t c1, size_t c2, size_t c3)
: input(batch_size, i1, i2, i3),
output(batch_size, i1 / c1, i2 / c2, i3 / c3),
errors(batch_size, i1 / c1, i2 / c2, i3 / c3) {}
};
template <typename DBN, typename Layer>
struct transform_output_type {
static constexpr const auto dimensions = dbn_traits<DBN>::is_convolutional() ? 4 : 2;
using weight = typename DBN::weight;
using type = etl::dyn_matrix<weight, dimensions>;
};
template <typename DBN, typename Layer>
using transform_output_type_t = typename transform_output_type<DBN, Layer>::type;
/*!
* \copydoc sgd_context
*/
template <typename DBN, typename Layer>
struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_transform_layer()>> {
using layer_t = Layer;
using weight = typename DBN::weight;
using inputs_t = transform_output_type_t<DBN, Layer>;
inputs_t output;
inputs_t errors;
};
} //end of dll namespace
<commit_msg>Unify sgd_context<commit_after>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
/*!
* \file sgd_context.hpp
* \brief Stochastic Gradient Descent (SGD) context Implementation.
*/
#pragma once
#include "etl/etl.hpp"
#include "dll/layer_traits.hpp"
#include "dll/dbn_traits.hpp"
namespace dll {
/*!
* \copydoc sgd_context
*/
template <typename DBN, typename Layer>
struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_dense_layer() && !layer_traits<Layer>::is_dynamic()>> {
using layer_t = Layer;
using weight = typename layer_t::weight;
static constexpr const auto num_visible = layer_t::num_visible;
static constexpr const auto num_hidden = layer_t::num_hidden;
static constexpr const auto batch_size = DBN::batch_size;
etl::fast_matrix<weight, num_visible, num_hidden> w_grad;
etl::fast_matrix<weight, num_hidden> b_grad;
etl::fast_matrix<weight, num_visible, num_hidden> w_inc;
etl::fast_matrix<weight, num_hidden> b_inc;
etl::fast_matrix<weight, batch_size, num_visible> input;
etl::fast_matrix<weight, batch_size, num_hidden> output;
etl::fast_matrix<weight, batch_size, num_hidden> errors;
sgd_context()
: w_inc(0.0), b_inc(0.0), output(0.0), errors(0.0) {}
};
/*!
* \copydoc sgd_context
*/
template <typename DBN, typename Layer>
struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_dense_layer() && layer_traits<Layer>::is_dynamic()>> {
using layer_t = Layer;
using weight = typename layer_t::weight;
static constexpr const auto batch_size = DBN::batch_size;
etl::dyn_matrix<weight, 2> w_grad;
etl::dyn_matrix<weight, 1> b_grad;
etl::dyn_matrix<weight, 2> w_inc;
etl::dyn_matrix<weight, 1> b_inc;
etl::dyn_matrix<weight, 2> input;
etl::dyn_matrix<weight, 2> output;
etl::dyn_matrix<weight, 2> errors;
sgd_context(std::size_t num_visible, std::size_t num_hidden)
: w_grad(num_visible, num_hidden), b_grad(num_hidden),
w_inc(num_visible, num_hidden, 0.0), b_inc(num_hidden, 0.0),
input(batch_size, num_visible, 0.0), output(batch_size, num_hidden, 0.0), errors(batch_size, num_hidden, 0.0) {}
};
/*!
* \copydoc sgd_context
*/
template <typename DBN, typename Layer>
struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_convolutional_layer() && !layer_traits<Layer>::is_dynamic()>> {
using layer_t = Layer;
using weight = typename layer_t::weight;
static_assert(!layer_traits<layer_t>::has_probabilistic_max_pooling(), "Probabilistic Max Pooling is not supported in backpropagation");
static constexpr const std::size_t NV1 = layer_t::NV1;
static constexpr const std::size_t NV2 = layer_t::NV2;
static constexpr const std::size_t NH1 = layer_t::NH1;
static constexpr const std::size_t NH2 = layer_t::NH2;
static constexpr const std::size_t NW1 = layer_t::NW1;
static constexpr const std::size_t NW2 = layer_t::NW2;
static constexpr const std::size_t NC = layer_t::NC;
static constexpr const std::size_t K = layer_t::K;
static constexpr const auto batch_size = DBN::batch_size;
etl::fast_matrix<weight, K, NC, NW1, NW2> w_grad;
etl::fast_matrix<weight, K> b_grad;
etl::fast_matrix<weight, K, NC, NW1, NW2> w_inc;
etl::fast_matrix<weight, K> b_inc;
etl::fast_matrix<weight, batch_size, NC, NV1, NV2> input;
etl::fast_matrix<weight, batch_size, K, NH1, NH2> output;
etl::fast_matrix<weight, batch_size, K, NH1, NH2> errors;
sgd_context()
: w_inc(0.0), b_inc(0.0), output(0.0), errors(0.0) {}
};
/*!
* \copydoc sgd_context
*/
template <typename DBN, typename Layer>
struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_convolutional_layer() && layer_traits<Layer>::is_dynamic()>> {
using layer_t = Layer;
using weight = typename layer_t::weight;
static_assert(!layer_traits<layer_t>::has_probabilistic_max_pooling(), "Probabilistic Max Pooling is not supported in backpropagation");
static constexpr const auto batch_size = DBN::batch_size;
etl::dyn_matrix<weight, 4> w_grad;
etl::dyn_matrix<weight, 1> b_grad;
etl::dyn_matrix<weight, 4> w_inc;
etl::dyn_matrix<weight, 1> b_inc;
etl::dyn_matrix<weight, 4> input;
etl::dyn_matrix<weight, 4> output;
etl::dyn_matrix<weight, 4> errors;
sgd_context(size_t nc, size_t nv1, size_t nv2, size_t k, size_t nh1, size_t nh2)
: w_grad(k, nc, nv1 - nh1 + 1, nv2 - nh2 + 1), b_grad(k),
w_inc(k, nc, nv1 - nh1 + 1, nv2 - nh2 + 1), b_inc(k),
input(batch_size, nc, nv1, nv2),
output(batch_size, k, nh1, nh2), errors(batch_size, k, nh1, nh2) {}
};
/*!
* \copydoc sgd_context
*/
template <typename DBN, typename Layer>
struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_pooling_layer() && !layer_traits<Layer>::is_dynamic()>> {
using layer_t = Layer;
using weight = typename layer_t::weight;
static constexpr const std::size_t I1 = layer_t::I1;
static constexpr const std::size_t I2 = layer_t::I2;
static constexpr const std::size_t I3 = layer_t::I3;
static constexpr const std::size_t O1 = layer_t::O1;
static constexpr const std::size_t O2 = layer_t::O2;
static constexpr const std::size_t O3 = layer_t::O3;
static constexpr const auto batch_size = DBN::batch_size;
etl::fast_matrix<weight, batch_size, I1, I2, I3> input;
etl::fast_matrix<weight, batch_size, O1, O2, O3> output;
etl::fast_matrix<weight, batch_size, O1, O2, O3> errors;
};
/*!
* \copydoc sgd_context
*/
template <typename DBN, typename Layer>
struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_pooling_layer() && layer_traits<Layer>::is_dynamic()>> {
using layer_t = Layer;
using weight = typename layer_t::weight;
static constexpr const auto batch_size = DBN::batch_size;
etl::dyn_matrix<weight, 4> input;
etl::dyn_matrix<weight, 4> output;
etl::dyn_matrix<weight, 4> errors;
sgd_context(size_t i1, size_t i2, size_t i3, size_t c1, size_t c2, size_t c3)
: input(batch_size, i1, i2, i3),
output(batch_size, i1 / c1, i2 / c2, i3 / c3),
errors(batch_size, i1 / c1, i2 / c2, i3 / c3) {}
};
template <typename DBN, typename Layer>
struct transform_output_type {
static constexpr const auto dimensions = dbn_traits<DBN>::is_convolutional() ? 4 : 2;
using weight = typename DBN::weight;
using type = etl::dyn_matrix<weight, dimensions>;
};
template <typename DBN, typename Layer>
using transform_output_type_t = typename transform_output_type<DBN, Layer>::type;
/*!
* \copydoc sgd_context
*/
template <typename DBN, typename Layer>
struct sgd_context<DBN, Layer, std::enable_if_t<layer_traits<Layer>::is_transform_layer()>> {
using layer_t = Layer;
using weight = typename DBN::weight;
using inputs_t = transform_output_type_t<DBN, Layer>;
inputs_t input;
inputs_t output;
inputs_t errors;
};
} //end of dll namespace
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 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 "base/utf_string_conversions.h"
#include "chrome/browser/password_manager/password_form_data.h"
#include "chrome/browser/sync/profile_sync_service_harness.h"
#include "chrome/browser/sync/sessions/session_state.h"
#include "chrome/test/live_sync/live_passwords_sync_test.h"
using webkit_glue::PasswordForm;
static const char* kValidPassphrase = "passphrase!";
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, Add) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
PasswordForm form = CreateTestPasswordForm(0);
AddLogin(GetVerifierPasswordStore(), form);
AddLogin(GetPasswordStore(0), form);
std::vector<PasswordForm> verifier_forms;
GetLogins(GetVerifierPasswordStore(), verifier_forms);
ASSERT_EQ(1U, verifier_forms.size());
ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));
std::vector<PasswordForm> forms0;
GetLogins(GetPasswordStore(0), forms0);
ASSERT_TRUE(ContainsSamePasswordForms(verifier_forms, forms0));
std::vector<PasswordForm> forms1;
GetLogins(GetPasswordStore(1), forms1);
ASSERT_TRUE(ContainsSamePasswordForms(verifier_forms, forms1));
}
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, Race) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
PasswordForm form0 = CreateTestPasswordForm(0);
AddLogin(GetPasswordStore(0), form0);
PasswordForm form1 = form0;
form1.password_value = ASCIIToUTF16("password1");
AddLogin(GetPasswordStore(1), form1);
ASSERT_TRUE(AwaitQuiescence());
std::vector<PasswordForm> forms0;
GetLogins(GetPasswordStore(0), forms0);
ASSERT_EQ(1U, forms0.size());
std::vector<PasswordForm> forms1;
GetLogins(GetPasswordStore(1), forms1);
ASSERT_EQ(1U, forms1.size());
ASSERT_TRUE(ContainsSamePasswordForms(forms0, forms1));
}
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, SetPassphrase) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
SetPassphrase(0, kValidPassphrase, true);
ASSERT_TRUE(GetClient(0)->AwaitPassphraseAccepted());
ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));
SetPassphrase(1, kValidPassphrase, false);
ASSERT_TRUE(GetClient(1)->AwaitPassphraseAccepted());
}
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest,
SetPassphraseAndAddPassword) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
SetPassphrase(0, kValidPassphrase, true);
ASSERT_TRUE(GetClient(0)->AwaitPassphraseAccepted());
ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));
SetPassphrase(1, kValidPassphrase, false);
ASSERT_TRUE(GetClient(1)->AwaitPassphraseAccepted());
PasswordForm form = CreateTestPasswordForm(0);
AddLogin(GetPasswordStore(0), form);
std::vector<PasswordForm> forms0;
GetLogins(GetPasswordStore(0), forms0);
ASSERT_EQ(1U, forms0.size());
ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));
std::vector<PasswordForm> forms1;
GetLogins(GetPasswordStore(1), forms1);
ASSERT_EQ(1U, forms1.size());
}
// TODO(rsimha): This test fails on mac -- see http://crbug.com/77956.
#if defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest,
FAILS_SetPassphraseAndThenSetupSync) {
#else
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest,
SetPassphraseAndThenSetupSync) {
#endif
ASSERT_TRUE(SetupClients()) << "SetupClients() failed.";
ASSERT_TRUE(GetClient(0)->SetupSync());
SetPassphrase(0, kValidPassphrase, true);
ASSERT_TRUE(GetClient(0)->AwaitPassphraseAccepted());
ASSERT_TRUE(GetClient(0)->AwaitSyncCycleCompletion("Initial sync."));
SetPassphrase(1, kValidPassphrase, false);
ASSERT_TRUE(GetClient(1)->SetupSync());
ASSERT_TRUE(GetClient(1)->AwaitPassphraseAccepted());
}
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, SetPassphraseTwice) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
SetPassphrase(0, kValidPassphrase, true);
ASSERT_TRUE(GetClient(0)->AwaitPassphraseAccepted());
ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));
SetPassphrase(1, kValidPassphrase, false);
ASSERT_TRUE(GetClient(1)->AwaitPassphraseAccepted());
SetPassphrase(1, kValidPassphrase, false);
ASSERT_TRUE(GetClient(1)->AwaitPassphraseAccepted());
}
<commit_msg>Marking sync test SetPassphraseAndThenSetupSync as failing.<commit_after>// Copyright (c) 2011 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 "base/utf_string_conversions.h"
#include "chrome/browser/password_manager/password_form_data.h"
#include "chrome/browser/sync/profile_sync_service_harness.h"
#include "chrome/browser/sync/sessions/session_state.h"
#include "chrome/test/live_sync/live_passwords_sync_test.h"
using webkit_glue::PasswordForm;
static const char* kValidPassphrase = "passphrase!";
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, Add) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
PasswordForm form = CreateTestPasswordForm(0);
AddLogin(GetVerifierPasswordStore(), form);
AddLogin(GetPasswordStore(0), form);
std::vector<PasswordForm> verifier_forms;
GetLogins(GetVerifierPasswordStore(), verifier_forms);
ASSERT_EQ(1U, verifier_forms.size());
ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));
std::vector<PasswordForm> forms0;
GetLogins(GetPasswordStore(0), forms0);
ASSERT_TRUE(ContainsSamePasswordForms(verifier_forms, forms0));
std::vector<PasswordForm> forms1;
GetLogins(GetPasswordStore(1), forms1);
ASSERT_TRUE(ContainsSamePasswordForms(verifier_forms, forms1));
}
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, Race) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
PasswordForm form0 = CreateTestPasswordForm(0);
AddLogin(GetPasswordStore(0), form0);
PasswordForm form1 = form0;
form1.password_value = ASCIIToUTF16("password1");
AddLogin(GetPasswordStore(1), form1);
ASSERT_TRUE(AwaitQuiescence());
std::vector<PasswordForm> forms0;
GetLogins(GetPasswordStore(0), forms0);
ASSERT_EQ(1U, forms0.size());
std::vector<PasswordForm> forms1;
GetLogins(GetPasswordStore(1), forms1);
ASSERT_EQ(1U, forms1.size());
ASSERT_TRUE(ContainsSamePasswordForms(forms0, forms1));
}
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, SetPassphrase) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
SetPassphrase(0, kValidPassphrase, true);
ASSERT_TRUE(GetClient(0)->AwaitPassphraseAccepted());
ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));
SetPassphrase(1, kValidPassphrase, false);
ASSERT_TRUE(GetClient(1)->AwaitPassphraseAccepted());
}
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest,
SetPassphraseAndAddPassword) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
SetPassphrase(0, kValidPassphrase, true);
ASSERT_TRUE(GetClient(0)->AwaitPassphraseAccepted());
ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));
SetPassphrase(1, kValidPassphrase, false);
ASSERT_TRUE(GetClient(1)->AwaitPassphraseAccepted());
PasswordForm form = CreateTestPasswordForm(0);
AddLogin(GetPasswordStore(0), form);
std::vector<PasswordForm> forms0;
GetLogins(GetPasswordStore(0), forms0);
ASSERT_EQ(1U, forms0.size());
ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));
std::vector<PasswordForm> forms1;
GetLogins(GetPasswordStore(1), forms1);
ASSERT_EQ(1U, forms1.size());
}
// TODO(rsimha): This test fails occasionally -- see http://crbug.com/77956.
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest,
FAILS_SetPassphraseAndThenSetupSync) {
ASSERT_TRUE(SetupClients()) << "SetupClients() failed.";
ASSERT_TRUE(GetClient(0)->SetupSync());
SetPassphrase(0, kValidPassphrase, true);
ASSERT_TRUE(GetClient(0)->AwaitPassphraseAccepted());
ASSERT_TRUE(GetClient(0)->AwaitSyncCycleCompletion("Initial sync."));
SetPassphrase(1, kValidPassphrase, false);
ASSERT_TRUE(GetClient(1)->SetupSync());
ASSERT_TRUE(GetClient(1)->AwaitPassphraseAccepted());
}
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, SetPassphraseTwice) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
SetPassphrase(0, kValidPassphrase, true);
ASSERT_TRUE(GetClient(0)->AwaitPassphraseAccepted());
ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));
SetPassphrase(1, kValidPassphrase, false);
ASSERT_TRUE(GetClient(1)->AwaitPassphraseAccepted());
SetPassphrase(1, kValidPassphrase, false);
ASSERT_TRUE(GetClient(1)->AwaitPassphraseAccepted());
}
<|endoftext|>
|
<commit_before>#include <ros/ros.h>
#include <std_msgs/Header.h>
inline void
time(std::string message, const std_msgs::Header &header, bool info=false){
ros::Time time = ros::Time::now();
std::ostringstream stringStream;
stringStream << message << ", Time now: " << time.sec <<"." << time.nsec << ", ";
stringStream << "header: " << header.stamp.sec << "." << header.stamp.nsec << ", ";
stringStream << "delta: " << (time.sec - header.stamp.sec) << "." << time.nsec - header.stamp.nsec;
std::string copyOfStr = stringStream.str();
if(info)
{
ROS_INFO("%s", copyOfStr.c_str());
}
else{
ROS_DEBUG("%s", copyOfStr.c_str());
}
}
inline void
time(std::string message, const std_msgs::Header &header, const std_msgs::Header &header2, bool info=false){
ros::Time time = ros::Time::now();
std::ostringstream stringStream;
stringStream << message << ", Time now: " << time.sec <<"." << time.nsec << ", ";
stringStream << "header: " << header.stamp.sec << "." << header.stamp.nsec << ", ";
stringStream << "header2: " << header2.stamp.sec << "." << header2.stamp.nsec << ", ";
stringStream << "delta: " << (header.stamp.sec - header2.stamp.sec) << "." << header.stamp.nsec - header2.stamp.nsec;
std::string copyOfStr = stringStream.str();
if(info)
{
ROS_INFO("%s", copyOfStr.c_str());
}
else{
ROS_DEBUG("%s", copyOfStr.c_str());
}
}
<commit_msg>added if def<commit_after>#include <ros/ros.h>
#include <std_msgs/Header.h>
#ifndef TIME_DEBUG_H_
#define TIME_DEBUG_H_
inline void
time(std::string message, const std_msgs::Header &header, bool info=false){
ros::Time time = ros::Time::now();
std::ostringstream stringStream;
stringStream << message << ", Time now: " << time.sec <<"." << time.nsec << ", ";
stringStream << "header: " << header.stamp.sec << "." << header.stamp.nsec << ", ";
stringStream << "delta: " << (time.sec - header.stamp.sec) << "." << time.nsec - header.stamp.nsec;
std::string copyOfStr = stringStream.str();
if(info)
{
ROS_INFO("%s", copyOfStr.c_str());
}
else{
ROS_DEBUG("%s", copyOfStr.c_str());
}
}
inline void
time(std::string message, const std_msgs::Header &header, const std_msgs::Header &header2, bool info=false){
ros::Time time = ros::Time::now();
std::ostringstream stringStream;
stringStream << message << ", Time now: " << time.sec <<"." << time.nsec << ", ";
stringStream << "header: " << header.stamp.sec << "." << header.stamp.nsec << ", ";
stringStream << "header2: " << header2.stamp.sec << "." << header2.stamp.nsec << ", ";
stringStream << "delta: " << (header.stamp.sec - header2.stamp.sec) << "." << header.stamp.nsec - header2.stamp.nsec;
std::string copyOfStr = stringStream.str();
if(info)
{
ROS_INFO("%s", copyOfStr.c_str());
}
else{
ROS_DEBUG("%s", copyOfStr.c_str());
}
}
#endif
<|endoftext|>
|
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2010, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include <cassert>
#include "boost/format.hpp"
#include "maya/MFnSkinCluster.h"
#include "maya/MFnDagNode.h"
#include "maya/MFnDependencyNode.h"
#include "maya/MFnMatrixData.h"
#include "maya/MDoubleArray.h"
#include "maya/MDagPath.h"
#include "maya/MDagPathArray.h"
#include "maya/MDGModifier.h"
#include "maya/MGlobal.h"
#include "maya/MItGeometry.h"
#include "maya/MObjectArray.h"
#include "maya/MPlug.h"
#include "maya/MPlugArray.h"
#include "maya/MSelectionList.h"
#include "IECore/SmoothSkinningData.h"
#include "IECore/PrimitiveVariable.h"
#include "IECore/MessageHandler.h"
#include "IECoreMaya/Convert.h"
#include "IECoreMaya/ToMayaSkinClusterConverter.h"
using namespace IECoreMaya;
ToMayaSkinClusterConverter::Description ToMayaSkinClusterConverter::g_skinClusterDescription( IECore::SmoothSkinningData::staticTypeId(), MFn::kSkinClusterFilter );
ToMayaSkinClusterConverter::ToMayaSkinClusterConverter( IECore::ConstObjectPtr object )
: ToMayaObjectConverter( "Converts IECore::SmoothSkinningData objects to a Maya skinCluster.", object)
{
}
bool ToMayaSkinClusterConverter::doConversion( IECore::ConstObjectPtr from, MObject &to, IECore::ConstCompoundObjectPtr operands ) const
{
MStatus s;
IECore::ConstSmoothSkinningDataPtr skinningData = IECore::runTimeCast<const IECore::SmoothSkinningData>( from );
assert( skinningData );
const std::vector<std::string> &influenceNames = skinningData->influenceNames()->readable();
const std::vector<Imath::M44f> &influencePoseData = skinningData->influencePose()->readable();
const std::vector<int> &pointIndexOffsets = skinningData->pointIndexOffsets()->readable();
const std::vector<int> &pointInfluenceCounts = skinningData->pointInfluenceCounts()->readable();
const std::vector<int> &pointInfluenceIndices = skinningData->pointInfluenceIndices()->readable();
const std::vector<float> &pointInfluenceWeights = skinningData->pointInfluenceWeights()->readable();
MFnDependencyNode fnSkinClusterNode( to, &s );
MFnSkinCluster fnSkinCluster( to, &s );
if ( s != MS::kSuccess )
{
/// \todo: optional parameter to allow custom node types and checks for the necessary attributes
/// \todo: create a new skinCluster if we want a kSkinClusterFilter and this isn't one
throw IECore::Exception( ( boost::format( "ToMayaSkinClusterConverter: \"%s\" is not a valid skinCluster" ) % fnSkinClusterNode.name() ).str() );
}
// gather the influence objects
/// \todo: optional parameter to keep existing influences
MObject mObj;
MDagPath path;
MSelectionList influenceList;
MDagPathArray influencePaths;
for ( unsigned i=0; i < influenceNames.size(); i++ )
{
MString influenceName( influenceNames[i].c_str() );
influenceList.add( influenceName );
s = influenceList.getDependNode( i, mObj );
if ( s != MS::kSuccess )
{
throw IECore::Exception( ( boost::format( "ToMayaSkinClusterConverter: Influence \"%s\" does not exist" ) % influenceName ).str() );
}
MFnDagNode fnInfluence( mObj, &s );
fnInfluence.getPath( path );
influencePaths.append( path );
}
/// \todo: optional parameter to reset the skinCluster's geomMatrix plug
// break existing influence connections to the skinCluster
MDGModifier dgModifier;
MPlugArray connectedPlugs;
MPlug matrixArrayPlug = fnSkinClusterNode.findPlug( "matrix", true, &s );
for ( unsigned i=0; i < matrixArrayPlug.numConnectedElements(); i++ )
{
MPlug matrixPlug = matrixArrayPlug.connectionByPhysicalIndex( i, &s );
matrixPlug.connectedTo( connectedPlugs, true, false );
dgModifier.disconnect( connectedPlugs[0], matrixPlug );
}
MPlug lockArrayPlug = fnSkinClusterNode.findPlug( "lockWeights", true, &s );
for ( unsigned i=0; i < lockArrayPlug.numConnectedElements(); i++ )
{
MPlug lockPlug = lockArrayPlug.connectionByPhysicalIndex( i, &s );
lockPlug.connectedTo( connectedPlugs, true, false );
dgModifier.disconnect( connectedPlugs[0], lockPlug );
}
MPlug paintPlug = fnSkinClusterNode.findPlug( "paintTrans", true, &s );
paintPlug.connectedTo( connectedPlugs, true, false );
if ( connectedPlugs.length() )
{
dgModifier.disconnect( connectedPlugs[0], paintPlug );
}
// break existing influence connections to the bind pose
MPlug bindPlug = fnSkinClusterNode.findPlug( "bindPose", true, &s );
bindPlug.connectedTo( connectedPlugs, true, false );
MFnDependencyNode fnBindPose( connectedPlugs[0].node() );
MPlug bindPoseMatrixArrayPlug = fnBindPose.findPlug( "worldMatrix", true, &s );
for ( unsigned i=0; i < bindPoseMatrixArrayPlug.numConnectedElements(); i++ )
{
MPlug matrixPlug = bindPoseMatrixArrayPlug.connectionByPhysicalIndex( i, &s );
matrixPlug.connectedTo( connectedPlugs, true, false );
dgModifier.disconnect( connectedPlugs[0], matrixPlug );
}
MPlug bindPoseMemberArrayPlug = fnBindPose.findPlug( "members", true, &s );
for ( unsigned i=0; i < bindPoseMemberArrayPlug.numConnectedElements(); i++ )
{
MPlug memberPlug = bindPoseMemberArrayPlug.connectionByPhysicalIndex( i, &s );
memberPlug.connectedTo( connectedPlugs, true, false );
dgModifier.disconnect( connectedPlugs[0], memberPlug );
}
dgModifier.doIt();
// make connections from influences to skinCluster and bindPose
for ( unsigned i=0; i < influenceNames.size(); i++ )
{
influenceList.getDependNode( i, mObj );
MFnDependencyNode fnInfluence( mObj );
MPlug influenceMatrixPlug = fnInfluence.findPlug( "worldMatrix", true, &s ).elementByLogicalIndex( 0, &s );
MPlug influenceLockPlug = fnInfluence.findPlug( "lockInfluenceWeights", true, &s );
MPlug influenceMessagePlug = fnInfluence.findPlug( "message", true, &s );
MPlug influenceBindPosePlug = fnInfluence.findPlug( "bindPose", true, &s );
// connect influence to the skinCluster
MPlug matrixPlug = matrixArrayPlug.elementByLogicalIndex( i );
MPlug lockPlug = lockArrayPlug.elementByLogicalIndex( i );
dgModifier.connect( influenceMatrixPlug, matrixPlug );
dgModifier.connect( influenceLockPlug, lockPlug );
// connect influence to the bindPose
MPlug bindPoseMatrixPlug = bindPoseMatrixArrayPlug.elementByLogicalIndex( i );
MPlug memberPlug = bindPoseMemberArrayPlug.elementByLogicalIndex( i );
dgModifier.connect( influenceMessagePlug, bindPoseMatrixPlug );
dgModifier.connect( influenceBindPosePlug, memberPlug );
}
influenceList.getDependNode( 0, mObj );
MFnDependencyNode fnInfluence( mObj );
MPlug influenceMessagePlug = fnInfluence.findPlug( "message", true, &s );
dgModifier.connect( influenceMessagePlug, paintPlug );
dgModifier.doIt();
// use influencePoseData as bindPreMatrix
MPlug bindPreMatrixArrayPlug = fnSkinClusterNode.findPlug( "bindPreMatrix", true, &s );
for ( unsigned i=0; i < influencePoseData.size(); i++ )
{
MPlug preMatrixPlug = bindPreMatrixArrayPlug.elementByLogicalIndex( i, &s );
preMatrixPlug.getValue( mObj );
MFnMatrixData matFn( mObj, &s );
matFn.set( IECore::convert<MMatrix>( influencePoseData[i] ) );
mObj = matFn.object();
preMatrixPlug.setValue( mObj );
}
// get the geometry
MObjectArray outputGeoObjs;
if ( !fnSkinCluster.getOutputGeometry( outputGeoObjs ) )
{
throw IECore::Exception( ( boost::format( "ToMayaSkinClusterConverter: skinCluster \"%s\" does not have any output geometry!" ) % fnSkinCluster.name() ).str() );
}
MFnDagNode dagFn( outputGeoObjs[0] );
MDagPath geoPath;
dagFn.getPath( geoPath );
// loop through all the points of the geometry and set the weights
MItGeometry geoIt( outputGeoObjs[0] );
MPlug weightListArrayPlug = fnSkinClusterNode.findPlug( "weightList", true, &s );
for ( unsigned pIndex=0; !geoIt.isDone(); geoIt.next(), pIndex++ )
{
MPlug pointWeightsPlug = weightListArrayPlug.elementByLogicalIndex( pIndex, &s ).child( 0 );
// remove existing influence weight plugs
MIntArray existingInfluenceIndices;
pointWeightsPlug.getExistingArrayAttributeIndices( existingInfluenceIndices );
for( unsigned i=0; i < existingInfluenceIndices.length(); i++ )
{
MPlug influenceWeightPlug = pointWeightsPlug.elementByLogicalIndex( existingInfluenceIndices[i], &s );
MGlobal::executeCommand( ( boost::format( "removeMultiInstance -break 1 %s" ) % influenceWeightPlug.name() ).str().c_str() );
}
// add new influence weight plugs
int firstIndex = pointIndexOffsets[pIndex];
for( int i=0; i < pointInfluenceCounts[pIndex]; i++ )
{
int influenceIndex = fnSkinCluster.indexForInfluenceObject( influencePaths[ pointInfluenceIndices[ firstIndex + i ] ] );
MPlug influenceWeightPlug = pointWeightsPlug.elementByLogicalIndex( influenceIndex, &s );
influenceWeightPlug.setValue( pointInfluenceWeights[ firstIndex + i ] );
}
}
return true;
}
<commit_msg>creating lockInfluenceWeights attribute if it doesnt exist<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2010, Image Engine Design Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of Image Engine Design nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include <cassert>
#include "boost/format.hpp"
#include "maya/MFnSkinCluster.h"
#include "maya/MFnDagNode.h"
#include "maya/MFnDependencyNode.h"
#include "maya/MFnMatrixData.h"
#include "maya/MDoubleArray.h"
#include "maya/MDagPath.h"
#include "maya/MDagPathArray.h"
#include "maya/MDGModifier.h"
#include "maya/MGlobal.h"
#include "maya/MItGeometry.h"
#include "maya/MFnNumericAttribute.h"
#include "maya/MObjectArray.h"
#include "maya/MPlug.h"
#include "maya/MPlugArray.h"
#include "maya/MSelectionList.h"
#include "IECore/SmoothSkinningData.h"
#include "IECore/PrimitiveVariable.h"
#include "IECore/MessageHandler.h"
#include "IECoreMaya/Convert.h"
#include "IECoreMaya/ToMayaSkinClusterConverter.h"
using namespace IECoreMaya;
ToMayaSkinClusterConverter::Description ToMayaSkinClusterConverter::g_skinClusterDescription( IECore::SmoothSkinningData::staticTypeId(), MFn::kSkinClusterFilter );
ToMayaSkinClusterConverter::ToMayaSkinClusterConverter( IECore::ConstObjectPtr object )
: ToMayaObjectConverter( "Converts IECore::SmoothSkinningData objects to a Maya skinCluster.", object)
{
}
bool ToMayaSkinClusterConverter::doConversion( IECore::ConstObjectPtr from, MObject &to, IECore::ConstCompoundObjectPtr operands ) const
{
MStatus s;
IECore::ConstSmoothSkinningDataPtr skinningData = IECore::runTimeCast<const IECore::SmoothSkinningData>( from );
assert( skinningData );
const std::vector<std::string> &influenceNames = skinningData->influenceNames()->readable();
const std::vector<Imath::M44f> &influencePoseData = skinningData->influencePose()->readable();
const std::vector<int> &pointIndexOffsets = skinningData->pointIndexOffsets()->readable();
const std::vector<int> &pointInfluenceCounts = skinningData->pointInfluenceCounts()->readable();
const std::vector<int> &pointInfluenceIndices = skinningData->pointInfluenceIndices()->readable();
const std::vector<float> &pointInfluenceWeights = skinningData->pointInfluenceWeights()->readable();
MFnDependencyNode fnSkinClusterNode( to, &s );
MFnSkinCluster fnSkinCluster( to, &s );
if ( s != MS::kSuccess )
{
/// \todo: optional parameter to allow custom node types and checks for the necessary attributes
/// \todo: create a new skinCluster if we want a kSkinClusterFilter and this isn't one
throw IECore::Exception( ( boost::format( "ToMayaSkinClusterConverter: \"%s\" is not a valid skinCluster" ) % fnSkinClusterNode.name() ).str() );
}
// gather the influence objects
/// \todo: optional parameter to keep existing influences
MObject mObj;
MDagPath path;
MSelectionList influenceList;
MDagPathArray influencePaths;
for ( unsigned i=0; i < influenceNames.size(); i++ )
{
MString influenceName( influenceNames[i].c_str() );
influenceList.add( influenceName );
s = influenceList.getDependNode( i, mObj );
if ( s != MS::kSuccess )
{
throw IECore::Exception( ( boost::format( "ToMayaSkinClusterConverter: Influence \"%s\" does not exist" ) % influenceName ).str() );
}
MFnDagNode fnInfluence( mObj, &s );
fnInfluence.getPath( path );
influencePaths.append( path );
}
/// \todo: optional parameter to reset the skinCluster's geomMatrix plug
// break existing influence connections to the skinCluster
MDGModifier dgModifier;
MPlugArray connectedPlugs;
MPlug matrixArrayPlug = fnSkinClusterNode.findPlug( "matrix", true, &s );
for ( unsigned i=0; i < matrixArrayPlug.numConnectedElements(); i++ )
{
MPlug matrixPlug = matrixArrayPlug.connectionByPhysicalIndex( i, &s );
matrixPlug.connectedTo( connectedPlugs, true, false );
dgModifier.disconnect( connectedPlugs[0], matrixPlug );
}
MPlug lockArrayPlug = fnSkinClusterNode.findPlug( "lockWeights", true, &s );
for ( unsigned i=0; i < lockArrayPlug.numConnectedElements(); i++ )
{
MPlug lockPlug = lockArrayPlug.connectionByPhysicalIndex( i, &s );
lockPlug.connectedTo( connectedPlugs, true, false );
dgModifier.disconnect( connectedPlugs[0], lockPlug );
}
MPlug paintPlug = fnSkinClusterNode.findPlug( "paintTrans", true, &s );
paintPlug.connectedTo( connectedPlugs, true, false );
if ( connectedPlugs.length() )
{
dgModifier.disconnect( connectedPlugs[0], paintPlug );
}
// break existing influence connections to the bind pose
MPlug bindPlug = fnSkinClusterNode.findPlug( "bindPose", true, &s );
bindPlug.connectedTo( connectedPlugs, true, false );
MFnDependencyNode fnBindPose( connectedPlugs[0].node() );
MPlug bindPoseMatrixArrayPlug = fnBindPose.findPlug( "worldMatrix", true, &s );
for ( unsigned i=0; i < bindPoseMatrixArrayPlug.numConnectedElements(); i++ )
{
MPlug matrixPlug = bindPoseMatrixArrayPlug.connectionByPhysicalIndex( i, &s );
matrixPlug.connectedTo( connectedPlugs, true, false );
dgModifier.disconnect( connectedPlugs[0], matrixPlug );
}
MPlug bindPoseMemberArrayPlug = fnBindPose.findPlug( "members", true, &s );
for ( unsigned i=0; i < bindPoseMemberArrayPlug.numConnectedElements(); i++ )
{
MPlug memberPlug = bindPoseMemberArrayPlug.connectionByPhysicalIndex( i, &s );
memberPlug.connectedTo( connectedPlugs, true, false );
dgModifier.disconnect( connectedPlugs[0], memberPlug );
}
dgModifier.doIt();
// make connections from influences to skinCluster and bindPose
for ( unsigned i=0; i < influenceNames.size(); i++ )
{
influenceList.getDependNode( i, mObj );
MFnDependencyNode fnInfluence( mObj );
MPlug influenceMatrixPlug = fnInfluence.findPlug( "worldMatrix", true, &s ).elementByLogicalIndex( 0, &s );
MPlug influenceMessagePlug = fnInfluence.findPlug( "message", true, &s );
MPlug influenceBindPosePlug = fnInfluence.findPlug( "bindPose", true, &s );
MPlug influenceLockPlug = fnInfluence.findPlug( "lockInfluenceWeights", true, &s );
if ( !s )
{
// add the lockInfluenceWeights attribute if it doesn't exist
MFnNumericAttribute nAttr;
MObject attribute = nAttr.create( "lockInfluenceWeights", "liw", MFnNumericData::kBoolean, false );
fnInfluence.addAttribute( attribute );
influenceLockPlug = fnInfluence.findPlug( "lockInfluenceWeights", true, &s );
}
// connect influence to the skinCluster
MPlug matrixPlug = matrixArrayPlug.elementByLogicalIndex( i );
MPlug lockPlug = lockArrayPlug.elementByLogicalIndex( i );
dgModifier.connect( influenceMatrixPlug, matrixPlug );
dgModifier.connect( influenceLockPlug, lockPlug );
// connect influence to the bindPose
MPlug bindPoseMatrixPlug = bindPoseMatrixArrayPlug.elementByLogicalIndex( i );
MPlug memberPlug = bindPoseMemberArrayPlug.elementByLogicalIndex( i );
dgModifier.connect( influenceMessagePlug, bindPoseMatrixPlug );
dgModifier.connect( influenceBindPosePlug, memberPlug );
}
influenceList.getDependNode( 0, mObj );
MFnDependencyNode fnInfluence( mObj );
MPlug influenceMessagePlug = fnInfluence.findPlug( "message", true, &s );
dgModifier.connect( influenceMessagePlug, paintPlug );
dgModifier.doIt();
// use influencePoseData as bindPreMatrix
MPlug bindPreMatrixArrayPlug = fnSkinClusterNode.findPlug( "bindPreMatrix", true, &s );
for ( unsigned i=0; i < influencePoseData.size(); i++ )
{
MPlug preMatrixPlug = bindPreMatrixArrayPlug.elementByLogicalIndex( i, &s );
preMatrixPlug.getValue( mObj );
MFnMatrixData matFn( mObj, &s );
matFn.set( IECore::convert<MMatrix>( influencePoseData[i] ) );
mObj = matFn.object();
preMatrixPlug.setValue( mObj );
}
// get the geometry
MObjectArray outputGeoObjs;
if ( !fnSkinCluster.getOutputGeometry( outputGeoObjs ) )
{
throw IECore::Exception( ( boost::format( "ToMayaSkinClusterConverter: skinCluster \"%s\" does not have any output geometry!" ) % fnSkinCluster.name() ).str() );
}
MFnDagNode dagFn( outputGeoObjs[0] );
MDagPath geoPath;
dagFn.getPath( geoPath );
// loop through all the points of the geometry and set the weights
MItGeometry geoIt( outputGeoObjs[0] );
MPlug weightListArrayPlug = fnSkinClusterNode.findPlug( "weightList", true, &s );
for ( unsigned pIndex=0; !geoIt.isDone(); geoIt.next(), pIndex++ )
{
MPlug pointWeightsPlug = weightListArrayPlug.elementByLogicalIndex( pIndex, &s ).child( 0 );
// remove existing influence weight plugs
MIntArray existingInfluenceIndices;
pointWeightsPlug.getExistingArrayAttributeIndices( existingInfluenceIndices );
for( unsigned i=0; i < existingInfluenceIndices.length(); i++ )
{
MPlug influenceWeightPlug = pointWeightsPlug.elementByLogicalIndex( existingInfluenceIndices[i], &s );
MGlobal::executeCommand( ( boost::format( "removeMultiInstance -break 1 %s" ) % influenceWeightPlug.name() ).str().c_str() );
}
// add new influence weight plugs
int firstIndex = pointIndexOffsets[pIndex];
for( int i=0; i < pointInfluenceCounts[pIndex]; i++ )
{
int influenceIndex = fnSkinCluster.indexForInfluenceObject( influencePaths[ pointInfluenceIndices[ firstIndex + i ] ] );
MPlug influenceWeightPlug = pointWeightsPlug.elementByLogicalIndex( influenceIndex, &s );
influenceWeightPlug.setValue( pointInfluenceWeights[ firstIndex + i ] );
}
}
return true;
}
<|endoftext|>
|
<commit_before>/********************************************************************************
LibVideoGfx - video processing library
Copyright (C) 2002 Dirk Farin
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
********************************************************************************/
#include "libvideogfx/graphics/fileio/jpeg.hh"
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#ifdef HAVE_LIBJPEG
extern "C" {
#include <jpeglib.h>
}
#endif
namespace videogfx {
using namespace std;
#ifndef HAVE_LIBJPEG
bool JPEG_Supported()
{
return false;
}
void ReadImage_JPEG(Image<Pixel>& img,const char* filename)
{
assert(false); // ,"JPEG support has not been compiled into libvideogfx.\n");
}
void WriteImage_JPEG(const char* filename,const Image<Pixel>& img)
{
assert(false); // ,"JPEG support has not been compiled into libvideogfx.\n");
}
#else
bool JPEG_Supported()
{
return true;
}
void ReadImage_JPEG(Image<Pixel>& img,const char* filename)
{
struct jpeg_decompress_struct cinfo;
struct jpeg_error_mgr jerr;
// open input file
FILE * infile;
if ((infile = fopen(filename, "rb")) == NULL) {
fprintf(stderr, "can't open %s\n", filename);
exit(1);
}
// initialize decompressor
jpeg_create_decompress(&cinfo);
cinfo.err = jpeg_std_error(&jerr);
jpeg_stdio_src(&cinfo, infile);
jpeg_read_header(&cinfo, TRUE);
if (cinfo.jpeg_color_space == JCS_GRAYSCALE)
{
cinfo.out_color_space = JCS_GRAYSCALE;
jpeg_start_decompress(&cinfo);
JSAMPARRAY buffer;
buffer = (*cinfo.mem->alloc_sarray)
((j_common_ptr) &cinfo, JPOOL_IMAGE, cinfo.output_width * cinfo.output_components, 1);
// create destination image
ImageParam spec = img.AskParam();
spec.width = cinfo.output_width;
spec.height = cinfo.output_height;
spec.colorspace = Colorspace_Greyscale;
img.Create(spec);
Pixel*const* py = img.AskFrameY();
// read the image
while (cinfo.output_scanline < cinfo.output_height) {
JOCTET* bufp;
(void) jpeg_read_scanlines(&cinfo, buffer, 1);
bufp = buffer[0];
for (unsigned int x=0;x<cinfo.output_width;x++)
{
py[cinfo.output_scanline-1][x] = *bufp++;
}
}
}
else
{
cinfo.out_color_space = JCS_YCbCr;
jpeg_start_decompress(&cinfo);
JSAMPARRAY buffer;
buffer = (*cinfo.mem->alloc_sarray)
((j_common_ptr) &cinfo, JPOOL_IMAGE, cinfo.output_width * cinfo.output_components, 1);
// create destination image
ImageParam spec = img.AskParam();
spec.width = cinfo.output_width;
spec.height = cinfo.output_height;
spec.colorspace = Colorspace_YUV;
spec.chroma = Chroma_420;
img.Create(spec);
Pixel*const* py = img.AskFrameY();
Pixel*const* pcb = img.AskFrameCb();
Pixel*const* pcr = img.AskFrameCr();
// read the image
while (cinfo.output_scanline < cinfo.output_height) {
JOCTET* bufp;
(void) jpeg_read_scanlines(&cinfo, buffer, 1);
bufp = buffer[0];
for (unsigned int x=0;x<cinfo.output_width;x+=2)
{
py [cinfo.output_scanline-1][x] = *bufp++;
pcb[(cinfo.output_scanline-1)/2][x/2] = *bufp++;
pcr[(cinfo.output_scanline-1)/2][x/2] = *bufp++;
if (x+1 < cinfo.output_width) {
py [cinfo.output_scanline-1][x+1] = *bufp++;
}
bufp+=2;
}
if (cinfo.output_scanline < cinfo.output_height) {
(void) jpeg_read_scanlines(&cinfo, buffer, 1);
bufp = buffer[0];
for (unsigned int x=0;x<cinfo.output_width;x++)
{
py [cinfo.output_scanline-1][x] = *bufp++;
bufp+=2;
}
}
}
}
// cleanup
jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
fclose(infile);
}
void WriteImage_JPEG(const char* filename, const Image<Pixel>& img)
{
assert(img.AskParam().colorspace == Colorspace_YUV ||
img.AskParam().colorspace == Colorspace_Greyscale);
struct jpeg_compress_struct cinfo;
struct jpeg_error_mgr jerr;
// open output file
FILE * outfile;
if ((outfile = fopen(filename, "wb")) == NULL) {
fprintf(stderr, "can't open %s\n", filename);
exit(1);
}
// initialize compressor
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_compress(&cinfo);
jpeg_stdio_dest(&cinfo, outfile);
cinfo.image_width = img.AskWidth();
cinfo.image_height = img.AskHeight();
if (img.AskParam().colorspace == Colorspace_YUV)
{
cinfo.input_components = 3;
cinfo.in_color_space = JCS_YCbCr;
jpeg_set_defaults(&cinfo);
jpeg_start_compress(&cinfo,TRUE);
JSAMPARRAY buffer;
buffer = (*cinfo.mem->alloc_sarray)
((j_common_ptr) &cinfo, JPOOL_IMAGE, cinfo.image_width * cinfo.input_components, 1);
const Pixel*const* py = img.AskFrameY();
const Pixel*const* pcb = img.AskFrameCb();
const Pixel*const* pcr = img.AskFrameCr();
// write the image
while (cinfo.next_scanline < cinfo.image_height) {
JOCTET* bufp;
JSAMPROW row[1];
row[0]=buffer[0];
bufp = buffer[0];
for (unsigned int x=0;x<cinfo.image_width;x++)
{
*bufp++ = py[cinfo.next_scanline][x];
*bufp++ = pcb[(cinfo.next_scanline)/2][x/2];
*bufp++ = pcr[(cinfo.next_scanline)/2][x/2];
}
jpeg_write_scanlines(&cinfo, row, 1);
}
}
else
{
cinfo.input_components = 1;
cinfo.in_color_space = JCS_GRAYSCALE;
jpeg_set_defaults(&cinfo);
jpeg_start_compress(&cinfo,TRUE);
JSAMPARRAY buffer;
buffer = (*cinfo.mem->alloc_sarray)
((j_common_ptr) &cinfo, JPOOL_IMAGE, cinfo.image_width * cinfo.input_components, 1);
const Pixel*const* py = img.AskFrameY();
// write the image
while (cinfo.next_scanline < cinfo.image_height) {
JOCTET* bufp;
JSAMPROW row[1];
row[0]=buffer[0];
bufp = buffer[0];
for (unsigned int x=0;x<cinfo.image_width;x++)
{
*bufp++ = py[cinfo.next_scanline][x];
}
jpeg_write_scanlines(&cinfo, row, 1);
}
}
// cleanup
jpeg_finish_compress(&cinfo);
jpeg_destroy_compress(&cinfo);
fclose(outfile);
}
#endif
}
<commit_msg>write JPEG to STDOUT when filename is NULL<commit_after>/********************************************************************************
LibVideoGfx - video processing library
Copyright (C) 2002 Dirk Farin
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
********************************************************************************/
#include "libvideogfx/graphics/fileio/jpeg.hh"
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#ifdef HAVE_LIBJPEG
extern "C" {
#include <jpeglib.h>
}
#endif
namespace videogfx {
using namespace std;
#ifndef HAVE_LIBJPEG
bool JPEG_Supported()
{
return false;
}
void ReadImage_JPEG(Image<Pixel>& img,const char* filename)
{
assert(false); // ,"JPEG support has not been compiled into libvideogfx.\n");
}
void WriteImage_JPEG(const char* filename,const Image<Pixel>& img)
{
assert(false); // ,"JPEG support has not been compiled into libvideogfx.\n");
}
#else
bool JPEG_Supported()
{
return true;
}
void ReadImage_JPEG(Image<Pixel>& img,const char* filename)
{
struct jpeg_decompress_struct cinfo;
struct jpeg_error_mgr jerr;
// open input file
FILE * infile;
if ((infile = fopen(filename, "rb")) == NULL) {
fprintf(stderr, "can't open %s\n", filename);
exit(1);
}
// initialize decompressor
jpeg_create_decompress(&cinfo);
cinfo.err = jpeg_std_error(&jerr);
jpeg_stdio_src(&cinfo, infile);
jpeg_read_header(&cinfo, TRUE);
if (cinfo.jpeg_color_space == JCS_GRAYSCALE)
{
cinfo.out_color_space = JCS_GRAYSCALE;
jpeg_start_decompress(&cinfo);
JSAMPARRAY buffer;
buffer = (*cinfo.mem->alloc_sarray)
((j_common_ptr) &cinfo, JPOOL_IMAGE, cinfo.output_width * cinfo.output_components, 1);
// create destination image
ImageParam spec = img.AskParam();
spec.width = cinfo.output_width;
spec.height = cinfo.output_height;
spec.colorspace = Colorspace_Greyscale;
img.Create(spec);
Pixel*const* py = img.AskFrameY();
// read the image
while (cinfo.output_scanline < cinfo.output_height) {
JOCTET* bufp;
(void) jpeg_read_scanlines(&cinfo, buffer, 1);
bufp = buffer[0];
for (unsigned int x=0;x<cinfo.output_width;x++)
{
py[cinfo.output_scanline-1][x] = *bufp++;
}
}
}
else
{
cinfo.out_color_space = JCS_YCbCr;
jpeg_start_decompress(&cinfo);
JSAMPARRAY buffer;
buffer = (*cinfo.mem->alloc_sarray)
((j_common_ptr) &cinfo, JPOOL_IMAGE, cinfo.output_width * cinfo.output_components, 1);
// create destination image
ImageParam spec = img.AskParam();
spec.width = cinfo.output_width;
spec.height = cinfo.output_height;
spec.colorspace = Colorspace_YUV;
spec.chroma = Chroma_420;
img.Create(spec);
Pixel*const* py = img.AskFrameY();
Pixel*const* pcb = img.AskFrameCb();
Pixel*const* pcr = img.AskFrameCr();
// read the image
while (cinfo.output_scanline < cinfo.output_height) {
JOCTET* bufp;
(void) jpeg_read_scanlines(&cinfo, buffer, 1);
bufp = buffer[0];
for (unsigned int x=0;x<cinfo.output_width;x+=2)
{
py [cinfo.output_scanline-1][x] = *bufp++;
pcb[(cinfo.output_scanline-1)/2][x/2] = *bufp++;
pcr[(cinfo.output_scanline-1)/2][x/2] = *bufp++;
if (x+1 < cinfo.output_width) {
py [cinfo.output_scanline-1][x+1] = *bufp++;
}
bufp+=2;
}
if (cinfo.output_scanline < cinfo.output_height) {
(void) jpeg_read_scanlines(&cinfo, buffer, 1);
bufp = buffer[0];
for (unsigned int x=0;x<cinfo.output_width;x++)
{
py [cinfo.output_scanline-1][x] = *bufp++;
bufp+=2;
}
}
}
}
// cleanup
jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
fclose(infile);
}
void WriteImage_JPEG(const char* filename, const Image<Pixel>& img)
{
assert(img.AskParam().colorspace == Colorspace_YUV ||
img.AskParam().colorspace == Colorspace_Greyscale);
struct jpeg_compress_struct cinfo;
struct jpeg_error_mgr jerr;
// open output file
FILE * outfile;
if (filename==nullptr) {
outfile = stdout;
}
else {
if ((outfile = fopen(filename, "wb")) == NULL) {
fprintf(stderr, "can't open %s\n", filename);
exit(1);
}
}
// initialize compressor
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_compress(&cinfo);
jpeg_stdio_dest(&cinfo, outfile);
cinfo.image_width = img.AskWidth();
cinfo.image_height = img.AskHeight();
if (img.AskParam().colorspace == Colorspace_YUV)
{
cinfo.input_components = 3;
cinfo.in_color_space = JCS_YCbCr;
jpeg_set_defaults(&cinfo);
jpeg_start_compress(&cinfo,TRUE);
JSAMPARRAY buffer;
buffer = (*cinfo.mem->alloc_sarray)
((j_common_ptr) &cinfo, JPOOL_IMAGE, cinfo.image_width * cinfo.input_components, 1);
const Pixel*const* py = img.AskFrameY();
const Pixel*const* pcb = img.AskFrameCb();
const Pixel*const* pcr = img.AskFrameCr();
// write the image
while (cinfo.next_scanline < cinfo.image_height) {
JOCTET* bufp;
JSAMPROW row[1];
row[0]=buffer[0];
bufp = buffer[0];
for (unsigned int x=0;x<cinfo.image_width;x++)
{
*bufp++ = py[cinfo.next_scanline][x];
*bufp++ = pcb[(cinfo.next_scanline)/2][x/2];
*bufp++ = pcr[(cinfo.next_scanline)/2][x/2];
}
jpeg_write_scanlines(&cinfo, row, 1);
}
}
else
{
cinfo.input_components = 1;
cinfo.in_color_space = JCS_GRAYSCALE;
jpeg_set_defaults(&cinfo);
jpeg_start_compress(&cinfo,TRUE);
JSAMPARRAY buffer;
buffer = (*cinfo.mem->alloc_sarray)
((j_common_ptr) &cinfo, JPOOL_IMAGE, cinfo.image_width * cinfo.input_components, 1);
const Pixel*const* py = img.AskFrameY();
// write the image
while (cinfo.next_scanline < cinfo.image_height) {
JOCTET* bufp;
JSAMPROW row[1];
row[0]=buffer[0];
bufp = buffer[0];
for (unsigned int x=0;x<cinfo.image_width;x++)
{
*bufp++ = py[cinfo.next_scanline][x];
}
jpeg_write_scanlines(&cinfo, row, 1);
}
}
// cleanup
jpeg_finish_compress(&cinfo);
jpeg_destroy_compress(&cinfo);
if (filename != nullptr) {
fclose(outfile);
}
}
#endif
}
<|endoftext|>
|
<commit_before>/************************************************************************/
/* */
/* Copyright 2015 by Thorsten Beier */
/* */
/* This file is part of the VIGRA computer vision library. */
/* The VIGRA Website is */
/* http://hci.iwr.uni-heidelberg.de/vigra/ */
/* Please direct questions, bug reports, and contributions to */
/* ullrich.koethe@iwr.uni-heidelberg.de or */
/* vigra@informatik.uni-hamburg.de */
/* */
/* 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 VIGRA_COUNTING_ITERATOR_HXX
#define VIGRA_COUNTING_ITERATOR_HXX
#include <cmath>
#include <iterator>
#include <limits>
#include <type_traits>
#include "error.hxx"
#include "tinyvector.hxx"
namespace vigra {
/** \addtogroup MathFunctions
*/
//@{
/** \brief Iterator that counts upwards or downwards with a given step size.
This iterator replicates the functionality of Python's
well-known range-function. It is especially convenient in
range-based for-loops. <tt>CountingIterator</tt> also works for
floating-point counting.
<b>Usage:</b>
<b>\#include</b> \<vigra/counting_iterator.hxx\><br>
Namespace: vigra
You will normally construct instances of this iterator with
one of the <tt>range()</tt> factory functions. There are three versions
of this function <tt>range(end)</tt>, <tt>range(begin, end)</tt>, and
<tt>range(begin, end, step)</tt>.
\code
// count upwards from 0 to 4
for(int i: range(5))
std::cout << i << " "; // prints '0 1 2 3 4'
// count upwards from 4 to 7
for(int i: range(4, 8))
std::cout << i << " "; // prints '4 5 6 7'
// count upwards from 0 to 9 with step 3
for(int i: range(0, 9, 3))
std::cout << i << " "; // prints '0 3 6'
// likewise (note upper bound)
for(int i: range(0, 7, 3))
std::cout << i << " "; // prints '0 3 6'
// count downwards from 4 to 1 with step -1
for(int i: range(4, 0))
std::cout << i << " "; // prints '4 3 2 1'
// count downwards from 8 to 2 with step -2
for(int i: range(8, 0, -2))
std::cout << i << " "; // prints '8 6 4 2'
\endcode
Alternatively, you can create a traditional random-access iterator pair.
The end iterator can be conveniently constructed by the begin iterator's
<tt>end()</tt> function:
\code
auto iter = range(5),
end = iter.end();
std::cout << std::accumulate(iter, end, 0) << std::endl; // prints '10'
\endcode
<tt>range()</tt> and <tt>CountingIterator</tt> also work for floating-point
arguments. As in the integer case, the upper bound is excluded from the range
if it can be reached by an integer multiple of the step (within machine
epsilon):
\code
for(auto i: range(1.0, 1.6, 0.1)) // 1.6 is excluded
std::cout << i << " "; // prints '1 1.1 1.2 1.3 1.4 1.5'
for(auto i: range(1.0, 1.61, 0.1)) // 1.6 is included
std::cout << i << " "; // prints '1 1.1 1.2 1.3 1.4 1.5 1.6'
\endcode
If you use an iterator pair, you can make clear which behavior you want
by using either <tt>iter < end</tt> or <tt>iter <= end</tt> to terminate
the loop:
\code
auto iter = range(1.0, 1.6, 0.1),
end = iter.end();
for(; iter < end; ++iter) // exclude upper bound
std::cout << *iter << " "; // prints '1 1.1 1.2 1.3 1.4 1.5'
iter = range(1.0, 1.6, 0.1);
for(; iter <= end; ++iter) // include upper bound
std::cout << *iter << " "; // prints '1 1.1 1.2 1.3 1.4 1.5 1.6'
\endcode
Note that the termination condition is still <tt>iter <= end</tt>, even
when the iterator counts downwards:
\code
auto iter = range(1.6, 1.0, -0.1),
end = iter.end();
for(; iter <= end; ++iter)
std::cout << *iter << " "; // prints '1.6 1.5 1.4 1.3 1.2 1.1 1'
\endcode
*/
template<class T = ptrdiff_t>
class CountingIterator
: public std::iterator<std::random_access_iterator_tag,
T, ptrdiff_t, T const *, T>
{
public:
CountingIterator()
: begin_(0)
, end_(0)
, step_(1)
{}
CountingIterator(T begin, T end)
: begin_(begin)
, end_(end)
, step_(1)
{
vigra_precondition(begin <= end,
"CountingIterator(): begin must be less or equal to end.");
}
CountingIterator(T begin, T end, T step)
: begin_(begin)
, end_(end)
, step_(step)
{
vigra_precondition(step != 0,
"CountingIterator(): step must be non-zero.");
vigra_precondition((step > 0 && begin <= end) || (step < 0 && begin >= end),
"CountingIterator(): sign mismatch between step and (end-begin).");
}
CountingIterator(CountingIterator const & other, ReverseCopyTag)
: begin_(other.end_)
, end_(other.begin_)
, step_(-other.step_)
{}
public:
CountingIterator begin() const
{
return *this;
}
CountingIterator end() const
{
// since the range-based for-loop checks "iter != end",
// (end - begin) must be a multiple of step to avoid infinite loops
T end = begin_ + step_*Compare::distance(begin_, end_, step_);
return CountingIterator(end, end, step_);
}
bool empty() const
{
return Compare::greater_equal(begin_, end_, step_);
}
CountingIterator& operator++() {begin_ += step_; return *this;} // prefix++
CountingIterator operator++(int) {CountingIterator tmp(*this); ++(*this); return tmp;} // postfix++
CountingIterator& operator--() {begin_ -= step_; return *this;} // prefix--
CountingIterator operator--(int) {CountingIterator tmp(*this); --(*this); return tmp;} // postfix--
CountingIterator& operator+=(ptrdiff_t n)
{
begin_ += n*step_;
return *this;
}
CountingIterator operator+(ptrdiff_t n) const
{
return CountingIterator(*this) += n;
}
CountingIterator& operator-=(ptrdiff_t n)
{
begin_ -= n*step_;
return *this;
}
CountingIterator operator-(ptrdiff_t n) const
{
return CountingIterator(*this) -= n;
}
ptrdiff_t operator-(const CountingIterator& other) const
{
return Compare::distance(other.begin_, begin_, step_);
}
bool operator<(CountingIterator const & other) const
{
return Compare::less(begin_, other.begin_, step_);
}
bool operator<=(CountingIterator const & other) const
{
return Compare::less_equal(begin_, other.begin_, step_);
}
bool operator>(CountingIterator const & other) const
{
return Compare::greater(begin_, other.begin_, step_);
}
bool operator>=(CountingIterator const & other) const
{
return Compare::greater_equal(begin_, other.begin_, step_);
}
bool operator==(const CountingIterator& other) const
{
return Compare::equal(begin_, other.begin_, step_);
}
bool operator!=(const CountingIterator& other) const
{
return Compare::not_equal(begin_, other.begin_, step_);
}
T operator[](ptrdiff_t n) const {
return begin_ + n*step_;
}
T operator*() const {
return begin_;
}
T const * operator->() const{
return &begin_;
}
private:
template <bool is_float=false>
struct CompareImpl
{
// use exact comparison for integer counting
static bool equal(T left, T right, T /* step */)
{
return left == right;
}
static bool not_equal(T left, T right, T /* step */)
{
return left != right;
}
static bool less(T left, T right, T step)
{
// NOTE: the more efficient '(right - left)*step > 0'
// fails for unsigned arguments
return step > 0
? left < right
: left > right;
}
static bool less_equal(T left, T right, T step)
{
return step > 0
? left <= right
: left >= right;
}
static bool greater(T left, T right, T step)
{
return step > 0
? left > right
: left < right;
}
static bool greater_equal(T left, T right, T step)
{
return step > 0
? left >= right
: left <= right;
}
// integer counting: if the raw distance is not divisible by step,
// we must round upwards
static ptrdiff_t distance(T from, T to, T step)
{
const double diff = (double(to) - double(from)) / double(step);
return diff > 0.0
? (ptrdiff_t)std::ceil(diff)
: (ptrdiff_t)std::floor(diff);
}
};
template <>
struct CompareImpl<true>
{
typedef std::numeric_limits<T> limit;
// use comparison with tolerance for floating-point counting
// (the natural epsilon is 0.5*step)
static bool equal(T left, T right, T step)
{
return std::fabs(right-left) <= 0.5*std::fabs(step);
}
static bool not_equal(T left, T right, T step)
{
return std::fabs(right-left) > 0.5*std::fabs(step);
}
static bool less(T left, T right, T step)
{
return step > 0.0
? right - left > 0.5*step
: right - left < 0.5*step;
}
static bool less_equal(T left, T right, T step)
{
return step > 0.0
? left - right < 0.5*step
: left - right > 0.5*step;
}
static bool greater(T left, T right, T step)
{
return step > 0.0
? left - right > 0.5*step
: left - right < 0.5*step;
}
static bool greater_equal(T left, T right, T step)
{
return step > 0.0
? right - left < 0.5*step
: right - left > 0.5*step;
}
// floating-point counting: if the raw distance is not divisible by step,
// we round to nearest if the difference is small, otherwise upwards
static ptrdiff_t distance(T from, T to, T step)
{
const double diff = (double(to) - double(from)) / double(step);
return diff > 0.0
? (ptrdiff_t)std::ceil(diff*(1.0-2.0*limit::epsilon()))
: (ptrdiff_t)std::floor(diff*(1.0-2.0*limit::epsilon()));
}
};
typedef CompareImpl<std::is_floating_point<T>::value> Compare;
T begin_, end_, step_;
};
template <class T1, class T2, class T3>
inline CountingIterator<T1>
range(T1 begin, T2 end, T3 step)
{
return CountingIterator<T1>(begin, end, step);
}
template <class T1, class T2>
inline CountingIterator<T1>
range(T1 begin, T2 end)
{
return CountingIterator<T1>(begin, end, 1);
}
template <class T>
inline CountingIterator<T>
range(T end)
{
return CountingIterator<T>(0, end, 1);
}
//@}
} // namespace vigra
#endif
<commit_msg>g++ needs std::ptrdiff_t<commit_after>/************************************************************************/
/* */
/* Copyright 2015 by Thorsten Beier */
/* */
/* This file is part of the VIGRA computer vision library. */
/* The VIGRA Website is */
/* http://hci.iwr.uni-heidelberg.de/vigra/ */
/* Please direct questions, bug reports, and contributions to */
/* ullrich.koethe@iwr.uni-heidelberg.de or */
/* vigra@informatik.uni-hamburg.de */
/* */
/* 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 VIGRA_COUNTING_ITERATOR_HXX
#define VIGRA_COUNTING_ITERATOR_HXX
#include <cmath>
#include <iterator>
#include <limits>
#include <type_traits>
#include "error.hxx"
#include "tinyvector.hxx"
namespace vigra {
/** \addtogroup MathFunctions
*/
//@{
/** \brief Iterator that counts upwards or downwards with a given step size.
This iterator replicates the functionality of Python's
well-known range-function. It is especially convenient in
range-based for-loops. <tt>CountingIterator</tt> also works for
floating-point counting.
<b>Usage:</b>
<b>\#include</b> \<vigra/counting_iterator.hxx\><br>
Namespace: vigra
You will normally construct instances of this iterator with
one of the <tt>range()</tt> factory functions. There are three versions
of this function <tt>range(end)</tt>, <tt>range(begin, end)</tt>, and
<tt>range(begin, end, step)</tt>.
\code
// count upwards from 0 to 4
for(int i: range(5))
std::cout << i << " "; // prints '0 1 2 3 4'
// count upwards from 4 to 7
for(int i: range(4, 8))
std::cout << i << " "; // prints '4 5 6 7'
// count upwards from 0 to 9 with step 3
for(int i: range(0, 9, 3))
std::cout << i << " "; // prints '0 3 6'
// likewise (note upper bound)
for(int i: range(0, 7, 3))
std::cout << i << " "; // prints '0 3 6'
// count downwards from 4 to 1 with step -1
for(int i: range(4, 0))
std::cout << i << " "; // prints '4 3 2 1'
// count downwards from 8 to 2 with step -2
for(int i: range(8, 0, -2))
std::cout << i << " "; // prints '8 6 4 2'
\endcode
Alternatively, you can create a traditional random-access iterator pair.
The end iterator can be conveniently constructed by the begin iterator's
<tt>end()</tt> function:
\code
auto iter = range(5),
end = iter.end();
std::cout << std::accumulate(iter, end, 0) << std::endl; // prints '10'
\endcode
<tt>range()</tt> and <tt>CountingIterator</tt> also work for floating-point
arguments. As in the integer case, the upper bound is excluded from the range
if it can be reached by an integer multiple of the step (within machine
epsilon):
\code
for(auto i: range(1.0, 1.6, 0.1)) // 1.6 is excluded
std::cout << i << " "; // prints '1 1.1 1.2 1.3 1.4 1.5'
for(auto i: range(1.0, 1.61, 0.1)) // 1.6 is included
std::cout << i << " "; // prints '1 1.1 1.2 1.3 1.4 1.5 1.6'
\endcode
If you use an iterator pair, you can make clear which behavior you want
by using either <tt>iter < end</tt> or <tt>iter <= end</tt> to terminate
the loop:
\code
auto iter = range(1.0, 1.6, 0.1),
end = iter.end();
for(; iter < end; ++iter) // exclude upper bound
std::cout << *iter << " "; // prints '1 1.1 1.2 1.3 1.4 1.5'
iter = range(1.0, 1.6, 0.1);
for(; iter <= end; ++iter) // include upper bound
std::cout << *iter << " "; // prints '1 1.1 1.2 1.3 1.4 1.5 1.6'
\endcode
Note that the termination condition is still <tt>iter <= end</tt>, even
when the iterator counts downwards:
\code
auto iter = range(1.6, 1.0, -0.1),
end = iter.end();
for(; iter <= end; ++iter)
std::cout << *iter << " "; // prints '1.6 1.5 1.4 1.3 1.2 1.1 1'
\endcode
*/
template<class T = std::ptrdiff_t>
class CountingIterator
: public std::iterator<std::random_access_iterator_tag,
T, std::ptrdiff_t, T const *, T>
{
public:
CountingIterator()
: begin_(0)
, end_(0)
, step_(1)
{}
CountingIterator(T begin, T end)
: begin_(begin)
, end_(end)
, step_(1)
{
vigra_precondition(begin <= end,
"CountingIterator(): begin must be less or equal to end.");
}
CountingIterator(T begin, T end, T step)
: begin_(begin)
, end_(end)
, step_(step)
{
vigra_precondition(step != 0,
"CountingIterator(): step must be non-zero.");
vigra_precondition((step > 0 && begin <= end) || (step < 0 && begin >= end),
"CountingIterator(): sign mismatch between step and (end-begin).");
}
CountingIterator(CountingIterator const & other, ReverseCopyTag)
: begin_(other.end_)
, end_(other.begin_)
, step_(-other.step_)
{}
public:
CountingIterator begin() const
{
return *this;
}
CountingIterator end() const
{
// since the range-based for-loop checks "iter != end",
// (end - begin) must be a multiple of step to avoid infinite loops
T end = begin_ + step_*Compare::distance(begin_, end_, step_);
return CountingIterator(end, end, step_);
}
bool empty() const
{
return Compare::greater_equal(begin_, end_, step_);
}
CountingIterator& operator++() {begin_ += step_; return *this;} // prefix++
CountingIterator operator++(int) {CountingIterator tmp(*this); ++(*this); return tmp;} // postfix++
CountingIterator& operator--() {begin_ -= step_; return *this;} // prefix--
CountingIterator operator--(int) {CountingIterator tmp(*this); --(*this); return tmp;} // postfix--
CountingIterator& operator+=(std::ptrdiff_t n)
{
begin_ += n*step_;
return *this;
}
CountingIterator operator+(std::ptrdiff_t n) const
{
return CountingIterator(*this) += n;
}
CountingIterator& operator-=(std::ptrdiff_t n)
{
begin_ -= n*step_;
return *this;
}
CountingIterator operator-(std::ptrdiff_t n) const
{
return CountingIterator(*this) -= n;
}
std::ptrdiff_t operator-(const CountingIterator& other) const
{
return Compare::distance(other.begin_, begin_, step_);
}
bool operator<(CountingIterator const & other) const
{
return Compare::less(begin_, other.begin_, step_);
}
bool operator<=(CountingIterator const & other) const
{
return Compare::less_equal(begin_, other.begin_, step_);
}
bool operator>(CountingIterator const & other) const
{
return Compare::greater(begin_, other.begin_, step_);
}
bool operator>=(CountingIterator const & other) const
{
return Compare::greater_equal(begin_, other.begin_, step_);
}
bool operator==(const CountingIterator& other) const
{
return Compare::equal(begin_, other.begin_, step_);
}
bool operator!=(const CountingIterator& other) const
{
return Compare::not_equal(begin_, other.begin_, step_);
}
T operator[](std::ptrdiff_t n) const {
return begin_ + n*step_;
}
T operator*() const {
return begin_;
}
T const * operator->() const{
return &begin_;
}
private:
template <bool is_float=false>
struct CompareImpl
{
// use exact comparison for integer counting
static bool equal(T left, T right, T /* step */)
{
return left == right;
}
static bool not_equal(T left, T right, T /* step */)
{
return left != right;
}
static bool less(T left, T right, T step)
{
// NOTE: the more efficient '(right - left)*step > 0'
// fails for unsigned arguments
return step > 0
? left < right
: left > right;
}
static bool less_equal(T left, T right, T step)
{
return step > 0
? left <= right
: left >= right;
}
static bool greater(T left, T right, T step)
{
return step > 0
? left > right
: left < right;
}
static bool greater_equal(T left, T right, T step)
{
return step > 0
? left >= right
: left <= right;
}
// integer counting: if the raw distance is not divisible by step,
// we must round upwards
static std::ptrdiff_t distance(T from, T to, T step)
{
const double diff = (double(to) - double(from)) / double(step);
return diff > 0.0
? (std::ptrdiff_t)std::ceil(diff)
: (std::ptrdiff_t)std::floor(diff);
}
};
template <>
struct CompareImpl<true>
{
typedef std::numeric_limits<T> limit;
// use comparison with tolerance for floating-point counting
// (the natural epsilon is 0.5*step)
static bool equal(T left, T right, T step)
{
return std::fabs(right-left) <= 0.5*std::fabs(step);
}
static bool not_equal(T left, T right, T step)
{
return std::fabs(right-left) > 0.5*std::fabs(step);
}
static bool less(T left, T right, T step)
{
return step > 0.0
? right - left > 0.5*step
: right - left < 0.5*step;
}
static bool less_equal(T left, T right, T step)
{
return step > 0.0
? left - right < 0.5*step
: left - right > 0.5*step;
}
static bool greater(T left, T right, T step)
{
return step > 0.0
? left - right > 0.5*step
: left - right < 0.5*step;
}
static bool greater_equal(T left, T right, T step)
{
return step > 0.0
? right - left < 0.5*step
: right - left > 0.5*step;
}
// floating-point counting: if the raw distance is not divisible by step,
// we round to nearest if the difference is small, otherwise upwards
static std::ptrdiff_t distance(T from, T to, T step)
{
const double diff = (double(to) - double(from)) / double(step);
return diff > 0.0
? (std::ptrdiff_t)std::ceil(diff*(1.0-2.0*limit::epsilon()))
: (std::ptrdiff_t)std::floor(diff*(1.0-2.0*limit::epsilon()));
}
};
typedef CompareImpl<std::is_floating_point<T>::value> Compare;
T begin_, end_, step_;
};
template <class T1, class T2, class T3>
inline CountingIterator<T1>
range(T1 begin, T2 end, T3 step)
{
return CountingIterator<T1>(begin, end, step);
}
template <class T1, class T2>
inline CountingIterator<T1>
range(T1 begin, T2 end)
{
return CountingIterator<T1>(begin, end, 1);
}
template <class T>
inline CountingIterator<T>
range(T end)
{
return CountingIterator<T>(0, end, 1);
}
//@}
} // namespace vigra
#endif
<|endoftext|>
|
<commit_before>#include "RadioUtils.h"
#include <RF12.h>
#include <Arduino.h>
#include <EEPROM.h>
#include "../../src/common.h"
RadioUtils::RadioUtils(){
dynamicRouting = false;
distance = 100;
int nodeID = 0;
int groupID = 0;
int parentID = 0;
}
void RadioUtils::initialize(){
nodeID = EEPROM.read(NODE_ID_LOCATION);
groupID = EEPROM.read(GROUP_ID_LOCATION);
parentID = EEPROM.read(PARENT_ID_LOCATION);
rf12_initialize(nodeID, FREQUENCY, groupID);
}
int RadioUtils::getNodeID(){
return nodeID;
}
void RadioUtils::setTransmitPower(byte txPower){
rf12_control(0x9850 | (txPower > 7 ? 7 : txPower));
}
int RadioUtils::getGroupID(){
return groupID;
}
int RadioUtils::getParentID(){
return parentID;
}
int RadioUtils::routeUpdateDistance(int d, byte p){
if(d < distance){
distance = d;
parentID = p;
return 1;
} else {
return 0;
}
}
int RadioUtils::routeGetLength(){
return distance;
}
int RadioUtils::routePerformOneStep(){
for(int i = 0; i < TIMEOUT; i++) {
if(rf12_recvDone()){
if(RF12_WANTS_ACK){
rf12_sendStart(RF12_ACK_REPLY,0,0);
}
if(rf12_crc == 0){
char text[MAX_MESSAGE_LENGTH] = "";
for (byte i = 0; i < rf12_len; ++i) {
text[i] = rf12_data[i];
}
String payload = String(text);
int d = routeParseDistance(payload);
byte id = 0;
byte saveHdr;
saveHdr = rf12_hdr;
getID(&saveHdr, &id);
int result = routeUpdateDistance(d+1, id);
if(result == 1){
//TODO print
}
routeBroadcastLength();
return 1;
}
}
delay(10);
}
routeBroadcastLength();
return -1;
}
void RadioUtils::routeBroadcastLength(){
byte hdr = 0;
String d = String(distance, DEC);
String message = String("distance:" + d);
char payload[15] = "";
message.toCharArray(payload, message.length()+d.length()+1);
setBroadcast(&hdr);
resetAck(&hdr);
rf12_sendNow(hdr, payload, message.length());
}
int RadioUtils::routeParseDistance(String d){
String head = d.substring(0,d.indexOf(':'));
if(head == "distance"){
String body = d.substring(d.indexOf(':')+1);
return body.toInt();
} else {
return -1;
}
}
int RadioUtils::setAck(byte* hdr){
byte ackOr = B10000000;
*hdr = (*hdr | ackOr);
return 0;
}
int RadioUtils::resetAck(byte* hdr){
byte ackOr = B10000000;
*hdr =(*hdr & ~ackOr);
return 0;
}
int RadioUtils::setBroadcast(byte* hdr){
byte broadOr = B10111111;
*hdr = (*hdr & broadOr);
return 0;
}
int RadioUtils::setID(byte* hdr, byte id){
byte idAnd = B00011111;
id = (id & idAnd);
*hdr = (*hdr & ~idAnd);
*hdr = (*hdr | id);
return 0;
}
int RadioUtils::getID(byte* hdr, byte* id){
byte idAnd = B00011111;
*id = *hdr & idAnd;
return 0;
}
void RadioUtils::enableDynamicRouting(){
dynamicRouting = true;
}
<commit_msg>include added<commit_after>#include "RadioUtils.h"
#include <EEPROM.h>
#include "../../src/common.h"
#include <RF12.h>
RadioUtils::RadioUtils(){
dynamicRouting = false;
distance = 100;
int nodeID = 0;
int groupID = 0;
int parentID = 0;
}
void RadioUtils::initialize(){
nodeID = EEPROM.read(NODE_ID_LOCATION);
groupID = EEPROM.read(GROUP_ID_LOCATION);
parentID = EEPROM.read(PARENT_ID_LOCATION);
rf12_initialize(nodeID, FREQUENCY, groupID);
}
int RadioUtils::getNodeID(){
return nodeID;
}
void RadioUtils::setTransmitPower(byte txPower){
rf12_control(0x9850 | (txPower > 7 ? 7 : txPower));
}
int RadioUtils::getGroupID(){
return groupID;
}
int RadioUtils::getParentID(){
return parentID;
}
int RadioUtils::routeUpdateDistance(int d, byte p){
if(d < distance){
distance = d;
parentID = p;
return 1;
} else {
return 0;
}
}
int RadioUtils::routeGetLength(){
return distance;
}
int RadioUtils::routePerformOneStep(){
for(int i = 0; i < TIMEOUT; i++) {
if(rf12_recvDone()){
if(RF12_WANTS_ACK){
rf12_sendStart(RF12_ACK_REPLY,0,0);
}
if(rf12_crc == 0){
char text[MAX_MESSAGE_LENGTH] = "";
for (byte i = 0; i < rf12_len; ++i) {
text[i] = rf12_data[i];
}
String payload = String(text);
int d = routeParseDistance(payload);
byte id = 0;
byte saveHdr;
saveHdr = rf12_hdr;
getID(&saveHdr, &id);
int result = routeUpdateDistance(d+1, id);
if(result == 1){
//TODO print
}
routeBroadcastLength();
return 1;
}
}
delay(90);
}
routeBroadcastLength();
return -1;
}
void RadioUtils::routeBroadcastLength(){
byte hdr = 0;
String d = String(distance, DEC);
String message = String("distance:" + d);
char payload[15] = "";
message.toCharArray(payload, message.length()+d.length()+1);
setBroadcast(&hdr);
resetAck(&hdr);
rf12_sendNow(hdr, payload, message.length());
}
int RadioUtils::routeParseDistance(String d){
String head = d.substring(0,d.indexOf(':'));
if(head == "distance"){
String body = d.substring(d.indexOf(':')+1);
return body.toInt();
} else {
return -1;
}
}
int RadioUtils::setAck(byte* hdr){
byte ackOr = B10000000;
*hdr = (*hdr | ackOr);
return 0;
}
int RadioUtils::resetAck(byte* hdr){
byte ackOr = B10000000;
*hdr =(*hdr & ~ackOr);
return 0;
}
int RadioUtils::setBroadcast(byte* hdr){
byte broadOr = B10111111;
*hdr = (*hdr & broadOr);
return 0;
}
int RadioUtils::setID(byte* hdr, byte id){
byte idAnd = B00011111;
id = (id & idAnd);
*hdr = (*hdr & ~idAnd);
*hdr = (*hdr | id);
return 0;
}
int RadioUtils::getID(byte* hdr, byte* id){
byte idAnd = B00011111;
*id = *hdr & idAnd;
return 0;
}
void RadioUtils::enableDynamicRouting(){
dynamicRouting = true;
}
<|endoftext|>
|
<commit_before>#ifndef VSMC_UTILITY_CL_MANAGER_HPP
#define VSMC_UTILITY_CL_MANAGER_HPP
#include <vsmc/internal/common.hpp>
namespace vsmc {
struct CLDefault
{
typedef cxx11::integral_constant<cl_device_type, CL_DEVICE_TYPE_DEFAULT>
opencl_device_type;
};
/// \brief OpenCL Manager
/// \ingroup Utility
///
/// \details
/// Each instance of CLManager is an singleton. Different `ID` template
/// parameter create distinct singletons. Each singleton manages a specific
/// OpenCL device. However, it is possible for different singletons to manage
/// the same device.
///
/// The `ID` template parameter, apart from ensuring that different IDs create
/// distinct singletons, it can also provide additional information about which
/// device CLManager shall choose by default. Therefore it can optionally be a
/// policy class.
///
/// At initialization, the constructor of the singleton check if the following
/// member type, data and member functions exit,
///
/// \code
/// cl_device_type ID::opencl_device_type::value;
/// \endcode
/// The device type. The cl_device_type integer that determine which type of
/// device to use Normally this shall be enough to narrow the choice of device
/// of CLManager If missing, `CL_DEVICE_TYPE_DEFAULT` is used.
///
/// \code
/// static bool ID::check_opencl_platform (const std::string &name);
/// \endcode
/// The name of the platform. If there are multiple OpenCL platforms
/// available, CLManager check each of the platform's name against this
/// function until one returns `true`. For example, say there are both the
/// Intel and AMD platform available for CPU through OpenCL ICD. One can write
/// the following in this policy class
/// \code
/// static bool check_opencl_platform (const std::string &name)
/// {return name.find(std::string("Intel")) != std::string::npos;}
/// \endcode
/// Then, only the Intel platform will be used even the AMD one is found first.
///
/// \code
/// static bool ID::check_opencl_device (const std::string &name);
/// \endcode
/// Similar to `check_opencl_platform` but for a given device name. If there
/// are multiple OpenCL device for a given platform, then this can help to
/// narrow down the selection further.
///
/// \note
/// Before using a CLManager, it is important to check that
/// `CLManager::instance().setup()` returns `true`. Possible reasons of
/// returning `false` include no OpenCL device found at all, or no device match
/// the desired device type, or platform or device name is found. In this case,
/// the user need to setup the CLManager manually.
template <typename ID>
class CLManager
{
public :
/// \brief Get an instance of the manager singleton
static CLManager<ID> &instance ()
{
static CLManager<ID> manager;
return manager;
}
/// \brief The platform currently being used
const cl::Platform &platform () const
{
return platform_;
}
/// \brief The vector of all platforms that the manager found
const std::vector<cl::Platform> &platform_vec () const
{
return platform_vec_;
}
/// \brief The context currently being used
const cl::Context &context () const
{
return context_;
}
/// \brief The device currently being used
const cl::Device &device () const
{
return device_;
}
/// \brief The vector of all device that the manager found in the platform
const std::vector<cl::Device> &device_vec () const
{
return device_vec_;
}
/// \brief The command queue currently being used
const cl::CommandQueue &command_queue () const
{
return command_queue_;
}
/// \brief Whether the platform, context, device and command queue has been
/// setup correctly
bool setup () const
{
return setup_;
}
/// \brief Try to setup the platform, context, device and command queue
/// using the given device type
bool setup (cl_device_type dev)
{
setup_ = false;
setup_cl_manager(dev);
return setup_;
}
/// \brief Set the platform, context, device and command queue manually
///
/// \details
/// After this member function call setup() will return `true` in future
/// calls
bool setup (const cl::Platform &plat, const cl::Context &ctx,
const cl::Device &dev, const cl::CommandQueue &cmd)
{
setup_ = false;
platform_ = plat;
cl::Platform::get(&platform_vec_);
context_ = ctx;
device_ = dev;
device_vec_ = context_.getInfo<CL_CONTEXT_DEVICES>();
command_queue_ = cmd;
setup_ = true;
return setup_;
}
/// \brief Create an OpenCL buffer of a given type and number of elements
template<typename CLType>
cl::Buffer create_buffer (std::size_t num) const
{
VSMC_RUNTIME_ASSERT_CL_MANAGER_SETUP(create_buffer);
if (!num)
return cl::Buffer();
return cl::Buffer(context_, CL_MEM_READ_WRITE, sizeof(CLType) * num);
}
/// \brief Create an OpenCL buffer of a given type from a range of elements
template<typename CLType, typename InputIter>
cl::Buffer create_buffer (InputIter first, InputIter last) const
{
using std::distance;
VSMC_RUNTIME_ASSERT_CL_MANAGER_SETUP(create_buffer);
std::size_t num = static_cast<std::size_t>(
std::abs(distance(first, last)));
if (!num)
return cl::Buffer();
cl::Buffer buf(create_buffer<CLType>(num));
write_buffer<CLType>(buf, num, first);
return buf;
}
/// \brief Read an OpenCL buffer of a given type and number of elements
/// into an iterator
template <typename CLType, typename OutputIter>
OutputIter read_buffer (const cl::Buffer &buf, std::size_t num,
OutputIter first) const
{
VSMC_RUNTIME_ASSERT_CL_MANAGER_SETUP(read_buffer);
CLType *temp = read_buffer_pool<CLType>(num);
command_queue_.finish();
command_queue_.enqueueReadBuffer(buf, CL_TRUE, 0,
sizeof(CLType) * num, (void *) temp);
for (std::size_t i = 0; i != num; ++i, ++first)
*first = temp[i];
return first;
}
/// \brief Read an OpenCL buffer of a given type and number of elements
/// into an pointer
template <typename CLType>
CLType *read_buffer (const cl::Buffer &buf, std::size_t num,
CLType *first) const
{
VSMC_RUNTIME_ASSERT_CL_MANAGER_SETUP(read_buffer);
command_queue_.finish();
command_queue_.enqueueReadBuffer(buf, CL_TRUE, 0,
sizeof(CLType) * num, (void *) first);
return first + num;
}
/// \brief Read an OpenCL buffer of a given type and number of elements
/// into an pointer
template <typename CLType, typename InputIter>
InputIter write_buffer (const cl::Buffer &buf, std::size_t num,
InputIter first) const
{
VSMC_RUNTIME_ASSERT_CL_MANAGER_SETUP(write_buffer);
CLType *temp = write_buffer_pool<CLType>(num);
for (std::size_t i = 0; i != num; ++i, ++first)
temp[i] = *first;
command_queue_.finish();
command_queue_.enqueueWriteBuffer(buf, CL_TRUE, 0,
sizeof(CLType) * num, (void *) temp);
return first;
}
/// \brief Write an OpenCL buffer of a given type and number of elements
/// from an iterator
template <typename CLType>
const CLType *write_buffer (const cl::Buffer &buf, std::size_t num,
const CLType *first) const
{
VSMC_RUNTIME_ASSERT_CL_MANAGER_SETUP(write_buffer);
command_queue_.finish();
command_queue_.enqueueWriteBuffer(buf, CL_TRUE, 0,
sizeof(CLType) * num, (void *) first);
return first + num;
}
/// \brief Write an OpenCL buffer of a given type and number of elements
/// from an pointer
template <typename CLType>
CLType *write_buffer (const cl::Buffer &buf, std::size_t num,
CLType *first) const
{
VSMC_RUNTIME_ASSERT_CL_MANAGER_SETUP(write_buffer);
command_queue_.finish();
command_queue_.enqueueWriteBuffer(buf, CL_TRUE, 0,
sizeof(CLType) * num, (void *) first);
return first + num;
}
/// \brief Copy an OpenCL buffer into another of a given type and number of
/// elements
template <typename CLType>
void copy_buffer (const cl::Buffer &src, std::size_t num,
const cl::Buffer &dst) const
{
VSMC_RUNTIME_ASSERT_CL_MANAGER_SETUP(copy_buffer);
command_queue_.finish();
command_queue_.enqueueCopyBuffer(src, dst, 0, 0, sizeof(CLType) * num);
command_queue_.finish();
}
/// \brief Create a program given the source within the current context
cl::Program create_program (const std::string &source) const
{
return cl::Program(context_, source);
}
/// \brief Run a given kernel with one dimensional global size and local
/// size on the current command queue
///
/// \details
/// OpenCL requires that `global_size` is a multiple of `local_size`. This
/// function will round `global_size` if it is not already a multiple of
/// `local_size`. In the kernel it is important to check that
/// `get_global_id(0)` is not out of range.
///
/// For example, say we have kernel that should be applied to `N` elements.
/// But the most efficient local size `K` does not divide `N`. Instead of
/// calculate the correct global size yourself, you can simple call
/// `run_kernel(kern, N, K)`. But within the kernel, you need to check
/// `get_global_id(0) < N`
void run_kernel (const cl::Kernel &kern,
std::size_t global_size, std::size_t local_size) const
{
command_queue_.finish();
command_queue_.enqueueNDRangeKernel(kern, cl::NullRange,
get_global_nd_range(global_size, local_size),
get_local_nd_range(global_size, local_size));
command_queue_.finish();
}
private :
cl::Platform platform_;
std::vector<cl::Platform> platform_vec_;
cl::Context context_;
cl::Device device_;
std::vector<cl::Device> device_vec_;
cl::CommandQueue command_queue_;
bool setup_;
mutable std::size_t read_buffer_pool_bytes_;
mutable std::size_t write_buffer_pool_bytes_;
mutable void *read_buffer_pool_;
mutable void *write_buffer_pool_;
CLManager () :
setup_(false), read_buffer_pool_bytes_(0), write_buffer_pool_bytes_(0),
read_buffer_pool_(VSMC_NULLPTR), write_buffer_pool_(VSMC_NULLPTR)
{
cl_device_type dev = OpenCLDeviceTypeTrait<ID>::value ?
OpenCLDeviceTypeTrait<ID>::type::value :
CLDefault::opencl_device_type::value;
setup_cl_manager(dev);
}
CLManager (const CLManager<ID> &);
CLManager<ID> &operator= (const CLManager<ID> &);
~CLManager ()
{
std::free(read_buffer_pool_);
std::free(write_buffer_pool_);
}
void setup_cl_manager (cl_device_type dev)
{
try {
cl::Platform::get(&platform_vec_);
} catch (cl::Error) {
platform_vec_.clear();
}
for (std::size_t p = 0; p != platform_vec_.size(); ++p) {
try {
platform_ = platform_vec_[p];
std::string pname;
platform_.getInfo(CL_PLATFORM_NAME, &pname);
if (!CheckOpenCLPlatformTrait<ID>::check(pname)) {
platform_ = cl::Platform();
continue;
}
cl_context_properties context_properties[] = {
CL_CONTEXT_PLATFORM,
(cl_context_properties)(platform_)(), 0
};
context_ = cl::Context(dev, context_properties);
device_vec_ = context_.getInfo<CL_CONTEXT_DEVICES>();
bool device_found = false;
for (std::size_t d = 0; d != device_vec_.size(); ++d) {
std::string dname;
device_vec_[d].getInfo(CL_DEVICE_NAME, &dname);
if (CheckOpenCLDeviceTrait<ID>::check(dname)) {
device_ = device_vec_[d];
device_found = true;
break;
}
}
if (!device_found) {
platform_ = cl::Platform();
context_ = cl::Context();
device_ = cl::Device();
continue;
}
command_queue_ = cl::CommandQueue(context_, device_, 0);
setup_ = true;
break;
} catch (cl::Error) {
platform_ = cl::Platform();
context_ = cl::Context();
device_ = cl::Device();
command_queue_ = cl::CommandQueue();
device_vec_.clear();
}
}
}
template <typename CLType>
CLType *read_buffer_pool (std::size_t num) const
{
std::size_t new_bytes = num * sizeof(CLType);
if (new_bytes > read_buffer_pool_bytes_) {
std::free(read_buffer_pool_);
read_buffer_pool_ = std::malloc(new_bytes);
if (!read_buffer_pool_ && new_bytes)
throw std::bad_alloc();
read_buffer_pool_bytes_ = new_bytes;
}
return static_cast<CLType *>(read_buffer_pool_);
}
template <typename CLType>
CLType *write_buffer_pool (std::size_t num) const
{
std::size_t new_bytes = num * sizeof(CLType);
if (new_bytes > write_buffer_pool_bytes_) {
std::free(write_buffer_pool_);
write_buffer_pool_ = std::malloc(new_bytes);
if (!write_buffer_pool_ && new_bytes)
throw std::bad_alloc();
write_buffer_pool_bytes_ = new_bytes;
}
return static_cast<CLType *>(write_buffer_pool_);
}
cl::NDRange get_global_nd_range (
std::size_t global_size, std::size_t local_size) const
{
return (local_size && global_size % local_size) ?
cl::NDRange((global_size / local_size + 1) * local_size):
cl::NDRange(global_size);
}
cl::NDRange get_local_nd_range (
std::size_t global_size, std::size_t local_size) const
{
return local_size ? cl::NDRange(local_size) : cl::NullRange;
}
}; // clss CLManager
} // namespace vsmc
#endif // VSMC_UTILITY_CL_MANAGER_HPP
<commit_msg>add mising header<commit_after>#ifndef VSMC_UTILITY_CL_MANAGER_HPP
#define VSMC_UTILITY_CL_MANAGER_HPP
#include <vsmc/internal/common.hpp>
#include <vsmc/utility.cl_wrapper.hpp>
namespace vsmc {
struct CLDefault
{
typedef cxx11::integral_constant<cl_device_type, CL_DEVICE_TYPE_DEFAULT>
opencl_device_type;
};
/// \brief OpenCL Manager
/// \ingroup Utility
///
/// \details
/// Each instance of CLManager is an singleton. Different `ID` template
/// parameter create distinct singletons. Each singleton manages a specific
/// OpenCL device. However, it is possible for different singletons to manage
/// the same device.
///
/// The `ID` template parameter, apart from ensuring that different IDs create
/// distinct singletons, it can also provide additional information about which
/// device CLManager shall choose by default. Therefore it can optionally be a
/// policy class.
///
/// At initialization, the constructor of the singleton check if the following
/// member type, data and member functions exit,
///
/// \code
/// cl_device_type ID::opencl_device_type::value;
/// \endcode
/// The device type. The cl_device_type integer that determine which type of
/// device to use Normally this shall be enough to narrow the choice of device
/// of CLManager If missing, `CL_DEVICE_TYPE_DEFAULT` is used.
///
/// \code
/// static bool ID::check_opencl_platform (const std::string &name);
/// \endcode
/// The name of the platform. If there are multiple OpenCL platforms
/// available, CLManager check each of the platform's name against this
/// function until one returns `true`. For example, say there are both the
/// Intel and AMD platform available for CPU through OpenCL ICD. One can write
/// the following in this policy class
/// \code
/// static bool check_opencl_platform (const std::string &name)
/// {return name.find(std::string("Intel")) != std::string::npos;}
/// \endcode
/// Then, only the Intel platform will be used even the AMD one is found first.
///
/// \code
/// static bool ID::check_opencl_device (const std::string &name);
/// \endcode
/// Similar to `check_opencl_platform` but for a given device name. If there
/// are multiple OpenCL device for a given platform, then this can help to
/// narrow down the selection further.
///
/// \note
/// Before using a CLManager, it is important to check that
/// `CLManager::instance().setup()` returns `true`. Possible reasons of
/// returning `false` include no OpenCL device found at all, or no device match
/// the desired device type, or platform or device name is found. In this case,
/// the user need to setup the CLManager manually.
template <typename ID>
class CLManager
{
public :
/// \brief Get an instance of the manager singleton
static CLManager<ID> &instance ()
{
static CLManager<ID> manager;
return manager;
}
/// \brief The platform currently being used
const cl::Platform &platform () const
{
return platform_;
}
/// \brief The vector of all platforms that the manager found
const std::vector<cl::Platform> &platform_vec () const
{
return platform_vec_;
}
/// \brief The context currently being used
const cl::Context &context () const
{
return context_;
}
/// \brief The device currently being used
const cl::Device &device () const
{
return device_;
}
/// \brief The vector of all device that the manager found in the platform
const std::vector<cl::Device> &device_vec () const
{
return device_vec_;
}
/// \brief The command queue currently being used
const cl::CommandQueue &command_queue () const
{
return command_queue_;
}
/// \brief Whether the platform, context, device and command queue has been
/// setup correctly
bool setup () const
{
return setup_;
}
/// \brief Try to setup the platform, context, device and command queue
/// using the given device type
bool setup (cl_device_type dev)
{
setup_ = false;
setup_cl_manager(dev);
return setup_;
}
/// \brief Set the platform, context, device and command queue manually
///
/// \details
/// After this member function call setup() will return `true` in future
/// calls
bool setup (const cl::Platform &plat, const cl::Context &ctx,
const cl::Device &dev, const cl::CommandQueue &cmd)
{
setup_ = false;
platform_ = plat;
cl::Platform::get(&platform_vec_);
context_ = ctx;
device_ = dev;
device_vec_ = context_.getInfo<CL_CONTEXT_DEVICES>();
command_queue_ = cmd;
setup_ = true;
return setup_;
}
/// \brief Create an OpenCL buffer of a given type and number of elements
template<typename CLType>
cl::Buffer create_buffer (std::size_t num) const
{
VSMC_RUNTIME_ASSERT_CL_MANAGER_SETUP(create_buffer);
if (!num)
return cl::Buffer();
return cl::Buffer(context_, CL_MEM_READ_WRITE, sizeof(CLType) * num);
}
/// \brief Create an OpenCL buffer of a given type from a range of elements
template<typename CLType, typename InputIter>
cl::Buffer create_buffer (InputIter first, InputIter last) const
{
using std::distance;
VSMC_RUNTIME_ASSERT_CL_MANAGER_SETUP(create_buffer);
std::size_t num = static_cast<std::size_t>(
std::abs(distance(first, last)));
if (!num)
return cl::Buffer();
cl::Buffer buf(create_buffer<CLType>(num));
write_buffer<CLType>(buf, num, first);
return buf;
}
/// \brief Read an OpenCL buffer of a given type and number of elements
/// into an iterator
template <typename CLType, typename OutputIter>
OutputIter read_buffer (const cl::Buffer &buf, std::size_t num,
OutputIter first) const
{
VSMC_RUNTIME_ASSERT_CL_MANAGER_SETUP(read_buffer);
CLType *temp = read_buffer_pool<CLType>(num);
command_queue_.finish();
command_queue_.enqueueReadBuffer(buf, CL_TRUE, 0,
sizeof(CLType) * num, (void *) temp);
for (std::size_t i = 0; i != num; ++i, ++first)
*first = temp[i];
return first;
}
/// \brief Read an OpenCL buffer of a given type and number of elements
/// into an pointer
template <typename CLType>
CLType *read_buffer (const cl::Buffer &buf, std::size_t num,
CLType *first) const
{
VSMC_RUNTIME_ASSERT_CL_MANAGER_SETUP(read_buffer);
command_queue_.finish();
command_queue_.enqueueReadBuffer(buf, CL_TRUE, 0,
sizeof(CLType) * num, (void *) first);
return first + num;
}
/// \brief Read an OpenCL buffer of a given type and number of elements
/// into an pointer
template <typename CLType, typename InputIter>
InputIter write_buffer (const cl::Buffer &buf, std::size_t num,
InputIter first) const
{
VSMC_RUNTIME_ASSERT_CL_MANAGER_SETUP(write_buffer);
CLType *temp = write_buffer_pool<CLType>(num);
for (std::size_t i = 0; i != num; ++i, ++first)
temp[i] = *first;
command_queue_.finish();
command_queue_.enqueueWriteBuffer(buf, CL_TRUE, 0,
sizeof(CLType) * num, (void *) temp);
return first;
}
/// \brief Write an OpenCL buffer of a given type and number of elements
/// from an iterator
template <typename CLType>
const CLType *write_buffer (const cl::Buffer &buf, std::size_t num,
const CLType *first) const
{
VSMC_RUNTIME_ASSERT_CL_MANAGER_SETUP(write_buffer);
command_queue_.finish();
command_queue_.enqueueWriteBuffer(buf, CL_TRUE, 0,
sizeof(CLType) * num, (void *) first);
return first + num;
}
/// \brief Write an OpenCL buffer of a given type and number of elements
/// from an pointer
template <typename CLType>
CLType *write_buffer (const cl::Buffer &buf, std::size_t num,
CLType *first) const
{
VSMC_RUNTIME_ASSERT_CL_MANAGER_SETUP(write_buffer);
command_queue_.finish();
command_queue_.enqueueWriteBuffer(buf, CL_TRUE, 0,
sizeof(CLType) * num, (void *) first);
return first + num;
}
/// \brief Copy an OpenCL buffer into another of a given type and number of
/// elements
template <typename CLType>
void copy_buffer (const cl::Buffer &src, std::size_t num,
const cl::Buffer &dst) const
{
VSMC_RUNTIME_ASSERT_CL_MANAGER_SETUP(copy_buffer);
command_queue_.finish();
command_queue_.enqueueCopyBuffer(src, dst, 0, 0, sizeof(CLType) * num);
command_queue_.finish();
}
/// \brief Create a program given the source within the current context
cl::Program create_program (const std::string &source) const
{
return cl::Program(context_, source);
}
/// \brief Run a given kernel with one dimensional global size and local
/// size on the current command queue
///
/// \details
/// OpenCL requires that `global_size` is a multiple of `local_size`. This
/// function will round `global_size` if it is not already a multiple of
/// `local_size`. In the kernel it is important to check that
/// `get_global_id(0)` is not out of range.
///
/// For example, say we have kernel that should be applied to `N` elements.
/// But the most efficient local size `K` does not divide `N`. Instead of
/// calculate the correct global size yourself, you can simple call
/// `run_kernel(kern, N, K)`. But within the kernel, you need to check
/// `get_global_id(0) < N`
void run_kernel (const cl::Kernel &kern,
std::size_t global_size, std::size_t local_size) const
{
command_queue_.finish();
command_queue_.enqueueNDRangeKernel(kern, cl::NullRange,
get_global_nd_range(global_size, local_size),
get_local_nd_range(global_size, local_size));
command_queue_.finish();
}
private :
cl::Platform platform_;
std::vector<cl::Platform> platform_vec_;
cl::Context context_;
cl::Device device_;
std::vector<cl::Device> device_vec_;
cl::CommandQueue command_queue_;
bool setup_;
mutable std::size_t read_buffer_pool_bytes_;
mutable std::size_t write_buffer_pool_bytes_;
mutable void *read_buffer_pool_;
mutable void *write_buffer_pool_;
CLManager () :
setup_(false), read_buffer_pool_bytes_(0), write_buffer_pool_bytes_(0),
read_buffer_pool_(VSMC_NULLPTR), write_buffer_pool_(VSMC_NULLPTR)
{
cl_device_type dev = OpenCLDeviceTypeTrait<ID>::value ?
OpenCLDeviceTypeTrait<ID>::type::value :
CLDefault::opencl_device_type::value;
setup_cl_manager(dev);
}
CLManager (const CLManager<ID> &);
CLManager<ID> &operator= (const CLManager<ID> &);
~CLManager ()
{
std::free(read_buffer_pool_);
std::free(write_buffer_pool_);
}
void setup_cl_manager (cl_device_type dev)
{
try {
cl::Platform::get(&platform_vec_);
} catch (cl::Error) {
platform_vec_.clear();
}
for (std::size_t p = 0; p != platform_vec_.size(); ++p) {
try {
platform_ = platform_vec_[p];
std::string pname;
platform_.getInfo(CL_PLATFORM_NAME, &pname);
if (!CheckOpenCLPlatformTrait<ID>::check(pname)) {
platform_ = cl::Platform();
continue;
}
cl_context_properties context_properties[] = {
CL_CONTEXT_PLATFORM,
(cl_context_properties)(platform_)(), 0
};
context_ = cl::Context(dev, context_properties);
device_vec_ = context_.getInfo<CL_CONTEXT_DEVICES>();
bool device_found = false;
for (std::size_t d = 0; d != device_vec_.size(); ++d) {
std::string dname;
device_vec_[d].getInfo(CL_DEVICE_NAME, &dname);
if (CheckOpenCLDeviceTrait<ID>::check(dname)) {
device_ = device_vec_[d];
device_found = true;
break;
}
}
if (!device_found) {
platform_ = cl::Platform();
context_ = cl::Context();
device_ = cl::Device();
continue;
}
command_queue_ = cl::CommandQueue(context_, device_, 0);
setup_ = true;
break;
} catch (cl::Error) {
platform_ = cl::Platform();
context_ = cl::Context();
device_ = cl::Device();
command_queue_ = cl::CommandQueue();
device_vec_.clear();
}
}
}
template <typename CLType>
CLType *read_buffer_pool (std::size_t num) const
{
std::size_t new_bytes = num * sizeof(CLType);
if (new_bytes > read_buffer_pool_bytes_) {
std::free(read_buffer_pool_);
read_buffer_pool_ = std::malloc(new_bytes);
if (!read_buffer_pool_ && new_bytes)
throw std::bad_alloc();
read_buffer_pool_bytes_ = new_bytes;
}
return static_cast<CLType *>(read_buffer_pool_);
}
template <typename CLType>
CLType *write_buffer_pool (std::size_t num) const
{
std::size_t new_bytes = num * sizeof(CLType);
if (new_bytes > write_buffer_pool_bytes_) {
std::free(write_buffer_pool_);
write_buffer_pool_ = std::malloc(new_bytes);
if (!write_buffer_pool_ && new_bytes)
throw std::bad_alloc();
write_buffer_pool_bytes_ = new_bytes;
}
return static_cast<CLType *>(write_buffer_pool_);
}
cl::NDRange get_global_nd_range (
std::size_t global_size, std::size_t local_size) const
{
return (local_size && global_size % local_size) ?
cl::NDRange((global_size / local_size + 1) * local_size):
cl::NDRange(global_size);
}
cl::NDRange get_local_nd_range (
std::size_t global_size, std::size_t local_size) const
{
return local_size ? cl::NDRange(local_size) : cl::NullRange;
}
}; // clss CLManager
} // namespace vsmc
#endif // VSMC_UTILITY_CL_MANAGER_HPP
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: localsinglebackend.hxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: rt $ $Date: 2005-09-08 04:06:32 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef CONFIGMGR_LOCALBE_LOCALSINGLEBACKEND_HXX_
#define CONFIGMGR_LOCALBE_LOCALSINGLEBACKEND_HXX_
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XSCHEMASUPPLIER_HPP_
#include <com/sun/star/configuration/backend/XSchemaSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XMULTILAYERSTRATUM_HPP_
#include <com/sun/star/configuration/backend/XMultiLayerStratum.hpp>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XBACKENDENTITIES_HPP_
#include <com/sun/star/configuration/backend/XBackendEntities.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif // _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif // _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif // _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#ifndef _COM_SUN_STAR_CONFIGURATION_INVALIDBOOTSTRAPFILEEXCEPTION_HPP_
#include <com/sun/star/configuration/InvalidBootstrapFileException.hpp>
#endif
#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_CANNOTCONNECTEXCEPTION_HPP_
#include <com/sun/star/configuration/backend/CannotConnectException.hpp>
#endif
#ifndef _CPPUHELPER_COMPBASE5_HXX_
#include <cppuhelper/compbase5.hxx>
#endif // _CPPUHELPER_COMPBASE5_HXX_
namespace configmgr { namespace localbe {
namespace css = com::sun::star ;
namespace uno = css::uno ;
namespace lang = css::lang ;
namespace backend = css::configuration::backend ;
typedef cppu::WeakComponentImplHelper5<backend::XSchemaSupplier,
backend::XMultiLayerStratum,
backend::XBackendEntities,
lang::XInitialization,
lang::XServiceInfo> SingleBackendBase ;
/**
Implements the SingleBackend service for local file access.
Layer identifiers in that backend are file URLs.
*/
class LocalSingleBackend : public SingleBackendBase {
public :
/**
Service constructor from a service factory.
@param xFactory service factory
*/
LocalSingleBackend(const uno::Reference<uno::XComponentContext>& xContext) ;
/** Destructor */
~LocalSingleBackend(void) ;
// XInitialize
virtual void SAL_CALL
initialize( const uno::Sequence<uno::Any>& aParameters)
throw (uno::RuntimeException, uno::Exception,
css::configuration::InvalidBootstrapFileException,
backend::CannotConnectException,
backend::BackendSetupException);
// XSchemaSupplier
virtual uno::Reference<backend::XSchema> SAL_CALL
getComponentSchema( const rtl::OUString& aComponent )
throw (backend::BackendAccessException,
lang::IllegalArgumentException,
uno::RuntimeException) ;
// XMultiLayerStratum
virtual uno::Sequence<rtl::OUString> SAL_CALL
listLayerIds( const rtl::OUString& aComponent, const rtl::OUString& aEntity )
throw (backend::BackendAccessException,
lang::IllegalArgumentException,
uno::RuntimeException) ;
virtual rtl::OUString SAL_CALL
getUpdateLayerId( const rtl::OUString& aComponent, const rtl::OUString& aEntity )
throw (backend::BackendAccessException,
lang::IllegalArgumentException,
uno::RuntimeException) ;
virtual uno::Reference<backend::XLayer> SAL_CALL
getLayer( const rtl::OUString& aLayerId, const rtl::OUString& aTimestamp )
throw (backend::BackendAccessException,
lang::IllegalArgumentException,
uno::RuntimeException) ;
virtual uno::Sequence<uno::Reference<backend::XLayer> > SAL_CALL
getLayers(const uno::Sequence<rtl::OUString>& aLayerIds,
const rtl::OUString& aTimestamp)
throw (backend::BackendAccessException,
lang::IllegalArgumentException,
uno::RuntimeException) ;
virtual uno::Sequence<uno::Reference<backend::XLayer> > SAL_CALL
getMultipleLayers(const uno::Sequence<rtl::OUString>& aLayerIds,
const uno::Sequence<rtl::OUString>& aTimestamps)
throw (backend::BackendAccessException,
lang::IllegalArgumentException,
uno::RuntimeException) ;
virtual uno::Reference<backend::XUpdatableLayer> SAL_CALL
getUpdatableLayer( const rtl::OUString& aLayerId )
throw (backend::BackendAccessException,
lang::IllegalArgumentException,
uno::RuntimeException) ;
// XBackendEntities
virtual rtl::OUString SAL_CALL
getOwnerEntity( )
throw (uno::RuntimeException);
virtual rtl::OUString SAL_CALL
getAdminEntity( )
throw (uno::RuntimeException);
virtual sal_Bool SAL_CALL
supportsEntity( const rtl::OUString& aEntity )
throw (backend::BackendAccessException, uno::RuntimeException);
virtual sal_Bool SAL_CALL
isEqualEntity( const rtl::OUString& aEntity, const rtl::OUString& aOtherEntity )
throw (backend::BackendAccessException, lang::IllegalArgumentException, uno::RuntimeException);
// XServiceInfo
virtual rtl::OUString SAL_CALL
getImplementationName( )
throw (uno::RuntimeException) ;
virtual sal_Bool SAL_CALL
supportsService( const rtl::OUString& aServiceName )
throw (uno::RuntimeException) ;
virtual uno::Sequence<rtl::OUString> SAL_CALL
getSupportedServiceNames( )
throw (uno::RuntimeException) ;
/**
Provides the implementation name.
@return implementation name
*/
static rtl::OUString SAL_CALL getName(void) ;
/**
Provides the supported services names
@return service names
*/
static uno::Sequence<rtl::OUString> SAL_CALL getServices(void) ;
public: // helpers for other implementation that need to use the same data
/**
Locates the main layer data and localized data directories in a layer directory hierarchy
*/
static bool getLayerSubDirectories( rtl::OUString const & aLayerBaseUrl,
rtl::OUString& aMainLayerUrl,
rtl::OUString& aSubLayerUrl);
/**
Creates a simple readonly non-composite layer for a component in a base directory
*/
static uno::Reference<backend::XLayer>
createSimpleLayer(const uno::Reference<lang::XMultiServiceFactory>& xFactory,
rtl::OUString const & aLayerBaseUrl,
rtl::OUString const & aComponent);
/**
Creates a simple readonly non-composite layer for a component in a given file
*/
static uno::Reference<backend::XLayer>
createSimpleLayer(const uno::Reference<lang::XMultiServiceFactory>& xFactory,
rtl::OUString const & aComponentUrl);
private :
/** Service factory */
uno::Reference<lang::XMultiServiceFactory> mFactory ;
/** Mutex for resources protection */
osl::Mutex mMutex ;
/**
Base of the schema data. Is a list to allow
for multiple schema directories.
*/
uno::Sequence<rtl::OUString> mSchemaDataUrls ;
/**
Base of the default data. Is a list to allow
for multiple layers of default data.
*/
uno::Sequence<rtl::OUString> mDefaultDataUrls ;
/** Base of the user data */
rtl::OUString mUserDataUrl ;
/** special index for entity */
sal_Int32 findEntity(rtl::OUString const & _aEntity);
/** parse and translate layer-id */
sal_Int32 resolveLayerId(rtl::OUString const & _aLayerId, rtl::OUString & _aFile);
/**
Builds a LocalFileLayer object given a layer id.
Since the LocalFileLayer implements the various
interfaces a layer can be accessed as, a few methods
need one. This method handles the layer id mapping
and the existence or not of sublayers.
@param aLayerId layer id
@return local file layer
@throws com::sun::star::lang::IllegalArgumentException
if the layer id is invalid.
*/
uno::Reference<backend::XUpdatableLayer> getFileLayer(const rtl::OUString& aLayerId)
throw (lang::IllegalArgumentException) ;
/**
Same as above, but using a component URL and layer index
combination instead of a layer id (which encodes both).
@param aComponent component URL
@param aLayerIndex layer index
@return local file layer
*/
uno::Reference<backend::XUpdatableLayer> getFileLayer(const rtl::OUString& aComponent,
sal_Int32 aLayerIndex) ;
/**
Maps a layer index (-1 for user layer, 0-x for defaults)
to the appropriate layer and sublayers base directories.
@param aLayerIndex layer index
@param aLayerUrl layer base URL, filled on return
@param aSubLayerUrl sublayer base URL, filled on return
*/
bool getLayerDirectories(sal_Int32 aLayerIndex,
rtl::OUString& aLayerUrl,
rtl::OUString& aSubLayerUrl) ;
/**
Tells if a file is more recent than a given date.
The date is formatted YYYYMMDDhhmmssZ.
@param aComponent URL of the component to check
@param aLayerIndex index of the layer involved (-1 = user)
@param aTimestamp timestamp to check against
@return sal_True if the file is more recent, sal_False otherwise
*/
sal_Bool isMoreRecent(const rtl::OUString& aComponent,
sal_Int32 aLayerId,
const rtl::OUString& aTimestamp) ;
} ;
} } // configmgr.localbe
#endif // CONFIGMGR_LOCALBE_LOCALSINGLEBACKEND_HXX_
<commit_msg>INTEGRATION: CWS changefileheader (1.10.130); FILE MERGED 2008/04/01 15:06:48 thb 1.10.130.3: #i85898# Stripping all external header guards 2008/04/01 12:27:28 thb 1.10.130.2: #i85898# Stripping all external header guards 2008/03/31 12:22:49 rt 1.10.130.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: localsinglebackend.hxx,v $
* $Revision: 1.11 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef CONFIGMGR_LOCALBE_LOCALSINGLEBACKEND_HXX_
#define CONFIGMGR_LOCALBE_LOCALSINGLEBACKEND_HXX_
#include <com/sun/star/configuration/backend/XSchemaSupplier.hpp>
#include <com/sun/star/configuration/backend/XMultiLayerStratum.hpp>
#include <com/sun/star/configuration/backend/XBackendEntities.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/configuration/InvalidBootstrapFileException.hpp>
#include <com/sun/star/configuration/backend/CannotConnectException.hpp>
#include <cppuhelper/compbase5.hxx>
namespace configmgr { namespace localbe {
namespace css = com::sun::star ;
namespace uno = css::uno ;
namespace lang = css::lang ;
namespace backend = css::configuration::backend ;
typedef cppu::WeakComponentImplHelper5<backend::XSchemaSupplier,
backend::XMultiLayerStratum,
backend::XBackendEntities,
lang::XInitialization,
lang::XServiceInfo> SingleBackendBase ;
/**
Implements the SingleBackend service for local file access.
Layer identifiers in that backend are file URLs.
*/
class LocalSingleBackend : public SingleBackendBase {
public :
/**
Service constructor from a service factory.
@param xFactory service factory
*/
LocalSingleBackend(const uno::Reference<uno::XComponentContext>& xContext) ;
/** Destructor */
~LocalSingleBackend(void) ;
// XInitialize
virtual void SAL_CALL
initialize( const uno::Sequence<uno::Any>& aParameters)
throw (uno::RuntimeException, uno::Exception,
css::configuration::InvalidBootstrapFileException,
backend::CannotConnectException,
backend::BackendSetupException);
// XSchemaSupplier
virtual uno::Reference<backend::XSchema> SAL_CALL
getComponentSchema( const rtl::OUString& aComponent )
throw (backend::BackendAccessException,
lang::IllegalArgumentException,
uno::RuntimeException) ;
// XMultiLayerStratum
virtual uno::Sequence<rtl::OUString> SAL_CALL
listLayerIds( const rtl::OUString& aComponent, const rtl::OUString& aEntity )
throw (backend::BackendAccessException,
lang::IllegalArgumentException,
uno::RuntimeException) ;
virtual rtl::OUString SAL_CALL
getUpdateLayerId( const rtl::OUString& aComponent, const rtl::OUString& aEntity )
throw (backend::BackendAccessException,
lang::IllegalArgumentException,
uno::RuntimeException) ;
virtual uno::Reference<backend::XLayer> SAL_CALL
getLayer( const rtl::OUString& aLayerId, const rtl::OUString& aTimestamp )
throw (backend::BackendAccessException,
lang::IllegalArgumentException,
uno::RuntimeException) ;
virtual uno::Sequence<uno::Reference<backend::XLayer> > SAL_CALL
getLayers(const uno::Sequence<rtl::OUString>& aLayerIds,
const rtl::OUString& aTimestamp)
throw (backend::BackendAccessException,
lang::IllegalArgumentException,
uno::RuntimeException) ;
virtual uno::Sequence<uno::Reference<backend::XLayer> > SAL_CALL
getMultipleLayers(const uno::Sequence<rtl::OUString>& aLayerIds,
const uno::Sequence<rtl::OUString>& aTimestamps)
throw (backend::BackendAccessException,
lang::IllegalArgumentException,
uno::RuntimeException) ;
virtual uno::Reference<backend::XUpdatableLayer> SAL_CALL
getUpdatableLayer( const rtl::OUString& aLayerId )
throw (backend::BackendAccessException,
lang::IllegalArgumentException,
uno::RuntimeException) ;
// XBackendEntities
virtual rtl::OUString SAL_CALL
getOwnerEntity( )
throw (uno::RuntimeException);
virtual rtl::OUString SAL_CALL
getAdminEntity( )
throw (uno::RuntimeException);
virtual sal_Bool SAL_CALL
supportsEntity( const rtl::OUString& aEntity )
throw (backend::BackendAccessException, uno::RuntimeException);
virtual sal_Bool SAL_CALL
isEqualEntity( const rtl::OUString& aEntity, const rtl::OUString& aOtherEntity )
throw (backend::BackendAccessException, lang::IllegalArgumentException, uno::RuntimeException);
// XServiceInfo
virtual rtl::OUString SAL_CALL
getImplementationName( )
throw (uno::RuntimeException) ;
virtual sal_Bool SAL_CALL
supportsService( const rtl::OUString& aServiceName )
throw (uno::RuntimeException) ;
virtual uno::Sequence<rtl::OUString> SAL_CALL
getSupportedServiceNames( )
throw (uno::RuntimeException) ;
/**
Provides the implementation name.
@return implementation name
*/
static rtl::OUString SAL_CALL getName(void) ;
/**
Provides the supported services names
@return service names
*/
static uno::Sequence<rtl::OUString> SAL_CALL getServices(void) ;
public: // helpers for other implementation that need to use the same data
/**
Locates the main layer data and localized data directories in a layer directory hierarchy
*/
static bool getLayerSubDirectories( rtl::OUString const & aLayerBaseUrl,
rtl::OUString& aMainLayerUrl,
rtl::OUString& aSubLayerUrl);
/**
Creates a simple readonly non-composite layer for a component in a base directory
*/
static uno::Reference<backend::XLayer>
createSimpleLayer(const uno::Reference<lang::XMultiServiceFactory>& xFactory,
rtl::OUString const & aLayerBaseUrl,
rtl::OUString const & aComponent);
/**
Creates a simple readonly non-composite layer for a component in a given file
*/
static uno::Reference<backend::XLayer>
createSimpleLayer(const uno::Reference<lang::XMultiServiceFactory>& xFactory,
rtl::OUString const & aComponentUrl);
private :
/** Service factory */
uno::Reference<lang::XMultiServiceFactory> mFactory ;
/** Mutex for resources protection */
osl::Mutex mMutex ;
/**
Base of the schema data. Is a list to allow
for multiple schema directories.
*/
uno::Sequence<rtl::OUString> mSchemaDataUrls ;
/**
Base of the default data. Is a list to allow
for multiple layers of default data.
*/
uno::Sequence<rtl::OUString> mDefaultDataUrls ;
/** Base of the user data */
rtl::OUString mUserDataUrl ;
/** special index for entity */
sal_Int32 findEntity(rtl::OUString const & _aEntity);
/** parse and translate layer-id */
sal_Int32 resolveLayerId(rtl::OUString const & _aLayerId, rtl::OUString & _aFile);
/**
Builds a LocalFileLayer object given a layer id.
Since the LocalFileLayer implements the various
interfaces a layer can be accessed as, a few methods
need one. This method handles the layer id mapping
and the existence or not of sublayers.
@param aLayerId layer id
@return local file layer
@throws com::sun::star::lang::IllegalArgumentException
if the layer id is invalid.
*/
uno::Reference<backend::XUpdatableLayer> getFileLayer(const rtl::OUString& aLayerId)
throw (lang::IllegalArgumentException) ;
/**
Same as above, but using a component URL and layer index
combination instead of a layer id (which encodes both).
@param aComponent component URL
@param aLayerIndex layer index
@return local file layer
*/
uno::Reference<backend::XUpdatableLayer> getFileLayer(const rtl::OUString& aComponent,
sal_Int32 aLayerIndex) ;
/**
Maps a layer index (-1 for user layer, 0-x for defaults)
to the appropriate layer and sublayers base directories.
@param aLayerIndex layer index
@param aLayerUrl layer base URL, filled on return
@param aSubLayerUrl sublayer base URL, filled on return
*/
bool getLayerDirectories(sal_Int32 aLayerIndex,
rtl::OUString& aLayerUrl,
rtl::OUString& aSubLayerUrl) ;
/**
Tells if a file is more recent than a given date.
The date is formatted YYYYMMDDhhmmssZ.
@param aComponent URL of the component to check
@param aLayerIndex index of the layer involved (-1 = user)
@param aTimestamp timestamp to check against
@return sal_True if the file is more recent, sal_False otherwise
*/
sal_Bool isMoreRecent(const rtl::OUString& aComponent,
sal_Int32 aLayerId,
const rtl::OUString& aTimestamp) ;
} ;
} } // configmgr.localbe
#endif // CONFIGMGR_LOCALBE_LOCALSINGLEBACKEND_HXX_
<|endoftext|>
|
<commit_before>// Copyright 2019 DeepMind Technologies Limited.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "reverb/cc/reverb_service_impl.h"
#include <algorithm>
#include <list>
#include <memory>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/strings/str_cat.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "reverb/cc/checkpointing/interface.h"
#include "reverb/cc/platform/logging.h"
#include "reverb/cc/platform/thread.h"
#include "reverb/cc/reverb_service.grpc.pb.h"
#include "reverb/cc/reverb_service.pb.h"
#include "reverb/cc/sampler.h"
#include "reverb/cc/support/cleanup.h"
#include "reverb/cc/support/grpc_util.h"
#include "reverb/cc/support/queue.h"
#include "reverb/cc/support/uint128.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
namespace deepmind {
namespace reverb {
namespace {
inline grpc::Status TableNotFound(absl::string_view name) {
return grpc::Status(grpc::StatusCode::NOT_FOUND,
absl::StrCat("Priority table ", name, " was not found"));
}
inline grpc::Status Internal(const std::string& message) {
return grpc::Status(grpc::StatusCode::INTERNAL, message);
}
} // namespace
ReverbServiceImpl::ReverbServiceImpl(
std::shared_ptr<CheckpointerInterface> checkpointer)
: checkpointer_(std::move(checkpointer)) {}
tensorflow::Status ReverbServiceImpl::Create(
std::vector<std::shared_ptr<Table>> tables,
std::shared_ptr<CheckpointerInterface> checkpointer,
std::unique_ptr<ReverbServiceImpl>* service) {
// Can't use make_unique because it can't see the Impl's private constructor.
auto new_service = std::unique_ptr<ReverbServiceImpl>(
new ReverbServiceImpl(std::move(checkpointer)));
TF_RETURN_IF_ERROR(new_service->Initialize(std::move(tables)));
std::swap(new_service, *service);
return tensorflow::Status::OK();
}
tensorflow::Status ReverbServiceImpl::Create(
std::vector<std::shared_ptr<Table>> tables,
std::unique_ptr<ReverbServiceImpl>* service) {
return Create(std::move(tables), /*checkpointer=*/nullptr, service);
}
tensorflow::Status ReverbServiceImpl::Initialize(
std::vector<std::shared_ptr<Table>> tables) {
if (checkpointer_ != nullptr) {
auto status = checkpointer_->LoadLatest(&chunk_store_, &tables);
if (!status.ok() && !tensorflow::errors::IsNotFound(status)) {
return status;
}
}
for (auto& table : tables) {
tables_[table->name()] = std::move(table);
}
tables_state_id_ = absl::MakeUint128(absl::Uniform<uint64_t>(rnd_),
absl::Uniform<uint64_t>(rnd_));
return tensorflow::Status::OK();
}
grpc::Status ReverbServiceImpl::Checkpoint(grpc::ServerContext* context,
const CheckpointRequest* request,
CheckpointResponse* response) {
if (checkpointer_ == nullptr) {
return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
"no Checkpointer configured for the replay service.");
}
std::vector<Table*> tables;
for (auto& table : tables_) {
tables.push_back(table.second.get());
}
auto status = checkpointer_->Save(std::move(tables), 1,
response->mutable_checkpoint_path());
if (!status.ok()) return ToGrpcStatus(status);
REVERB_LOG(REVERB_INFO) << "Stored checkpoint to "
<< response->checkpoint_path();
return grpc::Status::OK;
}
grpc::Status ReverbServiceImpl::InsertStream(
grpc::ServerContext* context,
grpc::ServerReader<InsertStreamRequest>* reader,
InsertStreamResponse* response) {
return InsertStreamInternal(context, reader, response);
}
grpc::Status ReverbServiceImpl::InsertStreamInternal(
grpc::ServerContext* context,
grpc::ServerReaderInterface<InsertStreamRequest>* reader,
InsertStreamResponse* response) {
// Start a background thread that unpacks the data ahead of time.
deepmind::reverb::internal::Queue<InsertStreamRequest> queue(1);
auto read_thread = internal::StartThread("ReadThread", [reader, &queue]() {
InsertStreamRequest request;
while (reader->Read(&request) && queue.Push(std::move(request))) {
request = InsertStreamRequest();
}
queue.SetLastItemPushed();
});
auto cleanup = internal::MakeCleanup([&queue] { queue.Close(); });
absl::flat_hash_map<ChunkStore::Key, std::shared_ptr<ChunkStore::Chunk>>
chunks;
InsertStreamRequest request;
while (queue.Pop(&request)) {
if (request.has_chunk()) {
ChunkStore::Key key = request.chunk().chunk_key();
std::shared_ptr<ChunkStore::Chunk> chunk =
chunk_store_.Insert(std::move(*request.mutable_chunk()));
if (!chunk) {
return grpc::Status(grpc::StatusCode::CANCELLED,
"Service has been closed");
}
chunks[key] = std::move(chunk);
} else if (request.has_item()) {
Table::Item item;
auto push_or = [&chunks, &item](ChunkStore::Key key) -> grpc::Status {
auto it = chunks.find(key);
if (it == chunks.end()) {
return Internal(
absl::StrCat("Could not find sequence chunk ", key, "."));
}
item.chunks.push_back(it->second);
return grpc::Status::OK;
};
for (ChunkStore::Key key : request.item().item().chunk_keys()) {
auto status = push_or(key);
if (!status.ok()) return status;
}
const auto& table_name = request.item().item().table();
Table* table = PriorityTableByName(table_name);
if (table == nullptr) return TableNotFound(table_name);
item.item = *request.mutable_item()->mutable_item();
if (auto status = table->InsertOrAssign(item); !status.ok()) {
return ToGrpcStatus(status);
}
// Only keep specified chunks.
absl::flat_hash_set<int64_t> keep_keys{
request.item().keep_chunk_keys().begin(),
request.item().keep_chunk_keys().end()};
for (auto it = chunks.cbegin(); it != chunks.cend();) {
if (keep_keys.find(it->first) == keep_keys.end()) {
chunks.erase(it++);
} else {
++it;
}
}
REVERB_CHECK_EQ(chunks.size(), keep_keys.size())
<< "Kept less chunks than expected.";
}
}
return grpc::Status::OK;
}
grpc::Status ReverbServiceImpl::MutatePriorities(
grpc::ServerContext* context, const MutatePrioritiesRequest* request,
MutatePrioritiesResponse* response) {
Table* table = PriorityTableByName(request->table());
if (table == nullptr) return TableNotFound(request->table());
auto status = table->MutateItems(
std::vector<KeyWithPriority>(request->updates().begin(),
request->updates().end()),
request->delete_keys());
if (!status.ok()) return ToGrpcStatus(status);
return grpc::Status::OK;
}
grpc::Status ReverbServiceImpl::Reset(grpc::ServerContext* context,
const ResetRequest* request,
ResetResponse* response) {
Table* table = PriorityTableByName(request->table());
if (table == nullptr) return TableNotFound(request->table());
auto status = table->Reset();
if (!status.ok()) {
return ToGrpcStatus(status);
}
return grpc::Status::OK;
}
grpc::Status ReverbServiceImpl::SampleStream(
grpc::ServerContext* context,
grpc::ServerReaderWriter<SampleStreamResponse, SampleStreamRequest>*
stream) {
return SampleStreamInternal(context, stream);
}
grpc::Status ReverbServiceImpl::SampleStreamInternal(
grpc::ServerContext* context,
grpc::ServerReaderWriterInterface<SampleStreamResponse,
SampleStreamRequest>* stream) {
SampleStreamRequest request;
if (!stream->Read(&request)) {
return Internal("Could not read initial request");
}
int64_t timeout_ms = request.has_rate_limiter_timeout()
? request.rate_limiter_timeout().milliseconds()
: -1;
absl::Duration timeout = (timeout_ms < 0) ? absl::InfiniteDuration()
: absl::Milliseconds(timeout_ms);
do {
if (request.num_samples() <= 0) {
return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
"`num_samples` must be > 0.");
}
if (request.flexible_batch_size() <= 0 &&
request.flexible_batch_size() != Sampler::kAutoSelectValue) {
return grpc::Status(
grpc::StatusCode::INVALID_ARGUMENT,
absl::StrCat("`flexible_batch_size` must be > 0 or ",
Sampler::kAutoSelectValue, " (for auto tuning)."));
}
Table* table = PriorityTableByName(request.table());
if (table == nullptr) return TableNotFound(request.table());
int32_t default_flexible_batch_size = table->DefaultFlexibleBatchSize();
int count = 0;
while (!context->IsCancelled() && count != request.num_samples()) {
std::vector<Table::SampledItem> samples;
int32_t max_batch_size = std::min<int32_t>(
request.flexible_batch_size() == Sampler::kAutoSelectValue
? default_flexible_batch_size
: request.flexible_batch_size(),
request.num_samples() - count);
if (auto status =
table->SampleFlexibleBatch(&samples, max_batch_size, timeout);
!status.ok()) {
return ToGrpcStatus(status);
}
count += samples.size();
for (auto& sample : samples) {
for (int i = 0; i < sample.chunks.size(); i++) {
SampleStreamResponse response;
response.set_end_of_sequence(i + 1 == sample.chunks.size());
// Attach the info to the first message.
if (i == 0) {
*response.mutable_info()->mutable_item() = sample.item;
response.mutable_info()->set_probability(sample.probability);
response.mutable_info()->set_table_size(sample.table_size);
}
// We const cast to avoid copying the proto.
response.set_allocated_data(
const_cast<ChunkData*>(&sample.chunks[i]->data()));
grpc::WriteOptions options;
options.set_no_compression(); // Data is already compressed.
bool ok = stream->Write(response, options);
response.release_data();
if (!ok) {
return Internal("Failed to write to Sample stream.");
}
// We no longer need our chunk reference, so we free it.
sample.chunks[i] = nullptr;
}
}
}
request.Clear();
} while (stream->Read(&request));
return grpc::Status::OK;
}
Table* ReverbServiceImpl::PriorityTableByName(absl::string_view name) const {
auto it = tables_.find(name);
if (it == tables_.end()) return nullptr;
return it->second.get();
}
void ReverbServiceImpl::Close() {
for (auto& table : tables_) {
table.second->Close();
}
}
grpc::Status ReverbServiceImpl::ServerInfo(grpc::ServerContext* context,
const ServerInfoRequest* request,
ServerInfoResponse* response) {
for (const auto& iter : tables_) {
*response->add_table_info() = iter.second->info();
}
*response->mutable_tables_state_id() = Uint128ToMessage(tables_state_id_);
return grpc::Status::OK;
}
absl::flat_hash_map<std::string, std::shared_ptr<Table>>
ReverbServiceImpl::tables() const {
return tables_;
}
} // namespace reverb
} // namespace deepmind
<commit_msg>Internal change<commit_after>// Copyright 2019 DeepMind Technologies Limited.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "reverb/cc/reverb_service_impl.h"
#include <algorithm>
#include <list>
#include <memory>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/strings/str_cat.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "reverb/cc/checkpointing/interface.h"
#include "reverb/cc/platform/logging.h"
#include "reverb/cc/platform/thread.h"
#include "reverb/cc/reverb_service.grpc.pb.h"
#include "reverb/cc/reverb_service.pb.h"
#include "reverb/cc/sampler.h"
#include "reverb/cc/support/cleanup.h"
#include "reverb/cc/support/grpc_util.h"
#include "reverb/cc/support/queue.h"
#include "reverb/cc/support/uint128.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
namespace deepmind {
namespace reverb {
namespace {
inline grpc::Status TableNotFound(absl::string_view name) {
return grpc::Status(grpc::StatusCode::NOT_FOUND,
absl::StrCat("Priority table ", name, " was not found"));
}
inline grpc::Status Internal(const std::string& message) {
return grpc::Status(grpc::StatusCode::INTERNAL, message);
}
} // namespace
ReverbServiceImpl::ReverbServiceImpl(
std::shared_ptr<CheckpointerInterface> checkpointer)
: checkpointer_(std::move(checkpointer)) {}
tensorflow::Status ReverbServiceImpl::Create(
std::vector<std::shared_ptr<Table>> tables,
std::shared_ptr<CheckpointerInterface> checkpointer,
std::unique_ptr<ReverbServiceImpl>* service) {
// Can't use make_unique because it can't see the Impl's private constructor.
auto new_service = std::unique_ptr<ReverbServiceImpl>(
new ReverbServiceImpl(std::move(checkpointer)));
TF_RETURN_IF_ERROR(new_service->Initialize(std::move(tables)));
std::swap(new_service, *service);
return tensorflow::Status::OK();
}
tensorflow::Status ReverbServiceImpl::Create(
std::vector<std::shared_ptr<Table>> tables,
std::unique_ptr<ReverbServiceImpl>* service) {
return Create(std::move(tables), /*checkpointer=*/nullptr, service);
}
tensorflow::Status ReverbServiceImpl::Initialize(
std::vector<std::shared_ptr<Table>> tables) {
if (checkpointer_ != nullptr) {
auto status = checkpointer_->LoadLatest(&chunk_store_, &tables);
if (!status.ok() && !tensorflow::errors::IsNotFound(status)) {
return status;
}
}
for (auto& table : tables) {
tables_[table->name()] = std::move(table);
}
tables_state_id_ = absl::MakeUint128(absl::Uniform<uint64_t>(rnd_),
absl::Uniform<uint64_t>(rnd_));
return tensorflow::Status::OK();
}
grpc::Status ReverbServiceImpl::Checkpoint(grpc::ServerContext* context,
const CheckpointRequest* request,
CheckpointResponse* response) {
if (checkpointer_ == nullptr) {
return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
"no Checkpointer configured for the replay service.");
}
std::vector<Table*> tables;
for (auto& table : tables_) {
tables.push_back(table.second.get());
}
auto status = checkpointer_->Save(std::move(tables), 1,
response->mutable_checkpoint_path());
if (!status.ok()) return ToGrpcStatus(status);
REVERB_LOG(REVERB_INFO) << "Stored checkpoint to "
<< response->checkpoint_path();
return grpc::Status::OK;
}
grpc::Status ReverbServiceImpl::InsertStream(
grpc::ServerContext* context,
grpc::ServerReader<InsertStreamRequest>* reader,
InsertStreamResponse* response) {
return InsertStreamInternal(context, reader, response);
}
grpc::Status ReverbServiceImpl::InsertStreamInternal(
grpc::ServerContext* context,
grpc::ServerReaderInterface<InsertStreamRequest>* reader,
InsertStreamResponse* response) {
// Start a background thread that unpacks the data ahead of time.
deepmind::reverb::internal::Queue<InsertStreamRequest> queue(1);
auto read_thread = internal::StartThread("ReadThread", [reader, &queue]() {
InsertStreamRequest request;
while (reader->Read(&request) && queue.Push(std::move(request))) {
request = InsertStreamRequest();
}
queue.SetLastItemPushed();
});
auto cleanup = internal::MakeCleanup([&queue] { queue.Close(); });
absl::flat_hash_map<ChunkStore::Key, std::shared_ptr<ChunkStore::Chunk>>
chunks;
InsertStreamRequest request;
while (queue.Pop(&request)) {
if (request.has_chunk()) {
ChunkStore::Key key = request.chunk().chunk_key();
std::shared_ptr<ChunkStore::Chunk> chunk =
chunk_store_.Insert(std::move(*request.mutable_chunk()));
if (!chunk) {
return grpc::Status(grpc::StatusCode::CANCELLED,
"Service has been closed");
}
chunks[key] = std::move(chunk);
} else if (request.has_item()) {
Table::Item item;
auto push_or = [&chunks, &item](ChunkStore::Key key) -> grpc::Status {
auto it = chunks.find(key);
if (it == chunks.end()) {
return Internal(
absl::StrCat("Could not find sequence chunk ", key, "."));
}
item.chunks.push_back(it->second);
return grpc::Status::OK;
};
for (ChunkStore::Key key : request.item().item().chunk_keys()) {
auto status = push_or(key);
if (!status.ok()) return status;
}
const auto& table_name = request.item().item().table();
Table* table = PriorityTableByName(table_name);
if (table == nullptr) return TableNotFound(table_name);
item.item = *request.mutable_item()->mutable_item();
if (auto status = table->InsertOrAssign(item); !status.ok()) {
return ToGrpcStatus(status);
}
// Only keep specified chunks.
absl::flat_hash_set<int64_t> keep_keys{
request.item().keep_chunk_keys().begin(),
request.item().keep_chunk_keys().end()};
for (auto it = chunks.cbegin(); it != chunks.cend();) {
if (keep_keys.find(it->first) == keep_keys.end()) {
chunks.erase(it++);
} else {
++it;
}
}
REVERB_CHECK_EQ(chunks.size(), keep_keys.size())
<< "Kept less chunks than expected.";
}
}
return grpc::Status::OK;
}
grpc::Status ReverbServiceImpl::MutatePriorities(
grpc::ServerContext* context, const MutatePrioritiesRequest* request,
MutatePrioritiesResponse* response) {
Table* table = PriorityTableByName(request->table());
if (table == nullptr) return TableNotFound(request->table());
auto status = table->MutateItems(
std::vector<KeyWithPriority>(request->updates().begin(),
request->updates().end()),
request->delete_keys());
if (!status.ok()) return ToGrpcStatus(status);
return grpc::Status::OK;
}
grpc::Status ReverbServiceImpl::Reset(grpc::ServerContext* context,
const ResetRequest* request,
ResetResponse* response) {
Table* table = PriorityTableByName(request->table());
if (table == nullptr) return TableNotFound(request->table());
auto status = table->Reset();
if (!status.ok()) {
return ToGrpcStatus(status);
}
return grpc::Status::OK;
}
grpc::Status ReverbServiceImpl::SampleStream(
grpc::ServerContext* context,
grpc::ServerReaderWriter<SampleStreamResponse, SampleStreamRequest>*
stream) {
return SampleStreamInternal(context, stream);
}
grpc::Status ReverbServiceImpl::SampleStreamInternal(
grpc::ServerContext* context,
grpc::ServerReaderWriterInterface<SampleStreamResponse,
SampleStreamRequest>* stream) {
SampleStreamRequest request;
if (!stream->Read(&request)) {
return Internal("Could not read initial request");
}
absl::Duration timeout =
request.has_rate_limiter_timeout()
? absl::Milliseconds(request.rate_limiter_timeout().milliseconds())
: absl::InfiniteDuration();
do {
if (request.num_samples() <= 0) {
return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT,
"`num_samples` must be > 0.");
}
if (request.flexible_batch_size() <= 0 &&
request.flexible_batch_size() != Sampler::kAutoSelectValue) {
return grpc::Status(
grpc::StatusCode::INVALID_ARGUMENT,
absl::StrCat("`flexible_batch_size` must be > 0 or ",
Sampler::kAutoSelectValue, " (for auto tuning)."));
}
Table* table = PriorityTableByName(request.table());
if (table == nullptr) return TableNotFound(request.table());
int32_t default_flexible_batch_size = table->DefaultFlexibleBatchSize();
int count = 0;
while (!context->IsCancelled() && count != request.num_samples()) {
std::vector<Table::SampledItem> samples;
int32_t max_batch_size = std::min<int32_t>(
request.flexible_batch_size() == Sampler::kAutoSelectValue
? default_flexible_batch_size
: request.flexible_batch_size(),
request.num_samples() - count);
if (auto status =
table->SampleFlexibleBatch(&samples, max_batch_size, timeout);
!status.ok()) {
return ToGrpcStatus(status);
}
count += samples.size();
for (auto& sample : samples) {
for (int i = 0; i < sample.chunks.size(); i++) {
SampleStreamResponse response;
response.set_end_of_sequence(i + 1 == sample.chunks.size());
// Attach the info to the first message.
if (i == 0) {
*response.mutable_info()->mutable_item() = sample.item;
response.mutable_info()->set_probability(sample.probability);
response.mutable_info()->set_table_size(sample.table_size);
}
// We const cast to avoid copying the proto.
response.set_allocated_data(
const_cast<ChunkData*>(&sample.chunks[i]->data()));
grpc::WriteOptions options;
options.set_no_compression(); // Data is already compressed.
bool ok = stream->Write(response, options);
response.release_data();
if (!ok) {
return Internal("Failed to write to Sample stream.");
}
// We no longer need our chunk reference, so we free it.
sample.chunks[i] = nullptr;
}
}
}
request.Clear();
} while (stream->Read(&request));
return grpc::Status::OK;
}
Table* ReverbServiceImpl::PriorityTableByName(absl::string_view name) const {
auto it = tables_.find(name);
if (it == tables_.end()) return nullptr;
return it->second.get();
}
void ReverbServiceImpl::Close() {
for (auto& table : tables_) {
table.second->Close();
}
}
grpc::Status ReverbServiceImpl::ServerInfo(grpc::ServerContext* context,
const ServerInfoRequest* request,
ServerInfoResponse* response) {
for (const auto& iter : tables_) {
*response->add_table_info() = iter.second->info();
}
*response->mutable_tables_state_id() = Uint128ToMessage(tables_state_id_);
return grpc::Status::OK;
}
absl::flat_hash_map<std::string, std::shared_ptr<Table>>
ReverbServiceImpl::tables() const {
return tables_;
}
} // namespace reverb
} // namespace deepmind
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: xlstyle.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2003-04-08 16:29:30 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
// ============================================================================
#ifndef SC_XLSTYLE_HXX
#define SC_XLSTYLE_HXX
#ifndef SC_XLTOOLS_HXX
#include "xltools.hxx"
#endif
// Color data =================================================================
/** Stores all default colors for a specific BIFF version. */
class XclDefaultPalette
{
private:
const ColorData* mpColorTable; /// The table with RGB values.
sal_uInt32 mnTableSize; /// The color table size.
sal_uInt16 mnIndexOffset; /// The Excel index of the first color.
public:
explicit XclDefaultPalette( XclBiff eBiff = xlBiffUnknown );
/** Activates the default colors for the passed BIFF version. */
void SetDefaultColors( XclBiff eBiff );
/** Returns the color count in the current palette. */
inline sal_uInt32 GetColorCount() const { return mnTableSize; }
/** Returns the Excel index of the first color. */
inline sal_uInt32 GetIndexOffset() const { return mnIndexOffset; }
/** Returns the Excel index of a 0-based color index. */
inline sal_uInt16 GetXclIndex( sal_uInt32 nIndex ) const;
/** Returns the default RGB color data for a (non-zero-based) Excel color or nDefault on error. */
ColorData GetDefColorData( sal_uInt16 nXclIndex, ColorData nDefault = COL_AUTO ) const;
/** Returns the default color for a (non-zero-based) Excel color or nDefault on error. */
inline Color GetDefColor( sal_uInt16 nXclIndex, ColorData nDefault = COL_AUTO ) const;
};
inline sal_uInt16 XclDefaultPalette::GetXclIndex( sal_uInt32 nIndex ) const
{
return static_cast< sal_uInt16 >( nIndex + GetIndexOffset() );
}
inline Color XclDefaultPalette::GetDefColor( sal_uInt16 nXclIndex, ColorData nDefault ) const
{
return Color( GetDefColorData( nXclIndex, nDefault ) );
}
// Font data ==================================================================
/** Text underline style. */
enum XclUnderline
{
xlUnderlNone = 0x00,
xlUnderlSingle = 0x01,
xlUnderlDouble = 0x02,
xlUnderlSingleAcc = 0x21,
xlUnderlDoubleAcc = 0x22
};
/** Super-/subscript type. */
enum XclEscapement
{
xlEscNone = 0x00,
xlEscSuper = 0x01,
xlEscSub = 0x02
};
// ----------------------------------------------------------------------------
/** This struct helps reading and writing Excel fonts.
@descr It stores all Excel compatible properties of a font. In detail this is the
name, family, character set, height, color, boldness, posture, script, underline,
strikeout, outline and shadow of the font. */
struct XclFontData
{
String maName; /// Font name.
String maStyle; /// String with styles (bold, italic).
XclUnderline meUnderline; /// Underline style.
XclEscapement meEscapem; /// Super-/subscript.
sal_uInt16 mnHeight; /// Font height in twips (1/20 of a point).
sal_uInt16 mnColor; /// Index to color palette.
sal_uInt16 mnWeight; /// Boldness: 400=normal, 700=bold.
sal_uInt8 mnFamily; /// Font family.
sal_uInt8 mnCharSet; /// Character set.
bool mbItalic; /// true = Italic.
bool mbStrikeout; /// true = Struck out.
bool mbOutline; /// true = Outlined.
bool mbShadow; /// true = Shadowed.
inline explicit XclFontData() { Clear(); }
/** Resets all members to default (empty) values. */
void Clear();
};
// Cell formatting data (XF) ==================================================
/** Contains all cell protection attributes. */
struct XclCellProt
{
bool mbLocked; /// true = Locked against editing.
bool mbHidden; /// true = Formula is hidden.
explicit XclCellProt();
};
bool operator==( const XclCellProt& rLeft, const XclCellProt& rRight );
// ----------------------------------------------------------------------------
/** Horizontal alignment of cell contents. */
enum XclHorAlign
{
xlHAlignGeneral = 0x00,
xlHAlignLeft = 0x01,
xlHAlignCenter = 0x02,
xlHAlignRight = 0x03,
xlHAlignFill = 0x04,
xlHAlignJustify = 0x05,
xlHAlignCenterAcrSel = 0x06,
xlHAlignDistrib = 0x07,
xlHAlign_Default = xlHAlignGeneral
};
/** Vertical alignment of cell contents. */
enum XclVerAlign
{
xlVAlignTop = 0x00,
xlVAlignCenter = 0x01,
xlVAlignBottom = 0x02,
xlVAlignJustify = 0x03,
xlVAlignDistrib = 0x04,
xlVAlign_Default = xlVAlignBottom
};
/** Text orientation. */
enum XclTextOrient
{
xlTextOrientNoRot = 0x00,
xlTextOrientTopBottom = 0x01,
xlTextOrient90ccw = 0x02,
xlTextOrient90cw = 0x03,
xlTextOrient_Default = xlTextOrientNoRot
};
/** CTL text direction. */
enum XclTextDirection
{
xlTextDirContext = 0x00,
xlTextDirLTR = 0x01,
xlTextDirRTL = 0x02,
xlTextDir_Default = xlTextDirContext
};
/** Contains all cell alignment attributes. */
struct XclCellAlign
{
XclHorAlign meHorAlign; /// Horizontal alignment.
XclVerAlign meVerAlign; /// Vertical alignment.
XclTextDirection meTextDir; /// CTL text direction.
XclTextOrient meOrient; /// Text orientation.
sal_uInt8 mnRotation; /// Text rotation angle.
sal_uInt8 mnIndent; /// Indentation.
bool mbWrapped; /// true = Multi-line text.
explicit XclCellAlign();
};
bool operator==( const XclCellAlign& rLeft, const XclCellAlign& rRight );
// ----------------------------------------------------------------------------
/** Contains color and line style for each cell border line. */
struct XclCellBorder
{
sal_uInt16 mnLeftColor; /// Palette index for left line.
sal_uInt16 mnRightColor; /// Palette index for right line.
sal_uInt16 mnTopColor; /// Palette index for top line.
sal_uInt16 mnBottomColor; /// Palette index for bottom line.
sal_uInt8 mnLeftLine; /// Style of left line.
sal_uInt8 mnRightLine; /// Style of right line.
sal_uInt8 mnTopLine; /// Style of top line.
sal_uInt8 mnBottomLine; /// Style of bottom line.
explicit XclCellBorder();
};
bool operator==( const XclCellBorder& rLeft, const XclCellBorder& rRight );
// ----------------------------------------------------------------------------
/** Contains background colors and pattern for a cell. */
struct XclCellArea
{
sal_uInt16 mnForeColor; /// Palette index to foreground color.
sal_uInt16 mnBackColor; /// Palette index to background color.
sal_uInt8 mnPattern; /// Fill pattern.
explicit XclCellArea();
/** Returns true, if the area represents transparent state. */
bool IsTransparent() const;
};
bool operator==( const XclCellArea& rLeft, const XclCellArea& rRight );
// ----------------------------------------------------------------------------
/** Contains base members for XF record import/export.
@In detail this class stores the XF type (cell/style), the index to the parent
style XF and all "attribute used" flags, which reflect the state of specific
attribute groups (true = user has changed the attributes). */
class XclXFBase
{
protected:
sal_uInt16 mnParent; /// Index to parent style XF.
bool mbCellXF; /// true = cell XF, false = style XF.
bool mbProtUsed; /// true = cell protection used.
bool mbFontUsed; /// true = font index used.
bool mbFmtUsed; /// true = number format used.
bool mbAlignUsed; /// true = alignment used.
bool mbBorderUsed; /// true = border data used.
bool mbAreaUsed; /// true = area data used.
public:
explicit XclXFBase( bool bCellXF );
/** Sets all "attribute used" flags to the passed state. */
void SetAllUsedFlags( bool bUsed );
inline bool IsCellXF() const { return mbCellXF; }
inline bool IsStyleXF() const { return !IsCellXF(); }
protected:
/** Returns true, if this object is equal to the passed. */
bool Equals( const XclXFBase& rCmp ) const;
};
// Page format ================================================================
/** The type of a margin value. */
enum XclMarginType
{
xlLeftMargin,
xlRightMargin,
xlTopMargin,
xlBottomMargin
};
/** Orientation for page breaks. */
enum XclPBOrientation
{
xlPBHorizontal,
xlPBVertical
};
// ============================================================================
#endif
<commit_msg>INTEGRATION: CWS apps61beta2 (1.1.4.2.24); FILE MERGED 2003/04/11 11:43:44 dr 1.1.4.2.24.2: #108487# export of column width 2003/04/10 12:50:17 dr 1.1.4.2.24.1: #105933# needs changes from CWS calc06 (#107688#)<commit_after>/*************************************************************************
*
* $RCSfile: xlstyle.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2003-04-28 15:40:41 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
// ============================================================================
#ifndef SC_XLSTYLE_HXX
#define SC_XLSTYLE_HXX
#ifndef _VCL_VCLENUM_HXX
#include <vcl/vclenum.hxx>
#endif
#ifndef _SVX_SVXENUM_HXX
#include <svx/svxenum.hxx>
#endif
#ifndef SC_XLTOOLS_HXX
#include "xltools.hxx"
#endif
// Color data =================================================================
/** Stores all default colors for a specific BIFF version. */
class XclDefaultPalette
{
private:
const ColorData* mpColorTable; /// The table with RGB values.
sal_uInt32 mnTableSize; /// The color table size.
sal_uInt16 mnIndexOffset; /// The Excel index of the first color.
public:
explicit XclDefaultPalette( XclBiff eBiff = xlBiffUnknown );
/** Activates the default colors for the passed BIFF version. */
void SetDefaultColors( XclBiff eBiff );
/** Returns the color count in the current palette. */
inline sal_uInt32 GetColorCount() const { return mnTableSize; }
/** Returns the Excel index of the first color. */
inline sal_uInt32 GetIndexOffset() const { return mnIndexOffset; }
/** Returns the Excel index of a 0-based color index. */
inline sal_uInt16 GetXclIndex( sal_uInt32 nIndex ) const;
/** Returns the default RGB color data for a (non-zero-based) Excel color or nDefault on error. */
ColorData GetDefColorData( sal_uInt16 nXclIndex, ColorData nDefault = COL_AUTO ) const;
/** Returns the default color for a (non-zero-based) Excel color or nDefault on error. */
inline Color GetDefColor( sal_uInt16 nXclIndex, ColorData nDefault = COL_AUTO ) const;
};
inline sal_uInt16 XclDefaultPalette::GetXclIndex( sal_uInt32 nIndex ) const
{
return static_cast< sal_uInt16 >( nIndex + GetIndexOffset() );
}
inline Color XclDefaultPalette::GetDefColor( sal_uInt16 nXclIndex, ColorData nDefault ) const
{
return Color( GetDefColorData( nXclIndex, nDefault ) );
}
// Font data ==================================================================
/** Text underline style. */
enum XclUnderline
{
xlUnderlNone = 0x00,
xlUnderlSingle = 0x01,
xlUnderlDouble = 0x02,
xlUnderlSingleAcc = 0x21,
xlUnderlDoubleAcc = 0x22
};
/** Super-/subscript type. */
enum XclEscapement
{
xlEscNone = 0x00,
xlEscSuper = 0x01,
xlEscSub = 0x02
};
// ----------------------------------------------------------------------------
class Font;
/** This struct helps reading and writing Excel fonts.
@descr It stores all Excel compatible properties of a font. In detail this is the
name, family, character set, height, color, boldness, posture, script, underline,
strikeout, outline and shadow of the font. */
struct XclFontData
{
String maName; /// Font name.
String maStyle; /// String with styles (bold, italic).
XclUnderline meUnderline; /// Underline style.
XclEscapement meEscapem; /// Super-/subscript.
sal_uInt16 mnHeight; /// Font height in twips (1/20 of a point).
sal_uInt16 mnColor; /// Index to color palette.
sal_uInt16 mnWeight; /// Boldness: 400=normal, 700=bold.
sal_uInt8 mnFamily; /// Windows font family.
sal_uInt8 mnCharSet; /// Windows character set.
bool mbItalic; /// true = Italic.
bool mbStrikeout; /// true = Struck out.
bool mbOutline; /// true = Outlined.
bool mbShadow; /// true = Shadowed.
/** Constructs an empty font data structure. */
explicit XclFontData();
/** Constructs a font data structure and fills it with the passed font attributes (except color). */
explicit XclFontData( const Font& rFont );
/** Resets all members to default (empty) values. */
void Clear();
/** Fills all members (except color) from the passed font. */
void FillFromFont( const Font& rFont );
/** Returns the Calc font family. */
FontFamily GetScFamily( CharSet eDefCharSet ) const;
/** Returns the Calc font character set. */
CharSet GetScCharSet() const;
/** Returns the Calc font posture. */
FontItalic GetScPosture() const;
/** Returns the Calc font weight. */
FontWeight GetScWeight() const;
/** Returns the Calc font underline style. */
FontUnderline GetScUnderline() const;
/** Returns the Calc escapement style. */
SvxEscapement GetScEscapement() const;
/** Returns the Calc strike-out style. */
FontStrikeout GetScStrikeout() const;
/** Sets the Calc font height (in twips). */
void SetScHeight( sal_Int32 nTwips );
/** Sets the Calc font family. */
void SetScFamily( FontFamily eScFamily );
/** Sets the Calc character set. */
void SetScCharSet( CharSet eScCharSet );
/** Sets the Calc font posture. */
void SetScPosture( FontItalic eScPosture );
/** Sets the Calc font weight. */
void SetScWeight( FontWeight eScWeight );
/** Sets the Calc underline style. */
void SetScUnderline( FontUnderline eScUnderl );
/** Sets the Calc escapement style. */
void SetScEscapement( SvxEscapement eScEscapem );
/** Sets the Calc strike-out style. */
void SetScStrikeout( FontStrikeout eScStrikeout );
};
bool operator==( const XclFontData& rLeft, const XclFontData& rRight );
// Cell formatting data (XF) ==================================================
/** Contains all cell protection attributes. */
struct XclCellProt
{
bool mbLocked; /// true = Locked against editing.
bool mbHidden; /// true = Formula is hidden.
explicit XclCellProt();
};
bool operator==( const XclCellProt& rLeft, const XclCellProt& rRight );
// ----------------------------------------------------------------------------
/** Horizontal alignment of cell contents. */
enum XclHorAlign
{
xlHAlignGeneral = 0x00,
xlHAlignLeft = 0x01,
xlHAlignCenter = 0x02,
xlHAlignRight = 0x03,
xlHAlignFill = 0x04,
xlHAlignJustify = 0x05,
xlHAlignCenterAcrSel = 0x06,
xlHAlignDistrib = 0x07,
xlHAlign_Default = xlHAlignGeneral
};
/** Vertical alignment of cell contents. */
enum XclVerAlign
{
xlVAlignTop = 0x00,
xlVAlignCenter = 0x01,
xlVAlignBottom = 0x02,
xlVAlignJustify = 0x03,
xlVAlignDistrib = 0x04,
xlVAlign_Default = xlVAlignBottom
};
/** Text orientation. */
enum XclTextOrient
{
xlTextOrientNoRot = 0x00,
xlTextOrientTopBottom = 0x01,
xlTextOrient90ccw = 0x02,
xlTextOrient90cw = 0x03,
xlTextOrient_Default = xlTextOrientNoRot
};
/** CTL text direction. */
enum XclTextDirection
{
xlTextDirContext = 0x00,
xlTextDirLTR = 0x01,
xlTextDirRTL = 0x02,
xlTextDir_Default = xlTextDirContext
};
/** Contains all cell alignment attributes. */
struct XclCellAlign
{
XclHorAlign meHorAlign; /// Horizontal alignment.
XclVerAlign meVerAlign; /// Vertical alignment.
XclTextDirection meTextDir; /// CTL text direction.
XclTextOrient meOrient; /// Text orientation.
sal_uInt8 mnRotation; /// Text rotation angle.
sal_uInt8 mnIndent; /// Indentation.
bool mbWrapped; /// true = Multi-line text.
explicit XclCellAlign();
};
bool operator==( const XclCellAlign& rLeft, const XclCellAlign& rRight );
// ----------------------------------------------------------------------------
/** Contains color and line style for each cell border line. */
struct XclCellBorder
{
sal_uInt16 mnLeftColor; /// Palette index for left line.
sal_uInt16 mnRightColor; /// Palette index for right line.
sal_uInt16 mnTopColor; /// Palette index for top line.
sal_uInt16 mnBottomColor; /// Palette index for bottom line.
sal_uInt8 mnLeftLine; /// Style of left line.
sal_uInt8 mnRightLine; /// Style of right line.
sal_uInt8 mnTopLine; /// Style of top line.
sal_uInt8 mnBottomLine; /// Style of bottom line.
explicit XclCellBorder();
};
bool operator==( const XclCellBorder& rLeft, const XclCellBorder& rRight );
// ----------------------------------------------------------------------------
/** Contains background colors and pattern for a cell. */
struct XclCellArea
{
sal_uInt16 mnForeColor; /// Palette index to foreground color.
sal_uInt16 mnBackColor; /// Palette index to background color.
sal_uInt8 mnPattern; /// Fill pattern.
explicit XclCellArea();
/** Returns true, if the area represents transparent state. */
bool IsTransparent() const;
};
bool operator==( const XclCellArea& rLeft, const XclCellArea& rRight );
// ----------------------------------------------------------------------------
/** Contains base members for XF record import/export.
@In detail this class stores the XF type (cell/style), the index to the parent
style XF and all "attribute used" flags, which reflect the state of specific
attribute groups (true = user has changed the attributes). */
class XclXFBase
{
protected:
sal_uInt16 mnParent; /// Index to parent style XF.
bool mbCellXF; /// true = cell XF, false = style XF.
bool mbProtUsed; /// true = cell protection used.
bool mbFontUsed; /// true = font index used.
bool mbFmtUsed; /// true = number format used.
bool mbAlignUsed; /// true = alignment used.
bool mbBorderUsed; /// true = border data used.
bool mbAreaUsed; /// true = area data used.
public:
explicit XclXFBase( bool bCellXF );
/** Sets all "attribute used" flags to the passed state. */
void SetAllUsedFlags( bool bUsed );
inline bool IsCellXF() const { return mbCellXF; }
inline bool IsStyleXF() const { return !IsCellXF(); }
protected:
/** Returns true, if this object is equal to the passed. */
bool Equals( const XclXFBase& rCmp ) const;
};
// Page format ================================================================
/** The type of a margin value. */
enum XclMarginType
{
xlLeftMargin,
xlRightMargin,
xlTopMargin,
xlBottomMargin
};
/** Orientation for page breaks. */
enum XclPBOrientation
{
xlPBHorizontal,
xlPBVertical
};
// ============================================================================
#endif
<|endoftext|>
|
<commit_before>#ifndef ITER_GROUP_BY_HPP_
#define ITER_GROUP_BY_HPP_
#include "iterbase.hpp"
#include <utility>
#include <iterator>
#include <initializer_list>
namespace iter {
template <typename Container, typename KeyFunc>
class GroupBy;
template <typename Container, typename KeyFunc>
GroupBy<Container, KeyFunc> groupby(Container&&, KeyFunc);
template <typename T, typename KeyFunc>
GroupBy<std::initializer_list<T>, KeyFunc> groupby(
std::initializer_list<T>, KeyFunc);
template <typename Container, typename KeyFunc>
class GroupBy {
private:
Container container;
KeyFunc key_func;
friend GroupBy groupby<Container, KeyFunc>(Container&&, KeyFunc);
template <typename T, typename KF>
friend GroupBy<std::initializer_list<T>, KF> groupby(
std::initializer_list<T>, KF);
using key_func_ret =
decltype(std::declval<KeyFunc>()(
std::declval<iterator_deref<Container>>()));
GroupBy(Container&& container, KeyFunc key_func)
: container(std::forward<Container>(container)),
key_func(key_func)
{ }
public:
GroupBy() = delete;
GroupBy(const GroupBy&) = delete;
GroupBy& operator=(const GroupBy&) = delete;
GroupBy& operator=(GroupBy&&) = delete;
GroupBy(GroupBy&&) = default;
class Iterator;
class Group;
private:
using KeyGroupPair =
std::pair<key_func_ret, Group>;
public:
class Iterator
: public std::iterator<std::input_iterator_tag, KeyGroupPair>
{
private:
iterator_type<Container> sub_iter;
iterator_type<Container> sub_iter_peek;
iterator_type<Container> sub_end;
KeyFunc key_func;
public:
Iterator (iterator_type<Container> si,
iterator_type<Container> end,
KeyFunc key_func)
: sub_iter{si},
sub_end{end},
key_func(key_func)
{ }
KeyGroupPair operator*() {
return KeyGroupPair(
this->key_func(*this->sub_iter),
Group(
*this,
this->key_func(*this->sub_iter)));
}
Iterator& operator++() {
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator&) const {
return !this->exhausted();
}
bool operator==(const Iterator& other) const {
return !(*this != other);
}
void increment_iterator() {
if (this->sub_iter != this->sub_end) {
++this->sub_iter;
}
}
bool exhausted() const {
return !(this->sub_iter != this->sub_end);
}
iterator_deref<Container> current() {
return *this->sub_iter;
}
key_func_ret next_key() {
return this->key_func(*this->sub_iter);
}
};
class Group {
private:
friend Iterator;
friend class GroupIterator;
Iterator& owner;
key_func_ret key;
// completed is set if a Group is iterated through
// completely. It is checked in the destructor, and
// if the Group has not been completed, the destructor
// exhausts it. This ensures that the next Group starts
// at the correct position when the user short-circuits
// iteration over a Group.
// The move constructor sets the rvalue's completed
// attribute to true, so its destructor doesn't do anything
// when called.
mutable bool completed = false;
Group(Iterator& owner, key_func_ret key) :
owner(owner),
key(key)
{ }
public:
~Group() {
if (!this->completed) {
for (auto iter = this->begin(), end = this->end();
iter != end;
++iter) { }
}
}
// movable, non-copyable
Group() = delete;
Group(const Group&) = delete;
Group& operator=(const Group&) = delete;
Group& operator=(Group&&) = delete;
Group(Group&& other)
: owner{other.owner},
key{other.key},
completed{other.completed} {
other.completed = true;
}
class GroupIterator
: public std::iterator<std::input_iterator_tag,
iterator_traits_deref<Container>>
{
private:
const key_func_ret key;
const Group& group;
bool not_at_end() {
return !this->group.owner.exhausted()&&
this->group.owner.next_key() == this->key;
}
public:
GroupIterator(const Group& group,
key_func_ret key)
: key{key},
group{group}
{ }
GroupIterator(const GroupIterator&) = default;
bool operator!=(const GroupIterator&) const {
return !this->group.completed;
#if 0
if (this->not_at_end()) {
return true;
} else {
this->group.completed = true;
return false;
}
#endif
}
bool operator==(const GroupIterator& other) const {
return !(*this != other);
}
GroupIterator& operator++() {
this->group.owner.increment_iterator();
if (!this->not_at_end()) {
this->group.completed = true;
}
return *this;
}
GroupIterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
iterator_deref<Container> operator*() {
return this->group.owner.current();
}
};
GroupIterator begin() {
return {*this, key};
}
GroupIterator end() {
return {*this, key};
}
};
Iterator begin() {
return {std::begin(this->container),
std::end(this->container),
this->key_func};
}
Iterator end() {
return {std::end(this->container),
std::end(this->container),
this->key_func};
}
};
// Takes something and returns it, used for default key of comparing
// items in the sequence directly
template <typename Container>
class ItemReturner {
public:
iterator_deref<Container> operator() (
iterator_deref<Container> item) const {
return item;
}
};
template <typename Container, typename KeyFunc>
GroupBy<Container, KeyFunc> groupby(
Container&& container, KeyFunc key_func) {
return {std::forward<Container>(container), key_func};
}
template <typename Container>
auto groupby(Container&& container) ->
decltype(groupby(std::forward<Container>(container),
ItemReturner<Container>())) {
return groupby(std::forward<Container>(container),
ItemReturner<Container>());
}
template <typename T, typename KeyFunc>
GroupBy<std::initializer_list<T>, KeyFunc> groupby(
std::initializer_list<T> il, KeyFunc key_func) {
return {std::move(il), key_func};
}
template <typename T>
auto groupby(std::initializer_list<T> il) ->
decltype(groupby(std::move(il),
ItemReturner<std::initializer_list<T>>())) {
return groupby(
std::move(il),
ItemReturner<std::initializer_list<T>>());
}
}
#endif
<commit_msg>removes commented out code<commit_after>#ifndef ITER_GROUP_BY_HPP_
#define ITER_GROUP_BY_HPP_
#include "iterbase.hpp"
#include <utility>
#include <iterator>
#include <initializer_list>
namespace iter {
template <typename Container, typename KeyFunc>
class GroupBy;
template <typename Container, typename KeyFunc>
GroupBy<Container, KeyFunc> groupby(Container&&, KeyFunc);
template <typename T, typename KeyFunc>
GroupBy<std::initializer_list<T>, KeyFunc> groupby(
std::initializer_list<T>, KeyFunc);
template <typename Container, typename KeyFunc>
class GroupBy {
private:
Container container;
KeyFunc key_func;
friend GroupBy groupby<Container, KeyFunc>(Container&&, KeyFunc);
template <typename T, typename KF>
friend GroupBy<std::initializer_list<T>, KF> groupby(
std::initializer_list<T>, KF);
using key_func_ret =
decltype(std::declval<KeyFunc>()(
std::declval<iterator_deref<Container>>()));
GroupBy(Container&& container, KeyFunc key_func)
: container(std::forward<Container>(container)),
key_func(key_func)
{ }
public:
GroupBy() = delete;
GroupBy(const GroupBy&) = delete;
GroupBy& operator=(const GroupBy&) = delete;
GroupBy& operator=(GroupBy&&) = delete;
GroupBy(GroupBy&&) = default;
class Iterator;
class Group;
private:
using KeyGroupPair =
std::pair<key_func_ret, Group>;
public:
class Iterator
: public std::iterator<std::input_iterator_tag, KeyGroupPair>
{
private:
iterator_type<Container> sub_iter;
iterator_type<Container> sub_iter_peek;
iterator_type<Container> sub_end;
KeyFunc key_func;
public:
Iterator (iterator_type<Container> si,
iterator_type<Container> end,
KeyFunc key_func)
: sub_iter{si},
sub_end{end},
key_func(key_func)
{ }
KeyGroupPair operator*() {
return KeyGroupPair(
this->key_func(*this->sub_iter),
Group(
*this,
this->key_func(*this->sub_iter)));
}
Iterator& operator++() {
return *this;
}
Iterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
bool operator!=(const Iterator&) const {
return !this->exhausted();
}
bool operator==(const Iterator& other) const {
return !(*this != other);
}
void increment_iterator() {
if (this->sub_iter != this->sub_end) {
++this->sub_iter;
}
}
bool exhausted() const {
return !(this->sub_iter != this->sub_end);
}
iterator_deref<Container> current() {
return *this->sub_iter;
}
key_func_ret next_key() {
return this->key_func(*this->sub_iter);
}
};
class Group {
private:
friend Iterator;
friend class GroupIterator;
Iterator& owner;
key_func_ret key;
// completed is set if a Group is iterated through
// completely. It is checked in the destructor, and
// if the Group has not been completed, the destructor
// exhausts it. This ensures that the next Group starts
// at the correct position when the user short-circuits
// iteration over a Group.
// The move constructor sets the rvalue's completed
// attribute to true, so its destructor doesn't do anything
// when called.
mutable bool completed = false;
Group(Iterator& owner, key_func_ret key) :
owner(owner),
key(key)
{ }
public:
~Group() {
if (!this->completed) {
for (auto iter = this->begin(), end = this->end();
iter != end;
++iter) { }
}
}
// movable, non-copyable
Group() = delete;
Group(const Group&) = delete;
Group& operator=(const Group&) = delete;
Group& operator=(Group&&) = delete;
Group(Group&& other)
: owner{other.owner},
key{other.key},
completed{other.completed} {
other.completed = true;
}
class GroupIterator
: public std::iterator<std::input_iterator_tag,
iterator_traits_deref<Container>>
{
private:
const key_func_ret key;
const Group& group;
bool not_at_end() {
return !this->group.owner.exhausted()&&
this->group.owner.next_key() == this->key;
}
public:
GroupIterator(const Group& group,
key_func_ret key)
: key{key},
group{group}
{ }
GroupIterator(const GroupIterator&) = default;
bool operator!=(const GroupIterator&) const {
return !this->group.completed;
}
bool operator==(const GroupIterator& other) const {
return !(*this != other);
}
GroupIterator& operator++() {
this->group.owner.increment_iterator();
if (!this->not_at_end()) {
this->group.completed = true;
}
return *this;
}
GroupIterator operator++(int) {
auto ret = *this;
++*this;
return ret;
}
iterator_deref<Container> operator*() {
return this->group.owner.current();
}
};
GroupIterator begin() {
return {*this, key};
}
GroupIterator end() {
return {*this, key};
}
};
Iterator begin() {
return {std::begin(this->container),
std::end(this->container),
this->key_func};
}
Iterator end() {
return {std::end(this->container),
std::end(this->container),
this->key_func};
}
};
// Takes something and returns it, used for default key of comparing
// items in the sequence directly
template <typename Container>
class ItemReturner {
public:
iterator_deref<Container> operator() (
iterator_deref<Container> item) const {
return item;
}
};
template <typename Container, typename KeyFunc>
GroupBy<Container, KeyFunc> groupby(
Container&& container, KeyFunc key_func) {
return {std::forward<Container>(container), key_func};
}
template <typename Container>
auto groupby(Container&& container) ->
decltype(groupby(std::forward<Container>(container),
ItemReturner<Container>())) {
return groupby(std::forward<Container>(container),
ItemReturner<Container>());
}
template <typename T, typename KeyFunc>
GroupBy<std::initializer_list<T>, KeyFunc> groupby(
std::initializer_list<T> il, KeyFunc key_func) {
return {std::move(il), key_func};
}
template <typename T>
auto groupby(std::initializer_list<T> il) ->
decltype(groupby(std::move(il),
ItemReturner<std::initializer_list<T>>())) {
return groupby(
std::move(il),
ItemReturner<std::initializer_list<T>>());
}
}
#endif
<|endoftext|>
|
<commit_before>#ifndef GROUP__BY__HPP
#define GROUP__BY__HPP
#include <iterbase.hpp>
#include <utility>
#include <iterator>
namespace iter {
template <typename Container, typename KeyFunc>
class GroupBy;
template <typename Container, typename KeyFunc>
GroupBy<Container, KeyFunc> groupby(Container &&, KeyFunc);
template <typename Container, typename KeyFunc>
class GroupBy : IterBase<Container> {
private:
Container & container;
KeyFunc key_func;
// The filter function is the only thing allowed to create a Filter
friend GroupBy groupby<Container, KeyFunc>(Container &&, KeyFunc);
using typename IterBase<Container>::contained_iter_type;
using typename IterBase<Container>::contained_iter_ret;
using key_func_ret =
decltype(std::declval<KeyFunc>()(
std::declval<contained_iter_ret>()));
GroupBy(Container && container, KeyFunc key_func) :
container(container),
key_func(key_func)
{ }
GroupBy () = delete;
GroupBy & operator=(const GroupBy &) = delete;
public:
GroupBy(const GroupBy &) = default;
class Iterator;
class Group;
class Iterator {
private:
contained_iter_type sub_iter;
contained_iter_type sub_iter_peek;
const contained_iter_type sub_end;
KeyFunc key_func;
using KeyGroupPair =
std::pair<key_func_ret, Group>;
public:
Iterator (contained_iter_type si,
contained_iter_type end,
KeyFunc key_func) :
sub_iter(si),
sub_end(end),
key_func(key_func)
{ }
KeyGroupPair operator*() {
return KeyGroupPair(
this->key_func(*this->sub_iter),
Group(
*this,
this->key_func(*this->sub_iter)));
}
Iterator & operator++() {
return *this;
}
bool operator!=(const Iterator &) const {
return !this->exhausted();
}
void increment_iterator() {
if (this->sub_iter != this->sub_end) {
++this->sub_iter;
}
}
bool exhausted() const {
return this->sub_iter == this->sub_end;
}
contained_iter_ret current() const {
return *this->sub_iter;
}
key_func_ret next_key() const {
return this->key_func(*this->sub_iter);
}
};
class Group {
private:
friend Iterator;
friend class GroupIterator;
Iterator & owner;
key_func_ret key;
// completed is set if a Group is iterated through
// completely. It is checked in the destructor, and
// if the Group has not been completed, the destructor
// exhausts it. This ensures that the next Group starts
// at the correct position when the user short-circuits
// iteration over a Group.
// The move constructor sets the rvalue's completed
// attribute to true, so its destructor doesn't do anything
// when called.
mutable bool completed = false;
Group(Iterator & owner, key_func_ret key) :
owner(owner),
key(key)
{ }
public:
~Group() {
if (!this->completed) {
for (auto iter = this->begin(), end = this->end();
iter != end;
++iter) { }
}
}
// can be move constructed, but not copied or move assigned
Group () = delete;
Group (const Group &) = delete;
Group & operator=(const Group &) = delete;
Group & operator=(Group &&) = delete;
Group (Group && other) :
owner(other.owner),
key(other.key),
completed(other.completed) {
other.completed = true;
}
class GroupIterator {
private:
const key_func_ret key;
const Group & group;
bool not_at_end() const {
return !this->group.owner.exhausted() &&
this->group.owner.next_key() == this->key;
}
public:
GroupIterator(const Group & group,
key_func_ret key) :
key(key),
group(group)
{ }
GroupIterator(const GroupIterator &) = default;
bool operator!=(const GroupIterator &) const {
if (this->not_at_end()) {
return true;
} else {
this->group.completed = true;
return false;
}
}
GroupIterator & operator++() {
this->group.owner.increment_iterator();
return *this;
}
contained_iter_ret operator*() const {
return this->group.owner.current();
}
};
GroupIterator begin() const {
return GroupIterator(*this, key);
}
GroupIterator end() const {
return GroupIterator(*this, key);
}
};
Iterator begin() const {
return Iterator(
std::begin(this->container),
std::end(this->container),
this->key_func);
}
Iterator end() const {
return Iterator(
std::end(this->container),
std::end(this->container),
this->key_func);
}
};
template <typename Container, typename KeyFunc>
GroupBy<Container, KeyFunc> groupby(
Container && container, KeyFunc key_func) {
return GroupBy<Container, KeyFunc>(
std::forward<Container>(container),
key_func);
}
template <typename Container>
class ItemReturner {
private:
using contained_iter_ret =
typename IterBase<Container>::contained_iter_ret;
public:
ItemReturner() = default;
contained_iter_ret operator() (contained_iter_ret item) const {
return item;
}
};
template <typename Container>
auto groupby(Container && container) ->
decltype(groupby(std::forward<Container>(container),
ItemReturner<Container>())) {
return groupby(std::forward<Container>(container),
ItemReturner<Container>());
}
}
#endif //#ifndef GROUP__BY__HPP
<commit_msg>Makes GroupBy movable, non-copyable<commit_after>#ifndef GROUP__BY__HPP
#define GROUP__BY__HPP
#include <iterbase.hpp>
#include <utility>
#include <iterator>
namespace iter {
template <typename Container, typename KeyFunc>
class GroupBy;
template <typename Container, typename KeyFunc>
GroupBy<Container, KeyFunc> groupby(Container &&, KeyFunc);
template <typename Container, typename KeyFunc>
class GroupBy : IterBase<Container> {
private:
Container & container;
KeyFunc key_func;
// The filter function is the only thing allowed to create a Filter
friend GroupBy groupby<Container, KeyFunc>(Container &&, KeyFunc);
using typename IterBase<Container>::contained_iter_type;
using typename IterBase<Container>::contained_iter_ret;
using key_func_ret =
decltype(std::declval<KeyFunc>()(
std::declval<contained_iter_ret>()));
GroupBy(Container && container, KeyFunc key_func) :
container(container),
key_func(key_func)
{ }
public:
GroupBy () = delete;
GroupBy(const GroupBy &) = delete;
GroupBy& operator=(const GroupBy &) = delete;
GroupBy (GroupBy &&) = default;
GroupBy & operator=(GroupBy &&) = default;
class Iterator;
class Group;
class Iterator {
private:
contained_iter_type sub_iter;
contained_iter_type sub_iter_peek;
const contained_iter_type sub_end;
KeyFunc key_func;
using KeyGroupPair =
std::pair<key_func_ret, Group>;
public:
Iterator (contained_iter_type si,
contained_iter_type end,
KeyFunc key_func) :
sub_iter(si),
sub_end(end),
key_func(key_func)
{ }
KeyGroupPair operator*() {
return KeyGroupPair(
this->key_func(*this->sub_iter),
Group(
*this,
this->key_func(*this->sub_iter)));
}
Iterator & operator++() {
return *this;
}
bool operator!=(const Iterator &) const {
return !this->exhausted();
}
void increment_iterator() {
if (this->sub_iter != this->sub_end) {
++this->sub_iter;
}
}
bool exhausted() const {
return this->sub_iter == this->sub_end;
}
contained_iter_ret current() const {
return *this->sub_iter;
}
key_func_ret next_key() const {
return this->key_func(*this->sub_iter);
}
};
class Group {
private:
friend Iterator;
friend class GroupIterator;
Iterator & owner;
key_func_ret key;
// completed is set if a Group is iterated through
// completely. It is checked in the destructor, and
// if the Group has not been completed, the destructor
// exhausts it. This ensures that the next Group starts
// at the correct position when the user short-circuits
// iteration over a Group.
// The move constructor sets the rvalue's completed
// attribute to true, so its destructor doesn't do anything
// when called.
mutable bool completed = false;
Group(Iterator & owner, key_func_ret key) :
owner(owner),
key(key)
{ }
public:
~Group() {
if (!this->completed) {
for (auto iter = this->begin(), end = this->end();
iter != end;
++iter) { }
}
}
// movable, non-copyable
Group () = delete;
Group (const Group &) = delete;
Group & operator=(const Group &) = delete;
Group & operator=(Group &&) = default;
Group (Group && other) :
owner(other.owner),
key(other.key),
completed(other.completed) {
other.completed = true;
}
class GroupIterator {
private:
const key_func_ret key;
const Group & group;
bool not_at_end() const {
return !this->group.owner.exhausted() &&
this->group.owner.next_key() == this->key;
}
public:
GroupIterator(const Group & group,
key_func_ret key) :
key(key),
group(group)
{ }
GroupIterator(const GroupIterator &) = default;
bool operator!=(const GroupIterator &) const {
if (this->not_at_end()) {
return true;
} else {
this->group.completed = true;
return false;
}
}
GroupIterator & operator++() {
this->group.owner.increment_iterator();
return *this;
}
contained_iter_ret operator*() const {
return this->group.owner.current();
}
};
GroupIterator begin() const {
return GroupIterator(*this, key);
}
GroupIterator end() const {
return GroupIterator(*this, key);
}
};
Iterator begin() const {
return Iterator(
std::begin(this->container),
std::end(this->container),
this->key_func);
}
Iterator end() const {
return Iterator(
std::end(this->container),
std::end(this->container),
this->key_func);
}
};
template <typename Container, typename KeyFunc>
GroupBy<Container, KeyFunc> groupby(
Container && container, KeyFunc key_func) {
return GroupBy<Container, KeyFunc>(
std::forward<Container>(container),
key_func);
}
template <typename Container>
class ItemReturner {
private:
using contained_iter_ret =
typename IterBase<Container>::contained_iter_ret;
public:
ItemReturner() = default;
contained_iter_ret operator() (contained_iter_ret item) const {
return item;
}
};
template <typename Container>
auto groupby(Container && container) ->
decltype(groupby(std::forward<Container>(container),
ItemReturner<Container>())) {
return groupby(std::forward<Container>(container),
ItemReturner<Container>());
}
}
#endif //#ifndef GROUP__BY__HPP
<|endoftext|>
|
<commit_before>#include <catch2/catch.hpp>
#include <iostream>
#include <mtao/geometry/mesh/laplacian.hpp>
#include <mtao/simulation/hexahedral/laplacian.hpp>
#include <mtao/simulation/simplicial/laplacian.hpp>
using namespace mtao::simulation::simplicial;
using namespace mtao::geometry::mesh;
TEST_CASE("Lap2", "[laplacian]") {
mtao::ColVecs2d V(2, 3);
V.col(0) = mtao::Vec2d(0.0, 1.0);
V.col(1) = mtao::Vec2d(0.8, 0.0);
V.col(2) = mtao::Vec2d(-.8, 0.0);
// V.col(0) = mtao::Vec2d(0.0,0.0);
// V.col(1) = mtao::Vec2d(1.,0.0);
// V.col(2) = mtao::Vec2d(0.,1.);
mtao::ColVecs3i F(3, 1);
F << 0, 1, 2;
auto L = laplacian(V, F);
std::cout << L << std::endl;
auto L2 = cot_laplacian(V, F);
std::cout << L2 << std::endl;
REQUIRE(1 == 1);
}
TEST_CASE("Lap3", "[laplacian]") {
mtao::ColVecs3d V(3, 4);
V.col(0) = mtao::Vec3d(0.0, 0.0, 0.0);
V.col(1) = mtao::Vec3d(1.0, 0.0, 0.0);
V.col(2) = mtao::Vec3d(0.0, 1.0, 0.0);
V.col(3) = mtao::Vec3d(0.0, 0.0, 1.0);
mtao::ColVecs4i F(4, 1);
F << 0, 1, 2, 3;
auto L = laplacian(V, F);
std::cout << L << std::endl;
REQUIRE(1 == 1);
}
TEST_CASE("hex", "[laplacian,hexahedral]") {
auto L2 = mtao::simulation::hexahedral::laplacian_stencil<float, 2>();
std::cout << L2 << std::endl;
std::cout << L2.colwise().sum() << std::endl;
auto L3 = mtao::simulation::hexahedral::laplacian_stencil<float, 3>();
std::cout << L3 << std::endl;
std::cout << L3.colwise().sum() << std::endl;
}
<commit_msg>commenting laplacian test until it actually is used for something<commit_after>#include <catch2/catch.hpp>
#include <iostream>
#include <mtao/geometry/mesh/laplacian.hpp>
#include <mtao/simulation/hexahedral/laplacian.hpp>
#include <mtao/simulation/simplicial/laplacian.hpp>
using namespace mtao::simulation::simplicial;
using namespace mtao::geometry::mesh;
TEST_CASE("Lap2", "[laplacian]") {
return;
mtao::ColVecs2d V(2, 3);
V.col(0) = mtao::Vec2d(0.0, 1.0);
V.col(1) = mtao::Vec2d(0.8, 0.0);
V.col(2) = mtao::Vec2d(-.8, 0.0);
// V.col(0) = mtao::Vec2d(0.0,0.0);
// V.col(1) = mtao::Vec2d(1.,0.0);
// V.col(2) = mtao::Vec2d(0.,1.);
mtao::ColVecs3i F(3, 1);
F << 0, 1, 2;
auto L = laplacian(V, F);
std::cout << L << std::endl;
auto L2 = cot_laplacian(V, F);
std::cout << L2 << std::endl;
REQUIRE(1 == 1);
}
TEST_CASE("Lap3", "[laplacian]") {
mtao::ColVecs3d V(3, 4);
V.col(0) = mtao::Vec3d(0.0, 0.0, 0.0);
V.col(1) = mtao::Vec3d(1.0, 0.0, 0.0);
V.col(2) = mtao::Vec3d(0.0, 1.0, 0.0);
V.col(3) = mtao::Vec3d(0.0, 0.0, 1.0);
mtao::ColVecs4i F(4, 1);
F << 0, 1, 2, 3;
auto L = laplacian(V, F);
std::cout << L << std::endl;
REQUIRE(1 == 1);
}
TEST_CASE("hex", "[laplacian,hexahedral]") {
return;
auto L2 = mtao::simulation::hexahedral::laplacian_stencil<float, 2>();
std::cout << L2 << std::endl;
std::cout << L2.colwise().sum() << std::endl;
auto L3 = mtao::simulation::hexahedral::laplacian_stencil<float, 3>();
std::cout << L3 << std::endl;
std::cout << L3.colwise().sum() << std::endl;
}
<|endoftext|>
|
<commit_before>#include <stdexcept>
#include <fstream>
#include <xorg/gtest/xorg-gtest.h>
#include <X11/extensions/XInput.h>
#include <X11/extensions/XInput2.h>
#include "input-driver-test.h"
class LegacyInputDriverTest : public InputDriverTest {
public:
virtual void ConfigureInputDevice(std::string &driver) {
config.AddInputSection(driver, "--device--", "Option \"CorePointer\" \"on\"\n");
}
virtual void SetUpConfigAndLog() {
std::string param = GetParam();
std::stringstream s;
s << "/tmp/Xorg-" << GetParam() << ".log";
log_file = s.str();
server.SetOption("-logfile",log_file);
s.str(std::string());
s << "/tmp/" << GetParam() << ".conf";
config_file = s.str();
ConfigureInputDevice(param);
config.WriteConfig(config_file);
server.SetOption("-config", config_file);
}
};
TEST_P(LegacyInputDriverTest, SimpleDeviceSection)
{
std::string param;
int ndevices;
XIDeviceInfo *info;
param = GetParam();
info = XIQueryDevice(Display(), XIAllDevices, &ndevices);
int expected_devices;
/* apparently when the acecad driver is loaded neither mouse nor kbd
* loads - probably a bug but that's current behaviour on RHEL 6.3 */
if (param.compare("acecad") == 0)
expected_devices = 4;
else
expected_devices = 6;
ASSERT_EQ(ndevices, expected_devices);
bool found = false;
while(ndevices--) {
if (strcmp(info[ndevices].name, "--device--") == 0) {
ASSERT_EQ(found, false) << "Duplicate device" << std::endl;
found = true;
}
}
/* No joke, they all fail. some fail for missing Device option, others
* for not finding the device, etc. */
ASSERT_EQ(found, false);
XIFreeDeviceInfo(info);
}
INSTANTIATE_TEST_CASE_P(, LegacyInputDriverTest,
::testing::Values("acecad", "aiptek", "elographics",
"fpit", "hyperpen", "mutouch",
"penmount"));
/***********************************************************************
* *
* ACECAD *
* *
***********************************************************************/
class AcecadInputDriverTest : public LegacyInputDriverTest {
public:
virtual void ConfigureInputDevice(std::string &driver) {
config.AddInputSection(driver, "--device--",
"Option \"CorePointer\" \"on\"\n"
"Option \"Device\" \"/dev/input/event0\"\n");
}
};
TEST_P(AcecadInputDriverTest, WithOptionDevice)
{
std::string param;
int ndevices;
XIDeviceInfo *info;
param = GetParam();
info = XIQueryDevice(Display(), XIAllDevices, &ndevices);
/* when the acecad driver succeeds (even with bogus device)
* mouse and keyboard load too */
ASSERT_EQ(ndevices, 7);
bool found = false;
while(ndevices--) {
if (strcmp(info[ndevices].name, "--device--") == 0) {
ASSERT_EQ(found, false) << "Duplicate device" << std::endl;
found = true;
}
}
ASSERT_EQ(found, true);
XIFreeDeviceInfo(info);
}
INSTANTIATE_TEST_CASE_P(, AcecadInputDriverTest, ::testing::Values(std::string("acecad")));
/***********************************************************************
* *
* AIPTEK *
* *
***********************************************************************/
class AiptekInputDriverTest : public LegacyInputDriverTest {
public:
virtual void ConfigureInputDevice(std::string &driver) {
config.AddInputSection(driver, "--device--",
"Option \"CorePointer\" \"on\"\n"
"Option \"Device\" \"/dev/input/event0\"\n"
"Option \"Type\" \"stylus\"");
}
};
TEST_P(AiptekInputDriverTest, WithOptionDevice)
{
std::string param;
int ndevices;
XIDeviceInfo *info;
param = GetParam();
info = XIQueryDevice(Display(), XIAllDevices, &ndevices);
bool found = false;
while(ndevices--) {
if (strcmp(info[ndevices].name, "--device--") == 0) {
ASSERT_EQ(found, false) << "Duplicate device" << std::endl;
found = true;
}
}
ASSERT_EQ(found, true);
XIFreeDeviceInfo(info);
}
INSTANTIATE_TEST_CASE_P(, AiptekInputDriverTest, ::testing::Values(std::string("aiptek")));
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>legacy-drivers: add two more tests for aiptek<commit_after>#include <stdexcept>
#include <fstream>
#include <xorg/gtest/xorg-gtest.h>
#include <X11/Xlib.h>
#include <X11/extensions/XInput.h>
#include <X11/extensions/XInput2.h>
#include "input-driver-test.h"
#include "helpers.h"
class LegacyInputDriverTest : public InputDriverTest {
public:
virtual void ConfigureInputDevice(std::string &driver) {
config.AddInputSection(driver, "--device--", "Option \"CorePointer\" \"on\"\n");
}
virtual void SetUpConfigAndLog() {
std::string param = GetParam();
std::stringstream s;
s << "/tmp/Xorg-" << GetParam() << ".log";
log_file = s.str();
server.SetOption("-logfile",log_file);
s.str(std::string());
s << "/tmp/" << GetParam() << ".conf";
config_file = s.str();
ConfigureInputDevice(param);
config.WriteConfig(config_file);
server.SetOption("-config", config_file);
}
};
TEST_P(LegacyInputDriverTest, SimpleDeviceSection)
{
std::string param;
int ndevices;
XIDeviceInfo *info;
param = GetParam();
info = XIQueryDevice(Display(), XIAllDevices, &ndevices);
int expected_devices;
/* apparently when the acecad driver is loaded neither mouse nor kbd
* loads - probably a bug but that's current behaviour on RHEL 6.3 */
if (param.compare("acecad") == 0)
expected_devices = 4;
else
expected_devices = 6;
ASSERT_EQ(ndevices, expected_devices);
bool found = false;
while(ndevices--) {
if (strcmp(info[ndevices].name, "--device--") == 0) {
ASSERT_EQ(found, false) << "Duplicate device" << std::endl;
found = true;
}
}
/* No joke, they all fail. some fail for missing Device option, others
* for not finding the device, etc. */
ASSERT_EQ(found, false);
XIFreeDeviceInfo(info);
}
INSTANTIATE_TEST_CASE_P(, LegacyInputDriverTest,
::testing::Values("acecad", "aiptek", "elographics",
"fpit", "hyperpen", "mutouch",
"penmount"));
/***********************************************************************
* *
* ACECAD *
* *
***********************************************************************/
class AcecadInputDriverTest : public LegacyInputDriverTest {
public:
virtual void ConfigureInputDevice(std::string &driver) {
config.AddInputSection(driver, "--device--",
"Option \"CorePointer\" \"on\"\n"
"Option \"Device\" \"/dev/input/event0\"\n");
}
};
TEST_P(AcecadInputDriverTest, WithOptionDevice)
{
std::string param;
int ndevices;
XIDeviceInfo *info;
param = GetParam();
info = XIQueryDevice(Display(), XIAllDevices, &ndevices);
/* when the acecad driver succeeds (even with bogus device)
* mouse and keyboard load too */
ASSERT_EQ(ndevices, 7);
bool found = false;
while(ndevices--) {
if (strcmp(info[ndevices].name, "--device--") == 0) {
ASSERT_EQ(found, false) << "Duplicate device" << std::endl;
found = true;
}
}
ASSERT_EQ(found, true);
XIFreeDeviceInfo(info);
}
INSTANTIATE_TEST_CASE_P(, AcecadInputDriverTest, ::testing::Values(std::string("acecad")));
/***********************************************************************
* *
* AIPTEK *
* *
***********************************************************************/
class AiptekInputDriverTest : public LegacyInputDriverTest {
public:
virtual void ConfigureInputDevice(std::string &driver) {
config.AddInputSection(driver, "--device--",
"Option \"CorePointer\" \"on\"\n"
"Option \"Device\" \"/dev/input/event0\"\n"
"Option \"Type\" \"stylus\"");
}
};
TEST_P(AiptekInputDriverTest, WithOptionDevice)
{
std::string param;
int ndevices;
XIDeviceInfo *info;
param = GetParam();
info = XIQueryDevice(Display(), XIAllDevices, &ndevices);
bool found = false;
while(ndevices--) {
if (strcmp(info[ndevices].name, "--device--") == 0) {
ASSERT_EQ(found, false) << "Duplicate device" << std::endl;
found = true;
}
}
ASSERT_EQ(found, true);
XIFreeDeviceInfo(info);
}
INSTANTIATE_TEST_CASE_P(, AiptekInputDriverTest, ::testing::Values(std::string("aiptek")));
TEST(AiptekInputDriver, TypeCursor)
{
XOrgConfig config;
xorg::testing::XServer server;
config.AddInputSection("aiptek", "--device--",
"Option \"CorePointer\" \"on\"\n"
"Option \"Device\" \"/dev/input/event0\"\n"
"Option \"Type\" \"cursor\"");
StartServer("aiptek-type-cursor", server, config);
::Display *dpy = XOpenDisplay(server.GetDisplayString().c_str());
int major = 2;
int minor = 0;
ASSERT_EQ(Success, XIQueryVersion(dpy, &major, &minor));
int ndevices;
XIDeviceInfo *info;
info = XIQueryDevice(dpy, XIAllDevices, &ndevices);
KillServer(server, config);
/* VCP, VCK, xtest, mouse, keyboard, aiptek */
ASSERT_EQ(ndevices, 7);
bool found = false;
while(ndevices--) {
if (strcmp(info[ndevices].name, "--device--") == 0) {
ASSERT_EQ(found, false) << "Duplicate device" << std::endl;
found = true;
}
}
ASSERT_EQ(found, true);
XIFreeDeviceInfo(info);
}
TEST(AiptekInputDriver, TypeEraser)
{
XOrgConfig config;
xorg::testing::XServer server;
config.AddInputSection("aiptek", "--device--",
"Option \"CorePointer\" \"on\"\n"
"Option \"Device\" \"/dev/input/event0\"\n"
"Option \"Type\" \"eraser\"");
StartServer("aiptek-type-eraser", server, config);
::Display *dpy = XOpenDisplay(server.GetDisplayString().c_str());
int major = 2;
int minor = 0;
ASSERT_EQ(Success, XIQueryVersion(dpy, &major, &minor));
int ndevices;
XIDeviceInfo *info;
info = XIQueryDevice(dpy, XIAllDevices, &ndevices);
KillServer(server, config);
/* VCP, VCK, xtest, mouse, keyboard, aiptek */
ASSERT_EQ(ndevices, 7);
bool found = false;
while(ndevices--) {
if (strcmp(info[ndevices].name, "--device--") == 0) {
ASSERT_EQ(found, false) << "Duplicate device" << std::endl;
found = true;
}
}
ASSERT_EQ(found, true);
XIFreeDeviceInfo(info);
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|>
|
<commit_before>/*******************************************************************************
* tests/net/group_test.cpp
*
* Part of Project c7a.
*
* Copyright (C) 2015 Timo Bingmann <tb@panthema.net>
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#include <c7a/net/group.hpp>
#include <c7a/net/flow_control_channel.hpp>
#include <c7a/net/dispatcher.hpp>
#include <c7a/net/manager.hpp>
#include <c7a/net/collective_communication.hpp>
#include <gtest/gtest.h>
#include <thread>
#include <vector>
#include <string>
#include <random>
using namespace c7a::net;
static void ThreadInitializeAsyncRead(Group* net) {
// send a message to all other clients except ourselves.
for (size_t i = 0; i != net->Size(); ++i)
{
if (i == net->MyRank()) continue;
net->connection(i).GetSocket().send(&i, sizeof(size_t));
}
size_t received = 0;
Dispatcher dispatcher;
Dispatcher::AsyncReadCallback callback =
[net, &received](Connection& /* s */, const Buffer& buffer) {
ASSERT_EQ(*(reinterpret_cast<const size_t*>(buffer.data())),
net->MyRank());
received++;
};
// add async reads to net dispatcher
for (size_t i = 0; i != net->Size(); ++i)
{
if (i == net->MyRank()) continue;
dispatcher.AsyncRead(net->connection(i), sizeof(size_t), callback);
}
while (received < net->Size() - 1) {
dispatcher.Dispatch();
}
}
static void ThreadInitializeBroadcastIntegral(Group* net) {
static const bool debug = false;
//Broadcast our ID to everyone
for (size_t i = 0; i != net->Size(); ++i)
{
if (i == net->MyRank()) continue;
net->SendTo(i, net->MyRank());
}
//Receive the id from everyone. Make sure that the id is correct.
for (size_t i = 0; i != net->Size(); ++i)
{
if (i == net->MyRank()) continue;
size_t val;
ClientId id;
net->ReceiveFromAny<size_t>(&id, &val);
LOG << "Received " << val << " from " << id;
ASSERT_EQ((int)id, (int)val);
}
}
static void ThreadInitializeSendReceive(Group* net) {
static const bool debug = false;
// send a message to all other clients except ourselves.
for (size_t i = 0; i != net->Size(); ++i)
{
if (i == net->MyRank()) continue;
net->SendStringTo(i, "Hello " + std::to_string(net->MyRank())
+ " -> " + std::to_string(i));
}
// receive the n-1 messages from clients in order
for (size_t i = 0; i != net->Size(); ++i)
{
if (i == net->MyRank()) continue;
std::string msg;
net->ReceiveStringFrom(i, &msg);
sLOG << "Received from client" << i << "msg" << msg;
ASSERT_EQ(msg, "Hello " + std::to_string(i)
+ " -> " + std::to_string(net->MyRank()));
}
// *****************************************************************
// send another message to all other clients except ourselves. Now with connection access.
for (size_t i = 0; i != net->Size(); ++i)
{
if (i == net->MyRank()) continue;
net->connection(i).SendString("Hello " + std::to_string(net->MyRank())
+ " -> " + std::to_string(i));
}
// receive the n-1 messages from clients in any order
for (size_t i = 0; i != net->Size(); ++i)
{
if (i == net->MyRank()) continue;
ClientId from;
std::string msg;
net->ReceiveStringFromAny(&from, &msg);
sLOG << "Received from client" << i << "msg" << msg;
ASSERT_EQ(msg, "Hello " + std::to_string(from)
+ " -> " + std::to_string(net->MyRank()));
}
}
static void ThreadInitializeSendReceiveALot(Group* net) {
for (int i = 0; i < 100; i++) {
ThreadInitializeSendReceive(net);
}
}
static void ThreadInitializeSendReceiveAsyncALot(Group* net) {
for (int i = 0; i < 100; i++) {
ThreadInitializeAsyncRead(net);
}
}
static void RealGroupConstructAndCall(
std::function<void(Group*)> thread_function) {
// randomize base port number for test
std::random_device random_device;
std::default_random_engine generator(random_device());
std::uniform_int_distribution<int> distribution(30000, 65000);
const size_t port_base = distribution(generator);
static const std::vector<Endpoint> endpoints = {
Endpoint("127.0.0.1:" + std::to_string(port_base + 0)),
Endpoint("127.0.0.1:" + std::to_string(port_base + 1)),
Endpoint("127.0.0.1:" + std::to_string(port_base + 2)),
Endpoint("127.0.0.1:" + std::to_string(port_base + 3)),
Endpoint("127.0.0.1:" + std::to_string(port_base + 4)),
Endpoint("127.0.0.1:" + std::to_string(port_base + 5))
};
sLOG1 << "Group test uses ports " << port_base << "-" << port_base + 5;
static const int count = endpoints.size();
std::vector<std::thread> threads(count);
// lambda to construct Group and call user thread function.
std::vector<Manager> groups(count);
for (int i = 0; i < count; i++) {
threads[i] = std::thread(
[i, &thread_function, &groups]() {
// construct Group i with endpoints
groups[i].Initialize(i, endpoints);
// run thread function
thread_function(&groups[i].GetFlowGroup());
});
}
for (int i = 0; i < count; i++) {
threads[i].join();
}
}
TEST(Group, RealInitializeAndClose) {
// Construct a real Group of 6 workers which do nothing but terminate.
RealGroupConstructAndCall([](Group*) { });
}
TEST(Group, RealInitializeSendReceive) {
// Construct a real Group of 6 workers which execute the thread function
// above which sends and receives a message from all neighbors.
RealGroupConstructAndCall(ThreadInitializeSendReceive);
}
TEST(Group, RealInitializeSendReceiveALot) {
// Construct a real Group of 6 workers which execute the thread function
// above which sends and receives a message from all neighbors.
RealGroupConstructAndCall(ThreadInitializeSendReceive);
}
TEST(Group, RealInitializeSendReceiveAsync) { //TODO(ej) test hangs from time to time
// Construct a real Group of 6 workers which execute the thread function
// which sends and receives asynchronous messages between all workers.
RealGroupConstructAndCall(ThreadInitializeAsyncRead);
}
TEST(Group, RealInitializeSendReceiveAsyncALot) {
// Construct a real Group of 6 workers which execute the thread function
// above which sends and receives a message from all neighbors.
RealGroupConstructAndCall(ThreadInitializeSendReceive);
}
TEST(Group, RealInitializeBroadcast) {
// Construct a real Group of 6 workers which execute the thread function
// above which sends and receives a message from all workers.
RealGroupConstructAndCall(ThreadInitializeBroadcastIntegral);
}
TEST(Group, InitializeAndClose) {
// Construct a Group of 6 workers which do nothing but terminate.
Group::ExecuteLocalMock(6, [](Group*) { });
}
TEST(Manager, InitializeAndClose) {
// Construct a Group of 6 workers which do nothing but terminate.
Manager::ExecuteLocalMock(6, [](Group*) { }, [](Group*) { }, [](Group*) { });
}
TEST(Group, InitializeSendReceive) {
// Construct a Group of 6 workers which execute the thread function
// which sends and receives asynchronous messages between all workers.
Group::ExecuteLocalMock(6, ThreadInitializeSendReceive);
}
TEST(Group, InitializeBroadcast) {
// Construct a Group of 6 workers which execute the thread function
// above which sends and receives a message from all workers.
Group::ExecuteLocalMock(6, ThreadInitializeBroadcastIntegral);
}
/*
TEST(Group, TestPrefixSum) {
for (size_t p = 2; p <= 8; p *= 2) {
// Construct Group of p workers which perform a PrefixSum collective
Group::ExecuteLocalMock(
p, [](Group* net) {
size_t local_value = 1;
net->PrefixSum(local_value);
ASSERT_EQ(local_value, net->MyRank() + 1);
});
}
}
*/
TEST(Group, TestAllReduce) {
for (size_t p = 0; p <= 8; ++p) {
// Construct Group of p workers which perform an AllReduce collective
Group::ExecuteLocalMock(
p, [](Group* net) {
size_t local_value = net->MyRank();
c7a::net::AllReduce(*net, local_value);
ASSERT_EQ(local_value, net->Size() * (net->Size() - 1) / 2);
});
}
}
TEST(Group, TestBroadcast) {
for (size_t p = 0; p <= 8; ++p) {
// Construct Group of p workers which perform an Broadcast collective
Group::ExecuteLocalMock(
p, [](Group* net) {
size_t local_value;
if (net->MyRank() == 0) local_value = 42;
c7a::net::Broadcast(*net, local_value);
ASSERT_EQ(local_value, 42u);
});
}
}
TEST(Group, TestReduceToRoot) {
for (size_t p = 0; p <= 8; ++p) {
// Construct Group of p workers which perform an Broadcast collective
Group::ExecuteLocalMock(
p, [](Group* net) {
size_t local_value = net->MyRank();
c7a::net::ReduceToRoot(*net, local_value);
if (net->MyRank() == 0)
ASSERT_EQ(local_value, net->Size() * (net->Size() - 1) / 2);
});
}
}
TEST(Group, TestBarrier) {
static const bool debug = false;
std::mutex sync_mtx; // Synchronisation mutex for the barrier
std::mutex local_mtx; // Mutex for writing to the results array
std::condition_variable cv; // Condition variable for the barrier
for (size_t p = 0; p <= 8; ++p) {
size_t workers = p;
size_t workers_copy = workers; // Will be decremented by the barrier function
std::vector<char> result(2 * workers);
int k = 0; // The counter for the result array
sLOG << "I'm in test" << workers;
Group::ExecuteLocalMock(
workers, [&](Group* net) {
local_mtx.lock();
result[k++] = 'B'; // B stands for 'Before barrier'
local_mtx.unlock();
sLOG << "Before Barrier, worker" << net->MyRank();
c7a::net::ThreadBarrier(sync_mtx, cv, workers_copy);
local_mtx.lock();
result[k++] = 'A'; // A stands for 'After barrier'
local_mtx.unlock();
sLOG << "After Barrier, worker" << net->MyRank();
});
for (size_t i = 0; i < workers; ++i) {
sLOG << "Checking position" << i;
ASSERT_EQ(result[i], 'B');
}
for (size_t i = workers; i < 2 * workers; ++i) {
sLOG << "Checking position" << i;
ASSERT_EQ(result[i], 'A');
}
}
}
/******************************************************************************/
<commit_msg>reverted type change causing compile error<commit_after>/*******************************************************************************
* tests/net/group_test.cpp
*
* Part of Project c7a.
*
* Copyright (C) 2015 Timo Bingmann <tb@panthema.net>
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#include <c7a/net/group.hpp>
#include <c7a/net/flow_control_channel.hpp>
#include <c7a/net/dispatcher.hpp>
#include <c7a/net/manager.hpp>
#include <c7a/net/collective_communication.hpp>
#include <gtest/gtest.h>
#include <thread>
#include <vector>
#include <string>
#include <random>
using namespace c7a::net;
static void ThreadInitializeAsyncRead(Group* net) {
// send a message to all other clients except ourselves.
for (size_t i = 0; i != net->Size(); ++i)
{
if (i == net->MyRank()) continue;
net->connection(i).GetSocket().send(&i, sizeof(size_t));
}
size_t received = 0;
Dispatcher dispatcher;
Dispatcher::AsyncReadCallback callback =
[net, &received](Connection& /* s */, const Buffer& buffer) {
ASSERT_EQ(*(reinterpret_cast<const size_t*>(buffer.data())),
net->MyRank());
received++;
};
// add async reads to net dispatcher
for (size_t i = 0; i != net->Size(); ++i)
{
if (i == net->MyRank()) continue;
dispatcher.AsyncRead(net->connection(i), sizeof(size_t), callback);
}
while (received < net->Size() - 1) {
dispatcher.Dispatch();
}
}
static void ThreadInitializeBroadcastIntegral(Group* net) {
static const bool debug = false;
//Broadcast our ID to everyone
for (size_t i = 0; i != net->Size(); ++i)
{
if (i == net->MyRank()) continue;
net->SendTo(i, net->MyRank());
}
//Receive the id from everyone. Make sure that the id is correct.
for (size_t i = 0; i != net->Size(); ++i)
{
if (i == net->MyRank()) continue;
size_t val;
ClientId id;
net->ReceiveFromAny<size_t>(&id, &val);
LOG << "Received " << val << " from " << id;
ASSERT_EQ((int)id, (int)val);
}
}
static void ThreadInitializeSendReceive(Group* net) {
static const bool debug = false;
// send a message to all other clients except ourselves.
for (size_t i = 0; i != net->Size(); ++i)
{
if (i == net->MyRank()) continue;
net->SendStringTo(i, "Hello " + std::to_string(net->MyRank())
+ " -> " + std::to_string(i));
}
// receive the n-1 messages from clients in order
for (size_t i = 0; i != net->Size(); ++i)
{
if (i == net->MyRank()) continue;
std::string msg;
net->ReceiveStringFrom(i, &msg);
sLOG << "Received from client" << i << "msg" << msg;
ASSERT_EQ(msg, "Hello " + std::to_string(i)
+ " -> " + std::to_string(net->MyRank()));
}
// *****************************************************************
// send another message to all other clients except ourselves. Now with connection access.
for (size_t i = 0; i != net->Size(); ++i)
{
if (i == net->MyRank()) continue;
net->connection(i).SendString("Hello " + std::to_string(net->MyRank())
+ " -> " + std::to_string(i));
}
// receive the n-1 messages from clients in any order
for (size_t i = 0; i != net->Size(); ++i)
{
if (i == net->MyRank()) continue;
ClientId from;
std::string msg;
net->ReceiveStringFromAny(&from, &msg);
sLOG << "Received from client" << i << "msg" << msg;
ASSERT_EQ(msg, "Hello " + std::to_string(from)
+ " -> " + std::to_string(net->MyRank()));
}
}
static void ThreadInitializeSendReceiveALot(Group* net) {
for (int i = 0; i < 100; i++) {
ThreadInitializeSendReceive(net);
}
}
static void ThreadInitializeSendReceiveAsyncALot(Group* net) {
for (int i = 0; i < 100; i++) {
ThreadInitializeAsyncRead(net);
}
}
static void RealGroupConstructAndCall(
std::function<void(Group*)> thread_function) {
// randomize base port number for test
std::random_device random_device;
std::default_random_engine generator(random_device());
std::uniform_int_distribution<int> distribution(30000, 65000);
const size_t port_base = distribution(generator);
static const std::vector<Endpoint> endpoints = {
Endpoint("127.0.0.1:" + std::to_string(port_base + 0)),
Endpoint("127.0.0.1:" + std::to_string(port_base + 1)),
Endpoint("127.0.0.1:" + std::to_string(port_base + 2)),
Endpoint("127.0.0.1:" + std::to_string(port_base + 3)),
Endpoint("127.0.0.1:" + std::to_string(port_base + 4)),
Endpoint("127.0.0.1:" + std::to_string(port_base + 5))
};
sLOG1 << "Group test uses ports " << port_base << "-" << port_base + 5;
static const int count = endpoints.size();
std::vector<std::thread> threads(count);
// lambda to construct Group and call user thread function.
std::vector<Manager> groups(count);
for (int i = 0; i < count; i++) {
threads[i] = std::thread(
[i, &thread_function, &groups]() {
// construct Group i with endpoints
groups[i].Initialize(i, endpoints);
// run thread function
thread_function(&groups[i].GetFlowGroup());
});
}
for (int i = 0; i < count; i++) {
threads[i].join();
}
}
TEST(Group, RealInitializeAndClose) {
// Construct a real Group of 6 workers which do nothing but terminate.
RealGroupConstructAndCall([](Group*) { });
}
TEST(Group, RealInitializeSendReceive) {
// Construct a real Group of 6 workers which execute the thread function
// above which sends and receives a message from all neighbors.
RealGroupConstructAndCall(ThreadInitializeSendReceive);
}
TEST(Group, RealInitializeSendReceiveALot) {
// Construct a real Group of 6 workers which execute the thread function
// above which sends and receives a message from all neighbors.
RealGroupConstructAndCall(ThreadInitializeSendReceive);
}
TEST(Group, RealInitializeSendReceiveAsync) { //TODO(ej) test hangs from time to time
// Construct a real Group of 6 workers which execute the thread function
// which sends and receives asynchronous messages between all workers.
RealGroupConstructAndCall(ThreadInitializeAsyncRead);
}
TEST(Group, RealInitializeSendReceiveAsyncALot) {
// Construct a real Group of 6 workers which execute the thread function
// above which sends and receives a message from all neighbors.
RealGroupConstructAndCall(ThreadInitializeSendReceive);
}
TEST(Group, RealInitializeBroadcast) {
// Construct a real Group of 6 workers which execute the thread function
// above which sends and receives a message from all workers.
RealGroupConstructAndCall(ThreadInitializeBroadcastIntegral);
}
TEST(Group, InitializeAndClose) {
// Construct a Group of 6 workers which do nothing but terminate.
Group::ExecuteLocalMock(6, [](Group*) { });
}
TEST(Manager, InitializeAndClose) {
// Construct a Group of 6 workers which do nothing but terminate.
Manager::ExecuteLocalMock(6, [](Group*) { }, [](Group*) { }, [](Group*) { });
}
TEST(Group, InitializeSendReceive) {
// Construct a Group of 6 workers which execute the thread function
// which sends and receives asynchronous messages between all workers.
Group::ExecuteLocalMock(6, ThreadInitializeSendReceive);
}
TEST(Group, InitializeBroadcast) {
// Construct a Group of 6 workers which execute the thread function
// above which sends and receives a message from all workers.
Group::ExecuteLocalMock(6, ThreadInitializeBroadcastIntegral);
}
/*
TEST(Group, TestPrefixSum) {
for (size_t p = 2; p <= 8; p *= 2) {
// Construct Group of p workers which perform a PrefixSum collective
Group::ExecuteLocalMock(
p, [](Group* net) {
size_t local_value = 1;
net->PrefixSum(local_value);
ASSERT_EQ(local_value, net->MyRank() + 1);
});
}
}
*/
TEST(Group, TestAllReduce) {
for (size_t p = 0; p <= 8; ++p) {
// Construct Group of p workers which perform an AllReduce collective
Group::ExecuteLocalMock(
p, [](Group* net) {
size_t local_value = net->MyRank();
c7a::net::AllReduce(*net, local_value);
ASSERT_EQ(local_value, net->Size() * (net->Size() - 1) / 2);
});
}
}
TEST(Group, TestBroadcast) {
for (size_t p = 0; p <= 8; ++p) {
// Construct Group of p workers which perform an Broadcast collective
Group::ExecuteLocalMock(
p, [](Group* net) {
size_t local_value;
if (net->MyRank() == 0) local_value = 42;
c7a::net::Broadcast(*net, local_value);
ASSERT_EQ(local_value, 42u);
});
}
}
TEST(Group, TestReduceToRoot) {
for (size_t p = 0; p <= 8; ++p) {
// Construct Group of p workers which perform an Broadcast collective
Group::ExecuteLocalMock(
p, [](Group* net) {
size_t local_value = net->MyRank();
c7a::net::ReduceToRoot(*net, local_value);
if (net->MyRank() == 0)
ASSERT_EQ(local_value, net->Size() * (net->Size() - 1) / 2);
});
}
}
TEST(Group, TestBarrier) {
static const bool debug = false;
std::mutex sync_mtx; // Synchronisation mutex for the barrier
std::mutex local_mtx; // Mutex for writing to the results array
std::condition_variable cv; // Condition variable for the barrier
for (int p = 0; p <= 8; ++p) {
int workers = p;
int workers_copy = workers; // Will be decremented by the barrier function
std::vector<char> result(2 * workers);
int k = 0; // The counter for the result array
sLOG << "I'm in test" << workers;
Group::ExecuteLocalMock(
workers, [&](Group* net) {
local_mtx.lock();
result[k++] = 'B'; // B stands for 'Before barrier'
local_mtx.unlock();
sLOG << "Before Barrier, worker" << net->MyRank();
c7a::net::ThreadBarrier(sync_mtx, cv, workers_copy);
local_mtx.lock();
result[k++] = 'A'; // A stands for 'After barrier'
local_mtx.unlock();
sLOG << "After Barrier, worker" << net->MyRank();
});
for (int i = 0; i < workers; ++i) {
sLOG << "Checking position" << i;
ASSERT_EQ(result[i], 'B');
}
for (int i = workers; i < 2 * workers; ++i) {
sLOG << "Checking position" << i;
ASSERT_EQ(result[i], 'A');
}
}
}
/******************************************************************************/
<|endoftext|>
|
<commit_before>/** \file
*
* Copyright (c) 2012 by Travis Gockel. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify it under the terms of the Apache License
* as published by the Apache Software Foundation, either version 2 of the License, or (at your option) any later
* version.
*
* \author Travis Gockel (travis@gockelhut.com)
**/
#include <jsonv/value.hpp>
#include <jsonv/parse.hpp>
#include "test.hpp"
TEST(parse_empty_string)
{
jsonv::value val = jsonv::parse("\"\"");
const std::string& str = val.as_string();
ensure(str == "");
}
TEST(parse_single_backslash)
{
jsonv::value val = jsonv::parse("\"\\\\\""); // "\\"
const std::string& str = val.as_string();
ensure(str == "\\");
}
<commit_msg>Issue #20: Adds a unit test to make sure string decoding errors show up as a parse_error.<commit_after>/** \file
*
* Copyright (c) 2012 by Travis Gockel. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify it under the terms of the Apache License
* as published by the Apache Software Foundation, either version 2 of the License, or (at your option) any later
* version.
*
* \author Travis Gockel (travis@gockelhut.com)
**/
#include <jsonv/value.hpp>
#include <jsonv/parse.hpp>
#include "test.hpp"
TEST(parse_empty_string)
{
jsonv::value val = jsonv::parse("\"\"");
const std::string& str = val.as_string();
ensure(str == "");
}
TEST(parse_single_backslash)
{
jsonv::value val = jsonv::parse("\"\\\\\""); // "\\"
const std::string& str = val.as_string();
ensure(str == "\\");
}
TEST(parse_bogus_string_throws)
{
// Specify a Unicode escape that isn't long enough and doesn't use hex.
ensure_throws(jsonv::parse_error, jsonv::parse("\"\\uTT\""));
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2019-2020 Fastly, Inc., Toru Maesaka, Goro Fuji
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <vector>
#include <unistd.h>
#include <stdarg.h>
#include "h2olog.h"
#include "h2o/memory.h"
#include "h2o/version.h"
#define POLL_TIMEOUT (1000)
#define PERF_BUFFER_PAGE_COUNT 256
static void usage(void)
{
printf(R"(h2olog (h2o v%s)
Usage: h2olog -p PID
h2olog quic -p PID
h2olog quic -s response_header_name -p PID
Other options:
-h Print this help and exit
-d Print debugging information
-w Path to write the output (default: stdout)
)",
H2O_VERSION);
return;
}
static void make_timestamp(char *buf, size_t buf_len)
{
time_t t = time(NULL);
struct tm tms;
localtime_r(&t, &tms);
const char *iso8601format = "%FT%TZ";
strftime(buf, buf_len, iso8601format, &tms);
}
static void infof(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
static void infof(const char *fmt, ...)
{
char buf[1024];
va_list args;
va_start(args, fmt);
vsnprintf(buf, sizeof(buf), fmt, args);
va_end(args);
char timestamp[128];
make_timestamp(timestamp, sizeof(timestamp));
fprintf(stderr, "%s %s\n", timestamp, buf);
}
static void show_event_per_sec(h2o_tracer_t *tracer, time_t *t0)
{
time_t t1 = time(NULL);
int64_t d = t1 - *t0;
if (d > 10) {
uint64_t c = tracer->count / d;
if (c > 0) {
if (tracer->lost_count > 0) {
infof("%20" PRIu64 " events/s (possibly lost %" PRIu64 " events)", c, tracer->lost_count);
tracer->lost_count = 0;
} else {
infof("%20" PRIu64 " events/s", c);
}
tracer->count = 0;
}
*t0 = t1;
}
}
static void show_process(pid_t pid)
{
char cmdline[256];
char proc_file[256];
snprintf(proc_file, sizeof(proc_file), "/proc/%d/cmdline", pid);
FILE *f = fopen(proc_file, "r");
if (f == nullptr) {
fprintf(stderr, "Error: failed to open %s: %s\n", proc_file, strerror(errno));
exit(EXIT_FAILURE);
}
size_t nread = fread(cmdline, 1, sizeof(cmdline), f);
fclose(f);
if (nread == 0) {
fprintf(stderr, "Error: failed to read from %s: %s\n", proc_file, strerror(errno));
exit(EXIT_FAILURE);
}
nread--; // skip trailing nul
for (size_t i = 0; i < nread; i++) {
if (cmdline[i] == '\0') {
cmdline[i] = ' ';
}
}
infof("Attaching pid=%d (%s)", pid, cmdline);
}
static std::string join_str(const std::string &sep, const std::vector<std::string> &strs)
{
std::string s;
for (auto iter = strs.cbegin(); iter != strs.cend(); ++iter) {
if (iter != strs.cbegin()) {
s += sep;
}
s += *iter;
}
return s;
}
static std::string generate_header_filter_cflag(const std::vector<std::string> &tokens)
{
std::vector<std::string> conditions;
for (auto &token : tokens) {
char buf[256];
snprintf(buf, sizeof(buf), "/* %s */ (slen) == %zu", token.c_str(), token.size());
std::vector<std::string> exprs = {buf};
for (size_t i = 0; i < token.size(); ++i) {
snprintf(buf, sizeof(buf), "(s)[%zu] == '%c'", i, token[i]);
exprs.push_back(buf);
}
conditions.push_back("(" + join_str(" && ", exprs) + ")");
}
std::string cflag("-DCHECK_ALLOWED_RES_HEADER_NAME(s,slen)=(");
cflag += join_str(" || ", conditions);
cflag += ")";
return cflag;
}
static std::string make_pid_cflag(const char *macro_name, pid_t pid)
{
char buf[256];
snprintf(buf, sizeof(buf), "-D%s=%d", macro_name, pid);
return std::string(buf);
}
static void event_cb(void *context, void *data, int len)
{
h2o_tracer_t *tracer = (h2o_tracer_t *)context;
tracer->count++;
tracer->handle_event(tracer, data, len);
}
static void lost_cb(void *context, uint64_t lost)
{
h2o_tracer_t *tracer = (h2o_tracer_t *)context;
tracer->lost_count += lost;
tracer->handle_lost(tracer, lost);
}
int main(int argc, char **argv)
{
h2o_tracer_t tracer = {};
if (argc > 1 && strcmp(argv[1], "quic") == 0) {
init_quic_tracer(&tracer);
--argc;
++argv;
} else {
init_http_tracer(&tracer);
}
int debug = 0;
const char *out_file = nullptr;
std::vector<std::string> event_type_filters;
std::vector<std::string> response_header_filters;
int c;
pid_t h2o_pid = -1;
while ((c = getopt(argc, argv, "hdp:t:s:w:")) != -1) {
switch (c) {
case 'p':
h2o_pid = atoi(optarg);
break;
case 't':
event_type_filters.push_back(optarg);
break;
case 's':
response_header_filters.push_back(optarg);
break;
case 'w':
out_file = optarg;
break;
case 'd':
debug++;
break;
case 'h':
usage();
exit(EXIT_SUCCESS);
default:
usage();
exit(EXIT_FAILURE);
}
}
if (argc > optind) {
fprintf(stderr, "Error: too many aruments\n");
usage();
exit(EXIT_FAILURE);
}
if (h2o_pid == -1) {
fprintf(stderr, "Error: -p option is missing\n");
usage();
exit(EXIT_FAILURE);
}
if (geteuid() != 0) {
fprintf(stderr, "Error: root privilege is required\n");
exit(EXIT_FAILURE);
}
if (out_file != nullptr) {
FILE *out = fopen(out_file, "w");
if (out == nullptr) {
fprintf(stderr, "Error: failed to open %s: %s", out_file, strerror(errno));
exit(EXIT_FAILURE);
}
tracer.out = out;
} else {
tracer.out = stdout;
}
std::vector<std::string> cflags({
make_pid_cflag("H2OLOG_H2O_PID", h2o_pid),
});
if (!response_header_filters.empty()) {
cflags.push_back(generate_header_filter_cflag(response_header_filters));
}
if (debug >= 2) {
fprintf(stderr, "cflags=");
for (size_t i = 0; i < cflags.size(); i++) {
if (i > 0) {
fprintf(stderr, " ");
}
fprintf(stderr, "%s", cflags[i].c_str());
}
fprintf(stderr, "\n");
fprintf(stderr, "<BPF>\n%s\n</BPF>\n", tracer.bpf_text().c_str());
}
ebpf::BPF *bpf = new ebpf::BPF();
std::vector<ebpf::USDT> probes = tracer.init_usdt_probes(h2o_pid);
ebpf::StatusTuple ret = bpf->init(tracer.bpf_text(), cflags, probes);
if (ret.code() != 0) {
fprintf(stderr, "Error: init: %s\n", ret.msg().c_str());
return EXIT_FAILURE;
}
bpf->attach_tracepoint("sched:sched_process_exit", "trace_sched_process_exit");
for (auto &probe : probes) {
ret = bpf->attach_usdt(probe);
if (ret.code() != 0) {
fprintf(stderr, "Error: attach_usdt: %s\n", ret.msg().c_str());
return EXIT_FAILURE;
}
}
ret = bpf->open_perf_buffer("events", event_cb, lost_cb, &tracer, PERF_BUFFER_PAGE_COUNT);
if (ret.code() != 0) {
fprintf(stderr, "Error: open_perf_buffer: %s\n", ret.msg().c_str());
return EXIT_FAILURE;
}
if (debug) {
show_process(h2o_pid);
}
ebpf::BPFPerfBuffer *perf_buffer = bpf->get_perf_buffer("events");
if (perf_buffer) {
time_t t0 = time(NULL);
while (true) {
perf_buffer->poll(POLL_TIMEOUT);
fflush(tracer.out);
if (debug) {
show_event_per_sec(&tracer, &t0);
}
}
}
fprintf(stderr, "Error: failed to get_perf_buffer()\n");
return EXIT_FAILURE;
}
<commit_msg>h2olog: explain -dd in the help message<commit_after>/*
* Copyright (c) 2019-2020 Fastly, Inc., Toru Maesaka, Goro Fuji
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <vector>
#include <unistd.h>
#include <stdarg.h>
#include "h2olog.h"
#include "h2o/memory.h"
#include "h2o/version.h"
#define POLL_TIMEOUT (1000)
#define PERF_BUFFER_PAGE_COUNT 256
static void usage(void)
{
printf(R"(h2olog (h2o v%s)
Usage: h2olog -p PID
h2olog quic -p PID
h2olog quic -s response_header_name -p PID
Other options:
-h Print this help and exit
-d Print debugging information (-dd shows more)
-w Path to write the output (default: stdout)
)",
H2O_VERSION);
return;
}
static void make_timestamp(char *buf, size_t buf_len)
{
time_t t = time(NULL);
struct tm tms;
localtime_r(&t, &tms);
const char *iso8601format = "%FT%TZ";
strftime(buf, buf_len, iso8601format, &tms);
}
static void infof(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
static void infof(const char *fmt, ...)
{
char buf[1024];
va_list args;
va_start(args, fmt);
vsnprintf(buf, sizeof(buf), fmt, args);
va_end(args);
char timestamp[128];
make_timestamp(timestamp, sizeof(timestamp));
fprintf(stderr, "%s %s\n", timestamp, buf);
}
static void show_event_per_sec(h2o_tracer_t *tracer, time_t *t0)
{
time_t t1 = time(NULL);
int64_t d = t1 - *t0;
if (d > 10) {
uint64_t c = tracer->count / d;
if (c > 0) {
if (tracer->lost_count > 0) {
infof("%20" PRIu64 " events/s (possibly lost %" PRIu64 " events)", c, tracer->lost_count);
tracer->lost_count = 0;
} else {
infof("%20" PRIu64 " events/s", c);
}
tracer->count = 0;
}
*t0 = t1;
}
}
static void show_process(pid_t pid)
{
char cmdline[256];
char proc_file[256];
snprintf(proc_file, sizeof(proc_file), "/proc/%d/cmdline", pid);
FILE *f = fopen(proc_file, "r");
if (f == nullptr) {
fprintf(stderr, "Error: failed to open %s: %s\n", proc_file, strerror(errno));
exit(EXIT_FAILURE);
}
size_t nread = fread(cmdline, 1, sizeof(cmdline), f);
fclose(f);
if (nread == 0) {
fprintf(stderr, "Error: failed to read from %s: %s\n", proc_file, strerror(errno));
exit(EXIT_FAILURE);
}
nread--; // skip trailing nul
for (size_t i = 0; i < nread; i++) {
if (cmdline[i] == '\0') {
cmdline[i] = ' ';
}
}
infof("Attaching pid=%d (%s)", pid, cmdline);
}
static std::string join_str(const std::string &sep, const std::vector<std::string> &strs)
{
std::string s;
for (auto iter = strs.cbegin(); iter != strs.cend(); ++iter) {
if (iter != strs.cbegin()) {
s += sep;
}
s += *iter;
}
return s;
}
static std::string generate_header_filter_cflag(const std::vector<std::string> &tokens)
{
std::vector<std::string> conditions;
for (auto &token : tokens) {
char buf[256];
snprintf(buf, sizeof(buf), "/* %s */ (slen) == %zu", token.c_str(), token.size());
std::vector<std::string> exprs = {buf};
for (size_t i = 0; i < token.size(); ++i) {
snprintf(buf, sizeof(buf), "(s)[%zu] == '%c'", i, token[i]);
exprs.push_back(buf);
}
conditions.push_back("(" + join_str(" && ", exprs) + ")");
}
std::string cflag("-DCHECK_ALLOWED_RES_HEADER_NAME(s,slen)=(");
cflag += join_str(" || ", conditions);
cflag += ")";
return cflag;
}
static std::string make_pid_cflag(const char *macro_name, pid_t pid)
{
char buf[256];
snprintf(buf, sizeof(buf), "-D%s=%d", macro_name, pid);
return std::string(buf);
}
static void event_cb(void *context, void *data, int len)
{
h2o_tracer_t *tracer = (h2o_tracer_t *)context;
tracer->count++;
tracer->handle_event(tracer, data, len);
}
static void lost_cb(void *context, uint64_t lost)
{
h2o_tracer_t *tracer = (h2o_tracer_t *)context;
tracer->lost_count += lost;
tracer->handle_lost(tracer, lost);
}
int main(int argc, char **argv)
{
h2o_tracer_t tracer = {};
if (argc > 1 && strcmp(argv[1], "quic") == 0) {
init_quic_tracer(&tracer);
--argc;
++argv;
} else {
init_http_tracer(&tracer);
}
int debug = 0;
const char *out_file = nullptr;
std::vector<std::string> event_type_filters;
std::vector<std::string> response_header_filters;
int c;
pid_t h2o_pid = -1;
while ((c = getopt(argc, argv, "hdp:t:s:w:")) != -1) {
switch (c) {
case 'p':
h2o_pid = atoi(optarg);
break;
case 't':
event_type_filters.push_back(optarg);
break;
case 's':
response_header_filters.push_back(optarg);
break;
case 'w':
out_file = optarg;
break;
case 'd':
debug++;
break;
case 'h':
usage();
exit(EXIT_SUCCESS);
default:
usage();
exit(EXIT_FAILURE);
}
}
if (argc > optind) {
fprintf(stderr, "Error: too many aruments\n");
usage();
exit(EXIT_FAILURE);
}
if (h2o_pid == -1) {
fprintf(stderr, "Error: -p option is missing\n");
usage();
exit(EXIT_FAILURE);
}
if (geteuid() != 0) {
fprintf(stderr, "Error: root privilege is required\n");
exit(EXIT_FAILURE);
}
if (out_file != nullptr) {
FILE *out = fopen(out_file, "w");
if (out == nullptr) {
fprintf(stderr, "Error: failed to open %s: %s", out_file, strerror(errno));
exit(EXIT_FAILURE);
}
tracer.out = out;
} else {
tracer.out = stdout;
}
std::vector<std::string> cflags({
make_pid_cflag("H2OLOG_H2O_PID", h2o_pid),
});
if (!response_header_filters.empty()) {
cflags.push_back(generate_header_filter_cflag(response_header_filters));
}
if (debug >= 2) {
fprintf(stderr, "cflags=");
for (size_t i = 0; i < cflags.size(); i++) {
if (i > 0) {
fprintf(stderr, " ");
}
fprintf(stderr, "%s", cflags[i].c_str());
}
fprintf(stderr, "\n");
fprintf(stderr, "<BPF>\n%s\n</BPF>\n", tracer.bpf_text().c_str());
}
ebpf::BPF *bpf = new ebpf::BPF();
std::vector<ebpf::USDT> probes = tracer.init_usdt_probes(h2o_pid);
ebpf::StatusTuple ret = bpf->init(tracer.bpf_text(), cflags, probes);
if (ret.code() != 0) {
fprintf(stderr, "Error: init: %s\n", ret.msg().c_str());
return EXIT_FAILURE;
}
bpf->attach_tracepoint("sched:sched_process_exit", "trace_sched_process_exit");
for (auto &probe : probes) {
ret = bpf->attach_usdt(probe);
if (ret.code() != 0) {
fprintf(stderr, "Error: attach_usdt: %s\n", ret.msg().c_str());
return EXIT_FAILURE;
}
}
ret = bpf->open_perf_buffer("events", event_cb, lost_cb, &tracer, PERF_BUFFER_PAGE_COUNT);
if (ret.code() != 0) {
fprintf(stderr, "Error: open_perf_buffer: %s\n", ret.msg().c_str());
return EXIT_FAILURE;
}
if (debug) {
show_process(h2o_pid);
}
ebpf::BPFPerfBuffer *perf_buffer = bpf->get_perf_buffer("events");
if (perf_buffer) {
time_t t0 = time(NULL);
while (true) {
perf_buffer->poll(POLL_TIMEOUT);
fflush(tracer.out);
if (debug) {
show_event_per_sec(&tracer, &t0);
}
}
}
fprintf(stderr, "Error: failed to get_perf_buffer()\n");
return EXIT_FAILURE;
}
<|endoftext|>
|
<commit_before><commit_msg>Coverity: Initialize member view_ to NULL in constructor.<commit_after><|endoftext|>
|
<commit_before>//===--- Local.cpp - Functions that perform local SIL transformations. ---===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===---------------------------------------------------------------------===//
#include "swift/SILPasses/Utils/Local.h"
#include "swift/SILAnalysis/Analysis.h"
#include "swift/SIL/CallGraph.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILModule.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/IR/Intrinsics.h"
#include <deque>
using namespace swift;
bool
swift::isSideEffectFree(BuiltinFunctionRefInst *FR) {
// First, check if we are dealing with a swift builtin.
const BuiltinInfo &BInfo = FR->getBuiltinInfo();
if (BInfo.ID != BuiltinValueKind::None) {
return BInfo.isReadNone();
}
// Second, specialcase llvm intrinsic.
const IntrinsicInfo & IInfo = FR->getIntrinsicInfo();
if (IInfo.ID != llvm::Intrinsic::not_intrinsic) {
return ( (IInfo.hasAttribute(llvm::Attribute::ReadNone) ||
IInfo.hasAttribute(llvm::Attribute::ReadOnly)) &&
IInfo.hasAttribute(llvm::Attribute::NoUnwind) );
}
llvm_unreachable("All cases are covered.");
}
bool swift::isReadNone(BuiltinFunctionRefInst *FR) {
// First, check if we are dealing with a swift builtin.
const BuiltinInfo &BInfo = FR->getBuiltinInfo();
if (BInfo.ID != BuiltinValueKind::None)
return BInfo.isReadNone();
// Second, specialcase llvm intrinsic.
const IntrinsicInfo & IInfo = FR->getIntrinsicInfo();
if (IInfo.ID != llvm::Intrinsic::not_intrinsic)
return IInfo.hasAttribute(llvm::Attribute::ReadNone) &&
IInfo.hasAttribute(llvm::Attribute::NoUnwind);
llvm_unreachable("All cases are covered.");
}
/// \brief Perform a fast local check to see if the instruction is dead.
///
/// This routine only examines the state of the instruction at hand.
bool
swift::isInstructionTriviallyDead(SILInstruction *I) {
if (!I->use_empty() || isa<TermInst>(I))
return false;
// We know that some calls do not have side effects.
if (const ApplyInst *AI = dyn_cast<ApplyInst>(I)) {
if (BuiltinFunctionRefInst *FR =
dyn_cast<BuiltinFunctionRefInst>(AI->getCallee().getDef())) {
return isSideEffectFree(FR);
}
}
// condfail instructions that obviously can't fail are dead.
if (auto *CFI = dyn_cast<CondFailInst>(I))
if (auto *ILI = dyn_cast<IntegerLiteralInst>(CFI->getOperand()))
if (!ILI->getValue())
return true;
// mark_uninitialized is never dead.
if (isa<MarkUninitializedInst>(I))
return false;
if (!I->mayHaveSideEffects())
return true;
return false;
}
/// \brief For each of the given instructions, if they are dead delete them
/// along with their dead operands.
///
/// \param IA The instruction to be deleted.
/// \param Force If Force is set, don't check if the top level instructions
/// are considered dead - delete them regardless.
bool
swift::recursivelyDeleteTriviallyDeadInstructions(ArrayRef<SILInstruction*> IA,
bool Force) {
// Delete these instruction and others that become dead after it's deleted.
llvm::SmallPtrSet<SILInstruction*, 8> DeadInsts;
for (auto I : IA) {
// If the instruction is not dead or force is false, there is nothing to do.
if (Force || isInstructionTriviallyDead(I))
DeadInsts.insert(I);
}
llvm::SmallPtrSet<SILInstruction*, 8> NextInsts;
while (!DeadInsts.empty()) {
for (auto I : DeadInsts) {
// Check if any of the operands will become dead as well.
MutableArrayRef<Operand> Ops = I->getAllOperands();
for (Operand &Op : Ops) {
SILValue OpVal = Op.get();
if (!OpVal) continue;
// Remove the reference from the instruction being deleted to this
// operand.
Op.drop();
// If the operand is an instruction that is only used by the instruction
// being deleted, delete it.
if (SILInstruction *OpValInst = dyn_cast<SILInstruction>(OpVal))
if (!DeadInsts.count(OpValInst) &&
isInstructionTriviallyDead(OpValInst))
NextInsts.insert(OpValInst);
}
}
for (auto I : DeadInsts) {
// This will remove this instruction and all its uses.
I->eraseFromParent();
}
NextInsts.swap(DeadInsts);
NextInsts.clear();
}
return true;
}
/// \brief If the given instruction is dead, delete it along with its dead
/// operands.
///
/// \param I The instruction to be deleted.
/// \param Force If Force is set, don't check if the top level instruction is
/// considered dead - delete it regardless.
/// \return Returns true if any instructions were deleted.
bool
swift::recursivelyDeleteTriviallyDeadInstructions(SILInstruction *I,
bool Force) {
return recursivelyDeleteTriviallyDeadInstructions(
ArrayRef<SILInstruction*>(I), Force);
}
void swift::eraseUsesOfInstruction(SILInstruction *Inst) {
for (auto UI : Inst->getUses()) {
auto *User = UI->getUser();
// If the instruction itself has any uses, recursively zap them so that
// nothing uses this instruction.
eraseUsesOfInstruction(User);
// Walk through the operand list and delete any random instructions that
// will become trivially dead when this instruction is removed.
for (auto &Op : User->getAllOperands()) {
if (auto *OpI = dyn_cast<SILInstruction>(Op.get().getDef())) {
// Don't recursively delete the pointer we're getting in.
if (OpI != Inst) {
Op.drop();
recursivelyDeleteTriviallyDeadInstructions(OpI);
}
}
}
User->eraseFromParent();
}
}
void swift::bottomUpCallGraphOrder(SILModule *M,
std::vector<SILFunction*> &order) {
CallGraphSorter<SILFunction*> sorter;
for (auto &Caller : *M)
for (auto &BB : Caller)
for (auto &I : BB)
if (FunctionRefInst *FRI = dyn_cast<FunctionRefInst>(&I)) {
SILFunction *Callee = FRI->getReferencedFunction();
sorter.addEdge(&Caller, Callee);
}
sorter.sort(order);
}
void swift::replaceWithSpecializedFunction(ApplyInst *AI, SILFunction *NewF) {
SILLocation Loc = AI->getLoc();
ArrayRef<Substitution> Subst;
SmallVector<SILValue, 4> Arguments;
for (auto &Op : AI->getArgumentOperands()) {
Arguments.push_back(Op.get());
}
SILBuilder Builder(AI);
FunctionRefInst *FRI = Builder.createFunctionRef(Loc, NewF);
ApplyInst *NAI =
Builder.createApply(Loc, FRI, Arguments, AI->isTransparent());
SILValue(AI, 0).replaceAllUsesWith(SILValue(NAI, 0));
recursivelyDeleteTriviallyDeadInstructions(AI, true);
}
/// \brief Returns True if the operand or one of its users is captured.
static bool useCaptured(Operand *UI) {
auto *User = UI->getUser();
// These instructions do not cause the address to escape.
if (isa<CopyAddrInst>(User) ||
isa<LoadInst>(User) ||
isa<ProtocolMethodInst>(User))
return false;
if (auto *Store = dyn_cast<StoreInst>(User)) {
if (Store->getDest() == UI->get())
return false;
} else if (auto *Assign = dyn_cast<AssignInst>(User)) {
if (Assign->getDest() == UI->get())
return false;
}
return true;
}
bool
swift::canValueEscape(SILValue V) {
for (auto UI : V.getUses()) {
auto *User = UI->getUser();
// These instructions do not cause the address to escape.
if (!useCaptured(UI))
continue;
// These instructions only cause the value to escape if they are used in
// a way that escapes. Recursively check that the uses of the instruction
// don't escape and collect all of the uses of the value.
if (isa<StructElementAddrInst>(User) || isa<TupleElementAddrInst>(User) ||
isa<ProjectExistentialInst>(User) || isa<OpenExistentialInst>(User) ||
isa<MarkUninitializedInst>(User) || isa<AddressToPointerInst>(User) ||
isa<PointerToAddressInst>(User)) {
if (canValueEscape(User))
return true;
continue;
}
// apply instructions do not capture the pointer when it is passed
// indirectly
if (auto apply = dyn_cast<ApplyInst>(User)) {
if (apply->getSubstCalleeType()
->getInterfaceParameters()[UI->getOperandNumber()-1].isIndirect()) {
continue;
}
}
// partial_apply instructions do not allow the pointer to escape
// when it is passed indirectly, unless the partial_apply itself
// escapes
if (auto partialApply = dyn_cast<PartialApplyInst>(User)) {
auto args = partialApply->getArguments();
auto params = partialApply->getSubstCalleeType()
->getInterfaceParameters();
params = params.slice(params.size() - args.size(), args.size());
if (params[UI->getOperandNumber()-1].isIndirect()) {
if (canValueEscape(User))
return true;
continue;
}
}
return true;
}
return false;
}
bool swift::hasUnboundGenericTypes(Type T) {
return T.findIf([](Type type) ->bool {
return isa<ArchetypeType>(type.getPointer());
});
}
<commit_msg>Update escape helpers with a few more cases.<commit_after>//===--- Local.cpp - Functions that perform local SIL transformations. ---===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===---------------------------------------------------------------------===//
#include "swift/SILPasses/Utils/Local.h"
#include "swift/SILAnalysis/Analysis.h"
#include "swift/SIL/CallGraph.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILModule.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/IR/Intrinsics.h"
#include <deque>
using namespace swift;
bool
swift::isSideEffectFree(BuiltinFunctionRefInst *FR) {
// First, check if we are dealing with a swift builtin.
const BuiltinInfo &BInfo = FR->getBuiltinInfo();
if (BInfo.ID != BuiltinValueKind::None) {
return BInfo.isReadNone();
}
// Second, specialcase llvm intrinsic.
const IntrinsicInfo & IInfo = FR->getIntrinsicInfo();
if (IInfo.ID != llvm::Intrinsic::not_intrinsic) {
return ( (IInfo.hasAttribute(llvm::Attribute::ReadNone) ||
IInfo.hasAttribute(llvm::Attribute::ReadOnly)) &&
IInfo.hasAttribute(llvm::Attribute::NoUnwind) );
}
llvm_unreachable("All cases are covered.");
}
bool swift::isReadNone(BuiltinFunctionRefInst *FR) {
// First, check if we are dealing with a swift builtin.
const BuiltinInfo &BInfo = FR->getBuiltinInfo();
if (BInfo.ID != BuiltinValueKind::None)
return BInfo.isReadNone();
// Second, specialcase llvm intrinsic.
const IntrinsicInfo & IInfo = FR->getIntrinsicInfo();
if (IInfo.ID != llvm::Intrinsic::not_intrinsic)
return IInfo.hasAttribute(llvm::Attribute::ReadNone) &&
IInfo.hasAttribute(llvm::Attribute::NoUnwind);
llvm_unreachable("All cases are covered.");
}
/// \brief Perform a fast local check to see if the instruction is dead.
///
/// This routine only examines the state of the instruction at hand.
bool
swift::isInstructionTriviallyDead(SILInstruction *I) {
if (!I->use_empty() || isa<TermInst>(I))
return false;
// We know that some calls do not have side effects.
if (const ApplyInst *AI = dyn_cast<ApplyInst>(I)) {
if (BuiltinFunctionRefInst *FR =
dyn_cast<BuiltinFunctionRefInst>(AI->getCallee().getDef())) {
return isSideEffectFree(FR);
}
}
// condfail instructions that obviously can't fail are dead.
if (auto *CFI = dyn_cast<CondFailInst>(I))
if (auto *ILI = dyn_cast<IntegerLiteralInst>(CFI->getOperand()))
if (!ILI->getValue())
return true;
// mark_uninitialized is never dead.
if (isa<MarkUninitializedInst>(I))
return false;
if (!I->mayHaveSideEffects())
return true;
return false;
}
/// \brief For each of the given instructions, if they are dead delete them
/// along with their dead operands.
///
/// \param IA The instruction to be deleted.
/// \param Force If Force is set, don't check if the top level instructions
/// are considered dead - delete them regardless.
bool
swift::recursivelyDeleteTriviallyDeadInstructions(ArrayRef<SILInstruction*> IA,
bool Force) {
// Delete these instruction and others that become dead after it's deleted.
llvm::SmallPtrSet<SILInstruction*, 8> DeadInsts;
for (auto I : IA) {
// If the instruction is not dead or force is false, there is nothing to do.
if (Force || isInstructionTriviallyDead(I))
DeadInsts.insert(I);
}
llvm::SmallPtrSet<SILInstruction*, 8> NextInsts;
while (!DeadInsts.empty()) {
for (auto I : DeadInsts) {
// Check if any of the operands will become dead as well.
MutableArrayRef<Operand> Ops = I->getAllOperands();
for (Operand &Op : Ops) {
SILValue OpVal = Op.get();
if (!OpVal) continue;
// Remove the reference from the instruction being deleted to this
// operand.
Op.drop();
// If the operand is an instruction that is only used by the instruction
// being deleted, delete it.
if (SILInstruction *OpValInst = dyn_cast<SILInstruction>(OpVal))
if (!DeadInsts.count(OpValInst) &&
isInstructionTriviallyDead(OpValInst))
NextInsts.insert(OpValInst);
}
}
for (auto I : DeadInsts) {
// This will remove this instruction and all its uses.
I->eraseFromParent();
}
NextInsts.swap(DeadInsts);
NextInsts.clear();
}
return true;
}
/// \brief If the given instruction is dead, delete it along with its dead
/// operands.
///
/// \param I The instruction to be deleted.
/// \param Force If Force is set, don't check if the top level instruction is
/// considered dead - delete it regardless.
/// \return Returns true if any instructions were deleted.
bool
swift::recursivelyDeleteTriviallyDeadInstructions(SILInstruction *I,
bool Force) {
return recursivelyDeleteTriviallyDeadInstructions(
ArrayRef<SILInstruction*>(I), Force);
}
void swift::eraseUsesOfInstruction(SILInstruction *Inst) {
for (auto UI : Inst->getUses()) {
auto *User = UI->getUser();
// If the instruction itself has any uses, recursively zap them so that
// nothing uses this instruction.
eraseUsesOfInstruction(User);
// Walk through the operand list and delete any random instructions that
// will become trivially dead when this instruction is removed.
for (auto &Op : User->getAllOperands()) {
if (auto *OpI = dyn_cast<SILInstruction>(Op.get().getDef())) {
// Don't recursively delete the pointer we're getting in.
if (OpI != Inst) {
Op.drop();
recursivelyDeleteTriviallyDeadInstructions(OpI);
}
}
}
User->eraseFromParent();
}
}
void swift::bottomUpCallGraphOrder(SILModule *M,
std::vector<SILFunction*> &order) {
CallGraphSorter<SILFunction*> sorter;
for (auto &Caller : *M)
for (auto &BB : Caller)
for (auto &I : BB)
if (FunctionRefInst *FRI = dyn_cast<FunctionRefInst>(&I)) {
SILFunction *Callee = FRI->getReferencedFunction();
sorter.addEdge(&Caller, Callee);
}
sorter.sort(order);
}
void swift::replaceWithSpecializedFunction(ApplyInst *AI, SILFunction *NewF) {
SILLocation Loc = AI->getLoc();
ArrayRef<Substitution> Subst;
SmallVector<SILValue, 4> Arguments;
for (auto &Op : AI->getArgumentOperands()) {
Arguments.push_back(Op.get());
}
SILBuilder Builder(AI);
FunctionRefInst *FRI = Builder.createFunctionRef(Loc, NewF);
ApplyInst *NAI =
Builder.createApply(Loc, FRI, Arguments, AI->isTransparent());
SILValue(AI, 0).replaceAllUsesWith(SILValue(NAI, 0));
recursivelyDeleteTriviallyDeadInstructions(AI, true);
}
/// \brief Returns True if the operand or one of its users is captured.
static bool useCaptured(Operand *UI) {
auto *User = UI->getUser();
// These instructions do not cause the address to escape.
if (isa<CopyAddrInst>(User) ||
isa<LoadInst>(User) ||
isa<ProtocolMethodInst>(User) ||
isa<DebugValueInst>(User) ||
isa<DebugValueAddrInst>(User))
return false;
if (auto *Store = dyn_cast<StoreInst>(User)) {
if (Store->getDest() == UI->get())
return false;
} else if (auto *Assign = dyn_cast<AssignInst>(User)) {
if (Assign->getDest() == UI->get())
return false;
}
return true;
}
bool
swift::canValueEscape(SILValue V) {
for (auto UI : V.getUses()) {
auto *User = UI->getUser();
// These instructions do not cause the address to escape.
if (!useCaptured(UI))
continue;
// These instructions only cause the value to escape if they are used in
// a way that escapes. Recursively check that the uses of the instruction
// don't escape and collect all of the uses of the value.
if (isa<StructElementAddrInst>(User) || isa<TupleElementAddrInst>(User) ||
isa<ProjectExistentialInst>(User) || isa<OpenExistentialInst>(User) ||
isa<MarkUninitializedInst>(User) || isa<AddressToPointerInst>(User) ||
isa<PointerToAddressInst>(User)) {
if (canValueEscape(User))
return true;
continue;
}
// apply instructions do not capture the pointer when it is passed
// indirectly
if (auto apply = dyn_cast<ApplyInst>(User)) {
// Applying a function does not cause the function to escape.
if (UI->getOperandNumber() == 0)
continue;
if (apply->getSubstCalleeType()
->getInterfaceParameters()[UI->getOperandNumber()-1].isIndirect()) {
continue;
}
}
// partial_apply instructions do not allow the pointer to escape
// when it is passed indirectly, unless the partial_apply itself
// escapes
if (auto partialApply = dyn_cast<PartialApplyInst>(User)) {
auto args = partialApply->getArguments();
auto params = partialApply->getSubstCalleeType()
->getInterfaceParameters();
params = params.slice(params.size() - args.size(), args.size());
if (params[UI->getOperandNumber()-1].isIndirect()) {
if (canValueEscape(User))
return true;
continue;
}
}
return true;
}
return false;
}
bool swift::hasUnboundGenericTypes(Type T) {
return T.findIf([](Type type) ->bool {
return isa<ArchetypeType>(type.getPointer());
});
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2009 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 "base/platform_thread.h"
#include "base/multiprocess_test.h"
#include "chrome/common/process_watcher.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
class ProcessWatcherTest : public MultiProcessTest {
};
MULTIPROCESS_TEST_MAIN(Sleep1ChildProcess) {
PlatformThread::Sleep(1000);
exit(0);
return 0;
}
MULTIPROCESS_TEST_MAIN(Sleep3ChildProcess) {
PlatformThread::Sleep(3000);
exit(0);
return 0;
}
TEST_F(ProcessWatcherTest, DiesBeforeTermination) {
base::ProcessHandle handle = this->SpawnChild(L"Sleep1ChildProcess");
ASSERT_NE(static_cast<base::ProcessHandle>(NULL), handle);
ProcessWatcher::EnsureProcessTerminated(handle);
PlatformThread::Sleep(2500);
// Normally we don't touch |handle| after calling EnsureProcessTerminated,
// but we know the EnsureProcessTerminated process finishes in 2000 ms, so
// it's safe to do so now. Same for Terminated test case below.
EXPECT_FALSE(base::CrashAwareSleep(handle, 0));
}
TEST_F(ProcessWatcherTest, Terminated) {
base::ProcessHandle handle = this->SpawnChild(L"Sleep3ChildProcess");
ASSERT_NE(static_cast<base::ProcessHandle>(NULL), handle);
ProcessWatcher::EnsureProcessTerminated(handle);
PlatformThread::Sleep(2500);
EXPECT_FALSE(base::CrashAwareSleep(handle, 0));
}
TEST_F(ProcessWatcherTest, NotTerminated) {
base::ProcessHandle handle = this->SpawnChild(L"Sleep3ChildProcess");
ASSERT_NE(static_cast<base::ProcessHandle>(NULL), handle);
EXPECT_TRUE(base::CrashAwareSleep(handle, 2500));
EXPECT_FALSE(base::CrashAwareSleep(handle, 1000));
}
} // namespace
<commit_msg>Revert 21259 because it broke the unit tests on windows.<commit_after><|endoftext|>
|
<commit_before>#line 2 "togo/core/lua/lua.hpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
@file
@brief Scripting interface.
@ingroup lib_core_lua
*/
#pragma once
#include <togo/core/config.hpp>
#include <togo/core/types.hpp>
#include <togo/core/error/assert.hpp>
#include <togo/core/utility/traits.hpp>
#include <togo/core/utility/utility.hpp>
#include <togo/core/memory/types.hpp>
#include <togo/core/string/string.hpp>
#include <togo/core/lua/types.hpp>
extern "C" {
#include <luajit-2.0/lua.h>
#include <luajit-2.0/lauxlib.h>
#include <luajit-2.0/lualib.h>
}
#include <togo/core/lua/lua.gen_interface>
namespace togo {
namespace lua {
/**
@addtogroup lib_core_lua
@{
*/
/// Push nil to the stack.
inline void push_value(lua_State* L, null_tag const) {
lua_pushnil(L);
}
/// Push an integral value to the stack.
template<class T>
inline enable_if<is_integral<T>::value, void> push_value(lua_State* L, T value) {
lua_pushinteger(L, value);
}
/// Get an argument from the stack as an integer.
inline LuaInt get_integer(lua_State* L, signed narg) {
return luaL_checkinteger(L, narg);
}
/// Push a floating-point value to the stack.
template<class T>
inline enable_if<is_floating_point<T>::value, void> push_value(lua_State* L, T value) {
lua_pushinteger(L, value);
}
/// Get an argument from the stack as an integer.
inline LuaFloat get_float(lua_State* L, signed narg) {
return luaL_checknumber(L, narg);
}
// NB: Using template to avoid implicit cast from pointers and integrals.
/// Push a bool to the stack.
template<class T>
inline enable_if<is_same<T, bool>::value, void> push_value(lua_State* L, T value) {
lua_pushboolean(L, value);
}
/// Get an argument from the stack as a boolean.
inline bool get_boolean(lua_State* L, signed narg) {
luaL_checktype(L, narg, LUA_TBOOLEAN);
return lua_toboolean(L, narg);
}
/// Push a string to the stack.
inline void push_value(lua_State* L, StringRef str) {
lua_pushlstring(L, str.data ? str.data : "", unsigned_cast(str.size));
}
/// Get a string from the stack as a string reference.
inline StringRef get_string(lua_State* L, signed narg) {
size_t size = 0;
auto data = luaL_checklstring(L, narg, &size);
return {data, static_cast<unsigned>(size)};
}
/// Push a C function to the stack.
inline void push_value(lua_State* L, LuaCFunction value) {
lua_pushcfunction(L, value);
}
/// Get a C function from the stack.
inline LuaCFunction* get_cfunction(lua_State* L, signed narg) {
luaL_checktype(L, narg, LUA_TFUNCTION);
return lua_tocfunction(L, narg);
}
/// Set table[name] = value (with settable).
template<class T>
inline void table_set(lua_State* L, signed table, StringRef name, T value) {
lua::push_value(L, name);
lua::push_value(L, value);
lua_settable(L, table);
}
/// Set top_of_stack[name] = value (with settable).
template<class T>
inline void table_set(lua_State* L, StringRef name, T value) {
lua::table_set(L, -3, name, value);
}
/// Set table[name] = value (with rawset).
template<class T>
inline void table_set_raw(lua_State* L, signed table, StringRef name, T value) {
lua::push_value(L, name);
lua::push_value(L, value);
lua_rawset(L, table);
}
/// Set top_of_stack[name] = value (with rawset).
template<class T>
inline void table_set_raw(lua_State* L, StringRef name, T value) {
lua::table_set_raw(L, -3, name, value);
}
/// Fetch the value of table[name] and push it on the stack (with gettable).
inline void table_get(lua_State* L, signed table, StringRef name) {
lua::push_value(L, name);
lua_gettable(L, table);
}
/// Fetch the value of top_of_stack[name] and push it on the stack (with gettable).
inline void table_get(lua_State* L, StringRef name) {
lua::table_get(L, -2, name);
}
/// Fetch the value of table[name] and push it on the stack (with rawget).
inline void table_get_raw(lua_State* L, signed table, StringRef name) {
lua::push_value(L, name);
lua_rawget(L, table);
}
/// Fetch the value of top_of_stack[name] and push it on the stack (with rawget).
inline void table_get_raw(lua_State* L, StringRef name) {
lua::table_get_raw(L, -2, name);
}
/// Set table[index] = value (with settable).
template<class T>
inline void table_set_index(lua_State* L, signed table, signed index, T value) {
lua::push_value(L, index);
lua::push_value(L, value);
lua_settable(L, table);
}
/// Set top_of_stack[index] = value (with settable).
template<class T>
inline void table_set_index(lua_State* L, signed index, T value) {
lua::table_set_index(L, -3, index, value);
}
/// Set table[index] = value (with rawset).
template<class T>
inline void table_set_index_raw(lua_State* L, signed table, signed index, T value) {
lua::push_value(L, value);
lua_rawseti(L, table, index);
}
/// Set top_of_stack[index] = value (with rawset).
template<class T>
inline void table_set_index_raw(lua_State* L, signed index, T value) {
lua::table_set_index_raw(L, -2, index, value);
}
/// Fetch the value of table[index] and push it on the stack (with rawget).
inline void table_get_index(lua_State* L, signed table, signed index) {
lua::push_value(L, index);
lua_gettable(L, table);
}
/// Fetch the value of top_of_stack[index] and push it on the stack (with rawget).
inline void table_get_index(lua_State* L, signed index) {
lua::table_get_index(L, -2, index);
}
/// Fetch the value of table[index] and push it on the stack (with rawget).
inline void table_get_index_raw(lua_State* L, signed table, signed index) {
lua_rawgeti(L, table, index);
}
/// Fetch the value of top_of_stack[index] and push it on the stack (with rawget).
inline void table_get_index_raw(lua_State* L, signed index) {
lua::table_get_index_raw(L, -1, index);
}
/// Set table[name] = stack[value] (with settable).
inline void table_set_copy(lua_State* L, signed table, StringRef name, signed value) {
lua::push_value(L, name);
lua_pushvalue(L, value - 1);
lua_settable(L, table);
}
/// Set top_of_stack[name] = stack[value] (with settable).
inline void table_set_copy(lua_State* L, StringRef name, signed value) {
lua::table_set_copy(L, -3, name, value);
}
/// Set table[name] = stack[value] (with rawset).
inline void table_set_copy_raw(lua_State* L, signed table, StringRef name, signed value) {
lua::push_value(L, name);
lua_pushvalue(L, value - 1);
lua_rawset(L, table);
}
/// Set top_of_stack[name] = stack[value] (with rawset).
inline void table_set_copy_raw(lua_State* L, StringRef name, signed value) {
lua::table_set_copy_raw(L, -3, name, value);
}
/// Set table[index] = stack[value] (with settable).
inline void table_set_copy_index(lua_State* L, signed table, signed index, signed value) {
lua::push_value(L, index);
lua_pushvalue(L, value - 1);
lua_settable(L, table);
}
/// Set top_of_stack[index] = stack[value] (with settable).
inline void table_set_copy_index(lua_State* L, signed index, signed value) {
lua::table_set_copy_index(L, -3, index, value);
}
/// Set table[index] = stack[value] (with rawset).
inline void table_set_copy_index_raw(lua_State* L, signed table, signed index, signed value) {
lua_pushvalue(L, value);
lua_rawseti(L, table, index);
}
/// Set top_of_stack[index] = stack[value] (with rawset).
inline void table_set_copy_index_raw(lua_State* L, signed index, signed value) {
lua::table_set_copy_index_raw(L, -2, index, value);
}
template<class T>
inline void register_userdata(lua_State* L, LuaCFunction destroy, bool keep_metatable = false) {
lua::table_get_raw(L, LUA_REGISTRYINDEX, "togo_class");
TOGO_ASSERT(!lua_isnil(L, -1), "core was not registered");
lua::table_get_raw(L, T::lua_metatable_name);
TOGO_ASSERT(lua_isnil(L, -1), "class metatable was already registered");
lua_pop(L, 1);
lua_createtable(L, 0, 1);
lua::table_set_copy_raw(L, "__index", -1);
lua::table_set_raw(L, "__gc", destroy);
// togo_class[T::lua_metatable_name] = metatable
lua::table_set_copy_raw(L, -4, T::lua_metatable_name, -1);
lua_remove(L, -2); // togo_class
if (!keep_metatable) {
lua_pop(L, 1);
}
}
/// Push a new userdata to the stack and setup its metatable.
template<class T, class... P>
inline T* new_userdata(lua_State* L, P&&... p) {
auto* ptr = lua_newuserdata(L, sizeof(T));
TOGO_DEBUG_ASSERTE(ptr);
lua::table_get_raw(L, LUA_REGISTRYINDEX, "togo_class");
TOGO_ASSERT(!lua_isnil(L, -1), "core was not registered");
lua::table_get_raw(L, T::lua_metatable_name);
TOGO_ASSERT(!lua_isnil(L, -1), "class metatable was not registered");
lua_setmetatable(L, -3);
lua_pop(L, 1);
return new(ptr) T(p...);
}
/// Get an argument from the stack as userdata (typed).
template<class T>
inline T* get_userdata(lua_State* L, signed narg, bool require = true) {
{auto type = lua_type(L, narg);
if (type != LUA_TUSERDATA && type != LUA_TNIL) {
luaL_argerror(L, narg, "expected userdata");
}}
auto p = lua_touserdata(L, narg);
if (require && !p) {
luaL_argerror(L, narg, "value must be non-null");
} else {
if (!lua_getmetatable(L, narg)) {
luaL_argerror(L, narg, "expected a metatable for userdata, but it has none");
}
lua::table_get_raw(L, LUA_REGISTRYINDEX, "togo_class");
TOGO_ASSERT(!lua_isnil(L, -1), "core was not registered");
lua::table_get_raw(L, T::lua_metatable_name);
TOGO_ASSERT(!lua_isnil(L, -1), "class metatable was not registered");
if (!lua_rawequal(L, -1, -3)) {
luaL_argerror(L, narg, "userdata metatable does not match the expected one");
}
lua_pop(L, 3);
}
return static_cast<T*>(p);
}
/// Push a light userdata to the stack or nil if the pointer is null.
inline void push_lightuserdata(lua_State* L, void* p) {
if (p) {
lua_pushlightuserdata(L, p);
} else {
lua_pushnil(L);
}
}
/// Get an argument from the stack as light userdata.
inline void* get_lightuserdata(lua_State* L, signed narg, bool require = true) {
{auto type = lua_type(L, narg);
if (type != LUA_TLIGHTUSERDATA && type != LUA_TNIL) {
luaL_argerror(L, narg, "expected light userdata");
}}
auto p = lua_touserdata(L, narg);
if (require && !p) {
luaL_argerror(L, narg, "value must be non-null");
}
return p;
}
/// Get an argument from the stack as light userdata (typed).
///
/// This is an unchecked cast.
template<class T>
inline T* get_lightuserdata_typed(lua_State* L, signed narg, bool require = true) {
return static_cast<T*>(get_lightuserdata(L, narg, require));
}
/** @} */ // end of doc-group lib_core_lua
} // namespace lua
} // namespace togo
<commit_msg>lib/core/lua: added get_pointer<T>().<commit_after>#line 2 "togo/core/lua/lua.hpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
@file
@brief Scripting interface.
@ingroup lib_core_lua
*/
#pragma once
#include <togo/core/config.hpp>
#include <togo/core/types.hpp>
#include <togo/core/error/assert.hpp>
#include <togo/core/utility/traits.hpp>
#include <togo/core/utility/utility.hpp>
#include <togo/core/memory/types.hpp>
#include <togo/core/string/string.hpp>
#include <togo/core/lua/types.hpp>
extern "C" {
#include <luajit-2.0/lua.h>
#include <luajit-2.0/lauxlib.h>
#include <luajit-2.0/lualib.h>
}
#include <togo/core/lua/lua.gen_interface>
namespace togo {
namespace lua {
/**
@addtogroup lib_core_lua
@{
*/
/// Push nil to the stack.
inline void push_value(lua_State* L, null_tag const) {
lua_pushnil(L);
}
/// Push an integral value to the stack.
template<class T>
inline enable_if<is_integral<T>::value, void> push_value(lua_State* L, T value) {
lua_pushinteger(L, value);
}
/// Get an argument from the stack as an integer.
inline LuaInt get_integer(lua_State* L, signed narg) {
return luaL_checkinteger(L, narg);
}
/// Push a floating-point value to the stack.
template<class T>
inline enable_if<is_floating_point<T>::value, void> push_value(lua_State* L, T value) {
lua_pushinteger(L, value);
}
/// Get an argument from the stack as an integer.
inline LuaFloat get_float(lua_State* L, signed narg) {
return luaL_checknumber(L, narg);
}
// NB: Using template to avoid implicit cast from pointers and integrals.
/// Push a bool to the stack.
template<class T>
inline enable_if<is_same<T, bool>::value, void> push_value(lua_State* L, T value) {
lua_pushboolean(L, value);
}
/// Get an argument from the stack as a boolean.
inline bool get_boolean(lua_State* L, signed narg) {
luaL_checktype(L, narg, LUA_TBOOLEAN);
return lua_toboolean(L, narg);
}
/// Push a string to the stack.
inline void push_value(lua_State* L, StringRef str) {
lua_pushlstring(L, str.data ? str.data : "", unsigned_cast(str.size));
}
/// Get a string from the stack as a string reference.
inline StringRef get_string(lua_State* L, signed narg) {
size_t size = 0;
auto data = luaL_checklstring(L, narg, &size);
return {data, static_cast<unsigned>(size)};
}
/// Push a C function to the stack.
inline void push_value(lua_State* L, LuaCFunction value) {
lua_pushcfunction(L, value);
}
/// Get a C function from the stack.
inline LuaCFunction* get_cfunction(lua_State* L, signed narg) {
luaL_checktype(L, narg, LUA_TFUNCTION);
return lua_tocfunction(L, narg);
}
/// Set table[name] = value (with settable).
template<class T>
inline void table_set(lua_State* L, signed table, StringRef name, T value) {
lua::push_value(L, name);
lua::push_value(L, value);
lua_settable(L, table);
}
/// Set top_of_stack[name] = value (with settable).
template<class T>
inline void table_set(lua_State* L, StringRef name, T value) {
lua::table_set(L, -3, name, value);
}
/// Set table[name] = value (with rawset).
template<class T>
inline void table_set_raw(lua_State* L, signed table, StringRef name, T value) {
lua::push_value(L, name);
lua::push_value(L, value);
lua_rawset(L, table);
}
/// Set top_of_stack[name] = value (with rawset).
template<class T>
inline void table_set_raw(lua_State* L, StringRef name, T value) {
lua::table_set_raw(L, -3, name, value);
}
/// Fetch the value of table[name] and push it on the stack (with gettable).
inline void table_get(lua_State* L, signed table, StringRef name) {
lua::push_value(L, name);
lua_gettable(L, table);
}
/// Fetch the value of top_of_stack[name] and push it on the stack (with gettable).
inline void table_get(lua_State* L, StringRef name) {
lua::table_get(L, -2, name);
}
/// Fetch the value of table[name] and push it on the stack (with rawget).
inline void table_get_raw(lua_State* L, signed table, StringRef name) {
lua::push_value(L, name);
lua_rawget(L, table);
}
/// Fetch the value of top_of_stack[name] and push it on the stack (with rawget).
inline void table_get_raw(lua_State* L, StringRef name) {
lua::table_get_raw(L, -2, name);
}
/// Set table[index] = value (with settable).
template<class T>
inline void table_set_index(lua_State* L, signed table, signed index, T value) {
lua::push_value(L, index);
lua::push_value(L, value);
lua_settable(L, table);
}
/// Set top_of_stack[index] = value (with settable).
template<class T>
inline void table_set_index(lua_State* L, signed index, T value) {
lua::table_set_index(L, -3, index, value);
}
/// Set table[index] = value (with rawset).
template<class T>
inline void table_set_index_raw(lua_State* L, signed table, signed index, T value) {
lua::push_value(L, value);
lua_rawseti(L, table, index);
}
/// Set top_of_stack[index] = value (with rawset).
template<class T>
inline void table_set_index_raw(lua_State* L, signed index, T value) {
lua::table_set_index_raw(L, -2, index, value);
}
/// Fetch the value of table[index] and push it on the stack (with rawget).
inline void table_get_index(lua_State* L, signed table, signed index) {
lua::push_value(L, index);
lua_gettable(L, table);
}
/// Fetch the value of top_of_stack[index] and push it on the stack (with rawget).
inline void table_get_index(lua_State* L, signed index) {
lua::table_get_index(L, -2, index);
}
/// Fetch the value of table[index] and push it on the stack (with rawget).
inline void table_get_index_raw(lua_State* L, signed table, signed index) {
lua_rawgeti(L, table, index);
}
/// Fetch the value of top_of_stack[index] and push it on the stack (with rawget).
inline void table_get_index_raw(lua_State* L, signed index) {
lua::table_get_index_raw(L, -1, index);
}
/// Set table[name] = stack[value] (with settable).
inline void table_set_copy(lua_State* L, signed table, StringRef name, signed value) {
lua::push_value(L, name);
lua_pushvalue(L, value - 1);
lua_settable(L, table);
}
/// Set top_of_stack[name] = stack[value] (with settable).
inline void table_set_copy(lua_State* L, StringRef name, signed value) {
lua::table_set_copy(L, -3, name, value);
}
/// Set table[name] = stack[value] (with rawset).
inline void table_set_copy_raw(lua_State* L, signed table, StringRef name, signed value) {
lua::push_value(L, name);
lua_pushvalue(L, value - 1);
lua_rawset(L, table);
}
/// Set top_of_stack[name] = stack[value] (with rawset).
inline void table_set_copy_raw(lua_State* L, StringRef name, signed value) {
lua::table_set_copy_raw(L, -3, name, value);
}
/// Set table[index] = stack[value] (with settable).
inline void table_set_copy_index(lua_State* L, signed table, signed index, signed value) {
lua::push_value(L, index);
lua_pushvalue(L, value - 1);
lua_settable(L, table);
}
/// Set top_of_stack[index] = stack[value] (with settable).
inline void table_set_copy_index(lua_State* L, signed index, signed value) {
lua::table_set_copy_index(L, -3, index, value);
}
/// Set table[index] = stack[value] (with rawset).
inline void table_set_copy_index_raw(lua_State* L, signed table, signed index, signed value) {
lua_pushvalue(L, value);
lua_rawseti(L, table, index);
}
/// Set top_of_stack[index] = stack[value] (with rawset).
inline void table_set_copy_index_raw(lua_State* L, signed index, signed value) {
lua::table_set_copy_index_raw(L, -2, index, value);
}
template<class T>
inline void register_userdata(lua_State* L, LuaCFunction destroy, bool keep_metatable = false) {
lua::table_get_raw(L, LUA_REGISTRYINDEX, "togo_class");
TOGO_ASSERT(!lua_isnil(L, -1), "core was not registered");
lua::table_get_raw(L, T::lua_metatable_name);
TOGO_ASSERT(lua_isnil(L, -1), "class metatable was already registered");
lua_pop(L, 1);
lua_createtable(L, 0, 1);
lua::table_set_copy_raw(L, "__index", -1);
lua::table_set_raw(L, "__gc", destroy);
// togo_class[T::lua_metatable_name] = metatable
lua::table_set_copy_raw(L, -4, T::lua_metatable_name, -1);
lua_remove(L, -2); // togo_class
if (!keep_metatable) {
lua_pop(L, 1);
}
}
/// Push a new userdata to the stack and setup its metatable.
template<class T, class... P>
inline T* new_userdata(lua_State* L, P&&... p) {
auto* ptr = lua_newuserdata(L, sizeof(T));
TOGO_DEBUG_ASSERTE(ptr);
lua::table_get_raw(L, LUA_REGISTRYINDEX, "togo_class");
TOGO_ASSERT(!lua_isnil(L, -1), "core was not registered");
lua::table_get_raw(L, T::lua_metatable_name);
TOGO_ASSERT(!lua_isnil(L, -1), "class metatable was not registered");
lua_setmetatable(L, -3);
lua_pop(L, 1);
return new(ptr) T(p...);
}
/// Get an argument from the stack as userdata (typed).
template<class T>
inline T* get_userdata(lua_State* L, signed narg, bool require = true) {
{auto type = lua_type(L, narg);
if (type != LUA_TUSERDATA && type != LUA_TNIL) {
luaL_argerror(L, narg, "expected userdata");
}}
auto p = lua_touserdata(L, narg);
if (require && !p) {
luaL_argerror(L, narg, "value must be non-null");
} else {
if (!lua_getmetatable(L, narg)) {
luaL_argerror(L, narg, "expected a metatable for userdata, but it has none");
}
lua::table_get_raw(L, LUA_REGISTRYINDEX, "togo_class");
TOGO_ASSERT(!lua_isnil(L, -1), "core was not registered");
lua::table_get_raw(L, T::lua_metatable_name);
TOGO_ASSERT(!lua_isnil(L, -1), "class metatable was not registered");
if (!lua_rawequal(L, -1, -3)) {
luaL_argerror(L, narg, "userdata metatable does not match the expected one");
}
lua_pop(L, 3);
}
return static_cast<T*>(p);
}
/// Push a light userdata to the stack or nil if the pointer is null.
inline void push_lightuserdata(lua_State* L, void* p) {
if (p) {
lua_pushlightuserdata(L, p);
} else {
lua_pushnil(L);
}
}
/// Get an argument from the stack as light userdata.
inline void* get_lightuserdata(lua_State* L, signed narg, bool require = true) {
{auto type = lua_type(L, narg);
if (type != LUA_TLIGHTUSERDATA && type != LUA_TNIL) {
luaL_argerror(L, narg, "expected light userdata");
}}
auto p = lua_touserdata(L, narg);
if (require && !p) {
luaL_argerror(L, narg, "value must be non-null");
}
return p;
}
/// Get an argument from the stack as light userdata (typed).
///
/// This is an unchecked cast.
template<class T>
inline T* get_lightuserdata_typed(lua_State* L, signed narg, bool require = true) {
return static_cast<T*>(get_lightuserdata(L, narg, require));
}
/// Get an argument from the stack as userdata or light userdata (typed).
///
/// This is an unchecked cast for light userdata.
template<class T>
inline T* get_pointer(lua_State* L, signed narg, bool require = true) {
if (lua_type(L, narg) == LUA_TUSERDATA) {
return get_userdata<T>(L, narg, require);
} else {
return get_lightuserdata_typed<T>(L, narg, require);
}
}
/** @} */ // end of doc-group lib_core_lua
} // namespace lua
} // namespace togo
<|endoftext|>
|
<commit_before>
#include <util/ScopeUtils.h>
#include <util/StringUtil.h>
#include <gtest/gtest.h>
using namespace aeron::common::util;
TEST(utilTests, scopeTest)
{
bool flag = false;
if (1)
{
OnScopeExit onExit ([&]()
{
flag = true;
});
ASSERT_EQ(flag, false);
}
ASSERT_EQ(flag, true);
}
TEST(utilTests, stringUtilTrimTest)
{
std::string test = " test ";
ASSERT_EQ(trimWSLeft(test), "test ");
ASSERT_EQ(trimWSRight(test), " test");
ASSERT_EQ(trimWSBoth(test), "test");
}
TEST(utilTests, stringUtilParseTest)
{
ASSERT_NO_THROW({
ASSERT_EQ(parse<int> ("100"), 100);
ASSERT_EQ(parse<double> ("100.25"), 100.25);
ASSERT_EQ(parse<std::uint64_t> ("0x123456789abcdef0"), 0x123456789abcdef0);
});
ASSERT_THROW(parse<int>(""), ParseException);
ASSERT_THROW(parse<int>(" "), ParseException);
ASSERT_THROW(parse<int>("xxx"), ParseException);
ASSERT_THROW(parse<int>("84473.3443"), ParseException);
}
TEST(utilTests, stringUtiltoStringTest)
{
ASSERT_EQ(toString(100), "100");
ASSERT_EQ(toString(1.25), "1.25");
ASSERT_EQ(toString("hello"), "hello");
}
TEST(utilTests, stringUtilstrPrintfTest)
{
std::string val = strPrintf("%s %s", "hello", "world");
ASSERT_EQ(val, "hello world");
}
<commit_msg>[C++] added missing header, which was stopping the windows build<commit_after>
#include <cstdint>
#include <util/ScopeUtils.h>
#include <util/StringUtil.h>
#include <gtest/gtest.h>
using namespace aeron::common::util;
TEST(utilTests, scopeTest)
{
bool flag = false;
if (1)
{
OnScopeExit onExit ([&]()
{
flag = true;
});
ASSERT_EQ(flag, false);
}
ASSERT_EQ(flag, true);
}
TEST(utilTests, stringUtilTrimTest)
{
std::string test = " test ";
ASSERT_EQ(trimWSLeft(test), "test ");
ASSERT_EQ(trimWSRight(test), " test");
ASSERT_EQ(trimWSBoth(test), "test");
}
TEST(utilTests, stringUtilParseTest)
{
ASSERT_NO_THROW({
ASSERT_EQ(parse<int> ("100"), 100);
ASSERT_EQ(parse<double> ("100.25"), 100.25);
ASSERT_EQ(parse<std::uint64_t> ("0x123456789abcdef0"), 0x123456789abcdef0);
});
ASSERT_THROW(parse<int>(""), ParseException);
ASSERT_THROW(parse<int>(" "), ParseException);
ASSERT_THROW(parse<int>("xxx"), ParseException);
ASSERT_THROW(parse<int>("84473.3443"), ParseException);
}
TEST(utilTests, stringUtiltoStringTest)
{
ASSERT_EQ(toString(100), "100");
ASSERT_EQ(toString(1.25), "1.25");
ASSERT_EQ(toString("hello"), "hello");
}
TEST(utilTests, stringUtilstrPrintfTest)
{
std::string val = strPrintf("%s %s", "hello", "world");
ASSERT_EQ(val, "hello world");
}
<|endoftext|>
|
<commit_before>/*
* istream implementation which reads a file from a NFS server.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "istream_nfs.hxx"
#include "istream/istream_internal.hxx"
#include "istream/istream_buffer.hxx"
#include "nfs_client.hxx"
#include "pool.hxx"
#include "util/Cast.hxx"
#include "util/ForeignFifoBuffer.hxx"
#include <assert.h>
#include <string.h>
static const size_t NFS_BUFFER_SIZE = 32768;
struct NfsIstream {
struct istream base;
struct nfs_file_handle *handle;
/**
* The offset of the next "pread" call on the NFS server.
*/
uint64_t offset;
/**
* The number of bytes that are remaining on the NFS server, not
* including the amount of data that is already pending.
*/
uint64_t remaining;
/**
* The number of bytes currently scheduled by nfs_pread_async().
*/
size_t pending_read = 0;
/**
* The number of bytes that shall be discarded from the
* nfs_pread_async() result. This is non-zero if istream_skip()
* has been called while a read call was pending.
*/
size_t discard_read = 0;
ForeignFifoBuffer<uint8_t> buffer;
NfsIstream():buffer(nullptr) {}
void ScheduleRead();
/**
* Check for end-of-file, and if there's more data to read, schedule
* another read call.
*
* The input buffer must be empty.
*/
void ScheduleReadOrEof();
void Feed(const void *data, size_t length);
void ReadFromBuffer();
};
void
NfsIstream::ScheduleReadOrEof()
{
assert(buffer.IsEmpty());
if (pending_read > 0)
return;
if (remaining > 0) {
/* read more */
ScheduleRead();
} else {
/* end of file */
nfs_client_close_file(handle);
istream_deinit_eof(&base);
}
}
inline void
NfsIstream::Feed(const void *data, size_t length)
{
assert(length > 0);
if (buffer.IsNull()) {
const uint64_t total_size = remaining + length;
const size_t buffer_size = total_size > NFS_BUFFER_SIZE
? NFS_BUFFER_SIZE
: (size_t)total_size;
buffer.SetBuffer(PoolAlloc<uint8_t>(*base.pool, buffer_size),
buffer_size);
}
auto w = buffer.Write();
assert(w.size >= length);
memcpy(w.data, data, length);
buffer.Append(length);
}
void
NfsIstream::ReadFromBuffer()
{
assert(buffer.IsDefined());
size_t remaining = istream_buffer_consume(&base, buffer);
if (remaining == 0 && pending_read == 0)
ScheduleReadOrEof();
}
/*
* nfs_client handler
*
*/
static void
istream_nfs_read_data(const void *data, size_t _length, void *ctx)
{
auto *n = (NfsIstream *)ctx;
assert(n->pending_read > 0);
assert(n->discard_read <= n->pending_read);
assert(_length <= n->pending_read);
if (_length < n->pending_read) {
nfs_client_close_file(n->handle);
GError *error = g_error_new_literal(g_file_error_quark(), 0,
"premature end of file");
istream_deinit_abort(&n->base, error);
return;
}
const size_t discard = n->discard_read;
const size_t length = n->pending_read - discard;
n->pending_read = 0;
n->discard_read = 0;
if (length > 0)
n->Feed((const char *)data + discard, length);
n->ReadFromBuffer();
}
static void
istream_nfs_read_error(GError *error, void *ctx)
{
auto *n = (NfsIstream *)ctx;
assert(n->pending_read > 0);
nfs_client_close_file(n->handle);
istream_deinit_abort(&n->base, error);
}
const struct nfs_client_read_file_handler istream_nfs_read_handler = {
istream_nfs_read_data,
istream_nfs_read_error,
};
inline void
NfsIstream::ScheduleRead()
{
assert(pending_read == 0);
const size_t max = buffer.IsDefined()
? buffer.Write().size
: NFS_BUFFER_SIZE;
size_t nbytes = remaining > max
? max
: (size_t)remaining;
const uint64_t read_offset = offset;
offset += nbytes;
remaining -= nbytes;
pending_read = nbytes;
nfs_client_read_file(handle, read_offset, nbytes,
&istream_nfs_read_handler, this);
}
/*
* istream implementation
*
*/
static inline NfsIstream *
istream_to_nfs(struct istream *istream)
{
return &ContainerCast2(*istream, &NfsIstream::base);
}
static off_t
istream_nfs_available(struct istream *istream, bool partial gcc_unused)
{
NfsIstream *n = istream_to_nfs(istream);
return n->remaining + n->pending_read - n->discard_read +
n->buffer.GetAvailable();
}
static off_t
istream_nfs_skip(struct istream *istream, off_t _length)
{
NfsIstream *n = istream_to_nfs(istream);
assert(n->discard_read <= n->pending_read);
uint64_t length = _length;
uint64_t result = 0;
if (n->buffer.IsDefined()) {
const uint64_t buffer_available = n->buffer.GetAvailable();
const uint64_t consume = length < buffer_available
? length
: buffer_available;
n->buffer.Consume(consume);
result += consume;
length -= consume;
}
const uint64_t pending_available =
n->pending_read - n->discard_read;
uint64_t consume = length < pending_available
? length
: pending_available;
n->discard_read += consume;
result += consume;
length -= consume;
if (length > n->remaining)
length = n->remaining;
n->remaining -= length;
n->offset += length;
result += length;
return result;
}
static void
istream_nfs_read(struct istream *istream)
{
NfsIstream *n = istream_to_nfs(istream);
if (!n->buffer.IsEmpty())
n->ReadFromBuffer();
else
n->ScheduleReadOrEof();
}
static void
istream_nfs_close(struct istream *istream)
{
NfsIstream *const n = istream_to_nfs(istream);
nfs_client_close_file(n->handle);
istream_deinit(&n->base);
}
static const struct istream_class istream_nfs = {
istream_nfs_available,
istream_nfs_skip,
istream_nfs_read,
nullptr,
istream_nfs_close,
};
/*
* constructor
*
*/
struct istream *
istream_nfs_new(struct pool *pool, struct nfs_file_handle *handle,
uint64_t start, uint64_t end)
{
assert(pool != nullptr);
assert(handle != nullptr);
assert(start <= end);
auto *n = NewFromPool<NfsIstream>(*pool);
istream_init(&n->base, &istream_nfs, pool);
n->handle = handle;
n->offset = start;
n->remaining = end - start;
return &n->base;
}
<commit_msg>istream_nfs: use the OO API<commit_after>/*
* istream implementation which reads a file from a NFS server.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "istream_nfs.hxx"
#include "istream/istream_oo.hxx"
#include "nfs_client.hxx"
#include "pool.hxx"
#include "util/Cast.hxx"
#include "util/ForeignFifoBuffer.hxx"
#include <assert.h>
#include <string.h>
static const size_t NFS_BUFFER_SIZE = 32768;
struct NfsIstream final : Istream {
struct nfs_file_handle *handle;
/**
* The offset of the next "pread" call on the NFS server.
*/
uint64_t offset;
/**
* The number of bytes that are remaining on the NFS server, not
* including the amount of data that is already pending.
*/
uint64_t remaining;
/**
* The number of bytes currently scheduled by nfs_pread_async().
*/
size_t pending_read = 0;
/**
* The number of bytes that shall be discarded from the
* nfs_pread_async() result. This is non-zero if istream_skip()
* has been called while a read call was pending.
*/
size_t discard_read = 0;
ForeignFifoBuffer<uint8_t> buffer;
explicit NfsIstream(struct pool &p):Istream(p), buffer(nullptr) {}
using Istream::DestroyError;
void ScheduleRead();
/**
* Check for end-of-file, and if there's more data to read, schedule
* another read call.
*
* The input buffer must be empty.
*/
void ScheduleReadOrEof();
void Feed(const void *data, size_t length);
void ReadFromBuffer();
/* virtual methods from class Istream */
off_t GetAvailable(gcc_unused bool partial) override {
return remaining + pending_read - discard_read +
buffer.GetAvailable();
}
off_t Skip(off_t length) override;
void Read() override {
if (!buffer.IsEmpty())
ReadFromBuffer();
else
ScheduleReadOrEof();
}
void Close() {
nfs_client_close_file(handle);
Istream::Close();
}
};
void
NfsIstream::ScheduleReadOrEof()
{
assert(buffer.IsEmpty());
if (pending_read > 0)
return;
if (remaining > 0) {
/* read more */
ScheduleRead();
} else {
/* end of file */
nfs_client_close_file(handle);
DestroyEof();
}
}
inline void
NfsIstream::Feed(const void *data, size_t length)
{
assert(length > 0);
if (buffer.IsNull()) {
const uint64_t total_size = remaining + length;
const size_t buffer_size = total_size > NFS_BUFFER_SIZE
? NFS_BUFFER_SIZE
: (size_t)total_size;
buffer.SetBuffer(PoolAlloc<uint8_t>(GetPool(), buffer_size),
buffer_size);
}
auto w = buffer.Write();
assert(w.size >= length);
memcpy(w.data, data, length);
buffer.Append(length);
}
void
NfsIstream::ReadFromBuffer()
{
assert(buffer.IsDefined());
size_t buffer_remaining = ConsumeFromBuffer(buffer);
if (buffer_remaining == 0 && pending_read == 0)
ScheduleReadOrEof();
}
/*
* nfs_client handler
*
*/
static void
istream_nfs_read_data(const void *data, size_t _length, void *ctx)
{
auto *n = (NfsIstream *)ctx;
assert(n->pending_read > 0);
assert(n->discard_read <= n->pending_read);
assert(_length <= n->pending_read);
if (_length < n->pending_read) {
nfs_client_close_file(n->handle);
GError *error = g_error_new_literal(g_file_error_quark(), 0,
"premature end of file");
n->DestroyError(error);
return;
}
const size_t discard = n->discard_read;
const size_t length = n->pending_read - discard;
n->pending_read = 0;
n->discard_read = 0;
if (length > 0)
n->Feed((const char *)data + discard, length);
n->ReadFromBuffer();
}
static void
istream_nfs_read_error(GError *error, void *ctx)
{
auto *n = (NfsIstream *)ctx;
assert(n->pending_read > 0);
nfs_client_close_file(n->handle);
n->DestroyError(error);
}
const struct nfs_client_read_file_handler istream_nfs_read_handler = {
istream_nfs_read_data,
istream_nfs_read_error,
};
inline void
NfsIstream::ScheduleRead()
{
assert(pending_read == 0);
const size_t max = buffer.IsDefined()
? buffer.Write().size
: NFS_BUFFER_SIZE;
size_t nbytes = remaining > max
? max
: (size_t)remaining;
const uint64_t read_offset = offset;
offset += nbytes;
remaining -= nbytes;
pending_read = nbytes;
nfs_client_read_file(handle, read_offset, nbytes,
&istream_nfs_read_handler, this);
}
/*
* istream implementation
*
*/
off_t
NfsIstream::Skip(off_t _length)
{
assert(discard_read <= pending_read);
uint64_t length = _length;
uint64_t result = 0;
if (buffer.IsDefined()) {
const uint64_t buffer_available = buffer.GetAvailable();
const uint64_t consume = length < buffer_available
? length
: buffer_available;
buffer.Consume(consume);
result += consume;
length -= consume;
}
const uint64_t pending_available =
pending_read - discard_read;
uint64_t consume = length < pending_available
? length
: pending_available;
discard_read += consume;
result += consume;
length -= consume;
if (length > remaining)
length = remaining;
remaining -= length;
offset += length;
result += length;
return result;
}
/*
* constructor
*
*/
struct istream *
istream_nfs_new(struct pool *pool, struct nfs_file_handle *handle,
uint64_t start, uint64_t end)
{
assert(pool != nullptr);
assert(handle != nullptr);
assert(start <= end);
auto *n = NewFromPool<NfsIstream>(*pool, *pool);
n->handle = handle;
n->offset = start;
n->remaining = end - start;
return n->Cast();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 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/bookmarks/bookmark_context_menu_controller.h"
#include "base/compiler_specific.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/bookmarks/bookmark_editor.h"
#include "chrome/browser/bookmarks/bookmark_folder_editor_controller.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/bookmarks/bookmark_utils.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/metrics/user_metrics.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/page_navigator.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/pref_names.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
BookmarkContextMenuController::BookmarkContextMenuController(
gfx::NativeWindow parent_window,
BookmarkContextMenuControllerDelegate* delegate,
Profile* profile,
PageNavigator* navigator,
const BookmarkNode* parent,
const std::vector<const BookmarkNode*>& selection)
: parent_window_(parent_window),
delegate_(delegate),
profile_(profile),
navigator_(navigator),
parent_(parent),
selection_(selection),
model_(profile->GetBookmarkModel()) {
DCHECK(profile_);
DCHECK(model_->IsLoaded());
menu_model_.reset(new ui::SimpleMenuModel(this));
model_->AddObserver(this);
BuildMenu();
}
BookmarkContextMenuController::~BookmarkContextMenuController() {
if (model_)
model_->RemoveObserver(this);
}
void BookmarkContextMenuController::BuildMenu() {
if (selection_.size() == 1 && selection_[0]->is_url()) {
AddItem(IDC_BOOKMARK_BAR_OPEN_ALL,
IDS_BOOMARK_BAR_OPEN_IN_NEW_TAB);
AddItem(IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW,
IDS_BOOMARK_BAR_OPEN_IN_NEW_WINDOW);
AddItem(IDC_BOOKMARK_BAR_OPEN_ALL_INCOGNITO,
IDS_BOOMARK_BAR_OPEN_INCOGNITO);
} else {
AddItem(IDC_BOOKMARK_BAR_OPEN_ALL, IDS_BOOMARK_BAR_OPEN_ALL);
AddItem(IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW,
IDS_BOOMARK_BAR_OPEN_ALL_NEW_WINDOW);
AddItem(IDC_BOOKMARK_BAR_OPEN_ALL_INCOGNITO,
IDS_BOOMARK_BAR_OPEN_ALL_INCOGNITO);
}
AddSeparator();
if (selection_.size() == 1 && selection_[0]->is_folder()) {
AddItem(IDC_BOOKMARK_BAR_RENAME_FOLDER, IDS_BOOKMARK_BAR_RENAME_FOLDER);
} else {
AddItem(IDC_BOOKMARK_BAR_EDIT, IDS_BOOKMARK_BAR_EDIT);
}
AddSeparator();
AddItem(IDC_CUT, IDS_CUT);
AddItem(IDC_COPY, IDS_COPY);
AddItem(IDC_PASTE, IDS_PASTE);
AddSeparator();
AddItem(IDC_BOOKMARK_BAR_REMOVE, IDS_BOOKMARK_BAR_REMOVE);
AddSeparator();
AddItem(IDC_BOOKMARK_BAR_ADD_NEW_BOOKMARK, IDS_BOOMARK_BAR_ADD_NEW_BOOKMARK);
AddItem(IDC_BOOKMARK_BAR_NEW_FOLDER, IDS_BOOMARK_BAR_NEW_FOLDER);
AddSeparator();
AddItem(IDC_BOOKMARK_MANAGER, IDS_BOOKMARK_MANAGER);
AddCheckboxItem(IDC_BOOKMARK_BAR_ALWAYS_SHOW, IDS_BOOMARK_BAR_ALWAYS_SHOW);
}
void BookmarkContextMenuController::AddItem(int id, int localization_id) {
menu_model_->AddItemWithStringId(id, localization_id);
}
void BookmarkContextMenuController::AddSeparator() {
menu_model_->AddSeparator();
}
void BookmarkContextMenuController::AddCheckboxItem(int id,
int localization_id) {
menu_model_->AddCheckItemWithStringId(id, localization_id);
}
void BookmarkContextMenuController::ExecuteCommand(int id) {
if (delegate_)
delegate_->WillExecuteCommand();
switch (id) {
case IDC_BOOKMARK_BAR_OPEN_ALL:
case IDC_BOOKMARK_BAR_OPEN_ALL_INCOGNITO:
case IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW: {
WindowOpenDisposition initial_disposition;
if (id == IDC_BOOKMARK_BAR_OPEN_ALL) {
initial_disposition = NEW_FOREGROUND_TAB;
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_OpenAll"),
profile_);
} else if (id == IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW) {
initial_disposition = NEW_WINDOW;
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_OpenAllInNewWindow"),
profile_);
} else {
initial_disposition = OFF_THE_RECORD;
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_OpenAllIncognito"),
profile_);
}
bookmark_utils::OpenAll(parent_window_, profile_, navigator_, selection_,
initial_disposition);
break;
}
case IDC_BOOKMARK_BAR_RENAME_FOLDER:
case IDC_BOOKMARK_BAR_EDIT:
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_Edit"),
profile_);
if (selection_.size() != 1) {
NOTREACHED();
break;
}
if (selection_[0]->is_url()) {
BookmarkEditor::Show(parent_window_, profile_, parent_,
BookmarkEditor::EditDetails(selection_[0]),
BookmarkEditor::SHOW_TREE);
} else {
BookmarkFolderEditorController::Show(profile_, parent_window_,
selection_[0], -1,
BookmarkFolderEditorController::EXISTING_BOOKMARK);
}
break;
case IDC_BOOKMARK_BAR_REMOVE: {
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_Remove"),
profile_);
for (size_t i = 0; i < selection_.size(); ++i) {
model_->Remove(selection_[i]->GetParent(),
selection_[i]->GetParent()->IndexOfChild(selection_[i]));
}
selection_.clear();
break;
}
case IDC_BOOKMARK_BAR_ADD_NEW_BOOKMARK: {
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_Add"),
profile_);
// TODO: this should honor the index from GetParentForNewNodes.
BookmarkEditor::Show(
parent_window_, profile_,
bookmark_utils::GetParentForNewNodes(parent_, selection_, NULL),
BookmarkEditor::EditDetails(), BookmarkEditor::SHOW_TREE);
break;
}
case IDC_BOOKMARK_BAR_NEW_FOLDER: {
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_NewFolder"),
profile_);
int index;
const BookmarkNode* parent =
bookmark_utils::GetParentForNewNodes(parent_, selection_, &index);
BookmarkFolderEditorController::Show(profile_, parent_window_, parent,
index, BookmarkFolderEditorController::NEW_BOOKMARK);
break;
}
case IDC_BOOKMARK_BAR_ALWAYS_SHOW:
bookmark_utils::ToggleWhenVisible(profile_);
break;
case IDC_BOOKMARK_MANAGER:
UserMetrics::RecordAction(UserMetricsAction("ShowBookmarkManager"),
profile_);
{
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
if (browser)
browser->OpenBookmarkManager();
else
NOTREACHED();
}
break;
case IDC_CUT:
bookmark_utils::CopyToClipboard(model_, selection_, true);
break;
case IDC_COPY:
bookmark_utils::CopyToClipboard(model_, selection_, false);
break;
case IDC_PASTE: {
int index;
const BookmarkNode* paste_target =
bookmark_utils::GetParentForNewNodes(parent_, selection_, &index);
if (!paste_target)
return;
bookmark_utils::PasteFromClipboard(model_, paste_target, index);
break;
}
default:
NOTREACHED();
}
if (delegate_)
delegate_->DidExecuteCommand();
}
bool BookmarkContextMenuController::IsCommandIdChecked(int command_id) const {
DCHECK(command_id == IDC_BOOKMARK_BAR_ALWAYS_SHOW);
return profile_->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar);
}
bool BookmarkContextMenuController::IsCommandIdEnabled(int command_id) const {
bool is_root_node =
(selection_.size() == 1 &&
selection_[0]->GetParent() == model_->root_node());
switch (command_id) {
case IDC_BOOKMARK_BAR_OPEN_INCOGNITO:
return !profile_->IsOffTheRecord();
case IDC_BOOKMARK_BAR_OPEN_ALL_INCOGNITO:
return HasURLs() && !profile_->IsOffTheRecord();
case IDC_BOOKMARK_BAR_OPEN_ALL:
case IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW:
return HasURLs();
case IDC_BOOKMARK_BAR_RENAME_FOLDER:
case IDC_BOOKMARK_BAR_EDIT:
return selection_.size() == 1 && !is_root_node;
case IDC_BOOKMARK_BAR_REMOVE:
return !selection_.empty() && !is_root_node;
case IDC_BOOKMARK_BAR_NEW_FOLDER:
case IDC_BOOKMARK_BAR_ADD_NEW_BOOKMARK:
return bookmark_utils::GetParentForNewNodes(
parent_, selection_, NULL) != NULL;
case IDC_COPY:
case IDC_CUT:
return selection_.size() > 0 && !is_root_node;
case IDC_PASTE:
// Paste to selection from the Bookmark Bar, to parent_ everywhere else
return (!selection_.empty() &&
bookmark_utils::CanPasteFromClipboard(selection_[0])) ||
bookmark_utils::CanPasteFromClipboard(parent_);
}
return true;
}
bool BookmarkContextMenuController::GetAcceleratorForCommandId(
int command_id,
ui::Accelerator* accelerator) {
return false;
}
void BookmarkContextMenuController::BookmarkModelChanged() {
if (delegate_)
delegate_->CloseMenu();
}
bool BookmarkContextMenuController::HasURLs() const {
for (size_t i = 0; i < selection_.size(); ++i) {
if (bookmark_utils::NodeHasURLs(selection_[i]))
return true;
}
return false;
}
<commit_msg>GTK uses a different controller for the bookmark bar view context menu than toolkit_views and this adds the same check for incognito pref that I added for views.<commit_after>// Copyright (c) 2011 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/bookmarks/bookmark_context_menu_controller.h"
#include "base/compiler_specific.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/bookmarks/bookmark_editor.h"
#include "chrome/browser/bookmarks/bookmark_folder_editor_controller.h"
#include "chrome/browser/bookmarks/bookmark_model.h"
#include "chrome/browser/bookmarks/bookmark_utils.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/metrics/user_metrics.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/page_navigator.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/pref_names.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
BookmarkContextMenuController::BookmarkContextMenuController(
gfx::NativeWindow parent_window,
BookmarkContextMenuControllerDelegate* delegate,
Profile* profile,
PageNavigator* navigator,
const BookmarkNode* parent,
const std::vector<const BookmarkNode*>& selection)
: parent_window_(parent_window),
delegate_(delegate),
profile_(profile),
navigator_(navigator),
parent_(parent),
selection_(selection),
model_(profile->GetBookmarkModel()) {
DCHECK(profile_);
DCHECK(model_->IsLoaded());
menu_model_.reset(new ui::SimpleMenuModel(this));
model_->AddObserver(this);
BuildMenu();
}
BookmarkContextMenuController::~BookmarkContextMenuController() {
if (model_)
model_->RemoveObserver(this);
}
void BookmarkContextMenuController::BuildMenu() {
if (selection_.size() == 1 && selection_[0]->is_url()) {
AddItem(IDC_BOOKMARK_BAR_OPEN_ALL,
IDS_BOOMARK_BAR_OPEN_IN_NEW_TAB);
AddItem(IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW,
IDS_BOOMARK_BAR_OPEN_IN_NEW_WINDOW);
AddItem(IDC_BOOKMARK_BAR_OPEN_ALL_INCOGNITO,
IDS_BOOMARK_BAR_OPEN_INCOGNITO);
} else {
AddItem(IDC_BOOKMARK_BAR_OPEN_ALL, IDS_BOOMARK_BAR_OPEN_ALL);
AddItem(IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW,
IDS_BOOMARK_BAR_OPEN_ALL_NEW_WINDOW);
AddItem(IDC_BOOKMARK_BAR_OPEN_ALL_INCOGNITO,
IDS_BOOMARK_BAR_OPEN_ALL_INCOGNITO);
}
AddSeparator();
if (selection_.size() == 1 && selection_[0]->is_folder()) {
AddItem(IDC_BOOKMARK_BAR_RENAME_FOLDER, IDS_BOOKMARK_BAR_RENAME_FOLDER);
} else {
AddItem(IDC_BOOKMARK_BAR_EDIT, IDS_BOOKMARK_BAR_EDIT);
}
AddSeparator();
AddItem(IDC_CUT, IDS_CUT);
AddItem(IDC_COPY, IDS_COPY);
AddItem(IDC_PASTE, IDS_PASTE);
AddSeparator();
AddItem(IDC_BOOKMARK_BAR_REMOVE, IDS_BOOKMARK_BAR_REMOVE);
AddSeparator();
AddItem(IDC_BOOKMARK_BAR_ADD_NEW_BOOKMARK, IDS_BOOMARK_BAR_ADD_NEW_BOOKMARK);
AddItem(IDC_BOOKMARK_BAR_NEW_FOLDER, IDS_BOOMARK_BAR_NEW_FOLDER);
AddSeparator();
AddItem(IDC_BOOKMARK_MANAGER, IDS_BOOKMARK_MANAGER);
AddCheckboxItem(IDC_BOOKMARK_BAR_ALWAYS_SHOW, IDS_BOOMARK_BAR_ALWAYS_SHOW);
}
void BookmarkContextMenuController::AddItem(int id, int localization_id) {
menu_model_->AddItemWithStringId(id, localization_id);
}
void BookmarkContextMenuController::AddSeparator() {
menu_model_->AddSeparator();
}
void BookmarkContextMenuController::AddCheckboxItem(int id,
int localization_id) {
menu_model_->AddCheckItemWithStringId(id, localization_id);
}
void BookmarkContextMenuController::ExecuteCommand(int id) {
if (delegate_)
delegate_->WillExecuteCommand();
switch (id) {
case IDC_BOOKMARK_BAR_OPEN_ALL:
case IDC_BOOKMARK_BAR_OPEN_ALL_INCOGNITO:
case IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW: {
WindowOpenDisposition initial_disposition;
if (id == IDC_BOOKMARK_BAR_OPEN_ALL) {
initial_disposition = NEW_FOREGROUND_TAB;
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_OpenAll"),
profile_);
} else if (id == IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW) {
initial_disposition = NEW_WINDOW;
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_OpenAllInNewWindow"),
profile_);
} else {
initial_disposition = OFF_THE_RECORD;
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_OpenAllIncognito"),
profile_);
}
bookmark_utils::OpenAll(parent_window_, profile_, navigator_, selection_,
initial_disposition);
break;
}
case IDC_BOOKMARK_BAR_RENAME_FOLDER:
case IDC_BOOKMARK_BAR_EDIT:
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_Edit"),
profile_);
if (selection_.size() != 1) {
NOTREACHED();
break;
}
if (selection_[0]->is_url()) {
BookmarkEditor::Show(parent_window_, profile_, parent_,
BookmarkEditor::EditDetails(selection_[0]),
BookmarkEditor::SHOW_TREE);
} else {
BookmarkFolderEditorController::Show(profile_, parent_window_,
selection_[0], -1,
BookmarkFolderEditorController::EXISTING_BOOKMARK);
}
break;
case IDC_BOOKMARK_BAR_REMOVE: {
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_Remove"),
profile_);
for (size_t i = 0; i < selection_.size(); ++i) {
model_->Remove(selection_[i]->GetParent(),
selection_[i]->GetParent()->IndexOfChild(selection_[i]));
}
selection_.clear();
break;
}
case IDC_BOOKMARK_BAR_ADD_NEW_BOOKMARK: {
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_Add"),
profile_);
// TODO: this should honor the index from GetParentForNewNodes.
BookmarkEditor::Show(
parent_window_, profile_,
bookmark_utils::GetParentForNewNodes(parent_, selection_, NULL),
BookmarkEditor::EditDetails(), BookmarkEditor::SHOW_TREE);
break;
}
case IDC_BOOKMARK_BAR_NEW_FOLDER: {
UserMetrics::RecordAction(
UserMetricsAction("BookmarkBar_ContextMenu_NewFolder"),
profile_);
int index;
const BookmarkNode* parent =
bookmark_utils::GetParentForNewNodes(parent_, selection_, &index);
BookmarkFolderEditorController::Show(profile_, parent_window_, parent,
index, BookmarkFolderEditorController::NEW_BOOKMARK);
break;
}
case IDC_BOOKMARK_BAR_ALWAYS_SHOW:
bookmark_utils::ToggleWhenVisible(profile_);
break;
case IDC_BOOKMARK_MANAGER:
UserMetrics::RecordAction(UserMetricsAction("ShowBookmarkManager"),
profile_);
{
Browser* browser = BrowserList::GetLastActiveWithProfile(profile_);
if (browser)
browser->OpenBookmarkManager();
else
NOTREACHED();
}
break;
case IDC_CUT:
bookmark_utils::CopyToClipboard(model_, selection_, true);
break;
case IDC_COPY:
bookmark_utils::CopyToClipboard(model_, selection_, false);
break;
case IDC_PASTE: {
int index;
const BookmarkNode* paste_target =
bookmark_utils::GetParentForNewNodes(parent_, selection_, &index);
if (!paste_target)
return;
bookmark_utils::PasteFromClipboard(model_, paste_target, index);
break;
}
default:
NOTREACHED();
}
if (delegate_)
delegate_->DidExecuteCommand();
}
bool BookmarkContextMenuController::IsCommandIdChecked(int command_id) const {
DCHECK(command_id == IDC_BOOKMARK_BAR_ALWAYS_SHOW);
return profile_->GetPrefs()->GetBoolean(prefs::kShowBookmarkBar);
}
bool BookmarkContextMenuController::IsCommandIdEnabled(int command_id) const {
bool is_root_node =
(selection_.size() == 1 &&
selection_[0]->GetParent() == model_->root_node());
switch (command_id) {
case IDC_BOOKMARK_BAR_OPEN_INCOGNITO:
return !profile_->IsOffTheRecord() &&
profile_->GetPrefs()->GetBoolean(prefs::kIncognitoEnabled);
case IDC_BOOKMARK_BAR_OPEN_ALL_INCOGNITO:
return HasURLs() && !profile_->IsOffTheRecord() &&
profile_->GetPrefs()->GetBoolean(prefs::kIncognitoEnabled);
case IDC_BOOKMARK_BAR_OPEN_ALL:
case IDC_BOOKMARK_BAR_OPEN_ALL_NEW_WINDOW:
return HasURLs();
case IDC_BOOKMARK_BAR_RENAME_FOLDER:
case IDC_BOOKMARK_BAR_EDIT:
return selection_.size() == 1 && !is_root_node;
case IDC_BOOKMARK_BAR_REMOVE:
return !selection_.empty() && !is_root_node;
case IDC_BOOKMARK_BAR_NEW_FOLDER:
case IDC_BOOKMARK_BAR_ADD_NEW_BOOKMARK:
return bookmark_utils::GetParentForNewNodes(
parent_, selection_, NULL) != NULL;
case IDC_COPY:
case IDC_CUT:
return selection_.size() > 0 && !is_root_node;
case IDC_PASTE:
// Paste to selection from the Bookmark Bar, to parent_ everywhere else
return (!selection_.empty() &&
bookmark_utils::CanPasteFromClipboard(selection_[0])) ||
bookmark_utils::CanPasteFromClipboard(parent_);
}
return true;
}
bool BookmarkContextMenuController::GetAcceleratorForCommandId(
int command_id,
ui::Accelerator* accelerator) {
return false;
}
void BookmarkContextMenuController::BookmarkModelChanged() {
if (delegate_)
delegate_->CloseMenu();
}
bool BookmarkContextMenuController::HasURLs() const {
for (size_t i = 0; i < selection_.size(); ++i) {
if (bookmark_utils::NodeHasURLs(selection_[i]))
return true;
}
return false;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/gdata/operation_registry.h"
#include "base/compiler_specific.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop.h"
#include "content/public/test/test_browser_thread.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using testing::ElementsAre;
namespace gdata {
namespace {
class MockOperation : public OperationRegistry::Operation,
public base::SupportsWeakPtr<MockOperation> {
public:
MockOperation(OperationRegistry* registry,
OperationRegistry::OperationType type,
const FilePath& path)
: OperationRegistry::Operation(registry, type, path) {}
MOCK_METHOD0(DoCancel, void());
// Make them public so that they can be called from test cases.
using OperationRegistry::Operation::NotifyStart;
using OperationRegistry::Operation::NotifyProgress;
using OperationRegistry::Operation::NotifyFinish;
};
class MockUploadOperation : public MockOperation {
public:
explicit MockUploadOperation(OperationRegistry* registry)
: MockOperation(registry,
OperationRegistry::OPERATION_UPLOAD,
FilePath("/dummy/upload")) {}
};
class MockDownloadOperation : public MockOperation {
public:
explicit MockDownloadOperation(OperationRegistry* registry)
: MockOperation(registry,
OperationRegistry::OPERATION_DOWNLOAD,
FilePath("/dummy/download")) {}
};
class MockOtherOperation : public MockOperation {
public:
explicit MockOtherOperation(OperationRegistry* registry)
: MockOperation(registry,
OperationRegistry::OPERATION_OTHER,
FilePath("/dummy/other")) {}
};
class TestObserver : public OperationRegistry::Observer {
public:
virtual void OnProgressUpdate(
const std::vector<OperationRegistry::ProgressStatus>& list)
OVERRIDE {
status_ = list;
}
const std::vector<OperationRegistry::ProgressStatus>& status() const {
return status_;
}
private:
std::vector<OperationRegistry::ProgressStatus> status_;
};
class ProgressMatcher
: public ::testing::MatcherInterface<
const OperationRegistry::ProgressStatus&> {
public:
ProgressMatcher(int64 expected_current, int64 expected_total)
: expected_current_(expected_current),
expected_total_(expected_total) {}
virtual bool MatchAndExplain(
const OperationRegistry::ProgressStatus& status,
testing::MatchResultListener* /* listener */) const OVERRIDE {
return status.progress_current == expected_current_ &&
status.progress_total == expected_total_;
}
virtual void DescribeTo(::std::ostream* os) const OVERRIDE {
*os << "current / total equals " << expected_current_ << " / " <<
expected_total_;
}
virtual void DescribeNegationTo(::std::ostream* os) const OVERRIDE {
*os << "current / total does not equal " << expected_current_ << " / " <<
expected_total_;
}
private:
const int64 expected_current_;
const int64 expected_total_;
};
testing::Matcher<const OperationRegistry::ProgressStatus&> Progress(
int64 current, int64 total) {
return testing::MakeMatcher(new ProgressMatcher(current, total));
}
} // namespace
// Pretty-prints ProgressStatus for testing purpose.
std::ostream& operator<<(std::ostream& os,
const OperationRegistry::ProgressStatus& status) {
return os << status.DebugString();
}
class OperationRegistryTest : public testing::Test {
protected:
OperationRegistryTest()
: ui_thread_(content::BrowserThread::UI, &message_loop_) {
}
MessageLoopForUI message_loop_;
content::TestBrowserThread ui_thread_;
};
TEST_F(OperationRegistryTest, OneSuccess) {
TestObserver observer;
OperationRegistry registry;
registry.DisableNotificationFrequencyControlForTest();
registry.AddObserver(&observer);
base::WeakPtr<MockOperation> op1 =
(new MockUploadOperation(®istry))->AsWeakPtr();
EXPECT_CALL(*op1, DoCancel()).Times(0);
EXPECT_EQ(0U, observer.status().size());
op1->NotifyStart();
EXPECT_THAT(observer.status(), ElementsAre(Progress(0, -1)));
op1->NotifyProgress(0, 100);
EXPECT_THAT(observer.status(), ElementsAre(Progress(0, 100)));
op1->NotifyProgress(100, 100);
EXPECT_THAT(observer.status(), ElementsAre(Progress(100, 100)));
op1->NotifyFinish(OperationRegistry::OPERATION_COMPLETED);
// Contains one "COMPLETED" notification.
EXPECT_THAT(observer.status(), ElementsAre(Progress(100, 100)));
// Then it is removed.
EXPECT_EQ(0U, registry.GetProgressStatusList().size());
EXPECT_EQ(NULL, op1.get()); // deleted
}
TEST_F(OperationRegistryTest, OneCancel) {
TestObserver observer;
OperationRegistry registry;
registry.DisableNotificationFrequencyControlForTest();
registry.AddObserver(&observer);
base::WeakPtr<MockOperation> op1 =
(new MockUploadOperation(®istry))->AsWeakPtr();
EXPECT_CALL(*op1, DoCancel());
EXPECT_EQ(0U, observer.status().size());
op1->NotifyStart();
EXPECT_THAT(observer.status(), ElementsAre(Progress(0, -1)));
op1->NotifyProgress(0, 100);
EXPECT_THAT(observer.status(), ElementsAre(Progress(0, 100)));
registry.CancelAll();
EXPECT_THAT(observer.status(), ElementsAre(Progress(0, 100)));
EXPECT_EQ(0U, registry.GetProgressStatusList().size());
EXPECT_EQ(NULL, op1.get()); // deleted
}
TEST_F(OperationRegistryTest, TwoSuccess) {
TestObserver observer;
OperationRegistry registry;
registry.DisableNotificationFrequencyControlForTest();
registry.AddObserver(&observer);
base::WeakPtr<MockOperation> op1 =
(new MockUploadOperation(®istry))->AsWeakPtr();
base::WeakPtr<MockOperation> op2 =
(new MockDownloadOperation(®istry))->AsWeakPtr();
EXPECT_CALL(*op1, DoCancel()).Times(0);
EXPECT_CALL(*op2, DoCancel()).Times(0);
EXPECT_EQ(0U, observer.status().size());
op1->NotifyStart();
op1->NotifyProgress(0, 100);
EXPECT_THAT(observer.status(), ElementsAre(Progress(0, 100)));
op2->NotifyStart();
op2->NotifyProgress(0, 200);
op1->NotifyProgress(50, 100);
EXPECT_THAT(observer.status(), ElementsAre(Progress(50, 100),
Progress(0, 200)));
op1->NotifyFinish(OperationRegistry::OPERATION_COMPLETED);
EXPECT_THAT(observer.status(), ElementsAre(Progress(50, 100),
Progress(0, 200)));
EXPECT_EQ(1U, registry.GetProgressStatusList().size());
op2->NotifyFinish(OperationRegistry::OPERATION_COMPLETED);
EXPECT_THAT(observer.status(), ElementsAre(Progress(0, 200)));
EXPECT_EQ(0U, registry.GetProgressStatusList().size());
EXPECT_EQ(NULL, op1.get()); // deleted
EXPECT_EQ(NULL, op2.get()); // deleted
}
TEST_F(OperationRegistryTest, ThreeCancel) {
TestObserver observer;
OperationRegistry registry;
registry.DisableNotificationFrequencyControlForTest();
registry.AddObserver(&observer);
base::WeakPtr<MockOperation> op1 =
(new MockUploadOperation(®istry))->AsWeakPtr();
base::WeakPtr<MockOperation> op2 =
(new MockDownloadOperation(®istry))->AsWeakPtr();
base::WeakPtr<MockOperation> op3 =
(new MockOtherOperation(®istry))->AsWeakPtr();
EXPECT_CALL(*op1, DoCancel());
EXPECT_CALL(*op2, DoCancel());
EXPECT_CALL(*op3, DoCancel());
EXPECT_EQ(0U, observer.status().size());
op1->NotifyStart();
EXPECT_EQ(1U, observer.status().size());
op2->NotifyStart();
EXPECT_EQ(2U, observer.status().size());
op3->NotifyStart();
EXPECT_EQ(2U, observer.status().size()); // only upload/download is reported.
registry.CancelAll();
EXPECT_EQ(1U, observer.status().size()); // holds the last one "COMPLETED"
EXPECT_EQ(0U, registry.GetProgressStatusList().size());
EXPECT_EQ(NULL, op1.get()); // deleted
EXPECT_EQ(NULL, op2.get()); // deleted
EXPECT_EQ(NULL, op3.get()); // deleted. CancelAll cares all operations.
}
TEST_F(OperationRegistryTest, RestartOperation) {
TestObserver observer;
OperationRegistry registry;
registry.DisableNotificationFrequencyControlForTest();
registry.AddObserver(&observer);
base::WeakPtr<MockOperation> op1 =
(new MockUploadOperation(®istry))->AsWeakPtr();
EXPECT_CALL(*op1, DoCancel()).Times(0);
op1->NotifyStart();
EXPECT_EQ(1U, registry.GetProgressStatusList().size());
op1->NotifyStart(); // restart
EXPECT_EQ(1U, registry.GetProgressStatusList().size());
op1->NotifyProgress(0, 200);
op1->NotifyFinish(OperationRegistry::OPERATION_COMPLETED);
EXPECT_EQ(0U, registry.GetProgressStatusList().size());
EXPECT_EQ(NULL, op1.get()); // deleted
}
} // namespace gdata
<commit_msg>Passing string literals to FilePath constructor causes type conversion errors on Windows trybot. Those literals should be wrapped with FILE_PATH_LITERAL macro.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/gdata/operation_registry.h"
#include "base/compiler_specific.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop.h"
#include "content/public/test/test_browser_thread.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using testing::ElementsAre;
namespace gdata {
namespace {
class MockOperation : public OperationRegistry::Operation,
public base::SupportsWeakPtr<MockOperation> {
public:
MockOperation(OperationRegistry* registry,
OperationRegistry::OperationType type,
const FilePath& path)
: OperationRegistry::Operation(registry, type, path) {}
MOCK_METHOD0(DoCancel, void());
// Make them public so that they can be called from test cases.
using OperationRegistry::Operation::NotifyStart;
using OperationRegistry::Operation::NotifyProgress;
using OperationRegistry::Operation::NotifyFinish;
};
class MockUploadOperation : public MockOperation {
public:
explicit MockUploadOperation(OperationRegistry* registry)
: MockOperation(registry,
OperationRegistry::OPERATION_UPLOAD,
FilePath(FILE_PATH_LITERAL("/dummy/upload"))) {}
};
class MockDownloadOperation : public MockOperation {
public:
explicit MockDownloadOperation(OperationRegistry* registry)
: MockOperation(registry,
OperationRegistry::OPERATION_DOWNLOAD,
FilePath(FILE_PATH_LITERAL("/dummy/download"))) {}
};
class MockOtherOperation : public MockOperation {
public:
explicit MockOtherOperation(OperationRegistry* registry)
: MockOperation(registry,
OperationRegistry::OPERATION_OTHER,
FilePath(FILE_PATH_LITERAL("/dummy/other"))) {}
};
class TestObserver : public OperationRegistry::Observer {
public:
virtual void OnProgressUpdate(
const std::vector<OperationRegistry::ProgressStatus>& list)
OVERRIDE {
status_ = list;
}
const std::vector<OperationRegistry::ProgressStatus>& status() const {
return status_;
}
private:
std::vector<OperationRegistry::ProgressStatus> status_;
};
class ProgressMatcher
: public ::testing::MatcherInterface<
const OperationRegistry::ProgressStatus&> {
public:
ProgressMatcher(int64 expected_current, int64 expected_total)
: expected_current_(expected_current),
expected_total_(expected_total) {}
virtual bool MatchAndExplain(
const OperationRegistry::ProgressStatus& status,
testing::MatchResultListener* /* listener */) const OVERRIDE {
return status.progress_current == expected_current_ &&
status.progress_total == expected_total_;
}
virtual void DescribeTo(::std::ostream* os) const OVERRIDE {
*os << "current / total equals " << expected_current_ << " / " <<
expected_total_;
}
virtual void DescribeNegationTo(::std::ostream* os) const OVERRIDE {
*os << "current / total does not equal " << expected_current_ << " / " <<
expected_total_;
}
private:
const int64 expected_current_;
const int64 expected_total_;
};
testing::Matcher<const OperationRegistry::ProgressStatus&> Progress(
int64 current, int64 total) {
return testing::MakeMatcher(new ProgressMatcher(current, total));
}
} // namespace
// Pretty-prints ProgressStatus for testing purpose.
std::ostream& operator<<(std::ostream& os,
const OperationRegistry::ProgressStatus& status) {
return os << status.DebugString();
}
class OperationRegistryTest : public testing::Test {
protected:
OperationRegistryTest()
: ui_thread_(content::BrowserThread::UI, &message_loop_) {
}
MessageLoopForUI message_loop_;
content::TestBrowserThread ui_thread_;
};
TEST_F(OperationRegistryTest, OneSuccess) {
TestObserver observer;
OperationRegistry registry;
registry.DisableNotificationFrequencyControlForTest();
registry.AddObserver(&observer);
base::WeakPtr<MockOperation> op1 =
(new MockUploadOperation(®istry))->AsWeakPtr();
EXPECT_CALL(*op1, DoCancel()).Times(0);
EXPECT_EQ(0U, observer.status().size());
op1->NotifyStart();
EXPECT_THAT(observer.status(), ElementsAre(Progress(0, -1)));
op1->NotifyProgress(0, 100);
EXPECT_THAT(observer.status(), ElementsAre(Progress(0, 100)));
op1->NotifyProgress(100, 100);
EXPECT_THAT(observer.status(), ElementsAre(Progress(100, 100)));
op1->NotifyFinish(OperationRegistry::OPERATION_COMPLETED);
// Contains one "COMPLETED" notification.
EXPECT_THAT(observer.status(), ElementsAre(Progress(100, 100)));
// Then it is removed.
EXPECT_EQ(0U, registry.GetProgressStatusList().size());
EXPECT_EQ(NULL, op1.get()); // deleted
}
TEST_F(OperationRegistryTest, OneCancel) {
TestObserver observer;
OperationRegistry registry;
registry.DisableNotificationFrequencyControlForTest();
registry.AddObserver(&observer);
base::WeakPtr<MockOperation> op1 =
(new MockUploadOperation(®istry))->AsWeakPtr();
EXPECT_CALL(*op1, DoCancel());
EXPECT_EQ(0U, observer.status().size());
op1->NotifyStart();
EXPECT_THAT(observer.status(), ElementsAre(Progress(0, -1)));
op1->NotifyProgress(0, 100);
EXPECT_THAT(observer.status(), ElementsAre(Progress(0, 100)));
registry.CancelAll();
EXPECT_THAT(observer.status(), ElementsAre(Progress(0, 100)));
EXPECT_EQ(0U, registry.GetProgressStatusList().size());
EXPECT_EQ(NULL, op1.get()); // deleted
}
TEST_F(OperationRegistryTest, TwoSuccess) {
TestObserver observer;
OperationRegistry registry;
registry.DisableNotificationFrequencyControlForTest();
registry.AddObserver(&observer);
base::WeakPtr<MockOperation> op1 =
(new MockUploadOperation(®istry))->AsWeakPtr();
base::WeakPtr<MockOperation> op2 =
(new MockDownloadOperation(®istry))->AsWeakPtr();
EXPECT_CALL(*op1, DoCancel()).Times(0);
EXPECT_CALL(*op2, DoCancel()).Times(0);
EXPECT_EQ(0U, observer.status().size());
op1->NotifyStart();
op1->NotifyProgress(0, 100);
EXPECT_THAT(observer.status(), ElementsAre(Progress(0, 100)));
op2->NotifyStart();
op2->NotifyProgress(0, 200);
op1->NotifyProgress(50, 100);
EXPECT_THAT(observer.status(), ElementsAre(Progress(50, 100),
Progress(0, 200)));
op1->NotifyFinish(OperationRegistry::OPERATION_COMPLETED);
EXPECT_THAT(observer.status(), ElementsAre(Progress(50, 100),
Progress(0, 200)));
EXPECT_EQ(1U, registry.GetProgressStatusList().size());
op2->NotifyFinish(OperationRegistry::OPERATION_COMPLETED);
EXPECT_THAT(observer.status(), ElementsAre(Progress(0, 200)));
EXPECT_EQ(0U, registry.GetProgressStatusList().size());
EXPECT_EQ(NULL, op1.get()); // deleted
EXPECT_EQ(NULL, op2.get()); // deleted
}
TEST_F(OperationRegistryTest, ThreeCancel) {
TestObserver observer;
OperationRegistry registry;
registry.DisableNotificationFrequencyControlForTest();
registry.AddObserver(&observer);
base::WeakPtr<MockOperation> op1 =
(new MockUploadOperation(®istry))->AsWeakPtr();
base::WeakPtr<MockOperation> op2 =
(new MockDownloadOperation(®istry))->AsWeakPtr();
base::WeakPtr<MockOperation> op3 =
(new MockOtherOperation(®istry))->AsWeakPtr();
EXPECT_CALL(*op1, DoCancel());
EXPECT_CALL(*op2, DoCancel());
EXPECT_CALL(*op3, DoCancel());
EXPECT_EQ(0U, observer.status().size());
op1->NotifyStart();
EXPECT_EQ(1U, observer.status().size());
op2->NotifyStart();
EXPECT_EQ(2U, observer.status().size());
op3->NotifyStart();
EXPECT_EQ(2U, observer.status().size()); // only upload/download is reported.
registry.CancelAll();
EXPECT_EQ(1U, observer.status().size()); // holds the last one "COMPLETED"
EXPECT_EQ(0U, registry.GetProgressStatusList().size());
EXPECT_EQ(NULL, op1.get()); // deleted
EXPECT_EQ(NULL, op2.get()); // deleted
EXPECT_EQ(NULL, op3.get()); // deleted. CancelAll cares all operations.
}
TEST_F(OperationRegistryTest, RestartOperation) {
TestObserver observer;
OperationRegistry registry;
registry.DisableNotificationFrequencyControlForTest();
registry.AddObserver(&observer);
base::WeakPtr<MockOperation> op1 =
(new MockUploadOperation(®istry))->AsWeakPtr();
EXPECT_CALL(*op1, DoCancel()).Times(0);
op1->NotifyStart();
EXPECT_EQ(1U, registry.GetProgressStatusList().size());
op1->NotifyStart(); // restart
EXPECT_EQ(1U, registry.GetProgressStatusList().size());
op1->NotifyProgress(0, 200);
op1->NotifyFinish(OperationRegistry::OPERATION_COMPLETED);
EXPECT_EQ(0U, registry.GetProgressStatusList().size());
EXPECT_EQ(NULL, op1.get()); // deleted
}
} // namespace gdata
<|endoftext|>
|
<commit_before>#include "TileRenderer.h"
namespace nme
{
TileRenderer::TileRenderer(const GraphicsJob &inJob, const GraphicsPath &inPath)
{
mBlendMode = bmNormal;
mFill = inJob.mFill->AsBitmapFill();
mFill->IncRef();
mFiller = Filler::Create(mFill);
const UserPoint *point = (const UserPoint *)&inPath.data[inJob.mData0];
int n = inJob.mCommandCount;
for(int j=0; j<n; j++)
{
int c = (inPath.commands[j+inJob.mCommand0]);
switch(c)
{
case pcBlendModeAdd:
mBlendMode = bmAdd;
break;
case pcWideMoveTo:
case pcWideLineTo:
case pcCurveTo:
point++;
case pcMoveTo:
case pcBeginAt:
case pcLineTo:
point++;
break;
case pcTile:
case pcTileTrans:
case pcTileCol:
case pcTileTransCol:
{
TileData data(point,c);
mTileData.push_back(data);
point+=3;
if (c & pcTile_Trans_Bit)
point++;
if (c & pcTile_Col_Bit)
point+=2;
}
}
}
}
TileRenderer::~TileRenderer()
{
mFill->DecRef();
delete mFiller;
}
void TileRenderer::Destroy() {
delete this;
}
bool TileRenderer::GetExtent(const Transform &inTransform,Extent2DF &ioExtent)
{
/*
printf("In extent %f,%f ... %f,%f\n",
ioExtent.mMinX, ioExtent.mMinY,
ioExtent.mMaxX, ioExtent.mMaxY );
*/
for(int i=0;i<mTileData.size();i++)
{
TileData &data= mTileData[i];
for(int c=0;c<4;c++)
{
UserPoint corner(data.mPos);
if (c&1) corner.x += data.mRect.w;
if (c&2) corner.y += data.mRect.h;
ioExtent.Add( inTransform.mMatrix->Apply(corner.x,corner.y) );
}
}
/*
printf("Got extent %f,%f ... %f,%f\n",
ioExtent.mMinX, ioExtent.mMinY,
ioExtent.mMaxX, ioExtent.mMaxY );
*/
return true;
}
bool TileRenderer::Hits(const RenderState &inState)
{
return false;
}
bool TileRenderer::Render(const RenderTarget &inTarget, const RenderState &inState)
{
Surface *s = mFill->bitmapData;
double bmp_scale_x = 1.0/s->Width();
double bmp_scale_y = 1.0/s->Height();
// Todo:skew
bool is_stretch = (inState.mTransform.mMatrix->m00!=1.0 ||
inState.mTransform.mMatrix->m11!=1.0) &&
( inState.mTransform.mMatrix->m00 > 0 &&
inState.mTransform.mMatrix->m11 > 0 );
for(int i=0;i<mTileData.size();i++)
{
TileData &data= mTileData[i];
BlendMode blend = data.mHasColour ? ( mBlendMode==bmAdd ? bmTintedAdd : bmTinted ):
mBlendMode;
UserPoint corner(data.mPos);
UserPoint pos = inState.mTransform.mMatrix->Apply(corner.x,corner.y);
if ( (is_stretch || data.mHasTrans) )
{
// Can use stretch if there is no skew and no colour transform...
if (!data.mHasColour && (!data.mHasTrans || data.mDxDxy==0) && mBlendMode==bmNormal )
{
UserPoint p0 = pos;
pos = inState.mTransform.mMatrix->Apply(corner.x+data.mRect.w,corner.y+data.mRect.h);
s->StretchTo(inTarget, data.mRect, DRect(p0.x,p0.y,pos.x,pos.y,true));
}
else
{
int tile_alpha = 256;
if (data.mHasColour)
{
tile_alpha = data.mColour>>24;
if (tile_alpha>0) tile_alpha++;
}
// Create alpha mask...
UserPoint p[4];
p[0] = inState.mTransform.mMatrix->Apply(corner.x,corner.y);
if (data.mHasTrans)
{
UserPoint t = data.mDxDxy;
p[1] = inState.mTransform.mMatrix->Apply(corner.x + data.mRect.w*t.x,
corner.y - data.mRect.w*t.y );
p[2] = inState.mTransform.mMatrix->Apply(corner.x + data.mRect.w*t.x + data.mRect.h*t.y,
corner.y - data.mRect.w*t.y + data.mRect.h*t.x );
p[3] = inState.mTransform.mMatrix->Apply(corner.x +data.mRect.h*t.y,
corner.y + data.mRect.h*t.x );
}
else
{
p[1] = inState.mTransform.mMatrix->Apply(corner.x+data.mRect.w,corner.y);
p[2] = inState.mTransform.mMatrix->Apply(corner.x+data.mRect.w,corner.y+data.mRect.h);
p[3] = inState.mTransform.mMatrix->Apply(corner.x,corner.y+data.mRect.h);
}
Extent2DF extent;
extent.Add(p[0]);
extent.Add(p[1]);
extent.Add(p[2]);
extent.Add(p[3]);
// Get bounding pixel rect
Rect rect = inState.mTransform.GetTargetRect(extent);
// Intersect with clip rect ...
Rect visible_pixels = rect.Intersect(inState.mClipRect);
int aa = 1;
SpanRect *span = new SpanRect(visible_pixels,aa);
for(int i=0;i<4;i++)
span->Line<false,false>(
Fixed10( p[i].x + 0.5, p[i].y + 0.5 ),
Fixed10( p[(i+1)&3].x + 0.5, p[(i+1)&3].y + 0.5 ) );
AlphaMask *alpha = span->CreateMask(inState.mTransform,tile_alpha);
delete span;
float uvt[6];
uvt[0] = (data.mRect.x) * bmp_scale_x;
uvt[1] = (data.mRect.y) * bmp_scale_y;
uvt[2] = (data.mRect.x + data.mRect.w) * bmp_scale_x;
uvt[3] = (data.mRect.y) * bmp_scale_y;
uvt[4] = (data.mRect.x + data.mRect.w) * bmp_scale_x;
uvt[5] = (data.mRect.y + data.mRect.h) * bmp_scale_y;
mFiller->SetMapping(p,uvt,2);
if (data.mHasColour && (( data.mColour&0x00ffffff ) != 0x00ffffff) )
{
ColorTransform buf;
RenderState col_state(inState);
ColorTransform tint;
tint.redMultiplier = ((data.mColour) & 0xff) * one_on_255;
tint.greenMultiplier = ((data.mColour>>8) & 0xff) * one_on_255;
tint.blueMultiplier = ((data.mColour>>16) & 0xff) * one_on_255;
col_state.CombineColourTransform(inState, &tint, &buf);
mFiller->Fill(*alpha,0,0,inTarget,col_state);
}
else
mFiller->Fill(*alpha,0,0,inTarget,inState);
alpha->Dispose();
}
}
else
s->BlitTo(inTarget, data.mRect, (int)(pos.x), (int)(pos.y), blend, 0, data.mColour);
}
return true;
}
}
<commit_msg>Use an off-screen buffer if required to get tile+transform+tint+add working<commit_after>#include "TileRenderer.h"
namespace nme
{
TileRenderer::TileRenderer(const GraphicsJob &inJob, const GraphicsPath &inPath)
{
mBlendMode = bmNormal;
mFill = inJob.mFill->AsBitmapFill();
mFill->IncRef();
mFiller = Filler::Create(mFill);
const UserPoint *point = (const UserPoint *)&inPath.data[inJob.mData0];
int n = inJob.mCommandCount;
for(int j=0; j<n; j++)
{
int c = (inPath.commands[j+inJob.mCommand0]);
switch(c)
{
case pcBlendModeAdd:
mBlendMode = bmAdd;
break;
case pcWideMoveTo:
case pcWideLineTo:
case pcCurveTo:
point++;
case pcMoveTo:
case pcBeginAt:
case pcLineTo:
point++;
break;
case pcTile:
case pcTileTrans:
case pcTileCol:
case pcTileTransCol:
{
TileData data(point,c);
mTileData.push_back(data);
point+=3;
if (c & pcTile_Trans_Bit)
point++;
if (c & pcTile_Col_Bit)
point+=2;
}
}
}
}
TileRenderer::~TileRenderer()
{
mFill->DecRef();
delete mFiller;
}
void TileRenderer::Destroy() {
delete this;
}
bool TileRenderer::GetExtent(const Transform &inTransform,Extent2DF &ioExtent)
{
/*
printf("In extent %f,%f ... %f,%f\n",
ioExtent.mMinX, ioExtent.mMinY,
ioExtent.mMaxX, ioExtent.mMaxY );
*/
for(int i=0;i<mTileData.size();i++)
{
TileData &data= mTileData[i];
for(int c=0;c<4;c++)
{
UserPoint corner(data.mPos);
if (c&1) corner.x += data.mRect.w;
if (c&2) corner.y += data.mRect.h;
ioExtent.Add( inTransform.mMatrix->Apply(corner.x,corner.y) );
}
}
/*
printf("Got extent %f,%f ... %f,%f\n",
ioExtent.mMinX, ioExtent.mMinY,
ioExtent.mMaxX, ioExtent.mMaxY );
*/
return true;
}
bool TileRenderer::Hits(const RenderState &inState)
{
return false;
}
bool TileRenderer::Render(const RenderTarget &inTarget, const RenderState &inState)
{
Surface *s = mFill->bitmapData;
double bmp_scale_x = 1.0/s->Width();
double bmp_scale_y = 1.0/s->Height();
// Todo:skew
bool is_stretch = (inState.mTransform.mMatrix->m00!=1.0 ||
inState.mTransform.mMatrix->m11!=1.0) &&
( inState.mTransform.mMatrix->m00 > 0 &&
inState.mTransform.mMatrix->m11 > 0 );
for(int i=0;i<mTileData.size();i++)
{
TileData &data= mTileData[i];
BlendMode blend = data.mHasColour ? ( mBlendMode==bmAdd ? bmTintedAdd : bmTinted ):
mBlendMode;
UserPoint corner(data.mPos);
UserPoint pos = inState.mTransform.mMatrix->Apply(corner.x,corner.y);
if ( (is_stretch || data.mHasTrans) )
{
// Can use stretch if there is no skew and no colour transform...
if (!data.mHasColour && (!data.mHasTrans || data.mDxDxy==0) && mBlendMode==bmNormal )
{
UserPoint p0 = pos;
pos = inState.mTransform.mMatrix->Apply(corner.x+data.mRect.w,corner.y+data.mRect.h);
s->StretchTo(inTarget, data.mRect, DRect(p0.x,p0.y,pos.x,pos.y,true));
}
else
{
int tile_alpha = 256;
bool just_alpha = (data.mHasColour) &&
((data.mColour&0x00ffffff ) == 0x00ffffff);
if (data.mHasColour && mBlendMode==bmNormal)
{
tile_alpha = data.mColour>>24;
if (tile_alpha>0) tile_alpha++;
}
// Create alpha mask...
UserPoint p[4];
p[0] = inState.mTransform.mMatrix->Apply(corner.x,corner.y);
if (data.mHasTrans)
{
UserPoint t = data.mDxDxy;
p[1] = inState.mTransform.mMatrix->Apply(corner.x + data.mRect.w*t.x,
corner.y - data.mRect.w*t.y );
p[2] = inState.mTransform.mMatrix->Apply(corner.x + data.mRect.w*t.x + data.mRect.h*t.y,
corner.y - data.mRect.w*t.y + data.mRect.h*t.x );
p[3] = inState.mTransform.mMatrix->Apply(corner.x +data.mRect.h*t.y,
corner.y + data.mRect.h*t.x );
}
else
{
p[1] = inState.mTransform.mMatrix->Apply(corner.x+data.mRect.w,corner.y);
p[2] = inState.mTransform.mMatrix->Apply(corner.x+data.mRect.w,corner.y+data.mRect.h);
p[3] = inState.mTransform.mMatrix->Apply(corner.x,corner.y+data.mRect.h);
}
Extent2DF extent;
extent.Add(p[0]);
extent.Add(p[1]);
extent.Add(p[2]);
extent.Add(p[3]);
// Get bounding pixel rect
Rect rect = inState.mTransform.GetTargetRect(extent);
// Intersect with clip rect ...
Rect visible_pixels = rect.Intersect(inState.mClipRect);
if (!visible_pixels.HasPixels())
continue;
Rect alpha_rect(visible_pixels);
bool offscreen_buffer = mBlendMode!=bmNormal;
if (offscreen_buffer)
{
for(int i=0;i<4;i++)
{
p[i].x -= visible_pixels.x;
p[i].y -= visible_pixels.y;
}
alpha_rect.x -= visible_pixels.x;
alpha_rect.y -= visible_pixels.y;
}
int aa = 1;
SpanRect *span = new SpanRect(alpha_rect,aa);
for(int i=0;i<4;i++)
span->Line<false,false>(
Fixed10( p[i].x + 0.5 , p[i].y + 0.5 ),
Fixed10( p[(i+1)&3].x + 0.5 , p[(i+1)&3].y + 0.5 ) );
AlphaMask *alpha = span->CreateMask(inState.mTransform,tile_alpha);
delete span;
float uvt[6];
uvt[0] = (data.mRect.x) * bmp_scale_x;
uvt[1] = (data.mRect.y) * bmp_scale_y;
uvt[2] = (data.mRect.x + data.mRect.w) * bmp_scale_x;
uvt[3] = (data.mRect.y) * bmp_scale_y;
uvt[4] = (data.mRect.x + data.mRect.w) * bmp_scale_x;
uvt[5] = (data.mRect.y + data.mRect.h) * bmp_scale_y;
mFiller->SetMapping(p,uvt,2);
// Can render straight to surface ....
if (!offscreen_buffer)
{
if (data.mHasTrans && !just_alpha)
{
ColorTransform buf;
RenderState col_state(inState);
ColorTransform tint;
tint.redMultiplier = ((data.mColour) & 0xff) * one_on_255;
tint.greenMultiplier = ((data.mColour>>8) & 0xff) * one_on_255;
tint.blueMultiplier = ((data.mColour>>16) & 0xff) * one_on_255;
col_state.CombineColourTransform(inState, &tint, &buf);
mFiller->Fill(*alpha,0,0,inTarget,col_state);
}
else
mFiller->Fill(*alpha,0,0,inTarget,inState);
}
else
{
// Create temp surface
SimpleSurface *tmp = new SimpleSurface(visible_pixels.w,visible_pixels.h, pfARGB);
tmp->IncRef();
tmp->Zero();
{
AutoSurfaceRender tmp_render(tmp);
const RenderTarget &target = tmp_render.Target();
mFiller->Fill(*alpha,0,0,target,inState);
}
tmp->BlitTo(inTarget, Rect(0,0,visible_pixels.w,visible_pixels.h),
visible_pixels.x, visible_pixels.y,
just_alpha ? bmAdd : blend, 0, data.mColour | 0xff000000);
tmp->DecRef();
}
alpha->Dispose();
}
}
else
s->BlitTo(inTarget, data.mRect, (int)(pos.x), (int)(pos.y), blend, 0, data.mColour);
}
return true;
}
}
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
* Copyright (c) 2016-2018 metaverse core developers (see MVS-AUTHORS)
*
* This file is part of metaverse.
*
* metaverse is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU 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/>.
*/
#include <metaverse/bitcoin/chain/header.hpp>
#include <utility>
#include <boost/iostreams/stream.hpp>
#include <metaverse/bitcoin/constants.hpp>
#include <metaverse/bitcoin/utility/container_sink.hpp>
#include <metaverse/bitcoin/utility/container_source.hpp>
#include <metaverse/bitcoin/utility/istream_reader.hpp>
#include <metaverse/bitcoin/utility/ostream_writer.hpp>
#include <metaverse/consensus/libdevcore/FixedHash.h>
namespace libbitcoin {
namespace chain {
uint64_t header::satoshi_fixed_size_without_transaction_count()
{
return 148;
}
header::header()
: header(0, null_hash, null_hash, 0, 0, 0, 0, 0, 0)
{
}
header::header(const header& other)
: header(other.version, other.previous_block_hash, other.merkle,
other.timestamp, other.bits, other.nonce, other.mixhash, other.number, other.transaction_count)
{
}
header::header(uint32_t version, const hash_digest& previous_block_hash,
const hash_digest& merkle, uint32_t timestamp, const u256& bits,
u64 nonce, const u256& mixhash, uint32_t number, uint64_t transaction_count)
: version(version),
previous_block_hash(previous_block_hash),
merkle(merkle),
timestamp(timestamp),
bits(bits),
nonce(nonce),
mixhash(mixhash),
number(number),
transaction_count(transaction_count),
hash_(nullptr)
{
}
header::header(header&& other)
: header(other.version, std::forward<hash_digest>(other.previous_block_hash),
std::forward<hash_digest>(other.merkle), other.timestamp, other.bits,
other.nonce, other.mixhash, other.number, other.transaction_count)
{
}
header::header(uint32_t version, hash_digest&& previous_block_hash,
hash_digest&& merkle, uint32_t timestamp, const u256& bits, u64 nonce, const u256& mixhash, uint32_t number,
uint64_t transaction_count)
: version(version),
previous_block_hash(std::forward<hash_digest>(previous_block_hash)),
merkle(std::forward<hash_digest>(merkle)),
timestamp(timestamp),
bits(bits),
nonce(nonce),
mixhash(mixhash),
number(number),
transaction_count(transaction_count),
hash_(nullptr)
{
}
header& header::operator=(header&& other)
{
version = other.version;
previous_block_hash = std::move(other.previous_block_hash);
merkle = std::move(other.merkle);
timestamp = other.timestamp;
bits = other.bits;
nonce = other.nonce;
mixhash = other.mixhash;
number = other.number;
transaction_count = other.transaction_count;
return *this;
}
// TODO: eliminate header copies and then delete this.
header& header::operator=(const header& other)
{
version = other.version;
previous_block_hash = other.previous_block_hash;
merkle = other.merkle;
timestamp = other.timestamp;
bits = other.bits;
nonce = other.nonce;
mixhash = other.mixhash;
number = other.number;
transaction_count = other.transaction_count;
return *this;
}
bool header::is_valid() const
{
return (version != 0) ||
(previous_block_hash != null_hash) ||
(merkle != null_hash) ||
(timestamp != 0) ||
(bits != 0) ||
(nonce != 0);
}
bool header::is_proof_of_stake() const
{
return version == block_version_pos;
}
bool header::is_proof_of_work() const
{
return version == block_version_pow;
}
bool header::is_proof_of_dpos() const
{
return version == block_version_dpos;
}
void header::reset()
{
version = 0;
previous_block_hash.fill(0);
merkle.fill(0);
timestamp = 0;
bits = 0;
nonce = 0;
mutex_.lock();
hash_.reset();
mutex_.unlock();
}
bool header::from_data_t(reader& source, bool with_transaction_count)
{
reset();
version = source.read_4_bytes_little_endian();
previous_block_hash = source.read_hash();
merkle = source.read_hash();
timestamp = source.read_4_bytes_little_endian();
unsigned char buff[32];
source.read_data(buff, 32);
bits = (h256::Arith)(h256((const uint8_t*)&buff[0], h256::ConstructFromPointer));
source.read_data(buff, 8);
nonce = (h64::Arith)(h64((const uint8_t*)&buff[0], h64::ConstructFromPointer));
source.read_data(buff, 32);
mixhash = (h256::Arith)(h256((const uint8_t*)&buff[0], h256::ConstructFromPointer));
number = source.read_4_bytes_little_endian();
transaction_count = 0;
if (with_transaction_count)
transaction_count = source.read_variable_uint_little_endian();
const auto result = static_cast<bool>(source);
if (!result)
reset();
return result;
}
void header::to_data_t(writer& sink, bool with_transaction_count) const
{
sink.write_4_bytes_little_endian(version);
sink.write_hash(previous_block_hash);
sink.write_hash(merkle);
sink.write_4_bytes_little_endian(timestamp);
sink.write_data((unsigned char*)h256(bits).data(), 32);
sink.write_data((unsigned char*)h64(nonce).data(), 8);
sink.write_data((unsigned char*)h256(mixhash).data(), 32);
sink.write_4_bytes_little_endian(number);
if (with_transaction_count)
sink.write_variable_uint_little_endian(transaction_count);
}
uint64_t header::serialized_size(bool with_transaction_count) const
{
auto size = satoshi_fixed_size_without_transaction_count();
if (with_transaction_count)
size += variable_uint_size(transaction_count);
return size;
}
hash_digest header::hash() const
{
///////////////////////////////////////////////////////////////////////////
// Critical Section
mutex_.lock_upgrade();
if (!hash_)
{
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
mutex_.unlock_upgrade_and_lock();
hash_.reset(new hash_digest(bitcoin_hash(to_data(false))));
mutex_.unlock_and_lock_upgrade();
//---------------------------------------------------------------------
}
hash_digest hash = *hash_;
mutex_.unlock_upgrade();
///////////////////////////////////////////////////////////////////////////
return hash;
}
bool operator==(const header& left, const header& right)
{
return (left.version == right.version)
&& (left.previous_block_hash == right.previous_block_hash)
&& (left.merkle == right.merkle)
&& (left.timestamp == right.timestamp)
&& (left.bits == right.bits)
&& (left.nonce == right.nonce)
&& (left.transaction_count == right.transaction_count);
}
bool operator!=(const header& left, const header& right)
{
return !(left == right);
}
std::string get_block_version(const header& header)
{
return get_block_version(header.version);
}
std::string get_block_version(block_version version)
{
return get_block_version((uint32_t)version);
}
std::string get_block_version(uint32_t version)
{
switch (version) {
case block_version_any:
return " Any";
case block_version_pow:
return " PoW";
case block_version_pos:
return " PoS";
case block_version_dpos:
return "DPoS";
default:;
}
return "Unknown";
}
} // namspace chain
} // namspace libbitcoin
<commit_msg>get_block_version<commit_after>/**
* Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
* Copyright (c) 2016-2018 metaverse core developers (see MVS-AUTHORS)
*
* This file is part of metaverse.
*
* metaverse is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU 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/>.
*/
#include <metaverse/bitcoin/chain/header.hpp>
#include <utility>
#include <boost/iostreams/stream.hpp>
#include <metaverse/bitcoin/constants.hpp>
#include <metaverse/bitcoin/utility/container_sink.hpp>
#include <metaverse/bitcoin/utility/container_source.hpp>
#include <metaverse/bitcoin/utility/istream_reader.hpp>
#include <metaverse/bitcoin/utility/ostream_writer.hpp>
#include <metaverse/consensus/libdevcore/FixedHash.h>
namespace libbitcoin {
namespace chain {
uint64_t header::satoshi_fixed_size_without_transaction_count()
{
return 148;
}
header::header()
: header(0, null_hash, null_hash, 0, 0, 0, 0, 0, 0)
{
}
header::header(const header& other)
: header(other.version, other.previous_block_hash, other.merkle,
other.timestamp, other.bits, other.nonce, other.mixhash, other.number, other.transaction_count)
{
}
header::header(uint32_t version, const hash_digest& previous_block_hash,
const hash_digest& merkle, uint32_t timestamp, const u256& bits,
u64 nonce, const u256& mixhash, uint32_t number, uint64_t transaction_count)
: version(version),
previous_block_hash(previous_block_hash),
merkle(merkle),
timestamp(timestamp),
bits(bits),
nonce(nonce),
mixhash(mixhash),
number(number),
transaction_count(transaction_count),
hash_(nullptr)
{
}
header::header(header&& other)
: header(other.version, std::forward<hash_digest>(other.previous_block_hash),
std::forward<hash_digest>(other.merkle), other.timestamp, other.bits,
other.nonce, other.mixhash, other.number, other.transaction_count)
{
}
header::header(uint32_t version, hash_digest&& previous_block_hash,
hash_digest&& merkle, uint32_t timestamp, const u256& bits, u64 nonce, const u256& mixhash, uint32_t number,
uint64_t transaction_count)
: version(version),
previous_block_hash(std::forward<hash_digest>(previous_block_hash)),
merkle(std::forward<hash_digest>(merkle)),
timestamp(timestamp),
bits(bits),
nonce(nonce),
mixhash(mixhash),
number(number),
transaction_count(transaction_count),
hash_(nullptr)
{
}
header& header::operator=(header&& other)
{
version = other.version;
previous_block_hash = std::move(other.previous_block_hash);
merkle = std::move(other.merkle);
timestamp = other.timestamp;
bits = other.bits;
nonce = other.nonce;
mixhash = other.mixhash;
number = other.number;
transaction_count = other.transaction_count;
return *this;
}
// TODO: eliminate header copies and then delete this.
header& header::operator=(const header& other)
{
version = other.version;
previous_block_hash = other.previous_block_hash;
merkle = other.merkle;
timestamp = other.timestamp;
bits = other.bits;
nonce = other.nonce;
mixhash = other.mixhash;
number = other.number;
transaction_count = other.transaction_count;
return *this;
}
bool header::is_valid() const
{
return (version != 0) ||
(previous_block_hash != null_hash) ||
(merkle != null_hash) ||
(timestamp != 0) ||
(bits != 0) ||
(nonce != 0);
}
bool header::is_proof_of_stake() const
{
return version == block_version_pos;
}
bool header::is_proof_of_work() const
{
return version == block_version_pow;
}
bool header::is_proof_of_dpos() const
{
return version == block_version_dpos;
}
void header::reset()
{
version = 0;
previous_block_hash.fill(0);
merkle.fill(0);
timestamp = 0;
bits = 0;
nonce = 0;
mutex_.lock();
hash_.reset();
mutex_.unlock();
}
bool header::from_data_t(reader& source, bool with_transaction_count)
{
reset();
version = source.read_4_bytes_little_endian();
previous_block_hash = source.read_hash();
merkle = source.read_hash();
timestamp = source.read_4_bytes_little_endian();
unsigned char buff[32];
source.read_data(buff, 32);
bits = (h256::Arith)(h256((const uint8_t*)&buff[0], h256::ConstructFromPointer));
source.read_data(buff, 8);
nonce = (h64::Arith)(h64((const uint8_t*)&buff[0], h64::ConstructFromPointer));
source.read_data(buff, 32);
mixhash = (h256::Arith)(h256((const uint8_t*)&buff[0], h256::ConstructFromPointer));
number = source.read_4_bytes_little_endian();
transaction_count = 0;
if (with_transaction_count)
transaction_count = source.read_variable_uint_little_endian();
const auto result = static_cast<bool>(source);
if (!result)
reset();
return result;
}
void header::to_data_t(writer& sink, bool with_transaction_count) const
{
sink.write_4_bytes_little_endian(version);
sink.write_hash(previous_block_hash);
sink.write_hash(merkle);
sink.write_4_bytes_little_endian(timestamp);
sink.write_data((unsigned char*)h256(bits).data(), 32);
sink.write_data((unsigned char*)h64(nonce).data(), 8);
sink.write_data((unsigned char*)h256(mixhash).data(), 32);
sink.write_4_bytes_little_endian(number);
if (with_transaction_count)
sink.write_variable_uint_little_endian(transaction_count);
}
uint64_t header::serialized_size(bool with_transaction_count) const
{
auto size = satoshi_fixed_size_without_transaction_count();
if (with_transaction_count)
size += variable_uint_size(transaction_count);
return size;
}
hash_digest header::hash() const
{
///////////////////////////////////////////////////////////////////////////
// Critical Section
mutex_.lock_upgrade();
if (!hash_)
{
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
mutex_.unlock_upgrade_and_lock();
hash_.reset(new hash_digest(bitcoin_hash(to_data(false))));
mutex_.unlock_and_lock_upgrade();
//---------------------------------------------------------------------
}
hash_digest hash = *hash_;
mutex_.unlock_upgrade();
///////////////////////////////////////////////////////////////////////////
return hash;
}
bool operator==(const header& left, const header& right)
{
return (left.version == right.version)
&& (left.previous_block_hash == right.previous_block_hash)
&& (left.merkle == right.merkle)
&& (left.timestamp == right.timestamp)
&& (left.bits == right.bits)
&& (left.nonce == right.nonce)
&& (left.transaction_count == right.transaction_count);
}
bool operator!=(const header& left, const header& right)
{
return !(left == right);
}
std::string get_block_version(const header& header)
{
return get_block_version(header.version);
}
std::string get_block_version(block_version version)
{
return get_block_version((uint32_t)version);
}
std::string get_block_version(uint32_t version)
{
switch (version) {
case block_version_any:
return "Any";
case block_version_pow:
return "PoW";
case block_version_pos:
return "PoS";
case block_version_dpos:
return "DPoS";
default:;
}
return "Unknown";
}
} // namspace chain
} // namspace libbitcoin
<|endoftext|>
|
<commit_before>#include <tiramisu/auto_scheduler/search_method.h>
#include <random>
namespace tiramisu::auto_scheduler
{
void beam_search::search(syntax_tree& ast)
{
if (ast.nb_explored_optims % NB_OPTIMIZATIONS == 0)
ast.clear_new_optimizations();
std::vector<syntax_tree*> children;
// Look for an optimization that can be applied
int nb_optims_tried = 0;
int nb_explored_optims = ast.nb_explored_optims;
while (children.size() == 0 && nb_optims_tried < NB_OPTIMIZATIONS && nb_explored_optims < max_depth)
{
optimization_type optim_type = DEFAULT_OPTIMIZATIONS_ORDER[nb_explored_optims % NB_OPTIMIZATIONS];
children = scheds_gen->generate_schedules(ast, optim_type);
nb_explored_optims++;
nb_optims_tried++;
}
// Stop if no more optimizations can be applied
if (children.size() == 0)
return ;
// Evaluate children and sort them from smallest to highest evaluation
// evaluate while removing illegal versions
auto iterator = children.begin();
while (iterator != children.end())
{
(*iterator)->nb_explored_optims = nb_explored_optims;
(*iterator)->transform_ast();
if ((*iterator)->ast_is_legal() == false) {
// print deleted Ast
(*iterator)->print_previous_optims();
std::cout << "\n-----------" << std::endl;
(*iterator)->print_new_optims();
(*iterator)->print_ast();
(*iterator)->print_isl_states();
std::cout << "\n<illegal>\n";
delete (*iterator);
iterator = children.erase(iterator);
}
else {
// evaluate and print Ast
(*iterator)->evaluation = eval_func->evaluate(*(*iterator));
(*iterator)->print_previous_optims();
std::cout << "\n-----------" << std::endl;
(*iterator)->print_new_optims();
(*iterator)->print_ast();
std::cout << "Evaluation : " << (*iterator)->evaluation << std::endl << std::endl;
(*iterator)->print_isl_states();
(*iterator)->print_computations_accesses();
std::cout << "\n<legal>\n";
if ((*iterator)->evaluation < best_evaluation)
{
best_evaluation = (*iterator)->evaluation;
best_ast = (*iterator);
}
++iterator;
}
nb_explored_schedules++;
}
// Stop if we reached the maximum depth
if (nb_explored_optims >= max_depth)
return ;
// Add the current AST to the list of children
syntax_tree *ast_copy = ast.copy_ast();
ast_copy->nb_explored_optims = nb_explored_optims;
children.push_back(ast_copy);
// Sort children from smallest evaluation to largest
std::cout<<"\noriginal list\n" ;
for (syntax_tree *child : children)
{
std::cout<<child->evaluation<<"+";
}
std::sort(children.begin(), children.end(), [](syntax_tree *a, syntax_tree *b) {
return a->evaluation < b->evaluation;
});
// keep the top 'beam_size' children and delete the rest
for (int i = beam_size; i < children.size(); ++i)
delete children[i];
children.resize(std::min(beam_size, (int)children.size()));
std::cout<<"\nremaining list\n" ;
for (syntax_tree *child : children)
{
std::cout<<child->evaluation<<"+";
}
// Search recursively on the best children
for (syntax_tree *child : children)
{
child->search_depth = ast.search_depth + 1;
search(*child);
}
}
void beam_search::search_save(syntax_tree& ast, std::vector<std::string> *schedules_annotations)
{
if (ast.nb_explored_optims % NB_OPTIMIZATIONS == 0)
ast.clear_new_optimizations();
std::vector<syntax_tree*> children;
// Look for an optimization that can be applied
int nb_optims_tried = 0;
int nb_explored_optims = ast.nb_explored_optims;
while (children.size() == 0 && nb_optims_tried < NB_OPTIMIZATIONS && nb_explored_optims < max_depth)
{
optimization_type optim_type = DEFAULT_OPTIMIZATIONS_ORDER[nb_explored_optims % NB_OPTIMIZATIONS];
children = scheds_gen->generate_schedules(ast, optim_type);
nb_explored_optims++;
nb_optims_tried++;
}
// Stop if no more optimizations can be applied
if (children.size() == 0)
return ;
// Evaluate children and sort them from smallest to highest evaluation
// evaluate while removing illegal versions
auto iterator = children.begin();
while (iterator != children.end())
{
syntax_tree *child = *iterator;
child->nb_explored_optims = nb_explored_optims;
child->transform_ast();
if (child->ast_is_legal() == false) {
if (std::getenv("AS_VERBOSE")!=NULL)
if (std::stoi(std::getenv("AS_VERBOSE"))==1){
// print deleted Ast
child->print_previous_optims();
std::cout << "\n-----------" << std::endl;
child->print_new_optims();
child->print_ast();
child->print_isl_states();
std::cout << "\n<illegal>\n";
iterator = children.erase(iterator);
}
}
else {
// print and evaluate Ast
if (std::getenv("AS_VERBOSE")!=NULL)
if (std::stoi(std::getenv("AS_VERBOSE"))==1){
child->print_previous_optims();
std::cout << "\n-----------" << std::endl;
child->print_new_optims();
child->print_ast();
child->print_isl_states();
std::cout << "\n<legal>\n";
}
child->evaluation = eval_func->evaluate(*child);
std::string schedule_annot = evaluate_by_learning_model::get_schedule_json(*child);
//remove the last two characters }\n
schedule_annot.pop_back();
schedule_annot.pop_back();
if (std::isfinite(child->evaluation)) // the evaluation is not finite mean that the schedule didn't run
schedule_annot += ", \n\"execution_time\" : " + std::to_string(child->evaluation) + "\n}\n";
else
schedule_annot += ", \n\"execution_time\" : null\n}\n";
schedules_annotations->push_back(schedule_annot);
if (std::getenv("AS_VERBOSE")!=NULL)
if (std::stoi(std::getenv("AS_VERBOSE"))==1){
std::cout << "Schedule number "<< schedules_annotations->size() << std::endl;
std::cout << "Evaluation : " << child->evaluation << std::endl;
std::cout << "===================================" << std::endl << std::endl;
}
if (std::isinf(child->evaluation))
std::cerr<< "Evaluation of schedule "<< schedules_annotations->size() <<" failed "<< std::endl;
if (child->evaluation < best_evaluation)
{
best_evaluation = child->evaluation;
best_ast = child;
}
++iterator;
}
nb_explored_schedules++;
}
// Stop if we reached the maximum depth
if (nb_explored_optims >= max_depth)
return ;
// Add the current AST to the list of children
syntax_tree *ast_copy = ast.copy_ast();
ast_copy->nb_explored_optims = nb_explored_optims;
children.push_back(ast_copy);
// Sort children from smallest evaluation to largest
std::sort(children.begin(), children.end(), [](syntax_tree *a, syntax_tree *b) {
return a->evaluation < b->evaluation;
});
// keep the top 'beam_size' children and delete the rest
for (int i = beam_size; i < children.size(); ++i)
delete children[i];
children.resize(std::min(beam_size, (int)children.size()));
// Search recursively on the best children
for (syntax_tree *child : children)
{
child->search_depth = ast.search_depth + 1;
search_save(*child, schedules_annotations);
}
}
void mcts::search(syntax_tree& ast)
{
std::default_random_engine rand_generator;
std::vector<syntax_tree*> samples;
std::vector<syntax_tree*> children;
std::vector<double> children_evals;
for (int epoch = 0; epoch < nb_samples; ++epoch)
{
// Starting from the initial ast, generate optimizations until reaching max_depth
syntax_tree *ast_sample = *
for (int depth = 0; depth < max_depth; ++depth)
{
optimization_type optim_type = DEFAULT_OPTIMIZATIONS_ORDER[depth % NB_OPTIMIZATIONS];
children = scheds_gen->generate_schedules(*ast_sample, optim_type);
if (children.empty())
continue;
children_evals.clear();
for (syntax_tree *child : children)
{
child->transform_ast();
child->evaluation = eval_func->evaluate(*child);
children_evals.push_back(child->evaluation);
nb_explored_schedules++;
}
// Add the current AST to the list of children
children.push_back(ast_sample->copy_ast());
children_evals.push_back(ast_sample->evaluation);
// Sample an AST
std::discrete_distribution<int> dist(children_evals.begin(), children_evals.end());
ast_sample = children[dist(rand_generator)];
samples.push_back(ast_sample);
}
}
if (samples.empty())
return ;
// Sort schedules with respect to evaluations
std::sort(samples.begin(), samples.end(), [](syntax_tree *a, syntax_tree *b) {
return a->evaluation < b->evaluation;
});
// Execute top-k schedules and return the best
for (int i = 0; i < topk; ++i)
{
float exec_time = exec_eval->evaluate(*samples[i]);
if (exec_time < best_evaluation)
{
best_evaluation = exec_time;
best_ast = samples[i];
}
}
}
void mcts::search_save(syntax_tree& ast, std::vector<std::string> *schedules_annotations)
{
std::cerr<< "mcts::search_save not yet implemented" << std::endl;
exit(1);
}
// -------------------------------------------------------------------------- //
void beam_search_topk::search(syntax_tree& ast)
{
// Do a beam search
beam_search_subroutine(ast);
// Sort schedules found
std::sort(schedules.begin(), schedules.end(), [](syntax_tree *a, syntax_tree *b) {
return a->evaluation < b->evaluation;
});
// Execute top-k schedules to find the best
for (int i = 0; i < topk; ++i)
{
float exec_time = exec_eval->evaluate(*schedules[i]);
if (exec_time < best_evaluation)
{
best_evaluation = exec_time;
best_ast = schedules[i];
}
}
}
void beam_search_topk::search_save(syntax_tree& ast, std::vector<std::string> *schedules_annotations)
{
std::cerr<< "beam_search_topk::search_save not yet implemented" << std::endl;
exit(1);
}
void beam_search_topk::beam_search_subroutine(syntax_tree& ast)
{
if (ast.nb_explored_optims % NB_OPTIMIZATIONS == 0)
ast.clear_new_optimizations();
std::vector<syntax_tree*> children;
// Look for an optimization that can be applied
int nb_optims_tried = 0;
int nb_explored_optims = ast.nb_explored_optims;
while (children.size() == 0 && nb_optims_tried < NB_OPTIMIZATIONS && nb_explored_optims < max_depth)
{
optimization_type optim_type = DEFAULT_OPTIMIZATIONS_ORDER[nb_explored_optims % NB_OPTIMIZATIONS];
children = scheds_gen->generate_schedules(ast, optim_type);
nb_explored_optims++;
nb_optims_tried++;
}
// Stop if no more optimizations can be applied
if (children.size() == 0)
return ;
// Evaluate children and sort them from smallest to highest evaluation
for (syntax_tree *child : children)
{
child->nb_explored_optims = nb_explored_optims;
child->transform_ast();
child->evaluation = eval_func->evaluate(*child);
nb_explored_schedules++;
}
// Add the current AST to the list of children
syntax_tree *ast_copy = ast.copy_ast();
ast_copy->nb_explored_optims = nb_explored_optims;
children.push_back(ast_copy);
// Sort children from smallest evaluation to largest
std::sort(children.begin(), children.end(), [](syntax_tree *a, syntax_tree *b) {
return a->evaluation < b->evaluation;
});
for (int i = 0; i < beam_size; ++i)
schedules.push_back(children[i]);
// Stop if we reached the maximum depth
if (nb_explored_optims >= max_depth)
return ;
// Search recursively on the best children
for (int i = beam_size; i < children.size(); ++i)
delete children[i];
children.resize(std::min(beam_size, (int)children.size()));
for (syntax_tree *child : children)
{
child->search_depth = ast.search_depth + 1;
search(*child);
}
}
void beam_search_accuracy_evaluator::search(syntax_tree& ast)
{
if (ast.nb_explored_optims % NB_OPTIMIZATIONS == 0)
ast.clear_new_optimizations();
std::vector<syntax_tree*> children;
// Look for an optimization that can be applied
int nb_optims_tried = 0;
int nb_explored_optims = ast.nb_explored_optims;
while (children.size() == 0 && nb_optims_tried < NB_OPTIMIZATIONS && nb_explored_optims < max_depth)
{
optimization_type optim_type = DEFAULT_OPTIMIZATIONS_ORDER[nb_explored_optims % NB_OPTIMIZATIONS];
children = scheds_gen->generate_schedules(ast, optim_type);
nb_explored_optims++;
nb_optims_tried++;
}
// Stop if no more optimizations can be applied
if (children.size() == 0)
return ;
// Evaluate children and sort them from smallest to highest evaluation
for (syntax_tree *child : children)
{
child->nb_explored_optims = nb_explored_optims;
child->transform_ast();
child->evaluation = eval_func->evaluate(*child);
// We evaluate both by the model and by execution
model_evals_list.push_back(child->evaluation);
exec_evals_list.push_back(exec_eval->evaluate(*child));
if (child->evaluation < best_evaluation)
{
best_evaluation = child->evaluation;
best_ast = child;
}
nb_explored_schedules++;
}
// Stop if we reached the maximum depth
if (nb_explored_optims >= max_depth)
return ;
// Add the current AST to the list of children
syntax_tree *ast_copy = ast.copy_ast();
ast_copy->nb_explored_optims = nb_explored_optims;
children.push_back(ast_copy);
// Sort children from smallest evaluation to largest
std::sort(children.begin(), children.end(), [](syntax_tree *a, syntax_tree *b) {
return a->evaluation < b->evaluation;
});
// Search recursively on the best children
for (int i = beam_size; i < children.size(); ++i)
delete children[i];
children.resize(std::min(beam_size, (int)children.size()));
for (syntax_tree *child : children)
{
child->search_depth = ast.search_depth + 1;
search(*child);
}
}
}
<commit_msg>Minor update to schedule space sampling<commit_after>#include <tiramisu/auto_scheduler/search_method.h>
#include <random>
namespace tiramisu::auto_scheduler
{
void beam_search::search(syntax_tree& ast)
{
if (ast.nb_explored_optims % NB_OPTIMIZATIONS == 0)
ast.clear_new_optimizations();
std::vector<syntax_tree*> children;
// Look for an optimization that can be applied
int nb_optims_tried = 0;
int nb_explored_optims = ast.nb_explored_optims;
while (children.size() == 0 && nb_optims_tried < NB_OPTIMIZATIONS && nb_explored_optims < max_depth)
{
optimization_type optim_type = DEFAULT_OPTIMIZATIONS_ORDER[nb_explored_optims % NB_OPTIMIZATIONS];
children = scheds_gen->generate_schedules(ast, optim_type);
nb_explored_optims++;
nb_optims_tried++;
}
// Stop if no more optimizations can be applied
if (children.size() == 0)
return ;
// Evaluate children and sort them from smallest to highest evaluation
// evaluate while removing illegal versions
auto iterator = children.begin();
while (iterator != children.end())
{
(*iterator)->nb_explored_optims = nb_explored_optims;
(*iterator)->transform_ast();
if ((*iterator)->ast_is_legal() == false) {
// print deleted Ast
(*iterator)->print_previous_optims();
std::cout << "\n-----------" << std::endl;
(*iterator)->print_new_optims();
(*iterator)->print_ast();
(*iterator)->print_isl_states();
std::cout << "\n<illegal>\n";
delete (*iterator);
iterator = children.erase(iterator);
}
else {
// evaluate and print Ast
(*iterator)->evaluation = eval_func->evaluate(*(*iterator));
(*iterator)->print_previous_optims();
std::cout << "\n-----------" << std::endl;
(*iterator)->print_new_optims();
(*iterator)->print_ast();
std::cout << "Evaluation : " << (*iterator)->evaluation << std::endl << std::endl;
(*iterator)->print_isl_states();
(*iterator)->print_computations_accesses();
std::cout << "\n<legal>\n";
if ((*iterator)->evaluation < best_evaluation)
{
best_evaluation = (*iterator)->evaluation;
best_ast = (*iterator);
}
++iterator;
}
nb_explored_schedules++;
}
// Stop if we reached the maximum depth
if (nb_explored_optims >= max_depth)
return ;
// Add the current AST to the list of children
syntax_tree *ast_copy = ast.copy_ast();
ast_copy->nb_explored_optims = nb_explored_optims;
children.push_back(ast_copy);
// Sort children from smallest evaluation to largest
std::cout<<"\noriginal list\n" ;
for (syntax_tree *child : children)
{
std::cout<<child->evaluation<<"+";
}
std::sort(children.begin(), children.end(), [](syntax_tree *a, syntax_tree *b) {
return a->evaluation < b->evaluation;
});
// keep the top 'beam_size' children and delete the rest
for (int i = beam_size; i < children.size(); ++i)
delete children[i];
children.resize(std::min(beam_size, (int)children.size()));
std::cout<<"\nremaining list\n" ;
for (syntax_tree *child : children)
{
std::cout<<child->evaluation<<"+";
}
// Search recursively on the best children
for (syntax_tree *child : children)
{
child->search_depth = ast.search_depth + 1;
search(*child);
}
}
void beam_search::search_save(syntax_tree& ast, std::vector<std::string> *schedules_annotations)
{
if (ast.nb_explored_optims % NB_OPTIMIZATIONS == 0)
ast.clear_new_optimizations();
std::vector<syntax_tree*> children;
// Look for an optimization that can be applied
int nb_optims_tried = 0;
int nb_explored_optims = ast.nb_explored_optims;
while (children.size() == 0 && nb_optims_tried < NB_OPTIMIZATIONS && nb_explored_optims < max_depth)
{
optimization_type optim_type = DEFAULT_OPTIMIZATIONS_ORDER[nb_explored_optims % NB_OPTIMIZATIONS];
children = scheds_gen->generate_schedules(ast, optim_type);
nb_explored_optims++;
nb_optims_tried++;
}
// Stop if no more optimizations can be applied
if (children.size() == 0)
return ;
// Evaluate children and sort them from smallest to highest evaluation
// evaluate while removing illegal versions
auto iterator = children.begin();
while (iterator != children.end())
{
syntax_tree *child = *iterator;
child->nb_explored_optims = nb_explored_optims;
child->transform_ast();
if (child->ast_is_legal() == false) {
if (std::getenv("AS_VERBOSE")!=NULL)
if (std::stoi(std::getenv("AS_VERBOSE"))==1){
// print deleted Ast
child->print_previous_optims();
std::cout << "\n-----------" << std::endl;
child->print_new_optims();
child->print_ast();
child->print_isl_states();
std::cout << "\n<illegal>\n";
delete child;
iterator = children.erase(iterator);
}
}
else {
// print and evaluate Ast
if (std::getenv("AS_VERBOSE")!=NULL)
if (std::stoi(std::getenv("AS_VERBOSE"))==1){
child->print_previous_optims();
std::cout << "\n-----------" << std::endl;
child->print_new_optims();
child->print_ast();
child->print_isl_states();
std::cout << "\n<legal>\n";
child->print_computations_accesses();
}
child->evaluation = eval_func->evaluate(*child);
std::string schedule_annot = evaluate_by_learning_model::get_schedule_json(*child);
//remove the last two characters }\n
schedule_annot.pop_back();
schedule_annot.pop_back();
if (std::isfinite(child->evaluation)) // the evaluation is not finite mean that the schedule didn't run
schedule_annot += ", \n\"execution_time\" : " + std::to_string(child->evaluation) + "\n}\n";
else
schedule_annot += ", \n\"execution_time\" : null\n}\n";
schedules_annotations->push_back(schedule_annot);
if (std::getenv("AS_VERBOSE")!=NULL)
if (std::stoi(std::getenv("AS_VERBOSE"))==1){
std::cout << "Schedule number "<< schedules_annotations->size() << std::endl;
std::cout << "Evaluation : " << child->evaluation << std::endl;
std::cout << "===================================" << std::endl << std::endl;
}
if (std::isinf(child->evaluation))
std::cerr<< "Evaluation of schedule "<< schedules_annotations->size() <<" failed "<< std::endl;
if (child->evaluation < best_evaluation)
{
best_evaluation = child->evaluation;
best_ast = child;
}
++iterator;
}
nb_explored_schedules++;
}
// Stop if we reached the maximum depth
if (nb_explored_optims >= max_depth)
return ;
// Add the current AST to the list of children
syntax_tree *ast_copy = ast.copy_ast();
ast_copy->nb_explored_optims = nb_explored_optims;
children.push_back(ast_copy);
// Sort children from smallest evaluation to largest
std::sort(children.begin(), children.end(), [](syntax_tree *a, syntax_tree *b) {
return a->evaluation < b->evaluation;
});
// keep the top 'beam_size' children and delete the rest
for (int i = beam_size; i < children.size(); ++i)
delete children[i];
children.resize(std::min(beam_size, (int)children.size()));
// Search recursively on the best children
for (syntax_tree *child : children)
{
child->search_depth = ast.search_depth + 1;
search_save(*child, schedules_annotations);
}
}
void mcts::search(syntax_tree& ast)
{
std::default_random_engine rand_generator;
std::vector<syntax_tree*> samples;
std::vector<syntax_tree*> children;
std::vector<double> children_evals;
for (int epoch = 0; epoch < nb_samples; ++epoch)
{
// Starting from the initial ast, generate optimizations until reaching max_depth
syntax_tree *ast_sample = *
for (int depth = 0; depth < max_depth; ++depth)
{
optimization_type optim_type = DEFAULT_OPTIMIZATIONS_ORDER[depth % NB_OPTIMIZATIONS];
children = scheds_gen->generate_schedules(*ast_sample, optim_type);
if (children.empty())
continue;
children_evals.clear();
for (syntax_tree *child : children)
{
child->transform_ast();
child->evaluation = eval_func->evaluate(*child);
children_evals.push_back(child->evaluation);
nb_explored_schedules++;
}
// Add the current AST to the list of children
children.push_back(ast_sample->copy_ast());
children_evals.push_back(ast_sample->evaluation);
// Sample an AST
std::discrete_distribution<int> dist(children_evals.begin(), children_evals.end());
ast_sample = children[dist(rand_generator)];
samples.push_back(ast_sample);
}
}
if (samples.empty())
return ;
// Sort schedules with respect to evaluations
std::sort(samples.begin(), samples.end(), [](syntax_tree *a, syntax_tree *b) {
return a->evaluation < b->evaluation;
});
// Execute top-k schedules and return the best
for (int i = 0; i < topk; ++i)
{
float exec_time = exec_eval->evaluate(*samples[i]);
if (exec_time < best_evaluation)
{
best_evaluation = exec_time;
best_ast = samples[i];
}
}
}
void mcts::search_save(syntax_tree& ast, std::vector<std::string> *schedules_annotations)
{
std::cerr<< "mcts::search_save not yet implemented" << std::endl;
exit(1);
}
// -------------------------------------------------------------------------- //
void beam_search_topk::search(syntax_tree& ast)
{
// Do a beam search
beam_search_subroutine(ast);
// Sort schedules found
std::sort(schedules.begin(), schedules.end(), [](syntax_tree *a, syntax_tree *b) {
return a->evaluation < b->evaluation;
});
// Execute top-k schedules to find the best
for (int i = 0; i < topk; ++i)
{
float exec_time = exec_eval->evaluate(*schedules[i]);
if (exec_time < best_evaluation)
{
best_evaluation = exec_time;
best_ast = schedules[i];
}
}
}
void beam_search_topk::search_save(syntax_tree& ast, std::vector<std::string> *schedules_annotations)
{
std::cerr<< "beam_search_topk::search_save not yet implemented" << std::endl;
exit(1);
}
void beam_search_topk::beam_search_subroutine(syntax_tree& ast)
{
if (ast.nb_explored_optims % NB_OPTIMIZATIONS == 0)
ast.clear_new_optimizations();
std::vector<syntax_tree*> children;
// Look for an optimization that can be applied
int nb_optims_tried = 0;
int nb_explored_optims = ast.nb_explored_optims;
while (children.size() == 0 && nb_optims_tried < NB_OPTIMIZATIONS && nb_explored_optims < max_depth)
{
optimization_type optim_type = DEFAULT_OPTIMIZATIONS_ORDER[nb_explored_optims % NB_OPTIMIZATIONS];
children = scheds_gen->generate_schedules(ast, optim_type);
nb_explored_optims++;
nb_optims_tried++;
}
// Stop if no more optimizations can be applied
if (children.size() == 0)
return ;
// Evaluate children and sort them from smallest to highest evaluation
for (syntax_tree *child : children)
{
child->nb_explored_optims = nb_explored_optims;
child->transform_ast();
child->evaluation = eval_func->evaluate(*child);
nb_explored_schedules++;
}
// Add the current AST to the list of children
syntax_tree *ast_copy = ast.copy_ast();
ast_copy->nb_explored_optims = nb_explored_optims;
children.push_back(ast_copy);
// Sort children from smallest evaluation to largest
std::sort(children.begin(), children.end(), [](syntax_tree *a, syntax_tree *b) {
return a->evaluation < b->evaluation;
});
for (int i = 0; i < beam_size; ++i)
schedules.push_back(children[i]);
// Stop if we reached the maximum depth
if (nb_explored_optims >= max_depth)
return ;
// Search recursively on the best children
for (int i = beam_size; i < children.size(); ++i)
delete children[i];
children.resize(std::min(beam_size, (int)children.size()));
for (syntax_tree *child : children)
{
child->search_depth = ast.search_depth + 1;
search(*child);
}
}
void beam_search_accuracy_evaluator::search(syntax_tree& ast)
{
if (ast.nb_explored_optims % NB_OPTIMIZATIONS == 0)
ast.clear_new_optimizations();
std::vector<syntax_tree*> children;
// Look for an optimization that can be applied
int nb_optims_tried = 0;
int nb_explored_optims = ast.nb_explored_optims;
while (children.size() == 0 && nb_optims_tried < NB_OPTIMIZATIONS && nb_explored_optims < max_depth)
{
optimization_type optim_type = DEFAULT_OPTIMIZATIONS_ORDER[nb_explored_optims % NB_OPTIMIZATIONS];
children = scheds_gen->generate_schedules(ast, optim_type);
nb_explored_optims++;
nb_optims_tried++;
}
// Stop if no more optimizations can be applied
if (children.size() == 0)
return ;
// Evaluate children and sort them from smallest to highest evaluation
for (syntax_tree *child : children)
{
child->nb_explored_optims = nb_explored_optims;
child->transform_ast();
child->evaluation = eval_func->evaluate(*child);
// We evaluate both by the model and by execution
model_evals_list.push_back(child->evaluation);
exec_evals_list.push_back(exec_eval->evaluate(*child));
if (child->evaluation < best_evaluation)
{
best_evaluation = child->evaluation;
best_ast = child;
}
nb_explored_schedules++;
}
// Stop if we reached the maximum depth
if (nb_explored_optims >= max_depth)
return ;
// Add the current AST to the list of children
syntax_tree *ast_copy = ast.copy_ast();
ast_copy->nb_explored_optims = nb_explored_optims;
children.push_back(ast_copy);
// Sort children from smallest evaluation to largest
std::sort(children.begin(), children.end(), [](syntax_tree *a, syntax_tree *b) {
return a->evaluation < b->evaluation;
});
// Search recursively on the best children
for (int i = beam_size; i < children.size(); ++i)
delete children[i];
children.resize(std::min(beam_size, (int)children.size()));
for (syntax_tree *child : children)
{
child->search_depth = ast.search_depth + 1;
search(*child);
}
}
}
<|endoftext|>
|
<commit_before><commit_msg>Modify page_load_test so that reliability_tests.exe option --noclearprofile works.<commit_after><|endoftext|>
|
<commit_before><commit_msg>Fix typo from r23272.<commit_after><|endoftext|>
|
<commit_before>// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: jmarantz@google.com (Joshua Marantz)
#include "net/instaweb/apache/apache_slurp.h"
// Must precede any Apache includes, for now, due a conflict in
// the use of 'OK" as an Instaweb enum and as an Apache #define.
#include "net/instaweb/apache/header_util.h"
#include "net/instaweb/apache/apache_config.h"
#include "net/instaweb/apache/instaweb_context.h"
// TODO(jmarantz): serf_url_async_fetcher evidently sets
// 'gzip' unconditionally, and the response includes the 'gzip'
// encoding header, but serf unzips the response itself.
//
// I think the correct behavior is that our async fetcher should
// transmit the 'gzip' request header if it was specified in the call
// to StreamingFetch. This would be easy to fix.
//
// Unfortunately, serf 0.31 appears to unzip the content for us, which
// is not what we are asking for. And it leaves the 'gzip' response
// header in despite having unzipped it itself. I have tried later
// versions of serf, but the API is not compatible (easy to deal with)
// but the resulting binary has unresolved symbols. I am wondering
// whether we will have to go to libcurl.
//
// For now use wget when slurping additional files.
#include "base/logging.h"
#include "net/instaweb/apache/apache_server_context.h"
#include "net/instaweb/apache/apache_writer.h"
#include "net/instaweb/http/public/async_fetch.h"
#include "net/instaweb/http/public/http_dump_url_fetcher.h"
#include "net/instaweb/http/public/meta_data.h"
#include "net/instaweb/http/public/request_context.h"
#include "net/instaweb/http/public/request_headers.h"
#include "net/instaweb/http/public/response_headers.h"
#include "net/instaweb/http/public/url_async_fetcher.h"
#include "net/instaweb/public/global_constants.h"
#include "net/instaweb/rewriter/public/domain_lawyer.h"
#include "net/instaweb/rewriter/public/rewrite_query.h"
#include "net/instaweb/util/public/abstract_mutex.h"
#include "net/instaweb/util/public/basictypes.h"
#include "net/instaweb/util/public/chunking_writer.h"
#include "net/instaweb/util/public/condvar.h"
#include "net/instaweb/util/public/google_url.h"
#include "net/instaweb/util/public/message_handler.h"
#include "net/instaweb/util/public/query_params.h"
#include "net/instaweb/util/public/scoped_ptr.h"
#include "net/instaweb/util/public/string.h"
#include "net/instaweb/util/public/string_util.h"
#include "net/instaweb/util/public/thread_system.h"
#include "net/instaweb/util/public/timer.h"
// The Apache headers must be after instaweb headers. Otherwise, the
// compiler will complain
// "strtoul_is_not_a_portable_function_use_strtol_instead".
#include "http_protocol.h"
#include "httpd.h"
namespace net_instaweb {
namespace {
// Default handler when the file is not found
void SlurpDefaultHandler(request_rec* r) {
ap_set_content_type(r, "text/html; charset=utf-8");
GoogleString buf = StringPrintf(
"<html><head><title>Slurp Error</title></head>"
"<body><h1>Slurp failed</h1>\n"
"<p>host=%s\n"
"<p>uri=%s\n"
"</body></html>",
r->hostname, r->unparsed_uri);
ap_rputs(buf.c_str(), r);
r->status = HttpStatus::kNotFound;
r->status_line = "Not Found";
}
// Remove any mod-pagespeed-specific modifiers before we go to our slurped
// fetcher.
//
// TODO(jmarantz): share the string constants from mod_instaweb.cc and
// formalize the prefix-matching assumed here.
GoogleString RemoveModPageSpeedQueryParams(
const GoogleString& uri, const char* query_param_string) {
QueryParams query_params, stripped_query_params;
query_params.Parse(query_param_string);
bool rewrite_query_params = false;
for (int i = 0; i < query_params.size(); ++i) {
StringPiece name = query_params.name(i);
if (name.starts_with(RewriteQuery::kModPagespeed)) {
rewrite_query_params = true;
} else {
const GoogleString* value = query_params.value(i);
StringPiece value_piece; // NULL data by default.
if (value != NULL) {
value_piece = *value;
}
stripped_query_params.Add(name, value_piece);
}
}
GoogleString stripped_url;
if (rewrite_query_params) {
// TODO(jmarantz): It would be nice to use GoogleUrl to do this but
// it's not clear how it would help. Instead just hack the string.
GoogleString::size_type question_mark = uri.find('?');
CHECK(question_mark != GoogleString::npos);
stripped_url.append(uri.data(), question_mark); // does not include "?" yet
if (stripped_query_params.size() != 0) {
StrAppend(&stripped_url, "?", stripped_query_params.ToString());
}
} else {
stripped_url = uri;
}
return stripped_url;
}
// Some of the sites we are trying to slurp have pagespeed enabled already.
// We actually want to start with the non-pagespeed-enabled site. But we'd
// rather not send ModPagespeed=off to servers that are not expecting it.
// TODO(sligocki): Perhaps we should just send the "ModPagespeed: off" header
// which seems less intrusive.
class StrippingFetch : public StringAsyncFetch {
public:
StrippingFetch(const GoogleString& url_input,
const DomainLawyer* lawyer,
UrlAsyncFetcher* fetcher,
ThreadSystem* thread_system,
const RequestContextPtr& ctx,
MessageHandler* message_handler)
: StringAsyncFetch(ctx),
fetcher_(fetcher),
lawyer_(lawyer),
url_(url_input),
message_handler_(message_handler),
stripped_(false),
mutex_(thread_system->NewMutex()),
condvar_(mutex_->NewCondvar()) {
}
// Blocking fetch.
bool Fetch() {
// To test sharding domains from a slurp of a site that does not support
// sharded domains, we apply mapping origin domain here. Simply map all
// the shards back into the origin domain in pagespeed.conf.
GoogleString origin_url;
bool is_proxy = false;
if (lawyer_->MapOrigin(url_, &origin_url, &is_proxy)) {
url_ = origin_url;
GoogleUrl gurl(url_);
request_headers()->Replace(HttpAttributes::kHost, gurl.Host());
}
fetcher_->Fetch(url_, message_handler_, this);
{
ScopedMutex lock(mutex_.get());
while (!done()) {
condvar_->TimedWait(Timer::kSecondMs);
}
}
return success();
}
virtual void HandleDone(bool success) {
bool done = true;
if (!success) {
set_success(false);
} else if (stripped_) {
// Second pass -- declare completion.
set_success(true);
// TODO(sligocki): Check for kPageSpeedHeader as well.
} else if (response_headers()->Lookup1(kModPagespeedHeader) != NULL) {
// First pass -- the slurped site evidently had mod_pagespeed already
// enabled. Turn it off and re-fetch.
LOG(ERROR) << "URL " << url_ << " already has mod_pagespeed. Stripping.";
Reset(); // Clears output buffer and response_headers.
GoogleString::size_type question = url_.find('?');
if (question == GoogleString::npos) {
url_ += "?ModPagespeed=off";
} else {
url_ += "&ModPagespeed=off";
}
stripped_ = true;
// TODO(sligocki): This currently allows infinite looping behavior if
// someone returns X-Mod-Pagespeed headers unexpectedly.
fetcher_->Fetch(url_, message_handler_, this);
done = false;
} else {
// First-pass -- the origin site did not have mod_pagespeed so no need
// for a second pass.
set_success(true);
}
if (done) {
ScopedMutex lock(mutex_.get());
set_done(true);
condvar_->Signal();
// Don't "delete this" -- this is allocated on the stack in ApacheSlurp.
}
}
private:
UrlAsyncFetcher* fetcher_;
const DomainLawyer* lawyer_;
GoogleString url_;
MessageHandler* message_handler_;
bool stripped_;
scoped_ptr<ThreadSystem::CondvarCapableMutex> mutex_;
scoped_ptr<ThreadSystem::Condvar> condvar_;
DISALLOW_COPY_AND_ASSIGN(StrippingFetch);
};
} // namespace
void SlurpUrl(ApacheServerContext* server_context, request_rec* r) {
const char* url =
InstawebContext::MakeRequestUrl(*server_context->global_options(), r);
GoogleString stripped_url = RemoveModPageSpeedQueryParams(
url, r->parsed_uri.query);
// Figure out if we should be using a slurp fetcher rather than the default
// system fetcher.
UrlAsyncFetcher* fetcher = server_context->DefaultSystemFetcher();
scoped_ptr<HttpDumpUrlFetcher> slurp_fetcher;
ApacheConfig* config = server_context->config();
if (config->test_proxy() && !config->test_proxy_slurp().empty()) {
slurp_fetcher.reset(new HttpDumpUrlFetcher(
config->test_proxy_slurp(), server_context->file_system(),
server_context->timer()));
fetcher = slurp_fetcher.get();
}
MessageHandler* handler = server_context->message_handler();
RequestContextPtr request_context(
new RequestContext(server_context->thread_system()->NewMutex(),
server_context->timer()));
StrippingFetch fetch(stripped_url, server_context->config()->domain_lawyer(),
fetcher, server_context->thread_system(),
request_context, handler);
ApacheRequestToRequestHeaders(*r, fetch.request_headers());
if (fetch.Fetch()) {
// We always disable downstream header filters when sending out
// slurped resources, since we've captured them from the origin
// in the fetch we did to write the slurp.
ApacheWriter apache_writer(r);
apache_writer.set_disable_downstream_header_filters(true);
ChunkingWriter chunking_writer(
&apache_writer, server_context->config()->slurp_flush_limit());
apache_writer.OutputHeaders(fetch.response_headers());
chunking_writer.Write(fetch.buffer(), handler);
} else {
handler->Message(kInfo, "mod_pagespeed: slurp of url %s failed.\n"
"Request Headers: %s\n\nResponse Headers: %s",
stripped_url.c_str(),
fetch.request_headers()->ToString().c_str(),
fetch.response_headers()->ToString().c_str());
SlurpDefaultHandler(r);
}
}
} // namespace net_instaweb
<commit_msg>Re-slurp with ?ModPagespeed=off for ngx_pagespeed & PSS results.<commit_after>// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: jmarantz@google.com (Joshua Marantz)
#include "net/instaweb/apache/apache_slurp.h"
// Must precede any Apache includes, for now, due a conflict in
// the use of 'OK" as an Instaweb enum and as an Apache #define.
#include "net/instaweb/apache/header_util.h"
#include "net/instaweb/apache/apache_config.h"
#include "net/instaweb/apache/instaweb_context.h"
// TODO(jmarantz): serf_url_async_fetcher evidently sets
// 'gzip' unconditionally, and the response includes the 'gzip'
// encoding header, but serf unzips the response itself.
//
// I think the correct behavior is that our async fetcher should
// transmit the 'gzip' request header if it was specified in the call
// to StreamingFetch. This would be easy to fix.
//
// Unfortunately, serf 0.31 appears to unzip the content for us, which
// is not what we are asking for. And it leaves the 'gzip' response
// header in despite having unzipped it itself. I have tried later
// versions of serf, but the API is not compatible (easy to deal with)
// but the resulting binary has unresolved symbols. I am wondering
// whether we will have to go to libcurl.
//
// For now use wget when slurping additional files.
#include "base/logging.h"
#include "net/instaweb/apache/apache_server_context.h"
#include "net/instaweb/apache/apache_writer.h"
#include "net/instaweb/http/public/async_fetch.h"
#include "net/instaweb/http/public/http_dump_url_fetcher.h"
#include "net/instaweb/http/public/meta_data.h"
#include "net/instaweb/http/public/request_context.h"
#include "net/instaweb/http/public/request_headers.h"
#include "net/instaweb/http/public/response_headers.h"
#include "net/instaweb/http/public/url_async_fetcher.h"
#include "net/instaweb/public/global_constants.h"
#include "net/instaweb/rewriter/public/domain_lawyer.h"
#include "net/instaweb/rewriter/public/rewrite_query.h"
#include "net/instaweb/util/public/abstract_mutex.h"
#include "net/instaweb/util/public/basictypes.h"
#include "net/instaweb/util/public/chunking_writer.h"
#include "net/instaweb/util/public/condvar.h"
#include "net/instaweb/util/public/google_url.h"
#include "net/instaweb/util/public/message_handler.h"
#include "net/instaweb/util/public/query_params.h"
#include "net/instaweb/util/public/scoped_ptr.h"
#include "net/instaweb/util/public/string.h"
#include "net/instaweb/util/public/string_util.h"
#include "net/instaweb/util/public/thread_system.h"
#include "net/instaweb/util/public/timer.h"
// The Apache headers must be after instaweb headers. Otherwise, the
// compiler will complain
// "strtoul_is_not_a_portable_function_use_strtol_instead".
#include "http_protocol.h"
#include "httpd.h"
namespace net_instaweb {
namespace {
// Default handler when the file is not found
void SlurpDefaultHandler(request_rec* r) {
ap_set_content_type(r, "text/html; charset=utf-8");
GoogleString buf = StringPrintf(
"<html><head><title>Slurp Error</title></head>"
"<body><h1>Slurp failed</h1>\n"
"<p>host=%s\n"
"<p>uri=%s\n"
"</body></html>",
r->hostname, r->unparsed_uri);
ap_rputs(buf.c_str(), r);
r->status = HttpStatus::kNotFound;
r->status_line = "Not Found";
}
// Remove any mod-pagespeed-specific modifiers before we go to our slurped
// fetcher.
//
// TODO(jmarantz): share the string constants from mod_instaweb.cc and
// formalize the prefix-matching assumed here.
GoogleString RemoveModPageSpeedQueryParams(
const GoogleString& uri, const char* query_param_string) {
QueryParams query_params, stripped_query_params;
query_params.Parse(query_param_string);
bool rewrite_query_params = false;
for (int i = 0; i < query_params.size(); ++i) {
StringPiece name = query_params.name(i);
if (name.starts_with(RewriteQuery::kModPagespeed)) {
rewrite_query_params = true;
} else {
const GoogleString* value = query_params.value(i);
StringPiece value_piece; // NULL data by default.
if (value != NULL) {
value_piece = *value;
}
stripped_query_params.Add(name, value_piece);
}
}
GoogleString stripped_url;
if (rewrite_query_params) {
// TODO(jmarantz): It would be nice to use GoogleUrl to do this but
// it's not clear how it would help. Instead just hack the string.
GoogleString::size_type question_mark = uri.find('?');
CHECK(question_mark != GoogleString::npos);
stripped_url.append(uri.data(), question_mark); // does not include "?" yet
if (stripped_query_params.size() != 0) {
StrAppend(&stripped_url, "?", stripped_query_params.ToString());
}
} else {
stripped_url = uri;
}
return stripped_url;
}
// Some of the sites we are trying to slurp have pagespeed enabled already.
// We actually want to start with the non-pagespeed-enabled site. But we'd
// rather not send ModPagespeed=off to servers that are not expecting it.
// TODO(sligocki): Perhaps we should just send the "ModPagespeed: off" header
// which seems less intrusive.
class StrippingFetch : public StringAsyncFetch {
public:
StrippingFetch(const GoogleString& url_input,
const DomainLawyer* lawyer,
UrlAsyncFetcher* fetcher,
ThreadSystem* thread_system,
const RequestContextPtr& ctx,
MessageHandler* message_handler)
: StringAsyncFetch(ctx),
fetcher_(fetcher),
lawyer_(lawyer),
url_(url_input),
message_handler_(message_handler),
stripped_(false),
mutex_(thread_system->NewMutex()),
condvar_(mutex_->NewCondvar()) {
}
// Blocking fetch.
bool Fetch() {
// To test sharding domains from a slurp of a site that does not support
// sharded domains, we apply mapping origin domain here. Simply map all
// the shards back into the origin domain in pagespeed.conf.
GoogleString origin_url;
bool is_proxy = false;
if (lawyer_->MapOrigin(url_, &origin_url, &is_proxy)) {
url_ = origin_url;
GoogleUrl gurl(url_);
request_headers()->Replace(HttpAttributes::kHost, gurl.Host());
}
fetcher_->Fetch(url_, message_handler_, this);
{
ScopedMutex lock(mutex_.get());
while (!done()) {
condvar_->TimedWait(Timer::kSecondMs);
}
}
return success();
}
virtual void HandleDone(bool success) {
bool done = true;
if (!success) {
set_success(false);
} else if (stripped_) {
// Second pass -- declare completion.
set_success(true);
// TODO(sligocki): Check for kPageSpeedHeader as well.
} else if ((response_headers()->Lookup1(kModPagespeedHeader) != NULL) ||
(response_headers()->Lookup1(kPageSpeedHeader) != NULL)) {
// First pass -- the slurped site evidently had mod_pagespeed already
// enabled. Turn it off and re-fetch.
LOG(ERROR) << "URL " << url_ << " already has mod_pagespeed. Stripping.";
Reset(); // Clears output buffer and response_headers.
GoogleString::size_type question = url_.find('?');
if (question == GoogleString::npos) {
url_ += "?ModPagespeed=off";
} else {
url_ += "&ModPagespeed=off";
}
stripped_ = true;
// TODO(sligocki): This currently allows infinite looping behavior if
// someone returns X-Mod-Pagespeed headers unexpectedly.
fetcher_->Fetch(url_, message_handler_, this);
done = false;
} else {
// First-pass -- the origin site did not have mod_pagespeed so no need
// for a second pass.
set_success(true);
}
if (done) {
ScopedMutex lock(mutex_.get());
set_done(true);
condvar_->Signal();
// Don't "delete this" -- this is allocated on the stack in ApacheSlurp.
}
}
private:
UrlAsyncFetcher* fetcher_;
const DomainLawyer* lawyer_;
GoogleString url_;
MessageHandler* message_handler_;
bool stripped_;
scoped_ptr<ThreadSystem::CondvarCapableMutex> mutex_;
scoped_ptr<ThreadSystem::Condvar> condvar_;
DISALLOW_COPY_AND_ASSIGN(StrippingFetch);
};
} // namespace
void SlurpUrl(ApacheServerContext* server_context, request_rec* r) {
const char* url =
InstawebContext::MakeRequestUrl(*server_context->global_options(), r);
GoogleString stripped_url = RemoveModPageSpeedQueryParams(
url, r->parsed_uri.query);
// Figure out if we should be using a slurp fetcher rather than the default
// system fetcher.
UrlAsyncFetcher* fetcher = server_context->DefaultSystemFetcher();
scoped_ptr<HttpDumpUrlFetcher> slurp_fetcher;
ApacheConfig* config = server_context->config();
if (config->test_proxy() && !config->test_proxy_slurp().empty()) {
slurp_fetcher.reset(new HttpDumpUrlFetcher(
config->test_proxy_slurp(), server_context->file_system(),
server_context->timer()));
fetcher = slurp_fetcher.get();
}
MessageHandler* handler = server_context->message_handler();
RequestContextPtr request_context(
new RequestContext(server_context->thread_system()->NewMutex(),
server_context->timer()));
StrippingFetch fetch(stripped_url, server_context->config()->domain_lawyer(),
fetcher, server_context->thread_system(),
request_context, handler);
ApacheRequestToRequestHeaders(*r, fetch.request_headers());
if (fetch.Fetch()) {
// We always disable downstream header filters when sending out
// slurped resources, since we've captured them from the origin
// in the fetch we did to write the slurp.
ApacheWriter apache_writer(r);
apache_writer.set_disable_downstream_header_filters(true);
ChunkingWriter chunking_writer(
&apache_writer, server_context->config()->slurp_flush_limit());
apache_writer.OutputHeaders(fetch.response_headers());
chunking_writer.Write(fetch.buffer(), handler);
} else {
handler->Message(kInfo, "mod_pagespeed: slurp of url %s failed.\n"
"Request Headers: %s\n\nResponse Headers: %s",
stripped_url.c_str(),
fetch.request_headers()->ToString().c_str(),
fetch.response_headers()->ToString().c_str());
SlurpDefaultHandler(r);
}
}
} // namespace net_instaweb
<|endoftext|>
|
<commit_before>#include "Processor.h"
#include "sim/config.h"
namespace Simulator
{
#define NUM_COUNTERS 18
size_t Processor::PerfCounters::GetSize() const { return NUM_COUNTERS * sizeof(Integer); }
Result Processor::PerfCounters::Read(MemAddr address, void *data, MemSize size, LFID fid, TID tid, const RegAddr& writeback)
{
if (size != sizeof(Integer) || address % sizeof(Integer) != 0 || address / sizeof(Integer) >= NUM_COUNTERS)
{
throw exceptf<InvalidArgumentException>(*this, "Invalid read to performance counter address by F%u/T%u: %#016llx/%u",
(unsigned)fid, (unsigned)tid, (unsigned long long)address, (unsigned)size);
}
address /= sizeof(Integer);
Processor& cpu = *static_cast<Processor*>(GetParent());
const size_t placeSize = cpu.m_familyTable[fid].placeSize;
const size_t placeStart = (cpu.m_pid / placeSize) * placeSize;
const size_t placeEnd = placeStart + placeSize;
Integer value;
switch (address)
{
case 0:
{
// Return the number of elapsed cycles
value = (Integer)GetKernel()->GetCycleNo();
}
break;
case 1:
{
// Return the number of executed instructions on all cores
Integer ops = 0;
for (size_t i = placeStart; i < placeEnd; ++i)
{
ops += cpu.m_grid[i]->GetPipeline().GetOp();
}
value = ops;
}
break;
case 2:
{
// Return the number of issued FP instructions on all cores
Integer flops = 0;
for (size_t i = placeStart; i < placeEnd; ++i)
{
flops += cpu.m_grid[i]->GetPipeline().GetFlop();
}
value = flops;
}
break;
case 3:
{
// Return the number of completed loads on all cores
uint64_t n = 0, dummy;
for (size_t i = placeStart; i < placeEnd; ++i)
{
cpu.m_grid[i]->GetPipeline().CollectMemOpStatistics(n, dummy, dummy, dummy);
}
value = (Integer)n;
}
break;
case 4:
{
// Return the number of completed stores on all cores
uint64_t n = 0, dummy;
for (size_t i = placeStart; i < placeEnd; ++i)
{
cpu.m_grid[i]->GetPipeline().CollectMemOpStatistics(dummy, n, dummy, dummy);
}
value = (Integer)n;
}
break;
case 5:
{
// Return the number of successfully loaded bytes on all cores
uint64_t n = 0, dummy;
for (size_t i = placeStart; i < placeEnd; ++i)
{
cpu.m_grid[i]->GetPipeline().CollectMemOpStatistics(dummy, dummy, n, dummy);
}
value = (Integer)n;
}
break;
case 6:
{
// Return the number of successfully stored bytes on all cores
uint64_t n = 0, dummy;
for (size_t i = placeStart; i < placeEnd; ++i)
{
cpu.m_grid[i]->GetPipeline().CollectMemOpStatistics(dummy, dummy, dummy, n);
}
value = (Integer)n;
}
break;
case 7:
{
// Return the number of memory loads overall from L1 to L2 (cache lines)
uint64_t n = 0, dummy;
cpu.m_memory.GetMemoryStatistics(n, dummy, dummy, dummy, dummy, dummy);
value = (Integer)n;
}
break;
case 8:
{
// Return the number of memory stores overall from L1 to L2 (cache lines)
uint64_t n = 0, dummy;
cpu.m_memory.GetMemoryStatistics(dummy, n, dummy, dummy, dummy, dummy);
value = (Integer)n;
}
break;
case 9:
{
value = (Integer)placeSize;
}
break;
case 10:
{
// Return the total cumulative allocated thread slots
Integer alloc = 0;
for (size_t i = placeStart; i < placeEnd; ++i)
{
alloc += cpu.m_grid[i]->GetTotalThreadsAllocated();
}
value = alloc;
}
break;
case 11:
{
// Return the total cumulative allocated thread slots
Integer alloc = 0;
for (size_t i = placeStart; i < placeEnd; ++i)
{
alloc += cpu.m_grid[i]->GetTotalFamiliesAllocated();
}
value = alloc;
}
break;
case 12:
{
// Return the total cumulative exclusive allocate queue size
Integer alloc = 0;
for (size_t i = placeStart; i < placeEnd; ++i)
{
alloc += cpu.m_grid[i]->GetTotalAllocateExQueueSize();
}
value = alloc;
}
break;
case 13:
case 14:
case 15:
// slots free to reuse
value = (Integer)-1;
break;
case 16:
{
// Return the number of memory loads overall from external memory (cache lines)
uint64_t n = 0, dummy;
cpu.m_memory.GetMemoryStatistics(dummy, dummy, dummy, dummy, n, dummy);
value = (Integer)n;
}
break;
case 17:
{
// Return the number of memory stores overall to external memory (cache lines)
uint64_t n = 0, dummy;
cpu.m_memory.GetMemoryStatistics(dummy, dummy, dummy, dummy, dummy, n);
value = (Integer)n;
}
break;
default:
value = 0;
}
DebugIOWrite("Read counter %u by F%u/T%u: %#016llx (%llu)",
(unsigned)address, (unsigned)fid, (unsigned)tid,
(unsigned long long)value, (unsigned long long)value);
COMMIT{
if (address == 0)
{
++m_nCycleSampleOps;
}
else
{
++m_nOtherSampleOps;
}
}
SerializeRegister(RT_INTEGER, value, data, sizeof(Integer));
return SUCCESS;
}
Processor::PerfCounters::PerfCounters(Processor& parent, Config& config)
: Processor::MMIOComponent("perfcounters", parent, parent.GetClock()),
m_nCycleSampleOps(0),
m_nOtherSampleOps(0)
{
parent.WriteASR(ASR_NUM_PERFCOUNTERS, NUM_COUNTERS);
parent.WriteASR(ASR_PERFCOUNTERS_BASE, config.getValue<MemAddr>(*this, "MMIO_BaseAddr"));
RegisterSampleVariableInObject(m_nCycleSampleOps, SVC_CUMULATIVE);
RegisterSampleVariableInObject(m_nOtherSampleOps, SVC_CUMULATIVE);
}
}
<commit_msg>[mgsim] Reinstate the short-latency sampling of real time.<commit_after>#include "Processor.h"
#include "sim/config.h"
#include <sys/time.h>
#include <ctime>
namespace Simulator
{
#define NUM_COUNTERS 18
size_t Processor::PerfCounters::GetSize() const { return NUM_COUNTERS * sizeof(Integer); }
Result Processor::PerfCounters::Read(MemAddr address, void *data, MemSize size, LFID fid, TID tid, const RegAddr& writeback)
{
if (size != sizeof(Integer) || address % sizeof(Integer) != 0 || address / sizeof(Integer) >= NUM_COUNTERS)
{
throw exceptf<InvalidArgumentException>(*this, "Invalid read to performance counter address by F%u/T%u: %#016llx/%u",
(unsigned)fid, (unsigned)tid, (unsigned long long)address, (unsigned)size);
}
address /= sizeof(Integer);
Processor& cpu = *static_cast<Processor*>(GetParent());
const size_t placeSize = cpu.m_familyTable[fid].placeSize;
const size_t placeStart = (cpu.m_pid / placeSize) * placeSize;
const size_t placeEnd = placeStart + placeSize;
Integer value;
switch (address)
{
case 0:
{
// Return the number of elapsed cycles
value = (Integer)GetKernel()->GetCycleNo();
}
break;
case 1:
{
// Return the number of executed instructions on all cores
Integer ops = 0;
for (size_t i = placeStart; i < placeEnd; ++i)
{
ops += cpu.m_grid[i]->GetPipeline().GetOp();
}
value = ops;
}
break;
case 2:
{
// Return the number of issued FP instructions on all cores
Integer flops = 0;
for (size_t i = placeStart; i < placeEnd; ++i)
{
flops += cpu.m_grid[i]->GetPipeline().GetFlop();
}
value = flops;
}
break;
case 3:
{
// Return the number of completed loads on all cores
uint64_t n = 0, dummy;
for (size_t i = placeStart; i < placeEnd; ++i)
{
cpu.m_grid[i]->GetPipeline().CollectMemOpStatistics(n, dummy, dummy, dummy);
}
value = (Integer)n;
}
break;
case 4:
{
// Return the number of completed stores on all cores
uint64_t n = 0, dummy;
for (size_t i = placeStart; i < placeEnd; ++i)
{
cpu.m_grid[i]->GetPipeline().CollectMemOpStatistics(dummy, n, dummy, dummy);
}
value = (Integer)n;
}
break;
case 5:
{
// Return the number of successfully loaded bytes on all cores
uint64_t n = 0, dummy;
for (size_t i = placeStart; i < placeEnd; ++i)
{
cpu.m_grid[i]->GetPipeline().CollectMemOpStatistics(dummy, dummy, n, dummy);
}
value = (Integer)n;
}
break;
case 6:
{
// Return the number of successfully stored bytes on all cores
uint64_t n = 0, dummy;
for (size_t i = placeStart; i < placeEnd; ++i)
{
cpu.m_grid[i]->GetPipeline().CollectMemOpStatistics(dummy, dummy, dummy, n);
}
value = (Integer)n;
}
break;
case 7:
{
// Return the number of memory loads overall from L1 to L2 (cache lines)
uint64_t n = 0, dummy;
cpu.m_memory.GetMemoryStatistics(n, dummy, dummy, dummy, dummy, dummy);
value = (Integer)n;
}
break;
case 8:
{
// Return the number of memory stores overall from L1 to L2 (cache lines)
uint64_t n = 0, dummy;
cpu.m_memory.GetMemoryStatistics(dummy, n, dummy, dummy, dummy, dummy);
value = (Integer)n;
}
break;
case 9:
{
value = (Integer)placeSize;
}
break;
case 10:
{
// Return the total cumulative allocated thread slots
Integer alloc = 0;
for (size_t i = placeStart; i < placeEnd; ++i)
{
alloc += cpu.m_grid[i]->GetTotalThreadsAllocated();
}
value = alloc;
}
break;
case 11:
{
// Return the total cumulative allocated thread slots
Integer alloc = 0;
for (size_t i = placeStart; i < placeEnd; ++i)
{
alloc += cpu.m_grid[i]->GetTotalFamiliesAllocated();
}
value = alloc;
}
break;
case 12:
{
// Return the total cumulative exclusive allocate queue size
Integer alloc = 0;
for (size_t i = placeStart; i < placeEnd; ++i)
{
alloc += cpu.m_grid[i]->GetTotalAllocateExQueueSize();
}
value = alloc;
}
break;
case 13:
{
// Return the Unix time
value = (Integer)time(0);
}
break;
case 14:
{
// Return the local date as a packed struct
// bits 0-4: day in month
// bits 5-8: month in year
// bits 9-31: year from 1900
time_t c = time(0);
struct tm * tm = gmtime(&c);
value = (Integer)tm->tm_mday |
((Integer)tm->tm_mon << 5) |
((Integer)tm->tm_year << 9);
}
break;
case 15:
{
// Return the local time as a packed struct
// bits 0-14 = microseconds / 2^5 (topmost 15 bits)
// bits 15-20 = seconds
// bits 21-26 = minutes
// bits 27-31 = hours
struct timeval tv;
gettimeofday(&tv, 0);
struct tm * tm = gmtime(&tv.tv_sec);
// get topmost 15 bits of precision of the usec field
// usec is 0-999999; so it has 20 bits of value
Integer usec = (tv.tv_usec >> 20-15) & 0x7fff;
value = usec | (tm->tm_sec << 15) | (tm->tm_min << 21) | (tm->tm_hour << 27);
}
break;
case 16:
{
// Return the number of memory loads overall from external memory (cache lines)
uint64_t n = 0, dummy;
cpu.m_memory.GetMemoryStatistics(dummy, dummy, dummy, dummy, n, dummy);
value = (Integer)n;
}
break;
case 17:
{
// Return the number of memory stores overall to external memory (cache lines)
uint64_t n = 0, dummy;
cpu.m_memory.GetMemoryStatistics(dummy, dummy, dummy, dummy, dummy, n);
value = (Integer)n;
}
break;
default:
value = 0;
}
DebugIOWrite("Read counter %u by F%u/T%u: %#016llx (%llu)",
(unsigned)address, (unsigned)fid, (unsigned)tid,
(unsigned long long)value, (unsigned long long)value);
COMMIT{
if (address == 0)
{
++m_nCycleSampleOps;
}
else
{
++m_nOtherSampleOps;
}
}
SerializeRegister(RT_INTEGER, value, data, sizeof(Integer));
return SUCCESS;
}
Processor::PerfCounters::PerfCounters(Processor& parent, Config& config)
: Processor::MMIOComponent("perfcounters", parent, parent.GetClock()),
m_nCycleSampleOps(0),
m_nOtherSampleOps(0)
{
parent.WriteASR(ASR_NUM_PERFCOUNTERS, NUM_COUNTERS);
parent.WriteASR(ASR_PERFCOUNTERS_BASE, config.getValue<MemAddr>(*this, "MMIO_BaseAddr"));
RegisterSampleVariableInObject(m_nCycleSampleOps, SVC_CUMULATIVE);
RegisterSampleVariableInObject(m_nOtherSampleOps, SVC_CUMULATIVE);
}
}
<|endoftext|>
|
<commit_before>//
// Created by Rui Wang on 16-4-29.
//
#include "hybrid_scan_executor.h"
#include <memory>
#include <utility>
#include <vector>
#include "backend/common/types.h"
#include "backend/executor/logical_tile.h"
#include "backend/executor/logical_tile_factory.h"
#include "backend/executor/executor_context.h"
#include "backend/expression/abstract_expression.h"
#include "backend/expression/container_tuple.h"
#include "backend/planner/hybrid_scan_plan.h"
#include "backend/storage/data_table.h"
#include "backend/storage/tile_group_header.h"
#include "backend/storage/tile.h"
#include "backend/concurrency/transaction_manager_factory.h"
#include "backend/common/logger.h"
namespace peloton {
namespace executor {
HybridScanExecutor::HybridScanExecutor(const planner::AbstractPlan *node,
ExecutorContext *executor_context)
: AbstractScanExecutor(node, executor_context), indexed_tile_offset_(START_OID) {}
bool HybridScanExecutor::DInit() {
const planner::HybridScanPlan &node = GetPlanNode<planner::HybridScanPlan>();
table_ = node.GetDataTable();
index_ = node.GetDataIndex();
if (table_ != nullptr && index_ == nullptr) {
type_ = SEQ;
current_tile_group_offset_ = START_OID;
if (table_ != nullptr) {
table_tile_group_count_ = table_->GetTileGroupCount();
if (column_ids_.empty()) {
column_ids_.resize(table_->GetSchema()->GetColumnCount());
std::iota(column_ids_.begin(), column_ids_.end(), 0);
}
}
} else if (table_ == nullptr && index_ != nullptr) {
type_ = INDEX;
} else {
type_ = HYBRID;
}
return true;
}
bool HybridScanExecutor::DExecute() {
if (type_ == SEQ) {
// assume do not read from a logical tile.
assert(children_.size() == 0);
LOG_INFO("Hybrid executor, Seq Scan :: 0 child, %d tile groups ", table_tile_group_count_);
assert(table_ != nullptr);
assert(column_ids_.size() > 0);
auto &transaction_manager =
concurrency::TransactionManagerFactory::GetInstance();
// Retrieve next tile group.
while (current_tile_group_offset_ < table_tile_group_count_) {
auto tile_group =
table_->GetTileGroup(current_tile_group_offset_++);
auto tile_group_header = tile_group->GetHeader();
oid_t active_tuple_count = tile_group->GetNextTupleSlot();
// Construct position list by looping through tile group
// and applying the predicate.
std::vector<oid_t> position_list;
for (oid_t tuple_id = 0; tuple_id < active_tuple_count; tuple_id++) {
ItemPointer location(tile_group->GetTileGroupId(), tuple_id);
// check transaction visibility
if (transaction_manager.IsVisible(tile_group_header, tuple_id)) {
// if the tuple is visible, then perform predicate evaluation.
if (predicate_ == nullptr) {
position_list.push_back(tuple_id);
auto res = transaction_manager.PerformRead(location);
if (!res) {
transaction_manager.SetTransactionResult(RESULT_FAILURE);
return res;
}
} else {
expression::ContainerTuple<storage::TileGroup> tuple(
tile_group.get(), tuple_id);
auto eval = predicate_->Evaluate(&tuple, nullptr, executor_context_)
.IsTrue();
if (eval == true) {
position_list.push_back(tuple_id);
auto res = transaction_manager.PerformRead(location);
if (!res) {
transaction_manager.SetTransactionResult(RESULT_FAILURE);
return res;
}
}
}
}
}
// Don't return empty tiles
if (position_list.size() == 0) {
continue;
}
// Construct logical tile.
std::unique_ptr<LogicalTile> logical_tile(LogicalTileFactory::GetTile());
logical_tile->AddColumns(tile_group, column_ids_);
logical_tile->AddPositionList(std::move(position_list));
SetOutput(logical_tile.release());
return true;
}
}
return false;
}
} // namespace executor
} // namespace peloton
<commit_msg>remove transaction<commit_after>//
// Created by Rui Wang on 16-4-29.
//
#include "hybrid_scan_executor.h"
#include <memory>
#include <utility>
#include <vector>
#include "backend/common/types.h"
#include "backend/executor/logical_tile.h"
#include "backend/executor/logical_tile_factory.h"
#include "backend/executor/executor_context.h"
#include "backend/expression/abstract_expression.h"
#include "backend/expression/container_tuple.h"
#include "backend/planner/hybrid_scan_plan.h"
#include "backend/storage/data_table.h"
#include "backend/storage/tile_group_header.h"
#include "backend/storage/tile.h"
#include "backend/concurrency/transaction_manager_factory.h"
#include "backend/common/logger.h"
namespace peloton {
namespace executor {
HybridScanExecutor::HybridScanExecutor(const planner::AbstractPlan *node,
ExecutorContext *executor_context)
: AbstractScanExecutor(node, executor_context), indexed_tile_offset_(START_OID) {}
bool HybridScanExecutor::DInit() {
const planner::HybridScanPlan &node = GetPlanNode<planner::HybridScanPlan>();
table_ = node.GetDataTable();
index_ = node.GetDataIndex();
if (table_ != nullptr && index_ == nullptr) {
type_ = SEQ;
current_tile_group_offset_ = START_OID;
if (table_ != nullptr) {
table_tile_group_count_ = table_->GetTileGroupCount();
if (column_ids_.empty()) {
column_ids_.resize(table_->GetSchema()->GetColumnCount());
std::iota(column_ids_.begin(), column_ids_.end(), 0);
}
}
} else if (table_ == nullptr && index_ != nullptr) {
type_ = INDEX;
} else {
type_ = HYBRID;
}
return true;
}
bool HybridScanExecutor::DExecute() {
if (type_ == SEQ) {
// assume do not read from a logical tile.
assert(children_.size() == 0);
LOG_INFO("Hybrid executor, Seq Scan :: 0 child");
assert(table_ != nullptr);
assert(column_ids_.size() > 0);
auto &transaction_manager =
concurrency::TransactionManagerFactory::GetInstance();
// Retrieve next tile group.
while (current_tile_group_offset_ < table_tile_group_count_) {
auto tile_group =
table_->GetTileGroup(current_tile_group_offset_++);
auto tile_group_header = tile_group->GetHeader();
oid_t active_tuple_count = tile_group->GetNextTupleSlot();
// Construct position list by looping through tile group
// and applying the predicate.
std::vector<oid_t> position_list;
for (oid_t tuple_id = 0; tuple_id < active_tuple_count; tuple_id++) {
ItemPointer location(tile_group->GetTileGroupId(), tuple_id);
// check transaction visibility
// if (transaction_manager.IsVisible(tile_group_header, tuple_id)) {
// if the tuple is visible, then perform predicate evaluation.
if (predicate_ == nullptr) {
position_list.push_back(tuple_id);
/*auto res = transaction_manager.PerformRead(location);
if (!res) {
transaction_manager.SetTransactionResult(RESULT_FAILURE);
return res;
}*/
} else {
expression::ContainerTuple<storage::TileGroup> tuple(
tile_group.get(), tuple_id);
auto eval = predicate_->Evaluate(&tuple, nullptr, executor_context_)
.IsTrue();
if (eval == true) {
position_list.push_back(tuple_id);
/*auto res = transaction_manager.PerformRead(location);
if (!res) {
transaction_manager.SetTransactionResult(RESULT_FAILURE);
return res;
}*/
}
}
// }
}
// Don't return empty tiles
if (position_list.size() == 0) {
continue;
}
// Construct logical tile.
std::unique_ptr<LogicalTile> logical_tile(LogicalTileFactory::GetTile());
logical_tile->AddColumns(tile_group, column_ids_);
logical_tile->AddPositionList(std::move(position_list));
LOG_INFO("Hybrid executor, Seq Scan :: Got a logical tile");
SetOutput(logical_tile.release());
return true;
}
}
return false;
}
} // namespace executor
} // namespace peloton
<|endoftext|>
|
<commit_before>// @(#)root/base:$Name: $:$Id: TRegexp.cxx,v 1.9 2002/09/30 17:31:46 rdm Exp $
// Author: Fons Rademakers 04/08/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TRegexp //
// //
// Regular expression class. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TRegexp.h"
#include "TString.h"
#include "TError.h"
const unsigned TRegexp::fgMaxpat = 2048;
ClassImp(TRegexp)
//______________________________________________________________________________
TRegexp::TRegexp(const char *re, Bool_t wildcard)
{
// Create a regular expression from the input string. If wildcard is true
// then the input string contains a wildcard expression (see MakeWildcard()).
if (wildcard)
GenPattern(MakeWildcard(re));
else
GenPattern(re);
}
//______________________________________________________________________________
TRegexp::TRegexp(const TString& re)
{
// Create a regular expression from a TString.
GenPattern(re.Data());
}
//______________________________________________________________________________
TRegexp::TRegexp(const TRegexp& r)
{
// Copy ctor.
CopyPattern(r);
}
//______________________________________________________________________________
TRegexp::~TRegexp()
{
delete [] fPattern;
}
//______________________________________________________________________________
TRegexp& TRegexp::operator=(const TRegexp& r)
{
// Assignment operator.
if (this != &r) {
delete [] fPattern;
CopyPattern(r);
}
return *this;
}
//______________________________________________________________________________
TRegexp& TRegexp::operator=(const char *str)
{
// Assignment operator taking a char* and assigning it to a regexp.
delete [] fPattern;
GenPattern(str);
return *this;
}
//______________________________________________________________________________
TRegexp& TRegexp::operator=(const TString &str)
{
// Assignment operator taking a TString.
delete [] fPattern;
GenPattern(str.Data());
return *this;
}
//______________________________________________________________________________
void TRegexp::GenPattern(const char *str)
{
// Generate the regular expression pattern.
fPattern = new Pattern_t[fgMaxpat];
int error = ::Makepat(str, fPattern, fgMaxpat);
fStat = (error < 3) ? (EStatVal) error : kToolong;
}
//______________________________________________________________________________
void TRegexp::CopyPattern(const TRegexp& r)
{
// Copy the regular expression pattern.
fPattern = new Pattern_t[fgMaxpat];
memcpy(fPattern, r.fPattern, fgMaxpat * sizeof(Pattern_t));
fStat = r.fStat;
}
//______________________________________________________________________________
const char *TRegexp::MakeWildcard(const char *re)
{
// This routine transforms a wildcarding regular expression into
// a general regular expression used for pattern matching.
// When using wildcards the regular expression is assumed to be
// preceded by a "^" (BOL) and terminated by a "$" (EOL). Also, all
// "*"'s (closures) are assumed to be preceded by a "." (i.e. any character,
// except "/"'s) and all .'s are escaped (so *.ps is different from *.eps).
// The special treatment of "/" allows the easy matching of pathnames, e.g.
// "*.root" will match "aap.root", but not "pipo/aap.root".
static char buf[fgMaxpat];
char *s = buf;
int len = strlen(re);
if (!re || !len) return "";
for (int i = 0; i < len; i++) {
if (i == 0 && re[i] != '^')
*s++ = '^';
if (re[i] == '*') {
#ifndef R__WIN32
//const char *wc = "[a-zA-Z0-9-+_\\.,: []<>]";
const char *wc = "[^/]";
#else
//const char *wc = "[a-zA-Z0-9-+_., []<>]";
const char *wc = "[^\\/:]";
#endif
strcpy(s, wc);
s += strlen(wc);
}
if (re[i] == '.')
*s++ = '\\';
*s++ = re[i];
if (i == len-1 && re[i] != '$')
*s++ = '$';
}
*s = '\0';
return buf;
}
//______________________________________________________________________________
Ssiz_t TRegexp::Index(const TString& string, Ssiz_t* len, Ssiz_t i) const
{
// Find the first occurance of the regexp in string and return the position.
// Len is length of the matched string and i is the offset at which the
// matching should start.
if (fStat != kOK)
Error("TRegexp::Index", "Bad Regular Expression");
const char* startp;
const char* s = string.Data();
Ssiz_t slen = string.Length();
if (slen < i) return kNPOS;
const char* endp = ::Matchs(s+i, slen-i, fPattern, &startp);
if (endp) {
*len = endp - startp;
return startp - s;
} else {
*len = 0;
return kNPOS;
}
}
//______________________________________________________________________________
TRegexp::EStatVal TRegexp::Status()
{
// Check status of regexp.
EStatVal temp = fStat;
fStat = kOK;
return temp;
}
//////////////////////////////////////////////////////////////////////////
// //
// TString member functions, put here so the linker will include //
// them only if regular expressions are used. //
// //
//////////////////////////////////////////////////////////////////////////
//______________________________________________________________________________
Ssiz_t TString::Index(const TRegexp& r, Ssiz_t start) const
{
// Find the first occurance of the regexp in string and return the position.
// Start is the offset at which the search should start.
Ssiz_t len;
return r.Index(*this, &len, start); // len not used
}
//______________________________________________________________________________
Ssiz_t TString::Index(const TRegexp& r, Ssiz_t* extent, Ssiz_t start) const
{
// Find the first occurance of the regexp in string and return the position.
// Extent is length of the matched string and start is the offset at which
// the matching should start.
return r.Index(*this, extent, start);
}
//______________________________________________________________________________
TSubString TString::operator()(const TRegexp& r, Ssiz_t start)
{
// Return the substring found by applying the regexp starting at start.
Ssiz_t len;
Ssiz_t begin = Index(r, &len, start);
return TSubString(*this, begin, len);
}
//______________________________________________________________________________
TSubString TString::operator()(const TRegexp& r)
{
// Return the substring found by applying the regexp.
return (*this)(r,0);
}
//______________________________________________________________________________
TSubString TString::operator()(const TRegexp& r, Ssiz_t start) const
{
// Return the substring found by applying the regexp starting at start.
Ssiz_t len;
Ssiz_t begin = Index(r, &len, start);
return TSubString(*this, begin, len);
}
//______________________________________________________________________________
TSubString TString::operator()(const TRegexp& r) const
{
// Return the substring found by applying the regexp.
return (*this)(r,0);
}
<commit_msg>Document TRegexp<commit_after>// @(#)root/base:$Name: $:$Id: TRegexp.cxx,v 1.10 2002/10/02 12:33:28 rdm Exp $
// Author: Fons Rademakers 04/08/95
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TRegexp //
// //
// Regular expression class. //
// //
// '^' // start-of-line anchor //
// '$' // end-of-line anchor //
// '.' // matches any character //
// '[' // start a character class //
// ']' // end a character class //
// '^' // negates character class if 1st character //
// '*' // Kleene closure (matches 0 or more) //
// '+' // Positive closure (1 or more) //
// '?' // Optional closure (0 or 1) //
// //
// Standard classes like [:alnum:], [:alpha:], etc. are not supported,//
// only [a-zA-Z], [^ntf] and so on. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TRegexp.h"
#include "TString.h"
#include "TError.h"
const unsigned TRegexp::fgMaxpat = 2048;
ClassImp(TRegexp)
//______________________________________________________________________________
TRegexp::TRegexp(const char *re, Bool_t wildcard)
{
// Create a regular expression from the input string. If wildcard is true
// then the input string contains a wildcard expression (see MakeWildcard()).
if (wildcard)
GenPattern(MakeWildcard(re));
else
GenPattern(re);
}
//______________________________________________________________________________
TRegexp::TRegexp(const TString& re)
{
// Create a regular expression from a TString.
GenPattern(re.Data());
}
//______________________________________________________________________________
TRegexp::TRegexp(const TRegexp& r)
{
// Copy ctor.
CopyPattern(r);
}
//______________________________________________________________________________
TRegexp::~TRegexp()
{
delete [] fPattern;
}
//______________________________________________________________________________
TRegexp& TRegexp::operator=(const TRegexp& r)
{
// Assignment operator.
if (this != &r) {
delete [] fPattern;
CopyPattern(r);
}
return *this;
}
//______________________________________________________________________________
TRegexp& TRegexp::operator=(const char *str)
{
// Assignment operator taking a char* and assigning it to a regexp.
delete [] fPattern;
GenPattern(str);
return *this;
}
//______________________________________________________________________________
TRegexp& TRegexp::operator=(const TString &str)
{
// Assignment operator taking a TString.
delete [] fPattern;
GenPattern(str.Data());
return *this;
}
//______________________________________________________________________________
void TRegexp::GenPattern(const char *str)
{
// Generate the regular expression pattern.
fPattern = new Pattern_t[fgMaxpat];
int error = ::Makepat(str, fPattern, fgMaxpat);
fStat = (error < 3) ? (EStatVal) error : kToolong;
}
//______________________________________________________________________________
void TRegexp::CopyPattern(const TRegexp& r)
{
// Copy the regular expression pattern.
fPattern = new Pattern_t[fgMaxpat];
memcpy(fPattern, r.fPattern, fgMaxpat * sizeof(Pattern_t));
fStat = r.fStat;
}
//______________________________________________________________________________
const char *TRegexp::MakeWildcard(const char *re)
{
// This routine transforms a wildcarding regular expression into
// a general regular expression used for pattern matching.
// When using wildcards the regular expression is assumed to be
// preceded by a "^" (BOL) and terminated by a "$" (EOL). Also, all
// "*"'s (closures) are assumed to be preceded by a "." (i.e. any character,
// except "/"'s) and all .'s are escaped (so *.ps is different from *.eps).
// The special treatment of "/" allows the easy matching of pathnames, e.g.
// "*.root" will match "aap.root", but not "pipo/aap.root".
static char buf[fgMaxpat];
char *s = buf;
int len = strlen(re);
if (!re || !len) return "";
for (int i = 0; i < len; i++) {
if (i == 0 && re[i] != '^')
*s++ = '^';
if (re[i] == '*') {
#ifndef R__WIN32
//const char *wc = "[a-zA-Z0-9-+_\\.,: []<>]";
const char *wc = "[^/]";
#else
//const char *wc = "[a-zA-Z0-9-+_., []<>]";
const char *wc = "[^\\/:]";
#endif
strcpy(s, wc);
s += strlen(wc);
}
if (re[i] == '.')
*s++ = '\\';
*s++ = re[i];
if (i == len-1 && re[i] != '$')
*s++ = '$';
}
*s = '\0';
return buf;
}
//______________________________________________________________________________
Ssiz_t TRegexp::Index(const TString& string, Ssiz_t* len, Ssiz_t i) const
{
// Find the first occurance of the regexp in string and return the position.
// Len is length of the matched string and i is the offset at which the
// matching should start.
if (fStat != kOK)
Error("TRegexp::Index", "Bad Regular Expression");
const char* startp;
const char* s = string.Data();
Ssiz_t slen = string.Length();
if (slen < i) return kNPOS;
const char* endp = ::Matchs(s+i, slen-i, fPattern, &startp);
if (endp) {
*len = endp - startp;
return startp - s;
} else {
*len = 0;
return kNPOS;
}
}
//______________________________________________________________________________
TRegexp::EStatVal TRegexp::Status()
{
// Check status of regexp.
EStatVal temp = fStat;
fStat = kOK;
return temp;
}
//////////////////////////////////////////////////////////////////////////
// //
// TString member functions, put here so the linker will include //
// them only if regular expressions are used. //
// //
//////////////////////////////////////////////////////////////////////////
//______________________________________________________________________________
Ssiz_t TString::Index(const TRegexp& r, Ssiz_t start) const
{
// Find the first occurance of the regexp in string and return the position.
// Start is the offset at which the search should start.
Ssiz_t len;
return r.Index(*this, &len, start); // len not used
}
//______________________________________________________________________________
Ssiz_t TString::Index(const TRegexp& r, Ssiz_t* extent, Ssiz_t start) const
{
// Find the first occurance of the regexp in string and return the position.
// Extent is length of the matched string and start is the offset at which
// the matching should start.
return r.Index(*this, extent, start);
}
//______________________________________________________________________________
TSubString TString::operator()(const TRegexp& r, Ssiz_t start)
{
// Return the substring found by applying the regexp starting at start.
Ssiz_t len;
Ssiz_t begin = Index(r, &len, start);
return TSubString(*this, begin, len);
}
//______________________________________________________________________________
TSubString TString::operator()(const TRegexp& r)
{
// Return the substring found by applying the regexp.
return (*this)(r,0);
}
//______________________________________________________________________________
TSubString TString::operator()(const TRegexp& r, Ssiz_t start) const
{
// Return the substring found by applying the regexp starting at start.
Ssiz_t len;
Ssiz_t begin = Index(r, &len, start);
return TSubString(*this, begin, len);
}
//______________________________________________________________________________
TSubString TString::operator()(const TRegexp& r) const
{
// Return the substring found by applying the regexp.
return (*this)(r,0);
}
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "qbsprojectmanager.h"
#include "qbslogsink.h"
#include "qbsproject.h"
#include "qbsprojectmanagerconstants.h"
#include "qbsprojectmanagerplugin.h"
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/kitmanager.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/toolchain.h>
#include <qmljstools/qmljstoolsconstants.h>
#include <qtsupport/baseqtversion.h>
#include <qtsupport/qtkitinformation.h>
#include <utils/qtcassert.h>
#include <QVariantMap>
#include <qbs.h>
// qbs settings structure:
const char PROFILE_LIST[] = "preferences.qtcreator.kit.";
const char PROFILES_PREFIX[] = "profiles.";
// Qt related settings:
const char QTCORE_BINPATH[] = ".Qt.core.binPath";
const char QTCORE_INCPATH[] = ".Qt.core.incPath";
const char QTCORE_LIBPATH[] = ".Qt.core.libPath";
const char QTCORE_VERSION[] = ".Qt.core.version";
const char QTCORE_NAMESPACE[] = ".Qt.core.namespace";
const char QTCORE_LIBINFIX[] = ".Qt.core.libInfix";
const char QTCORE_MKSPEC[] = ".Qt.core.mkspecPath";
const char QTCORE_FRAMEWORKBUILD[] = ".Qt.core.frameworkBuild";
// Toolchain related settings:
const char QBS_TARGETOS[] = ".qbs.targetOS";
const char QBS_SYSROOT[] = ".qbs.sysroot";
const char QBS_ARCHITECTURE[] = ".qbs.architecture";
const char QBS_TOOLCHAIN[] = ".qbs.toolchain";
const char CPP_TOOLCHAINPATH[] = ".cpp.toolchainInstallPath";
const char CPP_COMPILERNAME[] = ".cpp.compilerName";
const QChar sep = QChar(QLatin1Char('.'));
namespace QbsProjectManager {
qbs::Settings *QbsManager::m_settings = 0;
qbs::Preferences *QbsManager::m_preferences = 0;
QbsManager::QbsManager(Internal::QbsProjectManagerPlugin *plugin) :
m_plugin(plugin)
{
if (!m_settings)
m_settings = new qbs::Settings(QLatin1String("QtProject"), QLatin1String("qbs"));
if (!m_preferences)
m_preferences = new qbs::Preferences(m_settings);
setObjectName(QLatin1String("QbsProjectManager"));
connect(ProjectExplorer::KitManager::instance(), SIGNAL(kitsChanged()), this, SLOT(pushKitsToQbs()));
m_logSink = new Internal::QbsLogSink(this);
int level = qbs::LoggerWarning;
const QString levelEnv = QString::fromLocal8Bit(qgetenv("QBS_LOG_LEVEL"));
if (!levelEnv.isEmpty()) {
int tmp = levelEnv.toInt();
if (tmp < static_cast<int>(qbs::LoggerMinLevel))
tmp = static_cast<int>(qbs::LoggerMinLevel);
if (tmp > static_cast<int>(qbs::LoggerMaxLevel))
tmp = static_cast<int>(qbs::LoggerMaxLevel);
level = tmp;
}
m_logSink->setLogLevel(static_cast<qbs::LoggerLevel>(level));
}
QbsManager::~QbsManager()
{
delete m_settings;
}
QString QbsManager::mimeType() const
{
return QLatin1String(QmlJSTools::Constants::QBS_MIMETYPE);
}
ProjectExplorer::Project *QbsManager::openProject(const QString &fileName, QString *errorString)
{
if (!QFileInfo(fileName).isFile()) {
if (errorString)
*errorString = tr("Failed opening project '%1': Project is not a file")
.arg(fileName);
return 0;
}
return new Internal::QbsProject(this, fileName);
}
QString QbsManager::profileForKit(const ProjectExplorer::Kit *k) const
{
if (!k)
return QString();
return m_settings->value(QString::fromLatin1(PROFILE_LIST) + k->id().toString()).toString();
}
void QbsManager::setProfileForKit(const QString &name, const ProjectExplorer::Kit *k)
{
m_settings->setValue(QString::fromLatin1(PROFILE_LIST) + k->id().toString(), name);
}
QStringList QbsManager::profileNames() const
{
QStringList keyList = m_settings->allKeys();
QStringList result;
foreach (const QString &key, keyList) {
if (!key.startsWith(QString::fromLatin1(PROFILES_PREFIX)))
continue;
QString profile = key;
profile.remove(0, QString::fromLatin1(PROFILES_PREFIX).count());
profile = profile.left(profile.indexOf(sep));
if (!result.contains(profile))
result << profile;
}
return result;
}
qbs::Settings *QbsManager::settings()
{
return m_settings;
}
qbs::Preferences *QbsManager::preferences()
{
return m_preferences;
}
void QbsManager::addProfile(const QString &name, const QVariantMap &data)
{
const QString base = QLatin1String(PROFILES_PREFIX) + name;
const QVariantMap::ConstIterator cend = data.constEnd();
for (QVariantMap::ConstIterator it = data.constBegin(); it != cend; ++it)
m_settings->setValue(base + it.key(), it.value());
}
void QbsManager::removeCreatorProfiles()
{
QStringList keyList = m_settings->allKeys();
QStringList profilesToDelete;
// Find profiles to remove:
foreach (const QString &key, keyList) {
if (!key.startsWith(QLatin1String(PROFILE_LIST)))
continue;
profilesToDelete.append(m_settings->value(key).toString());
m_settings->remove(key);
}
// Remove profiles:
foreach (const QString &key, keyList) {
if (!key.startsWith(QLatin1String(PROFILES_PREFIX)))
continue;
const QString kitname = key.mid(QString::fromLatin1(PROFILES_PREFIX).size());
foreach (const QString &i, profilesToDelete) {
if (kitname.startsWith(i + sep))
m_settings->remove(key);
}
}
}
void QbsManager::addProfileFromKit(const ProjectExplorer::Kit *k)
{
QStringList usedProfileNames = profileNames();
const QString name = ProjectExplorer::Project::makeUnique(
QString::fromLatin1("qtc_") + k->fileSystemFriendlyName(), usedProfileNames);
setProfileForKit(name, k);
QVariantMap data;
QtSupport::BaseQtVersion *qt = QtSupport::QtKitInformation::qtVersion(k);
if (qt) {
data.insert(QLatin1String(QTCORE_BINPATH), qt->binPath().toUserOutput());
data.insert(QLatin1String(QTCORE_INCPATH), qt->headerPath().toUserOutput());
data.insert(QLatin1String(QTCORE_LIBPATH), qt->libraryPath().toUserOutput());
Utils::FileName mkspecPath = qt->mkspecsPath();
mkspecPath.appendPath(qt->mkspec().toString());
data.insert(QLatin1String(QTCORE_MKSPEC), mkspecPath.toUserOutput());
data.insert(QLatin1String(QTCORE_NAMESPACE), qt->qtNamespace());
data.insert(QLatin1String(QTCORE_LIBINFIX), qt->qtLibInfix());
data.insert(QLatin1String(QTCORE_VERSION), qt->qtVersionString());
if (qt->isFrameworkBuild())
data.insert(QLatin1String(QTCORE_FRAMEWORKBUILD), true);
}
if (ProjectExplorer::SysRootKitInformation::hasSysRoot(k))
data.insert(QLatin1String(QBS_SYSROOT), ProjectExplorer::SysRootKitInformation::sysRoot(k).toUserOutput());
ProjectExplorer::ToolChain *tc = ProjectExplorer::ToolChainKitInformation::toolChain(k);
if (tc) {
// FIXME/CLARIFY: How to pass the sysroot?
ProjectExplorer::Abi targetAbi = tc->targetAbi();
QString architecture = ProjectExplorer::Abi::toString(targetAbi.architecture());
if (targetAbi.wordWidth() == 64)
architecture.append(QLatin1String("_64"));
data.insert(QLatin1String(QBS_ARCHITECTURE), architecture);
if (targetAbi.os() == ProjectExplorer::Abi::WindowsOS) {
data.insert(QLatin1String(QBS_TARGETOS), QLatin1String("windows"));
data.insert(QLatin1String(QBS_TOOLCHAIN),
targetAbi.osFlavor() == ProjectExplorer::Abi::WindowsMSysFlavor ?
QLatin1String("mingw") : QLatin1String("msvc"));
} else if (targetAbi.os() == ProjectExplorer::Abi::MacOS) {
data.insert(QLatin1String(QBS_TARGETOS), QLatin1String("mac"));
data.insert(QLatin1String(QBS_TOOLCHAIN), QLatin1String("gcc"));
} else if (targetAbi.os() == ProjectExplorer::Abi::LinuxOS) {
data.insert(QLatin1String(QBS_TARGETOS), QLatin1String("linux"));
data.insert(QLatin1String(QBS_TOOLCHAIN), QLatin1String("gcc"));
}
Utils::FileName cxx = tc->compilerCommand();
data.insert(QLatin1String(CPP_TOOLCHAINPATH), cxx.toFileInfo().absolutePath());
data.insert(QLatin1String(CPP_COMPILERNAME), cxx.toFileInfo().fileName());
}
addProfile(name, data);
}
void QbsManager::pushKitsToQbs()
{
// Get all keys
removeCreatorProfiles();
// add definitions from our kits
foreach (const ProjectExplorer::Kit *k, ProjectExplorer::KitManager::instance()->kits())
addProfileFromKit(k);
}
} // namespace QbsProjectManager
<commit_msg>Qbs: Be more paranoid when setting the log level<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "qbsprojectmanager.h"
#include "qbslogsink.h"
#include "qbsproject.h"
#include "qbsprojectmanagerconstants.h"
#include "qbsprojectmanagerplugin.h"
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/kitmanager.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/toolchain.h>
#include <qmljstools/qmljstoolsconstants.h>
#include <qtsupport/baseqtversion.h>
#include <qtsupport/qtkitinformation.h>
#include <utils/qtcassert.h>
#include <QVariantMap>
#include <qbs.h>
// qbs settings structure:
const char PROFILE_LIST[] = "preferences.qtcreator.kit.";
const char PROFILES_PREFIX[] = "profiles.";
// Qt related settings:
const char QTCORE_BINPATH[] = ".Qt.core.binPath";
const char QTCORE_INCPATH[] = ".Qt.core.incPath";
const char QTCORE_LIBPATH[] = ".Qt.core.libPath";
const char QTCORE_VERSION[] = ".Qt.core.version";
const char QTCORE_NAMESPACE[] = ".Qt.core.namespace";
const char QTCORE_LIBINFIX[] = ".Qt.core.libInfix";
const char QTCORE_MKSPEC[] = ".Qt.core.mkspecPath";
const char QTCORE_FRAMEWORKBUILD[] = ".Qt.core.frameworkBuild";
// Toolchain related settings:
const char QBS_TARGETOS[] = ".qbs.targetOS";
const char QBS_SYSROOT[] = ".qbs.sysroot";
const char QBS_ARCHITECTURE[] = ".qbs.architecture";
const char QBS_TOOLCHAIN[] = ".qbs.toolchain";
const char CPP_TOOLCHAINPATH[] = ".cpp.toolchainInstallPath";
const char CPP_COMPILERNAME[] = ".cpp.compilerName";
const QChar sep = QChar(QLatin1Char('.'));
namespace QbsProjectManager {
qbs::Settings *QbsManager::m_settings = 0;
qbs::Preferences *QbsManager::m_preferences = 0;
QbsManager::QbsManager(Internal::QbsProjectManagerPlugin *plugin) :
m_plugin(plugin)
{
if (!m_settings)
m_settings = new qbs::Settings(QLatin1String("QtProject"), QLatin1String("qbs"));
if (!m_preferences)
m_preferences = new qbs::Preferences(m_settings);
setObjectName(QLatin1String("QbsProjectManager"));
connect(ProjectExplorer::KitManager::instance(), SIGNAL(kitsChanged()), this, SLOT(pushKitsToQbs()));
m_logSink = new Internal::QbsLogSink(this);
int level = qbs::LoggerWarning;
const QString levelEnv = QString::fromLocal8Bit(qgetenv("QBS_LOG_LEVEL"));
if (!levelEnv.isEmpty()) {
bool ok = false;
int tmp = levelEnv.toInt(&ok);
if (ok) {
if (tmp < static_cast<int>(qbs::LoggerMinLevel))
tmp = static_cast<int>(qbs::LoggerMinLevel);
if (tmp > static_cast<int>(qbs::LoggerMaxLevel))
tmp = static_cast<int>(qbs::LoggerMaxLevel);
level = tmp;
}
}
m_logSink->setLogLevel(static_cast<qbs::LoggerLevel>(level));
}
QbsManager::~QbsManager()
{
delete m_settings;
}
QString QbsManager::mimeType() const
{
return QLatin1String(QmlJSTools::Constants::QBS_MIMETYPE);
}
ProjectExplorer::Project *QbsManager::openProject(const QString &fileName, QString *errorString)
{
if (!QFileInfo(fileName).isFile()) {
if (errorString)
*errorString = tr("Failed opening project '%1': Project is not a file")
.arg(fileName);
return 0;
}
return new Internal::QbsProject(this, fileName);
}
QString QbsManager::profileForKit(const ProjectExplorer::Kit *k) const
{
if (!k)
return QString();
return m_settings->value(QString::fromLatin1(PROFILE_LIST) + k->id().toString()).toString();
}
void QbsManager::setProfileForKit(const QString &name, const ProjectExplorer::Kit *k)
{
m_settings->setValue(QString::fromLatin1(PROFILE_LIST) + k->id().toString(), name);
}
QStringList QbsManager::profileNames() const
{
QStringList keyList = m_settings->allKeys();
QStringList result;
foreach (const QString &key, keyList) {
if (!key.startsWith(QString::fromLatin1(PROFILES_PREFIX)))
continue;
QString profile = key;
profile.remove(0, QString::fromLatin1(PROFILES_PREFIX).count());
profile = profile.left(profile.indexOf(sep));
if (!result.contains(profile))
result << profile;
}
return result;
}
qbs::Settings *QbsManager::settings()
{
return m_settings;
}
qbs::Preferences *QbsManager::preferences()
{
return m_preferences;
}
void QbsManager::addProfile(const QString &name, const QVariantMap &data)
{
const QString base = QLatin1String(PROFILES_PREFIX) + name;
const QVariantMap::ConstIterator cend = data.constEnd();
for (QVariantMap::ConstIterator it = data.constBegin(); it != cend; ++it)
m_settings->setValue(base + it.key(), it.value());
}
void QbsManager::removeCreatorProfiles()
{
QStringList keyList = m_settings->allKeys();
QStringList profilesToDelete;
// Find profiles to remove:
foreach (const QString &key, keyList) {
if (!key.startsWith(QLatin1String(PROFILE_LIST)))
continue;
profilesToDelete.append(m_settings->value(key).toString());
m_settings->remove(key);
}
// Remove profiles:
foreach (const QString &key, keyList) {
if (!key.startsWith(QLatin1String(PROFILES_PREFIX)))
continue;
const QString kitname = key.mid(QString::fromLatin1(PROFILES_PREFIX).size());
foreach (const QString &i, profilesToDelete) {
if (kitname.startsWith(i + sep))
m_settings->remove(key);
}
}
}
void QbsManager::addProfileFromKit(const ProjectExplorer::Kit *k)
{
QStringList usedProfileNames = profileNames();
const QString name = ProjectExplorer::Project::makeUnique(
QString::fromLatin1("qtc_") + k->fileSystemFriendlyName(), usedProfileNames);
setProfileForKit(name, k);
QVariantMap data;
QtSupport::BaseQtVersion *qt = QtSupport::QtKitInformation::qtVersion(k);
if (qt) {
data.insert(QLatin1String(QTCORE_BINPATH), qt->binPath().toUserOutput());
data.insert(QLatin1String(QTCORE_INCPATH), qt->headerPath().toUserOutput());
data.insert(QLatin1String(QTCORE_LIBPATH), qt->libraryPath().toUserOutput());
Utils::FileName mkspecPath = qt->mkspecsPath();
mkspecPath.appendPath(qt->mkspec().toString());
data.insert(QLatin1String(QTCORE_MKSPEC), mkspecPath.toUserOutput());
data.insert(QLatin1String(QTCORE_NAMESPACE), qt->qtNamespace());
data.insert(QLatin1String(QTCORE_LIBINFIX), qt->qtLibInfix());
data.insert(QLatin1String(QTCORE_VERSION), qt->qtVersionString());
if (qt->isFrameworkBuild())
data.insert(QLatin1String(QTCORE_FRAMEWORKBUILD), true);
}
if (ProjectExplorer::SysRootKitInformation::hasSysRoot(k))
data.insert(QLatin1String(QBS_SYSROOT), ProjectExplorer::SysRootKitInformation::sysRoot(k).toUserOutput());
ProjectExplorer::ToolChain *tc = ProjectExplorer::ToolChainKitInformation::toolChain(k);
if (tc) {
// FIXME/CLARIFY: How to pass the sysroot?
ProjectExplorer::Abi targetAbi = tc->targetAbi();
QString architecture = ProjectExplorer::Abi::toString(targetAbi.architecture());
if (targetAbi.wordWidth() == 64)
architecture.append(QLatin1String("_64"));
data.insert(QLatin1String(QBS_ARCHITECTURE), architecture);
if (targetAbi.os() == ProjectExplorer::Abi::WindowsOS) {
data.insert(QLatin1String(QBS_TARGETOS), QLatin1String("windows"));
data.insert(QLatin1String(QBS_TOOLCHAIN),
targetAbi.osFlavor() == ProjectExplorer::Abi::WindowsMSysFlavor ?
QLatin1String("mingw") : QLatin1String("msvc"));
} else if (targetAbi.os() == ProjectExplorer::Abi::MacOS) {
data.insert(QLatin1String(QBS_TARGETOS), QLatin1String("mac"));
data.insert(QLatin1String(QBS_TOOLCHAIN), QLatin1String("gcc"));
} else if (targetAbi.os() == ProjectExplorer::Abi::LinuxOS) {
data.insert(QLatin1String(QBS_TARGETOS), QLatin1String("linux"));
data.insert(QLatin1String(QBS_TOOLCHAIN), QLatin1String("gcc"));
}
Utils::FileName cxx = tc->compilerCommand();
data.insert(QLatin1String(CPP_TOOLCHAINPATH), cxx.toFileInfo().absolutePath());
data.insert(QLatin1String(CPP_COMPILERNAME), cxx.toFileInfo().fileName());
}
addProfile(name, data);
}
void QbsManager::pushKitsToQbs()
{
// Get all keys
removeCreatorProfiles();
// add definitions from our kits
foreach (const ProjectExplorer::Kit *k, ProjectExplorer::KitManager::instance()->kits())
addProfileFromKit(k);
}
} // namespace QbsProjectManager
<|endoftext|>
|
<commit_before>// Copyright (c) 2009 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_frame/sync_msg_reply_dispatcher.h"
#include "ipc/ipc_sync_message.h"
void SyncMessageReplyDispatcher::Push(IPC::SyncMessage* msg,
SyncMessageCallContext* context,
void* key) {
context->message_type_ = msg->type();
context->id_ = IPC::SyncMessage::GetMessageId(*msg);
context->key_ = key;
AutoLock lock(message_queue_lock_);
message_queue_.push_back(context);
}
bool SyncMessageReplyDispatcher::HandleMessageType(
const IPC::Message& msg, SyncMessageCallContext* context) {
return false;
}
bool SyncMessageReplyDispatcher::OnMessageReceived(const IPC::Message& msg) {
SyncMessageCallContext* context = GetContext(msg);
// No context e.g. no return values and/or don't care
if (!context) {
return false;
}
return HandleMessageType(msg, context);
}
void SyncMessageReplyDispatcher::Cancel(void* key) {
DCHECK(key != NULL);
AutoLock lock(message_queue_lock_);
PendingSyncMessageQueue::iterator it = message_queue_.begin();
while (it != message_queue_.end()) {
SyncMessageCallContext* context = *it;
if (context->key_ == key) {
it = message_queue_.erase(it);
delete context;
} else {
++it;
}
}
}
SyncMessageReplyDispatcher::SyncMessageCallContext*
SyncMessageReplyDispatcher::GetContext(const IPC::Message& msg) {
if (!msg.is_reply())
return NULL;
int id = IPC::SyncMessage::GetMessageId(msg);
AutoLock lock(message_queue_lock_);
PendingSyncMessageQueue::iterator it;
for (it = message_queue_.begin(); it != message_queue_.end(); ++it) {
SyncMessageCallContext* context = *it;
if (context->id_ == id) {
message_queue_.erase(it);
return context;
}
}
return NULL;
}
<commit_msg>In ChromeFrame there are cases when the ChromeFrameAutomationProxy::SendAsAsync function can be passed a NULL callback. The dispatcher needs to check for the same and ignore the returned callback message. We currently crash on trunk.<commit_after>// Copyright (c) 2009 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_frame/sync_msg_reply_dispatcher.h"
#include "ipc/ipc_sync_message.h"
void SyncMessageReplyDispatcher::Push(IPC::SyncMessage* msg,
SyncMessageCallContext* context,
void* key) {
if (context) {
context->message_type_ = msg->type();
context->id_ = IPC::SyncMessage::GetMessageId(*msg);
context->key_ = key;
AutoLock lock(message_queue_lock_);
message_queue_.push_back(context);
}
}
bool SyncMessageReplyDispatcher::HandleMessageType(
const IPC::Message& msg, SyncMessageCallContext* context) {
return false;
}
bool SyncMessageReplyDispatcher::OnMessageReceived(const IPC::Message& msg) {
SyncMessageCallContext* context = GetContext(msg);
// No context e.g. no return values and/or don't care
if (!context) {
return false;
}
return HandleMessageType(msg, context);
}
void SyncMessageReplyDispatcher::Cancel(void* key) {
DCHECK(key != NULL);
AutoLock lock(message_queue_lock_);
PendingSyncMessageQueue::iterator it = message_queue_.begin();
while (it != message_queue_.end()) {
SyncMessageCallContext* context = *it;
if (context->key_ == key) {
it = message_queue_.erase(it);
delete context;
} else {
++it;
}
}
}
SyncMessageReplyDispatcher::SyncMessageCallContext*
SyncMessageReplyDispatcher::GetContext(const IPC::Message& msg) {
if (!msg.is_reply())
return NULL;
int id = IPC::SyncMessage::GetMessageId(msg);
AutoLock lock(message_queue_lock_);
PendingSyncMessageQueue::iterator it;
for (it = message_queue_.begin(); it != message_queue_.end(); ++it) {
SyncMessageCallContext* context = *it;
if (context->id_ == id) {
message_queue_.erase(it);
return context;
}
}
return NULL;
}
<|endoftext|>
|
<commit_before>#include "Processor.h"
#include "sim/config.h"
#include "sim/range.h"
#include <cassert>
#include <iomanip>
using namespace std;
namespace Simulator
{
//
// RegisterFile implementation
//
Processor::RegisterFile::RegisterFile(const std::string& name, Processor& parent, Clock& clock, Allocator& alloc, Config& config)
: Object(name, parent, clock),
Structure<RegAddr>(name, parent, clock),
Storage("storage", *this, clock),
p_pipelineR1(*this, "p_pipelineR1"),
p_pipelineR2(*this, "p_pipelineR2"),
p_pipelineW (*this, "p_pipelineW"),
p_asyncR (*this, "p_asyncR"),
p_asyncW (*this, "p_asyncW"),
m_parent(parent), m_allocator(alloc),
m_nUpdates(0),
m_integers(config.getValue<size_t>(*this, "NumIntRegisters")),
m_floats (config.getValue<size_t>(*this, "NumFltRegisters"))
{
// Initialize all registers to empty
for (RegSize i = 0; i < m_integers.size(); ++i)
{
m_integers[i] = MAKE_EMPTY_REG();
}
for (RegSize i = 0; i < m_floats.size(); ++i)
{
m_floats[i] = MAKE_EMPTY_REG();
}
// Set port priorities; first port has highest priority
AddPort(p_pipelineW);
AddPort(p_asyncW);
}
RegSize Processor::RegisterFile::GetSize(RegType type) const
{
const vector<RegValue>& regs = (type == RT_FLOAT) ? m_floats : m_integers;
return regs.size();
}
bool Processor::RegisterFile::ReadRegister(const RegAddr& addr, RegValue& data, bool quiet) const
{
const vector<RegValue>& regs = (addr.type == RT_FLOAT) ? m_floats : m_integers;
if (addr.index >= regs.size())
{
throw SimulationException("A component attempted to read from a non-existing register", *this);
}
data = regs[addr.index];
if (!quiet)
DebugRegWrite("Read from %s: %s", addr.str().c_str(), data.str(addr.type).c_str());
return true;
}
// Admin version
bool Processor::RegisterFile::WriteRegister(const RegAddr& addr, const RegValue& data)
{
vector<RegValue>& regs = (addr.type == RT_FLOAT) ? m_floats : m_integers;
if (addr.index < regs.size())
{
DebugRegWrite("Write to %s: %s becomes %s", addr.str().c_str(), regs[ addr.index ].str(addr.type).c_str(), data.str(addr.type).c_str());
regs[addr.index] = data;
return true;
}
return false;
}
bool Processor::RegisterFile::Clear(const RegAddr& addr, RegSize size)
{
std::vector<RegValue>& regs = (addr.type == RT_FLOAT) ? m_floats : m_integers;
if (addr.index + size > regs.size())
{
throw SimulationException("A component attempted to clear a non-existing register", *this);
}
COMMIT
{
const RegValue value = MAKE_EMPTY_REG();
for (RegSize i = 0; i < size; ++i)
{
regs[addr.index + i] = value;
}
}
return true;
}
bool Processor::RegisterFile::WriteRegister(const RegAddr& addr, const RegValue& data, bool from_memory)
{
std::vector<RegValue>& regs = (addr.type == RT_FLOAT) ? m_floats : m_integers;
if (addr.index >= regs.size())
{
throw SimulationException("A component attempted to write to a non-existing register", *this);
}
assert(data.m_state == RST_EMPTY || data.m_state == RST_PENDING || data.m_state == RST_WAITING || data.m_state == RST_FULL);
if (data.m_state == RST_EMPTY || data.m_state == RST_PENDING)
{
assert(data.m_waiting.head == INVALID_TID);
}
const RegValue& value = regs[addr.index];
if (value.m_state != RST_FULL)
{
if (value.m_state == RST_WAITING && data.m_state == RST_EMPTY)
{
throw exceptf<SimulationException>(*this, "Invalid reset of %s: %s becomes %s", addr.str().c_str(), value.str(addr.type).c_str(), data.str(addr.type).c_str());
}
if (value.m_memory.size != 0)
{
// Check that the memory information isn't changed
if (data.m_state == RST_FULL ||
data.m_memory.fid != value.m_memory.fid ||
data.m_memory.offset != value.m_memory.offset ||
data.m_memory.size != value.m_memory.size ||
data.m_memory.sign_extend != value.m_memory.sign_extend ||
data.m_memory.next != value.m_memory.next)
{
if (!from_memory)
{
// Only the memory can change memory-pending registers
throw exceptf<SimulationException>(*this, "Invalid reset of pending load %s: %s becomes %s", addr.str().c_str(), value.str(addr.type).c_str(), data.str(addr.type).c_str());
}
}
}
if (data.m_state == RST_FULL)
{
if (value.m_state == RST_WAITING && value.m_waiting.head != INVALID_TID)
{
// This write caused a reschedule
if (!m_allocator.ActivateThreads(value.m_waiting))
{
DeadlockWrite("Unable to wake up threads after write of %s: %s becomes %s", addr.str().c_str(), value.str(addr.type).c_str(), data.str(addr.type).c_str());
return false;
}
}
}
}
COMMIT
{
#ifndef NDEBUG
// Paranoid sanity check:
// We cannot have multiple writes to same register in a cycle
for (unsigned int i = 0; i < m_nUpdates; ++i)
{
assert(m_updates[i].first != addr);
}
#endif
// Queue the update
assert(m_nUpdates < MAX_UPDATES);
m_updates[m_nUpdates] = make_pair(addr, data);
if (m_nUpdates == 0) {
RegisterUpdate();
}
m_nUpdates++;
}
return true;
}
void Processor::RegisterFile::Update()
{
// Commit the queued updates to registers
assert(m_nUpdates > 0);
for (unsigned int i = 0; i < m_nUpdates; ++i)
{
RegAddr& addr = m_updates[i].first;
RegType type = addr.type;
vector<RegValue>& regs = (type == RT_FLOAT) ? m_floats : m_integers;
DebugRegWrite("Write to %s: %s becomes %s", addr.str().c_str(), regs[ addr.index ].str(type).c_str(), m_updates[i].second.str(type).c_str());
regs[ addr.index ] = m_updates[i].second;
}
m_nUpdates = 0;
}
void Processor::RegisterFile::Cmd_Info(std::ostream& out, const std::vector<std::string>& /*arguments*/) const
{
out <<
"The Register File stores the register for all threads running on a processor.\n"
"Each register consists of data and state bits.\n\n"
"Supported operations:\n"
"- inspect <component> [type] [range]\n"
" Reads and displays the used registers. The optional type argument can be\n"
" used to select between the integer (\"int\") and floating-point (\"float\")\n"
" Register Files.\n"
" An optional range argument can be given to only read those registers. The\n"
" range is a comma-seperated list of register ranges. Example ranges:\n"
" \"1\", \"1-4,15,7-8\", \"all\"\n";
}
void Processor::RegisterFile::Cmd_Read(std::ostream& out, const std::vector<std::string>& arguments) const
{
const RAUnit* rau = NULL;
const Allocator* alloc = NULL;
// Find the RAUnit and FamilyTable in the same processor
for (unsigned int i = 0; i < m_parent.GetNumChildren(); ++i)
{
const Object* child = m_parent.GetChild(i);
if (rau == NULL) rau = dynamic_cast<const RAUnit*>(child);
if (alloc == NULL) alloc = dynamic_cast<const Allocator*>(child);
}
RegType type = RT_INTEGER;
size_t i = 0;
if (!arguments.empty())
{
if (arguments[i] == "float") {
type = RT_FLOAT;
i++;
} else if (arguments[i] == "integer") {
type = RT_INTEGER;
i++;
}
}
vector<LFID> regs(GetSize(type), INVALID_LFID);
if (rau != NULL)
{
const RAUnit::List& list = rau->m_types[type].list;
const RegSize blockSize = rau->m_types[type].blockSize;
for (size_t i = 0; i < list.size();)
{
if (list[i].first != 0)
{
for (size_t j = 0; j < list[i].first * blockSize; ++j)
{
regs[i * blockSize + j] = list[i].second;
}
i += list[i].first;
}
else i++;
}
}
set<RegIndex> indices;
if (i < arguments.size())
{
indices = parse_range<RegIndex>(arguments[i], 0, regs.size());
}
else
{
// Default: add all registers that are part of a family
for (size_t i = 0; i < regs.size(); i++)
{
if (regs[i] != INVALID_LFID)
{
indices.insert(i);
}
}
}
out << "Addr | Fam | Thread | Role | State / Value" << endl
<< "------+-----+--------+-----------+--------------------------------" << endl;
for (set<RegIndex>::const_reverse_iterator p = indices.rbegin(); p != indices.rend(); ++p)
{
RegAddr addr = MAKE_REGADDR(type, *p);
LFID fid = regs[*p];
RegValue value;
ReadRegister(addr, value);
out << addr << " | ";
if (fid != INVALID_LFID) out << "F" << setw(2) << setfill('0') << dec << fid; else out << " ";
out << " | ";
RegClass group = RC_LOCAL;
TID tid = (fid != INVALID_LFID) ? alloc->GetRegisterType(fid, addr, &group) : INVALID_TID;
if (tid != INVALID_TID) {
out << "T" << setw(4) << setfill('0') << tid;
} else {
out << " - ";
}
out << " | ";
const char *groupstr = " - ";
switch (group)
{
case RC_GLOBAL: groupstr = "Global"; break;
case RC_DEPENDENT: groupstr = "Dependent"; break;
case RC_SHARED: groupstr = "Shared"; break;
case RC_LOCAL:
if (tid != INVALID_TID) groupstr = "Local";
break;
case RC_RAZ: break;
}
out << setw(9) << setfill(' ') << left << groupstr << right
<< " | "
<< value.str(type)
<< endl;
}
}
}
<commit_msg>[mgsim] Clean up the printing of the register file when register debugging is enabled.<commit_after>#include "Processor.h"
#include "sim/config.h"
#include "sim/range.h"
#include <cassert>
#include <iomanip>
using namespace std;
namespace Simulator
{
//
// RegisterFile implementation
//
Processor::RegisterFile::RegisterFile(const std::string& name, Processor& parent, Clock& clock, Allocator& alloc, Config& config)
: Object(name, parent, clock),
Structure<RegAddr>(name, parent, clock),
Storage("storage", *this, clock),
p_pipelineR1(*this, "p_pipelineR1"),
p_pipelineR2(*this, "p_pipelineR2"),
p_pipelineW (*this, "p_pipelineW"),
p_asyncR (*this, "p_asyncR"),
p_asyncW (*this, "p_asyncW"),
m_parent(parent), m_allocator(alloc),
m_nUpdates(0),
m_integers(config.getValue<size_t>(*this, "NumIntRegisters")),
m_floats (config.getValue<size_t>(*this, "NumFltRegisters"))
{
// Initialize all registers to empty
for (RegSize i = 0; i < m_integers.size(); ++i)
{
m_integers[i] = MAKE_EMPTY_REG();
}
for (RegSize i = 0; i < m_floats.size(); ++i)
{
m_floats[i] = MAKE_EMPTY_REG();
}
// Set port priorities; first port has highest priority
AddPort(p_pipelineW);
AddPort(p_asyncW);
}
RegSize Processor::RegisterFile::GetSize(RegType type) const
{
const vector<RegValue>& regs = (type == RT_FLOAT) ? m_floats : m_integers;
return regs.size();
}
bool Processor::RegisterFile::ReadRegister(const RegAddr& addr, RegValue& data, bool quiet) const
{
const vector<RegValue>& regs = (addr.type == RT_FLOAT) ? m_floats : m_integers;
if (addr.index >= regs.size())
{
throw SimulationException("A component attempted to read from a non-existing register", *this);
}
data = regs[addr.index];
if (!quiet)
DebugRegWrite("Read from %s: %s", addr.str().c_str(), data.str(addr.type).c_str());
return true;
}
// Admin version
bool Processor::RegisterFile::WriteRegister(const RegAddr& addr, const RegValue& data)
{
vector<RegValue>& regs = (addr.type == RT_FLOAT) ? m_floats : m_integers;
if (addr.index < regs.size())
{
DebugRegWrite("Write to %s: %s becomes %s", addr.str().c_str(), regs[ addr.index ].str(addr.type).c_str(), data.str(addr.type).c_str());
regs[addr.index] = data;
return true;
}
return false;
}
bool Processor::RegisterFile::Clear(const RegAddr& addr, RegSize size)
{
std::vector<RegValue>& regs = (addr.type == RT_FLOAT) ? m_floats : m_integers;
if (addr.index + size > regs.size())
{
throw SimulationException("A component attempted to clear a non-existing register", *this);
}
COMMIT
{
const RegValue value = MAKE_EMPTY_REG();
for (RegSize i = 0; i < size; ++i)
{
regs[addr.index + i] = value;
}
}
return true;
}
bool Processor::RegisterFile::WriteRegister(const RegAddr& addr, const RegValue& data, bool from_memory)
{
std::vector<RegValue>& regs = (addr.type == RT_FLOAT) ? m_floats : m_integers;
if (addr.index >= regs.size())
{
throw SimulationException("A component attempted to write to a non-existing register", *this);
}
assert(data.m_state == RST_EMPTY || data.m_state == RST_PENDING || data.m_state == RST_WAITING || data.m_state == RST_FULL);
if (data.m_state == RST_EMPTY || data.m_state == RST_PENDING)
{
assert(data.m_waiting.head == INVALID_TID);
}
const RegValue& value = regs[addr.index];
if (value.m_state != RST_FULL)
{
if (value.m_state == RST_WAITING && data.m_state == RST_EMPTY)
{
throw exceptf<SimulationException>(*this, "Invalid reset of %s: %s becomes %s", addr.str().c_str(), value.str(addr.type).c_str(), data.str(addr.type).c_str());
}
if (value.m_memory.size != 0)
{
// Check that the memory information isn't changed
if (data.m_state == RST_FULL ||
data.m_memory.fid != value.m_memory.fid ||
data.m_memory.offset != value.m_memory.offset ||
data.m_memory.size != value.m_memory.size ||
data.m_memory.sign_extend != value.m_memory.sign_extend ||
data.m_memory.next != value.m_memory.next)
{
if (!from_memory)
{
// Only the memory can change memory-pending registers
throw exceptf<SimulationException>(*this, "Invalid reset of pending load %s: %s becomes %s", addr.str().c_str(), value.str(addr.type).c_str(), data.str(addr.type).c_str());
}
}
}
if (data.m_state == RST_FULL)
{
if (value.m_state == RST_WAITING && value.m_waiting.head != INVALID_TID)
{
// This write caused a reschedule
if (!m_allocator.ActivateThreads(value.m_waiting))
{
DeadlockWrite("Unable to wake up threads after write of %s: %s becomes %s", addr.str().c_str(), value.str(addr.type).c_str(), data.str(addr.type).c_str());
return false;
}
}
}
}
COMMIT
{
#ifndef NDEBUG
// Paranoid sanity check:
// We cannot have multiple writes to same register in a cycle
for (unsigned int i = 0; i < m_nUpdates; ++i)
{
assert(m_updates[i].first != addr);
}
#endif
// Queue the update
assert(m_nUpdates < MAX_UPDATES);
m_updates[m_nUpdates] = make_pair(addr, data);
if (m_nUpdates == 0) {
RegisterUpdate();
}
m_nUpdates++;
}
return true;
}
void Processor::RegisterFile::Update()
{
// Commit the queued updates to registers
assert(m_nUpdates > 0);
for (unsigned int i = 0; i < m_nUpdates; ++i)
{
RegAddr& addr = m_updates[i].first;
RegType type = addr.type;
vector<RegValue>& regs = (type == RT_FLOAT) ? m_floats : m_integers;
DebugRegWrite("Write to %s: %s becomes %s", addr.str().c_str(), regs[ addr.index ].str(type).c_str(), m_updates[i].second.str(type).c_str());
regs[ addr.index ] = m_updates[i].second;
}
m_nUpdates = 0;
}
void Processor::RegisterFile::Cmd_Info(std::ostream& out, const std::vector<std::string>& /*arguments*/) const
{
out <<
"The Register File stores the register for all threads running on a processor.\n"
"Each register consists of data and state bits.\n\n"
"Supported operations:\n"
"- inspect <component> [type] [range]\n"
" Reads and displays the used registers. The optional type argument can be\n"
" used to select between the integer (\"int\") and floating-point (\"float\")\n"
" Register Files.\n"
" An optional range argument can be given to only read those registers. The\n"
" range is a comma-seperated list of register ranges. Example ranges:\n"
" \"1\", \"1-4,15,7-8\", \"all\"\n";
}
void Processor::RegisterFile::Cmd_Read(std::ostream& out, const std::vector<std::string>& arguments) const
{
const RAUnit* rau = NULL;
const Allocator* alloc = NULL;
// Find the RAUnit and FamilyTable in the same processor
for (unsigned int i = 0; i < m_parent.GetNumChildren(); ++i)
{
const Object* child = m_parent.GetChild(i);
if (rau == NULL) rau = dynamic_cast<const RAUnit*>(child);
if (alloc == NULL) alloc = dynamic_cast<const Allocator*>(child);
}
RegType type = RT_INTEGER;
size_t i = 0;
if (!arguments.empty())
{
if (arguments[i] == "float") {
type = RT_FLOAT;
i++;
} else if (arguments[i] == "integer") {
type = RT_INTEGER;
i++;
}
}
vector<LFID> regs(GetSize(type), INVALID_LFID);
if (rau != NULL)
{
const RAUnit::List& list = rau->m_types[type].list;
const RegSize blockSize = rau->m_types[type].blockSize;
for (size_t i = 0; i < list.size();)
{
if (list[i].first != 0)
{
for (size_t j = 0; j < list[i].first * blockSize; ++j)
{
regs[i * blockSize + j] = list[i].second;
}
i += list[i].first;
}
else i++;
}
}
set<RegIndex> indices;
if (i < arguments.size())
{
indices = parse_range<RegIndex>(arguments[i], 0, regs.size());
}
else
{
// Default: add all registers that are part of a family
for (size_t i = 0; i < regs.size(); i++)
{
if (regs[i] != INVALID_LFID)
{
indices.insert(i);
}
}
}
out << "Addr | Fam | Thread | Role | State / Value" << endl
<< "------+-----+--------+-----------+--------------------------------" << endl;
for (set<RegIndex>::const_reverse_iterator p = indices.rbegin(); p != indices.rend(); ++p)
{
RegAddr addr = MAKE_REGADDR(type, *p);
LFID fid = regs[*p];
RegValue value;
ReadRegister(addr, value, true);
out << addr << " | ";
if (fid != INVALID_LFID) out << "F" << setw(2) << setfill('0') << dec << fid; else out << " ";
out << " | ";
RegClass group = RC_LOCAL;
TID tid = (fid != INVALID_LFID) ? alloc->GetRegisterType(fid, addr, &group) : INVALID_TID;
if (tid != INVALID_TID) {
out << "T" << setw(4) << setfill('0') << tid;
} else {
out << " - ";
}
out << " | ";
const char *groupstr = " - ";
switch (group)
{
case RC_GLOBAL: groupstr = "Global"; break;
case RC_DEPENDENT: groupstr = "Dependent"; break;
case RC_SHARED: groupstr = "Shared"; break;
case RC_LOCAL:
if (tid != INVALID_TID) groupstr = "Local";
break;
case RC_RAZ: break;
}
out << setw(9) << setfill(' ') << left << groupstr << right
<< " | "
<< value.str(type)
<< endl;
}
}
}
<|endoftext|>
|
<commit_before>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// This one has to come first (includes the config.h)!
#include <dune/stuff/test/test_common.hh>
#include <dune/common/exceptions.hh>
#if HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H
#define ENABLE_ALUGRID 1
#include <dune/grid/alugrid.hh>
#else
#error This test requires ALUGrid!
#endif
#include <tuple>
#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/common/type_utils.hh>
#include <dune/stuff/common/color.hh>
#include <dune/stuff/common/print.hh>
#include <dune/stuff/common/string.hh>
#include <dune/stuff/common/float_cmp.hh>
#include <dune/stuff/functions/combined.hh>
#include <dune/stuff/la/solver.hh>
#include "elliptic-testcases.hh"
#include "elliptic-cg-discretization.hh"
//#include "elliptic-sipdg-discretization.hh"
//#include "elliptic-swipdg-discretization.hh"
class errors_are_not_as_expected : public Dune::Exception
{
};
typedef Dune::ALUConformGrid<2, 2> AluConform2dGridType;
// change this to toggle output
std::ostream& test_out = std::cout;
// std::ostream& test_out = DSC_LOG.devnull();
typedef testing::
Types<std::tuple<EllipticTestCase::ESV07<AluConform2dGridType>, Dune::Stuff::LA::EigenRowMajorSparseMatrix<double>,
Dune::Stuff::LA::EigenDenseVector<double>>,
std::tuple<EllipticTestCase::LocalThermalBlock<AluConform2dGridType>,
Dune::Stuff::LA::EigenRowMajorSparseMatrix<double>, Dune::Stuff::LA::EigenDenseVector<double>>,
std::tuple<EllipticTestCase::ER07<AluConform2dGridType>, Dune::Stuff::LA::EigenRowMajorSparseMatrix<double>,
Dune::Stuff::LA::EigenDenseVector<double>>,
std::tuple<EllipticTestCase::MixedBoundaryTypes<AluConform2dGridType>,
Dune::Stuff::LA::EigenRowMajorSparseMatrix<double>, Dune::Stuff::LA::EigenDenseVector<double>>,
std::tuple<EllipticTestCase::Spe10Model1<AluConform2dGridType>,
Dune::Stuff::LA::EigenRowMajorSparseMatrix<double>, Dune::Stuff::LA::EigenDenseVector<double>>>
AluConform2dTestCases;
template <class TestTuple>
struct EllipticCGDiscretization : public ::testing::Test
{
typedef typename std::tuple_element<0, TestTuple>::type TestCase;
typedef typename std::tuple_element<1, TestTuple>::type MatrixType;
typedef typename std::tuple_element<2, TestTuple>::type VectorType;
typedef EllipticCG::Discretization<typename TestCase::GridPartType, 1, MatrixType, VectorType> DiscretizationType;
void produces_correct_results() const
{
using namespace Dune;
using namespace Dune::GDT;
const TestCase test_case;
const auto grid_part = test_case.reference_grid_part();
DiscretizationType discretization(grid_part,
test_case.boundary_info(),
test_case.diffusion(),
test_case.force(),
test_case.dirichlet(),
test_case.neumann());
discretization.assemble();
std::cout << " test case: " << Stuff::Common::Typename<TestCase>::value() << std::endl;
std::cout << " matrix type: " << Stuff::Common::Typename<MatrixType>::value() << std::endl;
std::cout << " vector type: " << Stuff::Common::Typename<VectorType>::value() << std::endl;
std::cout << " system size: " << discretization.system_matrix().rows() << "x"
<< discretization.system_matrix().cols() << std::endl;
auto solution_vector = discretization.create_vector();
auto tmp_vector = discretization.create_vector();
Stuff::LA::Solver<MatrixType> linear_solver(discretization.system_matrix());
// print table header
const size_t min_first_column_width = std::string("solver option").size();
size_t first_column_width = min_first_column_width;
for (auto option : linear_solver.options())
first_column_width = std::max(first_column_width, option.size());
std::stringstream header;
std::stringstream delimiter;
header << " solver option";
delimiter << "--------------";
for (size_t ii = 0; ii <= first_column_width - min_first_column_width; ++ii) {
header << " ";
delimiter << "-";
}
header << "| time (s) | L^oo error (abs|rel) | thrown exception (see dune/stuff/solver.hh) ";
delimiter << "+----------+----------------------+---------------------------------------------";
std::cout << Stuff::Common::whitespaceify(header.str(), '=') << std::endl;
std::cout << header.str() << std::endl;
std::cout << delimiter.str() << std::endl;
// loop over all available options
size_t printed_rows = 0;
for (auto option : linear_solver.options()) {
if (option != "qr.sparse" && option.substr(0, 3) != "cg.") {
const Stuff::Common::ConfigTree config = linear_solver.options(option);
// print delimiter after every 3rd row
if (printed_rows == 3) {
std::cout << delimiter.str() << std::endl;
printed_rows = 0;
}
// print
std::cout << " " << option;
for (size_t ii = 0; ii < first_column_width - option.size(); ++ii)
std::cout << " ";
// solve the system
Dune::Timer timer;
std::stringstream error_msg;
bool success = true;
try {
linear_solver.apply(discretization.rhs_vector(), solution_vector, option);
} catch (Stuff::Exceptions::linear_solver_failed_bc_matrix_did_not_fulfill_requirements&) {
error_msg << Stuff::Common::colorStringRed("matrix_did_not_fulfill_requirements");
if (option.substr(0, 3) == "cg.")
error_msg << " (OK for this discretization)";
success = false;
} catch (Stuff::Exceptions::linear_solver_failed_bc_it_did_not_converge&) {
error_msg << Stuff::Common::colorStringRed("did_not_converge");
} catch (Stuff::Exceptions::linear_solver_failed_bc_it_was_not_set_up_correctly&) {
error_msg << Stuff::Common::colorStringRed("was_not_set_up_correctly");
success = false;
} catch (Stuff::Exceptions::linear_solver_failed_bc_the_solution_does_not_solve_the_system&) {
error_msg << Stuff::Common::colorStringRed("solution_does_not_solve_the_system");
} catch (Stuff::Exceptions::linear_solver_failed&) {
error_msg << Stuff::Common::colorStringRed("linear_solver_failed");
success = false;
}
std::cout << " | " << std::setw(8) << std::setprecision(2) << std::fixed << timer.elapsed();
std::cout << " | ";
// test solution
if (success) {
discretization.system_matrix().mv(solution_vector, tmp_vector);
tmp_vector -= discretization.rhs_vector();
double threshhold = config.get<double>("post_check_solves_system");
if (config.has_key("precision"))
threshhold = config.get<double>("precision");
std::stringstream absolute_error;
absolute_error << std::setw(9) << std::setprecision(2) << std::scientific << tmp_vector.sup_norm();
if (tmp_vector.sup_norm() < threshhold)
std::cout << Stuff::Common::colorString(Stuff::Common::toString(absolute_error.str()),
Stuff::Common::Colors::green);
else if (tmp_vector.sup_norm() < std::exp(0.5 * std::log(threshhold)))
std::cout << Stuff::Common::colorString(Stuff::Common::toString(absolute_error.str()),
Stuff::Common::Colors::brown);
else
std::cout << Stuff::Common::colorStringRed(Stuff::Common::toString(absolute_error.str()));
std::cout << " | " << std::setw(8) << std::setprecision(2) << std::scientific
<< tmp_vector.sup_norm() / discretization.rhs_vector().sup_norm();
} else
std::cout << " ";
std::cout << " | " << error_msg.str() << std::endl;
++printed_rows;
}
} // loop over all available options
}
}; // EllipticCGDiscretization
#if 0
template< class TestCase >
struct EllipticSIPDGDiscretization
: public ::testing::Test
{
void produces_correct_results() const
{
if (std::is_same< TestCase, EllipticTestCase::Spe10Model1< Dune::ALUConformGrid< 2, 2 > > >::value) {
std::cerr
<< Dune::Stuff::Common::colorStringRed("EllipticSIPDGDiscretization does not work for "
"EllipticTestCase::Spe10Model1< Dune::ALUConformGrid< 2, 2 > >!")
<< std::endl;
} else {
const TestCase test_case;
test_case.print_header(test_out);
test_out << std::endl;
EllipticSIPDG::EocStudy< TestCase, 1 > eoc_study_1(test_case);
auto errors_1 = eoc_study_1.run(test_out);
for (const auto& norm : eoc_study_1.provided_norms()) {
if (!Dune::Stuff::Common::FloatCmp::lt(errors_1[norm], eoc_study_1.expected_results(norm))) {
std::stringstream ss;
Dune::Stuff::Common::print(errors_1[norm], "errors (" + norm + ")", ss);
Dune::Stuff::Common::print(eoc_study_1.expected_results(norm), " expected results (" + norm + ")", ss);
DUNE_THROW_COLORFULLY(errors_are_not_as_expected, ss.str());
}
}
test_out << std::endl;
EllipticSIPDG::EocStudy< TestCase, 2 > eoc_study_2(test_case);
auto errors_2 = eoc_study_2.run(test_out);
for (const auto& norm : eoc_study_2.provided_norms())
if (!Dune::Stuff::Common::FloatCmp::lt(errors_2[norm], eoc_study_2.expected_results(norm))) {
std::stringstream ss;
Dune::Stuff::Common::print(errors_2[norm], "errors (" + norm + ")", ss);
Dune::Stuff::Common::print(eoc_study_2.expected_results(norm), " expected results (" + norm + ")", ss);
DUNE_THROW_COLORFULLY(errors_are_not_as_expected, ss.str());
}
}
}
}; // EllipticSIPDGDiscretization
template< class TestCase >
struct EllipticSWIPDGDiscretization
: public ::testing::Test
{
void produces_correct_results() const
{
const TestCase test_case;
test_case.print_header(test_out);
test_out << std::endl;
EllipticSWIPDG::EocStudy< TestCase, 1 > eoc_study_1(test_case);
auto errors_1 = eoc_study_1.run(test_out);
for (const auto& norm : eoc_study_1.provided_norms()) {
if (!Dune::Stuff::Common::FloatCmp::lt(errors_1[norm], eoc_study_1.expected_results(norm))) {
std::stringstream ss;
Dune::Stuff::Common::print(errors_1[norm], "errors (" + norm + ")", ss);
Dune::Stuff::Common::print(eoc_study_1.expected_results(norm), " expected results (" + norm + ")", ss);
DUNE_THROW_COLORFULLY(errors_are_not_as_expected, ss.str());
}
}
test_out << std::endl;
EllipticSWIPDG::EocStudy< TestCase, 2 > eoc_study_2(test_case);
auto errors_2 = eoc_study_2.run(test_out);
for (const auto& norm : eoc_study_2.provided_norms())
if (!Dune::Stuff::Common::FloatCmp::lt(errors_2[norm], eoc_study_2.expected_results(norm))) {
std::stringstream ss;
Dune::Stuff::Common::print(errors_2[norm], "errors (" + norm + ")", ss);
Dune::Stuff::Common::print(eoc_study_2.expected_results(norm), " expected results (" + norm + ")", ss);
DUNE_THROW_COLORFULLY(errors_are_not_as_expected, ss.str());
}
}
};
#endif
TYPED_TEST_CASE(EllipticCGDiscretization, AluConform2dTestCases);
TYPED_TEST(EllipticCGDiscretization, produces_correct_results)
{
this->produces_correct_results();
}
// TYPED_TEST_CASE(EllipticSIPDGDiscretization, AluConform2dTestCases);
// TYPED_TEST(EllipticSIPDGDiscretization, produces_correct_results) {
// this->produces_correct_results();
//}
// TYPED_TEST_CASE(EllipticSWIPDGDiscretization, AluConform2dTestCases);
// TYPED_TEST(EllipticSWIPDGDiscretization, produces_correct_results) {
// this->produces_correct_results();
//}
int main(int argc, char** argv)
{
try {
test_init(argc, argv);
return RUN_ALL_TESTS();
} catch (Dune::Exception& e) {
std::cerr << "\nDune reported error: " << e.what() << std::endl;
std::abort();
} catch (std::exception& e) {
std::cerr << "\n" << e.what() << std::endl;
std::abort();
} catch (...) {
std::cerr << "Unknown exception thrown!" << std::endl;
std::abort();
} // try
}
<commit_msg>[tests.stuff-la-solver] * refactor to allow for different discretizations * enable SIPDG and SWIPDG<commit_after>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// This one has to come first (includes the config.h)!
#include <dune/stuff/test/test_common.hh>
#include <dune/common/exceptions.hh>
#if HAVE_ALUGRID_SERIAL_H || HAVE_ALUGRID_PARALLEL_H
#define ENABLE_ALUGRID 1
#include <dune/grid/alugrid.hh>
#else
#error This test requires ALUGrid!
#endif
#include <tuple>
#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/common/type_utils.hh>
#include <dune/stuff/common/color.hh>
#include <dune/stuff/common/print.hh>
#include <dune/stuff/common/string.hh>
#include <dune/stuff/common/float_cmp.hh>
#include <dune/stuff/functions/combined.hh>
#include <dune/stuff/la/solver.hh>
#include "elliptic-testcases.hh"
#include "elliptic-cg-discretization.hh"
#include "elliptic-sipdg-discretization.hh"
#include "elliptic-swipdg-discretization.hh"
class errors_are_not_as_expected : public Dune::Exception
{
};
typedef Dune::ALUConformGrid<2, 2> AluConform2dGridType;
// change this to toggle output
std::ostream& test_out = std::cout;
// std::ostream& test_out = DSC_LOG.devnull();
typedef testing::
Types<std::tuple<EllipticTestCase::ESV07<AluConform2dGridType>, Dune::Stuff::LA::EigenRowMajorSparseMatrix<double>,
Dune::Stuff::LA::EigenDenseVector<double>>,
std::tuple<EllipticTestCase::LocalThermalBlock<AluConform2dGridType>,
Dune::Stuff::LA::EigenRowMajorSparseMatrix<double>, Dune::Stuff::LA::EigenDenseVector<double>>,
std::tuple<EllipticTestCase::ER07<AluConform2dGridType>, Dune::Stuff::LA::EigenRowMajorSparseMatrix<double>,
Dune::Stuff::LA::EigenDenseVector<double>>,
std::tuple<EllipticTestCase::MixedBoundaryTypes<AluConform2dGridType>,
Dune::Stuff::LA::EigenRowMajorSparseMatrix<double>, Dune::Stuff::LA::EigenDenseVector<double>>,
std::tuple<EllipticTestCase::Spe10Model1<AluConform2dGridType>,
Dune::Stuff::LA::EigenRowMajorSparseMatrix<double>, Dune::Stuff::LA::EigenDenseVector<double>>>
AluConform2dTestCases;
template <class TestTuple>
struct EllipticDiscretizations : public ::testing::Test
{
typedef typename std::tuple_element<0, TestTuple>::type TestCase;
typedef typename std::tuple_element<1, TestTuple>::type MatrixType;
typedef typename std::tuple_element<2, TestTuple>::type VectorType;
typedef typename TestCase::GridPartType GridPartType;
void produces_correct_results() const
{
using namespace Dune;
std::cout << " test case: " << Stuff::Common::Typename<TestCase>::value() << std::endl;
std::cout << " matrix type: " << Stuff::Common::Typename<MatrixType>::value() << std::endl;
std::cout << " vector type: " << Stuff::Common::Typename<VectorType>::value() << std::endl;
const TestCase test_case;
const auto grid_part = test_case.reference_grid_part();
run(EllipticCG::Discretization<GridPartType, 1, MatrixType, VectorType>(grid_part,
test_case.boundary_info(),
test_case.diffusion(),
test_case.force(),
test_case.dirichlet(),
test_case.neumann()),
"EllipticCG");
run(EllipticSIPDG::Discretization<GridPartType, 1, MatrixType, VectorType>(grid_part,
test_case.boundary_info(),
test_case.diffusion(),
test_case.force(),
test_case.dirichlet(),
test_case.neumann()),
"EllipticSIPDG");
run(EllipticSWIPDG::Discretization<GridPartType, 1, MatrixType, VectorType>(grid_part,
test_case.boundary_info(),
test_case.diffusion(),
test_case.force(),
test_case.dirichlet(),
test_case.neumann()),
"EllipticSWIPDG");
run(EllipticSWIPDG::Discretization<GridPartType, 2, MatrixType, VectorType>(grid_part,
test_case.boundary_info(),
test_case.diffusion(),
test_case.force(),
test_case.dirichlet(),
test_case.neumann()),
"EllipticSWIPDG");
}
template <class DiscretizationType>
void run(const DiscretizationType& discretization, const std::string discretization_id) const
{
using namespace Dune;
using namespace Dune::GDT;
discretization.assemble();
auto solution_vector = discretization.create_vector();
auto tmp_vector = discretization.create_vector();
Stuff::LA::Solver<MatrixType> linear_solver(discretization.system_matrix());
// print table header
const size_t min_first_column_width = std::string("solver option").size();
size_t first_column_width = min_first_column_width;
for (auto option : linear_solver.options())
first_column_width = std::max(first_column_width, option.size());
std::stringstream header;
std::stringstream delimiter;
header << " solver option";
delimiter << "--------------";
for (size_t ii = 0; ii <= first_column_width - min_first_column_width; ++ii) {
header << " ";
delimiter << "-";
}
header << "| time (s) | L^oo error (abs|rel) | thrown exception (see dune/stuff/solver.hh) ";
delimiter << "+----------+----------------------+---------------------------------------------";
std::cout << Stuff::Common::whitespaceify(header.str(), '=') << std::endl;
std::cout << " discretization: " << discretization_id << ", polorder " << discretization.polOrder
<< ", system size " << discretization.system_matrix().rows() << "x"
<< discretization.system_matrix().cols() << std::endl;
std::cout << delimiter.str() << std::endl;
std::cout << header.str() << std::endl;
std::cout << delimiter.str() << std::endl;
// loop over all available options
size_t printed_rows = 0;
for (auto option : linear_solver.options()) {
if (option != "qr.sparse" && option.substr(0, 3) != "cg.") {
const Stuff::Common::ConfigTree config = linear_solver.options(option);
// print delimiter after every 3rd row
if (printed_rows == 3) {
std::cout << delimiter.str() << std::endl;
printed_rows = 0;
}
// print
std::cout << " " << option;
for (size_t ii = 0; ii < first_column_width - option.size(); ++ii)
std::cout << " ";
// solve the system
Dune::Timer timer;
std::stringstream error_msg;
bool success = true;
try {
linear_solver.apply(discretization.rhs_vector(), solution_vector, option);
} catch (Stuff::Exceptions::linear_solver_failed_bc_matrix_did_not_fulfill_requirements&) {
error_msg << Stuff::Common::colorStringRed("matrix_did_not_fulfill_requirements");
if (option.substr(0, 3) == "cg.")
error_msg << " (OK for this discretization)";
success = false;
} catch (Stuff::Exceptions::linear_solver_failed_bc_it_did_not_converge&) {
error_msg << Stuff::Common::colorStringRed("did_not_converge");
} catch (Stuff::Exceptions::linear_solver_failed_bc_it_was_not_set_up_correctly&) {
error_msg << Stuff::Common::colorStringRed("was_not_set_up_correctly");
success = false;
} catch (Stuff::Exceptions::linear_solver_failed_bc_the_solution_does_not_solve_the_system&) {
error_msg << Stuff::Common::colorStringRed("solution_does_not_solve_the_system");
} catch (Stuff::Exceptions::linear_solver_failed&) {
error_msg << Stuff::Common::colorStringRed("linear_solver_failed");
success = false;
}
std::cout << " | " << std::setw(8) << std::setprecision(2) << std::fixed << timer.elapsed();
std::cout << " | ";
// test solution
if (success) {
discretization.system_matrix().mv(solution_vector, tmp_vector);
tmp_vector -= discretization.rhs_vector();
double threshhold = config.get<double>("post_check_solves_system");
if (config.has_key("precision"))
threshhold = config.get<double>("precision");
std::stringstream absolute_error;
absolute_error << std::setw(9) << std::setprecision(2) << std::scientific << tmp_vector.sup_norm();
if (tmp_vector.sup_norm() < threshhold)
std::cout << Stuff::Common::colorString(Stuff::Common::toString(absolute_error.str()),
Stuff::Common::Colors::green);
else if (tmp_vector.sup_norm() < std::exp(0.5 * std::log(threshhold)))
std::cout << Stuff::Common::colorString(Stuff::Common::toString(absolute_error.str()),
Stuff::Common::Colors::brown);
else
std::cout << Stuff::Common::colorStringRed(Stuff::Common::toString(absolute_error.str()));
std::cout << " | " << std::setw(8) << std::setprecision(2) << std::scientific
<< tmp_vector.sup_norm() / discretization.rhs_vector().sup_norm();
} else
std::cout << " ";
std::cout << " | " << error_msg.str() << std::endl;
++printed_rows;
}
} // loop over all available options
}
}; // EllipticDiscretizations
TYPED_TEST_CASE(EllipticDiscretizations, AluConform2dTestCases);
TYPED_TEST(EllipticDiscretizations, produces_correct_results)
{
this->produces_correct_results();
}
int main(int argc, char** argv)
{
try {
test_init(argc, argv);
return RUN_ALL_TESTS();
} catch (Dune::Exception& e) {
std::cerr << "\nDune reported error: " << e.what() << std::endl;
std::abort();
} catch (std::exception& e) {
std::cerr << "\n" << e.what() << std::endl;
std::abort();
} catch (...) {
std::cerr << "Unknown exception thrown!" << std::endl;
std::abort();
} // try
}
<|endoftext|>
|
<commit_before>#include "Archive.hpp"
#include <iostream>
WarArchive::WarArchive()
{
currentArchiveFileStream = NULL;
}
WarArchive::~WarArchive()
{
}
void WarArchive::LoadArchive(const std::string &filePath)
{
CleanArchive();
currentArchiveFileStream = new std::ifstream;
currentArchiveFileStream->open(filePath.c_str(), std::ios::binary);
currentArchiveFileStream->exceptions(std::ifstream::badbit | std::ifstream::failbit | std::ifstream::eofbit);
//Read in the magic number
currentArchiveFileStream->read((char *) &magicNumber, 4);
//Read in the number of entities (files) in the archive
currentArchiveFileStream->read((char *) &numberOfEntities, 2);
//Read in the types
currentArchiveFileStream->read((char *) &type, 2);
if(!fileOffsets)
{
fileOffsets = new std::vector<uint32_t>;
}
fileOffsets->resize(numberOfEntities);
//Populate the fileOffsets table
for(int currentGetFileOffset = 0; currentGetFileOffset < numberOfEntities; currentGetFileOffset++)
{
currentArchiveFileStream->read((char *) &fileOffsets->at(currentGetFileOffset), 4);
}
}
void WarArchive::LoadArchive(std::vector<char> *loadedFile)
{
/*CleanArchive();
std::vector<char>::iterator currentDataPosition = loadedFile->begin();
std::copy(currentDataPosition, (currentDataPosition += 4), &magicNumber);
std::copy(currentDataPosition, (currentDataPosition += 2), &numberOfEntities);
std::copy(currentDataPosition, (currentDataPosition += 2), &type);
fileOffsets->resize(numberOfEntities);
for(int currentOffsetLoad = 0; currentOffsetLoad < numberOfEntities; currentOffsetLoad++)
{
std::copy(currentDataPosition, (currentDataPosition +=4), fileOffsets->at(currentOffsetLoad));
}*/
//war->op[i] = war->data + war->filesize;
}
void WarArchive::ExtractEntity(const std::string &outFilePath, unsigned int entityNumber)
{
if(entityNumber > numberOfEntities)
{
//throw out of bounds error
#warning throw here
}
//unknown
int flags;
std::ofstream outFile;
outFile.open(outFilePath.c_str(), std::ios::binary);
outFile.exceptions(std::ofstream::failbit);
currentArchiveFileStream->seekg(fileOffsets->at(entityNumber));
int unCompressedFileLength;
currentArchiveFileStream->read((char *) &unCompressedFileLength, 3);
//??
#warning - 1 is a hack
flags = (unCompressedFileLength >> 10) - 1;
unCompressedFileLength &= 0x00FFFFFF;
//The data is compressed
if(flags == 0x20)
{
uint8_t ep;
int bi = 0;
for(int currentCompressedByte = 0; currentCompressedByte < unCompressedFileLength;)
{
uint16_t bflags;
currentArchiveFileStream->read((char *) &bflags, 1);
std::cout << "Bflags " << (int) bflags << '\n';
for(int currentUncompressedByte = 0; currentUncompressedByte < 8;)
{
uint8_t j;
int o;
if(bflags & 1)
{
currentArchiveFileStream->read((char *) &j, 1);
outFile.write((char *) &j, 1);
}
else
{
currentArchiveFileStream->read((char *) &o, 2);
j = (o >> 12) + 3;
o &= 0xFFF;
}
bflags >>= 1;
}
}
}
//The data is uncompressed
else if(flags == 0x00)
{
currentArchiveFileStream->read((char *) &outFile, unCompressedFileLength);
}
//Problem we don't know what the flag means : |
else
{
//throw error
#warning throw error
throw "fail";
}
outFile.close();
}
void ExtractEntity(std::vector<char> *uncompressedFile, unsigned int entityNumber)
{
}
void WarArchive::CloseArchive()
{
if(currentArchiveFileStream)
{
if(currentArchiveFileStream->is_open())
{
currentArchiveFileStream->close();
}
delete currentArchiveFileStream;
currentArchiveFileStream = NULL;
}
}
void WarArchive::CleanArchive()
{
CloseArchive();
if(fileOffsets)
{
delete fileOffsets;
fileOffsets = NULL;
}
}<commit_msg>*Issues with decompressing and vector<commit_after>#include "Archive.hpp"
#include <iostream>
WarArchive::WarArchive()
{
currentArchiveFileStream = NULL;
}
WarArchive::~WarArchive()
{
}
void WarArchive::LoadArchive(const std::string &filePath)
{
CleanArchive();
currentArchiveFileStream = new std::ifstream;
currentArchiveFileStream->open(filePath.c_str(), std::ios::binary);
currentArchiveFileStream->exceptions(std::ifstream::badbit | std::ifstream::failbit | std::ifstream::eofbit);
//Read in the magic number
currentArchiveFileStream->read((char *) &magicNumber, 4);
//Read in the number of entities (files) in the archive
currentArchiveFileStream->read((char *) &numberOfEntities, 2);
//Read in the types
currentArchiveFileStream->read((char *) &type, 2);
if(!fileOffsets)
{
fileOffsets = new std::vector<uint32_t>;
}
fileOffsets->resize(numberOfEntities);
//Populate the fileOffsets table
for(int currentGetFileOffset = 0; currentGetFileOffset < numberOfEntities; currentGetFileOffset++)
{
currentArchiveFileStream->read((char *) &fileOffsets->at(currentGetFileOffset), 4);
}
}
void WarArchive::LoadArchive(std::vector<char> *loadedFile)
{
/*CleanArchive();
std::vector<char>::iterator currentDataPosition = loadedFile->begin();
std::copy(currentDataPosition, (currentDataPosition += 4), &magicNumber);
std::copy(currentDataPosition, (currentDataPosition += 2), &numberOfEntities);
std::copy(currentDataPosition, (currentDataPosition += 2), &type);
fileOffsets->resize(numberOfEntities);
for(int currentOffsetLoad = 0; currentOffsetLoad < numberOfEntities; currentOffsetLoad++)
{
std::copy(currentDataPosition, (currentDataPosition +=4), fileOffsets->at(currentOffsetLoad));
}*/
//war->op[i] = war->data + war->filesize;
}
void WarArchive::ExtractEntity(const std::string &outFilePath, unsigned int entityNumber)
{
if(entityNumber > numberOfEntities)
{
//throw out of bounds error
throw "bad";
#warning throw here
}
//unknown
int flags;
int dp = 0;
std::ofstream outFile;
outFile.open(outFilePath.c_str(), std::ios::binary);
outFile.exceptions(std::ofstream::failbit);
currentArchiveFileStream->seekg(fileOffsets->at(entityNumber));
int unCompressedFileLength;
currentArchiveFileStream->read((char *) &unCompressedFileLength, 4);
flags = (unCompressedFileLength >> 24);
unCompressedFileLength &= 0x00FFFFFF;
std::vector<uint8_t> output;
output.resize(unCompressedFileLength);
//The data is compressed
if(flags == 0x20)
{
uint8_t ep;
int bi = 0;
unsigned char buf[409600];
for(int currentCompressedByte = 0; currentCompressedByte < unCompressedFileLength;)
{
int i;
int bflags;
currentArchiveFileStream->read((char *) &bflags, 1);
for(int i= 0; i < 8; ++i)
{
int j;
int o;
if(bflags & 1)
{
currentArchiveFileStream->read((char *) &j, 1);
output.at(dp++) = j;
buf[bi++ & 0xFFF] = j;
}
else
{
currentArchiveFileStream->read((char *) &o, 2);
j = (o >> 12) + 3;
o &= 0xFFF;
while (j--)
{
buf[bi++ & 0xFFF] = output.at(dp++) = buf[o++ & 0xFFF];
if(dp == unCompressedFileLength)
{
break;
}
}
}
}
}
}
outFile.close();
}
void ExtractEntity(std::vector<char> *uncompressedFile, unsigned int entityNumber)
{
}
void WarArchive::CloseArchive()
{
if(currentArchiveFileStream)
{
if(currentArchiveFileStream->is_open())
{
currentArchiveFileStream->close();
}
delete currentArchiveFileStream;
currentArchiveFileStream = NULL;
}
}
void WarArchive::CleanArchive()
{
CloseArchive();
if(fileOffsets)
{
delete fileOffsets;
fileOffsets = NULL;
}
}<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <QDebug>
#include <QStringList>
#include <QtMultimedia/qmediaserviceprovider.h>
#include <QtMultimedia/qmediaserviceproviderplugin.h>
#include <QtMultimedia/private/qmediapluginloader_p.h>
#include <QtMultimedia/qmediaobject.h>
#include <QtMultimedia/qmediaservice.h>
#include <QtMultimedia/qmediaplayer.h>
class MockMediaService : public QMediaService
{
Q_OBJECT
public:
MockMediaService(const QString& name, QObject *parent = 0) : QMediaService(parent)
{ setObjectName(name); }
~MockMediaService() {}
QMediaControl* control(const char *) const {return 0;}
};
class MockServicePlugin1 : public QMediaServiceProviderPlugin,
public QMediaServiceSupportedFormatsInterface,
public QMediaServiceSupportedDevicesInterface
{
Q_OBJECT
Q_INTERFACES(QMediaServiceSupportedFormatsInterface)
Q_INTERFACES(QMediaServiceSupportedDevicesInterface)
public:
QStringList keys() const
{
return QStringList() <<
QLatin1String(Q_MEDIASERVICE_MEDIAPLAYER);
}
QMediaService* create(QString const& key)
{
if (keys().contains(key))
return new MockMediaService("MockServicePlugin1");
else
return 0;
}
void release(QMediaService *service)
{
delete service;
}
QtMedia::SupportEstimate hasSupport(const QString &mimeType, const QStringList& codecs) const
{
if (codecs.contains(QLatin1String("mpeg4")))
return QtMedia::NotSupported;
if (mimeType == "audio/ogg") {
return QtMedia::ProbablySupported;
}
return QtMedia::MaybeSupported;
}
QStringList supportedMimeTypes() const
{
return QStringList("audio/ogg");
}
QList<QByteArray> devices(const QByteArray &service) const
{
QList<QByteArray> res;
return res;
}
QString deviceDescription(const QByteArray &service, const QByteArray &device)
{
if (devices(service).contains(device))
return QString(device)+" description";
else
return QString();
}
};
class MockServicePlugin2 : public QMediaServiceProviderPlugin,
public QMediaServiceSupportedFormatsInterface,
public QMediaServiceFeaturesInterface
{
Q_OBJECT
Q_INTERFACES(QMediaServiceSupportedFormatsInterface)
Q_INTERFACES(QMediaServiceFeaturesInterface)
public:
QStringList keys() const
{
return QStringList() << QLatin1String(Q_MEDIASERVICE_MEDIAPLAYER);
}
QMediaService* create(QString const& key)
{
if (keys().contains(key))
return new MockMediaService("MockServicePlugin2");
else
return 0;
}
void release(QMediaService *service)
{
delete service;
}
QtMedia::SupportEstimate hasSupport(const QString &mimeType, const QStringList& codecs) const
{
Q_UNUSED(codecs);
if (mimeType == "audio/wav")
return QtMedia::PreferedService;
return QtMedia::NotSupported;
}
QStringList supportedMimeTypes() const
{
return QStringList("audio/wav");
}
QMediaServiceProviderHint::Features supportedFeatures(const QByteArray &service) const
{
if (service == QByteArray(Q_MEDIASERVICE_MEDIAPLAYER))
return QMediaServiceProviderHint::LowLatencyPlayback;
else
return 0;
}
};
class MockServicePlugin3 : public QMediaServiceProviderPlugin,
public QMediaServiceSupportedDevicesInterface
{
Q_OBJECT
Q_INTERFACES(QMediaServiceSupportedDevicesInterface)
public:
QStringList keys() const
{
return QStringList() <<
QLatin1String(Q_MEDIASERVICE_MEDIAPLAYER);
}
QMediaService* create(QString const& key)
{
if (keys().contains(key))
return new MockMediaService("MockServicePlugin3");
else
return 0;
}
void release(QMediaService *service)
{
delete service;
}
QList<QByteArray> devices(const QByteArray &service) const
{
QList<QByteArray> res;
return res;
}
QString deviceDescription(const QByteArray &service, const QByteArray &device)
{
if (devices(service).contains(device))
return QString(device)+" description";
else
return QString();
}
};
class MockMediaServiceProvider : public QMediaServiceProvider
{
QMediaService* requestService(const QByteArray &type, const QMediaServiceProviderHint &)
{
Q_UNUSED(type);
return 0;
}
void releaseService(QMediaService *service)
{
Q_UNUSED(service);
}
};
class tst_QMediaServiceProvider : public QObject
{
Q_OBJECT
public slots:
void initTestCase();
private slots:
void testDefaultProviderAvailable();
void testObtainService();
void testHasSupport();
void testSupportedMimeTypes();
void testProviderHints();
private:
QObjectList plugins;
};
void tst_QMediaServiceProvider::initTestCase()
{
plugins << new MockServicePlugin1;
plugins << new MockServicePlugin2;
plugins << new MockServicePlugin3;
QMediaPluginLoader::setStaticPlugins(QLatin1String("/mediaservice"), plugins);
}
void tst_QMediaServiceProvider::testDefaultProviderAvailable()
{
// Must always be a default provider available
QVERIFY(QMediaServiceProvider::defaultServiceProvider() != 0);
}
void tst_QMediaServiceProvider::testObtainService()
{
QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider();
if (provider == 0)
QSKIP("No default provider", SkipSingle);
QMediaService *service = 0;
QTest::ignoreMessage(QtWarningMsg, "Load static plugins for \"/mediaservice/\" ");
// Player
service = provider->requestService(Q_MEDIASERVICE_MEDIAPLAYER);
QVERIFY(service != 0);
provider->releaseService(service);
}
void tst_QMediaServiceProvider::testHasSupport()
{
MockMediaServiceProvider mockProvider;
QCOMPARE(mockProvider.hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), "video/ogv", QStringList()),
QtMedia::MaybeSupported);
QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider();
if (provider == 0)
QSKIP("No default provider", SkipSingle);
QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), "video/ogv", QStringList()),
QtMedia::MaybeSupported);
QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), "audio/ogg", QStringList()),
QtMedia::ProbablySupported);
//while the service returns PreferredService, provider should return ProbablySupported
QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), "audio/wav", QStringList()),
QtMedia::ProbablySupported);
//even while all the plugins with "hasSupport" returned NotSupported,
//MockServicePlugin3 has no "hasSupport" interface, so MaybeSupported
QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), "video/avi",
QStringList() << "mpeg4"),
QtMedia::MaybeSupported);
QCOMPARE(provider->hasSupport(QByteArray("non existing service"), "video/ogv", QStringList()),
QtMedia::NotSupported);
QCOMPARE(QMediaPlayer::hasSupport("video/ogv"), QtMedia::MaybeSupported);
QCOMPARE(QMediaPlayer::hasSupport("audio/ogg"), QtMedia::ProbablySupported);
QCOMPARE(QMediaPlayer::hasSupport("audio/wav"), QtMedia::ProbablySupported);
//ensure the correct media player plugin is choosen for mime type
QMediaPlayer simplePlayer(0, QMediaPlayer::LowLatency);
QCOMPARE(simplePlayer.service()->objectName(), QLatin1String("MockServicePlugin2"));
QMediaPlayer mediaPlayer;
QVERIFY(mediaPlayer.service()->objectName() != QLatin1String("MockServicePlugin2"));
}
void tst_QMediaServiceProvider::testSupportedMimeTypes()
{
QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider();
if (provider == 0)
QSKIP("No default provider", SkipSingle);
QVERIFY(provider->supportedMimeTypes(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER)).contains("audio/ogg"));
QVERIFY(!provider->supportedMimeTypes(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER)).contains("audio/mp3"));
}
void tst_QMediaServiceProvider::testProviderHints()
{
{
QMediaServiceProviderHint hint;
QVERIFY(hint.isNull());
QCOMPARE(hint.type(), QMediaServiceProviderHint::Null);
QVERIFY(hint.device().isEmpty());
QVERIFY(hint.mimeType().isEmpty());
QVERIFY(hint.codecs().isEmpty());
QCOMPARE(hint.features(), 0);
}
{
QByteArray deviceName(QByteArray("testDevice"));
QMediaServiceProviderHint hint(deviceName);
QVERIFY(!hint.isNull());
QCOMPARE(hint.type(), QMediaServiceProviderHint::Device);
QCOMPARE(hint.device(), deviceName);
QVERIFY(hint.mimeType().isEmpty());
QVERIFY(hint.codecs().isEmpty());
QCOMPARE(hint.features(), 0);
}
{
QMediaServiceProviderHint hint(QMediaServiceProviderHint::LowLatencyPlayback);
QVERIFY(!hint.isNull());
QCOMPARE(hint.type(), QMediaServiceProviderHint::SupportedFeatures);
QVERIFY(hint.device().isEmpty());
QVERIFY(hint.mimeType().isEmpty());
QVERIFY(hint.codecs().isEmpty());
QCOMPARE(hint.features(), QMediaServiceProviderHint::LowLatencyPlayback);
}
{
QString mimeType(QLatin1String("video/ogg"));
QStringList codecs;
codecs << "theora" << "vorbis";
QMediaServiceProviderHint hint(mimeType,codecs);
QVERIFY(!hint.isNull());
QCOMPARE(hint.type(), QMediaServiceProviderHint::ContentType);
QVERIFY(hint.device().isEmpty());
QCOMPARE(hint.mimeType(), mimeType);
QCOMPARE(hint.codecs(), codecs);
QMediaServiceProviderHint hint2(hint);
QVERIFY(!hint2.isNull());
QCOMPARE(hint2.type(), QMediaServiceProviderHint::ContentType);
QVERIFY(hint2.device().isEmpty());
QCOMPARE(hint2.mimeType(), mimeType);
QCOMPARE(hint2.codecs(), codecs);
QMediaServiceProviderHint hint3;
QVERIFY(hint3.isNull());
hint3 = hint;
QVERIFY(!hint3.isNull());
QCOMPARE(hint3.type(), QMediaServiceProviderHint::ContentType);
QVERIFY(hint3.device().isEmpty());
QCOMPARE(hint3.mimeType(), mimeType);
QCOMPARE(hint3.codecs(), codecs);
QCOMPARE(hint, hint2);
QCOMPARE(hint3, hint2);
QMediaServiceProviderHint hint4(mimeType,codecs);
QCOMPARE(hint, hint4);
QMediaServiceProviderHint hint5(mimeType,QStringList());
QVERIFY(hint != hint5);
}
}
QTEST_MAIN(tst_QMediaServiceProvider)
#include "tst_qmediaserviceprovider.moc"
<commit_msg>Fix QMediaServiceProvider test.<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <QDebug>
#include <QStringList>
#include <QtMultimedia/qmediaserviceprovider.h>
#include <QtMultimedia/qmediaserviceproviderplugin.h>
#include <QtMultimedia/private/qmediapluginloader_p.h>
#include <QtMultimedia/qmediaobject.h>
#include <QtMultimedia/qmediaservice.h>
#include <QtMultimedia/qmediaplayer.h>
class MockMediaService : public QMediaService
{
Q_OBJECT
public:
MockMediaService(const QString& name, QObject *parent = 0) : QMediaService(parent)
{ setObjectName(name); }
~MockMediaService() {}
QMediaControl* control(const char *) const {return 0;}
};
class MockServicePlugin1 : public QMediaServiceProviderPlugin,
public QMediaServiceSupportedFormatsInterface,
public QMediaServiceSupportedDevicesInterface
{
Q_OBJECT
Q_INTERFACES(QMediaServiceSupportedFormatsInterface)
Q_INTERFACES(QMediaServiceSupportedDevicesInterface)
public:
QStringList keys() const
{
return QStringList() <<
QLatin1String(Q_MEDIASERVICE_MEDIAPLAYER);
}
QMediaService* create(QString const& key)
{
if (keys().contains(key))
return new MockMediaService("MockServicePlugin1");
else
return 0;
}
void release(QMediaService *service)
{
delete service;
}
QtMedia::SupportEstimate hasSupport(const QString &mimeType, const QStringList& codecs) const
{
if (codecs.contains(QLatin1String("mpeg4")))
return QtMedia::NotSupported;
if (mimeType == "audio/ogg") {
return QtMedia::ProbablySupported;
}
return QtMedia::MaybeSupported;
}
QStringList supportedMimeTypes() const
{
return QStringList("audio/ogg");
}
QList<QByteArray> devices(const QByteArray &service) const
{
Q_UNUSED(service);
QList<QByteArray> res;
return res;
}
QString deviceDescription(const QByteArray &service, const QByteArray &device)
{
if (devices(service).contains(device))
return QString(device)+" description";
else
return QString();
}
};
class MockServicePlugin2 : public QMediaServiceProviderPlugin,
public QMediaServiceSupportedFormatsInterface,
public QMediaServiceFeaturesInterface
{
Q_OBJECT
Q_INTERFACES(QMediaServiceSupportedFormatsInterface)
Q_INTERFACES(QMediaServiceFeaturesInterface)
public:
QStringList keys() const
{
return QStringList() << QLatin1String(Q_MEDIASERVICE_MEDIAPLAYER);
}
QMediaService* create(QString const& key)
{
if (keys().contains(key))
return new MockMediaService("MockServicePlugin2");
else
return 0;
}
void release(QMediaService *service)
{
delete service;
}
QtMedia::SupportEstimate hasSupport(const QString &mimeType, const QStringList& codecs) const
{
Q_UNUSED(codecs);
if (mimeType == "audio/wav")
return QtMedia::PreferedService;
return QtMedia::NotSupported;
}
QStringList supportedMimeTypes() const
{
return QStringList("audio/wav");
}
QMediaServiceProviderHint::Features supportedFeatures(const QByteArray &service) const
{
if (service == QByteArray(Q_MEDIASERVICE_MEDIAPLAYER))
return QMediaServiceProviderHint::LowLatencyPlayback;
else
return 0;
}
};
class MockServicePlugin3 : public QMediaServiceProviderPlugin,
public QMediaServiceSupportedDevicesInterface
{
Q_OBJECT
Q_INTERFACES(QMediaServiceSupportedDevicesInterface)
public:
QStringList keys() const
{
return QStringList() <<
QLatin1String(Q_MEDIASERVICE_MEDIAPLAYER);
}
QMediaService* create(QString const& key)
{
if (keys().contains(key))
return new MockMediaService("MockServicePlugin3");
else
return 0;
}
void release(QMediaService *service)
{
delete service;
}
QList<QByteArray> devices(const QByteArray &service) const
{
Q_UNUSED(service);
QList<QByteArray> res;
return res;
}
QString deviceDescription(const QByteArray &service, const QByteArray &device)
{
if (devices(service).contains(device))
return QString(device)+" description";
else
return QString();
}
};
class MockMediaServiceProvider : public QMediaServiceProvider
{
QMediaService* requestService(const QByteArray &type, const QMediaServiceProviderHint &)
{
Q_UNUSED(type);
return 0;
}
void releaseService(QMediaService *service)
{
Q_UNUSED(service);
}
};
class tst_QMediaServiceProvider : public QObject
{
Q_OBJECT
public slots:
void initTestCase();
private slots:
void testDefaultProviderAvailable();
void testObtainService();
void testHasSupport();
void testSupportedMimeTypes();
void testProviderHints();
private:
QObjectList plugins;
};
void tst_QMediaServiceProvider::initTestCase()
{
plugins << new MockServicePlugin1;
plugins << new MockServicePlugin2;
plugins << new MockServicePlugin3;
QMediaPluginLoader::setStaticPlugins(QLatin1String("/mediaservices"), plugins);
}
void tst_QMediaServiceProvider::testDefaultProviderAvailable()
{
// Must always be a default provider available
QVERIFY(QMediaServiceProvider::defaultServiceProvider() != 0);
}
void tst_QMediaServiceProvider::testObtainService()
{
QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider();
if (provider == 0)
QSKIP("No default provider", SkipSingle);
QMediaService *service = 0;
// Player
service = provider->requestService(Q_MEDIASERVICE_MEDIAPLAYER);
QVERIFY(service != 0);
provider->releaseService(service);
}
void tst_QMediaServiceProvider::testHasSupport()
{
MockMediaServiceProvider mockProvider;
QCOMPARE(mockProvider.hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), "video/ogv", QStringList()),
QtMedia::MaybeSupported);
QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider();
if (provider == 0)
QSKIP("No default provider", SkipSingle);
QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), "video/ogv", QStringList()),
QtMedia::MaybeSupported);
QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), "audio/ogg", QStringList()),
QtMedia::ProbablySupported);
//while the service returns PreferredService, provider should return ProbablySupported
QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), "audio/wav", QStringList()),
QtMedia::ProbablySupported);
//even while all the plugins with "hasSupport" returned NotSupported,
//MockServicePlugin3 has no "hasSupport" interface, so MaybeSupported
QCOMPARE(provider->hasSupport(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER), "video/avi",
QStringList() << "mpeg4"),
QtMedia::MaybeSupported);
QCOMPARE(provider->hasSupport(QByteArray("non existing service"), "video/ogv", QStringList()),
QtMedia::NotSupported);
QCOMPARE(QMediaPlayer::hasSupport("video/ogv"), QtMedia::MaybeSupported);
QCOMPARE(QMediaPlayer::hasSupport("audio/ogg"), QtMedia::ProbablySupported);
QCOMPARE(QMediaPlayer::hasSupport("audio/wav"), QtMedia::ProbablySupported);
//ensure the correct media player plugin is choosen for mime type
QMediaPlayer simplePlayer(0, QMediaPlayer::LowLatency);
QCOMPARE(simplePlayer.service()->objectName(), QLatin1String("MockServicePlugin2"));
QMediaPlayer mediaPlayer;
QVERIFY(mediaPlayer.service()->objectName() != QLatin1String("MockServicePlugin2"));
}
void tst_QMediaServiceProvider::testSupportedMimeTypes()
{
QMediaServiceProvider *provider = QMediaServiceProvider::defaultServiceProvider();
if (provider == 0)
QSKIP("No default provider", SkipSingle);
QVERIFY(provider->supportedMimeTypes(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER)).contains("audio/ogg"));
QVERIFY(!provider->supportedMimeTypes(QByteArray(Q_MEDIASERVICE_MEDIAPLAYER)).contains("audio/mp3"));
}
void tst_QMediaServiceProvider::testProviderHints()
{
{
QMediaServiceProviderHint hint;
QVERIFY(hint.isNull());
QCOMPARE(hint.type(), QMediaServiceProviderHint::Null);
QVERIFY(hint.device().isEmpty());
QVERIFY(hint.mimeType().isEmpty());
QVERIFY(hint.codecs().isEmpty());
QCOMPARE(hint.features(), 0);
}
{
QByteArray deviceName(QByteArray("testDevice"));
QMediaServiceProviderHint hint(deviceName);
QVERIFY(!hint.isNull());
QCOMPARE(hint.type(), QMediaServiceProviderHint::Device);
QCOMPARE(hint.device(), deviceName);
QVERIFY(hint.mimeType().isEmpty());
QVERIFY(hint.codecs().isEmpty());
QCOMPARE(hint.features(), 0);
}
{
QMediaServiceProviderHint hint(QMediaServiceProviderHint::LowLatencyPlayback);
QVERIFY(!hint.isNull());
QCOMPARE(hint.type(), QMediaServiceProviderHint::SupportedFeatures);
QVERIFY(hint.device().isEmpty());
QVERIFY(hint.mimeType().isEmpty());
QVERIFY(hint.codecs().isEmpty());
QCOMPARE(hint.features(), QMediaServiceProviderHint::LowLatencyPlayback);
}
{
QString mimeType(QLatin1String("video/ogg"));
QStringList codecs;
codecs << "theora" << "vorbis";
QMediaServiceProviderHint hint(mimeType,codecs);
QVERIFY(!hint.isNull());
QCOMPARE(hint.type(), QMediaServiceProviderHint::ContentType);
QVERIFY(hint.device().isEmpty());
QCOMPARE(hint.mimeType(), mimeType);
QCOMPARE(hint.codecs(), codecs);
QMediaServiceProviderHint hint2(hint);
QVERIFY(!hint2.isNull());
QCOMPARE(hint2.type(), QMediaServiceProviderHint::ContentType);
QVERIFY(hint2.device().isEmpty());
QCOMPARE(hint2.mimeType(), mimeType);
QCOMPARE(hint2.codecs(), codecs);
QMediaServiceProviderHint hint3;
QVERIFY(hint3.isNull());
hint3 = hint;
QVERIFY(!hint3.isNull());
QCOMPARE(hint3.type(), QMediaServiceProviderHint::ContentType);
QVERIFY(hint3.device().isEmpty());
QCOMPARE(hint3.mimeType(), mimeType);
QCOMPARE(hint3.codecs(), codecs);
QCOMPARE(hint, hint2);
QCOMPARE(hint3, hint2);
QMediaServiceProviderHint hint4(mimeType,codecs);
QCOMPARE(hint, hint4);
QMediaServiceProviderHint hint5(mimeType,QStringList());
QVERIFY(hint != hint5);
}
}
QTEST_MAIN(tst_QMediaServiceProvider)
#include "tst_qmediaserviceprovider.moc"
<|endoftext|>
|
<commit_before>#include "file-utils.h"
#include <QDir>
#include <QFileInfo>
#include <QString>
#include <QStringList>
bool copyRecursively(QString srcFilePath, QString tgtFilePath, bool overwrite)
{
// Trim directory names of their trailing slashes
if (srcFilePath.endsWith(QDir::separator())) {
srcFilePath.chop(1);
}
if (tgtFilePath.endsWith(QDir::separator())) {
tgtFilePath.chop(1);
}
// Directly copy files using Qt function
if (!QFileInfo(srcFilePath).isDir()) {
if (QFile::exists(tgtFilePath)) {
if (overwrite) {
QFile::remove(tgtFilePath);
} else {
return false;
}
}
return QFile(srcFilePath).copy(tgtFilePath);
}
// Try to create the target directory
QDir targetDir(tgtFilePath);
targetDir.cdUp();
if (!targetDir.mkpath(QDir(tgtFilePath).dirName())) {
return false;
}
QDir sourceDir(srcFilePath);
const QStringList fileNames = sourceDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden | QDir::System);
for (const QString &fileName : fileNames) {
const QString newSrcFilePath = srcFilePath + QDir::separator() + fileName;
const QString newTgtFilePath = tgtFilePath + QDir::separator() + fileName;
if (!copyRecursively(newSrcFilePath, newTgtFilePath, overwrite)) {
return false;
}
}
return true;
}
bool safeWriteFile(const QString &filePath, const QByteArray &data, bool backup)
{
const QString newFilePath = filePath + ".new";
// Write data to temporary "new" file
QFile newFile(newFilePath);
if (!newFile.open(QFile::WriteOnly | QFile::Text | QFile::Truncate)) {
return false;
}
newFile.write(data);
newFile.close();
// Rename does not overwrite, so we need to first clear the original file path
if (QFile::exists(filePath)) {
if (backup) {
// Move the file to a "bak" file to ensure no data is lost
const QString oldFilePath = filePath + ".bak";
if (QFile::exists(oldFilePath) && !QFile::remove(oldFilePath)) {
return false;
}
if (!QFile::rename(filePath, oldFilePath)) {
return false;
}
} else {
if (!QFile::remove(filePath)) {
return false;
}
}
}
// Move new file to existing one
return QFile::rename(newFilePath, filePath);
}
<commit_msg>Use QSaveFile to safely write to disk (issue #2199)<commit_after>#include "file-utils.h"
#include <QDir>
#include <QFileInfo>
#include <QSaveFile>
#include <QString>
#include <QStringList>
bool copyRecursively(QString srcFilePath, QString tgtFilePath, bool overwrite)
{
// Trim directory names of their trailing slashes
if (srcFilePath.endsWith(QDir::separator())) {
srcFilePath.chop(1);
}
if (tgtFilePath.endsWith(QDir::separator())) {
tgtFilePath.chop(1);
}
// Directly copy files using Qt function
if (!QFileInfo(srcFilePath).isDir()) {
if (QFile::exists(tgtFilePath)) {
if (overwrite) {
QFile::remove(tgtFilePath);
} else {
return false;
}
}
return QFile(srcFilePath).copy(tgtFilePath);
}
// Try to create the target directory
QDir targetDir(tgtFilePath);
targetDir.cdUp();
if (!targetDir.mkpath(QDir(tgtFilePath).dirName())) {
return false;
}
QDir sourceDir(srcFilePath);
const QStringList fileNames = sourceDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden | QDir::System);
for (const QString &fileName : fileNames) {
const QString newSrcFilePath = srcFilePath + QDir::separator() + fileName;
const QString newTgtFilePath = tgtFilePath + QDir::separator() + fileName;
if (!copyRecursively(newSrcFilePath, newTgtFilePath, overwrite)) {
return false;
}
}
return true;
}
bool safeWriteFile(const QString &filePath, const QByteArray &data, bool backup)
{
// Copy the file to a "bak" file to ensure no data is lost
if (backup) {
const QString backupFilePath = filePath + ".bak";
if (QFile::exists(backupFilePath) && !QFile::remove(backupFilePath)) {
return false;
}
if (!QFile::copy(filePath, backupFilePath)) {
return false;
}
}
// Use QSaveFile to safely write data to the file
QSaveFile file(filePath);
if (!file.open(QFile::WriteOnly | QFile::Text | QFile::Truncate)) {
return false;
}
file.write(data);
return file.commit();
}
<|endoftext|>
|
<commit_before>//===- DCE.cpp - Code to perform dead code elimination --------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements dead inst elimination and dead code elimination.
//
// Dead Inst Elimination performs a single pass over the function removing
// instructions that are obviously dead. Dead Code Elimination is similar, but
// it rechecks instructions that were used by removed instructions to see if
// they are newly dead.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "dce"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Instruction.h"
#include "llvm/Pass.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/InstIterator.h"
#include "llvm/ADT/Statistic.h"
#include <set>
using namespace llvm;
STATISTIC(DIEEliminated, "Number of insts removed by DIE pass");
STATISTIC(DCEEliminated, "Number of insts removed");
namespace {
//===--------------------------------------------------------------------===//
// DeadInstElimination pass implementation
//
struct VISIBILITY_HIDDEN DeadInstElimination : public BasicBlockPass {
static char ID; // Pass identification, replacement for typeid
DeadInstElimination() : BasicBlockPass(intptr_t(&ID)) {}
virtual bool runOnBasicBlock(BasicBlock &BB) {
bool Changed = false;
for (BasicBlock::iterator DI = BB.begin(); DI != BB.end(); )
if (dceInstruction(DI)) {
Changed = true;
++DIEEliminated;
} else
++DI;
return Changed;
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
}
};
}
char DeadInstElimination::ID = 0;
static RegisterPass<DeadInstElimination>
X("die", "Dead Instruction Elimination");
Pass *llvm::createDeadInstEliminationPass() {
return new DeadInstElimination();
}
namespace {
//===--------------------------------------------------------------------===//
// DeadCodeElimination pass implementation
//
struct DCE : public FunctionPass {
static char ID; // Pass identification, replacement for typeid
DCE() : FunctionPass(&ID) {}
virtual bool runOnFunction(Function &F);
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
}
};
}
char DCE::ID = 0;
static RegisterPass<DCE> Y("dce", "Dead Code Elimination");
bool DCE::runOnFunction(Function &F) {
// Start out with all of the instructions in the worklist...
std::vector<Instruction*> WorkList;
for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
WorkList.push_back(&*i);
// Loop over the worklist finding instructions that are dead. If they are
// dead make them drop all of their uses, making other instructions
// potentially dead, and work until the worklist is empty.
//
bool MadeChange = false;
while (!WorkList.empty()) {
Instruction *I = WorkList.back();
WorkList.pop_back();
if (isInstructionTriviallyDead(I)) { // If the instruction is dead.
// Loop over all of the values that the instruction uses, if there are
// instructions being used, add them to the worklist, because they might
// go dead after this one is removed.
//
for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
if (Instruction *Used = dyn_cast<Instruction>(*OI))
WorkList.push_back(Used);
// Remove the instruction.
I->eraseFromParent();
// Remove the instruction from the worklist if it still exists in it.
for (std::vector<Instruction*>::iterator WI = WorkList.begin();
WI != WorkList.end(); ) {
if (*WI == I)
WI = WorkList.erase(WI);
else
++WI;
}
MadeChange = true;
++DCEEliminated;
}
}
return MadeChange;
}
FunctionPass *llvm::createDeadCodeEliminationPass() {
return new DCE();
}
<commit_msg>simplify this logic.<commit_after>//===- DCE.cpp - Code to perform dead code elimination --------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements dead inst elimination and dead code elimination.
//
// Dead Inst Elimination performs a single pass over the function removing
// instructions that are obviously dead. Dead Code Elimination is similar, but
// it rechecks instructions that were used by removed instructions to see if
// they are newly dead.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "dce"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Instruction.h"
#include "llvm/Pass.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/InstIterator.h"
#include "llvm/ADT/Statistic.h"
#include <set>
using namespace llvm;
STATISTIC(DIEEliminated, "Number of insts removed by DIE pass");
STATISTIC(DCEEliminated, "Number of insts removed");
namespace {
//===--------------------------------------------------------------------===//
// DeadInstElimination pass implementation
//
struct VISIBILITY_HIDDEN DeadInstElimination : public BasicBlockPass {
static char ID; // Pass identification, replacement for typeid
DeadInstElimination() : BasicBlockPass(intptr_t(&ID)) {}
virtual bool runOnBasicBlock(BasicBlock &BB) {
bool Changed = false;
for (BasicBlock::iterator DI = BB.begin(); DI != BB.end(); ) {
Instruction *Inst = DI++;
if (isInstructionTriviallyDead(Inst)) {
Inst->eraseFromParent();
Changed = true;
++DIEEliminated;
}
}
return Changed;
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
}
};
}
char DeadInstElimination::ID = 0;
static RegisterPass<DeadInstElimination>
X("die", "Dead Instruction Elimination");
Pass *llvm::createDeadInstEliminationPass() {
return new DeadInstElimination();
}
namespace {
//===--------------------------------------------------------------------===//
// DeadCodeElimination pass implementation
//
struct DCE : public FunctionPass {
static char ID; // Pass identification, replacement for typeid
DCE() : FunctionPass(&ID) {}
virtual bool runOnFunction(Function &F);
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
}
};
}
char DCE::ID = 0;
static RegisterPass<DCE> Y("dce", "Dead Code Elimination");
bool DCE::runOnFunction(Function &F) {
// Start out with all of the instructions in the worklist...
std::vector<Instruction*> WorkList;
for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
WorkList.push_back(&*i);
// Loop over the worklist finding instructions that are dead. If they are
// dead make them drop all of their uses, making other instructions
// potentially dead, and work until the worklist is empty.
//
bool MadeChange = false;
while (!WorkList.empty()) {
Instruction *I = WorkList.back();
WorkList.pop_back();
if (isInstructionTriviallyDead(I)) { // If the instruction is dead.
// Loop over all of the values that the instruction uses, if there are
// instructions being used, add them to the worklist, because they might
// go dead after this one is removed.
//
for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
if (Instruction *Used = dyn_cast<Instruction>(*OI))
WorkList.push_back(Used);
// Remove the instruction.
I->eraseFromParent();
// Remove the instruction from the worklist if it still exists in it.
for (std::vector<Instruction*>::iterator WI = WorkList.begin();
WI != WorkList.end(); ) {
if (*WI == I)
WI = WorkList.erase(WI);
else
++WI;
}
MadeChange = true;
++DCEEliminated;
}
}
return MadeChange;
}
FunctionPass *llvm::createDeadCodeEliminationPass() {
return new DCE();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 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 "base/utf_string_conversions.h"
#include "chrome/browser/password_manager/password_form_data.h"
#include "chrome/browser/sync/profile_sync_service_harness.h"
#include "chrome/browser/sync/sessions/session_state.h"
#include "chrome/test/live_sync/live_passwords_sync_test.h"
using webkit_glue::PasswordForm;
static const char* kValidPassphrase = "passphrase!";
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, Add) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
PasswordForm form = CreateTestPasswordForm(0);
AddLogin(GetVerifierPasswordStore(), form);
AddLogin(GetPasswordStore(0), form);
std::vector<PasswordForm> verifier_forms;
GetLogins(GetVerifierPasswordStore(), verifier_forms);
ASSERT_EQ(1U, verifier_forms.size());
ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));
std::vector<PasswordForm> forms0;
GetLogins(GetPasswordStore(0), forms0);
ASSERT_TRUE(ContainsSamePasswordForms(verifier_forms, forms0));
std::vector<PasswordForm> forms1;
GetLogins(GetPasswordStore(1), forms1);
ASSERT_TRUE(ContainsSamePasswordForms(verifier_forms, forms1));
}
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, Race) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
PasswordForm form0 = CreateTestPasswordForm(0);
AddLogin(GetPasswordStore(0), form0);
PasswordForm form1 = form0;
form1.password_value = ASCIIToUTF16("password1");
AddLogin(GetPasswordStore(1), form1);
ASSERT_TRUE(AwaitQuiescence());
std::vector<PasswordForm> forms0;
GetLogins(GetPasswordStore(0), forms0);
ASSERT_EQ(1U, forms0.size());
std::vector<PasswordForm> forms1;
GetLogins(GetPasswordStore(1), forms1);
ASSERT_EQ(1U, forms1.size());
ASSERT_TRUE(ContainsSamePasswordForms(forms0, forms1));
}
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, SetPassphrase) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
SetPassphrase(0, kValidPassphrase, true);
ASSERT_TRUE(GetClient(0)->AwaitPassphraseAccepted());
ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));
SetPassphrase(1, kValidPassphrase, false);
ASSERT_TRUE(GetClient(1)->AwaitPassphraseAccepted());
ASSERT_TRUE(GetClient(1)->AwaitSyncCycleCompletion("Set passphrase."));
}
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest,
SetPassphraseAndAddPassword) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
SetPassphrase(0, kValidPassphrase, true);
ASSERT_TRUE(GetClient(0)->AwaitPassphraseAccepted());
ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));
SetPassphrase(1, kValidPassphrase, false);
ASSERT_TRUE(GetClient(1)->AwaitPassphraseAccepted());
PasswordForm form = CreateTestPasswordForm(0);
AddLogin(GetPasswordStore(0), form);
std::vector<PasswordForm> forms0;
GetLogins(GetPasswordStore(0), forms0);
ASSERT_EQ(1U, forms0.size());
ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));
std::vector<PasswordForm> forms1;
GetLogins(GetPasswordStore(1), forms1);
ASSERT_EQ(1U, forms1.size());
}
// TODO(rsimha): Marked as flaky due to crbug.com/81341.
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest,
FLAKY_SetPassphraseAndThenSetupSync) {
ASSERT_TRUE(SetupClients()) << "SetupClients() failed.";
ASSERT_TRUE(GetClient(0)->SetupSync());
SetPassphrase(0, kValidPassphrase, true);
ASSERT_TRUE(GetClient(0)->AwaitPassphraseAccepted());
ASSERT_TRUE(GetClient(0)->AwaitSyncCycleCompletion("Initial sync."));
ASSERT_FALSE(GetClient(1)->SetupSync());
SetPassphrase(1, kValidPassphrase, false);
ASSERT_TRUE(GetClient(1)->AwaitPassphraseAccepted());
ASSERT_TRUE(GetClient(1)->AwaitSyncCycleCompletion("Initial sync."));
}
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest,
SetPassphraseTwice) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
SetPassphrase(0, kValidPassphrase, true);
ASSERT_TRUE(GetClient(0)->AwaitPassphraseAccepted());
ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));
SetPassphrase(1, kValidPassphrase, false);
ASSERT_TRUE(GetClient(1)->AwaitPassphraseAccepted());
ASSERT_TRUE(GetClient(1)->AwaitSyncCycleCompletion("Set passphrase."));
SetPassphrase(1, kValidPassphrase, false);
ASSERT_TRUE(GetClient(1)->AwaitPassphraseAccepted());
ASSERT_TRUE(GetClient(1)->AwaitSyncCycleCompletion("Set passphrase again."));
}
<commit_msg>Mark TwoClientLivePasswordsSyncTest.SetPassphraseTwice as flaky.<commit_after>// Copyright (c) 2011 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 "base/utf_string_conversions.h"
#include "chrome/browser/password_manager/password_form_data.h"
#include "chrome/browser/sync/profile_sync_service_harness.h"
#include "chrome/browser/sync/sessions/session_state.h"
#include "chrome/test/live_sync/live_passwords_sync_test.h"
using webkit_glue::PasswordForm;
static const char* kValidPassphrase = "passphrase!";
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, Add) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
PasswordForm form = CreateTestPasswordForm(0);
AddLogin(GetVerifierPasswordStore(), form);
AddLogin(GetPasswordStore(0), form);
std::vector<PasswordForm> verifier_forms;
GetLogins(GetVerifierPasswordStore(), verifier_forms);
ASSERT_EQ(1U, verifier_forms.size());
ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));
std::vector<PasswordForm> forms0;
GetLogins(GetPasswordStore(0), forms0);
ASSERT_TRUE(ContainsSamePasswordForms(verifier_forms, forms0));
std::vector<PasswordForm> forms1;
GetLogins(GetPasswordStore(1), forms1);
ASSERT_TRUE(ContainsSamePasswordForms(verifier_forms, forms1));
}
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, Race) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
PasswordForm form0 = CreateTestPasswordForm(0);
AddLogin(GetPasswordStore(0), form0);
PasswordForm form1 = form0;
form1.password_value = ASCIIToUTF16("password1");
AddLogin(GetPasswordStore(1), form1);
ASSERT_TRUE(AwaitQuiescence());
std::vector<PasswordForm> forms0;
GetLogins(GetPasswordStore(0), forms0);
ASSERT_EQ(1U, forms0.size());
std::vector<PasswordForm> forms1;
GetLogins(GetPasswordStore(1), forms1);
ASSERT_EQ(1U, forms1.size());
ASSERT_TRUE(ContainsSamePasswordForms(forms0, forms1));
}
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest, SetPassphrase) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
SetPassphrase(0, kValidPassphrase, true);
ASSERT_TRUE(GetClient(0)->AwaitPassphraseAccepted());
ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));
SetPassphrase(1, kValidPassphrase, false);
ASSERT_TRUE(GetClient(1)->AwaitPassphraseAccepted());
ASSERT_TRUE(GetClient(1)->AwaitSyncCycleCompletion("Set passphrase."));
}
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest,
SetPassphraseAndAddPassword) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
SetPassphrase(0, kValidPassphrase, true);
ASSERT_TRUE(GetClient(0)->AwaitPassphraseAccepted());
ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));
SetPassphrase(1, kValidPassphrase, false);
ASSERT_TRUE(GetClient(1)->AwaitPassphraseAccepted());
PasswordForm form = CreateTestPasswordForm(0);
AddLogin(GetPasswordStore(0), form);
std::vector<PasswordForm> forms0;
GetLogins(GetPasswordStore(0), forms0);
ASSERT_EQ(1U, forms0.size());
ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));
std::vector<PasswordForm> forms1;
GetLogins(GetPasswordStore(1), forms1);
ASSERT_EQ(1U, forms1.size());
}
// TODO(rsimha): Marked as flaky due to crbug.com/81341.
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest,
FLAKY_SetPassphraseAndThenSetupSync) {
ASSERT_TRUE(SetupClients()) << "SetupClients() failed.";
ASSERT_TRUE(GetClient(0)->SetupSync());
SetPassphrase(0, kValidPassphrase, true);
ASSERT_TRUE(GetClient(0)->AwaitPassphraseAccepted());
ASSERT_TRUE(GetClient(0)->AwaitSyncCycleCompletion("Initial sync."));
ASSERT_FALSE(GetClient(1)->SetupSync());
SetPassphrase(1, kValidPassphrase, false);
ASSERT_TRUE(GetClient(1)->AwaitPassphraseAccepted());
ASSERT_TRUE(GetClient(1)->AwaitSyncCycleCompletion("Initial sync."));
}
// http://crbug.com/81341
IN_PROC_BROWSER_TEST_F(TwoClientLivePasswordsSyncTest,
FLAKY_SetPassphraseTwice) {
ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
SetPassphrase(0, kValidPassphrase, true);
ASSERT_TRUE(GetClient(0)->AwaitPassphraseAccepted());
ASSERT_TRUE(GetClient(0)->AwaitMutualSyncCycleCompletion(GetClient(1)));
SetPassphrase(1, kValidPassphrase, false);
ASSERT_TRUE(GetClient(1)->AwaitPassphraseAccepted());
ASSERT_TRUE(GetClient(1)->AwaitSyncCycleCompletion("Set passphrase."));
SetPassphrase(1, kValidPassphrase, false);
ASSERT_TRUE(GetClient(1)->AwaitPassphraseAccepted());
ASSERT_TRUE(GetClient(1)->AwaitSyncCycleCompletion("Set passphrase again."));
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>
* Copyright (C) 2010 Dan Leinir Turthra Jensen <admin@leinir.dk>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "gameproject.h"
#include "gameprojectprivate.h"
#include "scene.h"
#include "game.h"
#include "achievement.h"
#include "asset.h"
#include "achievementsmanager.h"
#include "projectmetadata.h"
#include <core/gdlserializer.h>
#include <core/scriptengine.h>
#include <core/debughelper.h>
#include <core/directoryprovider.h>
#include <QtGui/QImageWriter>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QTextStream>
#include <QtCore/QMetaProperty>
REGISTER_OBJECTTYPE( GluonEngine, GameProject )
using namespace GluonEngine;
GameProject::GameProject( QObject* parent )
: GluonObject( parent )
, d( new GameProjectPrivate )
{
setGameProject( this );
}
GameProject::GameProject( const GameProject& other, QObject* parent )
: GluonObject( parent )
, d( other.d )
{
}
GameProject::~GameProject()
{
}
void
GameProject::addChild( GluonObject* child )
{
GluonCore::GluonObject::addChild( child );
connect( child, SIGNAL(showDebug(QString)), Game::instance(), SIGNAL(showDebug(QString)) );
}
bool
GameProject::removeChild( GluonObject* child )
{
disconnect( child, SIGNAL(showDebug(QString)), Game::instance(), SIGNAL(showDebug(QString)) );
return GluonCore::GluonObject::removeChild( child );
}
bool
GameProject::saveToFile()
{
// Run through everything first and save each of the saveable assets
GameProjectPrivate::saveChildren( this );
if( !GluonCore::GDLSerializer::instance()->write( filename(), GluonCore::GluonObjectList() << this ) )
return false;
QString projectDir = filename().toLocalFile().section( '/', 0, -2 );
// Recreate the various icon files if we have an icon file available
QImage icon( 128, 128, QImage::Format_ARGB32 );
if( d->icon )
icon = d->icon->texture()->image().scaled( 128, 128, Qt::KeepAspectRatio, Qt::SmoothTransformation );
QString iconFile( projectDir );
iconFile.append( '/' );
iconFile.append( GluonEngine::projectIcon );
icon.save( iconFile );
if( QImageWriter::supportedImageFormats().contains( "ico" ) )
{
iconFile = projectDir;
iconFile.append( '/' );
iconFile.append( GluonEngine::projectWinIcon );
QImageWriter iconWriter( iconFile );
iconWriter.setFormat( "ico" );
iconWriter.write( icon );
}
// Build the folder information files for Windows and for XDG compliant file browsers
QFile directoryFile( projectDir + "/.directory" );
if( directoryFile.open( QFile::WriteOnly | QFile::Truncate | QIODevice::Text ) )
{
QTextStream out( &directoryFile );
out << "[Desktop Entry]" << endl << "Icon=game.png" << endl << "Type=Directory" << endl;
directoryFile.close();
}
QFile folderFile( projectDir + "/desktop.ini" );
if( folderFile.open( QFile::WriteOnly | QFile::Truncate | QIODevice::Text ) )
{
QTextStream out( &folderFile );
out << "[.ShellClassInfo]" << endl << "ConfirmFileOp=0" << endl << "IconFile=game.ico" << endl << "IconIndex=0" << endl << "InfoTip=A Gluon Game" << endl;
folderFile.close();
}
// Recreate the screenshot file if we have one such
if( d->screenshot )
{
QString screenshotFile = projectDir;
screenshotFile.append( '/' );
screenshotFile.append( GluonEngine::projectScreenshot );
d->screenshot->texture()->image().scaled( 800, 600, Qt::KeepAspectRatio ).save( screenshotFile );
}
// Save meta data
ProjectMetaData metaData( filename().toLocalFile(), name(), description(), property("id").toString() );
metaData.save();
// Create a template for the achievements in this project
AchievementsManager achievementsManager;
achievementsManager.readFromProject(achievements());
achievementsManager.makeTemplate();
QString saveDirectory = projectDir + "/.cache";
achievementsManager.save(saveDirectory);
return true;
}
void GameProject::traverseChildren(GluonObject* gluonObject)
{
foreach( QObject *child, gluonObject->children() )
{
Asset *assetChild = qobject_cast<Asset*>(child);
if (assetChild)
{
addAsset(assetChild);
assetChild->load();
}
}
}
bool
GameProject::loadFromFile()
{
// change directory to the project path..
QDir::setCurrent( QFileInfo( filename().toLocalFile() ).canonicalPath() );
setFilename( filename().toLocalFile() );
QList<GluonObject*> objectList;
if( GluonCore::GDLSerializer::instance()->read( filename(), objectList ) )
{
if( objectList.at(0)->metaObject() )
{
// If the first object in the list is a GluonProject, then let's
// adapt ourselves to represent that object...
if( objectList.at(0)->metaObject()->className() == metaObject()->className() )
{
GameProject* loadedProject = qobject_cast<GameProject*>( objectList[0] );
// First things first - clean ourselves out, all the children
// and the media info list should be gone-ified
qDeleteAll( children() );
// Reassign all the children of the newly loaded project to
// ourselves...
foreach( QObject * child, loadedProject->children() )
{
GluonObject* theChild = qobject_cast<GluonObject*>( child );
if( theChild )
{
theChild->setParent( this );
theChild->setGameProject( this );
traverseChildren(theChild);
}
}
// Set all the interesting values...
setName( loadedProject->name() );
// Copy across all the properties
const QMetaObject* metaobject = loadedProject->metaObject();
int count = metaobject->propertyCount();
for( int i = 0; i < count; ++i )
{
QMetaProperty metaproperty = metaobject->property( i );
const QString theName( metaproperty.name() );
if( theName == "objectName" || theName == "name" )
continue;
setProperty( metaproperty.name(), loadedProject->property( metaproperty.name() ) );
}
// Then get all the dynamic ones (in case any such exist)
QList<QByteArray> propertyNames = loadedProject->dynamicPropertyNames();
foreach( const QByteArray & propName, propertyNames )
{
setProperty( propName, loadedProject->property( propName ) );
}
// Sanitize me!
sanitize();
// Finally, get rid of the left-overs
qDeleteAll( objectList );
}
// Otherwise it is not a GluonProject, and should fail!
else
{
DEBUG_BLOCK
DEBUG_TEXT( QString( "First object loaded is not a Gluon::GameProject." ) )
DEBUG_TEXT2( "Type of loaded object: %1", objectList.at(0)->metaObject()->className() )
DEBUG_TEXT2( "Name of loaded object: %1", objectList.at(0)->name() )
return false;
}
}
else
{
return false;
}
}
return true;
}
bool
GameProject::loadFromFile( QUrl fileUrl )
{
setFilename( fileUrl );
setDirname( fileUrl.toLocalFile().section( '/', 0, -2 ) );
return loadFromFile();
}
bool
GameProject::loadFromFile( QString fileName )
{
setFilename( fileName );
setDirname( fileName.section( '/', 0, -2 ) );
return loadFromFile();
}
/******************************************************************************
* Property Getter-setters
*****************************************************************************/
QString
GameProject::description() const
{
return d->description;
}
void
GameProject::setDescription( QString newDescription )
{
d->description = newDescription;
}
QUrl
GameProject::homepage() const
{
return d->homepage;
}
void
GameProject::setHomepage( QUrl newHomepage )
{
d->homepage = newHomepage;
}
QList<QUrl>
GameProject::mediaInfo() const
{
return d->mediaInfo;
}
void
GameProject::setMediaInfo( QList<QUrl> newMediaInfo )
{
d->mediaInfo = newMediaInfo;
}
QUrl
GameProject::filename() const
{
return d->filename;
}
void
GameProject::setFilename( QUrl fileUrl )
{
d->filename = fileUrl;
}
void
GameProject::setFilename( QString fileName )
{
d->filename = QUrl::fromLocalFile( fileName );
}
Scene*
GameProject::entryPoint() const
{
return d->entryPoint;
}
QUrl
GameProject::dirname() const
{
return d->dirname;
}
void
GameProject::setDirname( QUrl dirUrl )
{
d->dirname = dirUrl;
}
void
GameProject::setDirname( QString dirName )
{
d->dirname = QUrl::fromLocalFile( dirName );
}
void
GameProject::setEntryPoint( Scene* newEntryPoint )
{
d->entryPoint = newEntryPoint;
}
GluonEngine::TextureAsset* GameProject::icon() const
{
return d->icon;
}
void GameProject::setIcon( GluonEngine::TextureAsset* newIcon )
{
d->icon = newIcon;
}
GluonEngine::TextureAsset* GameProject::screenshot() const
{
return d->screenshot;
}
void GameProject::setScreenshot( GluonEngine::TextureAsset* newScreenshot )
{
d->screenshot = newScreenshot;
}
QList<Achievement*> GameProject::achievements() const
{
return d->achievements;
}
void GameProject::addAchievement(Achievement* achievement)
{
if( !d->achievements.contains(achievement) )
d->achievements.append(achievement);
}
void GameProject::removeAchievement(Achievement* achievement)
{
d->achievements.removeOne(achievement);
}
QString GameProject::userName() const
{
return d->userName;
}
void GameProject::setUserName(const QString& newUserName)
{
d->userName = newUserName;
}
// ----------------------------------------------------------------------------
// Asset management
Asset* GameProject::findAsset( const QString& name ) const
{
Asset* foundAsset = 0;
foreach( Asset *asset, d->assets )
{
if( asset->name() == name )
{
foundAsset = asset;
break;
}
}
return foundAsset;
}
Asset* GameProject::findAssetByType( const QString& typeName ) const
{
int typeID = QMetaType::type( typeName.toAscii().data() );
return findAssetByType( typeID );
}
Asset* GameProject::findAssetByType( int type ) const
{
if( d->assetTypes.find( type ) != d->assetTypes.end() )
return d->assetTypes.value( type );
return 0;
}
QList<Asset*> GameProject::findAssetsByType( const QString& typeName ) const
{
int typeID = QMetaType::type( typeName.toAscii().data() );
return findAssetsByType( typeID );
}
QList<Asset*> GameProject::findAssetsByType( int type ) const
{
if( d->assetTypes.find( type ) != d->assetTypes.end() )
return d->assetTypes.values( type );
return QList<Asset*>();
}
void GameProject::addAsset( Asset* asset )
{
if( asset )
{
int typeID = GluonCore::GluonObjectFactory::instance()->objectTypeIDs().value( asset->metaObject()->className() );
if( d->assetTypes.constFind( typeID, asset ) == d->assetTypes.constEnd() )
{
d->assetTypes.insert( typeID, asset );
d->assets.append( asset );
// connect( asset, SIGNAL(destroyed(QObject*)), SLOT(childDeleted(QObject*)) );
// asset->setParent( this );
// asset->setGameProject( this );
// asset->setName( asset->name() );
}
}
else
{
DEBUG_BLOCK
DEBUG_TEXT( "Attempting to add a null asset" )
}
}
bool GameProject::removeAsset( Asset* asset )
{
int typeID = QMetaType::type( asset->metaObject()->className() );
d->assetTypes.remove( typeID, asset );
// disconnect( asset, SIGNAL(destroyed(QObject*)), this, SLOT(childDeleted(QObject*)) );
return d->assets.removeOne( asset );
}
QList<Asset*> GameProject::assets() const
{
return d->assets;
}
#include "gameproject.moc"
<commit_msg>Fix gameproject icon issue (now defaults to gluon icon)<commit_after>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>
* Copyright (C) 2010 Dan Leinir Turthra Jensen <admin@leinir.dk>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "gameproject.h"
#include "gameprojectprivate.h"
#include "scene.h"
#include "game.h"
#include "achievement.h"
#include "asset.h"
#include "achievementsmanager.h"
#include "projectmetadata.h"
#include <core/gdlserializer.h>
#include <core/scriptengine.h>
#include <core/debughelper.h>
#include <core/directoryprovider.h>
#include <QtGui/QImageWriter>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QTextStream>
#include <QtCore/QMetaProperty>
REGISTER_OBJECTTYPE( GluonEngine, GameProject )
using namespace GluonEngine;
GameProject::GameProject( QObject* parent )
: GluonObject( parent )
, d( new GameProjectPrivate )
{
setGameProject( this );
}
GameProject::GameProject( const GameProject& other, QObject* parent )
: GluonObject( parent )
, d( other.d )
{
}
GameProject::~GameProject()
{
}
void
GameProject::addChild( GluonObject* child )
{
GluonCore::GluonObject::addChild( child );
connect( child, SIGNAL(showDebug(QString)), Game::instance(), SIGNAL(showDebug(QString)) );
}
bool
GameProject::removeChild( GluonObject* child )
{
disconnect( child, SIGNAL(showDebug(QString)), Game::instance(), SIGNAL(showDebug(QString)) );
return GluonCore::GluonObject::removeChild( child );
}
bool
GameProject::saveToFile()
{
// Run through everything first and save each of the saveable assets
GameProjectPrivate::saveChildren( this );
if( !GluonCore::GDLSerializer::instance()->write( filename(), GluonCore::GluonObjectList() << this ) )
return false;
QString projectDir = filename().toLocalFile().section( '/', 0, -2 );
// Recreate the various icon files if we have an icon file available
QIcon tempIcon = QIcon::fromTheme ("gluon", QIcon( QPixmap( 128, 128 ) ) );
QImage icon = tempIcon.pixmap(128, 128).toImage();
if( d->icon )
icon = d->icon->texture()->image().scaled( 128, 128, Qt::KeepAspectRatio, Qt::SmoothTransformation );
QString iconFile( projectDir );
iconFile.append( '/' );
iconFile.append( GluonEngine::projectIcon );
icon.save( iconFile );
if( QImageWriter::supportedImageFormats().contains( "ico" ) )
{
iconFile = projectDir;
iconFile.append( '/' );
iconFile.append( GluonEngine::projectWinIcon );
QImageWriter iconWriter( iconFile );
iconWriter.setFormat( "ico" );
iconWriter.write( icon );
}
// Build the folder information files for Windows and for XDG compliant file browsers
QFile directoryFile( projectDir + "/.directory" );
if( directoryFile.open( QFile::WriteOnly | QFile::Truncate | QIODevice::Text ) )
{
QTextStream out( &directoryFile );
out << "[Desktop Entry]" << endl << "Icon=./game.png" << endl << "Type=Directory" << endl;
directoryFile.close();
}
QFile folderFile( projectDir + "/desktop.ini" );
if( folderFile.open( QFile::WriteOnly | QFile::Truncate | QIODevice::Text ) )
{
QTextStream out( &folderFile );
out << "[.ShellClassInfo]" << endl << "ConfirmFileOp=0" << endl << "IconFile=game.ico" << endl << "IconIndex=0" << endl << "InfoTip=A Gluon Game" << endl;
folderFile.close();
}
// Recreate the screenshot file if we have one such
if( d->screenshot )
{
QString screenshotFile = projectDir;
screenshotFile.append( '/' );
screenshotFile.append( GluonEngine::projectScreenshot );
d->screenshot->texture()->image().scaled( 800, 600, Qt::KeepAspectRatio ).save( screenshotFile );
}
// Save meta data
ProjectMetaData metaData( filename().toLocalFile(), name(), description(), property("id").toString() );
metaData.save();
// Create a template for the achievements in this project
AchievementsManager achievementsManager;
achievementsManager.readFromProject(achievements());
achievementsManager.makeTemplate();
QString saveDirectory = projectDir + "/.cache";
achievementsManager.save(saveDirectory);
return true;
}
void GameProject::traverseChildren(GluonObject* gluonObject)
{
foreach( QObject *child, gluonObject->children() )
{
Asset *assetChild = qobject_cast<Asset*>(child);
if (assetChild)
{
addAsset(assetChild);
assetChild->load();
}
}
}
bool
GameProject::loadFromFile()
{
// change directory to the project path..
QDir::setCurrent( QFileInfo( filename().toLocalFile() ).canonicalPath() );
setFilename( filename().toLocalFile() );
QList<GluonObject*> objectList;
if( GluonCore::GDLSerializer::instance()->read( filename(), objectList ) )
{
if( objectList.at(0)->metaObject() )
{
// If the first object in the list is a GluonProject, then let's
// adapt ourselves to represent that object...
if( objectList.at(0)->metaObject()->className() == metaObject()->className() )
{
GameProject* loadedProject = qobject_cast<GameProject*>( objectList[0] );
// First things first - clean ourselves out, all the children
// and the media info list should be gone-ified
qDeleteAll( children() );
// Reassign all the children of the newly loaded project to
// ourselves...
foreach( QObject * child, loadedProject->children() )
{
GluonObject* theChild = qobject_cast<GluonObject*>( child );
if( theChild )
{
theChild->setParent( this );
theChild->setGameProject( this );
traverseChildren(theChild);
}
}
// Set all the interesting values...
setName( loadedProject->name() );
// Copy across all the properties
const QMetaObject* metaobject = loadedProject->metaObject();
int count = metaobject->propertyCount();
for( int i = 0; i < count; ++i )
{
QMetaProperty metaproperty = metaobject->property( i );
const QString theName( metaproperty.name() );
if( theName == "objectName" || theName == "name" )
continue;
setProperty( metaproperty.name(), loadedProject->property( metaproperty.name() ) );
}
// Then get all the dynamic ones (in case any such exist)
QList<QByteArray> propertyNames = loadedProject->dynamicPropertyNames();
foreach( const QByteArray & propName, propertyNames )
{
setProperty( propName, loadedProject->property( propName ) );
}
// Sanitize me!
sanitize();
// Finally, get rid of the left-overs
qDeleteAll( objectList );
}
// Otherwise it is not a GluonProject, and should fail!
else
{
DEBUG_BLOCK
DEBUG_TEXT( QString( "First object loaded is not a Gluon::GameProject." ) )
DEBUG_TEXT2( "Type of loaded object: %1", objectList.at(0)->metaObject()->className() )
DEBUG_TEXT2( "Name of loaded object: %1", objectList.at(0)->name() )
return false;
}
}
else
{
return false;
}
}
return true;
}
bool
GameProject::loadFromFile( QUrl fileUrl )
{
setFilename( fileUrl );
setDirname( fileUrl.toLocalFile().section( '/', 0, -2 ) );
return loadFromFile();
}
bool
GameProject::loadFromFile( QString fileName )
{
setFilename( fileName );
setDirname( fileName.section( '/', 0, -2 ) );
return loadFromFile();
}
/******************************************************************************
* Property Getter-setters
*****************************************************************************/
QString
GameProject::description() const
{
return d->description;
}
void
GameProject::setDescription( QString newDescription )
{
d->description = newDescription;
}
QUrl
GameProject::homepage() const
{
return d->homepage;
}
void
GameProject::setHomepage( QUrl newHomepage )
{
d->homepage = newHomepage;
}
QList<QUrl>
GameProject::mediaInfo() const
{
return d->mediaInfo;
}
void
GameProject::setMediaInfo( QList<QUrl> newMediaInfo )
{
d->mediaInfo = newMediaInfo;
}
QUrl
GameProject::filename() const
{
return d->filename;
}
void
GameProject::setFilename( QUrl fileUrl )
{
d->filename = fileUrl;
}
void
GameProject::setFilename( QString fileName )
{
d->filename = QUrl::fromLocalFile( fileName );
}
Scene*
GameProject::entryPoint() const
{
return d->entryPoint;
}
QUrl
GameProject::dirname() const
{
return d->dirname;
}
void
GameProject::setDirname( QUrl dirUrl )
{
d->dirname = dirUrl;
}
void
GameProject::setDirname( QString dirName )
{
d->dirname = QUrl::fromLocalFile( dirName );
}
void
GameProject::setEntryPoint( Scene* newEntryPoint )
{
d->entryPoint = newEntryPoint;
}
GluonEngine::TextureAsset* GameProject::icon() const
{
return d->icon;
}
void GameProject::setIcon( GluonEngine::TextureAsset* newIcon )
{
d->icon = newIcon;
}
GluonEngine::TextureAsset* GameProject::screenshot() const
{
return d->screenshot;
}
void GameProject::setScreenshot( GluonEngine::TextureAsset* newScreenshot )
{
d->screenshot = newScreenshot;
}
QList<Achievement*> GameProject::achievements() const
{
return d->achievements;
}
void GameProject::addAchievement(Achievement* achievement)
{
if( !d->achievements.contains(achievement) )
d->achievements.append(achievement);
}
void GameProject::removeAchievement(Achievement* achievement)
{
d->achievements.removeOne(achievement);
}
QString GameProject::userName() const
{
return d->userName;
}
void GameProject::setUserName(const QString& newUserName)
{
d->userName = newUserName;
}
// ----------------------------------------------------------------------------
// Asset management
Asset* GameProject::findAsset( const QString& name ) const
{
Asset* foundAsset = 0;
foreach( Asset *asset, d->assets )
{
if( asset->name() == name )
{
foundAsset = asset;
break;
}
}
return foundAsset;
}
Asset* GameProject::findAssetByType( const QString& typeName ) const
{
int typeID = QMetaType::type( typeName.toAscii().data() );
return findAssetByType( typeID );
}
Asset* GameProject::findAssetByType( int type ) const
{
if( d->assetTypes.find( type ) != d->assetTypes.end() )
return d->assetTypes.value( type );
return 0;
}
QList<Asset*> GameProject::findAssetsByType( const QString& typeName ) const
{
int typeID = QMetaType::type( typeName.toAscii().data() );
return findAssetsByType( typeID );
}
QList<Asset*> GameProject::findAssetsByType( int type ) const
{
if( d->assetTypes.find( type ) != d->assetTypes.end() )
return d->assetTypes.values( type );
return QList<Asset*>();
}
void GameProject::addAsset( Asset* asset )
{
if( asset )
{
int typeID = GluonCore::GluonObjectFactory::instance()->objectTypeIDs().value( asset->metaObject()->className() );
if( d->assetTypes.constFind( typeID, asset ) == d->assetTypes.constEnd() )
{
d->assetTypes.insert( typeID, asset );
d->assets.append( asset );
// connect( asset, SIGNAL(destroyed(QObject*)), SLOT(childDeleted(QObject*)) );
// asset->setParent( this );
// asset->setGameProject( this );
// asset->setName( asset->name() );
}
}
else
{
DEBUG_BLOCK
DEBUG_TEXT( "Attempting to add a null asset" )
}
}
bool GameProject::removeAsset( Asset* asset )
{
int typeID = QMetaType::type( asset->metaObject()->className() );
d->assetTypes.remove( typeID, asset );
// disconnect( asset, SIGNAL(destroyed(QObject*)), this, SLOT(childDeleted(QObject*)) );
return d->assets.removeOne( asset );
}
QList<Asset*> GameProject::assets() const
{
return d->assets;
}
#include "gameproject.moc"
<|endoftext|>
|
<commit_before>#ifndef __CPREL_BDDDOMAIN_MANAGER_HH__
#define __CPREL_BDDDOMAIN_MANAGER_HH__
#include <iostream>
#include <boost/utility.hpp>
#include <boost/shared_ptr.hpp>
#include <cudd/cuddInt.h>
namespace MPG { namespace CPRel { namespace VarImpl {
namespace Limits {
/**
* \brief Number of bits to represent an element inside a relation
* tuple.
* \ingroup DomRepr
*
* The maximum number that can be part of relation's tuple is 2^bbv.
* - Setting this attribute to 5 will allow to represent positive integers
* of 32 bits.
*/
const int bbv = 2;
/**
* \brief Number of bits of the maximum arity that can be represented
* \ingroup DomRepr
*
* The maximum arity that a relation can have is 2^ba.
* - Setting this attribute to 3 will allow to represent up to 8-ary relations
*/
const int ba = 2;
/**
* \brief Number of bits used to represent each element of a tuple
* \ingroup DomRepr
*/
const int bitsPerInteger = 1 << bbv;
/**
* \brief Number of bits used to represent the arity
* \ingroup DomRepr
*/
const int arity = 1 << ba;
}
class BddManager;
typedef boost::shared_ptr<BddManager> PManager;
/**
* \brief Class to handle the creation and destruction of Cudd related objects.
* \ingroup DomRepr
*
* The idea of having this class is to create a global object that
* is in charge of the resource deallocation of Cudd entities. For
* this reason only one manager is used and this class implements the
* singleton pattern.
*/
class BddManager : private boost::noncopyable {
private:
/// Only one single instance of this class is allowed at run time
static PManager _instance;
/// Pointer to the Bdd manager
DdManager *dd;
/// Constant true
DdNode *one_;
/// Constant false
DdNode *zero_;
/// \name Constructors and destructor
//@{
/// Constructor that initializes the BDD manager of CUDD
BddManager (void)
: dd(Cudd_Init(0,0,CUDD_UNIQUE_SLOTS,CUDD_CACHE_SLOTS,0))
, one_(DD_ONE(dd))
, zero_(Cudd_Not(DD_ONE(dd)))
{
std::cout << "Created bdd manager" << std::endl;
}
/// Creates an instace of this object
static void create() {
_instance.reset( new BddManager, &deleter );
}
/// Destructor that releases the BDD manager of CUDD
~BddManager (void) {
std::cout << "Called destructor: " << references() << std::endl;
Cudd_Quit(dd);
}
//@}
/// Method called by the managed pointer when destructed
static void deleter(BddManager *ptr) {
delete ptr;
}
int references(void) {
return Cudd_CheckZeroRef(dd);
}
public:
/// Returns an instance of the manager
static PManager instance(void) {
if (_instance.get() != NULL)
return _instance;
create();
return _instance;
}
/// \name Access
//@{
/// Returns the bdd manager
DdManager* manager(void) {
return dd;
}
/// Returns the constant \c true
DdNode* one(void) {
return one_;
}
/// Returns the constant \c false
DdNode* zero(void) {
return zero_;
}
//@}
};
/**
* \brief Returns the manager
* \ingroup DomRepr
*/
inline
DdManager* dd(void) {
return BddManager::instance()->manager();
}
/**
* \brief Returns logical true
* \ingroup DomRepr
*/
inline
DdNode* one(void) {
return BddManager::instance()->one();
}
/**
* \brief Returns logical false
* \ingroup DomRepr
*/
inline
DdNode* zero(void) {
return BddManager::instance()->zero();
}
}}}
#endif
<commit_msg>I forgot to change the limits to allow "reasonable" relations<commit_after>#ifndef __CPREL_BDDDOMAIN_MANAGER_HH__
#define __CPREL_BDDDOMAIN_MANAGER_HH__
#include <iostream>
#include <boost/utility.hpp>
#include <boost/shared_ptr.hpp>
#include <cudd/cuddInt.h>
namespace MPG { namespace CPRel { namespace VarImpl {
namespace Limits {
/**
* \brief Number of bits to represent an element inside a relation
* tuple.
* \ingroup DomRepr
*
* The maximum number that can be part of relation's tuple is 2^bbv.
* - Setting this attribute to 5 will allow to represent positive integers
* of 32 bits.
*/
const int bbv = 5;
/**
* \brief Number of bits of the maximum arity that can be represented
* \ingroup DomRepr
*
* The maximum arity that a relation can have is 2^ba.
* - Setting this attribute to 3 will allow to represent up to 8-ary relations
*/
const int ba = 3;
/**
* \brief Number of bits used to represent each element of a tuple
* \ingroup DomRepr
*/
const int bitsPerInteger = 1 << bbv;
/**
* \brief Number of bits used to represent the arity
* \ingroup DomRepr
*/
const int arity = 1 << ba;
}
class BddManager;
typedef boost::shared_ptr<BddManager> PManager;
/**
* \brief Class to handle the creation and destruction of Cudd related objects.
* \ingroup DomRepr
*
* The idea of having this class is to create a global object that
* is in charge of the resource deallocation of Cudd entities. For
* this reason only one manager is used and this class implements the
* singleton pattern.
*/
class BddManager : private boost::noncopyable {
private:
/// Only one single instance of this class is allowed at run time
static PManager _instance;
/// Pointer to the Bdd manager
DdManager *dd;
/// Constant true
DdNode *one_;
/// Constant false
DdNode *zero_;
/// \name Constructors and destructor
//@{
/// Constructor that initializes the BDD manager of CUDD
BddManager (void)
: dd(Cudd_Init(0,0,CUDD_UNIQUE_SLOTS,CUDD_CACHE_SLOTS,0))
, one_(DD_ONE(dd))
, zero_(Cudd_Not(DD_ONE(dd)))
{
std::cout << "Created bdd manager" << std::endl;
}
/// Creates an instace of this object
static void create() {
_instance.reset( new BddManager, &deleter );
}
/// Destructor that releases the BDD manager of CUDD
~BddManager (void) {
std::cout << "Called destructor: " << references() << std::endl;
Cudd_Quit(dd);
}
//@}
/// Method called by the managed pointer when destructed
static void deleter(BddManager *ptr) {
delete ptr;
}
int references(void) {
return Cudd_CheckZeroRef(dd);
}
public:
/// Returns an instance of the manager
static PManager instance(void) {
if (_instance.get() != NULL)
return _instance;
create();
return _instance;
}
/// \name Access
//@{
/// Returns the bdd manager
DdManager* manager(void) {
return dd;
}
/// Returns the constant \c true
DdNode* one(void) {
return one_;
}
/// Returns the constant \c false
DdNode* zero(void) {
return zero_;
}
//@}
};
/**
* \brief Returns the manager
* \ingroup DomRepr
*/
inline
DdManager* dd(void) {
return BddManager::instance()->manager();
}
/**
* \brief Returns logical true
* \ingroup DomRepr
*/
inline
DdNode* one(void) {
return BddManager::instance()->one();
}
/**
* \brief Returns logical false
* \ingroup DomRepr
*/
inline
DdNode* zero(void) {
return BddManager::instance()->zero();
}
}}}
#endif
<|endoftext|>
|
<commit_before>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez.
//
// 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.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
#include <cmake.h>
#include <sstream>
#include <map>
#include <stdlib.h>
#include <Variant.h>
#include <Duration.h>
#include <Context.h>
#include <Nibbler.h>
#include <ISO8601.h>
#include <Date.h>
#include <text.h>
#include <i18n.h>
#include <DOM.h>
extern Context context;
////////////////////////////////////////////////////////////////////////////////
DOM::DOM ()
{
}
////////////////////////////////////////////////////////////////////////////////
DOM::~DOM ()
{
}
////////////////////////////////////////////////////////////////////////////////
// DOM Supported References:
//
// Configuration:
// rc.<name>
//
// System:
// context.program
// context.args
// context.width
// context.height
// system.version
// system.os
//
bool DOM::get (const std::string& name, Variant& value)
{
int len = name.length ();
Nibbler n (name);
// rc. --> context.config
if (len > 3 &&
name.substr (0, 3) == "rc.")
{
std::string key = name.substr (3);
auto c = context.config.find (key);
if (c != context.config.end ())
{
value = Variant (c->second);
return true;
}
return false;
}
// context.*
if (len > 8 &&
name.substr (0, 8) == "context.")
{
if (name == "context.program")
{
value = Variant (context.cli2.getBinary ());
return true;
}
else if (name == "context.args")
{
std::string commandLine;
join (commandLine, " ", context.cli2._original_args);
value = Variant (commandLine);
return true;
}
else if (name == "context.width")
{
value = Variant (static_cast<int> (context.terminal_width
? context.terminal_width
: context.getWidth ()));
return true;
}
else if (name == "context.height")
{
value = Variant (static_cast<int> (context.terminal_height
? context.terminal_height
: context.getHeight ()));
return true;
}
else
throw format (STRING_DOM_UNREC, name);
}
// TODO stats.<name>
// system. --> Implement locally.
if (len > 7 &&
name.substr (0, 7) == "system.")
{
// Taskwarrior version number.
if (name == "system.version")
{
value = Variant (VERSION);
return true;
}
// OS type.
else if (name == "system.os")
{
#if defined (DARWIN)
value = Variant ("Darwin");
#elif defined (SOLARIS)
value = Variant ("Solaris");
#elif defined (CYGWIN)
value = Variant ("Cygwin");
#elif defined (HAIKU)
value = Variant ("Haiku");
#elif defined (OPENBSD)
value = Variant ("OpenBSD");
#elif defined (FREEBSD)
value = Variant ("FreeBSD");
#elif defined (NETBSD)
value = Variant ("NetBSD");
#elif defined (LINUX)
value = Variant ("Linux");
#elif defined (KFREEBSD)
value = Variant ("GNU/kFreeBSD");
#elif defined (GNUHURD)
value = Variant ("GNU/Hurd");
#else
value = Variant (STRING_DOM_UNKNOWN);
#endif
return true;
}
else
throw format (STRING_DOM_UNREC, name);
}
// Empty string if nothing is found.
return false;
}
////////////////////////////////////////////////////////////////////////////////
// DOM Supported References:
//
// Relative or absolute attribute:
// <attribute>
// <id>.<attribute>
// <uuid>.<attribute>
//
// Single tag:
// tags.<word>
//
// Date type:
// <date>.year
// <date>.month
// <date>.day
// <date>.week
// <date>.weekday
// <date>.julian
// <date>.hour
// <date>.minute
// <date>.second
//
// Annotations (entry is a date):
// annotations.<N>.entry
// annotations.<N>.description
//
bool DOM::get (const std::string& name, const Task& task, Variant& value)
{
// <attr>
if (task.size () && name == "id")
{
value = Variant (static_cast<int> (task.id));
return true;
}
if (task.size () && name == "urgency")
{
value = Variant (task.urgency_c ());
return true;
}
// split name on '.'
std::vector <std::string> elements;
split (elements, name, '.');
if (elements.size () == 1)
{
std::string canonical;
if (task.size () && context.cli2.canonicalize (canonical, "attribute", name))
{
Column* column = context.columns[canonical];
if (column)
{
if (column->is_uda () && ! task.has (canonical))
{
value = Variant ("''");
return true;
}
if (column->type () == "date")
{
auto numeric = task.get_date (canonical);
if (numeric == 0)
value = Variant ("");
else
value = Variant (numeric, Variant::type_date);
}
else if (column->type () == "duration" || canonical == "recur")
value = Variant ((time_t) Duration (task.get (canonical)), Variant::type_duration);
else if (column->type () == "numeric")
value = Variant (task.get_float (canonical));
else // string
value = Variant (task.get (canonical));
return true;
}
}
}
else if (elements.size () > 1)
{
Task ref;
Nibbler n (elements[0]);
n.save ();
int id;
std::string uuid;
bool proceed = false;
if (n.getInt (id) && n.depleted ())
{
if (id == task.id)
ref = task;
else
context.tdb2.get (id, ref);
proceed = true;
}
else
{
n.restore ();
if (n.getUUID (uuid) && n.depleted ())
{
if (uuid == task.get ("uuid"))
ref = task;
else
context.tdb2.get (uuid, ref);
proceed = true;
}
}
if (proceed)
{
if (elements[1] == "id")
{
value = Variant (static_cast<int> (ref.id));
return true;
}
else if (elements[1] == "urgency")
{
value = Variant (ref.urgency_c ());
return true;
}
std::string canonical;
if (context.cli2.canonicalize (canonical, "attribute", elements[1]))
{
if (elements.size () == 2)
{
Column* column = context.columns[canonical];
if (column)
{
if (column->is_uda () && ! ref.has (canonical))
{
value = Variant ("''");
return true;
}
if (column->type () == "date")
{
auto numeric = ref.get_date (canonical);
if (numeric == 0)
value = Variant ("");
else
value = Variant (numeric, Variant::type_date);
}
else if (column->type () == "duration")
{
auto period = ref.get (canonical);
context.debug ("ref.get(" + canonical + ") --> " + period);
ISO8601p iso;
std::string::size_type cursor = 0;
if (iso.parse (period, cursor))
value = Variant ((time_t) iso._value, Variant::type_duration);
else
value = Variant ((time_t) Duration (ref.get (canonical)), Variant::type_duration);
context.debug ("value --> " + (std::string) value);
}
else if (column->type () == "numeric")
value = Variant (ref.get_float (canonical));
else
value = Variant (ref.get (canonical));
return true;
}
}
else if (elements.size () == 3)
{
// tags.<tag>
if (canonical == "tags")
{
value = Variant (ref.hasTag (elements[2]) ? elements[2] : "");
return true;
}
Column* column = context.columns[canonical];
if (column && column->type () == "date")
{
// <date>.year
// <date>.month
// <date>.day
// <date>.week
// <date>.weekday
// <date>.julian
// <date>.hour
// <date>.minute
// <date>.second
Date date (ref.get_date (canonical));
if (elements[2] == "year") { value = Variant (static_cast<int> (date.year ())); return true; }
else if (elements[2] == "month") { value = Variant (static_cast<int> (date.month ())); return true; }
else if (elements[2] == "day") { value = Variant (static_cast<int> (date.day ())); return true; }
else if (elements[2] == "week") { value = Variant (static_cast<int> (date.week ())); return true; }
else if (elements[2] == "weekday") { value = Variant (static_cast<int> (date.dayOfWeek ())); return true; }
else if (elements[2] == "julian") { value = Variant (static_cast<int> (date.dayOfYear ())); return true; }
else if (elements[2] == "hour") { value = Variant (static_cast<int> (date.hour ())); return true; }
else if (elements[2] == "minute") { value = Variant (static_cast<int> (date.minute ())); return true; }
else if (elements[2] == "second") { value = Variant (static_cast<int> (date.second ())); return true; }
}
}
}
else if (elements[1] == "annotations")
{
if (elements.size () == 4)
{
std::map <std::string, std::string> annos;
ref.getAnnotations (annos);
int a = strtol (elements[2].c_str (), NULL, 10);
int count = 0;
// Count off the 'a'th annotation.
for (auto& i : annos)
{
if (++count == a)
{
if (elements[3] == "entry")
{
// annotation_1234567890
// 0 ^11
value = Variant ((time_t) strtol (i.first.substr (11).c_str (), NULL, 10), Variant::type_date);
return true;
}
else if (elements[3] == "description")
{
value = Variant (i.second);
return true;
}
}
}
}
else if (elements.size () == 5)
{
std::map <std::string, std::string> annos;
ref.getAnnotations (annos);
int a = strtol (elements[2].c_str (), NULL, 10);
int count = 0;
// Count off the 'a'th annotation.
for (auto& i : annos)
{
if (++count == a)
{
// <annotations>.<N>.entry.year
// <annotations>.<N>.entry.month
// <annotations>.<N>.entry.day
// <annotations>.<N>.entry.week
// <annotations>.<N>.entry.weekday
// <annotations>.<N>.entry.julian
// <annotations>.<N>.entry.hour
// <annotations>.<N>.entry.minute
// <annotations>.<N>.entry.second
Date date (i.first.substr (11));
if (elements[4] == "year") { value = Variant (static_cast<int> (date.year ())); return true; }
else if (elements[4] == "month") { value = Variant (static_cast<int> (date.month ())); return true; }
else if (elements[4] == "day") { value = Variant (static_cast<int> (date.day ())); return true; }
else if (elements[4] == "week") { value = Variant (static_cast<int> (date.week ())); return true; }
else if (elements[4] == "weekday") { value = Variant (static_cast<int> (date.dayOfWeek ())); return true; }
else if (elements[4] == "julian") { value = Variant (static_cast<int> (date.dayOfYear ())); return true; }
else if (elements[4] == "hour") { value = Variant (static_cast<int> (date.hour ())); return true; }
else if (elements[4] == "minute") { value = Variant (static_cast<int> (date.minute ())); return true; }
else if (elements[4] == "second") { value = Variant (static_cast<int> (date.second ())); return true; }
}
}
}
}
}
}
// Delegate to the context-free version of DOM::get.
return this->get (name, value);
}
////////////////////////////////////////////////////////////////////////////////
<commit_msg>DOM: Missing value UDAs now return "", not "''".<commit_after>////////////////////////////////////////////////////////////////////////////////
//
// Copyright 2006 - 2015, Paul Beckingham, Federico Hernandez.
//
// 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.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////
#include <cmake.h>
#include <sstream>
#include <map>
#include <stdlib.h>
#include <Variant.h>
#include <Duration.h>
#include <Context.h>
#include <Nibbler.h>
#include <ISO8601.h>
#include <Date.h>
#include <text.h>
#include <i18n.h>
#include <DOM.h>
extern Context context;
////////////////////////////////////////////////////////////////////////////////
DOM::DOM ()
{
}
////////////////////////////////////////////////////////////////////////////////
DOM::~DOM ()
{
}
////////////////////////////////////////////////////////////////////////////////
// DOM Supported References:
//
// Configuration:
// rc.<name>
//
// System:
// context.program
// context.args
// context.width
// context.height
// system.version
// system.os
//
bool DOM::get (const std::string& name, Variant& value)
{
int len = name.length ();
Nibbler n (name);
// rc. --> context.config
if (len > 3 &&
name.substr (0, 3) == "rc.")
{
std::string key = name.substr (3);
auto c = context.config.find (key);
if (c != context.config.end ())
{
value = Variant (c->second);
return true;
}
return false;
}
// context.*
if (len > 8 &&
name.substr (0, 8) == "context.")
{
if (name == "context.program")
{
value = Variant (context.cli2.getBinary ());
return true;
}
else if (name == "context.args")
{
std::string commandLine;
join (commandLine, " ", context.cli2._original_args);
value = Variant (commandLine);
return true;
}
else if (name == "context.width")
{
value = Variant (static_cast<int> (context.terminal_width
? context.terminal_width
: context.getWidth ()));
return true;
}
else if (name == "context.height")
{
value = Variant (static_cast<int> (context.terminal_height
? context.terminal_height
: context.getHeight ()));
return true;
}
else
throw format (STRING_DOM_UNREC, name);
}
// TODO stats.<name>
// system. --> Implement locally.
if (len > 7 &&
name.substr (0, 7) == "system.")
{
// Taskwarrior version number.
if (name == "system.version")
{
value = Variant (VERSION);
return true;
}
// OS type.
else if (name == "system.os")
{
#if defined (DARWIN)
value = Variant ("Darwin");
#elif defined (SOLARIS)
value = Variant ("Solaris");
#elif defined (CYGWIN)
value = Variant ("Cygwin");
#elif defined (HAIKU)
value = Variant ("Haiku");
#elif defined (OPENBSD)
value = Variant ("OpenBSD");
#elif defined (FREEBSD)
value = Variant ("FreeBSD");
#elif defined (NETBSD)
value = Variant ("NetBSD");
#elif defined (LINUX)
value = Variant ("Linux");
#elif defined (KFREEBSD)
value = Variant ("GNU/kFreeBSD");
#elif defined (GNUHURD)
value = Variant ("GNU/Hurd");
#else
value = Variant (STRING_DOM_UNKNOWN);
#endif
return true;
}
else
throw format (STRING_DOM_UNREC, name);
}
// Empty string if nothing is found.
return false;
}
////////////////////////////////////////////////////////////////////////////////
// DOM Supported References:
//
// Relative or absolute attribute:
// <attribute>
// <id>.<attribute>
// <uuid>.<attribute>
//
// Single tag:
// tags.<word>
//
// Date type:
// <date>.year
// <date>.month
// <date>.day
// <date>.week
// <date>.weekday
// <date>.julian
// <date>.hour
// <date>.minute
// <date>.second
//
// Annotations (entry is a date):
// annotations.<N>.entry
// annotations.<N>.description
//
bool DOM::get (const std::string& name, const Task& task, Variant& value)
{
// <attr>
if (task.size () && name == "id")
{
value = Variant (static_cast<int> (task.id));
return true;
}
if (task.size () && name == "urgency")
{
value = Variant (task.urgency_c ());
return true;
}
// split name on '.'
std::vector <std::string> elements;
split (elements, name, '.');
if (elements.size () == 1)
{
std::string canonical;
if (task.size () && context.cli2.canonicalize (canonical, "attribute", name))
{
Column* column = context.columns[canonical];
if (column)
{
if (column->is_uda () && ! task.has (canonical))
{
value = Variant ("");
return true;
}
if (column->type () == "date")
{
auto numeric = task.get_date (canonical);
if (numeric == 0)
value = Variant ("");
else
value = Variant (numeric, Variant::type_date);
}
else if (column->type () == "duration" || canonical == "recur")
value = Variant ((time_t) Duration (task.get (canonical)), Variant::type_duration);
else if (column->type () == "numeric")
value = Variant (task.get_float (canonical));
else // string
value = Variant (task.get (canonical));
return true;
}
}
}
else if (elements.size () > 1)
{
Task ref;
Nibbler n (elements[0]);
n.save ();
int id;
std::string uuid;
bool proceed = false;
if (n.getInt (id) && n.depleted ())
{
if (id == task.id)
ref = task;
else
context.tdb2.get (id, ref);
proceed = true;
}
else
{
n.restore ();
if (n.getUUID (uuid) && n.depleted ())
{
if (uuid == task.get ("uuid"))
ref = task;
else
context.tdb2.get (uuid, ref);
proceed = true;
}
}
if (proceed)
{
if (elements[1] == "id")
{
value = Variant (static_cast<int> (ref.id));
return true;
}
else if (elements[1] == "urgency")
{
value = Variant (ref.urgency_c ());
return true;
}
std::string canonical;
if (context.cli2.canonicalize (canonical, "attribute", elements[1]))
{
if (elements.size () == 2)
{
Column* column = context.columns[canonical];
if (column)
{
if (column->is_uda () && ! ref.has (canonical))
{
value = Variant ("");
return true;
}
if (column->type () == "date")
{
auto numeric = ref.get_date (canonical);
if (numeric == 0)
value = Variant ("");
else
value = Variant (numeric, Variant::type_date);
}
else if (column->type () == "duration")
{
auto period = ref.get (canonical);
context.debug ("ref.get(" + canonical + ") --> " + period);
ISO8601p iso;
std::string::size_type cursor = 0;
if (iso.parse (period, cursor))
value = Variant ((time_t) iso._value, Variant::type_duration);
else
value = Variant ((time_t) Duration (ref.get (canonical)), Variant::type_duration);
context.debug ("value --> " + (std::string) value);
}
else if (column->type () == "numeric")
value = Variant (ref.get_float (canonical));
else
value = Variant (ref.get (canonical));
return true;
}
}
else if (elements.size () == 3)
{
// tags.<tag>
if (canonical == "tags")
{
value = Variant (ref.hasTag (elements[2]) ? elements[2] : "");
return true;
}
Column* column = context.columns[canonical];
if (column && column->type () == "date")
{
// <date>.year
// <date>.month
// <date>.day
// <date>.week
// <date>.weekday
// <date>.julian
// <date>.hour
// <date>.minute
// <date>.second
Date date (ref.get_date (canonical));
if (elements[2] == "year") { value = Variant (static_cast<int> (date.year ())); return true; }
else if (elements[2] == "month") { value = Variant (static_cast<int> (date.month ())); return true; }
else if (elements[2] == "day") { value = Variant (static_cast<int> (date.day ())); return true; }
else if (elements[2] == "week") { value = Variant (static_cast<int> (date.week ())); return true; }
else if (elements[2] == "weekday") { value = Variant (static_cast<int> (date.dayOfWeek ())); return true; }
else if (elements[2] == "julian") { value = Variant (static_cast<int> (date.dayOfYear ())); return true; }
else if (elements[2] == "hour") { value = Variant (static_cast<int> (date.hour ())); return true; }
else if (elements[2] == "minute") { value = Variant (static_cast<int> (date.minute ())); return true; }
else if (elements[2] == "second") { value = Variant (static_cast<int> (date.second ())); return true; }
}
}
}
else if (elements[1] == "annotations")
{
if (elements.size () == 4)
{
std::map <std::string, std::string> annos;
ref.getAnnotations (annos);
int a = strtol (elements[2].c_str (), NULL, 10);
int count = 0;
// Count off the 'a'th annotation.
for (auto& i : annos)
{
if (++count == a)
{
if (elements[3] == "entry")
{
// annotation_1234567890
// 0 ^11
value = Variant ((time_t) strtol (i.first.substr (11).c_str (), NULL, 10), Variant::type_date);
return true;
}
else if (elements[3] == "description")
{
value = Variant (i.second);
return true;
}
}
}
}
else if (elements.size () == 5)
{
std::map <std::string, std::string> annos;
ref.getAnnotations (annos);
int a = strtol (elements[2].c_str (), NULL, 10);
int count = 0;
// Count off the 'a'th annotation.
for (auto& i : annos)
{
if (++count == a)
{
// <annotations>.<N>.entry.year
// <annotations>.<N>.entry.month
// <annotations>.<N>.entry.day
// <annotations>.<N>.entry.week
// <annotations>.<N>.entry.weekday
// <annotations>.<N>.entry.julian
// <annotations>.<N>.entry.hour
// <annotations>.<N>.entry.minute
// <annotations>.<N>.entry.second
Date date (i.first.substr (11));
if (elements[4] == "year") { value = Variant (static_cast<int> (date.year ())); return true; }
else if (elements[4] == "month") { value = Variant (static_cast<int> (date.month ())); return true; }
else if (elements[4] == "day") { value = Variant (static_cast<int> (date.day ())); return true; }
else if (elements[4] == "week") { value = Variant (static_cast<int> (date.week ())); return true; }
else if (elements[4] == "weekday") { value = Variant (static_cast<int> (date.dayOfWeek ())); return true; }
else if (elements[4] == "julian") { value = Variant (static_cast<int> (date.dayOfYear ())); return true; }
else if (elements[4] == "hour") { value = Variant (static_cast<int> (date.hour ())); return true; }
else if (elements[4] == "minute") { value = Variant (static_cast<int> (date.minute ())); return true; }
else if (elements[4] == "second") { value = Variant (static_cast<int> (date.second ())); return true; }
}
}
}
}
}
}
// Delegate to the context-free version of DOM::get.
return this->get (name, value);
}
////////////////////////////////////////////////////////////////////////////////
<|endoftext|>
|
<commit_before>#ifndef OPENMVG_VOCABULARY_TREE_VOCABULARY_TREE_HPP
#define OPENMVG_VOCABULARY_TREE_VOCABULARY_TREE_HPP
#include "distance.hpp"
#include "feature_allocator.hpp"
#include <stdint.h>
#include <vector>
#include <cassert>
#include <limits>
#include <fstream>
#include <stdexcept>
#include <iostream>
namespace openMVG {
namespace voctree {
typedef int32_t Word;
/**
* @brief Optimized vocabulary tree quantizer, templated on feature type and distance metric
* for maximum efficiency.
*
* \c Feature is the data type of one feature. It has no requirements except compatibility with the distance metric.
*
* \c Distance is a functor that computes the distance between two Feature objects. It must have a \c result_type
* typedef specifying the type of the returned distance. For the purposes of VocabularyTree, this need not even be
* a metric; distances simply need to be comparable.
*
* \c FeatureAllocator is an STL-compatible allocator used to allocate Features internally.
*/
template<class Feature, template<typename, typename> class Distance = L2,
class FeatureAllocator = typename DefaultAllocator<Feature>::type>
class VocabularyTree
{
public:
/**
* @brief Constructor, empty tree.
*
* @param d Functor for computing the distance between two features
*
* @todo Allocator parameter, also in MutableVocabularyTree, TreeBuilder...
*/
VocabularyTree();
/**
* @brief Constructor, loads vocabulary from file.
*
* @param file Saved vocabulary file
* @param d Functor for computing the distance between two features
*/
VocabularyTree(const std::string& file);
/// Quantizes a feature into a discrete word.
template<class DescriptorT>
Word quantize(const DescriptorT& feature) const;
/// Quantizes a set of features into visual words.
template<class DescriptorT>
std::vector<Word> quantize(const std::vector<DescriptorT>& features) const;
/// Get the depth (number of levels) of the tree.
uint32_t levels() const;
/// Get the branching factor (max splits at each node) of the tree.
uint32_t splits() const;
/// Get the number of words the tree contains.
uint32_t words() const;
/// Clears vocabulary, leaving an empty tree.
void clear();
/// Save vocabulary to a file.
void save(const std::string& file) const;
/// Load vocabulary from a file.
void load(const std::string& file);
protected:
std::vector<Feature, FeatureAllocator> centers_;
std::vector<uint8_t> valid_centers_; /// @todo Consider bit-vector
uint32_t k_; // splits, or branching factor
uint32_t levels_;
uint32_t num_words_; // number of leaf nodes
uint32_t word_start_; // number of non-leaf nodes, or offset to the first leaf node
bool initialized() const
{
return num_words_ != 0;
}
void setNodeCounts();
};
template<class Feature, template<typename, typename> class Distance, class FeatureAllocator>
VocabularyTree<Feature, Distance, FeatureAllocator>::VocabularyTree()
: k_(0), levels_(0), num_words_(0), word_start_(0)
{
}
template<class Feature, template<typename, typename> class Distance, class FeatureAllocator>
VocabularyTree<Feature, Distance, FeatureAllocator>::VocabularyTree(const std::string& file)
: k_(0), levels_(0), num_words_(0), word_start_(0)
{
load(file);
}
template<class Feature, template<typename, typename> class Distance, class FeatureAllocator>
template<class DescriptorT>
Word VocabularyTree<Feature, Distance, FeatureAllocator>::quantize(const DescriptorT& feature) const
{
typedef typename Distance<Feature, DescriptorT>::result_type distance_type;
// printf("asserting\n");
assert(initialized());
// printf("initialized\n");
int32_t index = -1; // virtual "root" index, which has no associated center.
for(unsigned level = 0; level < levels_; ++level)
{
// Calculate the offset to the first child of the current index.
int32_t first_child = (index + 1) * splits();
// Find the child center closest to the query.
int32_t best_child = first_child;
distance_type best_distance = std::numeric_limits<distance_type>::max();
for(int32_t child = first_child; child < first_child + (int32_t) splits(); ++child)
{
if(!valid_centers_[child])
break; // Fewer than splits() children.
distance_type child_distance = Distance<DescriptorT, Feature>()(feature, centers_[child]);
if(child_distance < best_distance)
{
best_child = child;
best_distance = child_distance;
}
}
index = best_child;
}
return index - word_start_;
}
template<class Feature, template<typename, typename> class Distance, class FeatureAllocator>
template<class DescriptorT>
std::vector<Word> VocabularyTree<Feature, Distance, FeatureAllocator>::quantize(const std::vector<DescriptorT>& features) const
{
std::cout << std::endl;
std::cout << "VocabularyTree quantize: " << features.size() << std::endl;
std::vector<Word> imgVisualWords(features.size(), 0);
// quantize the features
#pragma omp parallel for
for(size_t j = 0; j < features.size(); ++j)
{
// store the visual word associated to the feature in the temporary list
imgVisualWords[j] = quantize<DescriptorT>(features[j]);
}
// add the vector to the documents
return imgVisualWords;
}
template<class Feature, template<typename, typename> class Distance, class FeatureAllocator>
uint32_t VocabularyTree<Feature, Distance, FeatureAllocator>::levels() const
{
return levels_;
}
template<class Feature, template<typename, typename> class Distance, class FeatureAllocator>
uint32_t VocabularyTree<Feature, Distance, FeatureAllocator>::splits() const
{
return k_;
}
template<class Feature, template<typename, typename> class Distance, class FeatureAllocator>
uint32_t VocabularyTree<Feature, Distance, FeatureAllocator>::words() const
{
return num_words_;
}
template<class Feature, template<typename, typename> class Distance, class FeatureAllocator>
void VocabularyTree<Feature, Distance, FeatureAllocator>::clear()
{
centers_.clear();
valid_centers_.clear();
k_ = levels_ = num_words_ = word_start_ = 0;
}
template<class Feature, template<typename, typename> class Distance, class FeatureAllocator>
void VocabularyTree<Feature, Distance, FeatureAllocator>::save(const std::string& file) const
{
/// @todo Support serializing of non-"simple" feature classes
/// @todo Some identifying name for the distance used
assert(initialized());
std::ofstream out(file.c_str(), std::ios_base::binary);
out.write((char*) (&k_), sizeof (uint32_t));
out.write((char*) (&levels_), sizeof (uint32_t));
uint32_t size = centers_.size();
out.write((char*) (&size), sizeof (uint32_t));
out.write((char*) (¢ers_[0]), centers_.size() * sizeof (Feature));
out.write((char*) (&valid_centers_[0]), valid_centers_.size());
}
template<class Feature, template<typename, typename> class Distance, class FeatureAllocator>
void VocabularyTree<Feature, Distance, FeatureAllocator>::load(const std::string& file)
{
clear();
std::ifstream in;
in.exceptions(std::ifstream::eofbit | std::ifstream::failbit | std::ifstream::badbit);
uint32_t size;
try
{
in.open(file.c_str(), std::ios_base::binary);
in.read((char*) (&k_), sizeof (uint32_t));
in.read((char*) (&levels_), sizeof (uint32_t));
in.read((char*) (&size), sizeof (uint32_t));
centers_.resize(size);
valid_centers_.resize(size);
in.read((char*) (¢ers_[0]), centers_.size() * sizeof (Feature));
in.read((char*) (&valid_centers_[0]), valid_centers_.size());
}
catch(std::ifstream::failure& e)
{
throw std::runtime_error("Failed to load vocabulary tree file" + file);
}
setNodeCounts();
assert(size == num_words_ + word_start_);
}
template<class Feature, template<typename, typename> class Distance, class FeatureAllocator>
void VocabularyTree<Feature, Distance, FeatureAllocator>::setNodeCounts()
{
num_words_ = k_;
word_start_ = 0;
for(uint32_t i = 0; i < levels_ - 1; ++i)
{
word_start_ += num_words_;
num_words_ *= k_;
}
}
}
}
#endif //OPENMVG_VOCABULARY_TREE_VOCABULARY_TREE_HPP
<commit_msg>[voctree] suppress useless cout<commit_after>#ifndef OPENMVG_VOCABULARY_TREE_VOCABULARY_TREE_HPP
#define OPENMVG_VOCABULARY_TREE_VOCABULARY_TREE_HPP
#include "distance.hpp"
#include "feature_allocator.hpp"
#include <stdint.h>
#include <vector>
#include <cassert>
#include <limits>
#include <fstream>
#include <stdexcept>
#include <iostream>
namespace openMVG {
namespace voctree {
typedef int32_t Word;
/**
* @brief Optimized vocabulary tree quantizer, templated on feature type and distance metric
* for maximum efficiency.
*
* \c Feature is the data type of one feature. It has no requirements except compatibility with the distance metric.
*
* \c Distance is a functor that computes the distance between two Feature objects. It must have a \c result_type
* typedef specifying the type of the returned distance. For the purposes of VocabularyTree, this need not even be
* a metric; distances simply need to be comparable.
*
* \c FeatureAllocator is an STL-compatible allocator used to allocate Features internally.
*/
template<class Feature, template<typename, typename> class Distance = L2,
class FeatureAllocator = typename DefaultAllocator<Feature>::type>
class VocabularyTree
{
public:
/**
* @brief Constructor, empty tree.
*
* @param d Functor for computing the distance between two features
*
* @todo Allocator parameter, also in MutableVocabularyTree, TreeBuilder...
*/
VocabularyTree();
/**
* @brief Constructor, loads vocabulary from file.
*
* @param file Saved vocabulary file
* @param d Functor for computing the distance between two features
*/
VocabularyTree(const std::string& file);
/// Quantizes a feature into a discrete word.
template<class DescriptorT>
Word quantize(const DescriptorT& feature) const;
/// Quantizes a set of features into visual words.
template<class DescriptorT>
std::vector<Word> quantize(const std::vector<DescriptorT>& features) const;
/// Get the depth (number of levels) of the tree.
uint32_t levels() const;
/// Get the branching factor (max splits at each node) of the tree.
uint32_t splits() const;
/// Get the number of words the tree contains.
uint32_t words() const;
/// Clears vocabulary, leaving an empty tree.
void clear();
/// Save vocabulary to a file.
void save(const std::string& file) const;
/// Load vocabulary from a file.
void load(const std::string& file);
protected:
std::vector<Feature, FeatureAllocator> centers_;
std::vector<uint8_t> valid_centers_; /// @todo Consider bit-vector
uint32_t k_; // splits, or branching factor
uint32_t levels_;
uint32_t num_words_; // number of leaf nodes
uint32_t word_start_; // number of non-leaf nodes, or offset to the first leaf node
bool initialized() const
{
return num_words_ != 0;
}
void setNodeCounts();
};
template<class Feature, template<typename, typename> class Distance, class FeatureAllocator>
VocabularyTree<Feature, Distance, FeatureAllocator>::VocabularyTree()
: k_(0), levels_(0), num_words_(0), word_start_(0)
{
}
template<class Feature, template<typename, typename> class Distance, class FeatureAllocator>
VocabularyTree<Feature, Distance, FeatureAllocator>::VocabularyTree(const std::string& file)
: k_(0), levels_(0), num_words_(0), word_start_(0)
{
load(file);
}
template<class Feature, template<typename, typename> class Distance, class FeatureAllocator>
template<class DescriptorT>
Word VocabularyTree<Feature, Distance, FeatureAllocator>::quantize(const DescriptorT& feature) const
{
typedef typename Distance<Feature, DescriptorT>::result_type distance_type;
// printf("asserting\n");
assert(initialized());
// printf("initialized\n");
int32_t index = -1; // virtual "root" index, which has no associated center.
for(unsigned level = 0; level < levels_; ++level)
{
// Calculate the offset to the first child of the current index.
int32_t first_child = (index + 1) * splits();
// Find the child center closest to the query.
int32_t best_child = first_child;
distance_type best_distance = std::numeric_limits<distance_type>::max();
for(int32_t child = first_child; child < first_child + (int32_t) splits(); ++child)
{
if(!valid_centers_[child])
break; // Fewer than splits() children.
distance_type child_distance = Distance<DescriptorT, Feature>()(feature, centers_[child]);
if(child_distance < best_distance)
{
best_child = child;
best_distance = child_distance;
}
}
index = best_child;
}
return index - word_start_;
}
template<class Feature, template<typename, typename> class Distance, class FeatureAllocator>
template<class DescriptorT>
std::vector<Word> VocabularyTree<Feature, Distance, FeatureAllocator>::quantize(const std::vector<DescriptorT>& features) const
{
// std::cout << std::endl;
// std::cout << "VocabularyTree quantize: " << features.size() << std::endl;
std::vector<Word> imgVisualWords(features.size(), 0);
// quantize the features
#pragma omp parallel for
for(size_t j = 0; j < features.size(); ++j)
{
// store the visual word associated to the feature in the temporary list
imgVisualWords[j] = quantize<DescriptorT>(features[j]);
}
// add the vector to the documents
return imgVisualWords;
}
template<class Feature, template<typename, typename> class Distance, class FeatureAllocator>
uint32_t VocabularyTree<Feature, Distance, FeatureAllocator>::levels() const
{
return levels_;
}
template<class Feature, template<typename, typename> class Distance, class FeatureAllocator>
uint32_t VocabularyTree<Feature, Distance, FeatureAllocator>::splits() const
{
return k_;
}
template<class Feature, template<typename, typename> class Distance, class FeatureAllocator>
uint32_t VocabularyTree<Feature, Distance, FeatureAllocator>::words() const
{
return num_words_;
}
template<class Feature, template<typename, typename> class Distance, class FeatureAllocator>
void VocabularyTree<Feature, Distance, FeatureAllocator>::clear()
{
centers_.clear();
valid_centers_.clear();
k_ = levels_ = num_words_ = word_start_ = 0;
}
template<class Feature, template<typename, typename> class Distance, class FeatureAllocator>
void VocabularyTree<Feature, Distance, FeatureAllocator>::save(const std::string& file) const
{
/// @todo Support serializing of non-"simple" feature classes
/// @todo Some identifying name for the distance used
assert(initialized());
std::ofstream out(file.c_str(), std::ios_base::binary);
out.write((char*) (&k_), sizeof (uint32_t));
out.write((char*) (&levels_), sizeof (uint32_t));
uint32_t size = centers_.size();
out.write((char*) (&size), sizeof (uint32_t));
out.write((char*) (¢ers_[0]), centers_.size() * sizeof (Feature));
out.write((char*) (&valid_centers_[0]), valid_centers_.size());
}
template<class Feature, template<typename, typename> class Distance, class FeatureAllocator>
void VocabularyTree<Feature, Distance, FeatureAllocator>::load(const std::string& file)
{
clear();
std::ifstream in;
in.exceptions(std::ifstream::eofbit | std::ifstream::failbit | std::ifstream::badbit);
uint32_t size;
try
{
in.open(file.c_str(), std::ios_base::binary);
in.read((char*) (&k_), sizeof (uint32_t));
in.read((char*) (&levels_), sizeof (uint32_t));
in.read((char*) (&size), sizeof (uint32_t));
centers_.resize(size);
valid_centers_.resize(size);
in.read((char*) (¢ers_[0]), centers_.size() * sizeof (Feature));
in.read((char*) (&valid_centers_[0]), valid_centers_.size());
}
catch(std::ifstream::failure& e)
{
throw std::runtime_error("Failed to load vocabulary tree file" + file);
}
setNodeCounts();
assert(size == num_words_ + word_start_);
}
template<class Feature, template<typename, typename> class Distance, class FeatureAllocator>
void VocabularyTree<Feature, Distance, FeatureAllocator>::setNodeCounts()
{
num_words_ = k_;
word_start_ = 0;
for(uint32_t i = 0; i < levels_ - 1; ++i)
{
word_start_ += num_words_;
num_words_ *= k_;
}
}
}
}
#endif //OPENMVG_VOCABULARY_TREE_VOCABULARY_TREE_HPP
<|endoftext|>
|
<commit_before>// Copyright (c) 2007, 2008 libmv authors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
#include <iostream>
#include <string>
#include "libmv/image/image.h"
#include "libmv/image/image_io.h"
#include "testing/testing.h"
using libmv::Array3Df;
using libmv::Array3Du;
using libmv::FloatImage;
using libmv::GetFormat;
using std::string;
namespace {
TEST(ReadPnm, InvalidFiles) {
Array3Du image;
Array3Df float_image;
string png_filename = string(THIS_SOURCE_DIR) + "/image_test/two_pixels.png";
EXPECT_FALSE(ReadPnm(png_filename.c_str(), &image));
EXPECT_FALSE(ReadPnm("hopefully_unexisting_file", &image));
EXPECT_FALSE(ReadPnm(png_filename.c_str(), &float_image));
EXPECT_FALSE(ReadPnm("hopefully_unexisting_file", &float_image));
}
TEST(ReadPnm, Pgm) {
Array3Du image;
string pgm_filename = string(THIS_SOURCE_DIR) + "/image_test/two_pixels.pgm";
EXPECT_TRUE(ReadPnm(pgm_filename.c_str(), &image));
EXPECT_EQ(2, image.Width());
EXPECT_EQ(1, image.Height());
EXPECT_EQ(1, image.Depth());
EXPECT_EQ(image(0,0), (unsigned char)255);
EXPECT_EQ(image(0,1), (unsigned char)0);
}
TEST(ReadPnm, PgmComments) {
Array3Du image;
string pgm_filename = string(THIS_SOURCE_DIR) + "/image_test/two_pixels_gray.pgm";
EXPECT_TRUE(ReadPnm(pgm_filename.c_str(), &image));
EXPECT_EQ(2, image.Width());
EXPECT_EQ(1, image.Height());
EXPECT_EQ(1, image.Depth());
EXPECT_EQ(image(0,0), (unsigned char)255);
EXPECT_EQ(image(0,1), (unsigned char)0);
}
TEST(ReadPnm, PgmFloat) {
FloatImage image;
string pgm_filename = string(THIS_SOURCE_DIR) + "/image_test/two_pixels.pgm";
EXPECT_TRUE(ReadPnm(pgm_filename.c_str(), &image));
EXPECT_EQ(2, image.Width());
EXPECT_EQ(1, image.Height());
EXPECT_EQ(1, image.Depth());
EXPECT_EQ(image(0,0), 1);
EXPECT_EQ(image(0,1), 0);
}
TEST(WritePnm, Pgm) {
Array3Du image(1,2);
image(0,0) = 255;
image(0,1) = 0;
string out_filename = string(THIS_SOURCE_DIR)
+ "/image_test/test_write_pnm.pgm";
EXPECT_TRUE(WritePnm(image, out_filename.c_str()));
Array3Du read_image;
EXPECT_TRUE(ReadPnm(out_filename.c_str(), &read_image));
EXPECT_TRUE(read_image == image);
}
TEST(ReadPnm, Ppm) {
Array3Du image;
string ppm_filename = string(THIS_SOURCE_DIR) + "/image_test/two_pixels.ppm";
EXPECT_TRUE(ReadPnm(ppm_filename.c_str(), &image));
EXPECT_EQ(2, image.Width());
EXPECT_EQ(1, image.Height());
EXPECT_EQ(3, image.Depth());
EXPECT_EQ(image(0,0,0), (unsigned char)255);
EXPECT_EQ(image(0,0,1), (unsigned char)255);
EXPECT_EQ(image(0,0,2), (unsigned char)255);
EXPECT_EQ(image(0,1,0), (unsigned char)0);
EXPECT_EQ(image(0,1,1), (unsigned char)0);
EXPECT_EQ(image(0,1,2), (unsigned char)0);
}
TEST(WritePnm, Ppm) {
Array3Du image(1,2,3);
image(0,0,0) = 255;
image(0,0,1) = 255;
image(0,0,2) = 255;
image(0,1,0) = 0;
image(0,1,1) = 0;
image(0,1,2) = 0;
string out_filename = string(THIS_SOURCE_DIR)
+ "/image_test/test_write_pnm.ppm";
EXPECT_TRUE(WritePnm(image, out_filename.c_str()));
Array3Du read_image;
EXPECT_TRUE(ReadPnm(out_filename.c_str(), &read_image));
EXPECT_TRUE(read_image == image);
}
TEST(ReadPng, InvalidFiles) {
Array3Du image;
Array3Df float_image;
string pnm_filename = string(THIS_SOURCE_DIR) + "/image_test/two_pixels.ppm";
EXPECT_FALSE(ReadPng(pnm_filename.c_str(), &image));
EXPECT_FALSE(ReadPng("hopefully_unexisting_file", &image));
EXPECT_FALSE(ReadPng(pnm_filename.c_str(), &float_image));
EXPECT_FALSE(ReadPng("hopefully_unexisting_file", &float_image));
}
TEST(ReadPng, Png) {
Array3Du image;
string png_filename = string(THIS_SOURCE_DIR) + "/image_test/two_pixels.png";
EXPECT_TRUE(ReadPng(png_filename.c_str(), &image));
EXPECT_EQ(2, image.Width());
EXPECT_EQ(1, image.Height());
EXPECT_EQ(1, image.Depth());
EXPECT_EQ(image(0,0), (unsigned char)255);
EXPECT_EQ(image(0,1), (unsigned char)0);
}
TEST(ReadPng, PngFloat) {
FloatImage image;
string pgm_filename = string(THIS_SOURCE_DIR) + "/image_test/two_pixels.png";
EXPECT_TRUE(ReadPng(pgm_filename.c_str(), &image));
EXPECT_EQ(2, image.Width());
EXPECT_EQ(1, image.Height());
EXPECT_EQ(1, image.Depth());
EXPECT_EQ(image(0,0), 1);
EXPECT_EQ(image(0,1), 0);
}
TEST(WritePng, Png) {
Array3Du image(1,2);
image(0,0) = 255;
image(0,1) = 0;
string out_filename = string(THIS_SOURCE_DIR)
+ "/image_test/test_write_png.png";
EXPECT_TRUE(WritePng(image, out_filename.c_str()));
Array3Du read_image;
EXPECT_TRUE(ReadPng(out_filename.c_str(), &read_image));
EXPECT_TRUE(read_image == image);
}
TEST(ReadJpg, InvalidFiles) {
Array3Du image;
Array3Df float_image;
string pnm_filename = string(THIS_SOURCE_DIR) + "/image_test/two_pixels.ppm";
EXPECT_FALSE(ReadJpg(pnm_filename.c_str(), &image));
EXPECT_FALSE(ReadJpg("hopefully_unexisting_file", &image));
EXPECT_FALSE(ReadJpg(pnm_filename.c_str(), &float_image));
EXPECT_FALSE(ReadJpg("hopefully_unexisting_file", &float_image));
}
TEST(ReadJpg, Jpg) {
Array3Du image;
string png_filename = string(THIS_SOURCE_DIR) + "/image_test/two_pixels.jpg";
EXPECT_TRUE(ReadJpg(png_filename.c_str(), &image));
EXPECT_EQ(2, image.Width());
EXPECT_EQ(1, image.Height());
EXPECT_EQ(1, image.Depth());
EXPECT_EQ(image(0,0), (unsigned char)255);
EXPECT_EQ(image(0,1), (unsigned char)0);
}
TEST(ReadJpg, JpgFloat) {
FloatImage image;
string pgm_filename = string(THIS_SOURCE_DIR) + "/image_test/two_pixels.jpg";
EXPECT_TRUE(ReadJpg(pgm_filename.c_str(), &image));
EXPECT_EQ(2, image.Width());
EXPECT_EQ(1, image.Height());
EXPECT_EQ(1, image.Depth());
EXPECT_EQ(image(0,0), 1);
EXPECT_EQ(image(0,1), 0);
}
TEST(WriteJpg, Jpg) {
Array3Du image(1,2);
image(0,0) = 255;
image(0,1) = 0;
string out_filename = string(THIS_SOURCE_DIR)
+ "/image_test/test_write_jpg.jpg";
EXPECT_TRUE(WriteJpg(image, out_filename.c_str(), 100));
Array3Du read_image;
EXPECT_TRUE(ReadJpg(out_filename.c_str(), &read_image));
EXPECT_TRUE(read_image == image);
}
TEST(GetFormat, filenames) {
EXPECT_EQ(GetFormat("something.jpg"), libmv::Jpg);
EXPECT_EQ(GetFormat("something.png"), libmv::Png);
EXPECT_EQ(GetFormat("something.pnm"), libmv::Pnm);
EXPECT_EQ(GetFormat("/some/thing.JpG"), libmv::Jpg);
EXPECT_EQ(GetFormat("/some/thing.pNG"), libmv::Png);
EXPECT_EQ(GetFormat("some/thing.PNm"), libmv::Pnm);
EXPECT_EQ(GetFormat(".s/o.m/e.t/h.i/n.g.JPG"), libmv::Jpg);
EXPECT_EQ(GetFormat(".s/o.m/e.t/h.i/n.g.PNG"), libmv::Png);
EXPECT_EQ(GetFormat(".s/o.m/e.t/h.i/n.g.PNM"), libmv::Pnm);
}
} // namespace
<commit_msg>Remove temp files created by image_io_test.<commit_after>// Copyright (c) 2007, 2008 libmv authors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
#include <iostream>
#include <string>
#include <vector>
#include <unistd.h>
#include "libmv/image/image.h"
#include "libmv/image/image_io.h"
#include "testing/testing.h"
using libmv::Array3Df;
using libmv::Array3Du;
using libmv::FloatImage;
using libmv::GetFormat;
using std::string;
#include <cstdio>
namespace {
class ImageIOTest : public testing::Test {
public:
string TmpFile(const char *filename) {
string temp_filename = string(THIS_SOURCE_DIR) + "/image_test/" + filename;
temp_files_.push_back(temp_filename);
return temp_filename;
}
void TearDown() {
for (size_t i = 0; i < temp_files_.size(); ++i) {
fprintf(stderr, "unlinking: %s\n", temp_files_[i].c_str());
unlink(temp_files_[i].c_str());
}
}
private:
std::vector<string> temp_files_;
};
TEST(ReadPnm, InvalidFiles) {
Array3Du image;
Array3Df float_image;
string png_filename = string(THIS_SOURCE_DIR) + "/image_test/two_pixels.png";
EXPECT_FALSE(ReadPnm(png_filename.c_str(), &image));
EXPECT_FALSE(ReadPnm("hopefully_unexisting_file", &image));
EXPECT_FALSE(ReadPnm(png_filename.c_str(), &float_image));
EXPECT_FALSE(ReadPnm("hopefully_unexisting_file", &float_image));
}
TEST(ReadPnm, Pgm) {
Array3Du image;
string pgm_filename = string(THIS_SOURCE_DIR) + "/image_test/two_pixels.pgm";
EXPECT_TRUE(ReadPnm(pgm_filename.c_str(), &image));
EXPECT_EQ(2, image.Width());
EXPECT_EQ(1, image.Height());
EXPECT_EQ(1, image.Depth());
EXPECT_EQ(image(0,0), (unsigned char)255);
EXPECT_EQ(image(0,1), (unsigned char)0);
}
TEST(ReadPnm, PgmComments) {
Array3Du image;
string pgm_filename = string(THIS_SOURCE_DIR) + "/image_test/two_pixels_gray.pgm";
EXPECT_TRUE(ReadPnm(pgm_filename.c_str(), &image));
EXPECT_EQ(2, image.Width());
EXPECT_EQ(1, image.Height());
EXPECT_EQ(1, image.Depth());
EXPECT_EQ(image(0,0), (unsigned char)255);
EXPECT_EQ(image(0,1), (unsigned char)0);
}
TEST(ReadPnm, PgmFloat) {
FloatImage image;
string pgm_filename = string(THIS_SOURCE_DIR) + "/image_test/two_pixels.pgm";
EXPECT_TRUE(ReadPnm(pgm_filename.c_str(), &image));
EXPECT_EQ(2, image.Width());
EXPECT_EQ(1, image.Height());
EXPECT_EQ(1, image.Depth());
EXPECT_EQ(image(0,0), 1);
EXPECT_EQ(image(0,1), 0);
}
TEST_F(ImageIOTest, Pgm) {
Array3Du image(1,2);
image(0,0) = 255;
image(0,1) = 0;
string out_filename = TmpFile("test_write_pnm.pgm");
EXPECT_TRUE(WritePnm(image, out_filename.c_str()));
Array3Du read_image;
EXPECT_TRUE(ReadPnm(out_filename.c_str(), &read_image));
EXPECT_TRUE(read_image == image);
}
TEST(ReadPnm, Ppm) {
Array3Du image;
string ppm_filename = string(THIS_SOURCE_DIR) + "/image_test/two_pixels.ppm";
EXPECT_TRUE(ReadPnm(ppm_filename.c_str(), &image));
EXPECT_EQ(2, image.Width());
EXPECT_EQ(1, image.Height());
EXPECT_EQ(3, image.Depth());
EXPECT_EQ(image(0,0,0), (unsigned char)255);
EXPECT_EQ(image(0,0,1), (unsigned char)255);
EXPECT_EQ(image(0,0,2), (unsigned char)255);
EXPECT_EQ(image(0,1,0), (unsigned char)0);
EXPECT_EQ(image(0,1,1), (unsigned char)0);
EXPECT_EQ(image(0,1,2), (unsigned char)0);
}
TEST_F(ImageIOTest, Ppm) {
Array3Du image(1,2,3);
image(0,0,0) = 255;
image(0,0,1) = 255;
image(0,0,2) = 255;
image(0,1,0) = 0;
image(0,1,1) = 0;
image(0,1,2) = 0;
string out_filename = TmpFile("test_write_pnm.ppm");
EXPECT_TRUE(WritePnm(image, out_filename.c_str()));
Array3Du read_image;
EXPECT_TRUE(ReadPnm(out_filename.c_str(), &read_image));
EXPECT_TRUE(read_image == image);
}
TEST(ReadPng, InvalidFiles) {
Array3Du image;
Array3Df float_image;
string pnm_filename = string(THIS_SOURCE_DIR) + "/image_test/two_pixels.ppm";
EXPECT_FALSE(ReadPng(pnm_filename.c_str(), &image));
EXPECT_FALSE(ReadPng("hopefully_unexisting_file", &image));
EXPECT_FALSE(ReadPng(pnm_filename.c_str(), &float_image));
EXPECT_FALSE(ReadPng("hopefully_unexisting_file", &float_image));
}
TEST(ReadPng, Png) {
Array3Du image;
string png_filename = string(THIS_SOURCE_DIR) + "/image_test/two_pixels.png";
EXPECT_TRUE(ReadPng(png_filename.c_str(), &image));
EXPECT_EQ(2, image.Width());
EXPECT_EQ(1, image.Height());
EXPECT_EQ(1, image.Depth());
EXPECT_EQ(image(0,0), (unsigned char)255);
EXPECT_EQ(image(0,1), (unsigned char)0);
}
TEST(ReadPng, PngFloat) {
FloatImage image;
string pgm_filename = string(THIS_SOURCE_DIR) + "/image_test/two_pixels.png";
EXPECT_TRUE(ReadPng(pgm_filename.c_str(), &image));
EXPECT_EQ(2, image.Width());
EXPECT_EQ(1, image.Height());
EXPECT_EQ(1, image.Depth());
EXPECT_EQ(image(0,0), 1);
EXPECT_EQ(image(0,1), 0);
}
TEST_F(ImageIOTest, Png) {
Array3Du image(1,2);
image(0,0) = 255;
image(0,1) = 0;
string out_filename = TmpFile("test_write_png.png");
EXPECT_TRUE(WritePng(image, out_filename.c_str()));
Array3Du read_image;
EXPECT_TRUE(ReadPng(out_filename.c_str(), &read_image));
EXPECT_TRUE(read_image == image);
}
TEST_F(ImageIOTest, InvalidFiles) {
Array3Du image;
Array3Df float_image;
string pnm_filename = string(THIS_SOURCE_DIR) + "/image_test/two_pixels.ppm";
EXPECT_FALSE(ReadJpg(pnm_filename.c_str(), &image));
EXPECT_FALSE(ReadJpg("hopefully_unexisting_file", &image));
EXPECT_FALSE(ReadJpg(pnm_filename.c_str(), &float_image));
EXPECT_FALSE(ReadJpg("hopefully_unexisting_file", &float_image));
}
TEST(ReadJpg, Jpg) {
Array3Du image;
string png_filename = string(THIS_SOURCE_DIR) + "/image_test/two_pixels.jpg";
EXPECT_TRUE(ReadJpg(png_filename.c_str(), &image));
EXPECT_EQ(2, image.Width());
EXPECT_EQ(1, image.Height());
EXPECT_EQ(1, image.Depth());
EXPECT_EQ(image(0,0), (unsigned char)255);
EXPECT_EQ(image(0,1), (unsigned char)0);
}
TEST(ReadJpg, JpgFloat) {
FloatImage image;
string pgm_filename = string(THIS_SOURCE_DIR) + "/image_test/two_pixels.jpg";
EXPECT_TRUE(ReadJpg(pgm_filename.c_str(), &image));
EXPECT_EQ(2, image.Width());
EXPECT_EQ(1, image.Height());
EXPECT_EQ(1, image.Depth());
EXPECT_EQ(image(0,0), 1);
EXPECT_EQ(image(0,1), 0);
}
TEST_F(ImageIOTest, Jpg) {
Array3Du image(1,2);
image(0,0) = 255;
image(0,1) = 0;
string out_filename = TmpFile("test_write_jpg.jpg");
EXPECT_TRUE(WriteJpg(image, out_filename.c_str(), 100));
Array3Du read_image;
EXPECT_TRUE(ReadJpg(out_filename.c_str(), &read_image));
EXPECT_TRUE(read_image == image);
}
TEST(GetFormat, filenames) {
EXPECT_EQ(GetFormat("something.jpg"), libmv::Jpg);
EXPECT_EQ(GetFormat("something.png"), libmv::Png);
EXPECT_EQ(GetFormat("something.pnm"), libmv::Pnm);
EXPECT_EQ(GetFormat("/some/thing.JpG"), libmv::Jpg);
EXPECT_EQ(GetFormat("/some/thing.pNG"), libmv::Png);
EXPECT_EQ(GetFormat("some/thing.PNm"), libmv::Pnm);
EXPECT_EQ(GetFormat(".s/o.m/e.t/h.i/n.g.JPG"), libmv::Jpg);
EXPECT_EQ(GetFormat(".s/o.m/e.t/h.i/n.g.PNG"), libmv::Png);
EXPECT_EQ(GetFormat(".s/o.m/e.t/h.i/n.g.PNM"), libmv::Pnm);
}
} // namespace
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: ViewTabBar.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-02-04 14:18:42 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "ViewTabBar.hxx"
#define USE_TAB_CONTROL
#include "ViewShell.hxx"
#include "PaneManager.hxx"
#include "ViewShellBase.hxx"
#include "DrawViewShell.hxx"
#include "FrameView.hxx"
#include "sdresid.hxx"
#include "strings.hrc"
#include "helpids.h"
#include <vcl/tabpage.hxx>
namespace {
enum ViewTabBarEntry {
VTBE_FIRST = 1,
VTBE_EDIT_VIEW = VTBE_FIRST,
VTBE_OUTLINE_VIEW,
VTBE_NOTES_VIEW,
VTBE_HANDOUT_VIEW,
VTBE_SLIDE_VIEW,
VTBE_LAST = VTBE_SLIDE_VIEW
};
} // end of anonymous namespace
namespace sd {
class ViewTabPage : public TabPage
{
public:
ViewTabPage (Window* pParent) : TabPage(pParent) {}
virtual void Resize (void)
{ SetPosSizePixel(Point(0,0),GetParent()->GetOutputSizePixel()); }
};
ViewTabBar::ViewTabBar (ViewShellBase& rViewShellBase, Window* pParent)
: TabControl (pParent),
mrViewShellBase (rViewShellBase)
{
// SetMaxPageWidth(150);
// SetHelpId( HID_SD_TABBAR_PAGES );
// Add tabs for the views that can be displayed in the center pane.
InsertPage (VTBE_EDIT_VIEW,
String (SdResId (STR_DRAW_MODE)));
InsertPage (VTBE_OUTLINE_VIEW,
String (SdResId (STR_OUTLINE_MODE)));
InsertPage (VTBE_NOTES_VIEW,
String (SdResId (STR_NOTES_MODE)));
InsertPage (VTBE_HANDOUT_VIEW,
String (SdResId (STR_HANDOUT_MODE)));
InsertPage (VTBE_SLIDE_VIEW,
String (SdResId (STR_SLIDE_MODE)));
// InsertPage (VTBE_OLD_SLIDE_VIEW,
// String (SdResId (STR_SLIDE_MODE)));
// Set one new tab page for all tab entries. We need it only to
// determine the height of the tab bar.
TabPage* pTabPage = new TabPage (this);
for (USHORT nIndex=VTBE_FIRST; nIndex<=VTBE_LAST; nIndex++)
{
SetTabPage (nIndex, pTabPage);
pTabPage->Hide();
}
// add some space before the tabitems
SetItemsOffset( Point( 5, 3) );
// Set help texts.
SetHelpId (VTBE_EDIT_VIEW, HID_SD_BTN_DRAW);
SetHelpId (VTBE_SLIDE_VIEW, HID_SD_BTN_SLIDE);
// SetHelpId (VTBE_OLD_SLIDE_VIEW, HID_SD_BTN_SLIDE);
SetHelpId (VTBE_OUTLINE_VIEW, HID_SD_BTN_OUTLINE);
SetHelpId (VTBE_NOTES_VIEW, HID_SD_BTN_NOTES);
SetHelpId (VTBE_HANDOUT_VIEW, HID_SD_BTN_HANDOUT);
// Register as listener at the view shell base.
mrViewShellBase.GetPaneManager().AddEventListener (
LINK(this, ViewTabBar, ViewShellBaseEventHandler));
}
ViewTabBar::~ViewTabBar (void)
{
// Set all references to the one tab page to NULL and delete the page.
TabPage* pTabPage = GetTabPage (VTBE_FIRST);
for (USHORT nIndex=VTBE_FIRST; nIndex<=VTBE_LAST; nIndex++)
{
SetTabPage (nIndex, NULL);
}
delete pTabPage;
// Tell the view shell base that we are not able to listen anymore.
mrViewShellBase.GetPaneManager().RemoveEventListener (
LINK(this, ViewTabBar, ViewShellBaseEventHandler));
}
void ViewTabBar::ActivatePage (void)
{
TabControl::ActivatePage ();
ViewShell::ShellType eType (
mrViewShellBase.GetPaneManager().GetViewShellType(
PaneManager::PT_CENTER));
PageKind ePageKind (PK_STANDARD);
switch (GetCurPageId())
{
case VTBE_EDIT_VIEW:
eType = ViewShell::ST_IMPRESS;
ePageKind = PK_STANDARD;
break;
case VTBE_OUTLINE_VIEW:
eType = ViewShell::ST_OUTLINE;
break;
case VTBE_NOTES_VIEW:
eType = ViewShell::ST_NOTES;
ePageKind = PK_NOTES;
break;
case VTBE_HANDOUT_VIEW:
eType = ViewShell::ST_HANDOUT;
ePageKind = PK_HANDOUT;
break;
case VTBE_SLIDE_VIEW:
eType = ViewShell::ST_SLIDE_SORTER;
break;
default:
eType = ViewShell::ST_NONE;
break;
}
ViewShell* pViewShell = mrViewShellBase.GetMainViewShell();
if (pViewShell != NULL)
{
FrameView* pFrameView = pViewShell->GetFrameView();
if (pFrameView != NULL)
{
pFrameView->SetViewShEditMode (EM_PAGE, pFrameView->GetPageKind());
DrawViewShell* pDrawViewShell = static_cast<DrawViewShell*>(pViewShell);
if (pDrawViewShell != NULL)
{
pFrameView->SetLayerMode (pDrawViewShell->IsLayerModeActive());
pFrameView->SetViewShEditMode(EM_PAGE, ePageKind);
}
}
}
mrViewShellBase.GetPaneManager().RequestMainViewShellChange (eType);
}
void ViewTabBar::Paint (const Rectangle& rRect)
{
Color aOriginalFillColor (GetFillColor());
Color aOriginalLineColor (GetLineColor());
// Because the actual window background is transparent--to avoid
// flickering due to multiple background paintings by this and by child
// windows--we have to paint the background for this control
// explicitly: the actual control is not painted over its whole bounding
// box.
SetFillColor (GetSettings().GetStyleSettings().GetDialogColor());
SetLineColor ();
DrawRect (rRect);
TabControl::Paint (rRect);
SetFillColor (aOriginalFillColor);
SetLineColor (aOriginalLineColor);
}
int ViewTabBar::GetHeight (void)
{
int nHeight (0);
TabPage* pActivePage (GetTabPage(GetCurPageId()));
if (pActivePage!=NULL && IsReallyVisible())
nHeight = pActivePage->GetPosPixel().Y();
if (nHeight <= 0)
// Using a default when the real height can not be determined. To
// get correct height this method should be called when the control
// is visible.
nHeight = 21;
return nHeight;
}
IMPL_LINK(ViewTabBar, ViewShellBaseEventHandler, PaneManagerEvent*, pEvent)
{
if (pEvent->meEventId == PaneManagerEvent::EID_VIEW_SHELL_ADDED
&& pEvent->mePane == PaneManager::PT_CENTER)
{
// Select the tab of the currently active view.
ViewTabBarEntry eActiveView = VTBE_EDIT_VIEW;
switch (mrViewShellBase.GetPaneManager().GetViewShellType (
PaneManager::PT_CENTER))
{
case ViewShell::ST_DRAW:
case ViewShell::ST_IMPRESS:
eActiveView = VTBE_EDIT_VIEW;
break;
case ViewShell::ST_OUTLINE:
eActiveView = VTBE_OUTLINE_VIEW;
break;
case ViewShell::ST_SLIDE_SORTER:
eActiveView = VTBE_SLIDE_VIEW;
break;
case ViewShell::ST_NOTES:
eActiveView = VTBE_NOTES_VIEW;
break;
case ViewShell::ST_HANDOUT:
eActiveView = VTBE_HANDOUT_VIEW;
break;
}
SetCurPageId (eActiveView);
}
return 0;
}
} // end of namespace sd
<commit_msg>INTEGRATION: CWS impress34 (1.4.2); FILE MERGED 2005/02/11 12:22:02 af 1.4.2.1: #i42445# Fixed use of cast operator.<commit_after>/*************************************************************************
*
* $RCSfile: ViewTabBar.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: vg $ $Date: 2005-02-24 15:13:37 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include "ViewTabBar.hxx"
#define USE_TAB_CONTROL
#include "ViewShell.hxx"
#include "PaneManager.hxx"
#include "ViewShellBase.hxx"
#include "DrawViewShell.hxx"
#include "FrameView.hxx"
#include "sdresid.hxx"
#include "strings.hrc"
#include "helpids.h"
#include <vcl/tabpage.hxx>
namespace {
enum ViewTabBarEntry {
VTBE_FIRST = 1,
VTBE_EDIT_VIEW = VTBE_FIRST,
VTBE_OUTLINE_VIEW,
VTBE_NOTES_VIEW,
VTBE_HANDOUT_VIEW,
VTBE_SLIDE_VIEW,
VTBE_LAST = VTBE_SLIDE_VIEW
};
} // end of anonymous namespace
namespace sd {
class ViewTabPage : public TabPage
{
public:
ViewTabPage (Window* pParent) : TabPage(pParent) {}
virtual void Resize (void)
{ SetPosSizePixel(Point(0,0),GetParent()->GetOutputSizePixel()); }
};
ViewTabBar::ViewTabBar (ViewShellBase& rViewShellBase, Window* pParent)
: TabControl (pParent),
mrViewShellBase (rViewShellBase)
{
// SetMaxPageWidth(150);
// SetHelpId( HID_SD_TABBAR_PAGES );
// Add tabs for the views that can be displayed in the center pane.
InsertPage (VTBE_EDIT_VIEW,
String (SdResId (STR_DRAW_MODE)));
InsertPage (VTBE_OUTLINE_VIEW,
String (SdResId (STR_OUTLINE_MODE)));
InsertPage (VTBE_NOTES_VIEW,
String (SdResId (STR_NOTES_MODE)));
InsertPage (VTBE_HANDOUT_VIEW,
String (SdResId (STR_HANDOUT_MODE)));
InsertPage (VTBE_SLIDE_VIEW,
String (SdResId (STR_SLIDE_MODE)));
// InsertPage (VTBE_OLD_SLIDE_VIEW,
// String (SdResId (STR_SLIDE_MODE)));
// Set one new tab page for all tab entries. We need it only to
// determine the height of the tab bar.
TabPage* pTabPage = new TabPage (this);
for (USHORT nIndex=VTBE_FIRST; nIndex<=VTBE_LAST; nIndex++)
{
SetTabPage (nIndex, pTabPage);
pTabPage->Hide();
}
// add some space before the tabitems
SetItemsOffset( Point( 5, 3) );
// Set help texts.
SetHelpId (VTBE_EDIT_VIEW, HID_SD_BTN_DRAW);
SetHelpId (VTBE_SLIDE_VIEW, HID_SD_BTN_SLIDE);
// SetHelpId (VTBE_OLD_SLIDE_VIEW, HID_SD_BTN_SLIDE);
SetHelpId (VTBE_OUTLINE_VIEW, HID_SD_BTN_OUTLINE);
SetHelpId (VTBE_NOTES_VIEW, HID_SD_BTN_NOTES);
SetHelpId (VTBE_HANDOUT_VIEW, HID_SD_BTN_HANDOUT);
// Register as listener at the view shell base.
mrViewShellBase.GetPaneManager().AddEventListener (
LINK(this, ViewTabBar, ViewShellBaseEventHandler));
}
ViewTabBar::~ViewTabBar (void)
{
// Set all references to the one tab page to NULL and delete the page.
TabPage* pTabPage = GetTabPage (VTBE_FIRST);
for (USHORT nIndex=VTBE_FIRST; nIndex<=VTBE_LAST; nIndex++)
{
SetTabPage (nIndex, NULL);
}
delete pTabPage;
// Tell the view shell base that we are not able to listen anymore.
mrViewShellBase.GetPaneManager().RemoveEventListener (
LINK(this, ViewTabBar, ViewShellBaseEventHandler));
}
void ViewTabBar::ActivatePage (void)
{
TabControl::ActivatePage ();
ViewShell::ShellType eType (
mrViewShellBase.GetPaneManager().GetViewShellType(
PaneManager::PT_CENTER));
PageKind ePageKind (PK_STANDARD);
switch (GetCurPageId())
{
case VTBE_EDIT_VIEW:
eType = ViewShell::ST_IMPRESS;
ePageKind = PK_STANDARD;
break;
case VTBE_OUTLINE_VIEW:
eType = ViewShell::ST_OUTLINE;
break;
case VTBE_NOTES_VIEW:
eType = ViewShell::ST_NOTES;
ePageKind = PK_NOTES;
break;
case VTBE_HANDOUT_VIEW:
eType = ViewShell::ST_HANDOUT;
ePageKind = PK_HANDOUT;
break;
case VTBE_SLIDE_VIEW:
eType = ViewShell::ST_SLIDE_SORTER;
break;
default:
eType = ViewShell::ST_NONE;
break;
}
ViewShell* pViewShell = mrViewShellBase.GetMainViewShell();
if (pViewShell != NULL)
{
FrameView* pFrameView = pViewShell->GetFrameView();
if (pFrameView != NULL)
{
pFrameView->SetViewShEditMode (EM_PAGE, pFrameView->GetPageKind());
DrawViewShell* pDrawViewShell = dynamic_cast<DrawViewShell*>(pViewShell);
if (pDrawViewShell != NULL)
{
pFrameView->SetLayerMode (pDrawViewShell->IsLayerModeActive());
pFrameView->SetViewShEditMode(EM_PAGE, ePageKind);
}
}
}
mrViewShellBase.GetPaneManager().RequestMainViewShellChange (eType);
}
void ViewTabBar::Paint (const Rectangle& rRect)
{
Color aOriginalFillColor (GetFillColor());
Color aOriginalLineColor (GetLineColor());
// Because the actual window background is transparent--to avoid
// flickering due to multiple background paintings by this and by child
// windows--we have to paint the background for this control
// explicitly: the actual control is not painted over its whole bounding
// box.
SetFillColor (GetSettings().GetStyleSettings().GetDialogColor());
SetLineColor ();
DrawRect (rRect);
TabControl::Paint (rRect);
SetFillColor (aOriginalFillColor);
SetLineColor (aOriginalLineColor);
}
int ViewTabBar::GetHeight (void)
{
int nHeight (0);
TabPage* pActivePage (GetTabPage(GetCurPageId()));
if (pActivePage!=NULL && IsReallyVisible())
nHeight = pActivePage->GetPosPixel().Y();
if (nHeight <= 0)
// Using a default when the real height can not be determined. To
// get correct height this method should be called when the control
// is visible.
nHeight = 21;
return nHeight;
}
IMPL_LINK(ViewTabBar, ViewShellBaseEventHandler, PaneManagerEvent*, pEvent)
{
if (pEvent->meEventId == PaneManagerEvent::EID_VIEW_SHELL_ADDED
&& pEvent->mePane == PaneManager::PT_CENTER)
{
// Select the tab of the currently active view.
ViewTabBarEntry eActiveView = VTBE_EDIT_VIEW;
switch (mrViewShellBase.GetPaneManager().GetViewShellType (
PaneManager::PT_CENTER))
{
case ViewShell::ST_DRAW:
case ViewShell::ST_IMPRESS:
eActiveView = VTBE_EDIT_VIEW;
break;
case ViewShell::ST_OUTLINE:
eActiveView = VTBE_OUTLINE_VIEW;
break;
case ViewShell::ST_SLIDE_SORTER:
eActiveView = VTBE_SLIDE_VIEW;
break;
case ViewShell::ST_NOTES:
eActiveView = VTBE_NOTES_VIEW;
break;
case ViewShell::ST_HANDOUT:
eActiveView = VTBE_HANDOUT_VIEW;
break;
}
SetCurPageId (eActiveView);
}
return 0;
}
} // end of namespace sd
<|endoftext|>
|
<commit_before>// Copyright (c) 2017 ASMlover. 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 ofconditions 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 materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <Chaos/Types.h>
int main(int argc, char* argv[]) {
CHAOS_UNUSED(argc), CHAOS_UNUSED(argv);
return 0;
}
<commit_msg>:white_check_mark: test(ParallelChannelMemory): add unittest for parallel channel gc<commit_after>// Copyright (c) 2017 ASMlover. 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 ofconditions 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 materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <Chaos/Types.h>
#include "parallel_channel.h"
int main(int argc, char* argv[]) {
CHAOS_UNUSED(argc), CHAOS_UNUSED(argv);
constexpr int kCount = 1000;
constexpr int kReleaseCount = 20;
constexpr int kCreateCount = kReleaseCount * 3;
for (auto i = 0; i < kCount; ++i) {
for (auto j = 0; j < kCreateCount; ++j) {
if ((j + 1) % 3 == 0) {
auto* second = gc::ParallelChannel::get_instance().fetch_out();
auto* first = gc::ParallelChannel::get_instance().fetch_out();
gc::ParallelChannel::get_instance().put_in(first, second);
}
else {
gc::ParallelChannel::get_instance().put_in(i * j);
}
}
for (auto j = 0; j < kReleaseCount; ++j)
gc::ParallelChannel::get_instance().fetch_out();
}
gc::ParallelChannel::get_instance().collect();
return 0;
}
<|endoftext|>
|
<commit_before>#include "../../edgeElement.h"
#include "../../nodeElement.h"
#include "embeddedLinker.h"
#include <math.h>
#include <QDebug>
#include <QStyle>
#include <QGraphicsItem>
#include <QStyleOptionGraphicsItem>
#include "../../../view/editorViewScene.h"
#include "../../../mainwindow/mainWindow.h"
#include "../../private/reshapeEdgeCommand.h"
using namespace qReal;
EmbeddedLinker::EmbeddedLinker()
: mEdge(NULL)
, mMaster(NULL)
, mColor(Qt::blue)
, mPressed(false)
, mTimeOfUpdate(0)
, mTimer(new QTimer(this))
{
mSize = SettingsManager::value("EmbeddedLinkerSize").toFloat();
if (mSize > 10) {
mSize *= 0.75;
}
mIndent = SettingsManager::value("EmbeddedLinkerIndent").toFloat();
mIndent *= 0.8;
if (mIndent > 17) {
mIndent *= 0.7;
}
mRectangle = QRectF(-mSize, -mSize, mSize * 2, mSize * 2);
mInnerRectangle = QRectF(-mSize / 2, -mSize / 2, mSize, mSize);
setZValue(300);
setFlag(ItemStacksBehindParent, false);
setAcceptHoverEvents(true);
connect(mTimer, SIGNAL(timeout()), this, SLOT(updateMasterEdge()));
}
EmbeddedLinker::~EmbeddedLinker()
{
}
NodeElement* EmbeddedLinker::getMaster()
{
return mMaster;
}
void EmbeddedLinker::setMaster(NodeElement *element)
{
mMaster = element;
setParentItem(element);
}
void EmbeddedLinker::generateColor()
{
int result = 0;
mColor = QColor(result % 192 + 64, result % 128 + 128, result % 64 + 192).darker(0);
}
void EmbeddedLinker::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget*)
{
Q_UNUSED(option);
painter->save();
QBrush brush;
brush.setColor(mColor);
brush.setStyle(Qt::SolidPattern);
painter->setBrush(brush);
painter->setOpacity(0.75);
painter->setPen(mColor);
mSize = SettingsManager::value("EmbeddedLinkerSize").toFloat();
if (mSize > 10) {
mSize *= 0.75;
}
mRectangle = QRectF(-mSize, -mSize, mSize * 2, mSize * 2);
mInnerRectangle = QRectF(-mSize / 2, -mSize / 2, mSize, mSize);
painter->drawEllipse(mRectangle);
painter->setOpacity(0.9);
painter->drawEllipse(mInnerRectangle);
painter->restore();
}
void EmbeddedLinker::setDirected(const bool directed)
{
this->mDirected = directed;
}
void EmbeddedLinker::initTitle()
{
EditorManagerInterface const &editorManagerInterface
= dynamic_cast<EditorViewScene*>(scene())->mainWindow()->editorManager();
QString edgeTypeFriendly = editorManagerInterface.friendlyName(Id::loadFromString("qrm:/"+ mMaster->id().editor()
+ "/" + mMaster->id().diagram() + "/" + mEdgeType.element()));
float textWidth = edgeTypeFriendly.size()*10;
float rectWidth = mMaster->boundingRect().right() - mMaster->boundingRect().left();
float rectHeight = mMaster->boundingRect().bottom() - mMaster->boundingRect().top();
int x = 0;
int y = 0;
if (scenePos().y() < mMaster->scenePos().y() + rectHeight/3)
y = -boundingRect().height() - 10;
else if (scenePos().y() > mMaster->scenePos().y() + 2*rectHeight/3)
y = +boundingRect().height() - 10;
if (scenePos().x() < mMaster->scenePos().x() + rectWidth/3)
x = -boundingRect().width() - textWidth + 20;
else if (scenePos().x() > mMaster->scenePos().x() + 2*rectWidth/3)
x = +boundingRect().width() - 10;
mTitle = new Label(static_cast<qreal>(x) / boundingRect().width()
, static_cast<qreal>(y) / boundingRect().height(), edgeTypeFriendly, 0);
mTitle->init(boundingRect());
mTitle->setTextWidth(textWidth);
mTitle->setParentItem(this);
}
void EmbeddedLinker::setEdgeType(const qReal::Id &edgeType)
{
this->mEdgeType = edgeType;
generateColor();
}
qReal::Id EmbeddedLinker::getEdgeType()
{
return mEdgeType;
}
bool EmbeddedLinker::isDirected()
{
return mDirected;
}
void EmbeddedLinker::takePosition(int index, int maxIndex)
{
qreal const pi = 3.141592;
QRectF const bounding = mMaster->boundingRect();
qreal const top = bounding.topLeft().y();
qreal const left = bounding.topLeft().x();
qreal const right = bounding.bottomRight().x();
qreal const bottom = bounding.bottomRight().y();
qreal const height = bottom - top;
qreal const width = right - left;
qreal const angle = 2 * pi * index / maxIndex;
int rW = width;
int rH = height;
if (rW < 150) {
rW *= 1.5;
} else {
rW += 5;
}
if (rH < 150) {
rH *= 1.5;
} else {
rH += 5;
}
// TODO: customize start angle
qreal const px = left + width / 2 + rW * cos(angle) / 2;
qreal const py = bottom - height / 2 + rH * sin(angle) / 2;
// if linker covers master node:
qreal min = py - top;
if (min > bottom - py) {
min = bottom - py;
}
if (min > px - left) {
min = px - left;
}
if (min > right - px) {
min = right - px;
}
qreal fx;
qreal fy;
mIndent = SettingsManager::value("EmbeddedLinkerIndent").toFloat();
mIndent *= 0.8;
if (mIndent > 17) {
mIndent *= 0.7;
}
//obviously, top != left != right != bottom
if ((bottom - py == min) || (py - top == min)) {
fx = px;
fy = bottom - py == min ? bottom + mIndent : top - mIndent;
} else {
fx = right - px == min ? right + mIndent : left - mIndent;
fy = py;
}
setPos(fx, fy);
}
QRectF EmbeddedLinker::boundingRect() const {
return mRectangle;
}
void EmbeddedLinker::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
Q_UNUSED(event)
mPressed = true;
if (event->button() == Qt::LeftButton) {
mEdge = NULL;
}
}
void EmbeddedLinker::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
mTimer->start(400);
if (mPressed) {
mPressed = false;
EditorViewScene *scene = dynamic_cast<EditorViewScene*>(mMaster->scene());
if (!scene) {
return;
}
QString const type = "qrm:/" + mMaster->id().editor() + "/" +
mMaster->id().diagram() + "/" + mEdgeType.element();
if (scene->mainWindow()->editorManager().hasElement(Id::loadFromString(type))) {
mMaster->setConnectingState(true);
// FIXME: I am raw. return strange pos() and inside me a small trash
Id edgeId = scene->createElement(type, event->scenePos(), true, &mCreateEdgeCommand);
mEdge = dynamic_cast<EdgeElement*>(scene->getElem(edgeId));
}
if (mEdge) {
mMaster->setZValue(1);
mEdge->setSrc(mMaster);
mEdge->setDst(NULL);
mEdge->highlight();
mEdge->tuneForLinker();
mEdge->placeEndTo(mEdge->mapFromScene(mapToScene(event->pos())));
mMaster->arrangeLinks();
mMaster->adjustLinks();
}
}
if (mEdge) {
if (mTimeOfUpdate == 14) {
mTimeOfUpdate = 0;
mEdge->adjustNeighborLinks();
mEdge->arrangeSrcAndDst();
} else {
mTimeOfUpdate++;
}
mEdge->placeEndTo(mEdge->mapFromScene(mapToScene(event->pos())));
}
}
void EmbeddedLinker::updateMasterEdge()
{
mTimer->stop();
mTimeOfUpdate = 0;
if (mEdge) {
mEdge->arrangeSrcAndDst();
mEdge->adjustNeighborLinks();
}
}
void EmbeddedLinker::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
hide();
mMaster->selectionState(false);
EditorViewScene* scene = dynamic_cast<EditorViewScene*>(mMaster->scene());
if (!mPressed && scene && mEdge) {
mEdge->hide();
QPointF const &eScenePos = event->scenePos();
NodeElement *under = dynamic_cast<NodeElement*>(scene->itemAt(eScenePos, QTransform()));
mEdge->show();
int result = 0;
commands::CreateElementCommand *createElementFromMenuCommand = NULL;
if (!under) {
result = scene->launchEdgeMenu(mEdge, mMaster, eScenePos, false, &createElementFromMenuCommand);
} else {
bool canBeConnected = false;
foreach(PossibleEdge const &pEdge, mEdge->src()->getPossibleEdges()) {
if (pEdge.first.second.element() == under->id().element()) {
canBeConnected = true;
}
}
if (under->isContainer()) {
result = scene->launchEdgeMenu(mEdge, mMaster, eScenePos,
canBeConnected, &createElementFromMenuCommand);
} else {
if (!canBeConnected) {
result = -1;
}
}
}
NodeElement *target = dynamic_cast<NodeElement*>(scene->getLastCreated());
if (result == -1) {
mEdge = NULL;
} else if ((result == 1) && target) {
mEdge->setDst(target);
target->storeGeometry();
}
if (result != -1) {
mEdge->connectToPort();
updateMasterEdge();
// This will restore edge state after undo/redo
commands::ReshapeEdgeCommand *reshapeEdge = new commands::ReshapeEdgeCommand(mEdge);
reshapeEdge->startTracking();
reshapeEdge->stopTracking();
reshapeEdge->setUndoEnabled(false);
if (createElementFromMenuCommand) {
createElementFromMenuCommand->addPostAction(reshapeEdge);
mCreateEdgeCommand->addPostAction(createElementFromMenuCommand);
} else {
mCreateEdgeCommand->addPostAction(reshapeEdge);
}
}
}
mPressed = false;
mEdge = NULL;
}
<commit_msg>Improved check for connectivity.<commit_after>#include "../../edgeElement.h"
#include "../../nodeElement.h"
#include "embeddedLinker.h"
#include <math.h>
#include <QDebug>
#include <QStyle>
#include <QGraphicsItem>
#include <QStyleOptionGraphicsItem>
#include "../../../view/editorViewScene.h"
#include "../../../mainwindow/mainWindow.h"
#include "../../private/reshapeEdgeCommand.h"
using namespace qReal;
EmbeddedLinker::EmbeddedLinker()
: mEdge(NULL)
, mMaster(NULL)
, mColor(Qt::blue)
, mPressed(false)
, mTimeOfUpdate(0)
, mTimer(new QTimer(this))
{
mSize = SettingsManager::value("EmbeddedLinkerSize").toFloat();
if (mSize > 10) {
mSize *= 0.75;
}
mIndent = SettingsManager::value("EmbeddedLinkerIndent").toFloat();
mIndent *= 0.8;
if (mIndent > 17) {
mIndent *= 0.7;
}
mRectangle = QRectF(-mSize, -mSize, mSize * 2, mSize * 2);
mInnerRectangle = QRectF(-mSize / 2, -mSize / 2, mSize, mSize);
setZValue(300);
setFlag(ItemStacksBehindParent, false);
setAcceptHoverEvents(true);
connect(mTimer, SIGNAL(timeout()), this, SLOT(updateMasterEdge()));
}
EmbeddedLinker::~EmbeddedLinker()
{
}
NodeElement* EmbeddedLinker::getMaster()
{
return mMaster;
}
void EmbeddedLinker::setMaster(NodeElement *element)
{
mMaster = element;
setParentItem(element);
}
void EmbeddedLinker::generateColor()
{
int result = 0;
mColor = QColor(result % 192 + 64, result % 128 + 128, result % 64 + 192).darker(0);
}
void EmbeddedLinker::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget*)
{
Q_UNUSED(option);
painter->save();
QBrush brush;
brush.setColor(mColor);
brush.setStyle(Qt::SolidPattern);
painter->setBrush(brush);
painter->setOpacity(0.75);
painter->setPen(mColor);
mSize = SettingsManager::value("EmbeddedLinkerSize").toFloat();
if (mSize > 10) {
mSize *= 0.75;
}
mRectangle = QRectF(-mSize, -mSize, mSize * 2, mSize * 2);
mInnerRectangle = QRectF(-mSize / 2, -mSize / 2, mSize, mSize);
painter->drawEllipse(mRectangle);
painter->setOpacity(0.9);
painter->drawEllipse(mInnerRectangle);
painter->restore();
}
void EmbeddedLinker::setDirected(const bool directed)
{
this->mDirected = directed;
}
void EmbeddedLinker::initTitle()
{
EditorManagerInterface const &editorManagerInterface
= dynamic_cast<EditorViewScene*>(scene())->mainWindow()->editorManager();
QString edgeTypeFriendly = editorManagerInterface.friendlyName(Id::loadFromString("qrm:/"+ mMaster->id().editor()
+ "/" + mMaster->id().diagram() + "/" + mEdgeType.element()));
float textWidth = edgeTypeFriendly.size()*10;
float rectWidth = mMaster->boundingRect().right() - mMaster->boundingRect().left();
float rectHeight = mMaster->boundingRect().bottom() - mMaster->boundingRect().top();
int x = 0;
int y = 0;
if (scenePos().y() < mMaster->scenePos().y() + rectHeight/3)
y = -boundingRect().height() - 10;
else if (scenePos().y() > mMaster->scenePos().y() + 2*rectHeight/3)
y = +boundingRect().height() - 10;
if (scenePos().x() < mMaster->scenePos().x() + rectWidth/3)
x = -boundingRect().width() - textWidth + 20;
else if (scenePos().x() > mMaster->scenePos().x() + 2*rectWidth/3)
x = +boundingRect().width() - 10;
mTitle = new Label(static_cast<qreal>(x) / boundingRect().width()
, static_cast<qreal>(y) / boundingRect().height(), edgeTypeFriendly, 0);
mTitle->init(boundingRect());
mTitle->setTextWidth(textWidth);
mTitle->setParentItem(this);
}
void EmbeddedLinker::setEdgeType(const qReal::Id &edgeType)
{
this->mEdgeType = edgeType;
generateColor();
}
qReal::Id EmbeddedLinker::getEdgeType()
{
return mEdgeType;
}
bool EmbeddedLinker::isDirected()
{
return mDirected;
}
void EmbeddedLinker::takePosition(int index, int maxIndex)
{
qreal const pi = 3.141592;
QRectF const bounding = mMaster->boundingRect();
qreal const top = bounding.topLeft().y();
qreal const left = bounding.topLeft().x();
qreal const right = bounding.bottomRight().x();
qreal const bottom = bounding.bottomRight().y();
qreal const height = bottom - top;
qreal const width = right - left;
qreal const angle = 2 * pi * index / maxIndex;
int rW = width;
int rH = height;
if (rW < 150) {
rW *= 1.5;
} else {
rW += 5;
}
if (rH < 150) {
rH *= 1.5;
} else {
rH += 5;
}
// TODO: customize start angle
qreal const px = left + width / 2 + rW * cos(angle) / 2;
qreal const py = bottom - height / 2 + rH * sin(angle) / 2;
// if linker covers master node:
qreal min = py - top;
if (min > bottom - py) {
min = bottom - py;
}
if (min > px - left) {
min = px - left;
}
if (min > right - px) {
min = right - px;
}
qreal fx;
qreal fy;
mIndent = SettingsManager::value("EmbeddedLinkerIndent").toFloat();
mIndent *= 0.8;
if (mIndent > 17) {
mIndent *= 0.7;
}
//obviously, top != left != right != bottom
if ((bottom - py == min) || (py - top == min)) {
fx = px;
fy = bottom - py == min ? bottom + mIndent : top - mIndent;
} else {
fx = right - px == min ? right + mIndent : left - mIndent;
fy = py;
}
setPos(fx, fy);
}
QRectF EmbeddedLinker::boundingRect() const {
return mRectangle;
}
void EmbeddedLinker::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
Q_UNUSED(event)
mPressed = true;
if (event->button() == Qt::LeftButton) {
mEdge = NULL;
}
}
void EmbeddedLinker::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
mTimer->start(400);
if (mPressed) {
mPressed = false;
EditorViewScene *scene = dynamic_cast<EditorViewScene*>(mMaster->scene());
if (!scene) {
return;
}
QString const type = "qrm:/" + mMaster->id().editor() + "/" +
mMaster->id().diagram() + "/" + mEdgeType.element();
if (scene->mainWindow()->editorManager().hasElement(Id::loadFromString(type))) {
mMaster->setConnectingState(true);
// FIXME: I am raw. return strange pos() and inside me a small trash
Id edgeId = scene->createElement(type, event->scenePos(), true, &mCreateEdgeCommand);
mEdge = dynamic_cast<EdgeElement*>(scene->getElem(edgeId));
}
if (mEdge) {
mMaster->setZValue(1);
mEdge->setSrc(mMaster);
mEdge->setDst(NULL);
mEdge->highlight();
mEdge->tuneForLinker();
mEdge->placeEndTo(mEdge->mapFromScene(mapToScene(event->pos())));
mMaster->arrangeLinks();
mMaster->adjustLinks();
}
}
if (mEdge) {
if (mTimeOfUpdate == 14) {
mTimeOfUpdate = 0;
mEdge->adjustNeighborLinks();
mEdge->arrangeSrcAndDst();
} else {
mTimeOfUpdate++;
}
mEdge->placeEndTo(mEdge->mapFromScene(mapToScene(event->pos())));
}
}
void EmbeddedLinker::updateMasterEdge()
{
mTimer->stop();
mTimeOfUpdate = 0;
if (mEdge) {
mEdge->arrangeSrcAndDst();
mEdge->adjustNeighborLinks();
}
}
void EmbeddedLinker::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
hide();
mMaster->selectionState(false);
EditorViewScene* scene = dynamic_cast<EditorViewScene*>(mMaster->scene());
if (!mPressed && scene && mEdge) {
mEdge->hide();
QPointF const &eScenePos = event->scenePos();
NodeElement *under = dynamic_cast<NodeElement*>(scene->itemAt(eScenePos, QTransform()));
mEdge->show();
int result = 0;
commands::CreateElementCommand *createElementFromMenuCommand = NULL;
if (!under) {
result = scene->launchEdgeMenu(mEdge, mMaster, eScenePos, false, &createElementFromMenuCommand);
} else {
bool canBeConnected = false;
foreach(PossibleEdge const &pEdge, mEdge->src()->getPossibleEdges()) {
if (pEdge.first.second.element() == under->id().element()) {
canBeConnected = true;
} else {
// pEdge.second.first is true, if edge can connect items in only one direction.
if (!pEdge.second.first) {
canBeConnected = (pEdge.first.first.element() == under->id().element());
}
}
}
if (under->isContainer()) {
result = scene->launchEdgeMenu(mEdge, mMaster, eScenePos,
canBeConnected, &createElementFromMenuCommand);
} else {
if (!canBeConnected) {
result = -1;
}
}
}
NodeElement *target = dynamic_cast<NodeElement*>(scene->getLastCreated());
if (result == -1) {
mEdge = NULL;
} else if ((result == 1) && target) {
mEdge->setDst(target);
target->storeGeometry();
}
if (result != -1) {
mEdge->connectToPort();
updateMasterEdge();
// This will restore edge state after undo/redo
commands::ReshapeEdgeCommand *reshapeEdge = new commands::ReshapeEdgeCommand(mEdge);
reshapeEdge->startTracking();
reshapeEdge->stopTracking();
reshapeEdge->setUndoEnabled(false);
if (createElementFromMenuCommand) {
createElementFromMenuCommand->addPostAction(reshapeEdge);
mCreateEdgeCommand->addPostAction(createElementFromMenuCommand);
} else {
mCreateEdgeCommand->addPostAction(reshapeEdge);
}
}
}
mPressed = false;
mEdge = NULL;
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2011, 2012 Esrille 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.
*/
// A test harness for the implementation report of
// the CSS2.1 Conformance Test Suite
// http://test.csswg.org/suites/css2.1/20110323/
#include <unistd.h>
#include <sys/wait.h>
#include <cstring>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <boost/version.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
enum {
INTERACTIVE,
HEADLESS,
REPORT,
UPDATE
};
int processOutput(std::istream& stream, std::string& result)
{
std::string output;
bool completed = false;
while (std::getline(stream, output)) {
if (!completed) {
if (output == "## complete")
completed = true;
continue;
}
if (output == "##")
break;
result += output + '\n';
}
return 0;
}
int runTest(int argc, char* argv[], std::string userStyle, std::string testFonts, std::string url, std::string& result, unsigned timeout)
{
int pipefd[2];
pipe(pipefd);
pid_t pid = fork();
if (pid == -1) {
std::cerr << "error: no more process to create\n";
return -1;
}
if (pid == 0) {
close(1);
dup(pipefd[1]);
close(pipefd[0]);
int argi = argc - 1;
if (!userStyle.empty())
argv[argi++] = strdup(userStyle.c_str());
if (testFonts == "on")
argv[argi++] ="-testfonts";
url = "http://localhost:8000/" + url;
// url = "http://test.csswg.org/suites/css2.1/20110323/" + url;
argv[argi++] = strdup(url.c_str());
argv[argi] = 0;
if (timeout)
alarm(timeout); // Terminate the process if it does not complete in 'timeout' seconds.
execvp(argv[0], argv);
exit(EXIT_FAILURE);
}
close(pipefd[1]);
#if 104400 <= BOOST_VERSION
boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(pipefd[0], boost::iostreams::close_handle);
#else
boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(pipefd[0], true);
#endif
processOutput(stream, result);
return pid;
}
void killTest(int pid)
{
int status;
kill(pid, SIGTERM);
if (wait(&status) == -1)
std::cerr << "error: failed to wait for a test process to complete\n";
}
bool loadLog(const std::string& path, std::string& result, std::string& log)
{
std::ifstream file(path.c_str());
if (!file) {
result = "?";
return false;
}
std::string line;
std::getline(file, line);
size_t pos = line.find('\t');
if (pos != std::string::npos)
result = line.substr(pos + 1);
else {
result = "?";
return false;
}
log.clear();
while (std::getline(file, line))
log += line + '\n';
return true;
}
bool saveLog(const std::string& path, const std::string& url, const std::string& result, const std::string& log)
{
std::ofstream file(path.c_str(), std::ios_base::out | std::ios_base::trunc);
if (!file) {
std::cerr << "error: failed to open the report file\n";
return false;
}
file << "# " << url.c_str() << '\t' << result << '\n' << log;
file.flush();
file.close();
return true;
}
int main(int argc, char* argv[])
{
int mode = HEADLESS;
unsigned timeout = 10;
int argi = 1;
while (*argv[argi] == '-') {
switch (argv[argi][1]) {
case 'i':
mode = INTERACTIVE;
timeout = 0;
break;
case 'r':
mode = REPORT;
break;
case 'u':
mode = UPDATE;
break;
default:
break;
}
++argi;
}
if (argc < argi + 2) {
std::cout << "usage: " << argv[0] << " [-i] report.data command [argument ...]\n";
return EXIT_FAILURE;
}
std::ifstream data(argv[argi]);
if (!data) {
std::cerr << "error: " << argv[argi] << ": no such file\n";
return EXIT_FAILURE;
}
std::ofstream report("report.data", std::ios_base::out | std::ios_base::trunc);
if (!report) {
std::cerr << "error: failed to open the report file\n";
return EXIT_FAILURE;
}
char* args[argc - argi + 3];
for (int i = 2; i < argc; ++i)
args[i - 2] = argv[i + argi - 1];
args[argc - argi] = args[argc - argi + 1] = args[argc - argi + 2] = 0;
std::string result;
std::string url;
std::string undo;
std::string userStyle;
std::string testFonts;
bool redo = false;
while (data) {
if (result == "undo") {
std::swap(url, undo);
redo = true;
} else if (redo) {
std::swap(url, undo);
redo = false;
} else {
std::string line;
std::getline(data, line);
if (line.empty() || line == "testname result comment") {
report << line << '\n';
continue;
}
if (line[0] == '#') {
if (line.compare(1, 9, "userstyle") == 0) {
if (10 < line.length()) {
std::stringstream s(line.substr(10), std::stringstream::in);
s >> userStyle;
} else
userStyle.clear();
} else if (line.compare(1, 9, "testfonts") == 0) {
if (10 < line.length()) {
std::stringstream s(line.substr(10), std::stringstream::in);
s >> testFonts;
} else
testFonts.clear();
}
report << line << '\n';
continue;
}
undo = url;
std::stringstream s(line, std::stringstream::in);
s >> url;
}
if (url.empty())
continue;
std::string path(url);
size_t pos = path.rfind('.');
if (pos != std::string::npos) {
path.erase(pos);
path += ".log";
}
std::string evaluation;
std::string log;
loadLog(path, evaluation, log);
pid_t pid = -1;
std::string output;
switch (mode) {
case REPORT:
break;
case UPDATE:
if (evaluation[0] == '?')
break;
// FALL THROUGH
default:
pid = runTest(argc - argi, args, userStyle, testFonts, url, output, timeout);
break;
}
if (0 < pid && output.empty())
result = "fatal";
else if (mode == INTERACTIVE) {
std::cout << "## complete\n" << output;
std::cout << '[' << url << "] ";
if (evaluation.empty() || evaluation[0] == '?')
std::cout << "pass? ";
else {
std::cout << evaluation << "? ";
if (evaluation != "pass")
std::cout << '\a';
}
std::getline(std::cin, result);
if (result.empty()) {
if (evaluation.empty() || evaluation[0] == '?')
result = "pass";
else
result = evaluation;
} else if (result == "p" || result == "\x1b")
result = "pass";
else if (result == "f")
result = "fail";
else if (result == "i")
result = "invalid";
else if (result == "k") // keep
result = evaluation;
else if (result == "n")
result = "na";
else if (result == "s")
result = "skip";
else if (result == "u")
result = "uncertain";
else if (result == "q" || result == "quit")
break;
else if (result == "z")
result = "undo";
if (result != "undo" && !saveLog(path, url, result, output)) {
std::cerr << "error: failed to open the report file\n";
return EXIT_FAILURE;
}
} else if (mode == HEADLESS) {
if (evaluation != "?" && output != log)
result = "uncertain";
else
result = evaluation;
} else if (mode == REPORT) {
result = evaluation;
} else if (mode == UPDATE) {
result = evaluation;
if (result[0] != '?') {
if (!saveLog(path, url, result, output)) {
std::cerr << "error: failed to open the report file\n";
return EXIT_FAILURE;
}
}
}
if (0 < pid)
killTest(pid);
if (result != "undo")
report << url << '\t' << result << '\n';
if (mode != INTERACTIVE && result[0] != '?')
std::cout << url << '\t' << result << '\n';
}
report.close();
}
<commit_msg>(harness) : Support the -j[jobs] option to run simultaneously.<commit_after>/*
* Copyright 2011, 2012 Esrille 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.
*/
// A test harness for the implementation report of
// the CSS2.1 Conformance Test Suite
// http://test.csswg.org/suites/css2.1/20110323/
#include <unistd.h>
#include <sys/wait.h>
#include <cstring>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <boost/version.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
enum {
INTERACTIVE,
HEADLESS,
REPORT,
UPDATE
};
int forkMax = 1;
int forkCount = 0;
int processOutput(std::istream& stream, std::string& result)
{
std::string output;
bool completed = false;
while (std::getline(stream, output)) {
if (!completed) {
if (output == "## complete")
completed = true;
continue;
}
if (output == "##")
break;
result += output + '\n';
}
return 0;
}
int runTest(int argc, char* argv[], std::string userStyle, std::string testFonts, std::string url, std::string& result, unsigned timeout)
{
int pipefd[2];
pipe(pipefd);
pid_t pid = fork();
if (pid == -1) {
std::cerr << "error: no more process to create\n";
return -1;
}
if (pid == 0) {
close(1);
dup(pipefd[1]);
close(pipefd[0]);
int argi = argc - 1;
if (!userStyle.empty())
argv[argi++] = strdup(userStyle.c_str());
if (testFonts == "on")
argv[argi++] ="-testfonts";
url = "http://localhost:8000/" + url;
// url = "http://test.csswg.org/suites/css2.1/20110323/" + url;
argv[argi++] = strdup(url.c_str());
argv[argi] = 0;
if (timeout)
alarm(timeout); // Terminate the process if it does not complete in 'timeout' seconds.
execvp(argv[0], argv);
exit(EXIT_FAILURE);
}
close(pipefd[1]);
#if 104400 <= BOOST_VERSION
boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(pipefd[0], boost::iostreams::close_handle);
#else
boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(pipefd[0], true);
#endif
processOutput(stream, result);
return pid;
}
void killTest(int pid)
{
int status;
kill(pid, SIGTERM);
if (wait(&status) == -1)
std::cerr << "error: failed to wait for a test process to complete\n";
}
bool loadLog(const std::string& path, std::string& result, std::string& log)
{
std::ifstream file(path.c_str());
if (!file) {
result = "?";
return false;
}
std::string line;
std::getline(file, line);
size_t pos = line.find('\t');
if (pos != std::string::npos)
result = line.substr(pos + 1);
else {
result = "?";
return false;
}
log.clear();
while (std::getline(file, line))
log += line + '\n';
return true;
}
bool saveLog(const std::string& path, const std::string& url, const std::string& result, const std::string& log)
{
std::ofstream file(path.c_str(), std::ios_base::out | std::ios_base::trunc);
if (!file) {
std::cerr << "error: failed to open the report file\n";
return false;
}
file << "# " << url.c_str() << '\t' << result << '\n' << log;
file.flush();
file.close();
return true;
}
std::string test(int mode, int argc, char* argv[], const std::string& url, const std::string& userStyle, const std::string& testFonts, unsigned timeout)
{
std::string path(url);
size_t pos = path.rfind('.');
if (pos != std::string::npos) {
path.erase(pos);
path += ".log";
}
std::string evaluation;
std::string log;
loadLog(path, evaluation, log);
pid_t pid = -1;
std::string output;
switch (mode) {
case REPORT:
break;
case UPDATE:
if (evaluation[0] == '?')
break;
// FALL THROUGH
default:
pid = runTest(argc, argv, userStyle, testFonts, url, output, timeout);
break;
}
std::string result;
if (0 < pid && output.empty())
result = "fatal";
else if (mode == INTERACTIVE) {
std::cout << "## complete\n" << output;
std::cout << '[' << url << "] ";
if (evaluation.empty() || evaluation[0] == '?')
std::cout << "pass? ";
else {
std::cout << evaluation << "? ";
if (evaluation != "pass")
std::cout << '\a';
}
std::getline(std::cin, result);
if (result.empty()) {
if (evaluation.empty() || evaluation[0] == '?')
result = "pass";
else
result = evaluation;
} else if (result == "p" || result == "\x1b")
result = "pass";
else if (result == "f")
result = "fail";
else if (result == "i")
result = "invalid";
else if (result == "k") // keep
result = evaluation;
else if (result == "n")
result = "na";
else if (result == "s")
result = "skip";
else if (result == "u")
result = "uncertain";
else if (result == "q" || result == "quit")
exit(EXIT_FAILURE);
else if (result == "z")
result = "undo";
if (result != "undo" && !saveLog(path, url, result, output)) {
std::cerr << "error: failed to open the report file\n";
exit(EXIT_FAILURE);
}
} else if (mode == HEADLESS) {
if (evaluation != "?" && output != log)
result = "uncertain";
else
result = evaluation;
} else if (mode == REPORT) {
result = evaluation;
} else if (mode == UPDATE) {
result = evaluation;
if (result[0] != '?') {
if (!saveLog(path, url, result, output)) {
std::cerr << "error: failed to open the report file\n";
exit(EXIT_FAILURE);
}
}
}
if (0 < pid)
killTest(pid);
if (mode != INTERACTIVE && result[0] != '?')
std::cout << url << '\t' << result << '\n';
return result;
}
std::string map(int mode, int argc, char* argv[], const std::string& url, const std::string& userStyle, const std::string& testFonts, unsigned timeout)
{
pid_t pid = fork();
if (pid == -1) {
std::cerr << "error: no more process to create\n";
exit(EXIT_FAILURE);
}
if (pid == 0) {
std::string path(url);
size_t pos = path.rfind('.');
if (pos != std::string::npos) {
path.erase(pos);
path += ".log";
}
std::string evaluation;
std::string log;
loadLog(path, evaluation, log);
pid_t pid = -1;
std::string output;
switch (mode) {
case UPDATE:
if (evaluation[0] == '?')
break;
// FALL THROUGH
default:
pid = runTest(argc, argv, userStyle, testFonts, url, output, timeout);
break;
}
std::string result;
if (0 < pid && output.empty())
result = "fatal";
else if (mode == HEADLESS) {
if (evaluation != "?" && output != log)
result = "uncertain";
else
result = evaluation;
} else if (mode == UPDATE) {
result = evaluation;
if (result[0] != '?') {
if (!saveLog(path, url, result, output)) {
std::cerr << "error: failed to open the report file\n";
exit(EXIT_FAILURE);
}
}
}
if (0 < pid)
killTest(pid);
if (result[0] != '?')
std::cout << url << '\t' << result << '\n';
exit(EXIT_SUCCESS);
}
if (++forkCount == forkMax) {
for (int j = 0; j < forkCount; ++j) {
int status;
wait(&status);
}
forkCount = 0;
}
return "na";
}
int main(int argc, char* argv[])
{
int mode = HEADLESS;
unsigned timeout = 10;
int argi = 1;
while (*argv[argi] == '-') {
switch (argv[argi][1]) {
case 'i':
mode = INTERACTIVE;
timeout = 0;
break;
case 'r':
mode = REPORT;
break;
case 'u':
mode = UPDATE;
break;
case 'j':
forkMax = strtoul(argv[argi] + 2, 0, 10);
break;
default:
break;
}
++argi;
}
if (argc < argi + 2) {
std::cout << "usage: " << argv[0] << " [-i] report.data command [argument ...]\n";
return EXIT_FAILURE;
}
std::ifstream data(argv[argi]);
if (!data) {
std::cerr << "error: " << argv[argi] << ": no such file\n";
return EXIT_FAILURE;
}
std::ofstream report("report.data", std::ios_base::out | std::ios_base::trunc);
if (!report) {
std::cerr << "error: failed to open the report file\n";
return EXIT_FAILURE;
}
char* args[argc - argi + 3];
for (int i = 2; i < argc; ++i)
args[i - 2] = argv[i + argi - 1];
args[argc - argi] = args[argc - argi + 1] = args[argc - argi + 2] = 0;
std::string result;
std::string url;
std::string undo;
std::string userStyle;
std::string testFonts;
bool redo = false;
for (;;) {
while (data) {
if (result == "undo") {
std::swap(url, undo);
redo = true;
} else if (redo) {
std::swap(url, undo);
redo = false;
} else {
std::string line;
std::getline(data, line);
if (line.empty() || line == "testname result comment") {
report << line << '\n';
continue;
}
if (line[0] == '#') {
if (line.compare(1, 9, "userstyle") == 0) {
if (10 < line.length()) {
std::stringstream s(line.substr(10), std::stringstream::in);
s >> userStyle;
} else
userStyle.clear();
} else if (line.compare(1, 9, "testfonts") == 0) {
if (10 < line.length()) {
std::stringstream s(line.substr(10), std::stringstream::in);
s >> testFonts;
} else
testFonts.clear();
}
report << line << '\n';
continue;
}
undo = url;
std::stringstream s(line, std::stringstream::in);
s >> url;
}
if (url.empty())
continue;
switch (mode) {
case HEADLESS:
case UPDATE:
result = map(mode, argc - argi, args, url, userStyle, testFonts, timeout);
break;
default:
result = test(mode, argc - argi, args, url, userStyle, testFonts, timeout);
if (result != "undo")
report << url << '\t' << result << '\n';
break;
}
}
if (mode == HEADLESS || mode == UPDATE) {
for (int j = 0; j < forkCount; ++j) {
int status;
wait(&status);
}
mode = REPORT;
data.clear();
data.seekg(0);
} else
break;
}
report.close();
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <gtest/gtest.h>
#include "../pipeline.h"
#include "../channel.h"
class PipelineTest : testing::Test { };
TEST(PipelineTest, Test_fibonacci_n4134)
{
/*
// n4134: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4134.pdf
generator<int> fib(int n)
{
int a = 0;
int b = 1;
while (n-- > 0)
{
yield a;
auto next = a + b;
a = b;
b = next;
}
}
*/
auto fib = [](int n_) {
return cu::pull_type<int>(
[&](cu::push_type<int>& yield) {
int n = n_;
int a = 0;
int b = 1;
while (n-- > 0)
{
yield (a);
auto next = a + b;
a = b;
b = next;
}
}
);
};
for (auto& v : fib(233))
{
std::cout << v << std::endl;
if (v > 10)
break;
}
}
TEST(PipelineTest, Test_recursive_n4134)
{
std::function<cu::pull_type<int>(int,int)> range = [&range](int a_, int b_) -> cu::pull_type<int> {
return cu::pull_type<int>(
[&](cu::push_type<int>& yield) {
int a = a_;
int b = b_;
/////////////////////
auto n = b - a;
if (n <= 0)
return;
if (n == 1)
{
yield (a);
return;
}
auto mid = a + n / 2;
// original proposal is:
// yield range(a, mid)
// yield range(mid, b)
for (auto i : range(a, mid))
yield (i);
for (auto i : range(mid, b))
yield (i);
///////////////////////
}
);
};
for (auto v : range(1, 10))
std::cout << v << std::endl;
}
TEST(PipelineTest, Test3)
{
auto fib = [](int n) {
return cu::push_type<int>(
[&](cu::pull_type<int>& source) {
for (auto& s : source)
{
std::cout << "<fib(" << n << ")> received: " << s << std::endl;
}
}
);
};
auto fib20 = fib(20);
fib20(1);
fib20(3);
fib20(7);
}
<commit_msg>Update test_coroutine.cpp<commit_after>#include <iostream>
#include <gtest/gtest.h>
#include <teelogging/teelogging.h>
#include "../pipeline.h"
#include "../channel.h"
class PipelineTest : testing::Test { };
TEST(PipelineTest, Test_fibonacci_n4134)
{
/*
// n4134: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4134.pdf
generator<int> fib(int n)
{
int a = 0;
int b = 1;
while (n-- > 0)
{
yield a;
auto next = a + b;
a = b;
b = next;
}
}
*/
auto fib = [](int n_) {
return cu::pull_type<int>(
[&](cu::push_type<int>& yield) {
int n = n_;
int a = 0;
int b = 1;
while (n-- > 0)
{
yield (a);
auto next = a + b;
a = b;
b = next;
}
}
);
};
for (auto& v : fib(233))
{
std::cout << v << std::endl;
if (v > 10)
break;
}
}
TEST(PipelineTest, Test_recursive_n4134)
{
std::function<cu::pull_type<int>(int,int)> range = [&range](int a_, int b_) -> cu::pull_type<int> {
return cu::pull_type<int>(
[&](cu::push_type<int>& yield) {
int a = a_;
int b = b_;
/////////////////////
auto n = b - a;
if (n <= 0)
return;
if (n == 1)
{
yield (a);
return;
}
auto mid = a + n / 2;
// original proposal is:
// yield range(a, mid)
// yield range(mid, b)
for (auto i : range(a, mid))
yield (i);
for (auto i : range(mid, b))
yield (i);
///////////////////////
}
);
};
for (auto v : range(1, 10))
LOGI("%d", v);
}
TEST(PipelineTest, Test3)
{
auto fib = [](int n) {
return cu::push_type<int>(
[&](cu::pull_type<int>& source) {
for (auto& s : source)
{
LOGI("<fib(%d)> received: %s", n, s);
}
}
);
};
auto fib20 = fib(20);
fib20(1);
fib20(3);
fib20(7);
}
<|endoftext|>
|
<commit_before>#include <nanyc/library.h>
#include <nanyc/program.h>
#include <yuni/yuni.h>
#include <yuni/core/getopt.h>
#include <yuni/core/string.h>
#include <yuni/io/filename-manipulation.h>
#include <yuni/datetime/timestamp.h>
#include <yuni/core/system/console/console.h>
#include <yuni/core/process/program.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <memory>
#include <random>
#include "libnanyc.h"
namespace ny {
namespace unittests {
namespace {
struct Entry final {
yuni::String module;
yuni::String name;
};
struct Result final {
Entry entry;
bool success;
int64_t duration_ms;
};
struct App final {
App();
App(App&&) = default;
~App();
void importFilenames(const std::vector<AnyString>&);
void fetch(bool nsl);
void run(const Entry&);
int run();
void statstics(int64_t duration) const;
void setcolor(yuni::System::Console::Color) const;
void resetcolor() const;
bool inExecutorMode() const;
struct final {
uint32_t total = 0;
uint32_t passing = 0;
uint32_t failed = 0;
}
stats;
nycompile_opts_t opts;
bool interactive = true;
bool colors = true;
uint32_t loops = 1;
bool shuffle = false;
std::vector<Entry> unittests;
std::vector<yuni::String> filenames;
std::vector<Result> results;
Entry execinfo;
AnyString argv0;
private:
void startEntry(const Entry&);
void endEntry(const Entry&, bool, int64_t);
bool execute(const Entry& entry);
};
App::App() {
memset(&opts, 0x0, sizeof(opts));
opts.userdata = this;;
}
App::~App() {
free(opts.sources.items);
}
void App::setcolor(yuni::System::Console::Color c) const {
if (colors)
yuni::System::Console::SetTextColor(std::cout, c);
}
void App::resetcolor() const {
if (colors)
yuni::System::Console::ResetTextColor(std::cout);
}
bool App::inExecutorMode() const {
return not execinfo.name.empty();
}
auto now() {
return yuni::DateTime::NowMilliSeconds();
}
bool operator < (const Entry& a, const Entry& b) {
return std::tie(a.module, a.name) < std::tie(b.module, b.name);
}
const char* plurals(auto count, const char* single, const char* many) {
return (count <= 1) ? single : many;
}
void App::importFilenames(const std::vector<AnyString>& list) {
uint32_t count = static_cast<uint32_t>(list.size());
filenames.resize(count);
std::transform(std::begin(list), std::end(list), std::begin(filenames), [](auto& item) -> yuni::String {
return std::move(yuni::IO::Canonicalize(item));
});
opts.sources.count = count;
opts.sources.items = (nysource_opts_t*) calloc(count, sizeof(nysource_opts_t));
if (unlikely(!opts.sources.items))
throw std::bad_alloc();
for (uint32_t i = 0; i != count; ++i) {
opts.sources.items[i].filename.len = filenames[i].size();
opts.sources.items[i].filename.c_str = filenames[i].c_str();
}
}
void App::fetch(bool nsl) {
unittests.reserve(512); // arbitrary
opts.with_nsl_unittests = nsl ? nytrue : nyfalse;
opts.on_unittest = [](void* userdata, const char* mod, uint32_t mlen, const char* name, uint32_t nlen) {
auto& self = *reinterpret_cast<App*>(userdata);
self.unittests.emplace_back();
auto& entry = self.unittests.back();
entry.module.assign(mod, mlen);
entry.name.assign(name, nlen);
};
std::cout << "searching for unittests in all source files...\n";
auto start = now();
nyprogram_compile(&opts);
opts.on_unittest = nullptr;
std::sort(std::begin(unittests), std::end(unittests));
auto duration = now() - start;
std::cout << unittests.size() << ' ' << plurals(unittests.size(), "test", "tests");
std::cout << " found (in " << duration << "ms)\n";
}
void App::startEntry(const Entry& entry) {
if (interactive) {
setcolor(yuni::System::Console::bold);
std::cout << "\r running ";
resetcolor();
std::cout << entry.module << '/' << entry.name;
std::cout << "... " << std::flush;
}
}
void App::endEntry(const Entry& entry, bool success, int64_t duration) {
++stats.total;
++(success ? stats.passing : stats.failed);
Result result;
result.entry = entry;
result.success = success;
result.duration_ms = duration;
results.emplace_back(std::move(result));
}
void App::statstics(int64_t duration) const {
if (interactive)
std::cout << '\r';
for (auto& result: results) {
if (result.success) {
setcolor(yuni::System::Console::green);
#ifndef YUNI_OS_WINDOWS
std::cout << " \u2713 ";
#else
std::cout << " OK ";
#endif
resetcolor();
}
else {
setcolor(yuni::System::Console::red);
std::cout << " ERR ";
resetcolor();
}
std::cout << result.entry.module << '/' << result.entry.name;
setcolor(yuni::System::Console::lightblue);
std::cout << " (" << result.duration_ms << "ms)";
resetcolor();
std::cout << '\n';
}
std::cout << "\n " << stats.total << ' ' << plurals(stats.total, "test", "tests");
if (stats.passing != 0) {
std::cout << ", ";
setcolor(yuni::System::Console::red);
std::cout << stats.passing << " passing";
resetcolor();
}
if (stats.failed) {
std::cout << ", ";
setcolor(yuni::System::Console::red);
std::cout << stats.failed << " failed";
resetcolor();
}
std::cout << " (";
if (duration < 10000)
std::cout << duration << "ms)";
else
std::cout << (duration / 1000) << "s)";
std::cout << "\n\n";
}
bool App::execute(const Entry& entry) {
auto* program = nyprogram_compile(&opts);
bool success = program != nullptr;
if (program) {
nyprogram_free(program);
}
return success;
}
void App::run(const Entry& entry) {
startEntry(entry);
yuni::Process::Program program;
program.durationPrecision(yuni::Process::Program::dpMilliseconds);
program.program(argv0);
program.argumentAdd("--executor-module");
program.argumentAdd(entry.module);
program.argumentAdd("--executor-name");
program.argumentAdd(entry.name);
for (auto& filename: filenames)
program.argumentAdd(filename);
auto start = now();
bool success = program.execute();
success = success and (program.wait() == 0);
auto duration = now() - start;
endEntry(entry, success, duration);
}
void shuffleDeck(std::vector<Entry>& unittests) {
std::cout << "shuffling the tests...\n" << std::flush;
auto seed = now();
auto useed = static_cast<uint32_t>(seed);
std::shuffle(unittests.begin(), unittests.end(), std::default_random_engine(useed));
}
int App::run() {
bool success;
if (not inExecutorMode()) {
results.reserve(loops * unittests.size());
std::cout << '\n';
auto start = now();
for (uint32_t l = 0; l != loops; ++l) {
if (unlikely(shuffle))
shuffleDeck(unittests);
for (auto& entry: unittests)
run(entry);
}
auto duration = now() - start;
statstics(duration);
success = stats.failed == 0 and stats.total != 0;
}
else {
success = execute(execinfo);
}
return success ? EXIT_SUCCESS : EXIT_FAILURE;
}
int printVersion() {
std::cout << libnanyc_version_to_cstr() << '\n';
return EXIT_SUCCESS;
}
int printBugreport() {
uint32_t length;
auto* text = libnanyc_get_bugreportdetails(&length);
if (text) {
std::cout.write(text, length);
free(text);
}
std::cout << '\n';
return EXIT_SUCCESS;
}
App prepare(int argc, char** argv) {
App app;
bool version = false;
bool bugreport = false;
bool nsl = false;
bool verbose = false;
bool nocolors = false;
std::vector<AnyString> filenames;
yuni::GetOpt::Parser options;
options.addFlag(filenames, 'i', "", "Input nanyc source files");
options.addFlag(nsl, ' ', "nsl", "Import NSL unittests");
options.add(app.execinfo.module, ' ', "executor-module", "Executor mode, module name (internal use)", false);
options.add(app.execinfo.name, ' ', "executor-name", "Executor mode, unittest (internal use)", false);
options.addParagraph("\nEntropy");
options.addFlag(app.loops, 'l', "loops", "Number of loops (default: 1)");
options.addFlag(app.shuffle, 's', "shuffle", "Randomly rearrange the unittests");
options.addParagraph("\nDisplay");
options.addFlag(nocolors, ' ', "no-colors", "Disable color output");
options.addParagraph("\nHelp");
options.addFlag(verbose, 'v', "verbose", "More stuff on the screen");
options.addFlag(bugreport, 'b', "bugreport", "Display some useful information to report a bug");
options.addFlag(version, ' ', "version", "Print the version");
options.remainingArguments(filenames);
if (not options(argc, argv)) {
if (options.errors())
throw std::runtime_error("Abort due to error");
throw EXIT_SUCCESS;
}
if (unlikely(version))
throw printVersion();
if (unlikely(bugreport))
throw printBugreport();
if (unlikely(verbose))
printBugreport();
app.importFilenames(filenames);
if (not app.inExecutorMode()) {
app.interactive = yuni::System::Console::IsStdoutTTY();
app.colors = (not nocolors) and app.interactive;
app.argv0 = argv[0];
app.fetch(nsl);
}
return app;
}
} // namespace
} // namespace unittests
} // namespace ny
int main(int argc, char** argv) {
try {
auto app = ny::unittests::prepare(argc, argv);
return app.run();
}
catch (const std::exception& e) {
std::cerr << "exception: " << e.what() << '\n';
}
catch (int e) {
return e;
}
return EXIT_FAILURE;;
}
<commit_msg>unittests: move the computation of statistics after executing all tests<commit_after>#include <nanyc/library.h>
#include <nanyc/program.h>
#include <yuni/yuni.h>
#include <yuni/core/getopt.h>
#include <yuni/core/string.h>
#include <yuni/io/filename-manipulation.h>
#include <yuni/datetime/timestamp.h>
#include <yuni/core/system/console/console.h>
#include <yuni/core/process/program.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <memory>
#include <random>
#include "libnanyc.h"
namespace ny {
namespace unittests {
namespace {
struct Entry final {
yuni::String module;
yuni::String name;
};
struct Result final {
Entry entry;
bool success;
int64_t duration_ms;
};
struct App final {
App();
App(App&&) = default;
~App();
void importFilenames(const std::vector<AnyString>&);
void fetch(bool nsl);
void run(const Entry&);
int run();
bool statstics(int64_t duration) const;
void setcolor(yuni::System::Console::Color) const;
void resetcolor() const;
bool inExecutorMode() const;
struct final {
uint32_t total = 0;
uint32_t passing = 0;
uint32_t failed = 0;
}
stats;
nycompile_opts_t opts;
bool interactive = true;
bool colors = true;
uint32_t loops = 1;
bool shuffle = false;
std::vector<Entry> unittests;
std::vector<yuni::String> filenames;
std::vector<Result> results;
Entry execinfo;
AnyString argv0;
private:
void startEntry(const Entry&);
void endEntry(const Entry&, bool, int64_t);
bool execute(const Entry& entry);
};
App::App() {
memset(&opts, 0x0, sizeof(opts));
opts.userdata = this;;
}
App::~App() {
free(opts.sources.items);
}
void App::setcolor(yuni::System::Console::Color c) const {
if (colors)
yuni::System::Console::SetTextColor(std::cout, c);
}
void App::resetcolor() const {
if (colors)
yuni::System::Console::ResetTextColor(std::cout);
}
bool App::inExecutorMode() const {
return not execinfo.name.empty();
}
auto now() {
return yuni::DateTime::NowMilliSeconds();
}
bool operator < (const Entry& a, const Entry& b) {
return std::tie(a.module, a.name) < std::tie(b.module, b.name);
}
const char* plurals(auto count, const char* single, const char* many) {
return (count <= 1) ? single : many;
}
void App::importFilenames(const std::vector<AnyString>& list) {
uint32_t count = static_cast<uint32_t>(list.size());
filenames.resize(count);
std::transform(std::begin(list), std::end(list), std::begin(filenames), [](auto& item) -> yuni::String {
return std::move(yuni::IO::Canonicalize(item));
});
opts.sources.count = count;
opts.sources.items = (nysource_opts_t*) calloc(count, sizeof(nysource_opts_t));
if (unlikely(!opts.sources.items))
throw std::bad_alloc();
for (uint32_t i = 0; i != count; ++i) {
opts.sources.items[i].filename.len = filenames[i].size();
opts.sources.items[i].filename.c_str = filenames[i].c_str();
}
}
void App::fetch(bool nsl) {
unittests.reserve(512); // arbitrary
opts.with_nsl_unittests = nsl ? nytrue : nyfalse;
opts.on_unittest = [](void* userdata, const char* mod, uint32_t mlen, const char* name, uint32_t nlen) {
auto& self = *reinterpret_cast<App*>(userdata);
self.unittests.emplace_back();
auto& entry = self.unittests.back();
entry.module.assign(mod, mlen);
entry.name.assign(name, nlen);
};
std::cout << "searching for unittests in all source files...\n";
auto start = now();
nyprogram_compile(&opts);
opts.on_unittest = nullptr;
std::sort(std::begin(unittests), std::end(unittests));
auto duration = now() - start;
std::cout << unittests.size() << ' ' << plurals(unittests.size(), "test", "tests");
std::cout << " found (in " << duration << "ms)\n";
}
void App::startEntry(const Entry& entry) {
if (interactive) {
setcolor(yuni::System::Console::bold);
std::cout << "\r running ";
resetcolor();
std::cout << entry.module << '/' << entry.name;
std::cout << "... " << std::flush;
}
}
void App::endEntry(const Entry& entry, bool success, int64_t duration) {
Result result;
result.entry = entry;
result.success = success;
result.duration_ms = duration;
results.emplace_back(std::move(result));
}
bool App::statstics(int64_t duration) const {
if (interactive)
std::cout << '\r';
for (auto& result: results) {
++(result.success ? stats.passing : stats.failed);
if (result.success) {
setcolor(yuni::System::Console::green);
#ifndef YUNI_OS_WINDOWS
std::cout << " \u2713 ";
#else
std::cout << " OK ";
#endif
resetcolor();
}
else {
setcolor(yuni::System::Console::red);
std::cout << " ERR ";
resetcolor();
}
std::cout << result.entry.module << '/' << result.entry.name;
setcolor(yuni::System::Console::lightblue);
std::cout << " (" << result.duration_ms << "ms)";
resetcolor();
std::cout << '\n';
}
std::cout << "\n " << stats.total << ' ' << plurals(stats.total, "test", "tests");
if (stats.passing != 0) {
std::cout << ", ";
setcolor(yuni::System::Console::red);
std::cout << stats.passing << " passing";
resetcolor();
}
if (stats.failed) {
std::cout << ", ";
setcolor(yuni::System::Console::red);
std::cout << stats.failed << " failed";
resetcolor();
}
std::cout << " (";
if (duration < 10000)
std::cout << duration << "ms)";
else
std::cout << (duration / 1000) << "s)";
std::cout << "\n\n";
return stats.failed == 0 and stats.total != 0;
}
bool App::execute(const Entry& entry) {
auto* program = nyprogram_compile(&opts);
bool success = program != nullptr;
if (program) {
nyprogram_free(program);
}
return success;
}
void App::run(const Entry& entry) {
startEntry(entry);
yuni::Process::Program program;
program.durationPrecision(yuni::Process::Program::dpMilliseconds);
program.program(argv0);
program.argumentAdd("--executor-module");
program.argumentAdd(entry.module);
program.argumentAdd("--executor-name");
program.argumentAdd(entry.name);
for (auto& filename: filenames)
program.argumentAdd(filename);
auto start = now();
bool success = program.execute();
success = success and (program.wait() == 0);
auto duration = now() - start;
endEntry(entry, success, duration);
}
void shuffleDeck(std::vector<Entry>& unittests) {
std::cout << "shuffling the tests...\n" << std::flush;
auto seed = now();
auto useed = static_cast<uint32_t>(seed);
std::shuffle(unittests.begin(), unittests.end(), std::default_random_engine(useed));
}
int App::run() {
bool success;
if (not inExecutorMode()) {
stats.total = static_cast<uint32_t>(loops * unittests.size());
results.reserve(stats.total);
std::cout << '\n';
auto start = now();
for (uint32_t l = 0; l != loops; ++l) {
if (unlikely(shuffle))
shuffleDeck(unittests);
for (auto& entry: unittests)
run(entry);
}
auto duration = now() - start;
success = statstics(duration);
}
else {
success = execute(execinfo);
}
return success ? EXIT_SUCCESS : EXIT_FAILURE;
}
int printVersion() {
std::cout << libnanyc_version_to_cstr() << '\n';
return EXIT_SUCCESS;
}
int printBugreport() {
uint32_t length;
auto* text = libnanyc_get_bugreportdetails(&length);
if (text) {
std::cout.write(text, length);
free(text);
}
std::cout << '\n';
return EXIT_SUCCESS;
}
App prepare(int argc, char** argv) {
App app;
bool version = false;
bool bugreport = false;
bool nsl = false;
bool verbose = false;
bool nocolors = false;
std::vector<AnyString> filenames;
yuni::GetOpt::Parser options;
options.addFlag(filenames, 'i', "", "Input nanyc source files");
options.addFlag(nsl, ' ', "nsl", "Import NSL unittests");
options.add(app.execinfo.module, ' ', "executor-module", "Executor mode, module name (internal use)", false);
options.add(app.execinfo.name, ' ', "executor-name", "Executor mode, unittest (internal use)", false);
options.addParagraph("\nEntropy");
options.addFlag(app.loops, 'l', "loops", "Number of loops (default: 1)");
options.addFlag(app.shuffle, 's', "shuffle", "Randomly rearrange the unittests");
options.addParagraph("\nDisplay");
options.addFlag(nocolors, ' ', "no-colors", "Disable color output");
options.addParagraph("\nHelp");
options.addFlag(verbose, 'v', "verbose", "More stuff on the screen");
options.addFlag(bugreport, 'b', "bugreport", "Display some useful information to report a bug");
options.addFlag(version, ' ', "version", "Print the version");
options.remainingArguments(filenames);
if (not options(argc, argv)) {
if (options.errors())
throw std::runtime_error("Abort due to error");
throw EXIT_SUCCESS;
}
if (unlikely(version))
throw printVersion();
if (unlikely(bugreport))
throw printBugreport();
if (unlikely(verbose))
printBugreport();
app.importFilenames(filenames);
if (not app.inExecutorMode()) {
app.interactive = yuni::System::Console::IsStdoutTTY();
app.colors = (not nocolors) and app.interactive;
app.argv0 = argv[0];
app.fetch(nsl);
}
return app;
}
} // namespace
} // namespace unittests
} // namespace ny
int main(int argc, char** argv) {
try {
auto app = ny::unittests::prepare(argc, argv);
return app.run();
}
catch (const std::exception& e) {
std::cerr << "exception: " << e.what() << '\n';
}
catch (int e) {
return e;
}
return EXIT_FAILURE;;
}
<|endoftext|>
|
<commit_before>#include <cstdio>
#include <vector>
#include <deque>
#include <string>
#include <sstream>
/* definitions */
const int stone_size = 8;
const int field_size = 32;
const int empty_val = -1; // 障害物やzkの無いことを表す
const int filled_val = 256; // 障害物を表す
FILE* dumpout = stdout; // dump系関数の出力先
struct Position {
/*座標を表現するクラス*/
int y, x;
bool operator==(const Position&obj) const {
return y == obj.y && x == obj.x;
}
bool operator<(const Position&obj) const {
if (y == obj.y) {
return x < obj.x;
}
return y < obj.y;
}
};
struct Stone {
/* 石 */
int raw[stone_size][stone_size]; // empty_val -> 空き, otherwise -> うまり
std::deque<Position> fills; // 埋まってる座標を持っておく
};
struct Field {
/* フィールド */
int raw[field_size][field_size];
std::deque<std::string> answer; // 答えとなる石の置き方を持っておく
};
int number_of_stones; // 与えられる石の数
Stone stones[256 * 8]; // 石を持っておくインスタンス(回転反転を考慮して8倍とってある)
Field initial_field; // 初期フィールド状態
std::deque<Position> initial_empties; // 初期フィールドで空いている場所を探す
int rotated(int n, int deg) {
/* n番の石をdeg度まわした石の番号を返す */
return n + number_of_stones * (deg/90);
}
int fliped(int n) {
/* n番の石を反転した時の石の番号を返す */
return n + number_of_stones * 4;
}
int all_stones_num() {
/* 全部で石が何個になるか */
return 8*number_of_stones;
}
/* util */
std::string to_s(int n) {
/* std::to_stringとかぶるけど、本番環境では必要になりそう*/
std::stringstream ss;
ss << n;
return ss.str();
}
int get() {
return getc(stdin) - '0';
}
void read_br() {
/* CRLFを読み飛ばす */
get();
get();
};
/* dump */
void dump_stone(int n) {
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
if (stones[n].raw[i][j] == empty_val) {
/* 空き */
putc('.', dumpout);
} else {
/* うまり */
putc('@', dumpout);
}
}
putc('\n', dumpout);
}
}
void dump_field(Field& f) {
for (int i = 0; i < field_size; ++i) {
for (int j = 0; j < field_size; ++j) {
if (f.raw[i][j] == empty_val) {
/* あき */
putc('.', dumpout);
} else if (f.raw[i][j] == filled_val) {
/* 障害物 */
putc('#', dumpout);
} else {
/* 石 */
putc('@', dumpout);
}
}
putc('\n', dumpout);
}
}
/* stone manipurates */
void init_stone(int n) {
/* 石を初期化しておく */
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
stones[n].raw[i][j] = empty_val;
}
}
}
void rotate_stone(int n, int deg) {
/* 石を回す。deg = 90でよばれて、内部で180, 270をよぶ */
init_stone(rotated(n, deg));
for (int i = 0; i < stones[n].fills.size(); ++i) {
int newy = stones[n].fills[i].x;
int newx = 7 - stones[n].fills[i].y;
stones[rotated(n, deg)].fills.push_back(Position{newy, newx});
stones[rotated(n, deg)].raw[newy][newx] = stones[n].raw[stones[n].fills[i].y][stones[n].fills[i].x];
}
if (deg != 270) {
rotate_stone(n, deg+90);
}
}
void flip_stone(int n) {
/* 石を反転させる */
init_stone(fliped(n));
for (int i = 0; i < stones[n].fills.size(); ++i) {
int newy = stones[n].fills[i].y;
int newx = 7 - stones[n].fills[i].x;
stones[fliped(n)].fills.push_back(Position{newy, newx});
stones[fliped(n)].raw[newy][newx] = stones[n].raw[stones[n].fills[i].y][stones[n].fills[i].x];
}
}
/* parsing */
void get_field() {
/* 初期フィールドを得る */
for (int i = 0; i < field_size; ++i) {
for (int j = 0; j < field_size; ++j) {
if (get() == 0) {
initial_field.raw[i][j] = empty_val;
} else {
initial_field.raw[i][j] = filled_val;
}
}
read_br();
}
}
void get_stone(int index) {
/* 石をひとつ読む */
for (int i = 0; i < stone_size; ++i) {
for (int j = 0; j < stone_size; ++j) {
if (get() == 0) {
stones[index].raw[i][j] = empty_val;
} else {
stones[index].raw[i][j] = index;
stones[index].fills.push_back(Position{i, j});
}
}
read_br();
}
}
void get_stones() {
/* 石をnumber_of_stones個よむ */
for (int i = 0; i < number_of_stones; ++i) {
get_stone(i);
read_br();
flip_stone(i);
rotate_stone(i, 90);
rotate_stone(fliped(i), 90);
}
}
void get_input() {
/* 入力を読む */
get_field(); read_br();
scanf("%d\n", &number_of_stones);
get_stones();
}
/* helper */
void create_candidates(std::deque<Position>& next_candidates, int n, std::deque<Position>& empties) {
/* 石の埋まっている場所とフィールド上の候補から、次に石を置く可能性のある場所に置く*/
next_candidates.resize(empties.size() * stones[n].fills.size());
for (auto p1 : empties) {
for (auto p2 : stones[n].fills) {
next_candidates.push_back(Position{ p1.y - p2.y, p1.x - p2.x });
}
}
}
/* solver */
void solve() {
/* とりあえずこれを呼んでsolveする */
std::deque<Position> first_candidates;
for (int i = 0; i < all_stones_num(); ++i) {
create_candidates(first_candidates, i, initial_empties); // 一個目の石を置く場所の候補を生成
}
}
/* main */
int main() {
initial_empties.resize(1024);
get_input();
// dump_field(initial_field);
// solve();
}
<commit_msg>operated関数を追加<commit_after>#include <cstdio>
#include <vector>
#include <deque>
#include <string>
#include <sstream>
/* definitions */
const int stone_size = 8;
const int field_size = 32;
const int empty_val = -1; // 障害物やzkの無いことを表す
const int filled_val = 256; // 障害物を表す
FILE* dumpout = stdout; // dump系関数の出力先
struct Position {
/*座標を表現するクラス*/
int y, x;
bool operator==(const Position&obj) const {
return y == obj.y && x == obj.x;
}
bool operator<(const Position&obj) const {
if (y == obj.y) {
return x < obj.x;
}
return y < obj.y;
}
};
struct Stone {
/* 石 */
int raw[stone_size][stone_size]; // empty_val -> 空き, otherwise -> うまり
std::deque<Position> fills; // 埋まってる座標を持っておく
};
struct Field {
/* フィールド */
int raw[field_size][field_size];
std::deque<std::string> answer; // 答えとなる石の置き方を持っておく
};
int number_of_stones; // 与えられる石の数
Stone stones[256 * 8]; // 石を持っておくインスタンス(回転反転を考慮して8倍とってある)
Field initial_field; // 初期フィールド状態
std::deque<Position> initial_empties; // 初期フィールドで空いている場所を探す
int rotated(int deg) {
/* 石をdeg度まわした石の番号のバイアスを返す */
return number_of_stones * (deg/90);
}
int fliped() {
/* 石を反転した時の石の番号のバイアスを返す */
return number_of_stones * 4;
}
int operated(bool flip, int deg) {
/* 石を操作した時の石の番号のバイアスを返す */
if (flip) {
if (deg == 0) {
return fliped();
}
return fliped() + rotated(deg);
}
return rotated(deg);
}
int rotated(int n, int deg) {
/* 石をdeg度まわした石の番号を返す */
return n + rotated(deg);
}
int fliped(int n) {
/* 石を反転した時の石の番号を返す */
return n + fliped();
}
int operated(int n, bool flip, int deg) {
/* 石を操作した時の石の番号のバイアスを返す */
return n + operated(flip, deg);
}
int all_stones_num() {
/* 全部で石が何個になるか */
return 8*number_of_stones;
}
/* util */
std::string to_s(int n) {
/* std::to_stringとかぶるけど、本番環境では必要になりそう*/
std::stringstream ss;
ss << n;
return ss.str();
}
int get() {
return getc(stdin) - '0';
}
void read_br() {
/* CRLFを読み飛ばす */
get();
get();
};
/* dump */
void dump_stone(int n) {
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
if (stones[n].raw[i][j] == empty_val) {
/* 空き */
putc('.', dumpout);
} else {
/* うまり */
putc('@', dumpout);
}
}
putc('\n', dumpout);
}
}
void dump_field(Field& f) {
for (int i = 0; i < field_size; ++i) {
for (int j = 0; j < field_size; ++j) {
if (f.raw[i][j] == empty_val) {
/* あき */
putc('.', dumpout);
} else if (f.raw[i][j] == filled_val) {
/* 障害物 */
putc('#', dumpout);
} else {
/* 石 */
putc('@', dumpout);
}
}
putc('\n', dumpout);
}
}
/* stone manipurates */
void init_stone(int n) {
/* 石を初期化しておく */
for (int i = 0; i < 8; ++i) {
for (int j = 0; j < 8; ++j) {
stones[n].raw[i][j] = empty_val;
}
}
}
void rotate_stone(int n, int deg) {
/* 石を回す。deg = 90でよばれて、内部で180, 270をよぶ */
init_stone(rotated(n, deg));
for (int i = 0; i < stones[n].fills.size(); ++i) {
int newy = stones[n].fills[i].x;
int newx = 7 - stones[n].fills[i].y;
stones[rotated(n, deg)].fills.push_back(Position{newy, newx});
stones[rotated(n, deg)].raw[newy][newx] = stones[n].raw[stones[n].fills[i].y][stones[n].fills[i].x];
}
if (deg != 270) {
rotate_stone(n, deg+90);
}
}
void flip_stone(int n) {
/* 石を反転させる */
init_stone(fliped(n));
for (int i = 0; i < stones[n].fills.size(); ++i) {
int newy = stones[n].fills[i].y;
int newx = 7 - stones[n].fills[i].x;
stones[fliped(n)].fills.push_back(Position{newy, newx});
stones[fliped(n)].raw[newy][newx] = stones[n].raw[stones[n].fills[i].y][stones[n].fills[i].x];
}
}
/* parsing */
void get_field() {
/* 初期フィールドを得る */
for (int i = 0; i < field_size; ++i) {
for (int j = 0; j < field_size; ++j) {
if (get() == 0) {
initial_field.raw[i][j] = empty_val;
} else {
initial_field.raw[i][j] = filled_val;
}
}
read_br();
}
}
void get_stone(int index) {
/* 石をひとつ読む */
for (int i = 0; i < stone_size; ++i) {
for (int j = 0; j < stone_size; ++j) {
if (get() == 0) {
stones[index].raw[i][j] = empty_val;
} else {
stones[index].raw[i][j] = index;
stones[index].fills.push_back(Position{i, j});
}
}
read_br();
}
}
void get_stones() {
/* 石をnumber_of_stones個よむ */
for (int i = 0; i < number_of_stones; ++i) {
get_stone(i);
read_br();
flip_stone(i);
rotate_stone(i, 90);
rotate_stone(fliped(i), 90);
}
}
void get_input() {
/* 入力を読む */
get_field(); read_br();
scanf("%d\n", &number_of_stones);
get_stones();
}
/* helper */
void create_candidates(std::deque<Position>& next_candidates, int n, std::deque<Position>& empties) {
/* 石の埋まっている場所とフィールド上の候補から、次に石を置く可能性のある場所に置く*/
next_candidates.resize(empties.size() * stones[n].fills.size());
for (auto p1 : empties) {
for (auto p2 : stones[n].fills) {
next_candidates.push_back(Position{ p1.y - p2.y, p1.x - p2.x });
}
}
}
/* solver */
void dfs(int n, bool fliped, int deg, Position p, Field& f) {
/* n番の石をfliped + degの状態で、f上のpに置くところから深く */
if (n >= number_of_stones) {
return;
}
int m = operated(n, fliped, deg);
}
void solve() {
/* とりあえずこれを呼んでsolveする */
std::deque<Position> first_candidates;
for (int i = 0; i < number_of_stones; ++i) {
create_candidates(first_candidates, i, initial_empties); // 一個目の石を置く場所の候補を生成
}
}
/* main */
int main() {
initial_empties.resize(1024);
get_input();
// dump_field(initial_field);
// solve();
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <algebra/infinite_vector.h>
#include <utils/array1d.h>
#include <interval/dku_basis.h>
using namespace std;
using namespace WaveletTL;
int main()
{
cout << "Testing the DKU bases..." << endl;
const int d = 2;
const int dT = 4;
typedef DKUBasis<d, dT> Basis;
Basis basis; // Bernstein SVD
// Basis basis(none);
cout << "- the (" << d << "," << dT << ") basis has j0=" << basis.j0() << endl;
cout << "- the default wavelet index: " << Basis::Index(&basis) << endl;
cout << "- leftmost generator on the coarsest level: " << basis.firstGenerator(basis.j0()) << endl;
cout << "- rightmost generator on the coarsest level: " << basis.lastGenerator(basis.j0()) << endl;
cout << "- leftmost wavelet on the coarsest level: " << basis.firstWavelet(basis.j0()) << endl;
cout << "- rightmost wavelet on the coarsest level: " << basis.lastWavelet(basis.j0()) << endl;
typedef Basis::Index Index;
#if 0
cout << "- iterating from first generator on coarsest level to last wavelet on next level:" << endl;
Index index(basis.firstGenerator(basis.j0()));
for (;; ++index) {
cout << index << endl;
if (index == basis.lastWavelet(basis.j0()+1)) break;
}
#endif
cout << "- index of leftmost right boundary generator on scale j0: "
<< basis.DeltaRmin(basis.j0()) << endl;
InfiniteVector<double, Index> coeff;
// coeff[basis.firstGenerator(basis.j0())] = 0.0;
// coeff[++basis.firstGenerator(basis.j0())] = 0.0;
Index index(basis.firstGenerator(basis.j0()+1));
coeff[index] = 1.0;
// for (int i = 0; i <= 8; i++)
// coeff[++index] = 1.0;
cout << " * a small but nontrivial coefficient set:" << endl << coeff;
cout << " * result of DECOMPOSE:" << endl;
InfiniteVector<double,Index> wcoeff;
basis.decompose(coeff, basis.j0(), wcoeff);
cout << wcoeff;
#if 0
cout << "- evaluating some primal generators:" << endl;
Index lambda(basis.firstGenerator(basis.j0()));
for (;; ++lambda) {
cout << lambda << endl;
basis.evaluate(lambda, true, 5).matlab_output(cout);
if (lambda == basis.lastGenerator(basis.j0())) break;
}
#endif
#if 0
cout << "- evaluating some dual generators:" << endl;
lambda = basis.firstGenerator(basis.j0());
for (;; ++lambda) {
basis.evaluate(lambda, false, 6).matlab_output(cout);
if (lambda == basis.lastGenerator(basis.j0())) break;
}
#endif
cout << "* another basis:" << endl;
const int d2 = 3;
const int dT2 = 5;
DKUBasis<d2, dT2> basis2;
cout << "- the (" << d2 << "," << dT2 << ") basis has j0=" << basis2.j0() << endl;
cout << "- the default wavelet index: " << DKUBasis<d2, dT2>::Index(&basis2) << endl;
cout << "- leftmost generator on the coarsest level: " << basis2.firstGenerator(basis2.j0()) << endl;
cout << "- rightmost generator on the coarsest level: " << basis2.lastGenerator(basis2.j0()) << endl;
cout << "- leftmost wavelet on the coarsest level: " << basis2.firstWavelet(basis2.j0()) << endl;
cout << "- rightmost wavelet on the coarsest level: " << basis2.lastWavelet(basis2.j0()) << endl;
cout << "* yet another basis:" << endl;
// const int d3 = 3;
// const int dT3 = 7;
// DKUBasis<d3, dT3> basis3;
// cout << "- the (" << d3 << "," << dT3 << ") basis has j0=" << basis3.j0() << endl;
// cout << "- the default wavelet index: " << DKUBasis<d3, dT3>::Index(&basis3) << endl;
// cout << "- leftmost generator on the coarsest level: " << basis3.firstGenerator(basis3.j0()) << endl;
// cout << "- rightmost generator on the coarsest level: " << basis3.lastGenerator(basis3.j0()) << endl;
// cout << "- leftmost wavelet on the coarsest level: " << basis3.firstWavelet(basis3.j0()) << endl;
// cout << "- rightmost wavelet on the coarsest level: " << basis3.lastWavelet(basis3.j0()) << endl;
return 0;
}
<commit_msg>added test for RECONSTRUCT; weekend backup...<commit_after>#include <iostream>
#include <algebra/infinite_vector.h>
#include <utils/array1d.h>
#include <interval/dku_basis.h>
using namespace std;
using namespace WaveletTL;
int main()
{
cout << "Testing the DKU bases..." << endl;
const int d = 2;
const int dT = 4;
typedef DKUBasis<d, dT> Basis;
Basis basis; // Bernstein SVD
// Basis basis(none);
cout << "- the (" << d << "," << dT << ") basis has j0=" << basis.j0() << endl;
cout << "- the default wavelet index: " << Basis::Index(&basis) << endl;
cout << "- leftmost generator on the coarsest level: " << basis.firstGenerator(basis.j0()) << endl;
cout << "- rightmost generator on the coarsest level: " << basis.lastGenerator(basis.j0()) << endl;
cout << "- leftmost wavelet on the coarsest level: " << basis.firstWavelet(basis.j0()) << endl;
cout << "- rightmost wavelet on the coarsest level: " << basis.lastWavelet(basis.j0()) << endl;
typedef Basis::Index Index;
#if 0
cout << "- iterating from first generator on coarsest level to last wavelet on next level:" << endl;
Index index(basis.firstGenerator(basis.j0()));
for (;; ++index) {
cout << index << endl;
if (index == basis.lastWavelet(basis.j0()+1)) break;
}
#endif
cout << "- index of leftmost right boundary generator on scale j0: "
<< basis.DeltaRmin(basis.j0()) << endl;
InfiniteVector<double, Index> coeff;
// coeff[basis.firstGenerator(basis.j0())] = 0.0;
// coeff[++basis.firstGenerator(basis.j0())] = 0.0;
Index index(basis.firstGenerator(basis.j0()+1));
coeff[index] = 1.0;
// for (int i = 0; i <= 8; i++)
// coeff[++index] = 1.0;
cout << " * a small but nontrivial coefficient set:" << endl << coeff;
cout << " * result of DECOMPOSE:" << endl;
InfiniteVector<double,Index> wcoeff;
basis.decompose(coeff, basis.j0(), wcoeff);
cout << wcoeff;
cout << " * RECONSTRUCT that:" << endl;
InfiniteVector<double,Index> rcoeff;
basis.reconstruct(wcoeff,basis.j0()+1,rcoeff);
cout << rcoeff;
#if 0
cout << "- evaluating some primal generators:" << endl;
Index lambda(basis.firstGenerator(basis.j0()));
for (;; ++lambda) {
cout << lambda << endl;
basis.evaluate(lambda, true, 5).matlab_output(cout);
if (lambda == basis.lastGenerator(basis.j0())) break;
}
#endif
#if 0
cout << "- evaluating some dual generators:" << endl;
lambda = basis.firstGenerator(basis.j0());
for (;; ++lambda) {
basis.evaluate(lambda, false, 6).matlab_output(cout);
if (lambda == basis.lastGenerator(basis.j0())) break;
}
#endif
cout << "* another basis:" << endl;
const int d2 = 3;
const int dT2 = 5;
DKUBasis<d2, dT2> basis2;
cout << "- the (" << d2 << "," << dT2 << ") basis has j0=" << basis2.j0() << endl;
cout << "- the default wavelet index: " << DKUBasis<d2, dT2>::Index(&basis2) << endl;
cout << "- leftmost generator on the coarsest level: " << basis2.firstGenerator(basis2.j0()) << endl;
cout << "- rightmost generator on the coarsest level: " << basis2.lastGenerator(basis2.j0()) << endl;
cout << "- leftmost wavelet on the coarsest level: " << basis2.firstWavelet(basis2.j0()) << endl;
cout << "- rightmost wavelet on the coarsest level: " << basis2.lastWavelet(basis2.j0()) << endl;
cout << "* yet another basis:" << endl;
// const int d3 = 3;
// const int dT3 = 7;
// DKUBasis<d3, dT3> basis3;
// cout << "- the (" << d3 << "," << dT3 << ") basis has j0=" << basis3.j0() << endl;
// cout << "- the default wavelet index: " << DKUBasis<d3, dT3>::Index(&basis3) << endl;
// cout << "- leftmost generator on the coarsest level: " << basis3.firstGenerator(basis3.j0()) << endl;
// cout << "- rightmost generator on the coarsest level: " << basis3.lastGenerator(basis3.j0()) << endl;
// cout << "- leftmost wavelet on the coarsest level: " << basis3.firstWavelet(basis3.j0()) << endl;
// cout << "- rightmost wavelet on the coarsest level: " << basis3.lastWavelet(basis3.j0()) << endl;
return 0;
}
<|endoftext|>
|
<commit_before>#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace cv;
using namespace std;
int main(int argc, char** argv) {
Mat src, src_gray;
Mat dst, dst_norm, dst_norm_scaled;
dst = Mat::zeros(src.size(), CV_32FC1);
/// Detector parameters
int blockSize = 2;
int apertureSize = 31;
double k = 0.01;
/// Load source image and convert it to gray
src = imread(argv[1], 1);
cvtColor(src, src_gray, CV_BGR2GRAY);
/// Detecting corners
cornerHarris(src_gray, dst, blockSize, apertureSize, k, BORDER_DEFAULT);
/// Normalizing
normalize(dst, dst_norm, 0, 255, NORM_MINMAX, CV_32FC1, Mat());
convertScaleAbs(dst_norm, dst_norm_scaled);
int occurences[4][256];
for (int i = 0; i < 4; i++)
fill(occurences[i], occurences[i] + 256, 0);
for (int j = 0; j < dst_norm.rows; j++) {
for (int i = 0; i < dst_norm.cols; i++) {
int index = (int) dst_norm.at<float>(j, i);
int quadrant;
if (i < dst_norm.cols / 2)
quadrant = j < dst_norm.rows / 2 ? 0 : 1;
else
quadrant = j < dst_norm.rows / 2 ? 2 : 3;
occurences[quadrant][index]++;
}
}
cout << "\n";
int threshold;
int corners_found[4] = {0, 0, 0, 0};
for (threshold = 255; threshold >= 0; threshold--) {
bool corner_in_every_quadrant = true;
for (int i = 0; i < 4; i++) {
corners_found[i] += occurences[i][threshold];
if (corners_found[i] == 0)
corner_in_every_quadrant = false;
}
if (corner_in_every_quadrant)
break;
}
cout << "{\"threshold\": " << threshold << ",\n";
cout << " \"points\": [";
bool first = true;
for (int j = 0; j < dst_norm.rows; j++) {
for (int i = 0; i < dst_norm.cols; i++) {
if ((int) dst_norm.at<float>(j, i) >= threshold) {
if (!first) cout << ", "; else first = false;
cout << "[" << i << ", " << j << "]";
}
}
}
end_loop:
cout << "]}\n";
}
<commit_msg>Removed Harris corner detection code.<commit_after><|endoftext|>
|
<commit_before>/*
* Copyright (c) 2003-2010 Rony Shapiro <ronys@users.sourceforge.net>.
* All rights reserved. Use of the code is allowed under the
* Artistic License 2.0 terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license-2.0.php
*/
/** \file PWSTreeCtrl.cpp
*
*/
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
////@begin includes
#include "wx/imaglist.h"
////@end includes
#include <utility> // for make_pair
#include <vector>
#include "PWStree.h"
#include "passwordsafeframe.h" // for DispatchDblClickAction()
#include "corelib/PWSprefs.h"
////@begin XPM images
////@end XPM images
#include "../graphics/wxWidgets/abase_exp.xpm"
#include "../graphics/wxWidgets/abase_warn.xpm"
#include "../graphics/wxWidgets/abase.xpm"
#include "../graphics/wxWidgets/alias.xpm"
#include "../graphics/wxWidgets/node.xpm"
#include "../graphics/wxWidgets/normal_exp.xpm"
#include "../graphics/wxWidgets/normal_warn.xpm"
#include "../graphics/wxWidgets/normal.xpm"
#include "../graphics/wxWidgets/sbase_exp.xpm"
#include "../graphics/wxWidgets/sbase_warn.xpm"
#include "../graphics/wxWidgets/sbase.xpm"
#include "../graphics/wxWidgets/shortcut.xpm"
/*!
* PWSTreeCtrl type definition
*/
IMPLEMENT_CLASS( PWSTreeCtrl, wxTreeCtrl )
// Image Indices - these match the order images are added
// in PWSTreeCtrl::CreateControls()
enum {
ABASE_EXP_II, // 0
ABASE_WARN_II, // 1
ABASE_II, // 2
ALIAS_II, // 3
NODE_II, // 4
NORMAL_EXP_II, // 5
NORMAL_WARN_II, // 6
NORMAL_II, // 7
SBASE_EXP_II, // 8
SBASE_WARN_II, // 9
SBASE_II, // 10
SHORTCUT_II, // 11
};
/*!
* PWSTreeCtrl event table definition
*/
BEGIN_EVENT_TABLE( PWSTreeCtrl, wxTreeCtrl )
////@begin PWSTreeCtrl event table entries
EVT_TREE_ITEM_ACTIVATED( ID_TREECTRL, PWSTreeCtrl::OnTreectrlItemActivated )
EVT_TREE_ITEM_MENU( ID_TREECTRL, PWSTreeCtrl::OnContextMenu )
EVT_CHAR( PWSTreeCtrl::OnChar )
////@end PWSTreeCtrl event table entries
EVT_TREE_ITEM_GETTOOLTIP( ID_TREECTRL, PWSTreeCtrl::OnGetToolTip )
END_EVENT_TABLE()
// helper class to match CItemData with wxTreeItemId
class PWTreeItemData : public wxTreeItemData
{
public:
PWTreeItemData(const CItemData &item)
{
item.GetUUID(m_uuid);
}
const uuid_array_t &GetUUID() const {return m_uuid;}
private:
uuid_array_t m_uuid;
};
/*!
* PWSTreeCtrl constructors
*/
PWSTreeCtrl::PWSTreeCtrl(PWScore &core) : m_core(core)
{
Init();
}
PWSTreeCtrl::PWSTreeCtrl(wxWindow* parent, PWScore &core,
wxWindowID id, const wxPoint& pos,
const wxSize& size, long style) : m_core(core)
{
Init();
Create(parent, id, pos, size, style);
}
/*!
* PWSTreeCtrl creator
*/
bool PWSTreeCtrl::Create(wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style)
{
////@begin PWSTreeCtrl creation
wxTreeCtrl::Create(parent, id, pos, size, style);
CreateControls();
////@end PWSTreeCtrl creation
return true;
}
/*!
* PWSTreeCtrl destructor
*/
PWSTreeCtrl::~PWSTreeCtrl()
{
////@begin PWSTreeCtrl destruction
////@end PWSTreeCtrl destruction
}
/*!
* Member initialisation
*/
void PWSTreeCtrl::Init()
{
////@begin PWSTreeCtrl member initialisation
////@end PWSTreeCtrl member initialisation
}
/*!
* Control creation for PWSTreeCtrl
*/
void PWSTreeCtrl::CreateControls()
{
////@begin PWSTreeCtrl content construction
////@end PWSTreeCtrl content construction
const char **xpmList[] = {
abase_exp_xpm, // 0
abase_warn_xpm, // 1
abase_xpm, // 2
alias_xpm, // 3
node_xpm, // 4
normal_exp_xpm, // 5
normal_warn_xpm, // 6
normal_xpm, // 7
sbase_exp_xpm, // 8
sbase_warn_xpm, // 9
sbase_xpm, // 10
shortcut_xpm, // 11
};
const int Nimages = sizeof(xpmList)/sizeof(xpmList[0]);
wxImageList *iList = new wxImageList(9, 9, true, Nimages);
for (int i = 0; i < Nimages; i++)
iList->Add(wxIcon(xpmList[i]));
AssignImageList(iList);
}
// XXX taken from Windows PWSTreeCtrl.cpp
// XXX move to corelib
static StringX GetPathElem(StringX &path)
{
// Get first path element and chop it off, i.e., if
// path = "a.b.c.d"
// will return "a" and path will be "b.c.d"
// (assuming GROUP_SEP is '.')
const char GROUP_SEP = '.';
StringX retval;
StringX::size_type N = path.find(GROUP_SEP);
if (N == StringX::npos) {
retval = path;
path = _T("");
} else {
const StringX::size_type Len = path.length();
retval = path.substr(0, N);
path = path.substr(Len - N - 1);
}
return retval;
}
bool PWSTreeCtrl::ExistsInTree(wxTreeItemId node,
const StringX &s, wxTreeItemId &si)
{
// returns true iff s is a direct descendant of node
wxTreeItemIdValue cookie;
wxTreeItemId ti = GetFirstChild(node, cookie);
while (ti) {
const wxString itemText = GetItemText(ti);
if (itemText == s.c_str()) {
si = ti;
return true;
}
ti = GetNextSibling(ti);
}
return false;
}
wxTreeItemId PWSTreeCtrl::AddGroup(const StringX &group)
{
wxTreeItemId ti = GetRootItem();
if (!ti.IsOk())
ti=AddRoot(wxString());
// Add a group at the end of path
wxTreeItemId si;
if (!group.empty()) {
StringX path = group;
StringX s;
do {
s = GetPathElem(path);
if (!ExistsInTree(ti, s, si)) {
ti = AppendItem(ti, s.c_str());
wxTreeCtrl::SetItemImage(ti, NODE_II);
} else
ti = si;
} while (!path.empty());
}
return ti;
}
wxString PWSTreeCtrl::ItemDisplayString(const CItemData &item) const
{
PWSprefs *prefs = PWSprefs::GetInstance();
const wxString title = item.GetTitle().c_str();
wxString disp = title;
if (prefs->GetPref(PWSprefs::ShowUsernameInTree)) {
const wxString user = item.GetUser().c_str();
if (!user.empty())
disp += _T(" [") + user + _("]");
}
if (prefs->GetPref(PWSprefs::ShowPasswordInTree)) {
const wxString passwd = item.GetPassword().c_str();
if (!passwd.empty())
disp += _T(" {") + passwd + _("}");
}
return disp;
}
wxString PWSTreeCtrl::GetPath(const wxTreeItemId &node) const
{
wxString retval;
std::vector<wxString> v;
const wxTreeItemId root = GetRootItem();
wxTreeItemId parent = GetItemParent(node);
while (parent != root) {
v.push_back(GetItemText(parent));
parent = GetItemParent(parent);
}
std::vector<wxString>::reverse_iterator iter;
for(iter = v.rbegin(); iter != v.rend(); iter++) {
retval += *iter;
if ((iter + 1) != v.rend())
retval += _(".");
}
return retval;
}
void PWSTreeCtrl::UpdateItem(const CItemData &item)
{
const wxTreeItemId node = Find(item);
if (node.IsOk()) {
const wxString oldGroup = GetPath(node);
const wxString newGroup = item.GetGroup().c_str();
if (oldGroup == newGroup) {
const wxString disp = ItemDisplayString(item);
SetItemText(node, disp);
SetItemImage(node, item);
} else { // uh-oh - group's changed
uuid_array_t uuid;
item.GetUUID(uuid);
// remove old item
m_item_map.erase(CUUIDGen(uuid));
Delete(node);
// add new group
AddItem(item);
}
Update();
}
}
void PWSTreeCtrl::AddItem(const CItemData &item)
{
wxTreeItemData *data = new PWTreeItemData(item);
wxTreeItemId gnode = AddGroup(item.GetGroup());
const wxString disp = ItemDisplayString(item);
wxTreeItemId titem = AppendItem(gnode, disp, -1, -1, data);
SetItemImage(titem, item);
SortChildren(gnode);
uuid_array_t uuid;
item.GetUUID(uuid);
m_item_map.insert(std::make_pair(CUUIDGen(uuid), titem));
}
CItemData *PWSTreeCtrl::GetItem(const wxTreeItemId &id) const
{
if (!id.IsOk())
return NULL;
PWTreeItemData *itemData = dynamic_cast<PWTreeItemData *>(GetItemData(id));
// return if a group is selected
if (itemData == NULL)
return NULL;
ItemListIter itemiter = m_core.Find(itemData->GetUUID());
if (itemiter == m_core.GetEntryEndIter())
return NULL;
return &itemiter->second;
}
//overriden from base for case-insensitive sort
int PWSTreeCtrl::OnCompareItems(const wxTreeItemId& item1, const wxTreeItemId& item2)
{
const bool groupsFirst = PWSprefs::GetInstance()->GetPref(PWSprefs::ExplorerTypeTree),
item1isGroup = ItemHasChildren(item1),
item2isGroup = ItemHasChildren(item2);
if (groupsFirst) {
if (item1isGroup && !item2isGroup)
return -1;
else if (item2isGroup && !item1isGroup)
return 1;
}
const wxString text1 = GetItemText(item1);
const wxString text2 = GetItemText(item2);
return text1.CmpNoCase(text2);
}
wxTreeItemId PWSTreeCtrl::Find(const uuid_array_t &uuid) const
{
wxTreeItemId fail;
CUUIDGen cuuid(uuid);
UUIDTIMapT::const_iterator iter = m_item_map.find(cuuid);
if (iter != m_item_map.end())
return iter->second;
else
return fail;
}
wxTreeItemId PWSTreeCtrl::Find(const CItemData &item) const
{
uuid_array_t uuid;
item.GetUUID(uuid);
return Find(uuid);
}
bool PWSTreeCtrl::Remove(const uuid_array_t &uuid)
{
wxTreeItemId id = Find(uuid);
if (id.IsOk()) {
m_item_map.erase(CUUIDGen(uuid));
// if item's the only leaf of group, delete parent
// group as well. repeat up the tree...
wxTreeItemId parentId = GetItemParent(id);
Delete(id);
while (parentId != GetRootItem()) {
wxTreeItemId grandparentId = GetItemParent(parentId);
if (GetChildrenCount(parentId) == 0) {
Delete(parentId);
parentId = grandparentId;
} else
break;
} // while
Refresh();
Update();
return true;
} else {
return false;
}
}
void PWSTreeCtrl::SetItemImage(const wxTreeItemId &node,
const CItemData &item)
{
// XXX TBD: modify to display warning and expired states
int i = NORMAL_II;
switch (item.GetEntryType()) {
case CItemData::ET_NORMAL: i = NORMAL_II; break;
case CItemData::ET_ALIASBASE: i = ABASE_II; break;
case CItemData::ET_ALIAS: i = ALIAS_II; break;
case CItemData::ET_SHORTCUTBASE: i = SBASE_II; break;
case CItemData::ET_SHORTCUT: i = SHORTCUT_II; break;
case CItemData::ET_INVALID: ASSERT(0); break;
default: ASSERT(0);
}
wxTreeCtrl::SetItemImage(node, i);
}
/*!
* wxEVT_COMMAND_TREE_ITEM_ACTIVATED event handler for ID_TREECTRL
*/
void PWSTreeCtrl::OnTreectrlItemActivated( wxTreeEvent& evt )
{
const wxTreeItemId item = evt.GetItem();
if (ItemHasChildren(item) && GetChildrenCount(item) > 0){
if (IsExpanded(item))
Collapse(item);
else {
Expand(item);
//scroll the last child of this node into visibility
EnsureVisible(GetLastChild(item));
//but if that scrolled the parent out of the view, bring it back
EnsureVisible(item);
}
}
else {
CItemData *ci = GetItem(item);
if (ci != NULL)
dynamic_cast<PasswordSafeFrame *>(GetParent())->
DispatchDblClickAction(*ci);
}
}
/*!
* wxEVT_TREE_ITEM_MENU event handler for ID_TREECTRL
*/
void PWSTreeCtrl::OnContextMenu( wxTreeEvent& evt )
{
dynamic_cast<PasswordSafeFrame*>(GetParent())->OnContextMenu(GetItem(evt.GetItem()));
}
void PWSTreeCtrl::SelectItem(const CUUIDGen & uuid)
{
uuid_array_t uuid_array;
uuid.GetUUID(uuid_array);
wxTreeItemId id = Find(uuid_array);
if (id.IsOk())
wxTreeCtrl::SelectItem(id);
}
void PWSTreeCtrl::OnGetToolTip( wxTreeEvent& evt )
{ // Added manually
if (PWSprefs::GetInstance()->GetPref(PWSprefs::ShowNotesAsTooltipsInViews)) {
wxTreeItemId id = evt.GetItem();
const CItemData *ci = GetItem(id);
if (ci != NULL) {
const wxString note = ci->GetNotes().c_str();
evt.SetToolTip(note);
}
}
}
/*!
* wxEVT_CHAR event handler for ID_TREECTRL
*/
void PWSTreeCtrl::OnChar( wxKeyEvent& evt )
{
if (evt.GetKeyCode() == WXK_ESCAPE &&
PWSprefs::GetInstance()->GetPref(PWSprefs::EscExits)) {
GetParent()->Close();
}
evt.Skip();
}
<commit_msg>Fix incorrect (sub)group handling in wxWidgets build<commit_after>/*
* Copyright (c) 2003-2010 Rony Shapiro <ronys@users.sourceforge.net>.
* All rights reserved. Use of the code is allowed under the
* Artistic License 2.0 terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license-2.0.php
*/
/** \file PWSTreeCtrl.cpp
*
*/
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
////@begin includes
#include "wx/imaglist.h"
////@end includes
#include <utility> // for make_pair
#include <vector>
#include "PWStree.h"
#include "passwordsafeframe.h" // for DispatchDblClickAction()
#include "corelib/PWSprefs.h"
////@begin XPM images
////@end XPM images
#include "../graphics/wxWidgets/abase_exp.xpm"
#include "../graphics/wxWidgets/abase_warn.xpm"
#include "../graphics/wxWidgets/abase.xpm"
#include "../graphics/wxWidgets/alias.xpm"
#include "../graphics/wxWidgets/node.xpm"
#include "../graphics/wxWidgets/normal_exp.xpm"
#include "../graphics/wxWidgets/normal_warn.xpm"
#include "../graphics/wxWidgets/normal.xpm"
#include "../graphics/wxWidgets/sbase_exp.xpm"
#include "../graphics/wxWidgets/sbase_warn.xpm"
#include "../graphics/wxWidgets/sbase.xpm"
#include "../graphics/wxWidgets/shortcut.xpm"
/*!
* PWSTreeCtrl type definition
*/
IMPLEMENT_CLASS( PWSTreeCtrl, wxTreeCtrl )
// Image Indices - these match the order images are added
// in PWSTreeCtrl::CreateControls()
enum {
ABASE_EXP_II, // 0
ABASE_WARN_II, // 1
ABASE_II, // 2
ALIAS_II, // 3
NODE_II, // 4
NORMAL_EXP_II, // 5
NORMAL_WARN_II, // 6
NORMAL_II, // 7
SBASE_EXP_II, // 8
SBASE_WARN_II, // 9
SBASE_II, // 10
SHORTCUT_II, // 11
};
/*!
* PWSTreeCtrl event table definition
*/
BEGIN_EVENT_TABLE( PWSTreeCtrl, wxTreeCtrl )
////@begin PWSTreeCtrl event table entries
EVT_TREE_ITEM_ACTIVATED( ID_TREECTRL, PWSTreeCtrl::OnTreectrlItemActivated )
EVT_TREE_ITEM_MENU( ID_TREECTRL, PWSTreeCtrl::OnContextMenu )
EVT_CHAR( PWSTreeCtrl::OnChar )
////@end PWSTreeCtrl event table entries
EVT_TREE_ITEM_GETTOOLTIP( ID_TREECTRL, PWSTreeCtrl::OnGetToolTip )
END_EVENT_TABLE()
// helper class to match CItemData with wxTreeItemId
class PWTreeItemData : public wxTreeItemData
{
public:
PWTreeItemData(const CItemData &item)
{
item.GetUUID(m_uuid);
}
const uuid_array_t &GetUUID() const {return m_uuid;}
private:
uuid_array_t m_uuid;
};
/*!
* PWSTreeCtrl constructors
*/
PWSTreeCtrl::PWSTreeCtrl(PWScore &core) : m_core(core)
{
Init();
}
PWSTreeCtrl::PWSTreeCtrl(wxWindow* parent, PWScore &core,
wxWindowID id, const wxPoint& pos,
const wxSize& size, long style) : m_core(core)
{
Init();
Create(parent, id, pos, size, style);
}
/*!
* PWSTreeCtrl creator
*/
bool PWSTreeCtrl::Create(wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style)
{
////@begin PWSTreeCtrl creation
wxTreeCtrl::Create(parent, id, pos, size, style);
CreateControls();
////@end PWSTreeCtrl creation
return true;
}
/*!
* PWSTreeCtrl destructor
*/
PWSTreeCtrl::~PWSTreeCtrl()
{
////@begin PWSTreeCtrl destruction
////@end PWSTreeCtrl destruction
}
/*!
* Member initialisation
*/
void PWSTreeCtrl::Init()
{
////@begin PWSTreeCtrl member initialisation
////@end PWSTreeCtrl member initialisation
}
/*!
* Control creation for PWSTreeCtrl
*/
void PWSTreeCtrl::CreateControls()
{
////@begin PWSTreeCtrl content construction
////@end PWSTreeCtrl content construction
const char **xpmList[] = {
abase_exp_xpm, // 0
abase_warn_xpm, // 1
abase_xpm, // 2
alias_xpm, // 3
node_xpm, // 4
normal_exp_xpm, // 5
normal_warn_xpm, // 6
normal_xpm, // 7
sbase_exp_xpm, // 8
sbase_warn_xpm, // 9
sbase_xpm, // 10
shortcut_xpm, // 11
};
const int Nimages = sizeof(xpmList)/sizeof(xpmList[0]);
wxImageList *iList = new wxImageList(9, 9, true, Nimages);
for (int i = 0; i < Nimages; i++)
iList->Add(wxIcon(xpmList[i]));
AssignImageList(iList);
}
// XXX taken from Windows PWSTreeCtrl.cpp
// XXX move to corelib
static StringX GetPathElem(StringX &path)
{
// Get first path element and chop it off, i.e., if
// path = "a.b.c.d"
// will return "a" and path will be "b.c.d"
// (assuming GROUP_SEP is '.')
const TCHAR GROUP_SEP = _T('.');
StringX retval;
StringX::size_type N = path.find(GROUP_SEP);
if (N == StringX::npos) {
retval = path;
path = _T("");
} else {
retval = path.substr(0, N);
path = path.substr(N + 1);
}
return retval;
}
bool PWSTreeCtrl::ExistsInTree(wxTreeItemId node,
const StringX &s, wxTreeItemId &si)
{
// returns true iff s is a direct descendant of node
wxTreeItemIdValue cookie;
wxTreeItemId ti = GetFirstChild(node, cookie);
while (ti) {
const wxString itemText = GetItemText(ti);
if (itemText == s.c_str()) {
si = ti;
return true;
}
ti = GetNextSibling(ti);
}
return false;
}
wxTreeItemId PWSTreeCtrl::AddGroup(const StringX &group)
{
wxTreeItemId ti = GetRootItem();
if (!ti.IsOk())
ti=AddRoot(wxString());
// Add a group at the end of path
wxTreeItemId si;
if (!group.empty()) {
StringX path = group;
StringX s;
do {
s = GetPathElem(path);
if (!ExistsInTree(ti, s, si)) {
ti = AppendItem(ti, s.c_str());
wxTreeCtrl::SetItemImage(ti, NODE_II);
} else
ti = si;
} while (!path.empty());
}
return ti;
}
wxString PWSTreeCtrl::ItemDisplayString(const CItemData &item) const
{
PWSprefs *prefs = PWSprefs::GetInstance();
const wxString title = item.GetTitle().c_str();
wxString disp = title;
if (prefs->GetPref(PWSprefs::ShowUsernameInTree)) {
const wxString user = item.GetUser().c_str();
if (!user.empty())
disp += _T(" [") + user + _("]");
}
if (prefs->GetPref(PWSprefs::ShowPasswordInTree)) {
const wxString passwd = item.GetPassword().c_str();
if (!passwd.empty())
disp += _T(" {") + passwd + _("}");
}
return disp;
}
wxString PWSTreeCtrl::GetPath(const wxTreeItemId &node) const
{
wxString retval;
std::vector<wxString> v;
const wxTreeItemId root = GetRootItem();
wxTreeItemId parent = GetItemParent(node);
while (parent != root) {
v.push_back(GetItemText(parent));
parent = GetItemParent(parent);
}
std::vector<wxString>::reverse_iterator iter;
for(iter = v.rbegin(); iter != v.rend(); iter++) {
retval += *iter;
if ((iter + 1) != v.rend())
retval += _(".");
}
return retval;
}
void PWSTreeCtrl::UpdateItem(const CItemData &item)
{
const wxTreeItemId node = Find(item);
if (node.IsOk()) {
const wxString oldGroup = GetPath(node);
const wxString newGroup = item.GetGroup().c_str();
if (oldGroup == newGroup) {
const wxString disp = ItemDisplayString(item);
SetItemText(node, disp);
SetItemImage(node, item);
} else { // uh-oh - group's changed
uuid_array_t uuid;
item.GetUUID(uuid);
// remove old item
m_item_map.erase(CUUIDGen(uuid));
Delete(node);
// add new group
AddItem(item);
}
Update();
}
}
void PWSTreeCtrl::AddItem(const CItemData &item)
{
wxTreeItemData *data = new PWTreeItemData(item);
wxTreeItemId gnode = AddGroup(item.GetGroup());
const wxString disp = ItemDisplayString(item);
wxTreeItemId titem = AppendItem(gnode, disp, -1, -1, data);
SetItemImage(titem, item);
SortChildren(gnode);
uuid_array_t uuid;
item.GetUUID(uuid);
m_item_map.insert(std::make_pair(CUUIDGen(uuid), titem));
}
CItemData *PWSTreeCtrl::GetItem(const wxTreeItemId &id) const
{
if (!id.IsOk())
return NULL;
PWTreeItemData *itemData = dynamic_cast<PWTreeItemData *>(GetItemData(id));
// return if a group is selected
if (itemData == NULL)
return NULL;
ItemListIter itemiter = m_core.Find(itemData->GetUUID());
if (itemiter == m_core.GetEntryEndIter())
return NULL;
return &itemiter->second;
}
//overriden from base for case-insensitive sort
int PWSTreeCtrl::OnCompareItems(const wxTreeItemId& item1, const wxTreeItemId& item2)
{
const bool groupsFirst = PWSprefs::GetInstance()->GetPref(PWSprefs::ExplorerTypeTree),
item1isGroup = ItemHasChildren(item1),
item2isGroup = ItemHasChildren(item2);
if (groupsFirst) {
if (item1isGroup && !item2isGroup)
return -1;
else if (item2isGroup && !item1isGroup)
return 1;
}
const wxString text1 = GetItemText(item1);
const wxString text2 = GetItemText(item2);
return text1.CmpNoCase(text2);
}
wxTreeItemId PWSTreeCtrl::Find(const uuid_array_t &uuid) const
{
wxTreeItemId fail;
CUUIDGen cuuid(uuid);
UUIDTIMapT::const_iterator iter = m_item_map.find(cuuid);
if (iter != m_item_map.end())
return iter->second;
else
return fail;
}
wxTreeItemId PWSTreeCtrl::Find(const CItemData &item) const
{
uuid_array_t uuid;
item.GetUUID(uuid);
return Find(uuid);
}
bool PWSTreeCtrl::Remove(const uuid_array_t &uuid)
{
wxTreeItemId id = Find(uuid);
if (id.IsOk()) {
m_item_map.erase(CUUIDGen(uuid));
// if item's the only leaf of group, delete parent
// group as well. repeat up the tree...
wxTreeItemId parentId = GetItemParent(id);
Delete(id);
while (parentId != GetRootItem()) {
wxTreeItemId grandparentId = GetItemParent(parentId);
if (GetChildrenCount(parentId) == 0) {
Delete(parentId);
parentId = grandparentId;
} else
break;
} // while
Refresh();
Update();
return true;
} else {
return false;
}
}
void PWSTreeCtrl::SetItemImage(const wxTreeItemId &node,
const CItemData &item)
{
// XXX TBD: modify to display warning and expired states
int i = NORMAL_II;
switch (item.GetEntryType()) {
case CItemData::ET_NORMAL: i = NORMAL_II; break;
case CItemData::ET_ALIASBASE: i = ABASE_II; break;
case CItemData::ET_ALIAS: i = ALIAS_II; break;
case CItemData::ET_SHORTCUTBASE: i = SBASE_II; break;
case CItemData::ET_SHORTCUT: i = SHORTCUT_II; break;
case CItemData::ET_INVALID: ASSERT(0); break;
default: ASSERT(0);
}
wxTreeCtrl::SetItemImage(node, i);
}
/*!
* wxEVT_COMMAND_TREE_ITEM_ACTIVATED event handler for ID_TREECTRL
*/
void PWSTreeCtrl::OnTreectrlItemActivated( wxTreeEvent& evt )
{
const wxTreeItemId item = evt.GetItem();
if (ItemHasChildren(item) && GetChildrenCount(item) > 0){
if (IsExpanded(item))
Collapse(item);
else {
Expand(item);
//scroll the last child of this node into visibility
EnsureVisible(GetLastChild(item));
//but if that scrolled the parent out of the view, bring it back
EnsureVisible(item);
}
}
else {
CItemData *ci = GetItem(item);
if (ci != NULL)
dynamic_cast<PasswordSafeFrame *>(GetParent())->
DispatchDblClickAction(*ci);
}
}
/*!
* wxEVT_TREE_ITEM_MENU event handler for ID_TREECTRL
*/
void PWSTreeCtrl::OnContextMenu( wxTreeEvent& evt )
{
dynamic_cast<PasswordSafeFrame*>(GetParent())->OnContextMenu(GetItem(evt.GetItem()));
}
void PWSTreeCtrl::SelectItem(const CUUIDGen & uuid)
{
uuid_array_t uuid_array;
uuid.GetUUID(uuid_array);
wxTreeItemId id = Find(uuid_array);
if (id.IsOk())
wxTreeCtrl::SelectItem(id);
}
void PWSTreeCtrl::OnGetToolTip( wxTreeEvent& evt )
{ // Added manually
if (PWSprefs::GetInstance()->GetPref(PWSprefs::ShowNotesAsTooltipsInViews)) {
wxTreeItemId id = evt.GetItem();
const CItemData *ci = GetItem(id);
if (ci != NULL) {
const wxString note = ci->GetNotes().c_str();
evt.SetToolTip(note);
}
}
}
/*!
* wxEVT_CHAR event handler for ID_TREECTRL
*/
void PWSTreeCtrl::OnChar( wxKeyEvent& evt )
{
if (evt.GetKeyCode() == WXK_ESCAPE &&
PWSprefs::GetInstance()->GetPref(PWSprefs::EscExits)) {
GetParent()->Close();
}
evt.Skip();
}
<|endoftext|>
|
<commit_before>#include <laser_odometry_core/laser_odometry_utils.h>
namespace laser_odometry
{
namespace utils
{
void tfFromXYTheta(const double x, const double y, const double theta, tf::Transform& t)
{
t = tf::Transform(tf::createQuaternionFromYaw(theta),
{x, y, 0});
}
bool getTf(const std::string& source_frame,
const std::string& target_frame,
tf::StampedTransform& tf)
{
tf::TransformListener tf_listener;
ros::Time t = ros::Time::now();
try
{
tf_listener.waitForTransform(
target_frame, source_frame, t, ros::Duration(1.0));
tf_listener.lookupTransform (
target_frame, source_frame, t, tf);
}
catch (tf::TransformException ex)
{
ROS_WARN("Could not get initial transform from base to laser frame, %s", ex.what());
tf.setIdentity();
return false;
}
return true;
}
bool getTf(const std::string& source_frame,
const std::string& target_frame,
tf::Transform& tf)
{
tf::StampedTransform stamped_tf;
bool ok = getTf(source_frame, target_frame, stamped_tf);
if (ok) tf = stamped_tf;
return ok;
}
bool getTf(const tf::tfMessagePtr tf_msg,
const std::string& source_frame,
const std::string& target_frame,
tf::Transform& tf)
{
for (const geometry_msgs::TransformStamped& tft : tf_msg->transforms)
{
if (tft.header.frame_id.compare(source_frame) == 0)
if (tft.child_frame_id.compare(target_frame) == 0)
{
tf::transformMsgToTF(tft.transform, tf);
return true;
}
}
return false;
}
void print(const tf::Transform& tf, const std::string& h)
{
std::cout << h
<< tf.getOrigin().getX()
<< " " << tf.getOrigin().getX()
<< " " << tf::getYaw(tf.getRotation()) << std::endl;
}
} /* namespace utils */
} /* namespace laser_odometry */
<commit_msg>fix getTf uninitialized<commit_after>#include <laser_odometry_core/laser_odometry_utils.h>
namespace laser_odometry
{
namespace utils
{
void tfFromXYTheta(const double x, const double y, const double theta, tf::Transform& t)
{
t = tf::Transform(tf::createQuaternionFromYaw(theta),
{x, y, 0});
}
bool getTf(const std::string& source_frame,
const std::string& target_frame,
tf::StampedTransform& tf)
{
tf::TransformListener tf_listener;
ros::Time t = ros::Time::now();
try
{
tf_listener.waitForTransform(
target_frame, source_frame, t, ros::Duration(1.0));
tf_listener.lookupTransform (
target_frame, source_frame, t, tf);
}
catch (tf::TransformException ex)
{
ROS_WARN("Could not get initial transform from base to laser frame, %s", ex.what());
tf.setIdentity();
return false;
}
return true;
}
bool getTf(const std::string& source_frame,
const std::string& target_frame,
tf::Transform& tf)
{
tf::StampedTransform stamped_tf;
bool ok = getTf(source_frame, target_frame, stamped_tf);
tf = stamped_tf;
return ok;
}
bool getTf(const tf::tfMessagePtr tf_msg,
const std::string& source_frame,
const std::string& target_frame,
tf::Transform& tf)
{
for (const geometry_msgs::TransformStamped& tft : tf_msg->transforms)
{
if (tft.header.frame_id.compare(source_frame) == 0)
if (tft.child_frame_id.compare(target_frame) == 0)
{
tf::transformMsgToTF(tft.transform, tf);
return true;
}
}
return false;
}
void print(const tf::Transform& tf, const std::string& h)
{
std::cout << h
<< tf.getOrigin().getX()
<< " " << tf.getOrigin().getX()
<< " " << tf::getYaw(tf.getRotation()) << std::endl;
}
} /* namespace utils */
} /* namespace laser_odometry */
<|endoftext|>
|
<commit_before>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE "test_functions"
#include <boost/test/unit_test.hpp>
#include "core/minimize.h"
#include "math/random.hpp"
#include "math/epsilon.hpp"
#include "func/function_trid.h"
#include "func/function_beale.h"
#include "func/function_booth.h"
#include "func/function_sphere.h"
#include "func/function_matyas.h"
#include "func/function_powell.h"
#include "func/function_mccormick.h"
#include "func/function_himmelblau.h"
#include "func/function_rosenbrock.h"
#include "func/function_3hump_camel.h"
#include "func/function_sum_squares.h"
#include "func/function_dixon_price.h"
#include "func/function_goldstein_price.h"
#include "func/function_rotated_ellipsoid.h"
namespace test
{
using namespace ncv;
static void check_function(const std::vector<test::function_t>& funcs)
{
BOOST_CHECK_EQUAL(funcs.empty(), false);
for (const test::function_t& func : funcs)
{
const auto& fn_size = func.m_opsize;
const auto& fn_fval = func.m_opfval;
const auto& fn_grad = func.m_opgrad;
const size_t trials = 1024;
const size_t dims = fn_size();
BOOST_CHECK_GT(dims, 0);
for (size_t t = 0; t < trials; t ++)
{
random_t<scalar_t> rgen(-1.0, +1.0);
vector_t x0(dims);
rgen(x0.data(), x0.data() + x0.size());
// check gradient
const opt_problem_t problem(fn_size, fn_fval, fn_grad);
BOOST_CHECK_LE(problem.grad_accuracy(x0), math::epsilon2<scalar_t>());
}
}
}
}
BOOST_AUTO_TEST_CASE(test_functions)
{
test::check_function(ncv::make_beale_funcs());
test::check_function(ncv::make_booth_funcs());
test::check_function(ncv::make_matyas_funcs());
test::check_function(ncv::make_trid_funcs(32));
test::check_function(ncv::make_sphere_funcs(8));
test::check_function(ncv::make_powell_funcs(32));
test::check_function(ncv::make_mccormick_funcs());
test::check_function(ncv::make_himmelblau_funcs());
test::check_function(ncv::make_rosenbrock_funcs(7));
test::check_function(ncv::make_3hump_camel_funcs());
test::check_function(ncv::make_dixon_price_funcs(32));
test::check_function(ncv::make_sum_squares_funcs(32));
test::check_function(ncv::make_goldstein_price_funcs());
test::check_function(ncv::make_rotated_ellipsoid_funcs(32));
}
<commit_msg>check problem size too<commit_after>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE "test_functions"
#include <boost/test/unit_test.hpp>
#include "core/minimize.h"
#include "math/random.hpp"
#include "math/epsilon.hpp"
#include "func/function_trid.h"
#include "func/function_beale.h"
#include "func/function_booth.h"
#include "func/function_sphere.h"
#include "func/function_matyas.h"
#include "func/function_powell.h"
#include "func/function_mccormick.h"
#include "func/function_himmelblau.h"
#include "func/function_rosenbrock.h"
#include "func/function_3hump_camel.h"
#include "func/function_sum_squares.h"
#include "func/function_dixon_price.h"
#include "func/function_goldstein_price.h"
#include "func/function_rotated_ellipsoid.h"
namespace test
{
using namespace ncv;
static void check_function(const std::vector<test::function_t>& funcs)
{
BOOST_CHECK_EQUAL(funcs.empty(), false);
for (const test::function_t& func : funcs)
{
const auto& fn_size = func.m_opsize;
const auto& fn_fval = func.m_opfval;
const auto& fn_grad = func.m_opgrad;
const size_t trials = 1024;
const size_t dims = fn_size();
BOOST_CHECK_GT(dims, 0);
for (size_t t = 0; t < trials; t ++)
{
random_t<scalar_t> rgen(-1.0, +1.0);
vector_t x0(dims);
rgen(x0.data(), x0.data() + x0.size());
// check gradient
const opt_problem_t problem(fn_size, fn_fval, fn_grad);
BOOST_CHECK_EQUAL(problem.size(), dims);
BOOST_CHECK_LE(problem.grad_accuracy(x0), math::epsilon2<scalar_t>());
}
}
}
}
BOOST_AUTO_TEST_CASE(test_functions)
{
test::check_function(ncv::make_beale_funcs());
test::check_function(ncv::make_booth_funcs());
test::check_function(ncv::make_matyas_funcs());
test::check_function(ncv::make_trid_funcs(32));
test::check_function(ncv::make_sphere_funcs(8));
test::check_function(ncv::make_powell_funcs(32));
test::check_function(ncv::make_mccormick_funcs());
test::check_function(ncv::make_himmelblau_funcs());
test::check_function(ncv::make_rosenbrock_funcs(7));
test::check_function(ncv::make_3hump_camel_funcs());
test::check_function(ncv::make_dixon_price_funcs(32));
test::check_function(ncv::make_sum_squares_funcs(32));
test::check_function(ncv::make_goldstein_price_funcs());
test::check_function(ncv::make_rotated_ellipsoid_funcs(32));
}
<|endoftext|>
|
<commit_before>/*
This is just a fast checksum to replace the old CRC32, nothing much here.
It hashes 4x4 (16) bytes at a time then merges them at the end.
*/
#include "checksum.hpp"
inline unsigned int Checksum::Load32(unsigned char *p)
{
return (p[0] << 24 | p[1] << 16 | p[2] << 8 | p[3]); // Endian safe
}
unsigned int Checksum::IntegrityCheck(Buffer Input)
{
unsigned char *p = Input.block;
size_t size = *Input.size;
unsigned int Prime = 0x9E3779B1;
unsigned int State = 0U;
unsigned int S[4] = {0U};
unsigned int j = 0;
while((j+16) < size)
{
S[0] ^= (Load32(&p[j+0]) + 1) * Prime;
S[1] ^= (Load32(&p[j+4]) + 1) * Prime;
S[2] ^= (Load32(&p[j+8]) + 1) * Prime;
S[3] ^= (Load32(&p[j+12]) + 1) * Prime;
j+=16;
}
while(j < size)
{
S[0] ^= (p[j] + 1) * Prime;
j++;
}
State = S[0] ^ S[1] ^ S[2] ^ S[3];
return State;
}
<commit_msg>Delete checksum.cpp<commit_after><|endoftext|>
|
<commit_before>//
// Fio.cpp
//
// Created by Jan Sten Adamek && Vojtech Micka on 2.10.13.
// Copyright (c) 2013 All rights reserved.
//
#include "Fio.h"
#include <unistd.h>
#include <memory.h>
Fio::Fio(int fileDescriptor):_fileDescriptor(fileDescriptor),_ptr(_buffer + B_SIZE),_gcount(0),_fileFinish(false),_finish(false) {
_readToBuffer();
}
Fio::~Fio() {
}
void Fio::_readToBuffer() {
ssize_t left = _buffer + B_SIZE - _ptr;
if (left > 0) {
memcpy(_buffer, _ptr, left);
}
_gcount = read(_fileDescriptor, _buffer + left, B_SIZE - left) + left;
_ptr = _buffer;
_buffer[_gcount] = 0;
if (_gcount < B_SIZE) {
_fileFinish = true;
}
}
long Fio::_parseLong(char *&ptr) {
register long n(0);
register char ch;
do {
ch = *ptr;
if (ch == 0) return 0;
++ptr;
} while (ch < '0' || ch > '9');
do {
n = (ch & 0x0f) + n * 10;
ch = *ptr;
++ptr;
} while (ch >= '0' && ch <= '9');
return n;
}
int Fio::nextInt() {
return (int) nextLong();
}
long Fio::nextLong() {
char * tPtr = _ptr;
long num = _parseLong(tPtr);
if (tPtr >= _buffer + _gcount) {
if (_fileFinish)
{
_finish = true;
return 0;
}
_readToBuffer();
num = _parseLong(tPtr);
}
_ptr = tPtr;
return num;
}<commit_msg>Bugfixs.<commit_after>//
// Fio.cpp
//
// Created by Jan Sten Adamek && Vojtech Micka on 2.10.13.
// Copyright (c) 2013 All rights reserved.
//
#include "Fio.h"
#include <unistd.h>
#include <memory.h>
Fio::Fio(int fileDescriptor):
_fileDescriptor(fileDescriptor),
_ptr(_buffer + B_SIZE),
_gcount(0),
_fileFinish(false),
_finish(false) {
_readToBuffer();
}
Fio::~Fio() {
}
void Fio::_readToBuffer() {
ssize_t left = _buffer + B_SIZE - _ptr;
if (left > 0) {
memcpy(_buffer, _ptr, left);
} else {
left = 0;
}
_gcount = read(_fileDescriptor, _buffer + left, B_SIZE - left) + left;
_ptr = _buffer;
_buffer[_gcount] = 0;
if (_gcount < B_SIZE) {
_fileFinish = true;
}
}
long Fio::_parseLong(char *&ptr) {
register long n(0);
register char ch;
do {
ch = *ptr;
if (ch == 0) return 0;
++ptr;
} while (ch < '0' || ch > '9');
do {
n = (ch & 0x0f) + n * 10;
ch = *ptr;
++ptr;
} while (ch >= '0' && ch <= '9');
return n;
}
int Fio::nextInt() {
return (int) nextLong();
}
long Fio::nextLong() {
char * tPtr = _ptr;
long num = _parseLong(tPtr);
if (tPtr >= _buffer + _gcount) {
if (_fileFinish)
{
_finish = true;
return num;
}
_readToBuffer();
tPtr = _ptr;
num = _parseLong(tPtr);
}
_ptr = tPtr;
return num;
}<|endoftext|>
|
<commit_before>/**
** \file scheduler/scheduler.hh
** \brief Definition of scheduler::Scheduler.
*/
#ifndef SCHEDULER_SCHEDULER_HH
# define SCHEDULER_SCHEDULER_HH
# include <queue>
# include <boost/tuple/tuple.hpp>
# include <boost/utility.hpp>
# include <libport/utime.hh>
# include "scheduler/fwd.hh"
# include "scheduler/libcoroutine/Coro.h"
namespace scheduler
{
typedef boost::tuple<libport::utime_t, Job*> deferred_job;
bool operator> (const deferred_job&, const deferred_job&);
class Scheduler : boost::noncopyable
{
public:
Scheduler ();
~Scheduler ();
public:
// Do one cycle of work, and return the next time we expect to be called.
// If we have work to do, 0 will be returned in order to be called again
// as soon as possible. If we only have time-suspended or dependent
// jobs, we will return the time of the next scheduled one. In short,
// calling work() again before the returned time is useless as there will
// be nothing to do except if some new work has been entered in.
libport::utime_t work ();
// Add a job to the list of jobs to be run later. Jobs will be started
// at the next cycle by the scheduler.
void add_job (Job* job);
/// Remove all jobs but the caller one. It will have to terminate
/// after that.
void killall_jobs ();
/// Kill a job, and delete it. It is not allowed to kill the currently
/// executing job as it will do very bad things.
void kill_job (Job* job);
/// Resume scheduler execution. Must be called from the job being
/// interrupted with itself as argument.
void resume_scheduler (Job* job);
/// Ditto, but put the job at the front of the run queue.
void resume_scheduler_front (Job* job);
/// Ditto, but put the job in the deferred run queue until the deadline
/// is reached.
void resume_scheduler_until (Job* job, libport::utime_t deadline);
/// Suspend the current job.
void resume_scheduler_suspend (Job* job);
/// Resume a job that has been previously suspended and add it at
/// the back of the run queue.
void resume_job (Job* job);
/// Return the currently executing job
Job& current_job ();
private:
void switch_back (Job* job);
private:
typedef std::priority_queue
<deferred_job, std::vector<deferred_job>, std::greater<deferred_job> >
deferred_jobs;
/// Regular jobs to schedule inconditionally during the next run
jobs jobs_;
/// Jobs registered for initialization but not yet started
jobs jobs_to_start_;
/// Deferred jobs
deferred_jobs deferred_jobs_;
/// Suspended jobs
jobs suspended_jobs_;
/// Current job
Job* current_job_;
/// Coroutine support
Coro* self_;
};
} // namespace scheduler
# include "scheduler.hxx"
#endif // !SCHEDULER_SCHEDULER_HH
<commit_msg>Use /// for Doxygen to pick the description<commit_after>/**
** \file scheduler/scheduler.hh
** \brief Definition of scheduler::Scheduler.
*/
#ifndef SCHEDULER_SCHEDULER_HH
# define SCHEDULER_SCHEDULER_HH
# include <queue>
# include <boost/tuple/tuple.hpp>
# include <boost/utility.hpp>
# include <libport/utime.hh>
# include "scheduler/fwd.hh"
# include "scheduler/libcoroutine/Coro.h"
namespace scheduler
{
typedef boost::tuple<libport::utime_t, Job*> deferred_job;
bool operator> (const deferred_job&, const deferred_job&);
class Scheduler : boost::noncopyable
{
public:
Scheduler ();
~Scheduler ();
public:
/// Do one cycle of work, and return the next time we expect to be called.
/// If we have work to do, 0 will be returned in order to be called again
/// as soon as possible. If we only have time-suspended or dependent
/// jobs, we will return the time of the next scheduled one. In short,
/// calling work() again before the returned time is useless as there will
/// be nothing to do except if some new work has been entered in.
libport::utime_t work ();
/// Add \a job to the list of jobs to be run later. Jobs will be started
/// at the next cycle by the scheduler.
void add_job (Job* job);
/// Remove all jobs but the caller one. It will have to terminate
/// after that.
void killall_jobs ();
/// Kill \a job, and delete it. It is not allowed to kill the currently
/// executing job as it will do very bad things.
void kill_job (Job* job);
/// Resume scheduler execution. Must be called from the job being
/// interrupted with itself as argument.
void resume_scheduler (Job* job);
/// Ditto, but put the job at the front of the run queue.
void resume_scheduler_front (Job* job);
/// Ditto, but put the job in the deferred run queue until the deadline
/// is reached.
void resume_scheduler_until (Job* job, libport::utime_t deadline);
/// Suspend the current job.
void resume_scheduler_suspend (Job* job);
/// Resume a job that has been previously suspended and add it at
/// the back of the run queue.
void resume_job (Job* job);
/// Return the currently executing job
Job& current_job ();
private:
void switch_back (Job* job);
private:
typedef std::priority_queue
<deferred_job, std::vector<deferred_job>, std::greater<deferred_job> >
deferred_jobs;
/// Regular jobs to schedule inconditionally during the next run
jobs jobs_;
/// Jobs registered for initialization but not yet started
jobs jobs_to_start_;
/// Deferred jobs
deferred_jobs deferred_jobs_;
/// Suspended jobs
jobs suspended_jobs_;
/// Current job
Job* current_job_;
/// Coroutine support
Coro* self_;
};
} // namespace scheduler
# include "scheduler.hxx"
#endif // !SCHEDULER_SCHEDULER_HH
<|endoftext|>
|
<commit_before>#include "Chemharp.hpp"
#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
#include <boost/numpy.hpp>
namespace py = boost::python;
namespace np = boost::numpy;
using namespace harp;
void translate_Error(Error const& e) {
auto err = std::string("Chemharp error: ") + e.what();
PyErr_SetString(PyExc_UserWarning, err.c_str());
}
void translate_FileError(FileError const& e) {
auto err = std::string("Chemharp file error: ") + e.what();
PyErr_SetString(PyExc_UserWarning, err.c_str());
}
void translate_MemoryError(MemoryError const& e) {
auto err = std::string("Chemharp memory error: ") + e.what();
PyErr_SetString(PyExc_UserWarning, err.c_str());
}
void translate_FormatError(FormatError const& e) {
auto err = std::string("Chemharp format error: ") + e.what();
PyErr_SetString(PyExc_UserWarning, err.c_str());
}
// ResultConverterGenerator used to transform Array3D to numpy ndarray.
struct Array3D_convertor {
template <class T> struct apply {
struct type {
// Convert Array3D to ndarray.
PyObject* operator()(const Array3D& A) const {
py::tuple shape = py::make_tuple(A.size(), 3);
np::dtype dtype = np::dtype::get_builtin<float>();
np::ndarray res = np::empty(shape, dtype);
auto c_arr = reinterpret_cast<float (*)[3]>(res.get_data());
for (size_t i=0; i<A.size(); i++)
for (size_t j=0; j<3; j++)
c_arr[i][j] = A[i][j];
return py::incref(res.ptr());
}
// Used for documentation.
const PyTypeObject* get_pytype() const { return 0; }
};
};
};
struct std_vector_convertor {
template <class T> struct apply {
struct type {
// Convert any std::vector to python list.
template <class S>
PyObject* operator()(const std::vector<S>& A) const {
py::list res;
for (auto val : A)
res.append(val);
return py::incref(res.ptr());
}
// Used for documentation.
const PyTypeObject* get_pytype() const { return 0; }
};
};
};
void init_module(){
// Removing this line will result in bad stuff appening, like segfaults and
// your grand mother being kidnaped by aliens. So don't do this!
np::initialize();
}
BOOST_PYTHON_MODULE(chemharp){
init_module();
/* Exception management ***************************************************/
py::register_exception_translator<Error>(&translate_Error);
py::register_exception_translator<FileError>(&translate_FileError);
py::register_exception_translator<MemoryError>(&translate_MemoryError);
py::register_exception_translator<FormatError>(&translate_FormatError);
/* Trajectory class *******************************************************/
py::class_<Trajectory, boost::noncopyable>("Trajectory",
py::init<std::string, py::optional<std::string, std::string>>())
.def("read_next_step", &Trajectory::read_next_step,
py::return_internal_reference<1,
py::with_custodian_and_ward_postcall<0, 1> >())
.def("read_at_step", &Trajectory::read_at_step,
py::return_internal_reference<1,
py::with_custodian_and_ward_postcall<0, 1> >())
.def("write_step", &Trajectory::write_step)
;
/* Frame class ************************************************************/
py::class_<Frame>("Frame")
.def("positions",
static_cast<const Array3D& (Frame::*)(void) const>(&Frame::positions),
py::return_value_policy<Array3D_convertor>())
.def("velocities",
static_cast<const Array3D& (Frame::*)(void) const>(&Frame::velocities),
py::return_value_policy<Array3D_convertor>())
.def("has_velocities", &Frame::has_velocities)
.def("__len__", &Frame::natoms)
.add_property("natoms", &Frame::natoms)
.add_property("topology",
py::make_function(
static_cast<const Topology& (Frame::*)(void) const>(&Frame::topology),
py::return_value_policy<py::copy_const_reference>()),
static_cast<void (Frame::*)(const Topology&)>(&Frame::topology))
.add_property("cell",
py::make_function(
static_cast<const UnitCell& (Frame::*)(void) const>(&Frame::cell),
py::return_value_policy<py::copy_const_reference>()),
static_cast<void (Frame::*)(const UnitCell&)>(&Frame::cell))
.add_property("step",
static_cast<size_t (Frame::*)(void) const>(&Frame::step),
static_cast<void (Frame::*)(size_t)>(&Frame::step))
;
/* Atom class *************************************************************/
py::scope atom_scope = py::class_<Atom>("Atom", py::init<std::string>())
.add_property("name",
py::make_function(
static_cast<const std::string& (Atom::*)(void) const>(&Atom::name),
py::return_value_policy<py::copy_const_reference>()),
static_cast<void (Atom::*)(const std::string&)>(&Atom::name))
.add_property("mass",
py::make_function(
static_cast<const float& (Atom::*)(void) const>(&Atom::mass),
py::return_value_policy<py::copy_const_reference>()),
static_cast<void (Atom::*)(float)>(&Atom::mass))
.add_property("charge",
py::make_function(
static_cast<const float& (Atom::*)(void) const>(&Atom::charge),
py::return_value_policy<py::copy_const_reference>()),
static_cast<void (Atom::*)(float)>(&Atom::charge))
.add_property("type",
py::make_function(
static_cast<const Atom::AtomType& (Atom::*)(void) const>(&Atom::type),
py::return_value_policy<py::copy_const_reference>()),
static_cast<void (Atom::*)(Atom::AtomType)>(&Atom::type))
;
/* AtomType enum **********************************************************/
py::enum_<Atom::AtomType>("AtomType")
.value("ELEMENT", Atom::ELEMENT)
.value("CORSE_GRAIN", Atom::CORSE_GRAIN)
.value("DUMMY", Atom::DUMMY)
.value("UNDEFINED", Atom::UNDEFINED)
;
/* Topology class *********************************************************/
py::class_<Topology>("Topology")
.def("append", &Topology::append)
.def("add_bond", &Topology::add_bond)
.def("__len__", &Topology::natoms)
.add_property("natoms", &Topology::natoms)
.add_property("natom_types", &Topology::natom_types)
.def("clear", &Topology::clear)
.def("resize", &Topology::resize)
/* TODO:
operator[]
void guess_bonds();
vector<bond> bonds(void);
vector<angle> angles(void);
vector<dihedral> dihedrals(void);
*/
;
/* UnitCell class *********************************************************/
py::class_<UnitCell>("UnitCell", py::init<>())
.def(py::init<double>())
.def(py::init<double, double, double>())
.def(py::init<double, double, double, double, double, double>())
.def(py::init<UnitCell::CellType>())
.def(py::init<UnitCell::CellType, double>())
.def(py::init<UnitCell::CellType, double, double, double>())
// TODO Matrix3D matricial() const;
.add_property("type",
py::make_function(
static_cast<const UnitCell::CellType& (UnitCell::*)(void) const>(&UnitCell::type),
py::return_value_policy<py::copy_const_reference>()),
static_cast<void (UnitCell::*)(UnitCell::CellType)>(&UnitCell::type))
.add_property("a",
static_cast<double (UnitCell::*)(void) const>(&UnitCell::a),
static_cast<void (UnitCell::*)(double)>(&UnitCell::a))
.add_property("b",
static_cast<double (UnitCell::*)(void) const>(&UnitCell::b),
static_cast<void (UnitCell::*)(double)>(&UnitCell::b))
.add_property("c",
static_cast<double (UnitCell::*)(void) const>(&UnitCell::c),
static_cast<void (UnitCell::*)(double)>(&UnitCell::c))
.add_property("alpha",
static_cast<double (UnitCell::*)(void) const>(&UnitCell::alpha),
static_cast<void (UnitCell::*)(double)>(&UnitCell::alpha))
.add_property("beta",
static_cast<double (UnitCell::*)(void) const>(&UnitCell::beta),
static_cast<void (UnitCell::*)(double)>(&UnitCell::beta))
.add_property("gamma",
static_cast<double (UnitCell::*)(void) const>(&UnitCell::gamma),
static_cast<void (UnitCell::*)(double)>(&UnitCell::gamma))
.add_property("periodic_x",
static_cast<bool (UnitCell::*)(void) const>(&UnitCell::periodic_x),
static_cast<void (UnitCell::*)(bool)>(&UnitCell::periodic_x))
.add_property("periodic_y",
static_cast<bool (UnitCell::*)(void) const>(&UnitCell::periodic_y),
static_cast<void (UnitCell::*)(bool)>(&UnitCell::periodic_y))
.add_property("periodic_z",
static_cast<bool (UnitCell::*)(void) const>(&UnitCell::periodic_z),
static_cast<void (UnitCell::*)(bool)>(&UnitCell::periodic_z))
.add_property("full_periodic",
static_cast<bool (UnitCell::*)(void) const>(&UnitCell::full_periodic),
static_cast<void (UnitCell::*)(bool)>(&UnitCell::full_periodic))
;
/* CellType enum **********************************************************/
py::enum_<UnitCell::CellType>("CellType")
.value("ORTHOROMBIC", UnitCell::ORTHOROMBIC)
.value("TRICLINIC", UnitCell::TRICLINIC)
.value("INFINITE", UnitCell::INFINITE)
;
// TODO: Logger class
}
<commit_msg>[doc] Document the Python API<commit_after>#include "Chemharp.hpp"
#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
#include <boost/numpy.hpp>
namespace py = boost::python;
namespace np = boost::numpy;
using namespace harp;
void translate_Error(Error const& e) {
auto err = std::string("Chemharp error: ") + e.what();
PyErr_SetString(PyExc_UserWarning, err.c_str());
}
void translate_FileError(FileError const& e) {
auto err = std::string("Chemharp file error: ") + e.what();
PyErr_SetString(PyExc_UserWarning, err.c_str());
}
void translate_MemoryError(MemoryError const& e) {
auto err = std::string("Chemharp memory error: ") + e.what();
PyErr_SetString(PyExc_UserWarning, err.c_str());
}
void translate_FormatError(FormatError const& e) {
auto err = std::string("Chemharp format error: ") + e.what();
PyErr_SetString(PyExc_UserWarning, err.c_str());
}
// ResultConverterGenerator used to transform Array3D to numpy ndarray.
struct Array3D_convertor {
template <class T> struct apply {
struct type {
// Convert Array3D to ndarray.
PyObject* operator()(const Array3D& A) const {
py::tuple shape = py::make_tuple(A.size(), 3);
np::dtype dtype = np::dtype::get_builtin<float>();
np::ndarray res = np::empty(shape, dtype);
auto c_arr = reinterpret_cast<float (*)[3]>(res.get_data());
for (size_t i=0; i<A.size(); i++)
for (size_t j=0; j<3; j++)
c_arr[i][j] = A[i][j];
return py::incref(res.ptr());
}
// Used for documentation.
const PyTypeObject* get_pytype() const { return 0; }
};
};
};
struct std_vector_convertor {
template <class T> struct apply {
struct type {
// Convert any std::vector to python list.
template <class S>
PyObject* operator()(const std::vector<S>& A) const {
py::list res;
for (auto val : A)
res.append(val);
return py::incref(res.ptr());
}
// Used for documentation.
const PyTypeObject* get_pytype() const { return 0; }
};
};
};
void init_module(){
// Removing this line will result in bad stuff appening, like segfaults and
// your grand mother being kidnaped by aliens. So don't do this!
np::initialize();
}
BOOST_PYTHON_MODULE(chemharp){
init_module();
/* Exception management ***************************************************/
py::register_exception_translator<Error>(&translate_Error);
py::register_exception_translator<FileError>(&translate_FileError);
py::register_exception_translator<MemoryError>(&translate_MemoryError);
py::register_exception_translator<FormatError>(&translate_FormatError);
/* Trajectory class *******************************************************/
py::class_<Trajectory, boost::noncopyable>("Trajectory",
py::init<std::string, py::optional<std::string, std::string>>())
.def("read_next_step", &Trajectory::read_next_step,
py::return_internal_reference<1,
py::with_custodian_and_ward_postcall<0, 1> >())
.def("read_at_step", &Trajectory::read_at_step,
py::return_internal_reference<1,
py::with_custodian_and_ward_postcall<0, 1> >())
.def("write_step", &Trajectory::write_step)
;
/* Frame class ************************************************************/
py::class_<Frame>("Frame")
.def("positions",
static_cast<const Array3D& (Frame::*)(void) const>(&Frame::positions),
py::return_value_policy<Array3D_convertor>())
.def("velocities",
static_cast<const Array3D& (Frame::*)(void) const>(&Frame::velocities),
py::return_value_policy<Array3D_convertor>())
.add_property("has_velocities", &Frame::has_velocities)
.def("__len__", &Frame::natoms)
.add_property("natoms", &Frame::natoms)
.add_property("topology",
py::make_function(
static_cast<const Topology& (Frame::*)(void) const>(&Frame::topology),
py::return_value_policy<py::copy_const_reference>()),
static_cast<void (Frame::*)(const Topology&)>(&Frame::topology))
.add_property("cell",
py::make_function(
static_cast<const UnitCell& (Frame::*)(void) const>(&Frame::cell),
py::return_value_policy<py::copy_const_reference>()),
static_cast<void (Frame::*)(const UnitCell&)>(&Frame::cell))
.add_property("step",
static_cast<size_t (Frame::*)(void) const>(&Frame::step),
static_cast<void (Frame::*)(size_t)>(&Frame::step))
;
/* Atom class *************************************************************/
py::scope atom_scope = py::class_<Atom>("Atom", py::init<std::string>())
.add_property("name",
py::make_function(
static_cast<const std::string& (Atom::*)(void) const>(&Atom::name),
py::return_value_policy<py::copy_const_reference>()),
static_cast<void (Atom::*)(const std::string&)>(&Atom::name))
.add_property("mass",
py::make_function(
static_cast<const float& (Atom::*)(void) const>(&Atom::mass),
py::return_value_policy<py::copy_const_reference>()),
static_cast<void (Atom::*)(float)>(&Atom::mass))
.add_property("charge",
py::make_function(
static_cast<const float& (Atom::*)(void) const>(&Atom::charge),
py::return_value_policy<py::copy_const_reference>()),
static_cast<void (Atom::*)(float)>(&Atom::charge))
.add_property("type",
py::make_function(
static_cast<const Atom::AtomType& (Atom::*)(void) const>(&Atom::type),
py::return_value_policy<py::copy_const_reference>()),
static_cast<void (Atom::*)(Atom::AtomType)>(&Atom::type))
;
/* AtomType enum **********************************************************/
py::enum_<Atom::AtomType>("AtomType")
.value("ELEMENT", Atom::ELEMENT)
.value("CORSE_GRAIN", Atom::CORSE_GRAIN)
.value("DUMMY", Atom::DUMMY)
.value("UNDEFINED", Atom::UNDEFINED)
;
/* Topology class *********************************************************/
py::class_<Topology>("Topology")
.def("append", &Topology::append)
.def("add_bond", &Topology::add_bond)
.def("__len__", &Topology::natoms)
.add_property("natoms", &Topology::natoms)
.add_property("natom_types", &Topology::natom_types)
.def("clear", &Topology::clear)
.def("resize", &Topology::resize)
/* TODO:
operator[]
void guess_bonds();
vector<bond> bonds(void);
vector<angle> angles(void);
vector<dihedral> dihedrals(void);
isbond,
isangle,
isdihedral,
constuctor
*/
;
/* UnitCell class *********************************************************/
py::class_<UnitCell>("UnitCell", py::init<>())
.def(py::init<double>())
.def(py::init<double, double, double>())
.def(py::init<double, double, double, double, double, double>())
.def(py::init<UnitCell::CellType>())
.def(py::init<UnitCell::CellType, double>())
.def(py::init<UnitCell::CellType, double, double, double>())
// TODO Matrix3D matricial() const;
.add_property("type",
py::make_function(
static_cast<const UnitCell::CellType& (UnitCell::*)(void) const>(&UnitCell::type),
py::return_value_policy<py::copy_const_reference>()),
static_cast<void (UnitCell::*)(UnitCell::CellType)>(&UnitCell::type))
.add_property("a",
static_cast<double (UnitCell::*)(void) const>(&UnitCell::a),
static_cast<void (UnitCell::*)(double)>(&UnitCell::a))
.add_property("b",
static_cast<double (UnitCell::*)(void) const>(&UnitCell::b),
static_cast<void (UnitCell::*)(double)>(&UnitCell::b))
.add_property("c",
static_cast<double (UnitCell::*)(void) const>(&UnitCell::c),
static_cast<void (UnitCell::*)(double)>(&UnitCell::c))
.add_property("alpha",
static_cast<double (UnitCell::*)(void) const>(&UnitCell::alpha),
static_cast<void (UnitCell::*)(double)>(&UnitCell::alpha))
.add_property("beta",
static_cast<double (UnitCell::*)(void) const>(&UnitCell::beta),
static_cast<void (UnitCell::*)(double)>(&UnitCell::beta))
.add_property("gamma",
static_cast<double (UnitCell::*)(void) const>(&UnitCell::gamma),
static_cast<void (UnitCell::*)(double)>(&UnitCell::gamma))
.add_property("periodic_x",
static_cast<bool (UnitCell::*)(void) const>(&UnitCell::periodic_x),
static_cast<void (UnitCell::*)(bool)>(&UnitCell::periodic_x))
.add_property("periodic_y",
static_cast<bool (UnitCell::*)(void) const>(&UnitCell::periodic_y),
static_cast<void (UnitCell::*)(bool)>(&UnitCell::periodic_y))
.add_property("periodic_z",
static_cast<bool (UnitCell::*)(void) const>(&UnitCell::periodic_z),
static_cast<void (UnitCell::*)(bool)>(&UnitCell::periodic_z))
.add_property("full_periodic",
static_cast<bool (UnitCell::*)(void) const>(&UnitCell::full_periodic),
static_cast<void (UnitCell::*)(bool)>(&UnitCell::full_periodic))
;
/* CellType enum **********************************************************/
py::enum_<UnitCell::CellType>("CellType")
.value("ORTHOROMBIC", UnitCell::ORTHOROMBIC)
.value("TRICLINIC", UnitCell::TRICLINIC)
.value("INFINITE", UnitCell::INFINITE)
;
// TODO: Logger class
}
<|endoftext|>
|
<commit_before>#ifndef __RWI_LOCK_HPP__
#define __RWI_LOCK_HPP__
#include "errors.hpp"
#include <boost/function.hpp>
#include "containers/intrusive_list.hpp"
#include "concurrency/access.hpp"
// Forward declarations
struct rwi_lock_t;
struct lock_request_t;
/**
* Callback class used to notify lock clients that they now have the
* lock.
*/
struct lock_available_callback_t {
public:
virtual ~lock_available_callback_t() {}
virtual void on_lock_available() = 0;
};
/**
* Read/write/intent lock allows locking a resource for reading,
* reading with the intent to potentially upgrade to write, and
* writing. This is useful in a btree setting, where something might
* be locked with.
*/
struct rwi_lock_t {
public:
// Note, the receiver of lock_request_t completion notifications
// is responsible for freeing associated memory by calling delete.
rwi_lock_t()
: state(rwis_unlocked), nreaders(0)
{}
// Call to lock for read, write, intent, or upgrade intent to write
bool lock(access_t access, lock_available_callback_t *callback);
// Like `lock()` but blocks; only legal in a coroutine. If `call_when_in_line` is not zero,
// it will be called as soon as `co_lock()` has gotten in line for the lock but before
// `co_lock()` actually returns.
void co_lock(access_t access, boost::function<void()> call_when_in_line = 0);
// Call if you've locked for read or write, or upgraded to write,
// and are now unlocking.
void unlock();
// Call if you've locked for intent before, didn't upgrade to
// write, and are now unlocking.
void unlock_intent();
// Returns true if the lock is locked in any form, but doesn't acquire the lock. (In the buffer
// cache, this is used by the page replacement algorithm to see whether the buffer is in use.)
bool locked();
struct read_acq_t {
read_acq_t() : lock(NULL) { }
read_acq_t(rwi_lock_t *l) : lock(l) {
lock->co_lock(rwi_read);
}
void reset() {
if (lock) {
lock->unlock();
lock = NULL;
}
}
void assert_is_holding(UNUSED rwi_lock_t *l) {
rassert(lock == l);
}
~read_acq_t() {
reset();
}
private:
friend void swap(read_acq_t &, read_acq_t &);
rwi_lock_t *lock;
DISABLE_COPYING(read_acq_t);
};
struct write_acq_t {
write_acq_t() : lock(NULL) { }
write_acq_t(rwi_lock_t *l) : lock(l) {
lock->co_lock(rwi_write);
}
void reset() {
if (lock) {
lock->unlock();
lock = NULL;
}
}
void assert_is_holding(UNUSED rwi_lock_t *l) {
rassert(lock == l);
}
~write_acq_t() {
reset();
}
private:
friend void swap(write_acq_t &, write_acq_t &);
rwi_lock_t *lock;
DISABLE_COPYING(write_acq_t);
};
private:
enum rwi_state {
rwis_unlocked,
rwis_reading,
rwis_writing,
rwis_reading_with_intent
};
typedef intrusive_list_t<lock_request_t> request_list_t;
bool try_lock(access_t access, bool from_queue);
bool try_lock_read(bool from_queue);
bool try_lock_write(bool from_queue);
bool try_lock_intent(bool from_queue);
bool try_lock_upgrade(bool from_queue);
void enqueue_request(access_t access, lock_available_callback_t *callback);
void process_queue();
rwi_state state;
int nreaders; // not counting reader with intent
request_list_t queue;
};
inline void swap(rwi_lock_t::read_acq_t &a1, rwi_lock_t::read_acq_t &a2) {
std::swap(a1.lock, a2.lock);
}
inline void swap(rwi_lock_t::write_acq_t &a1, rwi_lock_t::write_acq_t &a2) {
std::swap(a1.lock, a2.lock);
}
#endif // __RWI_LOCK_HPP__
<commit_msg>Add warning message.<commit_after>#ifndef __RWI_LOCK_HPP__
#define __RWI_LOCK_HPP__
#include "errors.hpp"
#include <boost/function.hpp>
#include "containers/intrusive_list.hpp"
#include "concurrency/access.hpp"
// Forward declarations
struct rwi_lock_t;
struct lock_request_t;
/**
* Callback class used to notify lock clients that they now have the
* lock.
*/
struct lock_available_callback_t {
public:
virtual ~lock_available_callback_t() {}
virtual void on_lock_available() = 0;
};
/**
* Read/write/intent lock allows locking a resource for reading,
* reading with the intent to potentially upgrade to write, and
* writing. This is useful in a btree setting, where something might
* be locked with.
*/
struct rwi_lock_t {
public:
// Note, the receiver of lock_request_t completion notifications
// is responsible for freeing associated memory by calling delete.
rwi_lock_t()
: state(rwis_unlocked), nreaders(0)
{}
// Call to lock for read, write, intent, or upgrade intent to write
bool lock(access_t access, lock_available_callback_t *callback);
// Like `lock()` but blocks; only legal in a coroutine. If `call_when_in_line` is not zero,
// it will be called as soon as `co_lock()` has gotten in line for the lock but before
// `co_lock()` actually returns.
// You are encouraged to use `read_acq_t` and `write_acq_t` instead of
// `co_lock()`.
void co_lock(access_t access, boost::function<void()> call_when_in_line = 0);
// Call if you've locked for read or write, or upgraded to write,
// and are now unlocking.
void unlock();
// Call if you've locked for intent before, didn't upgrade to
// write, and are now unlocking.
void unlock_intent();
// Returns true if the lock is locked in any form, but doesn't acquire the lock. (In the buffer
// cache, this is used by the page replacement algorithm to see whether the buffer is in use.)
bool locked();
struct read_acq_t {
read_acq_t() : lock(NULL) { }
read_acq_t(rwi_lock_t *l) : lock(l) {
lock->co_lock(rwi_read);
}
void reset() {
if (lock) {
lock->unlock();
lock = NULL;
}
}
void assert_is_holding(UNUSED rwi_lock_t *l) {
rassert(lock == l);
}
~read_acq_t() {
reset();
}
private:
friend void swap(read_acq_t &, read_acq_t &);
rwi_lock_t *lock;
DISABLE_COPYING(read_acq_t);
};
struct write_acq_t {
write_acq_t() : lock(NULL) { }
write_acq_t(rwi_lock_t *l) : lock(l) {
lock->co_lock(rwi_write);
}
void reset() {
if (lock) {
lock->unlock();
lock = NULL;
}
}
void assert_is_holding(UNUSED rwi_lock_t *l) {
rassert(lock == l);
}
~write_acq_t() {
reset();
}
private:
friend void swap(write_acq_t &, write_acq_t &);
rwi_lock_t *lock;
DISABLE_COPYING(write_acq_t);
};
private:
enum rwi_state {
rwis_unlocked,
rwis_reading,
rwis_writing,
rwis_reading_with_intent
};
typedef intrusive_list_t<lock_request_t> request_list_t;
bool try_lock(access_t access, bool from_queue);
bool try_lock_read(bool from_queue);
bool try_lock_write(bool from_queue);
bool try_lock_intent(bool from_queue);
bool try_lock_upgrade(bool from_queue);
void enqueue_request(access_t access, lock_available_callback_t *callback);
void process_queue();
rwi_state state;
int nreaders; // not counting reader with intent
request_list_t queue;
};
inline void swap(rwi_lock_t::read_acq_t &a1, rwi_lock_t::read_acq_t &a2) {
std::swap(a1.lock, a2.lock);
}
inline void swap(rwi_lock_t::write_acq_t &a1, rwi_lock_t::write_acq_t &a2) {
std::swap(a1.lock, a2.lock);
}
#endif // __RWI_LOCK_HPP__
<|endoftext|>
|
<commit_before>/*
** Copyright 2009-2013,2015,2018 Centreon
**
** 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.
**
** For more information : contact@centreon.com
*/
#include <getopt.h>
#include <cerrno>
#include <chrono>
#include <clocale>
#include <csignal>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <thread>
#include "com/centreon/broker/brokerrpc.hh"
#include "com/centreon/broker/config/applier/init.hh"
#include "com/centreon/broker/config/applier/state.hh"
#include "com/centreon/broker/config/parser.hh"
#include "com/centreon/broker/config/state.hh"
#include "com/centreon/broker/log_v2.hh"
#include "com/centreon/broker/misc/diagnostic.hh"
using namespace com::centreon::broker;
// Main config file.
static std::vector<std::string> gl_mainconfigfiles;
static config::state gl_state;
static std::atomic_bool gl_term{false};
static struct option long_options[] = {{"pool_size", required_argument, 0, 's'},
{"check", no_argument, 0, 'c'},
{"debug", no_argument, 0, 'd'},
{"diagnose", no_argument, 0, 'D'},
{"version", no_argument, 0, 'v'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}};
/**
* Function called when updating configuration (when program receives
* SIGHUP).
*
* @param[in] signum Signal number.
*/
static void hup_handler(int signum) {
(void)signum;
// Disable SIGHUP handling during handler execution.
signal(SIGHUP, SIG_IGN);
// Log message.
log_v2::core()->info("main: configuration update requested");
try {
// Parse configuration file.
config::parser parsr;
config::state conf{parsr.parse(gl_mainconfigfiles.front())};
try {
log_v2::instance().apply(conf);
} catch (const std::exception& e) {
log_v2::core()->error(e.what());
}
try {
// Apply resulting configuration.
config::applier::state::instance().apply(conf);
gl_state = conf;
} catch (const std::exception& e) {
log_v2::core()->error(
"main: configuration update could not succeed, reloading previous "
"configuration: {}",
e.what());
config::applier::state::instance().apply(gl_state);
} catch (...) {
log_v2::core()->error(
"main: configuration update could not succeed, reloading previous "
"configuration");
config::applier::state::instance().apply(gl_state);
}
} catch (const std::exception& e) {
log_v2::config()->info("main: configuration update failed: {}", e.what());
} catch (...) {
log_v2::config()->info(
"main: configuration update failed: unknown exception");
}
// Reenable SIGHUP handler.
signal(SIGHUP, &hup_handler);
}
/**
* Function called on termination request (when program receives
* SIGTERM).
*
* @param[in] signum Unused.
* @param[in] info Signal informations.
* @param[in] data Unused.
*/
static void term_handler(int signum) {
(void)signum;
gl_term = true;
}
/**
* @brief Program entry point.
*
* main() is the first function called when the program starts.
*
* @param[in] argc Number of arguments received on the command line.
* @param[in] argv Arguments received on the command line, stored in an
* array.
*
* @return 0 on normal termination, any other value on failure.
*/
int main(int argc, char* argv[]) {
// Initialization.
int opt, option_index = 0, n_thread = 0;
std::string broker_name{"unknown"};
uint16_t default_port{51000};
// Set configuration update handler.
if (signal(SIGHUP, hup_handler) == SIG_ERR) {
char const* err{strerror(errno)};
log_v2::core()->info(
"main: could not register configuration update handler: {}", err);
}
// Init signal handler.
struct sigaction sigterm_act;
memset(&sigterm_act, 0, sizeof(sigterm_act));
sigterm_act.sa_handler = &term_handler;
// Set termination handler.
if (sigaction(SIGTERM, &sigterm_act, nullptr) < 0)
log_v2::core()->info("main: could not register termination handler");
// Return value.
int retval(0);
try {
// Check the command line.
bool check(false);
bool debug(false);
bool diagnose(false);
bool help(false);
bool version(false);
opt = getopt_long(argc, argv, "t:cdDvh", long_options, &option_index);
switch (opt) {
case 't':
n_thread = atoi(optarg);
break;
case 'c':
check = true;
break;
case 'd':
debug = true;
break;
case 'D':
diagnose = true;
break;
case 'h':
help = true;
break;
case 'v':
version = true;
break;
default:
break;
}
if (optind < argc)
while (optind < argc)
gl_mainconfigfiles.push_back(argv[optind++]);
// Check parameters requirements.
if (diagnose) {
if (gl_mainconfigfiles.empty()) {
log_v2::core()->error(
"diagnostic: no configuration file provided: DIAGNOSTIC FILE MIGHT "
"NOT BE USEFUL");
}
misc::diagnostic diag;
diag.generate(gl_mainconfigfiles);
} else if (help) {
log_v2::core()->info(
"USAGE: {} [-t] [-c] [-d] [-D] [-h] [-v] [<configfile>]", argv[0]);
log_v2::core()->info(" -t Set x threads.");
log_v2::core()->info(" -c Check configuration file.");
log_v2::core()->info(" -d Enable debug mode.");
log_v2::core()->info(" -D Generate a diagnostic file.");
log_v2::core()->info(" -h Print this help.");
log_v2::core()->info(" -v Print Centreon Broker version.");
log_v2::core()->info("Centreon Broker {}", CENTREON_BROKER_VERSION);
log_v2::core()->info("Copyright 2009-2021 Centreon");
log_v2::core()->info(
"License ASL 2.0 <http://www.apache.org/licenses/LICENSE-2.0>");
retval = 0;
} else if (version) {
log_v2::core()->info("Centreon Broker {}", CENTREON_BROKER_VERSION);
retval = 0;
} else if (gl_mainconfigfiles.empty()) {
log_v2::core()->error(
"USAGE: {} [-c] [-d] [-D] [-h] [-v] [<configfile>]\n\n", argv[0]);
return 1;
} else {
log_v2::core()->info("Centreon Broker {}", CENTREON_BROKER_VERSION);
log_v2::core()->info("Copyright 2009-2021 Centreon");
log_v2::core()->info(
"License ASL 2.0 <http://www.apache.org/licenses/LICENSE-2.0>");
// Reset locale.
setlocale(LC_NUMERIC, "C");
{
// Parse configuration file.
config::parser parsr;
config::state conf{parsr.parse(gl_mainconfigfiles.front())};
try {
log_v2::instance().apply(conf);
} catch (const std::exception& e) {
log_v2::core()->error(e.what());
}
if (n_thread > 0 && n_thread < 100)
conf.pool_size(n_thread);
config::applier::init(conf);
// Apply resulting configuration totally or partially.
config::applier::state::instance().apply(conf, !check);
broker_name = conf.broker_name();
gl_state = conf;
}
if (gl_state.rpc_port() == 0)
default_port += gl_state.broker_id();
else
default_port = gl_state.rpc_port();
std::unique_ptr<brokerrpc, std::function<void(brokerrpc*)> > rpc(
new brokerrpc("0.0.0.0", default_port, broker_name),
[](brokerrpc* rpc) {
rpc->shutdown();
delete rpc;
});
// Launch event loop.
retval = EXIT_SUCCESS;
if (!check) {
while (!gl_term) {
std::this_thread::sleep_for(std::chrono::seconds(1));
}
log_v2::core()->info("main: termination request received by process");
}
// Unload endpoints.
config::applier::deinit();
}
}
// Standard exception.
catch (const std::exception& e) {
log_v2::core()->error("Error during cbd exit: {}", e.what());
retval = EXIT_FAILURE;
}
// Unknown exception.
catch (...) {
log_v2::core()->error("Error general during cbd exit");
retval = EXIT_FAILURE;
}
return retval;
}
<commit_msg>fix(main): sighup handler could be badly configured.<commit_after>/*
** Copyright 2009-2013,2015,2018 Centreon
**
** 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.
**
** For more information : contact@centreon.com
*/
#include <getopt.h>
#include <cerrno>
#include <chrono>
#include <clocale>
#include <csignal>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <thread>
#include "com/centreon/broker/brokerrpc.hh"
#include "com/centreon/broker/config/applier/init.hh"
#include "com/centreon/broker/config/applier/state.hh"
#include "com/centreon/broker/config/parser.hh"
#include "com/centreon/broker/config/state.hh"
#include "com/centreon/broker/log_v2.hh"
#include "com/centreon/broker/misc/diagnostic.hh"
using namespace com::centreon::broker;
// Main config file.
static std::vector<std::string> gl_mainconfigfiles;
static config::state gl_state;
static std::atomic_bool gl_term{false};
static struct option long_options[] = {{"pool_size", required_argument, 0, 's'},
{"check", no_argument, 0, 'c'},
{"debug", no_argument, 0, 'd'},
{"diagnose", no_argument, 0, 'D'},
{"version", no_argument, 0, 'v'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}};
/**
* Function called when updating configuration (when program receives
* SIGHUP).
*
* @param[in] signum Signal number.
*/
static void hup_handler(int signum) {
(void)signum;
// Disable SIGHUP handling during handler execution.
signal(SIGHUP, SIG_IGN);
// Log message.
log_v2::core()->info("main: configuration update requested");
try {
// Parse configuration file.
config::parser parsr;
config::state conf{parsr.parse(gl_mainconfigfiles.front())};
try {
log_v2::instance().apply(conf);
} catch (const std::exception& e) {
log_v2::core()->error(e.what());
}
try {
// Apply resulting configuration.
config::applier::state::instance().apply(conf);
gl_state = conf;
} catch (const std::exception& e) {
log_v2::core()->error(
"main: configuration update could not succeed, reloading previous "
"configuration: {}",
e.what());
config::applier::state::instance().apply(gl_state);
} catch (...) {
log_v2::core()->error(
"main: configuration update could not succeed, reloading previous "
"configuration");
config::applier::state::instance().apply(gl_state);
}
} catch (const std::exception& e) {
log_v2::config()->info("main: configuration update failed: {}", e.what());
} catch (...) {
log_v2::config()->info(
"main: configuration update failed: unknown exception");
}
// Reenable SIGHUP handler.
signal(SIGHUP, hup_handler);
}
/**
* Function called on termination request (when program receives
* SIGTERM).
*
* @param[in] signum Unused.
* @param[in] info Signal informations.
* @param[in] data Unused.
*/
static void term_handler(int signum) {
(void)signum;
gl_term = true;
}
/**
* @brief Program entry point.
*
* main() is the first function called when the program starts.
*
* @param[in] argc Number of arguments received on the command line.
* @param[in] argv Arguments received on the command line, stored in an
* array.
*
* @return 0 on normal termination, any other value on failure.
*/
int main(int argc, char* argv[]) {
// Initialization.
int opt, option_index = 0, n_thread = 0;
std::string broker_name{"unknown"};
uint16_t default_port{51000};
// Set configuration update handler.
if (signal(SIGHUP, hup_handler) == SIG_ERR) {
char const* err{strerror(errno)};
log_v2::core()->info(
"main: could not register configuration update handler: {}", err);
}
// Init signal handler.
struct sigaction sigterm_act;
memset(&sigterm_act, 0, sizeof(sigterm_act));
sigterm_act.sa_handler = &term_handler;
// Set termination handler.
if (sigaction(SIGTERM, &sigterm_act, nullptr) < 0)
log_v2::core()->info("main: could not register termination handler");
// Return value.
int retval(0);
try {
// Check the command line.
bool check(false);
bool debug(false);
bool diagnose(false);
bool help(false);
bool version(false);
opt = getopt_long(argc, argv, "t:cdDvh", long_options, &option_index);
switch (opt) {
case 't':
n_thread = atoi(optarg);
break;
case 'c':
check = true;
break;
case 'd':
debug = true;
break;
case 'D':
diagnose = true;
break;
case 'h':
help = true;
break;
case 'v':
version = true;
break;
default:
break;
}
if (optind < argc)
while (optind < argc)
gl_mainconfigfiles.push_back(argv[optind++]);
// Check parameters requirements.
if (diagnose) {
if (gl_mainconfigfiles.empty()) {
log_v2::core()->error(
"diagnostic: no configuration file provided: DIAGNOSTIC FILE MIGHT "
"NOT BE USEFUL");
}
misc::diagnostic diag;
diag.generate(gl_mainconfigfiles);
} else if (help) {
log_v2::core()->info(
"USAGE: {} [-t] [-c] [-d] [-D] [-h] [-v] [<configfile>]", argv[0]);
log_v2::core()->info(" -t Set x threads.");
log_v2::core()->info(" -c Check configuration file.");
log_v2::core()->info(" -d Enable debug mode.");
log_v2::core()->info(" -D Generate a diagnostic file.");
log_v2::core()->info(" -h Print this help.");
log_v2::core()->info(" -v Print Centreon Broker version.");
log_v2::core()->info("Centreon Broker {}", CENTREON_BROKER_VERSION);
log_v2::core()->info("Copyright 2009-2021 Centreon");
log_v2::core()->info(
"License ASL 2.0 <http://www.apache.org/licenses/LICENSE-2.0>");
retval = 0;
} else if (version) {
log_v2::core()->info("Centreon Broker {}", CENTREON_BROKER_VERSION);
retval = 0;
} else if (gl_mainconfigfiles.empty()) {
log_v2::core()->error(
"USAGE: {} [-c] [-d] [-D] [-h] [-v] [<configfile>]\n\n", argv[0]);
return 1;
} else {
log_v2::core()->info("Centreon Broker {}", CENTREON_BROKER_VERSION);
log_v2::core()->info("Copyright 2009-2021 Centreon");
log_v2::core()->info(
"License ASL 2.0 <http://www.apache.org/licenses/LICENSE-2.0>");
// Reset locale.
setlocale(LC_NUMERIC, "C");
{
// Parse configuration file.
config::parser parsr;
config::state conf{parsr.parse(gl_mainconfigfiles.front())};
try {
log_v2::instance().apply(conf);
} catch (const std::exception& e) {
log_v2::core()->error(e.what());
}
if (n_thread > 0 && n_thread < 100)
conf.pool_size(n_thread);
config::applier::init(conf);
// Apply resulting configuration totally or partially.
config::applier::state::instance().apply(conf, !check);
broker_name = conf.broker_name();
gl_state = conf;
}
if (gl_state.rpc_port() == 0)
default_port += gl_state.broker_id();
else
default_port = gl_state.rpc_port();
std::unique_ptr<brokerrpc, std::function<void(brokerrpc*)> > rpc(
new brokerrpc("0.0.0.0", default_port, broker_name),
[](brokerrpc* rpc) {
rpc->shutdown();
delete rpc;
});
// Launch event loop.
retval = EXIT_SUCCESS;
if (!check) {
while (!gl_term) {
std::this_thread::sleep_for(std::chrono::seconds(1));
}
log_v2::core()->info("main: termination request received by process");
}
// Unload endpoints.
config::applier::deinit();
}
}
// Standard exception.
catch (const std::exception& e) {
log_v2::core()->error("Error during cbd exit: {}", e.what());
retval = EXIT_FAILURE;
}
// Unknown exception.
catch (...) {
log_v2::core()->error("Error general during cbd exit");
retval = EXIT_FAILURE;
}
return retval;
}
<|endoftext|>
|
<commit_before>#include <bits/stdc++.h>
#define endl '\n'
#define debug(x) cout << #x << " " <<x <<endl
#define MAX (1000005)
using namespace std;
int block;
int cnt[MAX];
struct query {
int left;
int right;
int id;
void show(){
cout <<"["<< left << " "<< right <<"]"<<endl;
}
bool operator <(query q) const{
if(left/block == q.left/block ) return right < q.right;
return left/block < q.left/block;
}
};
typedef vector < int > vi;
typedef vector < query > vq;
int numDiff =0;
vi arr;
vi sols;
void add(int pos){
cnt[arr[pos]]++;
if(cnt[arr[pos]] == 1 ) numDiff++; // new element
}
void remove(int pos){
cnt[arr[pos]]--;
if(cnt[arr[pos]] == 0 ) numDiff--; //remove element
}
int main(){
#ifdef LOCAL
freopen("in.c", "r", stdin);
#endif
int numQueries, numElements;
//read elements
cin >> numElements;
arr.resize(numElements);
for( int i=0; i<numElements; i++){
cin >> arr[i];
}
cin >> numQueries;
//read queries
vq qs(numQueries);
sols.resize(numQueries);
for( int q=0; q<numQueries; q++){
cin >> qs[q].left >> qs[q].right;
qs[q].left--;
qs[q].right--;
qs[q].id = q;
}
//calc block size
block = sqrt(numElements);
//sort queries
sort(qs.begin(), qs.end());
//iterate over the queries
int currR = 0, currL =0;
for (query q : qs){
int l = q.left, r = q.right;
//remove elements previos range left
while(currL< l){
remove(currL);
currL++;
}
//Add elements in the current range
while(currL>l){
add(currL-1);
currL--;
}
while(currR<=r){
add(currR);
currR++;
}
//Remove elemnts previos range right
while(currR > r+1){
remove(currR-1);
currR--;
}
sols[q.id] = numDiff;
}
for(int i=0; i<numQueries; ++i){
cout << sols[i] <<endl;
}
return 0;
}
<commit_msg>Improve efficiency Mo's algorithm.<commit_after>#include <bits/stdc++.h>
#define endl '\n'
#define debug(x) cout << #x << " " <<x <<endl
#define MAX (1000005)
using namespace std;
int block;
int cnt[MAX];
struct query {
int left;
int right;
int id;
void show(){
cout <<"["<< left << " "<< right <<"]"<<endl;
}
bool operator <(query q) const{
if(left/block == q.left/block ) return right < q.right;
return left/block < q.left/block;
}
};
typedef vector < int > vi;
typedef vector < query > vq;
int currR = 0, currL =0;
int numDiff =0;
vi arr;
vi sols;
void add(int pos){
cnt[arr[pos]]++;
if(cnt[arr[pos]] == 1 ) numDiff++; // new element
}
void remove(int pos){
cnt[arr[pos]]--;
if(cnt[arr[pos]] == 0 ) numDiff--; //remove element
}
int seek(query &q){
int l = q.left, r = q.right;
//remove elements previos range left
while( currL < l ){
remove( currL );
currL++;
}
//Add elements in the current range
while( currL > l ){
currL--;
add( currL );
}
while( currR <= r ){
add( currR );
currR++;
}
//Remove elemnts previos range right
while( currR > r+1 ){
currR--;
remove( currR );
}
return numDiff;
}
int main(){
#ifdef LOCAL
// freopen("in.c", "r", stdin);
#endif
int numQueries, numElements;
//read elements
cin >> numElements;
arr.resize(numElements+1);
for( int i=1; i<=numElements; i++){
cin >> arr[i];
}
cin >> numQueries;
//read queries
vq qs(numQueries+1);
sols.resize(numQueries+1);
for( int q=1; q<=numQueries; q++){
cin >> qs[q].left >> qs[q].right;
qs[q].id = q;
}
//calc block size
block = sqrt(numElements);
//sort queries
sort(qs.begin(), qs.end());
//seek for answers
for (int q=1; q<=numQueries; q++)
sols[qs[q].id] = seek(qs[q]);
//display the answer
for(int i=1; i<=numQueries; ++i)
cout << sols[i] <<endl;
return 0;
}
<|endoftext|>
|
<commit_before>#ifndef __TDB_API_HELPER_H__
static_assert(0, "Include TDB_API/TDB_API_helper.h instead!");
#endif
#include "util.h"
#include "kdb+.util/type_convert.h"
#include <cassert>
#pragma region
template <typename TDBDefine_T>
K TDB::FieldAccessor<TDBDefine_T>::extract(TDBDefine_T const* dataArray, std::size_t arrayLen) const {
assert(NULL != dataArray);
assert(arrayLen >= 0);
q::K_ptr result(ktn(getTypeNum(), arrayLen));
for (std::size_t i = 0; i < arrayLen; ++i) {
setElement(result.get(), dataArray, i);
}
return result.release();
}
template <typename TDBDefine_T>
void TDB::CharAccessor<TDBDefine_T>::setElement(K out, TDBDefine_T const* dataArray, std::size_t index) const {
q::type_traits<C>::index(out)[index] = dataArray[index].*field_;
}
template <typename TDBDefine_T>
void TDB::DateAccessor<TDBDefine_T>::setElement(K out, TDBDefine_T const* dataArray, std::size_t index) const {
q::type_traits<I>::index(out)[index] = q::date2q(dataArray[index].*field_);
}
template <typename TDBDefine_T>
void TDB::TimeAccessor<TDBDefine_T>::setElement(K out, TDBDefine_T const* dataArray, std::size_t index) const {
q::type_traits<I>::index(out)[index] = util::time2q(dataArray[index].*field_);
}
template <typename TDBDefine_T, typename QType>
void TDB::IntAccessor<TDBDefine_T, QType>::setElement(K out, TDBDefine_T const* dataArray, std::size_t index) const {
q::type_traits<QType>::index(out)[index] = dataArray[index].*field_;
}
template <typename TDBDefine_T, typename Str, typename Encoder>
void TDB::StringAccessor<TDBDefine_T, Str, Encoder>::setElement(K out, TDBDefine_T const* dataArray, std::size_t index) const {
q::type_traits<void>::index(out)[index] = kp(const_cast<S>(encode_(dataArray[index].*field_).c_str()));
}
template <typename TDBDefine_T, typename Str, typename Encoder>
void TDB::SymbolAccessor<TDBDefine_T, Str, Encoder>::setElement(K out, TDBDefine_T const* dataArray, std::size_t index) const {
q::type_traits<S>::index(out)[index] = ss(const_cast<S>(encode_(dataArray[index].*field_).c_str()));
}
template <typename TDBDefine_T, typename Val>
void TDB::FloatAccessor<TDBDefine_T, Val>::setElement(K out, TDBDefine_T const* dataArray, std::size_t index) const {
q::type_traits<F>::index(out)[index] = scalar_ * dataArray[index].*field_;
}
template <typename TDBDefine_T, typename Vals>
void TDB::FloatsAccessor<TDBDefine_T, Vals>::setElement(K out, TDBDefine_T const* dataArray, std::size_t index) const {
std::size_t const size = std::extent<Vals, 0>::value;
K dst = q::type_traits<void>::index(out)[index] = ktn(KF, size);
Vals const& src = dataArray[index].*field_;
for (std::size_t j = 0; j < size; ++j) {
kF(dst)[j] = scalar_ * src[j];
}
}
#pragma endregion
template <typename TDBDefine_Wrap>
void TDB::parseIndicators(K indicators,
std::vector<typename TDBDefine_Wrap::field_accessor_type const*>& indis)
throw(std::string)
{
assert(indis.empty());
std::vector<std::string> const is = q::qList2String(indicators);
indis.reserve(is.size());
for (auto i = is.cbegin(); i != is.cend(); ++i) {
auto const f = TDBDefine_Wrap::FieldName::fromString(*i);
if (f == TDBDefine_Wrap::NIL) {
throw *i;
}
indis.push_back(TDBDefine_Wrap::Accessors[f].get());
assert(*indis.rbegin() != NULL);
}
}
template <typename TDBDefine_ReqT>
void TDB::parseTdbReq(K windCode, K begin, K end, TDBDefine_ReqT& req) throw(std::string) {
std::memset(&req, 0, sizeof(TDBDefine_ReqT));
std::string const code = q::q2String(windCode);
std::copy(code.begin(), code.end(), req.chCode);
req.chCode[code.size()] = '\0';
util::tm2DateTime(q::q2tm(begin), req.nBeginDate, req.nBeginTime);
util::tm2DateTime(q::q2tm(end), req.nEndDate, req.nEndTime);
}
template <typename TDBDefine_Wrap>
K TDB::getFields() {
std::vector<std::string> const fieldNames = TDBDefine_Wrap::FieldName::getAllStrings();
q::K_ptr result(ktn(KS, fieldNames.size()));
for (std::size_t i = 0; i < fieldNames.size(); ++i) {
kS(result.get())[i] = ss(const_cast<S>(fieldNames[i].c_str()));
}
return result.release();
}
template <typename TDBDefine_Wrap, typename TDBDefine_ReqT>
K TDB::runQuery(::THANDLE tdb, TDBDefine_ReqT const& req,
std::vector<typename TDBDefine_Wrap::field_accessor_type const*>& indis,
int(*tdbCall)(::THANDLE, TDBDefine_ReqT const*, typename TDBDefine_Wrap::tdb_result_type**, int*))
{
int arrayLen = 0;
typename TDBDefine_Wrap::tdb_result_type* dataArray = NULL;
int const result = tdbCall(tdb, &req, &dataArray, &arrayLen);
TDB::Ptr<typename TDBDefine_Wrap::tdb_result_type> data(dataArray);
if (result != TDB_SUCCESS) {
return q::error2q(TDB::getError(result));
}
assert(arrayLen >= 0);
assert(data);
// Convert each requested field
q::K_ptr out(ktn(0, indis.size()));
for (std::size_t i = 0; i < indis.size(); ++i) {
kK(out)[i] = indis[i]->extract(dataArray, arrayLen);
}
return out.release();
}<commit_msg>Bugfix: catch string length problems that may cause memory overflow.<commit_after>#ifndef __TDB_API_HELPER_H__
static_assert(0, "Include TDB_API/TDB_API_helper.h instead!");
#endif
#include "util.h"
#include "kdb+.util/type_convert.h"
#include <cassert>
#pragma region
template <typename TDBDefine_T>
K TDB::FieldAccessor<TDBDefine_T>::extract(TDBDefine_T const* dataArray, std::size_t arrayLen) const {
assert(NULL != dataArray);
assert(arrayLen >= 0);
q::K_ptr result(ktn(getTypeNum(), arrayLen));
for (std::size_t i = 0; i < arrayLen; ++i) {
setElement(result.get(), dataArray, i);
}
return result.release();
}
template <typename TDBDefine_T>
void TDB::CharAccessor<TDBDefine_T>::setElement(K out, TDBDefine_T const* dataArray, std::size_t index) const {
q::type_traits<C>::index(out)[index] = dataArray[index].*field_;
}
template <typename TDBDefine_T>
void TDB::DateAccessor<TDBDefine_T>::setElement(K out, TDBDefine_T const* dataArray, std::size_t index) const {
q::type_traits<I>::index(out)[index] = q::date2q(dataArray[index].*field_);
}
template <typename TDBDefine_T>
void TDB::TimeAccessor<TDBDefine_T>::setElement(K out, TDBDefine_T const* dataArray, std::size_t index) const {
q::type_traits<I>::index(out)[index] = util::time2q(dataArray[index].*field_);
}
template <typename TDBDefine_T, typename QType>
void TDB::IntAccessor<TDBDefine_T, QType>::setElement(K out, TDBDefine_T const* dataArray, std::size_t index) const {
q::type_traits<QType>::index(out)[index] = dataArray[index].*field_;
}
template <typename TDBDefine_T, typename Str, typename Encoder>
void TDB::StringAccessor<TDBDefine_T, Str, Encoder>::setElement(K out, TDBDefine_T const* dataArray, std::size_t index) const {
q::type_traits<void>::index(out)[index] = kp(const_cast<S>(encode_(dataArray[index].*field_).c_str()));
}
template <typename TDBDefine_T, typename Str, typename Encoder>
void TDB::SymbolAccessor<TDBDefine_T, Str, Encoder>::setElement(K out, TDBDefine_T const* dataArray, std::size_t index) const {
q::type_traits<S>::index(out)[index] = ss(const_cast<S>(encode_(dataArray[index].*field_).c_str()));
}
template <typename TDBDefine_T, typename Val>
void TDB::FloatAccessor<TDBDefine_T, Val>::setElement(K out, TDBDefine_T const* dataArray, std::size_t index) const {
q::type_traits<F>::index(out)[index] = scalar_ * dataArray[index].*field_;
}
template <typename TDBDefine_T, typename Vals>
void TDB::FloatsAccessor<TDBDefine_T, Vals>::setElement(K out, TDBDefine_T const* dataArray, std::size_t index) const {
std::size_t const size = std::extent<Vals, 0>::value;
K dst = q::type_traits<void>::index(out)[index] = ktn(KF, size);
Vals const& src = dataArray[index].*field_;
for (std::size_t j = 0; j < size; ++j) {
kF(dst)[j] = scalar_ * src[j];
}
}
#pragma endregion
template <typename TDBDefine_Wrap>
void TDB::parseIndicators(K indicators,
std::vector<typename TDBDefine_Wrap::field_accessor_type const*>& indis)
throw(std::string)
{
assert(indis.empty());
std::vector<std::string> const is = q::qList2String(indicators);
indis.reserve(is.size());
for (auto i = is.cbegin(); i != is.cend(); ++i) {
auto const f = TDBDefine_Wrap::FieldName::fromString(*i);
if (f == TDBDefine_Wrap::NIL) {
throw *i;
}
indis.push_back(TDBDefine_Wrap::Accessors[f].get());
assert(*indis.rbegin() != NULL);
}
}
template <typename TDBDefine_ReqT>
void TDB::parseTdbReq(K windCode, K begin, K end, TDBDefine_ReqT& req) throw(std::string) {
std::memset(&req, 0, sizeof(TDBDefine_ReqT));
std::string const code = q::q2String(windCode);
if (code.size() >= sizeof(req.chCode)) {
throw std::string("windCode too long");
}
std::copy(code.begin(), code.end(), req.chCode);
req.chCode[code.size()] = '\0';
util::tm2DateTime(q::q2tm(begin), req.nBeginDate, req.nBeginTime);
util::tm2DateTime(q::q2tm(end), req.nEndDate, req.nEndTime);
}
template <typename TDBDefine_Wrap>
K TDB::getFields() {
std::vector<std::string> const fieldNames = TDBDefine_Wrap::FieldName::getAllStrings();
q::K_ptr result(ktn(KS, fieldNames.size()));
for (std::size_t i = 0; i < fieldNames.size(); ++i) {
kS(result.get())[i] = ss(const_cast<S>(fieldNames[i].c_str()));
}
return result.release();
}
template <typename TDBDefine_Wrap, typename TDBDefine_ReqT>
K TDB::runQuery(::THANDLE tdb, TDBDefine_ReqT const& req,
std::vector<typename TDBDefine_Wrap::field_accessor_type const*>& indis,
int(*tdbCall)(::THANDLE, TDBDefine_ReqT const*, typename TDBDefine_Wrap::tdb_result_type**, int*))
{
int arrayLen = 0;
typename TDBDefine_Wrap::tdb_result_type* dataArray = NULL;
int const result = tdbCall(tdb, &req, &dataArray, &arrayLen);
TDB::Ptr<typename TDBDefine_Wrap::tdb_result_type> data(dataArray);
if (result != TDB_SUCCESS) {
return q::error2q(TDB::getError(result));
}
assert(arrayLen >= 0);
assert(data);
// Convert each requested field
q::K_ptr out(ktn(0, indis.size()));
for (std::size_t i = 0; i < indis.size(); ++i) {
kK(out)[i] = indis[i]->extract(dataArray, arrayLen);
}
return out.release();
}<|endoftext|>
|
<commit_before>2d490f85-2e4f-11e5-95e6-28cfe91dbc4b<commit_msg>2d51d678-2e4f-11e5-bc0b-28cfe91dbc4b<commit_after>2d51d678-2e4f-11e5-bc0b-28cfe91dbc4b<|endoftext|>
|
<commit_before>4c86970c-2748-11e6-8a0e-e0f84713e7b8<commit_msg>Fixed that one bug<commit_after>4c9b9a1c-2748-11e6-ae71-e0f84713e7b8<|endoftext|>
|
<commit_before>809e91a1-2d15-11e5-af21-0401358ea401<commit_msg>809e91a2-2d15-11e5-af21-0401358ea401<commit_after>809e91a2-2d15-11e5-af21-0401358ea401<|endoftext|>
|
<commit_before>/** main.cpp
* Dylan Auty, 2016
*/
#include <ncurses.h>
#include "CursesWindow.hpp"
#include "Map.hpp"
using namespace std;
// TODO: Move redrawMap to another file for tidiness
void redrawMap(WINDOW* &mapWin, WINDOW* &debugRowWin, Map &gameMap, int currMapY, int currMapX, int currFloor); ///< Function to clear then redraw the map on demand, within the map window.
int main(){
// Create the parent window and print exit instructions
CursesWindow parentWin;
mvprintw(0, 0, "Press F1 to quit.");
refresh();
// Create the map window
WINDOW* mapWin = newwin(parentWin.lines - 4, parentWin.cols - 4, 2, 2);
box(mapWin, 0, 0);
wrefresh(mapWin);
// Create debug row (window) at the bottom of the screen
WINDOW* debugRowWin = newwin(1, parentWin.cols, parentWin.lines - 1, 0);
mvwprintw(debugRowWin, 0, 0, "Dims:%dx%d", parentWin.lines, parentWin.cols);
wrefresh(debugRowWin);
// Create the map.
Map gameMap;
mvwprintw(debugRowWin, 0, 30, "GameMap Created");
wrefresh(debugRowWin);
int ch; // Input character
int newParentWinLines, newParentWinCols; // For checking for resizing
int currMapY = 0;
int currMapX = 0; // For the coordinates of the map to be displayed in the top left corner of the map window.
int currFloor = 0; // Current floor of the map.
// Main game loop.
while(1){
// Check window size is what it was before, and deal with it if not.
getmaxyx(stdscr, newParentWinLines, newParentWinCols);
if(newParentWinLines != parentWin.lines || newParentWinCols != parentWin.cols){
// Resize windows and redraw borders
parentWin.lines = newParentWinLines;
parentWin.cols = newParentWinCols;
// TODO: move resizing + redrawing into a subroutine of CursesWindow that can resize all subwindows regardless of layout.
// Would need each window to have a start position and size, and can move based on that.
// Some windows will be resizable, some will be fixed size (e.g. message windows maybe, or menus).
wclear(stdscr);
wclear(mapWin);
wclear(debugRowWin);
wresize(mapWin, parentWin.lines - 4, parentWin.cols - 4);
box(mapWin, 0, 0);
wresize(debugRowWin, 1, parentWin.cols);
mvwin(debugRowWin, parentWin.lines - 1, 0);
mvwprintw(debugRowWin, 0, 0, "Dims:%dx%d", parentWin.lines, parentWin.cols);
mvwprintw(stdscr, 0, 0, "Press F1 to quit.");
// TODO: Insert a routine for populating the mapWindow.
wrefresh(stdscr);
wrefresh(mapWin);
wrefresh(debugRowWin);
}
// Fetch input
ch = getch();
// Debugging: display input key in debugging window.
wclear(debugRowWin);
mvwprintw(debugRowWin, 0, 0, "Dims:%dx%d, Input %c", parentWin.lines, parentWin.cols, ch);
wrefresh(debugRowWin);
switch(ch){
case KEY_F(1): // EXIT
return 0;
// Moving around the map view
// currMapY, currMapX denote current tile of the map that coincides with the top left coordinate of the view window.
case KEY_UP: // Move view window up
currMapY -= 5;
break;
case KEY_DOWN: // Move view window down
currMapY += 5;
break;
case KEY_LEFT: // Move view window left
currMapX -= 5;
break;
case KEY_RIGHT: // Move view window right
currMapX += 5;
break;
default:
break;
}
redrawMap(mapWin, debugRowWin, gameMap, currMapY, currMapX, currFloor);
}
return 0;
}
void redrawMap(WINDOW* &mapWin, WINDOW* &debugRowWin, Map &gameMap, int currMapY, int currMapX, int currFloor) {
//NOTE: first line and column of a window is taken up by borders.
wclear(mapWin);
int mapWinLines = 0;
int mapWinCols = 0;
box(mapWin, 0, 0);
getmaxyx(mapWin, mapWinLines, mapWinCols);
for(int y = 1; y < mapWinLines-1; y++){
for(int x = 1; x < mapWinCols-1; x++){
// Placeholder
//gameMap.floorVec[currFloor].tiles[y][x]
// TODO: FINISH SANITY CHECKING COORDINATES, THIS CAUSES SEGFAULTS NOW
// Moving across screen coords, two things to check each time:
// 1) Does the corresponding map tile exist?
// - Corresponding map tile = (y + currMapY - 1, x + currMapX - 1)
// 2) If so, what is it and what needs printing? (May delegate this job to a tile object which has a char field.)
//mvwprintw(debugRowWin, 0, 30, "Curr:%dx%d", y, x);
//wrefresh(debugRowWin);
if((y + currMapY - 1) >= 0 && (x + currMapX - 1) >= 0 && (y + currMapY - 1) <= 100 && (x + currMapX - 1) <= 100){
switch(gameMap.floorVec[currFloor].tiles[currMapY + y - 1][currMapX + x - 1]){
case 1:
mvwaddch(mapWin, y, x, '#');
break;
case 2:
mvwaddch(mapWin, y, x, '.');
break;
default:
break;
}
//mvwaddch(mapWin, y, x, gameMap.floorVec[currFloor].tiles[currMapY + y - 1][currMapX + x - 1]); // 1 to deal with border offset from window border drawing.
}
}
}
wrefresh(mapWin);
return;
}
<commit_msg>Changed drawing chars temporarily<commit_after>/** main.cpp
* Dylan Auty, 2016
*/
#include <ncurses.h>
#include "CursesWindow.hpp"
#include "Map.hpp"
using namespace std;
// TODO: Move redrawMap to another file for tidiness
void redrawMap(WINDOW* &mapWin, WINDOW* &debugRowWin, Map &gameMap, int currMapY, int currMapX, int currFloor); ///< Function to clear then redraw the map on demand, within the map window.
int main(){
// Create the parent window and print exit instructions
CursesWindow parentWin;
mvprintw(0, 0, "Press F1 to quit.");
refresh();
// Create the map window
WINDOW* mapWin = newwin(parentWin.lines - 4, parentWin.cols - 4, 2, 2);
box(mapWin, 0, 0);
wrefresh(mapWin);
// Create debug row (window) at the bottom of the screen
WINDOW* debugRowWin = newwin(1, parentWin.cols, parentWin.lines - 1, 0);
mvwprintw(debugRowWin, 0, 0, "Dims:%dx%d", parentWin.lines, parentWin.cols);
wrefresh(debugRowWin);
// Create the map.
Map gameMap;
mvwprintw(debugRowWin, 0, 30, "GameMap Created");
wrefresh(debugRowWin);
int ch; // Input character
int newParentWinLines, newParentWinCols; // For checking for resizing
int currMapY = 0;
int currMapX = 0; // For the coordinates of the map to be displayed in the top left corner of the map window.
int currFloor = 0; // Current floor of the map.
redrawMap(mapWin, debugRowWin, gameMap, currMapY, currMapX, currFloor); // Draw map for the first time
// Main game loop.
while(1){
// Check window size is what it was before, and deal with it if not.
getmaxyx(stdscr, newParentWinLines, newParentWinCols);
if(newParentWinLines != parentWin.lines || newParentWinCols != parentWin.cols){
// Resize windows and redraw borders
parentWin.lines = newParentWinLines;
parentWin.cols = newParentWinCols;
// TODO: move resizing + redrawing into a subroutine of CursesWindow that can resize all subwindows regardless of layout.
// Would need each window to have a start position and size, and can move based on that.
// Some windows will be resizable, some will be fixed size (e.g. message windows maybe, or menus).
wclear(stdscr);
wclear(mapWin);
wclear(debugRowWin);
wresize(mapWin, parentWin.lines - 4, parentWin.cols - 4);
box(mapWin, 0, 0);
wresize(debugRowWin, 1, parentWin.cols);
mvwin(debugRowWin, parentWin.lines - 1, 0);
mvwprintw(debugRowWin, 0, 0, "Dims:%dx%d", parentWin.lines, parentWin.cols);
mvwprintw(stdscr, 0, 0, "Press F1 to quit.");
// TODO: Insert a routine for populating the mapWindow.
wrefresh(stdscr);
wrefresh(mapWin);
wrefresh(debugRowWin);
}
// Fetch input
ch = getch();
// Debugging: display input key in debugging window.
wclear(debugRowWin);
mvwprintw(debugRowWin, 0, 0, "Dims:%dx%d, Input %c", parentWin.lines, parentWin.cols, ch);
wrefresh(debugRowWin);
switch(ch){
case KEY_F(1): // EXIT
return 0;
// Moving around the map view
// currMapY, currMapX denote current tile of the map that coincides with the top left coordinate of the view window.
case KEY_UP: // Move view window up
currMapY -= 5;
break;
case KEY_DOWN: // Move view window down
currMapY += 5;
break;
case KEY_LEFT: // Move view window left
currMapX -= 5;
break;
case KEY_RIGHT: // Move view window right
currMapX += 5;
break;
default:
break;
}
redrawMap(mapWin, debugRowWin, gameMap, currMapY, currMapX, currFloor);
}
return 0;
}
void redrawMap(WINDOW* &mapWin, WINDOW* &debugRowWin, Map &gameMap, int currMapY, int currMapX, int currFloor) {
//NOTE: first line and column of a window is taken up by borders.
wclear(mapWin);
int mapWinLines = 0;
int mapWinCols = 0;
box(mapWin, 0, 0);
getmaxyx(mapWin, mapWinLines, mapWinCols);
for(int y = 1; y < mapWinLines-1; y++){
for(int x = 1; x < mapWinCols-1; x++){
// Placeholder
//gameMap.floorVec[currFloor].tiles[y][x]
// TODO: FINISH SANITY CHECKING COORDINATES, THIS CAUSES SEGFAULTS NOW
// Moving across screen coords, two things to check each time:
// 1) Does the corresponding map tile exist?
// - Corresponding map tile = (y + currMapY - 1, x + currMapX - 1)
// 2) If so, what is it and what needs printing? (May delegate this job to a tile object which has a char field.)
//mvwprintw(debugRowWin, 0, 30, "Curr:%dx%d", y, x);
//wrefresh(debugRowWin);
if((y + currMapY - 1) >= 0 && (x + currMapX - 1) >= 0 && (y + currMapY - 1) <= 100 && (x + currMapX - 1) <= 100){
switch(gameMap.floorVec[currFloor].tiles[currMapY + y - 1][currMapX + x - 1]){
case 0:
mvwaddch(mapWin, y, x, ' ');
break;
case 1:
mvwaddch(mapWin, y, x, '#');
break;
default:
break;
}
//mvwaddch(mapWin, y, x, gameMap.floorVec[currFloor].tiles[currMapY + y - 1][currMapX + x - 1]); // 1 to deal with border offset from window border drawing.
}
}
}
wrefresh(mapWin);
return;
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.