text
stringlengths 54
60.6k
|
---|
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "matchdatabuilder.h"
#include <vespa/searchlib/attribute/attributevector.h>
#include <vespa/searchlib/attribute/attributevector.hpp>
#include <vespa/searchlib/attribute/stringbase.h>
#include <vespa/vespalib/util/stringfmt.h>
#include <vespa/log/log.h>
LOG_SETUP(".fef.matchdatabuilder");
namespace search::fef::test {
MatchDataBuilder::MatchDataBuilder(QueryEnvironment &queryEnv, MatchData &data) :
_queryEnv(queryEnv),
_data(data),
_index(),
_match()
{
// reset all match data objects.
for (TermFieldHandle handle = 0; handle < _data.getNumTermFields(); ++handle) {
_data.resolveTermField(handle)->reset(TermFieldMatchData::invalidId());
}
}
MatchDataBuilder::~MatchDataBuilder() {}
TermFieldMatchData *
MatchDataBuilder::getTermFieldMatchData(uint32_t termId, uint32_t fieldId)
{
const ITermData *term = _queryEnv.getTerm(termId);
if (term == NULL) {
return NULL;
}
const ITermFieldData *field = term->lookupField(fieldId);
if (field == NULL || field->getHandle() >= _data.getNumTermFields()) {
return NULL;
}
return _data.resolveTermField(field->getHandle());
}
bool
MatchDataBuilder::setFieldLength(const vespalib::string &fieldName, uint32_t length)
{
const FieldInfo *info = _queryEnv.getIndexEnv()->getFieldByName(fieldName);
if (info == NULL) {
LOG(error, "Field '%s' does not exist.", fieldName.c_str());
return false;
}
_index[info->id()].fieldLength = length;
return true;
}
bool
MatchDataBuilder::addElement(const vespalib::string &fieldName, int32_t weight, uint32_t length)
{
const FieldInfo *info = _queryEnv.getIndexEnv()->getFieldByName(fieldName);
if (info == NULL) {
LOG(error, "Field '%s' does not exist.", fieldName.c_str());
return false;
}
_index[info->id()].elements.push_back(MyElement(weight, length));
return true;
}
bool
MatchDataBuilder::addOccurence(const vespalib::string &fieldName, uint32_t termId, uint32_t pos, uint32_t element)
{
const FieldInfo *info = _queryEnv.getIndexEnv()->getFieldByName(fieldName);
if (info == NULL) {
LOG(error, "Field '%s' does not exist.", fieldName.c_str());
return false;
}
if (termId >= _queryEnv.getNumTerms()) {
LOG(error, "Term id '%u' is invalid.", termId);
return false;
}
const ITermFieldData *tfd = _queryEnv.getTerm(termId)->lookupField(info->id());
if (tfd == NULL) {
LOG(error, "Field '%s' is not searched by the given term.",
fieldName.c_str());
return false;
}
_match[termId][info->id()].insert(Position(pos, element));
return true;
}
bool
MatchDataBuilder::setWeight(const vespalib::string &fieldName, uint32_t termId, int32_t weight)
{
const FieldInfo *info = _queryEnv.getIndexEnv()->getFieldByName(fieldName);
if (info == NULL) {
LOG(error, "Field '%s' does not exist.", fieldName.c_str());
return false;
}
if (termId >= _queryEnv.getNumTerms()) {
LOG(error, "Term id '%u' is invalid.", termId);
return false;
}
const ITermFieldData *tfd = _queryEnv.getTerm(termId)->lookupField(info->id());
if (tfd == NULL) {
LOG(error, "Field '%s' is not searched by the given term.",
fieldName.c_str());
return false;
}
uint32_t eid = _index[info->id()].elements.size();
_match[termId][info->id()].clear();
_match[termId][info->id()].insert(Position(0, eid));
_index[info->id()].elements.push_back(MyElement(weight, 1));
return true;
}
bool
MatchDataBuilder::apply(uint32_t docId)
{
// For each term, do
for (TermMap::const_iterator term_iter = _match.begin();
term_iter != _match.end(); ++term_iter)
{
uint32_t termId = term_iter->first;
for (FieldPositions::const_iterator field_iter = term_iter->second.begin();
field_iter != term_iter->second.end(); ++field_iter)
{
uint32_t fieldId = field_iter->first;
TermFieldMatchData *match = getTermFieldMatchData(termId, fieldId);
// Make sure there is a corresponding term field match data object.
if (match == NULL) {
LOG(error, "Term id '%u' is invalid.", termId);
return false;
}
match->reset(docId);
// find field data
MyField field;
IndexData::const_iterator idxItr = _index.find(fieldId);
if (idxItr != _index.end()) {
field = idxItr->second;
}
// For log, attempt to lookup field name.
const FieldInfo *info = _queryEnv.getIndexEnv()->getField(fieldId);
vespalib::string name = info != NULL ? info->name() : vespalib::make_string("%d", fieldId).c_str();
// For each occurence of that term, in that field, do
for (Positions::const_iterator occ_iter = field_iter->second.begin();
occ_iter != field_iter->second.end(); occ_iter++)
{
// Append a term match position to the term match data.
Position occ = *occ_iter;
match->appendPosition(TermFieldMatchDataPosition(
occ.eid,
occ.pos,
field.getWeight(occ.eid),
field.getLength(occ.eid)));
LOG(debug,
"Added occurence of term '%u' in field '%s'"
" at position '%u'.",
termId, name.c_str(), occ.pos);
if (occ.pos >= field.getLength(occ.eid)) {
LOG(warning,
"Added occurence of term '%u' in field '%s'"
" at position '%u' >= fieldLen '%u'.",
termId, name.c_str(), occ.pos, field.getLength(occ.eid));
}
}
}
}
// Return ok.
return true;
}
}
<commit_msg>NULL -> nullptr.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "matchdatabuilder.h"
#include <vespa/searchlib/attribute/attributevector.h>
#include <vespa/searchlib/attribute/attributevector.hpp>
#include <vespa/searchlib/attribute/stringbase.h>
#include <vespa/vespalib/util/stringfmt.h>
#include <vespa/log/log.h>
LOG_SETUP(".fef.matchdatabuilder");
namespace search::fef::test {
MatchDataBuilder::MatchDataBuilder(QueryEnvironment &queryEnv, MatchData &data) :
_queryEnv(queryEnv),
_data(data),
_index(),
_match()
{
// reset all match data objects.
for (TermFieldHandle handle = 0; handle < _data.getNumTermFields(); ++handle) {
_data.resolveTermField(handle)->reset(TermFieldMatchData::invalidId());
}
}
MatchDataBuilder::~MatchDataBuilder() {}
TermFieldMatchData *
MatchDataBuilder::getTermFieldMatchData(uint32_t termId, uint32_t fieldId)
{
const ITermData *term = _queryEnv.getTerm(termId);
if (term == nullptr) {
return nullptr;
}
const ITermFieldData *field = term->lookupField(fieldId);
if (field == nullptr || field->getHandle() >= _data.getNumTermFields()) {
return nullptr;
}
return _data.resolveTermField(field->getHandle());
}
bool
MatchDataBuilder::setFieldLength(const vespalib::string &fieldName, uint32_t length)
{
const FieldInfo *info = _queryEnv.getIndexEnv()->getFieldByName(fieldName);
if (info == nullptr) {
LOG(error, "Field '%s' does not exist.", fieldName.c_str());
return false;
}
_index[info->id()].fieldLength = length;
return true;
}
bool
MatchDataBuilder::addElement(const vespalib::string &fieldName, int32_t weight, uint32_t length)
{
const FieldInfo *info = _queryEnv.getIndexEnv()->getFieldByName(fieldName);
if (info == nullptr) {
LOG(error, "Field '%s' does not exist.", fieldName.c_str());
return false;
}
_index[info->id()].elements.push_back(MyElement(weight, length));
return true;
}
bool
MatchDataBuilder::addOccurence(const vespalib::string &fieldName, uint32_t termId, uint32_t pos, uint32_t element)
{
const FieldInfo *info = _queryEnv.getIndexEnv()->getFieldByName(fieldName);
if (info == nullptr) {
LOG(error, "Field '%s' does not exist.", fieldName.c_str());
return false;
}
if (termId >= _queryEnv.getNumTerms()) {
LOG(error, "Term id '%u' is invalid.", termId);
return false;
}
const ITermFieldData *tfd = _queryEnv.getTerm(termId)->lookupField(info->id());
if (tfd == nullptr) {
LOG(error, "Field '%s' is not searched by the given term.",
fieldName.c_str());
return false;
}
_match[termId][info->id()].insert(Position(pos, element));
return true;
}
bool
MatchDataBuilder::setWeight(const vespalib::string &fieldName, uint32_t termId, int32_t weight)
{
const FieldInfo *info = _queryEnv.getIndexEnv()->getFieldByName(fieldName);
if (info == nullptr) {
LOG(error, "Field '%s' does not exist.", fieldName.c_str());
return false;
}
if (termId >= _queryEnv.getNumTerms()) {
LOG(error, "Term id '%u' is invalid.", termId);
return false;
}
const ITermFieldData *tfd = _queryEnv.getTerm(termId)->lookupField(info->id());
if (tfd == nullptr) {
LOG(error, "Field '%s' is not searched by the given term.",
fieldName.c_str());
return false;
}
uint32_t eid = _index[info->id()].elements.size();
_match[termId][info->id()].clear();
_match[termId][info->id()].insert(Position(0, eid));
_index[info->id()].elements.push_back(MyElement(weight, 1));
return true;
}
bool
MatchDataBuilder::apply(uint32_t docId)
{
// For each term, do
for (TermMap::const_iterator term_iter = _match.begin();
term_iter != _match.end(); ++term_iter)
{
uint32_t termId = term_iter->first;
for (FieldPositions::const_iterator field_iter = term_iter->second.begin();
field_iter != term_iter->second.end(); ++field_iter)
{
uint32_t fieldId = field_iter->first;
TermFieldMatchData *match = getTermFieldMatchData(termId, fieldId);
// Make sure there is a corresponding term field match data object.
if (match == nullptr) {
LOG(error, "Term id '%u' is invalid.", termId);
return false;
}
match->reset(docId);
// find field data
MyField field;
IndexData::const_iterator idxItr = _index.find(fieldId);
if (idxItr != _index.end()) {
field = idxItr->second;
}
// For log, attempt to lookup field name.
const FieldInfo *info = _queryEnv.getIndexEnv()->getField(fieldId);
vespalib::string name = info != nullptr ? info->name() : vespalib::make_string("%d", fieldId).c_str();
// For each occurence of that term, in that field, do
for (Positions::const_iterator occ_iter = field_iter->second.begin();
occ_iter != field_iter->second.end(); occ_iter++)
{
// Append a term match position to the term match data.
Position occ = *occ_iter;
match->appendPosition(TermFieldMatchDataPosition(
occ.eid,
occ.pos,
field.getWeight(occ.eid),
field.getLength(occ.eid)));
LOG(debug,
"Added occurence of term '%u' in field '%s'"
" at position '%u'.",
termId, name.c_str(), occ.pos);
if (occ.pos >= field.getLength(occ.eid)) {
LOG(warning,
"Added occurence of term '%u' in field '%s'"
" at position '%u' >= fieldLen '%u'.",
termId, name.c_str(), occ.pos, field.getLength(occ.eid));
}
}
}
}
// Return ok.
return true;
}
}
<|endoftext|> |
<commit_before>// ==========================================================================
// bam_print_alignments.cpp
// ==========================================================================
// Copyright (c) 2006-2010, Knut Reinert, FU Berlin
// 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 Knut Reinert or the FU Berlin nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ==========================================================================
// Author: Manuel Holtgrewe <[email protected]>
// ==========================================================================
#include <iostream>
#include <seqan/basic.h>
#include <seqan/sequence.h>
#include <seqan/file.h> // For printing SeqAn Strings.
#include <seqan/align.h>
#include <seqan/bam_io.h>
namespace seqan {
template <typename TSource, typename TSpec, typename TReference>
void
createAlignmentFromBamRecord(Align<TSource, TSpec> & result, TReference & reference, BamAlignmentRecord & record)
{
// TODO(holtgrew): Clipping better than copying infix? But is it generic?
resize(rows(result), 2);
assignSource(row(result, 0), infix(reference, record.pos, record.pos + getAlignmentLengthInRef(record)));
cigarToGapAnchorContig(record.cigar, row(result, 0));
assignSource(row(result, 1), record.seq);
// if (hasFlagRC(record)) {
// std::cerr << "RC" << std::endl;
// reverseComplement(source(row(result, 1)));
// }
cigarToGapAnchorRead(record.cigar, row(result, 1));
}
} // namespace seqan
int main(int argc, char const ** argv)
{
using namespace seqan;
// Check command line arguments.
if (argc != 3)
{
std::cerr << "USAGE: bam_print_alignments REF.fasta FILE.bam" << std::endl;
return 1;
}
// Read FASTA file.
std::cerr << "Reading FASTA " << argv[1] << std::endl;
StringSet<CharString> refNameStore;
StringSet<Dna5String> seqs;
std::fstream inSeq(argv[1], std::ios::binary | std::ios::in);
if (!inSeq.good())
{
std::cerr << "Could not open FASTA file " << argv[1] << std::endl;
return 1;
}
RecordReader<std::fstream, SinglePass<> > reader(inSeq);
if (read2(refNameStore, seqs, reader, Fasta()) != 0)
return 1;
// Open BGZF stream.
std::cerr << "Opening BAM " << argv[2] << std::endl;
Stream<Bgzf> stream;
if (!open(stream, argv[2], "r"))
{
std::cerr << "[ERROR] Could not open BAM file" << argv[1] << std::endl;
return 1;
}
// Read Header.
std::cerr << "Reading Header" << std::endl;
NameStoreCache<StringSet<CharString> > refNameStoreCache(refNameStore);
BamIOContext<StringSet<CharString> > context(refNameStore, refNameStoreCache);
BamHeader header;
if (readRecord(header, context, stream, Bam()) != 0)
{
std::cerr << "[ERROR] Could not read header from BAM file!" << std::endl;
return 1;
}
// Stream through file, getting alignment and dumping it.
std::cerr << "Reading Alignments..." << std::endl;
Align<Dna5String> align;
BamAlignmentRecord record;
while (!atEnd(stream))
{
clear(record);
if (readRecord(record, context, stream, Bam()) != 0)
{
std::cerr << "[ERROR] Error reading alignment!" << std::endl;
return 1;
}
if (record.rId == -1)
continue; // Skip * reference.
createAlignmentFromBamRecord(align, seqs[record.rId], record);
write2(std::cout, record, context, Sam());
std::cout << refNameStore[record.rId] << ", " << nameStore(context)[record.rId] << std::endl;
std::cout << align << std::endl;
}
return 0;
}
<commit_msg>Update to ''bam_print_alignments'' demo.<commit_after>// ==========================================================================
// bam_print_alignments.cpp
// ==========================================================================
// Copyright (c) 2006-2010, Knut Reinert, FU Berlin
// 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 Knut Reinert or the FU Berlin nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ==========================================================================
// Author: Manuel Holtgrewe <[email protected]>
// ==========================================================================
#include <iostream>
#include <seqan/basic.h>
#include <seqan/sequence.h>
#include <seqan/file.h> // For printing SeqAn Strings.
#include <seqan/align.h>
#include <seqan/bam_io.h>
namespace seqan {
/**
.Function.
..signature:bamRecordToAlignment(align, reference, record)
..param.align:The alignment to create.
...type:Class.Align
..param.reference:String of Dna, Dna5, ... characters.
...type:Class.String
..param.record:The alignment record to convert.
...type:Class.BamAlignmentRecord
..returns:$void$
..include:seqan/bam_io.h
..example.code:
StringSet<Dna5String> references;
BamAlignment record;
// Read references and record.
Align<Dna5String> align;
if (record.rId != BamAlignmentRecord::INVALID_REFID)
bamRecordToAlignment(align, references[record.refId], record);
*/
template <typename TSource, typename TSpec, typename TReference>
void
bamRecordToAlignment(Align<TSource, TSpec> & result, TReference & reference, BamAlignmentRecord & record)
{
// TODO(holtgrew): Clipping better than copying infix? But is it generic?
resize(rows(result), 2);
assignSource(row(result, 0), infix(reference, record.pos, record.pos + getAlignmentLengthInRef(record)));
cigarToGapAnchorContig(record.cigar, row(result, 0));
assignSource(row(result, 1), record.seq);
cigarToGapAnchorRead(record.cigar, row(result, 1));
}
} // namespace seqan
int main(int argc, char const ** argv)
{
using namespace seqan;
// Check command line arguments.
if (argc != 3)
{
std::cerr << "USAGE: bam_print_alignments REF.fasta FILE.bam" << std::endl;
return 1;
}
// Read FASTA file.
std::cerr << "Reading FASTA " << argv[1] << std::endl;
StringSet<CharString> refNameStore;
StringSet<Dna5String> seqs;
std::fstream inSeq(argv[1], std::ios::binary | std::ios::in);
if (!inSeq.good())
{
std::cerr << "Could not open FASTA file " << argv[1] << std::endl;
return 1;
}
RecordReader<std::fstream, SinglePass<> > reader(inSeq);
if (read2(refNameStore, seqs, reader, Fasta()) != 0)
return 1;
// Open BGZF stream.
std::cerr << "Opening BAM " << argv[2] << std::endl;
Stream<Bgzf> stream;
if (!open(stream, argv[2], "r"))
{
std::cerr << "[ERROR] Could not open BAM file" << argv[1] << std::endl;
return 1;
}
// Read Header.
std::cerr << "Reading Header" << std::endl;
NameStoreCache<StringSet<CharString> > refNameStoreCache(refNameStore);
BamIOContext<StringSet<CharString> > context(refNameStore, refNameStoreCache);
BamHeader header;
if (readRecord(header, context, stream, Bam()) != 0)
{
std::cerr << "[ERROR] Could not read header from BAM file!" << std::endl;
return 1;
}
// Stream through file, getting alignment and dumping it.
std::cerr << "Reading Alignments..." << std::endl;
Align<Dna5String> align;
BamAlignmentRecord record;
while (!atEnd(stream))
{
clear(record);
if (readRecord(record, context, stream, Bam()) != 0)
{
std::cerr << "[ERROR] Error reading alignment!" << std::endl;
return 1;
}
if (record.rId == BamAlignmentRecord::INVALID_REFID)
continue; // Skip * reference.
// Convert BAM record to alignment.
bamRecordToAlignment(align, seqs[record.rId], record);
// Dump record as SAM and the alignment.
write2(std::cout, record, context, Sam());
std::cout << align << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>//===-- main.cpp ------------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// C includes
#include <pthread.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
pthread_t g_thread_1 = NULL;
pthread_t g_thread_2 = NULL;
pthread_t g_thread_3 = NULL;
char *g_char_ptr = NULL;
void
do_bad_thing_with_location(char *char_ptr, char new_val)
{
unsigned what = new_val;
printf("new value written to location(%p) = %u\n", char_ptr, what);
*char_ptr = new_val;
}
uint32_t access_pool (uint32_t flag = 0);
uint32_t
access_pool (uint32_t flag)
{
static pthread_mutex_t g_access_mutex = PTHREAD_MUTEX_INITIALIZER;
if (flag == 0)
::pthread_mutex_lock (&g_access_mutex);
char old_val = *g_char_ptr;
if (flag != 0)
do_bad_thing_with_location(g_char_ptr, old_val + 1);
if (flag == 0)
::pthread_mutex_unlock (&g_access_mutex);
return *g_char_ptr;
}
void *
thread_func (void *arg)
{
uint32_t thread_index = *((uint32_t *)arg);
printf ("%s (thread index = %u) startng...\n", __FUNCTION__, thread_index);
uint32_t count = 0;
uint32_t val;
while (count++ < 15)
{
// random micro second sleep from zero to 3 seconds
int usec = ::rand() % 3000000;
printf ("%s (thread = %u) doing a usleep (%d)...\n", __FUNCTION__, thread_index, usec);
::usleep (usec);
if (count < 7)
val = access_pool ();
else
val = access_pool (1);
printf ("%s (thread = %u) after usleep access_pool returns %d (count=%d)...\n", __FUNCTION__, thread_index, val, count);
}
printf ("%s (thread index = %u) exiting...\n", __FUNCTION__, thread_index);
return NULL;
}
int main (int argc, char const *argv[])
{
int err;
void *thread_result = NULL;
uint32_t thread_index_1 = 1;
uint32_t thread_index_2 = 2;
uint32_t thread_index_3 = 3;
g_char_ptr = (char *)malloc (1);
*g_char_ptr = 0;
// Create 3 threads
err = ::pthread_create (&g_thread_1, NULL, thread_func, &thread_index_1);
err = ::pthread_create (&g_thread_2, NULL, thread_func, &thread_index_2);
err = ::pthread_create (&g_thread_3, NULL, thread_func, &thread_index_3);
printf ("Before turning all three threads loose...\n"); // Set break point at this line.
// Join all of our threads
err = ::pthread_join (g_thread_1, &thread_result);
err = ::pthread_join (g_thread_2, &thread_result);
err = ::pthread_join (g_thread_3, &thread_result);
return 0;
}
<commit_msg>Add synchronization to TestWatchLocation.<commit_after>//===-- main.cpp ------------------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// C includes
#include <pthread.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
pthread_t g_thread_1 = NULL;
pthread_t g_thread_2 = NULL;
pthread_t g_thread_3 = NULL;
pthread_barrier_t g_barrier;
char *g_char_ptr = NULL;
void
do_bad_thing_with_location(char *char_ptr, char new_val)
{
unsigned what = new_val;
printf("new value written to location(%p) = %u\n", char_ptr, what);
*char_ptr = new_val;
}
uint32_t access_pool (uint32_t flag = 0);
uint32_t
access_pool (uint32_t flag)
{
static pthread_mutex_t g_access_mutex = PTHREAD_MUTEX_INITIALIZER;
if (flag == 0)
::pthread_mutex_lock (&g_access_mutex);
char old_val = *g_char_ptr;
if (flag != 0)
do_bad_thing_with_location(g_char_ptr, old_val + 1);
if (flag == 0)
::pthread_mutex_unlock (&g_access_mutex);
return *g_char_ptr;
}
void *
thread_func (void *arg)
{
uint32_t thread_index = *((uint32_t *)arg);
printf ("%s (thread index = %u) startng...\n", __FUNCTION__, thread_index);
pthread_barrier_wait(&g_barrier);
uint32_t count = 0;
uint32_t val;
while (count++ < 15)
{
// random micro second sleep from zero to 3 seconds
int usec = ::rand() % 3000000;
printf ("%s (thread = %u) doing a usleep (%d)...\n", __FUNCTION__, thread_index, usec);
::usleep (usec);
if (count < 7)
val = access_pool ();
else
val = access_pool (1);
printf ("%s (thread = %u) after usleep access_pool returns %d (count=%d)...\n", __FUNCTION__, thread_index, val, count);
}
printf ("%s (thread index = %u) exiting...\n", __FUNCTION__, thread_index);
return NULL;
}
int main (int argc, char const *argv[])
{
int err;
void *thread_result = NULL;
uint32_t thread_index_1 = 1;
uint32_t thread_index_2 = 2;
uint32_t thread_index_3 = 3;
g_char_ptr = (char *)malloc (1);
*g_char_ptr = 0;
pthread_barrier_init(&g_barrier, NULL, 4);
// Create 3 threads
err = ::pthread_create (&g_thread_1, NULL, thread_func, &thread_index_1);
err = ::pthread_create (&g_thread_2, NULL, thread_func, &thread_index_2);
err = ::pthread_create (&g_thread_3, NULL, thread_func, &thread_index_3);
printf ("Before turning all three threads loose...\n"); // Set break point at this line.
pthread_barrier_wait(&g_barrier);
// Join all of our threads
err = ::pthread_join (g_thread_1, &thread_result);
err = ::pthread_join (g_thread_2, &thread_result);
err = ::pthread_join (g_thread_3, &thread_result);
pthread_barrier_destroy(&g_barrier);
free(g_char_ptr);
return 0;
}
<|endoftext|> |
<commit_before>/*
* @file Configuration.cpp
*
* @author <a href="mailto:[email protected]">Thomas Krause</a>
* @author <a href="mailto:[email protected]">Xu Yuan</a>
* @breief the gloabl configuration for NaoTH framework
*
*/
#include "Configuration.h"
#include "Tools/StringTools.h"
#include "Tools/Debug/NaoTHAssert.h"
#include <iostream>
#include <fstream>
#include <string.h>
using namespace naoth;
Configuration::Configuration()
{
publicKeyFile = g_key_file_new();
privateKeyFile = g_key_file_new();
}
Configuration::Configuration(const Configuration& orig)
{
publicKeyFile = g_key_file_new();
privateKeyFile = g_key_file_new();
// copy public key
gsize bufferLength;
gchar* buffer = g_key_file_to_data(orig.publicKeyFile, &bufferLength, NULL);
g_key_file_load_from_data(publicKeyFile, buffer, bufferLength, G_KEY_FILE_NONE, NULL);
g_free(buffer);
// copy private key
buffer = g_key_file_to_data(orig.privateKeyFile, &bufferLength, NULL);
g_key_file_load_from_data(privateKeyFile, buffer, bufferLength, G_KEY_FILE_NONE, NULL);
g_free(buffer);
}
Configuration::~Configuration()
{
if (publicKeyFile != NULL)
{
g_key_file_free(publicKeyFile);
}
if (privateKeyFile != NULL)
{
g_key_file_free(privateKeyFile);
}
}
void Configuration::loadFromDir(std::string dirlocation,
const std::string& platform,
const std::string& scheme,
const std::string& strategy,
const std::string& bodyID,
const std::string& headID,
const std::string& robotName)
{
ASSERT_MSG(isDir(dirlocation), "Could not load configuration from " << dirlocation << ": directory does not exist.");
std::cout << "[INFO] loading configuration from " << dirlocation << std::endl;
if (!g_str_has_suffix(dirlocation.c_str(), "/")) {
dirlocation = dirlocation + "/";
}
loadFromSingleDir(publicKeyFile, dirlocation + "general/");
loadFromSingleDir(publicKeyFile, dirlocation + "platform/" + platform + "/");
if(scheme.size() > 0) {
loadFromSingleDir(publicKeyFile, dirlocation + "scheme/" + scheme + "/");
}
if(strategy.size() > 0) {
loadFromSingleDir(publicKeyFile, dirlocation + "strategy/" + strategy + "/");
}
bool robot_config_required = (platform == "Nao" || platform == "nao");
loadFromSingleDir(publicKeyFile, dirlocation + "robots/" + robotName + "/", robot_config_required);
loadFromSingleDir(publicKeyFile, dirlocation + "robots_bodies/" + bodyID + "/", false);
loadFromSingleDir(publicKeyFile, dirlocation + "robot_heads/" + headID + "/", false);
privateDir = dirlocation + "private/";
loadFromSingleDir(privateKeyFile, privateDir);
}
void Configuration::loadFromSingleDir(GKeyFile* keyFile, std::string dirlocation, bool required)
{
// make sure the directory exists
ASSERT_MSG(!required || isDir(dirlocation), "Could not load configuration from " << dirlocation << ": directory does not exist.");
if (!g_str_has_suffix(dirlocation.c_str(), "/")) {
dirlocation = dirlocation + "/";
}
// iterate over all files in the folder
GDir* dir = g_dir_open(dirlocation.c_str(), 0, NULL);
if (dir != NULL)
{
const gchar* name;
while ((name = g_dir_read_name(dir)) != NULL)
{
if (g_str_has_suffix(name, ".cfg"))
{
gchar* group = g_strndup(name, strlen(name) - strlen(".cfg"));
std::string completeFileName = dirlocation + name;
if (g_file_test(completeFileName.c_str(), G_FILE_TEST_EXISTS)
&& g_file_test(completeFileName.c_str(), G_FILE_TEST_IS_REGULAR))
{
loadFile(keyFile, completeFileName, std::string(group));
}
g_free(group);
}
}
g_dir_close(dir);
}
}
void Configuration::loadFile(GKeyFile* keyFile, std::string file, std::string groupName)
{
GError* err = NULL;
GKeyFile* tmpKeyFile = g_key_file_new();
g_key_file_load_from_file(tmpKeyFile, file.c_str(), G_KEY_FILE_NONE, &err);
if (err != NULL)
{
std::cerr << "[ERROR] " << file << ": " << err->message << std::endl;
g_error_free(err);
} else
{
// syntactically correct, check if there is only one group with the same
// name as the file
bool groupOK = true;
gsize numOfGroups;
gchar** groups = g_key_file_get_groups(tmpKeyFile, &numOfGroups);
for (gsize i = 0; groupOK && i < numOfGroups; i++)
{
if (g_strcmp0(groups[i], groupName.c_str()) != 0)
{
groupOK = false;
std::cerr << "[ERROR] " << file << ": config file contains illegal group \"" << groups[i] << "\"" << std::endl;
break;
}
}
if(groupOK && numOfGroups == 1)
{
// copy every single value to our configuration
gsize numOfKeys = 0;
gchar** keys = g_key_file_get_keys(tmpKeyFile, groups[0], &numOfKeys, NULL);
for(gsize i=0; i < numOfKeys; i++)
{
gchar* buffer = g_key_file_get_value(tmpKeyFile, groups[0], keys[i], NULL);
g_key_file_set_value(keyFile, groups[0], keys[i], buffer);
g_free(buffer);
}
g_strfreev(keys);
std::cout << "[INFO] loaded " << file << std::endl;
}
g_strfreev(groups);
}
g_key_file_free(tmpKeyFile);
}
void Configuration::save()
{
if (privateDir.empty())
return;
gsize length = 0;
gchar** groups = g_key_file_get_groups(privateKeyFile, &length);
for(gsize i=0; i < length; i++)
{
std::string groupname = std::string(groups[i]);
std::string filename = privateDir + groupname + ".cfg";
saveFile(privateKeyFile, filename, groupname );
}
g_strfreev(groups);
}
void Configuration::saveFile(GKeyFile* keyFile, const std::string& file, const std::string& group)
{
GKeyFile* tmpKeyFile = g_key_file_new();
gsize numOfKeys = 0;
gchar** keys = g_key_file_get_keys(keyFile, group.c_str(), &numOfKeys, NULL);
for(gsize i=0; i < numOfKeys; i++)
{
GError* err = NULL;
gchar* buffer = g_key_file_get_value(keyFile, group.c_str(), keys[i], &err);
if(err != NULL)
{
std::cout << "[WARN] " << err->message << std::endl;
}
g_key_file_set_value(tmpKeyFile, group.c_str(), keys[i], buffer);
g_free(buffer);
}
GError* err = NULL;
gsize dataLength;
gchar* data = g_key_file_to_data(tmpKeyFile, &dataLength, &err);
if(err == NULL)
{
if(dataLength > 0)
{
std::ofstream outFile(file.c_str(), std::ios::out);
if(outFile.is_open()) {
outFile.write(data, dataLength);
outFile.close();
} else {
std::cerr << "[ERROR] could not open the file " << file << std::endl;
}
g_free(data);
}
}
else
{
std::cerr << "[ERROR] could not save configuration file " << file << ": " << err->message << std::endl;
g_error_free(err);
}
g_key_file_free(tmpKeyFile);
}
std::set<std::string> Configuration::getKeys(const std::string& group) const
{
std::set<std::string> result;
// public keys
gsize length = 0;
gchar** keys = g_key_file_get_keys(publicKeyFile, group.c_str(), &length, NULL);
for(gsize i=0; i < length; i++)
{
result.insert(std::string(keys[i]));
}
g_strfreev(keys);
// private keys
length = 0;
keys = g_key_file_get_keys(privateKeyFile, group.c_str(), &length, NULL);
for(gsize i=0; i < length; i++)
{
result.insert(std::string(keys[i]));
}
g_strfreev(keys);
return result;
}
bool Configuration::hasKey(const std::string& group, const std::string& key) const
{
return ( g_key_file_has_key(publicKeyFile, group.c_str(), key.c_str(), NULL) > 0 )
|| ( g_key_file_has_key(privateKeyFile, group.c_str(), key.c_str(), NULL) > 0 );
}
bool Configuration::hasGroup(const std::string& group) const
{
return ( g_key_file_has_group(publicKeyFile, group.c_str()) > 0 )
|| ( g_key_file_has_group(privateKeyFile, group.c_str()) > 0 );
}
std::string Configuration::getString(const std::string& group, const std::string& key) const
{
GKeyFile* keyFile = chooseKeyFile(group, key);
gchar* buf = g_key_file_get_string(keyFile, group.c_str(), key.c_str(), NULL);
if (buf != NULL)
{
std::string result(buf);
g_free(buf);
return result;
}
return "";
}
void Configuration::setString(const std::string& group, const std::string& key, const std::string& value)
{
g_key_file_set_string(privateKeyFile, group.c_str(), key.c_str(), value.c_str());
}
void Configuration::setDefault(const std::string& group, const std::string& key, const std::string& value)
{
g_key_file_set_string(publicKeyFile, group.c_str(), key.c_str(), value.c_str());
}
std::string Configuration::getRawValue(const std::string& group, const std::string& key) const
{
GKeyFile* keyFile = chooseKeyFile(group, key);
gchar* buf = g_key_file_get_value(keyFile, group.c_str(), key.c_str(), NULL);
if (buf != NULL)
{
std::string result(buf);
g_free(buf);
return result;
}
return "";
}
void Configuration::setRawValue(const std::string& group, const std::string& key, const std::string& value)
{
g_key_file_set_value(privateKeyFile, group.c_str(), key.c_str(), value.c_str());
}
int Configuration::getInt(const std::string& group, const std::string& key) const
{
GKeyFile* keyFile = chooseKeyFile(group, key);
return g_key_file_get_integer(keyFile, group.c_str(), key.c_str(), NULL);
}
void Configuration::setInt(const std::string& group, const std::string& key, int value)
{
g_key_file_set_integer(privateKeyFile, group.c_str(), key.c_str(), value);
}
void Configuration::setDefault(const std::string& group, const std::string& key, int value)
{
g_key_file_set_integer(publicKeyFile, group.c_str(), key.c_str(), value);
}
void Configuration::setDefault(const std::string& group, const std::string& key, unsigned int value)
{
// todo check it!
int tmp = (int)value;
//ASSERT(tmp > 0);
g_key_file_set_integer(publicKeyFile, group.c_str(), key.c_str(), tmp);
}
double Configuration::getDouble(const std::string& group, const std::string& key) const
{
GKeyFile* keyFile = chooseKeyFile(group, key);
return g_key_file_get_double(keyFile, group.c_str(), key.c_str(), NULL);
}
void Configuration::setDouble(const std::string& group, const std::string& key, double value)
{
//g_key_file_set_double(privateKeyFile, group.c_str(), key.c_str(), value);
// the function above produce unecessary zeros
g_key_file_set_string(privateKeyFile, group.c_str(), key.c_str(), StringTools::toStr(value).c_str());
}
void Configuration::setDefault(const std::string& group, const std::string& key, double value)
{
g_key_file_set_string(publicKeyFile, group.c_str(), key.c_str(), StringTools::toStr(value).c_str());
}
bool Configuration::getBool(const std::string& group, const std::string& key) const
{
GKeyFile* keyFile = chooseKeyFile(group, key);
return g_key_file_get_boolean(keyFile, group.c_str(), key.c_str(), NULL) > 0;
}
void Configuration::setBool(const std::string& group, const std::string& key, bool value)
{
g_key_file_set_boolean(privateKeyFile, group.c_str(), key.c_str(), value);
}
void Configuration::setDefault(const std::string& group, const std::string& key, bool value)
{
g_key_file_set_boolean(publicKeyFile, group.c_str(), key.c_str(), value);
}
<commit_msg>Avoid that our C++ constructors generate a GLib error when accessing a non-existant configuration group.<commit_after>/*
* @file Configuration.cpp
*
* @author <a href="mailto:[email protected]">Thomas Krause</a>
* @author <a href="mailto:[email protected]">Xu Yuan</a>
* @breief the gloabl configuration for NaoTH framework
*
*/
#include "Configuration.h"
#include "Tools/StringTools.h"
#include "Tools/Debug/NaoTHAssert.h"
#include <iostream>
#include <fstream>
#include <string.h>
using namespace naoth;
Configuration::Configuration()
{
publicKeyFile = g_key_file_new();
privateKeyFile = g_key_file_new();
}
Configuration::Configuration(const Configuration& orig)
{
publicKeyFile = g_key_file_new();
privateKeyFile = g_key_file_new();
// copy public key
gsize bufferLength;
gchar* buffer = g_key_file_to_data(orig.publicKeyFile, &bufferLength, NULL);
g_key_file_load_from_data(publicKeyFile, buffer, bufferLength, G_KEY_FILE_NONE, NULL);
g_free(buffer);
// copy private key
buffer = g_key_file_to_data(orig.privateKeyFile, &bufferLength, NULL);
g_key_file_load_from_data(privateKeyFile, buffer, bufferLength, G_KEY_FILE_NONE, NULL);
g_free(buffer);
}
Configuration::~Configuration()
{
if (publicKeyFile != NULL)
{
g_key_file_free(publicKeyFile);
}
if (privateKeyFile != NULL)
{
g_key_file_free(privateKeyFile);
}
}
void Configuration::loadFromDir(std::string dirlocation,
const std::string& platform,
const std::string& scheme,
const std::string& strategy,
const std::string& bodyID,
const std::string& headID,
const std::string& robotName)
{
ASSERT_MSG(isDir(dirlocation), "Could not load configuration from " << dirlocation << ": directory does not exist.");
std::cout << "[INFO] loading configuration from " << dirlocation << std::endl;
if (!g_str_has_suffix(dirlocation.c_str(), "/")) {
dirlocation = dirlocation + "/";
}
loadFromSingleDir(publicKeyFile, dirlocation + "general/");
loadFromSingleDir(publicKeyFile, dirlocation + "platform/" + platform + "/");
if(scheme.size() > 0) {
loadFromSingleDir(publicKeyFile, dirlocation + "scheme/" + scheme + "/");
}
if(strategy.size() > 0) {
loadFromSingleDir(publicKeyFile, dirlocation + "strategy/" + strategy + "/");
}
bool robot_config_required = (platform == "Nao" || platform == "nao");
loadFromSingleDir(publicKeyFile, dirlocation + "robots/" + robotName + "/", robot_config_required);
loadFromSingleDir(publicKeyFile, dirlocation + "robots_bodies/" + bodyID + "/", false);
loadFromSingleDir(publicKeyFile, dirlocation + "robot_heads/" + headID + "/", false);
privateDir = dirlocation + "private/";
loadFromSingleDir(privateKeyFile, privateDir);
}
void Configuration::loadFromSingleDir(GKeyFile* keyFile, std::string dirlocation, bool required)
{
// make sure the directory exists
ASSERT_MSG(!required || isDir(dirlocation), "Could not load configuration from " << dirlocation << ": directory does not exist.");
if (!g_str_has_suffix(dirlocation.c_str(), "/")) {
dirlocation = dirlocation + "/";
}
// iterate over all files in the folder
GDir* dir = g_dir_open(dirlocation.c_str(), 0, NULL);
if (dir != NULL)
{
const gchar* name;
while ((name = g_dir_read_name(dir)) != NULL)
{
if (g_str_has_suffix(name, ".cfg"))
{
gchar* group = g_strndup(name, strlen(name) - strlen(".cfg"));
std::string completeFileName = dirlocation + name;
if (g_file_test(completeFileName.c_str(), G_FILE_TEST_EXISTS)
&& g_file_test(completeFileName.c_str(), G_FILE_TEST_IS_REGULAR))
{
loadFile(keyFile, completeFileName, std::string(group));
}
g_free(group);
}
}
g_dir_close(dir);
}
}
void Configuration::loadFile(GKeyFile* keyFile, std::string file, std::string groupName)
{
GError* err = NULL;
GKeyFile* tmpKeyFile = g_key_file_new();
g_key_file_load_from_file(tmpKeyFile, file.c_str(), G_KEY_FILE_NONE, &err);
if (err != NULL)
{
std::cerr << "[ERROR] " << file << ": " << err->message << std::endl;
g_error_free(err);
} else
{
// syntactically correct, check if there is only one group with the same
// name as the file
bool groupOK = true;
gsize numOfGroups;
gchar** groups = g_key_file_get_groups(tmpKeyFile, &numOfGroups);
for (gsize i = 0; groupOK && i < numOfGroups; i++)
{
if (g_strcmp0(groups[i], groupName.c_str()) != 0)
{
groupOK = false;
std::cerr << "[ERROR] " << file << ": config file contains illegal group \"" << groups[i] << "\"" << std::endl;
break;
}
}
if(groupOK && numOfGroups == 1)
{
// copy every single value to our configuration
gsize numOfKeys = 0;
gchar** keys = g_key_file_get_keys(tmpKeyFile, groups[0], &numOfKeys, NULL);
for(gsize i=0; i < numOfKeys; i++)
{
gchar* buffer = g_key_file_get_value(tmpKeyFile, groups[0], keys[i], NULL);
g_key_file_set_value(keyFile, groups[0], keys[i], buffer);
g_free(buffer);
}
g_strfreev(keys);
std::cout << "[INFO] loaded " << file << std::endl;
}
g_strfreev(groups);
}
g_key_file_free(tmpKeyFile);
}
void Configuration::save()
{
if (privateDir.empty())
return;
gsize length = 0;
gchar** groups = g_key_file_get_groups(privateKeyFile, &length);
for(gsize i=0; i < length; i++)
{
std::string groupname = std::string(groups[i]);
std::string filename = privateDir + groupname + ".cfg";
saveFile(privateKeyFile, filename, groupname );
}
g_strfreev(groups);
}
void Configuration::saveFile(GKeyFile* keyFile, const std::string& file, const std::string& group)
{
GKeyFile* tmpKeyFile = g_key_file_new();
gsize numOfKeys = 0;
gchar** keys = g_key_file_get_keys(keyFile, group.c_str(), &numOfKeys, NULL);
for(gsize i=0; i < numOfKeys; i++)
{
GError* err = NULL;
gchar* buffer = g_key_file_get_value(keyFile, group.c_str(), keys[i], &err);
if(err != NULL)
{
std::cout << "[WARN] " << err->message << std::endl;
}
g_key_file_set_value(tmpKeyFile, group.c_str(), keys[i], buffer);
g_free(buffer);
}
GError* err = NULL;
gsize dataLength;
gchar* data = g_key_file_to_data(tmpKeyFile, &dataLength, &err);
if(err == NULL)
{
if(dataLength > 0)
{
std::ofstream outFile(file.c_str(), std::ios::out);
if(outFile.is_open()) {
outFile.write(data, dataLength);
outFile.close();
} else {
std::cerr << "[ERROR] could not open the file " << file << std::endl;
}
g_free(data);
}
}
else
{
std::cerr << "[ERROR] could not save configuration file " << file << ": " << err->message << std::endl;
g_error_free(err);
}
g_key_file_free(tmpKeyFile);
}
std::set<std::string> Configuration::getKeys(const std::string& group) const
{
std::set<std::string> result;
// public keys
gsize length = 0;
gchar** keys = g_key_file_get_keys(publicKeyFile, group.c_str(), &length, NULL);
for(gsize i=0; i < length; i++)
{
result.insert(std::string(keys[i]));
}
g_strfreev(keys);
// private keys
length = 0;
keys = g_key_file_get_keys(privateKeyFile, group.c_str(), &length, NULL);
for(gsize i=0; i < length; i++)
{
result.insert(std::string(keys[i]));
}
g_strfreev(keys);
return result;
}
bool Configuration::hasKey(const std::string& group, const std::string& key) const
{
// HACK: If the group does not exist, g_key_file_has_key will log a GLib error and we need to avoid this at all cost.
// This function is called from constructors (e.g. via syncWithConfig()) and if any constructor generates a GLib error,
// newer versions of GLib will crash due the way they internally map string constants to internal IDs:
// https://gitlab.gnome.org/GNOME/glib/-/issues/1177
return (g_key_file_has_group(publicKeyFile, group.c_str()) && g_key_file_has_key(publicKeyFile, group.c_str(), key.c_str(), NULL) > 0 )
|| (g_key_file_has_group(privateKeyFile, group.c_str()) && g_key_file_has_key(privateKeyFile, group.c_str(), key.c_str(), NULL) > 0 );
}
bool Configuration::hasGroup(const std::string& group) const
{
return ( g_key_file_has_group(publicKeyFile, group.c_str()) > 0 )
|| ( g_key_file_has_group(privateKeyFile, group.c_str()) > 0 );
}
std::string Configuration::getString(const std::string& group, const std::string& key) const
{
GKeyFile* keyFile = chooseKeyFile(group, key);
gchar* buf = g_key_file_get_string(keyFile, group.c_str(), key.c_str(), NULL);
if (buf != NULL)
{
std::string result(buf);
g_free(buf);
return result;
}
return "";
}
void Configuration::setString(const std::string& group, const std::string& key, const std::string& value)
{
g_key_file_set_string(privateKeyFile, group.c_str(), key.c_str(), value.c_str());
}
void Configuration::setDefault(const std::string& group, const std::string& key, const std::string& value)
{
g_key_file_set_string(publicKeyFile, group.c_str(), key.c_str(), value.c_str());
}
std::string Configuration::getRawValue(const std::string& group, const std::string& key) const
{
GKeyFile* keyFile = chooseKeyFile(group, key);
gchar* buf = g_key_file_get_value(keyFile, group.c_str(), key.c_str(), NULL);
if (buf != NULL)
{
std::string result(buf);
g_free(buf);
return result;
}
return "";
}
void Configuration::setRawValue(const std::string& group, const std::string& key, const std::string& value)
{
g_key_file_set_value(privateKeyFile, group.c_str(), key.c_str(), value.c_str());
}
int Configuration::getInt(const std::string& group, const std::string& key) const
{
GKeyFile* keyFile = chooseKeyFile(group, key);
return g_key_file_get_integer(keyFile, group.c_str(), key.c_str(), NULL);
}
void Configuration::setInt(const std::string& group, const std::string& key, int value)
{
g_key_file_set_integer(privateKeyFile, group.c_str(), key.c_str(), value);
}
void Configuration::setDefault(const std::string& group, const std::string& key, int value)
{
g_key_file_set_integer(publicKeyFile, group.c_str(), key.c_str(), value);
}
void Configuration::setDefault(const std::string& group, const std::string& key, unsigned int value)
{
// todo check it!
int tmp = (int)value;
//ASSERT(tmp > 0);
g_key_file_set_integer(publicKeyFile, group.c_str(), key.c_str(), tmp);
}
double Configuration::getDouble(const std::string& group, const std::string& key) const
{
GKeyFile* keyFile = chooseKeyFile(group, key);
return g_key_file_get_double(keyFile, group.c_str(), key.c_str(), NULL);
}
void Configuration::setDouble(const std::string& group, const std::string& key, double value)
{
//g_key_file_set_double(privateKeyFile, group.c_str(), key.c_str(), value);
// the function above produce unecessary zeros
g_key_file_set_string(privateKeyFile, group.c_str(), key.c_str(), StringTools::toStr(value).c_str());
}
void Configuration::setDefault(const std::string& group, const std::string& key, double value)
{
g_key_file_set_string(publicKeyFile, group.c_str(), key.c_str(), StringTools::toStr(value).c_str());
}
bool Configuration::getBool(const std::string& group, const std::string& key) const
{
GKeyFile* keyFile = chooseKeyFile(group, key);
return g_key_file_get_boolean(keyFile, group.c_str(), key.c_str(), NULL) > 0;
}
void Configuration::setBool(const std::string& group, const std::string& key, bool value)
{
g_key_file_set_boolean(privateKeyFile, group.c_str(), key.c_str(), value);
}
void Configuration::setDefault(const std::string& group, const std::string& key, bool value)
{
g_key_file_set_boolean(publicKeyFile, group.c_str(), key.c_str(), value);
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperCompositeApplication.h"
#include "otbWrapperProxyParameter.h"
#include "otbWrapperApplicationRegistry.h"
#include "otbWrapperAddProcessToWatchEvent.h"
#include "otbWrapperParameterKey.h"
namespace otb
{
namespace Wrapper
{
CompositeApplication::CompositeApplication()
{
m_LogOutput = itk::StdStreamLogOutput::New();
m_LogOutput->SetStream(m_Oss);
m_AddProcessCommand = AddProcessCommandType::New();
m_AddProcessCommand->SetCallbackFunction(this, &CompositeApplication::LinkWatchers);
}
CompositeApplication::~CompositeApplication()
{
}
void
CompositeApplication
::LinkWatchers(itk::Object * itkNotUsed(caller), const itk::EventObject & event)
{
if (typeid(AddProcessToWatchEvent) == typeid( event ))
{
this->InvokeEvent(event);
}
}
bool
CompositeApplication
::AddApplication(std::string appType, std::string key, std::string desc)
{
if (m_AppContainer.count(key))
{
otbAppLogWARNING("The requested identifier for internal application is already used ("<<key<<")");
return false;
}
InternalApplication container;
container.App = ApplicationRegistry::CreateApplication(appType);
container.Desc = desc;
// Setup logger
container.App->GetLogger()->AddLogOutput(m_LogOutput);
container.App->GetLogger()->SetTimeStampFormat(itk::LoggerBase::HUMANREADABLE);
container.App->AddObserver(AddProcessToWatchEvent(), m_AddProcessCommand.GetPointer());
m_AppContainer[key] = container;
return true;
}
bool
CompositeApplication
::Connect(std::string fromKey, std::string toKey)
{
std::string key1(fromKey);
std::string key2(toKey);
Application *app1 = DecodeKey(key1);
Application *app2 = DecodeKey(key2);
Parameter* rawParam1 = app1->GetParameterByKey(key1, false);
if (dynamic_cast<ProxyParameter*>(rawParam1))
{
otbAppLogWARNING("Parameter is already connected ! Override current connection");
}
ProxyParameter::Pointer proxyParam = ProxyParameter::New();
ProxyParameter::ProxyTargetType target;
target.first = app2->GetParameterList();
target.second = key2;
proxyParam->SetTarget(target);
proxyParam->SetName(rawParam1->GetName());
proxyParam->SetDescription(rawParam1->GetDescription());
return app1->GetParameterList()->ReplaceParameter(key1, proxyParam.GetPointer());
}
bool
CompositeApplication
::ShareParameter(std::string localKey,
std::string internalKey,
std::string name,
std::string desc)
{
std::string internalKeyCheck(internalKey);
Application *app = DecodeKey(internalKeyCheck);
Parameter* rawTarget = app->GetParameterByKey(internalKeyCheck, false);
// Check source
ParameterKey pKey(localKey);
std::string proxyKey(pKey.GetLastElement());
// Create and setup proxy parameter
ProxyParameter::Pointer proxyParam = ProxyParameter::New();
ProxyParameter::ProxyTargetType target;
target.first = app->GetParameterList();
target.second = internalKeyCheck;
proxyParam->SetTarget(target);
proxyParam->SetName( name.empty() ? rawTarget->GetName() : name);
proxyParam->SetDescription(desc.empty() ? rawTarget->GetDescription() : desc);
proxyParam->SetKey(proxyKey);
// Get group parameter where the proxy should be added
Parameter::Pointer baseParam(proxyParam.GetPointer());
ParameterGroup *parentGroup = this->GetParameterList();
if (localKey.find('.') != std::string::npos)
{
Parameter::Pointer parentParam = this->GetParameterList()->GetParameterByKey(pKey.GetRoot());
parentGroup = dynamic_cast<ParameterGroup*>(parentParam.GetPointer());
baseParam->SetRoot(parentGroup);
parentGroup->AddChild(baseParam);
}
parentGroup->AddParameter(baseParam);
return true;
}
Application*
CompositeApplication
::DecodeKey(std::string &key)
{
Application *ret = this;
size_t pos = key.find('.');
if (pos != std::string::npos && m_AppContainer.count(key.substr(0,pos)))
{
ret = m_AppContainer[key.substr(0,pos)].App;
key = key.substr(pos+1);
}
return ret;
}
Application*
CompositeApplication
::GetInternalApplication(std::string id)
{
if (!m_AppContainer.count(id))
otbAppLogFATAL("Unknown internal application : "<<id);
return m_AppContainer[id].App;
}
std::string
CompositeApplication
::GetInternalAppDescription(std::string id)
{
if (!m_AppContainer.count(id))
otbAppLogFATAL("Unknown internal application : "<<id);
return m_AppContainer[id].Desc;
}
void
CompositeApplication
::ExecuteInternal(std::string key)
{
otbAppLogINFO(<< GetInternalAppDescription(key) <<"...");
GetInternalApplication(key)->Execute();
otbAppLogINFO(<< "\n" << m_Oss.str());
m_Oss.str(std::string(""));
}
void
CompositeApplication
::UpdateInternalParameters(std::string key)
{
GetInternalApplication(key)->UpdateParameters();
}
} // end namespace Wrapper
} // end namespace otb
<commit_msg>ENH: allow error message from internal application to appear in composite application<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperCompositeApplication.h"
#include "otbWrapperProxyParameter.h"
#include "otbWrapperApplicationRegistry.h"
#include "otbWrapperAddProcessToWatchEvent.h"
#include "otbWrapperParameterKey.h"
namespace otb
{
namespace Wrapper
{
CompositeApplication::CompositeApplication()
{
m_LogOutput = itk::StdStreamLogOutput::New();
m_LogOutput->SetStream(m_Oss);
m_AddProcessCommand = AddProcessCommandType::New();
m_AddProcessCommand->SetCallbackFunction(this, &CompositeApplication::LinkWatchers);
}
CompositeApplication::~CompositeApplication()
{
}
void
CompositeApplication
::LinkWatchers(itk::Object * itkNotUsed(caller), const itk::EventObject & event)
{
if (typeid(AddProcessToWatchEvent) == typeid( event ))
{
this->InvokeEvent(event);
}
}
bool
CompositeApplication
::AddApplication(std::string appType, std::string key, std::string desc)
{
if (m_AppContainer.count(key))
{
otbAppLogWARNING("The requested identifier for internal application is already used ("<<key<<")");
return false;
}
InternalApplication container;
container.App = ApplicationRegistry::CreateApplication(appType);
container.Desc = desc;
// Setup logger
container.App->GetLogger()->AddLogOutput(m_LogOutput);
container.App->GetLogger()->SetTimeStampFormat(itk::LoggerBase::HUMANREADABLE);
container.App->AddObserver(AddProcessToWatchEvent(), m_AddProcessCommand.GetPointer());
m_AppContainer[key] = container;
return true;
}
bool
CompositeApplication
::Connect(std::string fromKey, std::string toKey)
{
std::string key1(fromKey);
std::string key2(toKey);
Application *app1 = DecodeKey(key1);
Application *app2 = DecodeKey(key2);
Parameter* rawParam1 = app1->GetParameterByKey(key1, false);
if (dynamic_cast<ProxyParameter*>(rawParam1))
{
otbAppLogWARNING("Parameter is already connected ! Override current connection");
}
ProxyParameter::Pointer proxyParam = ProxyParameter::New();
ProxyParameter::ProxyTargetType target;
target.first = app2->GetParameterList();
target.second = key2;
proxyParam->SetTarget(target);
proxyParam->SetName(rawParam1->GetName());
proxyParam->SetDescription(rawParam1->GetDescription());
return app1->GetParameterList()->ReplaceParameter(key1, proxyParam.GetPointer());
}
bool
CompositeApplication
::ShareParameter(std::string localKey,
std::string internalKey,
std::string name,
std::string desc)
{
std::string internalKeyCheck(internalKey);
Application *app = DecodeKey(internalKeyCheck);
Parameter* rawTarget = app->GetParameterByKey(internalKeyCheck, false);
// Check source
ParameterKey pKey(localKey);
std::string proxyKey(pKey.GetLastElement());
// Create and setup proxy parameter
ProxyParameter::Pointer proxyParam = ProxyParameter::New();
ProxyParameter::ProxyTargetType target;
target.first = app->GetParameterList();
target.second = internalKeyCheck;
proxyParam->SetTarget(target);
proxyParam->SetName( name.empty() ? rawTarget->GetName() : name);
proxyParam->SetDescription(desc.empty() ? rawTarget->GetDescription() : desc);
proxyParam->SetKey(proxyKey);
// Get group parameter where the proxy should be added
Parameter::Pointer baseParam(proxyParam.GetPointer());
ParameterGroup *parentGroup = this->GetParameterList();
if (localKey.find('.') != std::string::npos)
{
Parameter::Pointer parentParam = this->GetParameterList()->GetParameterByKey(pKey.GetRoot());
parentGroup = dynamic_cast<ParameterGroup*>(parentParam.GetPointer());
baseParam->SetRoot(parentGroup);
parentGroup->AddChild(baseParam);
}
parentGroup->AddParameter(baseParam);
return true;
}
Application*
CompositeApplication
::DecodeKey(std::string &key)
{
Application *ret = this;
size_t pos = key.find('.');
if (pos != std::string::npos && m_AppContainer.count(key.substr(0,pos)))
{
ret = m_AppContainer[key.substr(0,pos)].App;
key = key.substr(pos+1);
}
return ret;
}
Application*
CompositeApplication
::GetInternalApplication(std::string id)
{
if (!m_AppContainer.count(id))
otbAppLogFATAL("Unknown internal application : "<<id);
return m_AppContainer[id].App;
}
std::string
CompositeApplication
::GetInternalAppDescription(std::string id)
{
if (!m_AppContainer.count(id))
otbAppLogFATAL("Unknown internal application : "<<id);
return m_AppContainer[id].Desc;
}
void
CompositeApplication
::ExecuteInternal(std::string key)
{
otbAppLogINFO(<< GetInternalAppDescription(key) <<"...");
try
{
GetInternalApplication(key)->Execute();
}
catch(...)
{
this->GetLogger()->Write( itk::LoggerBase::FATAL, std::string("\n") + m_Oss.str() );
throw;
}
otbAppLogINFO(<< "\n" << m_Oss.str());
m_Oss.str(std::string(""));
}
void
CompositeApplication
::UpdateInternalParameters(std::string key)
{
GetInternalApplication(key)->UpdateParameters();
}
} // end namespace Wrapper
} // end namespace otb
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: spritecanvas.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: obo $ $Date: 2006-09-17 03:31:24 $
*
* 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_canvas.hxx"
#include <canvas/debug.hxx>
#include <canvas/verbosetrace.hxx>
#include <canvas/canvastools.hxx>
#include <com/sun/star/registry/XRegistryKey.hpp>
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <cppuhelper/factory.hxx>
#include <cppuhelper/implementationentry.hxx>
#include <vcl/canvastools.hxx>
#include <vcl/outdev.hxx>
#include <vcl/window.hxx>
#include <vcl/bitmapex.hxx>
#include <basegfx/tools/canvastools.hxx>
#include <algorithm>
#include "spritecanvas.hxx"
using namespace ::com::sun::star;
#define IMPLEMENTATION_NAME "VCLCanvas::SpriteCanvas"
#define SERVICE_NAME "com.sun.star.rendering.VCLCanvas"
namespace
{
static ::rtl::OUString SAL_CALL getImplementationName_SpriteCanvas()
{
return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( IMPLEMENTATION_NAME ) );
}
static uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames_SpriteCanvas()
{
uno::Sequence< ::rtl::OUString > aRet(1);
aRet[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME ) );
return aRet;
}
}
namespace vclcanvas
{
SpriteCanvas::SpriteCanvas( const uno::Reference< uno::XComponentContext >& rxContext ) :
mxComponentContext( rxContext )
{
OSL_TRACE( "SpriteCanvas created" );
// add our own property to GraphicDevice
maPropHelper.addProperties(
::canvas::PropertySetHelper::MakeMap
("UnsafeScrolling",
boost::bind(&SpriteCanvasHelper::isUnsafeScrolling,
boost::ref(maCanvasHelper)),
boost::bind(&SpriteCanvasHelper::enableUnsafeScrolling,
boost::ref(maCanvasHelper),
_1))
("SpriteBounds",
boost::bind(&SpriteCanvasHelper::isSpriteBounds,
boost::ref(maCanvasHelper)),
boost::bind(&SpriteCanvasHelper::enableSpriteBounds,
boost::ref(maCanvasHelper),
_1)));
}
SpriteCanvas::~SpriteCanvas()
{
OSL_TRACE( "SpriteCanvas destroyed" );
}
void SAL_CALL SpriteCanvas::disposing()
{
tools::LocalGuard aGuard;
mxComponentContext.clear();
// forward to parent
SpriteCanvasBaseT::disposing();
}
::sal_Bool SAL_CALL SpriteCanvas::showBuffer( ::sal_Bool bUpdateAll ) throw (uno::RuntimeException)
{
tools::LocalGuard aGuard;
// avoid repaints on hidden window (hidden: not mapped to
// screen). Return failure, since the screen really has _not_
// been updated (caller should try again later)
return !mbIsVisible ? false : SpriteCanvasBaseT::showBuffer( bUpdateAll );
}
::sal_Bool SAL_CALL SpriteCanvas::switchBuffer( ::sal_Bool bUpdateAll ) throw (uno::RuntimeException)
{
tools::LocalGuard aGuard;
// avoid repaints on hidden window (hidden: not mapped to
// screen). Return failure, since the screen really has _not_
// been updated (caller should try again later)
return !mbIsVisible ? false : SpriteCanvasBaseT::switchBuffer( bUpdateAll );
}
sal_Bool SAL_CALL SpriteCanvas::updateScreen( sal_Bool bUpdateAll ) throw (uno::RuntimeException)
{
tools::LocalGuard aGuard;
// avoid repaints on hidden window (hidden: not mapped to
// screen). Return failure, since the screen really has _not_
// been updated (caller should try again later)
return !mbIsVisible ? false : maCanvasHelper.updateScreen(bUpdateAll,
mbSurfaceDirty);
}
void SAL_CALL SpriteCanvas::initialize( const uno::Sequence< uno::Any >& aArguments ) throw( uno::Exception,
uno::RuntimeException)
{
tools::LocalGuard aGuard;
VERBOSE_TRACE( "VCLSpriteCanvas::initialize called" );
CHECK_AND_THROW( aArguments.getLength() >= 1,
"SpriteCanvas::initialize: wrong number of arguments" );
// We expect a single Any here, containing a pointer to a valid
// VCL window, on which to output
if( aArguments.getLength() >= 1 &&
aArguments[0].getValueTypeClass() == uno::TypeClass_HYPER )
{
sal_Int64 nWindowPtr = 0;
aArguments[0] >>= nWindowPtr;
Window* pOutputWindow = reinterpret_cast<Window*>(nWindowPtr);
CHECK_AND_THROW( pOutputWindow != NULL,
"SpriteCanvas::initialize: invalid Window pointer" );
// setup helper
maDeviceHelper.init( *pOutputWindow,
*this );
maCanvasHelper.init( *this,
maDeviceHelper.getBackBuffer(),
false, // no OutDev state preservation
false ); // no alpha on surface
maCanvasHelper.setRedrawManager( maRedrawManager );
}
}
::rtl::OUString SAL_CALL SpriteCanvas::getImplementationName() throw( uno::RuntimeException )
{
return getImplementationName_SpriteCanvas();
}
sal_Bool SAL_CALL SpriteCanvas::supportsService( const ::rtl::OUString& ServiceName ) throw( uno::RuntimeException )
{
return ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME ) );
}
uno::Sequence< ::rtl::OUString > SAL_CALL SpriteCanvas::getSupportedServiceNames() throw( uno::RuntimeException )
{
return getSupportedServiceNames_SpriteCanvas();
}
::rtl::OUString SAL_CALL SpriteCanvas::getServiceName( ) throw (::com::sun::star::uno::RuntimeException)
{
return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( SERVICE_NAME ) );
}
uno::Reference< uno::XInterface > SAL_CALL SpriteCanvas::createInstance( const uno::Reference< uno::XComponentContext >& xContext ) throw ( uno::Exception )
{
return uno::Reference< uno::XInterface >( static_cast<cppu::OWeakObject*>(new SpriteCanvas( xContext )) );
}
bool SpriteCanvas::repaint( const GraphicObjectSharedPtr& rGrf,
const ::Point& rPt,
const ::Size& rSz,
const GraphicAttr& rAttr ) const
{
tools::LocalGuard aGuard;
return maCanvasHelper.repaint( rGrf, rPt, rSz, rAttr );
}
OutputDevice* SpriteCanvas::getOutDev() const
{
tools::LocalGuard aGuard;
return maDeviceHelper.getOutDev();
}
BackBufferSharedPtr SpriteCanvas::getBackBuffer() const
{
tools::LocalGuard aGuard;
return maDeviceHelper.getBackBuffer();
}
uno::Reference< beans::XPropertySetInfo > SAL_CALL SpriteCanvas::getPropertySetInfo() throw (uno::RuntimeException)
{
tools::LocalGuard aGuard;
return maPropHelper.getPropertySetInfo();
}
void SAL_CALL SpriteCanvas::setPropertyValue( const ::rtl::OUString& aPropertyName,
const uno::Any& aValue ) throw (beans::UnknownPropertyException,
beans::PropertyVetoException,
lang::IllegalArgumentException,
lang::WrappedTargetException,
uno::RuntimeException)
{
tools::LocalGuard aGuard;
maPropHelper.setPropertyValue( aPropertyName, aValue );
}
uno::Any SAL_CALL SpriteCanvas::getPropertyValue( const ::rtl::OUString& aPropertyName ) throw (beans::UnknownPropertyException,
lang::WrappedTargetException,
uno::RuntimeException)
{
tools::LocalGuard aGuard;
return maPropHelper.getPropertyValue( aPropertyName );
}
void SAL_CALL SpriteCanvas::addPropertyChangeListener( const ::rtl::OUString& aPropertyName,
const uno::Reference< beans::XPropertyChangeListener >& xListener ) throw (beans::UnknownPropertyException,
lang::WrappedTargetException,
uno::RuntimeException)
{
tools::LocalGuard aGuard;
maPropHelper.addPropertyChangeListener( aPropertyName,
xListener );
}
void SAL_CALL SpriteCanvas::removePropertyChangeListener( const ::rtl::OUString& aPropertyName,
const uno::Reference< beans::XPropertyChangeListener >& xListener ) throw (beans::UnknownPropertyException,
lang::WrappedTargetException,
uno::RuntimeException)
{
tools::LocalGuard aGuard;
maPropHelper.removePropertyChangeListener( aPropertyName,
xListener );
}
void SAL_CALL SpriteCanvas::addVetoableChangeListener( const ::rtl::OUString& aPropertyName,
const uno::Reference< beans::XVetoableChangeListener >& xListener ) throw (beans::UnknownPropertyException,
lang::WrappedTargetException,
uno::RuntimeException)
{
tools::LocalGuard aGuard;
maPropHelper.addVetoableChangeListener( aPropertyName,
xListener );
}
void SAL_CALL SpriteCanvas::removeVetoableChangeListener( const ::rtl::OUString& aPropertyName,
const uno::Reference< beans::XVetoableChangeListener >& xListener ) throw (beans::UnknownPropertyException,
lang::WrappedTargetException,
uno::RuntimeException)
{
tools::LocalGuard aGuard;
maPropHelper.removeVetoableChangeListener( aPropertyName,
xListener );
}
}
namespace
{
/* shared lib exports implemented with helpers */
static struct ::cppu::ImplementationEntry s_component_entries [] =
{
{
vclcanvas::SpriteCanvas::createInstance, getImplementationName_SpriteCanvas,
getSupportedServiceNames_SpriteCanvas, ::cppu::createSingleComponentFactory,
0, 0
},
{ 0, 0, 0, 0, 0, 0 }
};
}
/* Exported UNO methods for registration and object creation.
==========================================================
*/
extern "C"
{
void SAL_CALL component_getImplementationEnvironment( const sal_Char** ppEnvTypeName,
uno_Environment** )
{
*ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
sal_Bool SAL_CALL component_writeInfo( lang::XMultiServiceFactory* xMgr,
registry::XRegistryKey* xRegistry )
{
return ::cppu::component_writeInfoHelper(
xMgr, xRegistry, s_component_entries );
}
void * SAL_CALL component_getFactory( sal_Char const* implName,
lang::XMultiServiceFactory* xMgr,
registry::XRegistryKey* xRegistry )
{
return ::cppu::component_getFactoryHelper(
implName, xMgr, xRegistry, s_component_entries );
}
}
<commit_msg>INTEGRATION: CWS presfixes09 (1.10.32); FILE MERGED 2006/10/20 11:40:39 thb 1.10.32.8: #i10000# Removed post-merge compiler warnings; removed spurious semicolon after macro 2006/10/18 14:04:51 thb 1.10.32.7: RESYNC: (1.11-1.12); FILE MERGED 2006/09/15 15:45:30 thb 1.10.32.6: RESYNC: (1.10-1.11); FILE MERGED 2006/04/25 12:53:53 thb 1.10.32.5: #i63943# Handling probe construction special 2006/04/21 12:44:22 thb 1.10.32.4: #i63088# Cloned Cyrille's patches accordingly 2006/03/13 12:38:01 thb 1.10.32.3: #i49357# Renamed macro 2006/03/08 18:00:04 thb 1.10.32.2: #i49357# Now also providing the C lib entry points again 2006/03/07 15:08:03 thb 1.10.32.1: #i49357# Adapted to recent XWindow vs. XWindowListener changes; using dbo's new ServiceDecl goodness<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: spritecanvas.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: kz $ $Date: 2006-12-13 14:48: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_canvas.hxx"
#include <canvas/debug.hxx>
#include <canvas/verbosetrace.hxx>
#include <canvas/canvastools.hxx>
#include <com/sun/star/registry/XRegistryKey.hpp>
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#include <com/sun/star/uno/XComponentContext.hpp>
#include <cppuhelper/factory.hxx>
#include <cppuhelper/implementationentry.hxx>
#include <comphelper/servicedecl.hxx>
#include <vcl/canvastools.hxx>
#include <vcl/outdev.hxx>
#include <vcl/window.hxx>
#include <vcl/bitmapex.hxx>
#include <basegfx/tools/canvastools.hxx>
#include <algorithm>
#include "spritecanvas.hxx"
using namespace ::com::sun::star;
#define SERVICE_NAME "com.sun.star.rendering.VCLCanvas"
namespace vclcanvas
{
SpriteCanvas::SpriteCanvas( const uno::Sequence< uno::Any >& aArguments,
const uno::Reference< uno::XComponentContext >& rxContext ) :
mxComponentContext( rxContext )
{
// #i64742# Only call initialize when not in probe mode
if( aArguments.getLength() != 0 )
initialize( aArguments );
}
void SpriteCanvas::initialize( const uno::Sequence< uno::Any >& aArguments )
{
tools::LocalGuard aGuard;
OSL_TRACE( "SpriteCanvas created" );
// add our own property to GraphicDevice
maPropHelper.addProperties(
::canvas::PropertySetHelper::MakeMap
("UnsafeScrolling",
boost::bind(&SpriteCanvasHelper::isUnsafeScrolling,
boost::ref(maCanvasHelper)),
boost::bind(&SpriteCanvasHelper::enableUnsafeScrolling,
boost::ref(maCanvasHelper),
_1))
("SpriteBounds",
boost::bind(&SpriteCanvasHelper::isSpriteBounds,
boost::ref(maCanvasHelper)),
boost::bind(&SpriteCanvasHelper::enableSpriteBounds,
boost::ref(maCanvasHelper),
_1)));
VERBOSE_TRACE( "VCLSpriteCanvas::initialize called" );
CHECK_AND_THROW( aArguments.getLength() >= 1,
"SpriteCanvas::initialize: wrong number of arguments" );
// We expect a single Any here, containing a pointer to a valid
// VCL window, on which to output
if( aArguments.getLength() >= 1 &&
aArguments[0].getValueTypeClass() == uno::TypeClass_HYPER )
{
sal_Int64 nWindowPtr = 0;
aArguments[0] >>= nWindowPtr;
Window* pOutputWindow = reinterpret_cast<Window*>(nWindowPtr);
CHECK_AND_THROW( pOutputWindow != NULL,
"SpriteCanvas::initialize: invalid Window pointer" );
// setup helper
maDeviceHelper.init( *pOutputWindow,
*this );
maCanvasHelper.init( *this,
maDeviceHelper.getBackBuffer(),
false, // no OutDev state preservation
false ); // no alpha on surface
maCanvasHelper.setRedrawManager( maRedrawManager );
}
}
SpriteCanvas::~SpriteCanvas()
{
OSL_TRACE( "SpriteCanvas destroyed" );
}
void SAL_CALL SpriteCanvas::disposing()
{
tools::LocalGuard aGuard;
mxComponentContext.clear();
// forward to parent
SpriteCanvasBaseT::disposing();
}
::sal_Bool SAL_CALL SpriteCanvas::showBuffer( ::sal_Bool bUpdateAll ) throw (uno::RuntimeException)
{
tools::LocalGuard aGuard;
// avoid repaints on hidden window (hidden: not mapped to
// screen). Return failure, since the screen really has _not_
// been updated (caller should try again later)
return !mbIsVisible ? false : SpriteCanvasBaseT::showBuffer( bUpdateAll );
}
::sal_Bool SAL_CALL SpriteCanvas::switchBuffer( ::sal_Bool bUpdateAll ) throw (uno::RuntimeException)
{
tools::LocalGuard aGuard;
// avoid repaints on hidden window (hidden: not mapped to
// screen). Return failure, since the screen really has _not_
// been updated (caller should try again later)
return !mbIsVisible ? false : SpriteCanvasBaseT::switchBuffer( bUpdateAll );
}
sal_Bool SAL_CALL SpriteCanvas::updateScreen( sal_Bool bUpdateAll ) throw (uno::RuntimeException)
{
tools::LocalGuard aGuard;
// avoid repaints on hidden window (hidden: not mapped to
// screen). Return failure, since the screen really has _not_
// been updated (caller should try again later)
return !mbIsVisible ? false : maCanvasHelper.updateScreen(bUpdateAll,
mbSurfaceDirty);
}
::rtl::OUString SAL_CALL SpriteCanvas::getServiceName( ) throw (::com::sun::star::uno::RuntimeException)
{
return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( SERVICE_NAME ) );
}
bool SpriteCanvas::repaint( const GraphicObjectSharedPtr& rGrf,
const ::Point& rPt,
const ::Size& rSz,
const GraphicAttr& rAttr ) const
{
tools::LocalGuard aGuard;
return maCanvasHelper.repaint( rGrf, rPt, rSz, rAttr );
}
OutputDevice* SpriteCanvas::getOutDev() const
{
tools::LocalGuard aGuard;
return maDeviceHelper.getOutDev();
}
BackBufferSharedPtr SpriteCanvas::getBackBuffer() const
{
tools::LocalGuard aGuard;
return maDeviceHelper.getBackBuffer();
}
uno::Reference< beans::XPropertySetInfo > SAL_CALL SpriteCanvas::getPropertySetInfo() throw (uno::RuntimeException)
{
tools::LocalGuard aGuard;
return maPropHelper.getPropertySetInfo();
}
void SAL_CALL SpriteCanvas::setPropertyValue( const ::rtl::OUString& aPropertyName,
const uno::Any& aValue ) throw (beans::UnknownPropertyException,
beans::PropertyVetoException,
lang::IllegalArgumentException,
lang::WrappedTargetException,
uno::RuntimeException)
{
tools::LocalGuard aGuard;
maPropHelper.setPropertyValue( aPropertyName, aValue );
}
uno::Any SAL_CALL SpriteCanvas::getPropertyValue( const ::rtl::OUString& aPropertyName ) throw (beans::UnknownPropertyException,
lang::WrappedTargetException,
uno::RuntimeException)
{
tools::LocalGuard aGuard;
return maPropHelper.getPropertyValue( aPropertyName );
}
void SAL_CALL SpriteCanvas::addPropertyChangeListener( const ::rtl::OUString& aPropertyName,
const uno::Reference< beans::XPropertyChangeListener >& xListener ) throw (beans::UnknownPropertyException,
lang::WrappedTargetException,
uno::RuntimeException)
{
tools::LocalGuard aGuard;
maPropHelper.addPropertyChangeListener( aPropertyName,
xListener );
}
void SAL_CALL SpriteCanvas::removePropertyChangeListener( const ::rtl::OUString& aPropertyName,
const uno::Reference< beans::XPropertyChangeListener >& xListener ) throw (beans::UnknownPropertyException,
lang::WrappedTargetException,
uno::RuntimeException)
{
tools::LocalGuard aGuard;
maPropHelper.removePropertyChangeListener( aPropertyName,
xListener );
}
void SAL_CALL SpriteCanvas::addVetoableChangeListener( const ::rtl::OUString& aPropertyName,
const uno::Reference< beans::XVetoableChangeListener >& xListener ) throw (beans::UnknownPropertyException,
lang::WrappedTargetException,
uno::RuntimeException)
{
tools::LocalGuard aGuard;
maPropHelper.addVetoableChangeListener( aPropertyName,
xListener );
}
void SAL_CALL SpriteCanvas::removeVetoableChangeListener( const ::rtl::OUString& aPropertyName,
const uno::Reference< beans::XVetoableChangeListener >& xListener ) throw (beans::UnknownPropertyException,
lang::WrappedTargetException,
uno::RuntimeException)
{
tools::LocalGuard aGuard;
maPropHelper.removeVetoableChangeListener( aPropertyName,
xListener );
}
namespace sdecl = comphelper::service_decl;
#if defined (__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ <= 3)
sdecl::class_<SpriteCanvas, sdecl::with_args<true> > serviceImpl;
const sdecl::ServiceDecl vclCanvasDecl(
serviceImpl,
#else
const sdecl::ServiceDecl vclCanvasDecl(
sdecl::class_<SpriteCanvas, sdecl::with_args<true> >(),
#endif
"com.sun.star.comp.rendering.VCLCanvas",
SERVICE_NAME );
}
// The C shared lib entry points
COMPHELPER_SERVICEDECL_EXPORTS1(vclcanvas::vclCanvasDecl)
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/cache/p9_l3err_extract.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
//------------------------------------------------------------------------------
// *|
// *! TITLE : p3_l3err_extract.H
// *! DESCRIPTION : Parse and extract error information from L3 Scom Register (FAPI2)
// *!
// *! OWNER NAME : Chen Qian Email: [email protected]
// *!
// *! ADDITIONAL COMMENTS :
// *!
//------------------------------------------------------------------------------
#ifndef _P9_L3ERR_EXTRACT_H_
#define _P9_L3ERR_EXTRACT_H_
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <fapi2.H>
//------------------------------------------------------------------------------
// Structure definitions
//------------------------------------------------------------------------------
// enum used to denote what type of error occured or which we want to find
enum p9_l3err_extract_err_type
{
L3ERR_CE,
L3ERR_UE,
L3ERR_SUE,
L3ERR_CE_UE
};
// structure to document control/data registers for each supported trace array
struct p9_l3err_extract_err_data
{
p9_l3err_extract_err_type ce_ue;
uint8_t member;
uint8_t dw; //3-bit
uint8_t bank; //3-bit
uint8_t dataout; //decimal 0-144, 8-bit
uint16_t hashed_real_address_45_56;//12-bit
uint16_t cache_read_address;//14-bit
};
// function pointer typedef definition for HWP call support
typedef fapi2::ReturnCode (*p9_l3err_extract_FP_t)( const fapi2::Target<fapi2::TARGET_TYPE_EX>& i_target,
p9_l3err_extract_err_data& o_err_data,
bool& o_err_found);
extern "C"
{
//------------------------------------------------------------------------------
// Function prototype
//------------------------------------------------------------------------------
// function: FAPI p9_l3err_extract HWP entry point
// Parse and extract L3 error information from provided
// parameters: i_ex_chiplet => chiplet target used for callouts
// i_err_type => type of error that is to be extracted (CE,UE,both)
// o_err_data => failing location information for CE or UE
// o_err_found => error is found
fapi2::ReturnCode p9_l3err_extract(const fapi2::Target<fapi2::TARGET_TYPE_EX>& i_target,
p9_l3err_extract_err_data& o_err_data,
bool& o_error_found);
} // extern "C"
#endif // _P9_L3ERR_EXTRACT_H_
<commit_msg>L3 Update - p9_l3err_extract/linedelete HWPs<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/cache/p9_l3err_extract.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///----------------------------------------------------------------------------
///
/// @file p9_l3err_extract.H
///
/// @brief Parse and extract error information from L3 Scom Registers (FAPI2)
///
/// *HWP HWP Owner : Chen Qian <[email protected]>
/// *HWP FW Owner : Thi Tran <[email protected]>
/// *HWP Team : Quad
/// *HWP Consumed by : HB
/// *HWP Level : 3
///----------------------------------------------------------------------------
#ifndef _P9_L3ERR_EXTRACT_H_
#define _P9_L3ERR_EXTRACT_H_
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <fapi2.H>
//------------------------------------------------------------------------------
// Structure definitions
//------------------------------------------------------------------------------
// enum used to denote what type of error occured or which we want to find
enum p9_l3err_extract_err_type
{
L3ERR_CE,
L3ERR_UE,
L3ERR_SUE,
L3ERR_CE_UE
};
// structure to document control/data registers for each supported trace array
struct p9_l3err_extract_err_data
{
p9_l3err_extract_err_type ce_ue;
uint8_t member;
uint8_t dw; //3-bit
uint8_t bank; //3-bit
uint8_t dataout; //decimal 0-144, 8-bit
uint16_t hashed_real_address_45_56;//12-bit
uint16_t cache_read_address;//14-bit
};
// function pointer typedef definition for HWP call support
typedef fapi2::ReturnCode (*p9_l3err_extract_FP_t)(
const fapi2::Target<fapi2::TARGET_TYPE_EX>& i_target,
p9_l3err_extract_err_data& o_err_data,
bool& o_err_found);
extern "C"
{
//------------------------------------------------------------------------------
// Function prototype
//------------------------------------------------------------------------------
///
/// @brief FAPI p9_l3err_extract HWP entry point
/// Parse and extract L3 error information from provided
///
/// @param[in] i_target => EX chiplet target
/// @param[out] o_err_data => Failing location information for CE or UE
/// @param[out] o_error_found => Error is found
///
fapi2::ReturnCode p9_l3err_extract(
const fapi2::Target<fapi2::TARGET_TYPE_EX>& i_target,
p9_l3err_extract_err_data& o_err_data,
bool& o_error_found);
} // extern "C"
#endif // _P9_L3ERR_EXTRACT_H_
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/utils/stopreg/p9_stop_util.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_stop_util.C
/// @brief implements some utilty functions for STOP API.
///
// *HWP HW Owner : Greg Still <[email protected]>
// *HWP FW Owner : Prem Shanker Jha <[email protected]>
// *HWP Team : PM
// *HWP Level : 2
// *HWP Consumed by : HB:HYP
#ifdef PPC_HYP
#include <HvPlicModule.H>
#endif
#include "p9_stop_api.H"
#include "p9_stop_util.H"
#include "p9_stop_data_struct.H"
#ifdef __cplusplus
namespace stopImageSection
{
#endif
//-----------------------------------------------------------------------
/**
* @brief Returns proc chip's fuse mode status.
* @param i_pImage points to start of chip's HOMER image.
* @param o_fusedMode points to fuse mode information.
* @return STOP_SAVE_SUCCESS if functions succeeds, error code otherwise.
*/
STATIC StopReturnCode_t isFusedMode( void* const i_pImage, bool* o_fusedMode )
{
StopReturnCode_t l_rc = STOP_SAVE_SUCCESS;
uint64_t cpmrCheckWord = 0;
*o_fusedMode = false;
do
{
HomerSection_t* pHomerDesc = ( HomerSection_t* ) i_pImage;
HomerImgDesc_t* pHomer = (HomerImgDesc_t*)( pHomerDesc->interrruptHandler );
if( !i_pImage )
{
MY_ERR( "invalid pointer to HOMER image");
l_rc = STOP_SAVE_ARG_INVALID_IMG;
break;
}
cpmrCheckWord = SWIZZLE_8_BYTE(pHomer->cpmrMagicWord);
cpmrCheckWord = cpmrCheckWord >> 32;
if( CPMR_REGION_CHECK_WORD != cpmrCheckWord )
{
MY_ERR("corrupt or invalid HOMER image location 0x%016llx",
SWIZZLE_8_BYTE(pHomer->cpmrMagicWord) );
l_rc = STOP_SAVE_ARG_INVALID_IMG;
break;
}
if( (uint8_t) FUSED_CORE_MODE == pHomer->fusedModeStatus )
{
*o_fusedMode = true;
break;
}
if( (uint8_t) NONFUSED_CORE_MODE == pHomer->fusedModeStatus )
{
break;
}
MY_ERR("Unexpected value 0x%08x for fused mode. Bad or corrupt "
"HOMER location", pHomer->fusedModeStatus );
l_rc = STOP_SAVE_INVALID_FUSED_CORE_STATUS ;
}
while(0);
return l_rc;
}
//----------------------------------------------------------------------
StopReturnCode_t getCoreAndThread( void* const i_pImage, const uint64_t i_pir,
uint32_t* o_pCoreId, uint32_t* o_pThreadId )
{
StopReturnCode_t l_rc = STOP_SAVE_SUCCESS;
do
{
// for SPR restore using 'Virtual Thread' and 'Physical Core' number
// In Fused Mode:
// bit b28 and b31 of PIR give physical core and b29 and b30 gives
// virtual thread id.
// In Non Fused Mode
// bit 28 and b29 of PIR give both logical and physical core number
// whereas b30 and b31 gives logical and virtual thread id.
bool fusedMode = false;
uint8_t coreThreadInfo = (uint8_t)i_pir;
*o_pCoreId = 0;
*o_pThreadId = 0;
l_rc = isFusedMode( i_pImage, &fusedMode );
if( l_rc )
{
MY_ERR(" Checking Fused mode. Read failed 0x%08x", l_rc );
break;
}
if( fusedMode )
{
if( coreThreadInfo & FUSED_CORE_BIT1 )
{
*o_pThreadId = 2;
}
if( coreThreadInfo & FUSED_CORE_BIT2 )
{
*o_pThreadId += 1;
}
if( coreThreadInfo & FUSED_CORE_BIT0 )
{
*o_pCoreId = 2;
}
if( coreThreadInfo & FUSED_CORE_BIT3 )
{
*o_pCoreId += 1;
}
}
else
{
if( coreThreadInfo & FUSED_CORE_BIT0 )
{
*o_pCoreId = 2;
}
if ( coreThreadInfo & FUSED_CORE_BIT1 )
{
*o_pCoreId += 1;
}
if( coreThreadInfo & FUSED_CORE_BIT2 )
{
*o_pThreadId = 2;
}
if( coreThreadInfo & FUSED_CORE_BIT3 )
{
*o_pThreadId += 1;
}
}
MY_INF("Core Type %s", fusedMode ? "Fused" : "Un-Fused" );
//quad field is not affected by fuse mode
*o_pCoreId += 4 * (( coreThreadInfo & 0x70 ) >> 4 );
}
while(0);
return l_rc;
}
#ifdef __cplusplus
}//namespace stopImageSection ends
#endif
<commit_msg>UV Support : Augmented STOP API and self restore for enabling ultravisor.<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/utils/stopreg/p9_stop_util.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_stop_util.C
/// @brief implements some utilty functions for STOP API.
///
// *HWP HW Owner : Greg Still <[email protected]>
// *HWP FW Owner : Prem Shanker Jha <[email protected]>
// *HWP Team : PM
// *HWP Level : 2
// *HWP Consumed by : HB:HYP
#ifdef PPC_HYP
#include <HvPlicModule.H>
#endif
#include "p9_stop_api.H"
#include "p9_stop_util.H"
#include "p9_stop_data_struct.H"
#ifdef __cplusplus
namespace stopImageSection
{
#endif
//-----------------------------------------------------------------------
/**
* @brief Returns proc chip's fuse mode status.
* @param i_pImage points to start of chip's HOMER image.
* @param o_fusedMode points to fuse mode information.
* @return STOP_SAVE_SUCCESS if functions succeeds, error code otherwise.
*/
STATIC StopReturnCode_t isFusedMode( void* const i_pImage, bool* o_fusedMode )
{
StopReturnCode_t l_rc = STOP_SAVE_SUCCESS;
uint64_t cpmrCheckWord = 0;
*o_fusedMode = false;
do
{
HomerSection_t* pHomerDesc = ( HomerSection_t* ) i_pImage;
HomerImgDesc_t* pHomer = (HomerImgDesc_t*)( pHomerDesc->iv_interrruptHandler );
if( !i_pImage )
{
MY_ERR( "invalid pointer to HOMER image");
l_rc = STOP_SAVE_ARG_INVALID_IMG;
break;
}
cpmrCheckWord = SWIZZLE_8_BYTE(pHomer->cpmrMagicWord);
cpmrCheckWord = cpmrCheckWord >> 32;
if( CPMR_REGION_CHECK_WORD != cpmrCheckWord )
{
MY_ERR("corrupt or invalid HOMER image location 0x%016llx",
SWIZZLE_8_BYTE(pHomer->cpmrMagicWord) );
l_rc = STOP_SAVE_ARG_INVALID_IMG;
break;
}
if( (uint8_t) FUSED_CORE_MODE == pHomer->fusedModeStatus )
{
*o_fusedMode = true;
break;
}
if( (uint8_t) NONFUSED_CORE_MODE == pHomer->fusedModeStatus )
{
break;
}
MY_ERR("Unexpected value 0x%08x for fused mode. Bad or corrupt "
"HOMER location", pHomer->fusedModeStatus );
l_rc = STOP_SAVE_INVALID_FUSED_CORE_STATUS ;
}
while(0);
return l_rc;
}
//----------------------------------------------------------------------
StopReturnCode_t getCoreAndThread( void* const i_pImage, const uint64_t i_pir,
uint32_t* o_pCoreId, uint32_t* o_pThreadId )
{
StopReturnCode_t l_rc = STOP_SAVE_SUCCESS;
do
{
// for SPR restore using 'Virtual Thread' and 'Physical Core' number
// In Fused Mode:
// bit b28 and b31 of PIR give physical core and b29 and b30 gives
// virtual thread id.
// In Non Fused Mode
// bit 28 and b29 of PIR give both logical and physical core number
// whereas b30 and b31 gives logical and virtual thread id.
bool fusedMode = false;
uint8_t coreThreadInfo = (uint8_t)i_pir;
*o_pCoreId = 0;
*o_pThreadId = 0;
l_rc = isFusedMode( i_pImage, &fusedMode );
if( l_rc )
{
MY_ERR(" Checking Fused mode. Read failed 0x%08x", l_rc );
break;
}
if( fusedMode )
{
if( coreThreadInfo & FUSED_CORE_BIT1 )
{
*o_pThreadId = 2;
}
if( coreThreadInfo & FUSED_CORE_BIT2 )
{
*o_pThreadId += 1;
}
if( coreThreadInfo & FUSED_CORE_BIT0 )
{
*o_pCoreId = 2;
}
if( coreThreadInfo & FUSED_CORE_BIT3 )
{
*o_pCoreId += 1;
}
}
else
{
if( coreThreadInfo & FUSED_CORE_BIT0 )
{
*o_pCoreId = 2;
}
if ( coreThreadInfo & FUSED_CORE_BIT1 )
{
*o_pCoreId += 1;
}
if( coreThreadInfo & FUSED_CORE_BIT2 )
{
*o_pThreadId = 2;
}
if( coreThreadInfo & FUSED_CORE_BIT3 )
{
*o_pThreadId += 1;
}
}
MY_INF("Core Type %s", fusedMode ? "Fused" : "Un-Fused" );
//quad field is not affected by fuse mode
*o_pCoreId += 4 * (( coreThreadInfo & 0x70 ) >> 4 );
}
while(0);
return l_rc;
}
#ifdef __cplusplus
}//namespace stopImageSection ends
#endif
<|endoftext|> |
<commit_before>#include "mapcss/StyleSheet.hpp"
#include "mapcss/MapCssParser.cpp"
#include "utils/CoreUtils.hpp"
#include <boost/test/unit_test.hpp>
#include <string>
#include <memory>
using namespace utymap::mapcss;
typedef std::string::const_iterator StringIterator;
struct MapCss_MapCssParserFixture {
MapCss_MapCssParserFixture() { BOOST_TEST_MESSAGE("setup fixture"); }
~MapCss_MapCssParserFixture() { BOOST_TEST_MESSAGE("teardown fixture"); }
// grammars
CommentSkipper<StringIterator> skipper;
StyleSheetGrammar<StringIterator> styleSheetGrammar;
ConditionGrammar<StringIterator> conditionGrammar;
ZoomGrammar<StringIterator> zoomGrammar;
SelectorGrammar<StringIterator> selectorGrammar;
DeclarationGrammar<StringIterator> declarationGrammar;
RuleGrammar<StringIterator> ruleGrammar;
// parsed data
StyleSheet stylesheet;
Condition condition;
Zoom zoom;
Selector selector;
Declaration declaration;
Rule rule;
};
BOOST_FIXTURE_TEST_SUITE( MapCss_MapCssParser, MapCss_MapCssParserFixture )
/* Comment */
BOOST_AUTO_TEST_CASE( GivenCppComment_WhenParse_ThenDoesNotBreak )
{
std::string str = "/* Some \nncomment */\n way|z1-15[highway] {key:value;}";
bool success = phrase_parse(str.cbegin(), str.cend(), styleSheetGrammar, skipper, stylesheet);
BOOST_CHECK( success == true );
BOOST_CHECK( stylesheet.rules.size() == 1 );
}
BOOST_AUTO_TEST_CASE( GivenHtmlComment_WhenParse_ThenDoesNotBreak )
{
std::string str = "<!--Some \ncomment-->\n way|z1-15[highway] {key:value;}";
bool success = phrase_parse(str.cbegin(), str.cend(), styleSheetGrammar, skipper, stylesheet);
BOOST_CHECK( success == true );
BOOST_CHECK( stylesheet.rules.size() == 1 );
}
/* Condition */
BOOST_AUTO_TEST_CASE( GivenExistenceCondition_WhenParse_ThenOnlyKeyIsSet )
{
std::string str = "[highway]";
bool success = phrase_parse(str.cbegin(), str.cend(), conditionGrammar, skipper, condition);
BOOST_CHECK( success == true );
BOOST_CHECK( condition.key == "highway" );
BOOST_CHECK( condition.operation.empty() == true );
BOOST_CHECK( condition.value.empty() == true );
}
BOOST_AUTO_TEST_CASE( GivenEqualCondition_WhenParse_ThenKeyOpValueAreSet )
{
std::string str = "[highway=primary]";
bool success = phrase_parse(str.cbegin(), str.cend(), conditionGrammar, skipper, condition);
BOOST_CHECK( success == true );
BOOST_CHECK( condition.key == "highway" );
BOOST_CHECK( condition.operation == "=" );
BOOST_CHECK( condition.value == "primary" );
}
BOOST_AUTO_TEST_CASE( GivenNegativeCondition_WhenParse_ThenKeyOpValueAreSet )
{
std::string str = "[highway!=primary]";
bool success = phrase_parse(str.cbegin(), str.cend(), conditionGrammar, skipper, condition);
BOOST_CHECK( success == true );
BOOST_CHECK( condition.key == "highway" );
BOOST_CHECK( condition.operation == "!=" );
BOOST_CHECK( condition.value == "primary" );
}
/* Zoom */
BOOST_AUTO_TEST_CASE( GivenOneZoom_WhenParse_ThenStartAndEndAreSet )
{
std::string str = "|z1";
bool success = phrase_parse(str.cbegin(), str.cend(), zoomGrammar, skipper, zoom);
BOOST_CHECK( success == true );
BOOST_CHECK( zoom.start == 1 );
BOOST_CHECK( zoom.end == 1 );
}
BOOST_AUTO_TEST_CASE( GivenZoomRange_WhenParse_ThenStartAndEndAreSet )
{
std::string str = "|z12-21";
bool success = phrase_parse(str.cbegin(), str.cend(), zoomGrammar, skipper, zoom);
BOOST_CHECK( success == true );
BOOST_CHECK( zoom.start == 12 );
BOOST_CHECK( zoom.end == 21 );
}
/* Selector */
BOOST_AUTO_TEST_CASE( GivenSingleSelector_WhenParse_ThenNameAndConditionsAreSet )
{
std::string str = "way|z1[highway]";
bool success = phrase_parse(str.cbegin(), str.cend(), selectorGrammar, skipper, selector);
BOOST_CHECK( success == true );
BOOST_CHECK( selector.name == "way" );
BOOST_CHECK( selector.conditions.size() == 1 );
BOOST_CHECK( selector.conditions[0].key == "highway" );
}
BOOST_AUTO_TEST_CASE( GivenTwoSelectors_WhenParse_ThenNameAndConditionsAreSet )
{
std::string str = "way|z1[highway][landuse]";
bool success = phrase_parse(str.cbegin(), str.cend(), selectorGrammar, skipper, selector);
BOOST_CHECK( success == true );
BOOST_CHECK( selector.name == "way" );
BOOST_CHECK( selector.conditions.size() == 2 );
BOOST_CHECK( selector.conditions[0].key == "highway" );
BOOST_CHECK( selector.conditions[1].key == "landuse" );
}
/* Declaration */
BOOST_AUTO_TEST_CASE( GivenSingleDeclaraion_WhenParse_ThenKeyValueAreSet )
{
std::string str = "key1:value1;";
bool success = phrase_parse(str.cbegin(), str.cend(), declarationGrammar, skipper, declaration);
BOOST_CHECK( success == true );
BOOST_CHECK( declaration.key == "key1" );
BOOST_CHECK( declaration.value == "value1" );
}
/* Rule */
BOOST_AUTO_TEST_CASE( GivenSimpleRule_WhenParse_ThenSelectorAndDeclarationAreSet )
{
std::string str = "way|z1[highway] {key1:value1;}";
bool success = phrase_parse(str.cbegin(), str.cend(), ruleGrammar, skipper, rule);
BOOST_CHECK(success == true);
BOOST_CHECK( rule.selectors.size() == 1 );
BOOST_CHECK( rule.declarations.size() == 1 );
BOOST_CHECK( rule.selectors[0].conditions[0].key == "highway" );
BOOST_CHECK( rule.declarations[0].key == "key1" );
BOOST_CHECK( rule.declarations[0].value == "value1" );
}
BOOST_AUTO_TEST_CASE( GivenComplexRule_WhenParse_ThenSelectorAndDeclarationAreSet )
{
std::string str = "way|z1[highway],area|z2[landuse] { key1:value1; key2:value2; }";
bool success = phrase_parse(str.cbegin(), str.cend(), ruleGrammar, skipper, rule);
BOOST_CHECK(success == true);
BOOST_CHECK( rule.selectors.size() == 2 );
BOOST_CHECK( rule.declarations.size() == 2 );
BOOST_CHECK( rule.selectors[0].name == "way" );
BOOST_CHECK( rule.selectors[1].name == "area" );
BOOST_CHECK( rule.selectors[0].conditions[0].key == "highway" );
BOOST_CHECK( rule.selectors[1].conditions[0].key == "landuse" );
BOOST_CHECK( rule.declarations[0].key == "key1" );
BOOST_CHECK( rule.declarations[0].value == "value1" );
BOOST_CHECK( rule.declarations[1].key == "key2" );
BOOST_CHECK( rule.declarations[1].value == "value2" );
}
/* StyleSheet */
BOOST_AUTO_TEST_CASE( GivenFourRulesOnDifferentLines_WhenParse_ThenHasFourRules )
{
std::string str =
"way|z1[highway] { key1:value1; }\n"
"area|z2[landuse] { key2:value2; }\n"
"node|z3[amenity] { key3:value3; }\n"
"canvas|z3 { key4:value4; }";
bool success = phrase_parse(str.cbegin(), str.cend(), styleSheetGrammar, skipper, stylesheet);
BOOST_CHECK( success == true );
BOOST_CHECK( stylesheet.rules.size() == 4) ;
}
BOOST_AUTO_TEST_CASE( GivenSimpleStyleSheet_WhenParserParse_ThenNoErrorsAndHasValidStyleSheet )
{
std::string str = "way|z1[highway] { key1:value1; }\n";
Parser parser;
StyleSheet stylesheet = parser.parse(str);
BOOST_CHECK( parser.getError().empty() == true );
BOOST_CHECK( stylesheet.rules.size() == 1 );
}
BOOST_AUTO_TEST_CASE(GivenCanvasRule_WhenParse_ThenProcessValidStyleSheet)
{
std::string str = "canvas|z1 { key1:value1; }\n";
Parser parser;
StyleSheet stylesheet = parser.parse(str);
BOOST_CHECK(parser.getError().empty() == true);
BOOST_CHECK(stylesheet.rules.size() == 1);
}
BOOST_AUTO_TEST_CASE(GivenSimpleRule_WhenToString_ThenReturnCorrectRepresentation)
{
std::string str = "way|z1-12[highway]{key1:value1;}";
Parser parser;
StyleSheet stylesheet = parser.parse(str);
BOOST_CHECK(parser.getError().empty());
BOOST_CHECK_EQUAL(1, stylesheet.rules.size());
BOOST_CHECK_EQUAL(str, utymap::utils::toString(stylesheet.rules[0]));
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>mapcss: add test for zoom range parse<commit_after>#include "mapcss/StyleSheet.hpp"
#include "mapcss/MapCssParser.cpp"
#include "utils/CoreUtils.hpp"
#include <boost/test/unit_test.hpp>
#include <string>
#include <memory>
using namespace utymap::mapcss;
typedef std::string::const_iterator StringIterator;
struct MapCss_MapCssParserFixture {
MapCss_MapCssParserFixture() { BOOST_TEST_MESSAGE("setup fixture"); }
~MapCss_MapCssParserFixture() { BOOST_TEST_MESSAGE("teardown fixture"); }
// grammars
CommentSkipper<StringIterator> skipper;
StyleSheetGrammar<StringIterator> styleSheetGrammar;
ConditionGrammar<StringIterator> conditionGrammar;
ZoomGrammar<StringIterator> zoomGrammar;
SelectorGrammar<StringIterator> selectorGrammar;
DeclarationGrammar<StringIterator> declarationGrammar;
RuleGrammar<StringIterator> ruleGrammar;
// parsed data
StyleSheet stylesheet;
Condition condition;
Zoom zoom;
Selector selector;
Declaration declaration;
Rule rule;
};
BOOST_FIXTURE_TEST_SUITE( MapCss_MapCssParser, MapCss_MapCssParserFixture )
/* Comment */
BOOST_AUTO_TEST_CASE( GivenCppComment_WhenParse_ThenDoesNotBreak )
{
std::string str = "/* Some \nncomment */\n way|z1-15[highway] {key:value;}";
bool success = phrase_parse(str.cbegin(), str.cend(), styleSheetGrammar, skipper, stylesheet);
BOOST_CHECK( success == true );
BOOST_CHECK( stylesheet.rules.size() == 1 );
}
BOOST_AUTO_TEST_CASE( GivenHtmlComment_WhenParse_ThenDoesNotBreak )
{
std::string str = "<!--Some \ncomment-->\n way|z1-15[highway] {key:value;}";
bool success = phrase_parse(str.cbegin(), str.cend(), styleSheetGrammar, skipper, stylesheet);
BOOST_CHECK( success == true );
BOOST_CHECK( stylesheet.rules.size() == 1 );
}
/* Condition */
BOOST_AUTO_TEST_CASE( GivenExistenceCondition_WhenParse_ThenOnlyKeyIsSet )
{
std::string str = "[highway]";
bool success = phrase_parse(str.cbegin(), str.cend(), conditionGrammar, skipper, condition);
BOOST_CHECK( success == true );
BOOST_CHECK( condition.key == "highway" );
BOOST_CHECK( condition.operation.empty() == true );
BOOST_CHECK( condition.value.empty() == true );
}
BOOST_AUTO_TEST_CASE( GivenEqualCondition_WhenParse_ThenKeyOpValueAreSet )
{
std::string str = "[highway=primary]";
bool success = phrase_parse(str.cbegin(), str.cend(), conditionGrammar, skipper, condition);
BOOST_CHECK( success == true );
BOOST_CHECK( condition.key == "highway" );
BOOST_CHECK( condition.operation == "=" );
BOOST_CHECK( condition.value == "primary" );
}
BOOST_AUTO_TEST_CASE( GivenNegativeCondition_WhenParse_ThenKeyOpValueAreSet )
{
std::string str = "[highway!=primary]";
bool success = phrase_parse(str.cbegin(), str.cend(), conditionGrammar, skipper, condition);
BOOST_CHECK( success == true );
BOOST_CHECK( condition.key == "highway" );
BOOST_CHECK( condition.operation == "!=" );
BOOST_CHECK( condition.value == "primary" );
}
/* Zoom */
BOOST_AUTO_TEST_CASE( GivenOneZoom_WhenParse_ThenStartAndEndAreSet )
{
std::string str = "|z1";
bool success = phrase_parse(str.cbegin(), str.cend(), zoomGrammar, skipper, zoom);
BOOST_CHECK( success == true );
BOOST_CHECK( zoom.start == 1 );
BOOST_CHECK( zoom.end == 1 );
}
BOOST_AUTO_TEST_CASE( GivenZoomRange_WhenParse_ThenStartAndEndAreSet )
{
std::string str = "|z12-21";
bool success = phrase_parse(str.cbegin(), str.cend(), zoomGrammar, skipper, zoom);
BOOST_CHECK( success == true );
BOOST_CHECK( zoom.start == 12 );
BOOST_CHECK( zoom.end == 21 );
}
/* Selector */
BOOST_AUTO_TEST_CASE( GivenSingleSelector_WhenParse_ThenNameAndConditionsAreSet )
{
std::string str = "way|z1[highway]";
bool success = phrase_parse(str.cbegin(), str.cend(), selectorGrammar, skipper, selector);
BOOST_CHECK( success == true );
BOOST_CHECK( selector.name == "way" );
BOOST_CHECK( selector.conditions.size() == 1 );
BOOST_CHECK( selector.conditions[0].key == "highway" );
}
BOOST_AUTO_TEST_CASE( GivenTwoSelectors_WhenParse_ThenNameAndConditionsAreSet )
{
std::string str = "way|z1[highway][landuse]";
bool success = phrase_parse(str.cbegin(), str.cend(), selectorGrammar, skipper, selector);
BOOST_CHECK( success == true );
BOOST_CHECK( selector.name == "way" );
BOOST_CHECK( selector.conditions.size() == 2 );
BOOST_CHECK( selector.conditions[0].key == "highway" );
BOOST_CHECK( selector.conditions[1].key == "landuse" );
}
/* Declaration */
BOOST_AUTO_TEST_CASE( GivenSingleDeclaraion_WhenParse_ThenKeyValueAreSet )
{
std::string str = "key1:value1;";
bool success = phrase_parse(str.cbegin(), str.cend(), declarationGrammar, skipper, declaration);
BOOST_CHECK( success == true );
BOOST_CHECK( declaration.key == "key1" );
BOOST_CHECK( declaration.value == "value1" );
}
/* Rule */
BOOST_AUTO_TEST_CASE( GivenSimpleRule_WhenParse_ThenSelectorAndDeclarationAreSet )
{
std::string str = "way|z1[highway] {key1:value1;}";
bool success = phrase_parse(str.cbegin(), str.cend(), ruleGrammar, skipper, rule);
BOOST_CHECK(success == true);
BOOST_CHECK( rule.selectors.size() == 1 );
BOOST_CHECK( rule.declarations.size() == 1 );
BOOST_CHECK( rule.selectors[0].conditions[0].key == "highway" );
BOOST_CHECK( rule.declarations[0].key == "key1" );
BOOST_CHECK( rule.declarations[0].value == "value1" );
}
BOOST_AUTO_TEST_CASE( GivenComplexRule_WhenParse_ThenSelectorAndDeclarationAreSet )
{
std::string str = "way|z1[highway],area|z2[landuse] { key1:value1; key2:value2; }";
bool success = phrase_parse(str.cbegin(), str.cend(), ruleGrammar, skipper, rule);
BOOST_CHECK(success == true);
BOOST_CHECK( rule.selectors.size() == 2 );
BOOST_CHECK( rule.declarations.size() == 2 );
BOOST_CHECK( rule.selectors[0].name == "way" );
BOOST_CHECK( rule.selectors[1].name == "area" );
BOOST_CHECK( rule.selectors[0].conditions[0].key == "highway" );
BOOST_CHECK( rule.selectors[1].conditions[0].key == "landuse" );
BOOST_CHECK( rule.declarations[0].key == "key1" );
BOOST_CHECK( rule.declarations[0].value == "value1" );
BOOST_CHECK( rule.declarations[1].key == "key2" );
BOOST_CHECK( rule.declarations[1].value == "value2" );
}
/* StyleSheet */
BOOST_AUTO_TEST_CASE( GivenFourRulesOnDifferentLines_WhenParse_ThenHasFourRules )
{
std::string str =
"way|z1[highway] { key1:value1; }\n"
"area|z2[landuse] { key2:value2; }\n"
"node|z3[amenity] { key3:value3; }\n"
"canvas|z3 { key4:value4; }";
bool success = phrase_parse(str.cbegin(), str.cend(), styleSheetGrammar, skipper, stylesheet);
BOOST_CHECK( success == true );
BOOST_CHECK( stylesheet.rules.size() == 4) ;
}
BOOST_AUTO_TEST_CASE( GivenSimpleStyleSheet_WhenParserParse_ThenNoErrorsAndHasValidStyleSheet )
{
std::string str = "way|z1[highway] { key1:value1; }\n";
Parser parser;
StyleSheet stylesheet = parser.parse(str);
BOOST_CHECK( parser.getError().empty() == true );
BOOST_CHECK( stylesheet.rules.size() == 1 );
}
BOOST_AUTO_TEST_CASE(GivenCanvasRule_WhenParse_ThenProcessValidStyleSheet)
{
std::string str = "canvas|z1 { key1:value1; }\n";
Parser parser;
StyleSheet stylesheet = parser.parse(str);
BOOST_CHECK(parser.getError().empty() == true);
BOOST_CHECK(stylesheet.rules.size() == 1);
}
BOOST_AUTO_TEST_CASE(GivenSimpleRuleWithZoomRange_WhenParse_ThenReturnCorrectZoomStartAndEnd)
{
std::string str = "way|z1-12[highway]{key1:value1;}";
Parser parser;
StyleSheet stylesheet = parser.parse(str);
BOOST_CHECK(parser.getError().empty());
Selector selector = stylesheet.rules[0].selectors[0];
BOOST_CHECK_EQUAL(1, selector.zoom.start);
BOOST_CHECK_EQUAL(12, selector.zoom.end);
}
BOOST_AUTO_TEST_CASE(GivenSimpleRule_WhenToString_ThenReturnCorrectRepresentation)
{
std::string str = "way|z1-12[highway]{key1:value1;}";
Parser parser;
StyleSheet stylesheet = parser.parse(str);
BOOST_CHECK(parser.getError().empty());
BOOST_CHECK_EQUAL(1, stylesheet.rules.size());
BOOST_CHECK_EQUAL(str, utymap::utils::toString(stylesheet.rules[0]));
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015, Nils Moehrle, Michael Waechter
* TU Darmstadt - Graphics, Capture and Massively Parallel Computing
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD 3-Clause license. See the LICENSE.txt file for details.
*/
#include <numeric>
#include <mve/image_color.h>
#include <acc/bvh_tree.h>
#include <Eigen/Core>
#include <Eigen/LU>
#include "util.h"
#include "histogram.h"
#include "texturing.h"
#include "sparse_table.h"
#include "progress_counter.h"
typedef acc::BVHTree<unsigned int, math::Vec3f> BVHTree;
TEX_NAMESPACE_BEGIN
/**
* Dampens the quality of all views in which the face's projection
* has a much different color than in the majority of views.
* Returns whether the outlier removal was successfull.
*
* @param infos contains information about one face seen from several views
* @param settings runtime configuration.
*/
bool
photometric_outlier_detection(std::vector<FaceProjectionInfo> * infos, Settings const & settings) {
if (infos->size() == 0) return true;
/* Configuration variables. */
double const gauss_rejection_threshold = 6e-3;
/* If all covariances drop below this we stop outlier detection. */
double const minimal_covariance = 5e-4;
int const outlier_detection_iterations = 10;
int const minimal_num_inliers = 4;
float outlier_removal_factor = std::numeric_limits<float>::signaling_NaN();
switch (settings.outlier_removal) {
case OUTLIER_REMOVAL_NONE: return true;
case OUTLIER_REMOVAL_GAUSS_CLAMPING:
outlier_removal_factor = 1.0f;
break;
case OUTLIER_REMOVAL_GAUSS_DAMPING:
outlier_removal_factor = 0.2f;
break;
}
Eigen::MatrixX3d inliers(infos->size(), 3);
std::vector<std::uint32_t> is_inlier(infos->size(), 1);
for (std::size_t row = 0; row < infos->size(); ++row) {
inliers.row(row) = mve_to_eigen(infos->at(row).mean_color).cast<double>();
}
Eigen::RowVector3d var_mean;
Eigen::Matrix3d covariance;
Eigen::Matrix3d covariance_inv;
for (int i = 0; i < outlier_detection_iterations; ++i) {
if (inliers.rows() < minimal_num_inliers) {
return false;
}
/* Calculate the inliers' mean color and color covariance. */
var_mean = inliers.colwise().mean();
Eigen::MatrixX3d centered = inliers.rowwise() - var_mean;
covariance = (centered.adjoint() * centered) / double(inliers.rows() - 1);
/* If all covariances are very small we stop outlier detection
* and only keep the inliers (set quality of outliers to zero). */
if (covariance.array().abs().maxCoeff() < minimal_covariance) {
for (std::size_t row = 0; row < infos->size(); ++row) {
if (!is_inlier[row]) infos->at(row).quality = 0.0f;
}
return true;
}
/* Invert the covariance. FullPivLU is not the fastest way but
* it gives feedback about numerical stability during inversion. */
Eigen::FullPivLU<Eigen::Matrix3d> lu(covariance);
if (!lu.isInvertible()) {
return false;
}
covariance_inv = lu.inverse();
/* Compute new number of inliers (all views with a gauss value above a threshold). */
for (std::size_t row = 0; row < infos->size(); ++row) {
Eigen::RowVector3d color = mve_to_eigen(infos->at(row).mean_color).cast<double>();
double gauss_value = multi_gauss_unnormalized(color, var_mean, covariance_inv);
is_inlier[row] = (gauss_value >= gauss_rejection_threshold ? 1 : 0);
}
/* Resize Eigen matrix accordingly and fill with new inliers. */
inliers.resize(std::accumulate(is_inlier.begin(), is_inlier.end(), 0), Eigen::NoChange);
for (std::size_t row = 0, inlier_row = 0; row < infos->size(); ++row) {
if (is_inlier[row]) {
inliers.row(inlier_row++) = mve_to_eigen(infos->at(row).mean_color).cast<double>();
}
}
}
covariance_inv *= outlier_removal_factor;
for (FaceProjectionInfo & info : *infos) {
Eigen::RowVector3d color = mve_to_eigen(info.mean_color).cast<double>();
double gauss_value = multi_gauss_unnormalized(color, var_mean, covariance_inv);
assert(0.0 <= gauss_value && gauss_value <= 1.0);
switch(settings.outlier_removal) {
case OUTLIER_REMOVAL_NONE: return true;
case OUTLIER_REMOVAL_GAUSS_DAMPING:
info.quality *= gauss_value;
break;
case OUTLIER_REMOVAL_GAUSS_CLAMPING:
if (gauss_value < gauss_rejection_threshold) info.quality = 0.0f;
break;
}
}
return true;
}
void
calculate_face_projection_infos(mve::TriangleMesh::ConstPtr mesh,
std::vector<TextureView> * texture_views, Settings const & settings,
FaceProjectionInfos * face_projection_infos) {
std::vector<unsigned int> const & faces = mesh->get_faces();
std::vector<math::Vec3f> const & vertices = mesh->get_vertices();
mve::TriangleMesh::NormalList const & face_normals = mesh->get_face_normals();
std::size_t const num_views = texture_views->size();
util::WallTimer timer;
std::cout << "\tBuilding BVH from " << faces.size() / 3 << " faces... " << std::flush;
BVHTree bvh_tree(faces, vertices);
std::cout << "done. (Took: " << timer.get_elapsed() << " ms)" << std::endl;
ProgressCounter view_counter("\tCalculating face qualities", num_views);
#pragma omp parallel
{
std::vector<std::pair<std::size_t, FaceProjectionInfo> > projected_face_view_infos;
#pragma omp for schedule(dynamic)
for (std::uint16_t j = 0; j < texture_views->size(); ++j) {
view_counter.progress<SIMPLE>();
TextureView * texture_view = &texture_views->at(j);
texture_view->load_image();
texture_view->generate_validity_mask();
if (settings.data_term == DATA_TERM_GMI) {
texture_view->generate_gradient_magnitude();
texture_view->erode_validity_mask();
}
math::Vec3f const & view_pos = texture_view->get_pos();
math::Vec3f const & viewing_direction = texture_view->get_viewing_direction();
for (std::size_t i = 0; i < faces.size(); i += 3) {
std::size_t face_id = i / 3;
math::Vec3f const & v1 = vertices[faces[i]];
math::Vec3f const & v2 = vertices[faces[i + 1]];
math::Vec3f const & v3 = vertices[faces[i + 2]];
math::Vec3f const & face_normal = face_normals[face_id];
math::Vec3f const face_center = (v1 + v2 + v3) / 3.0f;
/* Check visibility and compute quality */
math::Vec3f view_to_face_vec = (face_center - view_pos).normalized();
math::Vec3f face_to_view_vec = (view_pos - face_center).normalized();
/* Backface and basic frustum culling */
float viewing_angle = face_to_view_vec.dot(face_normal);
if (viewing_angle < 0.0f || viewing_direction.dot(view_to_face_vec) < 0.0f)
continue;
if (std::acos(viewing_angle) > MATH_DEG2RAD(75.0f))
continue;
/* Projects into the valid part of the TextureView? */
if (!texture_view->inside(v1, v2, v3))
continue;
if (settings.geometric_visibility_test) {
/* Viewing rays do not collide? */
bool visible = true;
math::Vec3f const * samples[] = {&v1, &v2, &v3};
// TODO: random monte carlo samples...
for (std::size_t k = 0; k < sizeof(samples) / sizeof(samples[0]); ++k) {
BVHTree::Ray ray;
ray.origin = *samples[k];
ray.dir = view_pos - ray.origin;
ray.tmax = ray.dir.norm();
ray.tmin = ray.tmax * 0.0001f;
ray.dir.normalize();
BVHTree::Hit hit;
if (bvh_tree.intersect(ray, &hit)) {
visible = false;
break;
}
}
if (!visible) continue;
}
FaceProjectionInfo info = {j, 0.0f, math::Vec3f(0.0f, 0.0f, 0.0f)};
/* Calculate quality. */
texture_view->get_face_info(v1, v2, v3, &info, settings);
if (info.quality == 0.0) continue;
/* Change color space. */
mve::image::color_rgb_to_ycbcr(*(info.mean_color));
std::pair<std::size_t, FaceProjectionInfo> pair(face_id, info);
projected_face_view_infos.push_back(pair);
}
texture_view->release_image();
texture_view->release_validity_mask();
if (settings.data_term == DATA_TERM_GMI) {
texture_view->release_gradient_magnitude();
}
view_counter.inc();
}
//std::sort(projected_face_view_infos.begin(), projected_face_view_infos.end());
#pragma omp critical
{
for (std::size_t i = projected_face_view_infos.size(); 0 < i; --i) {
std::size_t face_id = projected_face_view_infos[i - 1].first;
FaceProjectionInfo const & info = projected_face_view_infos[i - 1].second;
face_projection_infos->at(face_id).push_back(info);
}
projected_face_view_infos.clear();
}
}
}
void
postprocess_face_infos(Settings const & settings,
FaceProjectionInfos * face_projection_infos,
DataCosts * data_costs) {
ProgressCounter face_counter("\tPostprocessing face infos",
face_projection_infos->size());
#pragma omp parallel for schedule(dynamic)
for (std::size_t i = 0; i < face_projection_infos->size(); ++i) {
face_counter.progress<SIMPLE>();
std::vector<FaceProjectionInfo> & infos = face_projection_infos->at(i);
if (settings.outlier_removal != OUTLIER_REMOVAL_NONE) {
photometric_outlier_detection(&infos, settings);
infos.erase(std::remove_if(infos.begin(), infos.end(),
[](FaceProjectionInfo const & info) -> bool {return info.quality == 0.0f;}),
infos.end());
}
std::sort(infos.begin(), infos.end());
face_counter.inc();
}
/* Determine the function for the normlization. */
float max_quality = 0.0f;
for (std::size_t i = 0; i < face_projection_infos->size(); ++i)
for (FaceProjectionInfo const & info : face_projection_infos->at(i))
max_quality = std::max(max_quality, info.quality);
Histogram hist_qualities(0.0f, max_quality, 10000);
for (std::size_t i = 0; i < face_projection_infos->size(); ++i)
for (FaceProjectionInfo const & info : face_projection_infos->at(i))
hist_qualities.add_value(info.quality);
float percentile = hist_qualities.get_approx_percentile(0.995f);
/* Calculate the costs. */
for (std::uint32_t i = 0; i < face_projection_infos->size(); ++i) {
for (FaceProjectionInfo const & info : face_projection_infos->at(i)) {
/* Clamp to percentile and normalize. */
float normalized_quality = std::min(1.0f, info.quality / percentile);
float data_cost = (1.0f - normalized_quality) * MRF_MAX_ENERGYTERM;
data_costs->set_value(i, info.view_id, data_cost);
}
/* Ensure that all memory is freeed. */
face_projection_infos->at(i) = std::vector<FaceProjectionInfo>();
}
std::cout << "\tMaximum quality of a face within an image: " << max_quality << std::endl;
std::cout << "\tClamping qualities to " << percentile << " within normalization." << std::endl;
}
void
calculate_data_costs(mve::TriangleMesh::ConstPtr mesh, std::vector<TextureView> * texture_views,
Settings const & settings, DataCosts * data_costs) {
std::size_t const num_faces = mesh->get_faces().size() / 3;
std::size_t const num_views = texture_views->size();
assert(num_faces < std::numeric_limits<std::uint32_t>::max());
assert(num_views < std::numeric_limits<std::uint16_t>::max());
assert(MRF_MAX_ENERGYTERM < std::numeric_limits<float>::max());
FaceProjectionInfos face_projection_infos(num_faces);
calculate_face_projection_infos(mesh, texture_views, settings, &face_projection_infos);
postprocess_face_infos(settings, &face_projection_infos, data_costs);
}
TEX_NAMESPACE_END
<commit_msg>Check index ranges at runtime - fixes #64<commit_after>/*
* Copyright (C) 2015, Nils Moehrle, Michael Waechter
* TU Darmstadt - Graphics, Capture and Massively Parallel Computing
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD 3-Clause license. See the LICENSE.txt file for details.
*/
#include <numeric>
#include <mve/image_color.h>
#include <acc/bvh_tree.h>
#include <Eigen/Core>
#include <Eigen/LU>
#include "util.h"
#include "histogram.h"
#include "texturing.h"
#include "sparse_table.h"
#include "progress_counter.h"
typedef acc::BVHTree<unsigned int, math::Vec3f> BVHTree;
TEX_NAMESPACE_BEGIN
/**
* Dampens the quality of all views in which the face's projection
* has a much different color than in the majority of views.
* Returns whether the outlier removal was successfull.
*
* @param infos contains information about one face seen from several views
* @param settings runtime configuration.
*/
bool
photometric_outlier_detection(std::vector<FaceProjectionInfo> * infos, Settings const & settings) {
if (infos->size() == 0) return true;
/* Configuration variables. */
double const gauss_rejection_threshold = 6e-3;
/* If all covariances drop below this we stop outlier detection. */
double const minimal_covariance = 5e-4;
int const outlier_detection_iterations = 10;
int const minimal_num_inliers = 4;
float outlier_removal_factor = std::numeric_limits<float>::signaling_NaN();
switch (settings.outlier_removal) {
case OUTLIER_REMOVAL_NONE: return true;
case OUTLIER_REMOVAL_GAUSS_CLAMPING:
outlier_removal_factor = 1.0f;
break;
case OUTLIER_REMOVAL_GAUSS_DAMPING:
outlier_removal_factor = 0.2f;
break;
}
Eigen::MatrixX3d inliers(infos->size(), 3);
std::vector<std::uint32_t> is_inlier(infos->size(), 1);
for (std::size_t row = 0; row < infos->size(); ++row) {
inliers.row(row) = mve_to_eigen(infos->at(row).mean_color).cast<double>();
}
Eigen::RowVector3d var_mean;
Eigen::Matrix3d covariance;
Eigen::Matrix3d covariance_inv;
for (int i = 0; i < outlier_detection_iterations; ++i) {
if (inliers.rows() < minimal_num_inliers) {
return false;
}
/* Calculate the inliers' mean color and color covariance. */
var_mean = inliers.colwise().mean();
Eigen::MatrixX3d centered = inliers.rowwise() - var_mean;
covariance = (centered.adjoint() * centered) / double(inliers.rows() - 1);
/* If all covariances are very small we stop outlier detection
* and only keep the inliers (set quality of outliers to zero). */
if (covariance.array().abs().maxCoeff() < minimal_covariance) {
for (std::size_t row = 0; row < infos->size(); ++row) {
if (!is_inlier[row]) infos->at(row).quality = 0.0f;
}
return true;
}
/* Invert the covariance. FullPivLU is not the fastest way but
* it gives feedback about numerical stability during inversion. */
Eigen::FullPivLU<Eigen::Matrix3d> lu(covariance);
if (!lu.isInvertible()) {
return false;
}
covariance_inv = lu.inverse();
/* Compute new number of inliers (all views with a gauss value above a threshold). */
for (std::size_t row = 0; row < infos->size(); ++row) {
Eigen::RowVector3d color = mve_to_eigen(infos->at(row).mean_color).cast<double>();
double gauss_value = multi_gauss_unnormalized(color, var_mean, covariance_inv);
is_inlier[row] = (gauss_value >= gauss_rejection_threshold ? 1 : 0);
}
/* Resize Eigen matrix accordingly and fill with new inliers. */
inliers.resize(std::accumulate(is_inlier.begin(), is_inlier.end(), 0), Eigen::NoChange);
for (std::size_t row = 0, inlier_row = 0; row < infos->size(); ++row) {
if (is_inlier[row]) {
inliers.row(inlier_row++) = mve_to_eigen(infos->at(row).mean_color).cast<double>();
}
}
}
covariance_inv *= outlier_removal_factor;
for (FaceProjectionInfo & info : *infos) {
Eigen::RowVector3d color = mve_to_eigen(info.mean_color).cast<double>();
double gauss_value = multi_gauss_unnormalized(color, var_mean, covariance_inv);
assert(0.0 <= gauss_value && gauss_value <= 1.0);
switch(settings.outlier_removal) {
case OUTLIER_REMOVAL_NONE: return true;
case OUTLIER_REMOVAL_GAUSS_DAMPING:
info.quality *= gauss_value;
break;
case OUTLIER_REMOVAL_GAUSS_CLAMPING:
if (gauss_value < gauss_rejection_threshold) info.quality = 0.0f;
break;
}
}
return true;
}
void
calculate_face_projection_infos(mve::TriangleMesh::ConstPtr mesh,
std::vector<TextureView> * texture_views, Settings const & settings,
FaceProjectionInfos * face_projection_infos) {
std::vector<unsigned int> const & faces = mesh->get_faces();
std::vector<math::Vec3f> const & vertices = mesh->get_vertices();
mve::TriangleMesh::NormalList const & face_normals = mesh->get_face_normals();
std::size_t const num_views = texture_views->size();
util::WallTimer timer;
std::cout << "\tBuilding BVH from " << faces.size() / 3 << " faces... " << std::flush;
BVHTree bvh_tree(faces, vertices);
std::cout << "done. (Took: " << timer.get_elapsed() << " ms)" << std::endl;
ProgressCounter view_counter("\tCalculating face qualities", num_views);
#pragma omp parallel
{
std::vector<std::pair<std::size_t, FaceProjectionInfo> > projected_face_view_infos;
#pragma omp for schedule(dynamic)
for (std::uint16_t j = 0; j < static_cast<std::uint16_t>(num_views); ++j) {
view_counter.progress<SIMPLE>();
TextureView * texture_view = &texture_views->at(j);
texture_view->load_image();
texture_view->generate_validity_mask();
if (settings.data_term == DATA_TERM_GMI) {
texture_view->generate_gradient_magnitude();
texture_view->erode_validity_mask();
}
math::Vec3f const & view_pos = texture_view->get_pos();
math::Vec3f const & viewing_direction = texture_view->get_viewing_direction();
for (std::size_t i = 0; i < faces.size(); i += 3) {
std::size_t face_id = i / 3;
math::Vec3f const & v1 = vertices[faces[i]];
math::Vec3f const & v2 = vertices[faces[i + 1]];
math::Vec3f const & v3 = vertices[faces[i + 2]];
math::Vec3f const & face_normal = face_normals[face_id];
math::Vec3f const face_center = (v1 + v2 + v3) / 3.0f;
/* Check visibility and compute quality */
math::Vec3f view_to_face_vec = (face_center - view_pos).normalized();
math::Vec3f face_to_view_vec = (view_pos - face_center).normalized();
/* Backface and basic frustum culling */
float viewing_angle = face_to_view_vec.dot(face_normal);
if (viewing_angle < 0.0f || viewing_direction.dot(view_to_face_vec) < 0.0f)
continue;
if (std::acos(viewing_angle) > MATH_DEG2RAD(75.0f))
continue;
/* Projects into the valid part of the TextureView? */
if (!texture_view->inside(v1, v2, v3))
continue;
if (settings.geometric_visibility_test) {
/* Viewing rays do not collide? */
bool visible = true;
math::Vec3f const * samples[] = {&v1, &v2, &v3};
// TODO: random monte carlo samples...
for (std::size_t k = 0; k < sizeof(samples) / sizeof(samples[0]); ++k) {
BVHTree::Ray ray;
ray.origin = *samples[k];
ray.dir = view_pos - ray.origin;
ray.tmax = ray.dir.norm();
ray.tmin = ray.tmax * 0.0001f;
ray.dir.normalize();
BVHTree::Hit hit;
if (bvh_tree.intersect(ray, &hit)) {
visible = false;
break;
}
}
if (!visible) continue;
}
FaceProjectionInfo info = {j, 0.0f, math::Vec3f(0.0f, 0.0f, 0.0f)};
/* Calculate quality. */
texture_view->get_face_info(v1, v2, v3, &info, settings);
if (info.quality == 0.0) continue;
/* Change color space. */
mve::image::color_rgb_to_ycbcr(*(info.mean_color));
std::pair<std::size_t, FaceProjectionInfo> pair(face_id, info);
projected_face_view_infos.push_back(pair);
}
texture_view->release_image();
texture_view->release_validity_mask();
if (settings.data_term == DATA_TERM_GMI) {
texture_view->release_gradient_magnitude();
}
view_counter.inc();
}
//std::sort(projected_face_view_infos.begin(), projected_face_view_infos.end());
#pragma omp critical
{
for (std::size_t i = projected_face_view_infos.size(); 0 < i; --i) {
std::size_t face_id = projected_face_view_infos[i - 1].first;
FaceProjectionInfo const & info = projected_face_view_infos[i - 1].second;
face_projection_infos->at(face_id).push_back(info);
}
projected_face_view_infos.clear();
}
}
}
void
postprocess_face_infos(Settings const & settings,
FaceProjectionInfos * face_projection_infos,
DataCosts * data_costs) {
ProgressCounter face_counter("\tPostprocessing face infos",
face_projection_infos->size());
#pragma omp parallel for schedule(dynamic)
for (std::size_t i = 0; i < face_projection_infos->size(); ++i) {
face_counter.progress<SIMPLE>();
std::vector<FaceProjectionInfo> & infos = face_projection_infos->at(i);
if (settings.outlier_removal != OUTLIER_REMOVAL_NONE) {
photometric_outlier_detection(&infos, settings);
infos.erase(std::remove_if(infos.begin(), infos.end(),
[](FaceProjectionInfo const & info) -> bool {return info.quality == 0.0f;}),
infos.end());
}
std::sort(infos.begin(), infos.end());
face_counter.inc();
}
/* Determine the function for the normlization. */
float max_quality = 0.0f;
for (std::size_t i = 0; i < face_projection_infos->size(); ++i)
for (FaceProjectionInfo const & info : face_projection_infos->at(i))
max_quality = std::max(max_quality, info.quality);
Histogram hist_qualities(0.0f, max_quality, 10000);
for (std::size_t i = 0; i < face_projection_infos->size(); ++i)
for (FaceProjectionInfo const & info : face_projection_infos->at(i))
hist_qualities.add_value(info.quality);
float percentile = hist_qualities.get_approx_percentile(0.995f);
/* Calculate the costs. */
for (std::uint32_t i = 0; i < face_projection_infos->size(); ++i) {
for (FaceProjectionInfo const & info : face_projection_infos->at(i)) {
/* Clamp to percentile and normalize. */
float normalized_quality = std::min(1.0f, info.quality / percentile);
float data_cost = (1.0f - normalized_quality) * MRF_MAX_ENERGYTERM;
data_costs->set_value(i, info.view_id, data_cost);
}
/* Ensure that all memory is freeed. */
face_projection_infos->at(i) = std::vector<FaceProjectionInfo>();
}
std::cout << "\tMaximum quality of a face within an image: " << max_quality << std::endl;
std::cout << "\tClamping qualities to " << percentile << " within normalization." << std::endl;
}
void
calculate_data_costs(mve::TriangleMesh::ConstPtr mesh, std::vector<TextureView> * texture_views,
Settings const & settings, DataCosts * data_costs) {
std::size_t const num_faces = mesh->get_faces().size() / 3;
std::size_t const num_views = texture_views->size();
if (num_faces > std::numeric_limits<std::uint32_t>::max())
throw std::runtime_error("Exeeded maximal number of faces");
if (num_views > std::numeric_limits<std::uint16_t>::max())
throw std::runtime_error("Exeeded maximal number of views");
static_assert(MRF_MAX_ENERGYTERM <= std::numeric_limits<float>::max(),
"MRF_MAX_ENERGYTERM has to be within float limits");
FaceProjectionInfos face_projection_infos(num_faces);
calculate_face_projection_infos(mesh, texture_views, settings, &face_projection_infos);
postprocess_face_infos(settings, &face_projection_infos, data_costs);
}
TEX_NAMESPACE_END
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#ifndef CHART2_INTERNALDATA_HXX
#define CHART2_INTERNALDATA_HXX
#include <com/sun/star/uno/Sequence.hxx>
#include <vector>
#include <valarray>
namespace chart
{
class InternalData
{
public:
InternalData();
void createDefaultData();
bool isDefaultData();
void clearDefaultData();
void setData( const ::com::sun::star::uno::Sequence<
::com::sun::star::uno::Sequence< double > > & rDataInRows );
::com::sun::star::uno::Sequence<
::com::sun::star::uno::Sequence< double > > getData() const;
::com::sun::star::uno::Sequence< double > getColumnValues( sal_Int32 nColumnIndex ) const;
::com::sun::star::uno::Sequence< double > getRowValues( sal_Int32 nRowIndex ) const;
void setColumnValues( sal_Int32 nColumnIndex, const ::std::vector< double > & rNewData );
void setRowValues( sal_Int32 nRowIndex, const ::std::vector< double > & rNewData );
void setComplexColumnLabel( sal_Int32 nColumnIndex, const ::std::vector< ::com::sun::star::uno::Any >& rComplexLabel );
void setComplexRowLabel( sal_Int32 nRowIndex, const ::std::vector< ::com::sun::star::uno::Any >& rComplexLabel );
::std::vector< ::com::sun::star::uno::Any > getComplexColumnLabel( sal_Int32 nColumnIndex ) const;
::std::vector< ::com::sun::star::uno::Any > getComplexRowLabel( sal_Int32 nRowIndex ) const;
void swapRowWithNext( sal_Int32 nRowIndex );
void swapColumnWithNext( sal_Int32 nColumnIndex );
void insertColumn( sal_Int32 nAfterIndex );
void insertRow( sal_Int32 nAfterIndex );
void deleteColumn( sal_Int32 nAtIndex );
void deleteRow( sal_Int32 nAtIndex );
/// @return the index of the newly appended column
sal_Int32 appendColumn();
/// @return the index of the newly appended row
sal_Int32 appendRow();
sal_Int32 getRowCount() const;
sal_Int32 getColumnCount() const;
typedef ::std::valarray< double > tDataType;
typedef ::std::vector< ::std::vector< ::com::sun::star::uno::Any > > tVecVecAny; //inner index is hierarchical level
void setComplexRowLabels( const tVecVecAny& rNewRowLabels );
tVecVecAny getComplexRowLabels() const;
void setComplexColumnLabels( const tVecVecAny& rNewColumnLabels );
tVecVecAny getComplexColumnLabels() const;
#if OSL_DEBUG_LEVEL > 1
void traceData() const;
#endif
private: //methods
/** resizes the data if at least one of the given dimensions is larger than
before. The data is never becoming smaller only larger.
@return </sal_True>, if the data was enlarged
*/
bool enlargeData( sal_Int32 nColumnCount, sal_Int32 nRowCount );
private:
sal_Int32 m_nColumnCount;
sal_Int32 m_nRowCount;
tDataType m_aData;
tVecVecAny m_aRowLabels;//outer index is row index, inner index is category level
tVecVecAny m_aColumnLabels;//outer index is column index
};
#endif
} // namespace chart
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>make this typedef private<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#ifndef CHART2_INTERNALDATA_HXX
#define CHART2_INTERNALDATA_HXX
#include <com/sun/star/uno/Sequence.hxx>
#include <vector>
#include <valarray>
namespace chart
{
class InternalData
{
public:
InternalData();
void createDefaultData();
bool isDefaultData();
void clearDefaultData();
void setData( const ::com::sun::star::uno::Sequence<
::com::sun::star::uno::Sequence< double > > & rDataInRows );
::com::sun::star::uno::Sequence<
::com::sun::star::uno::Sequence< double > > getData() const;
::com::sun::star::uno::Sequence< double > getColumnValues( sal_Int32 nColumnIndex ) const;
::com::sun::star::uno::Sequence< double > getRowValues( sal_Int32 nRowIndex ) const;
void setColumnValues( sal_Int32 nColumnIndex, const ::std::vector< double > & rNewData );
void setRowValues( sal_Int32 nRowIndex, const ::std::vector< double > & rNewData );
void setComplexColumnLabel( sal_Int32 nColumnIndex, const ::std::vector< ::com::sun::star::uno::Any >& rComplexLabel );
void setComplexRowLabel( sal_Int32 nRowIndex, const ::std::vector< ::com::sun::star::uno::Any >& rComplexLabel );
::std::vector< ::com::sun::star::uno::Any > getComplexColumnLabel( sal_Int32 nColumnIndex ) const;
::std::vector< ::com::sun::star::uno::Any > getComplexRowLabel( sal_Int32 nRowIndex ) const;
void swapRowWithNext( sal_Int32 nRowIndex );
void swapColumnWithNext( sal_Int32 nColumnIndex );
void insertColumn( sal_Int32 nAfterIndex );
void insertRow( sal_Int32 nAfterIndex );
void deleteColumn( sal_Int32 nAtIndex );
void deleteRow( sal_Int32 nAtIndex );
/// @return the index of the newly appended column
sal_Int32 appendColumn();
/// @return the index of the newly appended row
sal_Int32 appendRow();
sal_Int32 getRowCount() const;
sal_Int32 getColumnCount() const;
typedef ::std::vector< ::std::vector< ::com::sun::star::uno::Any > > tVecVecAny; //inner index is hierarchical level
void setComplexRowLabels( const tVecVecAny& rNewRowLabels );
tVecVecAny getComplexRowLabels() const;
void setComplexColumnLabels( const tVecVecAny& rNewColumnLabels );
tVecVecAny getComplexColumnLabels() const;
#if OSL_DEBUG_LEVEL > 1
void traceData() const;
#endif
private: //methods
/** resizes the data if at least one of the given dimensions is larger than
before. The data is never becoming smaller only larger.
@return </sal_True>, if the data was enlarged
*/
bool enlargeData( sal_Int32 nColumnCount, sal_Int32 nRowCount );
private:
sal_Int32 m_nColumnCount;
sal_Int32 m_nRowCount;
typedef ::std::valarray< double > tDataType;
tDataType m_aData;
tVecVecAny m_aRowLabels;//outer index is row index, inner index is category level
tVecVecAny m_aColumnLabels;//outer index is column index
};
#endif
} // namespace chart
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>#include <map>
#include <ros/ros.h>
#include <sensor_msgs/JointState.h>
#include <std_msgs/Float32.h>
std::map<std::string, double> g_servo_angle;
void angle_stateCb(const std_msgs::Float32::ConstPtr& sub_msg, const std::string& side)
{
g_servo_angle[side] = sub_msg->data;
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "gripper_joint_states_publisher");
ros::NodeHandle n;
ros::Publisher servo_angle_pub = n.advertise<sensor_msgs::JointState>("robot/joint_states", 100);
ros::Subscriber right_servo_angle_sub = n.subscribe<std_msgs::Float32>("gripper_front/limb/right/servo/angle/state",
10, boost::bind(&angle_stateCb, _1, "right"));
ros::Subscriber left_servo_angle_sub = n.subscribe<std_msgs::Float32>("gripper_front/limb/left/servo/angle/state", 10,
boost::bind(&angle_stateCb, _1, "left"));
std::map<std::string, std::string> side_to_jt;
side_to_jt["right"] = "right_gripper_vacuum_pad_joint";
side_to_jt["left"] = "left_gripper_vacuum_pad_joint";
ros::Rate r(30);
while (ros::ok())
{
ros::spinOnce();
if (g_servo_angle.size() == side_to_jt.size())
{
sensor_msgs::JointState pub_msg;
pub_msg.header.stamp = ros::Time::now();
for (std::map<std::string, std::string>::iterator pair = side_to_jt.begin(); pair != side_to_jt.end(); ++pair)
{
pub_msg.name.push_back(pair->second);
pub_msg.position.push_back(g_servo_angle[pair->first]);
pub_msg.velocity.push_back(0);
pub_msg.effort.push_back(0);
}
servo_angle_pub.publish(pub_msg);
}
r.sleep();
}
return 0;
}
<commit_msg>Push gripper joint states back of other joint states<commit_after>#include <map>
#include <ros/ros.h>
#include <sensor_msgs/JointState.h>
#include <std_msgs/Float32.h>
std::map<std::string, double> g_servo_angle;
std::map<std::string, std::string> g_side_to_jt;
sensor_msgs::JointState g_joint_states_except_gripper;
void angle_stateCb(const std_msgs::Float32::ConstPtr& sub_msg, const std::string& side)
{
g_servo_angle[side] = sub_msg->data;
}
void joint_statesCb(const sensor_msgs::JointState::ConstPtr& joint_states)
{
for (std::map<std::string, std::string>::iterator pair = g_side_to_jt.begin(); pair != g_side_to_jt.end(); ++pair)
{
for (int i = 0; i < joint_states->name.size(); i++)
{
if (joint_states->name[i] == pair->second)
return;
}
}
g_joint_states_except_gripper = (*joint_states);
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "gripper_joint_states_publisher");
ros::NodeHandle n;
ros::Publisher servo_angle_pub = n.advertise<sensor_msgs::JointState>("robot/joint_states", 100);
ros::Subscriber right_servo_angle_sub = n.subscribe<std_msgs::Float32>("gripper_front/limb/right/servo/angle/state",
10, boost::bind(&angle_stateCb, _1, "right"));
ros::Subscriber left_servo_angle_sub = n.subscribe<std_msgs::Float32>("gripper_front/limb/left/servo/angle/state", 10,
boost::bind(&angle_stateCb, _1, "left"));
ros::Subscriber joint_states_sub = n.subscribe("robot/joint_states", 10, joint_statesCb);
g_side_to_jt["right"] = "right_gripper_vacuum_pad_joint";
g_side_to_jt["left"] = "left_gripper_vacuum_pad_joint";
ros::Rate r(30);
while (ros::ok())
{
ros::spinOnce();
if (g_servo_angle.size() == g_side_to_jt.size())
{
sensor_msgs::JointState pub_msg;
pub_msg = g_joint_states_except_gripper;
pub_msg.header.stamp = ros::Time::now();
for (std::map<std::string, std::string>::iterator pair = g_side_to_jt.begin(); pair != g_side_to_jt.end(); ++pair)
{
pub_msg.name.push_back(pair->second);
pub_msg.position.push_back(g_servo_angle[pair->first]);
pub_msg.velocity.push_back(0);
pub_msg.effort.push_back(0);
}
servo_angle_pub.publish(pub_msg);
}
r.sleep();
}
return 0;
}
<|endoftext|> |
<commit_before>/* Sirikata
* HitPointScenario.cpp
*
* Copyright (c) 2010, Ewen Cheslack-Postava
* 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 Sirikata nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "HitPointScenario.hpp"
#include "ScenarioFactory.hpp"
#include "ObjectHost.hpp"
#include "Object.hpp"
#include <sirikata/core/options/Options.hpp>
#include <sirikata/core/network/SSTImpl.hpp>
#include <sirikata/core/options/CommonOptions.hpp>
#include "Options.hpp"
#include "ConnectedObjectTracker.hpp"
namespace Sirikata {
class DamagableObject {
public:
Object *object;
typedef float HPTYPE;
HPTYPE mHP;
unsigned int mListenPort;
DamagableObject (Object *obj, float hp, unsigned int listenPort){
mHP=hp;
object=obj;
mListenPort = listenPort;
}
void update() {
for (size_t i=0;i<mDamageReceivers.size();++i) {
mDamageReceivers[i]->sendUpdate();
}
}
class ReceiveDamage {
UUID mID;
DamagableObject *mParent;
boost::shared_ptr<Stream<UUID> > mSendStream;
boost::shared_ptr<Stream<UUID> > mReceiveStream;
uint8 mPartialUpdate[sizeof(DamagableObject::mHP)];
int mPartialCount;
uint8 mPartialSend[sizeof(DamagableObject::mHP)*2];
int mPartialSendCount;
public:
ReceiveDamage(DamagableObject*parent, UUID id) {
mID=id;
mParent=parent;
mPartialCount=0;
mPartialSendCount=0;
memset(mPartialSend,0,sizeof(DamagableObject::HPTYPE)*2);
memset(mPartialUpdate,0,sizeof(DamagableObject::HPTYPE));
Stream<UUID>::listen(std::tr1::bind(&DamagableObject::ReceiveDamage::login,this,_1,_2),
EndPoint<UUID>(mID,parent->mListenPort));
Stream<UUID>::connectStream(mParent->object,
EndPoint<UUID>(mParent->object->uuid(),parent->mListenPort),
EndPoint<UUID>(mID,parent->mListenPort),
std::tr1::bind(&DamagableObject::ReceiveDamage::connectionCallback,this,_1,_2));
}
void connectionCallback(int err, boost::shared_ptr<Stream<UUID> > s) {
if (err != 0 ) {
SILOG(hitpoint,error,"Failed to connect two objects\n");
}else {
this->mSendStream = s;
s->registerReadCallback( std::tr1::bind( &DamagableObject::ReceiveDamage::senderShouldNotGetUpdate, this, _1, _2) ) ;
sendUpdate();
}
}
void login(int err, boost::shared_ptr< Stream<UUID> > s) {
if (err != 0) {
SILOG(hitpoint,error,"Failed to listen on port for two objects\n");
}else {
s->registerReadCallback( std::tr1::bind( &DamagableObject::ReceiveDamage::getUpdate, this, _1, _2) ) ;
mReceiveStream=s;
}
}
void sendUpdate() {
int tosend=sizeof(DamagableObject::HPTYPE);
if (mPartialSendCount) {
memcpy(mPartialSend+sizeof(DamagableObject::HPTYPE),&mParent->mHP,sizeof(DamagableObject::HPTYPE));
tosend*=2;
tosend-=mPartialSendCount;
}else {
memcpy(mPartialSend,&mParent->mHP,tosend);
}
mPartialSendCount+=mSendStream->write(mPartialSend+mPartialSendCount,tosend);
if(mPartialSendCount>=sizeof(DamagableObject::HPTYPE)) {
mPartialSendCount-=sizeof(DamagableObject::HPTYPE);
memcpy(mPartialSend,mPartialSend+sizeof(DamagableObject::HPTYPE),sizeof(DamagableObject::HPTYPE));
}
if(mPartialSendCount>=sizeof(DamagableObject::HPTYPE)) {
mPartialSendCount=0;
}
assert(mPartialSendCount<sizeof(DamagableObject::HPTYPE));
}
void senderShouldNotGetUpdate(uint8*buffer, int length) {
SILOG(hitpoint,error,"Should not receive updates from receiver");
}
void getUpdate(uint8*buffer, int length) {
while (length>0) {
int datacopied = (length>sizeof(DamagableObject::HPTYPE)-mPartialCount?sizeof(DamagableObject::HPTYPE)-mPartialCount:length);
memcpy(mPartialUpdate+mPartialCount, buffer,datacopied);
mPartialCount+=datacopied;
if (mPartialCount==sizeof(DamagableObject::HPTYPE)) {
DamagableObject::HPTYPE hp;
memcpy(&hp,mPartialUpdate,mPartialCount);
SILOG(hitpoint,error,"Got hitpoint update for "<<mID.toString()<<" as "<<hp);
mPartialCount=0;
}
buffer+=datacopied;
length-=datacopied;
}
}
};
std::vector<ReceiveDamage*> mDamageReceivers;
friend class ReceiveDamage;
};
void PDSInitOptions(HitPointScenario *thus) {
Sirikata::InitializeClassOptions ico("HitPointScenario",thus,
new OptionValue("num-pings-per-second","1000",Sirikata::OptionValueType<double>(),"Number of pings launched per simulation second"),
new OptionValue("ping-size","1024",Sirikata::OptionValueType<uint32>(),"Size of ping payloads. Doesn't include any other fields in the ping or the object message headers."),
new OptionValue("flood-server","1",Sirikata::OptionValueType<uint32>(),"The index of the server to flood. Defaults to 1 so it will work with all layouts. To flood all servers, specify 0."),
new OptionValue("local","false",Sirikata::OptionValueType<bool>(),"If true, generated traffic will all be local, i.e. will all originate at the flood-server. Otherwise, it will always originate from other servers."),
NULL);
}
HitPointScenario::HitPointScenario(const String &options)
: mStartTime(Time::epoch())
{
mNumTotalPings=0;
mContext=NULL;
mObjectTracker = NULL;
mPingID=0;
PDSInitOptions(this);
OptionSet* optionsSet = OptionSet::getOptions("HitPointScenario",this);
optionsSet->parse(options);
mNumPingsPerSecond=optionsSet->referenceOption("num-pings-per-second")->as<double>();
mPingPayloadSize=optionsSet->referenceOption("ping-size")->as<uint32>();
mFloodServer = optionsSet->referenceOption("flood-server")->as<uint32>();
mLocalTraffic = optionsSet->referenceOption("local")->as<bool>();
mNumGeneratedPings = 0;
mGeneratePingsStrand = NULL;
mGeneratePingPoller = NULL;
mPings = // We allocate space for 1/4 seconds worth of pings
new Sirikata::SizedThreadSafeQueue<PingInfo,CountResourceMonitor>(
CountResourceMonitor(std::max((uint32)(mNumPingsPerSecond / 4), (uint32)2))
);
mPingPoller = NULL;
// NOTE: We have this limit because we can get in lock-step with the
// generator, causing this to run for excessively long when we fall behind
// on pings. This allows us to burst to catch up when there is time (and
// amortize the constant overhead of doing 1 round), but if
// there is other work to be done we won't make our target rate.
mMaxPingsPerRound = 40;
// Do we want to vary this based on mNumPingsPerSecond? 20 is a decent
// burst, but at 10k/s can take 2ms (we're seeing about 100us/ping
// currently), which is potentially a long delay for other things in this
// strand. If we try to get to 100k, that can be up to 20ms which is very
// long to block other things on the main strand.
}
HitPointScenario::~HitPointScenario(){
SILOG(deluge,fatal,
"HitPoint: Generated: " << mNumGeneratedPings <<
" Sent: " << mNumTotalPings);
delete mPings;
delete mPingPoller;
delete mPingProfiler;
}
HitPointScenario*HitPointScenario::create(const String&options){
return new HitPointScenario(options);
}
void HitPointScenario::addConstructorToFactory(ScenarioFactory*thus){
thus->registerConstructor("hitpoint",&HitPointScenario::create);
}
void HitPointScenario::initialize(ObjectHostContext*ctx) {
mContext=ctx;
mObjectTracker = new ConnectedObjectTracker(mContext->objectHost);
mPingProfiler = mContext->profiler->addStage("Object Host Send Pings");
mPingPoller = new Poller(
ctx->mainStrand,
std::tr1::bind(&HitPointScenario::sendPings, this),
mNumPingsPerSecond > 1000 ? // Try to amortize out some of the
// scheduling cost
Duration::seconds(10.0/mNumPingsPerSecond) :
Duration::seconds(1.0/mNumPingsPerSecond)
);
mGeneratePingProfiler = mContext->profiler->addStage("Object Host Generate Pings");
mGeneratePingsStrand = mContext->ioService->createStrand();
mGeneratePingPoller = new Poller(
mGeneratePingsStrand,
std::tr1::bind(&HitPointScenario::generatePings, this),
mNumPingsPerSecond > 1000 ? // Try to amortize out some of the
// scheduling cost
Duration::seconds(10.0/mNumPingsPerSecond) :
Duration::seconds(1.0/mNumPingsPerSecond)
);
}
void HitPointScenario::start() {
Duration connect_phase = GetOptionValue<Duration>(OBJECT_CONNECT_PHASE);
mContext->mainStrand->post(
connect_phase,
std::tr1::bind(&HitPointScenario::delayedStart, this)
);
}
void HitPointScenario::delayedStart() {
mStartTime = mContext->simTime();
mGeneratePingPoller->start();
mPingPoller->start();
}
void HitPointScenario::stop() {
mPingPoller->stop();
mGeneratePingPoller->stop();
}
bool HitPointScenario::generateOnePing(const Time& t, PingInfo* result) {
Object* objA = NULL;
Object* objB = NULL;
if (mFloodServer == 0) {
// When we don't have a flood server, we have a slightly different process.
if (mLocalTraffic) {
// If we need local traffic, pick a server and pin both of
// them to that server.
ServerID ss = rand() % mObjectTracker->numServerIDs();
objA = mObjectTracker->randomObjectFromServer(ss);
objB = mObjectTracker->randomObjectFromServer(ss);
}
else {
// Otherwise, we don't care about the origin of either
objA = mObjectTracker->randomObject();
objB = mObjectTracker->randomObject();
}
}
else {
// When we do have a flood server, we always pick the dest
// from that server.
objB = mObjectTracker->randomObjectFromServer(mFloodServer);
if (mLocalTraffic) {
// If forcing local traffic, pick source from same server
objA = mObjectTracker->randomObjectFromServer(mFloodServer);
}
else {
// Otherwise, pick from any *other* server.
objA = mObjectTracker->randomObjectExcludingServer(mFloodServer);
}
}
if (!objA || !objB) {
return false;
}
result->objA = objA->uuid();
result->objB = objB->uuid();
result->dist = (objA->location().position(t) - objB->location().position(t)).length();
result->ping = new Sirikata::Protocol::Object::Ping();
mContext->objectHost->fillPing(result->dist, mPingPayloadSize, result->ping);
return true;
}
void HitPointScenario::generatePings() {
mGeneratePingProfiler->started();
Time t=mContext->simTime();
int64 howManyPings=((t-mStartTime).toSeconds()+0.25)*mNumPingsPerSecond;
bool broke=false;
int64 limit=howManyPings-mNumGeneratedPings;
int64 i;
for (i=0;i<limit;++i) {
PingInfo result;
if (!mPings->probablyCanPush(result))
break;
if (!generateOnePing(t, &result))
break;
if (!mPings->push(result, false))
break;
}
mNumGeneratedPings += i;
mGeneratePingProfiler->finished();
}
void HitPointScenario::sendPings() {
mPingProfiler->started();
Time newTime=mContext->simTime();
int64 howManyPings = (newTime-mStartTime).toSeconds()*mNumPingsPerSecond;
bool broke=false;
// NOTE: We limit here because we can get in lock-step with the generator,
// causing this to run for excessively long when we fall behind on pings.
int64 limit = std::min((int64)howManyPings-mNumTotalPings, mMaxPingsPerRound);
int64 i;
for (i=0;i<limit;++i) {
Time t(mContext->simTime());
PingInfo result;
if (!mPings->pop(result)) {
SILOG(oh,insane,"[OH] " << "Ping queue underflowed.");
break;
}
bool sent_success = mContext->objectHost->sendPing(t, result.objA, result.objB, result.ping);
delete result.ping;
if (!sent_success)
break;
}
mNumTotalPings += i;
mPingProfiler->finished();
static bool printed=false;
if ( (i-limit) > (10*(int64)mNumPingsPerSecond) && !printed) {
SILOG(oh,debug,"[OH] " << i-limit<<" pending ");
printed=true;
}
}
}
<commit_msg>Fix compile error for older gcc.<commit_after>/* Sirikata
* HitPointScenario.cpp
*
* Copyright (c) 2010, Ewen Cheslack-Postava
* 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 Sirikata nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "HitPointScenario.hpp"
#include "ScenarioFactory.hpp"
#include "ObjectHost.hpp"
#include "Object.hpp"
#include <sirikata/core/options/Options.hpp>
#include <sirikata/core/network/SSTImpl.hpp>
#include <sirikata/core/options/CommonOptions.hpp>
#include "Options.hpp"
#include "ConnectedObjectTracker.hpp"
namespace Sirikata {
class DamagableObject {
public:
Object *object;
typedef float HPTYPE;
HPTYPE mHP;
unsigned int mListenPort;
DamagableObject (Object *obj, float hp, unsigned int listenPort){
mHP=hp;
object=obj;
mListenPort = listenPort;
}
void update() {
for (size_t i=0;i<mDamageReceivers.size();++i) {
mDamageReceivers[i]->sendUpdate();
}
}
class ReceiveDamage {
UUID mID;
DamagableObject *mParent;
boost::shared_ptr<Stream<UUID> > mSendStream;
boost::shared_ptr<Stream<UUID> > mReceiveStream;
uint8 mPartialUpdate[sizeof(HPTYPE)];
int mPartialCount;
uint8 mPartialSend[sizeof(HPTYPE)*2];
int mPartialSendCount;
public:
ReceiveDamage(DamagableObject*parent, UUID id) {
mID=id;
mParent=parent;
mPartialCount=0;
mPartialSendCount=0;
memset(mPartialSend,0,sizeof(DamagableObject::HPTYPE)*2);
memset(mPartialUpdate,0,sizeof(DamagableObject::HPTYPE));
Stream<UUID>::listen(std::tr1::bind(&DamagableObject::ReceiveDamage::login,this,_1,_2),
EndPoint<UUID>(mID,parent->mListenPort));
Stream<UUID>::connectStream(mParent->object,
EndPoint<UUID>(mParent->object->uuid(),parent->mListenPort),
EndPoint<UUID>(mID,parent->mListenPort),
std::tr1::bind(&DamagableObject::ReceiveDamage::connectionCallback,this,_1,_2));
}
void connectionCallback(int err, boost::shared_ptr<Stream<UUID> > s) {
if (err != 0 ) {
SILOG(hitpoint,error,"Failed to connect two objects\n");
}else {
this->mSendStream = s;
s->registerReadCallback( std::tr1::bind( &DamagableObject::ReceiveDamage::senderShouldNotGetUpdate, this, _1, _2) ) ;
sendUpdate();
}
}
void login(int err, boost::shared_ptr< Stream<UUID> > s) {
if (err != 0) {
SILOG(hitpoint,error,"Failed to listen on port for two objects\n");
}else {
s->registerReadCallback( std::tr1::bind( &DamagableObject::ReceiveDamage::getUpdate, this, _1, _2) ) ;
mReceiveStream=s;
}
}
void sendUpdate() {
int tosend=sizeof(DamagableObject::HPTYPE);
if (mPartialSendCount) {
memcpy(mPartialSend+sizeof(DamagableObject::HPTYPE),&mParent->mHP,sizeof(DamagableObject::HPTYPE));
tosend*=2;
tosend-=mPartialSendCount;
}else {
memcpy(mPartialSend,&mParent->mHP,tosend);
}
mPartialSendCount+=mSendStream->write(mPartialSend+mPartialSendCount,tosend);
if(mPartialSendCount>=sizeof(DamagableObject::HPTYPE)) {
mPartialSendCount-=sizeof(DamagableObject::HPTYPE);
memcpy(mPartialSend,mPartialSend+sizeof(DamagableObject::HPTYPE),sizeof(DamagableObject::HPTYPE));
}
if(mPartialSendCount>=sizeof(DamagableObject::HPTYPE)) {
mPartialSendCount=0;
}
assert(mPartialSendCount<sizeof(DamagableObject::HPTYPE));
}
void senderShouldNotGetUpdate(uint8*buffer, int length) {
SILOG(hitpoint,error,"Should not receive updates from receiver");
}
void getUpdate(uint8*buffer, int length) {
while (length>0) {
int datacopied = (length>sizeof(DamagableObject::HPTYPE)-mPartialCount?sizeof(DamagableObject::HPTYPE)-mPartialCount:length);
memcpy(mPartialUpdate+mPartialCount, buffer,datacopied);
mPartialCount+=datacopied;
if (mPartialCount==sizeof(DamagableObject::HPTYPE)) {
DamagableObject::HPTYPE hp;
memcpy(&hp,mPartialUpdate,mPartialCount);
SILOG(hitpoint,error,"Got hitpoint update for "<<mID.toString()<<" as "<<hp);
mPartialCount=0;
}
buffer+=datacopied;
length-=datacopied;
}
}
};
std::vector<ReceiveDamage*> mDamageReceivers;
friend class ReceiveDamage;
};
void PDSInitOptions(HitPointScenario *thus) {
Sirikata::InitializeClassOptions ico("HitPointScenario",thus,
new OptionValue("num-pings-per-second","1000",Sirikata::OptionValueType<double>(),"Number of pings launched per simulation second"),
new OptionValue("ping-size","1024",Sirikata::OptionValueType<uint32>(),"Size of ping payloads. Doesn't include any other fields in the ping or the object message headers."),
new OptionValue("flood-server","1",Sirikata::OptionValueType<uint32>(),"The index of the server to flood. Defaults to 1 so it will work with all layouts. To flood all servers, specify 0."),
new OptionValue("local","false",Sirikata::OptionValueType<bool>(),"If true, generated traffic will all be local, i.e. will all originate at the flood-server. Otherwise, it will always originate from other servers."),
NULL);
}
HitPointScenario::HitPointScenario(const String &options)
: mStartTime(Time::epoch())
{
mNumTotalPings=0;
mContext=NULL;
mObjectTracker = NULL;
mPingID=0;
PDSInitOptions(this);
OptionSet* optionsSet = OptionSet::getOptions("HitPointScenario",this);
optionsSet->parse(options);
mNumPingsPerSecond=optionsSet->referenceOption("num-pings-per-second")->as<double>();
mPingPayloadSize=optionsSet->referenceOption("ping-size")->as<uint32>();
mFloodServer = optionsSet->referenceOption("flood-server")->as<uint32>();
mLocalTraffic = optionsSet->referenceOption("local")->as<bool>();
mNumGeneratedPings = 0;
mGeneratePingsStrand = NULL;
mGeneratePingPoller = NULL;
mPings = // We allocate space for 1/4 seconds worth of pings
new Sirikata::SizedThreadSafeQueue<PingInfo,CountResourceMonitor>(
CountResourceMonitor(std::max((uint32)(mNumPingsPerSecond / 4), (uint32)2))
);
mPingPoller = NULL;
// NOTE: We have this limit because we can get in lock-step with the
// generator, causing this to run for excessively long when we fall behind
// on pings. This allows us to burst to catch up when there is time (and
// amortize the constant overhead of doing 1 round), but if
// there is other work to be done we won't make our target rate.
mMaxPingsPerRound = 40;
// Do we want to vary this based on mNumPingsPerSecond? 20 is a decent
// burst, but at 10k/s can take 2ms (we're seeing about 100us/ping
// currently), which is potentially a long delay for other things in this
// strand. If we try to get to 100k, that can be up to 20ms which is very
// long to block other things on the main strand.
}
HitPointScenario::~HitPointScenario(){
SILOG(deluge,fatal,
"HitPoint: Generated: " << mNumGeneratedPings <<
" Sent: " << mNumTotalPings);
delete mPings;
delete mPingPoller;
delete mPingProfiler;
}
HitPointScenario*HitPointScenario::create(const String&options){
return new HitPointScenario(options);
}
void HitPointScenario::addConstructorToFactory(ScenarioFactory*thus){
thus->registerConstructor("hitpoint",&HitPointScenario::create);
}
void HitPointScenario::initialize(ObjectHostContext*ctx) {
mContext=ctx;
mObjectTracker = new ConnectedObjectTracker(mContext->objectHost);
mPingProfiler = mContext->profiler->addStage("Object Host Send Pings");
mPingPoller = new Poller(
ctx->mainStrand,
std::tr1::bind(&HitPointScenario::sendPings, this),
mNumPingsPerSecond > 1000 ? // Try to amortize out some of the
// scheduling cost
Duration::seconds(10.0/mNumPingsPerSecond) :
Duration::seconds(1.0/mNumPingsPerSecond)
);
mGeneratePingProfiler = mContext->profiler->addStage("Object Host Generate Pings");
mGeneratePingsStrand = mContext->ioService->createStrand();
mGeneratePingPoller = new Poller(
mGeneratePingsStrand,
std::tr1::bind(&HitPointScenario::generatePings, this),
mNumPingsPerSecond > 1000 ? // Try to amortize out some of the
// scheduling cost
Duration::seconds(10.0/mNumPingsPerSecond) :
Duration::seconds(1.0/mNumPingsPerSecond)
);
}
void HitPointScenario::start() {
Duration connect_phase = GetOptionValue<Duration>(OBJECT_CONNECT_PHASE);
mContext->mainStrand->post(
connect_phase,
std::tr1::bind(&HitPointScenario::delayedStart, this)
);
}
void HitPointScenario::delayedStart() {
mStartTime = mContext->simTime();
mGeneratePingPoller->start();
mPingPoller->start();
}
void HitPointScenario::stop() {
mPingPoller->stop();
mGeneratePingPoller->stop();
}
bool HitPointScenario::generateOnePing(const Time& t, PingInfo* result) {
Object* objA = NULL;
Object* objB = NULL;
if (mFloodServer == 0) {
// When we don't have a flood server, we have a slightly different process.
if (mLocalTraffic) {
// If we need local traffic, pick a server and pin both of
// them to that server.
ServerID ss = rand() % mObjectTracker->numServerIDs();
objA = mObjectTracker->randomObjectFromServer(ss);
objB = mObjectTracker->randomObjectFromServer(ss);
}
else {
// Otherwise, we don't care about the origin of either
objA = mObjectTracker->randomObject();
objB = mObjectTracker->randomObject();
}
}
else {
// When we do have a flood server, we always pick the dest
// from that server.
objB = mObjectTracker->randomObjectFromServer(mFloodServer);
if (mLocalTraffic) {
// If forcing local traffic, pick source from same server
objA = mObjectTracker->randomObjectFromServer(mFloodServer);
}
else {
// Otherwise, pick from any *other* server.
objA = mObjectTracker->randomObjectExcludingServer(mFloodServer);
}
}
if (!objA || !objB) {
return false;
}
result->objA = objA->uuid();
result->objB = objB->uuid();
result->dist = (objA->location().position(t) - objB->location().position(t)).length();
result->ping = new Sirikata::Protocol::Object::Ping();
mContext->objectHost->fillPing(result->dist, mPingPayloadSize, result->ping);
return true;
}
void HitPointScenario::generatePings() {
mGeneratePingProfiler->started();
Time t=mContext->simTime();
int64 howManyPings=((t-mStartTime).toSeconds()+0.25)*mNumPingsPerSecond;
bool broke=false;
int64 limit=howManyPings-mNumGeneratedPings;
int64 i;
for (i=0;i<limit;++i) {
PingInfo result;
if (!mPings->probablyCanPush(result))
break;
if (!generateOnePing(t, &result))
break;
if (!mPings->push(result, false))
break;
}
mNumGeneratedPings += i;
mGeneratePingProfiler->finished();
}
void HitPointScenario::sendPings() {
mPingProfiler->started();
Time newTime=mContext->simTime();
int64 howManyPings = (newTime-mStartTime).toSeconds()*mNumPingsPerSecond;
bool broke=false;
// NOTE: We limit here because we can get in lock-step with the generator,
// causing this to run for excessively long when we fall behind on pings.
int64 limit = std::min((int64)howManyPings-mNumTotalPings, mMaxPingsPerRound);
int64 i;
for (i=0;i<limit;++i) {
Time t(mContext->simTime());
PingInfo result;
if (!mPings->pop(result)) {
SILOG(oh,insane,"[OH] " << "Ping queue underflowed.");
break;
}
bool sent_success = mContext->objectHost->sendPing(t, result.objA, result.objB, result.ping);
delete result.ping;
if (!sent_success)
break;
}
mNumTotalPings += i;
mPingProfiler->finished();
static bool printed=false;
if ( (i-limit) > (10*(int64)mNumPingsPerSecond) && !printed) {
SILOG(oh,debug,"[OH] " << i-limit<<" pending ");
printed=true;
}
}
}
<|endoftext|> |
<commit_before><commit_msg>DLL API finished.<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (C) 2006 by Tommi Maekitalo
* Copyright (C) 2006 by Marc Boris Duerner
* Copyright (C) 2006 by Stefan Bueder
*
* 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.
*
* As a special exception, you may use this file as part of a free
* software library without restriction. Specifically, if other files
* instantiate templates or use macros or inline functions from this
* file, or you compile this file and link it with other files to
* produce an executable, this file does not by itself cause the
* resulting executable to be covered by the GNU General Public
* License. This exception does not however invalidate any other
* reasons why the executable file might be covered by the GNU Library
* General Public License.
*
* 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 "cxxtools/smartptr.h"
#include "cxxtools/refcounted.h"
#include "cxxtools/unit/assertion.h"
#include "cxxtools/unit/testsuite.h"
#include "cxxtools/unit/registertest.h"
class Object : public cxxtools::RefCounted
{
public:
Object()
{ ++objectRefs; }
~Object()
{ --objectRefs; }
static std::size_t objectRefs;
};
std::size_t Object::objectRefs = 0;
class SmartPtrTest : public cxxtools::unit::TestSuite
{
public:
SmartPtrTest()
: cxxtools::unit::TestSuite( "SmartPtr" )
{
registerMethod( "RefCounted", *this, &SmartPtrTest::RefCounted );
registerMethod( "InternalRefCounted", *this, &SmartPtrTest::InternalRefCounted );
registerMethod( "RefLinked", *this, &SmartPtrTest::RefLinked );
}
public:
void setUp();
protected:
void RefCounted();
void InternalRefCounted();
void RefLinked();
};
cxxtools::unit::RegisterTest<SmartPtrTest> register_SmartPtrTest;
void SmartPtrTest::setUp()
{
Object::objectRefs = 0;
}
void SmartPtrTest::RefCounted()
{
Object* obj = new Object();
typedef cxxtools::SmartPtr<Object, cxxtools::ExternalRefCounted> Ptr;
{
Ptr smartPtr(obj);
CXXTOOLS_UNIT_ASSERT_EQUALS( smartPtr.refs(), 1 );
Ptr second(smartPtr);
CXXTOOLS_UNIT_ASSERT_EQUALS( second.refs(), 2);
Ptr third;
third = second;
CXXTOOLS_UNIT_ASSERT_EQUALS( third.refs(), 3);
third = third;
CXXTOOLS_UNIT_ASSERT_EQUALS( third.refs(), 3);
}
CXXTOOLS_UNIT_ASSERT_EQUALS(Object::objectRefs, 0);
}
void SmartPtrTest::InternalRefCounted()
{
Object* obj = new Object();
typedef cxxtools::SmartPtr<Object, cxxtools::InternalRefCounted> Ptr;
{
Ptr smartPtr(obj);
CXXTOOLS_UNIT_ASSERT_EQUALS( smartPtr->refs(), 1 );
Ptr second(smartPtr);
CXXTOOLS_UNIT_ASSERT_EQUALS( second->refs(), 2);
Ptr third;
third = second;
CXXTOOLS_UNIT_ASSERT_EQUALS( third->refs(), 3);
third = third;
CXXTOOLS_UNIT_ASSERT_EQUALS( third->refs(), 3);
}
CXXTOOLS_UNIT_ASSERT_EQUALS(Object::objectRefs, 0);
}
void SmartPtrTest::RefLinked()
{
Object* obj = new Object();
typedef cxxtools::SmartPtr<Object, cxxtools::RefLinked> Ptr;
{
Ptr smartPtr(obj);
Ptr second(smartPtr);
Ptr third;
Ptr fourth(third);
third = second;
}
CXXTOOLS_UNIT_ASSERT(Object::objectRefs == 0);
}
<commit_msg>add test for smart pointer with atomic counter<commit_after>/*
* Copyright (C) 2006 by Tommi Maekitalo
* Copyright (C) 2006 by Marc Boris Duerner
* Copyright (C) 2006 by Stefan Bueder
*
* 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.
*
* As a special exception, you may use this file as part of a free
* software library without restriction. Specifically, if other files
* instantiate templates or use macros or inline functions from this
* file, or you compile this file and link it with other files to
* produce an executable, this file does not by itself cause the
* resulting executable to be covered by the GNU General Public
* License. This exception does not however invalidate any other
* reasons why the executable file might be covered by the GNU Library
* General Public License.
*
* 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 "cxxtools/smartptr.h"
#include "cxxtools/refcounted.h"
#include "cxxtools/unit/assertion.h"
#include "cxxtools/unit/testsuite.h"
#include "cxxtools/unit/registertest.h"
class Object : public cxxtools::RefCounted
{
public:
Object()
{ ++objectRefs; }
~Object()
{ --objectRefs; }
static std::size_t objectRefs;
};
std::size_t Object::objectRefs = 0;
class AtomicObject : public cxxtools::AtomicRefCounted
{
public:
AtomicObject()
{ ++objectRefs; }
~AtomicObject()
{ --objectRefs; }
static std::size_t objectRefs;
};
std::size_t AtomicObject::objectRefs = 0;
class SmartPtrTest : public cxxtools::unit::TestSuite
{
public:
SmartPtrTest()
: cxxtools::unit::TestSuite( "SmartPtr" )
{
registerMethod( "RefCounted", *this, &SmartPtrTest::RefCounted );
registerMethod( "InternalRefCounted", *this, &SmartPtrTest::InternalRefCounted );
registerMethod( "AtomicInternalRefCounted", *this, &SmartPtrTest::AtomicInternalRefCounted );
registerMethod( "RefLinked", *this, &SmartPtrTest::RefLinked );
}
public:
void setUp();
protected:
void RefCounted();
void InternalRefCounted();
void AtomicInternalRefCounted();
void RefLinked();
};
cxxtools::unit::RegisterTest<SmartPtrTest> register_SmartPtrTest;
void SmartPtrTest::setUp()
{
Object::objectRefs = 0;
AtomicObject::objectRefs = 0;
}
void SmartPtrTest::RefCounted()
{
Object* obj = new Object();
typedef cxxtools::SmartPtr<Object, cxxtools::ExternalRefCounted> Ptr;
{
Ptr smartPtr(obj);
CXXTOOLS_UNIT_ASSERT_EQUALS( smartPtr.refs(), 1 );
Ptr second(smartPtr);
CXXTOOLS_UNIT_ASSERT_EQUALS( second.refs(), 2);
Ptr third;
third = second;
CXXTOOLS_UNIT_ASSERT_EQUALS( third.refs(), 3);
third = third;
CXXTOOLS_UNIT_ASSERT_EQUALS( third.refs(), 3);
}
CXXTOOLS_UNIT_ASSERT_EQUALS(Object::objectRefs, 0);
}
void SmartPtrTest::InternalRefCounted()
{
Object* obj = new Object();
typedef cxxtools::SmartPtr<Object, cxxtools::InternalRefCounted> Ptr;
{
Ptr smartPtr(obj);
CXXTOOLS_UNIT_ASSERT_EQUALS( smartPtr->refs(), 1 );
Ptr second(smartPtr);
CXXTOOLS_UNIT_ASSERT_EQUALS( second->refs(), 2);
Ptr third;
third = second;
CXXTOOLS_UNIT_ASSERT_EQUALS( third->refs(), 3);
third = third;
CXXTOOLS_UNIT_ASSERT_EQUALS( third->refs(), 3);
}
CXXTOOLS_UNIT_ASSERT_EQUALS(Object::objectRefs, 0);
}
void SmartPtrTest::AtomicInternalRefCounted()
{
AtomicObject* obj = new AtomicObject();
typedef cxxtools::SmartPtr<AtomicObject, cxxtools::InternalRefCounted> Ptr;
{
Ptr smartPtr(obj);
CXXTOOLS_UNIT_ASSERT_EQUALS( smartPtr->refs(), 1 );
Ptr second(smartPtr);
CXXTOOLS_UNIT_ASSERT_EQUALS( second->refs(), 2);
Ptr third;
third = second;
CXXTOOLS_UNIT_ASSERT_EQUALS( third->refs(), 3);
third = third;
CXXTOOLS_UNIT_ASSERT_EQUALS( third->refs(), 3);
}
CXXTOOLS_UNIT_ASSERT_EQUALS(AtomicObject::objectRefs, 0);
}
void SmartPtrTest::RefLinked()
{
Object* obj = new Object();
typedef cxxtools::SmartPtr<Object, cxxtools::RefLinked> Ptr;
{
Ptr smartPtr(obj);
Ptr second(smartPtr);
Ptr third;
Ptr fourth(third);
third = second;
}
CXXTOOLS_UNIT_ASSERT(Object::objectRefs == 0);
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2014 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 "genericproject.h"
#include "genericbuildconfiguration.h"
#include "genericmakestep.h"
#include "genericprojectconstants.h"
#include <coreplugin/documentmanager.h>
#include <coreplugin/icontext.h>
#include <coreplugin/icore.h>
#include <coreplugin/mimedatabase.h>
#include <cpptools/cpptoolsconstants.h>
#include <cpptools/cppmodelmanagerinterface.h>
#include <extensionsystem/pluginmanager.h>
#include <projectexplorer/abi.h>
#include <projectexplorer/buildsteplist.h>
#include <projectexplorer/headerpath.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/kitmanager.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <qtsupport/customexecutablerunconfiguration.h>
#include <utils/fileutils.h>
#include <utils/qtcassert.h>
#include <QDir>
#include <QProcessEnvironment>
using namespace Core;
using namespace ProjectExplorer;
namespace GenericProjectManager {
namespace Internal {
////////////////////////////////////////////////////////////////////////////////////
//
// GenericProject
//
////////////////////////////////////////////////////////////////////////////////////
GenericProject::GenericProject(Manager *manager, const QString &fileName)
: m_manager(manager),
m_fileName(fileName)
{
setId(Constants::GENERICPROJECT_ID);
setProjectContext(Context(GenericProjectManager::Constants::PROJECTCONTEXT));
setProjectLanguages(Context(ProjectExplorer::Constants::LANG_CXX));
QFileInfo fileInfo(m_fileName);
QDir dir = fileInfo.dir();
m_projectName = fileInfo.completeBaseName();
m_filesFileName = QFileInfo(dir, m_projectName + QLatin1String(".files")).absoluteFilePath();
m_includesFileName = QFileInfo(dir, m_projectName + QLatin1String(".includes")).absoluteFilePath();
m_configFileName = QFileInfo(dir, m_projectName + QLatin1String(".config")).absoluteFilePath();
m_creatorIDocument = new GenericProjectFile(this, m_fileName, GenericProject::Everything);
m_filesIDocument = new GenericProjectFile(this, m_filesFileName, GenericProject::Files);
m_includesIDocument = new GenericProjectFile(this, m_includesFileName, GenericProject::Configuration);
m_configIDocument = new GenericProjectFile(this, m_configFileName, GenericProject::Configuration);
DocumentManager::addDocument(m_creatorIDocument);
DocumentManager::addDocument(m_filesIDocument);
DocumentManager::addDocument(m_includesIDocument);
DocumentManager::addDocument(m_configIDocument);
m_rootNode = new GenericProjectNode(this, m_creatorIDocument);
m_manager->registerProject(this);
}
GenericProject::~GenericProject()
{
m_codeModelFuture.cancel();
m_manager->unregisterProject(this);
delete m_rootNode;
}
QString GenericProject::filesFileName() const
{
return m_filesFileName;
}
QString GenericProject::includesFileName() const
{
return m_includesFileName;
}
QString GenericProject::configFileName() const
{
return m_configFileName;
}
static QStringList readLines(const QString &absoluteFileName)
{
QStringList lines;
QFile file(absoluteFileName);
if (file.open(QFile::ReadOnly)) {
QTextStream stream(&file);
forever {
QString line = stream.readLine();
if (line.isNull())
break;
lines.append(line);
}
}
return lines;
}
bool GenericProject::saveRawFileList(const QStringList &rawFileList)
{
// Make sure we can open the file for writing
Utils::FileSaver saver(filesFileName(), QIODevice::Text);
if (!saver.hasError()) {
QTextStream stream(saver.file());
foreach (const QString &filePath, rawFileList)
stream << filePath << QLatin1Char('\n');
saver.setResult(&stream);
}
if (!saver.finalize(ICore::mainWindow()))
return false;
refresh(GenericProject::Files);
return true;
}
bool GenericProject::addFiles(const QStringList &filePaths)
{
QStringList newList = m_rawFileList;
QDir baseDir(QFileInfo(m_fileName).dir());
foreach (const QString &filePath, filePaths)
newList.append(baseDir.relativeFilePath(filePath));
return saveRawFileList(newList);
}
bool GenericProject::removeFiles(const QStringList &filePaths)
{
QStringList newList = m_rawFileList;
foreach (const QString &filePath, filePaths) {
QHash<QString, QString>::iterator i = m_rawListEntries.find(filePath);
if (i != m_rawListEntries.end())
newList.removeOne(i.value());
}
return saveRawFileList(newList);
}
bool GenericProject::setFiles(const QStringList &filePaths)
{
QStringList newList;
QDir baseDir(QFileInfo(m_fileName).dir());
foreach (const QString &filePath, filePaths)
newList.append(baseDir.relativeFilePath(filePath));
return saveRawFileList(newList);
}
bool GenericProject::renameFile(const QString &filePath, const QString &newFilePath)
{
QStringList newList = m_rawFileList;
QHash<QString, QString>::iterator i = m_rawListEntries.find(filePath);
if (i != m_rawListEntries.end()) {
int index = newList.indexOf(i.value());
if (index != -1) {
QDir baseDir(QFileInfo(m_fileName).dir());
newList.replace(index, baseDir.relativeFilePath(newFilePath));
}
}
return saveRawFileList(newList);
}
void GenericProject::parseProject(RefreshOptions options)
{
if (options & Files) {
m_rawListEntries.clear();
m_rawFileList = readLines(filesFileName());
m_files = processEntries(m_rawFileList, &m_rawListEntries);
}
if (options & Configuration) {
m_projectIncludePaths = processEntries(readLines(includesFileName()));
// TODO: Possibly load some configuration from the project file
//QSettings projectInfo(m_fileName, QSettings::IniFormat);
}
if (options & Files)
emit fileListChanged();
}
void GenericProject::refresh(RefreshOptions options)
{
QSet<QString> oldFileList;
if (!(options & Configuration))
oldFileList = m_files.toSet();
parseProject(options);
if (options & Files)
m_rootNode->refresh(oldFileList);
CppTools::CppModelManagerInterface *modelManager =
CppTools::CppModelManagerInterface::instance();
if (modelManager) {
CppTools::CppModelManagerInterface::ProjectInfo pinfo = modelManager->projectInfo(this);
pinfo.clearProjectParts();
CppTools::ProjectPart::Ptr part(new CppTools::ProjectPart);
part->project = this;
part->displayName = displayName();
part->projectFile = projectFilePath().toString();
foreach (const QString &inc, projectIncludePaths())
part->headerPaths += CppTools::ProjectPart::HeaderPath(
inc, CppTools::ProjectPart::HeaderPath::IncludePath);
Kit *k = activeTarget() ? activeTarget()->kit() : KitManager::defaultKit();
if (ToolChain *tc = ToolChainKitInformation::toolChain(k)) {
QStringList cxxflags; // FIXME: Can we do better?
part->evaluateToolchain(tc, cxxflags, cxxflags,
SysRootKitInformation::sysRoot(k));
}
part->cxxVersion = CppTools::ProjectPart::CXX11; // assume C++11
part->projectConfigFile = configFileName();
// ### add _defines.
// Add any C/C++ files to be parsed
CppTools::ProjectFileAdder adder(part->files);
foreach (const QString &file, files())
adder.maybeAdd(file);
m_codeModelFuture.cancel();
pinfo.appendProjectPart(part);
setProjectLanguage(ProjectExplorer::Constants::LANG_CXX, !part->files.isEmpty());
m_codeModelFuture = modelManager->updateProjectInfo(pinfo);
}
}
/**
* Expands environment variables in the given \a string when they are written
* like $$(VARIABLE).
*/
static void expandEnvironmentVariables(const QProcessEnvironment &env, QString &string)
{
static QRegExp candidate(QLatin1String("\\$\\$\\((.+)\\)"));
int index = candidate.indexIn(string);
while (index != -1) {
const QString value = env.value(candidate.cap(1));
string.replace(index, candidate.matchedLength(), value);
index += value.length();
index = candidate.indexIn(string, index);
}
}
/**
* Expands environment variables and converts the path from relative to the
* project to an absolute path.
*
* The \a map variable is an optional argument that will map the returned
* absolute paths back to their original \a entries.
*/
QStringList GenericProject::processEntries(const QStringList &paths,
QHash<QString, QString> *map) const
{
const QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
const QDir projectDir(QFileInfo(m_fileName).dir());
QFileInfo fileInfo;
QStringList absolutePaths;
foreach (const QString &path, paths) {
QString trimmedPath = path.trimmed();
if (trimmedPath.isEmpty())
continue;
expandEnvironmentVariables(env, trimmedPath);
trimmedPath = Utils::FileName::fromUserInput(trimmedPath).toString();
fileInfo.setFile(projectDir, trimmedPath);
if (fileInfo.exists()) {
const QString absPath = fileInfo.absoluteFilePath();
absolutePaths.append(absPath);
if (map)
map->insert(absPath, trimmedPath);
}
}
absolutePaths.removeDuplicates();
return absolutePaths;
}
QStringList GenericProject::projectIncludePaths() const
{
return m_projectIncludePaths;
}
QStringList GenericProject::files() const
{
return m_files;
}
QString GenericProject::displayName() const
{
return m_projectName;
}
IDocument *GenericProject::document() const
{
return m_creatorIDocument;
}
IProjectManager *GenericProject::projectManager() const
{
return m_manager;
}
GenericProjectNode *GenericProject::rootProjectNode() const
{
return m_rootNode;
}
QStringList GenericProject::files(FilesMode fileMode) const
{
Q_UNUSED(fileMode)
return m_files;
}
QStringList GenericProject::buildTargets() const
{
QStringList targets;
targets.append(QLatin1String("all"));
targets.append(QLatin1String("clean"));
return targets;
}
bool GenericProject::fromMap(const QVariantMap &map)
{
if (!Project::fromMap(map))
return false;
Kit *defaultKit = KitManager::defaultKit();
if (!activeTarget() && defaultKit)
addTarget(createTarget(defaultKit));
// Sanity check: We need both a buildconfiguration and a runconfiguration!
QList<Target *> targetList = targets();
foreach (Target *t, targetList) {
if (!t->activeBuildConfiguration()) {
removeTarget(t);
continue;
}
if (!t->activeRunConfiguration())
t->addRunConfiguration(new QtSupport::CustomExecutableRunConfiguration(t));
}
refresh(Everything);
return true;
}
////////////////////////////////////////////////////////////////////////////////////
//
// GenericProjectFile
//
////////////////////////////////////////////////////////////////////////////////////
GenericProjectFile::GenericProjectFile(GenericProject *parent, QString fileName, GenericProject::RefreshOptions options)
: IDocument(parent),
m_project(parent),
m_options(options)
{
setId("Generic.ProjectFile");
setMimeType(QLatin1String(Constants::GENERICMIMETYPE));
setFilePath(fileName);
}
bool GenericProjectFile::save(QString *, const QString &, bool)
{
return false;
}
QString GenericProjectFile::defaultPath() const
{
return QString();
}
QString GenericProjectFile::suggestedFileName() const
{
return QString();
}
bool GenericProjectFile::isModified() const
{
return false;
}
bool GenericProjectFile::isSaveAsAllowed() const
{
return false;
}
IDocument::ReloadBehavior GenericProjectFile::reloadBehavior(ChangeTrigger state, ChangeType type) const
{
Q_UNUSED(state)
Q_UNUSED(type)
return BehaviorSilent;
}
bool GenericProjectFile::reload(QString *errorString, ReloadFlag flag, ChangeType type)
{
Q_UNUSED(errorString)
Q_UNUSED(flag)
if (type == TypePermissions)
return true;
m_project->refresh(m_options);
return true;
}
} // namespace Internal
} // namespace GenericProjectManager
<commit_msg>GenericProject: Changed the way C++11 is specified<commit_after>/****************************************************************************
**
** Copyright (C) 2014 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 "genericproject.h"
#include "genericbuildconfiguration.h"
#include "genericmakestep.h"
#include "genericprojectconstants.h"
#include <coreplugin/documentmanager.h>
#include <coreplugin/icontext.h>
#include <coreplugin/icore.h>
#include <coreplugin/mimedatabase.h>
#include <cpptools/cpptoolsconstants.h>
#include <cpptools/cppmodelmanagerinterface.h>
#include <extensionsystem/pluginmanager.h>
#include <projectexplorer/abi.h>
#include <projectexplorer/buildsteplist.h>
#include <projectexplorer/headerpath.h>
#include <projectexplorer/kitinformation.h>
#include <projectexplorer/kitmanager.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <qtsupport/customexecutablerunconfiguration.h>
#include <utils/fileutils.h>
#include <utils/qtcassert.h>
#include <QDir>
#include <QProcessEnvironment>
using namespace Core;
using namespace ProjectExplorer;
namespace GenericProjectManager {
namespace Internal {
////////////////////////////////////////////////////////////////////////////////////
//
// GenericProject
//
////////////////////////////////////////////////////////////////////////////////////
GenericProject::GenericProject(Manager *manager, const QString &fileName)
: m_manager(manager),
m_fileName(fileName)
{
setId(Constants::GENERICPROJECT_ID);
setProjectContext(Context(GenericProjectManager::Constants::PROJECTCONTEXT));
setProjectLanguages(Context(ProjectExplorer::Constants::LANG_CXX));
QFileInfo fileInfo(m_fileName);
QDir dir = fileInfo.dir();
m_projectName = fileInfo.completeBaseName();
m_filesFileName = QFileInfo(dir, m_projectName + QLatin1String(".files")).absoluteFilePath();
m_includesFileName = QFileInfo(dir, m_projectName + QLatin1String(".includes")).absoluteFilePath();
m_configFileName = QFileInfo(dir, m_projectName + QLatin1String(".config")).absoluteFilePath();
m_creatorIDocument = new GenericProjectFile(this, m_fileName, GenericProject::Everything);
m_filesIDocument = new GenericProjectFile(this, m_filesFileName, GenericProject::Files);
m_includesIDocument = new GenericProjectFile(this, m_includesFileName, GenericProject::Configuration);
m_configIDocument = new GenericProjectFile(this, m_configFileName, GenericProject::Configuration);
DocumentManager::addDocument(m_creatorIDocument);
DocumentManager::addDocument(m_filesIDocument);
DocumentManager::addDocument(m_includesIDocument);
DocumentManager::addDocument(m_configIDocument);
m_rootNode = new GenericProjectNode(this, m_creatorIDocument);
m_manager->registerProject(this);
}
GenericProject::~GenericProject()
{
m_codeModelFuture.cancel();
m_manager->unregisterProject(this);
delete m_rootNode;
}
QString GenericProject::filesFileName() const
{
return m_filesFileName;
}
QString GenericProject::includesFileName() const
{
return m_includesFileName;
}
QString GenericProject::configFileName() const
{
return m_configFileName;
}
static QStringList readLines(const QString &absoluteFileName)
{
QStringList lines;
QFile file(absoluteFileName);
if (file.open(QFile::ReadOnly)) {
QTextStream stream(&file);
forever {
QString line = stream.readLine();
if (line.isNull())
break;
lines.append(line);
}
}
return lines;
}
bool GenericProject::saveRawFileList(const QStringList &rawFileList)
{
// Make sure we can open the file for writing
Utils::FileSaver saver(filesFileName(), QIODevice::Text);
if (!saver.hasError()) {
QTextStream stream(saver.file());
foreach (const QString &filePath, rawFileList)
stream << filePath << QLatin1Char('\n');
saver.setResult(&stream);
}
if (!saver.finalize(ICore::mainWindow()))
return false;
refresh(GenericProject::Files);
return true;
}
bool GenericProject::addFiles(const QStringList &filePaths)
{
QStringList newList = m_rawFileList;
QDir baseDir(QFileInfo(m_fileName).dir());
foreach (const QString &filePath, filePaths)
newList.append(baseDir.relativeFilePath(filePath));
return saveRawFileList(newList);
}
bool GenericProject::removeFiles(const QStringList &filePaths)
{
QStringList newList = m_rawFileList;
foreach (const QString &filePath, filePaths) {
QHash<QString, QString>::iterator i = m_rawListEntries.find(filePath);
if (i != m_rawListEntries.end())
newList.removeOne(i.value());
}
return saveRawFileList(newList);
}
bool GenericProject::setFiles(const QStringList &filePaths)
{
QStringList newList;
QDir baseDir(QFileInfo(m_fileName).dir());
foreach (const QString &filePath, filePaths)
newList.append(baseDir.relativeFilePath(filePath));
return saveRawFileList(newList);
}
bool GenericProject::renameFile(const QString &filePath, const QString &newFilePath)
{
QStringList newList = m_rawFileList;
QHash<QString, QString>::iterator i = m_rawListEntries.find(filePath);
if (i != m_rawListEntries.end()) {
int index = newList.indexOf(i.value());
if (index != -1) {
QDir baseDir(QFileInfo(m_fileName).dir());
newList.replace(index, baseDir.relativeFilePath(newFilePath));
}
}
return saveRawFileList(newList);
}
void GenericProject::parseProject(RefreshOptions options)
{
if (options & Files) {
m_rawListEntries.clear();
m_rawFileList = readLines(filesFileName());
m_files = processEntries(m_rawFileList, &m_rawListEntries);
}
if (options & Configuration) {
m_projectIncludePaths = processEntries(readLines(includesFileName()));
// TODO: Possibly load some configuration from the project file
//QSettings projectInfo(m_fileName, QSettings::IniFormat);
}
if (options & Files)
emit fileListChanged();
}
void GenericProject::refresh(RefreshOptions options)
{
QSet<QString> oldFileList;
if (!(options & Configuration))
oldFileList = m_files.toSet();
parseProject(options);
if (options & Files)
m_rootNode->refresh(oldFileList);
CppTools::CppModelManagerInterface *modelManager =
CppTools::CppModelManagerInterface::instance();
if (modelManager) {
CppTools::CppModelManagerInterface::ProjectInfo pinfo = modelManager->projectInfo(this);
pinfo.clearProjectParts();
CppTools::ProjectPart::Ptr part(new CppTools::ProjectPart);
part->project = this;
part->displayName = displayName();
part->projectFile = projectFilePath().toString();
foreach (const QString &inc, projectIncludePaths())
part->headerPaths += CppTools::ProjectPart::HeaderPath(
inc, CppTools::ProjectPart::HeaderPath::IncludePath);
Kit *k = activeTarget() ? activeTarget()->kit() : KitManager::defaultKit();
if (ToolChain *tc = ToolChainKitInformation::toolChain(k)) {
QStringList cflags;
QStringList cxxflags;
cxxflags << QLatin1String("-std=c++11");
part->evaluateToolchain(tc, cxxflags, cflags,
SysRootKitInformation::sysRoot(k));
}
part->projectConfigFile = configFileName();
// ### add _defines.
// Add any C/C++ files to be parsed
CppTools::ProjectFileAdder adder(part->files);
foreach (const QString &file, files())
adder.maybeAdd(file);
m_codeModelFuture.cancel();
pinfo.appendProjectPart(part);
setProjectLanguage(ProjectExplorer::Constants::LANG_CXX, !part->files.isEmpty());
m_codeModelFuture = modelManager->updateProjectInfo(pinfo);
}
}
/**
* Expands environment variables in the given \a string when they are written
* like $$(VARIABLE).
*/
static void expandEnvironmentVariables(const QProcessEnvironment &env, QString &string)
{
static QRegExp candidate(QLatin1String("\\$\\$\\((.+)\\)"));
int index = candidate.indexIn(string);
while (index != -1) {
const QString value = env.value(candidate.cap(1));
string.replace(index, candidate.matchedLength(), value);
index += value.length();
index = candidate.indexIn(string, index);
}
}
/**
* Expands environment variables and converts the path from relative to the
* project to an absolute path.
*
* The \a map variable is an optional argument that will map the returned
* absolute paths back to their original \a entries.
*/
QStringList GenericProject::processEntries(const QStringList &paths,
QHash<QString, QString> *map) const
{
const QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
const QDir projectDir(QFileInfo(m_fileName).dir());
QFileInfo fileInfo;
QStringList absolutePaths;
foreach (const QString &path, paths) {
QString trimmedPath = path.trimmed();
if (trimmedPath.isEmpty())
continue;
expandEnvironmentVariables(env, trimmedPath);
trimmedPath = Utils::FileName::fromUserInput(trimmedPath).toString();
fileInfo.setFile(projectDir, trimmedPath);
if (fileInfo.exists()) {
const QString absPath = fileInfo.absoluteFilePath();
absolutePaths.append(absPath);
if (map)
map->insert(absPath, trimmedPath);
}
}
absolutePaths.removeDuplicates();
return absolutePaths;
}
QStringList GenericProject::projectIncludePaths() const
{
return m_projectIncludePaths;
}
QStringList GenericProject::files() const
{
return m_files;
}
QString GenericProject::displayName() const
{
return m_projectName;
}
IDocument *GenericProject::document() const
{
return m_creatorIDocument;
}
IProjectManager *GenericProject::projectManager() const
{
return m_manager;
}
GenericProjectNode *GenericProject::rootProjectNode() const
{
return m_rootNode;
}
QStringList GenericProject::files(FilesMode fileMode) const
{
Q_UNUSED(fileMode)
return m_files;
}
QStringList GenericProject::buildTargets() const
{
QStringList targets;
targets.append(QLatin1String("all"));
targets.append(QLatin1String("clean"));
return targets;
}
bool GenericProject::fromMap(const QVariantMap &map)
{
if (!Project::fromMap(map))
return false;
Kit *defaultKit = KitManager::defaultKit();
if (!activeTarget() && defaultKit)
addTarget(createTarget(defaultKit));
// Sanity check: We need both a buildconfiguration and a runconfiguration!
QList<Target *> targetList = targets();
foreach (Target *t, targetList) {
if (!t->activeBuildConfiguration()) {
removeTarget(t);
continue;
}
if (!t->activeRunConfiguration())
t->addRunConfiguration(new QtSupport::CustomExecutableRunConfiguration(t));
}
refresh(Everything);
return true;
}
////////////////////////////////////////////////////////////////////////////////////
//
// GenericProjectFile
//
////////////////////////////////////////////////////////////////////////////////////
GenericProjectFile::GenericProjectFile(GenericProject *parent, QString fileName, GenericProject::RefreshOptions options)
: IDocument(parent),
m_project(parent),
m_options(options)
{
setId("Generic.ProjectFile");
setMimeType(QLatin1String(Constants::GENERICMIMETYPE));
setFilePath(fileName);
}
bool GenericProjectFile::save(QString *, const QString &, bool)
{
return false;
}
QString GenericProjectFile::defaultPath() const
{
return QString();
}
QString GenericProjectFile::suggestedFileName() const
{
return QString();
}
bool GenericProjectFile::isModified() const
{
return false;
}
bool GenericProjectFile::isSaveAsAllowed() const
{
return false;
}
IDocument::ReloadBehavior GenericProjectFile::reloadBehavior(ChangeTrigger state, ChangeType type) const
{
Q_UNUSED(state)
Q_UNUSED(type)
return BehaviorSilent;
}
bool GenericProjectFile::reload(QString *errorString, ReloadFlag flag, ChangeType type)
{
Q_UNUSED(errorString)
Q_UNUSED(flag)
if (type == TypePermissions)
return true;
m_project->refresh(m_options);
return true;
}
} // namespace Internal
} // namespace GenericProjectManager
<|endoftext|> |
<commit_before>/*
Copyright (c) 2017, Lukas Holecek <[email protected]>
This file is part of CopyQ.
CopyQ is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
CopyQ is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with CopyQ. If not, see <http://www.gnu.org/licenses/>.
*/
#include "fakevimactions.h"
#include "fakevimhandler.h"
#include <QApplication>
#include <QFontMetrics>
#include <QMainWindow>
#include <QMessageBox>
#include <QPainter>
#include <QPlainTextEdit>
#include <QStatusBar>
#include <QTextBlock>
#include <QTextEdit>
#include <QTextStream>
#include <QTemporaryFile>
#define EDITOR(editor, call) \
if (QPlainTextEdit *ed = qobject_cast<QPlainTextEdit *>(editor)) { \
(ed->call); \
} else if (QTextEdit *ed = qobject_cast<QTextEdit *>(editor)) { \
(ed->call); \
}
using namespace FakeVim::Internal;
typedef QLatin1String _;
/**
* Simple editor widget.
* @tparam TextEdit QTextEdit or QPlainTextEdit as base class
*/
template <typename TextEdit>
class Editor : public TextEdit
{
public:
Editor(QWidget *parent = 0) : TextEdit(parent)
{
TextEdit::setCursorWidth(0);
}
void paintEvent(QPaintEvent *e)
{
TextEdit::paintEvent(e);
if ( !m_cursorRect.isNull() && e->rect().intersects(m_cursorRect) ) {
QRect rect = m_cursorRect;
m_cursorRect = QRect();
TextEdit::viewport()->update(rect);
}
// Draw text cursor.
QRect rect = TextEdit::cursorRect();
if ( e->rect().intersects(rect) ) {
QPainter painter(TextEdit::viewport());
if ( TextEdit::overwriteMode() ) {
QFontMetrics fm(TextEdit::font());
const int position = TextEdit::textCursor().position();
const QChar c = TextEdit::document()->characterAt(position);
rect.setWidth(fm.width(c));
painter.setPen(Qt::NoPen);
painter.setBrush(TextEdit::palette().color(QPalette::Base));
painter.setCompositionMode(QPainter::CompositionMode_Difference);
} else {
rect.setWidth(TextEdit::cursorWidth());
painter.setPen(TextEdit::palette().color(QPalette::Text));
}
painter.drawRect(rect);
m_cursorRect = rect;
}
}
private:
QRect m_cursorRect;
};
class Proxy : public QObject
{
Q_OBJECT
public:
Proxy(QWidget *widget, QMainWindow *mw, QObject *parent = 0)
: QObject(parent), m_widget(widget), m_mainWindow(mw)
{
}
void openFile(const QString &fileName)
{
emit handleInput(QString(_(":r %1<CR>")).arg(fileName));
m_fileName = fileName;
}
signals:
void handleInput(const QString &keys);
public slots:
void changeStatusData(const QString &info)
{
m_statusData = info;
updateStatusBar();
}
void highlightMatches(const QString &pattern)
{
QTextEdit *ed = qobject_cast<QTextEdit *>(m_widget);
if (!ed)
return;
QTextCursor cur = ed->textCursor();
QTextEdit::ExtraSelection selection;
selection.format.setBackground(Qt::yellow);
selection.format.setForeground(Qt::black);
// Highlight matches.
QTextDocument *doc = ed->document();
QRegExp re(pattern);
cur = doc->find(re);
m_searchSelection.clear();
int a = cur.position();
while ( !cur.isNull() ) {
if ( cur.hasSelection() ) {
selection.cursor = cur;
m_searchSelection.append(selection);
} else {
cur.movePosition(QTextCursor::NextCharacter);
}
cur = doc->find(re, cur);
int b = cur.position();
if (a == b) {
cur.movePosition(QTextCursor::NextCharacter);
cur = doc->find(re, cur);
b = cur.position();
if (a == b) break;
}
a = b;
}
updateExtraSelections();
}
void changeStatusMessage(const QString &contents, int cursorPos)
{
m_statusMessage = cursorPos == -1 ? contents
: contents.left(cursorPos) + QChar(10073) + contents.mid(cursorPos);
updateStatusBar();
}
void changeExtraInformation(const QString &info)
{
QMessageBox::information(m_widget, tr("Information"), info);
}
void updateStatusBar()
{
int slack = 80 - m_statusMessage.size() - m_statusData.size();
QString msg = m_statusMessage + QString(slack, QLatin1Char(' ')) + m_statusData;
m_mainWindow->statusBar()->showMessage(msg);
}
void handleExCommand(bool *handled, const ExCommand &cmd)
{
if ( wantSaveAndQuit(cmd) ) {
// :wq
if (save())
cancel();
} else if ( wantSave(cmd) ) {
save(); // :w
} else if ( wantQuit(cmd) ) {
if (cmd.hasBang)
invalidate(); // :q!
else
cancel(); // :q
} else {
*handled = false;
return;
}
*handled = true;
}
void requestSetBlockSelection(const QTextCursor &tc)
{
QTextEdit *ed = qobject_cast<QTextEdit *>(m_widget);
if (!ed)
return;
QPalette pal = ed->parentWidget() != NULL ? ed->parentWidget()->palette()
: QApplication::palette();
m_blockSelection.clear();
m_clearSelection.clear();
QTextCursor cur = tc;
QTextEdit::ExtraSelection selection;
selection.format.setBackground( pal.color(QPalette::Base) );
selection.format.setForeground( pal.color(QPalette::Text) );
selection.cursor = cur;
m_clearSelection.append(selection);
selection.format.setBackground( pal.color(QPalette::Highlight) );
selection.format.setForeground( pal.color(QPalette::HighlightedText) );
int from = cur.positionInBlock();
int to = cur.anchor() - cur.document()->findBlock(cur.anchor()).position();
const int min = qMin(cur.position(), cur.anchor());
const int max = qMax(cur.position(), cur.anchor());
for ( QTextBlock block = cur.document()->findBlock(min);
block.isValid() && block.position() < max; block = block.next() ) {
cur.setPosition( block.position() + qMin(from, block.length()) );
cur.setPosition( block.position() + qMin(to, block.length()), QTextCursor::KeepAnchor );
selection.cursor = cur;
m_blockSelection.append(selection);
}
disconnect( ed, &QTextEdit::selectionChanged,
this, &Proxy::updateBlockSelection );
ed->setTextCursor(tc);
connect( ed, &QTextEdit::selectionChanged,
this, &Proxy::updateBlockSelection );
QPalette pal2 = ed->palette();
pal2.setColor(QPalette::Highlight, Qt::transparent);
pal2.setColor(QPalette::HighlightedText, Qt::transparent);
ed->setPalette(pal2);
updateExtraSelections();
}
void requestDisableBlockSelection()
{
QTextEdit *ed = qobject_cast<QTextEdit *>(m_widget);
if (!ed)
return;
QPalette pal = ed->parentWidget() != NULL ? ed->parentWidget()->palette()
: QApplication::palette();
m_blockSelection.clear();
m_clearSelection.clear();
ed->setPalette(pal);
disconnect( ed, &QTextEdit::selectionChanged,
this, &Proxy::updateBlockSelection );
updateExtraSelections();
}
void updateBlockSelection()
{
QTextEdit *ed = qobject_cast<QTextEdit *>(m_widget);
if (!ed)
return;
requestSetBlockSelection(ed->textCursor());
}
void requestHasBlockSelection(bool *on)
{
*on = !m_blockSelection.isEmpty();
}
void indentRegion(int beginBlock, int endBlock, QChar typedChar)
{
QTextEdit *ed = qobject_cast<QTextEdit *>(m_widget);
if (!ed)
return;
const auto indentSize = theFakeVimSetting(ConfigShiftWidth)->value().toInt();
QTextDocument *doc = ed->document();
QTextBlock startBlock = doc->findBlockByNumber(beginBlock);
// Record line lenghts for mark adjustments
QVector<int> lineLengths(endBlock - beginBlock + 1);
QTextBlock block = startBlock;
for (int i = beginBlock; i <= endBlock; ++i) {
const auto line = block.text();
lineLengths[i - beginBlock] = line.length();
if (typedChar.unicode() == 0 && line.simplified().isEmpty()) {
// clear empty lines
QTextCursor cursor(block);
while (!cursor.atBlockEnd())
cursor.deleteChar();
} else {
const auto previousBlock = block.previous();
const auto previousLine = previousBlock.isValid() ? previousBlock.text() : QString();
int indent = firstNonSpace(previousLine);
if (typedChar == '}')
indent = std::max(0, indent - indentSize);
else if ( previousLine.endsWith("{") )
indent += indentSize;
const auto indentString = QString(" ").repeated(indent);
QTextCursor cursor(block);
cursor.beginEditBlock();
cursor.movePosition(QTextCursor::StartOfBlock);
cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, firstNonSpace(line));
cursor.removeSelectedText();
cursor.insertText(indentString);
cursor.endEditBlock();
}
block = block.next();
}
}
void checkForElectricCharacter(bool *result, QChar c)
{
*result = c == '{' || c == '}';
}
private:
static int firstNonSpace(const QString &text)
{
int indent = 0;
while ( indent < text.length() && text.at(indent) == ' ' )
++indent;
return indent;
}
void updateExtraSelections()
{
QTextEdit *ed = qobject_cast<QTextEdit *>(m_widget);
if (ed)
ed->setExtraSelections(m_clearSelection + m_searchSelection + m_blockSelection);
}
bool wantSaveAndQuit(const ExCommand &cmd)
{
return cmd.cmd == "wq";
}
bool wantSave(const ExCommand &cmd)
{
return cmd.matches("w", "write") || cmd.matches("wa", "wall");
}
bool wantQuit(const ExCommand &cmd)
{
return cmd.matches("q", "quit") || cmd.matches("qa", "qall");
}
bool save()
{
if (!hasChanges())
return true;
QTemporaryFile tmpFile;
if (!tmpFile.open()) {
QMessageBox::critical(m_widget, tr("FakeVim Error"),
tr("Cannot create temporary file: %1").arg(tmpFile.errorString()));
return false;
}
QTextStream ts(&tmpFile);
ts << content();
ts.flush();
QFile::remove(m_fileName);
if (!QFile::copy(tmpFile.fileName(), m_fileName)) {
QMessageBox::critical(m_widget, tr("FakeVim Error"),
tr("Cannot write to file \"%1\"").arg(m_fileName));
return false;
}
return true;
}
void cancel()
{
if (hasChanges()) {
QMessageBox::critical(m_widget, tr("FakeVim Warning"),
tr("File \"%1\" was changed").arg(m_fileName));
} else {
invalidate();
}
}
void invalidate()
{
QApplication::quit();
}
bool hasChanges()
{
if (m_fileName.isEmpty() && content().isEmpty())
return false;
QFile f(m_fileName);
if (!f.open(QIODevice::ReadOnly))
return true;
QTextStream ts(&f);
return content() != ts.readAll();
}
QTextDocument *document() const
{
QTextDocument *doc = NULL;
if (QPlainTextEdit *ed = qobject_cast<QPlainTextEdit *>(m_widget))
doc = ed->document();
else if (QTextEdit *ed = qobject_cast<QTextEdit *>(m_widget))
doc = ed->document();
return doc;
}
QString content() const
{
return document()->toPlainText();
}
QWidget *m_widget;
QMainWindow *m_mainWindow;
QString m_statusMessage;
QString m_statusData;
QString m_fileName;
QList<QTextEdit::ExtraSelection> m_searchSelection;
QList<QTextEdit::ExtraSelection> m_clearSelection;
QList<QTextEdit::ExtraSelection> m_blockSelection;
};
QWidget *createEditorWidget(bool usePlainTextEdit)
{
QWidget *editor = 0;
if (usePlainTextEdit) {
Editor<QPlainTextEdit> *w = new Editor<QPlainTextEdit>;
w->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
editor = w;
} else {
Editor<QTextEdit> *w = new Editor<QTextEdit>;
w->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
editor = w;
}
editor->setObjectName(_("Editor"));
editor->setFocus();
return editor;
}
void initHandler(FakeVimHandler *handler)
{
handler->handleCommand(_("set nopasskeys"));
handler->handleCommand(_("set nopasscontrolkey"));
// Set some Vim options.
handler->handleCommand(_("set expandtab"));
handler->handleCommand(_("set shiftwidth=8"));
handler->handleCommand(_("set tabstop=16"));
handler->handleCommand(_("set autoindent"));
handler->handleCommand(_("set smartindent"));
// Try to source file "fakevimrc" from current directory.
handler->handleCommand(_("source fakevimrc"));
handler->installEventFilter();
handler->setupWidget();
}
void initMainWindow(QMainWindow *mainWindow, QWidget *centralWidget, const QString &title)
{
mainWindow->setWindowTitle(QString(_("FakeVim (%1)")).arg(title));
mainWindow->setCentralWidget(centralWidget);
mainWindow->resize(600, 650);
mainWindow->move(0, 0);
mainWindow->show();
// Set monospace font for editor and status bar.
QFont font = QApplication::font();
font.setFamily(_("Monospace"));
centralWidget->setFont(font);
mainWindow->statusBar()->setFont(font);
}
void clearUndoRedo(QWidget *editor)
{
EDITOR(editor, setUndoRedoEnabled(false));
EDITOR(editor, setUndoRedoEnabled(true));
}
void connectSignals(
FakeVimHandler *handler, QMainWindow *mainWindow, QWidget *editor,
const QString &fileToEdit)
{
auto proxy = new Proxy(editor, mainWindow, handler);
QObject::connect(handler, &FakeVimHandler::commandBufferChanged,
proxy, &Proxy::changeStatusMessage);
QObject::connect(handler, &FakeVimHandler::extraInformationChanged,
proxy, &Proxy::changeExtraInformation);
QObject::connect(handler, &FakeVimHandler::statusDataChanged,
proxy, &Proxy::changeStatusData);
QObject::connect(handler, &FakeVimHandler::highlightMatches,
proxy, &Proxy::highlightMatches);
QObject::connect(handler, &FakeVimHandler::handleExCommandRequested,
proxy, &Proxy::handleExCommand);
QObject::connect(handler, &FakeVimHandler::requestSetBlockSelection,
proxy, &Proxy::requestSetBlockSelection);
QObject::connect(handler, &FakeVimHandler::requestDisableBlockSelection,
proxy, &Proxy::requestDisableBlockSelection);
QObject::connect(handler, &FakeVimHandler::requestHasBlockSelection,
proxy, &Proxy::requestHasBlockSelection);
QObject::connect(handler, &FakeVimHandler::indentRegion,
proxy, &Proxy::indentRegion);
QObject::connect(handler, &FakeVimHandler::checkForElectricCharacter,
proxy, &Proxy::checkForElectricCharacter);
QObject::connect(proxy, &Proxy::handleInput,
handler, [handler] (const QString &text) { handler->handleInput(text); });
if (!fileToEdit.isEmpty())
proxy->openFile(fileToEdit);
}
#include "editor.moc"
<commit_msg>Omit auto-sourcing configuration file<commit_after>/*
Copyright (c) 2017, Lukas Holecek <[email protected]>
This file is part of CopyQ.
CopyQ is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
CopyQ is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with CopyQ. If not, see <http://www.gnu.org/licenses/>.
*/
#include "fakevimactions.h"
#include "fakevimhandler.h"
#include <QApplication>
#include <QFontMetrics>
#include <QMainWindow>
#include <QMessageBox>
#include <QPainter>
#include <QPlainTextEdit>
#include <QStatusBar>
#include <QTextBlock>
#include <QTextEdit>
#include <QTextStream>
#include <QTemporaryFile>
#define EDITOR(editor, call) \
if (QPlainTextEdit *ed = qobject_cast<QPlainTextEdit *>(editor)) { \
(ed->call); \
} else if (QTextEdit *ed = qobject_cast<QTextEdit *>(editor)) { \
(ed->call); \
}
using namespace FakeVim::Internal;
typedef QLatin1String _;
/**
* Simple editor widget.
* @tparam TextEdit QTextEdit or QPlainTextEdit as base class
*/
template <typename TextEdit>
class Editor : public TextEdit
{
public:
Editor(QWidget *parent = 0) : TextEdit(parent)
{
TextEdit::setCursorWidth(0);
}
void paintEvent(QPaintEvent *e)
{
TextEdit::paintEvent(e);
if ( !m_cursorRect.isNull() && e->rect().intersects(m_cursorRect) ) {
QRect rect = m_cursorRect;
m_cursorRect = QRect();
TextEdit::viewport()->update(rect);
}
// Draw text cursor.
QRect rect = TextEdit::cursorRect();
if ( e->rect().intersects(rect) ) {
QPainter painter(TextEdit::viewport());
if ( TextEdit::overwriteMode() ) {
QFontMetrics fm(TextEdit::font());
const int position = TextEdit::textCursor().position();
const QChar c = TextEdit::document()->characterAt(position);
rect.setWidth(fm.width(c));
painter.setPen(Qt::NoPen);
painter.setBrush(TextEdit::palette().color(QPalette::Base));
painter.setCompositionMode(QPainter::CompositionMode_Difference);
} else {
rect.setWidth(TextEdit::cursorWidth());
painter.setPen(TextEdit::palette().color(QPalette::Text));
}
painter.drawRect(rect);
m_cursorRect = rect;
}
}
private:
QRect m_cursorRect;
};
class Proxy : public QObject
{
Q_OBJECT
public:
Proxy(QWidget *widget, QMainWindow *mw, QObject *parent = 0)
: QObject(parent), m_widget(widget), m_mainWindow(mw)
{
}
void openFile(const QString &fileName)
{
emit handleInput(QString(_(":r %1<CR>")).arg(fileName));
m_fileName = fileName;
}
signals:
void handleInput(const QString &keys);
public slots:
void changeStatusData(const QString &info)
{
m_statusData = info;
updateStatusBar();
}
void highlightMatches(const QString &pattern)
{
QTextEdit *ed = qobject_cast<QTextEdit *>(m_widget);
if (!ed)
return;
QTextCursor cur = ed->textCursor();
QTextEdit::ExtraSelection selection;
selection.format.setBackground(Qt::yellow);
selection.format.setForeground(Qt::black);
// Highlight matches.
QTextDocument *doc = ed->document();
QRegExp re(pattern);
cur = doc->find(re);
m_searchSelection.clear();
int a = cur.position();
while ( !cur.isNull() ) {
if ( cur.hasSelection() ) {
selection.cursor = cur;
m_searchSelection.append(selection);
} else {
cur.movePosition(QTextCursor::NextCharacter);
}
cur = doc->find(re, cur);
int b = cur.position();
if (a == b) {
cur.movePosition(QTextCursor::NextCharacter);
cur = doc->find(re, cur);
b = cur.position();
if (a == b) break;
}
a = b;
}
updateExtraSelections();
}
void changeStatusMessage(const QString &contents, int cursorPos)
{
m_statusMessage = cursorPos == -1 ? contents
: contents.left(cursorPos) + QChar(10073) + contents.mid(cursorPos);
updateStatusBar();
}
void changeExtraInformation(const QString &info)
{
QMessageBox::information(m_widget, tr("Information"), info);
}
void updateStatusBar()
{
int slack = 80 - m_statusMessage.size() - m_statusData.size();
QString msg = m_statusMessage + QString(slack, QLatin1Char(' ')) + m_statusData;
m_mainWindow->statusBar()->showMessage(msg);
}
void handleExCommand(bool *handled, const ExCommand &cmd)
{
if ( wantSaveAndQuit(cmd) ) {
// :wq
if (save())
cancel();
} else if ( wantSave(cmd) ) {
save(); // :w
} else if ( wantQuit(cmd) ) {
if (cmd.hasBang)
invalidate(); // :q!
else
cancel(); // :q
} else {
*handled = false;
return;
}
*handled = true;
}
void requestSetBlockSelection(const QTextCursor &tc)
{
QTextEdit *ed = qobject_cast<QTextEdit *>(m_widget);
if (!ed)
return;
QPalette pal = ed->parentWidget() != NULL ? ed->parentWidget()->palette()
: QApplication::palette();
m_blockSelection.clear();
m_clearSelection.clear();
QTextCursor cur = tc;
QTextEdit::ExtraSelection selection;
selection.format.setBackground( pal.color(QPalette::Base) );
selection.format.setForeground( pal.color(QPalette::Text) );
selection.cursor = cur;
m_clearSelection.append(selection);
selection.format.setBackground( pal.color(QPalette::Highlight) );
selection.format.setForeground( pal.color(QPalette::HighlightedText) );
int from = cur.positionInBlock();
int to = cur.anchor() - cur.document()->findBlock(cur.anchor()).position();
const int min = qMin(cur.position(), cur.anchor());
const int max = qMax(cur.position(), cur.anchor());
for ( QTextBlock block = cur.document()->findBlock(min);
block.isValid() && block.position() < max; block = block.next() ) {
cur.setPosition( block.position() + qMin(from, block.length()) );
cur.setPosition( block.position() + qMin(to, block.length()), QTextCursor::KeepAnchor );
selection.cursor = cur;
m_blockSelection.append(selection);
}
disconnect( ed, &QTextEdit::selectionChanged,
this, &Proxy::updateBlockSelection );
ed->setTextCursor(tc);
connect( ed, &QTextEdit::selectionChanged,
this, &Proxy::updateBlockSelection );
QPalette pal2 = ed->palette();
pal2.setColor(QPalette::Highlight, Qt::transparent);
pal2.setColor(QPalette::HighlightedText, Qt::transparent);
ed->setPalette(pal2);
updateExtraSelections();
}
void requestDisableBlockSelection()
{
QTextEdit *ed = qobject_cast<QTextEdit *>(m_widget);
if (!ed)
return;
QPalette pal = ed->parentWidget() != NULL ? ed->parentWidget()->palette()
: QApplication::palette();
m_blockSelection.clear();
m_clearSelection.clear();
ed->setPalette(pal);
disconnect( ed, &QTextEdit::selectionChanged,
this, &Proxy::updateBlockSelection );
updateExtraSelections();
}
void updateBlockSelection()
{
QTextEdit *ed = qobject_cast<QTextEdit *>(m_widget);
if (!ed)
return;
requestSetBlockSelection(ed->textCursor());
}
void requestHasBlockSelection(bool *on)
{
*on = !m_blockSelection.isEmpty();
}
void indentRegion(int beginBlock, int endBlock, QChar typedChar)
{
QTextEdit *ed = qobject_cast<QTextEdit *>(m_widget);
if (!ed)
return;
const auto indentSize = theFakeVimSetting(ConfigShiftWidth)->value().toInt();
QTextDocument *doc = ed->document();
QTextBlock startBlock = doc->findBlockByNumber(beginBlock);
// Record line lenghts for mark adjustments
QVector<int> lineLengths(endBlock - beginBlock + 1);
QTextBlock block = startBlock;
for (int i = beginBlock; i <= endBlock; ++i) {
const auto line = block.text();
lineLengths[i - beginBlock] = line.length();
if (typedChar.unicode() == 0 && line.simplified().isEmpty()) {
// clear empty lines
QTextCursor cursor(block);
while (!cursor.atBlockEnd())
cursor.deleteChar();
} else {
const auto previousBlock = block.previous();
const auto previousLine = previousBlock.isValid() ? previousBlock.text() : QString();
int indent = firstNonSpace(previousLine);
if (typedChar == '}')
indent = std::max(0, indent - indentSize);
else if ( previousLine.endsWith("{") )
indent += indentSize;
const auto indentString = QString(" ").repeated(indent);
QTextCursor cursor(block);
cursor.beginEditBlock();
cursor.movePosition(QTextCursor::StartOfBlock);
cursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor, firstNonSpace(line));
cursor.removeSelectedText();
cursor.insertText(indentString);
cursor.endEditBlock();
}
block = block.next();
}
}
void checkForElectricCharacter(bool *result, QChar c)
{
*result = c == '{' || c == '}';
}
private:
static int firstNonSpace(const QString &text)
{
int indent = 0;
while ( indent < text.length() && text.at(indent) == ' ' )
++indent;
return indent;
}
void updateExtraSelections()
{
QTextEdit *ed = qobject_cast<QTextEdit *>(m_widget);
if (ed)
ed->setExtraSelections(m_clearSelection + m_searchSelection + m_blockSelection);
}
bool wantSaveAndQuit(const ExCommand &cmd)
{
return cmd.cmd == "wq";
}
bool wantSave(const ExCommand &cmd)
{
return cmd.matches("w", "write") || cmd.matches("wa", "wall");
}
bool wantQuit(const ExCommand &cmd)
{
return cmd.matches("q", "quit") || cmd.matches("qa", "qall");
}
bool save()
{
if (!hasChanges())
return true;
QTemporaryFile tmpFile;
if (!tmpFile.open()) {
QMessageBox::critical(m_widget, tr("FakeVim Error"),
tr("Cannot create temporary file: %1").arg(tmpFile.errorString()));
return false;
}
QTextStream ts(&tmpFile);
ts << content();
ts.flush();
QFile::remove(m_fileName);
if (!QFile::copy(tmpFile.fileName(), m_fileName)) {
QMessageBox::critical(m_widget, tr("FakeVim Error"),
tr("Cannot write to file \"%1\"").arg(m_fileName));
return false;
}
return true;
}
void cancel()
{
if (hasChanges()) {
QMessageBox::critical(m_widget, tr("FakeVim Warning"),
tr("File \"%1\" was changed").arg(m_fileName));
} else {
invalidate();
}
}
void invalidate()
{
QApplication::quit();
}
bool hasChanges()
{
if (m_fileName.isEmpty() && content().isEmpty())
return false;
QFile f(m_fileName);
if (!f.open(QIODevice::ReadOnly))
return true;
QTextStream ts(&f);
return content() != ts.readAll();
}
QTextDocument *document() const
{
QTextDocument *doc = NULL;
if (QPlainTextEdit *ed = qobject_cast<QPlainTextEdit *>(m_widget))
doc = ed->document();
else if (QTextEdit *ed = qobject_cast<QTextEdit *>(m_widget))
doc = ed->document();
return doc;
}
QString content() const
{
return document()->toPlainText();
}
QWidget *m_widget;
QMainWindow *m_mainWindow;
QString m_statusMessage;
QString m_statusData;
QString m_fileName;
QList<QTextEdit::ExtraSelection> m_searchSelection;
QList<QTextEdit::ExtraSelection> m_clearSelection;
QList<QTextEdit::ExtraSelection> m_blockSelection;
};
QWidget *createEditorWidget(bool usePlainTextEdit)
{
QWidget *editor = 0;
if (usePlainTextEdit) {
Editor<QPlainTextEdit> *w = new Editor<QPlainTextEdit>;
w->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
editor = w;
} else {
Editor<QTextEdit> *w = new Editor<QTextEdit>;
w->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
editor = w;
}
editor->setObjectName(_("Editor"));
editor->setFocus();
return editor;
}
void initHandler(FakeVimHandler *handler)
{
handler->handleCommand(_("set nopasskeys"));
handler->handleCommand(_("set nopasscontrolkey"));
// Set some Vim options.
handler->handleCommand(_("set expandtab"));
handler->handleCommand(_("set shiftwidth=8"));
handler->handleCommand(_("set tabstop=16"));
handler->handleCommand(_("set autoindent"));
handler->handleCommand(_("set smartindent"));
handler->installEventFilter();
handler->setupWidget();
}
void initMainWindow(QMainWindow *mainWindow, QWidget *centralWidget, const QString &title)
{
mainWindow->setWindowTitle(QString(_("FakeVim (%1)")).arg(title));
mainWindow->setCentralWidget(centralWidget);
mainWindow->resize(600, 650);
mainWindow->move(0, 0);
mainWindow->show();
// Set monospace font for editor and status bar.
QFont font = QApplication::font();
font.setFamily(_("Monospace"));
centralWidget->setFont(font);
mainWindow->statusBar()->setFont(font);
}
void clearUndoRedo(QWidget *editor)
{
EDITOR(editor, setUndoRedoEnabled(false));
EDITOR(editor, setUndoRedoEnabled(true));
}
void connectSignals(
FakeVimHandler *handler, QMainWindow *mainWindow, QWidget *editor,
const QString &fileToEdit)
{
auto proxy = new Proxy(editor, mainWindow, handler);
QObject::connect(handler, &FakeVimHandler::commandBufferChanged,
proxy, &Proxy::changeStatusMessage);
QObject::connect(handler, &FakeVimHandler::extraInformationChanged,
proxy, &Proxy::changeExtraInformation);
QObject::connect(handler, &FakeVimHandler::statusDataChanged,
proxy, &Proxy::changeStatusData);
QObject::connect(handler, &FakeVimHandler::highlightMatches,
proxy, &Proxy::highlightMatches);
QObject::connect(handler, &FakeVimHandler::handleExCommandRequested,
proxy, &Proxy::handleExCommand);
QObject::connect(handler, &FakeVimHandler::requestSetBlockSelection,
proxy, &Proxy::requestSetBlockSelection);
QObject::connect(handler, &FakeVimHandler::requestDisableBlockSelection,
proxy, &Proxy::requestDisableBlockSelection);
QObject::connect(handler, &FakeVimHandler::requestHasBlockSelection,
proxy, &Proxy::requestHasBlockSelection);
QObject::connect(handler, &FakeVimHandler::indentRegion,
proxy, &Proxy::indentRegion);
QObject::connect(handler, &FakeVimHandler::checkForElectricCharacter,
proxy, &Proxy::checkForElectricCharacter);
QObject::connect(proxy, &Proxy::handleInput,
handler, [handler] (const QString &text) { handler->handleInput(text); });
if (!fileToEdit.isEmpty())
proxy->openFile(fileToEdit);
}
#include "editor.moc"
<|endoftext|> |
<commit_before>//____________________________________________________________________
//
// To make an event sample (of size 100) do
//
// shell> root
// root [0] .L pythiaExample.C
// root [1] makeEventSample(1000)
//
// To start the tree view on the generated tree, do
//
// shell> root
// root [0] .L pythiaExample.C
// root [1] showEventSample()
//
//
// The following session:
// shell> root
// root [0] .x pythiaExample.C(500)
// will execute makeEventSample(500) and showEventSample()
//
// Alternatively, you can compile this to a program
// and then generate 1000 events with
//
// ./pythiaExample 1000
//
// To use the program to start the viewer, do
//
// ./pythiaExample -1
//
// NOTE 1: To run this example, you must have a version of ROOT
// compiled with the Pythia6 version enabled and have Pythia6 installed.
// The statement gSystem->Load("$HOME/pythia6/libPythia6"); (see below)
// assumes that the directory containing the Pythia6 library
// is in the pythia6 subdirectory of your $HOME. Locations
// that can specify this, are:
//
// Root.DynamicPath resource in your ROOT configuration file
// (/etc/root/system.rootrc or ~/.rootrc).
// Runtime load paths set on the executable (Using GNU ld,
// specified with flag `-rpath').
// Dynamic loader search path as specified in the loaders
// configuration file (On GNU/Linux this file is
// etc/ld.so.conf).
// For Un*x: Any directory mentioned in LD_LIBRARY_PATH
// For Windows: Any directory mentioned in PATH
//
// NOTE 2: The example can also be run with ACLIC:
// root > gSystem->Load("libEG");
// root > gSystem->Load("$HOME/pythia6/libPythia6"); //change to your setup
// root > gSystem->Load("libEGPythia6");
// root > .x pythiaExample.C+
//
//
//____________________________________________________________________
//
// $Id: pythiaExample.C,v 1.4 2003/01/24 09:49:59 brun Exp $
// Author: Christian Holm Christensen <[email protected]>
// Update: 2002-08-16 16:40:27+0200
// Copyright: 2002 (C) Christian Holm Christensen
//
//
#ifndef __CINT__
#include "TApplication.h"
#include "TPythia6.h"
#include "TFile.h"
#include "TError.h"
#include "TTree.h"
#include "TClonesArray.h"
#include "TH1.h"
#include "TF1.h"
#include "TStyle.h"
#include "TLatex.h"
#include "TCanvas.h"
#include "Riostream.h"
#include <cstdlib>
using namespace std;
#endif
#define FILENAME "pythia.root"
#define TREENAME "tree"
#define BRANCHNAME "particles"
#define HISTNAME "ptSpectra"
#define PDGNUMBER 211
// This funtion just load the needed libraries if we're executing from
// an interactive session.
void loadLibraries()
{
#ifdef __CINT__
// Load the Event Generator abstraction library, Pythia 6
// library, and the Pythia 6 interface library.
gSystem->Load("libEG");
gSystem->Load("$HOME/pythia6/libPythia6"); //change to your setup
gSystem->Load("libEGPythia6");
#endif
}
// nEvents is how many events we want.
int makeEventSample(Int_t nEvents)
{
// Load needed libraries
loadLibraries();
// Create an instance of the Pythia event generator ...
TPythia6* pythia = new TPythia6;
// ... and initialise it to run p+p at sqrt(200) GeV in CMS
pythia->Initialize("cms", "p", "p", 200);
// Open an output file
TFile* file = TFile::Open(FILENAME, "RECREATE");
if (!file || !file->IsOpen()) {
Error("makeEventSample", "Couldn;t open file %s", FILENAME);
return 1;
}
// Make a tree in that file ...
TTree* tree = new TTree(TREENAME, "Pythia 6 tree");
// ... and register a the cache of pythia on a branch (It's a
// TClonesArray of TMCParticle objects. )
TClonesArray* particles = (TClonesArray*)pythia->GetListOfParticles();
tree->Branch(BRANCHNAME, &particles);
// Now we make some events
for (Int_t i = 0; i < nEvents; i++) {
// Show how far we got every 100'th event.
if (i % 100 == 0)
cout << "Event # " << i << endl;
// Make one event.
pythia->GenerateEvent();
// Maybe you want to have another branch with global event
// information. In that case, you should process that here.
// You can also filter out particles here if you want.
// Now we're ready to fill the tree, and the event is over.
tree->Fill();
}
// Show tree structure
tree->Print();
// After the run is over, we may want to do some summary plots:
TH1D* hist = new TH1D(HISTNAME, "p_{#perp} spectrum for #pi^{+}",
100, 0, 3);
hist->SetXTitle("p_{#perp}");
hist->SetYTitle("dN/dp_{#perp}");
char expression[64];
sprintf(expression,"sqrt(pow(%s.fPx,2)+pow(%s.fPy,2))>>%s",
BRANCHNAME, BRANCHNAME, HISTNAME);
char selection[64];
sprintf(selection,"%s.fKF==%d", BRANCHNAME, PDGNUMBER);
tree->Draw(expression,selection);
// Normalise to the number of events, and the bin sizes.
hist->Sumw2();
hist->Scale(3 / 100. / hist->Integral());
hist->Fit("expo", "QO+", "", .25, 1.75);
TF1* func = hist->GetFunction("expo");
func->SetParNames("A", "- 1 / T");
// and now we flush and close the file
file->Write();
file->Close();
return 0;
}
// Show the Pt spectra, and start the tree viewer.
int showEventSample()
{
// Load needed libraries
loadLibraries();
// Open the file
TFile* file = TFile::Open(FILENAME, "READ");
if (!file || !file->IsOpen()) {
Error("showEventSample", "Couldn;t open file %s", FILENAME);
return 1;
}
// Get the tree
TTree* tree = (TTree*)file->Get(TREENAME);
if (!tree) {
Error("showEventSample", "couldn't get TTree %s", TREENAME);
return 2;
}
// Start the viewer.
tree->StartViewer();
// Get the histogram
TH1D* hist = (TH1D*)file->Get(HISTNAME);
if (!hist) {
Error("showEventSample", "couldn't get TH1D %s", HISTNAME);
return 4;
}
// Draw the histogram in a canvas
gStyle->SetOptStat(1);
TCanvas* canvas = new TCanvas("canvas", "canvas");
canvas->SetLogy();
hist->Draw("e1");
TF1* func = hist->GetFunction("expo");
char expression[64];
sprintf(expression,"T #approx %5.1f", -1000 / func->GetParameter(1));
TLatex* latex = new TLatex(1.5, 1e-4, expression);
latex->SetTextSize(.1);
latex->SetTextColor(4);
latex->Draw();
return 0;
}
void pythiaExample(Int_t n=1000) {
makeEventSample(n);
showEventSample();
}
#ifndef __CINT__
int main(int argc, char** argv)
{
TApplication app("app", &argc, argv);
Int_t n = 100;
if (argc > 1)
n = strtol(argv[1], NULL, 0);
int retVal = 0;
if (n > 0)
retVal = makeEventSample(n);
else {
retVal = showEventSample();
app.Run();
}
return retVal;
}
#endif
//____________________________________________________________________
//
// EOF
//
<commit_msg>Add reference to LPGL.<commit_after>//____________________________________________________________________
//
// To make an event sample (of size 100) do
//
// shell> root
// root [0] .L pythiaExample.C
// root [1] makeEventSample(1000)
//
// To start the tree view on the generated tree, do
//
// shell> root
// root [0] .L pythiaExample.C
// root [1] showEventSample()
//
//
// The following session:
// shell> root
// root [0] .x pythiaExample.C(500)
// will execute makeEventSample(500) and showEventSample()
//
// Alternatively, you can compile this to a program
// and then generate 1000 events with
//
// ./pythiaExample 1000
//
// To use the program to start the viewer, do
//
// ./pythiaExample -1
//
// NOTE 1: To run this example, you must have a version of ROOT
// compiled with the Pythia6 version enabled and have Pythia6 installed.
// The statement gSystem->Load("$HOME/pythia6/libPythia6"); (see below)
// assumes that the directory containing the Pythia6 library
// is in the pythia6 subdirectory of your $HOME. Locations
// that can specify this, are:
//
// Root.DynamicPath resource in your ROOT configuration file
// (/etc/root/system.rootrc or ~/.rootrc).
// Runtime load paths set on the executable (Using GNU ld,
// specified with flag `-rpath').
// Dynamic loader search path as specified in the loaders
// configuration file (On GNU/Linux this file is
// etc/ld.so.conf).
// For Un*x: Any directory mentioned in LD_LIBRARY_PATH
// For Windows: Any directory mentioned in PATH
//
// NOTE 2: The example can also be run with ACLIC:
// root > gSystem->Load("libEG");
// root > gSystem->Load("$HOME/pythia6/libPythia6"); //change to your setup
// root > gSystem->Load("libEGPythia6");
// root > .x pythiaExample.C+
//
//
//____________________________________________________________________
//
// $Id: pythiaExample.C,v 1.5 2004/05/12 10:39:29 brun Exp $
// Author: Christian Holm Christensen <[email protected]>
// Update: 2002-08-16 16:40:27+0200
// Copyright: 2002 (C) Christian Holm Christensen
// Copyright (C) 2006, Rene Brun and Fons Rademakers.
// For the licensing terms see $ROOTSYS/LICENSE.
//
#ifndef __CINT__
#include "TApplication.h"
#include "TPythia6.h"
#include "TFile.h"
#include "TError.h"
#include "TTree.h"
#include "TClonesArray.h"
#include "TH1.h"
#include "TF1.h"
#include "TStyle.h"
#include "TLatex.h"
#include "TCanvas.h"
#include "Riostream.h"
#include <cstdlib>
using namespace std;
#endif
#define FILENAME "pythia.root"
#define TREENAME "tree"
#define BRANCHNAME "particles"
#define HISTNAME "ptSpectra"
#define PDGNUMBER 211
// This funtion just load the needed libraries if we're executing from
// an interactive session.
void loadLibraries()
{
#ifdef __CINT__
// Load the Event Generator abstraction library, Pythia 6
// library, and the Pythia 6 interface library.
gSystem->Load("libEG");
gSystem->Load("$HOME/pythia6/libPythia6"); //change to your setup
gSystem->Load("libEGPythia6");
#endif
}
// nEvents is how many events we want.
int makeEventSample(Int_t nEvents)
{
// Load needed libraries
loadLibraries();
// Create an instance of the Pythia event generator ...
TPythia6* pythia = new TPythia6;
// ... and initialise it to run p+p at sqrt(200) GeV in CMS
pythia->Initialize("cms", "p", "p", 200);
// Open an output file
TFile* file = TFile::Open(FILENAME, "RECREATE");
if (!file || !file->IsOpen()) {
Error("makeEventSample", "Couldn;t open file %s", FILENAME);
return 1;
}
// Make a tree in that file ...
TTree* tree = new TTree(TREENAME, "Pythia 6 tree");
// ... and register a the cache of pythia on a branch (It's a
// TClonesArray of TMCParticle objects. )
TClonesArray* particles = (TClonesArray*)pythia->GetListOfParticles();
tree->Branch(BRANCHNAME, &particles);
// Now we make some events
for (Int_t i = 0; i < nEvents; i++) {
// Show how far we got every 100'th event.
if (i % 100 == 0)
cout << "Event # " << i << endl;
// Make one event.
pythia->GenerateEvent();
// Maybe you want to have another branch with global event
// information. In that case, you should process that here.
// You can also filter out particles here if you want.
// Now we're ready to fill the tree, and the event is over.
tree->Fill();
}
// Show tree structure
tree->Print();
// After the run is over, we may want to do some summary plots:
TH1D* hist = new TH1D(HISTNAME, "p_{#perp} spectrum for #pi^{+}",
100, 0, 3);
hist->SetXTitle("p_{#perp}");
hist->SetYTitle("dN/dp_{#perp}");
char expression[64];
sprintf(expression,"sqrt(pow(%s.fPx,2)+pow(%s.fPy,2))>>%s",
BRANCHNAME, BRANCHNAME, HISTNAME);
char selection[64];
sprintf(selection,"%s.fKF==%d", BRANCHNAME, PDGNUMBER);
tree->Draw(expression,selection);
// Normalise to the number of events, and the bin sizes.
hist->Sumw2();
hist->Scale(3 / 100. / hist->Integral());
hist->Fit("expo", "QO+", "", .25, 1.75);
TF1* func = hist->GetFunction("expo");
func->SetParNames("A", "- 1 / T");
// and now we flush and close the file
file->Write();
file->Close();
return 0;
}
// Show the Pt spectra, and start the tree viewer.
int showEventSample()
{
// Load needed libraries
loadLibraries();
// Open the file
TFile* file = TFile::Open(FILENAME, "READ");
if (!file || !file->IsOpen()) {
Error("showEventSample", "Couldn;t open file %s", FILENAME);
return 1;
}
// Get the tree
TTree* tree = (TTree*)file->Get(TREENAME);
if (!tree) {
Error("showEventSample", "couldn't get TTree %s", TREENAME);
return 2;
}
// Start the viewer.
tree->StartViewer();
// Get the histogram
TH1D* hist = (TH1D*)file->Get(HISTNAME);
if (!hist) {
Error("showEventSample", "couldn't get TH1D %s", HISTNAME);
return 4;
}
// Draw the histogram in a canvas
gStyle->SetOptStat(1);
TCanvas* canvas = new TCanvas("canvas", "canvas");
canvas->SetLogy();
hist->Draw("e1");
TF1* func = hist->GetFunction("expo");
char expression[64];
sprintf(expression,"T #approx %5.1f", -1000 / func->GetParameter(1));
TLatex* latex = new TLatex(1.5, 1e-4, expression);
latex->SetTextSize(.1);
latex->SetTextColor(4);
latex->Draw();
return 0;
}
void pythiaExample(Int_t n=1000) {
makeEventSample(n);
showEventSample();
}
#ifndef __CINT__
int main(int argc, char** argv)
{
TApplication app("app", &argc, argv);
Int_t n = 100;
if (argc > 1)
n = strtol(argv[1], NULL, 0);
int retVal = 0;
if (n > 0)
retVal = makeEventSample(n);
else {
retVal = showEventSample();
app.Run();
}
return retVal;
}
#endif
//____________________________________________________________________
//
// EOF
//
<|endoftext|> |
<commit_before>//
// Created by Derek van Vliet on 2014-12-10.
// Copyright (c) 2014 Get Set Games Inc. All rights reserved.
//
#include "BlueprintReflectionPluginPrivatePCH.h"
#include "AssetRegistryModule.h"
UClass* UBlueprintReflectionFunctions::GetClassByNameImpl(FString Name) {
if (UClass* result = FindObject<UClass>(ANY_PACKAGE, *Name)) {
return result;
}
if (UObjectRedirector* RenamedClassRedirector = FindObject<UObjectRedirector>(ANY_PACKAGE, *Name)) {
return CastChecked<UClass>(RenamedClassRedirector->DestinationObject);
}
return nullptr;
}
UClass* UBlueprintReflectionFunctions::GetClassByName(FString Name) {
if (UClass *result = UBlueprintReflectionFunctions::GetClassByNameImpl(Name)) {
return result;
}
FString BlueprintName = FString::Printf(TEXT("%s_C"),*Name);
if (UClass *result = UBlueprintReflectionFunctions::GetClassByNameImpl(BlueprintName)) {
return result;
}
UE_LOG(LogBlueprintReflection, Log, TEXT("Could not find class in memory, searching asset registry for class: %s"), *Name);
FAssetRegistryModule& AssetRegistryModule = FModuleManager::LoadModuleChecked<FAssetRegistryModule>(FName("AssetRegistry"));
IAssetRegistry& AssetRegistry = AssetRegistryModule.Get();
TArray<FAssetData> AssetList;
FARFilter AssetFilter;
AssetFilter.ClassNames.Add(UBlueprint::StaticClass()->GetFName());
AssetRegistry.GetAssets(AssetFilter, AssetList);
for (auto Itr(AssetList.CreateIterator()); Itr; Itr++)
{
if (Itr->AssetName.ToString().Equals(Name)) {
if (UClass* result = LoadObject<UClass>(nullptr, *Itr->ObjectPath.ToString())) {
return result;
}
if (UClass *result = UBlueprintReflectionFunctions::GetClassByNameImpl(BlueprintName)) {
return result;
}
}
}
return nullptr;
}
UObject* UBlueprintReflectionFunctions::ConstructObjectFromClass(TSubclassOf<UObject> Class) {
if (Class) {
return StaticConstructObject(Class);
}
return nullptr;
}
UObject* UBlueprintReflectionFunctions::ConstructObjectFromClassName(FString Name) {
return UBlueprintReflectionFunctions::ConstructObjectFromClass(UBlueprintReflectionFunctions::GetClassByName(Name));
}<commit_msg>[4.8] using StaticConstructObject_Internal instead of deprecated StaticConstructObject<commit_after>//
// Created by Derek van Vliet on 2014-12-10.
// Copyright (c) 2014 Get Set Games Inc. All rights reserved.
//
#include "BlueprintReflectionPluginPrivatePCH.h"
#include "AssetRegistryModule.h"
UClass* UBlueprintReflectionFunctions::GetClassByNameImpl(FString Name) {
if (UClass* result = FindObject<UClass>(ANY_PACKAGE, *Name)) {
return result;
}
if (UObjectRedirector* RenamedClassRedirector = FindObject<UObjectRedirector>(ANY_PACKAGE, *Name)) {
return CastChecked<UClass>(RenamedClassRedirector->DestinationObject);
}
return nullptr;
}
UClass* UBlueprintReflectionFunctions::GetClassByName(FString Name) {
if (UClass *result = UBlueprintReflectionFunctions::GetClassByNameImpl(Name)) {
return result;
}
FString BlueprintName = FString::Printf(TEXT("%s_C"),*Name);
if (UClass *result = UBlueprintReflectionFunctions::GetClassByNameImpl(BlueprintName)) {
return result;
}
UE_LOG(LogBlueprintReflection, Log, TEXT("Could not find class in memory, searching asset registry for class: %s"), *Name);
FAssetRegistryModule& AssetRegistryModule = FModuleManager::LoadModuleChecked<FAssetRegistryModule>(FName("AssetRegistry"));
IAssetRegistry& AssetRegistry = AssetRegistryModule.Get();
TArray<FAssetData> AssetList;
FARFilter AssetFilter;
AssetFilter.ClassNames.Add(UBlueprint::StaticClass()->GetFName());
AssetRegistry.GetAssets(AssetFilter, AssetList);
for (auto Itr(AssetList.CreateIterator()); Itr; Itr++)
{
if (Itr->AssetName.ToString().Equals(Name)) {
if (UClass* result = LoadObject<UClass>(nullptr, *Itr->ObjectPath.ToString())) {
return result;
}
if (UClass *result = UBlueprintReflectionFunctions::GetClassByNameImpl(BlueprintName)) {
return result;
}
}
}
return nullptr;
}
UObject* UBlueprintReflectionFunctions::ConstructObjectFromClass(TSubclassOf<UObject> Class) {
if (Class) {
return StaticConstructObject_Internal(Class);
}
return nullptr;
}
UObject* UBlueprintReflectionFunctions::ConstructObjectFromClassName(FString Name) {
return UBlueprintReflectionFunctions::ConstructObjectFromClass(UBlueprintReflectionFunctions::GetClassByName(Name));
}<|endoftext|> |
<commit_before>// Copyright 2016 Chris Conway (Koderz). All Rights Reserved.
#include "RuntimeMeshComponentEditorPrivatePCH.h"
#include "RuntimeMeshComponentDetails.h"
#include "DlgPickAssetPath.h"
#include "AssetToolsModule.h"
#include "AssetRegistryModule.h"
#define LOCTEXT_NAMESPACE "RuntimeMeshComponentDetails"
TSharedRef<IDetailCustomization> FRuntimeMeshComponentDetails::MakeInstance()
{
return MakeShareable(new FRuntimeMeshComponentDetails);
}
void FRuntimeMeshComponentDetails::CustomizeDetails( IDetailLayoutBuilder& DetailBuilder )
{
IDetailCategoryBuilder& RuntimeMeshCategory = DetailBuilder.EditCategory("RuntimeMesh");
const FText ConvertToStaticMeshText = LOCTEXT("ConvertToStaticMesh", "Create StaticMesh");
// Cache set of selected things
SelectedObjectsList = DetailBuilder.GetDetailsView().GetSelectedObjects();
RuntimeMeshCategory.AddCustomRow(ConvertToStaticMeshText, false)
.NameContent()
[
SNullWidget::NullWidget
]
.ValueContent()
.VAlign(VAlign_Center)
.MaxDesiredWidth(250)
[
SNew(SButton)
.VAlign(VAlign_Center)
.ToolTipText(LOCTEXT("ConvertToStaticMeshTooltip", "Create a new StaticMesh asset using current geometry from this RuntimeMeshComponent. Does not modify instance."))
.OnClicked(this, &FRuntimeMeshComponentDetails::ClickedOnConvertToStaticMesh)
.IsEnabled(this, &FRuntimeMeshComponentDetails::ConvertToStaticMeshEnabled)
.Content()
[
SNew(STextBlock)
.Text(ConvertToStaticMeshText)
]
];
}
URuntimeMeshComponent* FRuntimeMeshComponentDetails::GetFirstSelectedRuntimeMeshComp() const
{
// Find first selected valid RuntimeMeshComp
URuntimeMeshComponent* RuntimeMeshComp = nullptr;
for (const TWeakObjectPtr<UObject>& Object : SelectedObjectsList)
{
URuntimeMeshComponent* TestRuntimeComp = Cast<URuntimeMeshComponent>(Object.Get());
// See if this one is good
if (TestRuntimeComp != nullptr && !TestRuntimeComp->IsTemplate())
{
RuntimeMeshComp = TestRuntimeComp;
break;
}
}
return RuntimeMeshComp;
}
bool FRuntimeMeshComponentDetails::ConvertToStaticMeshEnabled() const
{
return GetFirstSelectedRuntimeMeshComp() != nullptr;
}
FReply FRuntimeMeshComponentDetails::ClickedOnConvertToStaticMesh()
{
// Find first selected RuntimeMeshComp
URuntimeMeshComponent* RuntimeMeshComp = GetFirstSelectedRuntimeMeshComp();
if (RuntimeMeshComp != nullptr)
{
FString NewNameSuggestion = FString(TEXT("RuntimeMeshComp"));
FString PackageName = FString(TEXT("/Game/Meshes/")) + NewNameSuggestion;
FString Name;
FAssetToolsModule& AssetToolsModule = FModuleManager::LoadModuleChecked<FAssetToolsModule>("AssetTools");
AssetToolsModule.Get().CreateUniqueAssetName(PackageName, TEXT(""), PackageName, Name);
TSharedPtr<SDlgPickAssetPath> PickAssetPathWidget =
SNew(SDlgPickAssetPath)
.Title(LOCTEXT("ConvertToStaticMeshPickName", "Choose New StaticMesh Location"))
.DefaultAssetPath(FText::FromString(PackageName));
if (PickAssetPathWidget->ShowModal() == EAppReturnType::Ok)
{
// Get the full name of where we want to create the physics asset.
FString UserPackageName = PickAssetPathWidget->GetFullAssetPath().ToString();
FName MeshName(*FPackageName::GetLongPackageAssetName(UserPackageName));
// Check if the user inputed a valid asset name, if they did not, give it the generated default name
if (MeshName == NAME_None)
{
// Use the defaults that were already generated.
UserPackageName = PackageName;
MeshName = *Name;
}
// Raw mesh data we are filling in
FRawMesh RawMesh;
// Unique Materials to apply to new mesh
#if ENGINE_MAJOR_VERSION == 4 && ENGINE_MINOR_VERSION >= 14
TArray<FStaticMaterial> Materials;
#else
TArray<UMaterialInterface*> Materials;
#endif
bool bUseHighPrecisionTangents = false;
bool bUseFullPrecisionUVs = false;
const int32 NumSections = RuntimeMeshComp->GetNumSections();
int32 VertexBase = 0;
for (int32 SectionIdx = 0; SectionIdx < NumSections; SectionIdx++)
{
const IRuntimeMeshVerticesBuilder* Vertices;
const FRuntimeMeshIndicesBuilder* Indices;
RuntimeMeshComp->GetSectionMesh(SectionIdx, Vertices, Indices);
if (Vertices->HasHighPrecisionNormals())
{
bUseHighPrecisionTangents = true;
}
if (Vertices->HasHighPrecisionUVs())
{
bUseFullPrecisionUVs = true;
}
// Copy verts
Vertices->Seek(-1);
while (Vertices->MoveNext() < Vertices->Length())
{
RawMesh.VertexPositions.Add(Vertices->GetPosition());
}
// Copy 'wedge' info
Indices->Seek(0);
while (Indices->HasRemaining())
{
int32 Index = Indices->ReadOne();
RawMesh.WedgeIndices.Add(Index + VertexBase);
Vertices->Seek(Index);
FVector TangentX = Vertices->GetTangent();
FVector TangentZ = Vertices->GetNormal();
FVector TangentY = (TangentX ^ TangentZ).GetSafeNormal() * Vertices->GetNormal().W;
RawMesh.WedgeTangentX.Add(TangentX);
RawMesh.WedgeTangentY.Add(TangentY);
RawMesh.WedgeTangentZ.Add(TangentZ);
for (int UVIndex = 0; UVIndex < 8; UVIndex++)
{
if (!Vertices->HasUVComponent(UVIndex))
{
break;
}
RawMesh.WedgeTexCoords[UVIndex].Add(Vertices->GetUV(UVIndex));
}
RawMesh.WedgeColors.Add(Vertices->GetColor());
}
// Find a material index for this section.
UMaterialInterface* Material = RuntimeMeshComp->GetMaterial(SectionIdx);
#if ENGINE_MAJOR_VERSION == 4 && ENGINE_MINOR_VERSION >= 14
int32 MaterialIndex = Materials.AddUnique(FStaticMaterial(Material));
#else
int32 MaterialIndex = Materials.AddUnique(Material);
#endif
// copy face info
int32 NumTris = Indices->Length() / 3;
for (int32 TriIdx=0; TriIdx < NumTris; TriIdx++)
{
// Set the face material
RawMesh.FaceMaterialIndices.Add(MaterialIndex);
RawMesh.FaceSmoothingMasks.Add(0); // Assume this is ignored as bRecomputeNormals is false
}
// Update offset for creating one big index/vertex buffer
VertexBase += Vertices->Length();
}
// If we got some valid data.
if (RawMesh.VertexPositions.Num() > 3 && RawMesh.WedgeIndices.Num() > 3)
{
// Then find/create it.
UPackage* Package = CreatePackage(NULL, *UserPackageName);
check(Package);
// Create StaticMesh object
UStaticMesh* StaticMesh = NewObject<UStaticMesh>(Package, MeshName, RF_Public | RF_Standalone);
StaticMesh->InitResources();
StaticMesh->LightingGuid = FGuid::NewGuid();
// Add source to new StaticMesh
FStaticMeshSourceModel* SrcModel = new (StaticMesh->SourceModels) FStaticMeshSourceModel();
SrcModel->BuildSettings.bRecomputeNormals = false;
SrcModel->BuildSettings.bRecomputeTangents = false;
SrcModel->BuildSettings.bRemoveDegenerates = false;
SrcModel->BuildSettings.bUseHighPrecisionTangentBasis = bUseHighPrecisionTangents;
SrcModel->BuildSettings.bUseFullPrecisionUVs = bUseFullPrecisionUVs;
SrcModel->BuildSettings.bGenerateLightmapUVs = true;
SrcModel->BuildSettings.SrcLightmapIndex = 0;
SrcModel->BuildSettings.DstLightmapIndex = 1;
SrcModel->RawMeshBulkData->SaveRawMesh(RawMesh);
// Set the materials used for this static mesh
#if ENGINE_MAJOR_VERSION == 4 && ENGINE_MINOR_VERSION >= 14
StaticMesh->StaticMaterials = Materials;
int32 NumMaterials = StaticMesh->StaticMaterials.Num();
#else
StaticMesh->Materials = Materials;
int32 NumMaterials = StaticMesh->Materials.Num();
#endif
// Set up the SectionInfoMap to enable collision
for (int32 SectionIdx = 0; SectionIdx < NumMaterials; SectionIdx++)
{
FMeshSectionInfo Info = StaticMesh->SectionInfoMap.Get(0, SectionIdx);
Info.MaterialIndex = SectionIdx;
Info.bEnableCollision = true;
StaticMesh->SectionInfoMap.Set(0, SectionIdx, Info);
}
// Build mesh from source
StaticMesh->Build(false);
// Make package dirty.
StaticMesh->MarkPackageDirty();
StaticMesh->PostEditChange();
// Notify asset registry of new asset
FAssetRegistryModule::AssetCreated(StaticMesh);
}
}
}
return FReply::Handled();
}
#undef LOCTEXT_NAMESPACE<commit_msg>Added support for automatically configuring the colliison for SMC -> RMC conversion.<commit_after>// Copyright 2016 Chris Conway (Koderz). All Rights Reserved.
#include "RuntimeMeshComponentEditorPrivatePCH.h"
#include "RuntimeMeshComponentDetails.h"
#include "DlgPickAssetPath.h"
#include "AssetToolsModule.h"
#include "AssetRegistryModule.h"
#include "PhysicsEngine/PhysicsSettings.h"
#include "PhysicsEngine/BodySetup.h"
#define LOCTEXT_NAMESPACE "RuntimeMeshComponentDetails"
TSharedRef<IDetailCustomization> FRuntimeMeshComponentDetails::MakeInstance()
{
return MakeShareable(new FRuntimeMeshComponentDetails);
}
void FRuntimeMeshComponentDetails::CustomizeDetails( IDetailLayoutBuilder& DetailBuilder )
{
IDetailCategoryBuilder& RuntimeMeshCategory = DetailBuilder.EditCategory("RuntimeMesh");
const FText ConvertToStaticMeshText = LOCTEXT("ConvertToStaticMesh", "Create StaticMesh");
// Cache set of selected things
SelectedObjectsList = DetailBuilder.GetDetailsView().GetSelectedObjects();
RuntimeMeshCategory.AddCustomRow(ConvertToStaticMeshText, false)
.NameContent()
[
SNullWidget::NullWidget
]
.ValueContent()
.VAlign(VAlign_Center)
.MaxDesiredWidth(250)
[
SNew(SButton)
.VAlign(VAlign_Center)
.ToolTipText(LOCTEXT("ConvertToStaticMeshTooltip", "Create a new StaticMesh asset using current geometry from this RuntimeMeshComponent. Does not modify instance."))
.OnClicked(this, &FRuntimeMeshComponentDetails::ClickedOnConvertToStaticMesh)
.IsEnabled(this, &FRuntimeMeshComponentDetails::ConvertToStaticMeshEnabled)
.Content()
[
SNew(STextBlock)
.Text(ConvertToStaticMeshText)
]
];
}
URuntimeMeshComponent* FRuntimeMeshComponentDetails::GetFirstSelectedRuntimeMeshComp() const
{
// Find first selected valid RuntimeMeshComp
URuntimeMeshComponent* RuntimeMeshComp = nullptr;
for (const TWeakObjectPtr<UObject>& Object : SelectedObjectsList)
{
URuntimeMeshComponent* TestRuntimeComp = Cast<URuntimeMeshComponent>(Object.Get());
// See if this one is good
if (TestRuntimeComp != nullptr && !TestRuntimeComp->IsTemplate())
{
RuntimeMeshComp = TestRuntimeComp;
break;
}
}
return RuntimeMeshComp;
}
bool FRuntimeMeshComponentDetails::ConvertToStaticMeshEnabled() const
{
return GetFirstSelectedRuntimeMeshComp() != nullptr;
}
FReply FRuntimeMeshComponentDetails::ClickedOnConvertToStaticMesh()
{
// Find first selected RuntimeMeshComp
URuntimeMeshComponent* RuntimeMeshComp = GetFirstSelectedRuntimeMeshComp();
if (RuntimeMeshComp != nullptr)
{
FString NewNameSuggestion = FString(TEXT("RuntimeMeshComp"));
FString PackageName = FString(TEXT("/Game/Meshes/")) + NewNameSuggestion;
FString Name;
FAssetToolsModule& AssetToolsModule = FModuleManager::LoadModuleChecked<FAssetToolsModule>("AssetTools");
AssetToolsModule.Get().CreateUniqueAssetName(PackageName, TEXT(""), PackageName, Name);
TSharedPtr<SDlgPickAssetPath> PickAssetPathWidget =
SNew(SDlgPickAssetPath)
.Title(LOCTEXT("ConvertToStaticMeshPickName", "Choose New StaticMesh Location"))
.DefaultAssetPath(FText::FromString(PackageName));
if (PickAssetPathWidget->ShowModal() == EAppReturnType::Ok)
{
// Get the full name of where we want to create the physics asset.
FString UserPackageName = PickAssetPathWidget->GetFullAssetPath().ToString();
FName MeshName(*FPackageName::GetLongPackageAssetName(UserPackageName));
// Check if the user inputed a valid asset name, if they did not, give it the generated default name
if (MeshName == NAME_None)
{
// Use the defaults that were already generated.
UserPackageName = PackageName;
MeshName = *Name;
}
// Raw mesh data we are filling in
FRawMesh RawMesh;
// Unique Materials to apply to new mesh
#if ENGINE_MAJOR_VERSION == 4 && ENGINE_MINOR_VERSION >= 14
TArray<FStaticMaterial> Materials;
#else
TArray<UMaterialInterface*> Materials;
#endif
bool bUseHighPrecisionTangents = false;
bool bUseFullPrecisionUVs = false;
const int32 NumSections = RuntimeMeshComp->GetNumSections();
int32 VertexBase = 0;
for (int32 SectionIdx = 0; SectionIdx < NumSections; SectionIdx++)
{
const IRuntimeMeshVerticesBuilder* Vertices;
const FRuntimeMeshIndicesBuilder* Indices;
RuntimeMeshComp->GetSectionMesh(SectionIdx, Vertices, Indices);
if (Vertices->HasHighPrecisionNormals())
{
bUseHighPrecisionTangents = true;
}
if (Vertices->HasHighPrecisionUVs())
{
bUseFullPrecisionUVs = true;
}
// Copy verts
Vertices->Seek(-1);
while (Vertices->MoveNext() < Vertices->Length())
{
RawMesh.VertexPositions.Add(Vertices->GetPosition());
}
// Copy 'wedge' info
Indices->Seek(0);
while (Indices->HasRemaining())
{
int32 Index = Indices->ReadOne();
RawMesh.WedgeIndices.Add(Index + VertexBase);
Vertices->Seek(Index);
FVector TangentX = Vertices->GetTangent();
FVector TangentZ = Vertices->GetNormal();
FVector TangentY = (TangentX ^ TangentZ).GetSafeNormal() * Vertices->GetNormal().W;
RawMesh.WedgeTangentX.Add(TangentX);
RawMesh.WedgeTangentY.Add(TangentY);
RawMesh.WedgeTangentZ.Add(TangentZ);
for (int UVIndex = 0; UVIndex < 8; UVIndex++)
{
if (!Vertices->HasUVComponent(UVIndex))
{
break;
}
RawMesh.WedgeTexCoords[UVIndex].Add(Vertices->GetUV(UVIndex));
}
RawMesh.WedgeColors.Add(Vertices->GetColor());
}
// Find a material index for this section.
UMaterialInterface* Material = RuntimeMeshComp->GetMaterial(SectionIdx);
#if ENGINE_MAJOR_VERSION == 4 && ENGINE_MINOR_VERSION >= 14
int32 MaterialIndex = Materials.AddUnique(FStaticMaterial(Material));
#else
int32 MaterialIndex = Materials.AddUnique(Material);
#endif
// copy face info
int32 NumTris = Indices->Length() / 3;
for (int32 TriIdx=0; TriIdx < NumTris; TriIdx++)
{
// Set the face material
RawMesh.FaceMaterialIndices.Add(MaterialIndex);
RawMesh.FaceSmoothingMasks.Add(0); // Assume this is ignored as bRecomputeNormals is false
}
// Update offset for creating one big index/vertex buffer
VertexBase += Vertices->Length();
}
// If we got some valid data.
if (RawMesh.VertexPositions.Num() > 3 && RawMesh.WedgeIndices.Num() > 3)
{
// Then find/create it.
UPackage* Package = CreatePackage(NULL, *UserPackageName);
check(Package);
// Create StaticMesh object
UStaticMesh* StaticMesh = NewObject<UStaticMesh>(Package, MeshName, RF_Public | RF_Standalone);
StaticMesh->InitResources();
StaticMesh->LightingGuid = FGuid::NewGuid();
// Add source to new StaticMesh
FStaticMeshSourceModel* SrcModel = new (StaticMesh->SourceModels) FStaticMeshSourceModel();
SrcModel->BuildSettings.bRecomputeNormals = false;
SrcModel->BuildSettings.bRecomputeTangents = false;
SrcModel->BuildSettings.bRemoveDegenerates = false;
SrcModel->BuildSettings.bUseHighPrecisionTangentBasis = bUseHighPrecisionTangents;
SrcModel->BuildSettings.bUseFullPrecisionUVs = bUseFullPrecisionUVs;
SrcModel->BuildSettings.bGenerateLightmapUVs = true;
SrcModel->BuildSettings.SrcLightmapIndex = 0;
SrcModel->BuildSettings.DstLightmapIndex = 1;
SrcModel->RawMeshBulkData->SaveRawMesh(RawMesh);
// Set the materials used for this static mesh
#if ENGINE_MAJOR_VERSION == 4 && ENGINE_MINOR_VERSION >= 14
StaticMesh->StaticMaterials = Materials;
int32 NumMaterials = StaticMesh->StaticMaterials.Num();
#else
StaticMesh->Materials = Materials;
int32 NumMaterials = StaticMesh->Materials.Num();
#endif
// Set up the SectionInfoMap to enable collision
for (int32 SectionIdx = 0; SectionIdx < NumMaterials; SectionIdx++)
{
FMeshSectionInfo Info = StaticMesh->SectionInfoMap.Get(0, SectionIdx);
Info.MaterialIndex = SectionIdx;
Info.bEnableCollision = true;
StaticMesh->SectionInfoMap.Set(0, SectionIdx, Info);
}
// Configure body setup for working collision.
StaticMesh->CreateBodySetup();
StaticMesh->BodySetup->CollisionTraceFlag = CTF_UseComplexAsSimple;
// Build mesh from source
StaticMesh->Build(false);
// Make package dirty.
StaticMesh->MarkPackageDirty();
StaticMesh->PostEditChange();
// Notify asset registry of new asset
FAssetRegistryModule::AssetCreated(StaticMesh);
}
}
}
return FReply::Handled();
}
#undef LOCTEXT_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/string_util.h"
#include "base/test/test_timeouts.h"
#include "base/threading/platform_thread.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "chrome/browser/net/url_request_failed_dns_job.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "net/test/test_server.h"
class ErrorPageTest : public UITest {
protected:
bool WaitForTitleMatching(const std::wstring& title) {
for (int i = 0; i < 10; ++i) {
if (GetActiveTabTitle() == title)
return true;
base::PlatformThread::Sleep(TestTimeouts::action_timeout_ms());
}
EXPECT_EQ(title, GetActiveTabTitle());
return false;
}
};
TEST_F(ErrorPageTest, DNSError_Basic) {
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
}
TEST_F(ErrorPageTest, DNSError_GoBack1) {
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
EXPECT_TRUE(GetActiveTab()->GoBack());
EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
// Flaky on Linux, see http://crbug.com/19361
#if defined(OS_LINUX)
#define MAYBE_DNSError_GoBack2 FLAKY_DNSError_GoBack2
#else
#define MAYBE_DNSError_GoBack2 DNSError_GoBack2
#endif
TEST_F(ErrorPageTest, MAYBE_DNSError_GoBack2) {
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title3.html"))));
// The first navigation should fail, and the second one should be the error
// page.
EXPECT_TRUE(GetActiveTab()->GoBackBlockUntilNavigationsComplete(2));
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
EXPECT_TRUE(GetActiveTab()->GoBack());
EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
// Flaky on Linux, see http://crbug.com/19361
#if defined(OS_LINUX)
#define MAYBE_DNSError_GoBack2AndForwar FLAKY_DNSError_GoBack2AndForwar
#else
#define MAYBE_DNSError_GoBack2AndForwar DNSError_GoBack2AndForwar
#endif
TEST_F(ErrorPageTest, MAYBE_DNSError_GoBack2AndForward) {
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title3.html"))));
// The first navigation should fail, and the second one should be the error
// page.
EXPECT_TRUE(GetActiveTab()->GoBackBlockUntilNavigationsComplete(2));
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
EXPECT_TRUE(GetActiveTab()->GoBack());
// The first navigation should fail, and the second one should be the error
// page.
EXPECT_TRUE(GetActiveTab()->GoForwardBlockUntilNavigationsComplete(2));
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
}
// Flaky on Linux, see http://crbug.com/19361
#if defined(OS_LINUX)
#define MAYBE_DNSError_GoBack2Forward2 FLAKY_DNSError_GoBack2Forward2
#else
#define MAYBE_DNSError_GoBack2Forward2 DNSError_GoBack2Forward2
#endif
TEST_F(ErrorPageTest, MAYBE_DNSError_GoBack2Forward2) {
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title3.html"))));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
// The first navigation should fail, and the second one should be the error
// page.
EXPECT_TRUE(GetActiveTab()->GoBackBlockUntilNavigationsComplete(2));
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
EXPECT_TRUE(GetActiveTab()->GoBack());
// The first navigation should fail, and the second one should be the error
// page.
EXPECT_TRUE(GetActiveTab()->GoForwardBlockUntilNavigationsComplete(2));
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
EXPECT_TRUE(GetActiveTab()->GoForward());
EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
TEST_F(ErrorPageTest, IFrameDNSError_Basic) {
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("iframe_dns_error.html"))));
EXPECT_TRUE(WaitForTitleMatching(L"Blah"));
}
TEST_F(ErrorPageTest, IFrameDNSError_GoBack) {
// Test that a DNS error occuring in an iframe does not result in an
// additional session history entry.
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("iframe_dns_error.html"))));
EXPECT_TRUE(GetActiveTab()->GoBack());
EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
TEST_F(ErrorPageTest, IFrameDNSError_GoBackAndForward) {
// Test that a DNS error occuring in an iframe does not result in an
// additional session history entry.
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("iframe_dns_error.html"))));
EXPECT_TRUE(GetActiveTab()->GoBack());
EXPECT_TRUE(GetActiveTab()->GoForward());
EXPECT_TRUE(WaitForTitleMatching(L"Blah"));
}
// Checks that the Link Doctor is not loaded when we receive an actual 404 page.
TEST_F(ErrorPageTest, Page404) {
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("page404.html"))));
EXPECT_TRUE(WaitForTitleMatching(L"SUCCESS"));
}
<commit_msg>Fixed a typo<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/string_util.h"
#include "base/test/test_timeouts.h"
#include "base/threading/platform_thread.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "chrome/browser/net/url_request_failed_dns_job.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "net/test/test_server.h"
class ErrorPageTest : public UITest {
protected:
bool WaitForTitleMatching(const std::wstring& title) {
for (int i = 0; i < 10; ++i) {
if (GetActiveTabTitle() == title)
return true;
base::PlatformThread::Sleep(TestTimeouts::action_timeout_ms());
}
EXPECT_EQ(title, GetActiveTabTitle());
return false;
}
};
TEST_F(ErrorPageTest, DNSError_Basic) {
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
}
TEST_F(ErrorPageTest, DNSError_GoBack1) {
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
EXPECT_TRUE(GetActiveTab()->GoBack());
EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
// Flaky on Linux, see http://crbug.com/19361
#if defined(OS_LINUX)
#define MAYBE_DNSError_GoBack2 FLAKY_DNSError_GoBack2
#else
#define MAYBE_DNSError_GoBack2 DNSError_GoBack2
#endif
TEST_F(ErrorPageTest, MAYBE_DNSError_GoBack2) {
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title3.html"))));
// The first navigation should fail, and the second one should be the error
// page.
EXPECT_TRUE(GetActiveTab()->GoBackBlockUntilNavigationsComplete(2));
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
EXPECT_TRUE(GetActiveTab()->GoBack());
EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
// Flaky on Linux, see http://crbug.com/19361
#if defined(OS_LINUX)
#define MAYBE_DNSError_GoBack2AndForwar FLAKY_DNSError_GoBack2AndForward
#else
#define MAYBE_DNSError_GoBack2AndForwar DNSError_GoBack2AndForward
#endif
TEST_F(ErrorPageTest, MAYBE_DNSError_GoBack2AndForward) {
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title3.html"))));
// The first navigation should fail, and the second one should be the error
// page.
EXPECT_TRUE(GetActiveTab()->GoBackBlockUntilNavigationsComplete(2));
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
EXPECT_TRUE(GetActiveTab()->GoBack());
// The first navigation should fail, and the second one should be the error
// page.
EXPECT_TRUE(GetActiveTab()->GoForwardBlockUntilNavigationsComplete(2));
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
}
// Flaky on Linux, see http://crbug.com/19361
#if defined(OS_LINUX)
#define MAYBE_DNSError_GoBack2Forward2 FLAKY_DNSError_GoBack2Forward2
#else
#define MAYBE_DNSError_GoBack2Forward2 DNSError_GoBack2Forward2
#endif
TEST_F(ErrorPageTest, MAYBE_DNSError_GoBack2Forward2) {
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title3.html"))));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
// The first navigation should fail, and the second one should be the error
// page.
EXPECT_TRUE(GetActiveTab()->GoBackBlockUntilNavigationsComplete(2));
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
EXPECT_TRUE(GetActiveTab()->GoBack());
// The first navigation should fail, and the second one should be the error
// page.
EXPECT_TRUE(GetActiveTab()->GoForwardBlockUntilNavigationsComplete(2));
EXPECT_TRUE(WaitForTitleMatching(L"Mock Link Doctor"));
EXPECT_TRUE(GetActiveTab()->GoForward());
EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
TEST_F(ErrorPageTest, IFrameDNSError_Basic) {
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("iframe_dns_error.html"))));
EXPECT_TRUE(WaitForTitleMatching(L"Blah"));
}
TEST_F(ErrorPageTest, IFrameDNSError_GoBack) {
// Test that a DNS error occuring in an iframe does not result in an
// additional session history entry.
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("iframe_dns_error.html"))));
EXPECT_TRUE(GetActiveTab()->GoBack());
EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
TEST_F(ErrorPageTest, IFrameDNSError_GoBackAndForward) {
// Test that a DNS error occuring in an iframe does not result in an
// additional session history entry.
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("title2.html"))));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("iframe_dns_error.html"))));
EXPECT_TRUE(GetActiveTab()->GoBack());
EXPECT_TRUE(GetActiveTab()->GoForward());
EXPECT_TRUE(WaitForTitleMatching(L"Blah"));
}
// Checks that the Link Doctor is not loaded when we receive an actual 404 page.
TEST_F(ErrorPageTest, Page404) {
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(
FilePath(FILE_PATH_LITERAL("page404.html"))));
EXPECT_TRUE(WaitForTitleMatching(L"SUCCESS"));
}
<|endoftext|> |
<commit_before>#include "Plater/Plate2D.hpp"
// libslic3r includes
#include "Geometry.hpp"
#include "Point.hpp"
#include "Log.hpp"
#include "ClipperUtils.hpp"
// wx includes
#include <wx/colour.h>
#include <wx/dcbuffer.h>
namespace Slic3r { namespace GUI {
Plate2D::Plate2D(wxWindow* parent, const wxSize& size, std::vector<PlaterObject>& _objects, std::shared_ptr<Model> _model, std::shared_ptr<Config> _config, std::shared_ptr<Settings> _settings) :
wxPanel(parent, wxID_ANY, wxDefaultPosition, size, wxTAB_TRAVERSAL), objects(_objects), model(_model), config(_config), settings(_settings)
{
this->Bind(wxEVT_PAINT, [=](wxPaintEvent &e) { this->repaint(e); });
this->Bind(wxEVT_MOTION, [=](wxMouseEvent &e) { this->mouse_drag(e); });
this->Bind(wxEVT_LEFT_DOWN, [=](wxMouseEvent &e) { this->mouse_down(e); });
this->Bind(wxEVT_LEFT_UP, [=](wxMouseEvent &e) { this->mouse_up(e); });
this->Bind(wxEVT_LEFT_DCLICK, [=](wxMouseEvent &e) { this->mouse_dclick(e); });
if (user_drawn_background) {
this->Bind(wxEVT_ERASE_BACKGROUND, [=](wxEraseEvent& e){ });
}
this->Bind(wxEVT_SIZE, [=](wxSizeEvent &e) { this->update_bed_size(); this->Refresh(); });
// Bind the varying mouse events
// Set the brushes
set_colors();
this->SetBackgroundStyle(wxBG_STYLE_PAINT);
}
void Plate2D::repaint(wxPaintEvent& e) {
// Need focus to catch keyboard events.
this->SetFocus();
auto dc {new wxAutoBufferedPaintDC(this)};
const auto& size {wxSize(this->GetSize().GetWidth(), this->GetSize().GetHeight())};
if (this->user_drawn_background) {
// On all systems the AutoBufferedPaintDC() achieves double buffering.
// On MacOS the background is erased, on Windows the background is not erased
// and on Linux/GTK the background is erased to gray color.
// Fill DC with the background on Windows & Linux/GTK.
const auto& brush_background {wxBrush(this->settings->color->BACKGROUND255(), wxBRUSHSTYLE_SOLID)};
const auto& pen_background {wxPen(this->settings->color->BACKGROUND255(), 1, wxPENSTYLE_SOLID)};
dc->SetPen(pen_background);
dc->SetBrush(brush_background);
const auto& rect {this->GetUpdateRegion().GetBox()};
dc->DrawRectangle(rect.GetLeft(), rect.GetTop(), rect.GetWidth(), rect.GetHeight());
}
// Draw bed
{
dc->SetPen(this->print_center_pen);
dc->SetBrush(this->bed_brush);
auto tmp {scaled_points_to_pixel(this->bed_polygon, true)};
dc->DrawPolygon(this->bed_polygon.points.size(), tmp.data(), 0, 0);
}
// draw print center
{
if (this->objects.size() > 0 && settings->autocenter) {
const auto center = this->unscaled_point_to_pixel(this->print_center);
dc->SetPen(print_center_pen);
dc->DrawLine(center.x, 0, center.x, size.y);
dc->DrawLine(0, center.y, size.x, center.y);
dc->SetTextForeground(wxColor(0,0,0));
dc->SetFont(wxFont(10, wxFONTFAMILY_ROMAN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL));
dc->DrawLabel(wxString::Format("X = %.0f", this->print_center.x), wxRect(0,0, center.x*2, this->GetSize().GetHeight()), wxALIGN_CENTER_HORIZONTAL | wxALIGN_BOTTOM);
dc->DrawRotatedText(wxString::Format("Y = %.0f", this->print_center.y), 0, center.y + 15, 90);
}
}
// draw text if plate is empty
if (this->objects.size() == 0) {
dc->SetTextForeground(settings->color->BED_OBJECTS());
dc->SetFont(wxFont(14, wxFONTFAMILY_ROMAN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL));
dc->DrawLabel(CANVAS_TEXT, wxRect(0,0, this->GetSize().GetWidth(), this->GetSize().GetHeight()), wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL);
} else {
// draw grid
dc->SetPen(grid_pen);
// Assumption: grid of lines is arranged
// as adjacent pairs of wxPoints
for (auto i = 0U; i < grid.size(); i+=2) {
dc->DrawLine(grid[i], grid[i+1]);
}
}
// Draw thumbnails
dc->SetPen(dark_pen);
this->clean_instance_thumbnails();
for (auto& obj : this->objects) {
auto model_object {this->model->objects.at(obj.identifier)};
if (obj.thumbnail.expolygons.size() == 0)
continue; // if there's no thumbnail move on
for (size_t instance_idx = 0U; instance_idx < model_object->instances.size(); instance_idx++) {
auto& instance {model_object->instances.at(instance_idx)};
if (obj.transformed_thumbnail.expolygons.size()) continue;
auto thumbnail {obj.transformed_thumbnail}; // starts in unscaled model coords
thumbnail.translate(Point::new_scale(instance->offset));
obj.instance_thumbnails.emplace_back(thumbnail);
if (0) { // object is dragged
dc->SetBrush(dragged_brush);
} else if (0) {
dc->SetBrush(instance_brush);
} else if (0) {
dc->SetBrush(selected_brush);
} else {
dc->SetBrush(objects_brush);
}
// porting notes: perl here seems to be making a single-item array of the
// thumbnail set.
// no idea why. It doesn't look necessary, so skip the outer layer
// and draw the contained expolygons
for (const auto& points : obj.instance_thumbnails.back().expolygons) {
auto poly { this->scaled_points_to_pixel(Polygon(points), 1) };
dc->DrawPolygon(poly.size(), poly.data(), 0, 0);
}
}
}
e.Skip();
}
void Plate2D::clean_instance_thumbnails() {
for (auto& obj : this->objects) {
obj.instance_thumbnails.clear();
}
}
void Plate2D::mouse_drag(wxMouseEvent& e) {
const auto pos {e.GetPosition()};
const auto& point {this->point_to_model_units(e.GetPosition())};
if (e.Dragging()) {
Slic3r::Log::info(LogChannel, L"Mouse dragging");
} else {
auto cursor = wxSTANDARD_CURSOR;
/*
if (find_first_of(this->objects.begin(), this->objects.end(); [=](const PlaterObject& o) { return o.contour->contains_point(point);} ) == this->object.end()) {
cursor = wxCursor(wxCURSOR_HAND);
}
*/
this->SetCursor(*cursor);
}
}
void Plate2D::mouse_down(wxMouseEvent& e) {
}
void Plate2D::mouse_up(wxMouseEvent& e) {
}
void Plate2D::mouse_dclick(wxMouseEvent& e) {
}
void Plate2D::set_colors() {
this->SetBackgroundColour(settings->color->BACKGROUND255());
this->objects_brush.SetColour(settings->color->BED_OBJECTS());
this->objects_brush.SetStyle(wxBRUSHSTYLE_SOLID);
this->instance_brush.SetColour(settings->color->BED_INSTANCE());
this->instance_brush.SetStyle(wxBRUSHSTYLE_SOLID);
this->selected_brush.SetColour(settings->color->BED_SELECTED());
this->selected_brush.SetStyle(wxBRUSHSTYLE_SOLID);
this->dragged_brush.SetColour(settings->color->BED_DRAGGED());
this->dragged_brush.SetStyle(wxBRUSHSTYLE_SOLID);
this->bed_brush.SetColour(settings->color->BED_COLOR());
this->bed_brush.SetStyle(wxBRUSHSTYLE_SOLID);
this->transparent_brush.SetColour(wxColour(0,0,0));
this->transparent_brush.SetStyle(wxBRUSHSTYLE_TRANSPARENT);
this->grid_pen.SetColour(settings->color->BED_GRID());
this->grid_pen.SetWidth(1);
this->grid_pen.SetStyle(wxPENSTYLE_SOLID);
this->print_center_pen.SetColour(settings->color->BED_CENTER());
this->print_center_pen.SetWidth(1);
this->print_center_pen.SetStyle(wxPENSTYLE_SOLID);
this->clearance_pen.SetColour(settings->color->BED_CLEARANCE());
this->clearance_pen.SetWidth(1);
this->clearance_pen.SetStyle(wxPENSTYLE_SOLID);
this->skirt_pen.SetColour(settings->color->BED_SKIRT());
this->skirt_pen.SetWidth(1);
this->skirt_pen.SetStyle(wxPENSTYLE_SOLID);
this->dark_pen.SetColour(settings->color->BED_DARK());
this->dark_pen.SetWidth(1);
this->dark_pen.SetStyle(wxPENSTYLE_SOLID);
}
void Plate2D::nudge_key(wxKeyEvent& e) {
const auto key = e.GetKeyCode();
switch( key ) {
case WXK_LEFT:
this->nudge(MoveDirection::Left);
case WXK_RIGHT:
this->nudge(MoveDirection::Right);
case WXK_DOWN:
this->nudge(MoveDirection::Down);
case WXK_UP:
this->nudge(MoveDirection::Up);
default:
break; // do nothing
}
}
void Plate2D::nudge(MoveDirection dir) {
if (this->selected_instance < this->objects.size()) {
auto i = 0U;
for (auto& obj : this->objects) {
if (obj.selected) {
if (obj.selected_instance != -1) {
}
}
i++;
}
}
if (selected_instance >= this->objects.size()) {
Slic3r::Log::warn(LogChannel, L"Nudge failed because there is no selected instance.");
return; // Abort
}
}
void Plate2D::update_bed_size() {
const auto& canvas_size {this->GetSize()};
const auto& canvas_w {canvas_size.GetWidth()};
const auto& canvas_h {canvas_size.GetHeight()};
if (canvas_w == 0) return; // Abort early if we haven't drawn canvas yet.
this->bed_polygon = Slic3r::Polygon(scale(dynamic_cast<ConfigOptionPoints*>(config->optptr("bed_shape"))->values));
const auto& polygon = bed_polygon;
const auto& bb = bed_polygon.bounding_box();
const auto& size = bb.size();
this->scaling_factor = std::min(canvas_w / unscale(size.x), canvas_h / unscale(size.y));
this->bed_origin = wxPoint(
canvas_w / 2 - (unscale(bb.max.x + bb.min.x)/2 * this->scaling_factor),
canvas_h - (canvas_h / 2 - (unscale(bb.max.y + bb.min.y)/2 * this->scaling_factor))
);
const auto& center = bb.center();
this->print_center = wxPoint(unscale(center.x), unscale(center.y));
// Cache bed contours and grid
{
const auto& step { scale_(10) };
auto grid {Polylines()};
for (coord_t x = (bb.min.x - (bb.min.x % step) + step); x < bb.max.x; x += step) {
grid.push_back(Polyline());
grid.back().append(Point(x, bb.min.y));
grid.back().append(Point(x, bb.max.y));
};
for (coord_t y = (bb.min.y - (bb.min.y % step) + step); y < bb.max.y; y += step) {
grid.push_back(Polyline());
grid.back().append(Point(bb.min.x, y));
grid.back().append(Point(bb.max.x, y));
};
grid = intersection_pl(grid, polygon);
for (auto& i : grid) {
const auto& tmpline { this->scaled_points_to_pixel(i, 1) };
this->grid.insert(this->grid.end(), tmpline.begin(), tmpline.end());
}
}
}
std::vector<wxPoint> Plate2D::scaled_points_to_pixel(const Slic3r::Polygon& poly, bool unscale) {
return this->scaled_points_to_pixel(Polyline(poly), unscale);
}
std::vector<wxPoint> Plate2D::scaled_points_to_pixel(const Slic3r::Polyline& poly, bool _unscale) {
std::vector<wxPoint> result;
for (const auto& pt : poly.points) {
const auto x {_unscale ? Slic3r::unscale(pt.x) : pt.x};
const auto y {_unscale ? Slic3r::unscale(pt.y) : pt.y};
result.push_back(wxPoint(x, y));
}
return result;
}
wxPoint Plate2D::unscaled_point_to_pixel(const wxPoint& in) {
const auto& canvas_height {this->GetSize().GetHeight()};
const auto& zero = this->bed_origin;
return wxPoint(in.x * this->scaling_factor + zero.x,
in.y * this->scaling_factor + (zero.y - canvas_height));
}
} } // Namespace Slic3r::GUI
<commit_msg>Being more specific about units.<commit_after>#include "Plater/Plate2D.hpp"
// libslic3r includes
#include "Geometry.hpp"
#include "Point.hpp"
#include "Log.hpp"
#include "ClipperUtils.hpp"
// wx includes
#include <wx/colour.h>
#include <wx/dcbuffer.h>
namespace Slic3r { namespace GUI {
Plate2D::Plate2D(wxWindow* parent, const wxSize& size, std::vector<PlaterObject>& _objects, std::shared_ptr<Model> _model, std::shared_ptr<Config> _config, std::shared_ptr<Settings> _settings) :
wxPanel(parent, wxID_ANY, wxDefaultPosition, size, wxTAB_TRAVERSAL), objects(_objects), model(_model), config(_config), settings(_settings)
{
this->Bind(wxEVT_PAINT, [=](wxPaintEvent &e) { this->repaint(e); });
this->Bind(wxEVT_MOTION, [=](wxMouseEvent &e) { this->mouse_drag(e); });
this->Bind(wxEVT_LEFT_DOWN, [=](wxMouseEvent &e) { this->mouse_down(e); });
this->Bind(wxEVT_LEFT_UP, [=](wxMouseEvent &e) { this->mouse_up(e); });
this->Bind(wxEVT_LEFT_DCLICK, [=](wxMouseEvent &e) { this->mouse_dclick(e); });
if (user_drawn_background) {
this->Bind(wxEVT_ERASE_BACKGROUND, [=](wxEraseEvent& e){ });
}
this->Bind(wxEVT_SIZE, [=](wxSizeEvent &e) { this->update_bed_size(); this->Refresh(); });
// Bind the varying mouse events
// Set the brushes
set_colors();
this->SetBackgroundStyle(wxBG_STYLE_PAINT);
}
void Plate2D::repaint(wxPaintEvent& e) {
// Need focus to catch keyboard events.
this->SetFocus();
auto dc {new wxAutoBufferedPaintDC(this)};
const auto& size {wxSize(this->GetSize().GetWidth(), this->GetSize().GetHeight())};
if (this->user_drawn_background) {
// On all systems the AutoBufferedPaintDC() achieves double buffering.
// On MacOS the background is erased, on Windows the background is not erased
// and on Linux/GTK the background is erased to gray color.
// Fill DC with the background on Windows & Linux/GTK.
const auto& brush_background {wxBrush(this->settings->color->BACKGROUND255(), wxBRUSHSTYLE_SOLID)};
const auto& pen_background {wxPen(this->settings->color->BACKGROUND255(), 1, wxPENSTYLE_SOLID)};
dc->SetPen(pen_background);
dc->SetBrush(brush_background);
const auto& rect {this->GetUpdateRegion().GetBox()};
dc->DrawRectangle(rect.GetLeft(), rect.GetTop(), rect.GetWidth(), rect.GetHeight());
}
// Draw bed
{
dc->SetPen(this->print_center_pen);
dc->SetBrush(this->bed_brush);
auto tmp {scaled_points_to_pixel(this->bed_polygon, true)};
dc->DrawPolygon(this->bed_polygon.points.size(), tmp.data(), 0, 0);
}
// draw print center
{
if (this->objects.size() > 0 && settings->autocenter) {
const auto center = this->unscaled_point_to_pixel(this->print_center);
dc->SetPen(print_center_pen);
dc->DrawLine(center.x, 0, center.x, size.y);
dc->DrawLine(0, center.y, size.x, center.y);
dc->SetTextForeground(wxColor(0,0,0));
dc->SetFont(wxFont(10, wxFONTFAMILY_ROMAN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL));
dc->DrawLabel(wxString::Format("X = %.0f", this->print_center.x), wxRect(0,0, center.x*2, this->GetSize().GetHeight()), wxALIGN_CENTER_HORIZONTAL | wxALIGN_BOTTOM);
dc->DrawRotatedText(wxString::Format("Y = %.0f", this->print_center.y), 0, center.y + 15, 90);
}
}
// draw text if plate is empty
if (this->objects.size() == 0) {
dc->SetTextForeground(settings->color->BED_OBJECTS());
dc->SetFont(wxFont(14, wxFONTFAMILY_ROMAN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL));
dc->DrawLabel(CANVAS_TEXT, wxRect(0,0, this->GetSize().GetWidth(), this->GetSize().GetHeight()), wxALIGN_CENTER_HORIZONTAL | wxALIGN_CENTER_VERTICAL);
} else {
// draw grid
dc->SetPen(grid_pen);
// Assumption: grid of lines is arranged
// as adjacent pairs of wxPoints
for (auto i = 0U; i < grid.size(); i+=2) {
dc->DrawLine(grid[i], grid[i+1]);
}
}
// Draw thumbnails
dc->SetPen(dark_pen);
this->clean_instance_thumbnails();
for (auto& obj : this->objects) {
auto model_object {this->model->objects.at(obj.identifier)};
if (obj.thumbnail.expolygons.size() == 0)
continue; // if there's no thumbnail move on
for (size_t instance_idx = 0U; instance_idx < model_object->instances.size(); instance_idx++) {
auto& instance {model_object->instances.at(instance_idx)};
if (obj.transformed_thumbnail.expolygons.size()) continue;
auto thumbnail {obj.transformed_thumbnail}; // starts in unscaled model coords
thumbnail.translate(Point::new_scale(instance->offset));
obj.instance_thumbnails.emplace_back(thumbnail);
if (0) { // object is dragged
dc->SetBrush(dragged_brush);
} else if (0) {
dc->SetBrush(instance_brush);
} else if (0) {
dc->SetBrush(selected_brush);
} else {
dc->SetBrush(objects_brush);
}
// porting notes: perl here seems to be making a single-item array of the
// thumbnail set.
// no idea why. It doesn't look necessary, so skip the outer layer
// and draw the contained expolygons
for (const auto& points : obj.instance_thumbnails.back().expolygons) {
auto poly { this->scaled_points_to_pixel(Polygon(points), 1) };
dc->DrawPolygon(poly.size(), poly.data(), 0, 0);
}
}
}
e.Skip();
}
void Plate2D::clean_instance_thumbnails() {
for (auto& obj : this->objects) {
obj.instance_thumbnails.clear();
}
}
void Plate2D::mouse_drag(wxMouseEvent& e) {
const auto pos {e.GetPosition()};
const auto& point {this->point_to_model_units(e.GetPosition())};
if (e.Dragging()) {
Slic3r::Log::info(LogChannel, L"Mouse dragging");
} else {
auto cursor = wxSTANDARD_CURSOR;
/*
if (find_first_of(this->objects.begin(), this->objects.end(); [=](const PlaterObject& o) { return o.contour->contains_point(point);} ) == this->object.end()) {
cursor = wxCursor(wxCURSOR_HAND);
}
*/
this->SetCursor(*cursor);
}
}
void Plate2D::mouse_down(wxMouseEvent& e) {
}
void Plate2D::mouse_up(wxMouseEvent& e) {
}
void Plate2D::mouse_dclick(wxMouseEvent& e) {
}
void Plate2D::set_colors() {
this->SetBackgroundColour(settings->color->BACKGROUND255());
this->objects_brush.SetColour(settings->color->BED_OBJECTS());
this->objects_brush.SetStyle(wxBRUSHSTYLE_SOLID);
this->instance_brush.SetColour(settings->color->BED_INSTANCE());
this->instance_brush.SetStyle(wxBRUSHSTYLE_SOLID);
this->selected_brush.SetColour(settings->color->BED_SELECTED());
this->selected_brush.SetStyle(wxBRUSHSTYLE_SOLID);
this->dragged_brush.SetColour(settings->color->BED_DRAGGED());
this->dragged_brush.SetStyle(wxBRUSHSTYLE_SOLID);
this->bed_brush.SetColour(settings->color->BED_COLOR());
this->bed_brush.SetStyle(wxBRUSHSTYLE_SOLID);
this->transparent_brush.SetColour(wxColour(0,0,0));
this->transparent_brush.SetStyle(wxBRUSHSTYLE_TRANSPARENT);
this->grid_pen.SetColour(settings->color->BED_GRID());
this->grid_pen.SetWidth(1);
this->grid_pen.SetStyle(wxPENSTYLE_SOLID);
this->print_center_pen.SetColour(settings->color->BED_CENTER());
this->print_center_pen.SetWidth(1);
this->print_center_pen.SetStyle(wxPENSTYLE_SOLID);
this->clearance_pen.SetColour(settings->color->BED_CLEARANCE());
this->clearance_pen.SetWidth(1);
this->clearance_pen.SetStyle(wxPENSTYLE_SOLID);
this->skirt_pen.SetColour(settings->color->BED_SKIRT());
this->skirt_pen.SetWidth(1);
this->skirt_pen.SetStyle(wxPENSTYLE_SOLID);
this->dark_pen.SetColour(settings->color->BED_DARK());
this->dark_pen.SetWidth(1);
this->dark_pen.SetStyle(wxPENSTYLE_SOLID);
}
void Plate2D::nudge_key(wxKeyEvent& e) {
const auto key = e.GetKeyCode();
switch( key ) {
case WXK_LEFT:
this->nudge(MoveDirection::Left);
case WXK_RIGHT:
this->nudge(MoveDirection::Right);
case WXK_DOWN:
this->nudge(MoveDirection::Down);
case WXK_UP:
this->nudge(MoveDirection::Up);
default:
break; // do nothing
}
}
void Plate2D::nudge(MoveDirection dir) {
if (this->selected_instance < this->objects.size()) {
auto i = 0U;
for (auto& obj : this->objects) {
if (obj.selected) {
if (obj.selected_instance != -1) {
}
}
i++;
}
}
if (selected_instance >= this->objects.size()) {
Slic3r::Log::warn(LogChannel, L"Nudge failed because there is no selected instance.");
return; // Abort
}
}
void Plate2D::update_bed_size() {
const auto& canvas_size {this->GetSize()};
const auto& canvas_w {canvas_size.GetWidth()};
const auto& canvas_h {canvas_size.GetHeight()};
if (canvas_w == 0) return; // Abort early if we haven't drawn canvas yet.
this->bed_polygon = Slic3r::Polygon(scale(dynamic_cast<ConfigOptionPoints*>(config->optptr("bed_shape"))->values));
const auto& polygon = bed_polygon;
const auto& bb = bed_polygon.bounding_box();
const auto& size = bb.size();
this->scaling_factor = std::min(static_cast<double>(canvas_w) / unscale(size.x), static_cast<double>(canvas_h) / unscale(size.y));
this->bed_origin = wxPoint(
canvas_w / 2.0 - (unscale(bb.max.x + bb.min.x)/2.0 * this->scaling_factor),
canvas_h - (canvas_h / 2.0 - (unscale(bb.max.y + bb.min.y)/2.0 * this->scaling_factor))
);
const auto& center = bb.center();
this->print_center = wxPoint(unscale(center.x), unscale(center.y));
// Cache bed contours and grid
{
const auto& step { scale_(10.0) }; // want a 10mm step for the lines
auto grid {Polylines()};
for (coord_t x = (bb.min.x - (bb.min.x % step) + step); x < bb.max.x; x += step) {
grid.push_back(Polyline());
grid.back().append(Point(x, bb.min.y));
grid.back().append(Point(x, bb.max.y));
};
for (coord_t y = (bb.min.y - (bb.min.y % step) + step); y < bb.max.y; y += step) {
grid.push_back(Polyline());
grid.back().append(Point(bb.min.x, y));
grid.back().append(Point(bb.max.x, y));
};
grid = intersection_pl(grid, polygon);
for (auto& i : grid) {
const auto& tmpline { this->scaled_points_to_pixel(i, 1) };
this->grid.insert(this->grid.end(), tmpline.begin(), tmpline.end());
}
}
}
std::vector<wxPoint> Plate2D::scaled_points_to_pixel(const Slic3r::Polygon& poly, bool unscale) {
return this->scaled_points_to_pixel(Polyline(poly), unscale);
}
std::vector<wxPoint> Plate2D::scaled_points_to_pixel(const Slic3r::Polyline& poly, bool _unscale) {
std::vector<wxPoint> result;
for (const auto& pt : poly.points) {
const auto x {_unscale ? Slic3r::unscale(pt.x) : pt.x};
const auto y {_unscale ? Slic3r::unscale(pt.y) : pt.y};
result.push_back(wxPoint(x, y));
}
return result;
}
wxPoint Plate2D::unscaled_point_to_pixel(const wxPoint& in) {
const auto& canvas_height {this->GetSize().GetHeight()};
const auto& zero = this->bed_origin;
return wxPoint(in.x * this->scaling_factor + zero.x,
in.y * this->scaling_factor + (zero.y - canvas_height));
}
} } // Namespace Slic3r::GUI
<|endoftext|> |
<commit_before>// Module: Log4CPLUS
// File: consoleappender.cxx
// Created: 6/2001
// Author: Tad E. Smith
//
//
// Copyright (C) The Apache Software Foundation. All rights reserved.
//
// This software is published under the terms of the Apache Software
// License version 1.1, a copy of which has been included with this
// distribution in the LICENSE.APL file.
//
#include <log4cplus/layout.h>
#include <log4cplus/consoleappender.h>
#include <log4cplus/helpers/loglog.h>
#include <log4cplus/spi/loggingevent.h>
#include <iostream>
using namespace std;
using namespace log4cplus::helpers;
log4cplus::ConsoleAppender::ConsoleAppender()
{
setLayout( std::auto_ptr<Layout>(new TTCCLayout()) );
}
log4cplus::ConsoleAppender::~ConsoleAppender()
{
destructorImpl();
}
void
log4cplus::ConsoleAppender::close()
{
getLogLog().debug("Entering ConsoleAppender::close()..");
}
// Normally, append() methods do not need to be locked since they are
// called by doAppend() which performs the locking. However, this locks
// on the LogLog instance, so we don't have multiple threads writing to
// cout and cerr
void
log4cplus::ConsoleAppender::append(const spi::InternalLoggingEvent& event)
{
LOG4CPLUS_BEGIN_SYNCHRONIZE_ON_MUTEX( getLogLog().mutex )
layout->formatAndAppend(cout, event);
LOG4CPLUS_END_SYNCHRONIZE_ON_MUTEX
}
<commit_msg>Added the ConsoleAppender(log4cplus::helpers::Properties properties) ctor.<commit_after>// Module: Log4CPLUS
// File: consoleappender.cxx
// Created: 6/2001
// Author: Tad E. Smith
//
//
// Copyright (C) The Apache Software Foundation. All rights reserved.
//
// This software is published under the terms of the Apache Software
// License version 1.1, a copy of which has been included with this
// distribution in the LICENSE.APL file.
//
#include <log4cplus/layout.h>
#include <log4cplus/consoleappender.h>
#include <log4cplus/helpers/loglog.h>
#include <log4cplus/spi/loggingevent.h>
#include <iostream>
using namespace std;
using namespace log4cplus::helpers;
log4cplus::ConsoleAppender::ConsoleAppender()
{
}
log4cplus::ConsoleAppender::ConsoleAppender(log4cplus::helpers::Properties properties)
: Appender(properties)
{
}
log4cplus::ConsoleAppender::~ConsoleAppender()
{
destructorImpl();
}
void
log4cplus::ConsoleAppender::close()
{
getLogLog().debug("Entering ConsoleAppender::close()..");
}
// Normally, append() methods do not need to be locked since they are
// called by doAppend() which performs the locking. However, this locks
// on the LogLog instance, so we don't have multiple threads writing to
// cout and cerr
void
log4cplus::ConsoleAppender::append(const spi::InternalLoggingEvent& event)
{
LOG4CPLUS_BEGIN_SYNCHRONIZE_ON_MUTEX( getLogLog().mutex )
layout->formatAndAppend(cout, event);
LOG4CPLUS_END_SYNCHRONIZE_ON_MUTEX
}
<|endoftext|> |
<commit_before>/** ==========================================================================
* 2011 by KjellKod.cc, modified by Vrecan in https://bitbucket.org/vrecan/g2log-dev
* 2015, adopted by KjellKod for g3log at:https://github.com/KjellKod/g3sinks
*
* This code is PUBLIC DOMAIN to use at your own risk and comes
* with no warranties. This code is yours to share, use and modify with no
* strings attached and no restrictions or obligations.
* ============================================================================*
* PUBLIC DOMAIN and Not copywrited. First published at KjellKod.cc
* ********************************************* */
#pragma once
#include <cstdio>
#include <string>
#include <memory>
#include <fstream>
#include <algorithm>
#include <future>
#include <cassert>
#include <chrono>
#include <g3log/time.hpp>
#include <zlib.h>
#include <boost/filesystem.hpp>
#include <boost/regex.hpp>
#include <map>
#include <vector>
#include <ctime>
#include <iostream>
namespace {
using steady_time_point = std::chrono::time_point<std::chrono::steady_clock>;
static const std::string file_name_time_formatted = "%Y%m%d-%H%M%S";
// check for filename validity - filename should not be part of PATH
bool isValidFilename(const std::string& prefix_filename) {
std::string illegal_characters("/,|<>:#$%{}()[]\'\"^!?+* ");
size_t pos = prefix_filename.find_first_of(illegal_characters, 0);
if (pos != std::string::npos) {
std::cerr << "Illegal character [" << prefix_filename.at(pos) << "] in logname prefix: " << "[" << prefix_filename << "]" << std::endl;
return false;
} else if (prefix_filename.empty()) {
std::cerr << "Empty filename prefix is not allowed" << std::endl;
return false;
}
return true;
}
/// @return a corrected prefix, if needed,
/// illegal characters are removed from @param prefix input
std::string prefixSanityFix(std::string prefix) {
prefix.erase(std::remove_if(prefix.begin(), prefix.end(), ::isspace), prefix.end());
prefix.erase(std::remove(prefix.begin(), prefix.end(), '/'), prefix.end()); // '/'
prefix.erase(std::remove(prefix.begin(), prefix.end(), '\\'), prefix.end()); // '\\'
prefix.erase(std::remove(prefix.begin(), prefix.end(), '.'), prefix.end()); // '.'
if (!isValidFilename(prefix)) {
return "";
}
return prefix;
}
/// @return the file header
std::string header() {
std::ostringstream ss_entry;
// Day Month Date Time Year: is written as "%a %b %d %H:%M:%S %Y" and formatted output as : Wed Sep 19 08:28:16 2012
ss_entry << "\ng3log: created log file at: " << g3::localtime_formatted(g3::systemtime_now(), "%a %b %d %H:%M:%S %Y") << "\n";
return ss_entry.str();
}
/// @return result as time from the file name
bool getDateFromFileName(const std::string& app_name, const std::string& file_name, long& result) {
if (file_name.find(app_name) != std::string::npos) {
std::string suffix = file_name.substr(app_name.size());
if (suffix.empty()) {
//this is the main log file
return false;
}
boost::regex date_regex("\\.(\\d{4}-\\d{2}-\\d{2}-\\d{2}-\\d{2}-\\d{2})\\.gz");
boost::smatch date_match;
if (boost::regex_match(suffix, date_match, date_regex)) {
if (date_match.size() == 2) {
std::string date = date_match[1].str();
struct tm tm;
time_t t;
if (strptime(date.c_str(), "%Y-%m-%d-%H-%M-%S", &tm) == NULL) {
return false;
}
t = mktime(&tm);
if (t == -1) {
return false;
}
result = (long) t;
return true;
}
}
}
return false;
}
/**
* Loop through the files in the folder
* @param dir
* @param file_name
*/
void expireArchives(const std::string dir, const std::string& app_name, unsigned long max_log_count) {
std::map<long, std::string> files;
boost::filesystem::path dir_path(dir);
if (!boost::filesystem::exists(dir_path)) return;
boost::filesystem::directory_iterator end_itr;
for (boost::filesystem::directory_iterator itr(dir_path);
itr != end_itr;
++itr) {
std::string current_file(itr->path().filename().c_str());
long time;
if (getDateFromFileName(app_name, current_file, time)) {
files.insert(std::pair<long, std::string > (time, current_file));
}
}
//delete old logs.
int logs_to_delete = files.size() - max_log_count;
if (logs_to_delete > 0) {
for (std::map<long, std::string>::iterator it = files.begin(); it != files.end(); ++it) {
if (logs_to_delete <= 0) {
break;
}
std::stringstream ss;
ss << dir.c_str() << it->second.c_str();
remove(ss.str().c_str());
--logs_to_delete;
}
}
}
/// create the file name
std::string createLogFileName(const std::string& verified_prefix) {
std::stringstream oss_name;
oss_name << verified_prefix << ".log";
return oss_name.str();
}
/// @return true if @param complete_file_with_path could be opened
/// @param outstream is the file stream
bool openLogFile(const std::string& complete_file_with_path, std::ofstream& outstream) {
std::ios_base::openmode mode = std::ios_base::out; // for clarity: it's really overkill since it's an ofstream
mode |= std::ios_base::app;
outstream.open(complete_file_with_path, mode);
if (!outstream.is_open()) {
std::ostringstream ss_error;
ss_error << "FILE ERROR: could not open log file:[" << complete_file_with_path << "]";
ss_error << "\n\t\t std::ios_base state = " << outstream.rdstate();
std::cerr << ss_error.str().c_str() << std::endl;
outstream.close();
return false;
}
return true;
}
/// create the file
std::unique_ptr<std::ofstream> createLogFile(const std::string& file_with_full_path) {
std::unique_ptr<std::ofstream> out(new std::ofstream);
std::ofstream& stream(*(out.get()));
bool success_with_open_file = openLogFile(file_with_full_path, stream);
if (false == success_with_open_file) {
out.release();
}
return out;
}
} // anonymous
/** The Real McCoy Background worker, while g3::LogWorker gives the
* asynchronous API to put job in the background the LogRotateHelper
* does the actual background thread work */
struct LogRotateHelper {
LogRotateHelper& operator=(const LogRotateHelper&) = delete;
LogRotateHelper(const LogRotateHelper& other) = delete;
LogRotateHelper(const std::string& log_prefix, const std::string& log_directory);
~LogRotateHelper();
void setMaxArchiveLogCount(int size);
void setMaxLogSize(int size);
void fileWrite(std::string message);
std::string changeLogFile(const std::string& directory, const std::string& new_name = "");
std::string logFileName();
bool archiveLog();
void addLogFileHeader();
bool rotateLog();
bool createCompressedFile(std::string file_name, std::string gzip_file_name);
std::ofstream& filestream() {
return *(outptr_.get());
}
std::string log_file_with_path_;
std::string log_directory_;
std::string log_prefix_backup_;
std::unique_ptr<std::ofstream> outptr_;
steady_time_point steady_start_time_;
int max_log_size_;
int max_archive_log_count_;
};
LogRotateHelper::LogRotateHelper(const std::string& log_prefix, const std::string& log_directory)
: log_file_with_path_(log_directory)
, log_directory_(log_directory)
, log_prefix_backup_(log_prefix)
, outptr_(new std::ofstream)
, steady_start_time_(std::chrono::steady_clock::now()) { // TODO: ha en timer function steadyTimer som har koll på start
log_prefix_backup_ = prefixSanityFix(log_prefix);
max_log_size_ = 524288000;
max_archive_log_count_ = 10;
if (!isValidFilename(log_prefix_backup_)) {
std::cerr << "g3log: forced abort due to illegal log prefix [" << log_prefix << "]" << std::endl;
abort();
}
std::string file_name = createLogFileName(log_prefix_backup_);
log_file_with_path_ = log_directory + file_name;
outptr_ = createLogFile(log_file_with_path_);
assert((nullptr != outptr_) && "cannot open log file at startup");
addLogFileHeader();
}
/**
* Max number of archived logs to keep.
* @param max_size
*/
void LogRotateHelper::setMaxArchiveLogCount(int max_size) {
max_archive_log_count_ = max_size;
}
/**
* Set the max file size in bytes.
* @param max_size
*/
void LogRotateHelper::setMaxLogSize(int max_size) {
max_log_size_ = max_size;
}
LogRotateHelper::~LogRotateHelper() {
std::ostringstream ss_exit;
ss_exit << "\ng2log file shutdown at: " << g3::localtime_formatted(g3::systemtime_now(), g3::internal::time_formatted) << "\n\n";
filestream() << ss_exit.str() << std::flush;
}
void LogRotateHelper::fileWrite(std::string message) {
rotateLog();
std::ofstream& out(filestream());
out << message << std::flush;
}
std::string LogRotateHelper::changeLogFile(const std::string& directory, const std::string& new_name) {
std::string file_name = new_name;
if (file_name.empty()) {
std::cout << "no filename" << std::endl;
file_name = createLogFileName(log_prefix_backup_);
}
std::string prospect_log = directory + file_name;
std::unique_ptr<std::ofstream> log_stream = createLogFile(prospect_log);
if (nullptr == log_stream) {
fileWrite("Unable to change log file. Illegal filename or busy? Unsuccessful log name was:" + prospect_log);
return ""; // no success
}
addLogFileHeader();
std::ostringstream ss_change;
std::string old_log = log_file_with_path_;
log_file_with_path_ = prospect_log;
outptr_ = std::move(log_stream);
log_directory_ = directory;
return log_file_with_path_;
}
/**
* Rotate the logs once they have exceeded our set size.
* @return
*/
bool LogRotateHelper::rotateLog() {
std::ofstream& is(filestream());
if (is.is_open()) {
// get length of file:
is.seekp(0, std::ios::end);
int length = is.tellp();
is.seekp(0, std::ios::beg);
if (length > max_log_size_) {
std::ostringstream gz_file_name;
gz_file_name << log_file_with_path_ << ".";
gz_file_name << g3::localtime_formatted(g3::systemtime_now(), "%Y-%m-%d-%H-%M-%S");
gz_file_name << ".gz";
if (!createCompressedFile(log_file_with_path_, gz_file_name.str())) {
fileWrite("Failed to compress log!");
return false;
}
is.close();
if (remove(log_file_with_path_.c_str()) == -1) {
fileWrite("Failed to remove old log!");
}
changeLogFile(log_directory_);
std::ostringstream ss;
ss << "Log rotated Archived file name: " << gz_file_name.str().c_str();
fileWrite(ss.str());
ss.clear();
ss.str("");
ss << log_prefix_backup_ << ".log";
expireArchives(log_directory_, ss.str(), max_archive_log_count_);
return true;
}
}
return false;
}
/**
* Create a compressed file of the current log.
* @param file_name
* @param gzip_file_name
* @return
*/
bool LogRotateHelper::createCompressedFile(std::string file_name, std::string gzip_file_name) {
int buffer_size = 16184;
char buffer[buffer_size];
FILE* input = fopen(file_name.c_str(), "rb");
gzFile output = gzopen(gzip_file_name.c_str(), "wb");
if (input == NULL || output == NULL) {
return false;
}
int N;
while ((N = fread(buffer, 1, buffer_size, input)) > 0) {
gzwrite(output, buffer, N);
}
if (gzclose(output) != Z_OK);
if (fclose(input) != 0) {
return false;
}
return true;
}
std::string LogRotateHelper::logFileName() {
return log_file_with_path_;
}
void LogRotateHelper::addLogFileHeader() {
filestream() << header();
}
<commit_msg>Update LogRotateHelper.ipp<commit_after>/** ==========================================================================
* 2011 by KjellKod.cc, modified by Vrecan in https://bitbucket.org/vrecan/g2log-dev
* 2015, adopted by KjellKod for g3log at:https://github.com/KjellKod/g3sinks
*
* This code is PUBLIC DOMAIN to use at your own risk and comes
* with no warranties. This code is yours to share, use and modify with no
* strings attached and no restrictions or obligations.
* ============================================================================*
* PUBLIC DOMAIN and Not copywrited. First published at KjellKod.cc
* ********************************************* */
#pragma once
#include <cstdio>
#include <string>
#include <memory>
#include <fstream>
#include <algorithm>
#include <future>
#include <cassert>
#include <chrono>
#include <g3log/time.hpp>
#include <zlib.h>
#include <boost/filesystem.hpp>
#include <boost/regex.hpp>
#include <map>
#include <vector>
#include <ctime>
#include <iostream>
namespace {
using steady_time_point = std::chrono::time_point<std::chrono::steady_clock>;
static const std::string file_name_time_formatted = "%Y%m%d-%H%M%S";
// check for filename validity - filename should not be part of PATH
bool isValidFilename(const std::string& prefix_filename) {
std::string illegal_characters("/,|<>:#$%{}()[]\'\"^!?+* ");
size_t pos = prefix_filename.find_first_of(illegal_characters, 0);
if (pos != std::string::npos) {
std::cerr << "Illegal character [" << prefix_filename.at(pos) << "] in logname prefix: " << "[" << prefix_filename << "]" << std::endl;
return false;
} else if (prefix_filename.empty()) {
std::cerr << "Empty filename prefix is not allowed" << std::endl;
return false;
}
return true;
}
/// @return a corrected prefix, if needed,
/// illegal characters are removed from @param prefix input
std::string prefixSanityFix(std::string prefix) {
prefix.erase(std::remove_if(prefix.begin(), prefix.end(), ::isspace), prefix.end());
prefix.erase(std::remove(prefix.begin(), prefix.end(), '/'), prefix.end()); // '/'
prefix.erase(std::remove(prefix.begin(), prefix.end(), '\\'), prefix.end()); // '\\'
prefix.erase(std::remove(prefix.begin(), prefix.end(), '.'), prefix.end()); // '.'
if (!isValidFilename(prefix)) {
return "";
}
return prefix;
}
/// @return the file header
std::string header() {
std::ostringstream ss_entry;
// Day Month Date Time Year: is written as "%a %b %d %H:%M:%S %Y" and formatted output as : Wed Sep 19 08:28:16 2012
ss_entry << "\ng3log: created log file at: " << g3::localtime_formatted(g3::systemtime_now(), "%a %b %d %H:%M:%S %Y") << "\n";
return ss_entry.str();
}
/// @return result as time from the file name
bool getDateFromFileName(const std::string& app_name, const std::string& file_name, long& result) {
if (file_name.find(app_name) != std::string::npos) {
std::string suffix = file_name.substr(app_name.size());
if (suffix.empty()) {
//this is the main log file
return false;
}
boost::regex date_regex("\\.(\\d{4}-\\d{2}-\\d{2}-\\d{2}-\\d{2}-\\d{2})\\.gz");
boost::smatch date_match;
if (boost::regex_match(suffix, date_match, date_regex)) {
if (date_match.size() == 2) {
std::string date = date_match[1].str();
struct tm tm;
time_t t;
if (strptime(date.c_str(), "%Y-%m-%d-%H-%M-%S", &tm) == NULL) {
return false;
}
t = mktime(&tm);
if (t == -1) {
return false;
}
result = (long) t;
return true;
}
}
}
return false;
}
/**
* Loop through the files in the folder
* @param dir
* @param file_name
*/
void expireArchives(const std::string dir, const std::string& app_name, unsigned long max_log_count) {
std::map<long, std::string> files;
boost::filesystem::path dir_path(dir);
if (!boost::filesystem::exists(dir_path)) return;
boost::filesystem::directory_iterator end_itr;
for (boost::filesystem::directory_iterator itr(dir_path);
itr != end_itr;
++itr) {
std::string current_file(itr->path().filename().c_str());
long time;
if (getDateFromFileName(app_name, current_file, time)) {
files.insert(std::pair<long, std::string > (time, current_file));
}
}
//delete old logs.
int logs_to_delete = files.size() - max_log_count;
if (logs_to_delete > 0) {
for (std::map<long, std::string>::iterator it = files.begin(); it != files.end(); ++it) {
if (logs_to_delete <= 0) {
break;
}
std::stringstream ss;
ss << dir.c_str() << it->second.c_str();
remove(ss.str().c_str());
--logs_to_delete;
}
}
}
/// create the file name
std::string createLogFileName(const std::string& verified_prefix) {
std::stringstream oss_name;
oss_name << verified_prefix << ".log";
return oss_name.str();
}
/// @return true if @param complete_file_with_path could be opened
/// @param outstream is the file stream
bool openLogFile(const std::string& complete_file_with_path, std::ofstream& outstream) {
std::ios_base::openmode mode = std::ios_base::out; // for clarity: it's really overkill since it's an ofstream
mode |= std::ios_base::app;
outstream.open(complete_file_with_path, mode);
if (!outstream.is_open()) {
std::ostringstream ss_error;
ss_error << "FILE ERROR: could not open log file:[" << complete_file_with_path << "]";
ss_error << "\n\t\t std::ios_base state = " << outstream.rdstate();
std::cerr << ss_error.str().c_str() << std::endl;
outstream.close();
return false;
}
return true;
}
/// create the file
std::unique_ptr<std::ofstream> createLogFile(const std::string& file_with_full_path) {
std::unique_ptr<std::ofstream> out(new std::ofstream);
std::ofstream& stream(*(out.get()));
bool success_with_open_file = openLogFile(file_with_full_path, stream);
if (false == success_with_open_file) {
out.release();
}
return out;
}
} // anonymous
/** The Real McCoy Background worker, while g3::LogWorker gives the
* asynchronous API to put job in the background the LogRotateHelper
* does the actual background thread work */
struct LogRotateHelper {
LogRotateHelper& operator=(const LogRotateHelper&) = delete;
LogRotateHelper(const LogRotateHelper& other) = delete;
LogRotateHelper(const std::string& log_prefix, const std::string& log_directory);
~LogRotateHelper();
void setMaxArchiveLogCount(int size);
void setMaxLogSize(int size);
void fileWrite(std::string message);
std::string changeLogFile(const std::string& directory, const std::string& new_name = "");
std::string logFileName();
bool archiveLog();
void addLogFileHeader();
bool rotateLog();
bool createCompressedFile(std::string file_name, std::string gzip_file_name);
std::ofstream& filestream() {
return *(outptr_.get());
}
std::string log_file_with_path_;
std::string log_directory_;
std::string log_prefix_backup_;
std::unique_ptr<std::ofstream> outptr_;
steady_time_point steady_start_time_;
int max_log_size_;
int max_archive_log_count_;
};
LogRotateHelper::LogRotateHelper(const std::string& log_prefix, const std::string& log_directory)
: log_file_with_path_(log_directory)
, log_directory_(log_directory)
, log_prefix_backup_(log_prefix)
, outptr_(new std::ofstream)
, steady_start_time_(std::chrono::steady_clock::now()) { // TODO: ha en timer function steadyTimer som har koll på start
log_prefix_backup_ = prefixSanityFix(log_prefix);
max_log_size_ = 524288000;
max_archive_log_count_ = 10;
if (!isValidFilename(log_prefix_backup_)) {
std::cerr << "g3log: forced abort due to illegal log prefix [" << log_prefix << "]" << std::endl;
abort();
}
std::string file_name = createLogFileName(log_prefix_backup_);
log_file_with_path_ = log_directory + file_name;
outptr_ = createLogFile(log_file_with_path_);
assert((nullptr != outptr_) && "cannot open log file at startup");
addLogFileHeader();
}
/**
* Max number of archived logs to keep.
* @param max_size
*/
void LogRotateHelper::setMaxArchiveLogCount(int max_size) {
max_archive_log_count_ = max_size;
}
/**
* Set the max file size in bytes.
* @param max_size
*/
void LogRotateHelper::setMaxLogSize(int max_size) {
max_log_size_ = max_size;
}
LogRotateHelper::~LogRotateHelper() {
std::ostringstream ss_exit;
ss_exit << "\ng3log file shutdown at: " << g3::localtime_formatted(g3::systemtime_now(), g3::internal::time_formatted) << "\n\n";
filestream() << ss_exit.str() << std::flush;
}
void LogRotateHelper::fileWrite(std::string message) {
rotateLog();
std::ofstream& out(filestream());
out << message << std::flush;
}
std::string LogRotateHelper::changeLogFile(const std::string& directory, const std::string& new_name) {
std::string file_name = new_name;
if (file_name.empty()) {
std::cout << "no filename" << std::endl;
file_name = createLogFileName(log_prefix_backup_);
}
std::string prospect_log = directory + file_name;
std::unique_ptr<std::ofstream> log_stream = createLogFile(prospect_log);
if (nullptr == log_stream) {
fileWrite("Unable to change log file. Illegal filename or busy? Unsuccessful log name was:" + prospect_log);
return ""; // no success
}
addLogFileHeader();
std::ostringstream ss_change;
std::string old_log = log_file_with_path_;
log_file_with_path_ = prospect_log;
outptr_ = std::move(log_stream);
log_directory_ = directory;
return log_file_with_path_;
}
/**
* Rotate the logs once they have exceeded our set size.
* @return
*/
bool LogRotateHelper::rotateLog() {
std::ofstream& is(filestream());
if (is.is_open()) {
// get length of file:
is.seekp(0, std::ios::end);
int length = is.tellp();
is.seekp(0, std::ios::beg);
if (length > max_log_size_) {
std::ostringstream gz_file_name;
gz_file_name << log_file_with_path_ << ".";
gz_file_name << g3::localtime_formatted(g3::systemtime_now(), "%Y-%m-%d-%H-%M-%S");
gz_file_name << ".gz";
if (!createCompressedFile(log_file_with_path_, gz_file_name.str())) {
fileWrite("Failed to compress log!");
return false;
}
is.close();
if (remove(log_file_with_path_.c_str()) == -1) {
fileWrite("Failed to remove old log!");
}
changeLogFile(log_directory_);
std::ostringstream ss;
ss << "Log rotated Archived file name: " << gz_file_name.str().c_str();
fileWrite(ss.str());
ss.clear();
ss.str("");
ss << log_prefix_backup_ << ".log";
expireArchives(log_directory_, ss.str(), max_archive_log_count_);
return true;
}
}
return false;
}
/**
* Create a compressed file of the current log.
* @param file_name
* @param gzip_file_name
* @return
*/
bool LogRotateHelper::createCompressedFile(std::string file_name, std::string gzip_file_name) {
int buffer_size = 16184;
char buffer[buffer_size];
FILE* input = fopen(file_name.c_str(), "rb");
gzFile output = gzopen(gzip_file_name.c_str(), "wb");
if (input == NULL || output == NULL) {
return false;
}
int N;
while ((N = fread(buffer, 1, buffer_size, input)) > 0) {
gzwrite(output, buffer, N);
}
if (gzclose(output) != Z_OK);
if (fclose(input) != 0) {
return false;
}
return true;
}
std::string LogRotateHelper::logFileName() {
return log_file_with_path_;
}
void LogRotateHelper::addLogFileHeader() {
filestream() << header();
}
<|endoftext|> |
<commit_before>/*!
@file
@copyright Edouard Alligand and Joel Falcou 2015-2017
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_BRIGAND_FUNCTIONS_BITWISE_HPP
#define BOOST_BRIGAND_FUNCTIONS_BITWISE_HPP
#include <brigand/functions/bitwise/bitand.hpp>
#include <brigand/functions/bitwise/bitor.hpp>
#include <brigand/functions/bitwise/bitxor.hpp>
#include <brigand/functions/bitwise/shift_left.hpp>
#include <brigand/functions/bitwise/shift_right.hpp>
#endif
<commit_msg>Delete bitwise.hpp<commit_after><|endoftext|> |
<commit_before>#ifndef HOUGH_IMAGE_HH
#define HOUGH_IMAGE_HH
#include <ctime>
#include <cstdlib>
#include <opencv2/highgui.hpp>
#include <vpp/vpp.hh>
#include <Eigen/Core>
#include <vpp/utils/opencv_bridge.hh>
#include <vpp/utils/opencv_utils.hh>
#include "boost/intrusive/list.hpp"
#include "dense_one_to_one_hough.hh"
#include "vpp/algorithms/Line_tracker_4_sfm/symbols.hh"
#include "vpp/algorithms/Line_tracker_4_sfm/miscellanous/define.hh"
using namespace vpp;
using namespace std;
using namespace Eigen;
using namespace iod;
using namespace cv;
namespace vpp{
float getVectorVal(std::vector<float> t_array, int vert,int hori,int i ,int j);
void Hough_Accumulator(image2d<uchar> img, int mode , int T_theta, Mat &bv, float acc_threshold);
cv::Mat Hough_Accumulator_Video_Map_and_Clusters(image2d<vuchar1> img, int mode , int T_theta,
std::vector<float>& t_accumulator, std::list<vint2>& interestedPoints,
float rhomax);
cv::Mat Hough_Accumulator_Video_Clusters(image2d<vuchar1> img, int mode , int T_theta,
std::vector<float>& t_accumulator,std::list<vint2>& interestedPoints,
float rhomax);
int getThetaMax(Theta_max discr);
cv::Mat accumulatorToFrame(std::vector<float> t_accumulator, float max, int rhomax, int T_theta);
cv::Mat accumulatorToFrame(std::list<vint2> interestedPoints, int rhomax, int T_theta);
void hough_image(int T_theta, float acc_threshold);
/*
template <typename... OPTS>
void Capture_Image(int mode, Theta_max discr , Sclare_rho scale
,Type_video_hough type_video
, Type_output type_sortie,
Type_Lines type_line,Frequence freq,Mode mode_type,
OPTS... options);*/
}
#include "fast_hough.hpp"
#endif // HOUGH_IMAGE_HH
<commit_msg>Update fast_hough.hh<commit_after>#ifndef HOUGH_IMAGE_HH
#define HOUGH_IMAGE_HH
#include <ctime>
#include <cstdlib>
#include <opencv2/highgui.hpp>
#include <vpp/vpp.hh>
#include <Eigen/Core>
#include <vpp/utils/opencv_bridge.hh>
#include <vpp/utils/opencv_utils.hh>
#include "boost/intrusive/list.hpp"
#include "dense_one_to_one_hough.hh"
#include "vpp/algorithms/Line_tracker_4_sfm/symbols.hh"
#include "vpp/algorithms/Line_tracker_4_sfm/miscellanous/define.hh"
using namespace vpp;
using namespace std;
using namespace Eigen;
using namespace iod;
using namespace cv;
namespace vpp{
float getVectorVal(std::vector<float> t_array, int vert,int hori,int i ,int j);
void Hough_Accumulator(image2d<uchar> img, int T_theta, Mat &bv, float acc_threshold);
cv::Mat Hough_Accumulator_Video_Map_and_Clusters(image2d<vuchar1> img, int mode , int T_theta,
std::vector<float>& t_accumulator, std::list<vint2>& interestedPoints,
float rhomax);
cv::Mat Hough_Accumulator_Video_Clusters(image2d<vuchar1> img, int mode , int T_theta,
std::vector<float>& t_accumulator,std::list<vint2>& interestedPoints,
float rhomax);
int getThetaMax(Theta_max discr);
cv::Mat accumulatorToFrame(std::vector<float> t_accumulator, float max, int rhomax, int T_theta);
cv::Mat accumulatorToFrame(std::list<vint2> interestedPoints, int rhomax, int T_theta);
void hough_image(int T_theta, float acc_threshold);
/*
template <typename... OPTS>
void Capture_Image(int mode, Theta_max discr , Sclare_rho scale
,Type_video_hough type_video
, Type_output type_sortie,
Type_Lines type_line,Frequence freq,Mode mode_type,
OPTS... options);*/
}
#include "fast_hough.hpp"
#endif // HOUGH_IMAGE_HH
<|endoftext|> |
<commit_before>#include "kernel.h"
#include "errorobject.h"
#include "complexdrawer.h"
using namespace Ilwis;
using namespace Geodrawer;
ComplexDrawer::ComplexDrawer(const QString &name,
DrawerInterface* parentDrawer,
RootDrawer *rootdrawer,
const IOOptions &options) : BaseDrawer(name, parentDrawer, rootdrawer, options)
{
}
bool ComplexDrawer::draw(const IOOptions &options)
{
if (!isActive() || !isValid())
return false;
bool ok = drawSideDrawers( _preDrawers, options) ;
for(const auto& drawer : _mainDrawers){
if ( drawer){
ok &= drawer->draw( options);
}
}
ok &= drawSideDrawers(_postDrawers, options);
return ok;
}
bool ComplexDrawer::prepare(DrawerInterface::PreparationType prepType, const IOOptions &options)
{
BaseDrawer::prepare(prepType, options);
for( auto& drawer : _preDrawers) {
if (!drawer.second->prepare(prepType, options))
return false;
}
for( auto& drawer : _mainDrawers){
if (!drawer->prepare(prepType, options))
return false;
}
for( auto& drawer : _postDrawers) {
if (!drawer.second->prepare(prepType, options))
return false;
}
return true;
}
void ComplexDrawer::unprepare(DrawerInterface::PreparationType prepType)
{
BaseDrawer::unprepare(prepType);
for( auto& drawer : _preDrawers) {
drawer.second->unprepare(prepType);
}
for( auto& drawer : _mainDrawers){
drawer->unprepare(prepType);
}
for( auto& drawer : _postDrawers) {
drawer.second->unprepare(prepType);
}
}
bool ComplexDrawer::prepareChildDrawers(DrawerInterface::PreparationType prepType, const IOOptions &options)
{
for(auto& drawer : _mainDrawers){
if ( drawer && drawer->isValid())
drawer->prepare(prepType, options);
}
return true;
}
quint32 ComplexDrawer::drawerCount(DrawerInterface::DrawerType tpe) const
{
switch(tpe){
case dtPRE:
return _postDrawers.size();
case dtMAIN:
return _mainDrawers.size();
case dtPOST:
return _postDrawers.size();
default:
return _postDrawers.size() + _preDrawers.size() + _mainDrawers.size();;
}
return iUNDEF;
}
const UPDrawer &ComplexDrawer::drawer(quint32 order, DrawerInterface::DrawerType drawerType) const
{
if ( drawerType == dtPOST || drawerType == dtPRE){
const DrawerMap& drawers = drawerType == dtPRE ? _preDrawers : _postDrawers;
const auto& current = drawers.find(order);
if ( current == drawers.end())
throw VisualizationError(TR("Invalid drawer number used while drawing"));
return current->second;
} else if ( drawerType == dtMAIN){
if ( order < _mainDrawers.size()){
return _mainDrawers[order];
}
}
throw VisualizationError(TR(QString("Drawer number %1 is not valid").arg(order)));
}
void ComplexDrawer::addDrawer(DrawerInterface *drawer, DrawerInterface::DrawerType drawerType, quint32 order,const QString &nme)
{
if ( !drawer)
return;
QString drawername = nme;
if ( drawerType == dtPOST || drawerType == dtPRE){
if ( order != iUNDEF){
DrawerMap& drawers = drawerType == dtPRE ? _preDrawers : _postDrawers;
drawers[order].reset(drawer);
if ( drawername == sUNDEF){
drawername = (drawerType == dtPOST ? "post_drawer_" : "pre_drawer_") + QString::number(drawer->id()) + "_" + QString::number(order);
}
}
}else if ( drawerType == dtMAIN){
UPDrawer drawerp(drawer);
_mainDrawers.push_back(std::move(drawerp));
if ( drawername == sUNDEF){
drawername = "drawer_layer_" + QString::number(drawer->id());
}
}
drawer->name(drawername);
}
void ComplexDrawer::setDrawer(quint32 order, DrawerInterface *drawer, DrawerInterface::DrawerType drawerType)
{
if ( drawerType == dtPOST || drawerType == dtPRE){
DrawerMap& drawers = drawerType == dtPRE ? _preDrawers : _postDrawers;
const auto& current = drawers.find(order);
if ( current == drawers.end()){
return;
}
drawers[order].reset(drawer);
} else if ( drawerType == dtMAIN){
if ( order < _mainDrawers.size()) {
_mainDrawers[order].reset(drawer);
}
}
}
void ComplexDrawer::removeDrawer(quint32 order, DrawerInterface::DrawerType drawerType)
{
if ( drawerType == dtPOST || drawerType == dtPRE){
DrawerMap& drawers = drawerType == dtPRE ? _preDrawers : _postDrawers;
auto current = drawers.find(order);
if ( current != drawers.end()){
(*current).second->cleanUp();
drawers.erase(current) ;
}
} else if ( drawerType == dtMAIN){
if ( order < _mainDrawers.size()) {
_mainDrawers[order]->cleanUp();
_mainDrawers.erase(_mainDrawers.begin() + order);
}
}
}
void ComplexDrawer::removeDrawer(const QString &idcode, bool ascode)
{
std::vector<quint32> selectedDrawers;
for( auto& drawer : _preDrawers){
if ( ascode){
if (drawer.second->code() == idcode){
selectedDrawers.push_back(drawer.first);
}
} else {
if (drawer.second->name() == idcode){
selectedDrawers.push_back(drawer.first);
}
}
}
for(auto order : selectedDrawers)
removeDrawer(order, DrawerInterface::dtPRE);
selectedDrawers.clear();
int count = 0;
for( auto& drawer : _mainDrawers){
if ( ascode){
if (drawer->code() == idcode){
selectedDrawers.push_back(count);
}
} else {
if (drawer->name() == idcode){
selectedDrawers.push_back(count);
}
}
++count;
}
for(auto order : selectedDrawers)
removeDrawer(order, DrawerInterface::dtMAIN);
selectedDrawers.clear();
for( auto& drawer : _postDrawers) {
if ( ascode){
if (drawer.second->code() == idcode){
selectedDrawers.push_back(drawer.first);
}
} else {
if (drawer.second->name() == idcode){
selectedDrawers.push_back(drawer.first);
}
}
}
for(auto order : selectedDrawers)
removeDrawer(order, DrawerInterface::dtPOST);
}
bool ComplexDrawer::drawerAttribute(const QString &drawercode, const QString &key, const QVariant &value)
{
if ( drawercode == code()){
setAttribute(key, value);
return true;
}
for( auto& drawer : _preDrawers){
if (drawer.second->drawerAttribute(drawercode, key, value))
return true;
}
for( auto& drawer : _mainDrawers){
if (drawer->drawerAttribute(drawercode, key, value))
return true;
}
for( auto& drawer : _postDrawers) {
if (drawer.second->drawerAttribute(drawercode, key, value))
return true;
}
return false;
}
bool ComplexDrawer::isSimple() const
{
return false;
}
void ComplexDrawer::cleanUp()
{
BaseDrawer::cleanUp();
for( auto& drawer : _preDrawers) {
drawer.second->cleanUp();
}
for( auto& drawer : _mainDrawers){
drawer->cleanUp();
}
for( auto& drawer : _postDrawers) {
drawer.second->cleanUp();
}
_preDrawers.clear();
_mainDrawers.clear();
_postDrawers.clear();
unprepare(ptALL);
}
bool ComplexDrawer::drawSideDrawers(const DrawerMap& drawers, const IOOptions &options) const
{
if (!isActive())
return false;
if ( drawers.size() > 0) {
for(const auto& current : drawers) {
const auto& drw = current.second;
if ( drw)
drw->draw(options);
}
}
return true;
}
std::vector<QVariant> ComplexDrawer::attributes(const QString &attrNames) const
{
std::vector<QVariant> results = BaseDrawer::attributes(attrNames);
QStringList parts = attrNames.split("|");
for(QString& part : parts)
part.toLower();
for(const QString& part : parts){
results.push_back(attribute(part));
}
return results;
}
QVariant ComplexDrawer::attribute(const QString &attrNme) const
{
QString attrName = attrNme.toLower();
QVariant var = BaseDrawer::attribute(attrName);
if ( var.isValid())
return var;
if ( attrName == "maindrawercount")
return drawerCount(DrawerInterface::dtMAIN);
if ( attrName == "predrawercount")
return drawerCount(DrawerInterface::dtPRE);
if ( attrName == "postdrawercount")
return drawerCount(DrawerInterface::dtPOST);
return QVariant();
}
QVariant ComplexDrawer::attributeOfDrawer(const QString &drawercode, const QString &attrName) const
{
if ( code() == drawercode)
return attribute(attrName);
QVariant var;
for( auto& drawer : _preDrawers){
var = drawer.second->attributeOfDrawer(drawercode, attrName);
if ( var.isValid())
return var;
}
for( auto& drawer : _mainDrawers){
var = drawer->attributeOfDrawer(drawercode, attrName);
if ( var.isValid())
return var;
}
for( auto& drawer : _postDrawers) {
var = drawer.second->attributeOfDrawer(drawercode, attrName);
if ( var.isValid())
return var;
}
return var;
}
<commit_msg>added blending mode<commit_after>#include "kernel.h"
#include "errorobject.h"
#include "complexdrawer.h"
using namespace Ilwis;
using namespace Geodrawer;
ComplexDrawer::ComplexDrawer(const QString &name,
DrawerInterface* parentDrawer,
RootDrawer *rootdrawer,
const IOOptions &options) : BaseDrawer(name, parentDrawer, rootdrawer, options)
{
}
bool ComplexDrawer::draw(const IOOptions &options)
{
if (!isActive() || !isValid())
return false;
bool ok = drawSideDrawers( _preDrawers, options) ;
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
for(const auto& drawer : _mainDrawers){
if ( drawer){
ok &= drawer->draw( options);
}
}
glDisable(GL_BLEND);
ok &= drawSideDrawers(_postDrawers, options);
return ok;
}
bool ComplexDrawer::prepare(DrawerInterface::PreparationType prepType, const IOOptions &options)
{
BaseDrawer::prepare(prepType, options);
for( auto& drawer : _preDrawers) {
if (!drawer.second->prepare(prepType, options))
return false;
}
for( auto& drawer : _mainDrawers){
if (!drawer->prepare(prepType, options))
return false;
}
for( auto& drawer : _postDrawers) {
if (!drawer.second->prepare(prepType, options))
return false;
}
return true;
}
void ComplexDrawer::unprepare(DrawerInterface::PreparationType prepType)
{
BaseDrawer::unprepare(prepType);
for( auto& drawer : _preDrawers) {
drawer.second->unprepare(prepType);
}
for( auto& drawer : _mainDrawers){
drawer->unprepare(prepType);
}
for( auto& drawer : _postDrawers) {
drawer.second->unprepare(prepType);
}
}
bool ComplexDrawer::prepareChildDrawers(DrawerInterface::PreparationType prepType, const IOOptions &options)
{
for(auto& drawer : _mainDrawers){
if ( drawer && drawer->isValid())
drawer->prepare(prepType, options);
}
return true;
}
quint32 ComplexDrawer::drawerCount(DrawerInterface::DrawerType tpe) const
{
switch(tpe){
case dtPRE:
return _postDrawers.size();
case dtMAIN:
return _mainDrawers.size();
case dtPOST:
return _postDrawers.size();
default:
return _postDrawers.size() + _preDrawers.size() + _mainDrawers.size();;
}
return iUNDEF;
}
const UPDrawer &ComplexDrawer::drawer(quint32 order, DrawerInterface::DrawerType drawerType) const
{
if ( drawerType == dtPOST || drawerType == dtPRE){
const DrawerMap& drawers = drawerType == dtPRE ? _preDrawers : _postDrawers;
const auto& current = drawers.find(order);
if ( current == drawers.end())
throw VisualizationError(TR("Invalid drawer number used while drawing"));
return current->second;
} else if ( drawerType == dtMAIN){
if ( order < _mainDrawers.size()){
return _mainDrawers[order];
}
}
throw VisualizationError(TR(QString("Drawer number %1 is not valid").arg(order)));
}
void ComplexDrawer::addDrawer(DrawerInterface *drawer, DrawerInterface::DrawerType drawerType, quint32 order,const QString &nme)
{
if ( !drawer)
return;
QString drawername = nme;
if ( drawerType == dtPOST || drawerType == dtPRE){
if ( order != iUNDEF){
DrawerMap& drawers = drawerType == dtPRE ? _preDrawers : _postDrawers;
drawers[order].reset(drawer);
if ( drawername == sUNDEF){
drawername = (drawerType == dtPOST ? "post_drawer_" : "pre_drawer_") + QString::number(drawer->id()) + "_" + QString::number(order);
}
}
}else if ( drawerType == dtMAIN){
UPDrawer drawerp(drawer);
_mainDrawers.push_back(std::move(drawerp));
if ( drawername == sUNDEF){
drawername = "drawer_layer_" + QString::number(drawer->id());
}
}
drawer->name(drawername);
}
void ComplexDrawer::setDrawer(quint32 order, DrawerInterface *drawer, DrawerInterface::DrawerType drawerType)
{
if ( drawerType == dtPOST || drawerType == dtPRE){
DrawerMap& drawers = drawerType == dtPRE ? _preDrawers : _postDrawers;
const auto& current = drawers.find(order);
if ( current == drawers.end()){
return;
}
drawers[order].reset(drawer);
} else if ( drawerType == dtMAIN){
if ( order < _mainDrawers.size()) {
_mainDrawers[order].reset(drawer);
}
}
}
void ComplexDrawer::removeDrawer(quint32 order, DrawerInterface::DrawerType drawerType)
{
if ( drawerType == dtPOST || drawerType == dtPRE){
DrawerMap& drawers = drawerType == dtPRE ? _preDrawers : _postDrawers;
auto current = drawers.find(order);
if ( current != drawers.end()){
(*current).second->cleanUp();
drawers.erase(current) ;
}
} else if ( drawerType == dtMAIN){
if ( order < _mainDrawers.size()) {
_mainDrawers[order]->cleanUp();
_mainDrawers.erase(_mainDrawers.begin() + order);
}
}
}
void ComplexDrawer::removeDrawer(const QString &idcode, bool ascode)
{
std::vector<quint32> selectedDrawers;
for( auto& drawer : _preDrawers){
if ( ascode){
if (drawer.second->code() == idcode){
selectedDrawers.push_back(drawer.first);
}
} else {
if (drawer.second->name() == idcode){
selectedDrawers.push_back(drawer.first);
}
}
}
for(auto order : selectedDrawers)
removeDrawer(order, DrawerInterface::dtPRE);
selectedDrawers.clear();
int count = 0;
for( auto& drawer : _mainDrawers){
if ( ascode){
if (drawer->code() == idcode){
selectedDrawers.push_back(count);
}
} else {
if (drawer->name() == idcode){
selectedDrawers.push_back(count);
}
}
++count;
}
for(auto order : selectedDrawers)
removeDrawer(order, DrawerInterface::dtMAIN);
selectedDrawers.clear();
for( auto& drawer : _postDrawers) {
if ( ascode){
if (drawer.second->code() == idcode){
selectedDrawers.push_back(drawer.first);
}
} else {
if (drawer.second->name() == idcode){
selectedDrawers.push_back(drawer.first);
}
}
}
for(auto order : selectedDrawers)
removeDrawer(order, DrawerInterface::dtPOST);
}
bool ComplexDrawer::drawerAttribute(const QString &drawercode, const QString &key, const QVariant &value)
{
if ( drawercode == code()){
setAttribute(key, value);
return true;
}
for( auto& drawer : _preDrawers){
if (drawer.second->drawerAttribute(drawercode, key, value))
return true;
}
for( auto& drawer : _mainDrawers){
if (drawer->drawerAttribute(drawercode, key, value))
return true;
}
for( auto& drawer : _postDrawers) {
if (drawer.second->drawerAttribute(drawercode, key, value))
return true;
}
return false;
}
bool ComplexDrawer::isSimple() const
{
return false;
}
void ComplexDrawer::cleanUp()
{
BaseDrawer::cleanUp();
for( auto& drawer : _preDrawers) {
drawer.second->cleanUp();
}
for( auto& drawer : _mainDrawers){
drawer->cleanUp();
}
for( auto& drawer : _postDrawers) {
drawer.second->cleanUp();
}
_preDrawers.clear();
_mainDrawers.clear();
_postDrawers.clear();
unprepare(ptALL);
}
bool ComplexDrawer::drawSideDrawers(const DrawerMap& drawers, const IOOptions &options) const
{
if (!isActive())
return false;
if ( drawers.size() > 0) {
for(const auto& current : drawers) {
const auto& drw = current.second;
if ( drw)
drw->draw(options);
}
}
return true;
}
std::vector<QVariant> ComplexDrawer::attributes(const QString &attrNames) const
{
std::vector<QVariant> results = BaseDrawer::attributes(attrNames);
QStringList parts = attrNames.split("|");
for(QString& part : parts)
part.toLower();
for(const QString& part : parts){
results.push_back(attribute(part));
}
return results;
}
QVariant ComplexDrawer::attribute(const QString &attrNme) const
{
QString attrName = attrNme.toLower();
QVariant var = BaseDrawer::attribute(attrName);
if ( var.isValid())
return var;
if ( attrName == "maindrawercount")
return drawerCount(DrawerInterface::dtMAIN);
if ( attrName == "predrawercount")
return drawerCount(DrawerInterface::dtPRE);
if ( attrName == "postdrawercount")
return drawerCount(DrawerInterface::dtPOST);
return QVariant();
}
QVariant ComplexDrawer::attributeOfDrawer(const QString &drawercode, const QString &attrName) const
{
if ( code() == drawercode)
return attribute(attrName);
QVariant var;
for( auto& drawer : _preDrawers){
var = drawer.second->attributeOfDrawer(drawercode, attrName);
if ( var.isValid())
return var;
}
for( auto& drawer : _mainDrawers){
var = drawer->attributeOfDrawer(drawercode, attrName);
if ( var.isValid())
return var;
}
for( auto& drawer : _postDrawers) {
var = drawer.second->attributeOfDrawer(drawercode, attrName);
if ( var.isValid())
return var;
}
return var;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2008, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/session.hpp"
#include "libtorrent/hasher.hpp"
#include <boost/thread.hpp>
#include <boost/tuple/tuple.hpp>
#include "test.hpp"
#include "setup_transfer.hpp"
#include "libtorrent/extensions/metadata_transfer.hpp"
#include "libtorrent/extensions/ut_metadata.hpp"
#include "libtorrent/extensions/lt_trackers.hpp"
using boost::tuples::ignore;
int test_main()
{
using namespace libtorrent;
session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48130, 49000), "0.0.0.0", 0);
session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49130, 50000), "0.0.0.0", 0);
ses1.add_extension(create_lt_trackers_plugin);
ses2.add_extension(create_lt_trackers_plugin);
add_torrent_params atp;
atp.info_hash = sha1_hash("12345678901234567890");
atp.save_path = "./";
torrent_handle tor1 = ses1.add_torrent(atp);
atp.tracker_url = "http://test.non-existent.com/announce";
torrent_handle tor2 = ses2.add_torrent(atp);
tor2.connect_peer(tcp::endpoint(address_v4::from_string("127.0.0.1"), ses1.listen_port()));
for (int i = 0; i < 130; ++i)
{
// make sure this function can be called on
// torrents without metadata
print_alerts(ses1, "ses1", false, true);
print_alerts(ses2, "ses2", false, true);
if (tor1.trackers().size() == 1) break;
test_sleep(1000);
}
TEST_CHECK(tor1.trackers().size() == 1);
}
<commit_msg>fix tracker test<commit_after>/*
Copyright (c) 2008, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/session.hpp"
#include "libtorrent/hasher.hpp"
#include <boost/thread.hpp>
#include <boost/tuple/tuple.hpp>
#include "test.hpp"
#include "setup_transfer.hpp"
#include "libtorrent/extensions/metadata_transfer.hpp"
#include "libtorrent/extensions/ut_metadata.hpp"
#include "libtorrent/extensions/lt_trackers.hpp"
using boost::tuples::ignore;
int test_main()
{
using namespace libtorrent;
session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48130, 49000), "0.0.0.0", 0);
session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49130, 50000), "0.0.0.0", 0);
ses1.add_extension(create_lt_trackers_plugin);
ses2.add_extension(create_lt_trackers_plugin);
add_torrent_params atp;
atp.info_hash = sha1_hash("12345678901234567890");
atp.save_path = "./";
torrent_handle tor1 = ses1.add_torrent(atp);
atp.tracker_url = "http://test.non-existent.com/announce";
torrent_handle tor2 = ses2.add_torrent(atp);
tor2.connect_peer(tcp::endpoint(address_v4::from_string("127.0.0.1"), ses1.listen_port()));
for (int i = 0; i < 130; ++i)
{
// make sure this function can be called on
// torrents without metadata
print_alerts(ses1, "ses1", false, true);
print_alerts(ses2, "ses2", false, true);
if (tor1.trackers().size() == 1) break;
test_sleep(1000);
}
TEST_CHECK(tor1.trackers().size() == 1);
return 0;
}
<|endoftext|> |
<commit_before>
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkCanvas.h"
#include "SkGradientShader.h"
#include "SkGraphics.h"
#include "SkPath.h"
#include "SkRegion.h"
#include "SkShader.h"
static void make_bitmap(SkBitmap* bitmap) {
bitmap->allocN32Pixels(64, 64);
SkCanvas canvas(*bitmap);
canvas.drawColor(SK_ColorRED);
SkPaint paint;
paint.setAntiAlias(true);
const SkPoint pts[] = { { 0, 0 }, { 64, 64 } };
const SkColor colors[] = { SK_ColorWHITE, SK_ColorBLUE };
paint.setShader(SkGradientShader::CreateLinear(pts, colors, NULL, 2,
SkShader::kClamp_TileMode))->unref();
canvas.drawCircle(32, 32, 32, paint);
}
class DrawBitmapRect2 : public skiagm::GM {
bool fUseIRect;
public:
DrawBitmapRect2(bool useIRect) : fUseIRect(useIRect) {
}
protected:
SkString onShortName() override {
SkString str;
str.printf("bitmaprect_%s", fUseIRect ? "i" : "s");
return str;
}
SkISize onISize() override {
return SkISize::Make(640, 480);
}
void onDraw(SkCanvas* canvas) override {
canvas->drawColor(0xFFCCCCCC);
const SkIRect src[] = {
{ 0, 0, 32, 32 },
{ 0, 0, 80, 80 },
{ 32, 32, 96, 96 },
{ -32, -32, 32, 32, }
};
SkPaint paint;
paint.setStyle(SkPaint::kStroke_Style);
SkBitmap bitmap;
make_bitmap(&bitmap);
SkRect dstR = { 0, 200, 128, 380 };
canvas->translate(16, 40);
for (size_t i = 0; i < SK_ARRAY_COUNT(src); i++) {
SkRect srcR;
srcR.set(src[i]);
canvas->drawBitmap(bitmap, 0, 0, &paint);
if (!fUseIRect) {
canvas->drawBitmapRectToRect(bitmap, &srcR, dstR, &paint);
} else {
canvas->drawBitmapRect(bitmap, &src[i], dstR, &paint);
}
canvas->drawRect(dstR, paint);
canvas->drawRect(srcR, paint);
canvas->translate(160, 0);
}
}
private:
typedef skiagm::GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static void make_3x3_bitmap(SkBitmap* bitmap) {
const int xSize = 3;
const int ySize = 3;
const SkColor textureData[xSize][ySize] = {
{ SK_ColorRED, SK_ColorWHITE, SK_ColorBLUE },
{ SK_ColorGREEN, SK_ColorBLACK, SK_ColorCYAN },
{ SK_ColorYELLOW, SK_ColorGRAY, SK_ColorMAGENTA }
};
bitmap->allocN32Pixels(xSize, ySize, true);
SkCanvas canvas(*bitmap);
SkPaint paint;
for (int y = 0; y < ySize; y++) {
for (int x = 0; x < xSize; x++) {
paint.setColor(textureData[x][y]);
canvas.drawIRect(SkIRect::MakeXYWH(x, y, 1, 1), paint);
}
}
}
// This GM attempts to make visible any issues drawBitmapRectToRect may have
// with partial source rects. In this case the eight pixels on the border
// should be half the width/height of the central pixel, i.e.:
// __|____|__
// | |
// __|____|__
// | |
class DrawBitmapRect3 : public skiagm::GM {
public:
DrawBitmapRect3() {
this->setBGColor(SK_ColorBLACK);
}
protected:
SkString onShortName() override {
SkString str;
str.printf("3x3bitmaprect");
return str;
}
SkISize onISize() override {
return SkISize::Make(640, 480);
}
void onDraw(SkCanvas* canvas) override {
SkBitmap bitmap;
make_3x3_bitmap(&bitmap);
SkRect srcR = { 0.5f, 0.5f, 2.5f, 2.5f };
SkRect dstR = { 100, 100, 300, 200 };
canvas->drawBitmapRectToRect(bitmap, &srcR, dstR, NULL);
}
private:
typedef skiagm::GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static void make_big_bitmap(SkBitmap* bitmap) {
static const int gXSize = 4096;
static const int gYSize = 4096;
static const int gBorderWidth = 10;
bitmap->allocN32Pixels(gXSize, gYSize);
for (int y = 0; y < gYSize; ++y) {
for (int x = 0; x < gXSize; ++x) {
if (x <= gBorderWidth || x >= gXSize-gBorderWidth ||
y <= gBorderWidth || y >= gYSize-gBorderWidth) {
*bitmap->getAddr32(x, y) = 0x88FFFFFF;
} else {
*bitmap->getAddr32(x, y) = 0x88FF0000;
}
}
}
}
// This GM attempts to reveal any issues we may have when the GPU has to
// break up a large texture in order to draw it. The XOR transfer mode will
// create stripes in the image if there is imprecision in the destination
// tile placement.
class DrawBitmapRect4 : public skiagm::GM {
bool fUseIRect;
SkBitmap fBigBitmap;
public:
DrawBitmapRect4(bool useIRect) : fUseIRect(useIRect) {
this->setBGColor(0x88444444);
}
protected:
SkString onShortName() override {
SkString str;
str.printf("bigbitmaprect_%s", fUseIRect ? "i" : "s");
return str;
}
SkISize onISize() override {
return SkISize::Make(640, 480);
}
void onOnceBeforeDraw() override {
make_big_bitmap(&fBigBitmap);
}
void onDraw(SkCanvas* canvas) override {
SkXfermode* mode = SkXfermode::Create(SkXfermode::kXor_Mode);
SkPaint paint;
paint.setAlpha(128);
paint.setXfermode(mode)->unref();
SkRect srcR1 = { 0.0f, 0.0f, 4096.0f, 2040.0f };
SkRect dstR1 = { 10.1f, 10.1f, 629.9f, 400.9f };
SkRect srcR2 = { 4085.0f, 10.0f, 4087.0f, 12.0f };
SkRect dstR2 = { 10, 410, 30, 430 };
if (!fUseIRect) {
canvas->drawBitmapRectToRect(fBigBitmap, &srcR1, dstR1, &paint);
canvas->drawBitmapRectToRect(fBigBitmap, &srcR2, dstR2, &paint);
} else {
SkIRect iSrcR1, iSrcR2;
srcR1.roundOut(&iSrcR1);
srcR2.roundOut(&iSrcR2);
canvas->drawBitmapRect(fBigBitmap, &iSrcR1, dstR1, &paint);
canvas->drawBitmapRect(fBigBitmap, &iSrcR2, dstR2, &paint);
}
}
private:
typedef skiagm::GM INHERITED;
};
class BitmapRectRounding : public skiagm::GM {
SkBitmap fBM;
public:
BitmapRectRounding() {}
protected:
SkString onShortName() override {
SkString str;
str.printf("bitmaprect_rounding");
return str;
}
SkISize onISize() override {
return SkISize::Make(640, 480);
}
void onOnceBeforeDraw() override {
fBM.allocN32Pixels(10, 10);
fBM.eraseColor(SK_ColorBLUE);
}
// This choice of coordinates and matrix land the bottom edge of the clip (and bitmap dst)
// at exactly 1/2 pixel boundary. However, drawBitmapRect may lose precision along the way.
// If it does, we may see a red-line at the bottom, instead of the bitmap exactly matching
// the clip (in which case we should see all blue).
// The correct image should be all blue.
void onDraw(SkCanvas* canvas) override {
SkPaint paint;
paint.setColor(SK_ColorRED);
const SkRect r = SkRect::MakeXYWH(1, 1, 110, 114);
canvas->scale(0.9f, 0.9f);
// the drawRect shows the same problem as clipRect(r) followed by drawcolor(red)
canvas->drawRect(r, paint);
canvas->drawBitmapRect(fBM, NULL, r, NULL);
}
private:
typedef skiagm::GM INHERITED;
};
DEF_GM( return new BitmapRectRounding; )
//////////////////////////////////////////////////////////////////////////////
static skiagm::GM* MyFactory0(void*) { return new DrawBitmapRect2(false); }
static skiagm::GM* MyFactory1(void*) { return new DrawBitmapRect2(true); }
static skiagm::GM* MyFactory2(void*) { return new DrawBitmapRect3(); }
#ifndef SK_BUILD_FOR_ANDROID
static skiagm::GM* MyFactory3(void*) { return new DrawBitmapRect4(false); }
static skiagm::GM* MyFactory4(void*) { return new DrawBitmapRect4(true); }
#endif
static skiagm::GMRegistry reg0(MyFactory0);
static skiagm::GMRegistry reg1(MyFactory1);
static skiagm::GMRegistry reg2(MyFactory2);
#ifndef SK_BUILD_FOR_ANDROID
static skiagm::GMRegistry reg3(MyFactory3);
static skiagm::GMRegistry reg4(MyFactory4);
#endif
<commit_msg>pass legal premul values to bitmap -- do we still need this GM?<commit_after>
/*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkCanvas.h"
#include "SkGradientShader.h"
#include "SkGraphics.h"
#include "SkPath.h"
#include "SkRegion.h"
#include "SkShader.h"
static void make_bitmap(SkBitmap* bitmap) {
bitmap->allocN32Pixels(64, 64);
SkCanvas canvas(*bitmap);
canvas.drawColor(SK_ColorRED);
SkPaint paint;
paint.setAntiAlias(true);
const SkPoint pts[] = { { 0, 0 }, { 64, 64 } };
const SkColor colors[] = { SK_ColorWHITE, SK_ColorBLUE };
paint.setShader(SkGradientShader::CreateLinear(pts, colors, NULL, 2,
SkShader::kClamp_TileMode))->unref();
canvas.drawCircle(32, 32, 32, paint);
}
class DrawBitmapRect2 : public skiagm::GM {
bool fUseIRect;
public:
DrawBitmapRect2(bool useIRect) : fUseIRect(useIRect) {
}
protected:
SkString onShortName() override {
SkString str;
str.printf("bitmaprect_%s", fUseIRect ? "i" : "s");
return str;
}
SkISize onISize() override {
return SkISize::Make(640, 480);
}
void onDraw(SkCanvas* canvas) override {
canvas->drawColor(0xFFCCCCCC);
const SkIRect src[] = {
{ 0, 0, 32, 32 },
{ 0, 0, 80, 80 },
{ 32, 32, 96, 96 },
{ -32, -32, 32, 32, }
};
SkPaint paint;
paint.setStyle(SkPaint::kStroke_Style);
SkBitmap bitmap;
make_bitmap(&bitmap);
SkRect dstR = { 0, 200, 128, 380 };
canvas->translate(16, 40);
for (size_t i = 0; i < SK_ARRAY_COUNT(src); i++) {
SkRect srcR;
srcR.set(src[i]);
canvas->drawBitmap(bitmap, 0, 0, &paint);
if (!fUseIRect) {
canvas->drawBitmapRectToRect(bitmap, &srcR, dstR, &paint);
} else {
canvas->drawBitmapRect(bitmap, &src[i], dstR, &paint);
}
canvas->drawRect(dstR, paint);
canvas->drawRect(srcR, paint);
canvas->translate(160, 0);
}
}
private:
typedef skiagm::GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static void make_3x3_bitmap(SkBitmap* bitmap) {
const int xSize = 3;
const int ySize = 3;
const SkColor textureData[xSize][ySize] = {
{ SK_ColorRED, SK_ColorWHITE, SK_ColorBLUE },
{ SK_ColorGREEN, SK_ColorBLACK, SK_ColorCYAN },
{ SK_ColorYELLOW, SK_ColorGRAY, SK_ColorMAGENTA }
};
bitmap->allocN32Pixels(xSize, ySize, true);
SkCanvas canvas(*bitmap);
SkPaint paint;
for (int y = 0; y < ySize; y++) {
for (int x = 0; x < xSize; x++) {
paint.setColor(textureData[x][y]);
canvas.drawIRect(SkIRect::MakeXYWH(x, y, 1, 1), paint);
}
}
}
// This GM attempts to make visible any issues drawBitmapRectToRect may have
// with partial source rects. In this case the eight pixels on the border
// should be half the width/height of the central pixel, i.e.:
// __|____|__
// | |
// __|____|__
// | |
class DrawBitmapRect3 : public skiagm::GM {
public:
DrawBitmapRect3() {
this->setBGColor(SK_ColorBLACK);
}
protected:
SkString onShortName() override {
SkString str;
str.printf("3x3bitmaprect");
return str;
}
SkISize onISize() override {
return SkISize::Make(640, 480);
}
void onDraw(SkCanvas* canvas) override {
SkBitmap bitmap;
make_3x3_bitmap(&bitmap);
SkRect srcR = { 0.5f, 0.5f, 2.5f, 2.5f };
SkRect dstR = { 100, 100, 300, 200 };
canvas->drawBitmapRectToRect(bitmap, &srcR, dstR, NULL);
}
private:
typedef skiagm::GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static void make_big_bitmap(SkBitmap* bitmap) {
static const int gXSize = 4096;
static const int gYSize = 4096;
static const int gBorderWidth = 10;
bitmap->allocN32Pixels(gXSize, gYSize);
for (int y = 0; y < gYSize; ++y) {
for (int x = 0; x < gXSize; ++x) {
if (x <= gBorderWidth || x >= gXSize-gBorderWidth ||
y <= gBorderWidth || y >= gYSize-gBorderWidth) {
*bitmap->getAddr32(x, y) = SkPreMultiplyColor(0x88FFFFFF);
} else {
*bitmap->getAddr32(x, y) = SkPreMultiplyColor(0x88FF0000);
}
}
}
}
// This GM attempts to reveal any issues we may have when the GPU has to
// break up a large texture in order to draw it. The XOR transfer mode will
// create stripes in the image if there is imprecision in the destination
// tile placement.
class DrawBitmapRect4 : public skiagm::GM {
bool fUseIRect;
SkBitmap fBigBitmap;
public:
DrawBitmapRect4(bool useIRect) : fUseIRect(useIRect) {
this->setBGColor(0x88444444);
}
protected:
SkString onShortName() override {
SkString str;
str.printf("bigbitmaprect_%s", fUseIRect ? "i" : "s");
return str;
}
SkISize onISize() override {
return SkISize::Make(640, 480);
}
void onOnceBeforeDraw() override {
make_big_bitmap(&fBigBitmap);
}
void onDraw(SkCanvas* canvas) override {
SkXfermode* mode = SkXfermode::Create(SkXfermode::kXor_Mode);
SkPaint paint;
paint.setAlpha(128);
paint.setXfermode(mode)->unref();
SkRect srcR1 = { 0.0f, 0.0f, 4096.0f, 2040.0f };
SkRect dstR1 = { 10.1f, 10.1f, 629.9f, 400.9f };
SkRect srcR2 = { 4085.0f, 10.0f, 4087.0f, 12.0f };
SkRect dstR2 = { 10, 410, 30, 430 };
if (!fUseIRect) {
canvas->drawBitmapRectToRect(fBigBitmap, &srcR1, dstR1, &paint);
canvas->drawBitmapRectToRect(fBigBitmap, &srcR2, dstR2, &paint);
} else {
SkIRect iSrcR1, iSrcR2;
srcR1.roundOut(&iSrcR1);
srcR2.roundOut(&iSrcR2);
canvas->drawBitmapRect(fBigBitmap, &iSrcR1, dstR1, &paint);
canvas->drawBitmapRect(fBigBitmap, &iSrcR2, dstR2, &paint);
}
}
private:
typedef skiagm::GM INHERITED;
};
class BitmapRectRounding : public skiagm::GM {
SkBitmap fBM;
public:
BitmapRectRounding() {}
protected:
SkString onShortName() override {
SkString str;
str.printf("bitmaprect_rounding");
return str;
}
SkISize onISize() override {
return SkISize::Make(640, 480);
}
void onOnceBeforeDraw() override {
fBM.allocN32Pixels(10, 10);
fBM.eraseColor(SK_ColorBLUE);
}
// This choice of coordinates and matrix land the bottom edge of the clip (and bitmap dst)
// at exactly 1/2 pixel boundary. However, drawBitmapRect may lose precision along the way.
// If it does, we may see a red-line at the bottom, instead of the bitmap exactly matching
// the clip (in which case we should see all blue).
// The correct image should be all blue.
void onDraw(SkCanvas* canvas) override {
SkPaint paint;
paint.setColor(SK_ColorRED);
const SkRect r = SkRect::MakeXYWH(1, 1, 110, 114);
canvas->scale(0.9f, 0.9f);
// the drawRect shows the same problem as clipRect(r) followed by drawcolor(red)
canvas->drawRect(r, paint);
canvas->drawBitmapRect(fBM, NULL, r, NULL);
}
private:
typedef skiagm::GM INHERITED;
};
DEF_GM( return new BitmapRectRounding; )
//////////////////////////////////////////////////////////////////////////////
static skiagm::GM* MyFactory0(void*) { return new DrawBitmapRect2(false); }
static skiagm::GM* MyFactory1(void*) { return new DrawBitmapRect2(true); }
static skiagm::GM* MyFactory2(void*) { return new DrawBitmapRect3(); }
#ifndef SK_BUILD_FOR_ANDROID
static skiagm::GM* MyFactory3(void*) { return new DrawBitmapRect4(false); }
static skiagm::GM* MyFactory4(void*) { return new DrawBitmapRect4(true); }
#endif
static skiagm::GMRegistry reg0(MyFactory0);
static skiagm::GMRegistry reg1(MyFactory1);
static skiagm::GMRegistry reg2(MyFactory2);
#ifndef SK_BUILD_FOR_ANDROID
static skiagm::GMRegistry reg3(MyFactory3);
static skiagm::GMRegistry reg4(MyFactory4);
#endif
<|endoftext|> |
<commit_before>/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "Resources.h"
#include "SkCodec.h"
#include "SkColorSpace.h"
#include "SkColorSpace_Base.h"
#include "SkHalf.h"
#include "SkImage.h"
static void clamp_if_necessary(const SkImageInfo& info, void* pixels) {
if (kRGBA_F16_SkColorType != info.colorType()) {
return;
}
for (int y = 0; y < info.height(); y++) {
for (int x = 0; x < info.width(); x++) {
uint64_t pixel = ((uint64_t*) pixels)[y * info.width() + x];
Sk4f rgba = SkHalfToFloat_finite_ftz(pixel);
if (kUnpremul_SkAlphaType == info.alphaType()) {
rgba = Sk4f::Max(0.0f, Sk4f::Min(rgba, 1.0f));
} else {
SkASSERT(kPremul_SkAlphaType == info.alphaType());
rgba = Sk4f::Max(0.0f, Sk4f::Min(rgba, rgba[3]));
}
SkFloatToHalf_finite_ftz(rgba).store(&pixel);
((uint64_t*) pixels)[y * info.width() + x] = pixel;
}
}
}
sk_sp<SkColorSpace> fix_for_colortype(SkColorSpace* colorSpace, SkColorType colorType) {
if (kRGBA_F16_SkColorType == colorType) {
return as_CSB(colorSpace)->makeLinearGamma();
}
return sk_ref_sp(colorSpace);
}
static const int kWidth = 64;
static const int kHeight = 64;
static sk_sp<SkImage> make_raster_image(SkColorType colorType, SkAlphaType alphaType) {
std::unique_ptr<SkStream> stream(GetResourceAsStream("google_chrome.ico"));
std::unique_ptr<SkCodec> codec(SkCodec::NewFromStream(stream.release()));
SkBitmap bitmap;
SkImageInfo info = codec->getInfo().makeWH(kWidth, kHeight)
.makeColorType(colorType)
.makeAlphaType(alphaType)
.makeColorSpace(fix_for_colortype(codec->getInfo().colorSpace(), colorType));
bitmap.allocPixels(info);
codec->getPixels(info, bitmap.getPixels(), bitmap.rowBytes());
bitmap.setImmutable();
return SkImage::MakeFromBitmap(bitmap);
}
static sk_sp<SkColorSpace> make_srgb_transfer_fn(const SkColorSpacePrimaries& primaries) {
SkMatrix44 toXYZD50;
SkAssertResult(primaries.toXYZD50(&toXYZD50));
return SkColorSpace::MakeRGB(SkColorSpace::kSRGB_RenderTargetGamma, toXYZD50);
}
static sk_sp<SkColorSpace> make_wide_gamut() {
// ProPhoto
SkColorSpacePrimaries primaries;
primaries.fRX = 0.7347f;
primaries.fRY = 0.2653f;
primaries.fGX = 0.1596f;
primaries.fGY = 0.8404f;
primaries.fBX = 0.0366f;
primaries.fBY = 0.0001f;
primaries.fWX = 0.34567f;
primaries.fWY = 0.35850f;
return make_srgb_transfer_fn(primaries);
}
static sk_sp<SkColorSpace> make_small_gamut() {
SkColorSpacePrimaries primaries;
primaries.fRX = 0.50f;
primaries.fRY = 0.33f;
primaries.fGX = 0.30f;
primaries.fGY = 0.50f;
primaries.fBX = 0.25f;
primaries.fBY = 0.16f;
primaries.fWX = 0.3127f;
primaries.fWY = 0.3290f;
return make_srgb_transfer_fn(primaries);
}
static void draw_image(SkCanvas* canvas, SkImage* image, SkColorType dstColorType,
SkAlphaType dstAlphaType, sk_sp<SkColorSpace> dstColorSpace) {
size_t rowBytes = image->width() * SkColorTypeBytesPerPixel(dstColorType);
sk_sp<SkData> data = SkData::MakeUninitialized(rowBytes * image->height());
dstColorSpace = fix_for_colortype(dstColorSpace.get(), dstColorType);
SkImageInfo dstInfo = SkImageInfo::Make(image->width(), image->height(), dstColorType,
dstAlphaType, dstColorSpace);
image->readPixels(dstInfo, data->writable_data(), rowBytes, 0, 0);
// readPixels() does not always clamp F16. The drawing code expects pixels in the 0-1 range.
clamp_if_necessary(dstInfo, data->writable_data());
// Now that we have called readPixels(), dump the raw pixels into an srgb image.
sk_sp<SkColorSpace> srgb = fix_for_colortype(
SkColorSpace::MakeNamed(SkColorSpace::kSRGB_Named).get(), dstColorType);
sk_sp<SkImage> raw = SkImage::MakeRasterData(dstInfo.makeColorSpace(srgb), data, rowBytes);
canvas->drawImage(raw.get(), 0.0f, 0.0f, nullptr);
}
class ReadPixelsGM : public skiagm::GM {
public:
ReadPixelsGM() {}
protected:
SkString onShortName() override {
return SkString("readpixels");
}
SkISize onISize() override {
return SkISize::Make(6 * kWidth, 18 * kHeight);
}
void onDraw(SkCanvas* canvas) override {
if (!canvas->imageInfo().colorSpace()) {
// This gm is only interesting in color correct modes.
return;
}
const SkAlphaType alphaTypes[] = {
kUnpremul_SkAlphaType,
kPremul_SkAlphaType,
};
const SkColorType colorTypes[] = {
kRGBA_8888_SkColorType,
kBGRA_8888_SkColorType,
kRGBA_F16_SkColorType,
};
const sk_sp<SkColorSpace> colorSpaces[] = {
make_wide_gamut(),
SkColorSpace::MakeNamed(SkColorSpace::kSRGB_Named),
make_small_gamut(),
};
for (sk_sp<SkColorSpace> dstColorSpace : colorSpaces) {
for (SkColorType srcColorType : colorTypes) {
for (SkAlphaType srcAlphaType : alphaTypes) {
canvas->save();
sk_sp<SkImage> image = make_raster_image(srcColorType, srcAlphaType);
for (SkColorType dstColorType : colorTypes) {
for (SkAlphaType dstAlphaType : alphaTypes) {
draw_image(canvas, image.get(), dstColorType, dstAlphaType,
dstColorSpace);
canvas->translate((float) kWidth, 0.0f);
}
}
canvas->restore();
canvas->translate(0.0f, (float) kHeight);
}
}
}
}
private:
typedef skiagm::GM INHERITED;
};
DEF_GM( return new ReadPixelsGM; )
<commit_msg>Fix iOS build<commit_after>/*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "Resources.h"
#include "SkCodec.h"
#include "SkColorSpace.h"
#include "SkColorSpace_Base.h"
#include "SkHalf.h"
#include "SkImage.h"
static void clamp_if_necessary(const SkImageInfo& info, void* pixels) {
if (kRGBA_F16_SkColorType != info.colorType()) {
return;
}
for (int y = 0; y < info.height(); y++) {
for (int x = 0; x < info.width(); x++) {
uint64_t pixel = ((uint64_t*) pixels)[y * info.width() + x];
Sk4f rgba = SkHalfToFloat_finite_ftz(pixel);
if (kUnpremul_SkAlphaType == info.alphaType()) {
rgba = Sk4f::Max(0.0f, Sk4f::Min(rgba, 1.0f));
} else {
SkASSERT(kPremul_SkAlphaType == info.alphaType());
rgba = Sk4f::Max(0.0f, Sk4f::Min(rgba, rgba[3]));
}
SkFloatToHalf_finite_ftz(rgba).store(&pixel);
((uint64_t*) pixels)[y * info.width() + x] = pixel;
}
}
}
sk_sp<SkColorSpace> fix_for_colortype(SkColorSpace* colorSpace, SkColorType colorType) {
if (kRGBA_F16_SkColorType == colorType) {
return as_CSB(colorSpace)->makeLinearGamma();
}
return sk_ref_sp(colorSpace);
}
static const int kWidth = 64;
static const int kHeight = 64;
static sk_sp<SkImage> make_raster_image(SkColorType colorType, SkAlphaType alphaType) {
std::unique_ptr<SkStream> stream(GetResourceAsStream("google_chrome.ico"));
std::unique_ptr<SkCodec> codec(SkCodec::NewFromStream(stream.release()));
SkBitmap bitmap;
SkImageInfo info = codec->getInfo().makeWH(kWidth, kHeight)
.makeColorType(colorType)
.makeAlphaType(alphaType)
.makeColorSpace(fix_for_colortype(codec->getInfo().colorSpace(), colorType));
bitmap.allocPixels(info);
codec->getPixels(info, bitmap.getPixels(), bitmap.rowBytes());
bitmap.setImmutable();
return SkImage::MakeFromBitmap(bitmap);
}
static sk_sp<SkColorSpace> make_srgb_transfer_fn(const SkColorSpacePrimaries& primaries) {
SkMatrix44 toXYZD50(SkMatrix44::kUninitialized_Constructor);
SkAssertResult(primaries.toXYZD50(&toXYZD50));
return SkColorSpace::MakeRGB(SkColorSpace::kSRGB_RenderTargetGamma, toXYZD50);
}
static sk_sp<SkColorSpace> make_wide_gamut() {
// ProPhoto
SkColorSpacePrimaries primaries;
primaries.fRX = 0.7347f;
primaries.fRY = 0.2653f;
primaries.fGX = 0.1596f;
primaries.fGY = 0.8404f;
primaries.fBX = 0.0366f;
primaries.fBY = 0.0001f;
primaries.fWX = 0.34567f;
primaries.fWY = 0.35850f;
return make_srgb_transfer_fn(primaries);
}
static sk_sp<SkColorSpace> make_small_gamut() {
SkColorSpacePrimaries primaries;
primaries.fRX = 0.50f;
primaries.fRY = 0.33f;
primaries.fGX = 0.30f;
primaries.fGY = 0.50f;
primaries.fBX = 0.25f;
primaries.fBY = 0.16f;
primaries.fWX = 0.3127f;
primaries.fWY = 0.3290f;
return make_srgb_transfer_fn(primaries);
}
static void draw_image(SkCanvas* canvas, SkImage* image, SkColorType dstColorType,
SkAlphaType dstAlphaType, sk_sp<SkColorSpace> dstColorSpace) {
size_t rowBytes = image->width() * SkColorTypeBytesPerPixel(dstColorType);
sk_sp<SkData> data = SkData::MakeUninitialized(rowBytes * image->height());
dstColorSpace = fix_for_colortype(dstColorSpace.get(), dstColorType);
SkImageInfo dstInfo = SkImageInfo::Make(image->width(), image->height(), dstColorType,
dstAlphaType, dstColorSpace);
image->readPixels(dstInfo, data->writable_data(), rowBytes, 0, 0);
// readPixels() does not always clamp F16. The drawing code expects pixels in the 0-1 range.
clamp_if_necessary(dstInfo, data->writable_data());
// Now that we have called readPixels(), dump the raw pixels into an srgb image.
sk_sp<SkColorSpace> srgb = fix_for_colortype(
SkColorSpace::MakeNamed(SkColorSpace::kSRGB_Named).get(), dstColorType);
sk_sp<SkImage> raw = SkImage::MakeRasterData(dstInfo.makeColorSpace(srgb), data, rowBytes);
canvas->drawImage(raw.get(), 0.0f, 0.0f, nullptr);
}
class ReadPixelsGM : public skiagm::GM {
public:
ReadPixelsGM() {}
protected:
SkString onShortName() override {
return SkString("readpixels");
}
SkISize onISize() override {
return SkISize::Make(6 * kWidth, 18 * kHeight);
}
void onDraw(SkCanvas* canvas) override {
if (!canvas->imageInfo().colorSpace()) {
// This gm is only interesting in color correct modes.
return;
}
const SkAlphaType alphaTypes[] = {
kUnpremul_SkAlphaType,
kPremul_SkAlphaType,
};
const SkColorType colorTypes[] = {
kRGBA_8888_SkColorType,
kBGRA_8888_SkColorType,
kRGBA_F16_SkColorType,
};
const sk_sp<SkColorSpace> colorSpaces[] = {
make_wide_gamut(),
SkColorSpace::MakeNamed(SkColorSpace::kSRGB_Named),
make_small_gamut(),
};
for (sk_sp<SkColorSpace> dstColorSpace : colorSpaces) {
for (SkColorType srcColorType : colorTypes) {
for (SkAlphaType srcAlphaType : alphaTypes) {
canvas->save();
sk_sp<SkImage> image = make_raster_image(srcColorType, srcAlphaType);
for (SkColorType dstColorType : colorTypes) {
for (SkAlphaType dstAlphaType : alphaTypes) {
draw_image(canvas, image.get(), dstColorType, dstAlphaType,
dstColorSpace);
canvas->translate((float) kWidth, 0.0f);
}
}
canvas->restore();
canvas->translate(0.0f, (float) kHeight);
}
}
}
}
private:
typedef skiagm::GM INHERITED;
};
DEF_GM( return new ReadPixelsGM; )
<|endoftext|> |
<commit_before>// Copyright Paul Dardeau, SwampBits LLC 2014
// BSD License
#include <stdio.h>
#include <string.h>
#include "HttpRequestHandler.h"
#include "Socket.h"
#include "SocketRequest.h"
#include "HttpServer.h"
#include "HTTP.h"
#include "HttpRequest.h"
#include "HttpResponse.h"
#include "Thread.h"
#include "BasicException.h"
#include "Logger.h"
#include "StrUtils.h"
static const std::string HTTP_ACCEPT_ENCODING = "accept-encoding";
static const std::string HTTP_CONNECTION = "Connection:";
static const std::string HTTP_CONTENT_LENGTH = "content-length:";
static const std::string HTTP_CONTENT_TYPE = "content-type:";
static const std::string HTTP_DATE = "date:";
static const std::string HTTP_SERVER = "server:";
static const std::string HTTP_USER_AGENT = "User-Agent";
static const std::string CONNECTION_CLOSE = "close";
static const std::string ZERO = "0";
static const std::string FAVICON_ICO = "/favicon.ico";
static const std::string CONTENT_TYPE_HTML = "text/html";
static const std::string COUNT_PATH = "path";
static const std::string COUNT_USER_AGENT = "user_agent";
static const std::string QUESTION_MARK = "?";
static const std::string GZIP = "gzip";
using namespace misere;
using namespace chaudiere;
//******************************************************************************
HttpRequestHandler::HttpRequestHandler(HttpServer& server,
SocketRequest* socketRequest) :
RequestHandler(socketRequest),
m_server(server) {
Logger::logInstanceCreate("HttpRequestHandler");
}
//******************************************************************************
HttpRequestHandler::HttpRequestHandler(HttpServer& server,
Socket* socket) :
RequestHandler(socket),
m_server(server) {
Logger::logInstanceCreate("HttpRequestHandler");
}
//******************************************************************************
HttpRequestHandler::~HttpRequestHandler() {
Logger::logInstanceDestroy("HttpRequestHandler");
}
//******************************************************************************
void HttpRequestHandler::run() {
Socket* socket = getSocket();
if (!socket) {
Logger::error("no socket or socket request present in RequestHandler");
return;
}
socket->setTcpNoDelay(true);
socket->setSendBufferSize(m_server.getSocketSendBufferSize());
socket->setReceiveBufferSize(m_server.getSocketReceiveBufferSize());
const bool isLoggingDebug = Logger::isLogging(Debug);
if (isLoggingDebug) {
Logger::debug("starting parse of HttpRequest");
}
HttpRequest request(*socket);
if (request.isInitialized()) {
if (isLoggingDebug) {
Logger::debug("ending parse of HttpRequest");
}
const std::string& method = request.getMethod();
const std::string& protocol = request.getProtocol();
const std::string& path = request.getPath();
std::string routingPath = path;
std::string clientIPAddress;
socket->getPeerIPAddress(clientIPAddress);
if (StrUtils::containsString(path, QUESTION_MARK)) {
// strip arguments from path
const std::string::size_type posQuestionMark =
path.find(QUESTION_MARK);
if (posQuestionMark != std::string::npos) {
routingPath = path.substr(0, posQuestionMark);
}
}
Logger::countOccurrence(COUNT_PATH, routingPath);
if (request.hasHeaderValue(HTTP_USER_AGENT)) {
Logger::countOccurrence(COUNT_USER_AGENT,
request.getHeaderValue(HTTP_USER_AGENT));
}
HttpHandler* pHandler = m_server.getPathHandler(routingPath);
bool handlerAvailable = false;
if (pHandler == NULL) {
Logger::info("no handler for request: " + routingPath);
}
// assume the worst
std::string responseCode = HTTP::HTTP_RESP_SERV_ERR_INTERNAL_ERROR;
const std::string systemDate = m_server.getSystemDateGMT();
KeyValuePairs headers;
headers.addPair(HTTP_CONNECTION, CONNECTION_CLOSE);
const std::string& serverString = m_server.getServerId();
if (!serverString.empty()) {
headers.addPair(HTTP_SERVER, serverString);
}
headers.addPair(HTTP_DATE, systemDate);
//headers.addPair(HTTP_CONTENT_TYPE, CONTENT_TYPE_HTML);
if ((HTTP::HTTP_PROTOCOL1_0 != protocol) &&
(HTTP::HTTP_PROTOCOL1_1 != protocol)) {
responseCode = HTTP::HTTP_RESP_SERV_ERR_HTTP_VERSION_UNSUPPORTED;
Logger::warning("unsupported protocol: " + protocol);
} else if (NULL == pHandler) { // path recognized?
responseCode = HTTP::HTTP_RESP_CLIENT_ERR_NOT_FOUND;
//Logger::warning("bad request: " + path);
} else if (!pHandler->isAvailable()) { // is our handler available?
responseCode = HTTP::HTTP_RESP_SERV_ERR_SERVICE_UNAVAILABLE;
Logger::warning("handler not available: " + routingPath);
} else {
handlerAvailable = true;
}
const std::string httpHeader = request.getRawHeader();
const std::string httpBody = request.getBody();
if (isLoggingDebug) {
Logger::debug("HttpServer method: " + method);
Logger::debug("HttpServer path: " + routingPath);
Logger::debug("HttpServer protocol: " + protocol);
Logger::debug("HttpServer header:");
Logger::debug(httpHeader);
Logger::debug("HttpServer body:");
Logger::debug(httpBody);
}
std::string::size_type contentLength = 0;
HttpResponse response;
if ((NULL != pHandler) && handlerAvailable) {
try {
pHandler->serviceRequest(request, response);
responseCode = StrUtils::toString(response.getStatusCode());
const std::string& responseBody = response.getBody();
contentLength = responseBody.size();
if ((contentLength > 0) && !response.hasContentEncoding()) {
if (request.hasAcceptEncoding()) {
const std::string& acceptEncoding =
request.getAcceptEncoding();
if (StrUtils::containsString(acceptEncoding, GZIP) &&
m_server.compressionEnabled() &&
m_server.compressResponse(response.getContentType()) &&
contentLength >= m_server.minimumCompressionSize()) {
try {
const std::string compressedResponseBody =
StrUtils::gzipCompress(responseBody);
contentLength = compressedResponseBody.size();
response.setBody(compressedResponseBody);
response.setContentEncoding(GZIP);
} catch (const std::exception& e) {
Logger::error("unable to compress response");
}
}
}
}
response.populateWithHeaders(headers);
} catch (const BasicException& be) {
responseCode = HTTP::HTTP_RESP_SERV_ERR_INTERNAL_ERROR;
Logger::error("exception handling request: " + be.whatString());
} catch (const std::exception& e) {
responseCode = HTTP::HTTP_RESP_SERV_ERR_INTERNAL_ERROR;
Logger::error("exception handling request: " + std::string(e.what()));
} catch (...) {
responseCode = HTTP::HTTP_RESP_SERV_ERR_INTERNAL_ERROR;
Logger::error("unknown exception handling request");
}
}
if (contentLength > 0) {
headers.addPair(HTTP_CONTENT_LENGTH,
StrUtils::toString(contentLength));
} else {
headers.addPair(HTTP_CONTENT_LENGTH, ZERO);
}
// log the request
if (isThreadPooling()) {
const std::string& runByWorkerThreadId = getRunByThreadWorkerId();
if (!runByWorkerThreadId.empty()) {
m_server.logRequest(clientIPAddress,
request.getRequestLine(),
responseCode,
runByWorkerThreadId);
} else {
m_server.logRequest(clientIPAddress,
request.getRequestLine(),
responseCode);
}
} else {
m_server.logRequest(clientIPAddress,
request.getRequestLine(),
responseCode);
}
std::string responseAsString =
m_server.buildHeader(responseCode, headers);
if (contentLength > 0) {
responseAsString += response.getBody();
}
socket->write(responseAsString);
/*
if (isLoggingDebug) {
Logger::debug("response written, calling read so that client can close first");
}
// invoke a read to give the client the chance to close the socket
// first. this also lets us easily detect the close on the client
// end of the connection. we won't actually read any data here,
// this is just a wait to allow the client to close first
char readBuffer[5];
socket->read(readBuffer, 4);
//if (m_socketRequest != NULL) {
// m_socketRequest->requestComplete();
//}
*/
} else {
::printf("error: unable to initialize HttpRequest\n");
}
}
//******************************************************************************
<commit_msg>change contentLength to int<commit_after>// Copyright Paul Dardeau, SwampBits LLC 2014
// BSD License
#include <stdio.h>
#include <string.h>
#include "HttpRequestHandler.h"
#include "Socket.h"
#include "SocketRequest.h"
#include "HttpServer.h"
#include "HTTP.h"
#include "HttpRequest.h"
#include "HttpResponse.h"
#include "Thread.h"
#include "BasicException.h"
#include "Logger.h"
#include "StrUtils.h"
static const std::string HTTP_ACCEPT_ENCODING = "accept-encoding";
static const std::string HTTP_CONNECTION = "Connection:";
static const std::string HTTP_CONTENT_LENGTH = "content-length:";
static const std::string HTTP_CONTENT_TYPE = "content-type:";
static const std::string HTTP_DATE = "date:";
static const std::string HTTP_SERVER = "server:";
static const std::string HTTP_USER_AGENT = "User-Agent";
static const std::string CONNECTION_CLOSE = "close";
static const std::string ZERO = "0";
static const std::string FAVICON_ICO = "/favicon.ico";
static const std::string CONTENT_TYPE_HTML = "text/html";
static const std::string COUNT_PATH = "path";
static const std::string COUNT_USER_AGENT = "user_agent";
static const std::string QUESTION_MARK = "?";
static const std::string GZIP = "gzip";
using namespace misere;
using namespace chaudiere;
//******************************************************************************
HttpRequestHandler::HttpRequestHandler(HttpServer& server,
SocketRequest* socketRequest) :
RequestHandler(socketRequest),
m_server(server) {
Logger::logInstanceCreate("HttpRequestHandler");
}
//******************************************************************************
HttpRequestHandler::HttpRequestHandler(HttpServer& server,
Socket* socket) :
RequestHandler(socket),
m_server(server) {
Logger::logInstanceCreate("HttpRequestHandler");
}
//******************************************************************************
HttpRequestHandler::~HttpRequestHandler() {
Logger::logInstanceDestroy("HttpRequestHandler");
}
//******************************************************************************
void HttpRequestHandler::run() {
Socket* socket = getSocket();
if (!socket) {
Logger::error("no socket or socket request present in RequestHandler");
return;
}
socket->setTcpNoDelay(true);
socket->setSendBufferSize(m_server.getSocketSendBufferSize());
socket->setReceiveBufferSize(m_server.getSocketReceiveBufferSize());
const bool isLoggingDebug = Logger::isLogging(Debug);
if (isLoggingDebug) {
Logger::debug("starting parse of HttpRequest");
}
HttpRequest request(*socket);
if (request.isInitialized()) {
if (isLoggingDebug) {
Logger::debug("ending parse of HttpRequest");
}
const std::string& method = request.getMethod();
const std::string& protocol = request.getProtocol();
const std::string& path = request.getPath();
std::string routingPath = path;
std::string clientIPAddress;
socket->getPeerIPAddress(clientIPAddress);
if (StrUtils::containsString(path, QUESTION_MARK)) {
// strip arguments from path
const std::string::size_type posQuestionMark =
path.find(QUESTION_MARK);
if (posQuestionMark != std::string::npos) {
routingPath = path.substr(0, posQuestionMark);
}
}
Logger::countOccurrence(COUNT_PATH, routingPath);
if (request.hasHeaderValue(HTTP_USER_AGENT)) {
Logger::countOccurrence(COUNT_USER_AGENT,
request.getHeaderValue(HTTP_USER_AGENT));
}
HttpHandler* pHandler = m_server.getPathHandler(routingPath);
bool handlerAvailable = false;
if (pHandler == NULL) {
Logger::info("no handler for request: " + routingPath);
}
// assume the worst
std::string responseCode = HTTP::HTTP_RESP_SERV_ERR_INTERNAL_ERROR;
const std::string systemDate = m_server.getSystemDateGMT();
KeyValuePairs headers;
headers.addPair(HTTP_CONNECTION, CONNECTION_CLOSE);
const std::string& serverString = m_server.getServerId();
if (!serverString.empty()) {
headers.addPair(HTTP_SERVER, serverString);
}
headers.addPair(HTTP_DATE, systemDate);
//headers.addPair(HTTP_CONTENT_TYPE, CONTENT_TYPE_HTML);
if ((HTTP::HTTP_PROTOCOL1_0 != protocol) &&
(HTTP::HTTP_PROTOCOL1_1 != protocol)) {
responseCode = HTTP::HTTP_RESP_SERV_ERR_HTTP_VERSION_UNSUPPORTED;
Logger::warning("unsupported protocol: " + protocol);
} else if (NULL == pHandler) { // path recognized?
responseCode = HTTP::HTTP_RESP_CLIENT_ERR_NOT_FOUND;
//Logger::warning("bad request: " + path);
} else if (!pHandler->isAvailable()) { // is our handler available?
responseCode = HTTP::HTTP_RESP_SERV_ERR_SERVICE_UNAVAILABLE;
Logger::warning("handler not available: " + routingPath);
} else {
handlerAvailable = true;
}
const std::string httpHeader = request.getRawHeader();
const std::string httpBody = request.getBody();
if (isLoggingDebug) {
Logger::debug("HttpServer method: " + method);
Logger::debug("HttpServer path: " + routingPath);
Logger::debug("HttpServer protocol: " + protocol);
Logger::debug("HttpServer header:");
Logger::debug(httpHeader);
Logger::debug("HttpServer body:");
Logger::debug(httpBody);
}
int contentLength = 0;
HttpResponse response;
if ((NULL != pHandler) && handlerAvailable) {
try {
pHandler->serviceRequest(request, response);
responseCode = StrUtils::toString(response.getStatusCode());
const std::string& responseBody = response.getBody();
contentLength = responseBody.size();
if ((contentLength > 0) && !response.hasContentEncoding()) {
if (request.hasAcceptEncoding()) {
const std::string& acceptEncoding =
request.getAcceptEncoding();
if (StrUtils::containsString(acceptEncoding, GZIP) &&
m_server.compressionEnabled() &&
m_server.compressResponse(response.getContentType()) &&
contentLength >= m_server.minimumCompressionSize()) {
try {
const std::string compressedResponseBody =
StrUtils::gzipCompress(responseBody);
contentLength = compressedResponseBody.size();
response.setBody(compressedResponseBody);
response.setContentEncoding(GZIP);
} catch (const std::exception& e) {
Logger::error("unable to compress response");
}
}
}
}
response.populateWithHeaders(headers);
} catch (const BasicException& be) {
responseCode = HTTP::HTTP_RESP_SERV_ERR_INTERNAL_ERROR;
Logger::error("exception handling request: " + be.whatString());
} catch (const std::exception& e) {
responseCode = HTTP::HTTP_RESP_SERV_ERR_INTERNAL_ERROR;
Logger::error("exception handling request: " + std::string(e.what()));
} catch (...) {
responseCode = HTTP::HTTP_RESP_SERV_ERR_INTERNAL_ERROR;
Logger::error("unknown exception handling request");
}
}
if (contentLength > 0) {
headers.addPair(HTTP_CONTENT_LENGTH,
StrUtils::toString(contentLength));
} else {
headers.addPair(HTTP_CONTENT_LENGTH, ZERO);
}
// log the request
if (isThreadPooling()) {
const std::string& runByWorkerThreadId = getRunByThreadWorkerId();
if (!runByWorkerThreadId.empty()) {
m_server.logRequest(clientIPAddress,
request.getRequestLine(),
responseCode,
runByWorkerThreadId);
} else {
m_server.logRequest(clientIPAddress,
request.getRequestLine(),
responseCode);
}
} else {
m_server.logRequest(clientIPAddress,
request.getRequestLine(),
responseCode);
}
std::string responseAsString =
m_server.buildHeader(responseCode, headers);
if (contentLength > 0) {
responseAsString += response.getBody();
}
socket->write(responseAsString);
/*
if (isLoggingDebug) {
Logger::debug("response written, calling read so that client can close first");
}
// invoke a read to give the client the chance to close the socket
// first. this also lets us easily detect the close on the client
// end of the connection. we won't actually read any data here,
// this is just a wait to allow the client to close first
char readBuffer[5];
socket->read(readBuffer, 4);
//if (m_socketRequest != NULL) {
// m_socketRequest->requestComplete();
//}
*/
} else {
::printf("error: unable to initialize HttpRequest\n");
}
}
//******************************************************************************
<|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 <gdk/gdkkeysyms.h>
#include <X11/XF86keysym.h>
#include "chrome/browser/accelerator_table_linux.h"
#include "base/basictypes.h"
#include "chrome/app/chrome_dll_resource.h"
namespace browser {
// Keep this in sync with various context menus which display the accelerators.
const AcceleratorMapping kAcceleratorMap[] = {
// Focus.
{ GDK_k, IDC_FOCUS_SEARCH, GDK_CONTROL_MASK },
{ GDK_e, IDC_FOCUS_SEARCH, GDK_CONTROL_MASK },
{ XF86XK_Search, IDC_FOCUS_SEARCH, GdkModifierType(0) },
{ GDK_l, IDC_FOCUS_LOCATION, GDK_CONTROL_MASK },
{ GDK_d, IDC_FOCUS_LOCATION, GDK_MOD1_MASK },
{ GDK_F6, IDC_FOCUS_LOCATION, GdkModifierType(0) },
{ XF86XK_OpenURL, IDC_FOCUS_LOCATION, GdkModifierType(0) },
{ XF86XK_Go, IDC_FOCUS_LOCATION, GdkModifierType(0) },
// Tab/window controls.
{ GDK_Page_Down, IDC_SELECT_NEXT_TAB, GDK_CONTROL_MASK },
{ GDK_Page_Up, IDC_SELECT_PREVIOUS_TAB, GDK_CONTROL_MASK },
{ GDK_w, IDC_CLOSE_TAB, GDK_CONTROL_MASK },
{ GDK_t, IDC_RESTORE_TAB,
GdkModifierType(GDK_CONTROL_MASK | GDK_SHIFT_MASK) },
{ GDK_1, IDC_SELECT_TAB_0, GDK_CONTROL_MASK },
{ GDK_2, IDC_SELECT_TAB_1, GDK_CONTROL_MASK },
{ GDK_3, IDC_SELECT_TAB_2, GDK_CONTROL_MASK },
{ GDK_4, IDC_SELECT_TAB_3, GDK_CONTROL_MASK },
{ GDK_5, IDC_SELECT_TAB_4, GDK_CONTROL_MASK },
{ GDK_6, IDC_SELECT_TAB_5, GDK_CONTROL_MASK },
{ GDK_7, IDC_SELECT_TAB_6, GDK_CONTROL_MASK },
{ GDK_8, IDC_SELECT_TAB_7, GDK_CONTROL_MASK },
{ GDK_9, IDC_SELECT_LAST_TAB, GDK_CONTROL_MASK },
{ GDK_1, IDC_SELECT_TAB_0, GDK_MOD1_MASK },
{ GDK_2, IDC_SELECT_TAB_1, GDK_MOD1_MASK },
{ GDK_3, IDC_SELECT_TAB_2, GDK_MOD1_MASK },
{ GDK_4, IDC_SELECT_TAB_3, GDK_MOD1_MASK },
{ GDK_5, IDC_SELECT_TAB_4, GDK_MOD1_MASK },
{ GDK_6, IDC_SELECT_TAB_5, GDK_MOD1_MASK },
{ GDK_7, IDC_SELECT_TAB_6, GDK_MOD1_MASK },
{ GDK_8, IDC_SELECT_TAB_7, GDK_MOD1_MASK },
{ GDK_9, IDC_SELECT_LAST_TAB, GDK_MOD1_MASK },
{ GDK_F4, IDC_CLOSE_TAB, GDK_CONTROL_MASK },
{ GDK_F4, IDC_CLOSE_WINDOW, GDK_MOD1_MASK },
// Zoom level.
{ GDK_plus, IDC_ZOOM_PLUS,
GdkModifierType(GDK_CONTROL_MASK | GDK_SHIFT_MASK) },
{ GDK_equal, IDC_ZOOM_PLUS, GDK_CONTROL_MASK },
{ XF86XK_ZoomIn, IDC_ZOOM_PLUS, GdkModifierType(0) },
{ GDK_0, IDC_ZOOM_NORMAL, GDK_CONTROL_MASK },
{ GDK_minus, IDC_ZOOM_MINUS, GDK_CONTROL_MASK },
{ GDK_underscore, IDC_ZOOM_MINUS,
GdkModifierType(GDK_CONTROL_MASK | GDK_SHIFT_MASK) },
{ XF86XK_ZoomOut, IDC_ZOOM_MINUS, GdkModifierType(0) },
// Find in page.
{ GDK_g, IDC_FIND_NEXT, GDK_CONTROL_MASK },
{ GDK_F3, IDC_FIND_NEXT, GdkModifierType(0) },
{ GDK_g, IDC_FIND_PREVIOUS,
GdkModifierType(GDK_CONTROL_MASK | GDK_SHIFT_MASK) },
{ GDK_F3, IDC_FIND_PREVIOUS, GDK_SHIFT_MASK },
// Navigation / toolbar buttons.
{ GDK_Home, IDC_HOME, GDK_MOD1_MASK },
{ XF86XK_HomePage, IDC_HOME, GdkModifierType(0) },
{ GDK_Escape, IDC_STOP, GdkModifierType(0) },
{ XF86XK_Stop, IDC_STOP, GdkModifierType(0) },
{ GDK_Left, IDC_BACK, GDK_MOD1_MASK },
{ GDK_BackSpace, IDC_BACK, GdkModifierType(0) },
{ XF86XK_Back, IDC_BACK, GdkModifierType(0) },
{ GDK_Right, IDC_FORWARD, GDK_MOD1_MASK },
{ GDK_BackSpace, IDC_FORWARD, GDK_SHIFT_MASK },
{ XF86XK_Forward, IDC_FORWARD, GdkModifierType(0) },
{ GDK_r, IDC_RELOAD, GDK_CONTROL_MASK },
{ GDK_F5, IDC_RELOAD, GdkModifierType(0) },
{ GDK_F5, IDC_RELOAD, GDK_CONTROL_MASK },
{ GDK_F5, IDC_RELOAD, GDK_SHIFT_MASK },
{ XF86XK_Reload, IDC_RELOAD, GdkModifierType(0) },
{ XF86XK_Refresh, IDC_RELOAD, GdkModifierType(0) },
// Miscellany.
{ GDK_d, IDC_STAR, GDK_CONTROL_MASK },
{ XF86XK_AddFavorite, IDC_STAR, GdkModifierType(0) },
{ XF86XK_Favorites, IDC_SHOW_BOOKMARK_BAR, GdkModifierType(0) },
{ XF86XK_History, IDC_SHOW_HISTORY, GdkModifierType(0) },
{ GDK_o, IDC_OPEN_FILE, GDK_CONTROL_MASK },
{ GDK_F11, IDC_FULLSCREEN, GdkModifierType(0) },
{ GDK_u, IDC_VIEW_SOURCE, GDK_CONTROL_MASK },
{ GDK_p, IDC_PRINT, GDK_CONTROL_MASK },
{ GDK_Escape, IDC_TASK_MANAGER, GDK_SHIFT_MASK },
#if defined(OS_CHROMEOS)
{ GDK_f, IDC_FULLSCREEN,
GdkModifierType(GDK_CONTROL_MASK | GDK_MOD1_MASK) },
{ GDK_Delete, IDC_TASK_MANAGER,
GdkModifierType(GDK_CONTROL_MASK | GDK_MOD1_MASK) },
{ GDK_comma, IDC_CONTROL_PANEL, GdkModifierType(GDK_CONTROL_MASK) },
#endif
};
const size_t kAcceleratorMapLength = arraysize(kAcceleratorMap);
} // namespace browser
<commit_msg>GTK: Allow keypad to be used for all tab selection accelerators.<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 <gdk/gdkkeysyms.h>
#include <X11/XF86keysym.h>
#include "chrome/browser/accelerator_table_linux.h"
#include "base/basictypes.h"
#include "chrome/app/chrome_dll_resource.h"
namespace browser {
// Keep this in sync with various context menus which display the accelerators.
const AcceleratorMapping kAcceleratorMap[] = {
// Focus.
{ GDK_k, IDC_FOCUS_SEARCH, GDK_CONTROL_MASK },
{ GDK_e, IDC_FOCUS_SEARCH, GDK_CONTROL_MASK },
{ XF86XK_Search, IDC_FOCUS_SEARCH, GdkModifierType(0) },
{ GDK_l, IDC_FOCUS_LOCATION, GDK_CONTROL_MASK },
{ GDK_d, IDC_FOCUS_LOCATION, GDK_MOD1_MASK },
{ GDK_F6, IDC_FOCUS_LOCATION, GdkModifierType(0) },
{ XF86XK_OpenURL, IDC_FOCUS_LOCATION, GdkModifierType(0) },
{ XF86XK_Go, IDC_FOCUS_LOCATION, GdkModifierType(0) },
// Tab/window controls.
{ GDK_Page_Down, IDC_SELECT_NEXT_TAB, GDK_CONTROL_MASK },
{ GDK_Page_Up, IDC_SELECT_PREVIOUS_TAB, GDK_CONTROL_MASK },
{ GDK_w, IDC_CLOSE_TAB, GDK_CONTROL_MASK },
{ GDK_t, IDC_RESTORE_TAB,
GdkModifierType(GDK_CONTROL_MASK | GDK_SHIFT_MASK) },
{ GDK_1, IDC_SELECT_TAB_0, GDK_CONTROL_MASK },
{ GDK_2, IDC_SELECT_TAB_1, GDK_CONTROL_MASK },
{ GDK_3, IDC_SELECT_TAB_2, GDK_CONTROL_MASK },
{ GDK_4, IDC_SELECT_TAB_3, GDK_CONTROL_MASK },
{ GDK_5, IDC_SELECT_TAB_4, GDK_CONTROL_MASK },
{ GDK_6, IDC_SELECT_TAB_5, GDK_CONTROL_MASK },
{ GDK_7, IDC_SELECT_TAB_6, GDK_CONTROL_MASK },
{ GDK_8, IDC_SELECT_TAB_7, GDK_CONTROL_MASK },
{ GDK_9, IDC_SELECT_LAST_TAB, GDK_CONTROL_MASK },
{ GDK_1, IDC_SELECT_TAB_0, GDK_MOD1_MASK },
{ GDK_2, IDC_SELECT_TAB_1, GDK_MOD1_MASK },
{ GDK_3, IDC_SELECT_TAB_2, GDK_MOD1_MASK },
{ GDK_4, IDC_SELECT_TAB_3, GDK_MOD1_MASK },
{ GDK_5, IDC_SELECT_TAB_4, GDK_MOD1_MASK },
{ GDK_6, IDC_SELECT_TAB_5, GDK_MOD1_MASK },
{ GDK_7, IDC_SELECT_TAB_6, GDK_MOD1_MASK },
{ GDK_8, IDC_SELECT_TAB_7, GDK_MOD1_MASK },
{ GDK_9, IDC_SELECT_LAST_TAB, GDK_MOD1_MASK },
{ GDK_KP_1, IDC_SELECT_TAB_0, GDK_CONTROL_MASK },
{ GDK_KP_2, IDC_SELECT_TAB_1, GDK_CONTROL_MASK },
{ GDK_KP_3, IDC_SELECT_TAB_2, GDK_CONTROL_MASK },
{ GDK_KP_4, IDC_SELECT_TAB_3, GDK_CONTROL_MASK },
{ GDK_KP_5, IDC_SELECT_TAB_4, GDK_CONTROL_MASK },
{ GDK_KP_6, IDC_SELECT_TAB_5, GDK_CONTROL_MASK },
{ GDK_KP_7, IDC_SELECT_TAB_6, GDK_CONTROL_MASK },
{ GDK_KP_8, IDC_SELECT_TAB_7, GDK_CONTROL_MASK },
{ GDK_KP_9, IDC_SELECT_LAST_TAB, GDK_CONTROL_MASK },
{ GDK_KP_1, IDC_SELECT_TAB_0, GDK_MOD1_MASK },
{ GDK_KP_2, IDC_SELECT_TAB_1, GDK_MOD1_MASK },
{ GDK_KP_3, IDC_SELECT_TAB_2, GDK_MOD1_MASK },
{ GDK_KP_4, IDC_SELECT_TAB_3, GDK_MOD1_MASK },
{ GDK_KP_5, IDC_SELECT_TAB_4, GDK_MOD1_MASK },
{ GDK_KP_6, IDC_SELECT_TAB_5, GDK_MOD1_MASK },
{ GDK_KP_7, IDC_SELECT_TAB_6, GDK_MOD1_MASK },
{ GDK_KP_8, IDC_SELECT_TAB_7, GDK_MOD1_MASK },
{ GDK_KP_9, IDC_SELECT_LAST_TAB, GDK_MOD1_MASK },
{ GDK_F4, IDC_CLOSE_TAB, GDK_CONTROL_MASK },
{ GDK_F4, IDC_CLOSE_WINDOW, GDK_MOD1_MASK },
// Zoom level.
{ GDK_plus, IDC_ZOOM_PLUS,
GdkModifierType(GDK_CONTROL_MASK | GDK_SHIFT_MASK) },
{ GDK_equal, IDC_ZOOM_PLUS, GDK_CONTROL_MASK },
{ XF86XK_ZoomIn, IDC_ZOOM_PLUS, GdkModifierType(0) },
{ GDK_0, IDC_ZOOM_NORMAL, GDK_CONTROL_MASK },
{ GDK_minus, IDC_ZOOM_MINUS, GDK_CONTROL_MASK },
{ GDK_underscore, IDC_ZOOM_MINUS,
GdkModifierType(GDK_CONTROL_MASK | GDK_SHIFT_MASK) },
{ XF86XK_ZoomOut, IDC_ZOOM_MINUS, GdkModifierType(0) },
// Find in page.
{ GDK_g, IDC_FIND_NEXT, GDK_CONTROL_MASK },
{ GDK_F3, IDC_FIND_NEXT, GdkModifierType(0) },
{ GDK_g, IDC_FIND_PREVIOUS,
GdkModifierType(GDK_CONTROL_MASK | GDK_SHIFT_MASK) },
{ GDK_F3, IDC_FIND_PREVIOUS, GDK_SHIFT_MASK },
// Navigation / toolbar buttons.
{ GDK_Home, IDC_HOME, GDK_MOD1_MASK },
{ XF86XK_HomePage, IDC_HOME, GdkModifierType(0) },
{ GDK_Escape, IDC_STOP, GdkModifierType(0) },
{ XF86XK_Stop, IDC_STOP, GdkModifierType(0) },
{ GDK_Left, IDC_BACK, GDK_MOD1_MASK },
{ GDK_BackSpace, IDC_BACK, GdkModifierType(0) },
{ XF86XK_Back, IDC_BACK, GdkModifierType(0) },
{ GDK_Right, IDC_FORWARD, GDK_MOD1_MASK },
{ GDK_BackSpace, IDC_FORWARD, GDK_SHIFT_MASK },
{ XF86XK_Forward, IDC_FORWARD, GdkModifierType(0) },
{ GDK_r, IDC_RELOAD, GDK_CONTROL_MASK },
{ GDK_F5, IDC_RELOAD, GdkModifierType(0) },
{ GDK_F5, IDC_RELOAD, GDK_CONTROL_MASK },
{ GDK_F5, IDC_RELOAD, GDK_SHIFT_MASK },
{ XF86XK_Reload, IDC_RELOAD, GdkModifierType(0) },
{ XF86XK_Refresh, IDC_RELOAD, GdkModifierType(0) },
// Miscellany.
{ GDK_d, IDC_STAR, GDK_CONTROL_MASK },
{ XF86XK_AddFavorite, IDC_STAR, GdkModifierType(0) },
{ XF86XK_Favorites, IDC_SHOW_BOOKMARK_BAR, GdkModifierType(0) },
{ XF86XK_History, IDC_SHOW_HISTORY, GdkModifierType(0) },
{ GDK_o, IDC_OPEN_FILE, GDK_CONTROL_MASK },
{ GDK_F11, IDC_FULLSCREEN, GdkModifierType(0) },
{ GDK_u, IDC_VIEW_SOURCE, GDK_CONTROL_MASK },
{ GDK_p, IDC_PRINT, GDK_CONTROL_MASK },
{ GDK_Escape, IDC_TASK_MANAGER, GDK_SHIFT_MASK },
#if defined(OS_CHROMEOS)
{ GDK_f, IDC_FULLSCREEN,
GdkModifierType(GDK_CONTROL_MASK | GDK_MOD1_MASK) },
{ GDK_Delete, IDC_TASK_MANAGER,
GdkModifierType(GDK_CONTROL_MASK | GDK_MOD1_MASK) },
{ GDK_comma, IDC_CONTROL_PANEL, GdkModifierType(GDK_CONTROL_MASK) },
#endif
};
const size_t kAcceleratorMapLength = arraysize(kAcceleratorMap);
} // namespace browser
<|endoftext|> |
<commit_before>/*
Copyright (c) 2006, 2012, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "rpl_utility.h"
#include "rpl_rli.h"
/*********************************************************************
* table_def member definitions *
*********************************************************************/
/*
This function returns the field size in raw bytes based on the type
and the encoded field data from the master's raw data.
*/
uint32 table_def::calc_field_size(uint col, uchar *master_data) const
{
uint32 length;
switch (type(col)) {
case MYSQL_TYPE_NEWDECIMAL:
length= my_decimal_get_binary_size(m_field_metadata[col] >> 8,
m_field_metadata[col] & 0xff);
break;
case MYSQL_TYPE_DECIMAL:
case MYSQL_TYPE_FLOAT:
case MYSQL_TYPE_DOUBLE:
length= m_field_metadata[col];
break;
/*
The cases for SET and ENUM are include for completeness, however
both are mapped to type MYSQL_TYPE_STRING and their real types
are encoded in the field metadata.
*/
case MYSQL_TYPE_SET:
case MYSQL_TYPE_ENUM:
case MYSQL_TYPE_STRING:
{
uchar type= m_field_metadata[col] >> 8U;
if ((type == MYSQL_TYPE_SET) || (type == MYSQL_TYPE_ENUM))
length= m_field_metadata[col] & 0x00ff;
else
{
/*
We are reading the actual size from the master_data record
because this field has the actual lengh stored in the first
byte.
*/
length= (uint) *master_data + 1;
DBUG_ASSERT(length != 0);
}
break;
}
case MYSQL_TYPE_YEAR:
case MYSQL_TYPE_TINY:
length= 1;
break;
case MYSQL_TYPE_SHORT:
length= 2;
break;
case MYSQL_TYPE_INT24:
length= 3;
break;
case MYSQL_TYPE_LONG:
length= 4;
break;
#ifdef HAVE_LONG_LONG
case MYSQL_TYPE_LONGLONG:
length= 8;
break;
#endif
case MYSQL_TYPE_NULL:
length= 0;
break;
case MYSQL_TYPE_NEWDATE:
length= 3;
break;
case MYSQL_TYPE_DATE:
case MYSQL_TYPE_TIME:
length= 3;
break;
case MYSQL_TYPE_TIMESTAMP:
length= 4;
break;
case MYSQL_TYPE_DATETIME:
length= 8;
break;
case MYSQL_TYPE_BIT:
{
/*
Decode the size of the bit field from the master.
from_len is the length in bytes from the master
from_bit_len is the number of extra bits stored in the master record
If from_bit_len is not 0, add 1 to the length to account for accurate
number of bytes needed.
*/
uint from_len= (m_field_metadata[col] >> 8U) & 0x00ff;
uint from_bit_len= m_field_metadata[col] & 0x00ff;
DBUG_ASSERT(from_bit_len <= 7);
length= from_len + ((from_bit_len > 0) ? 1 : 0);
break;
}
case MYSQL_TYPE_VARCHAR:
{
length= m_field_metadata[col] > 255 ? 2 : 1; // c&p of Field_varstring::data_length()
DBUG_ASSERT(uint2korr(master_data) > 0);
length+= length == 1 ? (uint32) *master_data : uint2korr(master_data);
break;
}
case MYSQL_TYPE_TINY_BLOB:
case MYSQL_TYPE_MEDIUM_BLOB:
case MYSQL_TYPE_LONG_BLOB:
case MYSQL_TYPE_BLOB:
case MYSQL_TYPE_GEOMETRY:
{
#if 1
/*
BUG#29549:
This is currently broken for NDB, which is using big-endian
order when packing length of BLOB. Once they have decided how to
fix the issue, we can enable the code below to make sure to
always read the length in little-endian order.
*/
Field_blob fb(m_field_metadata[col]);
length= fb.get_packed_size(master_data, TRUE);
#else
/*
Compute the length of the data. We cannot use get_length() here
since it is dependent on the specific table (and also checks the
packlength using the internal 'table' pointer) and replication
is using a fixed format for storing data in the binlog.
*/
switch (m_field_metadata[col]) {
case 1:
length= *master_data;
break;
case 2:
length= uint2korr(master_data);
break;
case 3:
length= uint3korr(master_data);
break;
case 4:
length= uint4korr(master_data);
break;
default:
DBUG_ASSERT(0); // Should not come here
break;
}
length+= m_field_metadata[col];
#endif
break;
}
default:
length= ~(uint32) 0;
}
return length;
}
/*
Is the definition compatible with a table?
*/
int
table_def::compatible_with(Relay_log_info const *rli_arg, TABLE *table)
const
{
/*
We only check the initial columns for the tables.
*/
uint const cols_to_check= min(table->s->fields, size());
int error= 0;
Relay_log_info const *rli= const_cast<Relay_log_info*>(rli_arg);
TABLE_SHARE const *const tsh= table->s;
for (uint col= 0 ; col < cols_to_check ; ++col)
{
Field *const field= table->field[col];
if (field->type() != type(col))
{
DBUG_ASSERT(col < size() && col < tsh->fields);
DBUG_ASSERT(tsh->db.str && tsh->table_name.str);
error= 1;
char buf[256];
my_snprintf(buf, sizeof(buf), "Column %d type mismatch - "
"received type %d, %s.%s has type %d",
col, type(col), tsh->db.str, tsh->table_name.str,
field->type());
rli->report(ERROR_LEVEL, ER_BINLOG_ROW_WRONG_TABLE_DEF,
ER(ER_BINLOG_ROW_WRONG_TABLE_DEF), buf);
}
/*
Check the slave's field size against that of the master.
*/
if (!error &&
!field->compatible_field_size(field_metadata(col), rli_arg, m_flags))
{
error= 1;
char buf[256];
my_snprintf(buf, sizeof(buf), "Column %d size mismatch - "
"master has size %d, %s.%s on slave has size %d."
" Master's column size should be <= the slave's "
"column size.", col,
field->pack_length_from_metadata(m_field_metadata[col]),
tsh->db.str, tsh->table_name.str,
field->row_pack_length());
rli->report(ERROR_LEVEL, ER_BINLOG_ROW_WRONG_TABLE_DEF,
ER(ER_BINLOG_ROW_WRONG_TABLE_DEF), buf);
}
}
return error;
}
#ifndef MYSQL_CLIENT
Deferred_log_events::Deferred_log_events(Relay_log_info *rli) : last_added(NULL)
{
my_init_dynamic_array(&array, sizeof(Log_event *), 32, 16);
}
Deferred_log_events::~Deferred_log_events()
{
delete_dynamic(&array);
}
int Deferred_log_events::add(Log_event *ev)
{
last_added= ev;
insert_dynamic(&array, (uchar*) &ev);
return 0;
}
bool Deferred_log_events::is_empty()
{
return array.elements == 0;
}
bool Deferred_log_events::execute(Relay_log_info *rli)
{
bool res= false;
DBUG_ASSERT(rli->deferred_events_collecting);
rli->deferred_events_collecting= false;
for (uint i= 0; !res && i < array.elements; i++)
{
Log_event *ev= (* (Log_event **)
dynamic_array_ptr(&array, i));
res= ev->apply_event(rli);
}
rli->deferred_events_collecting= true;
return res;
}
void Deferred_log_events::rewind()
{
/*
Reset preceeding Query log event events which execution was
deferred because of slave side filtering.
*/
if (!is_empty())
{
for (uint i= 0; i < array.elements; i++)
{
Log_event *ev= *(Log_event **) dynamic_array_ptr(&array, i);
delete ev;
}
if (array.elements > array.max_element)
freeze_size(&array);
reset_dynamic(&array);
}
}
#endif
<commit_msg>Bug#16056813-MEMORY LEAK ON FILTERED SLAVE<commit_after>/*
Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "rpl_utility.h"
#include "rpl_rli.h"
/*********************************************************************
* table_def member definitions *
*********************************************************************/
/*
This function returns the field size in raw bytes based on the type
and the encoded field data from the master's raw data.
*/
uint32 table_def::calc_field_size(uint col, uchar *master_data) const
{
uint32 length;
switch (type(col)) {
case MYSQL_TYPE_NEWDECIMAL:
length= my_decimal_get_binary_size(m_field_metadata[col] >> 8,
m_field_metadata[col] & 0xff);
break;
case MYSQL_TYPE_DECIMAL:
case MYSQL_TYPE_FLOAT:
case MYSQL_TYPE_DOUBLE:
length= m_field_metadata[col];
break;
/*
The cases for SET and ENUM are include for completeness, however
both are mapped to type MYSQL_TYPE_STRING and their real types
are encoded in the field metadata.
*/
case MYSQL_TYPE_SET:
case MYSQL_TYPE_ENUM:
case MYSQL_TYPE_STRING:
{
uchar type= m_field_metadata[col] >> 8U;
if ((type == MYSQL_TYPE_SET) || (type == MYSQL_TYPE_ENUM))
length= m_field_metadata[col] & 0x00ff;
else
{
/*
We are reading the actual size from the master_data record
because this field has the actual lengh stored in the first
byte.
*/
length= (uint) *master_data + 1;
DBUG_ASSERT(length != 0);
}
break;
}
case MYSQL_TYPE_YEAR:
case MYSQL_TYPE_TINY:
length= 1;
break;
case MYSQL_TYPE_SHORT:
length= 2;
break;
case MYSQL_TYPE_INT24:
length= 3;
break;
case MYSQL_TYPE_LONG:
length= 4;
break;
#ifdef HAVE_LONG_LONG
case MYSQL_TYPE_LONGLONG:
length= 8;
break;
#endif
case MYSQL_TYPE_NULL:
length= 0;
break;
case MYSQL_TYPE_NEWDATE:
length= 3;
break;
case MYSQL_TYPE_DATE:
case MYSQL_TYPE_TIME:
length= 3;
break;
case MYSQL_TYPE_TIMESTAMP:
length= 4;
break;
case MYSQL_TYPE_DATETIME:
length= 8;
break;
case MYSQL_TYPE_BIT:
{
/*
Decode the size of the bit field from the master.
from_len is the length in bytes from the master
from_bit_len is the number of extra bits stored in the master record
If from_bit_len is not 0, add 1 to the length to account for accurate
number of bytes needed.
*/
uint from_len= (m_field_metadata[col] >> 8U) & 0x00ff;
uint from_bit_len= m_field_metadata[col] & 0x00ff;
DBUG_ASSERT(from_bit_len <= 7);
length= from_len + ((from_bit_len > 0) ? 1 : 0);
break;
}
case MYSQL_TYPE_VARCHAR:
{
length= m_field_metadata[col] > 255 ? 2 : 1; // c&p of Field_varstring::data_length()
DBUG_ASSERT(uint2korr(master_data) > 0);
length+= length == 1 ? (uint32) *master_data : uint2korr(master_data);
break;
}
case MYSQL_TYPE_TINY_BLOB:
case MYSQL_TYPE_MEDIUM_BLOB:
case MYSQL_TYPE_LONG_BLOB:
case MYSQL_TYPE_BLOB:
case MYSQL_TYPE_GEOMETRY:
{
#if 1
/*
BUG#29549:
This is currently broken for NDB, which is using big-endian
order when packing length of BLOB. Once they have decided how to
fix the issue, we can enable the code below to make sure to
always read the length in little-endian order.
*/
Field_blob fb(m_field_metadata[col]);
length= fb.get_packed_size(master_data, TRUE);
#else
/*
Compute the length of the data. We cannot use get_length() here
since it is dependent on the specific table (and also checks the
packlength using the internal 'table' pointer) and replication
is using a fixed format for storing data in the binlog.
*/
switch (m_field_metadata[col]) {
case 1:
length= *master_data;
break;
case 2:
length= uint2korr(master_data);
break;
case 3:
length= uint3korr(master_data);
break;
case 4:
length= uint4korr(master_data);
break;
default:
DBUG_ASSERT(0); // Should not come here
break;
}
length+= m_field_metadata[col];
#endif
break;
}
default:
length= ~(uint32) 0;
}
return length;
}
/*
Is the definition compatible with a table?
*/
int
table_def::compatible_with(Relay_log_info const *rli_arg, TABLE *table)
const
{
/*
We only check the initial columns for the tables.
*/
uint const cols_to_check= min(table->s->fields, size());
int error= 0;
Relay_log_info const *rli= const_cast<Relay_log_info*>(rli_arg);
TABLE_SHARE const *const tsh= table->s;
for (uint col= 0 ; col < cols_to_check ; ++col)
{
Field *const field= table->field[col];
if (field->type() != type(col))
{
DBUG_ASSERT(col < size() && col < tsh->fields);
DBUG_ASSERT(tsh->db.str && tsh->table_name.str);
error= 1;
char buf[256];
my_snprintf(buf, sizeof(buf), "Column %d type mismatch - "
"received type %d, %s.%s has type %d",
col, type(col), tsh->db.str, tsh->table_name.str,
field->type());
rli->report(ERROR_LEVEL, ER_BINLOG_ROW_WRONG_TABLE_DEF,
ER(ER_BINLOG_ROW_WRONG_TABLE_DEF), buf);
}
/*
Check the slave's field size against that of the master.
*/
if (!error &&
!field->compatible_field_size(field_metadata(col), rli_arg, m_flags))
{
error= 1;
char buf[256];
my_snprintf(buf, sizeof(buf), "Column %d size mismatch - "
"master has size %d, %s.%s on slave has size %d."
" Master's column size should be <= the slave's "
"column size.", col,
field->pack_length_from_metadata(m_field_metadata[col]),
tsh->db.str, tsh->table_name.str,
field->row_pack_length());
rli->report(ERROR_LEVEL, ER_BINLOG_ROW_WRONG_TABLE_DEF,
ER(ER_BINLOG_ROW_WRONG_TABLE_DEF), buf);
}
}
return error;
}
#ifndef MYSQL_CLIENT
Deferred_log_events::Deferred_log_events(Relay_log_info *rli) : last_added(NULL)
{
my_init_dynamic_array(&array, sizeof(Log_event *), 32, 16);
}
Deferred_log_events::~Deferred_log_events()
{
delete_dynamic(&array);
}
int Deferred_log_events::add(Log_event *ev)
{
last_added= ev;
insert_dynamic(&array, (uchar*) &ev);
return 0;
}
bool Deferred_log_events::is_empty()
{
return array.elements == 0;
}
bool Deferred_log_events::execute(Relay_log_info *rli)
{
bool res= false;
DBUG_ASSERT(rli->deferred_events_collecting);
rli->deferred_events_collecting= false;
for (uint i= 0; !res && i < array.elements; i++)
{
Log_event *ev= (* (Log_event **)
dynamic_array_ptr(&array, i));
res= ev->apply_event(rli);
}
rli->deferred_events_collecting= true;
return res;
}
void Deferred_log_events::rewind()
{
/*
Reset preceeding Query log event events which execution was
deferred because of slave side filtering.
*/
if (!is_empty())
{
for (uint i= 0; i < array.elements; i++)
{
Log_event *ev= *(Log_event **) dynamic_array_ptr(&array, i);
delete ev;
}
last_added= NULL;
if (array.elements > array.max_element)
freeze_size(&array);
reset_dynamic(&array);
}
}
#endif
<|endoftext|> |
<commit_before>#include <BALL/VIEW/WIDGETS/HTMLView.h>
#include <BALL/VIEW/WIDGETS/HTMLPage.h>
#ifdef BALL_OS_DARWIN
# include <OpenGL/gl.h>
#else
# include <GL/gl.h>
#endif
namespace BALL
{
namespace VIEW
{
HTMLView::HTMLView(QWidget* parent)
: QWebEngineView(parent)
{
setPage(new HTMLPage(this));
setAttribute(Qt::WA_DontCreateNativeAncestors);
hide(); // hiding WebEngine widgets seems to be sufficient to prevent nouveau-related crashes
}
HTMLView::~HTMLView()
{}
HTMLViewDock::HTMLViewDock(HTMLView* view, QWidget* parent, const char* title)
: DockWidget(parent, title),
skip_checks_(false),
show_error_(false),
html_view_(0)
{
checkForIncompatibleDrivers_();
setHTMLView(view);
registerWidget(this);
}
HTMLViewDock::HTMLViewDock(QWidget* parent, const char* title)
: DockWidget(parent, title),
skip_checks_(false),
show_error_(false),
html_view_(0)
{
checkForIncompatibleDrivers_();
setHTMLView(new HTMLView(this));
registerWidget(this);
}
void HTMLViewDock::setHTMLView(HTMLView* html_view) {
if (!html_view)
{
return;
}
if (html_view != html_view_)
{
delete html_view_;
html_view_ = html_view;
}
if (!skip_checks_ && show_error_)
{
// In case of an error, replace the original widget with an error message
// but still keep it as a member (hidden!) so that it can be restored if
// the user decides to disable the driver checks.
setWidget(new HTMLViewErrorWidget(this));
return;
}
setWidget(html_view_);
}
void HTMLViewDock::resetHTMLView(bool skip_checks)
{
skip_checks_ = skip_checks;
setHTMLView(html_view_);
}
void HTMLViewDock::checkForIncompatibleDrivers_()
{
show_error_ = false;
char* vendor = (char*) glGetString(GL_VENDOR);
if (vendor)
{
show_error_ = String(vendor) == "nouveau";
}
}
}
}
<commit_msg>Fix GL redefintion errors on MSVC<commit_after>#include <BALL/VIEW/WIDGETS/HTMLView.h>
#include<BALL/VIEW/RENDERING/RENDERERS/glRenderer.h>
#include <BALL/VIEW/WIDGETS/HTMLPage.h>
namespace BALL
{
namespace VIEW
{
HTMLView::HTMLView(QWidget* parent)
: QWebEngineView(parent)
{
setPage(new HTMLPage(this));
setAttribute(Qt::WA_DontCreateNativeAncestors);
hide(); // hiding WebEngine widgets seems to be sufficient to prevent nouveau-related crashes
}
HTMLView::~HTMLView()
{}
HTMLViewDock::HTMLViewDock(HTMLView* view, QWidget* parent, const char* title)
: DockWidget(parent, title),
skip_checks_(false),
show_error_(false),
html_view_(0)
{
checkForIncompatibleDrivers_();
setHTMLView(view);
registerWidget(this);
}
HTMLViewDock::HTMLViewDock(QWidget* parent, const char* title)
: DockWidget(parent, title),
skip_checks_(false),
show_error_(false),
html_view_(0)
{
checkForIncompatibleDrivers_();
setHTMLView(new HTMLView(this));
registerWidget(this);
}
void HTMLViewDock::setHTMLView(HTMLView* html_view) {
if (!html_view)
{
return;
}
if (html_view != html_view_)
{
delete html_view_;
html_view_ = html_view;
}
if (!skip_checks_ && show_error_)
{
// In case of an error, replace the original widget with an error message
// but still keep it as a member (hidden!) so that it can be restored if
// the user decides to disable the driver checks.
setWidget(new HTMLViewErrorWidget(this));
return;
}
setWidget(html_view_);
}
void HTMLViewDock::resetHTMLView(bool skip_checks)
{
skip_checks_ = skip_checks;
setHTMLView(html_view_);
}
void HTMLViewDock::checkForIncompatibleDrivers_()
{
GLRenderer glr();
String vendor = glr.getVendor();
if (!vendor.empty() && vendor == "nouveau")
{
show_error_ = true;
}
}
}
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2014 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "TestUtil.h"
#include "IndexletManager.h"
#include "StringUtil.h"
namespace RAMCloud {
class IndexletManagerTest : public ::testing::Test {
public:
Context context;
IndexletManager im;
IndexletManagerTest()
: context()
, im(&context)
{
}
DISALLOW_COPY_AND_ASSIGN(IndexletManagerTest);
};
TEST_F(IndexletManagerTest, constructor) {
EXPECT_EQ(0U, im.indexletMap.size());
}
TEST_F(IndexletManagerTest, addIndexlet) {
string key1 = "a";
string key2 = "c";
string key3 = "f";
string key4 = "k";
string key5 = "u";
EXPECT_TRUE(im.addIndexlet(0, 0, key2.c_str(),
(uint16_t)key2.length(), key4.c_str(), (uint16_t)key4.length()));
EXPECT_FALSE(im.addIndexlet(0, 0, key2.c_str(),
(uint16_t)key2.length(), key4.c_str(), (uint16_t)key4.length()));
EXPECT_TRUE(im.addIndexlet(0, 0, key1.c_str(),
(uint16_t)key1.length(), key2.c_str(), (uint16_t)key2.length()));
EXPECT_TRUE(im.addIndexlet(0, 0, key4.c_str(),
(uint16_t)key4.length(), key5.c_str(), (uint16_t)key5.length()));
EXPECT_FALSE(im.addIndexlet(0, 0, key1.c_str(),
(uint16_t)key1.length(), key3.c_str(), (uint16_t)key3.length()));
SpinLock lock;
IndexletManager::Lock fakeGuard(lock);
IndexletManager::Indexlet* indexlet = &im.lookup(0, 0, key2.c_str(),
(uint16_t)key2.length(), fakeGuard)->second;
string firstKey = StringUtil::binaryToString(
indexlet->firstKey, indexlet->firstKeyLength);
string firstNotOwnedKey = StringUtil::binaryToString(
indexlet->firstNotOwnedKey, indexlet->firstNotOwnedKeyLength);
EXPECT_EQ(0, firstKey.compare("c"));
EXPECT_EQ(0, firstNotOwnedKey.compare("k"));
}
TEST_F(IndexletManagerTest, getIndexlet) {
string key1 = "a";
string key2 = "c";
string key3 = "f";
string key4 = "k";
string key5 = "u";
EXPECT_FALSE(im.getIndexlet(0, 0, key2.c_str(),
(uint16_t)key2.length(), key4.c_str(), (uint16_t)key4.length()));
im.addIndexlet(0, 0, key2.c_str(),
(uint16_t)key2.length(), key4.c_str(), (uint16_t)key4.length());
EXPECT_TRUE(im.getIndexlet(0, 0, key2.c_str(),
(uint16_t)key2.length(), key4.c_str(), (uint16_t)key4.length()));
EXPECT_FALSE(im.getIndexlet(1, 0, key2.c_str(),
(uint16_t)key2.length(), key4.c_str(), (uint16_t)key4.length()));
EXPECT_FALSE(im.getIndexlet(0, 1, key2.c_str(),
(uint16_t)key2.length(), key4.c_str(), (uint16_t)key4.length()));
EXPECT_FALSE(im.getIndexlet(0, 0, key2.c_str(),
(uint16_t)key2.length(), key3.c_str(), (uint16_t)key3.length()));
EXPECT_FALSE(im.getIndexlet(0, 0, key3.c_str(),
(uint16_t)key3.length(), key4.c_str(), (uint16_t)key4.length()));
EXPECT_FALSE(im.getIndexlet(0, 0, key1.c_str(),
(uint16_t)key1.length(), key4.c_str(), (uint16_t)key4.length()));
EXPECT_FALSE(im.getIndexlet(0, 1, key2.c_str(),
(uint16_t)key2.length(), key5.c_str(), (uint16_t)key5.length()));
EXPECT_FALSE(im.getIndexlet(0, 1, key1.c_str(),
(uint16_t)key1.length(), key5.c_str(), (uint16_t)key5.length()));
IndexletManager::Indexlet* indexlet =
im.getIndexlet(0, 0, key2.c_str(), (uint16_t)key2.length(),
key4.c_str(), (uint16_t)key4.length());
EXPECT_TRUE(indexlet);
string firstKey = StringUtil::binaryToString(
indexlet->firstKey, indexlet->firstKeyLength);
string firstNotOwnedKey = StringUtil::binaryToString(
indexlet->firstNotOwnedKey, indexlet->firstNotOwnedKeyLength);
EXPECT_EQ(0, firstKey.compare("c"));
EXPECT_EQ(0, firstNotOwnedKey.compare("k"));
}
TEST_F(IndexletManagerTest, deleteIndexlet) {
string key1 = "a";
string key2 = "c";
string key3 = "f";
string key4 = "k";
string key5 = "u";
//TODO(ashgup): add comments on each individual test
EXPECT_FALSE(im.getIndexlet(0, 0, key2.c_str(),
(uint16_t)key2.length(), key4.c_str(), (uint16_t)key4.length()));
im.addIndexlet(0, 0, key2.c_str(),
(uint16_t)key2.length(), key4.c_str(), (uint16_t)key4.length());
EXPECT_TRUE(im.getIndexlet(0, 0, key2.c_str(),
(uint16_t)key2.length(), key4.c_str(), (uint16_t)key4.length()));
EXPECT_TRUE(im.deleteIndexlet(0, 0, key2.c_str(),
(uint16_t)key2.length(), key4.c_str(), (uint16_t)key4.length()));
EXPECT_FALSE(im.getIndexlet(0, 0, key2.c_str(),
(uint16_t)key2.length(), key4.c_str(), (uint16_t)key4.length()));
EXPECT_FALSE(im.deleteIndexlet(0, 0, key2.c_str(),
(uint16_t)key2.length(), key4.c_str(), (uint16_t)key4.length()));
im.addIndexlet(0, 0, key2.c_str(),
(uint16_t)key2.length(), key4.c_str(), (uint16_t)key4.length());
EXPECT_FALSE(im.deleteIndexlet(0, 0, key2.c_str(),
(uint16_t)key2.length(), key5.c_str(), (uint16_t)key5.length()));
EXPECT_FALSE(im.deleteIndexlet(0, 0, key1.c_str(),
(uint16_t)key1.length(), key4.c_str(), (uint16_t)key4.length()));
}
} // namespace RAMCloud
<commit_msg>Adding unit test for IndexletManager::compareKey().<commit_after>/* Copyright (c) 2014 Stanford University
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "TestUtil.h"
#include "IndexletManager.h"
#include "RamCloud.h"
#include "StringUtil.h"
namespace RAMCloud {
class IndexletManagerTest : public ::testing::Test {
public:
Context context;
IndexletManager im;
IndexletManagerTest()
: context()
, im(&context)
{
}
DISALLOW_COPY_AND_ASSIGN(IndexletManagerTest);
};
TEST_F(IndexletManagerTest, constructor) {
EXPECT_EQ(0U, im.indexletMap.size());
}
TEST_F(IndexletManagerTest, addIndexlet) {
string key1 = "a";
string key2 = "c";
string key3 = "f";
string key4 = "k";
string key5 = "u";
EXPECT_TRUE(im.addIndexlet(0, 0, key2.c_str(),
(uint16_t)key2.length(), key4.c_str(), (uint16_t)key4.length()));
EXPECT_FALSE(im.addIndexlet(0, 0, key2.c_str(),
(uint16_t)key2.length(), key4.c_str(), (uint16_t)key4.length()));
EXPECT_TRUE(im.addIndexlet(0, 0, key1.c_str(),
(uint16_t)key1.length(), key2.c_str(), (uint16_t)key2.length()));
EXPECT_TRUE(im.addIndexlet(0, 0, key4.c_str(),
(uint16_t)key4.length(), key5.c_str(), (uint16_t)key5.length()));
EXPECT_FALSE(im.addIndexlet(0, 0, key1.c_str(),
(uint16_t)key1.length(), key3.c_str(), (uint16_t)key3.length()));
SpinLock lock;
IndexletManager::Lock fakeGuard(lock);
IndexletManager::Indexlet* indexlet = &im.lookup(0, 0, key2.c_str(),
(uint16_t)key2.length(), fakeGuard)->second;
string firstKey = StringUtil::binaryToString(
indexlet->firstKey, indexlet->firstKeyLength);
string firstNotOwnedKey = StringUtil::binaryToString(
indexlet->firstNotOwnedKey, indexlet->firstNotOwnedKeyLength);
EXPECT_EQ(0, firstKey.compare("c"));
EXPECT_EQ(0, firstNotOwnedKey.compare("k"));
}
TEST_F(IndexletManagerTest, getIndexlet) {
string key1 = "a";
string key2 = "c";
string key3 = "f";
string key4 = "k";
string key5 = "u";
EXPECT_FALSE(im.getIndexlet(0, 0, key2.c_str(),
(uint16_t)key2.length(), key4.c_str(), (uint16_t)key4.length()));
im.addIndexlet(0, 0, key2.c_str(),
(uint16_t)key2.length(), key4.c_str(), (uint16_t)key4.length());
EXPECT_TRUE(im.getIndexlet(0, 0, key2.c_str(),
(uint16_t)key2.length(), key4.c_str(), (uint16_t)key4.length()));
EXPECT_FALSE(im.getIndexlet(1, 0, key2.c_str(),
(uint16_t)key2.length(), key4.c_str(), (uint16_t)key4.length()));
EXPECT_FALSE(im.getIndexlet(0, 1, key2.c_str(),
(uint16_t)key2.length(), key4.c_str(), (uint16_t)key4.length()));
EXPECT_FALSE(im.getIndexlet(0, 0, key2.c_str(),
(uint16_t)key2.length(), key3.c_str(), (uint16_t)key3.length()));
EXPECT_FALSE(im.getIndexlet(0, 0, key3.c_str(),
(uint16_t)key3.length(), key4.c_str(), (uint16_t)key4.length()));
EXPECT_FALSE(im.getIndexlet(0, 0, key1.c_str(),
(uint16_t)key1.length(), key4.c_str(), (uint16_t)key4.length()));
EXPECT_FALSE(im.getIndexlet(0, 1, key2.c_str(),
(uint16_t)key2.length(), key5.c_str(), (uint16_t)key5.length()));
EXPECT_FALSE(im.getIndexlet(0, 1, key1.c_str(),
(uint16_t)key1.length(), key5.c_str(), (uint16_t)key5.length()));
IndexletManager::Indexlet* indexlet =
im.getIndexlet(0, 0, key2.c_str(), (uint16_t)key2.length(),
key4.c_str(), (uint16_t)key4.length());
EXPECT_TRUE(indexlet);
string firstKey = StringUtil::binaryToString(
indexlet->firstKey, indexlet->firstKeyLength);
string firstNotOwnedKey = StringUtil::binaryToString(
indexlet->firstNotOwnedKey, indexlet->firstNotOwnedKeyLength);
EXPECT_EQ(0, firstKey.compare("c"));
EXPECT_EQ(0, firstNotOwnedKey.compare("k"));
}
TEST_F(IndexletManagerTest, deleteIndexlet) {
string key1 = "a";
string key2 = "c";
string key3 = "f";
string key4 = "k";
string key5 = "u";
//TODO(ashgup): add comments on each individual test
EXPECT_FALSE(im.getIndexlet(0, 0, key2.c_str(),
(uint16_t)key2.length(), key4.c_str(), (uint16_t)key4.length()));
im.addIndexlet(0, 0, key2.c_str(),
(uint16_t)key2.length(), key4.c_str(), (uint16_t)key4.length());
EXPECT_TRUE(im.getIndexlet(0, 0, key2.c_str(),
(uint16_t)key2.length(), key4.c_str(), (uint16_t)key4.length()));
EXPECT_TRUE(im.deleteIndexlet(0, 0, key2.c_str(),
(uint16_t)key2.length(), key4.c_str(), (uint16_t)key4.length()));
EXPECT_FALSE(im.getIndexlet(0, 0, key2.c_str(),
(uint16_t)key2.length(), key4.c_str(), (uint16_t)key4.length()));
EXPECT_FALSE(im.deleteIndexlet(0, 0, key2.c_str(),
(uint16_t)key2.length(), key4.c_str(), (uint16_t)key4.length()));
im.addIndexlet(0, 0, key2.c_str(),
(uint16_t)key2.length(), key4.c_str(), (uint16_t)key4.length());
EXPECT_FALSE(im.deleteIndexlet(0, 0, key2.c_str(),
(uint16_t)key2.length(), key5.c_str(), (uint16_t)key5.length()));
EXPECT_FALSE(im.deleteIndexlet(0, 0, key1.c_str(),
(uint16_t)key1.length(), key4.c_str(), (uint16_t)key4.length()));
}
TEST_F(IndexletManagerTest, compareKey)
{
// Construct Object obj.
uint64_t tableId = 1;
uint8_t numKeys = 3;
KeyInfo keyList[3];
keyList[0].keyLength = 8;
keyList[0].key = "objkey0";
keyList[1].keyLength = 8;
keyList[1].key = "objkey1";
keyList[2].keyLength = 8;
keyList[2].key = "objkey2";
const void* value = "objvalue";
uint32_t valueLength = 9;
Buffer keysAndValueBuffer;
Object::appendKeysAndValueToBuffer(tableId, numKeys, keyList,
value, valueLength, keysAndValueBuffer);
Object obj(tableId, 1, 0, keysAndValueBuffer);
// Compare key for key index 1 of obj (called: "key") for different cases.
// Case0: firstKeyLength = keyLength = lastKeyLength and
// firstKey > key < lastKey
IndexletManager::KeyRange testRange0 = {1, "objkey2", 8, "objkey2", 8};
bool isInRange0 = IndexletManager::compareKey(&obj, &testRange0);
EXPECT_FALSE(isInRange0);
// Case1: firstKeyLength = keyLength = lastKeyLength and
// firstKey < key > lastKey
IndexletManager::KeyRange testRange1 = {1, "objkey0", 8, "objkey0", 8};
bool isInRange1 = IndexletManager::compareKey(&obj, &testRange1);
EXPECT_FALSE(isInRange1);
// Case2: firstKeyLength = keyLength = lastKeyLength and
// firstKey > key > lastKey
IndexletManager::KeyRange testRange2 = {1, "objkey2", 8, "objkey0", 8};
bool isInRange2 = IndexletManager::compareKey(&obj, &testRange2);
EXPECT_FALSE(isInRange2);
// Case3: firstKeyLength = keyLength = lastKeyLength and
// firstKey < key < lastKey
IndexletManager::KeyRange testRange3 = {1, "objkey0", 8, "objkey2", 8};
bool isInRange3 = IndexletManager::compareKey(&obj, &testRange3);
EXPECT_TRUE(isInRange3);
// Case4: firstKeyLength = keyLength = lastKeyLength and
// firstKey = key = lastKey
IndexletManager::KeyRange testRange4 = {1, "objkey1", 8, "objkey1", 8};
bool isInRange4 = IndexletManager::compareKey(&obj, &testRange4);
EXPECT_TRUE(isInRange4);
// Case5: firstKeyLength < keyLength < lastKeyLength and
// firstKey = key substring and key = lastKey substring
IndexletManager::KeyRange testRange5 = {1, "obj", 4, "objkey11", 9};
bool isInRange5 = IndexletManager::compareKey(&obj, &testRange5);
EXPECT_TRUE(isInRange5);
// Case6: firstKeyLength > keyLength < lastKeyLength and
// firstKey substring = key = lastKey substring
IndexletManager::KeyRange testRange6 = {1, "objkey11", 9, "objkey11", 9};
bool isInRange6 = IndexletManager::compareKey(&obj, &testRange6);
EXPECT_FALSE(isInRange6);
// Case7: firstKeyLength < keyLength > lastKeyLength and
// firstKey = key substring = lastKey
IndexletManager::KeyRange testRange7 = {1, "obj", 4, "obj", 4};
bool isInRange7 = IndexletManager::compareKey(&obj, &testRange7);
EXPECT_FALSE(isInRange7);
}
} // namespace RAMCloud
<|endoftext|> |
<commit_before>// Copyright (c) 2006-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 <string>
#include "base/file_util.h"
#include "base/scoped_temp_dir.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "chrome/browser/download/save_package.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
static const FilePath::CharType* kTestDir = FILE_PATH_LITERAL("encoding_tests");
class BrowserEncodingTest : public UITest {
protected:
BrowserEncodingTest() : UITest() {}
// Make sure the content of the page are as expected
// after override or auto-detect
void CheckFile(const FilePath& generated_file,
const FilePath& expected_result_file,
bool check_equal) {
FilePath expected_result_filepath = UITest::GetTestFilePath(
FilePath(kTestDir).ToWStringHack(),
expected_result_file.ToWStringHack());
ASSERT_TRUE(file_util::PathExists(expected_result_filepath));
WaitForGeneratedFileAndCheck(generated_file,
expected_result_filepath,
true, // We do care whether they are equal.
check_equal,
true); // Delete the generated file when done.
}
virtual void SetUp() {
UITest::SetUp();
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
save_dir_ = temp_dir_.path();
temp_sub_resource_dir_ = save_dir_.AppendASCII("sub_resource_files");
}
ScopedTempDir temp_dir_;
FilePath save_dir_;
FilePath temp_sub_resource_dir_;
};
// TODO(jnd): 1. Some encodings are missing here. It'll be added later. See
// http://crbug.com/13306.
// 2. Add more files with multiple encoding name variants for each canonical
// encoding name). Webkit layout tests cover some, but testing in the UI test is
// also necessary.
TEST_F(BrowserEncodingTest, TestEncodingAliasMapping) {
struct EncodingTestData {
const char* file_name;
const char* encoding_name;
};
const EncodingTestData kEncodingTestDatas[] = {
{ "Big5.html", "Big5" },
{ "EUC-JP.html", "EUC-JP" },
{ "gb18030.html", "gb18030" },
{ "iso-8859-1.html", "ISO-8859-1" },
{ "ISO-8859-2.html", "ISO-8859-2" },
{ "ISO-8859-4.html", "ISO-8859-4" },
{ "ISO-8859-5.html", "ISO-8859-5" },
{ "ISO-8859-6.html", "ISO-8859-6" },
{ "ISO-8859-7.html", "ISO-8859-7" },
{ "ISO-8859-8.html", "ISO-8859-8" },
{ "ISO-8859-13.html", "ISO-8859-13" },
{ "ISO-8859-15.html", "ISO-8859-15" },
{ "KOI8-R.html", "KOI8-R" },
{ "KOI8-U.html", "KOI8-U" },
{ "macintosh.html", "macintosh" },
{ "Shift-JIS.html", "Shift_JIS" },
{ "US-ASCII.html", "ISO-8859-1" }, // http://crbug.com/15801
{ "UTF-8.html", "UTF-8" },
{ "UTF-16LE.html", "UTF-16LE" },
{ "windows-874.html", "windows-874" },
{ "windows-949.html", "windows-949" },
{ "windows-1250.html", "windows-1250" },
{ "windows-1251.html", "windows-1251" },
{ "windows-1252.html", "windows-1252" },
{ "windows-1253.html", "windows-1253" },
{ "windows-1254.html", "windows-1254" },
{ "windows-1255.html", "windows-1255" },
{ "windows-1256.html", "windows-1256" },
{ "windows-1257.html", "windows-1257" },
{ "windows-1258.html", "windows-1258" }
};
const char* const kAliasTestDir = "alias_mapping";
FilePath test_dir_path = FilePath(kTestDir).AppendASCII(kAliasTestDir);
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kEncodingTestDatas); ++i) {
FilePath test_file_path(test_dir_path);
test_file_path = test_file_path.AppendASCII(
kEncodingTestDatas[i].file_name);
GURL url =
URLRequestMockHTTPJob::GetMockUrl(test_file_path.ToWStringHack());
scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
ASSERT_TRUE(tab_proxy.get());
ASSERT_TRUE(tab_proxy->NavigateToURL(url));
WaitUntilTabCount(1);
std::string encoding;
EXPECT_TRUE(tab_proxy->GetPageCurrentEncoding(&encoding));
EXPECT_EQ(encoding, kEncodingTestDatas[i].encoding_name);
}
}
#if defined(OS_WIN)
// We are disabling this test on MacOS and Linux because on those platforms
// AutomationProvider::OverrideEncoding is not implemented yet.
// TODO(port): Enable when encoding-related parts of Browser are ported.
TEST_F(BrowserEncodingTest, TestOverrideEncoding) {
const char* const kTestFileName = "gb18030_with_iso88591_meta.html";
const char* const kExpectedFileName =
"expected_gb18030_saved_from_iso88591_meta.html";
const char* const kOverrideTestDir = "user_override";
FilePath test_dir_path = FilePath(kTestDir).AppendASCII(kOverrideTestDir);
test_dir_path = test_dir_path.AppendASCII(kTestFileName);
GURL url = URLRequestMockHTTPJob::GetMockUrl(test_dir_path.ToWStringHack());
scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
ASSERT_TRUE(tab_proxy.get());
ASSERT_TRUE(tab_proxy->NavigateToURL(url));
WaitUntilTabCount(1);
// Get the encoding declared in the page.
std::string encoding;
EXPECT_TRUE(tab_proxy->GetPageCurrentEncoding(&encoding));
EXPECT_EQ(encoding, "ISO-8859-1");
// Override the encoding to "gb18030".
int64 last_nav_time = 0;
EXPECT_TRUE(tab_proxy->GetLastNavigationTime(&last_nav_time));
EXPECT_TRUE(tab_proxy->OverrideEncoding("gb18030"));
EXPECT_TRUE(tab_proxy->WaitForNavigation(last_nav_time));
// Re-get the encoding of page. It should be gb18030.
EXPECT_TRUE(tab_proxy->GetPageCurrentEncoding(&encoding));
EXPECT_EQ(encoding, "gb18030");
// Dump the page, the content of dump page should be identical to the
// expected result file.
FilePath full_file_name = save_dir_.AppendASCII(kTestFileName);
// We save the page as way of complete HTML file, which requires a directory
// name to save sub resources in it. Although this test file does not have
// sub resources, but the directory name is still required.
EXPECT_TRUE(tab_proxy->SavePage(full_file_name.ToWStringHack(),
temp_sub_resource_dir_.ToWStringHack(),
SavePackage::SAVE_AS_COMPLETE_HTML));
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
EXPECT_TRUE(WaitForDownloadShelfVisible(browser.get()));
FilePath expected_file_name = FilePath().AppendASCII(kOverrideTestDir);
expected_file_name = expected_file_name.AppendASCII(kExpectedFileName);
CheckFile(full_file_name, expected_file_name, true);
}
#endif // defined(OS_WIN)
// The following encodings are excluded from the auto-detection test because
// it's a known issue that the current encoding detector does not detect them:
// ISO-8859-4
// ISO-8859-13
// KOI8-U
// macintosh
// windows-874
// windows-1252
// windows-1253
// windows-1257
// windows-1258
// For Hebrew, the expected encoding value is ISO-8859-8-I. See
// http://crbug.com/2927 for more details.
TEST_F(BrowserEncodingTest, TestEncodingAutoDetect) {
struct EncodingAutoDetectTestData {
const char* test_file_name; // File name of test data.
const char* expected_result; // File name of expected results.
const char* expected_encoding; // expected encoding.
};
const EncodingAutoDetectTestData kTestDatas[] = {
{ "Big5_with_no_encoding_specified.html",
"expected_Big5_saved_from_no_encoding_specified.html",
"Big5" },
{ "gb18030_with_no_encoding_specified.html",
"expected_gb18030_saved_from_no_encoding_specified.html",
"gb18030" },
{ "iso-8859-1_with_no_encoding_specified.html",
"expected_iso-8859-1_saved_from_no_encoding_specified.html",
"ISO-8859-1" },
{ "ISO-8859-5_with_no_encoding_specified.html",
"expected_ISO-8859-5_saved_from_no_encoding_specified.html",
"ISO-8859-5" },
{ "ISO-8859-6_with_no_encoding_specified.html",
"expected_ISO-8859-6_saved_from_no_encoding_specified.html",
"ISO-8859-6" },
{ "ISO-8859-7_with_no_encoding_specified.html",
"expected_ISO-8859-7_saved_from_no_encoding_specified.html",
"ISO-8859-7" },
{ "ISO-8859-8_with_no_encoding_specified.html",
"expected_ISO-8859-8_saved_from_no_encoding_specified.html",
"ISO-8859-8-I" },
{ "KOI8-R_with_no_encoding_specified.html",
"expected_KOI8-R_saved_from_no_encoding_specified.html",
"KOI8-R" },
{ "Shift-JIS_with_no_encoding_specified.html",
"expected_Shift-JIS_saved_from_no_encoding_specified.html",
"Shift_JIS" },
{ "UTF-8_with_no_encoding_specified.html",
"expected_UTF-8_saved_from_no_encoding_specified.html",
"UTF-8" },
{ "windows-949_with_no_encoding_specified.html",
"expected_windows-949_saved_from_no_encoding_specified.html",
"windows-949" },
{ "windows-1251_with_no_encoding_specified.html",
"expected_windows-1251_saved_from_no_encoding_specified.html",
"windows-1251" },
{ "windows-1254_with_no_encoding_specified.html",
"expected_windows-1254_saved_from_no_encoding_specified.html",
"windows-1254" },
{ "windows-1255_with_no_encoding_specified.html",
"expected_windows-1255_saved_from_no_encoding_specified.html",
"windows-1255" },
{ "windows-1256_with_no_encoding_specified.html",
"expected_windows-1256_saved_from_no_encoding_specified.html",
"windows-1256" }
};
const char* const kAutoDetectDir = "auto_detect";
// Directory of the files of expected results.
const char* const kExpectedResultDir = "expected_results";
// Full path of saved file. full_file_name = save_dir_ + file_name[i];
FilePath full_saved_file_name;
FilePath test_dir_path = FilePath(kTestDir).AppendASCII(kAutoDetectDir);
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
// Set the default charset to one of encodings not supported by the current
// auto-detector (Please refer to the above comments) to make sure we
// incorrectly decode the page. Now we use ISO-8859-4.
browser->SetStringPreference(prefs::kDefaultCharset, L"ISO-8859-4");
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestDatas);i++) {
FilePath test_file_path(test_dir_path);
test_file_path = test_file_path.AppendASCII(kTestDatas[i].test_file_name);
GURL url =
URLRequestMockHTTPJob::GetMockUrl(test_file_path.ToWStringHack());
ASSERT_TRUE(tab->NavigateToURL(url));
WaitUntilTabCount(1);
// Disable auto detect if it is on.
EXPECT_TRUE(
browser->SetBooleanPreference(prefs::kWebKitUsesUniversalDetector,
false));
EXPECT_TRUE(tab->Reload());
// Get the encoding used for the page, it must be the default charset we
// just set.
std::string encoding;
EXPECT_TRUE(tab->GetPageCurrentEncoding(&encoding));
EXPECT_EQ(encoding, "ISO-8859-4");
// Enable the encoding auto detection.
EXPECT_TRUE(browser->SetBooleanPreference(
prefs::kWebKitUsesUniversalDetector, true));
EXPECT_TRUE(tab->Reload());
// Re-get the encoding of page. It should return the real encoding now.
bool encoding_auto_detect = false;
EXPECT_TRUE(
browser->GetBooleanPreference(prefs::kWebKitUsesUniversalDetector,
&encoding_auto_detect));
EXPECT_TRUE(encoding_auto_detect);
EXPECT_TRUE(tab->GetPageCurrentEncoding(&encoding));
EXPECT_EQ(encoding, kTestDatas[i].expected_encoding);
// Dump the page, the content of dump page should be equal with our expect
// result file.
full_saved_file_name = save_dir_.AppendASCII(kTestDatas[i].test_file_name);
// Full path of expect result file.
FilePath expected_result_file_name = FilePath().AppendASCII(kAutoDetectDir);
expected_result_file_name = expected_result_file_name.AppendASCII(
kExpectedResultDir);
expected_result_file_name = expected_result_file_name.AppendASCII(
kTestDatas[i].expected_result);
EXPECT_TRUE(tab->SavePage(full_saved_file_name.ToWStringHack(),
temp_sub_resource_dir_.ToWStringHack(),
SavePackage::SAVE_AS_COMPLETE_HTML));
EXPECT_TRUE(WaitForDownloadShelfVisible(browser.get()));
CheckFile(full_saved_file_name, expected_result_file_name, true);
}
}
<commit_msg>Disable TestOverrideEncoding test. It's been hanging the XP Tests (dbg)(3) ui_test all day.<commit_after>// Copyright (c) 2006-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 <string>
#include "base/file_util.h"
#include "base/scoped_temp_dir.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "chrome/browser/download/save_package.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
static const FilePath::CharType* kTestDir = FILE_PATH_LITERAL("encoding_tests");
class BrowserEncodingTest : public UITest {
protected:
BrowserEncodingTest() : UITest() {}
// Make sure the content of the page are as expected
// after override or auto-detect
void CheckFile(const FilePath& generated_file,
const FilePath& expected_result_file,
bool check_equal) {
FilePath expected_result_filepath = UITest::GetTestFilePath(
FilePath(kTestDir).ToWStringHack(),
expected_result_file.ToWStringHack());
ASSERT_TRUE(file_util::PathExists(expected_result_filepath));
WaitForGeneratedFileAndCheck(generated_file,
expected_result_filepath,
true, // We do care whether they are equal.
check_equal,
true); // Delete the generated file when done.
}
virtual void SetUp() {
UITest::SetUp();
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
save_dir_ = temp_dir_.path();
temp_sub_resource_dir_ = save_dir_.AppendASCII("sub_resource_files");
}
ScopedTempDir temp_dir_;
FilePath save_dir_;
FilePath temp_sub_resource_dir_;
};
// TODO(jnd): 1. Some encodings are missing here. It'll be added later. See
// http://crbug.com/13306.
// 2. Add more files with multiple encoding name variants for each canonical
// encoding name). Webkit layout tests cover some, but testing in the UI test is
// also necessary.
TEST_F(BrowserEncodingTest, TestEncodingAliasMapping) {
struct EncodingTestData {
const char* file_name;
const char* encoding_name;
};
const EncodingTestData kEncodingTestDatas[] = {
{ "Big5.html", "Big5" },
{ "EUC-JP.html", "EUC-JP" },
{ "gb18030.html", "gb18030" },
{ "iso-8859-1.html", "ISO-8859-1" },
{ "ISO-8859-2.html", "ISO-8859-2" },
{ "ISO-8859-4.html", "ISO-8859-4" },
{ "ISO-8859-5.html", "ISO-8859-5" },
{ "ISO-8859-6.html", "ISO-8859-6" },
{ "ISO-8859-7.html", "ISO-8859-7" },
{ "ISO-8859-8.html", "ISO-8859-8" },
{ "ISO-8859-13.html", "ISO-8859-13" },
{ "ISO-8859-15.html", "ISO-8859-15" },
{ "KOI8-R.html", "KOI8-R" },
{ "KOI8-U.html", "KOI8-U" },
{ "macintosh.html", "macintosh" },
{ "Shift-JIS.html", "Shift_JIS" },
{ "US-ASCII.html", "ISO-8859-1" }, // http://crbug.com/15801
{ "UTF-8.html", "UTF-8" },
{ "UTF-16LE.html", "UTF-16LE" },
{ "windows-874.html", "windows-874" },
{ "windows-949.html", "windows-949" },
{ "windows-1250.html", "windows-1250" },
{ "windows-1251.html", "windows-1251" },
{ "windows-1252.html", "windows-1252" },
{ "windows-1253.html", "windows-1253" },
{ "windows-1254.html", "windows-1254" },
{ "windows-1255.html", "windows-1255" },
{ "windows-1256.html", "windows-1256" },
{ "windows-1257.html", "windows-1257" },
{ "windows-1258.html", "windows-1258" }
};
const char* const kAliasTestDir = "alias_mapping";
FilePath test_dir_path = FilePath(kTestDir).AppendASCII(kAliasTestDir);
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kEncodingTestDatas); ++i) {
FilePath test_file_path(test_dir_path);
test_file_path = test_file_path.AppendASCII(
kEncodingTestDatas[i].file_name);
GURL url =
URLRequestMockHTTPJob::GetMockUrl(test_file_path.ToWStringHack());
scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
ASSERT_TRUE(tab_proxy.get());
ASSERT_TRUE(tab_proxy->NavigateToURL(url));
WaitUntilTabCount(1);
std::string encoding;
EXPECT_TRUE(tab_proxy->GetPageCurrentEncoding(&encoding));
EXPECT_EQ(encoding, kEncodingTestDatas[i].encoding_name);
}
}
#if defined(OS_WIN)
// We are disabling this test on MacOS and Linux because on those platforms
// AutomationProvider::OverrideEncoding is not implemented yet.
// TODO(port): Enable when encoding-related parts of Browser are ported.
TEST_F(BrowserEncodingTest, DISABLED_TestOverrideEncoding) {
const char* const kTestFileName = "gb18030_with_iso88591_meta.html";
const char* const kExpectedFileName =
"expected_gb18030_saved_from_iso88591_meta.html";
const char* const kOverrideTestDir = "user_override";
FilePath test_dir_path = FilePath(kTestDir).AppendASCII(kOverrideTestDir);
test_dir_path = test_dir_path.AppendASCII(kTestFileName);
GURL url = URLRequestMockHTTPJob::GetMockUrl(test_dir_path.ToWStringHack());
scoped_refptr<TabProxy> tab_proxy(GetActiveTab());
ASSERT_TRUE(tab_proxy.get());
ASSERT_TRUE(tab_proxy->NavigateToURL(url));
WaitUntilTabCount(1);
// Get the encoding declared in the page.
std::string encoding;
EXPECT_TRUE(tab_proxy->GetPageCurrentEncoding(&encoding));
EXPECT_EQ(encoding, "ISO-8859-1");
// Override the encoding to "gb18030".
int64 last_nav_time = 0;
EXPECT_TRUE(tab_proxy->GetLastNavigationTime(&last_nav_time));
EXPECT_TRUE(tab_proxy->OverrideEncoding("gb18030"));
EXPECT_TRUE(tab_proxy->WaitForNavigation(last_nav_time));
// Re-get the encoding of page. It should be gb18030.
EXPECT_TRUE(tab_proxy->GetPageCurrentEncoding(&encoding));
EXPECT_EQ(encoding, "gb18030");
// Dump the page, the content of dump page should be identical to the
// expected result file.
FilePath full_file_name = save_dir_.AppendASCII(kTestFileName);
// We save the page as way of complete HTML file, which requires a directory
// name to save sub resources in it. Although this test file does not have
// sub resources, but the directory name is still required.
EXPECT_TRUE(tab_proxy->SavePage(full_file_name.ToWStringHack(),
temp_sub_resource_dir_.ToWStringHack(),
SavePackage::SAVE_AS_COMPLETE_HTML));
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
EXPECT_TRUE(WaitForDownloadShelfVisible(browser.get()));
FilePath expected_file_name = FilePath().AppendASCII(kOverrideTestDir);
expected_file_name = expected_file_name.AppendASCII(kExpectedFileName);
CheckFile(full_file_name, expected_file_name, true);
}
#endif // defined(OS_WIN)
// The following encodings are excluded from the auto-detection test because
// it's a known issue that the current encoding detector does not detect them:
// ISO-8859-4
// ISO-8859-13
// KOI8-U
// macintosh
// windows-874
// windows-1252
// windows-1253
// windows-1257
// windows-1258
// For Hebrew, the expected encoding value is ISO-8859-8-I. See
// http://crbug.com/2927 for more details.
TEST_F(BrowserEncodingTest, TestEncodingAutoDetect) {
struct EncodingAutoDetectTestData {
const char* test_file_name; // File name of test data.
const char* expected_result; // File name of expected results.
const char* expected_encoding; // expected encoding.
};
const EncodingAutoDetectTestData kTestDatas[] = {
{ "Big5_with_no_encoding_specified.html",
"expected_Big5_saved_from_no_encoding_specified.html",
"Big5" },
{ "gb18030_with_no_encoding_specified.html",
"expected_gb18030_saved_from_no_encoding_specified.html",
"gb18030" },
{ "iso-8859-1_with_no_encoding_specified.html",
"expected_iso-8859-1_saved_from_no_encoding_specified.html",
"ISO-8859-1" },
{ "ISO-8859-5_with_no_encoding_specified.html",
"expected_ISO-8859-5_saved_from_no_encoding_specified.html",
"ISO-8859-5" },
{ "ISO-8859-6_with_no_encoding_specified.html",
"expected_ISO-8859-6_saved_from_no_encoding_specified.html",
"ISO-8859-6" },
{ "ISO-8859-7_with_no_encoding_specified.html",
"expected_ISO-8859-7_saved_from_no_encoding_specified.html",
"ISO-8859-7" },
{ "ISO-8859-8_with_no_encoding_specified.html",
"expected_ISO-8859-8_saved_from_no_encoding_specified.html",
"ISO-8859-8-I" },
{ "KOI8-R_with_no_encoding_specified.html",
"expected_KOI8-R_saved_from_no_encoding_specified.html",
"KOI8-R" },
{ "Shift-JIS_with_no_encoding_specified.html",
"expected_Shift-JIS_saved_from_no_encoding_specified.html",
"Shift_JIS" },
{ "UTF-8_with_no_encoding_specified.html",
"expected_UTF-8_saved_from_no_encoding_specified.html",
"UTF-8" },
{ "windows-949_with_no_encoding_specified.html",
"expected_windows-949_saved_from_no_encoding_specified.html",
"windows-949" },
{ "windows-1251_with_no_encoding_specified.html",
"expected_windows-1251_saved_from_no_encoding_specified.html",
"windows-1251" },
{ "windows-1254_with_no_encoding_specified.html",
"expected_windows-1254_saved_from_no_encoding_specified.html",
"windows-1254" },
{ "windows-1255_with_no_encoding_specified.html",
"expected_windows-1255_saved_from_no_encoding_specified.html",
"windows-1255" },
{ "windows-1256_with_no_encoding_specified.html",
"expected_windows-1256_saved_from_no_encoding_specified.html",
"windows-1256" }
};
const char* const kAutoDetectDir = "auto_detect";
// Directory of the files of expected results.
const char* const kExpectedResultDir = "expected_results";
// Full path of saved file. full_file_name = save_dir_ + file_name[i];
FilePath full_saved_file_name;
FilePath test_dir_path = FilePath(kTestDir).AppendASCII(kAutoDetectDir);
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
// Set the default charset to one of encodings not supported by the current
// auto-detector (Please refer to the above comments) to make sure we
// incorrectly decode the page. Now we use ISO-8859-4.
browser->SetStringPreference(prefs::kDefaultCharset, L"ISO-8859-4");
scoped_refptr<TabProxy> tab(GetActiveTab());
ASSERT_TRUE(tab.get());
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kTestDatas);i++) {
FilePath test_file_path(test_dir_path);
test_file_path = test_file_path.AppendASCII(kTestDatas[i].test_file_name);
GURL url =
URLRequestMockHTTPJob::GetMockUrl(test_file_path.ToWStringHack());
ASSERT_TRUE(tab->NavigateToURL(url));
WaitUntilTabCount(1);
// Disable auto detect if it is on.
EXPECT_TRUE(
browser->SetBooleanPreference(prefs::kWebKitUsesUniversalDetector,
false));
EXPECT_TRUE(tab->Reload());
// Get the encoding used for the page, it must be the default charset we
// just set.
std::string encoding;
EXPECT_TRUE(tab->GetPageCurrentEncoding(&encoding));
EXPECT_EQ(encoding, "ISO-8859-4");
// Enable the encoding auto detection.
EXPECT_TRUE(browser->SetBooleanPreference(
prefs::kWebKitUsesUniversalDetector, true));
EXPECT_TRUE(tab->Reload());
// Re-get the encoding of page. It should return the real encoding now.
bool encoding_auto_detect = false;
EXPECT_TRUE(
browser->GetBooleanPreference(prefs::kWebKitUsesUniversalDetector,
&encoding_auto_detect));
EXPECT_TRUE(encoding_auto_detect);
EXPECT_TRUE(tab->GetPageCurrentEncoding(&encoding));
EXPECT_EQ(encoding, kTestDatas[i].expected_encoding);
// Dump the page, the content of dump page should be equal with our expect
// result file.
full_saved_file_name = save_dir_.AppendASCII(kTestDatas[i].test_file_name);
// Full path of expect result file.
FilePath expected_result_file_name = FilePath().AppendASCII(kAutoDetectDir);
expected_result_file_name = expected_result_file_name.AppendASCII(
kExpectedResultDir);
expected_result_file_name = expected_result_file_name.AppendASCII(
kTestDatas[i].expected_result);
EXPECT_TRUE(tab->SavePage(full_saved_file_name.ToWStringHack(),
temp_sub_resource_dir_.ToWStringHack(),
SavePackage::SAVE_AS_COMPLETE_HTML));
EXPECT_TRUE(WaitForDownloadShelfVisible(browser.get()));
CheckFile(full_saved_file_name, expected_result_file_name, true);
}
}
<|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/chrome_browser_main_win.h"
#include <windows.h>
#include <shellapi.h>
#include <algorithm>
#include "base/command_line.h"
#include "base/environment.h"
#include "base/i18n/rtl.h"
#include "base/memory/scoped_ptr.h"
#include "base/path_service.h"
#include "base/scoped_native_library.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "base/win/metro.h"
#include "base/win/windows_version.h"
#include "base/win/wrapped_window_proc.h"
#include "chrome/browser/browser_util_win.h"
#include "chrome/browser/first_run/first_run.h"
#include "chrome/browser/media_gallery/media_device_notifications_window_win.h"
#include "chrome/browser/metrics/metrics_service.h"
#include "chrome/browser/profiles/profile_info_cache.h"
#include "chrome/browser/profiles/profile_shortcut_manager_win.h"
#include "chrome/browser/ui/simple_message_box.h"
#include "chrome/browser/ui/uninstall_browser_prompt.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_result_codes.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/env_vars.h"
#include "chrome/installer/util/browser_distribution.h"
#include "chrome/installer/util/helper.h"
#include "chrome/installer/util/install_util.h"
#include "chrome/installer/util/l10n_string_util.h"
#include "chrome/installer/util/shell_util.h"
#include "content/public/common/main_function_params.h"
#include "grit/app_locale_settings.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "installer_util_strings/installer_util_strings.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/l10n/l10n_util_win.h"
#include "ui/base/ui_base_switches.h"
#include "ui/base/win/message_box_win.h"
#include "ui/gfx/platform_font_win.h"
namespace {
typedef HRESULT (STDAPICALLTYPE* RegisterApplicationRestartProc)(
const wchar_t* command_line,
DWORD flags);
void InitializeWindowProcExceptions() {
// Get the breakpad pointer from chrome.exe
base::win::WinProcExceptionFilter exception_filter =
reinterpret_cast<base::win::WinProcExceptionFilter>(
::GetProcAddress(::GetModuleHandle(
chrome::kBrowserProcessExecutableName),
"CrashForException"));
exception_filter = base::win::SetWinProcExceptionFilter(exception_filter);
DCHECK(!exception_filter);
}
// gfx::Font callbacks
void AdjustUIFont(LOGFONT* logfont) {
l10n_util::AdjustUIFont(logfont);
}
int GetMinimumFontSize() {
int min_font_size;
base::StringToInt(l10n_util::GetStringUTF16(IDS_MINIMUM_UI_FONT_SIZE),
&min_font_size);
return min_font_size;
}
class TranslationDelegate : public installer::TranslationDelegate {
public:
virtual string16 GetLocalizedString(int installer_string_id) OVERRIDE;
};
} // namespace
void RecordBreakpadStatusUMA(MetricsService* metrics) {
metrics->RecordBreakpadHasDebugger(TRUE == ::IsDebuggerPresent());
}
void WarnAboutMinimumSystemRequirements() {
if (base::win::GetVersion() < base::win::VERSION_XP) {
const string16 title = l10n_util::GetStringUTF16(IDS_PRODUCT_NAME);
const string16 message =
l10n_util::GetStringUTF16(IDS_UNSUPPORTED_OS_PRE_WIN_XP);
browser::ShowMessageBox(NULL, title, message,
browser::MESSAGE_BOX_TYPE_WARNING);
}
}
void RecordBrowserStartupTime() {
// Calculate the time that has elapsed from our own process creation.
FILETIME creation_time = {};
FILETIME ignore = {};
::GetProcessTimes(::GetCurrentProcess(), &creation_time, &ignore, &ignore,
&ignore);
RecordPreReadExperimentTime("Startup.BrowserMessageLoopStartTime",
base::Time::Now() - base::Time::FromFileTime(creation_time));
}
void ShowCloseBrowserFirstMessageBox() {
const string16 title = l10n_util::GetStringUTF16(IDS_PRODUCT_NAME);
const string16 message = l10n_util::GetStringUTF16(IDS_UNINSTALL_CLOSE_APP);
browser::ShowMessageBox(NULL, title, message,
browser::MESSAGE_BOX_TYPE_WARNING);
}
int DoUninstallTasks(bool chrome_still_running) {
// We want to show a warning to user (and exit) if Chrome is already running
// *before* we show the uninstall confirmation dialog box. But while the
// uninstall confirmation dialog is up, user might start Chrome, so we
// check once again after user acknowledges Uninstall dialog.
if (chrome_still_running) {
ShowCloseBrowserFirstMessageBox();
return chrome::RESULT_CODE_UNINSTALL_CHROME_ALIVE;
}
int result = browser::ShowUninstallBrowserPrompt();
if (browser_util::IsBrowserAlreadyRunning()) {
ShowCloseBrowserFirstMessageBox();
return chrome::RESULT_CODE_UNINSTALL_CHROME_ALIVE;
}
if (result != chrome::RESULT_CODE_UNINSTALL_USER_CANCEL) {
// The following actions are just best effort.
VLOG(1) << "Executing uninstall actions";
if (!first_run::RemoveSentinel())
VLOG(1) << "Failed to delete sentinel file.";
// We want to remove user level shortcuts and we only care about the ones
// created by us and not by the installer so |alternate| is false.
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
if (!ShellUtil::RemoveChromeDesktopShortcut(
dist, ShellUtil::CURRENT_USER, ShellUtil::SHORTCUT_NO_OPTIONS)) {
VLOG(1) << "Failed to delete desktop shortcut.";
}
if (!ShellUtil::RemoveChromeDesktopShortcutsWithAppendedNames(
ProfileShortcutManagerWin::GenerateShortcutsFromProfiles(
ProfileInfoCache::GetProfileNames()))) {
VLOG(1) << "Failed to delete desktop profiles shortcuts.";
}
if (!ShellUtil::RemoveChromeQuickLaunchShortcut(dist,
ShellUtil::CURRENT_USER)) {
VLOG(1) << "Failed to delete quick launch shortcut.";
}
}
return result;
}
// ChromeBrowserMainPartsWin ---------------------------------------------------
ChromeBrowserMainPartsWin::ChromeBrowserMainPartsWin(
const content::MainFunctionParams& parameters)
: ChromeBrowserMainParts(parameters) {
}
ChromeBrowserMainPartsWin::~ChromeBrowserMainPartsWin() {
}
void ChromeBrowserMainPartsWin::ToolkitInitialized() {
ChromeBrowserMainParts::ToolkitInitialized();
gfx::PlatformFontWin::adjust_font_callback = &AdjustUIFont;
gfx::PlatformFontWin::get_minimum_font_size_callback = &GetMinimumFontSize;
}
void ChromeBrowserMainPartsWin::PreMainMessageLoopStart() {
// installer_util references strings that are normally compiled into
// setup.exe. In Chrome, these strings are in the locale files.
SetupInstallerUtilStrings();
ChromeBrowserMainParts::PreMainMessageLoopStart();
if (!parameters().ui_task) {
// Make sure that we know how to handle exceptions from the message loop.
InitializeWindowProcExceptions();
}
media_device_notifications_window_.reset(
new chrome::MediaDeviceNotificationsWindowWin());
}
// static
void ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
const CommandLine& parsed_command_line) {
// Clear this var so child processes don't show the dialog by default.
scoped_ptr<base::Environment> env(base::Environment::Create());
env->UnSetVar(env_vars::kShowRestart);
// For non-interactive tests we don't restart on crash.
if (env->HasVar(env_vars::kHeadless))
return;
// If the known command-line test options are used we don't create the
// environment block which means we don't get the restart dialog.
if (parsed_command_line.HasSwitch(switches::kBrowserCrashTest) ||
parsed_command_line.HasSwitch(switches::kBrowserAssertTest) ||
parsed_command_line.HasSwitch(switches::kNoErrorDialogs))
return;
// The encoding we use for the info is "title|context|direction" where
// direction is either env_vars::kRtlLocale or env_vars::kLtrLocale depending
// on the current locale.
string16 dlg_strings(l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_TITLE));
dlg_strings.push_back('|');
string16 adjusted_string(
l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_CONTENT));
base::i18n::AdjustStringForLocaleDirection(&adjusted_string);
dlg_strings.append(adjusted_string);
dlg_strings.push_back('|');
dlg_strings.append(ASCIIToUTF16(
base::i18n::IsRTL() ? env_vars::kRtlLocale : env_vars::kLtrLocale));
env->SetVar(env_vars::kRestartInfo, UTF16ToUTF8(dlg_strings));
}
// static
void ChromeBrowserMainPartsWin::RegisterApplicationRestart(
const CommandLine& parsed_command_line) {
DCHECK(base::win::GetVersion() >= base::win::VERSION_VISTA);
base::ScopedNativeLibrary library(FilePath(L"kernel32.dll"));
// Get the function pointer for RegisterApplicationRestart.
RegisterApplicationRestartProc register_application_restart =
static_cast<RegisterApplicationRestartProc>(
library.GetFunctionPointer("RegisterApplicationRestart"));
if (!register_application_restart) {
LOG(WARNING) << "Cannot find RegisterApplicationRestart in kernel32.dll";
return;
}
// The Windows Restart Manager expects a string of command line flags only,
// without the program.
CommandLine command_line(CommandLine::NO_PROGRAM);
command_line.AppendArguments(parsed_command_line, false);
if (!command_line.HasSwitch(switches::kRestoreLastSession))
command_line.AppendSwitch(switches::kRestoreLastSession);
// Restart Chrome if the computer is restarted as the result of an update.
// This could be extended to handle crashes, hangs, and patches.
HRESULT hr = register_application_restart(
command_line.GetCommandLineString().c_str(),
RESTART_NO_CRASH | RESTART_NO_HANG | RESTART_NO_PATCH);
if (FAILED(hr)) {
if (hr == E_INVALIDARG) {
LOG(WARNING) << "Command line too long for RegisterApplicationRestart";
} else {
NOTREACHED() << "RegisterApplicationRestart failed. hr: " << hr <<
", command_line: " << command_line.GetCommandLineString();
}
}
}
void ChromeBrowserMainPartsWin::ShowMissingLocaleMessageBox() {
ui::MessageBox(NULL, ASCIIToUTF16(chrome_browser::kMissingLocaleDataMessage),
ASCIIToUTF16(chrome_browser::kMissingLocaleDataTitle),
MB_OK | MB_ICONERROR | MB_TOPMOST);
}
// static
int ChromeBrowserMainPartsWin::HandleIconsCommands(
const CommandLine& parsed_command_line) {
if (parsed_command_line.HasSwitch(switches::kHideIcons)) {
string16 cp_applet;
base::win::Version version = base::win::GetVersion();
if (version >= base::win::VERSION_VISTA) {
cp_applet.assign(L"Programs and Features"); // Windows Vista and later.
} else if (version >= base::win::VERSION_XP) {
cp_applet.assign(L"Add/Remove Programs"); // Windows XP.
} else {
return chrome::RESULT_CODE_UNSUPPORTED_PARAM; // Not supported
}
const string16 msg =
l10n_util::GetStringFUTF16(IDS_HIDE_ICONS_NOT_SUPPORTED, cp_applet);
const string16 caption = l10n_util::GetStringUTF16(IDS_PRODUCT_NAME);
const UINT flags = MB_OKCANCEL | MB_ICONWARNING | MB_TOPMOST;
if (IDOK == ui::MessageBox(NULL, msg, caption, flags))
ShellExecute(NULL, NULL, L"appwiz.cpl", NULL, NULL, SW_SHOWNORMAL);
// Exit as we are not launching the browser.
return content::RESULT_CODE_NORMAL_EXIT;
}
// We don't hide icons so we shouldn't do anything special to show them
return chrome::RESULT_CODE_UNSUPPORTED_PARAM;
}
// static
bool ChromeBrowserMainPartsWin::CheckMachineLevelInstall() {
// TODO(tommi): Check if using the default distribution is always the right
// thing to do.
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
scoped_ptr<Version> version(InstallUtil::GetChromeVersion(dist, true));
if (version.get()) {
FilePath exe_path;
PathService::Get(base::DIR_EXE, &exe_path);
std::wstring exe = exe_path.value();
FilePath user_exe_path(installer::GetChromeInstallPath(false, dist));
if (FilePath::CompareEqualIgnoreCase(exe, user_exe_path.value())) {
const string16 text =
l10n_util::GetStringUTF16(IDS_MACHINE_LEVEL_INSTALL_CONFLICT);
const string16 caption = l10n_util::GetStringUTF16(IDS_PRODUCT_NAME);
const UINT flags = MB_OK | MB_ICONERROR | MB_TOPMOST;
ui::MessageBox(NULL, text, caption, flags);
CommandLine uninstall_cmd(
InstallUtil::GetChromeUninstallCmd(false, dist->GetType()));
if (!uninstall_cmd.GetProgram().empty()) {
uninstall_cmd.AppendSwitch(installer::switches::kForceUninstall);
uninstall_cmd.AppendSwitch(
installer::switches::kDoNotRemoveSharedItems);
base::LaunchProcess(uninstall_cmd, base::LaunchOptions(), NULL);
}
return true;
}
}
return false;
}
string16 TranslationDelegate::GetLocalizedString(int installer_string_id) {
int resource_id = 0;
switch (installer_string_id) {
// HANDLE_STRING is used by the DO_INSTALLER_STRING_MAPPING macro which is in
// the generated header installer_util_strings.h.
#define HANDLE_STRING(base_id, chrome_id) \
case base_id: \
resource_id = chrome_id; \
break;
DO_INSTALLER_STRING_MAPPING
#undef HANDLE_STRING
default:
NOTREACHED();
}
if (resource_id)
return l10n_util::GetStringUTF16(resource_id);
return string16();
}
// static
void ChromeBrowserMainPartsWin::SetupInstallerUtilStrings() {
CR_DEFINE_STATIC_LOCAL(TranslationDelegate, delegate, ());
installer::SetTranslationDelegate(&delegate);
}
<commit_msg>Adding --enable-touch-events to the browser command line for Windows 8 and up. This will be taken out once the touch events feature stabilizes. <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/chrome_browser_main_win.h"
#include <windows.h>
#include <shellapi.h>
#include <algorithm>
#include "base/command_line.h"
#include "base/environment.h"
#include "base/i18n/rtl.h"
#include "base/memory/scoped_ptr.h"
#include "base/path_service.h"
#include "base/scoped_native_library.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "base/win/metro.h"
#include "base/win/windows_version.h"
#include "base/win/wrapped_window_proc.h"
#include "chrome/browser/browser_util_win.h"
#include "chrome/browser/first_run/first_run.h"
#include "chrome/browser/media_gallery/media_device_notifications_window_win.h"
#include "chrome/browser/metrics/metrics_service.h"
#include "chrome/browser/profiles/profile_info_cache.h"
#include "chrome/browser/profiles/profile_shortcut_manager_win.h"
#include "chrome/browser/ui/simple_message_box.h"
#include "chrome/browser/ui/uninstall_browser_prompt.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_result_codes.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/env_vars.h"
#include "chrome/installer/util/browser_distribution.h"
#include "chrome/installer/util/helper.h"
#include "chrome/installer/util/install_util.h"
#include "chrome/installer/util/l10n_string_util.h"
#include "chrome/installer/util/shell_util.h"
#include "content/public/common/main_function_params.h"
#include "grit/app_locale_settings.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "installer_util_strings/installer_util_strings.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/l10n/l10n_util_win.h"
#include "ui/base/ui_base_switches.h"
#include "ui/base/win/message_box_win.h"
#include "ui/gfx/platform_font_win.h"
namespace {
typedef HRESULT (STDAPICALLTYPE* RegisterApplicationRestartProc)(
const wchar_t* command_line,
DWORD flags);
void InitializeWindowProcExceptions() {
// Get the breakpad pointer from chrome.exe
base::win::WinProcExceptionFilter exception_filter =
reinterpret_cast<base::win::WinProcExceptionFilter>(
::GetProcAddress(::GetModuleHandle(
chrome::kBrowserProcessExecutableName),
"CrashForException"));
exception_filter = base::win::SetWinProcExceptionFilter(exception_filter);
DCHECK(!exception_filter);
}
// gfx::Font callbacks
void AdjustUIFont(LOGFONT* logfont) {
l10n_util::AdjustUIFont(logfont);
}
int GetMinimumFontSize() {
int min_font_size;
base::StringToInt(l10n_util::GetStringUTF16(IDS_MINIMUM_UI_FONT_SIZE),
&min_font_size);
return min_font_size;
}
class TranslationDelegate : public installer::TranslationDelegate {
public:
virtual string16 GetLocalizedString(int installer_string_id) OVERRIDE;
};
} // namespace
void RecordBreakpadStatusUMA(MetricsService* metrics) {
metrics->RecordBreakpadHasDebugger(TRUE == ::IsDebuggerPresent());
}
void WarnAboutMinimumSystemRequirements() {
if (base::win::GetVersion() < base::win::VERSION_XP) {
const string16 title = l10n_util::GetStringUTF16(IDS_PRODUCT_NAME);
const string16 message =
l10n_util::GetStringUTF16(IDS_UNSUPPORTED_OS_PRE_WIN_XP);
browser::ShowMessageBox(NULL, title, message,
browser::MESSAGE_BOX_TYPE_WARNING);
}
}
void RecordBrowserStartupTime() {
// Calculate the time that has elapsed from our own process creation.
FILETIME creation_time = {};
FILETIME ignore = {};
::GetProcessTimes(::GetCurrentProcess(), &creation_time, &ignore, &ignore,
&ignore);
RecordPreReadExperimentTime("Startup.BrowserMessageLoopStartTime",
base::Time::Now() - base::Time::FromFileTime(creation_time));
}
void ShowCloseBrowserFirstMessageBox() {
const string16 title = l10n_util::GetStringUTF16(IDS_PRODUCT_NAME);
const string16 message = l10n_util::GetStringUTF16(IDS_UNINSTALL_CLOSE_APP);
browser::ShowMessageBox(NULL, title, message,
browser::MESSAGE_BOX_TYPE_WARNING);
}
int DoUninstallTasks(bool chrome_still_running) {
// We want to show a warning to user (and exit) if Chrome is already running
// *before* we show the uninstall confirmation dialog box. But while the
// uninstall confirmation dialog is up, user might start Chrome, so we
// check once again after user acknowledges Uninstall dialog.
if (chrome_still_running) {
ShowCloseBrowserFirstMessageBox();
return chrome::RESULT_CODE_UNINSTALL_CHROME_ALIVE;
}
int result = browser::ShowUninstallBrowserPrompt();
if (browser_util::IsBrowserAlreadyRunning()) {
ShowCloseBrowserFirstMessageBox();
return chrome::RESULT_CODE_UNINSTALL_CHROME_ALIVE;
}
if (result != chrome::RESULT_CODE_UNINSTALL_USER_CANCEL) {
// The following actions are just best effort.
VLOG(1) << "Executing uninstall actions";
if (!first_run::RemoveSentinel())
VLOG(1) << "Failed to delete sentinel file.";
// We want to remove user level shortcuts and we only care about the ones
// created by us and not by the installer so |alternate| is false.
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
if (!ShellUtil::RemoveChromeDesktopShortcut(
dist, ShellUtil::CURRENT_USER, ShellUtil::SHORTCUT_NO_OPTIONS)) {
VLOG(1) << "Failed to delete desktop shortcut.";
}
if (!ShellUtil::RemoveChromeDesktopShortcutsWithAppendedNames(
ProfileShortcutManagerWin::GenerateShortcutsFromProfiles(
ProfileInfoCache::GetProfileNames()))) {
VLOG(1) << "Failed to delete desktop profiles shortcuts.";
}
if (!ShellUtil::RemoveChromeQuickLaunchShortcut(dist,
ShellUtil::CURRENT_USER)) {
VLOG(1) << "Failed to delete quick launch shortcut.";
}
}
return result;
}
// ChromeBrowserMainPartsWin ---------------------------------------------------
ChromeBrowserMainPartsWin::ChromeBrowserMainPartsWin(
const content::MainFunctionParams& parameters)
: ChromeBrowserMainParts(parameters) {
if (base::win::GetVersion() >= base::win::VERSION_WIN8) {
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kEnableTouchEvents);
}
}
ChromeBrowserMainPartsWin::~ChromeBrowserMainPartsWin() {
}
void ChromeBrowserMainPartsWin::ToolkitInitialized() {
ChromeBrowserMainParts::ToolkitInitialized();
gfx::PlatformFontWin::adjust_font_callback = &AdjustUIFont;
gfx::PlatformFontWin::get_minimum_font_size_callback = &GetMinimumFontSize;
}
void ChromeBrowserMainPartsWin::PreMainMessageLoopStart() {
// installer_util references strings that are normally compiled into
// setup.exe. In Chrome, these strings are in the locale files.
SetupInstallerUtilStrings();
ChromeBrowserMainParts::PreMainMessageLoopStart();
if (!parameters().ui_task) {
// Make sure that we know how to handle exceptions from the message loop.
InitializeWindowProcExceptions();
}
media_device_notifications_window_.reset(
new chrome::MediaDeviceNotificationsWindowWin());
}
// static
void ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
const CommandLine& parsed_command_line) {
// Clear this var so child processes don't show the dialog by default.
scoped_ptr<base::Environment> env(base::Environment::Create());
env->UnSetVar(env_vars::kShowRestart);
// For non-interactive tests we don't restart on crash.
if (env->HasVar(env_vars::kHeadless))
return;
// If the known command-line test options are used we don't create the
// environment block which means we don't get the restart dialog.
if (parsed_command_line.HasSwitch(switches::kBrowserCrashTest) ||
parsed_command_line.HasSwitch(switches::kBrowserAssertTest) ||
parsed_command_line.HasSwitch(switches::kNoErrorDialogs))
return;
// The encoding we use for the info is "title|context|direction" where
// direction is either env_vars::kRtlLocale or env_vars::kLtrLocale depending
// on the current locale.
string16 dlg_strings(l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_TITLE));
dlg_strings.push_back('|');
string16 adjusted_string(
l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_CONTENT));
base::i18n::AdjustStringForLocaleDirection(&adjusted_string);
dlg_strings.append(adjusted_string);
dlg_strings.push_back('|');
dlg_strings.append(ASCIIToUTF16(
base::i18n::IsRTL() ? env_vars::kRtlLocale : env_vars::kLtrLocale));
env->SetVar(env_vars::kRestartInfo, UTF16ToUTF8(dlg_strings));
}
// static
void ChromeBrowserMainPartsWin::RegisterApplicationRestart(
const CommandLine& parsed_command_line) {
DCHECK(base::win::GetVersion() >= base::win::VERSION_VISTA);
base::ScopedNativeLibrary library(FilePath(L"kernel32.dll"));
// Get the function pointer for RegisterApplicationRestart.
RegisterApplicationRestartProc register_application_restart =
static_cast<RegisterApplicationRestartProc>(
library.GetFunctionPointer("RegisterApplicationRestart"));
if (!register_application_restart) {
LOG(WARNING) << "Cannot find RegisterApplicationRestart in kernel32.dll";
return;
}
// The Windows Restart Manager expects a string of command line flags only,
// without the program.
CommandLine command_line(CommandLine::NO_PROGRAM);
command_line.AppendArguments(parsed_command_line, false);
if (!command_line.HasSwitch(switches::kRestoreLastSession))
command_line.AppendSwitch(switches::kRestoreLastSession);
// Restart Chrome if the computer is restarted as the result of an update.
// This could be extended to handle crashes, hangs, and patches.
HRESULT hr = register_application_restart(
command_line.GetCommandLineString().c_str(),
RESTART_NO_CRASH | RESTART_NO_HANG | RESTART_NO_PATCH);
if (FAILED(hr)) {
if (hr == E_INVALIDARG) {
LOG(WARNING) << "Command line too long for RegisterApplicationRestart";
} else {
NOTREACHED() << "RegisterApplicationRestart failed. hr: " << hr <<
", command_line: " << command_line.GetCommandLineString();
}
}
}
void ChromeBrowserMainPartsWin::ShowMissingLocaleMessageBox() {
ui::MessageBox(NULL, ASCIIToUTF16(chrome_browser::kMissingLocaleDataMessage),
ASCIIToUTF16(chrome_browser::kMissingLocaleDataTitle),
MB_OK | MB_ICONERROR | MB_TOPMOST);
}
// static
int ChromeBrowserMainPartsWin::HandleIconsCommands(
const CommandLine& parsed_command_line) {
if (parsed_command_line.HasSwitch(switches::kHideIcons)) {
string16 cp_applet;
base::win::Version version = base::win::GetVersion();
if (version >= base::win::VERSION_VISTA) {
cp_applet.assign(L"Programs and Features"); // Windows Vista and later.
} else if (version >= base::win::VERSION_XP) {
cp_applet.assign(L"Add/Remove Programs"); // Windows XP.
} else {
return chrome::RESULT_CODE_UNSUPPORTED_PARAM; // Not supported
}
const string16 msg =
l10n_util::GetStringFUTF16(IDS_HIDE_ICONS_NOT_SUPPORTED, cp_applet);
const string16 caption = l10n_util::GetStringUTF16(IDS_PRODUCT_NAME);
const UINT flags = MB_OKCANCEL | MB_ICONWARNING | MB_TOPMOST;
if (IDOK == ui::MessageBox(NULL, msg, caption, flags))
ShellExecute(NULL, NULL, L"appwiz.cpl", NULL, NULL, SW_SHOWNORMAL);
// Exit as we are not launching the browser.
return content::RESULT_CODE_NORMAL_EXIT;
}
// We don't hide icons so we shouldn't do anything special to show them
return chrome::RESULT_CODE_UNSUPPORTED_PARAM;
}
// static
bool ChromeBrowserMainPartsWin::CheckMachineLevelInstall() {
// TODO(tommi): Check if using the default distribution is always the right
// thing to do.
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
scoped_ptr<Version> version(InstallUtil::GetChromeVersion(dist, true));
if (version.get()) {
FilePath exe_path;
PathService::Get(base::DIR_EXE, &exe_path);
std::wstring exe = exe_path.value();
FilePath user_exe_path(installer::GetChromeInstallPath(false, dist));
if (FilePath::CompareEqualIgnoreCase(exe, user_exe_path.value())) {
const string16 text =
l10n_util::GetStringUTF16(IDS_MACHINE_LEVEL_INSTALL_CONFLICT);
const string16 caption = l10n_util::GetStringUTF16(IDS_PRODUCT_NAME);
const UINT flags = MB_OK | MB_ICONERROR | MB_TOPMOST;
ui::MessageBox(NULL, text, caption, flags);
CommandLine uninstall_cmd(
InstallUtil::GetChromeUninstallCmd(false, dist->GetType()));
if (!uninstall_cmd.GetProgram().empty()) {
uninstall_cmd.AppendSwitch(installer::switches::kForceUninstall);
uninstall_cmd.AppendSwitch(
installer::switches::kDoNotRemoveSharedItems);
base::LaunchProcess(uninstall_cmd, base::LaunchOptions(), NULL);
}
return true;
}
}
return false;
}
string16 TranslationDelegate::GetLocalizedString(int installer_string_id) {
int resource_id = 0;
switch (installer_string_id) {
// HANDLE_STRING is used by the DO_INSTALLER_STRING_MAPPING macro which is in
// the generated header installer_util_strings.h.
#define HANDLE_STRING(base_id, chrome_id) \
case base_id: \
resource_id = chrome_id; \
break;
DO_INSTALLER_STRING_MAPPING
#undef HANDLE_STRING
default:
NOTREACHED();
}
if (resource_id)
return l10n_util::GetStringUTF16(resource_id);
return string16();
}
// static
void ChromeBrowserMainPartsWin::SetupInstallerUtilStrings() {
CR_DEFINE_STATIC_LOCAL(TranslationDelegate, delegate, ());
installer::SetTranslationDelegate(&delegate);
}
<|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/browser/download/download_shelf.h"
#include "app/l10n_util.h"
#include "base/file_util.h"
#include "chrome/browser/dom_ui/downloads_ui.h"
#include "chrome/browser/download/download_item_model.h"
#include "chrome/browser/download/download_manager.h"
#include "chrome/browser/metrics/user_metrics.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/url_constants.h"
#include "grit/generated_resources.h"
#if defined(OS_WIN)
#include "chrome/browser/download/download_util.h"
#elif defined(OS_POSIX)
#include "chrome/common/temp_scaffolding_stubs.h"
#endif
// DownloadShelf ---------------------------------------------------------------
void DownloadShelf::ShowAllDownloads() {
Profile* profile = tab_contents_->profile();
if (profile)
UserMetrics::RecordAction(L"ShowDownloads", profile);
tab_contents_->OpenURL(GURL(chrome::kChromeUIDownloadsURL), GURL(),
SINGLETON_TAB, PageTransition::AUTO_BOOKMARK);
}
void DownloadShelf::ChangeTabContents(TabContents* old_contents,
TabContents* new_contents) {
DCHECK(old_contents == tab_contents_);
tab_contents_ = new_contents;
}
// DownloadShelfContextMenu ----------------------------------------------------
DownloadShelfContextMenu::DownloadShelfContextMenu(
BaseDownloadItemModel* download_model)
: download_(download_model->download()),
model_(download_model) {
}
DownloadShelfContextMenu::~DownloadShelfContextMenu() {
}
bool DownloadShelfContextMenu::ItemIsChecked(int id) const {
switch (id) {
case OPEN_WHEN_COMPLETE:
return download_->open_when_complete();
case ALWAYS_OPEN_TYPE: {
const FilePath::StringType extension =
file_util::GetFileExtensionFromPath(download_->full_path());
return download_->manager()->ShouldOpenFileExtension(extension);
}
}
return false;
}
bool DownloadShelfContextMenu::ItemIsDefault(int id) const {
return id == OPEN_WHEN_COMPLETE;
}
std::wstring DownloadShelfContextMenu::GetItemLabel(int id) const {
switch (id) {
case SHOW_IN_FOLDER:
return l10n_util::GetString(IDS_DOWNLOAD_LINK_SHOW);
case OPEN_WHEN_COMPLETE:
if (download_->state() == DownloadItem::IN_PROGRESS)
return l10n_util::GetString(IDS_DOWNLOAD_MENU_OPEN_WHEN_COMPLETE);
return l10n_util::GetString(IDS_DOWNLOAD_MENU_OPEN);
case ALWAYS_OPEN_TYPE:
return l10n_util::GetString(IDS_DOWNLOAD_MENU_ALWAYS_OPEN_TYPE);
case CANCEL:
return l10n_util::GetString(IDS_DOWNLOAD_MENU_CANCEL);
default:
NOTREACHED();
}
return std::wstring();
}
bool DownloadShelfContextMenu::IsItemCommandEnabled(int id) const {
switch (id) {
case SHOW_IN_FOLDER:
case OPEN_WHEN_COMPLETE:
return download_->state() != DownloadItem::CANCELLED;
case ALWAYS_OPEN_TYPE:
#if defined(OS_WIN)
return download_util::CanOpenDownload(download_);
#else
// TODO(port): port download_util
NOTIMPLEMENTED();
return true;
#endif
case CANCEL:
return download_->state() == DownloadItem::IN_PROGRESS;
default:
return id > 0 && id < MENU_LAST;
}
}
void DownloadShelfContextMenu::ExecuteItemCommand(int id) {
switch (id) {
case SHOW_IN_FOLDER:
download_->manager()->ShowDownloadInShell(download_);
break;
case OPEN_WHEN_COMPLETE:
#if defined(OS_WIN)
download_util::OpenDownload(download_);
#else
// TODO(port): port download_util
NOTIMPLEMENTED();
#endif
break;
case ALWAYS_OPEN_TYPE: {
const FilePath::StringType extension =
file_util::GetFileExtensionFromPath(download_->full_path());
download_->manager()->OpenFilesOfExtension(
extension, !ItemIsChecked(ALWAYS_OPEN_TYPE));
break;
}
case CANCEL:
model_->CancelTask();
break;
default:
NOTREACHED();
}
}
<commit_msg>Remove one more notimpl.<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/browser/download/download_shelf.h"
#include "app/l10n_util.h"
#include "base/file_util.h"
#include "chrome/browser/dom_ui/downloads_ui.h"
#include "chrome/browser/download/download_item_model.h"
#include "chrome/browser/download/download_manager.h"
#include "chrome/browser/metrics/user_metrics.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/common/url_constants.h"
#include "grit/generated_resources.h"
#if defined(OS_WIN)
#include "chrome/browser/download/download_util.h"
#elif defined(OS_POSIX)
#include "chrome/common/temp_scaffolding_stubs.h"
#endif
// DownloadShelf ---------------------------------------------------------------
void DownloadShelf::ShowAllDownloads() {
Profile* profile = tab_contents_->profile();
if (profile)
UserMetrics::RecordAction(L"ShowDownloads", profile);
tab_contents_->OpenURL(GURL(chrome::kChromeUIDownloadsURL), GURL(),
SINGLETON_TAB, PageTransition::AUTO_BOOKMARK);
}
void DownloadShelf::ChangeTabContents(TabContents* old_contents,
TabContents* new_contents) {
DCHECK(old_contents == tab_contents_);
tab_contents_ = new_contents;
}
// DownloadShelfContextMenu ----------------------------------------------------
DownloadShelfContextMenu::DownloadShelfContextMenu(
BaseDownloadItemModel* download_model)
: download_(download_model->download()),
model_(download_model) {
}
DownloadShelfContextMenu::~DownloadShelfContextMenu() {
}
bool DownloadShelfContextMenu::ItemIsChecked(int id) const {
switch (id) {
case OPEN_WHEN_COMPLETE:
return download_->open_when_complete();
case ALWAYS_OPEN_TYPE: {
const FilePath::StringType extension =
file_util::GetFileExtensionFromPath(download_->full_path());
return download_->manager()->ShouldOpenFileExtension(extension);
}
}
return false;
}
bool DownloadShelfContextMenu::ItemIsDefault(int id) const {
return id == OPEN_WHEN_COMPLETE;
}
std::wstring DownloadShelfContextMenu::GetItemLabel(int id) const {
switch (id) {
case SHOW_IN_FOLDER:
return l10n_util::GetString(IDS_DOWNLOAD_LINK_SHOW);
case OPEN_WHEN_COMPLETE:
if (download_->state() == DownloadItem::IN_PROGRESS)
return l10n_util::GetString(IDS_DOWNLOAD_MENU_OPEN_WHEN_COMPLETE);
return l10n_util::GetString(IDS_DOWNLOAD_MENU_OPEN);
case ALWAYS_OPEN_TYPE:
return l10n_util::GetString(IDS_DOWNLOAD_MENU_ALWAYS_OPEN_TYPE);
case CANCEL:
return l10n_util::GetString(IDS_DOWNLOAD_MENU_CANCEL);
default:
NOTREACHED();
}
return std::wstring();
}
bool DownloadShelfContextMenu::IsItemCommandEnabled(int id) const {
switch (id) {
case SHOW_IN_FOLDER:
case OPEN_WHEN_COMPLETE:
return download_->state() != DownloadItem::CANCELLED;
case ALWAYS_OPEN_TYPE:
#if defined(OS_WIN)
return download_util::CanOpenDownload(download_);
#elif defined(OS_LINUX)
// Need to implement dangerous download stuff: http://crbug.com/11780
return false;
#endif
case CANCEL:
return download_->state() == DownloadItem::IN_PROGRESS;
default:
return id > 0 && id < MENU_LAST;
}
}
void DownloadShelfContextMenu::ExecuteItemCommand(int id) {
switch (id) {
case SHOW_IN_FOLDER:
download_->manager()->ShowDownloadInShell(download_);
break;
case OPEN_WHEN_COMPLETE:
#if defined(OS_WIN)
download_util::OpenDownload(download_);
#else
// TODO(port): port download_util
NOTIMPLEMENTED();
#endif
break;
case ALWAYS_OPEN_TYPE: {
const FilePath::StringType extension =
file_util::GetFileExtensionFromPath(download_->full_path());
download_->manager()->OpenFilesOfExtension(
extension, !ItemIsChecked(ALWAYS_OPEN_TYPE));
break;
}
case CANCEL:
model_->CancelTask();
break;
default:
NOTREACHED();
}
}
<|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.
// On Linux, when the user tries to launch a second copy of chrome, we check
// for a socket in the user's profile directory. If the socket file is open we
// send a message to the first chrome browser process with the current
// directory and second process command line flags. The second process then
// exits.
#include "chrome/browser/process_singleton.h"
#include <errno.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <set>
#include "base/base_paths.h"
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/eintr_wrapper.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/stl_util-inl.h"
#include "base/string_util.h"
#include "base/time.h"
#include "base/timer.h"
#include "chrome/browser/browser_init.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/profile_manager.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
namespace {
const char kStartToken[] = "START";
const char kTokenDelimiter = '\0';
const int kTimeOutInSeconds = 5;
const int kMaxMessageLength = 32 * 1024;
// Return 0 on success, -1 on failure.
int SetNonBlocking(int fd) {
int flags = fcntl(fd, F_GETFL, 0);
if (-1 == flags)
return flags;
if (flags & O_NONBLOCK)
return 0;
return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}
} // namespace
///////////////////////////////////////////////////////////////////////////////
// ProcessSingleton::LinuxWatcher
// A helper class for a Linux specific implementation of the process singleton.
// This class sets up a listener on the singleton socket and handles parsing
// messages that come in on the singleton socket.
class ProcessSingleton::LinuxWatcher
: public MessageLoopForIO::Watcher,
public MessageLoop::DestructionObserver,
public base::RefCountedThreadSafe<ProcessSingleton::LinuxWatcher> {
public:
// We expect to only be constructed on the UI thread.
explicit LinuxWatcher(ProcessSingleton* parent)
: ui_message_loop_(MessageLoop::current()),
parent_(parent) {
}
virtual ~LinuxWatcher() {
STLDeleteElements(&readers_);
}
// Start listening for connections on the socket. This method should be
// called from the IO thread.
void StartListening(int socket);
// This method determines if we should use the same process and if we should,
// opens a new browser tab. This runs on the UI thread.
void HandleMessage(std::string current_dir, std::vector<std::string> argv);
// MessageLoopForIO::Watcher impl. These run on the IO thread.
virtual void OnFileCanReadWithoutBlocking(int fd);
virtual void OnFileCanWriteWithoutBlocking(int fd) {
// ProcessSingleton only watches for accept (read) events.
NOTREACHED();
}
// MessageLoop::DestructionObserver
virtual void WillDestroyCurrentMessageLoop() {
fd_watcher_.StopWatchingFileDescriptor();
}
private:
class SocketReader : public MessageLoopForIO::Watcher {
public:
SocketReader(ProcessSingleton::LinuxWatcher* parent,
MessageLoop* ui_message_loop,
int fd)
: parent_(parent),
ui_message_loop_(ui_message_loop),
fd_(fd),
bytes_read_(0) {
// Wait for reads.
MessageLoopForIO::current()->WatchFileDescriptor(
fd, true, MessageLoopForIO::WATCH_READ, &fd_reader_, this);
timer_.Start(base::TimeDelta::FromSeconds(kTimeOutInSeconds),
this, &SocketReader::OnTimerExpiry);
}
virtual ~SocketReader() {
int rv = HANDLE_EINTR(close(fd_));
DCHECK_EQ(0, rv) << "Error closing socket: " << strerror(errno);
}
// MessageLoopForIO::Watcher impl.
virtual void OnFileCanReadWithoutBlocking(int fd);
virtual void OnFileCanWriteWithoutBlocking(int fd) {
// SocketReader only watches for accept (read) events.
NOTREACHED();
}
private:
// If we haven't completed in a reasonable amount of time, give up.
void OnTimerExpiry() {
parent_->RemoveSocketReader(this);
// We're deleted beyond this point.
}
MessageLoopForIO::FileDescriptorWatcher fd_reader_;
// The ProcessSingleton::LinuxWatcher that owns us.
ProcessSingleton::LinuxWatcher* const parent_;
// A reference to the UI message loop.
MessageLoop* const ui_message_loop_;
// The file descriptor we're reading.
const int fd_;
// Store the message in this buffer.
char buf_[kMaxMessageLength];
// Tracks the number of bytes we've read in case we're getting partial
// reads.
size_t bytes_read_;
base::OneShotTimer<SocketReader> timer_;
DISALLOW_COPY_AND_ASSIGN(SocketReader);
};
// Removes and deletes the SocketReader.
void RemoveSocketReader(SocketReader* reader);
MessageLoopForIO::FileDescriptorWatcher fd_watcher_;
// A reference to the UI message loop (i.e., the message loop we were
// constructed on).
MessageLoop* ui_message_loop_;
// The ProcessSingleton that owns us.
ProcessSingleton* const parent_;
std::set<SocketReader*> readers_;
DISALLOW_COPY_AND_ASSIGN(LinuxWatcher);
};
void ProcessSingleton::LinuxWatcher::OnFileCanReadWithoutBlocking(int fd) {
// Accepting incoming client.
sockaddr_un from;
socklen_t from_len = sizeof(from);
int connection_socket = HANDLE_EINTR(accept(
fd, reinterpret_cast<sockaddr*>(&from), &from_len));
if (-1 == connection_socket) {
LOG(ERROR) << "accept() failed: " << strerror(errno);
return;
}
SocketReader* reader = new SocketReader(this,
ui_message_loop_,
connection_socket);
readers_.insert(reader);
}
void ProcessSingleton::LinuxWatcher::StartListening(int socket) {
DCHECK(ChromeThread::GetMessageLoop(ChromeThread::IO) ==
MessageLoop::current());
// Watch for client connections on this socket.
MessageLoopForIO* ml = MessageLoopForIO::current();
ml->AddDestructionObserver(this);
ml->WatchFileDescriptor(socket, true, MessageLoopForIO::WATCH_READ,
&fd_watcher_, this);
}
void ProcessSingleton::LinuxWatcher::HandleMessage(std::string current_dir,
std::vector<std::string> argv) {
DCHECK(ui_message_loop_ == MessageLoop::current());
// Ignore the request if the browser process is already in shutdown path.
if (!g_browser_process || g_browser_process->IsShuttingDown()) {
LOG(WARNING) << "Not handling interprocess notification as browser"
" is shutting down";
return;
}
// If locked, it means we are not ready to process this message because
// we are probably in a first run critical phase.
if (parent_->locked()) {
DLOG(WARNING) << "Browser is locked";
return;
}
CommandLine parsed_command_line(argv);
PrefService* prefs = g_browser_process->local_state();
DCHECK(prefs);
FilePath user_data_dir;
PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
ProfileManager* profile_manager = g_browser_process->profile_manager();
Profile* profile = profile_manager->GetDefaultProfile(user_data_dir);
if (!profile) {
// We should only be able to get here if the profile already exists and
// has been created.
NOTREACHED();
return;
}
// TODO(tc): Send an ACK response on success.
// Run the browser startup sequence again, with the command line of the
// signalling process.
FilePath current_dir_file_path(current_dir);
BrowserInit::ProcessCommandLine(parsed_command_line,
current_dir_file_path.ToWStringHack(),
false, profile, NULL);
}
void ProcessSingleton::LinuxWatcher::RemoveSocketReader(SocketReader* reader) {
DCHECK(reader);
readers_.erase(reader);
delete reader;
}
///////////////////////////////////////////////////////////////////////////////
// ProcessSingleton::LinuxWatcher::SocketReader
//
void ProcessSingleton::LinuxWatcher::SocketReader::OnFileCanReadWithoutBlocking(
int fd) {
DCHECK_EQ(fd, fd_);
while (bytes_read_ < sizeof(buf_)) {
ssize_t rv = HANDLE_EINTR(
read(fd, buf_ + bytes_read_, sizeof(buf_) - bytes_read_));
if (rv < 0) {
if (errno != EAGAIN && errno != EWOULDBLOCK) {
LOG(ERROR) << "read() failed: " << strerror(errno);
rv = HANDLE_EINTR(close(fd));
DCHECK_EQ(0, rv) << "Error closing socket: " << strerror(errno);
return;
} else {
// It would block, so we just return and continue to watch for the next
// opportunity to read.
return;
}
} else if (!rv) {
// No more data to read. It's time to process the message.
break;
} else {
bytes_read_ += rv;
}
}
// Validate the message. The shortest message is kStartToken\0x\0x
const size_t kMinMessageLength = arraysize(kStartToken) + 4;
if (bytes_read_ < kMinMessageLength) {
buf_[bytes_read_] = 0;
LOG(ERROR) << "Invalid socket message (wrong length):" << buf_;
return;
}
std::string str(buf_, bytes_read_);
std::vector<std::string> tokens;
SplitString(str, kTokenDelimiter, &tokens);
if (tokens.size() < 3 || tokens[0] != kStartToken) {
LOG(ERROR) << "Wrong message format: " << str;
return;
}
std::string current_dir = tokens[1];
// Remove the first two tokens. The remaining tokens should be the command
// line argv array.
tokens.erase(tokens.begin());
tokens.erase(tokens.begin());
// Return to the UI thread to handle opening a new browser tab.
ui_message_loop_->PostTask(FROM_HERE, NewRunnableMethod(
parent_,
&ProcessSingleton::LinuxWatcher::HandleMessage,
current_dir,
tokens));
fd_reader_.StopWatchingFileDescriptor();
parent_->RemoveSocketReader(this);
// We are deleted beyond this point.
}
///////////////////////////////////////////////////////////////////////////////
// ProcessSingleton
//
ProcessSingleton::ProcessSingleton(const FilePath& user_data_dir)
: locked_(false),
foreground_window_(NULL),
ALLOW_THIS_IN_INITIALIZER_LIST(watcher_(new LinuxWatcher(this))) {
socket_path_ = user_data_dir.Append(chrome::kSingletonSocketFilename);
}
ProcessSingleton::~ProcessSingleton() {
}
bool ProcessSingleton::NotifyOtherProcess() {
int socket;
sockaddr_un addr;
SetupSocket(&socket, &addr);
// Connecting to the socket
int ret = HANDLE_EINTR(connect(socket,
reinterpret_cast<sockaddr*>(&addr),
sizeof(addr)));
if (ret < 0)
return false; // Tell the caller there's nobody to notify.
timeval timeout = {20, 0};
setsockopt(socket, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
// Found another process, prepare our command line
// format is "START\0<current dir>\0<argv[0]>\0...\0<argv[n]>".
std::string to_send(kStartToken);
to_send.push_back(kTokenDelimiter);
FilePath current_dir;
if (!PathService::Get(base::DIR_CURRENT, ¤t_dir))
return false;
to_send.append(current_dir.value());
const std::vector<std::string>& argv =
CommandLine::ForCurrentProcess()->argv();
for (std::vector<std::string>::const_iterator it = argv.begin();
it != argv.end(); ++it) {
to_send.push_back(kTokenDelimiter);
to_send.append(*it);
}
// Send the message
int bytes_written = 0;
const int buf_len = to_send.length();
do {
int rv = HANDLE_EINTR(
write(socket, to_send.data() + bytes_written, buf_len - bytes_written));
if (rv < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
// The socket shouldn't block, we're sending so little data. Just give
// up here, since NotifyOtherProcess() doesn't have an asynchronous api.
LOG(ERROR) << "ProcessSingleton would block on write(), so it gave up.";
return false;
}
LOG(ERROR) << "write() failed: " << strerror(errno);
return false;
}
bytes_written += rv;
} while (bytes_written < buf_len);
int rv = shutdown(socket, SHUT_WR);
if (rv < 0) {
LOG(ERROR) << "shutdown() failed: " << strerror(errno);
} else {
// TODO(tc): We should wait for an ACK, and if we don't get it in a certain
// time period, kill the other process.
}
rv = HANDLE_EINTR(close(socket));
DCHECK_EQ(0, rv) << strerror(errno);
// Assume the other process is handling the request.
return true;
}
void ProcessSingleton::Create() {
int sock;
sockaddr_un addr;
SetupSocket(&sock, &addr);
if (unlink(socket_path_.value().c_str()) < 0)
DCHECK_EQ(errno, ENOENT);
if (bind(sock, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) < 0) {
LOG(ERROR) << "bind() failed: " << strerror(errno);
LOG(ERROR) << "SingletonSocket failed to create a socket in your home "
"directory. This means that running multiple instances of "
"the Chrome binary will start multiple browser process "
"rather than opening a new window in the existing process.";
close(sock);
return;
}
if (listen(sock, 5) < 0)
NOTREACHED() << "listen failed: " << strerror(errno);
// Normally we would use ChromeThread, but the IO thread hasn't started yet.
// Using g_browser_process, we start the thread so we can listen on the
// socket.
MessageLoop* ml = g_browser_process->io_thread()->message_loop();
DCHECK(ml);
ml->PostTask(FROM_HERE, NewRunnableMethod(
watcher_.get(),
&ProcessSingleton::LinuxWatcher::StartListening,
sock));
}
void ProcessSingleton::SetupSocket(int* sock, struct sockaddr_un* addr) {
*sock = socket(PF_UNIX, SOCK_STREAM, 0);
if (*sock < 0)
LOG(FATAL) << "socket() failed: " << strerror(errno);
int rv = SetNonBlocking(*sock);
DCHECK_EQ(0, rv) << "Failed to make non-blocking socket.";
addr->sun_family = AF_UNIX;
if (socket_path_.value().length() > sizeof(addr->sun_path) - 1)
LOG(FATAL) << "Socket path too long: " << socket_path_.value();
base::strlcpy(addr->sun_path, socket_path_.value().c_str(),
sizeof(addr->sun_path));
}
<commit_msg>linux: set FD_CLOEXEC on the singleton socket<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.
// On Linux, when the user tries to launch a second copy of chrome, we check
// for a socket in the user's profile directory. If the socket file is open we
// send a message to the first chrome browser process with the current
// directory and second process command line flags. The second process then
// exits.
#include "chrome/browser/process_singleton.h"
#include <errno.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <set>
#include "base/base_paths.h"
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/eintr_wrapper.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/stl_util-inl.h"
#include "base/string_util.h"
#include "base/time.h"
#include "base/timer.h"
#include "chrome/browser/browser_init.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/profile_manager.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
namespace {
const char kStartToken[] = "START";
const char kTokenDelimiter = '\0';
const int kTimeOutInSeconds = 5;
const int kMaxMessageLength = 32 * 1024;
// Set a file descriptor to be non-blocking.
// Return 0 on success, -1 on failure.
int SetNonBlocking(int fd) {
int flags = fcntl(fd, F_GETFL, 0);
if (-1 == flags)
return flags;
if (flags & O_NONBLOCK)
return 0;
return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}
// Set the close-on-exec bit on a file descriptor.
// Returns 0 on success, -1 on failure.
int SetCloseOnExec(int fd) {
int flags = fcntl(fd, F_GETFD, 0);
if (-1 == flags)
return flags;
if (flags & FD_CLOEXEC)
return 0;
return fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
}
} // namespace
///////////////////////////////////////////////////////////////////////////////
// ProcessSingleton::LinuxWatcher
// A helper class for a Linux specific implementation of the process singleton.
// This class sets up a listener on the singleton socket and handles parsing
// messages that come in on the singleton socket.
class ProcessSingleton::LinuxWatcher
: public MessageLoopForIO::Watcher,
public MessageLoop::DestructionObserver,
public base::RefCountedThreadSafe<ProcessSingleton::LinuxWatcher> {
public:
// We expect to only be constructed on the UI thread.
explicit LinuxWatcher(ProcessSingleton* parent)
: ui_message_loop_(MessageLoop::current()),
parent_(parent) {
}
virtual ~LinuxWatcher() {
STLDeleteElements(&readers_);
}
// Start listening for connections on the socket. This method should be
// called from the IO thread.
void StartListening(int socket);
// This method determines if we should use the same process and if we should,
// opens a new browser tab. This runs on the UI thread.
void HandleMessage(std::string current_dir, std::vector<std::string> argv);
// MessageLoopForIO::Watcher impl. These run on the IO thread.
virtual void OnFileCanReadWithoutBlocking(int fd);
virtual void OnFileCanWriteWithoutBlocking(int fd) {
// ProcessSingleton only watches for accept (read) events.
NOTREACHED();
}
// MessageLoop::DestructionObserver
virtual void WillDestroyCurrentMessageLoop() {
fd_watcher_.StopWatchingFileDescriptor();
}
private:
class SocketReader : public MessageLoopForIO::Watcher {
public:
SocketReader(ProcessSingleton::LinuxWatcher* parent,
MessageLoop* ui_message_loop,
int fd)
: parent_(parent),
ui_message_loop_(ui_message_loop),
fd_(fd),
bytes_read_(0) {
// Wait for reads.
MessageLoopForIO::current()->WatchFileDescriptor(
fd, true, MessageLoopForIO::WATCH_READ, &fd_reader_, this);
timer_.Start(base::TimeDelta::FromSeconds(kTimeOutInSeconds),
this, &SocketReader::OnTimerExpiry);
}
virtual ~SocketReader() {
int rv = HANDLE_EINTR(close(fd_));
DCHECK_EQ(0, rv) << "Error closing socket: " << strerror(errno);
}
// MessageLoopForIO::Watcher impl.
virtual void OnFileCanReadWithoutBlocking(int fd);
virtual void OnFileCanWriteWithoutBlocking(int fd) {
// SocketReader only watches for accept (read) events.
NOTREACHED();
}
private:
// If we haven't completed in a reasonable amount of time, give up.
void OnTimerExpiry() {
parent_->RemoveSocketReader(this);
// We're deleted beyond this point.
}
MessageLoopForIO::FileDescriptorWatcher fd_reader_;
// The ProcessSingleton::LinuxWatcher that owns us.
ProcessSingleton::LinuxWatcher* const parent_;
// A reference to the UI message loop.
MessageLoop* const ui_message_loop_;
// The file descriptor we're reading.
const int fd_;
// Store the message in this buffer.
char buf_[kMaxMessageLength];
// Tracks the number of bytes we've read in case we're getting partial
// reads.
size_t bytes_read_;
base::OneShotTimer<SocketReader> timer_;
DISALLOW_COPY_AND_ASSIGN(SocketReader);
};
// Removes and deletes the SocketReader.
void RemoveSocketReader(SocketReader* reader);
MessageLoopForIO::FileDescriptorWatcher fd_watcher_;
// A reference to the UI message loop (i.e., the message loop we were
// constructed on).
MessageLoop* ui_message_loop_;
// The ProcessSingleton that owns us.
ProcessSingleton* const parent_;
std::set<SocketReader*> readers_;
DISALLOW_COPY_AND_ASSIGN(LinuxWatcher);
};
void ProcessSingleton::LinuxWatcher::OnFileCanReadWithoutBlocking(int fd) {
// Accepting incoming client.
sockaddr_un from;
socklen_t from_len = sizeof(from);
int connection_socket = HANDLE_EINTR(accept(
fd, reinterpret_cast<sockaddr*>(&from), &from_len));
if (-1 == connection_socket) {
LOG(ERROR) << "accept() failed: " << strerror(errno);
return;
}
SocketReader* reader = new SocketReader(this,
ui_message_loop_,
connection_socket);
readers_.insert(reader);
}
void ProcessSingleton::LinuxWatcher::StartListening(int socket) {
DCHECK(ChromeThread::GetMessageLoop(ChromeThread::IO) ==
MessageLoop::current());
// Watch for client connections on this socket.
MessageLoopForIO* ml = MessageLoopForIO::current();
ml->AddDestructionObserver(this);
ml->WatchFileDescriptor(socket, true, MessageLoopForIO::WATCH_READ,
&fd_watcher_, this);
}
void ProcessSingleton::LinuxWatcher::HandleMessage(std::string current_dir,
std::vector<std::string> argv) {
DCHECK(ui_message_loop_ == MessageLoop::current());
// Ignore the request if the browser process is already in shutdown path.
if (!g_browser_process || g_browser_process->IsShuttingDown()) {
LOG(WARNING) << "Not handling interprocess notification as browser"
" is shutting down";
return;
}
// If locked, it means we are not ready to process this message because
// we are probably in a first run critical phase.
if (parent_->locked()) {
DLOG(WARNING) << "Browser is locked";
return;
}
CommandLine parsed_command_line(argv);
PrefService* prefs = g_browser_process->local_state();
DCHECK(prefs);
FilePath user_data_dir;
PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
ProfileManager* profile_manager = g_browser_process->profile_manager();
Profile* profile = profile_manager->GetDefaultProfile(user_data_dir);
if (!profile) {
// We should only be able to get here if the profile already exists and
// has been created.
NOTREACHED();
return;
}
// TODO(tc): Send an ACK response on success.
// Run the browser startup sequence again, with the command line of the
// signalling process.
FilePath current_dir_file_path(current_dir);
BrowserInit::ProcessCommandLine(parsed_command_line,
current_dir_file_path.ToWStringHack(),
false, profile, NULL);
}
void ProcessSingleton::LinuxWatcher::RemoveSocketReader(SocketReader* reader) {
DCHECK(reader);
readers_.erase(reader);
delete reader;
}
///////////////////////////////////////////////////////////////////////////////
// ProcessSingleton::LinuxWatcher::SocketReader
//
void ProcessSingleton::LinuxWatcher::SocketReader::OnFileCanReadWithoutBlocking(
int fd) {
DCHECK_EQ(fd, fd_);
while (bytes_read_ < sizeof(buf_)) {
ssize_t rv = HANDLE_EINTR(
read(fd, buf_ + bytes_read_, sizeof(buf_) - bytes_read_));
if (rv < 0) {
if (errno != EAGAIN && errno != EWOULDBLOCK) {
LOG(ERROR) << "read() failed: " << strerror(errno);
rv = HANDLE_EINTR(close(fd));
DCHECK_EQ(0, rv) << "Error closing socket: " << strerror(errno);
return;
} else {
// It would block, so we just return and continue to watch for the next
// opportunity to read.
return;
}
} else if (!rv) {
// No more data to read. It's time to process the message.
break;
} else {
bytes_read_ += rv;
}
}
// Validate the message. The shortest message is kStartToken\0x\0x
const size_t kMinMessageLength = arraysize(kStartToken) + 4;
if (bytes_read_ < kMinMessageLength) {
buf_[bytes_read_] = 0;
LOG(ERROR) << "Invalid socket message (wrong length):" << buf_;
return;
}
std::string str(buf_, bytes_read_);
std::vector<std::string> tokens;
SplitString(str, kTokenDelimiter, &tokens);
if (tokens.size() < 3 || tokens[0] != kStartToken) {
LOG(ERROR) << "Wrong message format: " << str;
return;
}
std::string current_dir = tokens[1];
// Remove the first two tokens. The remaining tokens should be the command
// line argv array.
tokens.erase(tokens.begin());
tokens.erase(tokens.begin());
// Return to the UI thread to handle opening a new browser tab.
ui_message_loop_->PostTask(FROM_HERE, NewRunnableMethod(
parent_,
&ProcessSingleton::LinuxWatcher::HandleMessage,
current_dir,
tokens));
fd_reader_.StopWatchingFileDescriptor();
parent_->RemoveSocketReader(this);
// We are deleted beyond this point.
}
///////////////////////////////////////////////////////////////////////////////
// ProcessSingleton
//
ProcessSingleton::ProcessSingleton(const FilePath& user_data_dir)
: locked_(false),
foreground_window_(NULL),
ALLOW_THIS_IN_INITIALIZER_LIST(watcher_(new LinuxWatcher(this))) {
socket_path_ = user_data_dir.Append(chrome::kSingletonSocketFilename);
}
ProcessSingleton::~ProcessSingleton() {
}
bool ProcessSingleton::NotifyOtherProcess() {
int socket;
sockaddr_un addr;
SetupSocket(&socket, &addr);
// Connecting to the socket
int ret = HANDLE_EINTR(connect(socket,
reinterpret_cast<sockaddr*>(&addr),
sizeof(addr)));
if (ret < 0)
return false; // Tell the caller there's nobody to notify.
timeval timeout = {20, 0};
setsockopt(socket, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
// Found another process, prepare our command line
// format is "START\0<current dir>\0<argv[0]>\0...\0<argv[n]>".
std::string to_send(kStartToken);
to_send.push_back(kTokenDelimiter);
FilePath current_dir;
if (!PathService::Get(base::DIR_CURRENT, ¤t_dir))
return false;
to_send.append(current_dir.value());
const std::vector<std::string>& argv =
CommandLine::ForCurrentProcess()->argv();
for (std::vector<std::string>::const_iterator it = argv.begin();
it != argv.end(); ++it) {
to_send.push_back(kTokenDelimiter);
to_send.append(*it);
}
// Send the message
int bytes_written = 0;
const int buf_len = to_send.length();
do {
int rv = HANDLE_EINTR(
write(socket, to_send.data() + bytes_written, buf_len - bytes_written));
if (rv < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
// The socket shouldn't block, we're sending so little data. Just give
// up here, since NotifyOtherProcess() doesn't have an asynchronous api.
LOG(ERROR) << "ProcessSingleton would block on write(), so it gave up.";
return false;
}
LOG(ERROR) << "write() failed: " << strerror(errno);
return false;
}
bytes_written += rv;
} while (bytes_written < buf_len);
int rv = shutdown(socket, SHUT_WR);
if (rv < 0) {
LOG(ERROR) << "shutdown() failed: " << strerror(errno);
} else {
// TODO(tc): We should wait for an ACK, and if we don't get it in a certain
// time period, kill the other process.
}
rv = HANDLE_EINTR(close(socket));
DCHECK_EQ(0, rv) << strerror(errno);
// Assume the other process is handling the request.
return true;
}
void ProcessSingleton::Create() {
int sock;
sockaddr_un addr;
SetupSocket(&sock, &addr);
if (unlink(socket_path_.value().c_str()) < 0)
DCHECK_EQ(errno, ENOENT);
if (bind(sock, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) < 0) {
LOG(ERROR) << "bind() failed: " << strerror(errno);
LOG(ERROR) << "SingletonSocket failed to create a socket in your home "
"directory. This means that running multiple instances of "
"the Chrome binary will start multiple browser process "
"rather than opening a new window in the existing process.";
close(sock);
return;
}
if (listen(sock, 5) < 0)
NOTREACHED() << "listen failed: " << strerror(errno);
// Normally we would use ChromeThread, but the IO thread hasn't started yet.
// Using g_browser_process, we start the thread so we can listen on the
// socket.
MessageLoop* ml = g_browser_process->io_thread()->message_loop();
DCHECK(ml);
ml->PostTask(FROM_HERE, NewRunnableMethod(
watcher_.get(),
&ProcessSingleton::LinuxWatcher::StartListening,
sock));
}
void ProcessSingleton::SetupSocket(int* sock, struct sockaddr_un* addr) {
*sock = socket(PF_UNIX, SOCK_STREAM, 0);
if (*sock < 0)
LOG(FATAL) << "socket() failed: " << strerror(errno);
int rv = SetNonBlocking(*sock);
DCHECK_EQ(0, rv) << "Failed to make non-blocking socket.";
rv = SetCloseOnExec(*sock);
DCHECK_EQ(0, rv) << "Failed to set CLOEXEC on socket.";
addr->sun_family = AF_UNIX;
if (socket_path_.value().length() > sizeof(addr->sun_path) - 1)
LOG(FATAL) << "Socket path too long: " << socket_path_.value();
base::strlcpy(addr->sun_path, socket_path_.value().c_str(),
sizeof(addr->sun_path));
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006-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/browser/shell_integration.h"
#include <stdlib.h>
#include <vector>
#include "base/process_util.h"
#if defined(GOOGLE_CHROME_BUILD)
#define DESKTOP_APP_NAME "google-chrome.desktop"
#else // CHROMIUM_BUILD
#define DESKTOP_APP_NAME "chromium-browser.desktop"
#endif
// We delegate the difficult of setting the default browser in Linux desktop
// environments to a new xdg utility, xdg-settings. We'll have to include a copy
// of it for this to work, obviously, but that's actually the suggested approach
// for xdg utilities anyway.
bool ShellIntegration::SetAsDefaultBrowser() {
std::vector<std::string> argv;
argv.push_back("xdg-settings");
argv.push_back("set");
argv.push_back("default-web-browser");
argv.push_back(DESKTOP_APP_NAME);
int success_code;
base::ProcessHandle handle;
base::file_handle_mapping_vector no_files;
if (!base::LaunchApp(argv, no_files, false, &handle))
return false;
base::WaitForExitCode(handle, &success_code);
return success_code == EXIT_SUCCESS;
}
static bool GetDefaultBrowser(std::string* result) {
std::vector<std::string> argv;
argv.push_back("xdg-settings");
argv.push_back("get");
argv.push_back("default-web-browser");
return base::GetAppOutput(CommandLine(argv), result);
}
bool ShellIntegration::IsDefaultBrowser() {
std::string browser;
if (!GetDefaultBrowser(&browser)) {
// If GetDefaultBrowser() fails, we assume xdg-settings does not work for
// some reason, and that we should pretend we're the default browser to
// avoid giving repeated prompts to set ourselves as the default browser.
// TODO: Really, being the default browser should be a ternary query: yes,
// no, and "don't know" so that the UI can reflect this more accurately.
return true;
}
// Allow for an optional newline at the end.
if (browser.length() > 0 && browser[browser.length() - 1] == '\n')
browser.resize(browser.length() - 1);
return !browser.compare(DESKTOP_APP_NAME);
}
bool ShellIntegration::IsFirefoxDefaultBrowser() {
std::string browser;
// We don't care about the return value here.
GetDefaultBrowser(&browser);
return browser.find("irefox") != std::string::npos;
}
<commit_msg>Make standard input /dev/null when running xdg-settings to set the default browser. BUG=17219 TEST=run chrome from a terminal in KDE and use the "set as default browser" feature when ~/.kde/share/config/profilerc is owned by root; chrome should not freeze<commit_after>// Copyright (c) 2006-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/browser/shell_integration.h"
#include <fcntl.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <vector>
#include "base/process_util.h"
#if defined(GOOGLE_CHROME_BUILD)
#define DESKTOP_APP_NAME "google-chrome.desktop"
#else // CHROMIUM_BUILD
#define DESKTOP_APP_NAME "chromium-browser.desktop"
#endif
// We delegate the difficult of setting the default browser in Linux desktop
// environments to a new xdg utility, xdg-settings. We'll have to include a copy
// of it for this to work, obviously, but that's actually the suggested approach
// for xdg utilities anyway.
bool ShellIntegration::SetAsDefaultBrowser() {
std::vector<std::string> argv;
argv.push_back("xdg-settings");
argv.push_back("set");
argv.push_back("default-web-browser");
argv.push_back(DESKTOP_APP_NAME);
// xdg-settings internally runs xdg-mime, which uses mv to move newly-created
// files on top of originals after making changes to them. In the event that
// the original files are owned by another user (e.g. root, which can happen
// if they are updated within sudo), mv will prompt the user to confirm if
// standard input is a terminal (otherwise it just does it). So make sure it's
// not, to avoid locking everything up waiting for mv.
int devnull = open("/dev/null", O_RDONLY);
if (devnull < 0)
return false;
base::file_handle_mapping_vector no_stdin;
no_stdin.push_back(std::make_pair(devnull, STDIN_FILENO));
base::ProcessHandle handle;
if (!base::LaunchApp(argv, no_stdin, false, &handle)) {
close(devnull);
return false;
}
close(devnull);
int success_code;
base::WaitForExitCode(handle, &success_code);
return success_code == EXIT_SUCCESS;
}
static bool GetDefaultBrowser(std::string* result) {
std::vector<std::string> argv;
argv.push_back("xdg-settings");
argv.push_back("get");
argv.push_back("default-web-browser");
return base::GetAppOutput(CommandLine(argv), result);
}
bool ShellIntegration::IsDefaultBrowser() {
std::string browser;
if (!GetDefaultBrowser(&browser)) {
// If GetDefaultBrowser() fails, we assume xdg-settings does not work for
// some reason, and that we should pretend we're the default browser to
// avoid giving repeated prompts to set ourselves as the default browser.
// TODO: Really, being the default browser should be a ternary query: yes,
// no, and "don't know" so that the UI can reflect this more accurately.
return true;
}
// Allow for an optional newline at the end.
if (browser.length() > 0 && browser[browser.length() - 1] == '\n')
browser.resize(browser.length() - 1);
return !browser.compare(DESKTOP_APP_NAME);
}
bool ShellIntegration::IsFirefoxDefaultBrowser() {
std::string browser;
// We don't care about the return value here.
GetDefaultBrowser(&browser);
return browser.find("irefox") != std::string::npos;
}
<|endoftext|> |
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync_file_system/logger.h"
#include "base/file_util.h"
#include "base/lazy_instance.h"
#include "base/location.h"
#include "base/stringprintf.h"
#include "chrome/browser/google_apis/event_logger.h"
namespace sync_file_system {
namespace util {
namespace {
static base::LazyInstance<google_apis::EventLogger> g_logger =
LAZY_INSTANCE_INITIALIZER;
std::string LogSeverityToString(logging::LogSeverity level) {
switch (level) {
case logging::LOG_ERROR:
return "ERROR";
case logging::LOG_WARNING:
return "WARNING";
case logging::LOG_INFO:
return "INFO";
}
NOTREACHED();
return "Unknown Log Severity";
}
} // namespace
void ClearLog() {
g_logger.Pointer()->SetHistorySize(google_apis::kDefaultHistorySize);
}
void Log(logging::LogSeverity severity,
const tracked_objects::Location& location,
const char* format,
...) {
// Ignore log if level severity is not high enough.
if (severity < logging::GetMinLogLevel())
return;
std::string what;
va_list args;
va_start(args, format);
base::StringAppendV(&what, format, args);
va_end(args);
// Use same output format as normal console logger.
base::FilePath path = base::FilePath::FromUTF8Unsafe(location.file_name());
std::string log_output = base::StringPrintf(
"[%s: %s(%d)] %s",
LogSeverityToString(severity).c_str(),
path.BaseName().AsUTF8Unsafe().c_str(),
location.line_number(),
what.c_str());
// Log to WebUI.
// On thread-safety: LazyInstance guarantees thread-safety for the object
// creation. EventLogger::Log() internally maintains the lock.
google_apis::EventLogger* ptr = g_logger.Pointer();
ptr->Log("%s", log_output.c_str());
// Log to console.
logging::RawLog(severity, log_output.c_str());
}
std::vector<google_apis::EventLogger::Event> GetLogHistory() {
google_apis::EventLogger* ptr = g_logger.Pointer();
return ptr->GetHistory();
}
} // namespace util
} // namespace sync_file_system
<commit_msg>Fix SyncFS console logging for Release builds.<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/sync_file_system/logger.h"
#include "base/file_util.h"
#include "base/lazy_instance.h"
#include "base/location.h"
#include "base/stringprintf.h"
#include "chrome/browser/google_apis/event_logger.h"
namespace sync_file_system {
namespace util {
namespace {
static base::LazyInstance<google_apis::EventLogger> g_logger =
LAZY_INSTANCE_INITIALIZER;
std::string LogSeverityToString(logging::LogSeverity level) {
switch (level) {
case logging::LOG_ERROR:
return "ERROR";
case logging::LOG_WARNING:
return "WARNING";
case logging::LOG_INFO:
return "INFO";
}
NOTREACHED();
return "Unknown Log Severity";
}
} // namespace
void ClearLog() {
g_logger.Pointer()->SetHistorySize(google_apis::kDefaultHistorySize);
}
void Log(logging::LogSeverity severity,
const tracked_objects::Location& location,
const char* format,
...) {
// Ignore log if level severity is not high enough.
if (severity < logging::GetMinLogLevel())
return;
std::string what;
va_list args;
va_start(args, format);
base::StringAppendV(&what, format, args);
va_end(args);
// Use same output format as normal console logger.
base::FilePath path = base::FilePath::FromUTF8Unsafe(location.file_name());
std::string log_output = base::StringPrintf(
"[%s: %s(%d)] %s",
LogSeverityToString(severity).c_str(),
path.BaseName().AsUTF8Unsafe().c_str(),
location.line_number(),
what.c_str());
// Log to WebUI.
// On thread-safety: LazyInstance guarantees thread-safety for the object
// creation. EventLogger::Log() internally maintains the lock.
google_apis::EventLogger* ptr = g_logger.Pointer();
ptr->Log("%s", log_output.c_str());
// Log to console.
logging::LogMessage(location.file_name(), location.line_number(), severity)
.stream() << what;
}
std::vector<google_apis::EventLogger::Event> GetLogHistory() {
google_apis::EventLogger* ptr = g_logger.Pointer();
return ptr->GetHistory();
}
} // namespace util
} // namespace sync_file_system
<|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/test/chrome_process_util.h"
#include "chrome/test/ui/ui_test.h"
class ChromeProcessUtilTest : public UITest {
};
TEST_F(ChromeProcessUtilTest, SanityTest) {
EXPECT_TRUE(IsBrowserRunning());
ChromeProcessList processes = GetRunningChromeProcesses(browser_process_id());
EXPECT_FALSE(processes.empty());
QuitBrowser();
EXPECT_FALSE(IsBrowserRunning());
EXPECT_EQ(-1, browser_process_id());
processes = GetRunningChromeProcesses(browser_process_id());
EXPECT_TRUE(processes.empty());
}
<commit_msg>Mark ChromeProcessUtilTest.SanityTest as flaky.<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/test/chrome_process_util.h"
#include "chrome/test/ui/ui_test.h"
class ChromeProcessUtilTest : public UITest {
};
// Flaky on Mac only. See http://crbug.com/79175
TEST_F(ChromeProcessUtilTest, FLAKY_SanityTest) {
EXPECT_TRUE(IsBrowserRunning());
ChromeProcessList processes = GetRunningChromeProcesses(browser_process_id());
EXPECT_FALSE(processes.empty());
QuitBrowser();
EXPECT_FALSE(IsBrowserRunning());
EXPECT_EQ(-1, browser_process_id());
processes = GetRunningChromeProcesses(browser_process_id());
EXPECT_TRUE(processes.empty());
}
<|endoftext|> |
<commit_before>// Copyright 2008-2009, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Tests for the top plugins to catch regressions in our plugin host code, as
// well as in the out of process code. Currently this tests:
// Flash
// Real
// QuickTime
// Windows Media Player
// -this includes both WMP plugins. npdsplay.dll is the older one that
// comes with XP. np-mswmp.dll can be downloaded from Microsoft and
// needs SP2 or Vista.
#include <windows.h>
#include <shellapi.h>
#include <shlobj.h>
#include <comutil.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <string>
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/registry.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "third_party/npapi/bindings/npapi.h"
#include "webkit/default_plugin/plugin_impl.h"
#include "webkit/glue/plugins/plugin_constants_win.h"
#include "webkit/glue/plugins/plugin_list.h"
const char kTestCompleteCookie[] = "status";
const char kTestCompleteSuccess[] = "OK";
const int kShortWaitTimeout = 10 * 1000;
const int kLongWaitTimeout = 30 * 1000;
class PluginTest : public UITest {
protected:
virtual void SetUp() {
const testing::TestInfo* const test_info =
testing::UnitTest::GetInstance()->current_test_info();
if (strcmp(test_info->name(), "MediaPlayerNew") == 0) {
// The installer adds our process names to the registry key below. Since
// the installer might not have run on this machine, add it manually.
RegKey regkey;
if (regkey.Open(HKEY_LOCAL_MACHINE,
L"Software\\Microsoft\\MediaPlayer\\ShimInclusionList",
KEY_WRITE)) {
regkey.CreateKey(L"CHROME.EXE", KEY_READ);
}
} else if (strcmp(test_info->name(), "MediaPlayerOld") == 0) {
// When testing the old WMP plugin, we need to force Chrome to not load
// the new plugin.
launch_arguments_.AppendSwitch(kUseOldWMPPluginSwitch);
} else if (strcmp(test_info->name(), "FlashSecurity") == 0) {
launch_arguments_.AppendSwitchWithValue(switches::kTestSandbox,
L"security_tests.dll");
}
UITest::SetUp();
}
void TestPlugin(const std::wstring& test_case,
int timeout,
bool mock_http) {
GURL url = GetTestUrl(test_case, mock_http);
NavigateToURL(url);
WaitForFinish(timeout, mock_http);
}
// Generate the URL for testing a particular test.
// HTML for the tests is all located in test_directory\plugin\<testcase>
// Set |mock_http| to true to use mock HTTP server.
GURL GetTestUrl(const std::wstring &test_case, bool mock_http) {
if (mock_http)
return URLRequestMockHTTPJob::GetMockUrl(L"plugin/" + test_case);
FilePath path;
PathService::Get(chrome::DIR_TEST_DATA, &path);
path = path.AppendASCII("plugin");
path = path.Append(FilePath::FromWStringHack(test_case));
return net::FilePathToFileURL(path);
}
// Waits for the test case to finish.
void WaitForFinish(const int wait_time, bool mock_http) {
const int kSleepTime = 500; // 2 times per second
const int kMaxIntervals = wait_time / kSleepTime;
GURL url = GetTestUrl(L"done", mock_http);
scoped_refptr<TabProxy> tab(GetActiveTab());
std::string done_str;
for (int i = 0; i < kMaxIntervals; ++i) {
Sleep(kSleepTime);
// The webpage being tested has javascript which sets a cookie
// which signals completion of the test.
std::string cookieName = kTestCompleteCookie;
tab->GetCookieByName(url, cookieName, &done_str);
if (!done_str.empty())
break;
}
EXPECT_EQ(kTestCompleteSuccess, done_str);
}
};
TEST_F(PluginTest, Quicktime) {
TestPlugin(L"quicktime.html", kShortWaitTimeout, false);
}
TEST_F(PluginTest, MediaPlayerNew) {
TestPlugin(L"wmp_new.html", kShortWaitTimeout, false);
}
// http://crbug.com/4809
TEST_F(PluginTest, DISABLED_MediaPlayerOld) {
TestPlugin(L"wmp_old.html", kLongWaitTimeout, false);
}
TEST_F(PluginTest, Real) {
TestPlugin(L"real.html", kShortWaitTimeout, false);
}
TEST_F(PluginTest, Flash) {
TestPlugin(L"flash.html", kShortWaitTimeout, false);
}
TEST_F(PluginTest, FlashOctetStream) {
TestPlugin(L"flash-octet-stream.html", kShortWaitTimeout, false);
}
TEST_F(PluginTest, FlashSecurity) {
TestPlugin(L"flash.html", kShortWaitTimeout, false);
}
// http://crbug.com/16114
TEST_F(PluginTest, FlashLayoutWhilePainting) {
TestPlugin(L"flash-layout-while-painting.html", kShortWaitTimeout, true);
}
// http://crbug.com/8690
TEST_F(PluginTest, DISABLED_Java) {
TestPlugin(L"Java.html", kShortWaitTimeout, false);
}
TEST_F(PluginTest, Silverlight) {
TestPlugin(L"silverlight.html", kShortWaitTimeout, false);
}
<commit_msg>Disable flaky plugin tests. These keep causing bogus automatic tree closures.<commit_after>// Copyright 2008-2009, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Tests for the top plugins to catch regressions in our plugin host code, as
// well as in the out of process code. Currently this tests:
// Flash
// Real
// QuickTime
// Windows Media Player
// -this includes both WMP plugins. npdsplay.dll is the older one that
// comes with XP. np-mswmp.dll can be downloaded from Microsoft and
// needs SP2 or Vista.
#include <windows.h>
#include <shellapi.h>
#include <shlobj.h>
#include <comutil.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <string>
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/registry.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "third_party/npapi/bindings/npapi.h"
#include "webkit/default_plugin/plugin_impl.h"
#include "webkit/glue/plugins/plugin_constants_win.h"
#include "webkit/glue/plugins/plugin_list.h"
const char kTestCompleteCookie[] = "status";
const char kTestCompleteSuccess[] = "OK";
const int kShortWaitTimeout = 10 * 1000;
const int kLongWaitTimeout = 30 * 1000;
class PluginTest : public UITest {
protected:
virtual void SetUp() {
const testing::TestInfo* const test_info =
testing::UnitTest::GetInstance()->current_test_info();
if (strcmp(test_info->name(), "MediaPlayerNew") == 0) {
// The installer adds our process names to the registry key below. Since
// the installer might not have run on this machine, add it manually.
RegKey regkey;
if (regkey.Open(HKEY_LOCAL_MACHINE,
L"Software\\Microsoft\\MediaPlayer\\ShimInclusionList",
KEY_WRITE)) {
regkey.CreateKey(L"CHROME.EXE", KEY_READ);
}
} else if (strcmp(test_info->name(), "MediaPlayerOld") == 0) {
// When testing the old WMP plugin, we need to force Chrome to not load
// the new plugin.
launch_arguments_.AppendSwitch(kUseOldWMPPluginSwitch);
} else if (strcmp(test_info->name(), "FlashSecurity") == 0) {
launch_arguments_.AppendSwitchWithValue(switches::kTestSandbox,
L"security_tests.dll");
}
UITest::SetUp();
}
void TestPlugin(const std::wstring& test_case,
int timeout,
bool mock_http) {
GURL url = GetTestUrl(test_case, mock_http);
NavigateToURL(url);
WaitForFinish(timeout, mock_http);
}
// Generate the URL for testing a particular test.
// HTML for the tests is all located in test_directory\plugin\<testcase>
// Set |mock_http| to true to use mock HTTP server.
GURL GetTestUrl(const std::wstring &test_case, bool mock_http) {
if (mock_http)
return URLRequestMockHTTPJob::GetMockUrl(L"plugin/" + test_case);
FilePath path;
PathService::Get(chrome::DIR_TEST_DATA, &path);
path = path.AppendASCII("plugin");
path = path.Append(FilePath::FromWStringHack(test_case));
return net::FilePathToFileURL(path);
}
// Waits for the test case to finish.
void WaitForFinish(const int wait_time, bool mock_http) {
const int kSleepTime = 500; // 2 times per second
const int kMaxIntervals = wait_time / kSleepTime;
GURL url = GetTestUrl(L"done", mock_http);
scoped_refptr<TabProxy> tab(GetActiveTab());
std::string done_str;
for (int i = 0; i < kMaxIntervals; ++i) {
Sleep(kSleepTime);
// The webpage being tested has javascript which sets a cookie
// which signals completion of the test.
std::string cookieName = kTestCompleteCookie;
tab->GetCookieByName(url, cookieName, &done_str);
if (!done_str.empty())
break;
}
EXPECT_EQ(kTestCompleteSuccess, done_str);
}
};
TEST_F(PluginTest, Quicktime) {
TestPlugin(L"quicktime.html", kShortWaitTimeout, false);
}
TEST_F(PluginTest, MediaPlayerNew) {
TestPlugin(L"wmp_new.html", kShortWaitTimeout, false);
}
// http://crbug.com/4809
TEST_F(PluginTest, DISABLED_MediaPlayerOld) {
TestPlugin(L"wmp_old.html", kLongWaitTimeout, false);
}
TEST_F(PluginTest, Real) {
TestPlugin(L"real.html", kShortWaitTimeout, false);
}
TEST_F(PluginTest, Flash) {
TestPlugin(L"flash.html", kShortWaitTimeout, false);
}
TEST_F(PluginTest, FlashOctetStream) {
TestPlugin(L"flash-octet-stream.html", kShortWaitTimeout, false);
}
TEST_F(PluginTest, FlashSecurity) {
TestPlugin(L"flash.html", kShortWaitTimeout, false);
}
// http://crbug.com/16114
// Disabled for http://crbug.com/21538
TEST_F(PluginTest, DISABLED_FlashLayoutWhilePainting) {
TestPlugin(L"flash-layout-while-painting.html", kShortWaitTimeout, true);
}
// http://crbug.com/8690
TEST_F(PluginTest, DISABLED_Java) {
TestPlugin(L"Java.html", kShortWaitTimeout, false);
}
// Disabled for http://crbug.com/22666
TEST_F(PluginTest, DISABLED_Silverlight) {
TestPlugin(L"silverlight.html", kShortWaitTimeout, false);
}
<|endoftext|> |
<commit_before><commit_msg>Remove stale reference to ie_alt_tab. This went in by mistake.<commit_after><|endoftext|> |
<commit_before>#include <iostream>
#include <cstring>
#include <cstdlib>
#include "dacloud.h"
using namespace std;
int
main(int argc, char *argv[]) {
if (argc < 3)
return (-1);
string configpath = argv[1];
string useragent = argv[2];
da_cloud_config config;
::memset(&config, 0, sizeof(config));
if (da_cloud_init(&config, configpath.c_str()) == 0) {
da_cloud_header_head head;
da_cloud_property_head phead;
da_cloud_header_init(&head);
da_cloud_header_add(&head, "user-agent", useragent.c_str());
if (da_cloud_detect(&config, &head, &phead) == 0) {
da_cloud_property *p;
SLIST_FOREACH(p, &phead.list, entries) {
da_cloud_property_type type = p->type;
cout << p->name << ": ";
switch (type) {
case DA_CLOUD_LONG:
cout << p->value.l;
break;
case DA_CLOUD_BOOL:
cout << p->value.l > 0 ? "true" : "false";
break;
case DA_CLOUD_STRING:
cout << p->value.s;
break;
}
cout << endl;
}
da_cloud_properties_free(&phead);
}
da_cloud_header_free(&head);
da_cloud_fini(&config);
}
return (0);
}
<commit_msg>parenthesis around ternary expression<commit_after>#include <iostream>
#include <cstring>
#include <cstdlib>
#include "dacloud.h"
using namespace std;
int
main(int argc, char *argv[]) {
if (argc < 3)
return (-1);
string configpath = argv[1];
string useragent = argv[2];
da_cloud_config config;
::memset(&config, 0, sizeof(config));
if (da_cloud_init(&config, configpath.c_str()) == 0) {
da_cloud_header_head head;
da_cloud_property_head phead;
da_cloud_header_init(&head);
da_cloud_header_add(&head, "user-agent", useragent.c_str());
if (da_cloud_detect(&config, &head, &phead) == 0) {
da_cloud_property *p;
SLIST_FOREACH(p, &phead.list, entries) {
da_cloud_property_type type = p->type;
cout << p->name << ": ";
switch (type) {
case DA_CLOUD_LONG:
cout << p->value.l;
break;
case DA_CLOUD_BOOL:
cout << (p->value.l > 0 ? "true" : "false");
break;
case DA_CLOUD_STRING:
cout << p->value.s;
break;
}
cout << endl;
}
da_cloud_properties_free(&phead);
}
da_cloud_header_free(&head);
da_cloud_fini(&config);
}
return (0);
}
<|endoftext|> |
<commit_before>#ifndef ICMPHEADER_HPP_
#define ICMPHEADER_HPP_
/*
* Author: jrahm
* created: 2015/01/22
* ICMPHeader.hpp: <description>
*/
#include <Prelude>
#include <io/binary/Putter.hpp>
#include <io/binary/Getter.hpp>
#define ICMPHEADER_SIZE 8
namespace io {
namespace icmp {
enum Type {
ECHOREPLY=0 /* Echo Reply */
, DEST_UNREACH=3 /* Destination Unreachable */
, SOURCE_QUENCH=4 /* Source Quench */
, REDIRECT=5 /* Redirect (change route) */
, ECHO=8 /* Echo Request */
, TIME_EXCEEDED=11 /* Time Exceeded */
, PARAMETERPROB=12 /* Parameter Problem */
, TIMESTAMP=13 /* Timestamp Request */
, TIMESTAMPREPLY=14 /* Timestamp Reply */
, INFO_REQUEST=15 /* Information Request */
, INFO_REPLY=16 /* Information Reply */
, ADDRESS=17 /* Address Mask Request */
, ADDRESSREPLY=18 /* Address Mask Reply */
};
enum Code {
NET_UNREACH=0 /* Network Unreachable */
, HOST_UNREACH=1 /* Host Unreachable */
, PROT_UNREACH=2 /* Protocol Unreachable */
, PORT_UNREACH=3 /* Port Unreachable */
, FRAG_NEEDED=4 /* Fragmentation Needed/DF set */
, SR_FAILED=5 /* Source Route failed */
, NET_UNKNOWN=6
, HOST_UNKNOWN=7
, HOST_ISOLATED=8
, NET_ANO=9
, HOST_ANO=10
, NET_UNR_TOS=11
, HOST_UNR_TOS=12
, PKT_FILTERED=13 /* Packet filtered */
, PREC_VIOLATION=14 /* Precedence violation */
, PREC_CUTOFF=15 /* Precedence cut off */
};
}
class ICMPHeader {
public:
static ICMPHeader Echo(u16_t echoid, u16_t echo_seq);
inline void setType(icmp::Type type) { this->type = type; }
inline void setCode(icmp::Code code) { this->code = code; }
inline void setEchoId(u16_t echo_id) { this->echo_id = echo_id; }
inline void setEchoSequence(u16_t echo_seq) { this->echo_seq = echo_seq; }
inline void setGateway(u32_t gateway) { this->gw = gateway; }
inline void setMTU(u16_t mtu) { this->mtu = mtu; }
inline void setChecksum(u16_t check) { this->checksum = check; }
inline icmp::Type getType() { return type; }
inline icmp::Code getCode() { return code; }
inline u16_t getEchoId() { return echo_id; }
inline u16_t getEchoSequence() { return echo_seq; }
inline u32_t getGateway() { return gw; }
inline u16_t getMTU() { return mtu; }
size_t getChecksumSum() ;
inline ICMPHeader() {}
private:
inline ICMPHeader(icmp::Type t, icmp::Code c, u32_t g):
type(t), code(c), checksum(0), gw(g) {}
icmp::Type type;
icmp::Code code;
u16_t checksum;
union {
struct {
u16_t echo_id;
u16_t echo_seq;
};
u32_t gw;
struct {
u16_t unused;
u16_t mtu;
};
};
};
};
inline int putObject( io::Putter& putter, io::ICMPHeader& hdr ) {
putter.putByte( hdr.getType() );
putter.putByte( hdr.getCode() );
putter.putInt32be( hdr.getGateway() );
return 0;
}
inline int getObject( io::Getter& getter, io::ICMPHeader& hdr ) {
byte b; u32_t gw;
getter.getByte(b);
hdr.setType((io::icmp::Type)b);
getter.getByte(b);
hdr.setCode((io::icmp::Code)b);
getter.getInt32be(gw);
hdr.setGateway(gw);
return 0;
}
#endif /* ICMPHEADER_HPP_ */
<commit_msg>fixed serailize for icmp packet<commit_after>#ifndef ICMPHEADER_HPP_
#define ICMPHEADER_HPP_
/*
* Author: jrahm
* created: 2015/01/22
* ICMPHeader.hpp: <description>
*/
#include <Prelude>
#include <io/binary/Putter.hpp>
#include <io/binary/Getter.hpp>
#define ICMPHEADER_SIZE 8
namespace io {
namespace icmp {
enum Type {
ECHOREPLY=0 /* Echo Reply */
, DEST_UNREACH=3 /* Destination Unreachable */
, SOURCE_QUENCH=4 /* Source Quench */
, REDIRECT=5 /* Redirect (change route) */
, ECHO=8 /* Echo Request */
, TIME_EXCEEDED=11 /* Time Exceeded */
, PARAMETERPROB=12 /* Parameter Problem */
, TIMESTAMP=13 /* Timestamp Request */
, TIMESTAMPREPLY=14 /* Timestamp Reply */
, INFO_REQUEST=15 /* Information Request */
, INFO_REPLY=16 /* Information Reply */
, ADDRESS=17 /* Address Mask Request */
, ADDRESSREPLY=18 /* Address Mask Reply */
};
enum Code {
NET_UNREACH=0 /* Network Unreachable */
, HOST_UNREACH=1 /* Host Unreachable */
, PROT_UNREACH=2 /* Protocol Unreachable */
, PORT_UNREACH=3 /* Port Unreachable */
, FRAG_NEEDED=4 /* Fragmentation Needed/DF set */
, SR_FAILED=5 /* Source Route failed */
, NET_UNKNOWN=6
, HOST_UNKNOWN=7
, HOST_ISOLATED=8
, NET_ANO=9
, HOST_ANO=10
, NET_UNR_TOS=11
, HOST_UNR_TOS=12
, PKT_FILTERED=13 /* Packet filtered */
, PREC_VIOLATION=14 /* Precedence violation */
, PREC_CUTOFF=15 /* Precedence cut off */
};
}
class ICMPHeader {
public:
static ICMPHeader Echo(u16_t echoid, u16_t echo_seq);
inline void setType(icmp::Type type) { this->type = type; }
inline void setCode(icmp::Code code) { this->code = code; }
inline void setEchoId(u16_t echo_id) { this->echo_id = echo_id; }
inline void setEchoSequence(u16_t echo_seq) { this->echo_seq = echo_seq; }
inline void setGateway(u32_t gateway) { this->gw = gateway; }
inline void setMTU(u16_t mtu) { this->mtu = mtu; }
inline void setChecksum(u16_t check) { this->checksum = check; }
inline icmp::Type getType() { return type; }
inline icmp::Code getCode() { return code; }
inline u16_t getEchoId() { return echo_id; }
inline u16_t getEchoSequence() { return echo_seq; }
inline u32_t getGateway() { return gw; }
inline u16_t getMTU() { return mtu; }
inline u16_t getChecksum() { return checksum; }
size_t getChecksumSum() ;
inline ICMPHeader() {}
private:
inline ICMPHeader(icmp::Type t, icmp::Code c, u32_t g):
type(t), code(c), checksum(0), gw(g) {}
icmp::Type type;
icmp::Code code;
u16_t checksum;
union {
struct {
u16_t echo_id;
u16_t echo_seq;
};
u32_t gw;
struct {
u16_t unused;
u16_t mtu;
};
};
};
};
inline int putObject( io::Putter& putter, io::ICMPHeader& hdr ) {
putter.putByte( hdr.getType() );
putter.putByte( hdr.getCode() );
putter.putInt16be( hdr.getChecksum() );
putter.putInt32be( hdr.getGateway() );
return 0;
}
inline int getObject( io::Getter& getter, io::ICMPHeader& hdr ) {
byte b; u32_t gw; u16_t throwaway;
getter.getByte(b);
hdr.setType((io::icmp::Type)b);
getter.getByte(b);
hdr.setCode((io::icmp::Code)b);
getter.getInt16be(throwaway);
getter.getInt32be(gw);
hdr.setGateway(gw);
return 0;
}
#endif /* ICMPHEADER_HPP_ */
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkWebGLWidget.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkWebGLWidget.h"
#include "vtkActor2D.h"
#include "vtkDiscretizableColorTransferFunction.h"
#include "vtkObjectFactory.h"
#include "vtkScalarBarActor.h"
#include "vtkWebGLExporter.h"
#include "vtkWebGLObject.h"
#include <sstream>
vtkStandardNewMacro(vtkWebGLWidget);
vtkWebGLWidget::vtkWebGLWidget()
{
this->binaryData = NULL;
this->iswidget = false;
this->binarySize = 0;
this->orientation = 1;
this->interactAtServer = false;
this->title = NULL;
}
vtkWebGLWidget::~vtkWebGLWidget()
{
if (this->binaryData) delete[] this->binaryData;
while(this->colors.size() !=0)
{
double* xrgb = this->colors.back();
this->colors.pop_back();
delete[] xrgb;
}
if (this->title) delete[] this->title;
}
unsigned char* vtkWebGLWidget::GetBinaryData(int vtkNotUsed(part))
{
this->hasChanged = false;
return this->binaryData;
}
int vtkWebGLWidget::GetBinarySize(int vtkNotUsed(part))
{
return this->binarySize;
}
void vtkWebGLWidget::GenerateBinaryData()
{
if (this->binaryData)
{
delete[] this->binaryData;
}
std::string oldMD5 = "qqehissorapaz";
oldMD5 = this->MD5;
size_t pos = 0;
//Calculate the size used
//NumOfColors, Type, Position, Size, Colors, Orientation, numberOfLabels
int total = static_cast<int>(sizeof(int) + 1 + 4*sizeof(float) + this->colors.size()*(sizeof(float)+3*sizeof(char)) + 1 + 1 + strlen(this->title));
this->binaryData = new unsigned char[total];
int colorSize = static_cast<int>(this->colors.size());
memset(this->binaryData, 0, total); //Fill array with 0
memcpy(&this->binaryData[pos], &colorSize, sizeof(int)); pos+=sizeof(int); //Binary Data Size
this->binaryData[pos++] = 'C'; //Object Type
memcpy(&this->binaryData[pos], &this->position, sizeof(float)*2); pos+=sizeof(float)*2; //Position (double[2])
memcpy(&this->binaryData[pos], &this->size, sizeof(float)*2); pos+=sizeof(float)*2; //Size (double[2])
unsigned char rgb[3];
for(size_t i=0; i<colors.size(); i++) //Array of Colors (double, char[3])
{
float v = (float)this->colors[i][0];
memcpy(&this->binaryData[pos], &v, sizeof(float)); pos+=sizeof(float);
rgb[0] = (unsigned char)((int)(this->colors[i][1]*255));
rgb[1] = (unsigned char)((int)(this->colors[i][2]*255));
rgb[2] = (unsigned char)((int)(this->colors[i][3]*255));
memcpy(&this->binaryData[pos], rgb, 3*sizeof(unsigned char)); pos+=sizeof(unsigned char)*3;
}
unsigned char aux; aux = (unsigned char)this->orientation;
memcpy(&this->binaryData[pos], &aux, 1); pos++;
aux = (unsigned char)this->numberOfLabels;
memcpy(&this->binaryData[pos], &aux, 1); pos++;
memcpy(&this->binaryData[pos], this->title, strlen(this->title)); pos+=strlen(this->title);
this->binarySize = total;
vtkWebGLExporter::ComputeMD5(this->binaryData, total, this->MD5);
this->hasChanged = this->MD5.compare(oldMD5) != 0;
}
int vtkWebGLWidget::GetNumberOfParts()
{
return 1;
}
void vtkWebGLWidget::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
void vtkWebGLWidget::GetDataFromColorMap(vtkActor2D *actor)
{
vtkScalarBarActor* scalarbar = vtkScalarBarActor::SafeDownCast(actor);
this->numberOfLabels = scalarbar->GetNumberOfLabels();
std::stringstream title;
char* componentTitle = scalarbar->GetComponentTitle();
title << scalarbar->GetTitle();
if (componentTitle && strlen(componentTitle) > 0)
{
title << " ";
title << componentTitle;
}
if (this->title)
{
delete[] this->title;
}
std::string tmp = title.str();
this->title = new char[tmp.length()+1];
strcpy(this->title, tmp.c_str());
this->hasTransparency = (scalarbar->GetUseOpacity() != 0);
this->orientation = scalarbar->GetOrientation();
//Colors
vtkDiscretizableColorTransferFunction* lookup = vtkDiscretizableColorTransferFunction::SafeDownCast(scalarbar->GetLookupTable());
int num = 5*lookup->GetSize();
double* range = lookup->GetRange();
double v, s; v = range[0]; s = (range[1]-range[0])/(num-1);
for(int i=0; i<num; i++)
{
double* xrgb = new double[4];
scalarbar->GetLookupTable()->GetColor(v, &xrgb[1]);
xrgb[0] = v;
this->colors.push_back(xrgb);
v += s;
}
this->textFormat = scalarbar->GetLabelFormat(); //Float Format ex.: %-#6.3g
this->textPosition = scalarbar->GetTextPosition(); //Orientacao dos textos; 1;
double *pos = scalarbar->GetPosition();
double *siz = scalarbar->GetPosition2();
this->position[0] = pos[0]; this->position[1] = pos[1];//Widget Position
this->size[0] = siz[0]; this->size[1] = siz[1]; //Widget Size
}
<commit_msg>Fix shadowed variable warning.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkWebGLWidget.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkWebGLWidget.h"
#include "vtkActor2D.h"
#include "vtkDiscretizableColorTransferFunction.h"
#include "vtkObjectFactory.h"
#include "vtkScalarBarActor.h"
#include "vtkWebGLExporter.h"
#include "vtkWebGLObject.h"
#include <sstream>
vtkStandardNewMacro(vtkWebGLWidget);
vtkWebGLWidget::vtkWebGLWidget()
{
this->binaryData = NULL;
this->iswidget = false;
this->binarySize = 0;
this->orientation = 1;
this->interactAtServer = false;
this->title = NULL;
}
vtkWebGLWidget::~vtkWebGLWidget()
{
if (this->binaryData) delete[] this->binaryData;
while(this->colors.size() !=0)
{
double* xrgb = this->colors.back();
this->colors.pop_back();
delete[] xrgb;
}
if (this->title) delete[] this->title;
}
unsigned char* vtkWebGLWidget::GetBinaryData(int vtkNotUsed(part))
{
this->hasChanged = false;
return this->binaryData;
}
int vtkWebGLWidget::GetBinarySize(int vtkNotUsed(part))
{
return this->binarySize;
}
void vtkWebGLWidget::GenerateBinaryData()
{
if (this->binaryData)
{
delete[] this->binaryData;
}
std::string oldMD5 = "qqehissorapaz";
oldMD5 = this->MD5;
size_t pos = 0;
//Calculate the size used
//NumOfColors, Type, Position, Size, Colors, Orientation, numberOfLabels
int total = static_cast<int>(sizeof(int) + 1 + 4*sizeof(float) + this->colors.size()*(sizeof(float)+3*sizeof(char)) + 1 + 1 + strlen(this->title));
this->binaryData = new unsigned char[total];
int colorSize = static_cast<int>(this->colors.size());
memset(this->binaryData, 0, total); //Fill array with 0
memcpy(&this->binaryData[pos], &colorSize, sizeof(int)); pos+=sizeof(int); //Binary Data Size
this->binaryData[pos++] = 'C'; //Object Type
memcpy(&this->binaryData[pos], &this->position, sizeof(float)*2); pos+=sizeof(float)*2; //Position (double[2])
memcpy(&this->binaryData[pos], &this->size, sizeof(float)*2); pos+=sizeof(float)*2; //Size (double[2])
unsigned char rgb[3];
for(size_t i=0; i<colors.size(); i++) //Array of Colors (double, char[3])
{
float v = (float)this->colors[i][0];
memcpy(&this->binaryData[pos], &v, sizeof(float)); pos+=sizeof(float);
rgb[0] = (unsigned char)((int)(this->colors[i][1]*255));
rgb[1] = (unsigned char)((int)(this->colors[i][2]*255));
rgb[2] = (unsigned char)((int)(this->colors[i][3]*255));
memcpy(&this->binaryData[pos], rgb, 3*sizeof(unsigned char)); pos+=sizeof(unsigned char)*3;
}
unsigned char aux; aux = (unsigned char)this->orientation;
memcpy(&this->binaryData[pos], &aux, 1); pos++;
aux = (unsigned char)this->numberOfLabels;
memcpy(&this->binaryData[pos], &aux, 1); pos++;
memcpy(&this->binaryData[pos], this->title, strlen(this->title)); pos+=strlen(this->title);
this->binarySize = total;
vtkWebGLExporter::ComputeMD5(this->binaryData, total, this->MD5);
this->hasChanged = this->MD5.compare(oldMD5) != 0;
}
int vtkWebGLWidget::GetNumberOfParts()
{
return 1;
}
void vtkWebGLWidget::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
}
void vtkWebGLWidget::GetDataFromColorMap(vtkActor2D *actor)
{
vtkScalarBarActor* scalarbar = vtkScalarBarActor::SafeDownCast(actor);
this->numberOfLabels = scalarbar->GetNumberOfLabels();
std::stringstream theTitle;
char* componentTitle = scalarbar->GetComponentTitle();
theTitle << scalarbar->GetTitle();
if (componentTitle && strlen(componentTitle) > 0)
{
theTitle << " ";
theTitle << componentTitle;
}
if (this->title)
{
delete[] this->title;
}
std::string tmp = theTitle.str();
this->title = new char[tmp.length()+1];
strcpy(this->title, tmp.c_str());
this->hasTransparency = (scalarbar->GetUseOpacity() != 0);
this->orientation = scalarbar->GetOrientation();
//Colors
vtkDiscretizableColorTransferFunction* lookup = vtkDiscretizableColorTransferFunction::SafeDownCast(scalarbar->GetLookupTable());
int num = 5*lookup->GetSize();
double* range = lookup->GetRange();
double v, s; v = range[0]; s = (range[1]-range[0])/(num-1);
for(int i=0; i<num; i++)
{
double* xrgb = new double[4];
scalarbar->GetLookupTable()->GetColor(v, &xrgb[1]);
xrgb[0] = v;
this->colors.push_back(xrgb);
v += s;
}
this->textFormat = scalarbar->GetLabelFormat(); //Float Format ex.: %-#6.3g
this->textPosition = scalarbar->GetTextPosition(); //Orientacao dos textos; 1;
double *pos = scalarbar->GetPosition();
double *siz = scalarbar->GetPosition2();
this->position[0] = pos[0]; this->position[1] = pos[1];//Widget Position
this->size[0] = siz[0]; this->size[1] = siz[1]; //Widget Size
}
<|endoftext|> |
<commit_before>/* Copyright 2020 The TensorFlow Quantum Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <memory>
#include <vector>
#include "cirq/google/api/v2/program.pb.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/shape_inference.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/core/error_codes.pb.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow_quantum/core/ops/parse_context.h"
#include "tensorflow_quantum/core/ops/tfq_simulate_utils.h"
#include "tensorflow_quantum/core/proto/pauli_sum.pb.h"
#include "tensorflow_quantum/core/qsim/mux.h"
#include "tensorflow_quantum/core/qsim/state_space.h"
#include "tensorflow_quantum/core/src/circuit.h"
#include "tensorflow_quantum/core/src/circuit_parser.h"
#include "tensorflow_quantum/core/src/program_resolution.h"
namespace tfq {
using ::cirq::google::api::v2::Program;
using ::tensorflow::Status;
using ::tfq::proto::PauliSum;
using ::tfq::qsim::GetStateSpace;
using ::tfq::qsim::StateSpace;
class TfqSimulateExpectationOp : public tensorflow::OpKernel {
public:
explicit TfqSimulateExpectationOp(tensorflow::OpKernelConstruction *context)
: OpKernel(context) {}
void Compute(tensorflow::OpKernelContext *context) override {
// TODO (mbbrough): add more dimension checks for other inputs here.
const int num_inputs = context->num_inputs();
OP_REQUIRES(context, num_inputs == 4,
tensorflow::errors::InvalidArgument(absl::StrCat(
"Expected 4 inputs, got ", num_inputs, " inputs.")));
// Create the output Tensor.
const int output_dim_batch_size = context->input(0).dim_size(0);
const int output_dim_op_size = context->input(3).dim_size(1);
tensorflow::TensorShape output_shape;
output_shape.AddDim(output_dim_batch_size);
output_shape.AddDim(output_dim_op_size);
tensorflow::Tensor *output = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output));
auto output_tensor = output->matrix<float>();
std::vector<Program> programs;
std::vector<int> num_qubits;
std::vector<std::vector<PauliSum>> pauli_sums;
OP_REQUIRES_OK(context, GetProgramsAndNumQubits(context, &programs,
&num_qubits, &pauli_sums));
std::vector<SymbolMap> maps;
OP_REQUIRES_OK(context, GetSymbolMaps(context, &maps));
OP_REQUIRES(context, pauli_sums.size() == programs.size(),
tensorflow::errors::InvalidArgument(absl::StrCat(
"Number of circuits and PauliSums do not match. Got ",
programs.size(), " circuits and ", pauli_sums.size(),
" paulisums.")));
auto DoWork = [&](int start, int end) {
int old_batch_index = -2;
int cur_batch_index = -1;
int cur_op_index;
std::unique_ptr<StateSpace> test_state =
std::unique_ptr<StateSpace>(GetStateSpace(1, 1));
std::unique_ptr<StateSpace> scratch_state =
std::unique_ptr<StateSpace>(GetStateSpace(1, 1));
for (int i = start; i < end; i++) {
cur_batch_index = i / output_dim_op_size;
cur_op_index = i % output_dim_op_size;
// (#679) Just ignore empty program
if (programs[cur_batch_index].circuit().moments().empty()) {
output_tensor(cur_batch_index, cur_op_index) = -2.0;
continue;
}
if (cur_batch_index != old_batch_index) {
// We've run into a new wavefunction we must compute.
// Only compute a new wavefunction when we have to.
Program program = programs[cur_batch_index];
const int num = num_qubits[cur_batch_index];
OP_REQUIRES_OK(context,
ResolveSymbols(maps[cur_batch_index], &program));
Circuit circuit;
OP_REQUIRES_OK(context, CircuitFromProgram(program, num, &circuit));
// TODO(mbbrough): Update this allocation hack so that a StateSpace
// object can grow it's memory dynamically to larger and larger size
// without ever having to call free (until very end). This is tricky
// to implement because right now certain statespaces can't simulate
// all states and we use StateSpaceSlow for smaller circuits.
if (num != num_qubits[old_batch_index]) {
test_state.reset(GetStateSpace(num, 1));
test_state->CreateState();
// Also re-allocate scratch state for expectation calculations.
scratch_state.reset(GetStateSpace(num, 1));
scratch_state->CreateState();
}
// no need to update scratch_state since ComputeExpectation
// will take care of things for us.
test_state->SetStateZero();
OP_REQUIRES_OK(context, test_state->Update(circuit));
}
float expectation = 0.0;
OP_REQUIRES_OK(context, test_state->ComputeExpectation(
pauli_sums[cur_batch_index][cur_op_index],
scratch_state.get(), &expectation));
output_tensor(cur_batch_index, cur_op_index) = expectation;
old_batch_index = cur_batch_index;
}
};
const int block_size =
GetBlockSize(context, output_dim_batch_size * output_dim_op_size);
context->device()
->tensorflow_cpu_worker_threads()
->workers->TransformRangeConcurrently(
block_size, output_dim_batch_size * output_dim_op_size, DoWork);
}
};
REGISTER_KERNEL_BUILDER(
Name("TfqSimulateExpectation").Device(tensorflow::DEVICE_CPU),
TfqSimulateExpectationOp);
REGISTER_OP("TfqSimulateExpectation")
.Input("programs: string")
.Input("symbol_names: string")
.Input("symbol_values: float")
.Input("pauli_sums: string")
.Output("expectations: float")
.SetShapeFn([](tensorflow::shape_inference::InferenceContext *c) {
tensorflow::shape_inference::ShapeHandle programs_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 1, &programs_shape));
tensorflow::shape_inference::ShapeHandle symbol_names_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 1, &symbol_names_shape));
tensorflow::shape_inference::ShapeHandle symbol_values_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(2), 2, &symbol_values_shape));
tensorflow::shape_inference::ShapeHandle pauli_sums_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(3), 2, &pauli_sums_shape));
tensorflow::shape_inference::DimensionHandle output_rows =
c->Dim(programs_shape, 0);
tensorflow::shape_inference::DimensionHandle output_cols =
c->Dim(pauli_sums_shape, 1);
c->set_output(0, c->Matrix(output_rows, output_cols));
return tensorflow::Status::OK();
});
} // namespace tfq
<commit_msg>Fixed Memory Issues. (#127)<commit_after>/* Copyright 2020 The TensorFlow Quantum Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <memory>
#include <vector>
#include "cirq/google/api/v2/program.pb.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/shape_inference.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/core/error_codes.pb.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow_quantum/core/ops/parse_context.h"
#include "tensorflow_quantum/core/ops/tfq_simulate_utils.h"
#include "tensorflow_quantum/core/proto/pauli_sum.pb.h"
#include "tensorflow_quantum/core/qsim/mux.h"
#include "tensorflow_quantum/core/qsim/state_space.h"
#include "tensorflow_quantum/core/src/circuit.h"
#include "tensorflow_quantum/core/src/circuit_parser.h"
#include "tensorflow_quantum/core/src/program_resolution.h"
namespace tfq {
using ::cirq::google::api::v2::Program;
using ::tensorflow::Status;
using ::tfq::proto::PauliSum;
using ::tfq::qsim::GetStateSpace;
using ::tfq::qsim::StateSpace;
class TfqSimulateExpectationOp : public tensorflow::OpKernel {
public:
explicit TfqSimulateExpectationOp(tensorflow::OpKernelConstruction *context)
: OpKernel(context) {}
void Compute(tensorflow::OpKernelContext *context) override {
// TODO (mbbrough): add more dimension checks for other inputs here.
const int num_inputs = context->num_inputs();
OP_REQUIRES(context, num_inputs == 4,
tensorflow::errors::InvalidArgument(absl::StrCat(
"Expected 4 inputs, got ", num_inputs, " inputs.")));
// Create the output Tensor.
const int output_dim_batch_size = context->input(0).dim_size(0);
const int output_dim_op_size = context->input(3).dim_size(1);
tensorflow::TensorShape output_shape;
output_shape.AddDim(output_dim_batch_size);
output_shape.AddDim(output_dim_op_size);
tensorflow::Tensor *output = nullptr;
OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output));
auto output_tensor = output->matrix<float>();
std::vector<Program> programs;
std::vector<int> num_qubits;
std::vector<std::vector<PauliSum>> pauli_sums;
OP_REQUIRES_OK(context, GetProgramsAndNumQubits(context, &programs,
&num_qubits, &pauli_sums));
std::vector<SymbolMap> maps;
OP_REQUIRES_OK(context, GetSymbolMaps(context, &maps));
OP_REQUIRES(context, pauli_sums.size() == programs.size(),
tensorflow::errors::InvalidArgument(absl::StrCat(
"Number of circuits and PauliSums do not match. Got ",
programs.size(), " circuits and ", pauli_sums.size(),
" paulisums.")));
auto DoWork = [&](int start, int end) {
int old_batch_index = -2;
int cur_batch_index = -1;
int old_num_qubits = -2;
int cur_op_index;
std::unique_ptr<StateSpace> test_state =
std::unique_ptr<StateSpace>(GetStateSpace(1, 1));
std::unique_ptr<StateSpace> scratch_state =
std::unique_ptr<StateSpace>(GetStateSpace(1, 1));
for (int i = start; i < end; i++) {
cur_batch_index = i / output_dim_op_size;
cur_op_index = i % output_dim_op_size;
// (#679) Just ignore empty program
if (programs[cur_batch_index].circuit().moments().empty()) {
output_tensor(cur_batch_index, cur_op_index) = -2.0;
continue;
}
if (cur_batch_index != old_batch_index) {
// We've run into a new wavefunction we must compute.
// Only compute a new wavefunction when we have to.
Program program = programs[cur_batch_index];
const int num = num_qubits[cur_batch_index];
OP_REQUIRES_OK(context,
ResolveSymbols(maps[cur_batch_index], &program));
Circuit circuit;
OP_REQUIRES_OK(context, CircuitFromProgram(program, num, &circuit));
// TODO(mbbrough): Update this allocation hack so that a StateSpace
// object can grow it's memory dynamically to larger and larger size
// without ever having to call free (until very end). This is tricky
// to implement because right now certain statespaces can't simulate
// all states and we use StateSpaceSlow for smaller circuits.
if (num != old_num_qubits) {
test_state.reset(GetStateSpace(num, 1));
test_state->CreateState();
// Also re-allocate scratch state for expectation calculations.
scratch_state.reset(GetStateSpace(num, 1));
scratch_state->CreateState();
}
// no need to update scratch_state since ComputeExpectation
// will take care of things for us.
test_state->SetStateZero();
OP_REQUIRES_OK(context, test_state->Update(circuit));
old_num_qubits = num;
}
float expectation = 0.0;
OP_REQUIRES_OK(context, test_state->ComputeExpectation(
pauli_sums[cur_batch_index][cur_op_index],
scratch_state.get(), &expectation));
output_tensor(cur_batch_index, cur_op_index) = expectation;
old_batch_index = cur_batch_index;
}
};
const int block_size =
GetBlockSize(context, output_dim_batch_size * output_dim_op_size);
context->device()
->tensorflow_cpu_worker_threads()
->workers->TransformRangeConcurrently(
block_size, output_dim_batch_size * output_dim_op_size, DoWork);
}
};
REGISTER_KERNEL_BUILDER(
Name("TfqSimulateExpectation").Device(tensorflow::DEVICE_CPU),
TfqSimulateExpectationOp);
REGISTER_OP("TfqSimulateExpectation")
.Input("programs: string")
.Input("symbol_names: string")
.Input("symbol_values: float")
.Input("pauli_sums: string")
.Output("expectations: float")
.SetShapeFn([](tensorflow::shape_inference::InferenceContext *c) {
tensorflow::shape_inference::ShapeHandle programs_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 1, &programs_shape));
tensorflow::shape_inference::ShapeHandle symbol_names_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 1, &symbol_names_shape));
tensorflow::shape_inference::ShapeHandle symbol_values_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(2), 2, &symbol_values_shape));
tensorflow::shape_inference::ShapeHandle pauli_sums_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(3), 2, &pauli_sums_shape));
tensorflow::shape_inference::DimensionHandle output_rows =
c->Dim(programs_shape, 0);
tensorflow::shape_inference::DimensionHandle output_cols =
c->Dim(pauli_sums_shape, 1);
c->set_output(0, c->Matrix(output_rows, output_cols));
return tensorflow::Status::OK();
});
} // namespace tfq
<|endoftext|> |
<commit_before>#include "vulkan/vulkan.h"
#include <Windows.h>
int CALLBACK
WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
auto createInstanceFn = reinterpret_cast<PFN_vkCreateInstance>(vkGetInstanceProcAddr(nullptr, "vkCreateInstance"));
::VkInstanceCreateInfo createInfo;
//::VkAllocationCallbacks allocCbs;
::VkInstance instance;
memset(&createInfo, 0, sizeof(createInfo));
createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; // required
//memset(&allocCbs, 0, sizeof(allocCbs));
auto result = createInstanceFn(&createInfo, nullptr, &instance);
if (VK_SUCCESS == result)
{
auto destroyInstanceFn = reinterpret_cast<PFN_vkDestroyInstance>(vkGetInstanceProcAddr(instance, "vkDestroyInstance"));
destroyInstanceFn(instance, nullptr);
}
return 0;
}
<commit_msg>[tests,VulkanCube] Some more Vulkan test code, enumerating physical devices, querying their features, and creating a logical device (which doesn't work yet)<commit_after>#include "vulkan/vulkan.h"
#include <Windows.h>
int CALLBACK
WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
auto createInstanceFn = reinterpret_cast<PFN_vkCreateInstance>(vkGetInstanceProcAddr(nullptr, "vkCreateInstance"));
::VkInstanceCreateInfo createInfo;
//::VkAllocationCallbacks allocCbs;
::VkInstance instance;
memset(&createInfo, 0, sizeof(createInfo));
createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; // required
//memset(&allocCbs, 0, sizeof(allocCbs));
auto createInstanceRes = createInstanceFn(&createInfo, nullptr, &instance);
if (VK_SUCCESS != createInstanceRes)
{
return -1;
}
// enumerate physical devices
auto enumPhysDevicesFn = reinterpret_cast<PFN_vkEnumeratePhysicalDevices>(vkGetInstanceProcAddr(instance, "vkEnumeratePhysicalDevices"));
uint32_t numPhysicalDevices = 0;
// get number of physical devices
auto enumPhysDevicesRes = enumPhysDevicesFn(instance, &numPhysicalDevices, nullptr);
if (VK_SUCCESS != enumPhysDevicesRes)
{
// TODO: need some RAII on the instance
return -1;
}
auto physicalDevices = new VkPhysicalDevice[numPhysicalDevices];
enumPhysDevicesRes = enumPhysDevicesFn(instance, &numPhysicalDevices, physicalDevices);
if (VK_SUCCESS != enumPhysDevicesRes)
{
// TODO: need some RAII on the instance
return -1;
}
auto getPhysDeviceFeaturesFn = reinterpret_cast<PFN_vkGetPhysicalDeviceFeatures>(vkGetInstanceProcAddr(instance, "vkGetPhysicalDeviceFeatures"));
for (auto i = 0; i < numPhysicalDevices; ++i)
{
auto device = physicalDevices[i];
VkPhysicalDeviceFeatures features;
getPhysDeviceFeaturesFn(device, &features);
}
// create a logical device
auto createDeviceFn = reinterpret_cast<PFN_vkCreateDevice>(vkGetInstanceProcAddr(instance, "vkCreateDevice"));
VkDeviceCreateInfo deviceCreateInfo;
memset(&deviceCreateInfo, 0, sizeof(deviceCreateInfo));
deviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
VkDevice device;
auto createDeviceRes = createDeviceFn(physicalDevices[0], &deviceCreateInfo, nullptr, &device);
if (VK_SUCCESS != createDeviceRes)
{
return -1;
}
// destroy the logical device
auto destroyDeviceFn = reinterpret_cast<PFN_vkDestroyDevice>(vkGetInstanceProcAddr(instance, "vkDestroyDevice"));
destroyDeviceFn(device, nullptr);
delete[] physicalDevices;
auto destroyInstanceFn = reinterpret_cast<PFN_vkDestroyInstance>(vkGetInstanceProcAddr(instance, "vkDestroyInstance"));
destroyInstanceFn(instance, nullptr);
return 0;
}
<|endoftext|> |
<commit_before>#include "diagram.h"
#include "type.h"
#include "enumType.h"
#include "numericType.h"
#include "stringType.h"
#include "nodeType.h"
#include "edgeType.h"
#include "editor.h"
#include <QDebug>
Diagram::Diagram(QString const &name, QString const &nodeName, QString const &displayedName, Editor *editor)
: mDiagramName(name), mDiagramNodeName(nodeName), mDiagramDisplayedName(displayedName), mEditor(editor)
{}
Diagram::~Diagram()
{
foreach(Type *type, mTypes.values())
if (type)
delete type;
}
bool Diagram::init(QDomElement const &diagramElement)
{
for (QDomElement element = diagramElement.firstChildElement();
!element.isNull();
element = element.nextSiblingElement())
{
if (element.nodeName() == "graphicTypes") {
if (!initGraphicTypes(element))
return false;
} else if (element.nodeName() == "nonGraphicTypes") {
if (!initNonGraphicTypes(element))
return false;
} else if (element.nodeName() == "palette") {
initPaletteGroups(element);
} else
qDebug() << "ERROR: unknown tag" << element.nodeName();
}
return true;
}
bool Diagram::initGraphicTypes(QDomElement const &graphicTypesElement)
{
for (QDomElement element = graphicTypesElement.firstChildElement();
!element.isNull();
element = element.nextSiblingElement())
{
if (element.nodeName() == "node") {
Type *nodeType = new NodeType(this);
if (!nodeType->init(element, mDiagramName)) {
delete nodeType;
qDebug() << "Can't parse node";
return false;
}
mTypes[nodeType->qualifiedName()] = nodeType;
} else if (element.nodeName() == "edge") {
Type *edgeType = new EdgeType(this);
if (!edgeType->init(element, mDiagramName)) {
delete edgeType;
qDebug() << "Can't parse edge";
return false;
}
mTypes[edgeType->qualifiedName()] = edgeType;
} else if (element.nodeName() == "import") {
ImportSpecification import = {
element.attribute("name", ""),
element.attribute("as", ""),
element.attribute("displayedName", "")
};
mImports.append(import);
}
else
{
qDebug() << "ERROR: unknown graphic type" << element.nodeName();
return false;
}
}
return true;
}
bool Diagram::initNonGraphicTypes(QDomElement const &nonGraphicTypesElement)
{
for (QDomElement element = nonGraphicTypesElement.firstChildElement();
!element.isNull();
element = element.nextSiblingElement())
{
if (element.nodeName() == "enum")
{
Type *enumType = new EnumType();
if (!enumType->init(element, mDiagramName))
{
delete enumType;
qDebug() << "Can't parse enum";
return false;
}
mTypes[enumType->qualifiedName()] = enumType;
} else if (element.nodeName() == "numeric")
{
Type *numericType = new NumericType();
if (!numericType->init(element, mDiagramName))
{
delete numericType;
qDebug() << "Can't parse numeric type";
return false;
}
mTypes[numericType->qualifiedName()] = numericType;
} else if (element.nodeName() == "string")
{
Type *stringType = new StringType();
if (!stringType->init(element, mDiagramName))
{
delete stringType;
qDebug() << "Can't parse string type";
return false;
}
mTypes[stringType->qualifiedName()] = stringType;
}
else
{
qDebug() << "ERROR: unknown non graphic type" << element.nodeName();
return false;
}
}
return true;
}
void Diagram::initPaletteGroups(const QDomElement &paletteGroupsElement)
{
for (QDomElement element = paletteGroupsElement.firstChildElement("group");
!element.isNull();
element = element.nextSiblingElement("group"))
{
QString name = element.attribute("name");
QString description = element.attribute("description", "");
mPaletteGroupsDescriptions[name] = description;
FILE *f = fopen("1.txt", "wt");
fprintf(f, "%s\n", element.attribute("name").toStdString().c_str());
for (QDomElement groupElement = element.firstChildElement("element");
!groupElement.isNull();
groupElement = groupElement.nextSiblingElement("element"))
{
mPaletteGroups[name].append(groupElement.attribute("name"));
}
}
}
bool Diagram::resolve()
{
foreach (ImportSpecification import, mImports) {
Type *importedType = mEditor->findType(import.name);
if (importedType == NULL) {
qDebug() << "ERROR: imported type" << import.name << "not found, skipping";
continue;
}
Type *copiedType = importedType->clone();
copiedType->setName(import.as);
copiedType->setDisplayedName(import.displayedName);
copiedType->setDiagram(this);
copiedType->setContext(mDiagramName);
mTypes.insert(copiedType->qualifiedName(), copiedType);
}
foreach(Type *type, mTypes.values())
if (!type->resolve()) {
qDebug() << "ERROR: can't resolve type" << type->name();
return false;
}
return true;
}
Editor* Diagram::editor() const
{
return mEditor;
}
Type* Diagram::findType(QString name)
{
if (mTypes.contains(name))
return mTypes[name];
else
return mEditor->findType(name);
}
QMap<QString, Type*> Diagram::types() const
{
return mTypes;
}
QString Diagram::name() const
{
return mDiagramName;
}
QString Diagram::nodeName() const
{
return mDiagramNodeName;
}
QString Diagram::displayedName() const
{
return mDiagramDisplayedName;
}
QMap<QString, QStringList> Diagram::paletteGroups() const
{
return mPaletteGroups;
}
QMap<QString, QString> Diagram::paletteGroupsDescriptions() const
{
return mPaletteGroupsDescriptions;
}
<commit_msg>вроде как ненужные строчки убраны<commit_after>#include "diagram.h"
#include "type.h"
#include "enumType.h"
#include "numericType.h"
#include "stringType.h"
#include "nodeType.h"
#include "edgeType.h"
#include "editor.h"
#include <QDebug>
Diagram::Diagram(QString const &name, QString const &nodeName, QString const &displayedName, Editor *editor)
: mDiagramName(name), mDiagramNodeName(nodeName), mDiagramDisplayedName(displayedName), mEditor(editor)
{}
Diagram::~Diagram()
{
foreach(Type *type, mTypes.values())
if (type)
delete type;
}
bool Diagram::init(QDomElement const &diagramElement)
{
for (QDomElement element = diagramElement.firstChildElement();
!element.isNull();
element = element.nextSiblingElement())
{
if (element.nodeName() == "graphicTypes") {
if (!initGraphicTypes(element))
return false;
} else if (element.nodeName() == "nonGraphicTypes") {
if (!initNonGraphicTypes(element))
return false;
} else if (element.nodeName() == "palette") {
initPaletteGroups(element);
} else
qDebug() << "ERROR: unknown tag" << element.nodeName();
}
return true;
}
bool Diagram::initGraphicTypes(QDomElement const &graphicTypesElement)
{
for (QDomElement element = graphicTypesElement.firstChildElement();
!element.isNull();
element = element.nextSiblingElement())
{
if (element.nodeName() == "node") {
Type *nodeType = new NodeType(this);
if (!nodeType->init(element, mDiagramName)) {
delete nodeType;
qDebug() << "Can't parse node";
return false;
}
mTypes[nodeType->qualifiedName()] = nodeType;
} else if (element.nodeName() == "edge") {
Type *edgeType = new EdgeType(this);
if (!edgeType->init(element, mDiagramName)) {
delete edgeType;
qDebug() << "Can't parse edge";
return false;
}
mTypes[edgeType->qualifiedName()] = edgeType;
} else if (element.nodeName() == "import") {
ImportSpecification import = {
element.attribute("name", ""),
element.attribute("as", ""),
element.attribute("displayedName", "")
};
mImports.append(import);
}
else
{
qDebug() << "ERROR: unknown graphic type" << element.nodeName();
return false;
}
}
return true;
}
bool Diagram::initNonGraphicTypes(QDomElement const &nonGraphicTypesElement)
{
for (QDomElement element = nonGraphicTypesElement.firstChildElement();
!element.isNull();
element = element.nextSiblingElement())
{
if (element.nodeName() == "enum")
{
Type *enumType = new EnumType();
if (!enumType->init(element, mDiagramName))
{
delete enumType;
qDebug() << "Can't parse enum";
return false;
}
mTypes[enumType->qualifiedName()] = enumType;
} else if (element.nodeName() == "numeric")
{
Type *numericType = new NumericType();
if (!numericType->init(element, mDiagramName))
{
delete numericType;
qDebug() << "Can't parse numeric type";
return false;
}
mTypes[numericType->qualifiedName()] = numericType;
} else if (element.nodeName() == "string")
{
Type *stringType = new StringType();
if (!stringType->init(element, mDiagramName))
{
delete stringType;
qDebug() << "Can't parse string type";
return false;
}
mTypes[stringType->qualifiedName()] = stringType;
}
else
{
qDebug() << "ERROR: unknown non graphic type" << element.nodeName();
return false;
}
}
return true;
}
void Diagram::initPaletteGroups(const QDomElement &paletteGroupsElement)
{
for (QDomElement element = paletteGroupsElement.firstChildElement("group");
!element.isNull();
element = element.nextSiblingElement("group"))
{
QString name = element.attribute("name");
QString description = element.attribute("description", "");
mPaletteGroupsDescriptions[name] = description;
for (QDomElement groupElement = element.firstChildElement("element");
!groupElement.isNull();
groupElement = groupElement.nextSiblingElement("element"))
{
mPaletteGroups[name].append(groupElement.attribute("name"));
}
}
}
bool Diagram::resolve()
{
foreach (ImportSpecification import, mImports) {
Type *importedType = mEditor->findType(import.name);
if (importedType == NULL) {
qDebug() << "ERROR: imported type" << import.name << "not found, skipping";
continue;
}
Type *copiedType = importedType->clone();
copiedType->setName(import.as);
copiedType->setDisplayedName(import.displayedName);
copiedType->setDiagram(this);
copiedType->setContext(mDiagramName);
mTypes.insert(copiedType->qualifiedName(), copiedType);
}
foreach(Type *type, mTypes.values())
if (!type->resolve()) {
qDebug() << "ERROR: can't resolve type" << type->name();
return false;
}
return true;
}
Editor* Diagram::editor() const
{
return mEditor;
}
Type* Diagram::findType(QString name)
{
if (mTypes.contains(name))
return mTypes[name];
else
return mEditor->findType(name);
}
QMap<QString, Type*> Diagram::types() const
{
return mTypes;
}
QString Diagram::name() const
{
return mDiagramName;
}
QString Diagram::nodeName() const
{
return mDiagramNodeName;
}
QString Diagram::displayedName() const
{
return mDiagramDisplayedName;
}
QMap<QString, QStringList> Diagram::paletteGroups() const
{
return mPaletteGroups;
}
QMap<QString, QString> Diagram::paletteGroupsDescriptions() const
{
return mPaletteGroupsDescriptions;
}
<|endoftext|> |
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "remote_slobrok.h"
#include "rpc_server_map.h"
#include "rpc_server_manager.h"
#include "exchange_manager.h"
#include "sbenv.h"
#include <vespa/fnet/frt/supervisor.h>
#include <vespa/fnet/frt/target.h>
#include <vespa/log/log.h>
LOG_SETUP(".slobrok.server.remote_slobrok");
namespace slobrok {
//-----------------------------------------------------------------------------
RemoteSlobrok::RemoteSlobrok(const std::string &name, const std::string &spec,
ExchangeManager &manager)
: _exchanger(manager),
_rpcsrvmanager(manager._rpcsrvmanager),
_remote(nullptr),
_serviceMapMirror(),
_rpcserver(name, spec, *this),
_reconnecter(getSupervisor()->GetScheduler(), *this),
_failCnt(0),
_consensusSubscription(MapSubscription::subscribe(_serviceMapMirror, _exchanger._env.consensusMap())),
_remAddPeerReq(nullptr),
_remListReq(nullptr),
_remAddReq(nullptr),
_remRemReq(nullptr),
_remFetchReq(nullptr),
_pending()
{
_rpcserver.healthCheck();
}
void RemoteSlobrok::shutdown() {
_reconnecter.disable();
_pending.clear();
if (_remote != nullptr) {
_remote->SubRef();
_remote = nullptr;
}
if (_remFetchReq != nullptr) {
_remFetchReq->Abort();
}
if (_remAddPeerReq != nullptr) {
_remAddPeerReq->Abort();
}
if (_remListReq != nullptr) {
_remListReq->Abort();
}
if (_remAddReq != nullptr) {
_remAddReq->Abort();
}
if (_remRemReq != nullptr) {
_remRemReq->Abort();
}
_serviceMapMirror.clear();
}
RemoteSlobrok::~RemoteSlobrok() {
shutdown();
// _rpcserver destructor called automatically
}
void
RemoteSlobrok::doPending()
{
if (_remAddReq != nullptr) return;
if (_remRemReq != nullptr) return;
if (_remote == nullptr) return;
if ( ! _pending.empty() ) {
std::unique_ptr<NamedService> todo = std::move(_pending.front());
_pending.pop_front();
const NamedService *rpcsrv = _exchanger._rpcsrvmap.lookup(todo->getName());
if (rpcsrv == nullptr) {
_remRemReq = getSupervisor()->AllocRPCRequest();
_remRemReq->SetMethodName("slobrok.internal.doRemove");
_remRemReq->GetParams()->AddString(_exchanger._env.mySpec().c_str());
_remRemReq->GetParams()->AddString(todo->getName().c_str());
_remRemReq->GetParams()->AddString(todo->getSpec().c_str());
_remote->InvokeAsync(_remRemReq, 2.0, this);
} else {
_remAddReq = getSupervisor()->AllocRPCRequest();
_remAddReq->SetMethodName("slobrok.internal.doAdd");
_remAddReq->GetParams()->AddString(_exchanger._env.mySpec().c_str());
_remAddReq->GetParams()->AddString(todo->getName().c_str());
_remAddReq->GetParams()->AddString(rpcsrv->getSpec().c_str());
_remote->InvokeAsync(_remAddReq, 2.0, this);
}
// XXX should save this and pick up on RequestDone()
}
}
void RemoteSlobrok::maybeStartFetch() {
if (_remFetchReq != nullptr) return;
if (_remote == nullptr) return;
_remFetchReq = getSupervisor()->AllocRPCRequest();
_remFetchReq->SetMethodName("slobrok.internal.fetchLocalView");
_remFetchReq->GetParams()->AddInt32(_serviceMapMirror.currentGeneration().getAsInt());
_remFetchReq->GetParams()->AddInt32(5000);
_remote->InvokeAsync(_remFetchReq, 15.0, this);
}
void RemoteSlobrok::handleFetchResult() {
LOG_ASSERT(_remFetchReq != nullptr);
bool success = true;
if (_remFetchReq->CheckReturnTypes("iSSSi")) {
FRT_Values &answer = *(_remFetchReq->GetReturn());
uint32_t diff_from = answer[0]._intval32;
uint32_t numRemove = answer[1]._string_array._len;
FRT_StringValue *r = answer[1]._string_array._pt;
uint32_t numNames = answer[2]._string_array._len;
FRT_StringValue *n = answer[2]._string_array._pt;
uint32_t numSpecs = answer[3]._string_array._len;
FRT_StringValue *s = answer[3]._string_array._pt;
uint32_t diff_to = answer[4]._intval32;
std::vector<vespalib::string> removed;
for (uint32_t idx = 0; idx < numRemove; ++idx) {
removed.emplace_back(r[idx]._str);
}
ServiceMappingList updated;
if (numNames == numSpecs) {
for (uint32_t idx = 0; idx < numNames; ++idx) {
updated.emplace_back(n[idx]._str, s[idx]._str);
}
} else {
diff_from = 0;
diff_to = 0;
success = false;
}
MapDiff diff(diff_from, std::move(removed), std::move(updated), diff_to);
if (diff_from == 0) {
_serviceMapMirror.clear();
_serviceMapMirror.apply(std::move(diff));
} else if (diff_from == _serviceMapMirror.currentGeneration().getAsInt()) {
_serviceMapMirror.apply(std::move(diff));
} else {
_serviceMapMirror.clear();
success = false;
}
} else {
if (_remFetchReq->GetErrorCode() == FRTE_RPC_NO_SUCH_METHOD) {
LOG(debug, "partner slobrok too old - not mirroring");
} else {
LOG(warning, "fetchLocalView() failed with partner %s: %s",
getName().c_str(), _remFetchReq->GetErrorMessage());
}
_serviceMapMirror.clear();
success = false;
}
_remFetchReq->SubRef();
_remFetchReq = nullptr;
if (success) {
maybeStartFetch();
}
}
void
RemoteSlobrok::pushMine()
{
// all mine
std::vector<const NamedService *> mine = _exchanger._rpcsrvmap.allManaged();
while (mine.size() > 0) {
const NamedService *now = mine.back();
mine.pop_back();
_pending.push_back(std::make_unique<NamedService>(now->getName(), now->getSpec()));
}
doPending();
}
void
RemoteSlobrok::RequestDone(FRT_RPCRequest *req)
{
if (req == _remFetchReq) {
handleFetchResult();
return;
}
FRT_Values &answer = *(req->GetReturn());
if (req == _remAddPeerReq) {
// handle response after asking remote slobrok to add me as a peer:
if (req->IsError()) {
FRT_Values &args = *req->GetParams();
const char *myname = args[0]._string._str;
const char *myspec = args[1]._string._str;
LOG(info, "addPeer(%s, %s) on remote slobrok %s at %s: %s",
myname, myspec, getName().c_str(), getSpec().c_str(), req->GetErrorMessage());
req->SubRef();
_remAddPeerReq = nullptr;
goto retrylater;
}
req->SubRef();
_remAddPeerReq = nullptr;
// next step is to ask the remote to send its list of managed names:
LOG_ASSERT(_remListReq == nullptr);
_remListReq = getSupervisor()->AllocRPCRequest();
_remListReq->SetMethodName("slobrok.internal.listManagedRpcServers");
if (_remote != nullptr) {
_remote->InvokeAsync(_remListReq, 3.0, this);
}
// when _remListReq is returned, our managed list is added
} else if (req == _remListReq) {
// handle the list sent from the remote:
if (req->IsError()
|| strcmp(answer.GetTypeString(), "SS") != 0)
{
LOG(error, "error listing remote slobrok %s at %s: %s",
getName().c_str(), getSpec().c_str(), req->GetErrorMessage());
req->SubRef();
_remListReq = nullptr;
goto retrylater;
}
uint32_t numNames = answer.GetValue(0)._string_array._len;
uint32_t numSpecs = answer.GetValue(1)._string_array._len;
if (numNames != numSpecs) {
LOG(error, "inconsistent array lengths from %s at %s", getName().c_str(), getSpec().c_str());
req->SubRef();
_remListReq = nullptr;
goto retrylater;
}
FRT_StringValue *names = answer.GetValue(0)._string_array._pt;
FRT_StringValue *specs = answer.GetValue(1)._string_array._pt;
for (uint32_t idx = 0; idx < numNames; idx++) {
_rpcsrvmanager.addRemote(names[idx]._str, specs[idx]._str);
}
req->SubRef();
_remListReq = nullptr;
// next step is to push the ones I own:
maybeStartFetch();
maybePushMine();
} else if (req == _remAddReq) {
// handle response after pushing some name that we managed:
if (req->IsError() && (req->GetErrorCode() == FRTE_RPC_CONNECTION ||
req->GetErrorCode() == FRTE_RPC_TIMEOUT))
{
LOG(error, "connection error adding to remote slobrok: %s", req->GetErrorMessage());
req->SubRef();
_remAddReq = nullptr;
goto retrylater;
}
if (req->IsError()) {
FRT_Values &args = *req->GetParams();
const char *rpcsrvname = args[1]._string._str;
const char *rpcsrvspec = args[2]._string._str;
LOG(warning, "error adding [%s -> %s] to remote slobrok: %s",
rpcsrvname, rpcsrvspec, req->GetErrorMessage());
_rpcsrvmanager.removeLocal(rpcsrvname, rpcsrvspec);
}
req->SubRef();
_remAddReq = nullptr;
doPending();
} else if (req == _remRemReq) {
// handle response after pushing some remove we had pending:
if (req->IsError() && (req->GetErrorCode() == FRTE_RPC_CONNECTION ||
req->GetErrorCode() == FRTE_RPC_TIMEOUT))
{
LOG(error, "connection error adding to remote slobrok: %s", req->GetErrorMessage());
req->SubRef();
_remRemReq = nullptr;
goto retrylater;
}
if (req->IsError()) {
LOG(warning, "error removing on remote slobrok: %s", req->GetErrorMessage());
}
req->SubRef();
_remRemReq = nullptr;
doPending();
} else {
LOG(error, "got unknown request back in RequestDone()");
LOG_ASSERT(req == nullptr);
}
return;
retrylater:
fail();
return;
}
void
RemoteSlobrok::notifyFailedRpcSrv(ManagedRpcServer *rpcsrv, std::string errmsg)
{
if (++_failCnt > 10) {
LOG(warning, "remote location broker at %s failed: %s",
rpcsrv->getSpec().c_str(), errmsg.c_str());
} else {
LOG(debug, "remote location broker at %s failed: %s",
rpcsrv->getSpec().c_str(), errmsg.c_str());
}
LOG_ASSERT(rpcsrv == &_rpcserver);
fail();
}
void
RemoteSlobrok::fail()
{
// disconnect
if (_remote != nullptr) {
_remote->SubRef();
_remote = nullptr;
}
// schedule reconnect attempt
_reconnecter.scheduleTryConnect();
}
void
RemoteSlobrok::maybePushMine()
{
if (_remote != nullptr &&
_remAddPeerReq == nullptr &&
_remListReq == nullptr &&
_remAddReq == nullptr &&
_remRemReq == nullptr)
{
LOG(debug, "spamming remote at %s with my names", getName().c_str());
pushMine();
} else {
LOG(debug, "not pushing mine, as we have: remote %p r.a.p.r=%p r.l.r=%p r.a.r=%p r.r.r=%p",
_remote, _remAddPeerReq, _remListReq, _remAddReq, _remRemReq);
}
}
void
RemoteSlobrok::notifyOkRpcSrv(ManagedRpcServer *rpcsrv)
{
LOG_ASSERT(rpcsrv == &_rpcserver);
(void) rpcsrv;
// connection was OK, so disable any pending reconnect
_reconnecter.disable();
if (_remote != nullptr) {
maybeStartFetch();
// the rest here should only be done on first notifyOk
return;
}
_remote = getSupervisor()->GetTarget(getSpec().c_str());
maybeStartFetch();
// at this point, we will do (in sequence):
// ask peer to connect to us too;
// ask peer for its list of managed rpcservers, adding to our database
// add our managed rpcserver on peer
// any failure will cause disconnect and retry.
_remAddPeerReq = getSupervisor()->AllocRPCRequest();
_remAddPeerReq->SetMethodName("slobrok.admin.addPeer");
_remAddPeerReq->GetParams()->AddString(_exchanger._env.mySpec().c_str());
_remAddPeerReq->GetParams()->AddString(_exchanger._env.mySpec().c_str());
_remote->InvokeAsync(_remAddPeerReq, 3.0, this);
// when _remAddPeerReq is returned, our managed list is added via doAdd()
}
void
RemoteSlobrok::tryConnect()
{
_rpcserver.healthCheck();
}
FRT_Supervisor *
RemoteSlobrok::getSupervisor()
{
return _exchanger._env.getSupervisor();
}
//-----------------------------------------------------------------------------
RemoteSlobrok::Reconnecter::Reconnecter(FNET_Scheduler *sched,
RemoteSlobrok &owner)
: FNET_Task(sched),
_waittime(13),
_owner(owner)
{
}
RemoteSlobrok::Reconnecter::~Reconnecter()
{
Kill();
}
void
RemoteSlobrok::Reconnecter::scheduleTryConnect()
{
if (_waittime < 60)
++_waittime;
Schedule(_waittime + (random() & 255)/100.0);
}
void
RemoteSlobrok::Reconnecter::disable()
{
// called when connection OK
Unschedule();
_waittime = 13;
}
void
RemoteSlobrok::Reconnecter::PerformTask()
{
_owner.tryConnect();
}
void
RemoteSlobrok::invokeAsync(FRT_RPCRequest *req,
double timeout,
FRT_IRequestWait *rwaiter)
{
LOG_ASSERT(isConnected());
_remote->InvokeAsync(req, timeout, rwaiter);
}
//-----------------------------------------------------------------------------
} // namespace slobrok
<commit_msg>less log spam<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "remote_slobrok.h"
#include "rpc_server_map.h"
#include "rpc_server_manager.h"
#include "exchange_manager.h"
#include "sbenv.h"
#include <vespa/fnet/frt/supervisor.h>
#include <vespa/fnet/frt/target.h>
#include <vespa/log/log.h>
LOG_SETUP(".slobrok.server.remote_slobrok");
namespace slobrok {
//-----------------------------------------------------------------------------
RemoteSlobrok::RemoteSlobrok(const std::string &name, const std::string &spec,
ExchangeManager &manager)
: _exchanger(manager),
_rpcsrvmanager(manager._rpcsrvmanager),
_remote(nullptr),
_serviceMapMirror(),
_rpcserver(name, spec, *this),
_reconnecter(getSupervisor()->GetScheduler(), *this),
_failCnt(0),
_consensusSubscription(MapSubscription::subscribe(_serviceMapMirror, _exchanger._env.consensusMap())),
_remAddPeerReq(nullptr),
_remListReq(nullptr),
_remAddReq(nullptr),
_remRemReq(nullptr),
_remFetchReq(nullptr),
_pending()
{
_rpcserver.healthCheck();
}
void RemoteSlobrok::shutdown() {
_reconnecter.disable();
_pending.clear();
if (_remote != nullptr) {
_remote->SubRef();
_remote = nullptr;
}
if (_remFetchReq != nullptr) {
_remFetchReq->Abort();
}
if (_remAddPeerReq != nullptr) {
_remAddPeerReq->Abort();
}
if (_remListReq != nullptr) {
_remListReq->Abort();
}
if (_remAddReq != nullptr) {
_remAddReq->Abort();
}
if (_remRemReq != nullptr) {
_remRemReq->Abort();
}
_serviceMapMirror.clear();
}
RemoteSlobrok::~RemoteSlobrok() {
shutdown();
// _rpcserver destructor called automatically
}
void
RemoteSlobrok::doPending()
{
if (_remAddReq != nullptr) return;
if (_remRemReq != nullptr) return;
if (_remote == nullptr) return;
if ( ! _pending.empty() ) {
std::unique_ptr<NamedService> todo = std::move(_pending.front());
_pending.pop_front();
const NamedService *rpcsrv = _exchanger._rpcsrvmap.lookup(todo->getName());
if (rpcsrv == nullptr) {
_remRemReq = getSupervisor()->AllocRPCRequest();
_remRemReq->SetMethodName("slobrok.internal.doRemove");
_remRemReq->GetParams()->AddString(_exchanger._env.mySpec().c_str());
_remRemReq->GetParams()->AddString(todo->getName().c_str());
_remRemReq->GetParams()->AddString(todo->getSpec().c_str());
_remote->InvokeAsync(_remRemReq, 2.0, this);
} else {
_remAddReq = getSupervisor()->AllocRPCRequest();
_remAddReq->SetMethodName("slobrok.internal.doAdd");
_remAddReq->GetParams()->AddString(_exchanger._env.mySpec().c_str());
_remAddReq->GetParams()->AddString(todo->getName().c_str());
_remAddReq->GetParams()->AddString(rpcsrv->getSpec().c_str());
_remote->InvokeAsync(_remAddReq, 2.0, this);
}
// XXX should save this and pick up on RequestDone()
}
}
void RemoteSlobrok::maybeStartFetch() {
if (_remFetchReq != nullptr) return;
if (_remote == nullptr) return;
_remFetchReq = getSupervisor()->AllocRPCRequest();
_remFetchReq->SetMethodName("slobrok.internal.fetchLocalView");
_remFetchReq->GetParams()->AddInt32(_serviceMapMirror.currentGeneration().getAsInt());
_remFetchReq->GetParams()->AddInt32(5000);
_remote->InvokeAsync(_remFetchReq, 15.0, this);
}
void RemoteSlobrok::handleFetchResult() {
LOG_ASSERT(_remFetchReq != nullptr);
bool success = true;
if (_remFetchReq->CheckReturnTypes("iSSSi")) {
FRT_Values &answer = *(_remFetchReq->GetReturn());
uint32_t diff_from = answer[0]._intval32;
uint32_t numRemove = answer[1]._string_array._len;
FRT_StringValue *r = answer[1]._string_array._pt;
uint32_t numNames = answer[2]._string_array._len;
FRT_StringValue *n = answer[2]._string_array._pt;
uint32_t numSpecs = answer[3]._string_array._len;
FRT_StringValue *s = answer[3]._string_array._pt;
uint32_t diff_to = answer[4]._intval32;
std::vector<vespalib::string> removed;
for (uint32_t idx = 0; idx < numRemove; ++idx) {
removed.emplace_back(r[idx]._str);
}
ServiceMappingList updated;
if (numNames == numSpecs) {
for (uint32_t idx = 0; idx < numNames; ++idx) {
updated.emplace_back(n[idx]._str, s[idx]._str);
}
} else {
diff_from = 0;
diff_to = 0;
success = false;
}
MapDiff diff(diff_from, std::move(removed), std::move(updated), diff_to);
if (diff_from == 0) {
_serviceMapMirror.clear();
_serviceMapMirror.apply(std::move(diff));
} else if (diff_from == _serviceMapMirror.currentGeneration().getAsInt()) {
_serviceMapMirror.apply(std::move(diff));
} else {
_serviceMapMirror.clear();
success = false;
}
} else {
if (_remFetchReq->GetErrorCode() == FRTE_RPC_NO_SUCH_METHOD) {
LOG(debug, "partner slobrok too old - not mirroring");
} else {
LOG(debug, "fetchLocalView() failed with partner %s: %s",
getName().c_str(), _remFetchReq->GetErrorMessage());
fail();
}
_serviceMapMirror.clear();
success = false;
}
_remFetchReq->SubRef();
_remFetchReq = nullptr;
if (success) {
maybeStartFetch();
}
}
void
RemoteSlobrok::pushMine()
{
// all mine
std::vector<const NamedService *> mine = _exchanger._rpcsrvmap.allManaged();
while (mine.size() > 0) {
const NamedService *now = mine.back();
mine.pop_back();
_pending.push_back(std::make_unique<NamedService>(now->getName(), now->getSpec()));
}
doPending();
}
void
RemoteSlobrok::RequestDone(FRT_RPCRequest *req)
{
if (req == _remFetchReq) {
handleFetchResult();
return;
}
FRT_Values &answer = *(req->GetReturn());
if (req == _remAddPeerReq) {
// handle response after asking remote slobrok to add me as a peer:
if (req->IsError()) {
FRT_Values &args = *req->GetParams();
const char *myname = args[0]._string._str;
const char *myspec = args[1]._string._str;
LOG(info, "addPeer(%s, %s) on remote slobrok %s at %s: %s",
myname, myspec, getName().c_str(), getSpec().c_str(), req->GetErrorMessage());
req->SubRef();
_remAddPeerReq = nullptr;
goto retrylater;
}
req->SubRef();
_remAddPeerReq = nullptr;
// next step is to ask the remote to send its list of managed names:
LOG_ASSERT(_remListReq == nullptr);
_remListReq = getSupervisor()->AllocRPCRequest();
_remListReq->SetMethodName("slobrok.internal.listManagedRpcServers");
if (_remote != nullptr) {
_remote->InvokeAsync(_remListReq, 3.0, this);
}
// when _remListReq is returned, our managed list is added
} else if (req == _remListReq) {
// handle the list sent from the remote:
if (req->IsError()
|| strcmp(answer.GetTypeString(), "SS") != 0)
{
LOG(error, "error listing remote slobrok %s at %s: %s",
getName().c_str(), getSpec().c_str(), req->GetErrorMessage());
req->SubRef();
_remListReq = nullptr;
goto retrylater;
}
uint32_t numNames = answer.GetValue(0)._string_array._len;
uint32_t numSpecs = answer.GetValue(1)._string_array._len;
if (numNames != numSpecs) {
LOG(error, "inconsistent array lengths from %s at %s", getName().c_str(), getSpec().c_str());
req->SubRef();
_remListReq = nullptr;
goto retrylater;
}
FRT_StringValue *names = answer.GetValue(0)._string_array._pt;
FRT_StringValue *specs = answer.GetValue(1)._string_array._pt;
for (uint32_t idx = 0; idx < numNames; idx++) {
_rpcsrvmanager.addRemote(names[idx]._str, specs[idx]._str);
}
req->SubRef();
_remListReq = nullptr;
// next step is to push the ones I own:
maybeStartFetch();
maybePushMine();
} else if (req == _remAddReq) {
// handle response after pushing some name that we managed:
if (req->IsError() && (req->GetErrorCode() == FRTE_RPC_CONNECTION ||
req->GetErrorCode() == FRTE_RPC_TIMEOUT))
{
LOG(error, "connection error adding to remote slobrok: %s", req->GetErrorMessage());
req->SubRef();
_remAddReq = nullptr;
goto retrylater;
}
if (req->IsError()) {
FRT_Values &args = *req->GetParams();
const char *rpcsrvname = args[1]._string._str;
const char *rpcsrvspec = args[2]._string._str;
LOG(warning, "error adding [%s -> %s] to remote slobrok: %s",
rpcsrvname, rpcsrvspec, req->GetErrorMessage());
_rpcsrvmanager.removeLocal(rpcsrvname, rpcsrvspec);
}
req->SubRef();
_remAddReq = nullptr;
doPending();
} else if (req == _remRemReq) {
// handle response after pushing some remove we had pending:
if (req->IsError() && (req->GetErrorCode() == FRTE_RPC_CONNECTION ||
req->GetErrorCode() == FRTE_RPC_TIMEOUT))
{
LOG(error, "connection error adding to remote slobrok: %s", req->GetErrorMessage());
req->SubRef();
_remRemReq = nullptr;
goto retrylater;
}
if (req->IsError()) {
LOG(warning, "error removing on remote slobrok: %s", req->GetErrorMessage());
}
req->SubRef();
_remRemReq = nullptr;
doPending();
} else {
LOG(error, "got unknown request back in RequestDone()");
LOG_ASSERT(req == nullptr);
}
return;
retrylater:
fail();
return;
}
void
RemoteSlobrok::notifyFailedRpcSrv(ManagedRpcServer *rpcsrv, std::string errmsg)
{
if (++_failCnt > 10) {
LOG(warning, "remote location broker at %s failed: %s",
rpcsrv->getSpec().c_str(), errmsg.c_str());
} else {
LOG(debug, "remote location broker at %s failed: %s",
rpcsrv->getSpec().c_str(), errmsg.c_str());
}
LOG_ASSERT(rpcsrv == &_rpcserver);
fail();
}
void
RemoteSlobrok::fail()
{
// disconnect
if (_remote != nullptr) {
_remote->SubRef();
_remote = nullptr;
}
// schedule reconnect attempt
_reconnecter.scheduleTryConnect();
}
void
RemoteSlobrok::maybePushMine()
{
if (_remote != nullptr &&
_remAddPeerReq == nullptr &&
_remListReq == nullptr &&
_remAddReq == nullptr &&
_remRemReq == nullptr)
{
LOG(debug, "spamming remote at %s with my names", getName().c_str());
pushMine();
} else {
LOG(debug, "not pushing mine, as we have: remote %p r.a.p.r=%p r.l.r=%p r.a.r=%p r.r.r=%p",
_remote, _remAddPeerReq, _remListReq, _remAddReq, _remRemReq);
}
}
void
RemoteSlobrok::notifyOkRpcSrv(ManagedRpcServer *rpcsrv)
{
LOG_ASSERT(rpcsrv == &_rpcserver);
(void) rpcsrv;
// connection was OK, so disable any pending reconnect
_reconnecter.disable();
if (_remote != nullptr) {
maybeStartFetch();
// the rest here should only be done on first notifyOk
return;
}
_remote = getSupervisor()->GetTarget(getSpec().c_str());
maybeStartFetch();
// at this point, we will do (in sequence):
// ask peer to connect to us too;
// ask peer for its list of managed rpcservers, adding to our database
// add our managed rpcserver on peer
// any failure will cause disconnect and retry.
_remAddPeerReq = getSupervisor()->AllocRPCRequest();
_remAddPeerReq->SetMethodName("slobrok.admin.addPeer");
_remAddPeerReq->GetParams()->AddString(_exchanger._env.mySpec().c_str());
_remAddPeerReq->GetParams()->AddString(_exchanger._env.mySpec().c_str());
_remote->InvokeAsync(_remAddPeerReq, 3.0, this);
// when _remAddPeerReq is returned, our managed list is added via doAdd()
}
void
RemoteSlobrok::tryConnect()
{
_rpcserver.healthCheck();
}
FRT_Supervisor *
RemoteSlobrok::getSupervisor()
{
return _exchanger._env.getSupervisor();
}
//-----------------------------------------------------------------------------
RemoteSlobrok::Reconnecter::Reconnecter(FNET_Scheduler *sched,
RemoteSlobrok &owner)
: FNET_Task(sched),
_waittime(13),
_owner(owner)
{
}
RemoteSlobrok::Reconnecter::~Reconnecter()
{
Kill();
}
void
RemoteSlobrok::Reconnecter::scheduleTryConnect()
{
if (_waittime < 60)
++_waittime;
Schedule(_waittime + (random() & 255)/100.0);
}
void
RemoteSlobrok::Reconnecter::disable()
{
// called when connection OK
Unschedule();
_waittime = 13;
}
void
RemoteSlobrok::Reconnecter::PerformTask()
{
_owner.tryConnect();
}
void
RemoteSlobrok::invokeAsync(FRT_RPCRequest *req,
double timeout,
FRT_IRequestWait *rwaiter)
{
LOG_ASSERT(isConnected());
_remote->InvokeAsync(req, timeout, rwaiter);
}
//-----------------------------------------------------------------------------
} // namespace slobrok
<|endoftext|> |
<commit_before>// $Id: atomBondModelBaseProcessor.C,v 1.2 2000/12/12 16:19:24 oliver Exp $
#include <BALL/MOLVIEW/FUNCTOR/atomBondModelBaseProcessor.h>
using namespace std;
namespace BALL
{
namespace MOLVIEW
{
AtomBondModelBaseProcessor::AtomBondModelBaseProcessor()
: BaseModelProcessor(),
used_atoms_(),
hashed_atoms_()
{
}
AtomBondModelBaseProcessor::AtomBondModelBaseProcessor
(const AtomBondModelBaseProcessor& processor, bool deep)
: BaseModelProcessor(processor, deep),
used_atoms_(),
hashed_atoms_()
{
}
AtomBondModelBaseProcessor::~AtomBondModelBaseProcessor()
throw()
{
#ifdef BALL_VIEW_DEBUG
cout << "Destructing object " << (void *)this
<< " of class " << RTTI::getName<AtomBondModelBaseProcessor>() << endl;
#endif
destroy();
}
void AtomBondModelBaseProcessor::clear()
throw()
{
BaseModelProcessor::clear();
clearUsedAtoms_();
}
void AtomBondModelBaseProcessor::destroy()
throw()
{
BaseModelProcessor::destroy();
clearUsedAtoms_();
}
void AtomBondModelBaseProcessor::set
(const AtomBondModelBaseProcessor& processor, bool deep)
{
clearUsedAtoms_();
BaseModelProcessor::set(processor, deep);
}
AtomBondModelBaseProcessor& AtomBondModelBaseProcessor::operator =
(const AtomBondModelBaseProcessor& processor)
{
set(processor);
return *this;
}
void AtomBondModelBaseProcessor::get
(AtomBondModelBaseProcessor& processor, bool deep) const
{
processor.set(*this, deep);
}
void AtomBondModelBaseProcessor::swap
(AtomBondModelBaseProcessor& processor)
{
BaseModelProcessor::swap(processor);
}
bool AtomBondModelBaseProcessor::start()
{
clearUsedAtoms_();
return BaseModelProcessor::start();
}
bool AtomBondModelBaseProcessor::finish()
{
return BaseModelProcessor::finish();
}
Processor::Result AtomBondModelBaseProcessor::operator()(Composite & /* composite */)
{
return Processor::CONTINUE;
}
bool AtomBondModelBaseProcessor::isValid() const
{
return BaseModelProcessor::isValid();
}
void AtomBondModelBaseProcessor::dump
(ostream& s, Size depth) const
throw()
{
BALL_DUMP_STREAM_PREFIX(s);
BALL_DUMP_DEPTH(s, depth);
BALL_DUMP_HEADER(s, this, this);
BaseModelProcessor::dump(s, depth + 1);
BALL_DUMP_DEPTH(s, depth);
s << "used atoms: " << used_atoms_.size() << endl;
BALL_DUMP_STREAM_SUFFIX(s);
}
void AtomBondModelBaseProcessor::read(istream & /* s */)
{
throw ::BALL::Exception::NotImplemented(__FILE__, __LINE__);
}
void AtomBondModelBaseProcessor::write(ostream & /* s */) const
{
throw ::BALL::Exception::NotImplemented(__FILE__, __LINE__);
}
void AtomBondModelBaseProcessor::buildBondModels_()
{
// generate bond primitive
Atom *first__pAtom = 0;
Atom *second__pAtom = 0;
Bond *__pBond = 0;
AtomBondIterator bond__Iterator;
List<Atom*>::Iterator list_iterator;
// for all used atoms
for (list_iterator = getAtomList_().begin();
list_iterator != getAtomList_().end(); ++list_iterator)
{
first__pAtom = *list_iterator;
// for all bonds connected from first- to second atom
BALL_FOREACH_ATOM_BOND(*first__pAtom, bond__Iterator)
{
__pBond = &(*bond__Iterator);
if (first__pAtom != __pBond->getSecondAtom())
{
second__pAtom = __pBond->getSecondAtom();
}
else
{
second__pAtom = __pBond->getFirstAtom();
}
// use only atoms with greater handles than first atom
// or
// second atom not a used atom, but smaller as the first atom
// process bond between them
if (*first__pAtom < *second__pAtom
|| !getAtomSet_().has(second__pAtom))
{
// remove all models append to bond
removeGeometricObjects_(*__pBond, true);
// build connection primitive
__pBond->host(*getModelConnector());
}
}
}
}
# ifdef BALL_NO_INLINE_FUNCTIONS
# include <BALL/MOLVIEW/FUNCTOR/atomBondModelBaseProcessor.iC>
# endif
} // namespace MOLVIEW
} // namespace BALL
<commit_msg>fixed: variable names<commit_after>// $Id: atomBondModelBaseProcessor.C,v 1.3 2001/01/25 23:47:55 amoll Exp $
#include <BALL/MOLVIEW/FUNCTOR/atomBondModelBaseProcessor.h>
using namespace std;
namespace BALL
{
namespace MOLVIEW
{
AtomBondModelBaseProcessor::AtomBondModelBaseProcessor()
: BaseModelProcessor(),
used_atoms_(),
hashed_atoms_()
{
}
AtomBondModelBaseProcessor::AtomBondModelBaseProcessor
(const AtomBondModelBaseProcessor& processor, bool deep)
: BaseModelProcessor(processor, deep),
used_atoms_(),
hashed_atoms_()
{
}
AtomBondModelBaseProcessor::~AtomBondModelBaseProcessor()
throw()
{
#ifdef BALL_VIEW_DEBUG
cout << "Destructing object " << (void *)this
<< " of class " << RTTI::getName<AtomBondModelBaseProcessor>() << endl;
#endif
destroy();
}
void AtomBondModelBaseProcessor::clear()
throw()
{
BaseModelProcessor::clear();
clearUsedAtoms_();
}
void AtomBondModelBaseProcessor::destroy()
throw()
{
BaseModelProcessor::destroy();
clearUsedAtoms_();
}
void AtomBondModelBaseProcessor::set
(const AtomBondModelBaseProcessor& processor, bool deep)
{
clearUsedAtoms_();
BaseModelProcessor::set(processor, deep);
}
AtomBondModelBaseProcessor& AtomBondModelBaseProcessor::operator =
(const AtomBondModelBaseProcessor& processor)
{
set(processor);
return *this;
}
void AtomBondModelBaseProcessor::get
(AtomBondModelBaseProcessor& processor, bool deep) const
{
processor.set(*this, deep);
}
void AtomBondModelBaseProcessor::swap
(AtomBondModelBaseProcessor& processor)
{
BaseModelProcessor::swap(processor);
}
bool AtomBondModelBaseProcessor::start()
{
clearUsedAtoms_();
return BaseModelProcessor::start();
}
bool AtomBondModelBaseProcessor::finish()
{
return BaseModelProcessor::finish();
}
Processor::Result AtomBondModelBaseProcessor::operator()(Composite & /* composite */)
{
return Processor::CONTINUE;
}
bool AtomBondModelBaseProcessor::isValid() const
{
return BaseModelProcessor::isValid();
}
void AtomBondModelBaseProcessor::dump
(ostream& s, Size depth) const
throw()
{
BALL_DUMP_STREAM_PREFIX(s);
BALL_DUMP_DEPTH(s, depth);
BALL_DUMP_HEADER(s, this, this);
BaseModelProcessor::dump(s, depth + 1);
BALL_DUMP_DEPTH(s, depth);
s << "used atoms: " << used_atoms_.size() << endl;
BALL_DUMP_STREAM_SUFFIX(s);
}
void AtomBondModelBaseProcessor::read(istream & /* s */)
{
throw ::BALL::Exception::NotImplemented(__FILE__, __LINE__);
}
void AtomBondModelBaseProcessor::write(ostream & /* s */) const
{
throw ::BALL::Exception::NotImplemented(__FILE__, __LINE__);
}
void AtomBondModelBaseProcessor::buildBondModels_()
{
// generate bond primitive
Atom* first_pAtom = 0;
Atom* second_pAtom = 0;
Bond* pbond = 0;
AtomBondIterator bond_Iterator;
List<Atom*>::Iterator list_iterator;
// for all used atoms
for (list_iterator = getAtomList_().begin();
list_iterator != getAtomList_().end(); ++list_iterator)
{
first_pAtom = *list_iterator;
// for all bonds connected from first- to second atom
BALL_FOREACH_ATOM_BOND(*first_pAtom, bond_Iterator)
{
pbond = &(*bond_Iterator);
if (first_pAtom != pbond->getSecondAtom())
{
second_pAtom = pbond->getSecondAtom();
}
else
{
second_pAtom = pbond->getFirstAtom();
}
// use only atoms with greater handles than first atom
// or
// second atom not a used atom, but smaller as the first atom
// process bond between them
if (*first_pAtom < *second_pAtom
|| !getAtomSet_().has(second_pAtom))
{
// remove all models append to bond
removeGeometricObjects_(*pbond, true);
// build connection primitive
pbond->host(*getModelConnector());
}
}
}
}
# ifdef BALL_NO_INLINE_FUNCTIONS
# include <BALL/MOLVIEW/FUNCTOR/atomBondModelBaseProcessor.iC>
# endif
} // namespace MOLVIEW
} // namespace BALL
<|endoftext|> |
<commit_before>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (C) 2008 Sacha Schutz <[email protected]>
* Copyright (C) 2008 Olivier Gueudelot <[email protected]>
* Copyright (C) 2008 Charles Huet <[email protected]>
* Copyright (c) 2010 Arjen Hiemstra <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "item.h"
#include <QtGui/QMatrix4x4>
#include <core/debughelper.h>
#include "mesh.h"
#include "camera.h"
#include "frustrum.h"
#include "engine.h"
#include "math.h"
#include "materialinstance.h"
#include "material.h"
using namespace GluonGraphics;
class Item::ItemPrivate
{
public:
ItemPrivate() { materialInstance = 0; }
Mesh * mesh;
QMatrix4x4 transform;
MaterialInstance* materialInstance;
};
Item::Item(QObject * parent)
: QObject(parent),
d(new ItemPrivate)
{
d->materialInstance = Engine::instance()->material("default")->instance("default");
}
Item::~Item()
{
delete d;
}
Mesh*
Item::mesh()
{
return d->mesh;
}
QMatrix4x4
Item::transform()
{
return d->transform;
}
MaterialInstance*
Item::materialInstance()
{
return d->materialInstance;
}
void
Item::render()
{
Camera* activeCam = Engine::instance()->activeCamera();
#ifdef __GNUC__
#warning ToDo: Implement view frustum culling. After all, that is what that damn class is for... ;)
#endif
QMatrix4x4 modelViewProj = Math::calculateModelViewProj(d->transform, activeCam->viewMatrix(), activeCam->frustrum()->projectionMatrix());
d->materialInstance->bind();
d->materialInstance->setModelViewProjectionMatrix(modelViewProj);
d->mesh->render(d->materialInstance);
d->materialInstance->release();
}
void
Item::setTransform( const QMatrix4x4 transform )
{
d->transform = transform;
}
void
Item::setMesh( Mesh* mesh )
{
d->mesh = mesh;
}
void
Item::setMaterialInstance(MaterialInstance * instance)
{
d->materialInstance = instance;
}
#include "item.moc"
<commit_msg>Fix a crash when no active camera set.<commit_after>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (C) 2008 Sacha Schutz <[email protected]>
* Copyright (C) 2008 Olivier Gueudelot <[email protected]>
* Copyright (C) 2008 Charles Huet <[email protected]>
* Copyright (c) 2010 Arjen Hiemstra <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "item.h"
#include <QtGui/QMatrix4x4>
#include <core/debughelper.h>
#include "mesh.h"
#include "camera.h"
#include "frustrum.h"
#include "engine.h"
#include "math.h"
#include "materialinstance.h"
#include "material.h"
using namespace GluonGraphics;
class Item::ItemPrivate
{
public:
ItemPrivate() { materialInstance = 0; }
Mesh * mesh;
QMatrix4x4 transform;
MaterialInstance* materialInstance;
};
Item::Item(QObject * parent)
: QObject(parent),
d(new ItemPrivate)
{
d->materialInstance = Engine::instance()->material("default")->instance("default");
}
Item::~Item()
{
delete d;
}
Mesh*
Item::mesh()
{
return d->mesh;
}
QMatrix4x4
Item::transform()
{
return d->transform;
}
MaterialInstance*
Item::materialInstance()
{
return d->materialInstance;
}
void
Item::render()
{
Camera* activeCam = Engine::instance()->activeCamera();
if(!activeCam)
return;
#ifdef __GNUC__
#warning ToDo: Implement view frustum culling. After all, that is what that damn class is for... ;)
#endif
QMatrix4x4 modelViewProj = Math::calculateModelViewProj(d->transform, activeCam->viewMatrix(), activeCam->frustrum()->projectionMatrix());
d->materialInstance->bind();
d->materialInstance->setModelViewProjectionMatrix(modelViewProj);
d->mesh->render(d->materialInstance);
d->materialInstance->release();
}
void
Item::setTransform( const QMatrix4x4 transform )
{
d->transform = transform;
}
void
Item::setMesh( Mesh* mesh )
{
d->mesh = mesh;
}
void
Item::setMaterialInstance(MaterialInstance * instance)
{
d->materialInstance = instance;
}
#include "item.moc"
<|endoftext|> |
<commit_before>#include "test.h"
static_MTX(mtx3, mtxPrioProtect, 3);
static_CND(cnd3);
static void proc3()
{
unsigned event;
event = mtx_wait(mtx3); assert_success(event);
event = cnd_wait(cnd3, mtx3); assert_success(event);
event = mtx_wait(mtx2); assert_success(event);
cnd_give(cnd2, cndOne);
event = mtx_give(mtx2); assert_success(event);
event = mtx_give(mtx3); assert_success(event);
tsk_stop();
}
static void proc2()
{
unsigned event;
event = mtx_wait(mtx2); assert_success(event);
assert_dead(tsk3);
tsk_startFrom(tsk3, proc3);
event = mtx_wait(mtx3); assert_success(event);
cnd_give(cnd3, cndOne);
event = mtx_give(mtx3); assert_success(event);
event = cnd_wait(cnd2, mtx2); assert_success(event);
event = cnd_wait(cnd2, mtx2); assert_success(event);
event = mtx_wait(mtx1); assert_success(event);
cnd_give(cnd1, cndOne);
event = mtx_give(mtx1); assert_success(event);
event = mtx_give(mtx2); assert_success(event);
event = tsk_join(tsk3); assert_success(event);
tsk_stop();
}
static void proc1()
{
unsigned event;
event = mtx_wait(mtx1); assert_success(event);
assert_dead(tsk2);
tsk_startFrom(tsk2, proc2);
event = mtx_wait(mtx2); assert_success(event);
cnd_give(cnd2, cndOne);
event = mtx_give(mtx2); assert_success(event);
event = cnd_wait(cnd1, mtx1); assert_success(event);
event = cnd_wait(cnd1, mtx1); assert_success(event);
event = mtx_wait(&mtx0); assert_success(event);
cnd_give(&cnd0, cndOne);
event = mtx_give(&mtx0); assert_success(event);
event = mtx_give(mtx1); assert_success(event);
event = tsk_join(tsk2); assert_success(event);
tsk_stop();
}
static void proc0()
{
unsigned event;
event = mtx_wait(&mtx0); assert_success(event);
assert_dead(tsk1);
tsk_startFrom(tsk1, proc1);
event = mtx_wait(mtx1); assert_success(event);
cnd_give(cnd1, cndOne);
event = mtx_give(mtx1); assert_success(event);
event = cnd_wait(&cnd0, &mtx0); assert_success(event);
event = mtx_give(&mtx0); assert_success(event);
event = tsk_join(tsk1); assert_success(event);
tsk_stop();
}
static void test()
{
unsigned event;
assert_dead(&tsk0);
tsk_startFrom(&tsk0, proc0);
event = tsk_join(&tsk0); assert_success(event);
}
extern "C"
void test_condition_variable_2()
{
TEST_Notify();
mtx_init(&mtx0, mtxDefault, 0);
mtx_init(mtx1, mtxErrorCheck, 0);
mtx_init(mtx2, mtxPrioInherit, 0);
TEST_Call();
}
<commit_msg>Update test_condition_variable_2.cpp<commit_after>#include "test.h"
static_MTX(mtx3, mtxPrioProtect, 3);
static_CND(cnd3);
static void proc3()
{
unsigned event;
event = mtx_wait(mtx3); assert_success(event);
event = cnd_wait(cnd3, mtx3); assert_success(event);
event = mtx_wait(mtx2); assert_success(event);
cnd_give(cnd2, cndOne);
event = mtx_give(mtx2); assert_success(event);
event = mtx_give(mtx3); assert_success(event);
tsk_stop();
}
static void proc2()
{
unsigned event;
event = mtx_wait(mtx2); assert_success(event);
assert_dead(tsk3);
tsk_startFrom(tsk3, proc3); assert_ready(tsk3);
event = mtx_wait(mtx3); assert_success(event);
cnd_give(cnd3, cndOne);
event = mtx_give(mtx3); assert_success(event);
event = cnd_wait(cnd2, mtx2); assert_success(event);
event = cnd_wait(cnd2, mtx2); assert_success(event);
event = mtx_wait(mtx1); assert_success(event);
cnd_give(cnd1, cndOne);
event = mtx_give(mtx1); assert_success(event);
event = mtx_give(mtx2); assert_success(event);
event = tsk_join(tsk3); assert_success(event);
tsk_stop();
}
static void proc1()
{
unsigned event;
event = mtx_wait(mtx1); assert_success(event);
assert_dead(tsk2);
tsk_startFrom(tsk2, proc2); assert_ready(tsk2);
event = mtx_wait(mtx2); assert_success(event);
cnd_give(cnd2, cndOne);
event = mtx_give(mtx2); assert_success(event);
event = cnd_wait(cnd1, mtx1); assert_success(event);
event = cnd_wait(cnd1, mtx1); assert_success(event);
event = mtx_wait(&mtx0); assert_success(event);
cnd_give(&cnd0, cndOne);
event = mtx_give(&mtx0); assert_success(event);
event = mtx_give(mtx1); assert_success(event);
event = tsk_join(tsk2); assert_success(event);
tsk_stop();
}
static void proc0()
{
unsigned event;
event = mtx_wait(&mtx0); assert_success(event);
assert_dead(tsk1);
tsk_startFrom(tsk1, proc1); assert_ready(tsk1);
event = mtx_wait(mtx1); assert_success(event);
cnd_give(cnd1, cndOne);
event = mtx_give(mtx1); assert_success(event);
event = cnd_wait(&cnd0, &mtx0); assert_success(event);
event = mtx_give(&mtx0); assert_success(event);
event = tsk_join(tsk1); assert_success(event);
tsk_stop();
}
static void test()
{
unsigned event;
assert_dead(&tsk0);
tsk_startFrom(&tsk0, proc0); assert_ready(&tsk0);
event = tsk_join(&tsk0); assert_success(event);
}
extern "C"
void test_condition_variable_2()
{
TEST_Notify();
mtx_init(&mtx0, mtxDefault, 0);
mtx_init(mtx1, mtxErrorCheck, 0);
mtx_init(mtx2, mtxPrioInherit, 0);
TEST_Call();
}
<|endoftext|> |
<commit_before>#include <stan/math/mix/scal.hpp>
#include <gtest/gtest.h>
#include <boost/math/special_functions/digamma.hpp>
#include <test/unit/math/rev/mat/fun/util.hpp>
#include <test/unit/math/mix/scal/fun/nan_util.hpp>
TEST(AgradFwdLogFallingFactorial,FvarVar_FvarVar_1stDeriv) {
using stan::math::fvar;
using stan::math::var;
using stan::math::log_falling_factorial;
fvar<var> a(4.0,1.0);
fvar<var> b(3.0,1.0);
fvar<var> c = log_falling_factorial(a,b);
EXPECT_FLOAT_EQ(log(4), c.val_.val());
EXPECT_FLOAT_EQ(0.25, c.d_.val());
AVEC y = createAVEC(a.val_,b.val_);
VEC g;
c.val_.grad(y,g);
EXPECT_FLOAT_EQ(1.5061177, g[0]);
EXPECT_FLOAT_EQ(-1.2561177, g[1]);
}
TEST(AgradFwdLogFallingFactorial,FvarVar_Double_1stDeriv) {
using stan::math::fvar;
using stan::math::var;
using stan::math::log_falling_factorial;
fvar<var> a(4.0,1.0);
double b(3.0);
fvar<var> c = log_falling_factorial(a,b);
EXPECT_FLOAT_EQ(log(4), c.val_.val());
EXPECT_FLOAT_EQ(1.5061177, c.d_.val());
AVEC y = createAVEC(a.val_);
VEC g;
c.val_.grad(y,g);
EXPECT_FLOAT_EQ(1.5061177, g[0]);
}
TEST(AgradFwdLogFallingFactorial,Double_FvarVar_1stDeriv) {
using stan::math::fvar;
using stan::math::var;
using stan::math::log_falling_factorial;
double a(4.0);
fvar<var> b(3.0,1.0);
fvar<var> c = log_falling_factorial(a,b);
EXPECT_FLOAT_EQ(log(4), c.val_.val());
EXPECT_FLOAT_EQ(-1.2561177, c.d_.val());
AVEC y = createAVEC(b.val_);
VEC g;
c.val_.grad(y,g);
EXPECT_FLOAT_EQ(-1.2561177, g[0]);
}
TEST(AgradFwdLogFallingFactorial,FvarVar_FvarVar_2ndDeriv) {
using stan::math::fvar;
using stan::math::var;
using stan::math::log_falling_factorial;
fvar<var> a(4.0,1.0);
fvar<var> b(3.0,1.0);
fvar<var> c = log_falling_factorial(a,b);
AVEC y = createAVEC(a.val_,b.val_);
VEC g;
c.d_.grad(y,g);
EXPECT_FLOAT_EQ(0.22132295, g[0]);
EXPECT_FLOAT_EQ(-0.28382295, g[1]);
}
TEST(AgradFwdLogFallingFactorial,FvarVar_Double_2ndDeriv) {
using stan::math::fvar;
using stan::math::var;
using stan::math::log_falling_factorial;
fvar<var> a(4.0,1.0);
double b(3.0);
fvar<var> c = log_falling_factorial(a,b);
AVEC y = createAVEC(a.val_);
VEC g;
c.d_.grad(y,g);
EXPECT_FLOAT_EQ(0.22132295, g[0]);
}
TEST(AgradFwdLogFallingFactorial,Double_FvarVar_2ndDeriv) {
using stan::math::fvar;
using stan::math::var;
using stan::math::log_falling_factorial;
double a(4.0);
fvar<var> b(3.0,1.0);
fvar<var> c = log_falling_factorial(a,b);
AVEC y = createAVEC(b.val_);
VEC g;
c.d_.grad(y,g);
EXPECT_FLOAT_EQ(-0.28382295, g[0]);
}
TEST(AgradFwdLogFallingFactorial,FvarFvarVar_FvarFvarVar_1stDeriv) {
using stan::math::fvar;
using stan::math::var;
using stan::math::log_falling_factorial;
fvar<fvar<var> > x;
x.val_.val_ = 4.0;
x.val_.d_ = 1.0;
fvar<fvar<var> > y;
y.val_.val_ = 3.0;
y.d_.val_ = 1.0;
fvar<fvar<var> > a = log_falling_factorial(x,y);
EXPECT_FLOAT_EQ(1.3862944, a.val_.val_.val());
EXPECT_FLOAT_EQ(1.5061177, a.val_.d_.val());
EXPECT_FLOAT_EQ(-1.2561177, a.d_.val_.val());
EXPECT_FLOAT_EQ(0, a.d_.d_.val());
AVEC p = createAVEC(x.val_.val_,y.val_.val_);
VEC g;
a.val_.val_.grad(p,g);
EXPECT_FLOAT_EQ(1.5061177, g[0]);
EXPECT_FLOAT_EQ(-1.2561177, g[1]);
}
TEST(AgradFwdLogFallingFactorial,FvarFvarVar_Double_1stDeriv) {
using stan::math::fvar;
using stan::math::var;
using stan::math::log_falling_factorial;
fvar<fvar<var> > x;
x.val_.val_ = 4.0;
x.val_.d_ = 1.0;
double y(3.0);
fvar<fvar<var> > a = log_falling_factorial(x,y);
EXPECT_FLOAT_EQ(1.3862944, a.val_.val_.val());
EXPECT_FLOAT_EQ(1.5061177, a.val_.d_.val());
EXPECT_FLOAT_EQ(0, a.d_.val_.val());
EXPECT_FLOAT_EQ(0, a.d_.d_.val());
AVEC p = createAVEC(x.val_.val_);
VEC g;
a.val_.val_.grad(p,g);
EXPECT_FLOAT_EQ(1.5061177, g[0]);
}
TEST(AgradFwdLogFallingFactorial,Double_FvarFvarVar_1stDeriv) {
using stan::math::fvar;
using stan::math::var;
using stan::math::log_falling_factorial;
double x(4.0);
fvar<fvar<var> > y;
y.val_.val_ = 3.0;
y.d_.val_ = 1.0;
fvar<fvar<var> > a = log_falling_factorial(x,y);
EXPECT_FLOAT_EQ(1.3862944, a.val_.val_.val());
EXPECT_FLOAT_EQ(0, a.val_.d_.val());
EXPECT_FLOAT_EQ(-1.2561177, a.d_.val_.val());
EXPECT_FLOAT_EQ(0, a.d_.d_.val());
AVEC p = createAVEC(y.val_.val_);
VEC g;
a.val_.val_.grad(p,g);
EXPECT_FLOAT_EQ(-1.2561177, g[0]);
}
TEST(AgradFwdLogFallingFactorial,FvarFvarVar_FvarFvarVar_2ndDeriv_x) {
using stan::math::fvar;
using stan::math::var;
using stan::math::log_falling_factorial;
fvar<fvar<var> > x;
x.val_.val_ = 4.0;
x.val_.d_ = 1.0;
fvar<fvar<var> > y;
y.val_.val_ = 3.0;
y.d_.val_ = 1.0;
fvar<fvar<var> > a = log_falling_factorial(x,y);
AVEC p = createAVEC(x.val_.val_,y.val_.val_);
VEC g;
a.val_.d_.grad(p,g);
EXPECT_FLOAT_EQ(0.22132295, g[0]);
EXPECT_FLOAT_EQ(0, g[1]);
}
TEST(AgradFwdLogFallingFactorial,FvarFvarVar_FvarFvarVar_2ndDeriv_y) {
using stan::math::fvar;
using stan::math::var;
using stan::math::log_falling_factorial;
fvar<fvar<var> > x;
x.val_.val_ = 4.0;
x.val_.d_ = 1.0;
fvar<fvar<var> > y;
y.val_.val_ = 3.0;
y.d_.val_ = 1.0;
fvar<fvar<var> > a = log_falling_factorial(x,y);
AVEC p = createAVEC(x.val_.val_,y.val_.val_);
VEC g;
a.d_.val_.grad(p,g);
EXPECT_FLOAT_EQ(0, g[0]);
EXPECT_FLOAT_EQ(-0.28382295, g[1]);
}
TEST(AgradFwdLogFallingFactorial,FvarFvarVar_Double_2ndDeriv) {
using stan::math::fvar;
using stan::math::var;
using stan::math::log_falling_factorial;
fvar<fvar<var> > x;
x.val_.val_ = 4.0;
x.val_.d_ = 1.0;
double y(3.0);
fvar<fvar<var> > a = log_falling_factorial(x,y);
AVEC p = createAVEC(x.val_.val_);
VEC g;
a.val_.d_.grad(p,g);
EXPECT_FLOAT_EQ(0.22132295, g[0]);
}
TEST(AgradFwdLogFallingFactorial,Double_FvarFvarVar_2ndDeriv) {
using stan::math::fvar;
using stan::math::var;
using stan::math::log_falling_factorial;
double x(4.0);
fvar<fvar<var> > y;
y.val_.val_ = 3.0;
y.d_.val_ = 1.0;
fvar<fvar<var> > a = log_falling_factorial(x,y);
AVEC p = createAVEC(y.val_.val_);
VEC g;
a.d_.val_.grad(p,g);
EXPECT_FLOAT_EQ(-0.28382295, g[0]);
}
TEST(AgradFwdLogFallingFactorial,FvarFvarVar_FvarFvarVar_3rdDeriv) {
using stan::math::fvar;
using stan::math::var;
using stan::math::log_falling_factorial;
fvar<fvar<var> > x;
x.val_.val_ = 4.0;
x.val_.d_ = 1.0;
fvar<fvar<var> > y;
y.val_.val_ = 3.0;
y.d_.val_ = 1.0;
fvar<fvar<var> > a = log_falling_factorial(x,y);
AVEC p = createAVEC(x.val_.val_,y.val_.val_);
VEC g;
a.d_.d_.grad(p,g);
EXPECT_FLOAT_EQ(0, g[0]);
EXPECT_FLOAT_EQ(0, g[1]);
}
TEST(AgradFwdLogFallingFactorial,FvarFvarVar_Double_3rdDeriv) {
using stan::math::fvar;
using stan::math::var;
using stan::math::log_falling_factorial;
fvar<fvar<var> > x;
x.val_.val_ = 4.0;
x.val_.d_ = 1.0;
x.d_.val_ = 1.0;
double y(3.0);
fvar<fvar<var> > a = log_falling_factorial(x,y);
AVEC p = createAVEC(x.val_.val_);
VEC g;
a.d_.d_.grad(p,g);
EXPECT_FLOAT_EQ(-0.048789728, g[0]);
}
TEST(AgradFwdLogFallingFactorial,Double_FvarFvarVar_3rdDeriv) {
using stan::math::fvar;
using stan::math::var;
using stan::math::log_falling_factorial;
double x(4.0);
fvar<fvar<var> > y;
y.val_.val_ = 3.0;
y.d_.val_ = 1.0;
y.val_.d_ = 1.0;
fvar<fvar<var> > a = log_falling_factorial(x,y);
AVEC p = createAVEC(y.val_.val_);
VEC g;
a.d_.d_.grad(p,g);
EXPECT_FLOAT_EQ(0.080039732, g[0]);
}
struct log_falling_factorial_fun {
template <typename T0, typename T1>
inline
typename boost::math::tools::promote_args<T0,T1>::type
operator()(const T0 arg1,
const T1 arg2) const {
return log_falling_factorial(arg1,arg2);
}
};
TEST(AgradFwdLogFallingFactorial, nan) {
log_falling_factorial_fun log_falling_factorial_;
test_nan_mix(log_falling_factorial_,3.0,5.0,false);
}
<commit_msg>fixed mix log_falling_factorial tests<commit_after>#include <stan/math/mix/scal.hpp>
#include <gtest/gtest.h>
#include <boost/math/special_functions/digamma.hpp>
#include <test/unit/math/rev/mat/fun/util.hpp>
#include <test/unit/math/mix/scal/fun/nan_util.hpp>
double eps = 1e-6;
double first_deriv_a =
(stan::math::log_falling_factorial(5.0 + eps, 3.0)
- stan::math::log_falling_factorial(5.0 - eps, 3.0))
/ (2 * eps);
double first_deriv_b =
(stan::math::log_falling_factorial(5.0, 3.0 + eps)
- stan::math::log_falling_factorial(5.0, 3.0 - eps))
/ (2 * eps);
double eps2 = 1e-4;
double second_deriv_aa =
(stan::math::log_falling_factorial(5.0 + 2 * eps2, 3.0)
- 2 * stan::math::log_falling_factorial(5.0 + eps2, 3.0)
+ stan::math::log_falling_factorial(5.0, 3.0))
/ std::pow(eps2, 2);
double second_deriv_bb =
(stan::math::log_falling_factorial(5.0, 3.0 + 2 * eps2)
- 2 * stan::math::log_falling_factorial(5.0, 3.0 + eps2)
+ stan::math::log_falling_factorial(5.0, 3.0))
/ std::pow(eps2, 2);
double second_deriv_ab =
(stan::math::log_falling_factorial(5.0 + eps2, 3.0 + eps2)
- stan::math::log_falling_factorial(5.0 - eps2, 3.0 + eps2)
- stan::math::log_falling_factorial(5.0 + eps2, 3.0 - eps2)
+ stan::math::log_falling_factorial(5.0 - eps2, 3.0 - eps2))
/ 4 / std::pow(eps2, 2);
double third_deriv_aab =
(stan::math::log_falling_factorial(5.0 + 2 * eps2, 3.0 + eps2)
- 2 * stan::math::log_falling_factorial(5.0 + eps2, 3.0 + eps2)
+ stan::math::log_falling_factorial(5.0, 3.0 + eps2)
- stan::math::log_falling_factorial(5.0 + 2 * eps2, 3.0 - eps2)
+ 2 * stan::math::log_falling_factorial(5.0 + eps2, 3.0 - eps2)
- stan::math::log_falling_factorial(5.0, 3.0 - eps2))
/ 2 / std::pow(eps2, 3);
double third_deriv_abb =
(stan::math::log_falling_factorial(5.0 + eps2, 3.0 + 2 * eps2)
- 2 * stan::math::log_falling_factorial(5.0 + eps2, 3.0 + eps2)
+ stan::math::log_falling_factorial(5.0 + eps2, 3.0)
- stan::math::log_falling_factorial(5.0 - eps2, 3.0 + 2 * eps2)
+ 2 * stan::math::log_falling_factorial(5.0 - eps2, 3.0 + eps2)
- stan::math::log_falling_factorial(5.0 - eps2, 3.0))
/ 2 / std::pow(eps2, 3);
TEST(AgradFwdLogFallingFactorial,FvarVar_1stDeriv) {
using stan::math::fvar;
using stan::math::var;
using stan::math::log_falling_factorial;
fvar<var> a(5.0, 1.0);
fvar<var> b(3.0, 1.0);
fvar<var> c = log_falling_factorial(a,b);
EXPECT_FLOAT_EQ(std::log(60), c.val_.val());
EXPECT_FLOAT_EQ(first_deriv_a + first_deriv_b, c.d_.val());
AVEC y = createAVEC(a.val_,b.val_);
VEC g;
c.val_.grad(y,g);
EXPECT_FLOAT_EQ(first_deriv_a, g[0]);
EXPECT_FLOAT_EQ(first_deriv_b, g[1]);
}
TEST(AgradFwdLogFallingFactorial,FvarVar_2ndDeriv_x) {
using stan::math::fvar;
using stan::math::var;
using stan::math::log_falling_factorial;
fvar<var> a(5.0,1.0);
fvar<var> b(3.0,0.0);
fvar<var> c = log_falling_factorial(a,b);
AVEC y = createAVEC(a.val_,b.val_);
VEC g;
c.d_.grad(y,g);
ASSERT_NEAR(second_deriv_aa, g[0], 0.1);
}
TEST(AgradFwdLogFallingFactorial,FvarVar_2ndDeriv_y) {
using stan::math::fvar;
using stan::math::var;
using stan::math::log_falling_factorial;
fvar<var> a(5.0,0.0);
fvar<var> b(3.0,1.0);
fvar<var> c = log_falling_factorial(a,b);
AVEC y = createAVEC(a.val_,b.val_);
VEC g;
c.d_.grad(y,g);
ASSERT_NEAR(second_deriv_bb, g[1], 0.1);
}
TEST(AgradFwdLogFallingFactorial,FvarFvarVar_1stDeriv) {
using stan::math::fvar;
using stan::math::var;
using stan::math::log_falling_factorial;
fvar<fvar<var> > x;
x.val_.val_ = 5.0;
x.val_.d_ = 1.0;
fvar<fvar<var> > y;
y.val_.val_ = 3.0;
y.d_.val_ = 1.0;
fvar<fvar<var> > a = log_falling_factorial(x,y);
EXPECT_FLOAT_EQ(log_falling_factorial(5, 3.0), a.val_.val_.val());
EXPECT_FLOAT_EQ(first_deriv_a, a.val_.d_.val());
EXPECT_FLOAT_EQ(first_deriv_b, a.d_.val_.val());
ASSERT_NEAR(second_deriv_ab, a.d_.d_.val(), .01);
AVEC p = createAVEC(x.val_.val_,y.val_.val_);
VEC g;
a.val_.val_.grad(p,g);
EXPECT_FLOAT_EQ(first_deriv_a, g[0]);
EXPECT_FLOAT_EQ(first_deriv_b, g[1]);
}
TEST(AgradFwdLogFallingFactorial,FvarFvarVar_2ndDeriv_x) {
using stan::math::fvar;
using stan::math::var;
using stan::math::log_falling_factorial;
fvar<fvar<var> > x;
x.val_.val_ = 5.0;
x.val_.d_ = 1.0;
fvar<fvar<var> > y;
y.val_.val_ = 3.0;
y.d_.val_ = 1.0;
fvar<fvar<var> > a = log_falling_factorial(x,y);
AVEC p = createAVEC(x.val_.val_,y.val_.val_);
VEC g;
a.val_.d_.grad(p,g);
ASSERT_NEAR(second_deriv_aa, g[0], 0.01);
ASSERT_NEAR(second_deriv_ab, g[1], 0.01);
}
TEST(AgradFwdLogFallingFactorial,FvarFvarVar_2ndDeriv_y) {
using stan::math::fvar;
using stan::math::var;
using stan::math::log_falling_factorial;
fvar<fvar<var> > x;
x.val_.val_ = 5.0;
x.val_.d_ = 1.0;
fvar<fvar<var> > y;
y.val_.val_ = 3.0;
y.d_.val_ = 1.0;
fvar<fvar<var> > a = log_falling_factorial(x,y);
AVEC p = createAVEC(x.val_.val_,y.val_.val_);
VEC g;
a.d_.val_.grad(p,g);
ASSERT_NEAR(second_deriv_ab, g[0], 0.01);
ASSERT_NEAR(second_deriv_bb, g[1], 0.01);
}
TEST(AgradFwdLogFallingFactorial,FvarFvarVar_3rdDeriv) {
using stan::math::fvar;
using stan::math::var;
using stan::math::log_falling_factorial;
fvar<fvar<var> > x;
x.val_.val_ = 5.0;
x.val_.d_ = 1.0;
fvar<fvar<var> > y;
y.val_.val_ = 3.0;
y.d_.val_ = 1.0;
fvar<fvar<var> > a = log_falling_factorial(x,y);
AVEC p = createAVEC(x.val_.val_,y.val_.val_);
VEC g;
a.d_.d_.grad(p,g);
ASSERT_NEAR(third_deriv_aab, g[0], 0.03);
ASSERT_NEAR(third_deriv_abb, g[1], 0.03);
}
struct log_falling_factorial_fun {
template <typename T0, typename T1>
inline
typename boost::math::tools::promote_args<T0,T1>::type
operator()(const T0 arg1,
const T1 arg2) const {
return log_falling_factorial(arg1,arg2);
}
};
TEST(AgradFwdLogFallingFactorial, nan) {
log_falling_factorial_fun log_falling_factorial_;
test_nan_mix(log_falling_factorial_,3.0,5.0,false);
}
<|endoftext|> |
<commit_before><commit_msg>nitpicks<commit_after><|endoftext|> |
<commit_before>#pragma once
#include "Provider.hpp"
#include "Block.hpp"
#include "Transaction.hpp"
#include "Collection.hpp"
#include "FilterLog.hpp"
namespace Ethereum{namespace Connector{
class BlockChain
{
public:
BlockChain(Provider &);
bool isSyncing();
size_t getHeight();
Block getBlock(int);
Block getBlock(const char *);
Block getUncle(const char *, int);
Block getUncle(int, int);
Transaction getTransaction(const char *);
Transaction getBlockTransaction(const char *, size_t);
Transaction getBlockTransaction(size_t, size_t);
size_t getBlockTransactionsCount(size_t blockNumber);
size_t getBlockTransactionsCount(const char *blockHash);
size_t getTransactionsCount(const char *address);
size_t getBlockUnclesCount(size_t blockNumber);
size_t getBlockUnclesCount(const char *blockHash);
unsigned setNewFilter(const char *address, size_t fromBlock=0, size_t toBlock=0);
void removeFilter(unsigned id);
Collection<FilterLog> getFilterChanges(unsigned id);
Collection<FilterLog> getFilterLogs(unsigned id);
void retrieveBlockDetails(bool);
private:
Provider &_provider;
bool _fetchBlockDetails;
};
}}
<commit_msg>Block typedef<commit_after>#pragma once
#include "Provider.hpp"
#include "Block.hpp"
#include "Transaction.hpp"
#include "Collection.hpp"
#include "FilterLog.hpp"
namespace Ethereum{namespace Connector{
class BlockChain
{
public:
typedef Ethereum::Connector::Block Block;
public:
BlockChain(Provider &);
bool isSyncing();
size_t getHeight();
Block getBlock(int);
Block getBlock(const char *);
Block getUncle(const char *, int);
Block getUncle(int, int);
Transaction getTransaction(const char *);
Transaction getBlockTransaction(const char *, size_t);
Transaction getBlockTransaction(size_t, size_t);
size_t getBlockTransactionsCount(size_t blockNumber);
size_t getBlockTransactionsCount(const char *blockHash);
size_t getTransactionsCount(const char *address);
size_t getBlockUnclesCount(size_t blockNumber);
size_t getBlockUnclesCount(const char *blockHash);
unsigned setNewFilter(const char *address, size_t fromBlock=0, size_t toBlock=0);
void removeFilter(unsigned id);
Collection<FilterLog> getFilterChanges(unsigned id);
Collection<FilterLog> getFilterLogs(unsigned id);
void retrieveBlockDetails(bool);
private:
Provider &_provider;
bool _fetchBlockDetails;
};
}}
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include "drawingml/chart/chartspaceconverter.hxx"
#include <com/sun/star/chart/MissingValueTreatment.hpp>
#include <com/sun/star/chart/XChartDocument.hpp>
#include <com/sun/star/chart2/XChartDocument.hpp>
#include <com/sun/star/chart2/XTitled.hpp>
#include <com/sun/star/drawing/XDrawPageSupplier.hpp>
#include <com/sun/star/drawing/FillStyle.hpp>
#include "oox/core/xmlfilterbase.hxx"
#include "oox/drawingml/chart/chartconverter.hxx"
#include <oox/helper/graphichelper.hxx>
#include "drawingml/chart/chartdrawingfragment.hxx"
#include "drawingml/chart/chartspacemodel.hxx"
#include "drawingml/chart/plotareaconverter.hxx"
#include "drawingml/chart/titleconverter.hxx"
using namespace ::com::sun::star;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Exception;
using ::com::sun::star::uno::UNO_QUERY;
using ::com::sun::star::uno::UNO_QUERY_THROW;
using ::com::sun::star::uno::makeAny;
using ::com::sun::star::drawing::XDrawPageSupplier;
using ::com::sun::star::drawing::XShapes;
using ::com::sun::star::chart2::XDiagram;
using ::com::sun::star::chart2::XTitled;
using ::com::sun::star::beans::XPropertySet;
namespace oox {
namespace drawingml {
namespace chart {
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::chart2;
using namespace ::com::sun::star::chart2::data;
using namespace ::com::sun::star::drawing;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::util;
ChartSpaceConverter::ChartSpaceConverter( const ConverterRoot& rParent, ChartSpaceModel& rModel ) :
ConverterBase< ChartSpaceModel >( rParent, rModel )
{
}
ChartSpaceConverter::~ChartSpaceConverter()
{
}
void ChartSpaceConverter::convertFromModel( const Reference< XShapes >& rxExternalPage, const awt::Point& rChartPos )
{
if( !getChartConverter() )
return;
/* create data provider (virtual function in the ChartConverter class,
derived converters may create an external data provider) */
getChartConverter()->createDataProvider( getChartDocument() );
// formatting of the chart background. The default fill style varies with applications.
PropertySet aBackPropSet( getChartDocument()->getPageBackground() );
aBackPropSet.setProperty(
PROP_FillStyle,
uno::makeAny(getFilter().getGraphicHelper().getDefaultChartAreaFillStyle()));
getFormatter().convertFrameFormatting( aBackPropSet, mrModel.mxShapeProp, OBJECTTYPE_CHARTSPACE );
// convert plot area (container of all chart type groups)
PlotAreaConverter aPlotAreaConv( *this, mrModel.mxPlotArea.getOrCreate() );
aPlotAreaConv.convertFromModel( mrModel.mxView3D.getOrCreate() );
// plot area converter has created the diagram object
Reference< XDiagram > xDiagram = getChartDocument()->getFirstDiagram();
// convert wall and floor formatting in 3D charts
if( xDiagram.is() && aPlotAreaConv.isWall3dChart() )
{
WallFloorConverter aFloorConv( *this, mrModel.mxFloor.getOrCreate() );
aFloorConv.convertFromModel( xDiagram, OBJECTTYPE_FLOOR );
WallFloorConverter aWallConv( *this, mrModel.mxBackWall.getOrCreate() );
aWallConv.convertFromModel( xDiagram, OBJECTTYPE_WALL );
}
// chart title
if( !mrModel.mbAutoTitleDel ) try
{
/* If the title model is missing, but the chart shows exactly one
series, the series title is shown as chart title. */
OUString aAutoTitle = aPlotAreaConv.getAutomaticTitle();
if( mrModel.mxTitle.is() || !aAutoTitle.isEmpty() )
{
if( aAutoTitle.isEmpty() )
aAutoTitle = "Chart Title";
Reference< XTitled > xTitled( getChartDocument(), UNO_QUERY_THROW );
TitleConverter aTitleConv( *this, mrModel.mxTitle.getOrCreate() );
aTitleConv.convertFromModel( xTitled, aAutoTitle, OBJECTTYPE_CHARTTITLE );
}
}
catch( Exception& )
{
}
// legend
if( xDiagram.is() && mrModel.mxLegend.is() )
{
LegendConverter aLegendConv( *this, *mrModel.mxLegend );
aLegendConv.convertFromModel( xDiagram );
}
// treatment of missing values
if( xDiagram.is() )
{
using namespace ::com::sun::star::chart::MissingValueTreatment;
sal_Int32 nMissingValues = LEAVE_GAP;
switch( mrModel.mnDispBlanksAs )
{
case XML_gap: nMissingValues = LEAVE_GAP; break;
case XML_zero: nMissingValues = USE_ZERO; break;
case XML_span: nMissingValues = CONTINUE; break;
}
PropertySet aDiaProp( xDiagram );
aDiaProp.setProperty( PROP_MissingValueTreatment, nMissingValues );
}
/* Following all conversions needing the old Chart1 API that involves full
initialization of the chart view. */
namespace cssc = ::com::sun::star::chart;
Reference< cssc::XChartDocument > xChart1Doc( getChartDocument(), UNO_QUERY );
if( xChart1Doc.is() )
{
/* Set the IncludeHiddenCells property via the old API as only this
ensures that the data provider and all created sequences get this
flag correctly. */
PropertySet aDiaProp( xChart1Doc->getDiagram() );
aDiaProp.setProperty( PROP_IncludeHiddenCells, !mrModel.mbPlotVisOnly );
// plot area position and size
aPlotAreaConv.convertPositionFromModel();
// positions of main title and all axis titles
convertTitlePositions();
}
// embedded drawing shapes
if( !mrModel.maDrawingPath.isEmpty() ) try
{
/* Get the internal draw page of the chart document, if no external
drawing page has been passed. */
Reference< XShapes > xShapes;
awt::Point aShapesOffset( 0, 0 );
if( rxExternalPage.is() )
{
xShapes = rxExternalPage;
// offset for embedded shapes to move them inside the chart area
aShapesOffset = rChartPos;
}
else
{
Reference< XDrawPageSupplier > xDrawPageSupp( getChartDocument(), UNO_QUERY_THROW );
xShapes.set( xDrawPageSupp->getDrawPage(), UNO_QUERY_THROW );
}
/* If an external drawing page is passed, all embedded shapes will be
inserted there (used e.g. with 'chart sheets' in spreadsheet
documents). In this case, all types of shapes including OLE objects
are supported. If the shapes are inserted into the internal chart
drawing page instead, it is not possible to embed OLE objects. */
bool bOleSupport = rxExternalPage.is();
// now, xShapes is not null anymore
getFilter().importFragment( new ChartDrawingFragment(
getFilter(), mrModel.maDrawingPath, xShapes, getChartSize(), aShapesOffset, bOleSupport ) );
}
catch( Exception& )
{
}
// pivot chart
if ( mrModel.mbPivotChart )
{
PropertySet aProps( getChartDocument() );
aProps.setProperty( PROP_DisableDataTableDialog , true );
aProps.setProperty( PROP_DisableComplexChartTypes , true );
}
if(!mrModel.maSheetPath.isEmpty() )
{
Reference< ::com::sun::star::chart::XChartDocument > xChartDoc( getChartDocument(), UNO_QUERY );
PropertySet aProps( xChartDoc->getDiagram() );
aProps.setProperty( PROP_ExternalData , uno::makeAny(mrModel.maSheetPath) );
}
}
} // namespace chart
} // namespace drawingml
} // namespace oox
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>no need for that anymore<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include "drawingml/chart/chartspaceconverter.hxx"
#include <com/sun/star/chart/MissingValueTreatment.hpp>
#include <com/sun/star/chart/XChartDocument.hpp>
#include <com/sun/star/chart2/XChartDocument.hpp>
#include <com/sun/star/chart2/XTitled.hpp>
#include <com/sun/star/drawing/XDrawPageSupplier.hpp>
#include <com/sun/star/drawing/FillStyle.hpp>
#include "oox/core/xmlfilterbase.hxx"
#include "oox/drawingml/chart/chartconverter.hxx"
#include <oox/helper/graphichelper.hxx>
#include "drawingml/chart/chartdrawingfragment.hxx"
#include "drawingml/chart/chartspacemodel.hxx"
#include "drawingml/chart/plotareaconverter.hxx"
#include "drawingml/chart/titleconverter.hxx"
using namespace ::com::sun::star;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::Exception;
using ::com::sun::star::uno::UNO_QUERY;
using ::com::sun::star::uno::UNO_QUERY_THROW;
using ::com::sun::star::uno::makeAny;
using ::com::sun::star::drawing::XDrawPageSupplier;
using ::com::sun::star::drawing::XShapes;
using ::com::sun::star::chart2::XDiagram;
using ::com::sun::star::chart2::XTitled;
using ::com::sun::star::beans::XPropertySet;
namespace oox {
namespace drawingml {
namespace chart {
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::chart2;
using namespace ::com::sun::star::chart2::data;
using namespace ::com::sun::star::drawing;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::util;
ChartSpaceConverter::ChartSpaceConverter( const ConverterRoot& rParent, ChartSpaceModel& rModel ) :
ConverterBase< ChartSpaceModel >( rParent, rModel )
{
}
ChartSpaceConverter::~ChartSpaceConverter()
{
}
void ChartSpaceConverter::convertFromModel( const Reference< XShapes >& rxExternalPage, const awt::Point& rChartPos )
{
if( !getChartConverter() )
return;
/* create data provider (virtual function in the ChartConverter class,
derived converters may create an external data provider) */
getChartConverter()->createDataProvider( getChartDocument() );
// formatting of the chart background. The default fill style varies with applications.
PropertySet aBackPropSet( getChartDocument()->getPageBackground() );
getFormatter().convertFrameFormatting( aBackPropSet, mrModel.mxShapeProp, OBJECTTYPE_CHARTSPACE );
// convert plot area (container of all chart type groups)
PlotAreaConverter aPlotAreaConv( *this, mrModel.mxPlotArea.getOrCreate() );
aPlotAreaConv.convertFromModel( mrModel.mxView3D.getOrCreate() );
// plot area converter has created the diagram object
Reference< XDiagram > xDiagram = getChartDocument()->getFirstDiagram();
// convert wall and floor formatting in 3D charts
if( xDiagram.is() && aPlotAreaConv.isWall3dChart() )
{
WallFloorConverter aFloorConv( *this, mrModel.mxFloor.getOrCreate() );
aFloorConv.convertFromModel( xDiagram, OBJECTTYPE_FLOOR );
WallFloorConverter aWallConv( *this, mrModel.mxBackWall.getOrCreate() );
aWallConv.convertFromModel( xDiagram, OBJECTTYPE_WALL );
}
// chart title
if( !mrModel.mbAutoTitleDel ) try
{
/* If the title model is missing, but the chart shows exactly one
series, the series title is shown as chart title. */
OUString aAutoTitle = aPlotAreaConv.getAutomaticTitle();
if( mrModel.mxTitle.is() || !aAutoTitle.isEmpty() )
{
if( aAutoTitle.isEmpty() )
aAutoTitle = "Chart Title";
Reference< XTitled > xTitled( getChartDocument(), UNO_QUERY_THROW );
TitleConverter aTitleConv( *this, mrModel.mxTitle.getOrCreate() );
aTitleConv.convertFromModel( xTitled, aAutoTitle, OBJECTTYPE_CHARTTITLE );
}
}
catch( Exception& )
{
}
// legend
if( xDiagram.is() && mrModel.mxLegend.is() )
{
LegendConverter aLegendConv( *this, *mrModel.mxLegend );
aLegendConv.convertFromModel( xDiagram );
}
// treatment of missing values
if( xDiagram.is() )
{
using namespace ::com::sun::star::chart::MissingValueTreatment;
sal_Int32 nMissingValues = LEAVE_GAP;
switch( mrModel.mnDispBlanksAs )
{
case XML_gap: nMissingValues = LEAVE_GAP; break;
case XML_zero: nMissingValues = USE_ZERO; break;
case XML_span: nMissingValues = CONTINUE; break;
}
PropertySet aDiaProp( xDiagram );
aDiaProp.setProperty( PROP_MissingValueTreatment, nMissingValues );
}
/* Following all conversions needing the old Chart1 API that involves full
initialization of the chart view. */
namespace cssc = ::com::sun::star::chart;
Reference< cssc::XChartDocument > xChart1Doc( getChartDocument(), UNO_QUERY );
if( xChart1Doc.is() )
{
/* Set the IncludeHiddenCells property via the old API as only this
ensures that the data provider and all created sequences get this
flag correctly. */
PropertySet aDiaProp( xChart1Doc->getDiagram() );
aDiaProp.setProperty( PROP_IncludeHiddenCells, !mrModel.mbPlotVisOnly );
// plot area position and size
aPlotAreaConv.convertPositionFromModel();
// positions of main title and all axis titles
convertTitlePositions();
}
// embedded drawing shapes
if( !mrModel.maDrawingPath.isEmpty() ) try
{
/* Get the internal draw page of the chart document, if no external
drawing page has been passed. */
Reference< XShapes > xShapes;
awt::Point aShapesOffset( 0, 0 );
if( rxExternalPage.is() )
{
xShapes = rxExternalPage;
// offset for embedded shapes to move them inside the chart area
aShapesOffset = rChartPos;
}
else
{
Reference< XDrawPageSupplier > xDrawPageSupp( getChartDocument(), UNO_QUERY_THROW );
xShapes.set( xDrawPageSupp->getDrawPage(), UNO_QUERY_THROW );
}
/* If an external drawing page is passed, all embedded shapes will be
inserted there (used e.g. with 'chart sheets' in spreadsheet
documents). In this case, all types of shapes including OLE objects
are supported. If the shapes are inserted into the internal chart
drawing page instead, it is not possible to embed OLE objects. */
bool bOleSupport = rxExternalPage.is();
// now, xShapes is not null anymore
getFilter().importFragment( new ChartDrawingFragment(
getFilter(), mrModel.maDrawingPath, xShapes, getChartSize(), aShapesOffset, bOleSupport ) );
}
catch( Exception& )
{
}
// pivot chart
if ( mrModel.mbPivotChart )
{
PropertySet aProps( getChartDocument() );
aProps.setProperty( PROP_DisableDataTableDialog , true );
aProps.setProperty( PROP_DisableComplexChartTypes , true );
}
if(!mrModel.maSheetPath.isEmpty() )
{
Reference< ::com::sun::star::chart::XChartDocument > xChartDoc( getChartDocument(), UNO_QUERY );
PropertySet aProps( xChartDoc->getDiagram() );
aProps.setProperty( PROP_ExternalData , uno::makeAny(mrModel.maSheetPath) );
}
}
} // namespace chart
} // namespace drawingml
} // namespace oox
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>#ifndef MJOLNIR_READ_FORCEFIELD
#define MJOLNIR_READ_FORCEFIELD
#include <extlib/toml/toml.hpp>
#include <mjolnir/core/ForceField.hpp>
#include <mjolnir/util/get_toml_value.hpp>
#include <mjolnir/input/read_interaction.hpp>
namespace mjolnir
{
template<typename traitsT>
LocalForceField<traitsT>
read_local_forcefield(std::vector<toml::Table> interactions)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_SCOPE(read_local_forcefield(), 0);
LocalForceField<traitsT> lff;
for(const auto& interaction : interactions)
{
lff.emplace(read_local_interaction<traitsT>(interaction));
}
return lff;
}
template<typename traitsT>
GlobalForceField<traitsT>
read_global_forcefield(std::vector<toml::Table> interactions)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_SCOPE(read_global_forcefield(), 0);
GlobalForceField<traitsT> gff;
for(const auto& interaction : interactions)
{
gff.emplace(read_global_interaction<traitsT>(interaction));
}
return gff;
}
template<typename traitsT>
ExternalForceField<traitsT>
read_external_forcefield(std::vector<toml::Table> interactions)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_SCOPE(read_external_forcefield(), 0);
ExternalForceField<traitsT> eff;
for(const auto& interaction : interactions)
{
eff.emplace(read_external_interaction<traitsT>(interaction));
}
return eff;
}
template<typename traitsT>
ForceField<traitsT>
read_forcefield(const toml::Table& data, std::size_t N)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_SCOPE(read_forcefield(), 0);
const auto& ffs = toml_value_at(data, "forcefields", "<root>"
).cast<toml::value_t::Array>();
if(ffs.size() <= N)
{
throw std::out_of_range("no enough forcefields: " + std::to_string(N));
}
const auto& ff = ffs.at(N).cast<toml::value_t::Table>();
MJOLNIR_LOG_INFO(ffs.size(), " forcefields are provided");
MJOLNIR_LOG_INFO("using ", N, "-th forcefield");
std::vector<toml::Table> fflocal, ffglobal, ffexternal;
if(ff.count("local") == 1)
{
MJOLNIR_LOG_INFO("LocalForceField found");
fflocal = toml::get<std::vector<toml::Table>>(
toml_value_at(ff, "local", "[forcefields]"));
}
if(ff.count("global") == 1)
{
MJOLNIR_LOG_INFO("GlobalForceField found");
ffglobal = toml::get<std::vector<toml::Table>>(
toml_value_at(ff, "global", "[forcefields]"));
}
if(ff.count("external") == 1)
{
MJOLNIR_LOG_INFO("ExternalForceField found");
ffexternal = toml::get<std::vector<toml::Table>>(
toml_value_at(ff, "external", "[forcefields]"));
}
MJOLNIR_LOG_INFO("reading each forcefield settings");
return ForceField<traitsT>(
read_local_forcefield<traitsT>(std::move(fflocal)),
read_global_forcefield<traitsT>(std::move(ffglobal)),
read_external_forcefield<traitsT>(std::move(ffexternal)));
}
} // mjolnir
#endif// MJOLNIR_READ_FORCEFIELD
<commit_msg>#11 enable to read [[forcefields]] section from separated file<commit_after>#ifndef MJOLNIR_READ_FORCEFIELD
#define MJOLNIR_READ_FORCEFIELD
#include <extlib/toml/toml.hpp>
#include <mjolnir/core/ForceField.hpp>
#include <mjolnir/util/get_toml_value.hpp>
#include <mjolnir/input/read_interaction.hpp>
namespace mjolnir
{
template<typename traitsT>
LocalForceField<traitsT>
read_local_forcefield(std::vector<toml::Table> interactions)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_SCOPE(read_local_forcefield(), 0);
LocalForceField<traitsT> lff;
for(const auto& interaction : interactions)
{
lff.emplace(read_local_interaction<traitsT>(interaction));
}
return lff;
}
template<typename traitsT>
GlobalForceField<traitsT>
read_global_forcefield(std::vector<toml::Table> interactions)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_SCOPE(read_global_forcefield(), 0);
GlobalForceField<traitsT> gff;
for(const auto& interaction : interactions)
{
gff.emplace(read_global_interaction<traitsT>(interaction));
}
return gff;
}
template<typename traitsT>
ExternalForceField<traitsT>
read_external_forcefield(std::vector<toml::Table> interactions)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_SCOPE(read_external_forcefield(), 0);
ExternalForceField<traitsT> eff;
for(const auto& interaction : interactions)
{
eff.emplace(read_external_interaction<traitsT>(interaction));
}
return eff;
}
template<typename traitsT>
ForceField<traitsT>
read_forcefield_from_table(const toml::Table& ff)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_SCOPE(read_forcefield_from_table(), 0);
std::vector<toml::Table> fflocal, ffglobal, ffexternal;
if(ff.count("local") == 1)
{
MJOLNIR_LOG_INFO("LocalForceField found");
fflocal = toml::get<std::vector<toml::Table>>(
toml_value_at(ff, "local", "[forcefields]"));
}
if(ff.count("global") == 1)
{
MJOLNIR_LOG_INFO("GlobalForceField found");
ffglobal = toml::get<std::vector<toml::Table>>(
toml_value_at(ff, "global", "[forcefields]"));
}
if(ff.count("external") == 1)
{
MJOLNIR_LOG_INFO("ExternalForceField found");
ffexternal = toml::get<std::vector<toml::Table>>(
toml_value_at(ff, "external", "[forcefields]"));
}
for(const auto kv: ff)
{
if(kv.first != "local" && kv.first != "global" && kv.first != "external")
{
std::cerr << "WARNING: unknown key `" << kv.first << "` appeared. ";
std::cerr << "in [[forcefields]] table. It will be ignored.\n";
MJOLNIR_LOG_WARN("unknown key ", kv.first, "appeared.");
}
}
return ForceField<traitsT>(
read_local_forcefield<traitsT>(std::move(fflocal)),
read_global_forcefield<traitsT>(std::move(ffglobal)),
read_external_forcefield<traitsT>(std::move(ffexternal)));
}
template<typename traitsT>
ForceField<traitsT>
read_forcefield(const toml::Table& data, std::size_t N)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_SCOPE(read_forcefield(), 0);
const auto& ffs = toml_value_at(data, "forcefields", "<root>"
).cast<toml::value_t::Array>();
if(ffs.size() <= N)
{
throw std::out_of_range("no enough forcefields: " + std::to_string(N));
}
MJOLNIR_LOG_INFO(ffs.size(), " forcefields are provided");
MJOLNIR_LOG_INFO("using ", N, "-th forcefield");
const auto& ff = ffs.at(N).cast<toml::value_t::Table>();
if(ff.count("filename") == 1)
{
MJOLNIR_SCOPE(ff.count("filename") == 1, 1);
if(ff.size() != 1)
{
std::cerr << "WARNING: [[forcefields]] has `filename` key.";
std::cerr << "When `filename` is provided, all settings will be ";
std::cerr << "read from the file, so other settings are ignored.\n";
MJOLNIR_LOG_WARN("[[forcefields]] has filename and other settings");
}
const std::string filename = toml::get<std::string>(ff.at("filename"));
MJOLNIR_LOG_INFO("filename is ", filename);
const auto forcefield_file = toml::parse(filename);
if(forcefield_file.count("forcefields") == 1)
{
MJOLNIR_LOG_INFO("`forcefields` value found in ", filename);
const auto forcefield_toml_type =
forcefield_file.at("forcefields").type();
if(forcefield_toml_type != toml::value_t::Table)
{
std::cerr << "FATAL: each [forcefields] should be provided as ";
std::cerr << "a table in each file (" << filename << ").\n";
std::cerr << " : because it represents one set of ";
std::cerr << "forcefield. currently it is provided as ";
std::cerr << forcefield_toml_type << ".\n";
std::exit(1);
}
std::cerr << "WARNING: [forcefields] isn't necessary for splitted ";
std::cerr << "toml file. you can define just [[local]], [[global]]";
std::cerr << " and [[external]] forcefields in " << filename << '\n';
MJOLNIR_LOG_INFO("reading `forcefields` table");
return read_forcefield_from_table<traitsT>(forcefield_file.at(
"forcefields").template cast<toml::value_t::Table>());
}
return read_forcefield_from_table<traitsT>(forcefield_file);
}
// else
return read_forcefield_from_table<traitsT>(ff);
}
} // mjolnir
#endif// MJOLNIR_READ_FORCEFIELD
<|endoftext|> |
<commit_before>#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
#include <opengm/inference/inference.hxx>
#include <opengm/graphicalmodel/graphicalmodel.hxx>
#include <opengm/inference/auxiliary/fusion_move/fusion_mover.hxx>
#include <opengm/python/opengmpython.hxx>
#include <opengm/python/converter.hxx>
#include <opengm/python/numpyview.hxx>
#include <opengm/python/pythonfunction.hxx>
// Fusion Move Solver
#include "opengm/inference/astar.hxx"
#include "opengm/inference/lazyflipper.hxx"
#include "opengm/inference/infandflip.hxx"
#include <opengm/inference/messagepassing/messagepassing.hxx>
#ifdef WITH_AD3
#include "opengm/inference/external/ad3.hxx"
#endif
#ifdef WITH_CPLEX
#include "opengm/inference/lpcplex.hxx"
#endif
#ifdef WITH_QPBO
#include "QPBO.h"
#endif
template<class GM,class ACC>
class PythonFusionMover{
typedef GM GraphicalModelType;
typedef ACC AccumulationType;
OPENGM_GM_TYPE_TYPEDEFS;
typedef opengm::FusionMover<GM,ACC> CppFusionMover;
typedef typename CppFusionMover::SubGmType SubGmType;
// sub-inf-astar
typedef opengm::AStar<SubGmType,AccumulationType> AStarSubInf;
// sub-inf-lf
typedef opengm::LazyFlipper<SubGmType,AccumulationType> LazyFlipperSubInf;
// sub-inf-bp
typedef opengm::BeliefPropagationUpdateRules<SubGmType,AccumulationType> UpdateRulesType;
typedef opengm::MessagePassing<SubGmType,AccumulationType,UpdateRulesType, opengm::MaxDistance> BpSubInf;
// sub-inf-bp-lf
typedef opengm::InfAndFlip<SubGmType,AccumulationType,BpSubInf> BpLfSubInf;
//#ifdef WITH_AD3
//typedef opengm::external::AD3Inf<SubGmType,AccumulationType> Ad3SubInf;
//#endif
#ifdef WITH_QPBO
typedef kolmogorov::qpbo::QPBO<double> QpboSubInf;
#endif
#ifdef WITH_CPLEX
typedef opengm::LPCplex<SubGmType,AccumulationType> CplexSubInf;
#endif
public:
PythonFusionMover(const GM & gm)
: gm_(gm),
fusionMover_(gm),
argA_(gm.numberOfVariables()),
argB_(gm.numberOfVariables()),
argR_(gm.numberOfVariables()),
factorOrder_(gm.factorOrder())
{
}
boost::python::tuple fuse(
opengm::python::NumpyView<LabelType,1> labelsA,
opengm::python::NumpyView<LabelType,1> labelsB,
const std::string & fusionSolver
)
{
// copy input
//#std::cout<<"copy input\n";
std::copy(labelsA.begin(),labelsA.end(),argA_.begin());
std::copy(labelsB.begin(),labelsB.end(),argB_.begin());
// do setup
//#std::cout<<"setup\n";
fusionMover_.setup(
argA_,argB_,argR_,
gm_.evaluate(argA_.begin()),gm_.evaluate(argB_.begin())
);
//std::cout<<"do fusion\n";
// do the fusion
const ValueType resultValue = this->doFusion(fusionSolver);
//std::cout<<"make result\n";
// return result
return boost::python::make_tuple(
opengm::python::iteratorToNumpy(argR_.begin(), argR_.size()),
fusionMover_.valueResult(),
fusionMover_.valueA(),
fusionMover_.valueB()
);
}
private:
ValueType doFusion(const std::string & fusionSolver){
if(fusionSolver==std::string("qpbo")){
#ifdef WITH_QPBO
if(factorOrder_<=2){
return fusionMover_. template fuseQpbo<QpboSubInf> ();
}
else{
return fusionMover_. template fuseFixQpbo<QpboSubInf> ();
}
#else
OPENGM_CHECK(false,"qpbo fusion solver need WITH_QPBO");
#endif
}
else if(fusionSolver==std::string("lf2")){
return fusionMover_. template fuse<LazyFlipperSubInf> (typename LazyFlipperSubInf::Parameter(2),true);
}
else if(fusionSolver==std::string("lf3")){
return fusionMover_. template fuse<LazyFlipperSubInf> (typename LazyFlipperSubInf::Parameter(3),true);
}
}
const GM & gm_;
CppFusionMover fusionMover_;
std::vector<LabelType> argA_;
std::vector<LabelType> argB_;
std::vector<LabelType> argR_;
size_t factorOrder_;
};
template<class GM,class ACC>
void export_fusion_moves(){
using namespace boost::python;
boost::python::numeric::array::set_module_and_type("numpy", "ndarray");
boost::python::docstring_options docstringOptions(true,true,false);
import_array();
typedef PythonFusionMover<GM,ACC> PyFusionMover;
boost::python::class_<PyFusionMover > ("FusionMover",
boost::python::init<const GM &>("Construct a FusionMover from a graphical model ")
[with_custodian_and_ward<1 /*custodian == self*/, 2 /*ward == const PyGM& */>()]
)
.def("fuse",&PyFusionMover::fuse)
;
}
template void export_fusion_moves<opengm::python::GmAdder ,opengm::Minimizer>();
<commit_msg>fix return-type warning in python bindings<commit_after>#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
#include <opengm/inference/inference.hxx>
#include <opengm/graphicalmodel/graphicalmodel.hxx>
#include <opengm/inference/auxiliary/fusion_move/fusion_mover.hxx>
#include <opengm/python/opengmpython.hxx>
#include <opengm/python/converter.hxx>
#include <opengm/python/numpyview.hxx>
#include <opengm/python/pythonfunction.hxx>
// Fusion Move Solver
#include "opengm/inference/astar.hxx"
#include "opengm/inference/lazyflipper.hxx"
#include "opengm/inference/infandflip.hxx"
#include <opengm/inference/messagepassing/messagepassing.hxx>
#ifdef WITH_AD3
#include "opengm/inference/external/ad3.hxx"
#endif
#ifdef WITH_CPLEX
#include "opengm/inference/lpcplex.hxx"
#endif
#ifdef WITH_QPBO
#include "QPBO.h"
#endif
template<class GM,class ACC>
class PythonFusionMover{
typedef GM GraphicalModelType;
typedef ACC AccumulationType;
OPENGM_GM_TYPE_TYPEDEFS;
typedef opengm::FusionMover<GM,ACC> CppFusionMover;
typedef typename CppFusionMover::SubGmType SubGmType;
// sub-inf-astar
typedef opengm::AStar<SubGmType,AccumulationType> AStarSubInf;
// sub-inf-lf
typedef opengm::LazyFlipper<SubGmType,AccumulationType> LazyFlipperSubInf;
// sub-inf-bp
typedef opengm::BeliefPropagationUpdateRules<SubGmType,AccumulationType> UpdateRulesType;
typedef opengm::MessagePassing<SubGmType,AccumulationType,UpdateRulesType, opengm::MaxDistance> BpSubInf;
// sub-inf-bp-lf
typedef opengm::InfAndFlip<SubGmType,AccumulationType,BpSubInf> BpLfSubInf;
//#ifdef WITH_AD3
//typedef opengm::external::AD3Inf<SubGmType,AccumulationType> Ad3SubInf;
//#endif
#ifdef WITH_QPBO
typedef kolmogorov::qpbo::QPBO<double> QpboSubInf;
#endif
#ifdef WITH_CPLEX
typedef opengm::LPCplex<SubGmType,AccumulationType> CplexSubInf;
#endif
public:
PythonFusionMover(const GM & gm)
: gm_(gm),
fusionMover_(gm),
argA_(gm.numberOfVariables()),
argB_(gm.numberOfVariables()),
argR_(gm.numberOfVariables()),
factorOrder_(gm.factorOrder())
{
}
boost::python::tuple fuse(
opengm::python::NumpyView<LabelType,1> labelsA,
opengm::python::NumpyView<LabelType,1> labelsB,
const std::string & fusionSolver
)
{
// copy input
//#std::cout<<"copy input\n";
std::copy(labelsA.begin(),labelsA.end(),argA_.begin());
std::copy(labelsB.begin(),labelsB.end(),argB_.begin());
// do setup
//#std::cout<<"setup\n";
fusionMover_.setup(
argA_,argB_,argR_,
gm_.evaluate(argA_.begin()),gm_.evaluate(argB_.begin())
);
//std::cout<<"do fusion\n";
// do the fusion
const ValueType resultValue = this->doFusion(fusionSolver);
//std::cout<<"make result\n";
// return result
return boost::python::make_tuple(
opengm::python::iteratorToNumpy(argR_.begin(), argR_.size()),
fusionMover_.valueResult(),
fusionMover_.valueA(),
fusionMover_.valueB()
);
}
private:
ValueType doFusion(const std::string & fusionSolver){
if(fusionSolver==std::string("qpbo")){
#ifdef WITH_QPBO
if(factorOrder_<=2){
return fusionMover_. template fuseQpbo<QpboSubInf> ();
}
else{
return fusionMover_. template fuseFixQpbo<QpboSubInf> ();
}
#else
OPENGM_CHECK(false,"qpbo fusion solver need WITH_QPBO");
#endif
}
else if(fusionSolver==std::string("lf2")){
return fusionMover_. template fuse<LazyFlipperSubInf> (typename LazyFlipperSubInf::Parameter(2),true);
}
else if(fusionSolver==std::string("lf3")){
return fusionMover_. template fuse<LazyFlipperSubInf> (typename LazyFlipperSubInf::Parameter(3),true);
}
throw opengm::RuntimeError("unknown fusion solver");
}
const GM & gm_;
CppFusionMover fusionMover_;
std::vector<LabelType> argA_;
std::vector<LabelType> argB_;
std::vector<LabelType> argR_;
size_t factorOrder_;
};
template<class GM,class ACC>
void export_fusion_moves(){
using namespace boost::python;
boost::python::numeric::array::set_module_and_type("numpy", "ndarray");
boost::python::docstring_options docstringOptions(true,true,false);
import_array();
typedef PythonFusionMover<GM,ACC> PyFusionMover;
boost::python::class_<PyFusionMover > ("FusionMover",
boost::python::init<const GM &>("Construct a FusionMover from a graphical model ")
[with_custodian_and_ward<1 /*custodian == self*/, 2 /*ward == const PyGM& */>()]
)
.def("fuse",&PyFusionMover::fuse)
;
}
template void export_fusion_moves<opengm::python::GmAdder ,opengm::Minimizer>();
<|endoftext|> |
<commit_before>/*
* Software License Agreement (Apache License)
*
* Copyright (c) 2014, Dan Solomon
*
* 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 <console_bridge/console.h>
#include "descartes_moveit/moveit_state_adapter.h"
#include "eigen_conversions/eigen_msg.h"
#include "random_numbers/random_numbers.h"
#include "descartes_core/pretty_print.hpp"
#include "descartes_moveit/seed_search.h"
#include <sstream>
const static int SAMPLE_ITERATIONS = 10;
namespace
{
bool getJointVelocityLimits(const moveit::core::RobotState& state,
const std::string& group_name,
std::vector<double>& output)
{
std::vector<double> result;
auto models = state.getJointModelGroup(group_name)->getActiveJointModels();
for (const moveit::core::JointModel* model : models)
{
const auto& bounds = model->getVariableBounds();
// Check to see if there is a single bounds constraint (more might indicate
// not revolute joint)
if (bounds.size() != 1)
{
ROS_ERROR_STREAM(__FUNCTION__ << " Unexpected joint bounds array size (did not equal 1)");
return false;
}
else
{
result.push_back(bounds[0].max_velocity_);
}
}
output = result;
return true;
}
} // end anon namespace
namespace descartes_moveit
{
MoveitStateAdapter::MoveitStateAdapter()
{}
MoveitStateAdapter::MoveitStateAdapter(const moveit::core::RobotState & robot_state, const std::string & group_name,
const std::string & tool_frame, const std::string & world_frame) :
robot_state_(new moveit::core::RobotState(robot_state)),
group_name_(group_name),
tool_frame_(tool_frame),
world_frame_(world_frame),
world_to_root_(Eigen::Affine3d::Identity())
{
ROS_INFO_STREAM("Generated random seeds");
seed_states_ = seed::findRandomSeeds(*robot_state_, group_name_, SAMPLE_ITERATIONS);
const moveit::core::JointModelGroup* joint_model_group_ptr = robot_state_->getJointModelGroup(group_name);
if (joint_model_group_ptr)
{
// Find the velocity limits
if (!getJointVelocityLimits(*robot_state_, group_name, velocity_limits_))
{
logWarn("Could not determine velocity limits of RobotModel from MoveIt");
}
joint_model_group_ptr->printGroupInfo();
const std::vector<std::string>& link_names = joint_model_group_ptr->getLinkModelNames();
if (tool_frame_ != link_names.back())
{
logWarn("Tool frame '%s' does not match group tool frame '%s', functionality will be implemented in the future",
tool_frame_.c_str(), link_names.back().c_str());
}
if (world_frame_ != robot_state_->getRobotModel()->getModelFrame())
{
logWarn("World frame '%s' does not match model root frame '%s', all poses will be transformed to world frame '%s'",
world_frame_.c_str(), link_names.front().c_str(),world_frame_.c_str());
Eigen::Affine3d root_to_world = robot_state_->getFrameTransform(world_frame_);
world_to_root_ = descartes_core::Frame(root_to_world.inverse());
}
}
else
{
logError("Joint group: %s does not exist in robot model", group_name_.c_str());
std::stringstream msg;
msg << "Possible group names: " << robot_state_->getRobotModel()->getJointModelGroupNames();
logError(msg.str().c_str());
}
return;
}
bool MoveitStateAdapter::initialize(const std::string& robot_description, const std::string& group_name,
const std::string& world_frame,const std::string& tcp_frame)
{
robot_model_loader_.reset(new robot_model_loader::RobotModelLoader(robot_description));
robot_model_ptr_ = robot_model_loader_->getModel();
robot_state_.reset(new moveit::core::RobotState(robot_model_ptr_));
planning_scene_.reset(new planning_scene::PlanningScene(robot_model_loader_->getModel()));
group_name_ = group_name;
tool_frame_ = tcp_frame;
world_frame_ = world_frame;
if (seed_states_.empty())
{
seed_states_ = seed::findRandomSeeds(*robot_state_, group_name_, SAMPLE_ITERATIONS);
ROS_INFO_STREAM("Generated "<<seed_states_.size()<< " random seeds");
}
// Find the velocity limits
if (!getJointVelocityLimits(*robot_state_, group_name, velocity_limits_))
{
logWarn("Could not determine velocity limits of RobotModel from MoveIt");
}
const moveit::core::JointModelGroup* joint_model_group_ptr = robot_state_->getJointModelGroup(group_name);
if (joint_model_group_ptr)
{
joint_model_group_ptr->printGroupInfo();
const std::vector<std::string>& link_names = joint_model_group_ptr->getLinkModelNames();
if (tool_frame_ != link_names.back())
{
logWarn("Tool frame '%s' does not match group tool frame '%s', functionality will be implemented in the future",
tool_frame_.c_str(), link_names.back().c_str());
}
if (world_frame_ != robot_state_->getRobotModel()->getModelFrame())
{
logWarn("World frame '%s' does not match model root frame '%s', all poses will be transformed to world frame '%s'",
world_frame_.c_str(), robot_state_->getRobotModel()->getModelFrame().c_str(),world_frame_.c_str());
Eigen::Affine3d root_to_world = robot_state_->getFrameTransform(world_frame_);
world_to_root_ = descartes_core::Frame(root_to_world.inverse());
}
}
else
{
logError("Joint group: %s does not exist in robot model", group_name_.c_str());
std::stringstream msg;
msg << "Possible group names: " << robot_state_->getRobotModel()->getJointModelGroupNames();
logError(msg.str().c_str());
}
return true;
}
bool MoveitStateAdapter::getIK(const Eigen::Affine3d &pose, const std::vector<double> &seed_state,
std::vector<double> &joint_pose) const
{
robot_state_->setJointGroupPositions(group_name_, seed_state);
return getIK(pose, joint_pose);
}
bool MoveitStateAdapter::getIK(const Eigen::Affine3d &pose, std::vector<double> &joint_pose) const
{
bool rtn = false;
// transform to group base
Eigen::Affine3d tool_pose = world_to_root_.frame* pose;
if (robot_state_->setFromIK(robot_state_->getJointModelGroup(group_name_), tool_pose,
tool_frame_))
{
robot_state_->copyJointGroupPositions(group_name_, joint_pose);
if(!isValid(joint_pose))
{
ROS_DEBUG_STREAM("Robot joint pose is invalid");
}
else
{
rtn = true;
}
}
else
{
rtn = false;
}
return rtn;
}
bool MoveitStateAdapter::getAllIK(const Eigen::Affine3d &pose, std::vector<std::vector<double> > &joint_poses) const
{
//The minimum difference between solutions should be greater than the search discretization
//used by the IK solver. This value is multiplied by 4 to remove any chance that a solution
//in the middle of a discretization step could be double counted. In reality, we'd like solutions
//to be further apart than this.
double epsilon = 4 * robot_state_->getRobotModel()->getJointModelGroup(group_name_)->getSolverInstance()->
getSearchDiscretization();
logDebug("Utilizing an min. difference of %f between IK solutions", epsilon);
joint_poses.clear();
for (size_t sample_iter = 0; sample_iter < seed_states_.size(); ++sample_iter)
{
robot_state_->setJointGroupPositions(group_name_, seed_states_[sample_iter]);
std::vector<double> joint_pose;
if (getIK(pose, joint_pose))
{
if( joint_poses.empty())
{
std::stringstream msg;
msg << "Found *first* solution on " << sample_iter << " iteration, joint: " << joint_pose;
logDebug(msg.str().c_str());
joint_poses.push_back(joint_pose);
}
else
{
std::stringstream msg;
msg << "Found *potential* solution on " << sample_iter << " iteration, joint: " << joint_pose;
logDebug(msg.str().c_str());
std::vector<std::vector<double> >::iterator joint_pose_it;
bool match_found = false;
for(joint_pose_it = joint_poses.begin(); joint_pose_it != joint_poses.end(); ++joint_pose_it)
{
if( descartes_core::utils::equal(joint_pose, (*joint_pose_it), epsilon) )
{
logDebug("Found matching, potential solution is not new");
match_found = true;
break;
}
}
if (!match_found)
{
std::stringstream msg;
msg << "Found *new* solution on " << sample_iter << " iteration, joint: " << joint_pose;
logDebug(msg.str().c_str());
joint_poses.push_back(joint_pose);
}
}
}
}
logDebug("Found %d joint solutions out of %d iterations", joint_poses.size(), seed_states_.size());
if (joint_poses.empty())
{
logError("Found 0 joint solutions out of %d iterations", seed_states_.size());
return false;
}
else
{
logInform("Found %d joint solutions out of %d iterations", joint_poses.size(), seed_states_.size());
return true;
}
}
bool MoveitStateAdapter::isInCollision(const std::vector<double>& joint_pose) const
{
bool in_collision = false;
if(check_collisions_)
{
robot_state_->setJointGroupPositions(group_name_, joint_pose);
in_collision = planning_scene_->isStateColliding(*robot_state_,group_name_);
}
return in_collision;
}
bool MoveitStateAdapter::getFK(const std::vector<double> &joint_pose, Eigen::Affine3d &pose) const
{
bool rtn = false;
robot_state_->setJointGroupPositions(group_name_, joint_pose);
if ( isValid(joint_pose) )
{
if (robot_state_->knowsFrameTransform(tool_frame_))
{
pose = world_to_root_.frame*robot_state_->getFrameTransform(tool_frame_);
rtn = true;
}
else
{
logError("Robot state does not recognize tool frame: %s", tool_frame_.c_str());
rtn = false;
}
}
else
{
logError("Invalid joint pose passed to get forward kinematics");
rtn = false;
}
std::stringstream msg;
msg << "Returning the pose " << std::endl << pose.matrix() << std::endl
<< "For joint pose: " << joint_pose;
logDebug(msg.str().c_str());
return rtn;
}
bool MoveitStateAdapter::isValid(const std::vector<double> &joint_pose) const
{
bool rtn = false;
if (robot_state_->getJointModelGroup(group_name_)->getActiveJointModels().size() ==
joint_pose.size())
{
robot_state_->setJointGroupPositions(group_name_, joint_pose);
//TODO: At some point velocities and accelerations should be set for the group as
//well.
robot_state_->setVariableVelocities(std::vector<double>(joint_pose.size(), 0.));
robot_state_->setVariableAccelerations(std::vector<double>(joint_pose.size(), 0.));
if (robot_state_->satisfiesBounds())
{
rtn = true;
}
else
{
std::stringstream msg;
msg << "Joint pose: " << joint_pose << ", outside joint boundaries";
logDebug(msg.str().c_str());
}
if(isInCollision(joint_pose))
{
ROS_DEBUG_STREAM("Robot is in collision at this joint pose");
rtn = false;
}
}
else
{
logError("Size of joint pose: %d doesn't match robot state variable size: %d",
joint_pose.size(),
robot_state_->getJointModelGroup(group_name_)->getActiveJointModels().size());
rtn = false;
}
return rtn;
}
bool MoveitStateAdapter::isValid(const Eigen::Affine3d &pose) const
{
//TODO: Could check robot extents first as a quick check
std::vector<double> dummy;
return getIK(pose, dummy);
}
int MoveitStateAdapter::getDOF() const
{
const moveit::core::JointModelGroup* group;
group = robot_state_->getJointModelGroup(group_name_);
return group->getVariableCount();
}
bool MoveitStateAdapter::isValidMove(const std::vector<double>& from_joint_pose,
const std::vector<double>& to_joint_pose,
double dt) const
{
std::vector<double> max_joint_deltas;
max_joint_deltas.reserve(velocity_limits_.size());
// Check for equal sized arrays
if (from_joint_pose.size() != to_joint_pose.size())
{
ROS_DEBUG_STREAM("To and From joint poses are of different sizes.");
return false;
}
// Build a vector of the maximum angle delta per joint
for (std::vector<double>::const_iterator it = velocity_limits_.begin(); it != velocity_limits_.end(); ++it)
{
max_joint_deltas.push_back((*it) * dt);
}
for (std::vector<double>::size_type i = 0; i < from_joint_pose.size(); ++i)
{
if ( std::abs(from_joint_pose[i] - to_joint_pose[i]) > max_joint_deltas[i] )
{
return false;
}
}
return true;
}
} //descartes_moveit
<commit_msg>Changed the getJointVelocityLimits function to check the type of the joint instead of the bounds size()<commit_after>/*
* Software License Agreement (Apache License)
*
* Copyright (c) 2014, Dan Solomon
*
* 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 <console_bridge/console.h>
#include "descartes_moveit/moveit_state_adapter.h"
#include "eigen_conversions/eigen_msg.h"
#include "random_numbers/random_numbers.h"
#include "descartes_core/pretty_print.hpp"
#include "descartes_moveit/seed_search.h"
#include <sstream>
const static int SAMPLE_ITERATIONS = 10;
namespace
{
bool getJointVelocityLimits(const moveit::core::RobotState& state,
const std::string& group_name,
std::vector<double>& output)
{
std::vector<double> result;
auto models = state.getJointModelGroup(group_name)->getActiveJointModels();
for (const moveit::core::JointModel* model : models)
{
const auto& bounds = model->getVariableBounds();
// Check to see if there is a single bounds constraint (more might indicate
// not revolute joint)
if (model->getType() != moveit::core::JointModel::REVOLUTE &&
model->getType() != moveit::core::JointModel::PRISMATIC)
{
ROS_ERROR_STREAM(__FUNCTION__ << " Unexpected joint type. Currently works only with single axis prismatic or revolute joints.");
return false;
}
else
{
result.push_back(bounds[0].max_velocity_);
}
}
output = result;
return true;
}
} // end anon namespace
namespace descartes_moveit
{
MoveitStateAdapter::MoveitStateAdapter()
{}
MoveitStateAdapter::MoveitStateAdapter(const moveit::core::RobotState & robot_state, const std::string & group_name,
const std::string & tool_frame, const std::string & world_frame) :
robot_state_(new moveit::core::RobotState(robot_state)),
group_name_(group_name),
tool_frame_(tool_frame),
world_frame_(world_frame),
world_to_root_(Eigen::Affine3d::Identity())
{
ROS_INFO_STREAM("Generated random seeds");
seed_states_ = seed::findRandomSeeds(*robot_state_, group_name_, SAMPLE_ITERATIONS);
const moveit::core::JointModelGroup* joint_model_group_ptr = robot_state_->getJointModelGroup(group_name);
if (joint_model_group_ptr)
{
// Find the velocity limits
if (!getJointVelocityLimits(*robot_state_, group_name, velocity_limits_))
{
logWarn("Could not determine velocity limits of RobotModel from MoveIt");
}
joint_model_group_ptr->printGroupInfo();
const std::vector<std::string>& link_names = joint_model_group_ptr->getLinkModelNames();
if (tool_frame_ != link_names.back())
{
logWarn("Tool frame '%s' does not match group tool frame '%s', functionality will be implemented in the future",
tool_frame_.c_str(), link_names.back().c_str());
}
if (world_frame_ != robot_state_->getRobotModel()->getModelFrame())
{
logWarn("World frame '%s' does not match model root frame '%s', all poses will be transformed to world frame '%s'",
world_frame_.c_str(), link_names.front().c_str(),world_frame_.c_str());
Eigen::Affine3d root_to_world = robot_state_->getFrameTransform(world_frame_);
world_to_root_ = descartes_core::Frame(root_to_world.inverse());
}
}
else
{
logError("Joint group: %s does not exist in robot model", group_name_.c_str());
std::stringstream msg;
msg << "Possible group names: " << robot_state_->getRobotModel()->getJointModelGroupNames();
logError(msg.str().c_str());
}
return;
}
bool MoveitStateAdapter::initialize(const std::string& robot_description, const std::string& group_name,
const std::string& world_frame,const std::string& tcp_frame)
{
robot_model_loader_.reset(new robot_model_loader::RobotModelLoader(robot_description));
robot_model_ptr_ = robot_model_loader_->getModel();
robot_state_.reset(new moveit::core::RobotState(robot_model_ptr_));
planning_scene_.reset(new planning_scene::PlanningScene(robot_model_loader_->getModel()));
group_name_ = group_name;
tool_frame_ = tcp_frame;
world_frame_ = world_frame;
if (seed_states_.empty())
{
seed_states_ = seed::findRandomSeeds(*robot_state_, group_name_, SAMPLE_ITERATIONS);
ROS_INFO_STREAM("Generated "<<seed_states_.size()<< " random seeds");
}
// Find the velocity limits
if (!getJointVelocityLimits(*robot_state_, group_name, velocity_limits_))
{
logWarn("Could not determine velocity limits of RobotModel from MoveIt");
}
const moveit::core::JointModelGroup* joint_model_group_ptr = robot_state_->getJointModelGroup(group_name);
if (joint_model_group_ptr)
{
joint_model_group_ptr->printGroupInfo();
const std::vector<std::string>& link_names = joint_model_group_ptr->getLinkModelNames();
if (tool_frame_ != link_names.back())
{
logWarn("Tool frame '%s' does not match group tool frame '%s', functionality will be implemented in the future",
tool_frame_.c_str(), link_names.back().c_str());
}
if (world_frame_ != robot_state_->getRobotModel()->getModelFrame())
{
logWarn("World frame '%s' does not match model root frame '%s', all poses will be transformed to world frame '%s'",
world_frame_.c_str(), robot_state_->getRobotModel()->getModelFrame().c_str(),world_frame_.c_str());
Eigen::Affine3d root_to_world = robot_state_->getFrameTransform(world_frame_);
world_to_root_ = descartes_core::Frame(root_to_world.inverse());
}
}
else
{
logError("Joint group: %s does not exist in robot model", group_name_.c_str());
std::stringstream msg;
msg << "Possible group names: " << robot_state_->getRobotModel()->getJointModelGroupNames();
logError(msg.str().c_str());
}
return true;
}
bool MoveitStateAdapter::getIK(const Eigen::Affine3d &pose, const std::vector<double> &seed_state,
std::vector<double> &joint_pose) const
{
robot_state_->setJointGroupPositions(group_name_, seed_state);
return getIK(pose, joint_pose);
}
bool MoveitStateAdapter::getIK(const Eigen::Affine3d &pose, std::vector<double> &joint_pose) const
{
bool rtn = false;
// transform to group base
Eigen::Affine3d tool_pose = world_to_root_.frame* pose;
if (robot_state_->setFromIK(robot_state_->getJointModelGroup(group_name_), tool_pose,
tool_frame_))
{
robot_state_->copyJointGroupPositions(group_name_, joint_pose);
if(!isValid(joint_pose))
{
ROS_DEBUG_STREAM("Robot joint pose is invalid");
}
else
{
rtn = true;
}
}
else
{
rtn = false;
}
return rtn;
}
bool MoveitStateAdapter::getAllIK(const Eigen::Affine3d &pose, std::vector<std::vector<double> > &joint_poses) const
{
//The minimum difference between solutions should be greater than the search discretization
//used by the IK solver. This value is multiplied by 4 to remove any chance that a solution
//in the middle of a discretization step could be double counted. In reality, we'd like solutions
//to be further apart than this.
double epsilon = 4 * robot_state_->getRobotModel()->getJointModelGroup(group_name_)->getSolverInstance()->
getSearchDiscretization();
logDebug("Utilizing an min. difference of %f between IK solutions", epsilon);
joint_poses.clear();
for (size_t sample_iter = 0; sample_iter < seed_states_.size(); ++sample_iter)
{
robot_state_->setJointGroupPositions(group_name_, seed_states_[sample_iter]);
std::vector<double> joint_pose;
if (getIK(pose, joint_pose))
{
if( joint_poses.empty())
{
std::stringstream msg;
msg << "Found *first* solution on " << sample_iter << " iteration, joint: " << joint_pose;
logDebug(msg.str().c_str());
joint_poses.push_back(joint_pose);
}
else
{
std::stringstream msg;
msg << "Found *potential* solution on " << sample_iter << " iteration, joint: " << joint_pose;
logDebug(msg.str().c_str());
std::vector<std::vector<double> >::iterator joint_pose_it;
bool match_found = false;
for(joint_pose_it = joint_poses.begin(); joint_pose_it != joint_poses.end(); ++joint_pose_it)
{
if( descartes_core::utils::equal(joint_pose, (*joint_pose_it), epsilon) )
{
logDebug("Found matching, potential solution is not new");
match_found = true;
break;
}
}
if (!match_found)
{
std::stringstream msg;
msg << "Found *new* solution on " << sample_iter << " iteration, joint: " << joint_pose;
logDebug(msg.str().c_str());
joint_poses.push_back(joint_pose);
}
}
}
}
logDebug("Found %d joint solutions out of %d iterations", joint_poses.size(), seed_states_.size());
if (joint_poses.empty())
{
logError("Found 0 joint solutions out of %d iterations", seed_states_.size());
return false;
}
else
{
logInform("Found %d joint solutions out of %d iterations", joint_poses.size(), seed_states_.size());
return true;
}
}
bool MoveitStateAdapter::isInCollision(const std::vector<double>& joint_pose) const
{
bool in_collision = false;
if(check_collisions_)
{
robot_state_->setJointGroupPositions(group_name_, joint_pose);
in_collision = planning_scene_->isStateColliding(*robot_state_,group_name_);
}
return in_collision;
}
bool MoveitStateAdapter::getFK(const std::vector<double> &joint_pose, Eigen::Affine3d &pose) const
{
bool rtn = false;
robot_state_->setJointGroupPositions(group_name_, joint_pose);
if ( isValid(joint_pose) )
{
if (robot_state_->knowsFrameTransform(tool_frame_))
{
pose = world_to_root_.frame*robot_state_->getFrameTransform(tool_frame_);
rtn = true;
}
else
{
logError("Robot state does not recognize tool frame: %s", tool_frame_.c_str());
rtn = false;
}
}
else
{
logError("Invalid joint pose passed to get forward kinematics");
rtn = false;
}
std::stringstream msg;
msg << "Returning the pose " << std::endl << pose.matrix() << std::endl
<< "For joint pose: " << joint_pose;
logDebug(msg.str().c_str());
return rtn;
}
bool MoveitStateAdapter::isValid(const std::vector<double> &joint_pose) const
{
bool rtn = false;
if (robot_state_->getJointModelGroup(group_name_)->getActiveJointModels().size() ==
joint_pose.size())
{
robot_state_->setJointGroupPositions(group_name_, joint_pose);
//TODO: At some point velocities and accelerations should be set for the group as
//well.
robot_state_->setVariableVelocities(std::vector<double>(joint_pose.size(), 0.));
robot_state_->setVariableAccelerations(std::vector<double>(joint_pose.size(), 0.));
if (robot_state_->satisfiesBounds())
{
rtn = true;
}
else
{
std::stringstream msg;
msg << "Joint pose: " << joint_pose << ", outside joint boundaries";
logDebug(msg.str().c_str());
}
if(isInCollision(joint_pose))
{
ROS_DEBUG_STREAM("Robot is in collision at this joint pose");
rtn = false;
}
}
else
{
logError("Size of joint pose: %d doesn't match robot state variable size: %d",
joint_pose.size(),
robot_state_->getJointModelGroup(group_name_)->getActiveJointModels().size());
rtn = false;
}
return rtn;
}
bool MoveitStateAdapter::isValid(const Eigen::Affine3d &pose) const
{
//TODO: Could check robot extents first as a quick check
std::vector<double> dummy;
return getIK(pose, dummy);
}
int MoveitStateAdapter::getDOF() const
{
const moveit::core::JointModelGroup* group;
group = robot_state_->getJointModelGroup(group_name_);
return group->getVariableCount();
}
bool MoveitStateAdapter::isValidMove(const std::vector<double>& from_joint_pose,
const std::vector<double>& to_joint_pose,
double dt) const
{
std::vector<double> max_joint_deltas;
max_joint_deltas.reserve(velocity_limits_.size());
// Check for equal sized arrays
if (from_joint_pose.size() != to_joint_pose.size())
{
ROS_ERROR_STREAM("To and From joint poses are of different sizes.");
return false;
}
// Build a vector of the maximum angle delta per joint
for (std::vector<double>::const_iterator it = velocity_limits_.begin(); it != velocity_limits_.end(); ++it)
{
max_joint_deltas.push_back((*it) * dt);
}
for (std::vector<double>::size_type i = 0; i < from_joint_pose.size(); ++i)
{
if ( std::abs(from_joint_pose[i] - to_joint_pose[i]) > max_joint_deltas[i] )
{
return false;
}
}
return true;
}
} //descartes_moveit
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkClipDataSet.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=========================================================================*/
#include <math.h>
#include "vtkClipDataSet.h"
#include "vtkMergePoints.h"
#include "vtkObjectFactory.h"
//--------------------------------------------------------------------------
vtkClipDataSet* vtkClipDataSet::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkClipDataSet");
if(ret)
{
return (vtkClipDataSet*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkClipDataSet;
}
//----------------------------------------------------------------------------
// Construct with user-specified implicit function; InsideOut turned off; value
// set to 0.0; and generate clip scalars turned off.
vtkClipDataSet::vtkClipDataSet(vtkImplicitFunction *cf)
{
this->ClipFunction = cf;
this->InsideOut = 0;
this->Locator = NULL;
this->Value = 0.0;
this->GenerateClipScalars = 0;
this->GenerateClippedOutput = 0;
this->vtkSource::SetNthOutput(1,vtkUnstructuredGrid::New());
this->Outputs[1]->Delete();
}
//----------------------------------------------------------------------------
vtkClipDataSet::~vtkClipDataSet()
{
if ( this->Locator )
{
this->Locator->UnRegister(this);
this->Locator = NULL;
}
this->SetClipFunction(NULL);
}
//----------------------------------------------------------------------------
// Overload standard modified time function. If Clip functions is modified,
// then this object is modified as well.
unsigned long vtkClipDataSet::GetMTime()
{
unsigned long mTime=this->vtkDataSetToUnstructuredGridFilter::GetMTime();
unsigned long time;
if ( this->ClipFunction != NULL )
{
time = this->ClipFunction->GetMTime();
mTime = ( time > mTime ? time : mTime );
}
if ( this->Locator != NULL )
{
time = this->Locator->GetMTime();
mTime = ( time > mTime ? time : mTime );
}
return mTime;
}
vtkUnstructuredGrid *vtkClipDataSet::GetClippedOutput()
{
if (this->NumberOfOutputs < 2)
{
return NULL;
}
return (vtkUnstructuredGrid *)(this->Outputs[1]);
}
//----------------------------------------------------------------------------
//
// Clip through data generating surface.
//
void vtkClipDataSet::Execute()
{
vtkDataSet *input = this->GetInput();
vtkUnstructuredGrid *output = this->GetOutput();
vtkUnstructuredGrid *clippedOutput = this->GetClippedOutput();
int numPts = input->GetNumberOfPoints();
int numCells = input->GetNumberOfCells();
vtkPointData *inPD=input->GetPointData(), *outPD = output->GetPointData();
vtkCellData *inCD=input->GetCellData();
vtkCellData *outCD[2];
vtkPoints *newPoints;
vtkScalars *cellScalars;
vtkScalars *clipScalars;
vtkPoints *cellPts;
vtkIdList *cellIds;
float s;
int npts, *pts;
int cellType = 0;
int i, j;
int estimatedSize;
vtkUnsignedCharArray *types[2];
vtkIntArray *locs[2];
vtkDebugMacro(<< "Clipping dataset");
// Initialize self; create output objects
//
if ( numPts < 1 )
{
//vtkErrorMacro(<<"No data to clip");
return;
}
if ( !this->ClipFunction && this->GenerateClipScalars )
{
vtkErrorMacro(<<"Cannot generate clip scalars if no clip function defined");
return;
}
// allocate the output and associated helper classes
estimatedSize = numCells;
estimatedSize = estimatedSize / 1024 * 1024; //multiple of 1024
if (estimatedSize < 1024)
{
estimatedSize = 1024;
}
cellScalars = vtkScalars::New();
cellScalars->Allocate(VTK_CELL_SIZE);
vtkCellArray *conn[2];
conn[0] = vtkCellArray::New();
conn[0]->Allocate(estimatedSize,estimatedSize/2);
conn[0]->InitTraversal();
types[0] = vtkUnsignedCharArray::New();
types[0]->Allocate(estimatedSize,estimatedSize/2);
locs[0] = vtkIntArray::New();
locs[0]->Allocate(estimatedSize,estimatedSize/2);
if ( this->GenerateClippedOutput )
{
conn[1] = vtkCellArray::New();
conn[1]->Allocate(estimatedSize,estimatedSize/2);
conn[1]->InitTraversal();
types[1] = vtkUnsignedCharArray::New();
types[1]->Allocate(estimatedSize,estimatedSize/2);
locs[1] = vtkIntArray::New();
locs[1]->Allocate(estimatedSize,estimatedSize/2);
}
newPoints = vtkPoints::New();
newPoints->Allocate(numPts,numPts/2);
// locator used to merge potentially duplicate points
if ( this->Locator == NULL )
{
this->CreateDefaultLocator();
}
this->Locator->InitPointInsertion (newPoints, input->GetBounds());
// Determine whether we're clipping with input scalars or a clip function
// and do necessary setup.
if ( this->ClipFunction )
{
vtkScalars *tmpScalars = vtkScalars::New();
tmpScalars->SetNumberOfScalars(numPts);
inPD = vtkPointData::New();
inPD->ShallowCopy(input->GetPointData());//copies original
if ( this->GenerateClipScalars )
{
inPD->SetScalars(tmpScalars);
}
for ( i=0; i < numPts; i++ )
{
s = this->ClipFunction->FunctionValue(input->GetPoint(i));
tmpScalars->SetScalar(i,s);
}
clipScalars = (vtkScalars *)tmpScalars;
}
else //using input scalars
{
clipScalars = inPD->GetScalars();
if ( !clipScalars )
{
vtkErrorMacro(<<"Cannot clip without clip function or input scalars");
return;
}
}
if ( !this->GenerateClipScalars && !input->GetPointData()->GetScalars())
{
outPD->CopyScalarsOff();
}
else
{
outPD->CopyScalarsOn();
}
outPD->InterpolateAllocate(inPD,estimatedSize,estimatedSize/2);
outCD[0] = output->GetCellData();
outCD[0]->CopyAllocate(inCD,estimatedSize,estimatedSize/2);
if ( this->GenerateClippedOutput )
{
outCD[1] = clippedOutput->GetCellData();
outCD[1]->CopyAllocate(inCD,estimatedSize,estimatedSize/2);
}
//Process all cells and clip each in turn
//
int abort=0;
int updateTime = numCells/20 + 1; // update roughly every 5%
vtkGenericCell *cell = vtkGenericCell::New();
int num[2]; num[0]=num[1]=0;
int numNew[2]; numNew[0]=numNew[1]=0;
for (int cellId=0; cellId < numCells && !abort; cellId++)
{
if ( !(cellId % updateTime) )
{
this->UpdateProgress((float)cellId / numCells);
abort = this->GetAbortExecute();
}
input->GetCell(cellId,cell);
cellPts = cell->GetPoints();
cellIds = cell->GetPointIds();
npts = cellPts->GetNumberOfPoints();
// evaluate implicit cutting function
for ( i=0; i < npts; i++ )
{
s = clipScalars->GetScalar(cellIds->GetId(i));
cellScalars->InsertScalar(i, s);
}
// perform the clipping
cell->Clip(this->Value, cellScalars, this->Locator, conn[0],
inPD, outPD, inCD, cellId, outCD[0], this->InsideOut);
numNew[0] = conn[0]->GetNumberOfCells() - num[0];
num[0] = conn[0]->GetNumberOfCells();
if ( this->GenerateClippedOutput )
{
cell->Clip(this->Value, cellScalars, this->Locator, conn[1],
inPD, outPD, inCD, cellId, outCD[1], !this->InsideOut);
numNew[1] = conn[1]->GetNumberOfCells() - num[1];
num[1] = conn[1]->GetNumberOfCells();
}
for (i=0; i<2; i++) //for both outputs
{
for (j=0; j < numNew[i]; j++)
{
locs[i]->InsertNextValue(conn[i]->GetTraversalLocation());
conn[i]->GetNextCell(npts,pts);
//For each new cell added, got to set the type of the cell
switch ( cell->GetCellDimension() )
{
case 0: //points are generated-------------------------------
cellType = (npts > 1 ? VTK_POLY_VERTEX : VTK_VERTEX);
break;
case 1: //lines are generated----------------------------------
cellType = (npts > 2 ? VTK_POLY_LINE : VTK_LINE);
break;
case 2: //polygons are generated------------------------------
cellType = (npts == 3 ? VTK_TRIANGLE :
(npts == 4 ? VTK_QUAD : VTK_POLYGON));
break;
case 3: //tetrahedra are generated------------------------------
cellType = VTK_TETRA;
break;
} //switch
types[i]->InsertNextValue(cellType);
} //for each new cell
} //for both outputs
} //for each cell
cell->Delete();
cellScalars->Delete();
if ( this->ClipFunction )
{
clipScalars->Delete();
inPD->Delete();
}
output->SetPoints(newPoints);
output->SetCells(types[0], locs[0], conn[0]);
conn[0]->Delete();
types[0]->Delete();
locs[0]->Delete();
if ( this->GenerateClippedOutput )
{
clippedOutput->SetPoints(newPoints);
clippedOutput->SetCells(types[1], locs[1], conn[1]);
conn[1]->Delete();
types[1]->Delete();
locs[1]->Delete();
}
newPoints->Delete();
this->Locator->Initialize();//release any extra memory
output->Squeeze();
}
//----------------------------------------------------------------------------
// Specify a spatial locator for merging points. By default,
// an instance of vtkMergePoints is used.
void vtkClipDataSet::SetLocator(vtkPointLocator *locator)
{
if ( this->Locator == locator)
{
return;
}
if ( this->Locator )
{
this->Locator->UnRegister(this);
this->Locator = NULL;
}
if ( locator )
{
locator->Register(this);
}
this->Locator = locator;
this->Modified();
}
//----------------------------------------------------------------------------
void vtkClipDataSet::CreateDefaultLocator()
{
if ( this->Locator == NULL )
{
this->Locator = vtkMergePoints::New();
}
}
//----------------------------------------------------------------------------
void vtkClipDataSet::PrintSelf(ostream& os, vtkIndent indent)
{
vtkDataSetToUnstructuredGridFilter::PrintSelf(os,indent);
if ( this->ClipFunction )
{
os << indent << "Clip Function: " << this->ClipFunction << "\n";
}
else
{
os << indent << "Clip Function: (none)\n";
}
os << indent << "InsideOut: " << (this->InsideOut ? "On\n" : "Off\n");
os << indent << "Value: " << this->Value << "\n";
if ( this->Locator )
{
os << indent << "Locator: " << this->Locator << "\n";
}
else
{
os << indent << "Locator: (none)\n";
}
os << indent << "Generate Clip Scalars: "
<< (this->GenerateClipScalars ? "On\n" : "Off\n");
os << indent << "Generate Clipped Output: "
<< (this->GenerateClippedOutput ? "On\n" : "Off\n");
}
<commit_msg>ERR:Bug if only one output is produced<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkClipDataSet.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
=========================================================================*/
#include <math.h>
#include "vtkClipDataSet.h"
#include "vtkMergePoints.h"
#include "vtkObjectFactory.h"
//--------------------------------------------------------------------------
vtkClipDataSet* vtkClipDataSet::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkClipDataSet");
if(ret)
{
return (vtkClipDataSet*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkClipDataSet;
}
//----------------------------------------------------------------------------
// Construct with user-specified implicit function; InsideOut turned off; value
// set to 0.0; and generate clip scalars turned off.
vtkClipDataSet::vtkClipDataSet(vtkImplicitFunction *cf)
{
this->ClipFunction = cf;
this->InsideOut = 0;
this->Locator = NULL;
this->Value = 0.0;
this->GenerateClipScalars = 0;
this->GenerateClippedOutput = 0;
this->vtkSource::SetNthOutput(1,vtkUnstructuredGrid::New());
this->Outputs[1]->Delete();
}
//----------------------------------------------------------------------------
vtkClipDataSet::~vtkClipDataSet()
{
if ( this->Locator )
{
this->Locator->UnRegister(this);
this->Locator = NULL;
}
this->SetClipFunction(NULL);
}
//----------------------------------------------------------------------------
// Overload standard modified time function. If Clip functions is modified,
// then this object is modified as well.
unsigned long vtkClipDataSet::GetMTime()
{
unsigned long mTime=this->vtkDataSetToUnstructuredGridFilter::GetMTime();
unsigned long time;
if ( this->ClipFunction != NULL )
{
time = this->ClipFunction->GetMTime();
mTime = ( time > mTime ? time : mTime );
}
if ( this->Locator != NULL )
{
time = this->Locator->GetMTime();
mTime = ( time > mTime ? time : mTime );
}
return mTime;
}
vtkUnstructuredGrid *vtkClipDataSet::GetClippedOutput()
{
if (this->NumberOfOutputs < 2)
{
return NULL;
}
return (vtkUnstructuredGrid *)(this->Outputs[1]);
}
//----------------------------------------------------------------------------
//
// Clip through data generating surface.
//
void vtkClipDataSet::Execute()
{
vtkDataSet *input = this->GetInput();
vtkUnstructuredGrid *output = this->GetOutput();
vtkUnstructuredGrid *clippedOutput = this->GetClippedOutput();
int numPts = input->GetNumberOfPoints();
int numCells = input->GetNumberOfCells();
vtkPointData *inPD=input->GetPointData(), *outPD = output->GetPointData();
vtkCellData *inCD=input->GetCellData();
vtkCellData *outCD[2];
vtkPoints *newPoints;
vtkScalars *cellScalars;
vtkScalars *clipScalars;
vtkPoints *cellPts;
vtkIdList *cellIds;
float s;
int npts, *pts;
int cellType = 0;
int i, j;
int estimatedSize;
vtkUnsignedCharArray *types[2];
vtkIntArray *locs[2];
int numOutputs = 1;
vtkDebugMacro(<< "Clipping dataset");
// Initialize self; create output objects
//
if ( numPts < 1 )
{
//vtkErrorMacro(<<"No data to clip");
return;
}
if ( !this->ClipFunction && this->GenerateClipScalars )
{
vtkErrorMacro(<<"Cannot generate clip scalars if no clip function defined");
return;
}
// allocate the output and associated helper classes
estimatedSize = numCells;
estimatedSize = estimatedSize / 1024 * 1024; //multiple of 1024
if (estimatedSize < 1024)
{
estimatedSize = 1024;
}
cellScalars = vtkScalars::New();
cellScalars->Allocate(VTK_CELL_SIZE);
vtkCellArray *conn[2];
conn[0] = vtkCellArray::New();
conn[0]->Allocate(estimatedSize,estimatedSize/2);
conn[0]->InitTraversal();
types[0] = vtkUnsignedCharArray::New();
types[0]->Allocate(estimatedSize,estimatedSize/2);
locs[0] = vtkIntArray::New();
locs[0]->Allocate(estimatedSize,estimatedSize/2);
if ( this->GenerateClippedOutput )
{
numOutputs = 2;
conn[1] = vtkCellArray::New();
conn[1]->Allocate(estimatedSize,estimatedSize/2);
conn[1]->InitTraversal();
types[1] = vtkUnsignedCharArray::New();
types[1]->Allocate(estimatedSize,estimatedSize/2);
locs[1] = vtkIntArray::New();
locs[1]->Allocate(estimatedSize,estimatedSize/2);
}
newPoints = vtkPoints::New();
newPoints->Allocate(numPts,numPts/2);
// locator used to merge potentially duplicate points
if ( this->Locator == NULL )
{
this->CreateDefaultLocator();
}
this->Locator->InitPointInsertion (newPoints, input->GetBounds());
// Determine whether we're clipping with input scalars or a clip function
// and do necessary setup.
if ( this->ClipFunction )
{
vtkScalars *tmpScalars = vtkScalars::New();
tmpScalars->SetNumberOfScalars(numPts);
inPD = vtkPointData::New();
inPD->ShallowCopy(input->GetPointData());//copies original
if ( this->GenerateClipScalars )
{
inPD->SetScalars(tmpScalars);
}
for ( i=0; i < numPts; i++ )
{
s = this->ClipFunction->FunctionValue(input->GetPoint(i));
tmpScalars->SetScalar(i,s);
}
clipScalars = (vtkScalars *)tmpScalars;
}
else //using input scalars
{
clipScalars = inPD->GetScalars();
if ( !clipScalars )
{
vtkErrorMacro(<<"Cannot clip without clip function or input scalars");
return;
}
}
if ( !this->GenerateClipScalars && !input->GetPointData()->GetScalars())
{
outPD->CopyScalarsOff();
}
else
{
outPD->CopyScalarsOn();
}
outPD->InterpolateAllocate(inPD,estimatedSize,estimatedSize/2);
outCD[0] = output->GetCellData();
outCD[0]->CopyAllocate(inCD,estimatedSize,estimatedSize/2);
if ( this->GenerateClippedOutput )
{
outCD[1] = clippedOutput->GetCellData();
outCD[1]->CopyAllocate(inCD,estimatedSize,estimatedSize/2);
}
//Process all cells and clip each in turn
//
int abort=0;
int updateTime = numCells/20 + 1; // update roughly every 5%
vtkGenericCell *cell = vtkGenericCell::New();
int num[2]; num[0]=num[1]=0;
int numNew[2]; numNew[0]=numNew[1]=0;
for (int cellId=0; cellId < numCells && !abort; cellId++)
{
if ( !(cellId % updateTime) )
{
this->UpdateProgress((float)cellId / numCells);
abort = this->GetAbortExecute();
}
input->GetCell(cellId,cell);
cellPts = cell->GetPoints();
cellIds = cell->GetPointIds();
npts = cellPts->GetNumberOfPoints();
// evaluate implicit cutting function
for ( i=0; i < npts; i++ )
{
s = clipScalars->GetScalar(cellIds->GetId(i));
cellScalars->InsertScalar(i, s);
}
// perform the clipping
cell->Clip(this->Value, cellScalars, this->Locator, conn[0],
inPD, outPD, inCD, cellId, outCD[0], this->InsideOut);
numNew[0] = conn[0]->GetNumberOfCells() - num[0];
num[0] = conn[0]->GetNumberOfCells();
if ( this->GenerateClippedOutput )
{
cell->Clip(this->Value, cellScalars, this->Locator, conn[1],
inPD, outPD, inCD, cellId, outCD[1], !this->InsideOut);
numNew[1] = conn[1]->GetNumberOfCells() - num[1];
num[1] = conn[1]->GetNumberOfCells();
}
for (i=0; i<numOutputs; i++) //for both outputs
{
for (j=0; j < numNew[i]; j++)
{
locs[i]->InsertNextValue(conn[i]->GetTraversalLocation());
conn[i]->GetNextCell(npts,pts);
//For each new cell added, got to set the type of the cell
switch ( cell->GetCellDimension() )
{
case 0: //points are generated-------------------------------
cellType = (npts > 1 ? VTK_POLY_VERTEX : VTK_VERTEX);
break;
case 1: //lines are generated----------------------------------
cellType = (npts > 2 ? VTK_POLY_LINE : VTK_LINE);
break;
case 2: //polygons are generated------------------------------
cellType = (npts == 3 ? VTK_TRIANGLE :
(npts == 4 ? VTK_QUAD : VTK_POLYGON));
break;
case 3: //tetrahedra are generated------------------------------
cellType = VTK_TETRA;
break;
} //switch
types[i]->InsertNextValue(cellType);
} //for each new cell
} //for both outputs
} //for each cell
cell->Delete();
cellScalars->Delete();
if ( this->ClipFunction )
{
clipScalars->Delete();
inPD->Delete();
}
output->SetPoints(newPoints);
output->SetCells(types[0], locs[0], conn[0]);
conn[0]->Delete();
types[0]->Delete();
locs[0]->Delete();
if ( this->GenerateClippedOutput )
{
clippedOutput->SetPoints(newPoints);
clippedOutput->SetCells(types[1], locs[1], conn[1]);
conn[1]->Delete();
types[1]->Delete();
locs[1]->Delete();
}
newPoints->Delete();
this->Locator->Initialize();//release any extra memory
output->Squeeze();
}
//----------------------------------------------------------------------------
// Specify a spatial locator for merging points. By default,
// an instance of vtkMergePoints is used.
void vtkClipDataSet::SetLocator(vtkPointLocator *locator)
{
if ( this->Locator == locator)
{
return;
}
if ( this->Locator )
{
this->Locator->UnRegister(this);
this->Locator = NULL;
}
if ( locator )
{
locator->Register(this);
}
this->Locator = locator;
this->Modified();
}
//----------------------------------------------------------------------------
void vtkClipDataSet::CreateDefaultLocator()
{
if ( this->Locator == NULL )
{
this->Locator = vtkMergePoints::New();
}
}
//----------------------------------------------------------------------------
void vtkClipDataSet::PrintSelf(ostream& os, vtkIndent indent)
{
vtkDataSetToUnstructuredGridFilter::PrintSelf(os,indent);
if ( this->ClipFunction )
{
os << indent << "Clip Function: " << this->ClipFunction << "\n";
}
else
{
os << indent << "Clip Function: (none)\n";
}
os << indent << "InsideOut: " << (this->InsideOut ? "On\n" : "Off\n");
os << indent << "Value: " << this->Value << "\n";
if ( this->Locator )
{
os << indent << "Locator: " << this->Locator << "\n";
}
else
{
os << indent << "Locator: (none)\n";
}
os << indent << "Generate Clip Scalars: "
<< (this->GenerateClipScalars ? "On\n" : "Off\n");
os << indent << "Generate Clipped Output: "
<< (this->GenerateClippedOutput ? "On\n" : "Off\n");
}
<|endoftext|> |
<commit_before>//
// PROJECT: Aspia
// FILE: client/file_transfer.cc
// LICENSE: GNU General Public License 3
// PROGRAMMERS: Dmitry Chapyshev ([email protected])
//
#include "client/file_transfer.h"
#include "client/file_status.h"
#include "client/file_transfer_queue_builder.h"
namespace aspia {
FileTransfer::FileTransfer(Type type, QObject* parent)
: QObject(parent),
type_(type)
{
actions_.insert(OtherError, QPair<Actions, Action>(Abort, Ask));
actions_.insert(DirectoryCreateError,
QPair<Actions, Action>(Abort | Skip | SkipAll, Ask));
actions_.insert(FileCreateError,
QPair<Actions, Action>(Abort | Skip | SkipAll, Ask));
actions_.insert(FileOpenError,
QPair<Actions, Action>(Abort | Skip | SkipAll, Ask));
actions_.insert(FileAlreadyExists,
QPair<Actions, Action>(Abort | Skip | SkipAll | Replace | ReplaceAll, Ask));
actions_.insert(FileWriteError,
QPair<Actions, Action>(Abort | Skip | SkipAll, Ask));
actions_.insert(FileReadError,
QPair<Actions, Action>(Abort | Skip | SkipAll, Ask));
}
void FileTransfer::start(const QString& source_path,
const QString& target_path,
const QList<Item>& items)
{
builder_ = new FileTransferQueueBuilder();
connect(builder_, &FileTransferQueueBuilder::started, this, &FileTransfer::started);
connect(builder_, &FileTransferQueueBuilder::error, this, &FileTransfer::taskQueueError);
connect(builder_, &FileTransferQueueBuilder::finished, this, &FileTransfer::taskQueueReady);
if (type_ == Downloader)
{
connect(builder_, &FileTransferQueueBuilder::newRequest, this, &FileTransfer::remoteRequest);
}
else
{
Q_ASSERT(type_ == Uploader);
connect(builder_, &FileTransferQueueBuilder::newRequest, this, &FileTransfer::localRequest);
}
connect(builder_, &FileTransferQueueBuilder::finished,
builder_, &FileTransferQueueBuilder::deleteLater);
builder_->start(source_path, target_path, items);
}
FileTransfer::Actions FileTransfer::availableActions(Error error_type) const
{
return actions_[error_type].first;
}
FileTransfer::Action FileTransfer::defaultAction(Error error_type) const
{
return actions_[error_type].second;
}
void FileTransfer::setDefaultAction(Error error_type, Action action)
{
actions_[error_type].second = action;
}
FileTransferTask& FileTransfer::currentTask()
{
return tasks_.front();
}
void FileTransfer::targetReply(const proto::file_transfer::Request& request,
const proto::file_transfer::Reply& reply)
{
if (request.has_create_directory_request())
{
if (reply.status() == proto::file_transfer::STATUS_SUCCESS ||
reply.status() == proto::file_transfer::STATUS_PATH_ALREADY_EXISTS)
{
processNextTask();
return;
}
processError(DirectoryCreateError,
tr("Failed to create directory \"%1\": %2")
.arg(currentTask().targetPath())
.arg(fileStatusToString(reply.status())));
}
else if (request.has_upload_request())
{
if (reply.status() != proto::file_transfer::STATUS_SUCCESS)
{
Error error_type = FileCreateError;
if (reply.status() == proto::file_transfer::STATUS_PATH_ALREADY_EXISTS)
error_type = FileAlreadyExists;
processError(error_type,
tr("Failed to create file \"%1\": %2")
.arg(currentTask().targetPath())
.arg(fileStatusToString(reply.status())));
return;
}
FileRequest* request = FileRequest::packetRequest();
connect(request, &FileRequest::replyReady, this, &FileTransfer::sourceReply);
sourceRequest(request);
}
else if (request.has_packet())
{
if (reply.status() != proto::file_transfer::STATUS_SUCCESS)
{
processError(FileWriteError,
tr("Failed to write file \"%1\": %2")
.arg(currentTask().targetPath())
.arg(fileStatusToString(reply.status())));
return;
}
if (currentTask().size() && total_size_)
{
qint64 packet_size = request.packet().data().size();
task_transfered_size_ += packet_size;
total_transfered_size_ += packet_size;
int task_percentage = task_transfered_size_ * 100 / currentTask().size();
int total_percentage = total_transfered_size_ * 100 / total_size_;
if (task_percentage != task_percentage_ || total_percentage != total_percentage_)
{
task_percentage_ = task_percentage;
total_percentage_ = total_percentage;
emit progressChanged(total_percentage_, task_percentage_);
}
}
if (request.packet().flags() & proto::file_transfer::Packet::FLAG_LAST_PACKET)
{
processNextTask();
return;
}
FileRequest* request = FileRequest::packetRequest();
connect(request, &FileRequest::replyReady, this, &FileTransfer::sourceReply);
sourceRequest(request);
}
else
{
emit error(this, OtherError, tr("An unexpected response to the request was received"));
}
}
void FileTransfer::sourceReply(const proto::file_transfer::Request& request,
const proto::file_transfer::Reply& reply)
{
if (request.has_download_request())
{
if (reply.status() != proto::file_transfer::STATUS_SUCCESS)
{
processError(FileOpenError,
tr("Failed to open file \"%1\": %2")
.arg(currentTask().sourcePath()
.arg(fileStatusToString(reply.status()))));
return;
}
FileRequest* request = FileRequest::uploadRequest(currentTask().targetPath(),
currentTask().overwrite());
connect(request, &FileRequest::replyReady, this, &FileTransfer::targetReply);
targetRequest(request);
}
else if (request.has_packet_request())
{
if (reply.status() != proto::file_transfer::STATUS_SUCCESS)
{
processError(FileReadError,
tr("Failed to read file \"%1\": %2")
.arg(currentTask().sourcePath())
.arg(fileStatusToString(reply.status())));
return;
}
FileRequest* request = FileRequest::packet(reply.packet());
connect(request, &FileRequest::replyReady, this, &FileTransfer::targetReply);
targetRequest(request);
}
else
{
emit error(this, OtherError, tr("An unexpected response to the request was received"));
}
}
void FileTransfer::taskQueueError(const QString& message)
{
emit error(this, OtherError, message);
}
void FileTransfer::taskQueueReady()
{
Q_ASSERT(builder_ != nullptr);
tasks_ = builder_->taskQueue();
for (const auto& task : tasks_)
total_size_ += task.size();
processTask(false);
}
void FileTransfer::applyAction(Error error_type, Action action)
{
switch (action)
{
case Action::Abort:
emit finished();
break;
case Action::Replace:
case Action::ReplaceAll:
{
if (action == Action::ReplaceAll)
setDefaultAction(error_type, action);
processTask(true);
}
break;
case Action::Skip:
case Action::SkipAll:
{
if (action == Action::SkipAll)
setDefaultAction(error_type, action);
processNextTask();
}
break;
default:
qFatal("Unexpected action");
break;
}
}
void FileTransfer::processTask(bool overwrite)
{
task_percentage_ = 0;
task_transfered_size_ = 0;
FileTransferTask& task = currentTask();
task.setOverwrite(overwrite);
emit currentItemChanged(task.sourcePath(), task.targetPath());
if (task.isDirectory())
{
FileRequest* request = FileRequest::createDirectoryRequest(task.targetPath());
connect(request, &FileRequest::replyReady, this, &FileTransfer::targetReply);
targetRequest(request);
}
else
{
FileRequest* request = FileRequest::FileRequest::downloadRequest(task.sourcePath());
connect(request, &FileRequest::replyReady, this, &FileTransfer::sourceReply);
sourceRequest(request);
}
}
void FileTransfer::processNextTask()
{
if (!tasks_.isEmpty())
{
// Delete the task only after confirmation of its successful execution.
tasks_.pop_front();
}
if (tasks_.isEmpty())
{
emit finished();
return;
}
processTask(false);
}
void FileTransfer::processError(Error error_type, const QString& message)
{
Action action = defaultAction(error_type);
if (action != Ask)
{
applyAction(error_type, action);
return;
}
emit error(this, error_type, message);
}
void FileTransfer::sourceRequest(FileRequest* request)
{
if (type_ == Downloader)
{
QMetaObject::invokeMethod(this, "remoteRequest", Q_ARG(FileRequest*, request));
}
else
{
Q_ASSERT(type_ == Uploader);
QMetaObject::invokeMethod(this, "localRequest", Q_ARG(FileRequest*, request));
}
}
void FileTransfer::targetRequest(FileRequest* request)
{
if (type_ == Downloader)
{
QMetaObject::invokeMethod(this, "localRequest", Q_ARG(FileRequest*, request));
}
else
{
Q_ASSERT(type_ == Uploader);
QMetaObject::invokeMethod(this, "remoteRequest", Q_ARG(FileRequest*, request));
}
}
} // namespace aspia
<commit_msg>- Direct calls.<commit_after>//
// PROJECT: Aspia
// FILE: client/file_transfer.cc
// LICENSE: GNU General Public License 3
// PROGRAMMERS: Dmitry Chapyshev ([email protected])
//
#include "client/file_transfer.h"
#include "client/file_status.h"
#include "client/file_transfer_queue_builder.h"
namespace aspia {
FileTransfer::FileTransfer(Type type, QObject* parent)
: QObject(parent),
type_(type)
{
actions_.insert(OtherError, QPair<Actions, Action>(Abort, Ask));
actions_.insert(DirectoryCreateError,
QPair<Actions, Action>(Abort | Skip | SkipAll, Ask));
actions_.insert(FileCreateError,
QPair<Actions, Action>(Abort | Skip | SkipAll, Ask));
actions_.insert(FileOpenError,
QPair<Actions, Action>(Abort | Skip | SkipAll, Ask));
actions_.insert(FileAlreadyExists,
QPair<Actions, Action>(Abort | Skip | SkipAll | Replace | ReplaceAll, Ask));
actions_.insert(FileWriteError,
QPair<Actions, Action>(Abort | Skip | SkipAll, Ask));
actions_.insert(FileReadError,
QPair<Actions, Action>(Abort | Skip | SkipAll, Ask));
}
void FileTransfer::start(const QString& source_path,
const QString& target_path,
const QList<Item>& items)
{
builder_ = new FileTransferQueueBuilder();
connect(builder_, &FileTransferQueueBuilder::started, this, &FileTransfer::started);
connect(builder_, &FileTransferQueueBuilder::error, this, &FileTransfer::taskQueueError);
connect(builder_, &FileTransferQueueBuilder::finished, this, &FileTransfer::taskQueueReady);
if (type_ == Downloader)
{
connect(builder_, &FileTransferQueueBuilder::newRequest, this, &FileTransfer::remoteRequest);
}
else
{
Q_ASSERT(type_ == Uploader);
connect(builder_, &FileTransferQueueBuilder::newRequest, this, &FileTransfer::localRequest);
}
connect(builder_, &FileTransferQueueBuilder::finished,
builder_, &FileTransferQueueBuilder::deleteLater);
builder_->start(source_path, target_path, items);
}
FileTransfer::Actions FileTransfer::availableActions(Error error_type) const
{
return actions_[error_type].first;
}
FileTransfer::Action FileTransfer::defaultAction(Error error_type) const
{
return actions_[error_type].second;
}
void FileTransfer::setDefaultAction(Error error_type, Action action)
{
actions_[error_type].second = action;
}
FileTransferTask& FileTransfer::currentTask()
{
return tasks_.front();
}
void FileTransfer::targetReply(const proto::file_transfer::Request& request,
const proto::file_transfer::Reply& reply)
{
if (request.has_create_directory_request())
{
if (reply.status() == proto::file_transfer::STATUS_SUCCESS ||
reply.status() == proto::file_transfer::STATUS_PATH_ALREADY_EXISTS)
{
processNextTask();
return;
}
processError(DirectoryCreateError,
tr("Failed to create directory \"%1\": %2")
.arg(currentTask().targetPath())
.arg(fileStatusToString(reply.status())));
}
else if (request.has_upload_request())
{
if (reply.status() != proto::file_transfer::STATUS_SUCCESS)
{
Error error_type = FileCreateError;
if (reply.status() == proto::file_transfer::STATUS_PATH_ALREADY_EXISTS)
error_type = FileAlreadyExists;
processError(error_type,
tr("Failed to create file \"%1\": %2")
.arg(currentTask().targetPath())
.arg(fileStatusToString(reply.status())));
return;
}
FileRequest* request = FileRequest::packetRequest();
connect(request, &FileRequest::replyReady, this, &FileTransfer::sourceReply);
sourceRequest(request);
}
else if (request.has_packet())
{
if (reply.status() != proto::file_transfer::STATUS_SUCCESS)
{
processError(FileWriteError,
tr("Failed to write file \"%1\": %2")
.arg(currentTask().targetPath())
.arg(fileStatusToString(reply.status())));
return;
}
if (currentTask().size() && total_size_)
{
qint64 packet_size = request.packet().data().size();
task_transfered_size_ += packet_size;
total_transfered_size_ += packet_size;
int task_percentage = task_transfered_size_ * 100 / currentTask().size();
int total_percentage = total_transfered_size_ * 100 / total_size_;
if (task_percentage != task_percentage_ || total_percentage != total_percentage_)
{
task_percentage_ = task_percentage;
total_percentage_ = total_percentage;
emit progressChanged(total_percentage_, task_percentage_);
}
}
if (request.packet().flags() & proto::file_transfer::Packet::FLAG_LAST_PACKET)
{
processNextTask();
return;
}
FileRequest* request = FileRequest::packetRequest();
connect(request, &FileRequest::replyReady, this, &FileTransfer::sourceReply);
sourceRequest(request);
}
else
{
emit error(this, OtherError, tr("An unexpected response to the request was received"));
}
}
void FileTransfer::sourceReply(const proto::file_transfer::Request& request,
const proto::file_transfer::Reply& reply)
{
if (request.has_download_request())
{
if (reply.status() != proto::file_transfer::STATUS_SUCCESS)
{
processError(FileOpenError,
tr("Failed to open file \"%1\": %2")
.arg(currentTask().sourcePath()
.arg(fileStatusToString(reply.status()))));
return;
}
FileRequest* request = FileRequest::uploadRequest(currentTask().targetPath(),
currentTask().overwrite());
connect(request, &FileRequest::replyReady, this, &FileTransfer::targetReply);
targetRequest(request);
}
else if (request.has_packet_request())
{
if (reply.status() != proto::file_transfer::STATUS_SUCCESS)
{
processError(FileReadError,
tr("Failed to read file \"%1\": %2")
.arg(currentTask().sourcePath())
.arg(fileStatusToString(reply.status())));
return;
}
FileRequest* request = FileRequest::packet(reply.packet());
connect(request, &FileRequest::replyReady, this, &FileTransfer::targetReply);
targetRequest(request);
}
else
{
emit error(this, OtherError, tr("An unexpected response to the request was received"));
}
}
void FileTransfer::taskQueueError(const QString& message)
{
emit error(this, OtherError, message);
}
void FileTransfer::taskQueueReady()
{
Q_ASSERT(builder_ != nullptr);
tasks_ = builder_->taskQueue();
for (const auto& task : tasks_)
total_size_ += task.size();
processTask(false);
}
void FileTransfer::applyAction(Error error_type, Action action)
{
switch (action)
{
case Action::Abort:
emit finished();
break;
case Action::Replace:
case Action::ReplaceAll:
{
if (action == Action::ReplaceAll)
setDefaultAction(error_type, action);
processTask(true);
}
break;
case Action::Skip:
case Action::SkipAll:
{
if (action == Action::SkipAll)
setDefaultAction(error_type, action);
processNextTask();
}
break;
default:
qFatal("Unexpected action");
break;
}
}
void FileTransfer::processTask(bool overwrite)
{
task_percentage_ = 0;
task_transfered_size_ = 0;
FileTransferTask& task = currentTask();
task.setOverwrite(overwrite);
emit currentItemChanged(task.sourcePath(), task.targetPath());
if (task.isDirectory())
{
FileRequest* request = FileRequest::createDirectoryRequest(task.targetPath());
connect(request, &FileRequest::replyReady, this, &FileTransfer::targetReply);
targetRequest(request);
}
else
{
FileRequest* request = FileRequest::FileRequest::downloadRequest(task.sourcePath());
connect(request, &FileRequest::replyReady, this, &FileTransfer::sourceReply);
sourceRequest(request);
}
}
void FileTransfer::processNextTask()
{
if (!tasks_.isEmpty())
{
// Delete the task only after confirmation of its successful execution.
tasks_.pop_front();
}
if (tasks_.isEmpty())
{
emit finished();
return;
}
processTask(false);
}
void FileTransfer::processError(Error error_type, const QString& message)
{
Action action = defaultAction(error_type);
if (action != Ask)
{
applyAction(error_type, action);
return;
}
emit error(this, error_type, message);
}
void FileTransfer::sourceRequest(FileRequest* request)
{
if (type_ == Downloader)
{
emit remoteRequest(request);
}
else
{
Q_ASSERT(type_ == Uploader);
emit localRequest(request);
}
}
void FileTransfer::targetRequest(FileRequest* request)
{
if (type_ == Downloader)
{
emit localRequest(request);
}
else
{
Q_ASSERT(type_ == Uploader);
emit remoteRequest(request);
}
}
} // namespace aspia
<|endoftext|> |
<commit_before>#include "raven_client.h"
#include <assert.h>
#include <time.h>
#include <QApplication>
#include <QDebug>
#include <QHostAddress>
#include <QHostInfo>
#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkInterface>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QUuid>
namespace {
int g_next_request_id;
char kRequestIdProperty[] = "RequestIdProperty";
}
const char Raven::kClientName[] = "Raven-Qt";
const char Raven::kClientVersion[] = "0.2";
Raven* g_client;
Raven::Raven()
: initialized_(false) {
g_client = this;
}
Raven::~Raven() {
assert(pending_request_.isEmpty());
g_client = NULL;
}
// static
Raven* Raven::instance() {
if (!g_client)
g_client = new Raven();
return g_client;
}
bool Raven::initialize(const QString& DSN) {
// If an empty DSN is passed, you should treat it as valid option
// which signifies disabling the client.
if (DSN.isEmpty()) {
qDebug() << "Raven client is disabled.";
return true;
}
QUrl url(DSN);
if (!url.isValid())
return false;
protocol_ = url.scheme();
public_key_ = url.userName();
secret_key_ = url.password();
host_ = url.host();
path_ = url.path();
project_id_ = url.fileName();
int i = path_.lastIndexOf('/');
if (i >= 0)
path_ = path_.left(i);
int port = url.port(80);
if (port != 80)
host_.append(":").append(QString::number(port));
qDebug() << "Raven client is ready.";
initialized_ = true;
return true;
}
void Raven::set_global_tags(const QString& key, const QString& value) {
if (!key.isEmpty() && !value.isEmpty())
global_tags_[key] = value;
}
void Raven::set_user_data(const QString& key, const QString& value) {
if (!key.isEmpty() && !value.isEmpty())
user_data_[key] = value;
}
// static
// According to http://sentry.readthedocs.org/en/latest/developer/client/
void Raven::captureMessage(
Level level,
const QString& from_here,
const QString& message,
QJsonObject extra,
QJsonObject tags) {
Raven* instance = Raven::instance();
if (!instance->initialized_) {
qDebug() << "Sentry has not been initialized succefully. Failed to send message.";
return;
}
QJsonObject jdata;
jdata["event_id"] = QUuid::createUuid().toString();
jdata["timestamp"] = QDateTime::currentDateTime().toString(Qt::ISODate);
jdata["server_name"] = QHostInfo::localHostName();
jdata["user"] = instance->GetUserInfo();
jdata["level"] = GetLevelString(level);
jdata["culprit"] = from_here;
jdata["message"] = message;
jdata["logger"] = kClientName;
jdata["platform"] = "C++/Qt";
// Add global tags
const QJsonObject& gtags = instance->global_tags_;
if (!gtags.isEmpty()) {
for (auto it = gtags.begin(); it != gtags.end(); ++it)
tags[it.key()] = *it;
}
if (!tags.isEmpty())
jdata["tags"] = tags;
if (!extra.isEmpty())
jdata["extra"] = extra;
//jdata["modules"] = QJsonObject();
instance->Send(jdata);
}
void Raven::Send(const QJsonObject& jbody) {
QString client_info = QString("%1/%2").
arg(kClientName).arg(kClientVersion);
QString auth_info = QString("Sentry sentry_version=5,sentry_client=%1,sentry_timestamp=%2,sentry_key=%3,sentry_secret=%4").
arg(client_info, QString::number(time(NULL)), public_key_, secret_key_);
// http://192.168.1.x:9000/api/4/store/
QString url = QString("%1://%2%3/api/%4/store/").
arg(protocol_).arg(host_).arg(path_).arg(project_id_);
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
request.setHeader(QNetworkRequest::UserAgentHeader, client_info);
request.setRawHeader("X-Sentry-Auth", auth_info.toUtf8());
QByteArray body = QJsonDocument(jbody).toJson(QJsonDocument::Indented);
QNetworkReply* reply = network_access_manager_.post(request, body);
reply->setProperty(kRequestIdProperty, QVariant(++g_next_request_id));
pending_request_[g_next_request_id] = body;
ConnectReply(reply);
}
void Raven::ConnectReply(QNetworkReply* reply) {
connect(reply, SIGNAL(finished()), this, SLOT(slotFinished()));
connect(reply, SIGNAL(sslErrors(const QList<QSslError>&)), this, SLOT(slotSslError(const QList<QSslError>&)));
}
void Raven::slotFinished() {
QNetworkReply* reply = static_cast<QNetworkReply*>(sender());
int id = GetRequestId(reply);
if (pending_request_.find(id) == pending_request_.end()) {
reply->deleteLater();
return;
}
// Deal with redirection
QUrl possibleRedirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
if (!possibleRedirectUrl.isEmpty() && possibleRedirectUrl != reply->url()) {
QNetworkRequest request = reply->request();
QByteArray body = pending_request_[id];
request.setUrl(possibleRedirectUrl);
QNetworkReply* new_reply = network_access_manager_.post(request, body);
new_reply->setProperty(kRequestIdProperty, QVariant(id));
ConnectReply(new_reply);
} else {
QNetworkReply::NetworkError e = reply->error();
QByteArray res = reply->readAll();
if (e == QNetworkReply::NoError) {
qDebug() << "Sentry log ID " << res;
}
else {
qDebug() << "Failed to send log to sentry: [" << e << "]:" << res;
}
pending_request_.remove(id);
}
reply->deleteLater();
}
void Raven::slotSslError(const QList<QSslError>& e) {
QNetworkReply* reply = static_cast<QNetworkReply*>(sender());
reply->ignoreSslErrors();
}
int Raven::GetRequestId(QNetworkReply* reply) {
QVariant var = reply->property(kRequestIdProperty);
if (var.type() != QVariant::Int)
return kInvalidRequestId;
return var.toInt();
}
QJsonObject Raven::GetUserInfo() {
QJsonObject user;
if (!user_id_.isEmpty())
user["id"] = user_id_;
if (!user_name_.isEmpty())
user["username"] = user_name_;
if (!user_email_.isEmpty())
user["email"] = user_email_;
if (!user_data_.isEmpty()) {
for (auto it = user_data_.begin(); it != user_data_.end(); ++it)
user[it.key()] = *it;
}
user["ip_address"] = LocalAddress();
return user;
}
QString Raven::LocalAddress() {
QList<QHostAddress> list = QNetworkInterface::allAddresses();
for (int nIter = 0; nIter < list.count(); nIter++) {
if (!list[nIter].isLoopback()) {
if (list[nIter].protocol() == QAbstractSocket::IPv4Protocol)
return list[nIter].toString();
}
}
return "0.0.0.0";
}
// static
QString Raven::locationInfo(const char* file, const char* func, int line) {
return QString("%1 in %2 at %3").arg(file).arg(func).arg(QString::number(line));
}
// static
Raven::Level Raven::fromUnixLogLevel(int i) {
Level level;
switch (i) {
case 7: //Debug
level = Raven::kDebug;
break;
case 6: //Info
case 5: //Notice
level = Raven::kInfo;
break;
case 4: //Warning
level = Raven::kWarning;
break;
case 3: //Error
case 2: //Critical
case 1: //Alert
level = Raven::kError;
break;
case 0: //Emergency
level = Raven::kFatal;
break;
default:
level = Raven::kDebug;
break;
}
return level;
}
// static
QString Raven::GetLevelString(Level level) {
QString s;
switch (level) {
case kDebug:
s = "debug";
break;
case kInfo:
s = "info";
break;
case kWarning:
s = "warning";
break;
case kError:
s = "error";
break;
case kFatal:
s = "fatal";
break;
default:
qDebug() << "Wrong sentry log level, default to error.";
s = "error";
break;
}
return s;
}
<commit_msg>warning removed<commit_after>#include "raven_client.h"
#include <assert.h>
#include <time.h>
#include <QApplication>
#include <QDebug>
#include <QHostAddress>
#include <QHostInfo>
#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkInterface>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QUuid>
namespace {
int g_next_request_id;
char kRequestIdProperty[] = "RequestIdProperty";
}
const char Raven::kClientName[] = "Raven-Qt";
const char Raven::kClientVersion[] = "0.2";
Raven* g_client;
Raven::Raven()
: initialized_(false) {
g_client = this;
}
Raven::~Raven() {
assert(pending_request_.isEmpty());
g_client = NULL;
}
// static
Raven* Raven::instance() {
if (!g_client)
g_client = new Raven();
return g_client;
}
bool Raven::initialize(const QString& DSN) {
// If an empty DSN is passed, you should treat it as valid option
// which signifies disabling the client.
if (DSN.isEmpty()) {
qDebug() << "Raven client is disabled.";
return true;
}
QUrl url(DSN);
if (!url.isValid())
return false;
protocol_ = url.scheme();
public_key_ = url.userName();
secret_key_ = url.password();
host_ = url.host();
path_ = url.path();
project_id_ = url.fileName();
int i = path_.lastIndexOf('/');
if (i >= 0)
path_ = path_.left(i);
int port = url.port(80);
if (port != 80)
host_.append(":").append(QString::number(port));
qDebug() << "Raven client is ready.";
initialized_ = true;
return true;
}
void Raven::set_global_tags(const QString& key, const QString& value) {
if (!key.isEmpty() && !value.isEmpty())
global_tags_[key] = value;
}
void Raven::set_user_data(const QString& key, const QString& value) {
if (!key.isEmpty() && !value.isEmpty())
user_data_[key] = value;
}
// static
// According to http://sentry.readthedocs.org/en/latest/developer/client/
void Raven::captureMessage(
Level level,
const QString& from_here,
const QString& message,
QJsonObject extra,
QJsonObject tags) {
Raven* instance = Raven::instance();
if (!instance->initialized_) {
qDebug() << "Sentry has not been initialized succefully. Failed to send message.";
return;
}
QJsonObject jdata;
jdata["event_id"] = QUuid::createUuid().toString();
jdata["timestamp"] = QDateTime::currentDateTime().toString(Qt::ISODate);
jdata["server_name"] = QHostInfo::localHostName();
jdata["user"] = instance->GetUserInfo();
jdata["level"] = GetLevelString(level);
jdata["culprit"] = from_here;
jdata["message"] = message;
jdata["logger"] = kClientName;
jdata["platform"] = "C++/Qt";
// Add global tags
const QJsonObject& gtags = instance->global_tags_;
if (!gtags.isEmpty()) {
for (auto it = gtags.begin(); it != gtags.end(); ++it)
tags[it.key()] = *it;
}
if (!tags.isEmpty())
jdata["tags"] = tags;
if (!extra.isEmpty())
jdata["extra"] = extra;
//jdata["modules"] = QJsonObject();
instance->Send(jdata);
}
void Raven::Send(const QJsonObject& jbody) {
QString client_info = QString("%1/%2").
arg(kClientName).arg(kClientVersion);
QString auth_info = QString("Sentry sentry_version=5,sentry_client=%1,sentry_timestamp=%2,sentry_key=%3,sentry_secret=%4").
arg(client_info, QString::number(time(NULL)), public_key_, secret_key_);
// http://192.168.1.x:9000/api/4/store/
QString url = QString("%1://%2%3/api/%4/store/").
arg(protocol_).arg(host_).arg(path_).arg(project_id_);
QNetworkRequest request(url);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
request.setHeader(QNetworkRequest::UserAgentHeader, client_info);
request.setRawHeader("X-Sentry-Auth", auth_info.toUtf8());
QByteArray body = QJsonDocument(jbody).toJson(QJsonDocument::Indented);
QNetworkReply* reply = network_access_manager_.post(request, body);
reply->setProperty(kRequestIdProperty, QVariant(++g_next_request_id));
pending_request_[g_next_request_id] = body;
ConnectReply(reply);
}
void Raven::ConnectReply(QNetworkReply* reply) {
connect(reply, SIGNAL(finished()), this, SLOT(slotFinished()));
connect(reply, SIGNAL(sslErrors(const QList<QSslError>&)), this, SLOT(slotSslError(const QList<QSslError>&)));
}
void Raven::slotFinished() {
QNetworkReply* reply = static_cast<QNetworkReply*>(sender());
int id = GetRequestId(reply);
if (pending_request_.find(id) == pending_request_.end()) {
reply->deleteLater();
return;
}
// Deal with redirection
QUrl possibleRedirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
if (!possibleRedirectUrl.isEmpty() && possibleRedirectUrl != reply->url()) {
QNetworkRequest request = reply->request();
QByteArray body = pending_request_[id];
request.setUrl(possibleRedirectUrl);
QNetworkReply* new_reply = network_access_manager_.post(request, body);
new_reply->setProperty(kRequestIdProperty, QVariant(id));
ConnectReply(new_reply);
} else {
QNetworkReply::NetworkError e = reply->error();
QByteArray res = reply->readAll();
if (e == QNetworkReply::NoError) {
qDebug() << "Sentry log ID " << res;
}
else {
qDebug() << "Failed to send log to sentry: [" << e << "]:" << res;
}
pending_request_.remove(id);
}
reply->deleteLater();
}
void Raven::slotSslError(const QList<QSslError>& ) {
QNetworkReply* reply = static_cast<QNetworkReply*>(sender());
reply->ignoreSslErrors();
}
int Raven::GetRequestId(QNetworkReply* reply) {
QVariant var = reply->property(kRequestIdProperty);
if (var.type() != QVariant::Int)
return kInvalidRequestId;
return var.toInt();
}
QJsonObject Raven::GetUserInfo() {
QJsonObject user;
if (!user_id_.isEmpty())
user["id"] = user_id_;
if (!user_name_.isEmpty())
user["username"] = user_name_;
if (!user_email_.isEmpty())
user["email"] = user_email_;
if (!user_data_.isEmpty()) {
for (auto it = user_data_.begin(); it != user_data_.end(); ++it)
user[it.key()] = *it;
}
user["ip_address"] = LocalAddress();
return user;
}
QString Raven::LocalAddress() {
QList<QHostAddress> list = QNetworkInterface::allAddresses();
for (int nIter = 0; nIter < list.count(); nIter++) {
if (!list[nIter].isLoopback()) {
if (list[nIter].protocol() == QAbstractSocket::IPv4Protocol)
return list[nIter].toString();
}
}
return "0.0.0.0";
}
// static
QString Raven::locationInfo(const char* file, const char* func, int line) {
return QString("%1 in %2 at %3").arg(file).arg(func).arg(QString::number(line));
}
// static
Raven::Level Raven::fromUnixLogLevel(int i) {
Level level;
switch (i) {
case 7: //Debug
level = Raven::kDebug;
break;
case 6: //Info
case 5: //Notice
level = Raven::kInfo;
break;
case 4: //Warning
level = Raven::kWarning;
break;
case 3: //Error
case 2: //Critical
case 1: //Alert
level = Raven::kError;
break;
case 0: //Emergency
level = Raven::kFatal;
break;
default:
level = Raven::kDebug;
break;
}
return level;
}
// static
QString Raven::GetLevelString(Level level) {
QString s;
switch (level) {
case kDebug:
s = "debug";
break;
case kInfo:
s = "info";
break;
case kWarning:
s = "warning";
break;
case kError:
s = "error";
break;
case kFatal:
s = "fatal";
break;
default:
qDebug() << "Wrong sentry log level, default to error.";
s = "error";
break;
}
return s;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: TableFieldDescWin.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: rt $ $Date: 2007-07-06 08:43:52 $
*
* 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_dbaccess.hxx"
#ifndef DBAUI_TABLEFIELDDESCRIPTION_HXX
#include "TableFieldDescWin.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef DBAUI_FIELDDESCRIPTIONS_HXX
#include "FieldDescriptions.hxx"
#endif
#ifndef _DBU_TBL_HRC_
#include "dbu_tbl.hrc"
#endif
#ifndef DBAUI_FIELDDESCRIPTIONS_HXX
#include "FieldDescriptions.hxx"
#endif
#ifndef DBAUI_TABLEDESIGNHELPBAR_HXX
#include "TableDesignHelpBar.hxx"
#endif
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef _DBA_DBACCESS_HELPID_HRC_
#include "dbaccess_helpid.hrc"
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#include <memory>
#define STANDARD_MARGIN 6
#define DETAILS_HEADER_HEIGHT 25
#define CONTROL_SPACING_X 18 // 6
#define CONTROL_SPACING_Y 5
#define CONTROL_HEIGHT 20
#define CONTROL_WIDTH_1 140 // 100
#define CONTROL_WIDTH_2 100 // 60
#define CONTROL_WIDTH_3 250
#define CONTROL_WIDTH_4 (CONTROL_WIDTH_3 - CONTROL_HEIGHT - 5)
#define DETAILS_OPT_PAGE_WIDTH (CONTROL_WIDTH_1 + CONTROL_SPACING_X + CONTROL_WIDTH_4 + 50)
#define DETAILS_OPT_PAGE_HEIGHT ((CONTROL_HEIGHT + CONTROL_SPACING_Y) * 5)
#define DETAILS_MIN_HELP_WIDTH 100
#define DETAILS_OPT_HELP_WIDTH 200
#define DETAILS_MIN_HELP_HEIGHT 50
#define DETAILS_OPT_HELP_HEIGHT 100
using namespace dbaui;
//==================================================================
// class OTableFieldDescWin
//==================================================================
DBG_NAME(OTableFieldDescWin)
//------------------------------------------------------------------------------
OTableFieldDescWin::OTableFieldDescWin( Window* pParent)
:TabPage(pParent, WB_3DLOOK)
{
DBG_CTOR(OTableFieldDescWin,NULL);
//////////////////////////////////////////////////////////////////////
// Header
m_pHeader = new FixedText( this, WB_CENTER | WB_INFO ); // | WB_3DLOOK
m_pHeader->SetText( String(ModuleRes(STR_TAB_PROPERTIES)) );
m_pHeader->Show();
//////////////////////////////////////////////////////////////////////
// HelpBar
m_pHelpBar = new OTableDesignHelpBar( this );
m_pHelpBar->SetHelpId(HID_TAB_DESIGN_HELP_TEXT_FRAME);
m_pHelpBar->Show();
m_pGenPage = new OFieldDescGenWin( this, m_pHelpBar );
getGenPage()->SetHelpId( HID_TABLE_DESIGN_TABPAGE_GENERAL );
getGenPage()->Show();
}
//------------------------------------------------------------------------------
OTableFieldDescWin::~OTableFieldDescWin()
{
DBG_DTOR(OTableFieldDescWin,NULL);
//////////////////////////////////////////////////////////////////////
// Childs zerstoeren
m_pHelpBar->Hide();
getGenPage()->Hide();
m_pHeader->Hide();
{
::std::auto_ptr<Window> aTemp(m_pGenPage);
m_pGenPage = NULL;
}
{
::std::auto_ptr<Window> aTemp(m_pHeader);
m_pHeader = NULL;
}
{
::std::auto_ptr<Window> aTemp(m_pHelpBar);
m_pHelpBar = NULL;
}
}
//------------------------------------------------------------------------------
void OTableFieldDescWin::Init()
{
DBG_ASSERT(getGenPage() != NULL, "OTableFieldDescWin::Init : ups ... no GenericPage ... this will crash ...");
getGenPage()->Init();
}
//------------------------------------------------------------------------------
void OTableFieldDescWin::SetReadOnly( sal_Bool bRead )
{
DBG_CHKTHIS(OTableFieldDescWin,NULL);
getGenPage()->SetReadOnly( bRead );
}
//------------------------------------------------------------------------------
void OTableFieldDescWin::DisplayData( OFieldDescription* pFieldDescr )
{
DBG_CHKTHIS(OTableFieldDescWin,NULL);
getGenPage()->DisplayData( pFieldDescr );
}
//------------------------------------------------------------------------------
void OTableFieldDescWin::SaveData( OFieldDescription* pFieldDescr )
{
DBG_CHKTHIS(OTableFieldDescWin,NULL);
getGenPage()->SaveData( pFieldDescr );
}
//------------------------------------------------------------------------------
void OTableFieldDescWin::Paint( const Rectangle& /*rRect*/ )
{
DBG_CHKTHIS(OTableFieldDescWin,NULL);
//////////////////////////////////////////////////////////////////////
// 3D-Linie am oberen Fensterrand
const StyleSettings& rStyleSettings = GetSettings().GetStyleSettings();
SetLineColor( rStyleSettings.GetLightColor() );
DrawLine( Point(0,0), Point(GetSizePixel().Width(),0) );
//////////////////////////////////////////////////////////////////////
// 3D-Linie zum Abtrennen des Headers
DrawLine( Point(3, DETAILS_HEADER_HEIGHT), Point(GetSizePixel().Width()-6, DETAILS_HEADER_HEIGHT) );
SetLineColor( rStyleSettings.GetShadowColor() );
DrawLine( Point(3, DETAILS_HEADER_HEIGHT-1), Point(GetSizePixel().Width()-6, DETAILS_HEADER_HEIGHT-1) );
}
//------------------------------------------------------------------------------
void OTableFieldDescWin::Resize()
{
DBG_CHKTHIS(OTableFieldDescWin,NULL);
//////////////////////////////////////////////////////////////////////
// Abmessungen parent window
Size aOutputSize( GetOutputSizePixel() );
long nOutputWidth = aOutputSize.Width();
long nOutputHeight = aOutputSize.Height();
// da die GenPage scrollen kann, ich selber aber nicht, positioniere ich das HelpFenster, wenn ich zu schmal werde,
// _unter_ der Genpage, nicht rechts daneben. Zuvor versuche ich aber noch, es etwas schmaler zu machen
long nHelpX, nHelpY;
long nHelpWidth, nHelpHeight;
long nPageWidth, nPageHeight;
// passen beide nebeneinander (Rand + Page + Rand + Help) ?
if (STANDARD_MARGIN + DETAILS_OPT_PAGE_WIDTH + STANDARD_MARGIN + DETAILS_MIN_HELP_WIDTH <= nOutputWidth)
{ // ja -> dann ist die Frage, ob man der Hilfe ihre Optimal-Breite geben kann
nHelpWidth = DETAILS_OPT_HELP_WIDTH;
nPageWidth = nOutputWidth - nHelpWidth - STANDARD_MARGIN - STANDARD_MARGIN;
if (nPageWidth < DETAILS_OPT_PAGE_WIDTH)
{ // dann doch lieber die Hilfe von ihrer optimalen in Richtung auf die minimale Groesse
long nTransfer = DETAILS_OPT_PAGE_WIDTH - nPageWidth;
nPageWidth += nTransfer;
nHelpWidth -= nTransfer;
}
nHelpX = nOutputWidth - nHelpWidth;
// die Hoehen sind dann einfach ...
nHelpY = DETAILS_HEADER_HEIGHT + 1;
nHelpHeight = nOutputHeight - nHelpY;
nPageHeight = nOutputHeight - STANDARD_MARGIN - DETAILS_HEADER_HEIGHT - STANDARD_MARGIN;
}
else
{ // nebeneinander geht nicht, also untereinander (Rand + Header + Page + Help)
if (STANDARD_MARGIN + DETAILS_HEADER_HEIGHT + DETAILS_OPT_PAGE_HEIGHT + DETAILS_MIN_HELP_HEIGHT <= nOutputHeight)
{ // es reicht zumindest, um beide untereinander (Page optimal, Help minimal) unterzubringen
nHelpHeight = DETAILS_OPT_HELP_HEIGHT;
nPageHeight = nOutputHeight - nHelpHeight - DETAILS_HEADER_HEIGHT - STANDARD_MARGIN;
if (nPageHeight < DETAILS_OPT_PAGE_HEIGHT)
{ // wie oben : Page optimal, Hilfe soviel wie eben bleibt (das ist groesser/gleich ihrem Minimum)
long nTransfer = DETAILS_OPT_PAGE_HEIGHT - nPageHeight;
nPageHeight += nTransfer;
nHelpHeight -= nTransfer;
}
nHelpY = nOutputHeight - nHelpHeight;
// und ueber die ganze Breite
nHelpX = 0; // ohne Margin, da das HelpCtrl einen eigenen hat
nHelpWidth = nOutputWidth; // dito
nPageWidth = nOutputWidth - STANDARD_MARGIN - STANDARD_MARGIN;
}
else
{ // dummerweise reicht es nicht mal, um Page optimal und Help minimal zu zeigen
nHelpX = nHelpY = nHelpWidth = nHelpHeight = 0; // -> kein Help-Fenster
nPageWidth = nOutputWidth - STANDARD_MARGIN - STANDARD_MARGIN;
nPageHeight = nOutputHeight - STANDARD_MARGIN - DETAILS_HEADER_HEIGHT - STANDARD_MARGIN;
}
}
m_pHeader->SetPosSizePixel( Point(0, STANDARD_MARGIN), Size(nOutputWidth, 15) );
getGenPage()->SetPosSizePixel(Point ( STANDARD_MARGIN,
STANDARD_MARGIN + DETAILS_HEADER_HEIGHT
),
Size ( nPageWidth,
nPageHeight
)
);
if (nHelpHeight)
{
m_pHelpBar->Show();
m_pHelpBar->SetPosSizePixel(Point ( nHelpX,
nHelpY
),
Size ( nHelpWidth,
nHelpHeight
)
);
}
else
{
m_pHelpBar->Hide();
}
Invalidate();
}
// -----------------------------------------------------------------------------
IClipboardTest* OTableFieldDescWin::getActiveChild() const
{
IClipboardTest* pTest = NULL;
switch(m_eChildFocus)
{
case DESCRIPTION:
pTest = getGenPage();
break;
default:
pTest = getHelpBar();
break;
}
return pTest;
}
// -----------------------------------------------------------------------------
sal_Bool OTableFieldDescWin::isCopyAllowed()
{
return getActiveChild() && getActiveChild()->isCopyAllowed();
}
// -----------------------------------------------------------------------------
sal_Bool OTableFieldDescWin::isCutAllowed()
{
return (getGenPage() && getGenPage()->HasChildPathFocus() && getGenPage()->isCutAllowed());
}
// -----------------------------------------------------------------------------
sal_Bool OTableFieldDescWin::isPasteAllowed()
{
return (getGenPage() && getGenPage()->HasChildPathFocus() && getGenPage()->isPasteAllowed());
}
// -----------------------------------------------------------------------------
void OTableFieldDescWin::cut()
{
if ( getGenPage() && getGenPage()->HasChildPathFocus() )
getGenPage()->cut();
}
// -----------------------------------------------------------------------------
void OTableFieldDescWin::copy()
{
if ( getActiveChild() )
getActiveChild()->copy();
}
// -----------------------------------------------------------------------------
void OTableFieldDescWin::paste()
{
if ( getGenPage() && getGenPage()->HasChildPathFocus() )
getGenPage()->paste();
}
// -----------------------------------------------------------------------------
void OTableFieldDescWin::GetFocus()
{
if ( getGenPage() )
getGenPage()->GetFocus();
}
// -----------------------------------------------------------------------------
void OTableFieldDescWin::LoseFocus()
{
if ( getGenPage() )
getGenPage()->LoseFocus();
}
// -----------------------------------------------------------------------------
long OTableFieldDescWin::PreNotify( NotifyEvent& rNEvt )
{
BOOL bHandled = FALSE;
switch(rNEvt.GetType())
{
case EVENT_GETFOCUS:
if( getGenPage() && getGenPage()->HasChildPathFocus() )
m_eChildFocus = DESCRIPTION;
else
m_eChildFocus = HELP;
break;
}
return bHandled ? 1L : TabPage::PreNotify(rNEvt);
}
<commit_msg>INTEGRATION: CWS changefileheader (1.13.162); FILE MERGED 2008/03/31 13:28:07 rt 1.13.162.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: TableFieldDescWin.cxx,v $
* $Revision: 1.14 $
*
* 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.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbaccess.hxx"
#ifndef DBAUI_TABLEFIELDDESCRIPTION_HXX
#include "TableFieldDescWin.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef DBAUI_FIELDDESCRIPTIONS_HXX
#include "FieldDescriptions.hxx"
#endif
#ifndef _DBU_TBL_HRC_
#include "dbu_tbl.hrc"
#endif
#ifndef DBAUI_FIELDDESCRIPTIONS_HXX
#include "FieldDescriptions.hxx"
#endif
#ifndef DBAUI_TABLEDESIGNHELPBAR_HXX
#include "TableDesignHelpBar.hxx"
#endif
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef _DBA_DBACCESS_HELPID_HRC_
#include "dbaccess_helpid.hrc"
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#include <memory>
#define STANDARD_MARGIN 6
#define DETAILS_HEADER_HEIGHT 25
#define CONTROL_SPACING_X 18 // 6
#define CONTROL_SPACING_Y 5
#define CONTROL_HEIGHT 20
#define CONTROL_WIDTH_1 140 // 100
#define CONTROL_WIDTH_2 100 // 60
#define CONTROL_WIDTH_3 250
#define CONTROL_WIDTH_4 (CONTROL_WIDTH_3 - CONTROL_HEIGHT - 5)
#define DETAILS_OPT_PAGE_WIDTH (CONTROL_WIDTH_1 + CONTROL_SPACING_X + CONTROL_WIDTH_4 + 50)
#define DETAILS_OPT_PAGE_HEIGHT ((CONTROL_HEIGHT + CONTROL_SPACING_Y) * 5)
#define DETAILS_MIN_HELP_WIDTH 100
#define DETAILS_OPT_HELP_WIDTH 200
#define DETAILS_MIN_HELP_HEIGHT 50
#define DETAILS_OPT_HELP_HEIGHT 100
using namespace dbaui;
//==================================================================
// class OTableFieldDescWin
//==================================================================
DBG_NAME(OTableFieldDescWin)
//------------------------------------------------------------------------------
OTableFieldDescWin::OTableFieldDescWin( Window* pParent)
:TabPage(pParent, WB_3DLOOK)
{
DBG_CTOR(OTableFieldDescWin,NULL);
//////////////////////////////////////////////////////////////////////
// Header
m_pHeader = new FixedText( this, WB_CENTER | WB_INFO ); // | WB_3DLOOK
m_pHeader->SetText( String(ModuleRes(STR_TAB_PROPERTIES)) );
m_pHeader->Show();
//////////////////////////////////////////////////////////////////////
// HelpBar
m_pHelpBar = new OTableDesignHelpBar( this );
m_pHelpBar->SetHelpId(HID_TAB_DESIGN_HELP_TEXT_FRAME);
m_pHelpBar->Show();
m_pGenPage = new OFieldDescGenWin( this, m_pHelpBar );
getGenPage()->SetHelpId( HID_TABLE_DESIGN_TABPAGE_GENERAL );
getGenPage()->Show();
}
//------------------------------------------------------------------------------
OTableFieldDescWin::~OTableFieldDescWin()
{
DBG_DTOR(OTableFieldDescWin,NULL);
//////////////////////////////////////////////////////////////////////
// Childs zerstoeren
m_pHelpBar->Hide();
getGenPage()->Hide();
m_pHeader->Hide();
{
::std::auto_ptr<Window> aTemp(m_pGenPage);
m_pGenPage = NULL;
}
{
::std::auto_ptr<Window> aTemp(m_pHeader);
m_pHeader = NULL;
}
{
::std::auto_ptr<Window> aTemp(m_pHelpBar);
m_pHelpBar = NULL;
}
}
//------------------------------------------------------------------------------
void OTableFieldDescWin::Init()
{
DBG_ASSERT(getGenPage() != NULL, "OTableFieldDescWin::Init : ups ... no GenericPage ... this will crash ...");
getGenPage()->Init();
}
//------------------------------------------------------------------------------
void OTableFieldDescWin::SetReadOnly( sal_Bool bRead )
{
DBG_CHKTHIS(OTableFieldDescWin,NULL);
getGenPage()->SetReadOnly( bRead );
}
//------------------------------------------------------------------------------
void OTableFieldDescWin::DisplayData( OFieldDescription* pFieldDescr )
{
DBG_CHKTHIS(OTableFieldDescWin,NULL);
getGenPage()->DisplayData( pFieldDescr );
}
//------------------------------------------------------------------------------
void OTableFieldDescWin::SaveData( OFieldDescription* pFieldDescr )
{
DBG_CHKTHIS(OTableFieldDescWin,NULL);
getGenPage()->SaveData( pFieldDescr );
}
//------------------------------------------------------------------------------
void OTableFieldDescWin::Paint( const Rectangle& /*rRect*/ )
{
DBG_CHKTHIS(OTableFieldDescWin,NULL);
//////////////////////////////////////////////////////////////////////
// 3D-Linie am oberen Fensterrand
const StyleSettings& rStyleSettings = GetSettings().GetStyleSettings();
SetLineColor( rStyleSettings.GetLightColor() );
DrawLine( Point(0,0), Point(GetSizePixel().Width(),0) );
//////////////////////////////////////////////////////////////////////
// 3D-Linie zum Abtrennen des Headers
DrawLine( Point(3, DETAILS_HEADER_HEIGHT), Point(GetSizePixel().Width()-6, DETAILS_HEADER_HEIGHT) );
SetLineColor( rStyleSettings.GetShadowColor() );
DrawLine( Point(3, DETAILS_HEADER_HEIGHT-1), Point(GetSizePixel().Width()-6, DETAILS_HEADER_HEIGHT-1) );
}
//------------------------------------------------------------------------------
void OTableFieldDescWin::Resize()
{
DBG_CHKTHIS(OTableFieldDescWin,NULL);
//////////////////////////////////////////////////////////////////////
// Abmessungen parent window
Size aOutputSize( GetOutputSizePixel() );
long nOutputWidth = aOutputSize.Width();
long nOutputHeight = aOutputSize.Height();
// da die GenPage scrollen kann, ich selber aber nicht, positioniere ich das HelpFenster, wenn ich zu schmal werde,
// _unter_ der Genpage, nicht rechts daneben. Zuvor versuche ich aber noch, es etwas schmaler zu machen
long nHelpX, nHelpY;
long nHelpWidth, nHelpHeight;
long nPageWidth, nPageHeight;
// passen beide nebeneinander (Rand + Page + Rand + Help) ?
if (STANDARD_MARGIN + DETAILS_OPT_PAGE_WIDTH + STANDARD_MARGIN + DETAILS_MIN_HELP_WIDTH <= nOutputWidth)
{ // ja -> dann ist die Frage, ob man der Hilfe ihre Optimal-Breite geben kann
nHelpWidth = DETAILS_OPT_HELP_WIDTH;
nPageWidth = nOutputWidth - nHelpWidth - STANDARD_MARGIN - STANDARD_MARGIN;
if (nPageWidth < DETAILS_OPT_PAGE_WIDTH)
{ // dann doch lieber die Hilfe von ihrer optimalen in Richtung auf die minimale Groesse
long nTransfer = DETAILS_OPT_PAGE_WIDTH - nPageWidth;
nPageWidth += nTransfer;
nHelpWidth -= nTransfer;
}
nHelpX = nOutputWidth - nHelpWidth;
// die Hoehen sind dann einfach ...
nHelpY = DETAILS_HEADER_HEIGHT + 1;
nHelpHeight = nOutputHeight - nHelpY;
nPageHeight = nOutputHeight - STANDARD_MARGIN - DETAILS_HEADER_HEIGHT - STANDARD_MARGIN;
}
else
{ // nebeneinander geht nicht, also untereinander (Rand + Header + Page + Help)
if (STANDARD_MARGIN + DETAILS_HEADER_HEIGHT + DETAILS_OPT_PAGE_HEIGHT + DETAILS_MIN_HELP_HEIGHT <= nOutputHeight)
{ // es reicht zumindest, um beide untereinander (Page optimal, Help minimal) unterzubringen
nHelpHeight = DETAILS_OPT_HELP_HEIGHT;
nPageHeight = nOutputHeight - nHelpHeight - DETAILS_HEADER_HEIGHT - STANDARD_MARGIN;
if (nPageHeight < DETAILS_OPT_PAGE_HEIGHT)
{ // wie oben : Page optimal, Hilfe soviel wie eben bleibt (das ist groesser/gleich ihrem Minimum)
long nTransfer = DETAILS_OPT_PAGE_HEIGHT - nPageHeight;
nPageHeight += nTransfer;
nHelpHeight -= nTransfer;
}
nHelpY = nOutputHeight - nHelpHeight;
// und ueber die ganze Breite
nHelpX = 0; // ohne Margin, da das HelpCtrl einen eigenen hat
nHelpWidth = nOutputWidth; // dito
nPageWidth = nOutputWidth - STANDARD_MARGIN - STANDARD_MARGIN;
}
else
{ // dummerweise reicht es nicht mal, um Page optimal und Help minimal zu zeigen
nHelpX = nHelpY = nHelpWidth = nHelpHeight = 0; // -> kein Help-Fenster
nPageWidth = nOutputWidth - STANDARD_MARGIN - STANDARD_MARGIN;
nPageHeight = nOutputHeight - STANDARD_MARGIN - DETAILS_HEADER_HEIGHT - STANDARD_MARGIN;
}
}
m_pHeader->SetPosSizePixel( Point(0, STANDARD_MARGIN), Size(nOutputWidth, 15) );
getGenPage()->SetPosSizePixel(Point ( STANDARD_MARGIN,
STANDARD_MARGIN + DETAILS_HEADER_HEIGHT
),
Size ( nPageWidth,
nPageHeight
)
);
if (nHelpHeight)
{
m_pHelpBar->Show();
m_pHelpBar->SetPosSizePixel(Point ( nHelpX,
nHelpY
),
Size ( nHelpWidth,
nHelpHeight
)
);
}
else
{
m_pHelpBar->Hide();
}
Invalidate();
}
// -----------------------------------------------------------------------------
IClipboardTest* OTableFieldDescWin::getActiveChild() const
{
IClipboardTest* pTest = NULL;
switch(m_eChildFocus)
{
case DESCRIPTION:
pTest = getGenPage();
break;
default:
pTest = getHelpBar();
break;
}
return pTest;
}
// -----------------------------------------------------------------------------
sal_Bool OTableFieldDescWin::isCopyAllowed()
{
return getActiveChild() && getActiveChild()->isCopyAllowed();
}
// -----------------------------------------------------------------------------
sal_Bool OTableFieldDescWin::isCutAllowed()
{
return (getGenPage() && getGenPage()->HasChildPathFocus() && getGenPage()->isCutAllowed());
}
// -----------------------------------------------------------------------------
sal_Bool OTableFieldDescWin::isPasteAllowed()
{
return (getGenPage() && getGenPage()->HasChildPathFocus() && getGenPage()->isPasteAllowed());
}
// -----------------------------------------------------------------------------
void OTableFieldDescWin::cut()
{
if ( getGenPage() && getGenPage()->HasChildPathFocus() )
getGenPage()->cut();
}
// -----------------------------------------------------------------------------
void OTableFieldDescWin::copy()
{
if ( getActiveChild() )
getActiveChild()->copy();
}
// -----------------------------------------------------------------------------
void OTableFieldDescWin::paste()
{
if ( getGenPage() && getGenPage()->HasChildPathFocus() )
getGenPage()->paste();
}
// -----------------------------------------------------------------------------
void OTableFieldDescWin::GetFocus()
{
if ( getGenPage() )
getGenPage()->GetFocus();
}
// -----------------------------------------------------------------------------
void OTableFieldDescWin::LoseFocus()
{
if ( getGenPage() )
getGenPage()->LoseFocus();
}
// -----------------------------------------------------------------------------
long OTableFieldDescWin::PreNotify( NotifyEvent& rNEvt )
{
BOOL bHandled = FALSE;
switch(rNEvt.GetType())
{
case EVENT_GETFOCUS:
if( getGenPage() && getGenPage()->HasChildPathFocus() )
m_eChildFocus = DESCRIPTION;
else
m_eChildFocus = HELP;
break;
}
return bHandled ? 1L : TabPage::PreNotify(rNEvt);
}
<|endoftext|> |
<commit_before>// readWrite-bmp.cc
//
// extracts pixel data from user-specified .bmp file
// inserts data back into new .bmp file
//
// gw
// uncomment for MSVS
// #include "stdafx.h"
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <vector>
#include <cmath>
#include <ctime>
#include <omp.h>
using namespace std;
#pragma pack(1)
typedef struct {
char id[2];
int file_size;
int reserved;
int offset;
} header_type;
#pragma pack(1)
typedef struct {
int header_size;
int width;
int height;
unsigned short int color_planes;
unsigned short int color_depth;
unsigned int compression;
int image_size;
int xresolution;
int yresolution;
int num_colors;
int num_important_colors;
} information_type;
int main(int argc, char* argv[])
{
header_type header;
information_type information;
string imageFileName, newImageFileName;
unsigned char tempData[3];
int row, col, row_bytes, padding;
vector <vector <int> > data, newData;
// prepare files
cout << "Original imagefile? ";
cin >> imageFileName;
ifstream imageFile;
imageFile.open (imageFileName.c_str(), ios::binary);
if (!imageFile) {
cerr << "file not found" << endl;
exit(-1);
}
cout << "New imagefile name? ";
cin >> newImageFileName;
ofstream newImageFile;
newImageFile.open (newImageFileName.c_str(), ios::binary);
// read file header
imageFile.read ((char *) &header, sizeof(header_type));
if (header.id[0] != 'B' || header.id[1] != 'M') {
cerr << "Does not appear to be a .bmp file. Goodbye." << endl;
exit(-1);
}
// read/compute image information
imageFile.read ((char *) &information, sizeof(information_type));
row_bytes = information.width * 3;
padding = row_bytes % 4;
if (padding)
padding = 4 - padding;
// extract image data, initialize vectors
for (row=0; row < information.height; row++) {
data.push_back (vector <int>());
for (col=0; col < information.width; col++) {
imageFile.read ((char *) tempData, 3 * sizeof(unsigned char));
data[row].push_back ((int) tempData[0]);
}
if (padding)
imageFile.read ((char *) tempData, padding * sizeof(unsigned char));
}
cout << imageFileName << ": " << information.width << " x " << information.height << endl;
// insert transformation code here
// this code simply recreates the original Black-and-White image
for (row=0; row < information.height; row++) {
newData.push_back (vector <int>());
for (col=0; col < information.width; col++) {
newData[row].push_back (data[row][col]);
}
}
// write header to new image file
newImageFile.write ((char *) &header, sizeof(header_type));
newImageFile.write ((char *) &information, sizeof(information_type));
// write new image data to new image file
for (row=0; row < information.height; row++) {
for (col=0; col < information.width; col++) {
tempData[0] = (unsigned char) newData[row][col];
tempData[1] = (unsigned char) newData[row][col];
tempData[2] = (unsigned char) newData[row][col];
newImageFile.write ((char *) tempData, 3 * sizeof(unsigned char));
}
if (padding) {
tempData[0] = 0;
tempData[1] = 0;
tempData[2] = 0;
newImageFile.write ((char *) tempData, padding * sizeof(unsigned char));
}
}
cout << newImageFileName << " done." << endl;
imageFile.close();
newImageFile.close();
return 0;
}
<commit_msg>try algorithm<commit_after>// readWrite-bmp.cc
//
// extracts pixel data from user-specified .bmp file
// inserts data back into new .bmp file
//
// gw
// uncomment for MSVS
// #include "stdafx.h"
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
#include <vector>
#include <cmath>
#include <ctime>
#include <omp.h>
using namespace std;
#pragma pack(1)
typedef struct {
char id[2];
int file_size;
int reserved;
int offset;
} header_type;
#pragma pack(1)
typedef struct {
int header_size;
int width;
int height;
unsigned short int color_planes;
unsigned short int color_depth;
unsigned int compression;
int image_size;
int xresolution;
int yresolution;
int num_colors;
int num_important_colors;
} information_type;
int main(int argc, char* argv[])
{
header_type header;
information_type information;
string imageFileName, newImageFileName;
unsigned char tempData[3];
int row, col, row_bytes, padding;
vector <vector <int> > data, newData;
// prepare files
cout << "Original imagefile? ";
cin >> imageFileName;
ifstream imageFile;
imageFile.open (imageFileName.c_str(), ios::binary);
if (!imageFile) {
cerr << "file not found" << endl;
exit(-1);
}
cout << "New imagefile name? ";
cin >> newImageFileName;
ofstream newImageFile;
newImageFile.open (newImageFileName.c_str(), ios::binary);
// read file header
imageFile.read ((char *) &header, sizeof(header_type));
if (header.id[0] != 'B' || header.id[1] != 'M') {
cerr << "Does not appear to be a .bmp file. Goodbye." << endl;
exit(-1);
}
// read/compute image information
imageFile.read ((char *) &information, sizeof(information_type));
row_bytes = information.width * 3;
padding = row_bytes % 4;
if (padding)
padding = 4 - padding;
// extract image data, initialize vectors
// pad row
data.push_back(vector <int>());
for (row=1; row <= information.height; row++) {
data.push_back (vector <int>());
// pad column
data[row].push_back(0);
for (col=0; col < information.width; col++) {
imageFile.read ((char *) tempData, 3 * sizeof(unsigned char));
data[row].push_back ((int) tempData[0]);
}
if (padding)
imageFile.read ((char *) tempData, padding * sizeof(unsigned char));
}
cout << imageFileName << ": " << information.width << " x " << information.height << endl;
// insert transformation code here
// this code simply recreates the original Black-and-White image
int x_0, x_1, x_2, x_3, x_5, x_6, x_7, x_8, sum_0, sum_1;
for (row=1; row < information.height; row++) {
newData.push_back (vector <int>());
for (col=1; col < information.width; col++) {
// newData[row].push_back (data[row][col]);
x_0 = data[row-1][col-1];
x_1 = data[row-1][col];
x_2 = data[row-1][col+1];
x_3 = data[row][col-1];
x_5 = data[row][col+1];
x_6 = data[row+1][col-1];
x_7 = data[row+1][col];
x_8 = data[row+1][col+1];
sum_0 = (x_0 + (2*x_1) + x_2) - (x_6 + (2*x_7) + x_8);
sum_1 = (x_2 + (2*x_5) + x_8) - (x_0 + (2*x_3) + x_6);
newData[row].push_back (sum_0 + sum_1);
}
}
// write header to new image file
newImageFile.write ((char *) &header, sizeof(header_type));
newImageFile.write ((char *) &information, sizeof(information_type));
// write new image data to new image file
for (row=0; row < information.height; row++) {
for (col=0; col < information.width; col++) {
tempData[0] = (unsigned char) newData[row][col];
tempData[1] = (unsigned char) newData[row][col];
tempData[2] = (unsigned char) newData[row][col];
newImageFile.write ((char *) tempData, 3 * sizeof(unsigned char));
}
if (padding) {
tempData[0] = 0;
tempData[1] = 0;
tempData[2] = 0;
newImageFile.write ((char *) tempData, padding * sizeof(unsigned char));
}
}
cout << newImageFileName << " done." << endl;
imageFile.close();
newImageFile.close();
return 0;
}
<|endoftext|> |
<commit_before>
#include "VideoSource.h"
#include "DestinNetworkAlt.h"
int main(int argc, char ** argv){
VideoSource vs(true, "");
SupportedImageWidths siw = W512;
uint centroid_counts[] = {20,16,14,12,10,8,4,2};
destin_network_alt network(siw, 8, centroid_counts);
vs.enableDisplayWindow();
while(vs.grab()){
network.doDestin(vs. getOutput());
}
return 0;
}
<commit_msg>forgot to trasnfer image to card<commit_after>
#include "VideoSource.h"
#include "DestinNetworkAlt.h"
#include "Transporter.h"
#include "stdio.h"
int main(int argc, char ** argv){
VideoSource vs(true, "");
SupportedImageWidths siw = W512;
uint centroid_counts[] = {20,16,14,12,10,8,4,2};
destin_network_alt network(siw, 8, centroid_counts);
vs.enableDisplayWindow();
Transporter t(512 * 512);
float * beliefs;
while(vs.grab()){
t.setHostSourceImage(vs.getOutput());
t.transport(); //move video from host to card
network.doDestin(t.getDeviceDest());
beliefs = network.getNodeBeliefs(7,0,0);
//printf("%c[2A", 27); //earase two lines so window doesn't scroll
printf("0: %f\n");
printf("1: %f\n");
}
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************/
/* button.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "button.h"
#include "print_string.h"
#include "servers/visual_server.h"
#include "translation.h"
Size2 Button::get_minimum_size() const {
Size2 minsize = get_font("font")->get_string_size(xl_text);
if (clip_text)
minsize.width = 0;
Ref<Texture> _icon;
if (icon.is_null() && has_icon("icon"))
_icon = Control::get_icon("icon");
else
_icon = icon;
if (!_icon.is_null()) {
minsize.height = MAX(minsize.height, _icon->get_height());
minsize.width += _icon->get_width();
if (xl_text != "")
minsize.width += get_constant("hseparation");
}
return get_stylebox("normal")->get_minimum_size() + minsize;
}
void Button::_notification(int p_what) {
if (p_what == NOTIFICATION_TRANSLATION_CHANGED) {
xl_text = tr(text);
minimum_size_changed();
update();
}
if (p_what == NOTIFICATION_DRAW) {
RID ci = get_canvas_item();
Size2 size = get_size();
Color color;
Color color_icon(1, 1, 1, 1);
//print_line(get_text()+": "+itos(is_flat())+" hover "+itos(get_draw_mode()));
Ref<StyleBox> style = get_stylebox("normal");
switch (get_draw_mode()) {
case DRAW_NORMAL: {
style = get_stylebox("normal");
if (!flat)
style->draw(ci, Rect2(Point2(0, 0), size));
color = get_color("font_color");
if (has_color("icon_color_normal"))
color_icon = get_color("icon_color_normal");
} break;
case DRAW_PRESSED: {
style = get_stylebox("pressed");
if (!flat)
style->draw(ci, Rect2(Point2(0, 0), size));
if (has_color("font_color_pressed"))
color = get_color("font_color_pressed");
else
color = get_color("font_color");
if (has_color("icon_color_pressed"))
color_icon = get_color("icon_color_pressed");
} break;
case DRAW_HOVER: {
style = get_stylebox("hover");
if (!flat)
style->draw(ci, Rect2(Point2(0, 0), size));
color = get_color("font_color_hover");
if (has_color("icon_color_hover"))
color_icon = get_color("icon_color_hover");
} break;
case DRAW_DISABLED: {
style = get_stylebox("disabled");
if (!flat)
style->draw(ci, Rect2(Point2(0, 0), size));
color = get_color("font_color_disabled");
if (has_color("icon_color_disabled"))
color_icon = get_color("icon_color_disabled");
} break;
}
if (has_focus()) {
Ref<StyleBox> style = get_stylebox("focus");
style->draw(ci, Rect2(Point2(), size));
}
Ref<Font> font = get_font("font");
Ref<Texture> _icon;
if (icon.is_null() && has_icon("icon"))
_icon = Control::get_icon("icon");
else
_icon = icon;
Point2 icon_ofs = (!_icon.is_null()) ? Point2(_icon->get_width() + get_constant("hseparation"), 0) : Point2();
int text_clip = size.width - style->get_minimum_size().width - icon_ofs.width;
Point2 text_ofs = (size - style->get_minimum_size() - icon_ofs - font->get_string_size(xl_text)) / 2.0;
switch (align) {
case ALIGN_LEFT: {
text_ofs.x = style->get_margin(MARGIN_LEFT) + icon_ofs.x;
text_ofs.y += style->get_offset().y;
} break;
case ALIGN_CENTER: {
if (text_ofs.x < 0)
text_ofs.x = 0;
text_ofs += icon_ofs;
text_ofs += style->get_offset();
} break;
case ALIGN_RIGHT: {
text_ofs.x = size.x - style->get_margin(MARGIN_RIGHT) - font->get_string_size(xl_text).x;
text_ofs.y += style->get_offset().y;
} break;
}
text_ofs.y += font->get_ascent();
font->draw(ci, text_ofs.floor(), xl_text, color, clip_text ? text_clip : -1);
if (!_icon.is_null()) {
int valign = size.height - style->get_minimum_size().y;
if (is_disabled())
color_icon.a = 0.4;
_icon->draw(ci, style->get_offset() + Point2(0, Math::floor((valign - _icon->get_height()) / 2.0)), color_icon);
}
}
}
void Button::set_text(const String &p_text) {
if (text == p_text)
return;
text = p_text;
xl_text = tr(p_text);
update();
_change_notify("text");
minimum_size_changed();
}
String Button::get_text() const {
return text;
}
void Button::set_icon(const Ref<Texture> &p_icon) {
if (icon == p_icon)
return;
icon = p_icon;
update();
_change_notify("icon");
minimum_size_changed();
}
Ref<Texture> Button::get_icon() const {
return icon;
}
void Button::set_flat(bool p_flat) {
flat = p_flat;
update();
_change_notify("flat");
}
bool Button::is_flat() const {
return flat;
}
void Button::set_clip_text(bool p_clip_text) {
clip_text = p_clip_text;
update();
minimum_size_changed();
}
bool Button::get_clip_text() const {
return clip_text;
}
void Button::set_text_align(TextAlign p_align) {
align = p_align;
update();
}
Button::TextAlign Button::get_text_align() const {
return align;
}
void Button::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_text", "text"), &Button::set_text);
ClassDB::bind_method(D_METHOD("get_text"), &Button::get_text);
ClassDB::bind_method(D_METHOD("set_button_icon", "texture"), &Button::set_icon);
ClassDB::bind_method(D_METHOD("get_button_icon"), &Button::get_icon);
ClassDB::bind_method(D_METHOD("set_flat", "enabled"), &Button::set_flat);
ClassDB::bind_method(D_METHOD("set_clip_text", "enabled"), &Button::set_clip_text);
ClassDB::bind_method(D_METHOD("get_clip_text"), &Button::get_clip_text);
ClassDB::bind_method(D_METHOD("set_text_align", "align"), &Button::set_text_align);
ClassDB::bind_method(D_METHOD("get_text_align"), &Button::get_text_align);
ClassDB::bind_method(D_METHOD("is_flat"), &Button::is_flat);
BIND_ENUM_CONSTANT(ALIGN_LEFT);
BIND_ENUM_CONSTANT(ALIGN_CENTER);
BIND_ENUM_CONSTANT(ALIGN_RIGHT);
ADD_PROPERTYNZ(PropertyInfo(Variant::STRING, "text", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT_INTL), "set_text", "get_text");
ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT, "icon", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_button_icon", "get_button_icon");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "flat"), "set_flat", "is_flat");
ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "clip_text"), "set_clip_text", "get_clip_text");
ADD_PROPERTYNO(PropertyInfo(Variant::INT, "align", PROPERTY_HINT_ENUM, "Left,Center,Right"), "set_text_align", "get_text_align");
}
Button::Button(const String &p_text) {
flat = false;
clip_text = false;
set_mouse_filter(MOUSE_FILTER_STOP);
set_text(p_text);
align = ALIGN_CENTER;
}
Button::~Button() {
}
<commit_msg>Fix align=center info is not saved with CheckBox & CheckButton<commit_after>/*************************************************************************/
/* button.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "button.h"
#include "print_string.h"
#include "servers/visual_server.h"
#include "translation.h"
Size2 Button::get_minimum_size() const {
Size2 minsize = get_font("font")->get_string_size(xl_text);
if (clip_text)
minsize.width = 0;
Ref<Texture> _icon;
if (icon.is_null() && has_icon("icon"))
_icon = Control::get_icon("icon");
else
_icon = icon;
if (!_icon.is_null()) {
minsize.height = MAX(minsize.height, _icon->get_height());
minsize.width += _icon->get_width();
if (xl_text != "")
minsize.width += get_constant("hseparation");
}
return get_stylebox("normal")->get_minimum_size() + minsize;
}
void Button::_notification(int p_what) {
if (p_what == NOTIFICATION_TRANSLATION_CHANGED) {
xl_text = tr(text);
minimum_size_changed();
update();
}
if (p_what == NOTIFICATION_DRAW) {
RID ci = get_canvas_item();
Size2 size = get_size();
Color color;
Color color_icon(1, 1, 1, 1);
//print_line(get_text()+": "+itos(is_flat())+" hover "+itos(get_draw_mode()));
Ref<StyleBox> style = get_stylebox("normal");
switch (get_draw_mode()) {
case DRAW_NORMAL: {
style = get_stylebox("normal");
if (!flat)
style->draw(ci, Rect2(Point2(0, 0), size));
color = get_color("font_color");
if (has_color("icon_color_normal"))
color_icon = get_color("icon_color_normal");
} break;
case DRAW_PRESSED: {
style = get_stylebox("pressed");
if (!flat)
style->draw(ci, Rect2(Point2(0, 0), size));
if (has_color("font_color_pressed"))
color = get_color("font_color_pressed");
else
color = get_color("font_color");
if (has_color("icon_color_pressed"))
color_icon = get_color("icon_color_pressed");
} break;
case DRAW_HOVER: {
style = get_stylebox("hover");
if (!flat)
style->draw(ci, Rect2(Point2(0, 0), size));
color = get_color("font_color_hover");
if (has_color("icon_color_hover"))
color_icon = get_color("icon_color_hover");
} break;
case DRAW_DISABLED: {
style = get_stylebox("disabled");
if (!flat)
style->draw(ci, Rect2(Point2(0, 0), size));
color = get_color("font_color_disabled");
if (has_color("icon_color_disabled"))
color_icon = get_color("icon_color_disabled");
} break;
}
if (has_focus()) {
Ref<StyleBox> style = get_stylebox("focus");
style->draw(ci, Rect2(Point2(), size));
}
Ref<Font> font = get_font("font");
Ref<Texture> _icon;
if (icon.is_null() && has_icon("icon"))
_icon = Control::get_icon("icon");
else
_icon = icon;
Point2 icon_ofs = (!_icon.is_null()) ? Point2(_icon->get_width() + get_constant("hseparation"), 0) : Point2();
int text_clip = size.width - style->get_minimum_size().width - icon_ofs.width;
Point2 text_ofs = (size - style->get_minimum_size() - icon_ofs - font->get_string_size(xl_text)) / 2.0;
switch (align) {
case ALIGN_LEFT: {
text_ofs.x = style->get_margin(MARGIN_LEFT) + icon_ofs.x;
text_ofs.y += style->get_offset().y;
} break;
case ALIGN_CENTER: {
if (text_ofs.x < 0)
text_ofs.x = 0;
text_ofs += icon_ofs;
text_ofs += style->get_offset();
} break;
case ALIGN_RIGHT: {
text_ofs.x = size.x - style->get_margin(MARGIN_RIGHT) - font->get_string_size(xl_text).x;
text_ofs.y += style->get_offset().y;
} break;
}
text_ofs.y += font->get_ascent();
font->draw(ci, text_ofs.floor(), xl_text, color, clip_text ? text_clip : -1);
if (!_icon.is_null()) {
int valign = size.height - style->get_minimum_size().y;
if (is_disabled())
color_icon.a = 0.4;
_icon->draw(ci, style->get_offset() + Point2(0, Math::floor((valign - _icon->get_height()) / 2.0)), color_icon);
}
}
}
void Button::set_text(const String &p_text) {
if (text == p_text)
return;
text = p_text;
xl_text = tr(p_text);
update();
_change_notify("text");
minimum_size_changed();
}
String Button::get_text() const {
return text;
}
void Button::set_icon(const Ref<Texture> &p_icon) {
if (icon == p_icon)
return;
icon = p_icon;
update();
_change_notify("icon");
minimum_size_changed();
}
Ref<Texture> Button::get_icon() const {
return icon;
}
void Button::set_flat(bool p_flat) {
flat = p_flat;
update();
_change_notify("flat");
}
bool Button::is_flat() const {
return flat;
}
void Button::set_clip_text(bool p_clip_text) {
clip_text = p_clip_text;
update();
minimum_size_changed();
}
bool Button::get_clip_text() const {
return clip_text;
}
void Button::set_text_align(TextAlign p_align) {
align = p_align;
update();
}
Button::TextAlign Button::get_text_align() const {
return align;
}
void Button::_bind_methods() {
ClassDB::bind_method(D_METHOD("set_text", "text"), &Button::set_text);
ClassDB::bind_method(D_METHOD("get_text"), &Button::get_text);
ClassDB::bind_method(D_METHOD("set_button_icon", "texture"), &Button::set_icon);
ClassDB::bind_method(D_METHOD("get_button_icon"), &Button::get_icon);
ClassDB::bind_method(D_METHOD("set_flat", "enabled"), &Button::set_flat);
ClassDB::bind_method(D_METHOD("set_clip_text", "enabled"), &Button::set_clip_text);
ClassDB::bind_method(D_METHOD("get_clip_text"), &Button::get_clip_text);
ClassDB::bind_method(D_METHOD("set_text_align", "align"), &Button::set_text_align);
ClassDB::bind_method(D_METHOD("get_text_align"), &Button::get_text_align);
ClassDB::bind_method(D_METHOD("is_flat"), &Button::is_flat);
BIND_ENUM_CONSTANT(ALIGN_LEFT);
BIND_ENUM_CONSTANT(ALIGN_CENTER);
BIND_ENUM_CONSTANT(ALIGN_RIGHT);
ADD_PROPERTYNZ(PropertyInfo(Variant::STRING, "text", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_DEFAULT_INTL), "set_text", "get_text");
ADD_PROPERTYNZ(PropertyInfo(Variant::OBJECT, "icon", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_button_icon", "get_button_icon");
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "flat"), "set_flat", "is_flat");
ADD_PROPERTYNZ(PropertyInfo(Variant::BOOL, "clip_text"), "set_clip_text", "get_clip_text");
ADD_PROPERTY(PropertyInfo(Variant::INT, "align", PROPERTY_HINT_ENUM, "Left,Center,Right"), "set_text_align", "get_text_align");
}
Button::Button(const String &p_text) {
flat = false;
clip_text = false;
set_mouse_filter(MOUSE_FILTER_STOP);
set_text(p_text);
align = ALIGN_CENTER;
}
Button::~Button() {
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2004-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
// Copyright 2004-present Facebook. All rights reserved.
#include "Route.h"
#include "fboss/agent/state/NodeBase-defs.h"
#include "fboss/agent/FbossError.h"
#include "fboss/agent/AddressUtil.h"
using facebook::network::toBinaryAddress;
namespace {
constexpr auto kPrefix = "prefix";
constexpr auto kNextHops = "nexthops"; // Necessary for reading old data
constexpr auto kNextHopsMulti = "nexthopsmulti";
constexpr auto kFwdInfo = "forwardingInfo";
constexpr auto kFlags = "flags";
}
namespace facebook { namespace fboss {
using std::string;
using folly::IPAddress;
// RouteFields<> Class
template<typename AddrT>
RouteFields<AddrT>::RouteFields(const Prefix& prefix) : prefix(prefix) {
}
template<typename AddrT>
RouteFields<AddrT>::RouteFields(const RouteFields& rf,
CopyBehavior copyBehavior) : prefix(rf.prefix) {
switch(copyBehavior) {
case COPY_PREFIX_AND_NEXTHOPS:
nexthopsmulti = rf.nexthopsmulti;
break;
default:
throw FbossError("Unknown CopyBehavior passed to RouteFields ctor");
}
}
template<typename AddrT>
bool RouteFields<AddrT>::operator==(const RouteFields& rf) const {
return (flags == rf.flags
&& prefix == rf.prefix
&& nexthopsmulti == rf.nexthopsmulti
&& fwd == rf.fwd);
}
template<typename AddrT>
folly::dynamic RouteFields<AddrT>::toFollyDynamic() const {
folly::dynamic routeFields = folly::dynamic::object;
routeFields[kPrefix] = prefix.toFollyDynamic();
routeFields[kNextHopsMulti] = nexthopsmulti.toFollyDynamic();
routeFields[kFwdInfo] = fwd.toFollyDynamic();
routeFields[kFlags] = flags;
return routeFields;
}
template<typename AddrT>
RouteDetails RouteFields<AddrT>::toRouteDetails() const {
RouteDetails rd;
// Add the prefix
rd.dest.ip = toBinaryAddress(prefix.network);
rd.dest.prefixLength = prefix.mask;
// Add the action
rd.action = forwardActionStr(fwd.getAction());
// Add the forwarding info
for (const auto& nh : fwd.getNexthops()) {
IfAndIP ifAndIp;
ifAndIp.interfaceID = nh.intf;
ifAndIp.ip = toBinaryAddress(nh.nexthop);
rd.fwdInfo.push_back(ifAndIp);
}
// Add the multi-nexthops
rd.nextHopMulti = nexthopsmulti.toThrift();
return rd;
}
template<typename AddrT>
RouteFields<AddrT>
RouteFields<AddrT>::fromFollyDynamic(const folly::dynamic& routeJson) {
RouteFields rt(Prefix::fromFollyDynamic(routeJson[kPrefix]));
if (routeJson.find(kNextHops) != routeJson.items().end()) {
// If routeJson[kNextHops] exists, we're reading json that was serialized
// by an older version of the code. We will assume the nexthops were
// provided by BGPd. It kind of doesn't matter. In about 15 seconds, BGPd
// will have assembled a new set of routes, and will replace these routes
// en masse.
//
// This code supporting routeJson[kNextHops] can be removed once all fboss
// switches have been upgraded.
//
// This check for size is necessary since the old code serialized nexthop
// lists of size zero even for non-NEXTHOPS routes.
if (routeJson[kNextHops].size() > 0) {
RouteNextHops nhops;
for (const auto& nhop: routeJson[kNextHops]) {
nhops.emplace(nhop.stringPiece());
}
rt.nexthopsmulti.update(ClientID((int32_t)StdClientIds::BGPD), nhops);
}
} else {
rt.nexthopsmulti =
std::move(RouteNextHopsMulti::
fromFollyDynamic(routeJson[kNextHopsMulti]));
}
rt.fwd = std::move(RouteForwardInfo::fromFollyDynamic(routeJson[kFwdInfo]));
rt.flags = routeJson[kFlags].asInt();
return rt;
}
template class RouteFields<folly::IPAddressV4>;
template class RouteFields<folly::IPAddressV6>;
// Route<> Class
template<typename AddrT>
Route<AddrT>::Route(const Prefix& prefix,
InterfaceID intf, const IPAddress& addr)
: RouteBase(prefix) {
update(intf, addr);
}
template<typename AddrT>
Route<AddrT>::Route(const Prefix& prefix, ClientID clientId,
const RouteNextHops& nhs)
: RouteBase(prefix) {
update(clientId, nhs);
}
template<typename AddrT>
Route<AddrT>::Route(const Prefix& prefix, ClientID client, RouteNextHops&& nhs)
: RouteBase(prefix) {
update(client, std::move(nhs));
}
template<typename AddrT>
Route<AddrT>::Route(const Prefix& prefix, Action action)
: RouteBase(prefix) {
update(action);
}
template<typename AddrT>
Route<AddrT>::~Route() {
}
template<typename AddrT>
std::string Route<AddrT>::str() const {
std::string ret;
ret = folly::to<string>(prefix(), '@');
ret.append(RouteBase::getFields()->nexthopsmulti.str());
ret.append(" State:");
if (isConnected()) {
ret.append("C");
}
if (isResolved()) {
ret.append("R");
}
if (isUnresolvable()) {
ret.append("U");
}
if (isProcessing()) {
ret.append("P");
}
ret.append(", => ");
ret.append(RouteBase::getFields()->fwd.str());
return ret;
}
template<typename AddrT>
bool Route<AddrT>::isSame(InterfaceID intf, const IPAddress& addr) const {
if (!isConnected()) {
return false;
}
const auto& fwd = RouteBase::getFields()->fwd;
const auto& nhops = fwd.getNexthops();
CHECK_EQ(nhops.size(), 1);
const auto iter = nhops.begin();
return iter->intf == intf && iter->nexthop == addr;
}
template<typename AddrT>
bool Route<AddrT>::isSame(ClientID clientId, const RouteNextHops& nhs) const {
return RouteBase::getFields()->nexthopsmulti.isSame(clientId, nhs);
}
template<typename AddrT>
bool Route<AddrT>::isSame(Action action) const {
CHECK(action == Action::DROP || action == Action::TO_CPU);
if (action == Action::DROP) {
return isDrop();
} else {
return isToCPU();
}
}
template<typename AddrT>
bool Route<AddrT>::isSame(const Route<AddrT>* rt) const {
return *this->getFields() == *rt->getFields();
}
template<typename AddrT>
void Route<AddrT>::update(InterfaceID intf, const IPAddress& addr) {
// clear all existing nexthop info
RouteBase::writableFields()->nexthopsmulti.clear();
// replace the forwarding info for this route with just one nexthop
RouteBase::writableFields()->fwd.setNexthops(intf, addr);
setFlagsConnected();
}
template<typename AddrT>
void Route<AddrT>::updateNexthopCommon(const RouteNextHops& nhs) {
if (!nhs.size()) {
throw FbossError("Update with an empty set of nexthops for route ", str());
}
RouteBase::writableFields()->fwd.reset();
clearFlags();
}
template<typename AddrT>
void Route<AddrT>::update(ClientID clientid, const RouteNextHops& nhs) {
updateNexthopCommon(nhs);
RouteBase::writableFields()->nexthopsmulti.update(clientid, nhs);
}
template<typename AddrT>
void Route<AddrT>::update(ClientID clientid, RouteNextHops&& nhs) {
updateNexthopCommon(nhs);
RouteBase::writableFields()->nexthopsmulti.update(clientid, std::move(nhs));
}
template<typename AddrT>
void Route<AddrT>::update(Action action) {
CHECK(action == Action::DROP || action == Action::TO_CPU);
// clear all existing nexthop info
RouteBase::writableFields()->nexthopsmulti.clear();
if (action == Action::DROP) {
this->writableFields()->fwd.setDrop();
setFlagsResolved();
} else {
this->writableFields()->fwd.setToCPU();
setFlagsResolved();
}
}
template<typename AddrT>
void Route<AddrT>::delNexthopsForClient(ClientID clientId) {
RouteBase::writableFields()->nexthopsmulti.delNexthopsForClient(clientId);
}
template<typename AddrT>
void Route<AddrT>::setUnresolvable() {
RouteBase::writableFields()->fwd.reset();
setFlagsUnresolvable();
}
template class Route<folly::IPAddressV4>;
template class Route<folly::IPAddressV6>;
}}
<commit_msg>Write the RIB in a form that older code can read.<commit_after>/*
* Copyright (c) 2004-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
// Copyright 2004-present Facebook. All rights reserved.
#include "Route.h"
#include "fboss/agent/state/NodeBase-defs.h"
#include "fboss/agent/FbossError.h"
#include "fboss/agent/AddressUtil.h"
using facebook::network::toBinaryAddress;
namespace {
constexpr auto kPrefix = "prefix";
constexpr auto kNextHops = "nexthops"; // Necessary for reading old data
constexpr auto kNextHopsMulti = "nexthopsmulti";
constexpr auto kFwdInfo = "forwardingInfo";
constexpr auto kFlags = "flags";
}
namespace facebook { namespace fboss {
using std::string;
using folly::IPAddress;
// RouteFields<> Class
template<typename AddrT>
RouteFields<AddrT>::RouteFields(const Prefix& prefix) : prefix(prefix) {
}
template<typename AddrT>
RouteFields<AddrT>::RouteFields(const RouteFields& rf,
CopyBehavior copyBehavior) : prefix(rf.prefix) {
switch(copyBehavior) {
case COPY_PREFIX_AND_NEXTHOPS:
nexthopsmulti = rf.nexthopsmulti;
break;
default:
throw FbossError("Unknown CopyBehavior passed to RouteFields ctor");
}
}
template<typename AddrT>
bool RouteFields<AddrT>::operator==(const RouteFields& rf) const {
return (flags == rf.flags
&& prefix == rf.prefix
&& nexthopsmulti == rf.nexthopsmulti
&& fwd == rf.fwd);
}
template<typename AddrT>
folly::dynamic RouteFields<AddrT>::toFollyDynamic() const {
folly::dynamic routeFields = folly::dynamic::object;
routeFields[kPrefix] = prefix.toFollyDynamic();
routeFields[kNextHopsMulti] = nexthopsmulti.toFollyDynamic();
//
// For backward compatibility, we will also write the 1-best
// nexthops list to the [kNextHops] field. This is just so,
// if a machine is reverted from a multi-nexthop code base back
// to a code base that's not aware of multi-nexthops, it can continue
// serving traffic without an outage. Please remove this code
// once all developers have rebased beyond the diff containing this
// message.
folly::dynamic nhopsList = folly::dynamic::array;
if (!nexthopsmulti.isEmpty()) {
for (const auto& nhop: nexthopsmulti.bestNextHopList()) {
nhopsList.push_back(nhop.str());
}
}
routeFields[kNextHops] = std::move(nhopsList);
// End of backward-compatibility code
//
routeFields[kFwdInfo] = fwd.toFollyDynamic();
routeFields[kFlags] = flags;
return routeFields;
}
template<typename AddrT>
RouteDetails RouteFields<AddrT>::toRouteDetails() const {
RouteDetails rd;
// Add the prefix
rd.dest.ip = toBinaryAddress(prefix.network);
rd.dest.prefixLength = prefix.mask;
// Add the action
rd.action = forwardActionStr(fwd.getAction());
// Add the forwarding info
for (const auto& nh : fwd.getNexthops()) {
IfAndIP ifAndIp;
ifAndIp.interfaceID = nh.intf;
ifAndIp.ip = toBinaryAddress(nh.nexthop);
rd.fwdInfo.push_back(ifAndIp);
}
// Add the multi-nexthops
rd.nextHopMulti = nexthopsmulti.toThrift();
return rd;
}
template<typename AddrT>
RouteFields<AddrT>
RouteFields<AddrT>::fromFollyDynamic(const folly::dynamic& routeJson) {
RouteFields rt(Prefix::fromFollyDynamic(routeJson[kPrefix]));
if (routeJson.find(kNextHopsMulti) != routeJson.items().end()) {
rt.nexthopsmulti =
std::move(RouteNextHopsMulti::
fromFollyDynamic(routeJson[kNextHopsMulti]));
} else {
// If routeJson[kNextMultiHops] does not exist, we're reading json that
// was serialized by an older version of the code.
// We will assume the nexthops were provided by BGPd.
// It kind of doesn't matter. In about 15 seconds, BGPd will have
// assembled a new set of routes, and will replace these routes en masse.
//
// This code supporting routeJson[kNextHops] can be removed once all fboss
// switches have been upgraded.
//
// This check for size is necessary since the old code serialized nexthop
// lists of size zero even for non-NEXTHOPS routes.
if (routeJson[kNextHops].size() > 0) {
RouteNextHops nhops;
for (const auto& nhop: routeJson[kNextHops]) {
nhops.emplace(nhop.stringPiece());
}
rt.nexthopsmulti.update(ClientID((int32_t)StdClientIds::BGPD), nhops);
}
}
rt.fwd = std::move(RouteForwardInfo::fromFollyDynamic(routeJson[kFwdInfo]));
rt.flags = routeJson[kFlags].asInt();
return rt;
}
template class RouteFields<folly::IPAddressV4>;
template class RouteFields<folly::IPAddressV6>;
// Route<> Class
template<typename AddrT>
Route<AddrT>::Route(const Prefix& prefix,
InterfaceID intf, const IPAddress& addr)
: RouteBase(prefix) {
update(intf, addr);
}
template<typename AddrT>
Route<AddrT>::Route(const Prefix& prefix, ClientID clientId,
const RouteNextHops& nhs)
: RouteBase(prefix) {
update(clientId, nhs);
}
template<typename AddrT>
Route<AddrT>::Route(const Prefix& prefix, ClientID client, RouteNextHops&& nhs)
: RouteBase(prefix) {
update(client, std::move(nhs));
}
template<typename AddrT>
Route<AddrT>::Route(const Prefix& prefix, Action action)
: RouteBase(prefix) {
update(action);
}
template<typename AddrT>
Route<AddrT>::~Route() {
}
template<typename AddrT>
std::string Route<AddrT>::str() const {
std::string ret;
ret = folly::to<string>(prefix(), '@');
ret.append(RouteBase::getFields()->nexthopsmulti.str());
ret.append(" State:");
if (isConnected()) {
ret.append("C");
}
if (isResolved()) {
ret.append("R");
}
if (isUnresolvable()) {
ret.append("U");
}
if (isProcessing()) {
ret.append("P");
}
ret.append(", => ");
ret.append(RouteBase::getFields()->fwd.str());
return ret;
}
template<typename AddrT>
bool Route<AddrT>::isSame(InterfaceID intf, const IPAddress& addr) const {
if (!isConnected()) {
return false;
}
const auto& fwd = RouteBase::getFields()->fwd;
const auto& nhops = fwd.getNexthops();
CHECK_EQ(nhops.size(), 1);
const auto iter = nhops.begin();
return iter->intf == intf && iter->nexthop == addr;
}
template<typename AddrT>
bool Route<AddrT>::isSame(ClientID clientId, const RouteNextHops& nhs) const {
return RouteBase::getFields()->nexthopsmulti.isSame(clientId, nhs);
}
template<typename AddrT>
bool Route<AddrT>::isSame(Action action) const {
CHECK(action == Action::DROP || action == Action::TO_CPU);
if (action == Action::DROP) {
return isDrop();
} else {
return isToCPU();
}
}
template<typename AddrT>
bool Route<AddrT>::isSame(const Route<AddrT>* rt) const {
return *this->getFields() == *rt->getFields();
}
template<typename AddrT>
void Route<AddrT>::update(InterfaceID intf, const IPAddress& addr) {
// clear all existing nexthop info
RouteBase::writableFields()->nexthopsmulti.clear();
// replace the forwarding info for this route with just one nexthop
RouteBase::writableFields()->fwd.setNexthops(intf, addr);
setFlagsConnected();
}
template<typename AddrT>
void Route<AddrT>::updateNexthopCommon(const RouteNextHops& nhs) {
if (!nhs.size()) {
throw FbossError("Update with an empty set of nexthops for route ", str());
}
RouteBase::writableFields()->fwd.reset();
clearFlags();
}
template<typename AddrT>
void Route<AddrT>::update(ClientID clientid, const RouteNextHops& nhs) {
updateNexthopCommon(nhs);
RouteBase::writableFields()->nexthopsmulti.update(clientid, nhs);
}
template<typename AddrT>
void Route<AddrT>::update(ClientID clientid, RouteNextHops&& nhs) {
updateNexthopCommon(nhs);
RouteBase::writableFields()->nexthopsmulti.update(clientid, std::move(nhs));
}
template<typename AddrT>
void Route<AddrT>::update(Action action) {
CHECK(action == Action::DROP || action == Action::TO_CPU);
// clear all existing nexthop info
RouteBase::writableFields()->nexthopsmulti.clear();
if (action == Action::DROP) {
this->writableFields()->fwd.setDrop();
setFlagsResolved();
} else {
this->writableFields()->fwd.setToCPU();
setFlagsResolved();
}
}
template<typename AddrT>
void Route<AddrT>::delNexthopsForClient(ClientID clientId) {
RouteBase::writableFields()->nexthopsmulti.delNexthopsForClient(clientId);
}
template<typename AddrT>
void Route<AddrT>::setUnresolvable() {
RouteBase::writableFields()->fwd.reset();
setFlagsUnresolvable();
}
template class Route<folly::IPAddressV4>;
template class Route<folly::IPAddressV6>;
}}
<|endoftext|> |
<commit_before>/**
* @copyright
* ====================================================================
* Copyright (c) 2007 CollabNet. All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://subversion.tigris.org/license-1.html.
* If newer versions of this license are posted there, you may use a
* newer version instead, at your option.
*
* This software consists of voluntary contributions made by many
* individuals. For exact contribution history, see the revision
* history and logs, available at http://subversion.tigris.org/.
* ====================================================================
* @endcopyright
*
* @file StatusCallback.cpp
* @brief Implementation of the class StatusCallback
*/
#include "StatusCallback.h"
#include "EnumMapper.h"
#include "SVNClient.h"
#include "JNIUtil.h"
#include "svn_time.h"
#include "../include/org_tigris_subversion_javahl_NodeKind.h"
#include "../include/org_tigris_subversion_javahl_Revision.h"
#include "../include/org_tigris_subversion_javahl_StatusKind.h"
/**
* Create a StatusCallback object
* @param jcallback the Java callback object.
*/
StatusCallback::StatusCallback(jobject jcallback)
{
m_callback = jcallback;
}
/**
* Destroy a StatusCallback object
*/
StatusCallback::~StatusCallback()
{
// the m_callback does not need to be destroyed, because it is the passed
// in parameter to the Java SVNClient.status method.
}
svn_error_t *
StatusCallback::callback(void *baton,
const char *path,
svn_wc_status2_t *status,
apr_pool_t *pool)
{
if (baton)
((StatusCallback *)baton)->doStatus(path, status);
return SVN_NO_ERROR;
}
/**
* Callback called for a single status item.
*/
svn_error_t *
StatusCallback::doStatus(const char *path, svn_wc_status2_t *status)
{
JNIEnv *env = JNIUtil::getEnv();
static jmethodID mid = 0; // the method id will not change during
// the time this library is loaded, so
// it can be cached.
if (mid == 0)
{
jclass clazz = env->FindClass(JAVA_PACKAGE"/StatusCallback");
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
mid = env->GetMethodID(clazz, "doStatus",
"(L"JAVA_PACKAGE"/Status;)V");
if (JNIUtil::isJavaExceptionThrown() || mid == 0)
return SVN_NO_ERROR;
env->DeleteLocalRef(clazz);
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
}
jobject jStatus = createJavaStatus(path, status);
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
env->CallVoidMethod(m_callback, mid, jStatus);
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
env->DeleteLocalRef(jStatus);
// We return here regardless of whether an exception is thrown or not,
// so we do not need to explicitly check for one.
return SVN_NO_ERROR;
}
jobject
StatusCallback::createJavaStatus(const char *path,
svn_wc_status2_t *status)
{
JNIEnv *env = JNIUtil::getEnv();
jclass clazz = env->FindClass(JAVA_PACKAGE"/Status");
if (JNIUtil::isJavaExceptionThrown())
return NULL;
static jmethodID mid = 0;
if (mid == 0)
{
mid = env->GetMethodID(clazz, "<init>",
"(Ljava/lang/String;Ljava/lang/String;"
"IJJJLjava/lang/String;IIIIZZ"
"Ljava/lang/String;Ljava/lang/String;"
"Ljava/lang/String;Ljava/lang/String;"
"JZLjava/lang/String;Ljava/lang/String;"
"Ljava/lang/String;"
"JLorg/tigris/subversion/javahl/Lock;"
"JJILjava/lang/String;Ljava/lang/String;)V");
if (JNIUtil::isJavaExceptionThrown())
return NULL;
}
jstring jPath = JNIUtil::makeJString(path);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
jstring jUrl = NULL;
jint jNodeKind = org_tigris_subversion_javahl_NodeKind_unknown;
jlong jRevision = org_tigris_subversion_javahl_Revision_SVN_INVALID_REVNUM;
jlong jLastChangedRevision =
org_tigris_subversion_javahl_Revision_SVN_INVALID_REVNUM;
jlong jLastChangedDate = 0;
jstring jLastCommitAuthor = NULL;
jint jTextType = org_tigris_subversion_javahl_StatusKind_none;
jint jPropType = org_tigris_subversion_javahl_StatusKind_none;
jint jRepositoryTextType = org_tigris_subversion_javahl_StatusKind_none;
jint jRepositoryPropType = org_tigris_subversion_javahl_StatusKind_none;
jboolean jIsLocked = JNI_FALSE;
jboolean jIsCopied = JNI_FALSE;
jboolean jIsSwitched = JNI_FALSE;
jstring jConflictOld = NULL;
jstring jConflictNew = NULL;
jstring jConflictWorking = NULL;
jstring jURLCopiedFrom = NULL;
jlong jRevisionCopiedFrom =
org_tigris_subversion_javahl_Revision_SVN_INVALID_REVNUM;
jstring jLockToken = NULL;
jstring jLockComment = NULL;
jstring jLockOwner = NULL;
jlong jLockCreationDate = 0;
jobject jLock = NULL;
jlong jOODLastCmtRevision =
org_tigris_subversion_javahl_Revision_SVN_INVALID_REVNUM;
jlong jOODLastCmtDate = 0;
jint jOODKind = org_tigris_subversion_javahl_NodeKind_none;
jstring jOODLastCmtAuthor = NULL;
jstring jChangelist = NULL;
if (status != NULL)
{
jTextType = EnumMapper::mapStatusKind(status->text_status);
jPropType = EnumMapper::mapStatusKind(status->prop_status);
jRepositoryTextType = EnumMapper::mapStatusKind(
status->repos_text_status);
jRepositoryPropType = EnumMapper::mapStatusKind(
status->repos_prop_status);
jIsCopied = (status->copied == 1) ? JNI_TRUE: JNI_FALSE;
jIsLocked = (status->locked == 1) ? JNI_TRUE: JNI_FALSE;
jIsSwitched = (status->switched == 1) ? JNI_TRUE: JNI_FALSE;
jLock = SVNClient::createJavaLock(status->repos_lock);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
jUrl = JNIUtil::makeJString(status->url);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
jOODLastCmtRevision = status->ood_last_cmt_rev;
jOODLastCmtDate = status->ood_last_cmt_date;
jOODKind = EnumMapper::mapNodeKind(status->ood_kind);
jOODLastCmtAuthor = JNIUtil::makeJString(status->ood_last_cmt_author);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
svn_wc_entry_t *entry = status->entry;
if (entry != NULL)
{
jNodeKind = EnumMapper::mapNodeKind(entry->kind);
jRevision = entry->revision;
jLastChangedRevision = entry->cmt_rev;
jLastChangedDate = entry->cmt_date;
jLastCommitAuthor = JNIUtil::makeJString(entry->cmt_author);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
jConflictNew = JNIUtil::makeJString(entry->conflict_new);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
jConflictOld = JNIUtil::makeJString(entry->conflict_old);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
jConflictWorking= JNIUtil::makeJString(entry->conflict_wrk);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
jURLCopiedFrom = JNIUtil::makeJString(entry->copyfrom_url);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
jRevisionCopiedFrom = entry->copyfrom_rev;
jLockToken = JNIUtil::makeJString(entry->lock_token);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
jLockComment = JNIUtil::makeJString(entry->lock_comment);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
jLockOwner = JNIUtil::makeJString(entry->lock_owner);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
jLockCreationDate = entry->lock_creation_date;
jChangelist = JNIUtil::makeJString(entry->changelist);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
}
}
jobject ret = env->NewObject(clazz, mid, jPath, jUrl, jNodeKind, jRevision,
jLastChangedRevision, jLastChangedDate,
jLastCommitAuthor, jTextType, jPropType,
jRepositoryTextType, jRepositoryPropType,
jIsLocked, jIsCopied, jConflictOld,
jConflictNew, jConflictWorking,
jURLCopiedFrom, jRevisionCopiedFrom,
jIsSwitched, jLockToken, jLockOwner,
jLockComment, jLockCreationDate, jLock,
jOODLastCmtRevision, jOODLastCmtDate,
jOODKind, jOODLastCmtAuthor, jChangelist);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
env->DeleteLocalRef(clazz);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
env->DeleteLocalRef(jPath);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
env->DeleteLocalRef(jUrl);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
env->DeleteLocalRef(jLastCommitAuthor);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
env->DeleteLocalRef(jConflictNew);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
env->DeleteLocalRef(jConflictOld);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
env->DeleteLocalRef(jConflictWorking);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
env->DeleteLocalRef(jURLCopiedFrom);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
env->DeleteLocalRef(jLockComment);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
env->DeleteLocalRef(jLockOwner);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
env->DeleteLocalRef(jLockToken);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
env->DeleteLocalRef(jLock);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
env->DeleteLocalRef(jOODLastCmtAuthor);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
env->DeleteLocalRef(jChangelist);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
return ret;
}
<commit_msg>Followup to r33744 (which was a followup to r33739) by returning the output of a worker method in the JavaHL bindings.<commit_after>/**
* @copyright
* ====================================================================
* Copyright (c) 2007 CollabNet. All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://subversion.tigris.org/license-1.html.
* If newer versions of this license are posted there, you may use a
* newer version instead, at your option.
*
* This software consists of voluntary contributions made by many
* individuals. For exact contribution history, see the revision
* history and logs, available at http://subversion.tigris.org/.
* ====================================================================
* @endcopyright
*
* @file StatusCallback.cpp
* @brief Implementation of the class StatusCallback
*/
#include "StatusCallback.h"
#include "EnumMapper.h"
#include "SVNClient.h"
#include "JNIUtil.h"
#include "svn_time.h"
#include "../include/org_tigris_subversion_javahl_NodeKind.h"
#include "../include/org_tigris_subversion_javahl_Revision.h"
#include "../include/org_tigris_subversion_javahl_StatusKind.h"
/**
* Create a StatusCallback object
* @param jcallback the Java callback object.
*/
StatusCallback::StatusCallback(jobject jcallback)
{
m_callback = jcallback;
}
/**
* Destroy a StatusCallback object
*/
StatusCallback::~StatusCallback()
{
// the m_callback does not need to be destroyed, because it is the passed
// in parameter to the Java SVNClient.status method.
}
svn_error_t *
StatusCallback::callback(void *baton,
const char *path,
svn_wc_status2_t *status,
apr_pool_t *pool)
{
if (baton)
return ((StatusCallback *)baton)->doStatus(path, status);
return SVN_NO_ERROR;
}
/**
* Callback called for a single status item.
*/
svn_error_t *
StatusCallback::doStatus(const char *path, svn_wc_status2_t *status)
{
JNIEnv *env = JNIUtil::getEnv();
static jmethodID mid = 0; // the method id will not change during
// the time this library is loaded, so
// it can be cached.
if (mid == 0)
{
jclass clazz = env->FindClass(JAVA_PACKAGE"/StatusCallback");
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
mid = env->GetMethodID(clazz, "doStatus",
"(L"JAVA_PACKAGE"/Status;)V");
if (JNIUtil::isJavaExceptionThrown() || mid == 0)
return SVN_NO_ERROR;
env->DeleteLocalRef(clazz);
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
}
jobject jStatus = createJavaStatus(path, status);
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
env->CallVoidMethod(m_callback, mid, jStatus);
if (JNIUtil::isJavaExceptionThrown())
return SVN_NO_ERROR;
env->DeleteLocalRef(jStatus);
// We return here regardless of whether an exception is thrown or not,
// so we do not need to explicitly check for one.
return SVN_NO_ERROR;
}
jobject
StatusCallback::createJavaStatus(const char *path,
svn_wc_status2_t *status)
{
JNIEnv *env = JNIUtil::getEnv();
jclass clazz = env->FindClass(JAVA_PACKAGE"/Status");
if (JNIUtil::isJavaExceptionThrown())
return NULL;
static jmethodID mid = 0;
if (mid == 0)
{
mid = env->GetMethodID(clazz, "<init>",
"(Ljava/lang/String;Ljava/lang/String;"
"IJJJLjava/lang/String;IIIIZZ"
"Ljava/lang/String;Ljava/lang/String;"
"Ljava/lang/String;Ljava/lang/String;"
"JZLjava/lang/String;Ljava/lang/String;"
"Ljava/lang/String;"
"JLorg/tigris/subversion/javahl/Lock;"
"JJILjava/lang/String;Ljava/lang/String;)V");
if (JNIUtil::isJavaExceptionThrown())
return NULL;
}
jstring jPath = JNIUtil::makeJString(path);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
jstring jUrl = NULL;
jint jNodeKind = org_tigris_subversion_javahl_NodeKind_unknown;
jlong jRevision = org_tigris_subversion_javahl_Revision_SVN_INVALID_REVNUM;
jlong jLastChangedRevision =
org_tigris_subversion_javahl_Revision_SVN_INVALID_REVNUM;
jlong jLastChangedDate = 0;
jstring jLastCommitAuthor = NULL;
jint jTextType = org_tigris_subversion_javahl_StatusKind_none;
jint jPropType = org_tigris_subversion_javahl_StatusKind_none;
jint jRepositoryTextType = org_tigris_subversion_javahl_StatusKind_none;
jint jRepositoryPropType = org_tigris_subversion_javahl_StatusKind_none;
jboolean jIsLocked = JNI_FALSE;
jboolean jIsCopied = JNI_FALSE;
jboolean jIsSwitched = JNI_FALSE;
jstring jConflictOld = NULL;
jstring jConflictNew = NULL;
jstring jConflictWorking = NULL;
jstring jURLCopiedFrom = NULL;
jlong jRevisionCopiedFrom =
org_tigris_subversion_javahl_Revision_SVN_INVALID_REVNUM;
jstring jLockToken = NULL;
jstring jLockComment = NULL;
jstring jLockOwner = NULL;
jlong jLockCreationDate = 0;
jobject jLock = NULL;
jlong jOODLastCmtRevision =
org_tigris_subversion_javahl_Revision_SVN_INVALID_REVNUM;
jlong jOODLastCmtDate = 0;
jint jOODKind = org_tigris_subversion_javahl_NodeKind_none;
jstring jOODLastCmtAuthor = NULL;
jstring jChangelist = NULL;
if (status != NULL)
{
jTextType = EnumMapper::mapStatusKind(status->text_status);
jPropType = EnumMapper::mapStatusKind(status->prop_status);
jRepositoryTextType = EnumMapper::mapStatusKind(
status->repos_text_status);
jRepositoryPropType = EnumMapper::mapStatusKind(
status->repos_prop_status);
jIsCopied = (status->copied == 1) ? JNI_TRUE: JNI_FALSE;
jIsLocked = (status->locked == 1) ? JNI_TRUE: JNI_FALSE;
jIsSwitched = (status->switched == 1) ? JNI_TRUE: JNI_FALSE;
jLock = SVNClient::createJavaLock(status->repos_lock);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
jUrl = JNIUtil::makeJString(status->url);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
jOODLastCmtRevision = status->ood_last_cmt_rev;
jOODLastCmtDate = status->ood_last_cmt_date;
jOODKind = EnumMapper::mapNodeKind(status->ood_kind);
jOODLastCmtAuthor = JNIUtil::makeJString(status->ood_last_cmt_author);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
svn_wc_entry_t *entry = status->entry;
if (entry != NULL)
{
jNodeKind = EnumMapper::mapNodeKind(entry->kind);
jRevision = entry->revision;
jLastChangedRevision = entry->cmt_rev;
jLastChangedDate = entry->cmt_date;
jLastCommitAuthor = JNIUtil::makeJString(entry->cmt_author);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
jConflictNew = JNIUtil::makeJString(entry->conflict_new);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
jConflictOld = JNIUtil::makeJString(entry->conflict_old);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
jConflictWorking= JNIUtil::makeJString(entry->conflict_wrk);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
jURLCopiedFrom = JNIUtil::makeJString(entry->copyfrom_url);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
jRevisionCopiedFrom = entry->copyfrom_rev;
jLockToken = JNIUtil::makeJString(entry->lock_token);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
jLockComment = JNIUtil::makeJString(entry->lock_comment);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
jLockOwner = JNIUtil::makeJString(entry->lock_owner);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
jLockCreationDate = entry->lock_creation_date;
jChangelist = JNIUtil::makeJString(entry->changelist);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
}
}
jobject ret = env->NewObject(clazz, mid, jPath, jUrl, jNodeKind, jRevision,
jLastChangedRevision, jLastChangedDate,
jLastCommitAuthor, jTextType, jPropType,
jRepositoryTextType, jRepositoryPropType,
jIsLocked, jIsCopied, jConflictOld,
jConflictNew, jConflictWorking,
jURLCopiedFrom, jRevisionCopiedFrom,
jIsSwitched, jLockToken, jLockOwner,
jLockComment, jLockCreationDate, jLock,
jOODLastCmtRevision, jOODLastCmtDate,
jOODKind, jOODLastCmtAuthor, jChangelist);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
env->DeleteLocalRef(clazz);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
env->DeleteLocalRef(jPath);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
env->DeleteLocalRef(jUrl);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
env->DeleteLocalRef(jLastCommitAuthor);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
env->DeleteLocalRef(jConflictNew);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
env->DeleteLocalRef(jConflictOld);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
env->DeleteLocalRef(jConflictWorking);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
env->DeleteLocalRef(jURLCopiedFrom);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
env->DeleteLocalRef(jLockComment);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
env->DeleteLocalRef(jLockOwner);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
env->DeleteLocalRef(jLockToken);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
env->DeleteLocalRef(jLock);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
env->DeleteLocalRef(jOODLastCmtAuthor);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
env->DeleteLocalRef(jChangelist);
if (JNIUtil::isJavaExceptionThrown())
return NULL;
return ret;
}
<|endoftext|> |
<commit_before>#include <chrono>
#include <iostream>
#include <fstream>
#include <numeric>
#include <math.h>
#include <string>
#include <time.h>
#include <iomanip>
#include "mkldnn.hpp"
#include "configure.h"
using namespace mkldnn;
using namespace std;
void resnetBlock()
{
auto cpu_engine = engine(engine::cpu, 0);
std::vector<float> net_src(BATCH_SIZE * 3 * N * N);
/* Initializing non-zero values for src */
srand(1);
for (size_t i = 0; i < net_src.size(); ++i)
net_src[i] = rand() % 1000;
/****** Conv 1 **********/
memory::dims conv_src_tz = {BATCH_SIZE, 3, N, N};
memory::dims conv_weights_tz = {64, 3, 3, 3};
memory::dims conv_bias_tz = {64};
memory::dims conv_dst_tz = {BATCH_SIZE, 64, N, N};
memory::dims conv_strides = {1, 1};
auto conv_padding = {1, 1};
std::vector<float> conv_weights(
std::accumulate(conv_weights_tz.begin(), conv_weights_tz.end(), 1,
std::multiplies<uint32_t>()));
std::vector<float> conv_bias(std::accumulate(conv_bias_tz.begin(),
conv_bias_tz.end(), 1,
std::multiplies<uint32_t>()));
/* Initializing non-zero values for weights and bias */
for (int i = 0; i < (int)conv_weights.size(); ++i)
conv_weights[i] = 1;
for (size_t i = 0; i < conv_bias.size(); ++i)
conv_bias[i] = 0;
/* Create memory for user data */
auto conv_user_src_memory = memory(
{{{conv_src_tz}, memory::data_type::f32, memory::format::nchw},
cpu_engine},
net_src.data());
auto conv_user_weights_memory = memory(
{{{conv_weights_tz}, memory::data_type::f32, memory::format::nchw},
cpu_engine},
conv_weights.data());
auto conv_user_bias_memory = memory(
{{{conv_bias_tz}, memory::data_type::f32, memory::format::x},
cpu_engine},
conv_bias.data());
/* Create mmemory descriptors for convolution data */
auto conv_src_md = memory::desc({conv_src_tz}, memory::data_type::f32,
memory::format::nchw);
auto conv_bias_md = memory::desc({conv_bias_tz}, memory::data_type::f32,
memory::format::any);
auto conv_weights_md = memory::desc({conv_weights_tz}, memory::data_type::f32,
memory::format::nchw);
auto conv_dst_md = memory::desc({conv_dst_tz}, memory::data_type::f32,
memory::format::nchw);
/* Create a convolution primitive descriptor */
auto conv_desc = convolution_forward::desc(
prop_kind::forward, convolution_direct, conv_src_md,
conv_weights_md, conv_bias_md, conv_dst_md, conv_strides,
conv_padding, conv_padding, padding_kind::zero);
auto conv_pd = convolution_forward::primitive_desc(conv_desc, cpu_engine);
/* Create reorder primitives between user input and conv src if needed */
auto conv_src_memory = conv_user_src_memory;
bool reorder_conv_src = false;
primitive conv_reorder_src;
if (memory::primitive_desc(conv_pd.src_primitive_desc()) != conv_user_src_memory.get_primitive_desc())
{
conv_src_memory = memory(conv_pd.src_primitive_desc());
conv_reorder_src = reorder(conv_user_src_memory, conv_src_memory);
reorder_conv_src = true;
}
auto conv_weights_memory = conv_user_weights_memory;
bool reorder_conv_weights = false;
primitive conv_reorder_weights;
if (memory::primitive_desc(conv_pd.weights_primitive_desc()) != conv_user_weights_memory.get_primitive_desc())
{
conv_weights_memory = memory(conv_pd.weights_primitive_desc());
conv_reorder_weights = reorder(conv_user_weights_memory, conv_weights_memory);
reorder_conv_weights = true;
}
/* Create memory primitive for conv dst */
auto conv_dst_memory = memory(conv_pd.dst_primitive_desc());
/* Finally create a convolution primitive */
auto conv = convolution_forward(conv_pd, conv_src_memory, conv_weights_memory,
conv_user_bias_memory, conv_dst_memory);
/****** Batch normalization 1 **********/
std::vector<float> bn_dst(BATCH_SIZE * 64 * N * N);
std::vector<float> mean_vect(64);
std::vector<float> variance_vect(64);
memory::dims bn_dst_tz = {BATCH_SIZE, 64, N, N};
memory::dims mean_tz = {0, 64, 0, 0};
memory::dims variance_tz = {0, 64, 0, 0};
/* Create memory for bn dst data in user format */
auto bn_dst_memory = memory(
{{{bn_dst_tz}, memory::data_type::f32, memory::format::nchw},
cpu_engine},
bn_dst.data());
auto mean_memory = memory(
{{{mean_tz}, memory::data_type::f32, memory::format::nchw},
cpu_engine},
mean_vect.data());
auto variance_memory = memory(
{{{variance_tz}, memory::data_type::f32, memory::format::nchw},
cpu_engine},
variance_vect.data());
/* Create bn dst memory descriptor in format any */
auto bn_dst_md = memory::desc({bn_dst_tz}, memory::data_type::f32,
memory::format::any);
/* Create bn primitive descriptor */
auto epsilon = 0;
unsigned flags = !mkldnn_use_global_stats && !mkldnn_use_scaleshift && !mkldnn_fuse_bn_relu;
auto bn_desc = batch_normalization_forward::desc(
prop_kind::forward, conv_dst_md, epsilon, flags);
auto bn_pd = batch_normalization_forward::primitive_desc(bn_desc, cpu_engine);
/* Create a bn primitive */
auto bn = batch_normalization_forward(bn_pd, conv_dst_memory, bn_dst_memory, mean_memory, variance_memory);
/****** Relu **********/
const float negative_slope = 0.0f;
/* Create relu primitive desc */
auto relu_desc = eltwise_forward::desc(prop_kind::forward,
algorithm::eltwise_relu, bn_pd.dst_primitive_desc().desc(),
negative_slope);
auto relu_pd = eltwise_forward::primitive_desc(relu_desc, cpu_engine);
/* Create relu dst memory primitive */
auto relu_dst_memory = memory(relu_pd.dst_primitive_desc());
/* Finally create a relu primitive */
auto relu = eltwise_forward(relu_pd, bn_dst_memory, relu_dst_memory);
/****** Conv 2 **********/
memory::dims conv2_weights_tz = {64, 64, 3, 3};
memory::dims conv2_bias_tz = {64};
memory::dims conv2_dst_tz = {BATCH_SIZE, 64, N, N};
memory::dims conv2_strides = {1, 1};
auto conv2_padding = {1, 1};
std::vector<float> conv2_weights(std::accumulate(conv2_weights_tz.begin(),
conv2_weights_tz.end(), 1,
std::multiplies<uint32_t>()));
std::vector<float> conv2_bias(std::accumulate(conv2_bias_tz.begin(),
conv2_bias_tz.end(), 1,
std::multiplies<uint32_t>()));
/* Initializing non-zero values for weights and bias */
for (int i = 0; i < (int)conv2_weights.size(); ++i)
conv2_weights[i] = 1;
for (size_t i = 0; i < conv2_bias.size(); ++i)
conv2_bias[i] = 0;
/* Create memory for user data */
auto conv2_user_weights_memory = memory({{{conv2_weights_tz}, memory::data_type::f32, memory::format::nchw},
cpu_engine},
conv2_weights.data());
auto conv2_user_bias_memory = memory({{{conv2_bias_tz}, memory::data_type::f32, memory::format::x},
cpu_engine},
conv2_bias.data());
/* Create mmemory descriptors for convolution data */
auto conv2_bias_md = memory::desc({conv2_bias_tz}, memory::data_type::f32,
memory::format::any);
auto conv2_weights_md = memory::desc({conv2_weights_tz}, memory::data_type::f32,
memory::format::nchw);
auto conv2_dst_md = memory::desc({conv2_dst_tz}, memory::data_type::f32,
memory::format::nchw);
/* Create a convolution primitive descriptor */
auto conv2_desc = convolution_forward::desc(
prop_kind::forward, convolution_direct, bn_dst_md,
conv2_weights_md, conv2_bias_md, conv2_dst_md, conv2_strides,
conv2_padding, conv2_padding, padding_kind::zero);
auto conv2_pd = convolution_forward::primitive_desc(conv2_desc, cpu_engine);
/* Create reorder primitives between user input and conv src if needed */
auto conv2_src_memory = relu_dst_memory;
bool reorder_conv2_src = false;
primitive conv2_reorder_src;
if (memory::primitive_desc(conv2_pd.src_primitive_desc()) != relu_dst_memory.get_primitive_desc())
{
conv2_src_memory = memory(conv2_pd.src_primitive_desc());
conv2_reorder_src = reorder(relu_dst_memory, conv2_src_memory);
reorder_conv2_src = true;
}
auto conv2_weights_memory = conv2_user_weights_memory;
bool reorder_conv2_weights = false;
primitive conv2_reorder_weights;
if (memory::primitive_desc(conv2_pd.weights_primitive_desc()) != conv2_user_weights_memory.get_primitive_desc())
{
conv2_weights_memory = memory(conv2_pd.weights_primitive_desc());
conv2_reorder_weights = reorder(conv2_user_weights_memory, conv2_weights_memory);
reorder_conv2_weights = true;
}
/* Create memory primitive for conv dst */
auto conv2_dst_memory = memory(conv2_pd.dst_primitive_desc());
/* Finally create a convolution primitive */
auto conv2 = convolution_forward(conv2_pd, conv2_src_memory, conv2_weights_memory,
conv2_user_bias_memory, conv2_dst_memory);
/****** Batch normalization 2 **********/
std::vector<float> bn2_dst(BATCH_SIZE * 64 * N * N);
std::vector<float> mean2_vect(64);
std::vector<float> variance2_vect(64);
memory::dims bn2_dst_tz = {BATCH_SIZE, 64, N, N};
memory::dims mean2_tz = {0, 64, 0, 0};
memory::dims variance2_tz = {0, 64, 0, 0};
/* Create memory for bn dst data in user format */
auto bn2_dst_memory = memory(
{{{bn2_dst_tz}, memory::data_type::f32, memory::format::nchw},
cpu_engine},
bn2_dst.data());
auto mean2_memory = memory(
{{{mean2_tz}, memory::data_type::f32, memory::format::nchw},
cpu_engine},
mean2_vect.data());
auto variance2_memory = memory(
{{{variance2_tz}, memory::data_type::f32, memory::format::nchw},
cpu_engine},
variance2_vect.data());
/* Create bn2 dst memory descriptor in format any */
auto bn2_dst_md = memory::desc({bn2_dst_tz}, memory::data_type::f32,
memory::format::any);
auto bn2_desc = batch_normalization_forward::desc(
prop_kind::forward, conv2_dst_md, epsilon, flags);
auto bn2_pd = batch_normalization_forward::primitive_desc(bn2_desc, cpu_engine);
/* Create a bn primitive */
auto bn2 = batch_normalization_forward(bn2_pd, conv2_dst_memory, bn2_dst_memory, mean2_memory, variance2_memory);
/* Build forward net */
std::vector<primitive> net_fwd;
if (reorder_conv_src)
net_fwd.push_back(conv_reorder_src);
if (reorder_conv_weights)
net_fwd.push_back(conv_reorder_weights);
net_fwd.push_back(conv);
net_fwd.push_back(bn);
net_fwd.push_back(relu);
if (reorder_conv2_src)
net_fwd.push_back(conv2_reorder_src);
if (reorder_conv2_weights)
net_fwd.push_back(conv2_reorder_weights);
net_fwd.push_back(conv2);
net_fwd.push_back(bn2);
std::vector<std::chrono::duration<double, std::milli>> duration_vector_2;
for (int i = 0; i < NB_TESTS; i++)
{
auto start1 = std::chrono::high_resolution_clock::now();
stream(stream::kind::eager).submit(net_fwd).wait();
auto end1 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> duration = end1 - start1;
duration_vector_2.push_back(duration);
}
std::cout << "\t\tMKL-DNN convolution duration"
<< ": " << median(duration_vector_2) << "; " << std::endl;
printf("writing result in file\n");
ofstream resultfile;
resultfile.open("mkldnn_result.txt");
float *output = (float *)bn2_dst_memory.get_data_handle();
for (size_t i = 0; i < BATCH_SIZE; ++i)
for (size_t j = 0; j < 64; ++j)
for (size_t k = 0; k < N; ++k)
for (size_t l = 0; l < N; ++l)
{
resultfile << fixed << setprecision(2) << (float)((int)(output[i * 64 * N * N + j * N * N + k * N + l] * 1000) / 1000.0);
}
resultfile.close();
}
int main(int argc, char **argv)
{
try
{
resnetBlock();
}
catch (error &e)
{
std::cerr << "status: " << e.status << std::endl;
std::cerr << "message: " << e.message << std::endl;
}
return 0;
}
<commit_msg>Each line for one output value in result file<commit_after>#include <chrono>
#include <iostream>
#include <fstream>
#include <numeric>
#include <math.h>
#include <string>
#include <time.h>
#include <iomanip>
#include "mkldnn.hpp"
#include "configure.h"
using namespace mkldnn;
using namespace std;
void resnetBlock()
{
auto cpu_engine = engine(engine::cpu, 0);
std::vector<float> net_src(BATCH_SIZE * 3 * N * N);
/* Initializing non-zero values for src */
srand(1);
for (size_t i = 0; i < net_src.size(); ++i)
net_src[i] = rand() % 1000;
/****** Conv 1 **********/
memory::dims conv_src_tz = {BATCH_SIZE, 3, N, N};
memory::dims conv_weights_tz = {64, 3, 3, 3};
memory::dims conv_bias_tz = {64};
memory::dims conv_dst_tz = {BATCH_SIZE, 64, N, N};
memory::dims conv_strides = {1, 1};
auto conv_padding = {1, 1};
std::vector<float> conv_weights(
std::accumulate(conv_weights_tz.begin(), conv_weights_tz.end(), 1,
std::multiplies<uint32_t>()));
std::vector<float> conv_bias(std::accumulate(conv_bias_tz.begin(),
conv_bias_tz.end(), 1,
std::multiplies<uint32_t>()));
/* Initializing non-zero values for weights and bias */
for (int i = 0; i < (int)conv_weights.size(); ++i)
conv_weights[i] = 1;
for (size_t i = 0; i < conv_bias.size(); ++i)
conv_bias[i] = 0;
/* Create memory for user data */
auto conv_user_src_memory = memory(
{{{conv_src_tz}, memory::data_type::f32, memory::format::nchw},
cpu_engine},
net_src.data());
auto conv_user_weights_memory = memory(
{{{conv_weights_tz}, memory::data_type::f32, memory::format::nchw},
cpu_engine},
conv_weights.data());
auto conv_user_bias_memory = memory(
{{{conv_bias_tz}, memory::data_type::f32, memory::format::x},
cpu_engine},
conv_bias.data());
/* Create mmemory descriptors for convolution data */
auto conv_src_md = memory::desc({conv_src_tz}, memory::data_type::f32,
memory::format::nchw);
auto conv_bias_md = memory::desc({conv_bias_tz}, memory::data_type::f32,
memory::format::any);
auto conv_weights_md = memory::desc({conv_weights_tz}, memory::data_type::f32,
memory::format::nchw);
auto conv_dst_md = memory::desc({conv_dst_tz}, memory::data_type::f32,
memory::format::nchw);
/* Create a convolution primitive descriptor */
auto conv_desc = convolution_forward::desc(
prop_kind::forward, convolution_direct, conv_src_md,
conv_weights_md, conv_bias_md, conv_dst_md, conv_strides,
conv_padding, conv_padding, padding_kind::zero);
auto conv_pd = convolution_forward::primitive_desc(conv_desc, cpu_engine);
/* Create reorder primitives between user input and conv src if needed */
auto conv_src_memory = conv_user_src_memory;
bool reorder_conv_src = false;
primitive conv_reorder_src;
if (memory::primitive_desc(conv_pd.src_primitive_desc()) != conv_user_src_memory.get_primitive_desc())
{
conv_src_memory = memory(conv_pd.src_primitive_desc());
conv_reorder_src = reorder(conv_user_src_memory, conv_src_memory);
reorder_conv_src = true;
}
auto conv_weights_memory = conv_user_weights_memory;
bool reorder_conv_weights = false;
primitive conv_reorder_weights;
if (memory::primitive_desc(conv_pd.weights_primitive_desc()) != conv_user_weights_memory.get_primitive_desc())
{
conv_weights_memory = memory(conv_pd.weights_primitive_desc());
conv_reorder_weights = reorder(conv_user_weights_memory, conv_weights_memory);
reorder_conv_weights = true;
}
/* Create memory primitive for conv dst */
auto conv_dst_memory = memory(conv_pd.dst_primitive_desc());
/* Finally create a convolution primitive */
auto conv = convolution_forward(conv_pd, conv_src_memory, conv_weights_memory,
conv_user_bias_memory, conv_dst_memory);
/****** Batch normalization 1 **********/
std::vector<float> bn_dst(BATCH_SIZE * 64 * N * N);
std::vector<float> mean_vect(64);
std::vector<float> variance_vect(64);
memory::dims bn_dst_tz = {BATCH_SIZE, 64, N, N};
memory::dims mean_tz = {0, 64, 0, 0};
memory::dims variance_tz = {0, 64, 0, 0};
/* Create memory for bn dst data in user format */
auto bn_dst_memory = memory(
{{{bn_dst_tz}, memory::data_type::f32, memory::format::nchw},
cpu_engine},
bn_dst.data());
auto mean_memory = memory(
{{{mean_tz}, memory::data_type::f32, memory::format::nchw},
cpu_engine},
mean_vect.data());
auto variance_memory = memory(
{{{variance_tz}, memory::data_type::f32, memory::format::nchw},
cpu_engine},
variance_vect.data());
/* Create bn dst memory descriptor in format any */
auto bn_dst_md = memory::desc({bn_dst_tz}, memory::data_type::f32,
memory::format::any);
/* Create bn primitive descriptor */
auto epsilon = 0;
unsigned flags = !mkldnn_use_global_stats && !mkldnn_use_scaleshift && !mkldnn_fuse_bn_relu;
auto bn_desc = batch_normalization_forward::desc(
prop_kind::forward, conv_dst_md, epsilon, flags);
auto bn_pd = batch_normalization_forward::primitive_desc(bn_desc, cpu_engine);
/* Create a bn primitive */
auto bn = batch_normalization_forward(bn_pd, conv_dst_memory, bn_dst_memory, mean_memory, variance_memory);
/****** Relu **********/
const float negative_slope = 0.0f;
/* Create relu primitive desc */
auto relu_desc = eltwise_forward::desc(prop_kind::forward,
algorithm::eltwise_relu, bn_pd.dst_primitive_desc().desc(),
negative_slope);
auto relu_pd = eltwise_forward::primitive_desc(relu_desc, cpu_engine);
/* Create relu dst memory primitive */
auto relu_dst_memory = memory(relu_pd.dst_primitive_desc());
/* Finally create a relu primitive */
auto relu = eltwise_forward(relu_pd, bn_dst_memory, relu_dst_memory);
/****** Conv 2 **********/
memory::dims conv2_weights_tz = {64, 64, 3, 3};
memory::dims conv2_bias_tz = {64};
memory::dims conv2_dst_tz = {BATCH_SIZE, 64, N, N};
memory::dims conv2_strides = {1, 1};
auto conv2_padding = {1, 1};
std::vector<float> conv2_weights(std::accumulate(conv2_weights_tz.begin(),
conv2_weights_tz.end(), 1,
std::multiplies<uint32_t>()));
std::vector<float> conv2_bias(std::accumulate(conv2_bias_tz.begin(),
conv2_bias_tz.end(), 1,
std::multiplies<uint32_t>()));
/* Initializing non-zero values for weights and bias */
for (int i = 0; i < (int)conv2_weights.size(); ++i)
conv2_weights[i] = 1;
for (size_t i = 0; i < conv2_bias.size(); ++i)
conv2_bias[i] = 0;
/* Create memory for user data */
auto conv2_user_weights_memory = memory({{{conv2_weights_tz}, memory::data_type::f32, memory::format::nchw},
cpu_engine},
conv2_weights.data());
auto conv2_user_bias_memory = memory({{{conv2_bias_tz}, memory::data_type::f32, memory::format::x},
cpu_engine},
conv2_bias.data());
/* Create mmemory descriptors for convolution data */
auto conv2_bias_md = memory::desc({conv2_bias_tz}, memory::data_type::f32,
memory::format::any);
auto conv2_weights_md = memory::desc({conv2_weights_tz}, memory::data_type::f32,
memory::format::nchw);
auto conv2_dst_md = memory::desc({conv2_dst_tz}, memory::data_type::f32,
memory::format::nchw);
/* Create a convolution primitive descriptor */
auto conv2_desc = convolution_forward::desc(
prop_kind::forward, convolution_direct, bn_dst_md,
conv2_weights_md, conv2_bias_md, conv2_dst_md, conv2_strides,
conv2_padding, conv2_padding, padding_kind::zero);
auto conv2_pd = convolution_forward::primitive_desc(conv2_desc, cpu_engine);
/* Create reorder primitives between user input and conv src if needed */
auto conv2_src_memory = relu_dst_memory;
bool reorder_conv2_src = false;
primitive conv2_reorder_src;
if (memory::primitive_desc(conv2_pd.src_primitive_desc()) != relu_dst_memory.get_primitive_desc())
{
conv2_src_memory = memory(conv2_pd.src_primitive_desc());
conv2_reorder_src = reorder(relu_dst_memory, conv2_src_memory);
reorder_conv2_src = true;
}
auto conv2_weights_memory = conv2_user_weights_memory;
bool reorder_conv2_weights = false;
primitive conv2_reorder_weights;
if (memory::primitive_desc(conv2_pd.weights_primitive_desc()) != conv2_user_weights_memory.get_primitive_desc())
{
conv2_weights_memory = memory(conv2_pd.weights_primitive_desc());
conv2_reorder_weights = reorder(conv2_user_weights_memory, conv2_weights_memory);
reorder_conv2_weights = true;
}
/* Create memory primitive for conv dst */
auto conv2_dst_memory = memory(conv2_pd.dst_primitive_desc());
/* Finally create a convolution primitive */
auto conv2 = convolution_forward(conv2_pd, conv2_src_memory, conv2_weights_memory,
conv2_user_bias_memory, conv2_dst_memory);
/****** Batch normalization 2 **********/
std::vector<float> bn2_dst(BATCH_SIZE * 64 * N * N);
std::vector<float> mean2_vect(64);
std::vector<float> variance2_vect(64);
memory::dims bn2_dst_tz = {BATCH_SIZE, 64, N, N};
memory::dims mean2_tz = {0, 64, 0, 0};
memory::dims variance2_tz = {0, 64, 0, 0};
/* Create memory for bn dst data in user format */
auto bn2_dst_memory = memory(
{{{bn2_dst_tz}, memory::data_type::f32, memory::format::nchw},
cpu_engine},
bn2_dst.data());
auto mean2_memory = memory(
{{{mean2_tz}, memory::data_type::f32, memory::format::nchw},
cpu_engine},
mean2_vect.data());
auto variance2_memory = memory(
{{{variance2_tz}, memory::data_type::f32, memory::format::nchw},
cpu_engine},
variance2_vect.data());
/* Create bn2 dst memory descriptor in format any */
auto bn2_dst_md = memory::desc({bn2_dst_tz}, memory::data_type::f32,
memory::format::any);
auto bn2_desc = batch_normalization_forward::desc(
prop_kind::forward, conv2_dst_md, epsilon, flags);
auto bn2_pd = batch_normalization_forward::primitive_desc(bn2_desc, cpu_engine);
/* Create a bn primitive */
auto bn2 = batch_normalization_forward(bn2_pd, conv2_dst_memory, bn2_dst_memory, mean2_memory, variance2_memory);
/* Build forward net */
std::vector<primitive> net_fwd;
if (reorder_conv_src)
net_fwd.push_back(conv_reorder_src);
if (reorder_conv_weights)
net_fwd.push_back(conv_reorder_weights);
net_fwd.push_back(conv);
net_fwd.push_back(bn);
net_fwd.push_back(relu);
if (reorder_conv2_src)
net_fwd.push_back(conv2_reorder_src);
if (reorder_conv2_weights)
net_fwd.push_back(conv2_reorder_weights);
net_fwd.push_back(conv2);
net_fwd.push_back(bn2);
std::vector<std::chrono::duration<double, std::milli>> duration_vector_2;
for (int i = 0; i < NB_TESTS; i++)
{
auto start1 = std::chrono::high_resolution_clock::now();
stream(stream::kind::eager).submit(net_fwd).wait();
auto end1 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> duration = end1 - start1;
duration_vector_2.push_back(duration);
}
std::cout << "\t\tMKL-DNN convolution duration"
<< ": " << median(duration_vector_2) << "; " << std::endl;
printf("writing result in file\n");
ofstream resultfile;
resultfile.open("mkldnn_result.txt");
float *output = (float *)bn2_dst_memory.get_data_handle();
for (size_t i = 0; i < BATCH_SIZE; ++i)
for (size_t j = 0; j < 64; ++j)
for (size_t k = 0; k < N; ++k)
for (size_t l = 0; l < N; ++l)
{
resultfile << fixed << setprecision(2) << (float)((int)(output[i * 64 * N * N + j * N * N + k * N + l] * 1000) / 1000.0);
resultfile << "\n";
}
resultfile.close();
}
int main(int argc, char **argv)
{
try
{
resnetBlock();
}
catch (error &e)
{
std::cerr << "status: " << e.status << std::endl;
std::cerr << "message: " << e.message << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkLineSource.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkLineSource.h"
#include "vtkCellArray.h"
#include "vtkFloatArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkPointData.h"
#include "vtkPoints.h"
#include "vtkPolyData.h"
#include <math.h>
vtkCxxRevisionMacro(vtkLineSource, "1.47");
vtkStandardNewMacro(vtkLineSource);
vtkLineSource::vtkLineSource(int res)
{
this->Point1[0] = -0.5;
this->Point1[1] = 0.0;
this->Point1[2] = 0.0;
this->Point2[0] = 0.5;
this->Point2[1] = 0.0;
this->Point2[2] = 0.0;
this->Resolution = (res < 1 ? 1 : res);
this->SetNumberOfInputPorts(0);
}
int vtkLineSource::RequestInformation(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **vtkNotUsed(inputVector),
vtkInformationVector *outputVector)
{
// get the info object
vtkInformation *outInfo = outputVector->GetInformationObject(0);
outInfo->Set(vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(),
-1);
return 1;
}
int vtkLineSource::RequestData(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **vtkNotUsed(inputVector),
vtkInformationVector *outputVector)
{
// get the info object
vtkInformation *outInfo = outputVector->GetInformationObject(0);
// get the ouptut
vtkPolyData *output = vtkPolyData::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
int numLines=this->Resolution;
int numPts=this->Resolution+1;
double x[3], tc[3], v[3];
int i, j;
vtkPoints *newPoints;
vtkFloatArray *newTCoords;
vtkCellArray *newLines;
if (outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()) > 0)
{
return 1;
}
newPoints = vtkPoints::New();
newPoints->Allocate(numPts);
newTCoords = vtkFloatArray::New();
newTCoords->SetNumberOfComponents(2);
newTCoords->Allocate(2*numPts);
newLines = vtkCellArray::New();
newLines->Allocate(newLines->EstimateSize(numLines,2));
//
// Generate points and texture coordinates
//
for (i=0; i<3; i++)
{
v[i] = this->Point2[i] - this->Point1[i];
}
tc[1] = 0.0;
tc[2] = 0.0;
for (i=0; i<numPts; i++)
{
tc[0] = ((double)i/this->Resolution);
for (j=0; j<3; j++)
{
x[j] = this->Point1[j] + tc[0]*v[j];
}
newPoints->InsertPoint(i,x);
newTCoords->InsertTuple(i,tc);
}
//
// Generate lines
//
newLines->InsertNextCell(numPts);
for (i=0; i < numPts; i++)
{
newLines->InsertCellPoint (i);
}
//
// Update ourselves and release memory
//
output->SetPoints(newPoints);
newPoints->Delete();
output->GetPointData()->SetTCoords(newTCoords);
newTCoords->Delete();
output->SetLines(newLines);
newLines->Delete();
return 1;
}
void vtkLineSource::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Resolution: " << this->Resolution << "\n";
os << indent << "Point 1: (" << this->Point1[0] << ", "
<< this->Point1[1] << ", "
<< this->Point1[2] << ")\n";
os << indent << "Point 2: (" << this->Point2[0] << ", "
<< this->Point2[1] << ", "
<< this->Point2[2] << ")\n";
}
<commit_msg>BUG: #0006565 has been fixed. This problem was due to not providing a name for "vtkFloatArray *newTCoords" in vtkLineSource::RequestData() --- line 85 ~ line 88, which is though later evaluated through "strlen(nms[i])" in vtkExodusIIWriter::FlattenOutVariableNames() --- line 1027.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkLineSource.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkLineSource.h"
#include "vtkCellArray.h"
#include "vtkFloatArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkPointData.h"
#include "vtkPoints.h"
#include "vtkPolyData.h"
#include <math.h>
vtkCxxRevisionMacro(vtkLineSource, "1.48");
vtkStandardNewMacro(vtkLineSource);
vtkLineSource::vtkLineSource(int res)
{
this->Point1[0] = -0.5;
this->Point1[1] = 0.0;
this->Point1[2] = 0.0;
this->Point2[0] = 0.5;
this->Point2[1] = 0.0;
this->Point2[2] = 0.0;
this->Resolution = (res < 1 ? 1 : res);
this->SetNumberOfInputPorts(0);
}
int vtkLineSource::RequestInformation(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **vtkNotUsed(inputVector),
vtkInformationVector *outputVector)
{
// get the info object
vtkInformation *outInfo = outputVector->GetInformationObject(0);
outInfo->Set(vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(),
-1);
return 1;
}
int vtkLineSource::RequestData(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **vtkNotUsed(inputVector),
vtkInformationVector *outputVector)
{
// get the info object
vtkInformation *outInfo = outputVector->GetInformationObject(0);
// get the ouptut
vtkPolyData *output = vtkPolyData::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
int numLines=this->Resolution;
int numPts=this->Resolution+1;
double x[3], tc[3], v[3];
int i, j;
vtkPoints *newPoints;
vtkFloatArray *newTCoords;
vtkCellArray *newLines;
if (outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()) > 0)
{
return 1;
}
newPoints = vtkPoints::New();
newPoints->Allocate(numPts);
newTCoords = vtkFloatArray::New();
newTCoords->SetNumberOfComponents(2);
newTCoords->Allocate(2*numPts);
newTCoords->SetName("Texture Coordinates");
newLines = vtkCellArray::New();
newLines->Allocate(newLines->EstimateSize(numLines,2));
//
// Generate points and texture coordinates
//
for (i=0; i<3; i++)
{
v[i] = this->Point2[i] - this->Point1[i];
}
tc[1] = 0.0;
tc[2] = 0.0;
for (i=0; i<numPts; i++)
{
tc[0] = ((double)i/this->Resolution);
for (j=0; j<3; j++)
{
x[j] = this->Point1[j] + tc[0]*v[j];
}
newPoints->InsertPoint(i,x);
newTCoords->InsertTuple(i,tc);
}
//
// Generate lines
//
newLines->InsertNextCell(numPts);
for (i=0; i < numPts; i++)
{
newLines->InsertCellPoint (i);
}
//
// Update ourselves and release memory
//
output->SetPoints(newPoints);
newPoints->Delete();
output->GetPointData()->SetTCoords(newTCoords);
newTCoords->Delete();
output->SetLines(newLines);
newLines->Delete();
return 1;
}
void vtkLineSource::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Resolution: " << this->Resolution << "\n";
os << indent << "Point 1: (" << this->Point1[0] << ", "
<< this->Point1[1] << ", "
<< this->Point1[2] << ")\n";
os << indent << "Point 2: (" << this->Point2[0] << ", "
<< this->Point2[1] << ", "
<< this->Point2[2] << ")\n";
}
<|endoftext|> |
<commit_before>/*
* Part of HTTPP.
*
* Distributed under the 3-clause BSD licence (See LICENCE.TXT file at the
* project root).
*
* Copyright (c) 2014 Thomas Sanchez. All rights reserved.
*
*/
#include <iostream>
#include <chrono>
#include <thread>
#include <boost/test/unit_test.hpp>
#include "httpp/HttpServer.hpp"
#include "httpp/HttpClient.hpp"
using namespace HTTPP;
using HTTPP::HTTP::Request;
using HTTPP::HTTP::Response;
using HTTPP::HTTP::Connection;
void handler(Connection* connection, Request&& request)
{
auto headers = request.getSortedHeaders();
auto const& host = headers["Host"];
auto port = stoi(host.substr(host.find(':') + 1));
if (port < 8084)
{
connection->response()
.setCode(HTTP::HttpCode::MovedPermentaly)
.addHeader("Location", "http://localhost:" + std::to_string(port + 1))
.setBody("");
connection->sendResponse();
}
else
{
connection->response()
.setCode(HTTP::HttpCode::Ok)
.setBody("Ok");
connection->sendResponse();
}
}
BOOST_AUTO_TEST_CASE(follow_redirect)
{
HttpServer server;
server.start();
server.setSink(&handler);
server.bind("localhost", "8080");
server.bind("localhost", "8081");
server.bind("localhost", "8082");
server.bind("localhost", "8083");
server.bind("localhost", "8084");
HttpClient client;
HttpClient::Request request;
request
.url("http://localhost:8080")
.followRedirect(true);
auto response = client.get(std::move(request));
BOOST_CHECK_EQUAL(std::string(response.body.data(), response.body.size()),
"Ok");
for (const auto& h : response.headers)
{
std::cout << h.first << ": " << h.second << std::endl;
}
}
<commit_msg>Add a test for follow redirect<commit_after>/*
* Part of HTTPP.
*
* Distributed under the 3-clause BSD licence (See LICENCE.TXT file at the
* project root).
*
* Copyright (c) 2014 Thomas Sanchez. All rights reserved.
*
*/
#include <iostream>
#include <chrono>
#include <thread>
#include <boost/test/unit_test.hpp>
#include "httpp/HttpServer.hpp"
#include "httpp/HttpClient.hpp"
using namespace HTTPP;
using HTTPP::HTTP::Request;
using HTTPP::HTTP::Response;
using HTTPP::HTTP::Connection;
void handler(Connection* connection, Request&& request)
{
auto headers = request.getSortedHeaders();
auto const& host = headers["Host"];
auto port = stoi(host.substr(host.find(':') + 1));
if (port < 8084)
{
connection->response()
.setCode(HTTP::HttpCode::MovedPermentaly)
.addHeader("Location", "http://localhost:" + std::to_string(port + 1))
.setBody("");
connection->sendResponse();
}
else
{
connection->response()
.setCode(HTTP::HttpCode::Ok)
.setBody("Ok");
connection->sendResponse();
}
}
BOOST_AUTO_TEST_CASE(follow_redirect)
{
HttpServer server;
server.start();
server.setSink(&handler);
server.bind("localhost", "8080");
server.bind("localhost", "8081");
server.bind("localhost", "8082");
server.bind("localhost", "8083");
server.bind("localhost", "8084");
HttpClient client;
HttpClient::Request request;
request
.url("http://localhost:8080")
.followRedirect(true);
auto response = client.get(std::move(request));
BOOST_CHECK_EQUAL(std::string(response.body.data(), response.body.size()),
"Ok");
for (const auto& h : response.headers)
{
std::cout << h.first << ": " << h.second << std::endl;
}
}
void handler2(Connection* connection, Request&& request)
{
if (request.uri == "//redirect")
{
connection->response()
.setCode(HTTP::HttpCode::MovedPermentaly)
.addHeader("Location", "/ok")
.setBody("");
connection->sendResponse();
}
else if (request.uri == "/ok")
{
connection->response()
.setCode(HTTP::HttpCode::Ok)
.setBody("Ok");
connection->sendResponse();
}
else
{
abort();
}
}
BOOST_AUTO_TEST_CASE(follow_redirect2)
{
HttpServer server;
server.start();
server.setSink(&handler2);
server.bind("localhost", "8080");
HttpClient client;
HttpClient::Request request;
request
.url("http://localhost:8080//redirect")
.followRedirect(true);
auto response = client.get(std::move(request));
BOOST_CHECK_EQUAL(std::string(response.body.data(), response.body.size()),
"Ok");
for (const auto& h : response.headers)
{
std::cout << h.first << ": " << h.second << std::endl;
}
}
<|endoftext|> |
<commit_before>/***********************************************************************
* Joystick *
* read joystick data, normalize from -90 to +90, write data to serial *
* *
* @author: Navid Kalaei <[email protected]> *
* @github: @navid-kalaei *
* @license: MIT *
***********************************************************************/
#include "Arduino.h"
// time to wait in millis
#define DELAY_TIME 1000
#define SERIAL_RATE 9600
#define JOY_PIN_X 0
#define JOY_PIN_Y 1
// boundries of analogRead()
#define ANALOG_READ_LOW 0
#define ANALOG_READ_HIGH 1023
// boundries for normalizing analogRead() from -90 to +90
#define NORMALIZE_BOUND_LOW -90
#define NORMALIZE_BOUND_HIGH 90
// use this number to shift normalize value be between 0 to 180
#define NORMALIZE_ORIGIN 90
// the value that joystick has at first
// they're usefull in normalizing
short int joyXOrigin = 0;
short int joyYOrigin = 0;
short int joyXOriginNormalized = 0;
short int joyYOriginNormalized = 0;
short int joyValueX = 0;
short int joyValueY = 0;
short int joyValueXNormalized = 0;
short int joyValueYNormalized = 0;
short int normalize(short int value){
/*
* a wrapper for map built-in function
*
* @param value: is within analogRead boundries
* @return: normalize value within normalize boundries
*/
// https://www.arduino.cc/en/Reference/Map
// map(value, fromLow, fromHigh, toLow, toHigh)
return map(value,
ANALOG_READ_LOW, ANALOG_READ_HIGH,
NORMALIZE_BOUND_LOW, NORMALIZE_BOUND_HIGH);
}
void checkBoundries(short int &value){
/*
* check if value is between normalized boudries or reset it to a boundry
*
* @param value: to check
* @return: void
*/
if(value > NORMALIZE_BOUND_HIGH){
value = NORMALIZE_BOUND_HIGH;
}
else if(value < NORMALIZE_BOUND_LOW){
value = NORMALIZE_BOUND_LOW;
}
}
void setup(){
// initialize joystick pins
pinMode(JOY_PIN_X, INPUT);
pinMode(JOY_PIN_Y, INPUT);
joyXOrigin = analogRead(JOY_PIN_X);
joyYOrigin = analogRead(JOY_PIN_Y);
joyXOriginNormalized = normalize(joyXOrigin);
joyYOriginNormalized = normalize(joyYOrigin);
// wait until Serail is not available
while(!Serial);
Serial.begin(SERIAL_RATE);
}
void loop(){
joyValueX = analogRead(JOY_PIN_X);
joyValueXNormalized = normalize(joyValueX) - joyXOriginNormalized;
checkBoundries(joyValueXNormalized);
joyValueY = analogRead(JOY_PIN_Y);
joyValueYNormalized = normalize(joyValueY) - joyYOriginNormalized;
checkBoundries(joyValueYNormalized);
Serial.print(joyValueX);
Serial.print(' ');
Serial.print(joyValueXNormalized);
Serial.print(" - ");
Serial.print(joyValueY);
Serial.print(' ');
Serial.println(joyValueYNormalized);
delay(DELAY_TIME);
}
<commit_msg>get joystick/main to use custom_joystick lib<commit_after>/***********************************************************************
* Joystick *
* read joystick data, normalize from -90 to +90, write data to serial *
* *
* @author: Navid Kalaei <[email protected]> *
* @github: @navid-kalaei *
* @license: MIT *
***********************************************************************/
#include "Arduino.h"
// time to wait in millis
#define DELAY_TIME 1000
#define SERIAL_RATE 9600
#define JOY_PIN_X 0
#define JOY_PIN_Y 1
void setup(){
// initialize joystick pins
pinMode(JOY_PIN_X, INPUT);
pinMode(JOY_PIN_Y, INPUT);
joyXOrigin = analogRead(JOY_PIN_X);
joyYOrigin = analogRead(JOY_PIN_Y);
joyXOriginNormalized = normalize(joyXOrigin);
joyYOriginNormalized = normalize(joyYOrigin);
// wait until Serail is not available
while(!Serial);
Serial.begin(SERIAL_RATE);
}
void loop(){
joyValueX = analogRead(JOY_PIN_X);
joyValueXNormalized = normalize(joyValueX) - joyXOriginNormalized;
checkBoundries(joyValueXNormalized);
joyValueY = analogRead(JOY_PIN_Y);
joyValueYNormalized = normalize(joyValueY) - joyYOriginNormalized;
checkBoundries(joyValueYNormalized);
Serial.print(joyValueX);
Serial.print(' ');
Serial.print(joyValueXNormalized);
Serial.print(" - ");
Serial.print(joyValueY);
Serial.print(' ');
Serial.println(joyValueYNormalized);
delay(DELAY_TIME);
}
<|endoftext|> |
<commit_before>#include "pch.h"
#include "memory_stream.h"
MemoryStream::MemoryStream()
{
}
MemoryStream::~MemoryStream()
{
close();
}
void MemoryStream::close()
{
_ownedBuffer.reset();
_readBuffer = nullptr;
_writeBuffer = nullptr;
_cursor = _bufferSize = 0;
_autoBuffer.clear();
}
MemoryStream * MemoryStream::create(const void * buffer, size_t bufferSize)
{
if (!buffer)
return nullptr;
MemoryStream * res = new MemoryStream();
res->_readBuffer = reinterpret_cast<const uint8_t *>(buffer);
res->_writeBuffer = nullptr;
res->_bufferSize = bufferSize;
res->_cursor = 0;
res->_canAllocate = false;
return res;
}
MemoryStream * MemoryStream::create(void * buffer, size_t bufferSize)
{
if (!buffer)
return nullptr;
MemoryStream * res = new MemoryStream();
res->_readBuffer = reinterpret_cast<const uint8_t *>(buffer);
res->_writeBuffer = reinterpret_cast<uint8_t *>(buffer);
res->_bufferSize = bufferSize;
res->_cursor = 0;
res->_canAllocate = false;
return res;
}
MemoryStream * MemoryStream::create(std::unique_ptr< uint8_t[] >& buffer, size_t bufferSize)
{
if (!buffer.get())
return nullptr;
MemoryStream * res = new MemoryStream();
res->_ownedBuffer.reset(buffer.release());
res->_readBuffer = reinterpret_cast<const uint8_t *>(res->_ownedBuffer.get());
res->_writeBuffer = reinterpret_cast<uint8_t *>(res->_ownedBuffer.get());
res->_bufferSize = bufferSize;
res->_cursor = 0;
res->_canAllocate = false;
return res;
}
MemoryStream * MemoryStream::create()
{
MemoryStream * res = new MemoryStream();
res->_readBuffer = nullptr;
res->_writeBuffer = nullptr;
res->_bufferSize = 0;
res->_cursor = 0;
res->_canAllocate = true;
return res;
}
size_t MemoryStream::read(void* ptr, size_t size, size_t count)
{
if (size == 0)
return 0;
size_t maxReadBytes = std::min(_bufferSize - _cursor, size * count);
size_t maxReadElements = maxReadBytes / size;
if (maxReadElements == 0)
return 0;
maxReadBytes = maxReadElements * size;
memcpy(ptr, _readBuffer + _cursor, maxReadBytes);
_cursor += maxReadBytes;
return maxReadElements;
}
char* MemoryStream::readLine(char* str, int num)
{
if (num <= 0)
return NULL;
size_t maxReadBytes = std::min<size_t>(_bufferSize - _cursor, num);
char * strSave = str;
while (maxReadBytes > 0)
{
const char& ch = *(_readBuffer + _cursor);
if (ch == '\r' || ch == '\n')
{
*str++ = ch;
if (str - strSave < num)
*str++ = '\0';
return strSave;
}
*str++ = ch;
_cursor++;
maxReadBytes--;
}
if (str - strSave < num)
*str++ = '\0';
return strSave;
}
size_t MemoryStream::write(const void* ptr, size_t size, size_t count)
{
if (!canWrite())
return 0;
size_t maxWriteBytes = _canAllocate ? size * count : std::min(_bufferSize - _cursor, size * count);
size_t maxWriteElements = maxWriteBytes / size;
if (maxWriteBytes == 0)
return 0;
if (_canAllocate && _cursor + maxWriteBytes > _bufferSize)
{
_bufferSize = _cursor + maxWriteBytes;
_autoBuffer.resize(_bufferSize);
_readBuffer = _writeBuffer = &_autoBuffer.front();
}
maxWriteBytes = maxWriteElements * size;
memcpy(_writeBuffer + _cursor, ptr, maxWriteBytes);
_cursor += maxWriteBytes;
return maxWriteElements;
}
bool MemoryStream::seek(long int offset, int origin)
{
switch (origin)
{
case SEEK_SET:
_cursor = static_cast<size_t>(offset);
break;
case SEEK_CUR:
_cursor = static_cast<size_t>(position() + offset);
break;
case SEEK_END:
_cursor = static_cast<size_t>(static_cast<long int>(_bufferSize)+offset);
break;
}
GP_ASSERT(_cursor <= _bufferSize);
return _cursor <= _bufferSize;
}<commit_msg>fixed readLine method of MemoryStream<commit_after>#include "pch.h"
#include "memory_stream.h"
MemoryStream::MemoryStream()
{
}
MemoryStream::~MemoryStream()
{
close();
}
void MemoryStream::close()
{
_ownedBuffer.reset();
_readBuffer = nullptr;
_writeBuffer = nullptr;
_cursor = _bufferSize = 0;
_autoBuffer.clear();
}
MemoryStream * MemoryStream::create(const void * buffer, size_t bufferSize)
{
if (!buffer)
return nullptr;
MemoryStream * res = new MemoryStream();
res->_readBuffer = reinterpret_cast<const uint8_t *>(buffer);
res->_writeBuffer = nullptr;
res->_bufferSize = bufferSize;
res->_cursor = 0;
res->_canAllocate = false;
return res;
}
MemoryStream * MemoryStream::create(void * buffer, size_t bufferSize)
{
if (!buffer)
return nullptr;
MemoryStream * res = new MemoryStream();
res->_readBuffer = reinterpret_cast<const uint8_t *>(buffer);
res->_writeBuffer = reinterpret_cast<uint8_t *>(buffer);
res->_bufferSize = bufferSize;
res->_cursor = 0;
res->_canAllocate = false;
return res;
}
MemoryStream * MemoryStream::create(std::unique_ptr< uint8_t[] >& buffer, size_t bufferSize)
{
if (!buffer.get())
return nullptr;
MemoryStream * res = new MemoryStream();
res->_ownedBuffer.reset(buffer.release());
res->_readBuffer = reinterpret_cast<const uint8_t *>(res->_ownedBuffer.get());
res->_writeBuffer = reinterpret_cast<uint8_t *>(res->_ownedBuffer.get());
res->_bufferSize = bufferSize;
res->_cursor = 0;
res->_canAllocate = false;
return res;
}
MemoryStream * MemoryStream::create()
{
MemoryStream * res = new MemoryStream();
res->_readBuffer = nullptr;
res->_writeBuffer = nullptr;
res->_bufferSize = 0;
res->_cursor = 0;
res->_canAllocate = true;
return res;
}
size_t MemoryStream::read(void* ptr, size_t size, size_t count)
{
if (size == 0)
return 0;
size_t maxReadBytes = std::min(_bufferSize - _cursor, size * count);
size_t maxReadElements = maxReadBytes / size;
if (maxReadElements == 0)
return 0;
maxReadBytes = maxReadElements * size;
memcpy(ptr, _readBuffer + _cursor, maxReadBytes);
_cursor += maxReadBytes;
return maxReadElements;
}
char* MemoryStream::readLine(char* str, int num)
{
if (num <= 0)
return NULL;
size_t maxReadBytes = std::min<size_t>(_bufferSize - _cursor, num);
char * strSave = str;
while (maxReadBytes > 0)
{
const char& ch = *(_readBuffer + _cursor);
if (ch == '\r' || ch == '\n')
{
*str++ = ch;
_cursor++;
if (str - strSave < num)
*str++ = '\0';
return strSave;
}
*str++ = ch;
_cursor++;
maxReadBytes--;
}
if (str - strSave < num)
*str++ = '\0';
return strSave;
}
size_t MemoryStream::write(const void* ptr, size_t size, size_t count)
{
if (!canWrite())
return 0;
size_t maxWriteBytes = _canAllocate ? size * count : std::min(_bufferSize - _cursor, size * count);
size_t maxWriteElements = maxWriteBytes / size;
if (maxWriteBytes == 0)
return 0;
if (_canAllocate && _cursor + maxWriteBytes > _bufferSize)
{
_bufferSize = _cursor + maxWriteBytes;
_autoBuffer.resize(_bufferSize);
_readBuffer = _writeBuffer = &_autoBuffer.front();
}
maxWriteBytes = maxWriteElements * size;
memcpy(_writeBuffer + _cursor, ptr, maxWriteBytes);
_cursor += maxWriteBytes;
return maxWriteElements;
}
bool MemoryStream::seek(long int offset, int origin)
{
switch (origin)
{
case SEEK_SET:
_cursor = static_cast<size_t>(offset);
break;
case SEEK_CUR:
_cursor = static_cast<size_t>(position() + offset);
break;
case SEEK_END:
_cursor = static_cast<size_t>(static_cast<long int>(_bufferSize)+offset);
break;
}
GP_ASSERT(_cursor <= _bufferSize);
return _cursor <= _bufferSize;
}<|endoftext|> |
<commit_before>/*
* Copyright (C) 2012 BMW Car IT GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include "capu/os/Math.h"
TEST(Math, abs1)
{
capu::int_t val = 5;
EXPECT_EQ(5, capu::Math::Abs(val));
val = -5;
EXPECT_EQ(5, capu::Math::Abs(val));
}
TEST(Math, abs2)
{
capu::double_t val = 6;
EXPECT_EQ(6, capu::Math::Abs(val));
val = -6;
EXPECT_EQ(6, capu::Math::Abs(val));
}
TEST(Math, abs3)
{
capu::float_t val = 7;
EXPECT_EQ(7, capu::Math::Abs(val));
val = -7;
EXPECT_EQ(7, capu::Math::Abs(val));
}
TEST(Math, PI)
{
capu::float_t val = capu::Math::PI_f;
capu::double_t val2 = capu::Math::PI_d;
EXPECT_TRUE(val > 3);
EXPECT_TRUE(val2 > 3);
}
TEST(Math, Log2)
{
EXPECT_FLOAT_EQ(3.321928f, capu::Math::Log2(10.f));
EXPECT_NEAR(3.3219280948873644, capu::Math::Log2(10.0), 0.0000000000001);
}
TEST(Math, Exp)
{
EXPECT_FLOAT_EQ(200.33685f, capu::Math::Exp(5.3f));
EXPECT_NEAR(200.33680997479166, capu::Math::Exp(5.3), 0.0000000000001);
}
<commit_msg>Added missing tests for Math<commit_after>/*
* Copyright (C) 2012 BMW Car IT GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include "capu/os/Math.h"
TEST(Math, abs1)
{
capu::int_t val = 5;
EXPECT_EQ(5, capu::Math::Abs(val));
val = -5;
EXPECT_EQ(5, capu::Math::Abs(val));
}
TEST(Math, abs2)
{
capu::double_t val = 6;
EXPECT_EQ(6, capu::Math::Abs(val));
val = -6;
EXPECT_EQ(6, capu::Math::Abs(val));
}
TEST(Math, abs3)
{
capu::float_t val = 7;
EXPECT_EQ(7, capu::Math::Abs(val));
val = -7;
EXPECT_EQ(7, capu::Math::Abs(val));
}
TEST(Math, PI)
{
capu::float_t val = capu::Math::PI_f;
capu::double_t val2 = capu::Math::PI_d;
EXPECT_TRUE(val > 3);
EXPECT_TRUE(val2 > 3);
}
TEST(Math, Log2)
{
EXPECT_FLOAT_EQ(3.321928f, capu::Math::Log2(10.f));
EXPECT_NEAR(3.3219280948873644, capu::Math::Log2(10.0), 0.0000000000001);
}
TEST(Math, Exp)
{
EXPECT_FLOAT_EQ(200.33685f, capu::Math::Exp(5.3f));
EXPECT_NEAR(200.33680997479166, capu::Math::Exp(5.3), 0.0000000000001);
}
TEST(Math, Ceil)
{
EXPECT_FLOAT_EQ(3.0f, capu::Math::Ceil(2.3f));
EXPECT_FLOAT_EQ(3.0f, capu::Math::Ceil(2.8f));
EXPECT_FLOAT_EQ(-2.0f, capu::Math::Ceil(-2.8f));
EXPECT_DOUBLE_EQ(3.0, capu::Math::Ceil(2.3));
EXPECT_DOUBLE_EQ(3.0, capu::Math::Ceil(2.8));
EXPECT_DOUBLE_EQ(-2.0, capu::Math::Ceil(-2.8));
}
TEST(Math, Floor)
{
EXPECT_FLOAT_EQ(2.0f, capu::Math::Floor(2.3f));
EXPECT_FLOAT_EQ(2.0f, capu::Math::Floor(2.8f));
EXPECT_FLOAT_EQ(-3.0f, capu::Math::Floor(-2.3f));
EXPECT_DOUBLE_EQ(2.0, capu::Math::Floor(2.3));
EXPECT_DOUBLE_EQ(2.0, capu::Math::Floor(2.8));
EXPECT_DOUBLE_EQ(-3.0, capu::Math::Floor(-2.3));
}
TEST(Math, Sqrt)
{
EXPECT_FLOAT_EQ(3.0f, capu::Math::Sqrt(9.0f));
EXPECT_DOUBLE_EQ(3.0, capu::Math::Sqrt(9.0));
}
TEST(Math, Pow)
{
EXPECT_FLOAT_EQ(4.0f, capu::Math::Pow2(2.0f));
EXPECT_DOUBLE_EQ(4.0, capu::Math::Pow2(2.0));
EXPECT_FLOAT_EQ(8.0f, capu::Math::Pow(2.0f, 3.0f));
EXPECT_DOUBLE_EQ(8.0, capu::Math::Pow(2.0, 3.0));
EXPECT_FLOAT_EQ(capu::Math::Pow(4.0f, 2.0f), capu::Math::Pow2(4.0f));
EXPECT_DOUBLE_EQ(capu::Math::Pow(4.0, 2.0), capu::Math::Pow2(4.0));
}
TEST(Math, Cos)
{
capu::double_t pid = capu::Math::PI_d;
capu::float_t pif = capu::Math::PI_f;
EXPECT_FLOAT_EQ(-1.0f, capu::Math::Cos(pif));
EXPECT_DOUBLE_EQ(-1.0, capu::Math::Cos(pid));
}
TEST(Math, Sin)
{
capu::double_t pid = capu::Math::PI_d;
capu::float_t pif = capu::Math::PI_f;
EXPECT_FLOAT_EQ(1.0f, capu::Math::Sin(pif/2.0f));
EXPECT_DOUBLE_EQ(1.0, capu::Math::Sin(pid/2.0));
}
TEST(Math, Tan)
{
capu::double_t pid = capu::Math::PI_d;
capu::float_t pif = capu::Math::PI_f;
EXPECT_FLOAT_EQ(1.0f, capu::Math::Tan(pif/4.0f));
EXPECT_DOUBLE_EQ(1.0, capu::Math::Tan(pid/4.0));
}
TEST(Math, ArcCos)
{
capu::double_t pid = capu::Math::PI_d;
capu::float_t pif = capu::Math::PI_f;
EXPECT_FLOAT_EQ(pif, capu::Math::ArcCos(-1.0f));
EXPECT_DOUBLE_EQ(pid, capu::Math::ArcCos(-1.0));
}
TEST(Math, ArcSin)
{
capu::double_t pid = capu::Math::PI_d;
capu::float_t pif = capu::Math::PI_f;
EXPECT_FLOAT_EQ(pif/2.0f, capu::Math::ArcSin(1.0f));
EXPECT_DOUBLE_EQ(pid/2.0, capu::Math::ArcSin(1.0));
}
TEST(Math, ArcTan)
{
capu::double_t pid = capu::Math::PI_d;
capu::float_t pif = capu::Math::PI_f;
EXPECT_FLOAT_EQ(pif/4.0f, capu::Math::ArcTan(1.0f));
EXPECT_DOUBLE_EQ(pid/4.0, capu::Math::ArcTan(1.0));
}
TEST(Math, Rad2Deg)
{
EXPECT_FLOAT_EQ(180.0f, capu::Math::Rad2Deg(capu::Math::PI_f));
EXPECT_DOUBLE_EQ(180.0, capu::Math::Rad2Deg(capu::Math::PI_d));
}
TEST(Math, Deg2Rad)
{
EXPECT_FLOAT_EQ(capu::Math::PI_f, capu::Math::Deg2Rad(180.0f));
EXPECT_DOUBLE_EQ(capu::Math::PI_d, capu::Math::Deg2Rad(180.0));
}<|endoftext|> |
<commit_before>// Copyright (c) 2010 Nickolas Pohilets
//
// This file is a part of the CppEvents library.
//
// 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 <Cpp/Events/Threading.hpp>
#include <Cpp/Events/ThreadData.hpp>
#include <Cpp/Threading/AtomicInt.hpp>
#include <Cpp/Threading/RecursiveMutex.hpp>
#include <Cpp/Threading/ThreadStorage.hpp>
#include <Std/Assert.hpp>
#include <Std/New.hpp>
namespace Cpp {
//------------------------------------------------------------------------------
class ThreadDataImpl
{
public:
ThreadDataImpl() { }
~ThreadDataImpl() { assert(ref_.isNull()); }
void lock()
{
mutex_.lock();
}
void unlock()
{
mutex_.unlock();
}
void retain()
{
ref_.retain();
}
void release()
{
if(ref_.release())
{
delete this;
}
}
private:
AtomicInt ref_;
RecursiveMutex mutex_;
};
//------------------------------------------------------------------------------
typedef ThreadStorage<ThreadDataImpl*> ThreadDataStorage;
static char storageBytes[sizeof(ThreadDataStorage)];
static ThreadDataStorage * storage = 0;
//------------------------------------------------------------------------------
void Threading::constructProcessData()
{
assert(!storage);
storage = new(storageBytes) ThreadDataStorage();
constructThreadData();
}
//------------------------------------------------------------------------------
void Threading::destructProcessData()
{
destructThreadData();
assert(storage);
storage->~ThreadDataStorage();
storage = 0;
}
//------------------------------------------------------------------------------
void Threading::constructThreadData()
{
assert(storage);
assert(!storage->data());
ThreadDataImpl * data = new ThreadDataImpl();
data->retain();
storage->setData(data);
}
//------------------------------------------------------------------------------
void Threading::destructThreadData()
{
assert(storage);
ThreadDataImpl * data = storage->data();
assert(data);
data->release();
storage->setData(0);
}
//------------------------------------------------------------------------------
Threading::ThreadData * Threading::currentThreadData()
{
assert(storage);
ThreadDataImpl * data = storage->data();
assert(data);
return reinterpret_cast<Threading::ThreadData*>(data);
}
//------------------------------------------------------------------------------
void Threading::ThreadData::lock()
{
reinterpret_cast<ThreadDataImpl*>(this)->lock();
}
//------------------------------------------------------------------------------
void Threading::ThreadData::unlock()
{
reinterpret_cast<ThreadDataImpl*>(this)->lock();
}
//------------------------------------------------------------------------------
void Threading::ThreadData::retain()
{
reinterpret_cast<ThreadDataImpl*>(this)->retain();
}
//------------------------------------------------------------------------------
void Threading::ThreadData::release()
{
reinterpret_cast<ThreadDataImpl*>(this)->release();
}
//------------------------------------------------------------------------------
} //namespace Cpp
<commit_msg>-: Fixed: horrible typo in Threading::ThreadData::unlock()<commit_after>// Copyright (c) 2010 Nickolas Pohilets
//
// This file is a part of the CppEvents library.
//
// 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 <Cpp/Events/Threading.hpp>
#include <Cpp/Events/ThreadData.hpp>
#include <Cpp/Threading/AtomicInt.hpp>
#include <Cpp/Threading/RecursiveMutex.hpp>
#include <Cpp/Threading/ThreadStorage.hpp>
#include <Std/Assert.hpp>
#include <Std/New.hpp>
namespace Cpp {
//------------------------------------------------------------------------------
class ThreadDataImpl
{
public:
ThreadDataImpl() { }
~ThreadDataImpl() { assert(ref_.isNull()); }
void lock()
{
mutex_.lock();
}
void unlock()
{
mutex_.unlock();
}
void retain()
{
ref_.retain();
}
void release()
{
if(ref_.release())
{
delete this;
}
}
private:
AtomicInt ref_;
RecursiveMutex mutex_;
};
//------------------------------------------------------------------------------
typedef ThreadStorage<ThreadDataImpl*> ThreadDataStorage;
static char storageBytes[sizeof(ThreadDataStorage)];
static ThreadDataStorage * storage = 0;
//------------------------------------------------------------------------------
void Threading::constructProcessData()
{
assert(!storage);
storage = new(storageBytes) ThreadDataStorage();
constructThreadData();
}
//------------------------------------------------------------------------------
void Threading::destructProcessData()
{
destructThreadData();
assert(storage);
storage->~ThreadDataStorage();
storage = 0;
}
//------------------------------------------------------------------------------
void Threading::constructThreadData()
{
assert(storage);
assert(!storage->data());
ThreadDataImpl * data = new ThreadDataImpl();
data->retain();
storage->setData(data);
}
//------------------------------------------------------------------------------
void Threading::destructThreadData()
{
assert(storage);
ThreadDataImpl * data = storage->data();
assert(data);
data->release();
storage->setData(0);
}
//------------------------------------------------------------------------------
Threading::ThreadData * Threading::currentThreadData()
{
assert(storage);
ThreadDataImpl * data = storage->data();
assert(data);
return reinterpret_cast<Threading::ThreadData*>(data);
}
//------------------------------------------------------------------------------
void Threading::ThreadData::lock()
{
reinterpret_cast<ThreadDataImpl*>(this)->lock();
}
//------------------------------------------------------------------------------
void Threading::ThreadData::unlock()
{
reinterpret_cast<ThreadDataImpl*>(this)->unlock();
}
//------------------------------------------------------------------------------
void Threading::ThreadData::retain()
{
reinterpret_cast<ThreadDataImpl*>(this)->retain();
}
//------------------------------------------------------------------------------
void Threading::ThreadData::release()
{
reinterpret_cast<ThreadDataImpl*>(this)->release();
}
//------------------------------------------------------------------------------
} //namespace Cpp
<|endoftext|> |
<commit_before>#include "DirectoryCorpusReader.ih"
DirectoryCorpusReader::DirectoryCorpusReader(QString const &directory) :
d_directory(directory)
{
}
QVector<QString> DirectoryCorpusReader::entries() const
{
return d_entries;
}
bool DirectoryCorpusReader::open()
{
QDir dir(d_directory, "*.xml");
if (!dir.exists() || !dir.isReadable()) {
qCritical() <<
"DirectoryCorpusReader::DirectoryCorpusReader: Could not read directory entries!";
return false;
}
// Retrieve and sort directory entries.
QDirIterator entryIter(dir, QDirIterator::Subdirectories | QDirIterator::FollowSymlinks);
QVector<IndexNamePair> indexedEntries;
while (entryIter.hasNext()) {
QString entry = entryIter.next();
entry = entry.remove(0, d_directory.length());
if (entry[0] == '/')
entry.remove(0, 1);
indexedEntries.push_back(entry);
}
sort(indexedEntries.begin(), indexedEntries.end(), IndexNamePairCompare());
for (QVector<IndexNamePair>::const_iterator iter = indexedEntries.constBegin();
iter != indexedEntries.constEnd(); ++iter)
d_entries.push_back(iter->name);
return true;
}
QString DirectoryCorpusReader::read(QString const &entry)
{
QString filename(QString("%1/%2").arg(d_directory).arg(entry));
return readFile(filename);
}
<commit_msg>DirectoryCorpusReader: build up entry list, so callers can get the size.<commit_after>#include "DirectoryCorpusReader.ih"
DirectoryCorpusReader::DirectoryCorpusReader(QString const &directory) :
d_directory(directory)
{
}
QVector<QString> DirectoryCorpusReader::entries() const
{
return d_entries;
}
bool DirectoryCorpusReader::open()
{
QDir dir(d_directory, "*.xml");
if (!dir.exists() || !dir.isReadable()) {
qCritical() <<
"DirectoryCorpusReader::DirectoryCorpusReader: Could not read directory entries!";
return false;
}
// Retrieve and sort directory entries.
QDirIterator entryIter(dir, QDirIterator::Subdirectories | QDirIterator::FollowSymlinks);
QVector<IndexNamePair> indexedEntries;
while (entryIter.hasNext()) {
QString entry = entryIter.next();
entry = entry.remove(0, d_directory.length());
if (entry[0] == '/')
entry.remove(0, 1);
indexedEntries.push_back(entry);
d_entries.push_back(entry); // Ugly hack to inform readers.
}
sort(indexedEntries.begin(), indexedEntries.end(), IndexNamePairCompare());
d_entries.clear();
for (QVector<IndexNamePair>::const_iterator iter = indexedEntries.constBegin();
iter != indexedEntries.constEnd(); ++iter)
d_entries.push_back(iter->name);
return true;
}
QString DirectoryCorpusReader::read(QString const &entry)
{
QString filename(QString("%1/%2").arg(d_directory).arg(entry));
return readFile(filename);
}
<|endoftext|> |
<commit_before>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// This transformation pass takes operations in TensorFlowLite dialect and
// optimizes them to resulting operations in TensorFlowLite dialect.
#include <climits>
#include <cstdint>
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/Casting.h"
#include "mlir/IR/Attributes.h" // TF:local_config_mlir
#include "mlir/IR/Matchers.h" // TF:local_config_mlir
#include "mlir/IR/PatternMatch.h" // TF:local_config_mlir
#include "mlir/IR/StandardTypes.h" // TF:local_config_mlir
#include "mlir/Pass/Pass.h" // TF:local_config_mlir
#include "mlir/StandardOps/Ops.h" // TF:local_config_mlir
#include "mlir/Support/Functional.h" // TF:local_config_mlir
#include "mlir/Support/LLVM.h" // TF:local_config_mlir
#include "tensorflow/compiler/mlir/lite/ir/tfl_ops.h"
#include "tensorflow/compiler/mlir/lite/transforms/passes.h"
#include "tensorflow/compiler/mlir/lite/utils/validators.h"
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
namespace mlir {
namespace TFL {
//===----------------------------------------------------------------------===//
// The actual Optimize Pass.
namespace {
using ::llvm::cast;
using ::llvm::isa;
// Optimize TFLite operations in functions.
struct Optimize : public FunctionPass<Optimize> {
void runOnFunction() override;
};
// Returns whether the given type `a` is broadcast-compatible with `b`.
bool IsBroadcastableElementsAttrAndType(Type a, Type b) {
return OpTrait::util::getBroadcastedType(a, b) != Type();
}
// Returns whether the given `a` and `b` ElementsAttr have broadcast-compatible
// types.
bool IsBroadcastableElementsAttrs(Attribute a, Attribute b) {
return IsBroadcastableElementsAttrAndType(a.getType(), b.getType());
}
#include "tensorflow/compiler/mlir/lite/transforms/generated_optimize.inc"
// Fuse Add with proceeding FullyConnected.
// Note that this assumes that the bias in the fullyConnected
// is always None.
// TODO(b/136285429): Move to tablegen when variadic is supported
// and add support for bias with noneType type.
struct FuseFullyConnectedAndAdd : public RewritePattern {
explicit FuseFullyConnectedAndAdd(MLIRContext *context)
: RewritePattern(TFL::AddOp::getOperationName(),
{"tfl.fully_connected", "tfl.add", "std.constant"}, 4,
context) {}
PatternMatchResult matchAndRewrite(Operation *add_op,
PatternRewriter &rewriter) const override {
// Fully Connected.
Operation *fully_connected = add_op->getOperand(0)->getDefiningOp();
if (!fully_connected || !isa<TFL::FullyConnectedOp>(fully_connected))
return matchFailure();
TFL::FullyConnectedOp fully_connected_op =
llvm::cast<TFL::FullyConnectedOp>(fully_connected);
Value *input = fully_connected_op.input();
Value *filter = fully_connected_op.filter();
// Make sure the bias is None.
// TODO(karimnosseir): Support non None case.
Operation *bias_op = fully_connected_op.bias()->getDefiningOp();
if (!bias_op || !isa<ConstantOp>(bias_op)) return matchFailure();
if (!fully_connected_op.bias()->getType().isa<NoneType>())
return matchFailure();
auto activation_func = fully_connected_op.getAttrOfType<StringAttr>(
"fused_activation_function");
if (!activation_func) return matchFailure();
if (activation_func.cast<StringAttr>().getValue() != "NONE")
return matchFailure();
auto weight_format =
fully_connected_op.getAttrOfType<StringAttr>("weights_format");
if (!weight_format) return matchFailure();
auto keep_num_dims =
fully_connected_op.getAttrOfType<BoolAttr>("keep_num_dims");
if (!keep_num_dims) return matchFailure();
auto constant_op = add_op->getOperand(1)->getDefiningOp();
if (!constant_op) return matchFailure();
if (!isa<ConstantOp>(constant_op)) return matchFailure();
auto add_value = constant_op->getAttrOfType<Attribute>("value");
if (!add_value) return matchFailure();
if (!((add_value.cast<ElementsAttr>().getType().getElementType().isF32())))
return matchFailure();
auto fused_activation_func =
add_op->getAttrOfType<StringAttr>("fused_activation_function");
if (!fused_activation_func) return matchFailure();
// Rewrite
// TODO(karimnosseir): Check what constraints needed to apply.
// TODO(b/136171362): Check for single output consumer.
rewriter.replaceOpWithNewOp<TFL::FullyConnectedOp>(
add_op, add_op->getResult(0)->getType(),
/*input=*/input,
/*filter=*/filter,
/*bias=*/add_op->getOperand(1),
/*fused_activation_function=*/fused_activation_func,
/*weights_format=*/weight_format,
/*keep_num_dims=*/keep_num_dims);
return matchSuccess();
}
};
// TODO(b/136285429): Move to tablegen when variadic is supported.
struct FuseFullyConnectedAndRelu : public RewritePattern {
explicit FuseFullyConnectedAndRelu(MLIRContext *context)
: RewritePattern(TFL::ReluOp::getOperationName(), {"tfl.fully_connected"},
4, context) {}
PatternMatchResult matchAndRewrite(Operation *op,
PatternRewriter &rewriter) const override {
auto relu_op = cast<ReluOp>(op);
Operation *input = relu_op.getOperand()->getDefiningOp();
if (!isa_and_nonnull<FullyConnectedOp>(input)) return matchFailure();
auto fully_connected_op = cast<FullyConnectedOp>(input);
if (fully_connected_op.fused_activation_function() != "NONE")
return matchFailure();
auto new_activation_func = rewriter.getStringAttr("RELU");
auto new_weights_format =
rewriter.getStringAttr(fully_connected_op.weights_format());
auto new_keep_num_dims =
rewriter.getBoolAttr(fully_connected_op.keep_num_dims());
rewriter.replaceOpWithNewOp<FullyConnectedOp>(
relu_op, relu_op.getType(), fully_connected_op.input(),
fully_connected_op.filter(), fully_connected_op.bias(),
new_activation_func, new_weights_format, new_keep_num_dims);
return matchSuccess();
}
};
// Fuse Mul with proceeding FullyConnected.
// TODO(b/136285429): Move to tablegen when variadic is supported
struct FuseFullyConnectedAndMul : public RewritePattern {
explicit FuseFullyConnectedAndMul(MLIRContext *context)
: RewritePattern(TFL::MulOp::getOperationName(),
{"tfl.fully_connected", "tfl.mul", "std.constant"}, 4,
context) {}
PatternMatchResult matchAndRewrite(Operation *op,
PatternRewriter &rewriter) const override {
// Mul.
auto mul_op = cast<MulOp>(op);
DenseElementsAttr cst;
Value *constant_val = mul_op.rhs();
if (!matchPattern(constant_val, m_Constant(&cst))) return matchFailure();
// Fully Connected.
auto fc_op =
dyn_cast_or_null<TFL::FullyConnectedOp>(mul_op.lhs()->getDefiningOp());
if (!fc_op) return matchFailure();
Value *filter = fc_op.filter();
Value *bias = fc_op.bias();
ElementsAttr cst_tmp;
if (!matchPattern(filter, m_Constant(&cst_tmp))) return matchFailure();
if (!bias->getType().isa<NoneType>() &&
!matchPattern(bias, m_Constant(&cst_tmp)))
return matchFailure();
if (fc_op.fused_activation_function().equals("None")) return matchFailure();
// Broadcast the constant operand of Mul if it isn't compatible to the
// filter input. We only support broadcasting the operand along the depth
// dimension, when the operand's depth is 1.
Value *new_const_val = constant_val;
if (!IsBroadcastableElementsAttrAndType(cst.getType(), filter->getType())) {
auto original_shape = cst.getType().getShape();
llvm::SmallVector<int64_t, 4> normalized_shape(original_shape.begin(),
original_shape.end());
normalized_shape.push_back(1);
auto new_cst = cst.reshape(rewriter.getTensorType(
normalized_shape, cst.getType().getElementType()));
Type new_type = new_cst.getType();
if (!IsBroadcastableElementsAttrAndType(new_type, filter->getType())) {
return matchFailure();
}
auto new_op =
rewriter.create<ConstantOp>(mul_op.getLoc(), new_type, new_cst);
new_const_val = new_op.getResult();
}
// Rewrite. Since the folder of TFL::MulOp couldn't broadcast the operands,
// TF::MulOp is used to fold the constant.
// TODO(b/139192933): switch to the TFL constant folding
Location loc = fc_op.getLoc();
auto new_filter =
rewriter.create<TF::MulOp>(loc, filter, new_const_val).z();
// If bias isn't None, it needs to be multiplied as well.
if (!bias->getType().isa<NoneType>()) {
bias = rewriter.create<TF::MulOp>(loc, bias, constant_val).z();
}
rewriter.replaceOpWithNewOp<TFL::FullyConnectedOp>(
mul_op, mul_op.getType(),
/*input=*/fc_op.input(),
/*filter=*/new_filter,
/*bias=*/bias,
/*fused_activation_function=*/
rewriter.getStringAttr(mul_op.fused_activation_function()),
/*weights_format=*/rewriter.getStringAttr(fc_op.weights_format()),
/*keep_num_dims=*/rewriter.getBoolAttr(fc_op.keep_num_dims()));
return matchSuccess();
}
};
// StridedSlice can have complicated atributes like begin_axis_mask,
// end_axis_mask, ellipsis_axis_mask, new_axis_mask, shrink_axis_mask. These
// masks will complicate the strided_slice computation logic, we can simplify
// the logic by inserting a reshape op to pad the inputs so strided_slice can
// be easier to handle.
//
// So the graph may looks like below:
// original_input -> strided_slice -> output
// (transforms)
// original_input -> reshape -> strided_slice -> output
//
// And the new shape is computed based on the masks.
//
// An example for new_axis_mask. say the new_axis_mask is 9 which represents
// [1 0 0 1], and that means we're inserting two new axes at 0 & 3 dim, so
// if original shape is [2, 3], now we reshape that into [1, 2, 3, 1].
struct PadStridedSliceDims : public RewritePattern {
explicit PadStridedSliceDims(MLIRContext *context)
: RewritePattern(TFL::StridedSliceOp::getOperationName(),
{"tfl.strided_slice", "tfl.strided_slice"}, 2, context) {
}
PatternMatchResult matchAndRewrite(Operation *strided_slice_op,
PatternRewriter &rewriter) const override {
// TODO(renjieliu): Consider expand the transformation for ellipsis & shrink
// mask as well.
TFL::StridedSliceOp strided_slice =
llvm::cast<TFL::StridedSliceOp>(strided_slice_op);
const uint64_t new_axis_mask = strided_slice.new_axis_mask().getZExtValue();
if (new_axis_mask == 0) return matchFailure();
// Insert a new reshape op.
Value *original_input = strided_slice.input();
const RankedTensorType &original_input_type =
original_input->getType().template cast<RankedTensorType>();
const ArrayRef<int64_t> &original_input_shape =
original_input_type.getShape();
const RankedTensorType &begin_type =
strided_slice.begin()->getType().template cast<RankedTensorType>();
const int dim_size = begin_type.getShape()[0];
SmallVector<int64_t, 4> new_shape;
int mask = 1;
int index = 0;
for (int i = 0; i < dim_size; ++i) {
if (mask & new_axis_mask) {
new_shape.emplace_back(1);
} else {
new_shape.emplace_back(original_input_shape[index]);
++index;
}
mask = mask << 1;
}
auto new_output_type =
rewriter.getTensorType(new_shape, original_input_type.getElementType());
TFL::ReshapeOp reshape = rewriter.create<TFL::ReshapeOp>(
strided_slice.getLoc(), new_output_type, original_input);
// Replace the original strided_slice.
llvm::APInt new_begin_mask = strided_slice.begin_mask();
llvm::APInt new_end_mask = strided_slice.end_mask();
// Since we expand the dims, we need to apply them to the begin_mask &
// end_mask.
new_begin_mask |= strided_slice.new_axis_mask();
new_end_mask |= strided_slice.new_axis_mask();
auto attribute_type = rewriter.getIntegerType(32);
rewriter.replaceOpWithNewOp<TFL::StridedSliceOp>(
strided_slice_op, strided_slice.getType(), reshape,
strided_slice.begin(), strided_slice.end(), strided_slice.strides(),
rewriter.getIntegerAttr(attribute_type, new_begin_mask),
rewriter.getIntegerAttr(attribute_type, new_end_mask),
rewriter.getIntegerAttr(attribute_type, strided_slice.ellipsis_mask()),
rewriter.getI32IntegerAttr(0),
rewriter.getIntegerAttr(attribute_type,
strided_slice.shrink_axis_mask()));
return matchSuccess();
}
};
void Optimize::runOnFunction() {
OwningRewritePatternList patterns;
auto *ctx = &getContext();
auto func = getFunction();
// Add the generated patterns to the list.
TFL::populateWithGenerated(ctx, &patterns);
patterns.insert<FuseFullyConnectedAndAdd, FuseFullyConnectedAndRelu,
FuseFullyConnectedAndMul, PadStridedSliceDims>(ctx);
applyPatternsGreedily(func, patterns);
}
} // namespace
// Creates an instance of the TensorFlow Lite dialect Optimize pass.
FunctionPassBase *CreateOptimizePass() { return new Optimize(); }
static PassRegistration<Optimize> pass(
"tfl-optimize", "Optimize within the TensorFlow Lite dialect");
} // namespace TFL
} // namespace mlir
<commit_msg>Remove unnecessary const & for Type and also remove unnecessary 'template'.<commit_after>/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// This transformation pass takes operations in TensorFlowLite dialect and
// optimizes them to resulting operations in TensorFlowLite dialect.
#include <climits>
#include <cstdint>
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/Casting.h"
#include "mlir/IR/Attributes.h" // TF:local_config_mlir
#include "mlir/IR/Matchers.h" // TF:local_config_mlir
#include "mlir/IR/PatternMatch.h" // TF:local_config_mlir
#include "mlir/IR/StandardTypes.h" // TF:local_config_mlir
#include "mlir/Pass/Pass.h" // TF:local_config_mlir
#include "mlir/StandardOps/Ops.h" // TF:local_config_mlir
#include "mlir/Support/Functional.h" // TF:local_config_mlir
#include "mlir/Support/LLVM.h" // TF:local_config_mlir
#include "tensorflow/compiler/mlir/lite/ir/tfl_ops.h"
#include "tensorflow/compiler/mlir/lite/transforms/passes.h"
#include "tensorflow/compiler/mlir/lite/utils/validators.h"
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
namespace mlir {
namespace TFL {
//===----------------------------------------------------------------------===//
// The actual Optimize Pass.
namespace {
using ::llvm::cast;
using ::llvm::isa;
// Optimize TFLite operations in functions.
struct Optimize : public FunctionPass<Optimize> {
void runOnFunction() override;
};
// Returns whether the given type `a` is broadcast-compatible with `b`.
bool IsBroadcastableElementsAttrAndType(Type a, Type b) {
return OpTrait::util::getBroadcastedType(a, b) != Type();
}
// Returns whether the given `a` and `b` ElementsAttr have broadcast-compatible
// types.
bool IsBroadcastableElementsAttrs(Attribute a, Attribute b) {
return IsBroadcastableElementsAttrAndType(a.getType(), b.getType());
}
#include "tensorflow/compiler/mlir/lite/transforms/generated_optimize.inc"
// Fuse Add with proceeding FullyConnected.
// Note that this assumes that the bias in the fullyConnected
// is always None.
// TODO(b/136285429): Move to tablegen when variadic is supported
// and add support for bias with noneType type.
struct FuseFullyConnectedAndAdd : public RewritePattern {
explicit FuseFullyConnectedAndAdd(MLIRContext *context)
: RewritePattern(TFL::AddOp::getOperationName(),
{"tfl.fully_connected", "tfl.add", "std.constant"}, 4,
context) {}
PatternMatchResult matchAndRewrite(Operation *add_op,
PatternRewriter &rewriter) const override {
// Fully Connected.
Operation *fully_connected = add_op->getOperand(0)->getDefiningOp();
if (!fully_connected || !isa<TFL::FullyConnectedOp>(fully_connected))
return matchFailure();
TFL::FullyConnectedOp fully_connected_op =
llvm::cast<TFL::FullyConnectedOp>(fully_connected);
Value *input = fully_connected_op.input();
Value *filter = fully_connected_op.filter();
// Make sure the bias is None.
// TODO(karimnosseir): Support non None case.
Operation *bias_op = fully_connected_op.bias()->getDefiningOp();
if (!bias_op || !isa<ConstantOp>(bias_op)) return matchFailure();
if (!fully_connected_op.bias()->getType().isa<NoneType>())
return matchFailure();
auto activation_func = fully_connected_op.getAttrOfType<StringAttr>(
"fused_activation_function");
if (!activation_func) return matchFailure();
if (activation_func.cast<StringAttr>().getValue() != "NONE")
return matchFailure();
auto weight_format =
fully_connected_op.getAttrOfType<StringAttr>("weights_format");
if (!weight_format) return matchFailure();
auto keep_num_dims =
fully_connected_op.getAttrOfType<BoolAttr>("keep_num_dims");
if (!keep_num_dims) return matchFailure();
auto constant_op = add_op->getOperand(1)->getDefiningOp();
if (!constant_op) return matchFailure();
if (!isa<ConstantOp>(constant_op)) return matchFailure();
auto add_value = constant_op->getAttrOfType<Attribute>("value");
if (!add_value) return matchFailure();
if (!((add_value.cast<ElementsAttr>().getType().getElementType().isF32())))
return matchFailure();
auto fused_activation_func =
add_op->getAttrOfType<StringAttr>("fused_activation_function");
if (!fused_activation_func) return matchFailure();
// Rewrite
// TODO(karimnosseir): Check what constraints needed to apply.
// TODO(b/136171362): Check for single output consumer.
rewriter.replaceOpWithNewOp<TFL::FullyConnectedOp>(
add_op, add_op->getResult(0)->getType(),
/*input=*/input,
/*filter=*/filter,
/*bias=*/add_op->getOperand(1),
/*fused_activation_function=*/fused_activation_func,
/*weights_format=*/weight_format,
/*keep_num_dims=*/keep_num_dims);
return matchSuccess();
}
};
// TODO(b/136285429): Move to tablegen when variadic is supported.
struct FuseFullyConnectedAndRelu : public RewritePattern {
explicit FuseFullyConnectedAndRelu(MLIRContext *context)
: RewritePattern(TFL::ReluOp::getOperationName(), {"tfl.fully_connected"},
4, context) {}
PatternMatchResult matchAndRewrite(Operation *op,
PatternRewriter &rewriter) const override {
auto relu_op = cast<ReluOp>(op);
Operation *input = relu_op.getOperand()->getDefiningOp();
if (!isa_and_nonnull<FullyConnectedOp>(input)) return matchFailure();
auto fully_connected_op = cast<FullyConnectedOp>(input);
if (fully_connected_op.fused_activation_function() != "NONE")
return matchFailure();
auto new_activation_func = rewriter.getStringAttr("RELU");
auto new_weights_format =
rewriter.getStringAttr(fully_connected_op.weights_format());
auto new_keep_num_dims =
rewriter.getBoolAttr(fully_connected_op.keep_num_dims());
rewriter.replaceOpWithNewOp<FullyConnectedOp>(
relu_op, relu_op.getType(), fully_connected_op.input(),
fully_connected_op.filter(), fully_connected_op.bias(),
new_activation_func, new_weights_format, new_keep_num_dims);
return matchSuccess();
}
};
// Fuse Mul with proceeding FullyConnected.
// TODO(b/136285429): Move to tablegen when variadic is supported
struct FuseFullyConnectedAndMul : public RewritePattern {
explicit FuseFullyConnectedAndMul(MLIRContext *context)
: RewritePattern(TFL::MulOp::getOperationName(),
{"tfl.fully_connected", "tfl.mul", "std.constant"}, 4,
context) {}
PatternMatchResult matchAndRewrite(Operation *op,
PatternRewriter &rewriter) const override {
// Mul.
auto mul_op = cast<MulOp>(op);
DenseElementsAttr cst;
Value *constant_val = mul_op.rhs();
if (!matchPattern(constant_val, m_Constant(&cst))) return matchFailure();
// Fully Connected.
auto fc_op =
dyn_cast_or_null<TFL::FullyConnectedOp>(mul_op.lhs()->getDefiningOp());
if (!fc_op) return matchFailure();
Value *filter = fc_op.filter();
Value *bias = fc_op.bias();
ElementsAttr cst_tmp;
if (!matchPattern(filter, m_Constant(&cst_tmp))) return matchFailure();
if (!bias->getType().isa<NoneType>() &&
!matchPattern(bias, m_Constant(&cst_tmp)))
return matchFailure();
if (fc_op.fused_activation_function().equals("None")) return matchFailure();
// Broadcast the constant operand of Mul if it isn't compatible to the
// filter input. We only support broadcasting the operand along the depth
// dimension, when the operand's depth is 1.
Value *new_const_val = constant_val;
if (!IsBroadcastableElementsAttrAndType(cst.getType(), filter->getType())) {
auto original_shape = cst.getType().getShape();
llvm::SmallVector<int64_t, 4> normalized_shape(original_shape.begin(),
original_shape.end());
normalized_shape.push_back(1);
auto new_cst = cst.reshape(rewriter.getTensorType(
normalized_shape, cst.getType().getElementType()));
Type new_type = new_cst.getType();
if (!IsBroadcastableElementsAttrAndType(new_type, filter->getType())) {
return matchFailure();
}
auto new_op =
rewriter.create<ConstantOp>(mul_op.getLoc(), new_type, new_cst);
new_const_val = new_op.getResult();
}
// Rewrite. Since the folder of TFL::MulOp couldn't broadcast the operands,
// TF::MulOp is used to fold the constant.
// TODO(b/139192933): switch to the TFL constant folding
Location loc = fc_op.getLoc();
auto new_filter =
rewriter.create<TF::MulOp>(loc, filter, new_const_val).z();
// If bias isn't None, it needs to be multiplied as well.
if (!bias->getType().isa<NoneType>()) {
bias = rewriter.create<TF::MulOp>(loc, bias, constant_val).z();
}
rewriter.replaceOpWithNewOp<TFL::FullyConnectedOp>(
mul_op, mul_op.getType(),
/*input=*/fc_op.input(),
/*filter=*/new_filter,
/*bias=*/bias,
/*fused_activation_function=*/
rewriter.getStringAttr(mul_op.fused_activation_function()),
/*weights_format=*/rewriter.getStringAttr(fc_op.weights_format()),
/*keep_num_dims=*/rewriter.getBoolAttr(fc_op.keep_num_dims()));
return matchSuccess();
}
};
// StridedSlice can have complicated atributes like begin_axis_mask,
// end_axis_mask, ellipsis_axis_mask, new_axis_mask, shrink_axis_mask. These
// masks will complicate the strided_slice computation logic, we can simplify
// the logic by inserting a reshape op to pad the inputs so strided_slice can
// be easier to handle.
//
// So the graph may looks like below:
// original_input -> strided_slice -> output
// (transforms)
// original_input -> reshape -> strided_slice -> output
//
// And the new shape is computed based on the masks.
//
// An example for new_axis_mask. say the new_axis_mask is 9 which represents
// [1 0 0 1], and that means we're inserting two new axes at 0 & 3 dim, so
// if original shape is [2, 3], now we reshape that into [1, 2, 3, 1].
struct PadStridedSliceDims : public RewritePattern {
explicit PadStridedSliceDims(MLIRContext *context)
: RewritePattern(TFL::StridedSliceOp::getOperationName(),
{"tfl.strided_slice", "tfl.strided_slice"}, 2, context) {
}
PatternMatchResult matchAndRewrite(Operation *strided_slice_op,
PatternRewriter &rewriter) const override {
// TODO(renjieliu): Consider expand the transformation for ellipsis & shrink
// mask as well.
TFL::StridedSliceOp strided_slice =
llvm::cast<TFL::StridedSliceOp>(strided_slice_op);
const uint64_t new_axis_mask = strided_slice.new_axis_mask().getZExtValue();
if (new_axis_mask == 0) return matchFailure();
// Insert a new reshape op.
Value *original_input = strided_slice.input();
RankedTensorType original_input_type =
original_input->getType().cast<RankedTensorType>();
const ArrayRef<int64_t> &original_input_shape =
original_input_type.getShape();
RankedTensorType begin_type =
strided_slice.begin()->getType().cast<RankedTensorType>();
const int dim_size = begin_type.getShape()[0];
SmallVector<int64_t, 4> new_shape;
int mask = 1;
int index = 0;
for (int i = 0; i < dim_size; ++i) {
if (mask & new_axis_mask) {
new_shape.emplace_back(1);
} else {
new_shape.emplace_back(original_input_shape[index]);
++index;
}
mask = mask << 1;
}
auto new_output_type =
rewriter.getTensorType(new_shape, original_input_type.getElementType());
TFL::ReshapeOp reshape = rewriter.create<TFL::ReshapeOp>(
strided_slice.getLoc(), new_output_type, original_input);
// Replace the original strided_slice.
llvm::APInt new_begin_mask = strided_slice.begin_mask();
llvm::APInt new_end_mask = strided_slice.end_mask();
// Since we expand the dims, we need to apply them to the begin_mask &
// end_mask.
new_begin_mask |= strided_slice.new_axis_mask();
new_end_mask |= strided_slice.new_axis_mask();
auto attribute_type = rewriter.getIntegerType(32);
rewriter.replaceOpWithNewOp<TFL::StridedSliceOp>(
strided_slice_op, strided_slice.getType(), reshape,
strided_slice.begin(), strided_slice.end(), strided_slice.strides(),
rewriter.getIntegerAttr(attribute_type, new_begin_mask),
rewriter.getIntegerAttr(attribute_type, new_end_mask),
rewriter.getIntegerAttr(attribute_type, strided_slice.ellipsis_mask()),
rewriter.getI32IntegerAttr(0),
rewriter.getIntegerAttr(attribute_type,
strided_slice.shrink_axis_mask()));
return matchSuccess();
}
};
void Optimize::runOnFunction() {
OwningRewritePatternList patterns;
auto *ctx = &getContext();
auto func = getFunction();
// Add the generated patterns to the list.
TFL::populateWithGenerated(ctx, &patterns);
patterns.insert<FuseFullyConnectedAndAdd, FuseFullyConnectedAndRelu,
FuseFullyConnectedAndMul, PadStridedSliceDims>(ctx);
applyPatternsGreedily(func, patterns);
}
} // namespace
// Creates an instance of the TensorFlow Lite dialect Optimize pass.
FunctionPassBase *CreateOptimizePass() { return new Optimize(); }
static PassRegistration<Optimize> pass(
"tfl-optimize", "Optimize within the TensorFlow Lite dialect");
} // namespace TFL
} // namespace mlir
<|endoftext|> |
<commit_before>/*
SDL - Simple DirectMedia Layer
Copyright (C) 1997-2009 Sam Lantinga
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 St, Fifth Floor, Boston, MA 02110-1301 USA
Sam Lantinga
[email protected]
*/
#include "SDL_config.h"
/* Being a null driver, there's no event stream. We just define stubs for
most of the API. */
#include "SDL.h"
#include "../../events/SDL_sysevents.h"
#include "../../events/SDL_events_c.h"
#include "SDL_nullvideo.h"
#include "SDL_nullevents_c.h"
#include <syslog.h>
#include <input/Input.h>
void input_handler(Input::InputNotification ¬e)
{
syslog(LOG_NOTICE, "got input!");
if(note.type == Input::Key)
{
SDL_keysym sym;
sym.scancode = 0;
sym.sym = static_cast<SDLKey>(note.data.key.key);
sym.mod = KMOD_NONE;
sym.unicode = 0;
SDL_PrivateKeyboard(SDL_PRESSED, &sym);
SDL_PrivateKeyboard(SDL_RELEASED, &sym);
}
else if(note.type == Input::Mouse)
{
Uint8 state = 0;
for(int i = 0; i < 8; i++)
if(note.data.pointy.buttons[i])
state |= (1 << i);
SDL_PrivateMouseMotion(state, 1, (Sint16) note.data.pointy.relx, (Sint16) note.data.pointy.rely);
}
}
void PEDIGREE_InitInput()
{
Input::installCallback(input_handler);
}
void PEDIGREE_DestroyInput()
{
Input::removeCallback(input_handler);
}
void PEDIGREE_PumpEvents(_THIS)
{
/* do nothing. */
}
void PEDIGREE_InitOSKeymap(_THIS)
{
/* do nothing. */
}
/* end of SDL_nullevents.c ... */
<commit_msg>Remove annoying debug from SDL_nullevents.cc<commit_after>/*
SDL - Simple DirectMedia Layer
Copyright (C) 1997-2009 Sam Lantinga
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 St, Fifth Floor, Boston, MA 02110-1301 USA
Sam Lantinga
[email protected]
*/
#include "SDL_config.h"
/* Being a null driver, there's no event stream. We just define stubs for
most of the API. */
#include "SDL.h"
#include "../../events/SDL_sysevents.h"
#include "../../events/SDL_events_c.h"
#include "SDL_nullvideo.h"
#include "SDL_nullevents_c.h"
#include <syslog.h>
#include <input/Input.h>
void input_handler(Input::InputNotification ¬e)
{
if(note.type == Input::Key)
{
SDL_keysym sym;
sym.scancode = 0;
sym.sym = static_cast<SDLKey>(note.data.key.key);
sym.mod = KMOD_NONE;
sym.unicode = 0;
SDL_PrivateKeyboard(SDL_PRESSED, &sym);
SDL_PrivateKeyboard(SDL_RELEASED, &sym);
}
else if(note.type == Input::Mouse)
{
Uint8 state = 0;
for(int i = 0; i < 8; i++)
if(note.data.pointy.buttons[i])
state |= (1 << i);
SDL_PrivateMouseMotion(state, 1, (Sint16) note.data.pointy.relx, (Sint16) note.data.pointy.rely);
}
}
void PEDIGREE_InitInput()
{
Input::installCallback(input_handler);
}
void PEDIGREE_DestroyInput()
{
Input::removeCallback(input_handler);
}
void PEDIGREE_PumpEvents(_THIS)
{
/* do nothing. */
}
void PEDIGREE_InitOSKeymap(_THIS)
{
/* do nothing. */
}
/* end of SDL_nullevents.c ... */
<|endoftext|> |
<commit_before>
#include <QOpenGLShaderProgram>
#include <QOpenGLFunctions_3_2_Core>
#include "UniformParser.h"
namespace glraw
{
void UniformParser::setUniforms(
QOpenGLFunctions_3_2_Core & gl
, QOpenGLShaderProgram & program
, const QMap<QString, QString> & uniforms)
{
if (uniforms.isEmpty())
return;
if (!program.isLinked())
return;
program.bind();
GLint activeUniforms = 0;
gl.glGetProgramiv(program.programId(), GL_ACTIVE_UNIFORMS, &activeUniforms);
GLint activeUniformMaxLength = 0;
gl.glGetProgramiv(program.programId(), GL_ACTIVE_UNIFORM_MAX_LENGTH, &activeUniformMaxLength);
QMap<QString, GLenum> uniformTypesByName;
// gather all active uniform names and types
for (int i = 0; i < activeUniforms; ++i)
{
GLenum uniformType = 0;
GLchar * uniformName = new GLchar[activeUniformMaxLength];
GLsizei uniformNameLength = -1;
GLint uniformSize = -1;
gl.glGetActiveUniform(program.programId(), i, activeUniformMaxLength
, &uniformNameLength, &uniformSize, &uniformType, uniformName);
uniformTypesByName.insert(QString(uniformName), uniformType);
delete[] uniformName;
}
for (const QString & uniform : uniforms.keys())
{
if (!uniformTypesByName.contains(uniform))
continue;
const GLenum type = uniformTypesByName[uniform];
QString value = uniforms[uniform];
switch (type)
{
case GL_FLOAT:
case GL_DOUBLE:
setFloat(program, uniform, value);
break;
case GL_FLOAT_VEC2:
case GL_DOUBLE_VEC2:
setVec2(program, uniform, value);
break;
case GL_FLOAT_VEC3:
case GL_DOUBLE_VEC3:
setVec3(program, uniform, value);
break;
case GL_FLOAT_VEC4:
case GL_DOUBLE_VEC4:
setVec4(program, uniform, value);
break;
case GL_INT:
setInt(program, uniform, value);
break;
case GL_INT_VEC2:
case GL_INT_VEC3:
case GL_INT_VEC4:
case GL_UNSIGNED_INT:
case GL_UNSIGNED_INT_VEC2:
case GL_UNSIGNED_INT_VEC3:
case GL_UNSIGNED_INT_VEC4:
typeUnsupported(uniform);
break;
case GL_BOOL:
case GL_BOOL_VEC2:
case GL_BOOL_VEC3:
case GL_BOOL_VEC4:
typeUnsupported(uniform);
break;
case GL_FLOAT_MAT2:
case GL_FLOAT_MAT3:
case GL_FLOAT_MAT4:
case GL_FLOAT_MAT2x3:
case GL_FLOAT_MAT2x4:
case GL_FLOAT_MAT3x2:
case GL_FLOAT_MAT3x4:
case GL_FLOAT_MAT4x2:
case GL_FLOAT_MAT4x3:
case GL_DOUBLE_MAT2:
case GL_DOUBLE_MAT3:
case GL_DOUBLE_MAT4:
case GL_DOUBLE_MAT2x3:
case GL_DOUBLE_MAT2x4:
case GL_DOUBLE_MAT3x2:
case GL_DOUBLE_MAT3x4:
case GL_DOUBLE_MAT4x2:
case GL_DOUBLE_MAT4x3:
typeUnsupported(uniform);
break;
case GL_SAMPLER_1D:
case GL_SAMPLER_2D:
case GL_SAMPLER_3D:
case GL_SAMPLER_CUBE:
case GL_SAMPLER_1D_SHADOW:
case GL_SAMPLER_2D_SHADOW:
case GL_SAMPLER_1D_ARRAY:
case GL_SAMPLER_2D_ARRAY:
case GL_SAMPLER_1D_ARRAY_SHADOW:
case GL_SAMPLER_2D_ARRAY_SHADOW:
case GL_SAMPLER_2D_MULTISAMPLE:
case GL_SAMPLER_2D_MULTISAMPLE_ARRAY:
case GL_SAMPLER_CUBE_SHADOW:
case GL_SAMPLER_BUFFER:
case GL_SAMPLER_2D_RECT:
case GL_SAMPLER_2D_RECT_SHADOW:
case GL_INT_SAMPLER_1D:
case GL_INT_SAMPLER_2D:
case GL_INT_SAMPLER_3D:
case GL_INT_SAMPLER_CUBE:
case GL_INT_SAMPLER_1D_ARRAY:
case GL_INT_SAMPLER_2D_ARRAY:
case GL_INT_SAMPLER_2D_MULTISAMPLE:
case GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY:
case GL_INT_SAMPLER_BUFFER:
case GL_INT_SAMPLER_2D_RECT:
case GL_UNSIGNED_INT_SAMPLER_1D:
case GL_UNSIGNED_INT_SAMPLER_2D:
case GL_UNSIGNED_INT_SAMPLER_3D:
case GL_UNSIGNED_INT_SAMPLER_CUBE:
case GL_UNSIGNED_INT_SAMPLER_1D_ARRAY:
case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY:
case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE:
case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY:
case GL_UNSIGNED_INT_SAMPLER_BUFFER:
case GL_UNSIGNED_INT_SAMPLER_2D_RECT:
case GL_IMAGE_1D:
case GL_IMAGE_2D:
case GL_IMAGE_3D:
case GL_IMAGE_2D_RECT:
case GL_IMAGE_CUBE:
case GL_IMAGE_BUFFER:
case GL_IMAGE_1D_ARRAY:
case GL_IMAGE_2D_ARRAY:
case GL_IMAGE_2D_MULTISAMPLE:
case GL_IMAGE_2D_MULTISAMPLE_ARRAY:
case GL_INT_IMAGE_1D:
case GL_INT_IMAGE_2D:
case GL_INT_IMAGE_3D:
case GL_INT_IMAGE_2D_RECT:
case GL_INT_IMAGE_CUBE:
case GL_INT_IMAGE_BUFFER:
case GL_INT_IMAGE_1D_ARRAY:
case GL_INT_IMAGE_2D_ARRAY:
case GL_INT_IMAGE_2D_MULTISAMPLE:
case GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY:
case GL_UNSIGNED_INT_IMAGE_1D:
case GL_UNSIGNED_INT_IMAGE_2D:
case GL_UNSIGNED_INT_IMAGE_3D:
case GL_UNSIGNED_INT_IMAGE_2D_RECT:
case GL_UNSIGNED_INT_IMAGE_CUBE:
case GL_UNSIGNED_INT_IMAGE_BUFFER:
case GL_UNSIGNED_INT_IMAGE_1D_ARRAY:
case GL_UNSIGNED_INT_IMAGE_2D_ARRAY:
case GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE:
case GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY:
case GL_UNSIGNED_INT_ATOMIC_COUNTER:
setInt(program, uniform, value);
break;
}
}
}
void UniformParser::setFloat(
QOpenGLShaderProgram & program
, const QString & uniform
, QString value)
{
bool ok;
float v = value.toFloat(&ok);
if (ok)
program.setUniformValue(uniform.toStdString().c_str(), v);
else
parsingFailed(uniform, value);
}
void UniformParser::setInt(
QOpenGLShaderProgram & program
, const QString & uniform
, QString value)
{
bool ok;
int v = value.toInt(&ok);
if (!ok)
v = static_cast<int>(value.toFloat(&ok));
if (ok)
program.setUniformValue(uniform.toStdString().c_str(), v);
else
parsingFailed(uniform, value);
}
void UniformParser::setUInt(
QOpenGLShaderProgram & program
, const QString & uniform
, QString value)
{
bool ok;
int v = value.toUInt(&ok);
if (!ok)
v = static_cast<unsigned int>(value.toFloat(&ok));
if (ok)
program.setUniformValue(uniform.toStdString().c_str(), v);
else
parsingFailed(uniform, value);
}
void UniformParser::setVec2(
QOpenGLShaderProgram & program
, const QString & uniform
, QString value)
{
if (!value.startsWith("dvec2") && !value.startsWith("vec2"))
{
typeMismatch(uniform);
return;
}
value.remove("dvec2(");
value.remove("vec2(");
value.remove(")");
const QStringList values = value.split(",");
if (values.size() == 2)
{
bool ok[2];
const QVector2D vec2(
values[0].toFloat(&ok[0])
, values[1].toFloat(&ok[1]));
if (ok[0] && ok[1])
{
program.setUniformValue(uniform.toStdString().c_str(), vec2);
return;
}
}
parsingFailed(uniform, value);
}
void UniformParser::setVec3(
QOpenGLShaderProgram & program
, const QString & uniform
, QString value)
{
if (!value.startsWith("dvec3") && !value.startsWith("vec3"))
{
typeMismatch(uniform);
return;
}
value.remove("dvec3(");
value.remove("vec3(");
value.remove(")");
const QStringList values = value.split(",");
if (values.size() == 3)
{
bool ok[3];
const QVector3D vec3(
values[0].toFloat(&ok[0])
, values[1].toFloat(&ok[1])
, values[2].toFloat(&ok[2]));
if (ok[0] && ok[1] && ok[2])
{
program.setUniformValue(uniform.toStdString().c_str(), vec3);
return;
}
}
parsingFailed(uniform, value);
}
void UniformParser::setVec4(
QOpenGLShaderProgram & program
, const QString & uniform
, QString value)
{
if (!value.startsWith("dvec4") && !value.startsWith("vec4"))
{
typeMismatch(uniform);
return;
}
value.remove("dvec4(");
value.remove("vec4(");
value.remove(")");
const QStringList values = value.split(",");
if (values.size() == 4)
{
bool ok[4];
const QVector4D vec4(
values[0].toFloat(&ok[0])
, values[1].toFloat(&ok[1])
, values[2].toFloat(&ok[2])
, values[3].toFloat(&ok[3]));
if (ok[0] && ok[1] && ok[2] && ok[3])
{
program.setUniformValue(uniform.toStdString().c_str(), vec4);
return;
}
}
parsingFailed(uniform, value);
}
void UniformParser::typeMismatch(const QString & uniform)
{
qDebug() << "Uniform value-type missmatch for" << uniform << ".";
}
void UniformParser::typeUnsupported(const QString & uniform)
{
qDebug() << "Uniform value-type" << uniform << " is not supported.";
}
void UniformParser::parsingFailed(const QString & uniform, const QString & value)
{
qDebug() << "Parsing uniform value" << value << "for" << uniform << "failed.";
}
} // namespace glraw
<commit_msg>Fix use of OpenGL constants nor yet supported with OpenGL 4.1 (Mac).<commit_after>
#include <QOpenGLShaderProgram>
#include <QOpenGLFunctions_3_2_Core>
#include "UniformParser.h"
namespace glraw
{
void UniformParser::setUniforms(
QOpenGLFunctions_3_2_Core & gl
, QOpenGLShaderProgram & program
, const QMap<QString, QString> & uniforms)
{
if (uniforms.isEmpty())
return;
if (!program.isLinked())
return;
program.bind();
GLint activeUniforms = 0;
gl.glGetProgramiv(program.programId(), GL_ACTIVE_UNIFORMS, &activeUniforms);
GLint activeUniformMaxLength = 0;
gl.glGetProgramiv(program.programId(), GL_ACTIVE_UNIFORM_MAX_LENGTH, &activeUniformMaxLength);
QMap<QString, GLenum> uniformTypesByName;
// gather all active uniform names and types
for (int i = 0; i < activeUniforms; ++i)
{
GLenum uniformType = 0;
GLchar * uniformName = new GLchar[activeUniformMaxLength];
GLsizei uniformNameLength = -1;
GLint uniformSize = -1;
gl.glGetActiveUniform(program.programId(), i, activeUniformMaxLength
, &uniformNameLength, &uniformSize, &uniformType, uniformName);
uniformTypesByName.insert(QString(uniformName), uniformType);
delete[] uniformName;
}
for (const QString & uniform : uniforms.keys())
{
if (!uniformTypesByName.contains(uniform))
continue;
const GLenum type = uniformTypesByName[uniform];
QString value = uniforms[uniform];
switch (type)
{
case GL_FLOAT:
case GL_DOUBLE:
setFloat(program, uniform, value);
break;
case GL_FLOAT_VEC2:
case GL_DOUBLE_VEC2:
setVec2(program, uniform, value);
break;
case GL_FLOAT_VEC3:
case GL_DOUBLE_VEC3:
setVec3(program, uniform, value);
break;
case GL_FLOAT_VEC4:
case GL_DOUBLE_VEC4:
setVec4(program, uniform, value);
break;
case GL_INT:
setInt(program, uniform, value);
break;
case GL_INT_VEC2:
case GL_INT_VEC3:
case GL_INT_VEC4:
case GL_UNSIGNED_INT:
case GL_UNSIGNED_INT_VEC2:
case GL_UNSIGNED_INT_VEC3:
case GL_UNSIGNED_INT_VEC4:
case GL_BOOL:
case GL_BOOL_VEC2:
case GL_BOOL_VEC3:
case GL_BOOL_VEC4:
case GL_FLOAT_MAT2:
case GL_FLOAT_MAT3:
case GL_FLOAT_MAT4:
case GL_FLOAT_MAT2x3:
case GL_FLOAT_MAT2x4:
case GL_FLOAT_MAT3x2:
case GL_FLOAT_MAT3x4:
case GL_FLOAT_MAT4x2:
case GL_FLOAT_MAT4x3:
case GL_DOUBLE_MAT2:
case GL_DOUBLE_MAT3:
case GL_DOUBLE_MAT4:
case GL_DOUBLE_MAT2x3:
case GL_DOUBLE_MAT2x4:
case GL_DOUBLE_MAT3x2:
case GL_DOUBLE_MAT3x4:
case GL_DOUBLE_MAT4x2:
case GL_DOUBLE_MAT4x3:
default:
typeUnsupported(uniform);
break;
// case GL_SAMPLER_1D:
// case GL_SAMPLER_2D:
// case GL_SAMPLER_3D:
// case GL_SAMPLER_CUBE:
// case GL_SAMPLER_1D_SHADOW:
// case GL_SAMPLER_2D_SHADOW:
// case GL_SAMPLER_1D_ARRAY:
// case GL_SAMPLER_2D_ARRAY:
// case GL_SAMPLER_1D_ARRAY_SHADOW:
// case GL_SAMPLER_2D_ARRAY_SHADOW:
// case GL_SAMPLER_2D_MULTISAMPLE:
// case GL_SAMPLER_2D_MULTISAMPLE_ARRAY:
// case GL_SAMPLER_CUBE_SHADOW:
// case GL_SAMPLER_BUFFER:
// case GL_SAMPLER_2D_RECT:
// case GL_SAMPLER_2D_RECT_SHADOW:
// case GL_INT_SAMPLER_1D:
// case GL_INT_SAMPLER_2D:
// case GL_INT_SAMPLER_3D:
// case GL_INT_SAMPLER_CUBE:
// case GL_INT_SAMPLER_1D_ARRAY:
// case GL_INT_SAMPLER_2D_ARRAY:
// case GL_INT_SAMPLER_2D_MULTISAMPLE:
// case GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY:
// case GL_INT_SAMPLER_BUFFER:
// case GL_INT_SAMPLER_2D_RECT:
// case GL_UNSIGNED_INT_SAMPLER_1D:
// case GL_UNSIGNED_INT_SAMPLER_2D:
// case GL_UNSIGNED_INT_SAMPLER_3D:
// case GL_UNSIGNED_INT_SAMPLER_CUBE:
// case GL_UNSIGNED_INT_SAMPLER_1D_ARRAY:
// case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY:
// case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE:
// case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY:
// case GL_UNSIGNED_INT_SAMPLER_BUFFER:
// case GL_UNSIGNED_INT_SAMPLER_2D_RECT:
// case GL_IMAGE_1D:
// case GL_IMAGE_2D:
// case GL_IMAGE_3D:
// case GL_IMAGE_2D_RECT:
// case GL_IMAGE_CUBE:
// case GL_IMAGE_BUFFER:
// case GL_IMAGE_1D_ARRAY:
// case GL_IMAGE_2D_ARRAY:
// case GL_IMAGE_2D_MULTISAMPLE:
// case GL_IMAGE_2D_MULTISAMPLE_ARRAY:
// case GL_INT_IMAGE_1D:
// case GL_INT_IMAGE_2D:
// case GL_INT_IMAGE_3D:
// case GL_INT_IMAGE_2D_RECT:
// case GL_INT_IMAGE_CUBE:
// case GL_INT_IMAGE_BUFFER:
// case GL_INT_IMAGE_1D_ARRAY:
// case GL_INT_IMAGE_2D_ARRAY:
// case GL_INT_IMAGE_2D_MULTISAMPLE:
// case GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY:
// case GL_UNSIGNED_INT_IMAGE_1D:
// case GL_UNSIGNED_INT_IMAGE_2D:
// case GL_UNSIGNED_INT_IMAGE_3D:
// case GL_UNSIGNED_INT_IMAGE_2D_RECT:
// case GL_UNSIGNED_INT_IMAGE_CUBE:
// case GL_UNSIGNED_INT_IMAGE_BUFFER:
// case GL_UNSIGNED_INT_IMAGE_1D_ARRAY:
// case GL_UNSIGNED_INT_IMAGE_2D_ARRAY:
// case GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE:
// case GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY:
// case GL_UNSIGNED_INT_ATOMIC_COUNTER:
// setInt(program, uniform, value);
// break;
}
}
}
void UniformParser::setFloat(
QOpenGLShaderProgram & program
, const QString & uniform
, QString value)
{
bool ok;
float v = value.toFloat(&ok);
if (ok)
program.setUniformValue(uniform.toStdString().c_str(), v);
else
parsingFailed(uniform, value);
}
void UniformParser::setInt(
QOpenGLShaderProgram & program
, const QString & uniform
, QString value)
{
bool ok;
int v = value.toInt(&ok);
if (!ok)
v = static_cast<int>(value.toFloat(&ok));
if (ok)
program.setUniformValue(uniform.toStdString().c_str(), v);
else
parsingFailed(uniform, value);
}
void UniformParser::setUInt(
QOpenGLShaderProgram & program
, const QString & uniform
, QString value)
{
bool ok;
int v = value.toUInt(&ok);
if (!ok)
v = static_cast<unsigned int>(value.toFloat(&ok));
if (ok)
program.setUniformValue(uniform.toStdString().c_str(), v);
else
parsingFailed(uniform, value);
}
void UniformParser::setVec2(
QOpenGLShaderProgram & program
, const QString & uniform
, QString value)
{
if (!value.startsWith("dvec2") && !value.startsWith("vec2"))
{
typeMismatch(uniform);
return;
}
value.remove("dvec2(");
value.remove("vec2(");
value.remove(")");
const QStringList values = value.split(",");
if (values.size() == 2)
{
bool ok[2];
const QVector2D vec2(
values[0].toFloat(&ok[0])
, values[1].toFloat(&ok[1]));
if (ok[0] && ok[1])
{
program.setUniformValue(uniform.toStdString().c_str(), vec2);
return;
}
}
parsingFailed(uniform, value);
}
void UniformParser::setVec3(
QOpenGLShaderProgram & program
, const QString & uniform
, QString value)
{
if (!value.startsWith("dvec3") && !value.startsWith("vec3"))
{
typeMismatch(uniform);
return;
}
value.remove("dvec3(");
value.remove("vec3(");
value.remove(")");
const QStringList values = value.split(",");
if (values.size() == 3)
{
bool ok[3];
const QVector3D vec3(
values[0].toFloat(&ok[0])
, values[1].toFloat(&ok[1])
, values[2].toFloat(&ok[2]));
if (ok[0] && ok[1] && ok[2])
{
program.setUniformValue(uniform.toStdString().c_str(), vec3);
return;
}
}
parsingFailed(uniform, value);
}
void UniformParser::setVec4(
QOpenGLShaderProgram & program
, const QString & uniform
, QString value)
{
if (!value.startsWith("dvec4") && !value.startsWith("vec4"))
{
typeMismatch(uniform);
return;
}
value.remove("dvec4(");
value.remove("vec4(");
value.remove(")");
const QStringList values = value.split(",");
if (values.size() == 4)
{
bool ok[4];
const QVector4D vec4(
values[0].toFloat(&ok[0])
, values[1].toFloat(&ok[1])
, values[2].toFloat(&ok[2])
, values[3].toFloat(&ok[3]));
if (ok[0] && ok[1] && ok[2] && ok[3])
{
program.setUniformValue(uniform.toStdString().c_str(), vec4);
return;
}
}
parsingFailed(uniform, value);
}
void UniformParser::typeMismatch(const QString & uniform)
{
qDebug() << "Uniform value-type missmatch for" << uniform << ".";
}
void UniformParser::typeUnsupported(const QString & uniform)
{
qDebug() << "Uniform value-type" << uniform << " is not supported.";
}
void UniformParser::parsingFailed(const QString & uniform, const QString & value)
{
qDebug() << "Parsing uniform value" << value << "for" << uniform << "failed.";
}
} // namespace glraw
<|endoftext|> |
<commit_before>// MFEM Example 1 - Parallel Version
//
// Compile with: make ex1p
//
// Sample runs: mpirun -np 4 ex1p -m ../data/square-disc.mesh
// mpirun -np 4 ex1p -m ../data/star.mesh
// mpirun -np 4 ex1p -m ../data/star-mixed.mesh
// mpirun -np 4 ex1p -m ../data/escher.mesh
// mpirun -np 4 ex1p -m ../data/fichera.mesh
// mpirun -np 4 ex1p -m ../data/fichera-mixed.mesh
// mpirun -np 4 ex1p -m ../data/toroid-wedge.mesh
// mpirun -np 4 ex1p -m ../data/octahedron.mesh -o 1
// mpirun -np 4 ex1p -m ../data/periodic-annulus-sector.msh
// mpirun -np 4 ex1p -m ../data/periodic-torus-sector.msh
// mpirun -np 4 ex1p -m ../data/square-disc-p2.vtk -o 2
// mpirun -np 4 ex1p -m ../data/square-disc-p3.mesh -o 3
// mpirun -np 4 ex1p -m ../data/square-disc-nurbs.mesh -o -1
// mpirun -np 4 ex1p -m ../data/star-mixed-p2.mesh -o 2
// mpirun -np 4 ex1p -m ../data/disc-nurbs.mesh -o -1
// mpirun -np 4 ex1p -m ../data/pipe-nurbs.mesh -o -1
// mpirun -np 4 ex1p -m ../data/ball-nurbs.mesh -o 2
// mpirun -np 4 ex1p -m ../data/fichera-mixed-p2.mesh -o 2
// mpirun -np 4 ex1p -m ../data/star-surf.mesh
// mpirun -np 4 ex1p -m ../data/square-disc-surf.mesh
// mpirun -np 4 ex1p -m ../data/inline-segment.mesh
// mpirun -np 4 ex1p -m ../data/amr-quad.mesh
// mpirun -np 4 ex1p -m ../data/amr-hex.mesh
// mpirun -np 4 ex1p -m ../data/mobius-strip.mesh
// mpirun -np 4 ex1p -m ../data/mobius-strip.mesh -o -1 -sc
//
// Device sample runs:
// mpirun -np 4 ex1p -pa -d cuda
// mpirun -np 4 ex1p -fa -d cuda
// mpirun -np 4 ex1p -pa -d occa-cuda
// mpirun -np 4 ex1p -pa -d raja-omp
// mpirun -np 4 ex1p -pa -d ceed-cpu
// mpirun -np 4 ex1p -pa -d ceed-cpu -o 4 -a
// TODO: REVERT mpirun -np 4 ex1p -pa -d ceed-cpu -m ../data/square-mixed.mesh
// mpirun -np 4 ex1p -pa -d ceed-cpu -m ../data/fichera-mixed.mesh
// * mpirun -np 4 ex1p -pa -d ceed-cuda
// * mpirun -np 4 ex1p -pa -d ceed-hip
// mpirun -np 4 ex1p -pa -d ceed-cuda:/gpu/cuda/shared
// TODO: REVERT mpirun -np 4 ex1p -pa -d ceed-cuda:/gpu/cuda/shared -m ../data/square-mixed.mesh
// mpirun -np 4 ex1p -pa -d ceed-cuda:/gpu/cuda/shared -m ../data/fichera-mixed.mesh
// mpirun -np 4 ex1p -m ../data/beam-tet.mesh -pa -d ceed-cpu
//
// Description: This example code demonstrates the use of MFEM to define a
// simple finite element discretization of the Laplace problem
// -Delta u = 1 with homogeneous Dirichlet boundary conditions.
// Specifically, we discretize using a FE space of the specified
// order, or if order < 1 using an isoparametric/isogeometric
// space (i.e. quadratic for quadratic curvilinear mesh, NURBS for
// NURBS mesh, etc.)
//
// The example highlights the use of mesh refinement, finite
// element grid functions, as well as linear and bilinear forms
// corresponding to the left-hand side and right-hand side of the
// discrete linear system. We also cover the explicit elimination
// of essential boundary conditions, static condensation, and the
// optional connection to the GLVis tool for visualization.
#include "mfem.hpp"
#include <fstream>
#include <iostream>
using namespace std;
using namespace mfem;
int main(int argc, char *argv[])
{
// 1. Initialize MPI and HYPRE.
Mpi::Init();
int num_procs = Mpi::WorldSize();
int myid = Mpi::WorldRank();
Hypre::Init();
// 2. Parse command-line options.
const char *mesh_file = "../data/star.mesh";
int order = 1;
bool static_cond = false;
bool pa = false;
bool fa = false;
const char *device_config = "cpu";
bool visualization = true;
bool algebraic_ceed = false;
OptionsParser args(argc, argv);
args.AddOption(&mesh_file, "-m", "--mesh",
"Mesh file to use.");
args.AddOption(&order, "-o", "--order",
"Finite element order (polynomial degree) or -1 for"
" isoparametric space.");
args.AddOption(&static_cond, "-sc", "--static-condensation", "-no-sc",
"--no-static-condensation", "Enable static condensation.");
args.AddOption(&pa, "-pa", "--partial-assembly", "-no-pa",
"--no-partial-assembly", "Enable Partial Assembly.");
args.AddOption(&fa, "-fa", "--full-assembly", "-no-fa",
"--no-full-assembly", "Enable Full Assembly.");
args.AddOption(&device_config, "-d", "--device",
"Device configuration string, see Device::Configure().");
#ifdef MFEM_USE_CEED
args.AddOption(&algebraic_ceed, "-a", "--algebraic",
"-no-a", "--no-algebraic",
"Use algebraic Ceed solver");
#endif
args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
"--no-visualization",
"Enable or disable GLVis visualization.");
args.Parse();
if (!args.Good())
{
if (myid == 0)
{
args.PrintUsage(cout);
}
return 1;
}
if (myid == 0)
{
args.PrintOptions(cout);
}
// 3. Enable hardware devices such as GPUs, and programming models such as
// CUDA, OCCA, RAJA and OpenMP based on command line options.
Device device(device_config);
if (myid == 0) { device.Print(); }
// 4. Read the (serial) mesh from the given mesh file on all processors. We
// can handle triangular, quadrilateral, tetrahedral, hexahedral, surface
// and volume meshes with the same code.
Mesh mesh(mesh_file, 1, 1);
int dim = mesh.Dimension();
// 5. Refine the serial mesh on all processors to increase the resolution. In
// this example we do 'ref_levels' of uniform refinement. We choose
// 'ref_levels' to be the largest number that gives a final mesh with no
// more than 10,000 elements.
{
int ref_levels =
(int)floor(log(10000./mesh.GetNE())/log(2.)/dim);
for (int l = 0; l < ref_levels; l++)
{
mesh.UniformRefinement();
}
}
// 6. Define a parallel mesh by a partitioning of the serial mesh. Refine
// this mesh further in parallel to increase the resolution. Once the
// parallel mesh is defined, the serial mesh can be deleted.
ParMesh pmesh(MPI_COMM_WORLD, mesh);
mesh.Clear();
{
int par_ref_levels = 2;
for (int l = 0; l < par_ref_levels; l++)
{
pmesh.UniformRefinement();
}
}
// 7. Define a parallel finite element space on the parallel mesh. Here we
// use continuous Lagrange finite elements of the specified order. If
// order < 1, we instead use an isoparametric/isogeometric space.
FiniteElementCollection *fec;
bool delete_fec;
if (order > 0)
{
fec = new H1_FECollection(order, dim);
delete_fec = true;
}
else if (pmesh.GetNodes())
{
fec = pmesh.GetNodes()->OwnFEC();
delete_fec = false;
if (myid == 0)
{
cout << "Using isoparametric FEs: " << fec->Name() << endl;
}
}
else
{
fec = new H1_FECollection(order = 1, dim);
delete_fec = true;
}
ParFiniteElementSpace fespace(&pmesh, fec);
HYPRE_BigInt size = fespace.GlobalTrueVSize();
if (myid == 0)
{
cout << "Number of finite element unknowns: " << size << endl;
}
// 8. Determine the list of true (i.e. parallel conforming) essential
// boundary dofs. In this example, the boundary conditions are defined
// by marking all the boundary attributes from the mesh as essential
// (Dirichlet) and converting them to a list of true dofs.
Array<int> ess_tdof_list;
if (pmesh.bdr_attributes.Size())
{
Array<int> ess_bdr(pmesh.bdr_attributes.Max());
ess_bdr = 1;
fespace.GetEssentialTrueDofs(ess_bdr, ess_tdof_list);
}
// 9. Set up the parallel linear form b(.) which corresponds to the
// right-hand side of the FEM linear system, which in this case is
// (1,phi_i) where phi_i are the basis functions in fespace.
ParLinearForm b(&fespace);
ConstantCoefficient one(1.0);
b.AddDomainIntegrator(new DomainLFIntegrator(one));
b.Assemble();
// 10. Define the solution vector x as a parallel finite element grid
// function corresponding to fespace. Initialize x with initial guess of
// zero, which satisfies the boundary conditions.
ParGridFunction x(&fespace);
x = 0.0;
// 11. Set up the parallel bilinear form a(.,.) on the finite element space
// corresponding to the Laplacian operator -Delta, by adding the
// Diffusion domain integrator.
ParBilinearForm a(&fespace);
if (pa) { a.SetAssemblyLevel(AssemblyLevel::PARTIAL); }
if (fa) { a.SetAssemblyLevel(AssemblyLevel::FULL); }
a.AddDomainIntegrator(new DiffusionIntegrator(one));
// 12. Assemble the parallel bilinear form and the corresponding linear
// system, applying any necessary transformations such as: parallel
// assembly, eliminating boundary conditions, applying conforming
// constraints for non-conforming AMR, static condensation, etc.
if (static_cond) { a.EnableStaticCondensation(); }
a.Assemble();
OperatorPtr A;
Vector B, X;
a.FormLinearSystem(ess_tdof_list, x, b, A, X, B);
// 13. Solve the linear system A X = B.
// * With full assembly, use the BoomerAMG preconditioner from hypre.
// * With partial assembly, use Jacobi smoothing, for now.
Solver *prec = NULL;
if (pa)
{
if (UsesTensorBasis(fespace))
{
if (algebraic_ceed)
{
prec = new ceed::AlgebraicSolver(a, ess_tdof_list);
}
else
{
prec = new OperatorJacobiSmoother(a, ess_tdof_list);
}
}
}
else
{
prec = new HypreBoomerAMG;
}
CGSolver cg(MPI_COMM_WORLD);
cg.SetRelTol(1e-12);
cg.SetMaxIter(2000);
cg.SetPrintLevel(1);
if (prec) { cg.SetPreconditioner(*prec); }
cg.SetOperator(*A);
cg.Mult(B, X);
delete prec;
// 14. Recover the parallel grid function corresponding to X. This is the
// local finite element solution on each processor.
a.RecoverFEMSolution(X, b, x);
// 15. Save the refined mesh and the solution in parallel. This output can
// be viewed later using GLVis: "glvis -np <np> -m mesh -g sol".
{
ostringstream mesh_name, sol_name;
mesh_name << "mesh." << setfill('0') << setw(6) << myid;
sol_name << "sol." << setfill('0') << setw(6) << myid;
ofstream mesh_ofs(mesh_name.str().c_str());
mesh_ofs.precision(8);
pmesh.Print(mesh_ofs);
ofstream sol_ofs(sol_name.str().c_str());
sol_ofs.precision(8);
x.Save(sol_ofs);
}
// 16. Send the solution by socket to a GLVis server.
if (visualization)
{
char vishost[] = "localhost";
int visport = 19916;
socketstream sol_sock(vishost, visport);
sol_sock << "parallel " << num_procs << " " << myid << "\n";
sol_sock.precision(8);
sol_sock << "solution\n" << pmesh << x << flush;
}
// 17. Free the used memory.
if (delete_fec)
{
delete fec;
}
return 0;
}
<commit_msg>Revert "Temporarily disable 2D parallel mixed mesg runs until #2953 is fixed"<commit_after>// MFEM Example 1 - Parallel Version
//
// Compile with: make ex1p
//
// Sample runs: mpirun -np 4 ex1p -m ../data/square-disc.mesh
// mpirun -np 4 ex1p -m ../data/star.mesh
// mpirun -np 4 ex1p -m ../data/star-mixed.mesh
// mpirun -np 4 ex1p -m ../data/escher.mesh
// mpirun -np 4 ex1p -m ../data/fichera.mesh
// mpirun -np 4 ex1p -m ../data/fichera-mixed.mesh
// mpirun -np 4 ex1p -m ../data/toroid-wedge.mesh
// mpirun -np 4 ex1p -m ../data/octahedron.mesh -o 1
// mpirun -np 4 ex1p -m ../data/periodic-annulus-sector.msh
// mpirun -np 4 ex1p -m ../data/periodic-torus-sector.msh
// mpirun -np 4 ex1p -m ../data/square-disc-p2.vtk -o 2
// mpirun -np 4 ex1p -m ../data/square-disc-p3.mesh -o 3
// mpirun -np 4 ex1p -m ../data/square-disc-nurbs.mesh -o -1
// mpirun -np 4 ex1p -m ../data/star-mixed-p2.mesh -o 2
// mpirun -np 4 ex1p -m ../data/disc-nurbs.mesh -o -1
// mpirun -np 4 ex1p -m ../data/pipe-nurbs.mesh -o -1
// mpirun -np 4 ex1p -m ../data/ball-nurbs.mesh -o 2
// mpirun -np 4 ex1p -m ../data/fichera-mixed-p2.mesh -o 2
// mpirun -np 4 ex1p -m ../data/star-surf.mesh
// mpirun -np 4 ex1p -m ../data/square-disc-surf.mesh
// mpirun -np 4 ex1p -m ../data/inline-segment.mesh
// mpirun -np 4 ex1p -m ../data/amr-quad.mesh
// mpirun -np 4 ex1p -m ../data/amr-hex.mesh
// mpirun -np 4 ex1p -m ../data/mobius-strip.mesh
// mpirun -np 4 ex1p -m ../data/mobius-strip.mesh -o -1 -sc
//
// Device sample runs:
// mpirun -np 4 ex1p -pa -d cuda
// mpirun -np 4 ex1p -fa -d cuda
// mpirun -np 4 ex1p -pa -d occa-cuda
// mpirun -np 4 ex1p -pa -d raja-omp
// mpirun -np 4 ex1p -pa -d ceed-cpu
// mpirun -np 4 ex1p -pa -d ceed-cpu -o 4 -a
// mpirun -np 4 ex1p -pa -d ceed-cpu -m ../data/square-mixed.mesh
// mpirun -np 4 ex1p -pa -d ceed-cpu -m ../data/fichera-mixed.mesh
// * mpirun -np 4 ex1p -pa -d ceed-cuda
// * mpirun -np 4 ex1p -pa -d ceed-hip
// mpirun -np 4 ex1p -pa -d ceed-cuda:/gpu/cuda/shared
// mpirun -np 4 ex1p -pa -d ceed-cuda:/gpu/cuda/shared -m ../data/square-mixed.mesh
// mpirun -np 4 ex1p -pa -d ceed-cuda:/gpu/cuda/shared -m ../data/fichera-mixed.mesh
// mpirun -np 4 ex1p -m ../data/beam-tet.mesh -pa -d ceed-cpu
//
// Description: This example code demonstrates the use of MFEM to define a
// simple finite element discretization of the Laplace problem
// -Delta u = 1 with homogeneous Dirichlet boundary conditions.
// Specifically, we discretize using a FE space of the specified
// order, or if order < 1 using an isoparametric/isogeometric
// space (i.e. quadratic for quadratic curvilinear mesh, NURBS for
// NURBS mesh, etc.)
//
// The example highlights the use of mesh refinement, finite
// element grid functions, as well as linear and bilinear forms
// corresponding to the left-hand side and right-hand side of the
// discrete linear system. We also cover the explicit elimination
// of essential boundary conditions, static condensation, and the
// optional connection to the GLVis tool for visualization.
#include "mfem.hpp"
#include <fstream>
#include <iostream>
using namespace std;
using namespace mfem;
int main(int argc, char *argv[])
{
// 1. Initialize MPI and HYPRE.
Mpi::Init();
int num_procs = Mpi::WorldSize();
int myid = Mpi::WorldRank();
Hypre::Init();
// 2. Parse command-line options.
const char *mesh_file = "../data/star.mesh";
int order = 1;
bool static_cond = false;
bool pa = false;
bool fa = false;
const char *device_config = "cpu";
bool visualization = true;
bool algebraic_ceed = false;
OptionsParser args(argc, argv);
args.AddOption(&mesh_file, "-m", "--mesh",
"Mesh file to use.");
args.AddOption(&order, "-o", "--order",
"Finite element order (polynomial degree) or -1 for"
" isoparametric space.");
args.AddOption(&static_cond, "-sc", "--static-condensation", "-no-sc",
"--no-static-condensation", "Enable static condensation.");
args.AddOption(&pa, "-pa", "--partial-assembly", "-no-pa",
"--no-partial-assembly", "Enable Partial Assembly.");
args.AddOption(&fa, "-fa", "--full-assembly", "-no-fa",
"--no-full-assembly", "Enable Full Assembly.");
args.AddOption(&device_config, "-d", "--device",
"Device configuration string, see Device::Configure().");
#ifdef MFEM_USE_CEED
args.AddOption(&algebraic_ceed, "-a", "--algebraic",
"-no-a", "--no-algebraic",
"Use algebraic Ceed solver");
#endif
args.AddOption(&visualization, "-vis", "--visualization", "-no-vis",
"--no-visualization",
"Enable or disable GLVis visualization.");
args.Parse();
if (!args.Good())
{
if (myid == 0)
{
args.PrintUsage(cout);
}
return 1;
}
if (myid == 0)
{
args.PrintOptions(cout);
}
// 3. Enable hardware devices such as GPUs, and programming models such as
// CUDA, OCCA, RAJA and OpenMP based on command line options.
Device device(device_config);
if (myid == 0) { device.Print(); }
// 4. Read the (serial) mesh from the given mesh file on all processors. We
// can handle triangular, quadrilateral, tetrahedral, hexahedral, surface
// and volume meshes with the same code.
Mesh mesh(mesh_file, 1, 1);
int dim = mesh.Dimension();
// 5. Refine the serial mesh on all processors to increase the resolution. In
// this example we do 'ref_levels' of uniform refinement. We choose
// 'ref_levels' to be the largest number that gives a final mesh with no
// more than 10,000 elements.
{
int ref_levels =
(int)floor(log(10000./mesh.GetNE())/log(2.)/dim);
for (int l = 0; l < ref_levels; l++)
{
mesh.UniformRefinement();
}
}
// 6. Define a parallel mesh by a partitioning of the serial mesh. Refine
// this mesh further in parallel to increase the resolution. Once the
// parallel mesh is defined, the serial mesh can be deleted.
ParMesh pmesh(MPI_COMM_WORLD, mesh);
mesh.Clear();
{
int par_ref_levels = 2;
for (int l = 0; l < par_ref_levels; l++)
{
pmesh.UniformRefinement();
}
}
// 7. Define a parallel finite element space on the parallel mesh. Here we
// use continuous Lagrange finite elements of the specified order. If
// order < 1, we instead use an isoparametric/isogeometric space.
FiniteElementCollection *fec;
bool delete_fec;
if (order > 0)
{
fec = new H1_FECollection(order, dim);
delete_fec = true;
}
else if (pmesh.GetNodes())
{
fec = pmesh.GetNodes()->OwnFEC();
delete_fec = false;
if (myid == 0)
{
cout << "Using isoparametric FEs: " << fec->Name() << endl;
}
}
else
{
fec = new H1_FECollection(order = 1, dim);
delete_fec = true;
}
ParFiniteElementSpace fespace(&pmesh, fec);
HYPRE_BigInt size = fespace.GlobalTrueVSize();
if (myid == 0)
{
cout << "Number of finite element unknowns: " << size << endl;
}
// 8. Determine the list of true (i.e. parallel conforming) essential
// boundary dofs. In this example, the boundary conditions are defined
// by marking all the boundary attributes from the mesh as essential
// (Dirichlet) and converting them to a list of true dofs.
Array<int> ess_tdof_list;
if (pmesh.bdr_attributes.Size())
{
Array<int> ess_bdr(pmesh.bdr_attributes.Max());
ess_bdr = 1;
fespace.GetEssentialTrueDofs(ess_bdr, ess_tdof_list);
}
// 9. Set up the parallel linear form b(.) which corresponds to the
// right-hand side of the FEM linear system, which in this case is
// (1,phi_i) where phi_i are the basis functions in fespace.
ParLinearForm b(&fespace);
ConstantCoefficient one(1.0);
b.AddDomainIntegrator(new DomainLFIntegrator(one));
b.Assemble();
// 10. Define the solution vector x as a parallel finite element grid
// function corresponding to fespace. Initialize x with initial guess of
// zero, which satisfies the boundary conditions.
ParGridFunction x(&fespace);
x = 0.0;
// 11. Set up the parallel bilinear form a(.,.) on the finite element space
// corresponding to the Laplacian operator -Delta, by adding the
// Diffusion domain integrator.
ParBilinearForm a(&fespace);
if (pa) { a.SetAssemblyLevel(AssemblyLevel::PARTIAL); }
if (fa) { a.SetAssemblyLevel(AssemblyLevel::FULL); }
a.AddDomainIntegrator(new DiffusionIntegrator(one));
// 12. Assemble the parallel bilinear form and the corresponding linear
// system, applying any necessary transformations such as: parallel
// assembly, eliminating boundary conditions, applying conforming
// constraints for non-conforming AMR, static condensation, etc.
if (static_cond) { a.EnableStaticCondensation(); }
a.Assemble();
OperatorPtr A;
Vector B, X;
a.FormLinearSystem(ess_tdof_list, x, b, A, X, B);
// 13. Solve the linear system A X = B.
// * With full assembly, use the BoomerAMG preconditioner from hypre.
// * With partial assembly, use Jacobi smoothing, for now.
Solver *prec = NULL;
if (pa)
{
if (UsesTensorBasis(fespace))
{
if (algebraic_ceed)
{
prec = new ceed::AlgebraicSolver(a, ess_tdof_list);
}
else
{
prec = new OperatorJacobiSmoother(a, ess_tdof_list);
}
}
}
else
{
prec = new HypreBoomerAMG;
}
CGSolver cg(MPI_COMM_WORLD);
cg.SetRelTol(1e-12);
cg.SetMaxIter(2000);
cg.SetPrintLevel(1);
if (prec) { cg.SetPreconditioner(*prec); }
cg.SetOperator(*A);
cg.Mult(B, X);
delete prec;
// 14. Recover the parallel grid function corresponding to X. This is the
// local finite element solution on each processor.
a.RecoverFEMSolution(X, b, x);
// 15. Save the refined mesh and the solution in parallel. This output can
// be viewed later using GLVis: "glvis -np <np> -m mesh -g sol".
{
ostringstream mesh_name, sol_name;
mesh_name << "mesh." << setfill('0') << setw(6) << myid;
sol_name << "sol." << setfill('0') << setw(6) << myid;
ofstream mesh_ofs(mesh_name.str().c_str());
mesh_ofs.precision(8);
pmesh.Print(mesh_ofs);
ofstream sol_ofs(sol_name.str().c_str());
sol_ofs.precision(8);
x.Save(sol_ofs);
}
// 16. Send the solution by socket to a GLVis server.
if (visualization)
{
char vishost[] = "localhost";
int visport = 19916;
socketstream sol_sock(vishost, visport);
sol_sock << "parallel " << num_procs << " " << myid << "\n";
sol_sock.precision(8);
sol_sock << "solution\n" << pmesh << x << flush;
}
// 17. Free the used memory.
if (delete_fec)
{
delete fec;
}
return 0;
}
<|endoftext|> |
<commit_before>#include "LinearStrainHardening.h"
#include "MooseException.h"
#include "SymmIsotropicElasticityTensor.h"
template<>
InputParameters validParams<LinearStrainHardening>()
{
InputParameters params = validParams<SolidModel>();
/*
Iteration control parameters
*/
params.addParam<Real>("tolerance", 1e-5, "Convergence tolerance for sub-newtion iteration");
/*
Linear strain hardening parameters
*/
params.addRequiredParam<Real>("yield_stress", "The point at which plastic strain begins accumulating");
params.addRequiredParam<Real>("hardening_constant", "Hardening slope");
params.addParam<Real>("tolerance", 1e-5, "Sub-BiLin iteration tolerance");
params.addParam<unsigned int>("max_its", 10, "Maximum number of Sub-newton iterations");
return params;
}
LinearStrainHardening::LinearStrainHardening( const std::string & name,
InputParameters parameters )
:SolidModel( name, parameters ),
_tolerance(parameters.get<Real>("tolerance")),
_max_its(parameters.get<unsigned int>("max_its")),
_yield_stress(parameters.get<Real>("yield_stress")),
_hardening_constant(parameters.get<Real>("hardening_constant")),
_plastic_strain(declareProperty<SymmTensor>("plastic_strain")),
_plastic_strain_old(declarePropertyOld<SymmTensor>("plastic_strain")),
_hardening_variable(declareProperty<Real>("hardening_variable")),
_hardening_variable_old(declarePropertyOld<Real>("hardening_variable"))
{
}
void
LinearStrainHardening::initQpStatefulProperties()
{
_hardening_variable[_qp] = _hardening_variable_old[_qp] = 0;
SolidModel::initQpStatefulProperties();
}
void
LinearStrainHardening::computeStress()
{
// compute trial stress
SymmTensor stress_new = *elasticityTensor() * _strain_increment;
stress_new += _stress_old;
// compute deviatoric trial stress
SymmTensor dev_trial_stress(stress_new);
dev_trial_stress.addDiag( -stress_new.trace()/3.0 );
// effective trial stress
Real dts_squared = dev_trial_stress.doubleContraction(dev_trial_stress);
Real effective_trial_stress = std::sqrt(1.5 * dts_squared);
// determine if yield condition is satisfied
Real yield_condition = effective_trial_stress - _hardening_variable_old[_qp] - _yield_stress;
_plastic_strain[_qp] = _plastic_strain_old[_qp];
_hardening_variable[_qp] = _hardening_variable_old[_qp];
if (yield_condition > 0.) //then use newton iteration to determine effective plastic strain increment
{
unsigned int it = 0;
Real scalar_plastic_strain_increment = 0.;
Real norm_residual = 10.;
while(it < _max_its && norm_residual > _tolerance)
{
Real plastic_residual = effective_trial_stress - (3. * _shear_modulus * scalar_plastic_strain_increment) - _hardening_variable[_qp] - _yield_stress;
norm_residual = std::abs(plastic_residual);
scalar_plastic_strain_increment += ((plastic_residual) / (3. * _shear_modulus + _hardening_constant));
_hardening_variable[_qp] = _hardening_variable_old[_qp] + (_hardening_constant * scalar_plastic_strain_increment);
++it;
}
if(it == _max_its)
{
std::stringstream errorMsg;
errorMsg << "Max sub-newton iteration hit during plasticity increment solve!";
if (libMesh::n_processors()>1)
{
mooseError(errorMsg.str());
}
else
{
std::cout<<std::endl<<errorMsg.str()<<std::endl<<std::endl;
throw MooseException();
}
}
// compute plastic and elastic strain increments (avoid potential divide by zero - how should this be done)?
if (effective_trial_stress < 0.01)
{
effective_trial_stress = 0.01;
}
SymmTensor plastic_strain_increment(dev_trial_stress);
plastic_strain_increment *= (1.5*scalar_plastic_strain_increment/effective_trial_stress);
_strain_increment -= plastic_strain_increment;
// update stress and plastic strain
// compute stress increment
_stress[_qp] = *elasticityTensor() * _strain_increment;
_stress[_qp] += _stress_old;
_plastic_strain[_qp] += plastic_strain_increment;
} // end of if statement
else
{
// update stress
_stress[_qp] = *elasticityTensor() * _strain_increment;
_stress[_qp] += _stress_old;
} // end of else
} // end of computeStress
<commit_msg>Minor cleanup<commit_after>#include "LinearStrainHardening.h"
#include "MooseException.h"
#include "SymmIsotropicElasticityTensor.h"
template<>
InputParameters validParams<LinearStrainHardening>()
{
InputParameters params = validParams<SolidModel>();
/*
Iteration control parameters
*/
params.addParam<Real>("tolerance", 1e-5, "Convergence tolerance for sub-newtion iteration");
/*
Linear strain hardening parameters
*/
params.addRequiredParam<Real>("yield_stress", "The point at which plastic strain begins accumulating");
params.addRequiredParam<Real>("hardening_constant", "Hardening slope");
params.addParam<Real>("tolerance", 1e-5, "Sub-BiLin iteration tolerance");
params.addParam<unsigned int>("max_its", 10, "Maximum number of Sub-newton iterations");
return params;
}
LinearStrainHardening::LinearStrainHardening( const std::string & name,
InputParameters parameters )
:SolidModel( name, parameters ),
_tolerance(parameters.get<Real>("tolerance")),
_max_its(parameters.get<unsigned int>("max_its")),
_yield_stress(parameters.get<Real>("yield_stress")),
_hardening_constant(parameters.get<Real>("hardening_constant")),
_plastic_strain(declareProperty<SymmTensor>("plastic_strain")),
_plastic_strain_old(declarePropertyOld<SymmTensor>("plastic_strain")),
_hardening_variable(declareProperty<Real>("hardening_variable")),
_hardening_variable_old(declarePropertyOld<Real>("hardening_variable"))
{
}
void
LinearStrainHardening::initQpStatefulProperties()
{
_hardening_variable[_qp] = _hardening_variable_old[_qp] = 0;
SolidModel::initQpStatefulProperties();
}
void
LinearStrainHardening::computeStress()
{
// compute trial stress
SymmTensor stress_new = *elasticityTensor() * _strain_increment;
stress_new += _stress_old;
// compute deviatoric trial stress
SymmTensor dev_trial_stress(stress_new);
dev_trial_stress.addDiag( -stress_new.trace()/3.0 );
// effective trial stress
Real dts_squared = dev_trial_stress.doubleContraction(dev_trial_stress);
Real effective_trial_stress = std::sqrt(1.5 * dts_squared);
// determine if yield condition is satisfied
Real yield_condition = effective_trial_stress - _hardening_variable_old[_qp] - _yield_stress;
_plastic_strain[_qp] = _plastic_strain_old[_qp];
_hardening_variable[_qp] = _hardening_variable_old[_qp];
if (yield_condition > 0.) //then use newton iteration to determine effective plastic strain increment
{
unsigned int it = 0;
Real scalar_plastic_strain_increment = 0.;
Real norm_residual = 10.;
while(it < _max_its && norm_residual > _tolerance)
{
Real plastic_residual = effective_trial_stress - (3. * _shear_modulus * scalar_plastic_strain_increment) - _hardening_variable[_qp] - _yield_stress;
norm_residual = std::abs(plastic_residual);
scalar_plastic_strain_increment += ((plastic_residual) / (3. * _shear_modulus + _hardening_constant));
_hardening_variable[_qp] = _hardening_variable_old[_qp] + (_hardening_constant * scalar_plastic_strain_increment);
++it;
}
if(it == _max_its)
{
std::stringstream errorMsg;
errorMsg << "Max sub-newton iteration hit during plasticity increment solve!";
if (libMesh::n_processors()>1)
{
mooseError(errorMsg.str());
}
else
{
std::cout<<std::endl<<errorMsg.str()<<std::endl<<std::endl;
throw MooseException();
}
}
// compute plastic and elastic strain increments (avoid potential divide by zero - how should this be done)?
if (effective_trial_stress < 0.01)
{
effective_trial_stress = 0.01;
}
SymmTensor plastic_strain_increment(dev_trial_stress);
plastic_strain_increment *= (1.5*scalar_plastic_strain_increment/effective_trial_stress);
_strain_increment -= plastic_strain_increment;
// update stress and plastic strain
// compute stress increment
_stress[_qp] = *elasticityTensor() * _strain_increment;
_stress[_qp] += _stress_old;
_plastic_strain[_qp] += plastic_strain_increment;
} // end of if statement
else
{
// update stress
_stress[_qp] = stress_new;
} // end of else
} // end of computeStress
<|endoftext|> |
<commit_before>// Copyright (c) 2015 Yandex LLC. All rights reserved.
// Author: Vasily Chekalkin <[email protected]>
#include "sdch_dictionary_factory.h"
#include <algorithm>
namespace sdch {
namespace {
bool compare_dict_conf(const DictConfig& a, const DictConfig& b) {
ngx_int_t c = ngx_memn2cmp(a.groupname.data, b.groupname.data,
a.groupname.len, b.groupname.len);
if (c != 0)
return c < 0;
return a.priority < b.priority;
}
} // namespace
DictionaryFactory::DictionaryFactory(ngx_pool_t* pool)
: pool_(pool),
dict_storage_(DictStorage::allocator_type(pool)),
conf_storage_(DictConfStorage::allocator_type(pool)) {}
DictConfig* DictionaryFactory::store_config(Dictionary* dict,
ngx_str_t& groupname,
ngx_uint_t prio) {
conf_storage_.emplace_back();
auto* res = &*conf_storage_.rbegin();
res->groupname.len = groupname.len;
res->groupname.data = ngx_pstrdup(pool_, &groupname);
res->priority = prio != ngx_uint_t(-1) ? prio : conf_storage_.size() - 1;
res->dict = dict;
res->best = false;
return res;
}
Dictionary* DictionaryFactory::allocate_dictionary() {
auto* res = pool_alloc<Dictionary>(pool_);
dict_storage_.push_back(res);
return res;
}
DictConfig* DictionaryFactory::choose_best_dictionary(DictConfig* old,
DictConfig* n,
const ngx_str_t& group) {
if (old == nullptr)
return n;
if (n == nullptr)
return old;
int om =
ngx_memn2cmp(
old->groupname.data, group.data, old->groupname.len, group.len) == 0;
int nm = ngx_memn2cmp(
n->groupname.data, group.data, n->groupname.len, group.len) == 0;
if (om && !nm)
return old;
if (nm && !om)
return n;
if (n->priority < old->priority)
return n;
return old;
}
DictConfig* DictionaryFactory::find_dictionary(const u_char* client_id) {
for (auto& c : conf_storage_) {
if (ngx_strncmp(client_id, c.dict->client_id().data(), 8) == 0)
return &c;
}
return nullptr;
}
void DictionaryFactory::merge(const DictionaryFactory* parent) {
// Merge dictionaries from parent.
conf_storage_.insert(conf_storage_.end(),
parent->conf_storage_.begin(),
parent->conf_storage_.end());
// And sort them
std::sort(conf_storage_.begin(), conf_storage_.end(), compare_dict_conf);
if (!conf_storage_.empty()) {
conf_storage_.begin()->best = 1;
}
for (size_t i = 1; i < conf_storage_.size(); ++i) {
if (ngx_memn2cmp(conf_storage_[i - 1].groupname.data,
conf_storage_[i].groupname.data,
conf_storage_[i - 1].groupname.len,
conf_storage_[i].groupname.len)) {
conf_storage_[i].best = 1;
}
}
}
} // namespace sdch
<commit_msg>Dictionaries on inner block should override dictionaries on outer blocks.<commit_after>// Copyright (c) 2015 Yandex LLC. All rights reserved.
// Author: Vasily Chekalkin <[email protected]>
#include "sdch_dictionary_factory.h"
#include <algorithm>
namespace sdch {
namespace {
bool compare_dict_conf(const DictConfig& a, const DictConfig& b) {
ngx_int_t c = ngx_memn2cmp(a.groupname.data, b.groupname.data,
a.groupname.len, b.groupname.len);
if (c != 0)
return c < 0;
return a.priority < b.priority;
}
} // namespace
DictionaryFactory::DictionaryFactory(ngx_pool_t* pool)
: pool_(pool),
dict_storage_(DictStorage::allocator_type(pool)),
conf_storage_(DictConfStorage::allocator_type(pool)) {}
DictConfig* DictionaryFactory::store_config(Dictionary* dict,
ngx_str_t& groupname,
ngx_uint_t prio) {
conf_storage_.emplace_back();
auto* res = &*conf_storage_.rbegin();
res->groupname.len = groupname.len;
res->groupname.data = ngx_pstrdup(pool_, &groupname);
res->priority = prio != ngx_uint_t(-1) ? prio : conf_storage_.size() - 1;
res->dict = dict;
res->best = false;
return res;
}
Dictionary* DictionaryFactory::allocate_dictionary() {
auto* res = pool_alloc<Dictionary>(pool_);
dict_storage_.push_back(res);
return res;
}
DictConfig* DictionaryFactory::choose_best_dictionary(DictConfig* old,
DictConfig* n,
const ngx_str_t& group) {
if (old == nullptr)
return n;
if (n == nullptr)
return old;
int om =
ngx_memn2cmp(
old->groupname.data, group.data, old->groupname.len, group.len) == 0;
int nm = ngx_memn2cmp(
n->groupname.data, group.data, n->groupname.len, group.len) == 0;
if (om && !nm)
return old;
if (nm && !om)
return n;
if (n->priority < old->priority)
return n;
return old;
}
DictConfig* DictionaryFactory::find_dictionary(const u_char* client_id) {
for (auto& c : conf_storage_) {
if (ngx_strncmp(client_id, c.dict->client_id().data(), 8) == 0)
return &c;
}
return nullptr;
}
void DictionaryFactory::merge(const DictionaryFactory* parent) {
// Merge dictionaries from parent.
if (conf_storage_.empty())
conf_storage_.insert(conf_storage_.end(),
parent->conf_storage_.begin(),
parent->conf_storage_.end());
// And sort them
std::sort(conf_storage_.begin(), conf_storage_.end(), compare_dict_conf);
if (!conf_storage_.empty()) {
conf_storage_.begin()->best = 1;
}
for (size_t i = 1; i < conf_storage_.size(); ++i) {
if (ngx_memn2cmp(conf_storage_[i - 1].groupname.data,
conf_storage_[i].groupname.data,
conf_storage_[i - 1].groupname.len,
conf_storage_[i].groupname.len)) {
conf_storage_[i].best = 1;
}
}
}
} // namespace sdch
<|endoftext|> |
<commit_before>/* The MIT License
Copyright (c) 2013 Adrian Tan <[email protected]>
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 "program.h"
void VTOutput::failure(TCLAP::CmdLineInterface& c, TCLAP::ArgException& e)
{
std::clog << " " << e.what() << "\n\n";
usage(c);
exit(1);
}
void VTOutput::usage(TCLAP::CmdLineInterface& c)
{
std::string s = "";
std::list<TCLAP::Arg*> args = c.getArgList();
//prints unlabeled arument list first
for (TCLAP::ArgListIterator it = args.begin(); it != args.end(); it++)
{
if (typeid(**it)==typeid(TCLAP::UnlabeledValueArg<std::string>))
{
TCLAP::UnlabeledValueArg<std::string> *i = (TCLAP::UnlabeledValueArg<std::string> *) (*it);
s = i->getName();
}
}
std::clog << c.getProgramName() << " v" << c.getVersion() << "\n\n";
std::clog << "description : " << c.getMessage() << "\n\n";
std::clog << "usage : vt " << c.getProgramName() << " [options] " << s << "\n\n";
//prints rest of arguments
for (TCLAP::ArgListIterator it = args.begin(); it != args.end(); it++)
{
if (it==args.begin())
{
std::clog << "options : ";
}
else
{
std::clog << " ";
}
if (typeid(**it)==typeid(TCLAP::ValueArg<std::string>) ||
typeid(**it)==typeid(TCLAP::ValueArg<uint32_t>) ||
typeid(**it)==typeid(TCLAP::ValueArg<double>))
{
TCLAP::ValueArg<std::string> *i = (TCLAP::ValueArg<std::string> *) (*it);
std::clog << "-" << i->getFlag()
<< " " << i->getDescription() << "\n";
}
else if (typeid(**it)==typeid(TCLAP::SwitchArg))
{
TCLAP::SwitchArg *i = (TCLAP::SwitchArg *) (*it);
std::clog << "-" << i->getFlag()
<< " " << i->getDescription() << "\n";
}
else if (typeid(**it)==typeid(TCLAP::UnlabeledValueArg<std::string>))
{
//ignored
}
else
{
std::clog << "oops, argument type not handled\n";
}
}
std::cout << "\n";
}
/**
* Parse intervals. Processes the interval list first followed by the interval string. Duplicates are dropped.
*
* @intervals - intervals stored in this vector
* @interval_list - file containing intervals
* @interval_string - comma delimited intervals in a string
*
* todo: merge overlapping sites?
*/
void Program::parse_intervals(std::vector<GenomeInterval>& intervals, std::string interval_list, std::string interval_string)
{
intervals.clear();
std::map<std::string, uint32_t> m;
if (interval_list!="")
{
htsFile *file = hts_open(interval_list.c_str(), "r");
if (file)
{
kstring_t *s = &file->line;
while (hts_getline(file, '\n', s)>=0)
{
std::string ss = std::string(s->s);
if (m.find(ss)==m.end())
{
m[ss] = 1;
GenomeInterval interval(ss);
intervals.push_back(interval);
}
}
hts_close(file);
}
}
std::vector<std::string> v;
if (interval_string!="")
split(v, ",", interval_string);
for (uint32_t i=0; i<v.size(); ++i)
{
if (m.find(v[i])==m.end())
{
m[v[i]] = 1;
GenomeInterval interval(v[i]);
intervals.push_back(interval);
}
}
}
/**
* Print intervals option.
*/
void Program::print_int_op(const char* option_line, std::vector<GenomeInterval>& intervals)
{
if (intervals.size()!=0)
{
std::clog << option_line;
for (uint32_t i=0; i<std::min((uint32_t)intervals.size(),(uint32_t)5); ++i)
{
if (i) std::clog << ",";
std::clog << intervals[i].to_string();
}
if (intervals.size()>5)
{
std::clog << " and " << (intervals.size()-5) << " other intervals\n";
}
}
}
/**
* Parse samples. Processes the sample list. Duplicates are dropped.
*
* @samples - samples stored in this vector
* @sample_map - samples stored in this map
* @sample_list - file containing sample names
*/
void Program::read_sample_list(std::vector<std::string>& samples, std::string sample_list)
{
samples.clear();
std::map<std::string, int32_t> map;
if (sample_list!="")
{
htsFile *file = hts_open(sample_list.c_str(), "r");
if (file)
{
kstring_t *s = &file->line;
while (hts_getline(file, '\n', s)>=0)
{
std::string ss = std::string(s->s);
if (map.find(ss)==map.end())
{
map[ss] = 1;
samples.push_back(ss);
}
}
hts_close(file);
}
}
}<commit_msg>minor changes + formatting<commit_after>/* The MIT License
Copyright (c) 2013 Adrian Tan <[email protected]>
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 "program.h"
void VTOutput::failure(TCLAP::CmdLineInterface& c, TCLAP::ArgException& e)
{
std::clog << " " << e.what() << "\n\n";
usage(c);
exit(1);
}
void VTOutput::usage(TCLAP::CmdLineInterface& c)
{
std::string s = "";
std::list<TCLAP::Arg*> args = c.getArgList();
//prints unlabeled arument list first
for (TCLAP::ArgListIterator it = args.begin(); it != args.end(); it++)
{
if (typeid(**it)==typeid(TCLAP::UnlabeledValueArg<std::string>))
{
TCLAP::UnlabeledValueArg<std::string> *i = (TCLAP::UnlabeledValueArg<std::string> *) (*it);
s = i->getName();
}
}
std::clog << c.getProgramName() << " v" << c.getVersion() << "\n\n";
std::clog << "description : " << c.getMessage() << "\n\n";
std::clog << "usage : vt " << c.getProgramName() << " [options] " << s << "\n\n";
//prints rest of arguments
for (TCLAP::ArgListIterator it = args.begin(); it != args.end(); it++)
{
if (it==args.begin())
{
std::clog << "options : ";
}
else
{
std::clog << " ";
}
if (typeid(**it)==typeid(TCLAP::ValueArg<std::string>) ||
typeid(**it)==typeid(TCLAP::ValueArg<uint32_t>) ||
typeid(**it)==typeid(TCLAP::ValueArg<int32_t>) ||
typeid(**it)==typeid(TCLAP::ValueArg<double>))
{
TCLAP::ValueArg<std::string> *i = (TCLAP::ValueArg<std::string> *) (*it);
std::clog << "-" << i->getFlag()
<< " " << i->getDescription() << "\n";
}
else if (typeid(**it)==typeid(TCLAP::SwitchArg))
{
TCLAP::SwitchArg *i = (TCLAP::SwitchArg *) (*it);
std::clog << "-" << i->getFlag()
<< " " << i->getDescription() << "\n";
}
else if (typeid(**it)==typeid(TCLAP::UnlabeledValueArg<std::string>))
{
//ignored
}
else
{
std::clog << "oops, argument type not handled\n";
}
}
std::clog << "\n";
}
/**
* Parse intervals. Processes the interval list first followed by the interval string. Duplicates are dropped.
*
* @intervals - intervals stored in this vector
* @interval_list - file containing intervals
* @interval_string - comma delimited intervals in a string
*
* todo: merge overlapping sites?
*/
void Program::parse_intervals(std::vector<GenomeInterval>& intervals, std::string interval_list, std::string interval_string)
{
intervals.clear();
std::map<std::string, uint32_t> m;
if (interval_list!="")
{
htsFile *file = hts_open(interval_list.c_str(), "r");
if (file)
{
kstring_t *s = &file->line;
while (hts_getline(file, '\n', s)>=0)
{
std::string ss = std::string(s->s);
if (m.find(ss)==m.end())
{
m[ss] = 1;
GenomeInterval interval(ss);
intervals.push_back(interval);
}
}
hts_close(file);
}
}
std::vector<std::string> v;
if (interval_string!="")
split(v, ",", interval_string);
for (uint32_t i=0; i<v.size(); ++i)
{
if (m.find(v[i])==m.end())
{
m[v[i]] = 1;
GenomeInterval interval(v[i]);
intervals.push_back(interval);
}
}
}
/**
* Print intervals option.
*/
void Program::print_int_op(const char* option_line, std::vector<GenomeInterval>& intervals)
{
if (intervals.size()!=0)
{
std::clog << option_line;
for (uint32_t i=0; i<std::min((uint32_t)intervals.size(),(uint32_t)5); ++i)
{
if (i) std::clog << ",";
std::clog << intervals[i].to_string();
}
if (intervals.size()>5)
{
std::clog << " and " << (intervals.size()-5) << " other intervals\n";
}
}
}
/**
* Parse samples. Processes the sample list. Duplicates are dropped.
*
* @samples - samples stored in this vector
* @sample_map - samples stored in this map
* @sample_list - file containing sample names
*/
void Program::read_sample_list(std::vector<std::string>& samples, std::string sample_list)
{
samples.clear();
std::map<std::string, int32_t> map;
if (sample_list!="")
{
htsFile *file = hts_open(sample_list.c_str(), "r");
if (file)
{
kstring_t *s = &file->line;
while (hts_getline(file, '\n', s)>=0)
{
std::string ss = std::string(s->s);
if (map.find(ss)==map.end())
{
map[ss] = 1;
samples.push_back(ss);
}
}
hts_close(file);
}
}
}<|endoftext|> |
<commit_before>#include "utility.hpp"
#include <sse/schemes/sophos/sophos_client.hpp>
#include <sse/schemes/sophos/sophos_server.hpp>
#include <sse/schemes/utils/utils.hpp>
#include <sse/crypto/utils.hpp>
#include <gtest/gtest.h>
#include <algorithm>
#include <fstream>
#include <functional>
#include <iostream>
#include <map>
#include <memory>
#include <mutex>
#include <thread>
namespace sse {
namespace sophos {
namespace test {
constexpr auto client_sk_path = "test_sophos/tdp_sk.key";
constexpr auto client_master_key_path = "test_sophos/derivation_master.key";
constexpr auto client_tdp_prg_key_path = "test_sophos/tdp_prg.key";
constexpr auto server_pk_path = "test_sophos/tdp_pk.key";
#define SSE_SOPHOS_TEST_DIR "test_sophos"
constexpr auto sophos_test_dir = SSE_SOPHOS_TEST_DIR;
constexpr auto client_data_path = SSE_SOPHOS_TEST_DIR "/client.dat";
constexpr auto server_data_path = SSE_SOPHOS_TEST_DIR "/server.dat";
void create_client_server(std::unique_ptr<sophos::SophosClient>& client,
std::unique_ptr<sophos::SophosServer>& server)
{
std::ifstream client_sk_in(client_sk_path);
std::ifstream client_master_key_in(client_master_key_path);
std::ifstream client_tdp_prg_key_in(client_tdp_prg_key_path);
std::ifstream server_pk_in(server_pk_path);
// check that all the streams are in an invalid state:
// good() returns true if the file exists, false o/w
ASSERT_FALSE(client_sk_in.good());
ASSERT_FALSE(client_master_key_in.good());
ASSERT_FALSE(client_tdp_prg_key_in.good());
ASSERT_FALSE(server_pk_in.good());
// start the client and the server from scratch
// generate the keys
std::array<uint8_t, sophos::SophosClient::kKeySize> derivation_master_key
= sse::crypto::random_bytes<uint8_t, sophos::SophosClient::kKeySize>();
std::array<uint8_t, sophos::SophosClient::kKeySize> rsa_prg_key
= sse::crypto::random_bytes<uint8_t, sophos::SophosClient::kKeySize>();
sse::crypto::TdpInverse tdp;
// start by writing all the keys
std::ofstream client_sk_out(client_sk_path);
client_sk_out << tdp.private_key();
client_sk_out.close();
std::ofstream client_master_key_out(client_master_key_path);
client_master_key_out << std::string(derivation_master_key.begin(),
derivation_master_key.end());
client_master_key_out.close();
std::ofstream client_tdp_prg_key_out(client_tdp_prg_key_path);
client_tdp_prg_key_out << std::string(rsa_prg_key.begin(),
rsa_prg_key.end());
client_tdp_prg_key_out.close();
std::ofstream server_pk_out(server_pk_path);
server_pk_out << tdp.public_key();
server_pk_out.close();
// create the client and the server
client.reset(new sophos::SophosClient(
client_data_path,
tdp.private_key(),
sse::crypto::Key<SophosClient::kKeySize>(derivation_master_key.data()),
sse::crypto::Key<SophosClient::kKeySize>(rsa_prg_key.data())));
server.reset(new sophos::SophosServer(server_data_path, tdp.public_key()));
client_sk_in.close();
client_master_key_in.close();
server_pk_in.close();
}
void restart_client_server(std::unique_ptr<sophos::SophosClient>& client,
std::unique_ptr<sophos::SophosServer>& server)
{
std::ifstream client_sk_in(client_sk_path);
std::ifstream client_master_key_in(client_master_key_path);
std::ifstream client_tdp_prg_key_in(client_tdp_prg_key_path);
std::ifstream server_pk_in(server_pk_path);
// check that all the streams are in a valid state:
// good() returns true if the file exists, false o/w
ASSERT_TRUE(client_sk_in.good());
ASSERT_TRUE(client_master_key_in.good());
ASSERT_TRUE(client_tdp_prg_key_in.good());
ASSERT_TRUE(server_pk_in.good());
// reload the keys from the key filesi
std::stringstream client_sk_buf, client_master_key_buf, server_pk_buf,
client_tdp_prg_key_buf;
client_sk_buf << client_sk_in.rdbuf();
client_master_key_buf << client_master_key_in.rdbuf();
server_pk_buf << server_pk_in.rdbuf();
client_tdp_prg_key_buf << client_tdp_prg_key_in.rdbuf();
std::array<uint8_t, 32> client_master_key_array;
std::array<uint8_t, 32> client_tdp_prg_key_array;
ASSERT_EQ(client_master_key_buf.str().size(),
client_master_key_array.size());
ASSERT_EQ(client_tdp_prg_key_buf.str().size(),
client_tdp_prg_key_array.size());
auto client_master_key = client_master_key_buf.str();
auto client_tdp_prg_key = client_tdp_prg_key_buf.str();
std::copy(client_master_key.begin(),
client_master_key.end(),
client_master_key_array.begin());
std::copy(client_tdp_prg_key.begin(),
client_tdp_prg_key.end(),
client_tdp_prg_key_array.begin());
client.reset(new sophos::SophosClient(
client_data_path,
client_sk_buf.str(),
sse::crypto::Key<sophos::SophosClient::kKeySize>(
client_master_key_array.data()),
sse::crypto::Key<sophos::SophosClient::kKeySize>(
client_tdp_prg_key_array.data())));
server.reset(
new sophos::SophosServer(server_data_path, server_pk_buf.str()));
client_sk_in.close();
client_master_key_in.close();
server_pk_in.close();
// check that the TDP is correct
sse::crypto::TdpInverse tdp(client_sk_buf.str());
ASSERT_EQ(tdp.public_key(), server->public_key());
}
TEST(sophos, create_reload)
{
std::unique_ptr<sophos::SophosClient> client;
std::unique_ptr<sophos::SophosServer> server;
// start by cleaning up the test directory
sse::test::cleanup_directory(sophos_test_dir);
// first, create a client and a server from scratch
create_client_server(client, server);
// destroy them
client.reset(nullptr);
server.reset(nullptr);
// reload them from the disk
restart_client_server(client, server);
}
TEST(sophos, insertion_search)
{
std::unique_ptr<sophos::SophosClient> client;
std::unique_ptr<sophos::SophosServer> server;
// start by cleaning up the test directory
sse::test::cleanup_directory(sophos_test_dir);
// first, create a client and a server from scratch
create_client_server(client, server);
const std::map<std::string, std::list<uint64_t>> test_db
= {{"kw_1", {0, 1}}, {"kw_2", {0}}, {"kw_3", {0}}};
sse::test::insert_database(client, server, test_db);
sse::test::test_search_correctness(client, server, test_db);
}
inline void check_same_results(const std::list<uint64_t>& l1,
const std::list<uint64_t>& l2)
{
std::set<uint64_t> s1(l1.begin(), l1.end());
std::set<uint64_t> s2(l2.begin(), l2.end());
ASSERT_EQ(s1, s2);
}
// To test all the different search algorithms
// We do not try to find any kind of concurrency bug here:
// this is kept for an other test, so the concurrency level is often set to 1
TEST(sophos, search_algorithms)
{
std::unique_ptr<sophos::SophosClient> client;
std::unique_ptr<sophos::SophosServer> server;
// start by cleaning up the test directory
sse::test::cleanup_directory(sophos_test_dir);
// first, create a client and a server from scratch
create_client_server(client, server);
std::list<uint64_t> long_list;
for (size_t i = 0; i < 1000; i++) {
long_list.push_back(i);
}
const std::string keyword = "kw_1";
const std::map<std::string, std::list<uint64_t>> test_db
= {{keyword, long_list}};
sse::test::insert_database(client, server, test_db);
sophos::SearchRequest u_req;
std::mutex res_list_mutex;
auto search_callback
= [&res_list_mutex](std::list<uint64_t>* res_list, uint64_t index) {
std::lock_guard<std::mutex> lock(res_list_mutex);
res_list->push_back(index);
};
// Search requests can only be used once
u_req = client->search_request(keyword);
auto res = server->search(u_req);
u_req = client->search_request(keyword);
auto res_par = server->search_parallel(u_req, 1);
u_req = client->search_request(keyword);
auto res_par_light = server->search_parallel_light(u_req, 1);
// u_req, std::thread::hardware_concurrency());
// u_req = client->search_request(keyword);
// auto res_par_full = server->search_parallel_full(u_req);
check_same_results(long_list, res);
check_same_results(long_list, res_par);
check_same_results(long_list, res_par_light);
// check_same_results(long_list, res_par_full);
std::list<uint64_t> res_callback;
std::list<uint64_t> res_par_callback;
std::list<uint64_t> res_par_light_callback;
u_req = client->search_request(keyword);
server->search_callback(
u_req,
std::bind(search_callback, &res_callback, std::placeholders::_1));
check_same_results(long_list, res_callback);
u_req = client->search_request(keyword);
server->search_parallel_callback(
u_req,
std::bind(search_callback, &res_par_callback, std::placeholders::_1),
1,
1,
1);
check_same_results(long_list, res_par_callback);
u_req = client->search_request(keyword);
server->search_parallel_light_callback(u_req,
std::bind(search_callback,
&res_par_light_callback,
std::placeholders::_1),
1);
}
} // namespace test
} // namespace sophos
} // namespace sse<commit_msg>Small test improvements.Remove useless code.Use constants to avoid typos in path.<commit_after>#include "utility.hpp"
#include <sse/schemes/sophos/sophos_client.hpp>
#include <sse/schemes/sophos/sophos_server.hpp>
#include <sse/schemes/utils/utils.hpp>
#include <sse/crypto/utils.hpp>
#include <gtest/gtest.h>
#include <algorithm>
#include <fstream>
#include <functional>
#include <iostream>
#include <map>
#include <memory>
#include <mutex>
#include <thread>
namespace sse {
namespace sophos {
namespace test {
#define SSE_SOPHOS_TEST_DIR "test_sophos"
constexpr auto client_sk_path = SSE_SOPHOS_TEST_DIR "/tdp_sk.key";
constexpr auto client_master_key_path
= SSE_SOPHOS_TEST_DIR "/derivation_master.key";
constexpr auto client_tdp_prg_key_path = SSE_SOPHOS_TEST_DIR "/tdp_prg.key";
constexpr auto server_pk_path = SSE_SOPHOS_TEST_DIR "/tdp_pk.key";
constexpr auto sophos_test_dir = SSE_SOPHOS_TEST_DIR;
constexpr auto client_data_path = SSE_SOPHOS_TEST_DIR "/client.dat";
constexpr auto server_data_path = SSE_SOPHOS_TEST_DIR "/server.dat";
void create_client_server(std::unique_ptr<sophos::SophosClient>& client,
std::unique_ptr<sophos::SophosServer>& server)
{
// check that the key files do not already exist
ASSERT_FALSE(utility::exists(client_sk_path));
ASSERT_FALSE(utility::exists(client_master_key_path));
ASSERT_FALSE(utility::exists(client_tdp_prg_key_path));
ASSERT_FALSE(utility::exists(server_pk_path));
// start the client and the server from scratch
// generate the keys
std::array<uint8_t, sophos::SophosClient::kKeySize> derivation_master_key
= sse::crypto::random_bytes<uint8_t, sophos::SophosClient::kKeySize>();
std::array<uint8_t, sophos::SophosClient::kKeySize> rsa_prg_key
= sse::crypto::random_bytes<uint8_t, sophos::SophosClient::kKeySize>();
sse::crypto::TdpInverse tdp;
// start by writing all the keys
std::ofstream client_sk_out(client_sk_path);
client_sk_out << tdp.private_key();
client_sk_out.close();
std::ofstream client_master_key_out(client_master_key_path);
client_master_key_out << std::string(derivation_master_key.begin(),
derivation_master_key.end());
client_master_key_out.close();
std::ofstream client_tdp_prg_key_out(client_tdp_prg_key_path);
client_tdp_prg_key_out << std::string(rsa_prg_key.begin(),
rsa_prg_key.end());
client_tdp_prg_key_out.close();
std::ofstream server_pk_out(server_pk_path);
server_pk_out << tdp.public_key();
server_pk_out.close();
// create the client and the server
client.reset(new sophos::SophosClient(
client_data_path,
tdp.private_key(),
sse::crypto::Key<SophosClient::kKeySize>(derivation_master_key.data()),
sse::crypto::Key<SophosClient::kKeySize>(rsa_prg_key.data())));
server.reset(new sophos::SophosServer(server_data_path, tdp.public_key()));
}
void restart_client_server(std::unique_ptr<sophos::SophosClient>& client,
std::unique_ptr<sophos::SophosServer>& server)
{
std::ifstream client_sk_in(client_sk_path);
std::ifstream client_master_key_in(client_master_key_path);
std::ifstream client_tdp_prg_key_in(client_tdp_prg_key_path);
std::ifstream server_pk_in(server_pk_path);
// check that all the streams are in a valid state:
// good() returns true if the file exists, false o/w
ASSERT_TRUE(client_sk_in.good());
ASSERT_TRUE(client_master_key_in.good());
ASSERT_TRUE(client_tdp_prg_key_in.good());
ASSERT_TRUE(server_pk_in.good());
// reload the keys from the key filesi
std::stringstream client_sk_buf, client_master_key_buf, server_pk_buf,
client_tdp_prg_key_buf;
client_sk_buf << client_sk_in.rdbuf();
client_master_key_buf << client_master_key_in.rdbuf();
server_pk_buf << server_pk_in.rdbuf();
client_tdp_prg_key_buf << client_tdp_prg_key_in.rdbuf();
std::array<uint8_t, 32> client_master_key_array;
std::array<uint8_t, 32> client_tdp_prg_key_array;
ASSERT_EQ(client_master_key_buf.str().size(),
client_master_key_array.size());
ASSERT_EQ(client_tdp_prg_key_buf.str().size(),
client_tdp_prg_key_array.size());
auto client_master_key = client_master_key_buf.str();
auto client_tdp_prg_key = client_tdp_prg_key_buf.str();
std::copy(client_master_key.begin(),
client_master_key.end(),
client_master_key_array.begin());
std::copy(client_tdp_prg_key.begin(),
client_tdp_prg_key.end(),
client_tdp_prg_key_array.begin());
client.reset(new sophos::SophosClient(
client_data_path,
client_sk_buf.str(),
sse::crypto::Key<sophos::SophosClient::kKeySize>(
client_master_key_array.data()),
sse::crypto::Key<sophos::SophosClient::kKeySize>(
client_tdp_prg_key_array.data())));
server.reset(
new sophos::SophosServer(server_data_path, server_pk_buf.str()));
client_sk_in.close();
client_master_key_in.close();
server_pk_in.close();
// check that the TDP is correct
sse::crypto::TdpInverse tdp(client_sk_buf.str());
ASSERT_EQ(tdp.public_key(), server->public_key());
}
TEST(sophos, create_reload)
{
std::unique_ptr<sophos::SophosClient> client;
std::unique_ptr<sophos::SophosServer> server;
// start by cleaning up the test directory
sse::test::cleanup_directory(sophos_test_dir);
// first, create a client and a server from scratch
create_client_server(client, server);
// destroy them
client.reset(nullptr);
server.reset(nullptr);
// reload them from the disk
restart_client_server(client, server);
}
TEST(sophos, insertion_search)
{
std::unique_ptr<sophos::SophosClient> client;
std::unique_ptr<sophos::SophosServer> server;
// start by cleaning up the test directory
sse::test::cleanup_directory(sophos_test_dir);
// first, create a client and a server from scratch
create_client_server(client, server);
const std::map<std::string, std::list<uint64_t>> test_db
= {{"kw_1", {0, 1}}, {"kw_2", {0}}, {"kw_3", {0}}};
sse::test::insert_database(client, server, test_db);
sse::test::test_search_correctness(client, server, test_db);
}
inline void check_same_results(const std::list<uint64_t>& l1,
const std::list<uint64_t>& l2)
{
std::set<uint64_t> s1(l1.begin(), l1.end());
std::set<uint64_t> s2(l2.begin(), l2.end());
ASSERT_EQ(s1, s2);
}
// To test all the different search algorithms
// We do not try to find any kind of concurrency bug here:
// this is kept for an other test, so the concurrency level is often set to 1
TEST(sophos, search_algorithms)
{
std::unique_ptr<sophos::SophosClient> client;
std::unique_ptr<sophos::SophosServer> server;
// start by cleaning up the test directory
sse::test::cleanup_directory(sophos_test_dir);
// first, create a client and a server from scratch
create_client_server(client, server);
std::list<uint64_t> long_list;
for (size_t i = 0; i < 1000; i++) {
long_list.push_back(i);
}
const std::string keyword = "kw_1";
const std::map<std::string, std::list<uint64_t>> test_db
= {{keyword, long_list}};
sse::test::insert_database(client, server, test_db);
sophos::SearchRequest u_req;
std::mutex res_list_mutex;
auto search_callback
= [&res_list_mutex](std::list<uint64_t>* res_list, uint64_t index) {
std::lock_guard<std::mutex> lock(res_list_mutex);
res_list->push_back(index);
};
// Search requests can only be used once
u_req = client->search_request(keyword);
auto res = server->search(u_req);
u_req = client->search_request(keyword);
auto res_par = server->search_parallel(u_req, 1);
u_req = client->search_request(keyword);
auto res_par_light = server->search_parallel_light(u_req, 1);
// u_req, std::thread::hardware_concurrency());
// u_req = client->search_request(keyword);
// auto res_par_full = server->search_parallel_full(u_req);
check_same_results(long_list, res);
check_same_results(long_list, res_par);
check_same_results(long_list, res_par_light);
// check_same_results(long_list, res_par_full);
std::list<uint64_t> res_callback;
std::list<uint64_t> res_par_callback;
std::list<uint64_t> res_par_light_callback;
u_req = client->search_request(keyword);
server->search_callback(
u_req,
std::bind(search_callback, &res_callback, std::placeholders::_1));
check_same_results(long_list, res_callback);
u_req = client->search_request(keyword);
server->search_parallel_callback(
u_req,
std::bind(search_callback, &res_par_callback, std::placeholders::_1),
1,
1,
1);
check_same_results(long_list, res_par_callback);
u_req = client->search_request(keyword);
server->search_parallel_light_callback(u_req,
std::bind(search_callback,
&res_par_light_callback,
std::placeholders::_1),
1);
check_same_results(long_list, res_par_light_callback);
}
} // namespace test
} // namespace sophos
} // namespace sse<|endoftext|> |
<commit_before>// IFC SDK : IFC2X3 C++ Early Classes
// Copyright (C) 2009 CSTB
//
// 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.
// The full license is in Licence.txt file included with this
// distribution or is available at :
// http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
//
// 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.
#include "Step/BaseSPFWriter.h"
#include "Step/SPFData.h"
#include "Step/SPFHeader.h"
#include "Step/SPFFunctions.h"
#include "Step/BaseSPFObject.h"
#include "Step/BaseExpressDataSet.h"
#include "Step/logger.h"
#include <locale>
#include <assert.h>
using namespace Step;
#ifndef DBL_DIG
# define DBL_DIG __DBL_DIG__
#endif
BaseSPFWriter::BaseSPFWriter(BaseExpressDataSet * e) : _callback(0)
{
m_expressDataSet = e;
m_precision = DBL_DIG + 1;
}
BaseSPFWriter::~BaseSPFWriter()
{
}
bool BaseSPFWriter::init(std::ostream& filestream)
{
m_out = &filestream;
if (!outputStream().good())
return false;
outputStream().precision(m_precision);
return true;
}
void BaseSPFWriter::writeHeader()
{
SPFHeader& header = m_expressDataSet->getHeader();
unsigned int i;
outputStream() << "ISO-10303-21;" << std::endl;
outputStream() << "HEADER;" << std::endl;
outputStream() << "FILE_DESCRIPTION((";
SPFHeader::FileDescription& file_description = header.getFileDescription();
//std::list<std::string> file_description = m_expressDataSet->get_file_description() ;
for (i = 0; i < file_description.description.size(); i++)
{
outputStream() << file_description.description[i].toSPF();
if (i != (file_description.description.size() - 1))
outputStream() << ",";
}
outputStream() << "), " << file_description.implementationLevel.toSPF() << ");"
<< std::endl;
SPFHeader::FileName& filename = header.getFileName();
outputStream() << "FILE_NAME(" << filename.name.toSPF() << ","
<< filename.timeStamp.toSPF() << ",(";
std::vector<String> author = filename.author;
for (i = 0; i < author.size(); i++)
{
outputStream() << author[i].toSPF();
if (i != author.size() - 1)
outputStream() << ",";
}
outputStream() << "),(";
std::vector<String> organization = filename.organization;
for (i = 0; i < organization.size(); i++)
{
outputStream() << organization[i].toSPF();
if (i != organization.size() - 1)
outputStream() << ",";
}
outputStream() << "), " << filename.preprocessorVersion.toSPF() << ", "
<< filename.originatingSystem.toSPF() << ", "
<< filename.authorization.toSPF() << ");" << std::endl;
outputStream() << "FILE_SCHEMA((";
std::vector<String> schema_identifiers =
header.getFileSchema().schemaIdentifiers;
for (i = 0; i < schema_identifiers.size(); i++)
{
outputStream() << schema_identifiers[i].toSPF();
if (i != schema_identifiers.size() - 1)
outputStream() << ", ";
}
outputStream() << "));" << std::endl;
outputStream() << "ENDSEC;" << std::endl;
outputStream() << "DATA;" << std::endl;
}
void BaseSPFWriter::writeEnder()
{
outputStream() << "ENDSEC;" << std::endl;
outputStream() << "END-ISO-10303-21;" << std::endl;
}
bool BaseSPFWriter::writeIfNotInited(Id id)
{
#define CHECK_IF_EXIST(str) (str[0] == '#'?(m_expressDataSet->exists((unsigned)atol(str.substr(1).c_str()))?str:"$"):str)
SPFData* args = m_expressDataSet->getArgs(id);
if (!args || args->argc() <= 0)
return false;
outputStream() << CHECK_IF_EXIST(args->at(0));
for (int i = 1; i < args->argc(); i++)
{
outputStream() << "," << CHECK_IF_EXIST(args->at(i));
}
outputStream() << ");" << std::endl;
return true;
#undef CHECK_IF_EXIST
}
void BaseSPFWriter::writeAttribute(BaseEntity* entity)
{
Step::Id curId = entity->getKey();
if (m_expressDataSet->exists(curId))
outputStream() << "#" << curId;
else
outputStream() << "$";
}
void BaseSPFWriter::writeAttribute(Real value)
{
if (isUnset(value))
{
outputStream() << "$";
}
else
{
const double fabs_value = fabs(value);
if(fabs_value < pow(10.0, -m_precision) * 0.5)
{
outputStream() << "0.";
}
else
{
std::string str;
std::stringstream stream;
stream.imbue(std::locale::classic());
const double exp = log10(fabs_value);
size_t end;
if(exp > DBL_DIG + 1)
{
stream << std::setprecision(DBL_DIG + 1)
<< std::setiosflags (std::ios_base::scientific | std::ios_base::uppercase | std::ios_base::showpoint)
<< value;
str = stream.str();
end = str.find('E');
}
else
{
const int digits = exp < 0.0 ? 0 : ((int) exp);
stream << std::setprecision(std::min(m_precision, DBL_DIG + 1 - digits))
<< std::setiosflags (std::ios_base::fixed | std::ios_base::uppercase | std::ios_base::showpoint)
<< value;
str = stream.str();
end = str.size();
}
size_t begin = str.find('.');
size_t it = end;
// Remove trailing zeros
while(--it > begin)
{
if(str[it] != '0')
break;
}
it++;
str.erase(it, end - it);
assert(fabs(Step::fromString<double>(str) - value) < pow(10.0, m_precision));
outputStream() << str;
}
}
}
void BaseSPFWriter::writeAttribute(Integer value)
{
if (isUnset(value))
outputStream() << "$";
else
outputStream() << value;
}
void BaseSPFWriter::writeAttribute(Boolean value)
{
outputStream() << (value == BTrue ? ".T." : (value == BFalse ? ".F." : "$"));
}
void BaseSPFWriter::writeAttribute(Logical value)
{
switch (value)
{
case LTrue:
outputStream() << ".T.";
break;
case LFalse:
outputStream() << ".F.";
break;
case LUnknown:
outputStream() << ".U.";
break;
case LUnset:
default:
outputStream() << "$";
break;
}
}
void BaseSPFWriter::writeAttribute(const String& value)
{
if (isUnset(value))
outputStream() << "$";
else
outputStream() << value.toSPF();
}
void BaseSPFWriter::setDecimalPrecision(const int precision)
{
if(precision >= 0)
m_precision = precision;
}
<commit_msg>check if entity exist before accessing it<commit_after>// IFC SDK : IFC2X3 C++ Early Classes
// Copyright (C) 2009 CSTB
//
// 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.
// The full license is in Licence.txt file included with this
// distribution or is available at :
// http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
//
// 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.
#include "Step/BaseSPFWriter.h"
#include "Step/SPFData.h"
#include "Step/SPFHeader.h"
#include "Step/SPFFunctions.h"
#include "Step/BaseSPFObject.h"
#include "Step/BaseExpressDataSet.h"
#include "Step/logger.h"
#include <locale>
#include <assert.h>
using namespace Step;
#ifndef DBL_DIG
# define DBL_DIG __DBL_DIG__
#endif
BaseSPFWriter::BaseSPFWriter(BaseExpressDataSet * e) : _callback(0)
{
m_expressDataSet = e;
m_precision = DBL_DIG + 1;
}
BaseSPFWriter::~BaseSPFWriter()
{
}
bool BaseSPFWriter::init(std::ostream& filestream)
{
m_out = &filestream;
if (!outputStream().good())
return false;
outputStream().precision(m_precision);
return true;
}
void BaseSPFWriter::writeHeader()
{
SPFHeader& header = m_expressDataSet->getHeader();
unsigned int i;
outputStream() << "ISO-10303-21;" << std::endl;
outputStream() << "HEADER;" << std::endl;
outputStream() << "FILE_DESCRIPTION((";
SPFHeader::FileDescription& file_description = header.getFileDescription();
//std::list<std::string> file_description = m_expressDataSet->get_file_description() ;
for (i = 0; i < file_description.description.size(); i++)
{
outputStream() << file_description.description[i].toSPF();
if (i != (file_description.description.size() - 1))
outputStream() << ",";
}
outputStream() << "), " << file_description.implementationLevel.toSPF() << ");"
<< std::endl;
SPFHeader::FileName& filename = header.getFileName();
outputStream() << "FILE_NAME(" << filename.name.toSPF() << ","
<< filename.timeStamp.toSPF() << ",(";
std::vector<String> author = filename.author;
for (i = 0; i < author.size(); i++)
{
outputStream() << author[i].toSPF();
if (i != author.size() - 1)
outputStream() << ",";
}
outputStream() << "),(";
std::vector<String> organization = filename.organization;
for (i = 0; i < organization.size(); i++)
{
outputStream() << organization[i].toSPF();
if (i != organization.size() - 1)
outputStream() << ",";
}
outputStream() << "), " << filename.preprocessorVersion.toSPF() << ", "
<< filename.originatingSystem.toSPF() << ", "
<< filename.authorization.toSPF() << ");" << std::endl;
outputStream() << "FILE_SCHEMA((";
std::vector<String> schema_identifiers =
header.getFileSchema().schemaIdentifiers;
for (i = 0; i < schema_identifiers.size(); i++)
{
outputStream() << schema_identifiers[i].toSPF();
if (i != schema_identifiers.size() - 1)
outputStream() << ", ";
}
outputStream() << "));" << std::endl;
outputStream() << "ENDSEC;" << std::endl;
outputStream() << "DATA;" << std::endl;
}
void BaseSPFWriter::writeEnder()
{
outputStream() << "ENDSEC;" << std::endl;
outputStream() << "END-ISO-10303-21;" << std::endl;
}
bool BaseSPFWriter::writeIfNotInited(Id id)
{
#define CHECK_IF_EXIST(str) (str[0] == '#'?(m_expressDataSet->exists((unsigned)atol(str.substr(1).c_str()))?str:"$"):str)
SPFData* args = m_expressDataSet->getArgs(id);
if (!args || args->argc() <= 0)
return false;
outputStream() << CHECK_IF_EXIST(args->at(0));
for (int i = 1; i < args->argc(); i++)
{
outputStream() << "," << CHECK_IF_EXIST(args->at(i));
}
outputStream() << ");" << std::endl;
return true;
#undef CHECK_IF_EXIST
}
void BaseSPFWriter::writeAttribute(BaseEntity* entity)
{
if (entity)
{
Step::Id curId = entity->getKey();
if (m_expressDataSet->exists(curId))
{
outputStream() << "#" << curId;
return ;
}
}
outputStream() << "$";
}
void BaseSPFWriter::writeAttribute(Real value)
{
if (isUnset(value))
{
outputStream() << "$";
}
else
{
const double fabs_value = fabs(value);
if(fabs_value < pow(10.0, -m_precision) * 0.5)
{
outputStream() << "0.";
}
else
{
std::string str;
std::stringstream stream;
stream.imbue(std::locale::classic());
const double exp = log10(fabs_value);
size_t end;
if(exp > DBL_DIG + 1)
{
stream << std::setprecision(DBL_DIG + 1)
<< std::setiosflags (std::ios_base::scientific | std::ios_base::uppercase | std::ios_base::showpoint)
<< value;
str = stream.str();
end = str.find('E');
}
else
{
const int digits = exp < 0.0 ? 0 : ((int) exp);
stream << std::setprecision(std::min(m_precision, DBL_DIG + 1 - digits))
<< std::setiosflags (std::ios_base::fixed | std::ios_base::uppercase | std::ios_base::showpoint)
<< value;
str = stream.str();
end = str.size();
}
size_t begin = str.find('.');
size_t it = end;
// Remove trailing zeros
while(--it > begin)
{
if(str[it] != '0')
break;
}
it++;
str.erase(it, end - it);
assert(fabs(Step::fromString<double>(str) - value) < pow(10.0, m_precision));
outputStream() << str;
}
}
}
void BaseSPFWriter::writeAttribute(Integer value)
{
if (isUnset(value))
outputStream() << "$";
else
outputStream() << value;
}
void BaseSPFWriter::writeAttribute(Boolean value)
{
outputStream() << (value == BTrue ? ".T." : (value == BFalse ? ".F." : "$"));
}
void BaseSPFWriter::writeAttribute(Logical value)
{
switch (value)
{
case LTrue:
outputStream() << ".T.";
break;
case LFalse:
outputStream() << ".F.";
break;
case LUnknown:
outputStream() << ".U.";
break;
case LUnset:
default:
outputStream() << "$";
break;
}
}
void BaseSPFWriter::writeAttribute(const String& value)
{
if (isUnset(value))
outputStream() << "$";
else
outputStream() << value.toSPF();
}
void BaseSPFWriter::setDecimalPrecision(const int precision)
{
if(precision >= 0)
m_precision = precision;
}
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2008, 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 <boost/python.hpp>
#include "IECore/bindings/ParameterBinding.h"
#include "IECore/bindings/Wrapper.h"
#include "IECore/TypedObjectParameter.h"
#include "IECore/CompoundObject.h"
#include "IECore/bindings/WrapperToPython.h"
#include "IECore/bindings/IntrusivePtrPatch.h"
#include "IECore/bindings/RunTimeTypedBinding.h"
#include "IECore/Renderable.h"
#include "IECore/StateRenderable.h"
#include "IECore/AttributeState.h"
#include "IECore/Shader.h"
#include "IECore/Transform.h"
#include "IECore/MatrixMotionTransform.h"
#include "IECore/MatrixTransform.h"
#include "IECore/VisibleRenderable.h"
#include "IECore/Group.h"
#include "IECore/MotionPrimitive.h"
#include "IECore/Primitive.h"
#include "IECore/ImagePrimitive.h"
#include "IECore/MeshPrimitive.h"
#include "IECore/PointsPrimitive.h"
using namespace std;
using namespace boost;
using namespace boost::python;
namespace IECore
{
template<typename T>
class TypedObjectParameterWrap : public TypedObjectParameter<T>, public Wrapper< TypedObjectParameter<T> >
{
public:
IE_CORE_DECLAREMEMBERPTR( TypedObjectParameterWrap<T> );
protected:
static typename TypedObjectParameter<T>::ObjectPresetsMap makePresets( const dict &d )
{
typename TypedObjectParameter<T>::ObjectPresetsMap p;
boost::python::list keys = d.keys();
boost::python::list values = d.values();
for( int i = 0; i<keys.attr( "__len__" )(); i++ )
{
extract<typename T::Ptr> e( values[i] );
p.insert( typename TypedObjectParameter<T>::ObjectPresetsMap::value_type( extract<string>( keys[i] )(), e() ) );
}
return p;
}
public :
TypedObjectParameterWrap( PyObject *self, const std::string &n, const std::string &d, typename T::Ptr dv, const dict &p = dict(), bool po = false, CompoundObjectPtr ud = 0 )
: TypedObjectParameter<T>( n, d, dv, makePresets( p ), po, ud ), Wrapper< TypedObjectParameter<T> >( self, this ) {};
TypedObjectParameterWrap( PyObject *self, const std::string &n, const std::string &d, typename T::Ptr dv, CompoundObjectPtr ud )
: TypedObjectParameter<T>( n, d, dv, typename TypedObjectParameter<T>::ObjectPresetsMap(), false, ud ), Wrapper< TypedObjectParameter<T> >( self, this ) {};
IE_COREPYTHON_PARAMETERWRAPPERFNS( TypedObjectParameter<T> );
};
template<typename T>
static void bindTypedObjectParameter( const char *name )
{
typedef class_< TypedObjectParameter<T>, typename TypedObjectParameterWrap< T >::Ptr , boost::noncopyable, bases<ObjectParameter> > TypedObjectParameterPyClass;
TypedObjectParameterPyClass( name, no_init )
.def( init< const std::string &, const std::string &, typename T::Ptr, optional<const dict &, bool, CompoundObjectPtr > >( args( "name", "description", "defaultValue", "presets", "presetsOnly", "userData") ) )
.def( init< const std::string &, const std::string &, typename T::Ptr, CompoundObjectPtr >( args( "name", "description", "defaultValue", "userData") ) )
.IE_COREPYTHON_DEFPARAMETERWRAPPERFNS( TypedObjectParameter<T> )
.IE_COREPYTHON_DEFRUNTIMETYPEDSTATICMETHODS( TypedObjectParameter<T> )
;
WrapperToPython< typename TypedObjectParameter<T>::Ptr >();
INTRUSIVE_PTR_PATCH( TypedObjectParameter<T>, typename TypedObjectParameterPyClass );
implicitly_convertible< typename TypedObjectParameter<T>::Ptr, ObjectParameterPtr>();
}
void bindTypedObjectParameter()
{
bindTypedObjectParameter<Renderable>( "RenderableParameter" );
bindTypedObjectParameter<StateRenderable>( "StateRenderableParameter" );
bindTypedObjectParameter<AttributeState>( "AttributeStateParameter" );
bindTypedObjectParameter<Shader>( "ShaderParameter" );
bindTypedObjectParameter<Transform>( "TransformParameter" );
bindTypedObjectParameter<MatrixMotionTransform>( "MatrixMotionTransformParameter" );
bindTypedObjectParameter<MatrixTransform>( "MatrixTransformParameter" );
bindTypedObjectParameter<VisibleRenderable>( "VisibleRenderableParameter" );
bindTypedObjectParameter<Group>( "GroupParameter" );
bindTypedObjectParameter<MotionPrimitive>( "MotionPrimitiveParameter" );
bindTypedObjectParameter<Primitive>( "PrimitiveParameter" );
bindTypedObjectParameter<ImagePrimitive>( "ImagePrimitiveParameter" );
bindTypedObjectParameter<MeshPrimitive>( "MeshPrimitiveParameter" );
bindTypedObjectParameter<PointsPrimitive>( "PointsPrimitiveParameter" );
}
} // namespace IECore
<commit_msg>Added namespace clarification that seems necessary to compile now.<commit_after>//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2008, 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 <boost/python.hpp>
#include "IECore/bindings/ParameterBinding.h"
#include "IECore/bindings/Wrapper.h"
#include "IECore/TypedObjectParameter.h"
#include "IECore/CompoundObject.h"
#include "IECore/bindings/WrapperToPython.h"
#include "IECore/bindings/IntrusivePtrPatch.h"
#include "IECore/bindings/RunTimeTypedBinding.h"
#include "IECore/Renderable.h"
#include "IECore/StateRenderable.h"
#include "IECore/AttributeState.h"
#include "IECore/Shader.h"
#include "IECore/Transform.h"
#include "IECore/MatrixMotionTransform.h"
#include "IECore/MatrixTransform.h"
#include "IECore/VisibleRenderable.h"
#include "IECore/Group.h"
#include "IECore/MotionPrimitive.h"
#include "IECore/Primitive.h"
#include "IECore/ImagePrimitive.h"
#include "IECore/MeshPrimitive.h"
#include "IECore/PointsPrimitive.h"
using namespace std;
using namespace boost;
using namespace boost::python;
namespace IECore
{
template<typename T>
class TypedObjectParameterWrap : public TypedObjectParameter<T>, public Wrapper< TypedObjectParameter<T> >
{
public:
IE_CORE_DECLAREMEMBERPTR( TypedObjectParameterWrap<T> );
protected:
static typename TypedObjectParameter<T>::ObjectPresetsMap makePresets( const dict &d )
{
typename TypedObjectParameter<T>::ObjectPresetsMap p;
boost::python::list keys = d.keys();
boost::python::list values = d.values();
for( int i = 0; i<keys.attr( "__len__" )(); i++ )
{
extract<typename T::Ptr> e( values[i] );
p.insert( typename TypedObjectParameter<T>::ObjectPresetsMap::value_type( extract<string>( keys[i] )(), e() ) );
}
return p;
}
public :
TypedObjectParameterWrap( PyObject *self, const std::string &n, const std::string &d, typename T::Ptr dv, const dict &p = dict(), bool po = false, CompoundObjectPtr ud = 0 )
: TypedObjectParameter<T>( n, d, dv, makePresets( p ), po, ud ), Wrapper< TypedObjectParameter<T> >( self, this ) {};
TypedObjectParameterWrap( PyObject *self, const std::string &n, const std::string &d, typename T::Ptr dv, CompoundObjectPtr ud )
: TypedObjectParameter<T>( n, d, dv, typename TypedObjectParameter<T>::ObjectPresetsMap(), false, ud ), Wrapper< TypedObjectParameter<T> >( self, this ) {};
IE_COREPYTHON_PARAMETERWRAPPERFNS( TypedObjectParameter<T> );
};
template<typename T>
static void bindTypedObjectParameter( const char *name )
{
typedef class_< TypedObjectParameter<T>, typename TypedObjectParameterWrap< T >::Ptr , boost::noncopyable, bases<ObjectParameter> > TypedObjectParameterPyClass;
TypedObjectParameterPyClass( name, no_init )
.def( init< const std::string &, const std::string &, typename T::Ptr, boost::python::optional<const dict &, bool, CompoundObjectPtr > >( args( "name", "description", "defaultValue", "presets", "presetsOnly", "userData") ) )
.def( init< const std::string &, const std::string &, typename T::Ptr, CompoundObjectPtr >( args( "name", "description", "defaultValue", "userData") ) )
.IE_COREPYTHON_DEFPARAMETERWRAPPERFNS( TypedObjectParameter<T> )
.IE_COREPYTHON_DEFRUNTIMETYPEDSTATICMETHODS( TypedObjectParameter<T> )
;
WrapperToPython< typename TypedObjectParameter<T>::Ptr >();
INTRUSIVE_PTR_PATCH( TypedObjectParameter<T>, typename TypedObjectParameterPyClass );
implicitly_convertible< typename TypedObjectParameter<T>::Ptr, ObjectParameterPtr>();
}
void bindTypedObjectParameter()
{
bindTypedObjectParameter<Renderable>( "RenderableParameter" );
bindTypedObjectParameter<StateRenderable>( "StateRenderableParameter" );
bindTypedObjectParameter<AttributeState>( "AttributeStateParameter" );
bindTypedObjectParameter<Shader>( "ShaderParameter" );
bindTypedObjectParameter<Transform>( "TransformParameter" );
bindTypedObjectParameter<MatrixMotionTransform>( "MatrixMotionTransformParameter" );
bindTypedObjectParameter<MatrixTransform>( "MatrixTransformParameter" );
bindTypedObjectParameter<VisibleRenderable>( "VisibleRenderableParameter" );
bindTypedObjectParameter<Group>( "GroupParameter" );
bindTypedObjectParameter<MotionPrimitive>( "MotionPrimitiveParameter" );
bindTypedObjectParameter<Primitive>( "PrimitiveParameter" );
bindTypedObjectParameter<ImagePrimitive>( "ImagePrimitiveParameter" );
bindTypedObjectParameter<MeshPrimitive>( "MeshPrimitiveParameter" );
bindTypedObjectParameter<PointsPrimitive>( "PointsPrimitiveParameter" );
}
} // namespace IECore
<|endoftext|> |
<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Youssef Kashef
// Copyright (c) 2015, ELM Library Project
// 3-clause BSD License
//
//M*/
#include "elm/layers/medianblur.h"
#include <opencv2/imgproc/imgproc.hpp>
#include "elm/core/exception.h"
#include "elm/core/layerconfig.h"
#include "elm/core/signal.h"
#include "elm/ts/layerattr_.h"
using namespace cv;
using namespace elm;
/** @todo why does define guard lead to undefined reference error?
*/
//#ifdef __WITH_GTEST
#include <boost/assign/list_of.hpp>
template <>
elm::MapIONames LayerAttr_<MedianBlur>::io_pairs = boost::assign::map_list_of
ELM_ADD_INPUT_PAIR(detail::BASE_SINGLE_INPUT_FEATURE_LAYER__KEY_INPUT_STIMULUS)
ELM_ADD_OUTPUT_PAIR(detail::BASE_MATOUTPUT_LAYER__KEY_OUTPUT_RESPONSE)
;
//#endif
MedianBlur::MedianBlur()
: base_SmoothLayer()
{
Clear();
}
MedianBlur::MedianBlur(const LayerConfig &config)
: base_SmoothLayer(config)
{
Reset(config);
IONames(config);
}
void MedianBlur::Reconfigure(const LayerConfig &config)
{
base_SmoothLayer::Reconfigure(config);
if(ksize_ <= 1 || ksize_ % 2 == 0) {
std::stringstream s;
s << "Aperture size for median filer must be > 1 and odd." <<
" Got " << ksize_;
ELM_THROW_VALUE_ERROR(s.str());
}
}
void MedianBlur::Activate(const Signal &signal)
{
Mat src, dst;
/* from OpneCV's docs:
* when ksize is 3 or 5,
* the image depth should be CV_8U, CV_16U, or CV_32F,
* for larger aperture sizes, it can only be CV_8U
**/
if(ksize_ > 5) {
signal.MostRecentMat1f(name_input_).convertTo(src, CV_8U);
}
else {
src = signal.MostRecentMat1f(name_input_);
Mat1b nan = elm::isnan(src);
if(cv::countNonZero(nan) > 0) {
src = src.clone();
src.setTo(1e7, nan);
}
}
medianBlur(src, dst, ksize_);
m_ = dst;
}
<commit_msg>restore nan values in smoothed image<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, Youssef Kashef
// Copyright (c) 2015, ELM Library Project
// 3-clause BSD License
//
//M*/
#include "elm/layers/medianblur.h"
#include <opencv2/imgproc/imgproc.hpp>
#include "elm/core/exception.h"
#include "elm/core/layerconfig.h"
#include "elm/core/signal.h"
#include "elm/ts/layerattr_.h"
using namespace cv;
using namespace elm;
/** @todo why does define guard lead to undefined reference error?
*/
//#ifdef __WITH_GTEST
#include <boost/assign/list_of.hpp>
template <>
elm::MapIONames LayerAttr_<MedianBlur>::io_pairs = boost::assign::map_list_of
ELM_ADD_INPUT_PAIR(detail::BASE_SINGLE_INPUT_FEATURE_LAYER__KEY_INPUT_STIMULUS)
ELM_ADD_OUTPUT_PAIR(detail::BASE_MATOUTPUT_LAYER__KEY_OUTPUT_RESPONSE)
;
//#endif
MedianBlur::MedianBlur()
: base_SmoothLayer()
{
Clear();
}
MedianBlur::MedianBlur(const LayerConfig &config)
: base_SmoothLayer(config)
{
Reset(config);
IONames(config);
}
void MedianBlur::Reconfigure(const LayerConfig &config)
{
base_SmoothLayer::Reconfigure(config);
if(ksize_ <= 1 || ksize_ % 2 == 0) {
std::stringstream s;
s << "Aperture size for median filer must be > 1 and odd." <<
" Got " << ksize_;
ELM_THROW_VALUE_ERROR(s.str());
}
}
void MedianBlur::Activate(const Signal &signal)
{
Mat src, dst;
Mat1b mask_nan;
/* from OpneCV's docs:
* when ksize is 3 or 5,
* the image depth should be CV_8U, CV_16U, or CV_32F,
* for larger aperture sizes, it can only be CV_8U
**/
if(ksize_ > 5) {
signal.MostRecentMat1f(name_input_).convertTo(src, CV_8U);
}
else {
src = signal.MostRecentMat1f(name_input_);
mask_nan = elm::isnan(src);
if(cv::countNonZero(mask_nan) > 0) {
src = src.clone();
src.setTo(1e7, mask_nan);
}
}
medianBlur(src, dst, ksize_);
if(!mask_nan.empty()) {
dst.setTo(std::numeric_limits<float>::quiet_NaN(), mask_nan);
}
m_ = dst;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: virdev.cxx,v $
*
* $Revision: 1.26 $
*
* last change: $Author: obo $ $Date: 2006-07-10 17:26:14 $
*
* 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 _SV_SVSYS_HXX
#include <svsys.h>
#endif
#ifndef _SV_SALINST_HXX
#include <salinst.hxx>
#endif
#ifndef _SV_SALGDI_HXX
#include <salgdi.hxx>
#endif
#ifndef _SV_SALFRAME_HXX
#include <salframe.hxx>
#endif
#ifndef _SV_SALVD_HXX
#include <salvd.hxx>
#endif
#ifndef _DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _SV_SVDATA_HXX
#include <svdata.hxx>
#endif
#ifndef _SV_SETTINGS_HXX
#include <settings.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <svapp.hxx>
#endif
#ifndef _SV_WRKWIN_HXX
#include <wrkwin.hxx>
#endif
#ifndef _SV_OUTDEV_H
#include <outdev.h>
#endif
#ifndef _SV_VIRDEV_HXX
#include <virdev.hxx>
#endif
using namespace ::com::sun::star::uno;
// =======================================================================
void VirtualDevice::ImplInitVirDev( const OutputDevice* pOutDev,
long nDX, long nDY, USHORT nBitCount, const SystemGraphicsData *pData )
{
DBG_ASSERT( nBitCount <= 1,
"VirtualDevice::VirtualDevice(): Only 0 or 1 is for BitCount allowed" );
if ( nDX < 1 )
nDX = 1;
if ( nDY < 1 )
nDY = 1;
ImplSVData* pSVData = ImplGetSVData();
if ( !pOutDev )
pOutDev = ImplGetDefaultWindow();
if( !pOutDev )
return;
SalGraphics* pGraphics;
if ( !pOutDev->mpGraphics )
((OutputDevice*)pOutDev)->ImplGetGraphics();
pGraphics = pOutDev->mpGraphics;
if ( pGraphics )
mpVirDev = pSVData->mpDefInst->CreateVirtualDevice( pGraphics, nDX, nDY, nBitCount, pData );
else
mpVirDev = NULL;
if ( !mpVirDev )
{
// do not abort but throw an exception, may be the current thread terminates anyway (plugin-scenario)
throw ::com::sun::star::uno::RuntimeException(
OUString( RTL_CONSTASCII_USTRINGPARAM( "Could not create system bitmap!" ) ),
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >() );
//GetpApp()->Exception( EXC_SYSOBJNOTCREATED );
}
mnBitCount = ( nBitCount ? nBitCount : pOutDev->GetBitCount() );
mnOutWidth = nDX;
mnOutHeight = nDY;
mbScreenComp = TRUE;
mbScreenComp = FALSE;
mnAlphaDepth = -1;
// #i59315# init vdev size from system object, when passed a
// SystemGraphicsData. Otherwise, output size will always
// incorrectly stay at (1,1)
if( pData && mpVirDev )
mpVirDev->GetSize(mnOutWidth,mnOutHeight);
if( mnBitCount < 8 )
SetAntialiasing( ANTIALIASING_DISABLE_TEXT );
if ( pOutDev->GetOutDevType() == OUTDEV_PRINTER )
mbScreenComp = FALSE;
else if ( pOutDev->GetOutDevType() == OUTDEV_VIRDEV )
mbScreenComp = ((VirtualDevice*)pOutDev)->mbScreenComp;
meOutDevType = OUTDEV_VIRDEV;
mbDevOutput = TRUE;
mpFontList = pSVData->maGDIData.mpScreenFontList;
mpFontCache = pSVData->maGDIData.mpScreenFontCache;
mnDPIX = pOutDev->mnDPIX;
mnDPIY = pOutDev->mnDPIY;
maFont = pOutDev->maFont;
if( maTextColor != pOutDev->maTextColor )
{
maTextColor = pOutDev->maTextColor;
mbInitTextColor = true;
}
// Virtuelle Devices haben defaultmaessig einen weissen Hintergrund
SetBackground( Wallpaper( Color( COL_WHITE ) ) );
// #i59283# don't erase user-provided surface
if( !pData )
Erase();
// VirDev in Liste eintragen
mpNext = pSVData->maGDIData.mpFirstVirDev;
mpPrev = NULL;
if ( mpNext )
mpNext->mpPrev = this;
else
pSVData->maGDIData.mpLastVirDev = this;
pSVData->maGDIData.mpFirstVirDev = this;
}
// -----------------------------------------------------------------------
VirtualDevice::VirtualDevice( USHORT nBitCount )
: mpVirDev( NULL ),
meRefDevMode( REFDEV_NONE )
{
DBG_TRACE1( "VirtualDevice::VirtualDevice( %hu )", nBitCount );
ImplInitVirDev( Application::GetDefaultDevice(), 1, 1, nBitCount );
}
// -----------------------------------------------------------------------
VirtualDevice::VirtualDevice( const OutputDevice& rCompDev, USHORT nBitCount )
: mpVirDev( NULL ),
meRefDevMode( REFDEV_NONE )
{
DBG_TRACE1( "VirtualDevice::VirtualDevice( %hu )", nBitCount );
ImplInitVirDev( &rCompDev, 1, 1, nBitCount );
}
// -----------------------------------------------------------------------
VirtualDevice::VirtualDevice( const OutputDevice& rCompDev, USHORT nBitCount, USHORT nAlphaBitCount )
: mpVirDev( NULL )
{
DBG_TRACE1( "VirtualDevice::VirtualDevice( %hu )", nBitCount );
ImplInitVirDev( &rCompDev, 1, 1, nBitCount );
// #110958# Enable alpha channel
mnAlphaDepth = sal::static_int_cast<sal_Int8>(nAlphaBitCount);
}
// -----------------------------------------------------------------------
VirtualDevice::VirtualDevice( const SystemGraphicsData *pData, USHORT nBitCount )
: mpVirDev( NULL ),
meRefDevMode( REFDEV_NONE )
{
DBG_TRACE1( "VirtualDevice::VirtualDevice( %hu )", nBitCount );
ImplInitVirDev( Application::GetDefaultDevice(), 1, 1, nBitCount, pData );
}
// -----------------------------------------------------------------------
VirtualDevice::~VirtualDevice()
{
DBG_TRACE( "VirtualDevice::~VirtualDevice()" );
ImplSVData* pSVData = ImplGetSVData();
ImplReleaseGraphics();
if ( mpVirDev )
pSVData->mpDefInst->DestroyVirtualDevice( mpVirDev );
// remove this VirtualDevice from the double-linked global list
if( mpPrev )
mpPrev->mpNext = mpNext;
else
pSVData->maGDIData.mpFirstVirDev = mpNext;
if( mpNext )
mpNext->mpPrev = mpPrev;
else
pSVData->maGDIData.mpLastVirDev = mpPrev;
}
// -----------------------------------------------------------------------
BOOL VirtualDevice::ImplSetOutputSizePixel( const Size& rNewSize, BOOL bErase )
{
DBG_TRACE3( "VirtualDevice::ImplSetOutputSizePixel( %ld, %ld, %d )", rNewSize.Width(), rNewSize.Height(), (int)bErase );
if ( !mpVirDev )
return FALSE;
else if ( rNewSize == GetOutputSizePixel() )
{
if ( bErase )
Erase();
return TRUE;
}
BOOL bRet;
long nNewWidth = rNewSize.Width(), nNewHeight = rNewSize.Height();
if ( nNewWidth < 1 )
nNewWidth = 1;
if ( nNewHeight < 1 )
nNewHeight = 1;
if ( bErase )
{
bRet = mpVirDev->SetSize( nNewWidth, nNewHeight );
if ( bRet )
{
mnOutWidth = rNewSize.Width();
mnOutHeight = rNewSize.Height();
Erase();
}
}
else
{
SalVirtualDevice* pNewVirDev;
ImplSVData* pSVData = ImplGetSVData();
// we need a graphics
if ( !mpGraphics )
{
if ( !ImplGetGraphics() )
return FALSE;
}
pNewVirDev = pSVData->mpDefInst->CreateVirtualDevice( mpGraphics, nNewWidth, nNewHeight, mnBitCount );
if ( pNewVirDev )
{
SalGraphics* pGraphics = pNewVirDev->GetGraphics();
if ( pGraphics )
{
SalTwoRect aPosAry;
long nWidth;
long nHeight;
if ( mnOutWidth < nNewWidth )
nWidth = mnOutWidth;
else
nWidth = nNewWidth;
if ( mnOutHeight < nNewHeight )
nHeight = mnOutHeight;
else
nHeight = nNewHeight;
aPosAry.mnSrcX = 0;
aPosAry.mnSrcY = 0;
aPosAry.mnSrcWidth = nWidth;
aPosAry.mnSrcHeight = nHeight;
aPosAry.mnDestX = 0;
aPosAry.mnDestY = 0;
aPosAry.mnDestWidth = nWidth;
aPosAry.mnDestHeight = nHeight;
pGraphics->CopyBits( &aPosAry, mpGraphics, this, this );
pNewVirDev->ReleaseGraphics( pGraphics );
ImplReleaseGraphics();
pSVData->mpDefInst->DestroyVirtualDevice( mpVirDev );
mpVirDev = pNewVirDev;
mnOutWidth = rNewSize.Width();
mnOutHeight = rNewSize.Height();
bRet = TRUE;
}
else
{
bRet = FALSE;
pSVData->mpDefInst->DestroyVirtualDevice( pNewVirDev );
}
}
else
bRet = FALSE;
}
return bRet;
}
// -----------------------------------------------------------------------
// #i32109#: Fill opaque areas correctly (without relying on
// fill/linecolor state)
void VirtualDevice::ImplFillOpaqueRectangle( const Rectangle& rRect )
{
// Set line and fill color to black (->opaque),
// fill rect with that (linecolor, too, because of
// those pesky missing pixel problems)
Push( PUSH_LINECOLOR | PUSH_FILLCOLOR );
SetLineColor( COL_BLACK );
SetFillColor( COL_BLACK );
DrawRect( rRect );
Pop();
}
// -----------------------------------------------------------------------
BOOL VirtualDevice::SetOutputSizePixel( const Size& rNewSize, BOOL bErase )
{
if( ImplSetOutputSizePixel(rNewSize, bErase) )
{
if( mnAlphaDepth != -1 )
{
// #110958# Setup alpha bitmap
if(mpAlphaVDev && mpAlphaVDev->GetOutputSizePixel() != rNewSize)
{
delete mpAlphaVDev;
mpAlphaVDev = 0L;
}
if( !mpAlphaVDev )
{
mpAlphaVDev = new VirtualDevice( *this, mnAlphaDepth );
mpAlphaVDev->ImplSetOutputSizePixel(rNewSize, bErase);
}
// TODO: copy full outdev state to new one, here. Also needed in outdev2.cxx:DrawOutDev
if( GetLineColor() != Color( COL_TRANSPARENT ) )
mpAlphaVDev->SetLineColor( COL_BLACK );
if( GetFillColor() != Color( COL_TRANSPARENT ) )
mpAlphaVDev->SetFillColor( COL_BLACK );
mpAlphaVDev->SetMapMode( GetMapMode() );
}
return TRUE;
}
return FALSE;
}
// -----------------------------------------------------------------------
void VirtualDevice::SetReferenceDevice( RefDevMode eRefDevMode )
{
switch( eRefDevMode )
{
case REFDEV_NONE:
default:
DBG_ASSERT( FALSE, "VDev::SetRefDev illegal argument!" );
// fall through
case REFDEV_MODE06:
mnDPIX = mnDPIY = 600;
break;
case REFDEV_MODE48:
mnDPIX = mnDPIY = 4800;
break;
case REFDEV_MODE_MSO1:
mnDPIX = mnDPIY = 6*1440;
break;
case REFDEV_MODE_PDF1:
mnDPIX = mnDPIY = 720;
break;
}
EnableOutput( FALSE ); // prevent output on reference device
mbScreenComp = FALSE;
// invalidate currently selected fonts
mbInitFont = TRUE;
mbNewFont = TRUE;
// avoid adjusting font lists when already in refdev mode
BYTE nOldRefDevMode = meRefDevMode;
meRefDevMode = (BYTE)eRefDevMode;
if( nOldRefDevMode != REFDEV_NONE )
return;
// the reference device should have only scalable fonts
// => clean up the original font lists before getting new ones
if ( mpFontEntry )
{
mpFontCache->Release( mpFontEntry );
mpFontEntry = NULL;
}
if ( mpGetDevFontList )
{
delete mpGetDevFontList;
mpGetDevFontList = NULL;
}
if ( mpGetDevSizeList )
{
delete mpGetDevSizeList;
mpGetDevSizeList = NULL;
}
// preserve global font lists
ImplSVData* pSVData = ImplGetSVData();
if( mpFontList && (mpFontList != pSVData->maGDIData.mpScreenFontList) )
delete mpFontList;
if( mpFontCache && (mpFontCache != pSVData->maGDIData.mpScreenFontCache) )
delete mpFontCache;
// get font list with scalable fonts only
ImplGetGraphics();
mpFontList = pSVData->maGDIData.mpScreenFontList->Clone( true, false );
// prepare to use new font lists
mpFontCache = new ImplFontCache( false );
}
// -----------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS pchfix02 (1.26.76); FILE MERGED 2006/09/01 17:57:49 kaib 1.26.76.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: virdev.cxx,v $
*
* $Revision: 1.27 $
*
* last change: $Author: obo $ $Date: 2006-09-17 12:11:55 $
*
* 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_vcl.hxx"
#ifndef _SV_SVSYS_HXX
#include <svsys.h>
#endif
#ifndef _SV_SALINST_HXX
#include <salinst.hxx>
#endif
#ifndef _SV_SALGDI_HXX
#include <salgdi.hxx>
#endif
#ifndef _SV_SALFRAME_HXX
#include <salframe.hxx>
#endif
#ifndef _SV_SALVD_HXX
#include <salvd.hxx>
#endif
#ifndef _DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _SV_SVDATA_HXX
#include <svdata.hxx>
#endif
#ifndef _SV_SETTINGS_HXX
#include <settings.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <svapp.hxx>
#endif
#ifndef _SV_WRKWIN_HXX
#include <wrkwin.hxx>
#endif
#ifndef _SV_OUTDEV_H
#include <outdev.h>
#endif
#ifndef _SV_VIRDEV_HXX
#include <virdev.hxx>
#endif
using namespace ::com::sun::star::uno;
// =======================================================================
void VirtualDevice::ImplInitVirDev( const OutputDevice* pOutDev,
long nDX, long nDY, USHORT nBitCount, const SystemGraphicsData *pData )
{
DBG_ASSERT( nBitCount <= 1,
"VirtualDevice::VirtualDevice(): Only 0 or 1 is for BitCount allowed" );
if ( nDX < 1 )
nDX = 1;
if ( nDY < 1 )
nDY = 1;
ImplSVData* pSVData = ImplGetSVData();
if ( !pOutDev )
pOutDev = ImplGetDefaultWindow();
if( !pOutDev )
return;
SalGraphics* pGraphics;
if ( !pOutDev->mpGraphics )
((OutputDevice*)pOutDev)->ImplGetGraphics();
pGraphics = pOutDev->mpGraphics;
if ( pGraphics )
mpVirDev = pSVData->mpDefInst->CreateVirtualDevice( pGraphics, nDX, nDY, nBitCount, pData );
else
mpVirDev = NULL;
if ( !mpVirDev )
{
// do not abort but throw an exception, may be the current thread terminates anyway (plugin-scenario)
throw ::com::sun::star::uno::RuntimeException(
OUString( RTL_CONSTASCII_USTRINGPARAM( "Could not create system bitmap!" ) ),
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >() );
//GetpApp()->Exception( EXC_SYSOBJNOTCREATED );
}
mnBitCount = ( nBitCount ? nBitCount : pOutDev->GetBitCount() );
mnOutWidth = nDX;
mnOutHeight = nDY;
mbScreenComp = TRUE;
mbScreenComp = FALSE;
mnAlphaDepth = -1;
// #i59315# init vdev size from system object, when passed a
// SystemGraphicsData. Otherwise, output size will always
// incorrectly stay at (1,1)
if( pData && mpVirDev )
mpVirDev->GetSize(mnOutWidth,mnOutHeight);
if( mnBitCount < 8 )
SetAntialiasing( ANTIALIASING_DISABLE_TEXT );
if ( pOutDev->GetOutDevType() == OUTDEV_PRINTER )
mbScreenComp = FALSE;
else if ( pOutDev->GetOutDevType() == OUTDEV_VIRDEV )
mbScreenComp = ((VirtualDevice*)pOutDev)->mbScreenComp;
meOutDevType = OUTDEV_VIRDEV;
mbDevOutput = TRUE;
mpFontList = pSVData->maGDIData.mpScreenFontList;
mpFontCache = pSVData->maGDIData.mpScreenFontCache;
mnDPIX = pOutDev->mnDPIX;
mnDPIY = pOutDev->mnDPIY;
maFont = pOutDev->maFont;
if( maTextColor != pOutDev->maTextColor )
{
maTextColor = pOutDev->maTextColor;
mbInitTextColor = true;
}
// Virtuelle Devices haben defaultmaessig einen weissen Hintergrund
SetBackground( Wallpaper( Color( COL_WHITE ) ) );
// #i59283# don't erase user-provided surface
if( !pData )
Erase();
// VirDev in Liste eintragen
mpNext = pSVData->maGDIData.mpFirstVirDev;
mpPrev = NULL;
if ( mpNext )
mpNext->mpPrev = this;
else
pSVData->maGDIData.mpLastVirDev = this;
pSVData->maGDIData.mpFirstVirDev = this;
}
// -----------------------------------------------------------------------
VirtualDevice::VirtualDevice( USHORT nBitCount )
: mpVirDev( NULL ),
meRefDevMode( REFDEV_NONE )
{
DBG_TRACE1( "VirtualDevice::VirtualDevice( %hu )", nBitCount );
ImplInitVirDev( Application::GetDefaultDevice(), 1, 1, nBitCount );
}
// -----------------------------------------------------------------------
VirtualDevice::VirtualDevice( const OutputDevice& rCompDev, USHORT nBitCount )
: mpVirDev( NULL ),
meRefDevMode( REFDEV_NONE )
{
DBG_TRACE1( "VirtualDevice::VirtualDevice( %hu )", nBitCount );
ImplInitVirDev( &rCompDev, 1, 1, nBitCount );
}
// -----------------------------------------------------------------------
VirtualDevice::VirtualDevice( const OutputDevice& rCompDev, USHORT nBitCount, USHORT nAlphaBitCount )
: mpVirDev( NULL )
{
DBG_TRACE1( "VirtualDevice::VirtualDevice( %hu )", nBitCount );
ImplInitVirDev( &rCompDev, 1, 1, nBitCount );
// #110958# Enable alpha channel
mnAlphaDepth = sal::static_int_cast<sal_Int8>(nAlphaBitCount);
}
// -----------------------------------------------------------------------
VirtualDevice::VirtualDevice( const SystemGraphicsData *pData, USHORT nBitCount )
: mpVirDev( NULL ),
meRefDevMode( REFDEV_NONE )
{
DBG_TRACE1( "VirtualDevice::VirtualDevice( %hu )", nBitCount );
ImplInitVirDev( Application::GetDefaultDevice(), 1, 1, nBitCount, pData );
}
// -----------------------------------------------------------------------
VirtualDevice::~VirtualDevice()
{
DBG_TRACE( "VirtualDevice::~VirtualDevice()" );
ImplSVData* pSVData = ImplGetSVData();
ImplReleaseGraphics();
if ( mpVirDev )
pSVData->mpDefInst->DestroyVirtualDevice( mpVirDev );
// remove this VirtualDevice from the double-linked global list
if( mpPrev )
mpPrev->mpNext = mpNext;
else
pSVData->maGDIData.mpFirstVirDev = mpNext;
if( mpNext )
mpNext->mpPrev = mpPrev;
else
pSVData->maGDIData.mpLastVirDev = mpPrev;
}
// -----------------------------------------------------------------------
BOOL VirtualDevice::ImplSetOutputSizePixel( const Size& rNewSize, BOOL bErase )
{
DBG_TRACE3( "VirtualDevice::ImplSetOutputSizePixel( %ld, %ld, %d )", rNewSize.Width(), rNewSize.Height(), (int)bErase );
if ( !mpVirDev )
return FALSE;
else if ( rNewSize == GetOutputSizePixel() )
{
if ( bErase )
Erase();
return TRUE;
}
BOOL bRet;
long nNewWidth = rNewSize.Width(), nNewHeight = rNewSize.Height();
if ( nNewWidth < 1 )
nNewWidth = 1;
if ( nNewHeight < 1 )
nNewHeight = 1;
if ( bErase )
{
bRet = mpVirDev->SetSize( nNewWidth, nNewHeight );
if ( bRet )
{
mnOutWidth = rNewSize.Width();
mnOutHeight = rNewSize.Height();
Erase();
}
}
else
{
SalVirtualDevice* pNewVirDev;
ImplSVData* pSVData = ImplGetSVData();
// we need a graphics
if ( !mpGraphics )
{
if ( !ImplGetGraphics() )
return FALSE;
}
pNewVirDev = pSVData->mpDefInst->CreateVirtualDevice( mpGraphics, nNewWidth, nNewHeight, mnBitCount );
if ( pNewVirDev )
{
SalGraphics* pGraphics = pNewVirDev->GetGraphics();
if ( pGraphics )
{
SalTwoRect aPosAry;
long nWidth;
long nHeight;
if ( mnOutWidth < nNewWidth )
nWidth = mnOutWidth;
else
nWidth = nNewWidth;
if ( mnOutHeight < nNewHeight )
nHeight = mnOutHeight;
else
nHeight = nNewHeight;
aPosAry.mnSrcX = 0;
aPosAry.mnSrcY = 0;
aPosAry.mnSrcWidth = nWidth;
aPosAry.mnSrcHeight = nHeight;
aPosAry.mnDestX = 0;
aPosAry.mnDestY = 0;
aPosAry.mnDestWidth = nWidth;
aPosAry.mnDestHeight = nHeight;
pGraphics->CopyBits( &aPosAry, mpGraphics, this, this );
pNewVirDev->ReleaseGraphics( pGraphics );
ImplReleaseGraphics();
pSVData->mpDefInst->DestroyVirtualDevice( mpVirDev );
mpVirDev = pNewVirDev;
mnOutWidth = rNewSize.Width();
mnOutHeight = rNewSize.Height();
bRet = TRUE;
}
else
{
bRet = FALSE;
pSVData->mpDefInst->DestroyVirtualDevice( pNewVirDev );
}
}
else
bRet = FALSE;
}
return bRet;
}
// -----------------------------------------------------------------------
// #i32109#: Fill opaque areas correctly (without relying on
// fill/linecolor state)
void VirtualDevice::ImplFillOpaqueRectangle( const Rectangle& rRect )
{
// Set line and fill color to black (->opaque),
// fill rect with that (linecolor, too, because of
// those pesky missing pixel problems)
Push( PUSH_LINECOLOR | PUSH_FILLCOLOR );
SetLineColor( COL_BLACK );
SetFillColor( COL_BLACK );
DrawRect( rRect );
Pop();
}
// -----------------------------------------------------------------------
BOOL VirtualDevice::SetOutputSizePixel( const Size& rNewSize, BOOL bErase )
{
if( ImplSetOutputSizePixel(rNewSize, bErase) )
{
if( mnAlphaDepth != -1 )
{
// #110958# Setup alpha bitmap
if(mpAlphaVDev && mpAlphaVDev->GetOutputSizePixel() != rNewSize)
{
delete mpAlphaVDev;
mpAlphaVDev = 0L;
}
if( !mpAlphaVDev )
{
mpAlphaVDev = new VirtualDevice( *this, mnAlphaDepth );
mpAlphaVDev->ImplSetOutputSizePixel(rNewSize, bErase);
}
// TODO: copy full outdev state to new one, here. Also needed in outdev2.cxx:DrawOutDev
if( GetLineColor() != Color( COL_TRANSPARENT ) )
mpAlphaVDev->SetLineColor( COL_BLACK );
if( GetFillColor() != Color( COL_TRANSPARENT ) )
mpAlphaVDev->SetFillColor( COL_BLACK );
mpAlphaVDev->SetMapMode( GetMapMode() );
}
return TRUE;
}
return FALSE;
}
// -----------------------------------------------------------------------
void VirtualDevice::SetReferenceDevice( RefDevMode eRefDevMode )
{
switch( eRefDevMode )
{
case REFDEV_NONE:
default:
DBG_ASSERT( FALSE, "VDev::SetRefDev illegal argument!" );
// fall through
case REFDEV_MODE06:
mnDPIX = mnDPIY = 600;
break;
case REFDEV_MODE48:
mnDPIX = mnDPIY = 4800;
break;
case REFDEV_MODE_MSO1:
mnDPIX = mnDPIY = 6*1440;
break;
case REFDEV_MODE_PDF1:
mnDPIX = mnDPIY = 720;
break;
}
EnableOutput( FALSE ); // prevent output on reference device
mbScreenComp = FALSE;
// invalidate currently selected fonts
mbInitFont = TRUE;
mbNewFont = TRUE;
// avoid adjusting font lists when already in refdev mode
BYTE nOldRefDevMode = meRefDevMode;
meRefDevMode = (BYTE)eRefDevMode;
if( nOldRefDevMode != REFDEV_NONE )
return;
// the reference device should have only scalable fonts
// => clean up the original font lists before getting new ones
if ( mpFontEntry )
{
mpFontCache->Release( mpFontEntry );
mpFontEntry = NULL;
}
if ( mpGetDevFontList )
{
delete mpGetDevFontList;
mpGetDevFontList = NULL;
}
if ( mpGetDevSizeList )
{
delete mpGetDevSizeList;
mpGetDevSizeList = NULL;
}
// preserve global font lists
ImplSVData* pSVData = ImplGetSVData();
if( mpFontList && (mpFontList != pSVData->maGDIData.mpScreenFontList) )
delete mpFontList;
if( mpFontCache && (mpFontCache != pSVData->maGDIData.mpScreenFontCache) )
delete mpFontCache;
// get font list with scalable fonts only
ImplGetGraphics();
mpFontList = pSVData->maGDIData.mpScreenFontList->Clone( true, false );
// prepare to use new font lists
mpFontCache = new ImplFontCache( false );
}
// -----------------------------------------------------------------------
<|endoftext|> |
<commit_before>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
Bohrium is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the
GNU Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __OPENCL_DTYPE_HPP
#define __OPENCL_DTYPE_HPP
#include <bh_type.h>
// Return OpenCL API types, which are used at the host (not inside the JIT kernels)
const char* write_opencl_api_type(bh_type dtype)
{
switch (dtype)
{
case BH_INT8: return "cl_char";
case BH_INT16: return "cl_short";
case BH_INT32: return "cl_int";
case BH_INT64: return"cl_long";
case BH_UINT8: return "cl_uchar";
case BH_UINT16: return "cl_ushort";
case BH_UINT32: return "cl_uint";
case BH_UINT64: return "cl_ulong";
case BH_FLOAT32: return "cl_float";
case BH_FLOAT64: return "cl_double";
case BH_COMPLEX64: return "cl_float2";
case BH_COMPLEX128: return "cl_double2";
case BH_R123: return "cl_ulong2";
default: throw std::runtime_error("Unknown OCLtype");
}
}
// Return OpenCL API types, which are used inside the JIT kernels
const char* write_opencl_type(bh_type dtype)
{
switch (dtype)
{
case BH_INT8: return "char";
case BH_INT16: return "short";
case BH_INT32: return "int";
case BH_INT64: return"long";
case BH_UINT8: return "uchar";
case BH_UINT16: return "ushort";
case BH_UINT32: return "uint";
case BH_UINT64: return "ulong";
case BH_FLOAT32: return "float";
case BH_FLOAT64: return "double";
case BH_COMPLEX64: return "float2";
case BH_COMPLEX128: return "double2";
case BH_R123: return "ulong2";
default: throw std::runtime_error("Unknown OCLtype");
}
}
#endif
<commit_msg>opencl: added boolean<commit_after>/*
This file is part of Bohrium and copyright (c) 2012 the Bohrium
team <http://www.bh107.org>.
Bohrium is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
Bohrium is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the
GNU Lesser General Public License along with Bohrium.
If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __OPENCL_DTYPE_HPP
#define __OPENCL_DTYPE_HPP
#include <cassert>
#include <bh_type.h>
// Return OpenCL API types, which are used inside the JIT kernels
const char* write_opencl_type(bh_type dtype)
{
switch (dtype)
{
case BH_BOOL: return "bool";
case BH_INT8: return "char";
case BH_INT16: return "short";
case BH_INT32: return "int";
case BH_INT64: return"long";
case BH_UINT8: return "uchar";
case BH_UINT16: return "ushort";
case BH_UINT32: return "uint";
case BH_UINT64: return "ulong";
case BH_FLOAT32: return "float";
case BH_FLOAT64: return "double";
case BH_COMPLEX64: return "float2";
case BH_COMPLEX128: return "double2";
case BH_R123: return "ulong2";
default:
std::cerr << "Unknown OpenCL type: " << bh_type_text(dtype) << std::endl;
throw std::runtime_error("Unknown OpenCL type");
}
}
#endif
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
#include "Adapter/D3D12/Device.hpp"
#include "Adapter/D3D12/Adapter.hpp"
#include "Adapter/D3D12/Instance.hpp"
#include "Adapter/D3D12/CommandPool.hpp"
#include "Adapter/D3D12/CommandBuffer.hpp"
#include "Adapter/D3D12/Fence.hpp"
#include "Adapter/D3D12/SwapChain.hpp"
#include "Adapter/D3D12/Image.hpp"
#include "Adapter/D3D12/Shader.hpp"
#include "Adapter/D3D12/Pipeline.hpp"
#include "Adapter/D3D12/ResourceBinding.hpp"
#include "Adapter/D3D12/Resource.hpp"
#include "Adapter/D3D12/ConstantBuffer.hpp"
#include "Adapter/D3D12/IndexBuffer.hpp"
#include "Adapter/D3D12/VertexBuffer.hpp"
#include "Graphics/BinaryBlob.hpp"
#include "Logging/Logging.hpp"
#include "String.hpp"
using namespace Cpf;
using namespace Adapter;
using namespace D3D12;
Device::Device(Graphics::iAdapter* adapter)
{
#ifdef CPF_DEBUG
ID3D12Debug* debugController = nullptr;
if (FAILED(D3D12GetDebugInterface(IID_PPV_ARGS(&debugController))))
{
// TODO: error.
}
debugController->EnableDebugLayer();
debugController->Release();
#endif
Adapter* d3dAdapter = static_cast<Adapter*>(adapter);
const D3D_FEATURE_LEVEL levels[] =
{
D3D_FEATURE_LEVEL_12_1,
D3D_FEATURE_LEVEL_12_0,
D3D_FEATURE_LEVEL_11_1,
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0,
D3D_FEATURE_LEVEL_9_3,
D3D_FEATURE_LEVEL_9_2,
D3D_FEATURE_LEVEL_9_1
};
const int levelCount = sizeof(levels) / sizeof(D3D_FEATURE_LEVEL);
D3D_FEATURE_LEVEL highestLevel = D3D_FEATURE_LEVEL(0);
for (int i = 0; i < levelCount; ++i)
{
if (SUCCEEDED(D3D12CreateDevice(d3dAdapter->GetD3DAdapter(), levels[i], _uuidof(ID3D12Device), nullptr)))
{
highestLevel = levels[i];
break;
}
}
if (highestLevel != D3D_FEATURE_LEVEL(0))
{
ID3D12Device* d3dDevice = nullptr;
if (SUCCEEDED(D3D12CreateDevice(d3dAdapter->GetD3DAdapter(), highestLevel, IID_PPV_ARGS(&d3dDevice))))
{
mpDevice.Adopt(d3dDevice);
}
}
D3D12_COMMAND_QUEUE_DESC desc;
ZeroMemory(&desc, sizeof(desc));
desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
desc.Priority = D3D12_COMMAND_QUEUE_PRIORITY_NORMAL;
desc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
desc.NodeMask = 0;
mpDevice->CreateCommandQueue(&desc, IID_PPV_ARGS(mpQueue.AsTypePP()));
CPF_LOG(D3D12, Info) << "Created device: " << intptr_t(this) << " - " << intptr_t(mpDevice.Ptr()) << " - " << intptr_t(mpQueue.Ptr());
}
Device::~Device()
{
Shutdown();
CPF_LOG(D3D12, Info) << "Destroyed device: " << intptr_t(this) << " - " << intptr_t(mpDevice.Ptr()) << " - " << intptr_t(mpQueue.Ptr());
}
bool Device::Initialize()
{
return (
mConstantDescriptors.Initialize(this, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, kConstantDescriptors) &&
mSamplerDescriptors.Initialize(this, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, kSamplerDescriptors) &&
mRenderTargetDescriptors.Initialize(this, D3D12_DESCRIPTOR_HEAP_TYPE_RTV, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, kRenderTargetDescriptors) &&
mDepthStencilDescriptors.Initialize(this, D3D12_DESCRIPTOR_HEAP_TYPE_DSV, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, kDepthStencilDescriptors)
);
}
bool Device::Shutdown()
{
return (
mConstantDescriptors.Shutdown() &&
mSamplerDescriptors.Shutdown() &&
mRenderTargetDescriptors.Shutdown() &&
mDepthStencilDescriptors.Shutdown()
);
}
void Device::BeginFrame(Graphics::iCommandBuffer* cmds)
{
CommandBuffer* commands = static_cast<CommandBuffer*>(cmds);
for (auto& item : mUploadQueue)
{
switch (item.mType)
{
case WorkType::eUploadVertexBuffer:
{
const auto& work = item.UploadVertexBuffer;
commands->mpCommandList->CopyResource(work.mpDestination, work.mpSource);
CD3DX12_RESOURCE_BARRIER barrier = CD3DX12_RESOURCE_BARRIER::Transition(work.mpDestination, work.mDstStartState, work.mDstEndState);
commands->mpCommandList->ResourceBarrier(1, &barrier);
work.mpDestination->Release();
mReleaseQueue.push_back(work.mpSource);
}
break;
}
}
mUploadQueue.clear();
}
void Device::EndFrame(Graphics::iCommandBuffer* cmds)
{
(void)cmds;
// CommandBuffer* commands = static_cast<CommandBuffer*>(cmds);
}
void Device::Finalize()
{
for (auto item : mReleaseQueue)
{
item->Release();
}
mReleaseQueue.clear();
}
bool Device::CreateSwapChain(Graphics::iInstance* instance, iWindow* window, const Graphics::SwapChainDesc* desc, Graphics::iSwapChain** swapChain)
{
Graphics::iSwapChain* result = new SwapChain(static_cast<Instance*>(instance), this, window, desc);
if (result)
{
*swapChain = result;
return true;
}
return false;
}
bool Device::CreateCommandPool(Graphics::iCommandPool** pool)
{
CommandPool* result = new CommandPool(this);
if (pool)
{
*pool = result;
return true;
}
return false;
}
bool Device::CreateCommandBuffer(Graphics::iCommandPool* pool, Graphics::iCommandBuffer** buffer)
{
CommandBuffer* result = new CommandBuffer(this, pool);
if (result)
{
*buffer = result;
return true;
}
return false;
}
bool Device::CreateFence(int64_t initValue, Graphics::iFence** fence)
{
Fence* result = new Fence(this, initValue);
if (result)
{
*fence = result;
return true;
}
return false;
}
bool Device::CreateImage2D(const Graphics::ImageDesc* desc, Graphics::iImage** image)
{
Image* result = new Image(this, desc);
if (result)
{
*image = result;
return true;
}
return false;
}
bool Device::CreateShader(Graphics::BinaryBlob* blob, Graphics::iShader** shader)
{
IntrusivePtr<Shader> result(new Shader());
if (result)
{
if (result->LoadFrom(this, blob))
{
*shader = result;
result->AddRef();
return true;
}
}
return false;
}
bool Device::CreateResourceBinding(const Graphics::ResourceBindingDesc* resourceState, Graphics::iResourceBinding** binding)
{
IntrusivePtr<ResourceBinding> resourceBinding(new ResourceBinding(this, resourceState));
if (resourceBinding)
{
resourceBinding->AddRef();
*binding = resourceBinding;
return true;
}
return false;
}
bool Device::CreatePipeline(const Graphics::PipelineStateDesc* desc, Graphics::iResourceBinding* rb, Graphics::iPipeline** pipeline)
{
IntrusivePtr<Pipeline> result(new Pipeline(this, desc, static_cast<const ResourceBinding*>(rb)));
if (result)
{
result->AddRef();
*pipeline = result;
return true;
}
return false;
}
bool Device::CreateResource(const Graphics::ResourceDesc* desc, Graphics::iResource** resource)
{
IntrusivePtr<Resource> result(new Resource(this, desc));
if (result)
{
result->AddRef();
*resource = result;
return true;
}
return false;
}
bool Device::CreateIndexBuffer(Graphics::Format format, Graphics::BufferUsage usage, size_t byteSize, const void* initData, Graphics::iIndexBuffer** indexBuffer)
{
IntrusivePtr<IndexBuffer> result(new IndexBuffer(this, format, usage, byteSize, initData));
if (result)
{
*indexBuffer = result;
result.Abandon();
return true;
}
return false;
}
bool Device::CreateVertexBuffer(Graphics::BufferUsage usage, size_t byteSize, size_t byteStride, const void* initData, Graphics::iVertexBuffer** vertexBuffer)
{
IntrusivePtr<VertexBuffer> result(new VertexBuffer(this, usage, byteSize, byteStride, initData));
if (result)
{
*vertexBuffer = result;
result.Abandon();
return true;
}
return false;
}
bool Device::CreateConstantBuffer(size_t bufferSize, const void* initData, Graphics::iConstantBuffer** cbuf)
{
IntrusivePtr<ConstantBuffer> result(new ConstantBuffer(this, bufferSize, initData));
if (result)
{
*cbuf = result;
result.Abandon();
return true;
}
return false;
}
bool Device::CompileToByteCode(const String& entryPoint, Graphics::ShaderType type, size_t size, char* source, Graphics::BinaryBlob** outBlob)
{
if (size > 0 && source)
{
static const char* shaderTypes[] =
{
"vs_5_0",
"ps_5_0",
"cs_5_0",
"ds_5_0",
"gs_5_0",
"hs_5_0"
};
IntrusivePtr<ID3DBlob> blob;
IntrusivePtr<ID3DBlob> errorBlob;
#if defined(CPF_DEBUG)
UINT compileFlags = D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION;
#else
UINT compileFlags = 0;
#endif
if (SUCCEEDED(D3DCompile(
source,
size,
nullptr,
nullptr,
nullptr,
entryPoint.c_str(),
shaderTypes[size_t(type)],
compileFlags, // Flags1
0, // Flags2
blob.AsTypePP(),
errorBlob.AsTypePP()
)))
{
Graphics::BinaryBlob::Create(blob->GetBufferSize(), blob->GetBufferPointer(), outBlob);
return true;
}
if (errorBlob)
{
String errors;
errors.resize(errorBlob->GetBufferSize());
::memcpy(&errors[0], errorBlob->GetBufferPointer(), errorBlob->GetBufferSize());
CPF_LOG(D3D12, Error) << "Shader compile errors: " << errors;
}
}
return false;
}
bool Device::CreateDepthStencilView(Graphics::iImage* image, const Graphics::DepthStencilViewDesc* dsDesc, Graphics::iImageView** imageView)
{
ImageView* result = new ImageView(this, static_cast<Image*>(image), dsDesc);
if (result)
{
*imageView = result;
return true;
}
return false;
}
bool Device::Signal(Graphics::iFence* fence, int64_t value)
{
auto d3dFence = static_cast<Fence*>(fence);
if (SUCCEEDED(mpQueue->Signal(d3dFence->GetD3DFence(), UINT64(value))))
return true;
return false;
}
void Device::Submit(int32_t count, Graphics::iCommandBuffer** buffers)
{
ID3D12CommandList* commands[64];
for (int i = 0; i < count; ++i)
commands[i] = static_cast<CommandBuffer*>(buffers[i])->GetCommandList();
mpQueue->ExecuteCommandLists(count, commands);
}
DescriptorManager& Device::GetConstantDescriptors()
{
return mConstantDescriptors;
}
DescriptorManager& Device::GetSamplerDescriptors()
{
return mSamplerDescriptors;
}
DescriptorManager& Device::GetRenderTargetViewDescriptors()
{
return mRenderTargetDescriptors;
}
DescriptorManager& Device::GetDepthStencilViewDescriptors()
{
return mDepthStencilDescriptors;
}
void Device::QueueUpload(ID3D12Resource* src, ID3D12Resource* dst, D3D12_RESOURCE_STATES dstStartState, D3D12_RESOURCE_STATES dstEndState)
{
WorkEntry entry;
entry.mType = WorkType::eUploadVertexBuffer;
entry.UploadVertexBuffer.mpSource = src;
entry.UploadVertexBuffer.mpDestination = dst;
entry.UploadVertexBuffer.mDstStartState = dstStartState;
entry.UploadVertexBuffer.mDstEndState = dstEndState;
mUploadQueue.push_back(entry);
}
<commit_msg>Undo the fallback change, 11 is the lowest supported to create a device.<commit_after>//////////////////////////////////////////////////////////////////////////
#include "Adapter/D3D12/Device.hpp"
#include "Adapter/D3D12/Adapter.hpp"
#include "Adapter/D3D12/Instance.hpp"
#include "Adapter/D3D12/CommandPool.hpp"
#include "Adapter/D3D12/CommandBuffer.hpp"
#include "Adapter/D3D12/Fence.hpp"
#include "Adapter/D3D12/SwapChain.hpp"
#include "Adapter/D3D12/Image.hpp"
#include "Adapter/D3D12/Shader.hpp"
#include "Adapter/D3D12/Pipeline.hpp"
#include "Adapter/D3D12/ResourceBinding.hpp"
#include "Adapter/D3D12/Resource.hpp"
#include "Adapter/D3D12/ConstantBuffer.hpp"
#include "Adapter/D3D12/IndexBuffer.hpp"
#include "Adapter/D3D12/VertexBuffer.hpp"
#include "Graphics/BinaryBlob.hpp"
#include "Logging/Logging.hpp"
#include "String.hpp"
using namespace Cpf;
using namespace Adapter;
using namespace D3D12;
Device::Device(Graphics::iAdapter* adapter)
{
#ifdef CPF_DEBUG
ID3D12Debug* debugController = nullptr;
if (FAILED(D3D12GetDebugInterface(IID_PPV_ARGS(&debugController))))
{
// TODO: error.
}
debugController->EnableDebugLayer();
debugController->Release();
#endif
Adapter* d3dAdapter = static_cast<Adapter*>(adapter);
const D3D_FEATURE_LEVEL levels[] =
{
D3D_FEATURE_LEVEL_12_1,
D3D_FEATURE_LEVEL_12_0,
D3D_FEATURE_LEVEL_11_1,
D3D_FEATURE_LEVEL_11_0
};
const int levelCount = sizeof(levels) / sizeof(D3D_FEATURE_LEVEL);
D3D_FEATURE_LEVEL highestLevel = D3D_FEATURE_LEVEL(0);
for (int i = 0; i < levelCount; ++i)
{
if (SUCCEEDED(D3D12CreateDevice(d3dAdapter->GetD3DAdapter(), levels[i], _uuidof(ID3D12Device), nullptr)))
{
highestLevel = levels[i];
break;
}
}
if (highestLevel != D3D_FEATURE_LEVEL(0))
{
ID3D12Device* d3dDevice = nullptr;
if (SUCCEEDED(D3D12CreateDevice(d3dAdapter->GetD3DAdapter(), highestLevel, IID_PPV_ARGS(&d3dDevice))))
{
mpDevice.Adopt(d3dDevice);
}
}
D3D12_COMMAND_QUEUE_DESC desc;
ZeroMemory(&desc, sizeof(desc));
desc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
desc.Priority = D3D12_COMMAND_QUEUE_PRIORITY_NORMAL;
desc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
desc.NodeMask = 0;
mpDevice->CreateCommandQueue(&desc, IID_PPV_ARGS(mpQueue.AsTypePP()));
CPF_LOG(D3D12, Info) << "Created device: " << intptr_t(this) << " - " << intptr_t(mpDevice.Ptr()) << " - " << intptr_t(mpQueue.Ptr());
}
Device::~Device()
{
Shutdown();
CPF_LOG(D3D12, Info) << "Destroyed device: " << intptr_t(this) << " - " << intptr_t(mpDevice.Ptr()) << " - " << intptr_t(mpQueue.Ptr());
}
bool Device::Initialize()
{
return (
mConstantDescriptors.Initialize(this, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, kConstantDescriptors) &&
mSamplerDescriptors.Initialize(this, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, kSamplerDescriptors) &&
mRenderTargetDescriptors.Initialize(this, D3D12_DESCRIPTOR_HEAP_TYPE_RTV, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, kRenderTargetDescriptors) &&
mDepthStencilDescriptors.Initialize(this, D3D12_DESCRIPTOR_HEAP_TYPE_DSV, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, kDepthStencilDescriptors)
);
}
bool Device::Shutdown()
{
return (
mConstantDescriptors.Shutdown() &&
mSamplerDescriptors.Shutdown() &&
mRenderTargetDescriptors.Shutdown() &&
mDepthStencilDescriptors.Shutdown()
);
}
void Device::BeginFrame(Graphics::iCommandBuffer* cmds)
{
CommandBuffer* commands = static_cast<CommandBuffer*>(cmds);
for (auto& item : mUploadQueue)
{
switch (item.mType)
{
case WorkType::eUploadVertexBuffer:
{
const auto& work = item.UploadVertexBuffer;
commands->mpCommandList->CopyResource(work.mpDestination, work.mpSource);
CD3DX12_RESOURCE_BARRIER barrier = CD3DX12_RESOURCE_BARRIER::Transition(work.mpDestination, work.mDstStartState, work.mDstEndState);
commands->mpCommandList->ResourceBarrier(1, &barrier);
work.mpDestination->Release();
mReleaseQueue.push_back(work.mpSource);
}
break;
}
}
mUploadQueue.clear();
}
void Device::EndFrame(Graphics::iCommandBuffer* cmds)
{
(void)cmds;
// CommandBuffer* commands = static_cast<CommandBuffer*>(cmds);
}
void Device::Finalize()
{
for (auto item : mReleaseQueue)
{
item->Release();
}
mReleaseQueue.clear();
}
bool Device::CreateSwapChain(Graphics::iInstance* instance, iWindow* window, const Graphics::SwapChainDesc* desc, Graphics::iSwapChain** swapChain)
{
Graphics::iSwapChain* result = new SwapChain(static_cast<Instance*>(instance), this, window, desc);
if (result)
{
*swapChain = result;
return true;
}
return false;
}
bool Device::CreateCommandPool(Graphics::iCommandPool** pool)
{
CommandPool* result = new CommandPool(this);
if (pool)
{
*pool = result;
return true;
}
return false;
}
bool Device::CreateCommandBuffer(Graphics::iCommandPool* pool, Graphics::iCommandBuffer** buffer)
{
CommandBuffer* result = new CommandBuffer(this, pool);
if (result)
{
*buffer = result;
return true;
}
return false;
}
bool Device::CreateFence(int64_t initValue, Graphics::iFence** fence)
{
Fence* result = new Fence(this, initValue);
if (result)
{
*fence = result;
return true;
}
return false;
}
bool Device::CreateImage2D(const Graphics::ImageDesc* desc, Graphics::iImage** image)
{
Image* result = new Image(this, desc);
if (result)
{
*image = result;
return true;
}
return false;
}
bool Device::CreateShader(Graphics::BinaryBlob* blob, Graphics::iShader** shader)
{
IntrusivePtr<Shader> result(new Shader());
if (result)
{
if (result->LoadFrom(this, blob))
{
*shader = result;
result->AddRef();
return true;
}
}
return false;
}
bool Device::CreateResourceBinding(const Graphics::ResourceBindingDesc* resourceState, Graphics::iResourceBinding** binding)
{
IntrusivePtr<ResourceBinding> resourceBinding(new ResourceBinding(this, resourceState));
if (resourceBinding)
{
resourceBinding->AddRef();
*binding = resourceBinding;
return true;
}
return false;
}
bool Device::CreatePipeline(const Graphics::PipelineStateDesc* desc, Graphics::iResourceBinding* rb, Graphics::iPipeline** pipeline)
{
IntrusivePtr<Pipeline> result(new Pipeline(this, desc, static_cast<const ResourceBinding*>(rb)));
if (result)
{
result->AddRef();
*pipeline = result;
return true;
}
return false;
}
bool Device::CreateResource(const Graphics::ResourceDesc* desc, Graphics::iResource** resource)
{
IntrusivePtr<Resource> result(new Resource(this, desc));
if (result)
{
result->AddRef();
*resource = result;
return true;
}
return false;
}
bool Device::CreateIndexBuffer(Graphics::Format format, Graphics::BufferUsage usage, size_t byteSize, const void* initData, Graphics::iIndexBuffer** indexBuffer)
{
IntrusivePtr<IndexBuffer> result(new IndexBuffer(this, format, usage, byteSize, initData));
if (result)
{
*indexBuffer = result;
result.Abandon();
return true;
}
return false;
}
bool Device::CreateVertexBuffer(Graphics::BufferUsage usage, size_t byteSize, size_t byteStride, const void* initData, Graphics::iVertexBuffer** vertexBuffer)
{
IntrusivePtr<VertexBuffer> result(new VertexBuffer(this, usage, byteSize, byteStride, initData));
if (result)
{
*vertexBuffer = result;
result.Abandon();
return true;
}
return false;
}
bool Device::CreateConstantBuffer(size_t bufferSize, const void* initData, Graphics::iConstantBuffer** cbuf)
{
IntrusivePtr<ConstantBuffer> result(new ConstantBuffer(this, bufferSize, initData));
if (result)
{
*cbuf = result;
result.Abandon();
return true;
}
return false;
}
bool Device::CompileToByteCode(const String& entryPoint, Graphics::ShaderType type, size_t size, char* source, Graphics::BinaryBlob** outBlob)
{
if (size > 0 && source)
{
static const char* shaderTypes[] =
{
"vs_5_0",
"ps_5_0",
"cs_5_0",
"ds_5_0",
"gs_5_0",
"hs_5_0"
};
IntrusivePtr<ID3DBlob> blob;
IntrusivePtr<ID3DBlob> errorBlob;
#if defined(CPF_DEBUG)
UINT compileFlags = D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION;
#else
UINT compileFlags = 0;
#endif
if (SUCCEEDED(D3DCompile(
source,
size,
nullptr,
nullptr,
nullptr,
entryPoint.c_str(),
shaderTypes[size_t(type)],
compileFlags, // Flags1
0, // Flags2
blob.AsTypePP(),
errorBlob.AsTypePP()
)))
{
Graphics::BinaryBlob::Create(blob->GetBufferSize(), blob->GetBufferPointer(), outBlob);
return true;
}
if (errorBlob)
{
String errors;
errors.resize(errorBlob->GetBufferSize());
::memcpy(&errors[0], errorBlob->GetBufferPointer(), errorBlob->GetBufferSize());
CPF_LOG(D3D12, Error) << "Shader compile errors: " << errors;
}
}
return false;
}
bool Device::CreateDepthStencilView(Graphics::iImage* image, const Graphics::DepthStencilViewDesc* dsDesc, Graphics::iImageView** imageView)
{
ImageView* result = new ImageView(this, static_cast<Image*>(image), dsDesc);
if (result)
{
*imageView = result;
return true;
}
return false;
}
bool Device::Signal(Graphics::iFence* fence, int64_t value)
{
auto d3dFence = static_cast<Fence*>(fence);
if (SUCCEEDED(mpQueue->Signal(d3dFence->GetD3DFence(), UINT64(value))))
return true;
return false;
}
void Device::Submit(int32_t count, Graphics::iCommandBuffer** buffers)
{
ID3D12CommandList* commands[64];
for (int i = 0; i < count; ++i)
commands[i] = static_cast<CommandBuffer*>(buffers[i])->GetCommandList();
mpQueue->ExecuteCommandLists(count, commands);
}
DescriptorManager& Device::GetConstantDescriptors()
{
return mConstantDescriptors;
}
DescriptorManager& Device::GetSamplerDescriptors()
{
return mSamplerDescriptors;
}
DescriptorManager& Device::GetRenderTargetViewDescriptors()
{
return mRenderTargetDescriptors;
}
DescriptorManager& Device::GetDepthStencilViewDescriptors()
{
return mDepthStencilDescriptors;
}
void Device::QueueUpload(ID3D12Resource* src, ID3D12Resource* dst, D3D12_RESOURCE_STATES dstStartState, D3D12_RESOURCE_STATES dstEndState)
{
WorkEntry entry;
entry.mType = WorkType::eUploadVertexBuffer;
entry.UploadVertexBuffer.mpSource = src;
entry.UploadVertexBuffer.mpDestination = dst;
entry.UploadVertexBuffer.mDstStartState = dstStartState;
entry.UploadVertexBuffer.mDstEndState = dstEndState;
mUploadQueue.push_back(entry);
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/test/testsupport/fileutils.h"
#include "webrtc/voice_engine/test/auto_test/fixtures/after_streaming_fixture.h"
#include "webrtc/voice_engine/test/auto_test/voe_standard_test.h"
class TestRtpObserver : public webrtc::VoERTPObserver {
public:
TestRtpObserver();
virtual ~TestRtpObserver();
virtual void OnIncomingCSRCChanged(int channel,
unsigned int CSRC,
bool added);
virtual void OnIncomingSSRCChanged(int channel,
unsigned int SSRC);
void Reset();
public:
unsigned int ssrc_[2];
unsigned int csrc_[2][2]; // Stores 2 CSRCs for each channel.
bool added_[2][2];
int size_[2];
};
TestRtpObserver::TestRtpObserver() {
Reset();
}
TestRtpObserver::~TestRtpObserver() {
}
void TestRtpObserver::Reset() {
for (int i = 0; i < 2; i++) {
ssrc_[i] = 0;
csrc_[i][0] = 0;
csrc_[i][1] = 0;
added_[i][0] = false;
added_[i][1] = false;
size_[i] = 0;
}
}
void TestRtpObserver::OnIncomingCSRCChanged(int channel,
unsigned int CSRC,
bool added) {
char msg[128];
sprintf(msg, "=> OnIncomingCSRCChanged(channel=%d, CSRC=%u, added=%d)\n",
channel, CSRC, added);
TEST_LOG("%s", msg);
if (channel > 1)
return; // Not enough memory.
csrc_[channel][size_[channel]] = CSRC;
added_[channel][size_[channel]] = added;
size_[channel]++;
if (size_[channel] == 2)
size_[channel] = 0;
}
void TestRtpObserver::OnIncomingSSRCChanged(int channel,
unsigned int SSRC) {
char msg[128];
sprintf(msg, "\n=> OnIncomingSSRCChanged(channel=%d, SSRC=%u)\n", channel,
SSRC);
TEST_LOG("%s", msg);
ssrc_[channel] = SSRC;
}
class RtcpAppHandler : public webrtc::VoERTCPObserver {
public:
void OnApplicationDataReceived(int channel,
unsigned char sub_type,
unsigned int name,
const unsigned char* data,
unsigned short length_in_bytes);
void Reset();
~RtcpAppHandler() {}
unsigned short length_in_bytes_;
unsigned char data_[256];
unsigned char sub_type_;
unsigned int name_;
};
static const char* const RTCP_CNAME = "Whatever";
class RtpRtcpTest : public AfterStreamingFixture {
protected:
void SetUp() {
// We need a second channel for this test, so set it up.
second_channel_ = voe_base_->CreateChannel();
EXPECT_GE(second_channel_, 0);
transport_ = new LoopBackTransport(voe_network_);
EXPECT_EQ(0, voe_network_->RegisterExternalTransport(second_channel_,
*transport_));
EXPECT_EQ(0, voe_base_->StartReceive(second_channel_));
EXPECT_EQ(0, voe_base_->StartPlayout(second_channel_));
EXPECT_EQ(0, voe_rtp_rtcp_->SetLocalSSRC(second_channel_, 5678));
EXPECT_EQ(0, voe_base_->StartSend(second_channel_));
// We'll set up the RTCP CNAME and SSRC to something arbitrary here.
voe_rtp_rtcp_->SetRTCP_CNAME(channel_, RTCP_CNAME);
}
void TearDown() {
EXPECT_EQ(0, voe_network_->DeRegisterExternalTransport(second_channel_));
voe_base_->DeleteChannel(second_channel_);
delete transport_;
}
int second_channel_;
LoopBackTransport* transport_;
};
void RtcpAppHandler::OnApplicationDataReceived(
const int /*channel*/, unsigned char sub_type,
unsigned int name, const unsigned char* data,
unsigned short length_in_bytes) {
length_in_bytes_ = length_in_bytes;
memcpy(data_, &data[0], length_in_bytes);
sub_type_ = sub_type;
name_ = name;
}
void RtcpAppHandler::Reset() {
length_in_bytes_ = 0;
memset(data_, 0, sizeof(data_));
sub_type_ = 0;
name_ = 0;
}
TEST_F(RtpRtcpTest, RemoteRtcpCnameHasPropagatedToRemoteSide) {
if (!FLAGS_include_timing_dependent_tests) {
TEST_LOG("Skipping test - running in slow execution environment...\n");
return;
}
// We need to sleep a bit here for the name to propagate. For instance,
// 200 milliseconds is not enough, so we'll go with one second here.
Sleep(1000);
char char_buffer[256];
voe_rtp_rtcp_->GetRemoteRTCP_CNAME(channel_, char_buffer);
EXPECT_STREQ(RTCP_CNAME, char_buffer);
}
TEST_F(RtpRtcpTest, SSRCPropagatesCorrectly) {
unsigned int local_ssrc = 1234;
EXPECT_EQ(0, voe_base_->StopSend(channel_));
EXPECT_EQ(0, voe_rtp_rtcp_->SetLocalSSRC(channel_, local_ssrc));
EXPECT_EQ(0, voe_base_->StartSend(channel_));
Sleep(1000);
unsigned int ssrc;
EXPECT_EQ(0, voe_rtp_rtcp_->GetLocalSSRC(channel_, ssrc));
EXPECT_EQ(local_ssrc, ssrc);
EXPECT_EQ(0, voe_rtp_rtcp_->GetRemoteSSRC(channel_, ssrc));
EXPECT_EQ(local_ssrc, ssrc);
}
TEST_F(RtpRtcpTest, RtcpApplicationDefinedPacketsCanBeSentAndReceived) {
RtcpAppHandler rtcp_app_handler;
EXPECT_EQ(0, voe_rtp_rtcp_->RegisterRTCPObserver(
channel_, rtcp_app_handler));
// Send data aligned to 32 bytes.
const char* data = "application-dependent data------";
unsigned short data_length = strlen(data);
unsigned int data_name = 0x41424344; // 'ABCD' in ascii
unsigned char data_subtype = 1;
EXPECT_EQ(0, voe_rtp_rtcp_->SendApplicationDefinedRTCPPacket(
channel_, data_subtype, data_name, data, data_length));
// Ensure the RTP-RTCP process gets scheduled.
Sleep(1000);
// Ensure we received the data in the callback.
EXPECT_EQ(data_length, rtcp_app_handler.length_in_bytes_);
EXPECT_EQ(0, memcmp(data, rtcp_app_handler.data_, data_length));
EXPECT_EQ(data_name, rtcp_app_handler.name_);
EXPECT_EQ(data_subtype, rtcp_app_handler.sub_type_);
EXPECT_EQ(0, voe_rtp_rtcp_->DeRegisterRTCPObserver(channel_));
}
TEST_F(RtpRtcpTest, DisabledRtcpObserverDoesNotReceiveData) {
RtcpAppHandler rtcp_app_handler;
EXPECT_EQ(0, voe_rtp_rtcp_->RegisterRTCPObserver(
channel_, rtcp_app_handler));
// Put observer in a known state before de-registering.
rtcp_app_handler.Reset();
EXPECT_EQ(0, voe_rtp_rtcp_->DeRegisterRTCPObserver(channel_));
const char* data = "whatever";
EXPECT_EQ(0, voe_rtp_rtcp_->SendApplicationDefinedRTCPPacket(
channel_, 1, 0x41424344, data, strlen(data)));
// Ensure the RTP-RTCP process gets scheduled.
Sleep(1000);
// Ensure we received no data.
EXPECT_EQ(0u, rtcp_app_handler.name_);
EXPECT_EQ(0u, rtcp_app_handler.sub_type_);
}
TEST_F(RtpRtcpTest, InsertExtraRTPPacketDealsWithInvalidArguments) {
const char payload_data[8] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H' };
EXPECT_EQ(-1, voe_rtp_rtcp_->InsertExtraRTPPacket(
-1, 0, false, payload_data, 8)) <<
"Should reject: invalid channel.";
EXPECT_EQ(-1, voe_rtp_rtcp_->InsertExtraRTPPacket(
channel_, -1, false, payload_data, 8)) <<
"Should reject: invalid payload type.";
EXPECT_EQ(-1, voe_rtp_rtcp_->InsertExtraRTPPacket(
channel_, 128, false, payload_data, 8)) <<
"Should reject: invalid payload type.";
EXPECT_EQ(-1, voe_rtp_rtcp_->InsertExtraRTPPacket(
channel_, 99, false, NULL, 8)) <<
"Should reject: bad pointer.";
EXPECT_EQ(-1, voe_rtp_rtcp_->InsertExtraRTPPacket(
channel_, 99, false, payload_data, 1500 - 28 + 1)) <<
"Should reject: invalid size.";
}
TEST_F(RtpRtcpTest, CanTransmitExtraRtpPacketsWithoutError) {
const char payload_data[8] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H' };
for (int i = 0; i < 128; ++i) {
// Try both with and without the marker bit set
EXPECT_EQ(0, voe_rtp_rtcp_->InsertExtraRTPPacket(
channel_, i, false, payload_data, 8));
EXPECT_EQ(0, voe_rtp_rtcp_->InsertExtraRTPPacket(
channel_, i, true, payload_data, 8));
}
}
// TODO(xians, phoglund): Re-enable when issue 372 is resolved.
TEST_F(RtpRtcpTest, DISABLED_CanCreateRtpDumpFilesWithoutError) {
// Create two RTP dump files (3 seconds long). You can verify these after
// the test using rtpplay or NetEqRTPplay if you like.
std::string output_path = webrtc::test::OutputPath();
std::string incoming_filename = output_path + "dump_in_3sec.rtp";
std::string outgoing_filename = output_path + "dump_out_3sec.rtp";
EXPECT_EQ(0, voe_rtp_rtcp_->StartRTPDump(
channel_, incoming_filename.c_str(), webrtc::kRtpIncoming));
EXPECT_EQ(0, voe_rtp_rtcp_->StartRTPDump(
channel_, outgoing_filename.c_str(), webrtc::kRtpOutgoing));
Sleep(3000);
EXPECT_EQ(0, voe_rtp_rtcp_->StopRTPDump(channel_, webrtc::kRtpIncoming));
EXPECT_EQ(0, voe_rtp_rtcp_->StopRTPDump(channel_, webrtc::kRtpOutgoing));
}
TEST_F(RtpRtcpTest, ObserverGetsNotifiedOnSsrcChange) {
TestRtpObserver rtcp_observer;
EXPECT_EQ(0, voe_rtp_rtcp_->RegisterRTPObserver(
channel_, rtcp_observer));
rtcp_observer.Reset();
unsigned int new_ssrc = 7777;
EXPECT_EQ(0, voe_base_->StopSend(channel_));
EXPECT_EQ(0, voe_rtp_rtcp_->SetLocalSSRC(channel_, new_ssrc));
EXPECT_EQ(0, voe_base_->StartSend(channel_));
Sleep(500);
// Verify we got the new SSRC.
EXPECT_EQ(new_ssrc, rtcp_observer.ssrc_[0]);
// Now try another SSRC.
unsigned int newer_ssrc = 1717;
EXPECT_EQ(0, voe_base_->StopSend(channel_));
EXPECT_EQ(0, voe_rtp_rtcp_->SetLocalSSRC(channel_, newer_ssrc));
EXPECT_EQ(0, voe_base_->StartSend(channel_));
Sleep(500);
EXPECT_EQ(newer_ssrc, rtcp_observer.ssrc_[0]);
EXPECT_EQ(0, voe_rtp_rtcp_->DeRegisterRTPObserver(channel_));
}
<commit_msg>Default constructor for RtcpAppHandler.<commit_after>/*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/test/testsupport/fileutils.h"
#include "webrtc/voice_engine/test/auto_test/fixtures/after_streaming_fixture.h"
#include "webrtc/voice_engine/test/auto_test/voe_standard_test.h"
class TestRtpObserver : public webrtc::VoERTPObserver {
public:
TestRtpObserver();
virtual ~TestRtpObserver();
virtual void OnIncomingCSRCChanged(int channel,
unsigned int CSRC,
bool added);
virtual void OnIncomingSSRCChanged(int channel,
unsigned int SSRC);
void Reset();
public:
unsigned int ssrc_[2];
unsigned int csrc_[2][2]; // Stores 2 CSRCs for each channel.
bool added_[2][2];
int size_[2];
};
TestRtpObserver::TestRtpObserver() {
Reset();
}
TestRtpObserver::~TestRtpObserver() {
}
void TestRtpObserver::Reset() {
for (int i = 0; i < 2; i++) {
ssrc_[i] = 0;
csrc_[i][0] = 0;
csrc_[i][1] = 0;
added_[i][0] = false;
added_[i][1] = false;
size_[i] = 0;
}
}
void TestRtpObserver::OnIncomingCSRCChanged(int channel,
unsigned int CSRC,
bool added) {
char msg[128];
sprintf(msg, "=> OnIncomingCSRCChanged(channel=%d, CSRC=%u, added=%d)\n",
channel, CSRC, added);
TEST_LOG("%s", msg);
if (channel > 1)
return; // Not enough memory.
csrc_[channel][size_[channel]] = CSRC;
added_[channel][size_[channel]] = added;
size_[channel]++;
if (size_[channel] == 2)
size_[channel] = 0;
}
void TestRtpObserver::OnIncomingSSRCChanged(int channel,
unsigned int SSRC) {
char msg[128];
sprintf(msg, "\n=> OnIncomingSSRCChanged(channel=%d, SSRC=%u)\n", channel,
SSRC);
TEST_LOG("%s", msg);
ssrc_[channel] = SSRC;
}
class RtcpAppHandler : public webrtc::VoERTCPObserver {
public:
RtcpAppHandler() : length_in_bytes_(0), sub_type_(0), name_(0) {}
void OnApplicationDataReceived(int channel,
unsigned char sub_type,
unsigned int name,
const unsigned char* data,
unsigned short length_in_bytes);
void Reset();
~RtcpAppHandler() {}
unsigned short length_in_bytes_;
unsigned char data_[256];
unsigned char sub_type_;
unsigned int name_;
};
static const char* const RTCP_CNAME = "Whatever";
class RtpRtcpTest : public AfterStreamingFixture {
protected:
void SetUp() {
// We need a second channel for this test, so set it up.
second_channel_ = voe_base_->CreateChannel();
EXPECT_GE(second_channel_, 0);
transport_ = new LoopBackTransport(voe_network_);
EXPECT_EQ(0, voe_network_->RegisterExternalTransport(second_channel_,
*transport_));
EXPECT_EQ(0, voe_base_->StartReceive(second_channel_));
EXPECT_EQ(0, voe_base_->StartPlayout(second_channel_));
EXPECT_EQ(0, voe_rtp_rtcp_->SetLocalSSRC(second_channel_, 5678));
EXPECT_EQ(0, voe_base_->StartSend(second_channel_));
// We'll set up the RTCP CNAME and SSRC to something arbitrary here.
voe_rtp_rtcp_->SetRTCP_CNAME(channel_, RTCP_CNAME);
}
void TearDown() {
EXPECT_EQ(0, voe_network_->DeRegisterExternalTransport(second_channel_));
voe_base_->DeleteChannel(second_channel_);
delete transport_;
}
int second_channel_;
LoopBackTransport* transport_;
};
void RtcpAppHandler::OnApplicationDataReceived(
const int /*channel*/, unsigned char sub_type,
unsigned int name, const unsigned char* data,
unsigned short length_in_bytes) {
length_in_bytes_ = length_in_bytes;
memcpy(data_, &data[0], length_in_bytes);
sub_type_ = sub_type;
name_ = name;
}
void RtcpAppHandler::Reset() {
length_in_bytes_ = 0;
memset(data_, 0, sizeof(data_));
sub_type_ = 0;
name_ = 0;
}
TEST_F(RtpRtcpTest, RemoteRtcpCnameHasPropagatedToRemoteSide) {
if (!FLAGS_include_timing_dependent_tests) {
TEST_LOG("Skipping test - running in slow execution environment...\n");
return;
}
// We need to sleep a bit here for the name to propagate. For instance,
// 200 milliseconds is not enough, so we'll go with one second here.
Sleep(1000);
char char_buffer[256];
voe_rtp_rtcp_->GetRemoteRTCP_CNAME(channel_, char_buffer);
EXPECT_STREQ(RTCP_CNAME, char_buffer);
}
TEST_F(RtpRtcpTest, SSRCPropagatesCorrectly) {
unsigned int local_ssrc = 1234;
EXPECT_EQ(0, voe_base_->StopSend(channel_));
EXPECT_EQ(0, voe_rtp_rtcp_->SetLocalSSRC(channel_, local_ssrc));
EXPECT_EQ(0, voe_base_->StartSend(channel_));
Sleep(1000);
unsigned int ssrc;
EXPECT_EQ(0, voe_rtp_rtcp_->GetLocalSSRC(channel_, ssrc));
EXPECT_EQ(local_ssrc, ssrc);
EXPECT_EQ(0, voe_rtp_rtcp_->GetRemoteSSRC(channel_, ssrc));
EXPECT_EQ(local_ssrc, ssrc);
}
TEST_F(RtpRtcpTest, RtcpApplicationDefinedPacketsCanBeSentAndReceived) {
RtcpAppHandler rtcp_app_handler;
EXPECT_EQ(0, voe_rtp_rtcp_->RegisterRTCPObserver(
channel_, rtcp_app_handler));
// Send data aligned to 32 bytes.
const char* data = "application-dependent data------";
unsigned short data_length = strlen(data);
unsigned int data_name = 0x41424344; // 'ABCD' in ascii
unsigned char data_subtype = 1;
EXPECT_EQ(0, voe_rtp_rtcp_->SendApplicationDefinedRTCPPacket(
channel_, data_subtype, data_name, data, data_length));
// Ensure the RTP-RTCP process gets scheduled.
Sleep(1000);
// Ensure we received the data in the callback.
ASSERT_EQ(data_length, rtcp_app_handler.length_in_bytes_);
EXPECT_EQ(0, memcmp(data, rtcp_app_handler.data_, data_length));
EXPECT_EQ(data_name, rtcp_app_handler.name_);
EXPECT_EQ(data_subtype, rtcp_app_handler.sub_type_);
EXPECT_EQ(0, voe_rtp_rtcp_->DeRegisterRTCPObserver(channel_));
}
TEST_F(RtpRtcpTest, DisabledRtcpObserverDoesNotReceiveData) {
RtcpAppHandler rtcp_app_handler;
EXPECT_EQ(0, voe_rtp_rtcp_->RegisterRTCPObserver(
channel_, rtcp_app_handler));
// Put observer in a known state before de-registering.
rtcp_app_handler.Reset();
EXPECT_EQ(0, voe_rtp_rtcp_->DeRegisterRTCPObserver(channel_));
const char* data = "whatever";
EXPECT_EQ(0, voe_rtp_rtcp_->SendApplicationDefinedRTCPPacket(
channel_, 1, 0x41424344, data, strlen(data)));
// Ensure the RTP-RTCP process gets scheduled.
Sleep(1000);
// Ensure we received no data.
EXPECT_EQ(0u, rtcp_app_handler.name_);
EXPECT_EQ(0u, rtcp_app_handler.sub_type_);
}
TEST_F(RtpRtcpTest, InsertExtraRTPPacketDealsWithInvalidArguments) {
const char payload_data[8] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H' };
EXPECT_EQ(-1, voe_rtp_rtcp_->InsertExtraRTPPacket(
-1, 0, false, payload_data, 8)) <<
"Should reject: invalid channel.";
EXPECT_EQ(-1, voe_rtp_rtcp_->InsertExtraRTPPacket(
channel_, -1, false, payload_data, 8)) <<
"Should reject: invalid payload type.";
EXPECT_EQ(-1, voe_rtp_rtcp_->InsertExtraRTPPacket(
channel_, 128, false, payload_data, 8)) <<
"Should reject: invalid payload type.";
EXPECT_EQ(-1, voe_rtp_rtcp_->InsertExtraRTPPacket(
channel_, 99, false, NULL, 8)) <<
"Should reject: bad pointer.";
EXPECT_EQ(-1, voe_rtp_rtcp_->InsertExtraRTPPacket(
channel_, 99, false, payload_data, 1500 - 28 + 1)) <<
"Should reject: invalid size.";
}
TEST_F(RtpRtcpTest, CanTransmitExtraRtpPacketsWithoutError) {
const char payload_data[8] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H' };
for (int i = 0; i < 128; ++i) {
// Try both with and without the marker bit set
EXPECT_EQ(0, voe_rtp_rtcp_->InsertExtraRTPPacket(
channel_, i, false, payload_data, 8));
EXPECT_EQ(0, voe_rtp_rtcp_->InsertExtraRTPPacket(
channel_, i, true, payload_data, 8));
}
}
// TODO(xians, phoglund): Re-enable when issue 372 is resolved.
TEST_F(RtpRtcpTest, DISABLED_CanCreateRtpDumpFilesWithoutError) {
// Create two RTP dump files (3 seconds long). You can verify these after
// the test using rtpplay or NetEqRTPplay if you like.
std::string output_path = webrtc::test::OutputPath();
std::string incoming_filename = output_path + "dump_in_3sec.rtp";
std::string outgoing_filename = output_path + "dump_out_3sec.rtp";
EXPECT_EQ(0, voe_rtp_rtcp_->StartRTPDump(
channel_, incoming_filename.c_str(), webrtc::kRtpIncoming));
EXPECT_EQ(0, voe_rtp_rtcp_->StartRTPDump(
channel_, outgoing_filename.c_str(), webrtc::kRtpOutgoing));
Sleep(3000);
EXPECT_EQ(0, voe_rtp_rtcp_->StopRTPDump(channel_, webrtc::kRtpIncoming));
EXPECT_EQ(0, voe_rtp_rtcp_->StopRTPDump(channel_, webrtc::kRtpOutgoing));
}
TEST_F(RtpRtcpTest, ObserverGetsNotifiedOnSsrcChange) {
TestRtpObserver rtcp_observer;
EXPECT_EQ(0, voe_rtp_rtcp_->RegisterRTPObserver(
channel_, rtcp_observer));
rtcp_observer.Reset();
unsigned int new_ssrc = 7777;
EXPECT_EQ(0, voe_base_->StopSend(channel_));
EXPECT_EQ(0, voe_rtp_rtcp_->SetLocalSSRC(channel_, new_ssrc));
EXPECT_EQ(0, voe_base_->StartSend(channel_));
Sleep(500);
// Verify we got the new SSRC.
EXPECT_EQ(new_ssrc, rtcp_observer.ssrc_[0]);
// Now try another SSRC.
unsigned int newer_ssrc = 1717;
EXPECT_EQ(0, voe_base_->StopSend(channel_));
EXPECT_EQ(0, voe_rtp_rtcp_->SetLocalSSRC(channel_, newer_ssrc));
EXPECT_EQ(0, voe_base_->StartSend(channel_));
Sleep(500);
EXPECT_EQ(newer_ssrc, rtcp_observer.ssrc_[0]);
EXPECT_EQ(0, voe_rtp_rtcp_->DeRegisterRTPObserver(channel_));
}
<|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/string_util.h"
#include "webkit/glue/media/media_resource_loader_bridge_factory.h"
namespace {
// A constant for an unknown position.
const int64 kPositionNotSpecified = -1;
} // namespace
namespace webkit_glue {
MediaResourceLoaderBridgeFactory::MediaResourceLoaderBridgeFactory(
const GURL& referrer,
const std::string& frame_origin,
const std::string& main_frame_origin,
int origin_pid,
int app_cache_context_id,
int32 routing_id)
: referrer_(referrer),
frame_origin_(frame_origin),
main_frame_origin_(main_frame_origin),
origin_pid_(origin_pid),
app_cache_context_id_(app_cache_context_id),
routing_id_(routing_id) {
}
ResourceLoaderBridge* MediaResourceLoaderBridgeFactory::CreateBridge(
const GURL& url,
int load_flags,
int64 first_byte_position,
int64 last_byte_position) {
return webkit_glue::ResourceLoaderBridge::Create(
"GET",
url,
url,
referrer_,
frame_origin_,
main_frame_origin_,
GenerateHeaders(first_byte_position, last_byte_position),
load_flags,
origin_pid_,
ResourceType::MEDIA,
app_cache_context_id_,
routing_id_);
}
// static
const std::string MediaResourceLoaderBridgeFactory::GenerateHeaders (
int64 first_byte_position, int64 last_byte_position) {
// Construct the range header.
std::string header;
if (first_byte_position > kPositionNotSpecified &&
last_byte_position > kPositionNotSpecified) {
if (first_byte_position <= last_byte_position) {
header = StringPrintf("Range: bytes=%lld-%lld",
first_byte_position,
last_byte_position);
}
} else if (first_byte_position > kPositionNotSpecified) {
header = StringPrintf("Range: bytes=%lld-", first_byte_position);
} else {
NOTIMPLEMENTED() << "Operation not supported.";
}
return header;
}
} // namespace webkit_glue
<commit_msg>Logic in MediaResourceLoaderBridgeFactory was wrong The logic outputs an extra "Not implemented" message for a correct case, and this extra message causes some layout tests to fail..<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 "base/string_util.h"
#include "webkit/glue/media/media_resource_loader_bridge_factory.h"
namespace {
// A constant for an unknown position.
const int64 kPositionNotSpecified = -1;
} // namespace
namespace webkit_glue {
MediaResourceLoaderBridgeFactory::MediaResourceLoaderBridgeFactory(
const GURL& referrer,
const std::string& frame_origin,
const std::string& main_frame_origin,
int origin_pid,
int app_cache_context_id,
int32 routing_id)
: referrer_(referrer),
frame_origin_(frame_origin),
main_frame_origin_(main_frame_origin),
origin_pid_(origin_pid),
app_cache_context_id_(app_cache_context_id),
routing_id_(routing_id) {
}
ResourceLoaderBridge* MediaResourceLoaderBridgeFactory::CreateBridge(
const GURL& url,
int load_flags,
int64 first_byte_position,
int64 last_byte_position) {
return webkit_glue::ResourceLoaderBridge::Create(
"GET",
url,
url,
referrer_,
frame_origin_,
main_frame_origin_,
GenerateHeaders(first_byte_position, last_byte_position),
load_flags,
origin_pid_,
ResourceType::MEDIA,
app_cache_context_id_,
routing_id_);
}
// static
const std::string MediaResourceLoaderBridgeFactory::GenerateHeaders (
int64 first_byte_position, int64 last_byte_position) {
// Construct the range header.
std::string header;
if (first_byte_position > kPositionNotSpecified &&
last_byte_position > kPositionNotSpecified) {
if (first_byte_position <= last_byte_position) {
header = StringPrintf("Range: bytes=%lld-%lld",
first_byte_position,
last_byte_position);
}
} else if (first_byte_position > kPositionNotSpecified) {
header = StringPrintf("Range: bytes=%lld-", first_byte_position);
} else if (last_byte_position > kPositionNotSpecified) {
NOTIMPLEMENTED() << "Suffix range not implemented";
}
return header;
}
} // namespace webkit_glue
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of Intel Corporation may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//
//
// The code has been contributed by Justin G. Eskesen on 2010 Jan
//
#include "precomp.hpp"
#ifdef HAVE_PVAPI
#if !defined WIN32 && !defined _WIN32 && !defined _LINUX
#define _LINUX
#endif
#if defined(_x64) || defined (__x86_64) || defined (_WIN64)
#define _x64 1
#elif defined(_x86) || defined(__i386) || defined (_WIN32)
#define _x86 1
#endif
#include <PvApi.h>
#include <unistd.h>
//#include <arpa/inet.h>
#define MAX_CAMERAS 10
/********************* Capturing video from camera via PvAPI *********************/
class CvCaptureCAM_PvAPI : public CvCapture
{
public:
CvCaptureCAM_PvAPI();
virtual ~CvCaptureCAM_PvAPI()
{
close();
}
virtual bool open( int index );
virtual void close();
virtual double getProperty(int);
virtual bool setProperty(int, double);
virtual bool grabFrame();
virtual IplImage* retrieveFrame(int);
virtual int getCaptureDomain()
{
return CV_CAP_PVAPI;
}
protected:
virtual void Sleep(unsigned int time);
typedef struct
{
unsigned long UID;
tPvHandle Handle;
tPvFrame Frame;
} tCamera;
IplImage *frame;
IplImage *grayframe;
tCamera Camera;
tPvErr Errcode;
bool monocrome;
};
CvCaptureCAM_PvAPI::CvCaptureCAM_PvAPI()
{
monocrome=false;
}
void CvCaptureCAM_PvAPI::Sleep(unsigned int time)
{
struct timespec t,r;
t.tv_sec = time / 1000;
t.tv_nsec = (time % 1000) * 1000000;
while(nanosleep(&t,&r)==-1)
t = r;
}
void CvCaptureCAM_PvAPI::close()
{
// Stop the acquisition & free the camera
PvCommandRun(Camera.Handle, "AcquisitionStop");
PvCaptureEnd(Camera.Handle);
PvCameraClose(Camera.Handle);
}
// Initialize camera input
bool CvCaptureCAM_PvAPI::open( int index )
{
tPvCameraInfo cameraList[MAX_CAMERAS];
tPvCameraInfo camInfo;
tPvIpSettings ipSettings;
if (PvInitialize())
return false;
Sleep(1000);
//close();
int numCameras=PvCameraList(cameraList, MAX_CAMERAS, NULL);
if (numCameras <= 0 || index >= numCameras)
return false;
Camera.UID = cameraList[index].UniqueId;
if (!PvCameraInfo(Camera.UID,&camInfo) && !PvCameraIpSettingsGet(Camera.UID,&ipSettings)) {
/*
struct in_addr addr;
addr.s_addr = ipSettings.CurrentIpAddress;
printf("Current address:\t%s\n",inet_ntoa(addr));
addr.s_addr = ipSettings.CurrentIpSubnet;
printf("Current subnet:\t\t%s\n",inet_ntoa(addr));
addr.s_addr = ipSettings.CurrentIpGateway;
printf("Current gateway:\t%s\n",inet_ntoa(addr));
*/
}
else {
fprintf(stderr,"ERROR: could not retrieve camera IP settings.\n");
return false;
}
if (PvCameraOpen(Camera.UID, ePvAccessMaster, &(Camera.Handle))==ePvErrSuccess)
{
//Set Pixel Format to BRG24 to follow conventions
/*Errcode = PvAttrEnumSet(Camera.Handle, "PixelFormat", "Bgr24");
if (Errcode != ePvErrSuccess)
{
fprintf(stderr, "PvAPI: couldn't set PixelFormat to Bgr24\n");
return NULL;
}
*/
tPvUint32 frameWidth, frameHeight, frameSize, maxSize;
char pixelFormat[256];
PvAttrUint32Get(Camera.Handle, "TotalBytesPerFrame", &frameSize);
PvAttrUint32Get(Camera.Handle, "Width", &frameWidth);
PvAttrUint32Get(Camera.Handle, "Height", &frameHeight);
PvAttrEnumGet(Camera.Handle, "PixelFormat", pixelFormat,256,NULL);
maxSize = 8228;
PvAttrUint32Get(Camera.Handle,"PacketSize",&maxSize);
if (PvCaptureAdjustPacketSize(Camera.Handle,maxSize)!=ePvErrSuccess)
return false;
//printf ("Pixel Format %s %d %d\n ", pixelFormat,frameWidth,frameHeight);
if (strncmp(pixelFormat, "Mono8",NULL)==0) {
grayframe = cvCreateImage(cvSize((int)frameWidth, (int)frameHeight), IPL_DEPTH_8U, 1);
grayframe->widthStep = (int)frameWidth;
frame = cvCreateImage(cvSize((int)frameWidth, (int)frameHeight), IPL_DEPTH_8U, 3);
frame->widthStep = (int)frameWidth*3;
Camera.Frame.ImageBufferSize = frameSize;
Camera.Frame.ImageBuffer = grayframe->imageData;
}
else if (strncmp(pixelFormat, "Mono16",NULL)==0) {
grayframe = cvCreateImage(cvSize((int)frameWidth, (int)frameHeight), IPL_DEPTH_16U, 1);
grayframe->widthStep = (int)frameWidth;
frame = cvCreateImage(cvSize((int)frameWidth, (int)frameHeight), IPL_DEPTH_16U, 3);
frame->widthStep = (int)frameWidth*3;
Camera.Frame.ImageBufferSize = frameSize;
Camera.Frame.ImageBuffer = grayframe->imageData;
}
else if (strncmp(pixelFormat, "Bgr24",NULL)==0) {
frame = cvCreateImage(cvSize((int)frameWidth, (int)frameHeight), IPL_DEPTH_8U, 3);
frame->widthStep = (int)frameWidth*3;
Camera.Frame.ImageBufferSize = frameSize;
Camera.Frame.ImageBuffer = frame->imageData;
}
else
return false;
// Start the camera
PvCaptureStart(Camera.Handle);
// Set the camera to capture continuously
if(PvAttrEnumSet(Camera.Handle, "AcquisitionMode", "Continuous")!= ePvErrSuccess)
{
fprintf(stderr,"Could not set Prosilica Acquisition Mode\n");
return false;
}
if(PvCommandRun(Camera.Handle, "AcquisitionStart")!= ePvErrSuccess)
{
fprintf(stderr,"Could not start Prosilica acquisition\n");
return false;
}
if(PvAttrEnumSet(Camera.Handle, "FrameStartTriggerMode", "Freerun")!= ePvErrSuccess)
{
fprintf(stderr,"Error setting Prosilica trigger to \"Freerun\"");
return false;
}
return true;
}
fprintf(stderr,"Error cannot open camera\n");
return false;
}
bool CvCaptureCAM_PvAPI::grabFrame()
{
//if(Camera.Frame.Status != ePvErrUnplugged && Camera.Frame.Status != ePvErrCancelled)
return PvCaptureQueueFrame(Camera.Handle, &(Camera.Frame), NULL) == ePvErrSuccess;
}
IplImage* CvCaptureCAM_PvAPI::retrieveFrame(int)
{
if (PvCaptureWaitForFrameDone(Camera.Handle, &(Camera.Frame), 1000) == ePvErrSuccess) {
if (!monocrome)
cvMerge(grayframe,grayframe,grayframe,NULL,frame);
printf("Frame ok\n");
return frame;
}
else return NULL;
}
double CvCaptureCAM_PvAPI::getProperty( int property_id )
{
tPvUint32 nTemp;
switch ( property_id )
{
case CV_CAP_PROP_FRAME_WIDTH:
PvAttrUint32Get(Camera.Handle, "Width", &nTemp);
return (double)nTemp;
case CV_CAP_PROP_FRAME_HEIGHT:
PvAttrUint32Get(Camera.Handle, "Height", &nTemp);
return (double)nTemp;
}
return -1.0;
}
bool CvCaptureCAM_PvAPI::setProperty( int property_id, double value )
{
switch ( property_id )
{
/* TODO: Camera works, but IplImage must be modified for the new size
case CV_CAP_PROP_FRAME_WIDTH:
PvAttrUint32Set(Camera.Handle, "Width", (tPvUint32)value);
break;
case CV_CAP_PROP_FRAME_HEIGHT:
PvAttrUint32Set(Camera.Handle, "Heigth", (tPvUint32)value);
break;
*/
case CV_CAP_PROP_MONOCROME:
char pixelFormat[256];
PvAttrEnumGet(Camera.Handle, "PixelFormat", pixelFormat,256,NULL);
if ((strncmp(pixelFormat, "Mono8",NULL)==0) || strncmp(pixelFormat, "Mono16",NULL)==0) {
monocrome=true;
break;
}
else
return false;
default:
return false;
}
return true;
}
CvCapture* cvCreateCameraCapture_PvAPI( int index )
{
CvCaptureCAM_PvAPI* capture = new CvCaptureCAM_PvAPI;
if ( capture->open( index ))
return capture;
delete capture;
return NULL;
}
#ifdef _MSC_VER
#pragma comment(lib, "PvAPI.lib")
#endif
#endif
<commit_msg>Removed a debug print<commit_after>////////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of Intel Corporation may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//
//
// The code has been contributed by Justin G. Eskesen on 2010 Jan
//
#include "precomp.hpp"
#ifdef HAVE_PVAPI
#if !defined WIN32 && !defined _WIN32 && !defined _LINUX
#define _LINUX
#endif
#if defined(_x64) || defined (__x86_64) || defined (_WIN64)
#define _x64 1
#elif defined(_x86) || defined(__i386) || defined (_WIN32)
#define _x86 1
#endif
#include <PvApi.h>
#include <unistd.h>
//#include <arpa/inet.h>
#define MAX_CAMERAS 10
/********************* Capturing video from camera via PvAPI *********************/
class CvCaptureCAM_PvAPI : public CvCapture
{
public:
CvCaptureCAM_PvAPI();
virtual ~CvCaptureCAM_PvAPI()
{
close();
}
virtual bool open( int index );
virtual void close();
virtual double getProperty(int);
virtual bool setProperty(int, double);
virtual bool grabFrame();
virtual IplImage* retrieveFrame(int);
virtual int getCaptureDomain()
{
return CV_CAP_PVAPI;
}
protected:
virtual void Sleep(unsigned int time);
typedef struct
{
unsigned long UID;
tPvHandle Handle;
tPvFrame Frame;
} tCamera;
IplImage *frame;
IplImage *grayframe;
tCamera Camera;
tPvErr Errcode;
bool monocrome;
};
CvCaptureCAM_PvAPI::CvCaptureCAM_PvAPI()
{
monocrome=false;
}
void CvCaptureCAM_PvAPI::Sleep(unsigned int time)
{
struct timespec t,r;
t.tv_sec = time / 1000;
t.tv_nsec = (time % 1000) * 1000000;
while(nanosleep(&t,&r)==-1)
t = r;
}
void CvCaptureCAM_PvAPI::close()
{
// Stop the acquisition & free the camera
PvCommandRun(Camera.Handle, "AcquisitionStop");
PvCaptureEnd(Camera.Handle);
PvCameraClose(Camera.Handle);
}
// Initialize camera input
bool CvCaptureCAM_PvAPI::open( int index )
{
tPvCameraInfo cameraList[MAX_CAMERAS];
tPvCameraInfo camInfo;
tPvIpSettings ipSettings;
if (PvInitialize())
return false;
Sleep(1000);
//close();
int numCameras=PvCameraList(cameraList, MAX_CAMERAS, NULL);
if (numCameras <= 0 || index >= numCameras)
return false;
Camera.UID = cameraList[index].UniqueId;
if (!PvCameraInfo(Camera.UID,&camInfo) && !PvCameraIpSettingsGet(Camera.UID,&ipSettings)) {
/*
struct in_addr addr;
addr.s_addr = ipSettings.CurrentIpAddress;
printf("Current address:\t%s\n",inet_ntoa(addr));
addr.s_addr = ipSettings.CurrentIpSubnet;
printf("Current subnet:\t\t%s\n",inet_ntoa(addr));
addr.s_addr = ipSettings.CurrentIpGateway;
printf("Current gateway:\t%s\n",inet_ntoa(addr));
*/
}
else {
fprintf(stderr,"ERROR: could not retrieve camera IP settings.\n");
return false;
}
if (PvCameraOpen(Camera.UID, ePvAccessMaster, &(Camera.Handle))==ePvErrSuccess)
{
//Set Pixel Format to BRG24 to follow conventions
/*Errcode = PvAttrEnumSet(Camera.Handle, "PixelFormat", "Bgr24");
if (Errcode != ePvErrSuccess)
{
fprintf(stderr, "PvAPI: couldn't set PixelFormat to Bgr24\n");
return NULL;
}
*/
tPvUint32 frameWidth, frameHeight, frameSize, maxSize;
char pixelFormat[256];
PvAttrUint32Get(Camera.Handle, "TotalBytesPerFrame", &frameSize);
PvAttrUint32Get(Camera.Handle, "Width", &frameWidth);
PvAttrUint32Get(Camera.Handle, "Height", &frameHeight);
PvAttrEnumGet(Camera.Handle, "PixelFormat", pixelFormat,256,NULL);
maxSize = 8228;
PvAttrUint32Get(Camera.Handle,"PacketSize",&maxSize);
if (PvCaptureAdjustPacketSize(Camera.Handle,maxSize)!=ePvErrSuccess)
return false;
//printf ("Pixel Format %s %d %d\n ", pixelFormat,frameWidth,frameHeight);
if (strncmp(pixelFormat, "Mono8",NULL)==0) {
grayframe = cvCreateImage(cvSize((int)frameWidth, (int)frameHeight), IPL_DEPTH_8U, 1);
grayframe->widthStep = (int)frameWidth;
frame = cvCreateImage(cvSize((int)frameWidth, (int)frameHeight), IPL_DEPTH_8U, 3);
frame->widthStep = (int)frameWidth*3;
Camera.Frame.ImageBufferSize = frameSize;
Camera.Frame.ImageBuffer = grayframe->imageData;
}
else if (strncmp(pixelFormat, "Mono16",NULL)==0) {
grayframe = cvCreateImage(cvSize((int)frameWidth, (int)frameHeight), IPL_DEPTH_16U, 1);
grayframe->widthStep = (int)frameWidth;
frame = cvCreateImage(cvSize((int)frameWidth, (int)frameHeight), IPL_DEPTH_16U, 3);
frame->widthStep = (int)frameWidth*3;
Camera.Frame.ImageBufferSize = frameSize;
Camera.Frame.ImageBuffer = grayframe->imageData;
}
else if (strncmp(pixelFormat, "Bgr24",NULL)==0) {
frame = cvCreateImage(cvSize((int)frameWidth, (int)frameHeight), IPL_DEPTH_8U, 3);
frame->widthStep = (int)frameWidth*3;
Camera.Frame.ImageBufferSize = frameSize;
Camera.Frame.ImageBuffer = frame->imageData;
}
else
return false;
// Start the camera
PvCaptureStart(Camera.Handle);
// Set the camera to capture continuously
if(PvAttrEnumSet(Camera.Handle, "AcquisitionMode", "Continuous")!= ePvErrSuccess)
{
fprintf(stderr,"Could not set Prosilica Acquisition Mode\n");
return false;
}
if(PvCommandRun(Camera.Handle, "AcquisitionStart")!= ePvErrSuccess)
{
fprintf(stderr,"Could not start Prosilica acquisition\n");
return false;
}
if(PvAttrEnumSet(Camera.Handle, "FrameStartTriggerMode", "Freerun")!= ePvErrSuccess)
{
fprintf(stderr,"Error setting Prosilica trigger to \"Freerun\"");
return false;
}
return true;
}
fprintf(stderr,"Error cannot open camera\n");
return false;
}
bool CvCaptureCAM_PvAPI::grabFrame()
{
//if(Camera.Frame.Status != ePvErrUnplugged && Camera.Frame.Status != ePvErrCancelled)
return PvCaptureQueueFrame(Camera.Handle, &(Camera.Frame), NULL) == ePvErrSuccess;
}
IplImage* CvCaptureCAM_PvAPI::retrieveFrame(int)
{
if (PvCaptureWaitForFrameDone(Camera.Handle, &(Camera.Frame), 1000) == ePvErrSuccess) {
if (!monocrome)
cvMerge(grayframe,grayframe,grayframe,NULL,frame);
return frame;
}
else return NULL;
}
double CvCaptureCAM_PvAPI::getProperty( int property_id )
{
tPvUint32 nTemp;
switch ( property_id )
{
case CV_CAP_PROP_FRAME_WIDTH:
PvAttrUint32Get(Camera.Handle, "Width", &nTemp);
return (double)nTemp;
case CV_CAP_PROP_FRAME_HEIGHT:
PvAttrUint32Get(Camera.Handle, "Height", &nTemp);
return (double)nTemp;
}
return -1.0;
}
bool CvCaptureCAM_PvAPI::setProperty( int property_id, double value )
{
switch ( property_id )
{
/* TODO: Camera works, but IplImage must be modified for the new size
case CV_CAP_PROP_FRAME_WIDTH:
PvAttrUint32Set(Camera.Handle, "Width", (tPvUint32)value);
break;
case CV_CAP_PROP_FRAME_HEIGHT:
PvAttrUint32Set(Camera.Handle, "Heigth", (tPvUint32)value);
break;
*/
case CV_CAP_PROP_MONOCROME:
char pixelFormat[256];
PvAttrEnumGet(Camera.Handle, "PixelFormat", pixelFormat,256,NULL);
if ((strncmp(pixelFormat, "Mono8",NULL)==0) || strncmp(pixelFormat, "Mono16",NULL)==0) {
monocrome=true;
break;
}
else
return false;
default:
return false;
}
return true;
}
CvCapture* cvCreateCameraCapture_PvAPI( int index )
{
CvCaptureCAM_PvAPI* capture = new CvCaptureCAM_PvAPI;
if ( capture->open( index ))
return capture;
delete capture;
return NULL;
}
#ifdef _MSC_VER
#pragma comment(lib, "PvAPI.lib")
#endif
#endif
<|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 "ui/views/widget/desktop_aura/x11_whole_screen_move_loop.h"
#include <X11/Xlib.h>
// Get rid of a macro from Xlib.h that conflicts with Aura's RootWindow class.
#undef RootWindow
#include "base/message_loop/message_loop.h"
#include "base/message_loop/message_pump_x11.h"
#include "base/run_loop.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/aura/env.h"
#include "ui/aura/window.h"
#include "ui/aura/window_event_dispatcher.h"
#include "ui/aura/window_tree_host.h"
#include "ui/base/x/x11_util.h"
#include "ui/events/event.h"
#include "ui/events/keycodes/keyboard_code_conversion_x.h"
#include "ui/gfx/point_conversions.h"
#include "ui/gfx/screen.h"
#include "ui/views/controls/image_view.h"
#include "ui/views/widget/widget.h"
namespace views {
namespace {
// The minimum alpha before we declare a pixel transparent when searching in
// our source image.
const int kMinAlpha = 32;
class ScopedCapturer {
public:
explicit ScopedCapturer(aura::WindowTreeHost* host)
: host_(host) {
host_->SetCapture();
}
~ScopedCapturer() {
host_->ReleaseCapture();
}
private:
aura::WindowTreeHost* host_;
DISALLOW_COPY_AND_ASSIGN(ScopedCapturer);
};
} // namespace
X11WholeScreenMoveLoop::X11WholeScreenMoveLoop(
X11WholeScreenMoveLoopDelegate* delegate)
: delegate_(delegate),
in_move_loop_(false),
should_reset_mouse_flags_(false),
grab_input_window_(None) {
}
X11WholeScreenMoveLoop::~X11WholeScreenMoveLoop() {}
////////////////////////////////////////////////////////////////////////////////
// DesktopWindowTreeHostLinux, MessagePumpDispatcher implementation:
uint32_t X11WholeScreenMoveLoop::Dispatch(const base::NativeEvent& event) {
XEvent* xev = event;
// Note: the escape key is handled in the tab drag controller, which has
// keyboard focus even though we took pointer grab.
switch (xev->type) {
case MotionNotify: {
if (drag_widget_.get()) {
gfx::Screen* screen = gfx::Screen::GetNativeScreen();
gfx::Point location = gfx::ToFlooredPoint(
screen->GetCursorScreenPoint() - drag_offset_);
drag_widget_->SetBounds(gfx::Rect(location, drag_image_.size()));
}
delegate_->OnMouseMovement(&xev->xmotion);
break;
}
case ButtonRelease: {
if (xev->xbutton.button == Button1) {
// Assume that drags are being done with the left mouse button. Only
// break the drag if the left mouse button was released.
delegate_->OnMouseReleased();
}
break;
}
case KeyPress: {
if (ui::KeyboardCodeFromXKeyEvent(xev) == ui::VKEY_ESCAPE)
EndMoveLoop();
break;
}
}
return POST_DISPATCH_NONE;
}
////////////////////////////////////////////////////////////////////////////////
// DesktopWindowTreeHostLinux, aura::client::WindowMoveClient implementation:
bool X11WholeScreenMoveLoop::RunMoveLoop(aura::Window* source,
gfx::NativeCursor cursor) {
// Start a capture on the host, so that it continues to receive events during
// the drag. This may be second time we are capturing the mouse events - the
// first being when a mouse is first pressed. That first capture needs to be
// released before the call to GrabPointerAndKeyboard below, otherwise it may
// get released while we still need the pointer grab, which is why we restrict
// the scope here.
{
ScopedCapturer capturer(source->GetHost());
DCHECK(!in_move_loop_); // Can only handle one nested loop at a time.
in_move_loop_ = true;
XDisplay* display = gfx::GetXDisplay();
grab_input_window_ = CreateDragInputWindow(display);
if (!drag_image_.isNull() && CheckIfIconValid())
CreateDragImageWindow();
base::MessagePumpX11::Current()->AddDispatcherForWindow(
this, grab_input_window_);
// Releasing ScopedCapturer ensures that any other instance of
// X11ScopedCapture will not prematurely release grab that will be acquired
// below.
}
// TODO(varkha): Consider integrating GrabPointerAndKeyboard with
// ScopedCapturer to avoid possibility of logically keeping multiple grabs.
if (!GrabPointerAndKeyboard(cursor))
return false;
// We are handling a mouse drag outside of the aura::RootWindow system. We
// must manually make aura think that the mouse button is pressed so that we
// don't draw extraneous tooltips.
aura::Env* env = aura::Env::GetInstance();
if (!env->IsMouseButtonDown()) {
env->set_mouse_button_flags(ui::EF_LEFT_MOUSE_BUTTON);
should_reset_mouse_flags_ = true;
}
base::MessageLoopForUI* loop = base::MessageLoopForUI::current();
base::MessageLoop::ScopedNestableTaskAllower allow_nested(loop);
base::RunLoop run_loop;
quit_closure_ = run_loop.QuitClosure();
run_loop.Run();
return true;
}
void X11WholeScreenMoveLoop::UpdateCursor(gfx::NativeCursor cursor) {
if (in_move_loop_) {
// If we're still in the move loop, regrab the pointer with the updated
// cursor. Note: we can be called from handling an XdndStatus message after
// EndMoveLoop() was called, but before we return from the nested RunLoop.
GrabPointerAndKeyboard(cursor);
}
}
void X11WholeScreenMoveLoop::EndMoveLoop() {
if (!in_move_loop_)
return;
// We undo our emulated mouse click from RunMoveLoop();
if (should_reset_mouse_flags_) {
aura::Env::GetInstance()->set_mouse_button_flags(0);
should_reset_mouse_flags_ = false;
}
// TODO(erg): Is this ungrab the cause of having to click to give input focus
// on drawn out windows? Not ungrabbing here screws the X server until I kill
// the chrome process.
// Ungrab before we let go of the window.
XDisplay* display = gfx::GetXDisplay();
XUngrabPointer(display, CurrentTime);
XUngrabKeyboard(display, CurrentTime);
base::MessagePumpX11::Current()->RemoveDispatcherForWindow(
grab_input_window_);
drag_widget_.reset();
delegate_->OnMoveLoopEnded();
XDestroyWindow(display, grab_input_window_);
in_move_loop_ = false;
quit_closure_.Run();
}
void X11WholeScreenMoveLoop::SetDragImage(const gfx::ImageSkia& image,
gfx::Vector2dF offset) {
drag_image_ = image;
drag_offset_ = offset;
// Reset the Y offset, so that the drag-image is always just below the cursor,
// so that it is possible to see where the cursor is going.
drag_offset_.set_y(0.f);
}
bool X11WholeScreenMoveLoop::GrabPointerAndKeyboard(gfx::NativeCursor cursor) {
XDisplay* display = gfx::GetXDisplay();
XGrabServer(display);
XUngrabPointer(display, CurrentTime);
int ret = XGrabPointer(
display,
grab_input_window_,
False,
ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
GrabModeAsync,
GrabModeAsync,
None,
cursor.platform(),
CurrentTime);
if (ret != GrabSuccess) {
DLOG(ERROR) << "Grabbing pointer for dragging failed: "
<< ui::GetX11ErrorString(display, ret);
} else {
XUngrabKeyboard(display, CurrentTime);
ret = XGrabKeyboard(
display,
grab_input_window_,
False,
GrabModeAsync,
GrabModeAsync,
CurrentTime);
if (ret != GrabSuccess) {
DLOG(ERROR) << "Grabbing keyboard for dragging failed: "
<< ui::GetX11ErrorString(display, ret);
}
}
XUngrabServer(display);
return ret == GrabSuccess;
}
Window X11WholeScreenMoveLoop::CreateDragInputWindow(XDisplay* display) {
// Creates an invisible, InputOnly toplevel window. This window will receive
// all mouse movement for drags. It turns out that normal windows doing a
// grab doesn't redirect pointer motion events if the pointer isn't over the
// grabbing window. But InputOnly windows are able to grab everything. This
// is what GTK+ does, and I found a patch to KDE that did something similar.
unsigned long attribute_mask = CWEventMask | CWOverrideRedirect;
XSetWindowAttributes swa;
memset(&swa, 0, sizeof(swa));
swa.event_mask = ButtonPressMask | ButtonReleaseMask | PointerMotionMask |
KeyPressMask | KeyReleaseMask | StructureNotifyMask;
swa.override_redirect = True;
Window window = XCreateWindow(display,
DefaultRootWindow(display),
-100, -100, 10, 10,
0, CopyFromParent, InputOnly, CopyFromParent,
attribute_mask, &swa);
XMapRaised(display, window);
base::MessagePumpX11::Current()->BlockUntilWindowMapped(window);
return window;
}
void X11WholeScreenMoveLoop::CreateDragImageWindow() {
Widget* widget = new Widget;
Widget::InitParams params(Widget::InitParams::TYPE_DRAG);
params.opacity = Widget::InitParams::OPAQUE_WINDOW;
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.accept_events = false;
gfx::Point location = gfx::ToFlooredPoint(
gfx::Screen::GetNativeScreen()->GetCursorScreenPoint() - drag_offset_);
params.bounds = gfx::Rect(location, drag_image_.size());
widget->set_focus_on_creation(false);
widget->set_frame_type(Widget::FRAME_TYPE_FORCE_NATIVE);
widget->Init(params);
widget->GetNativeWindow()->SetName("DragWindow");
ImageView* image = new ImageView();
image->SetImage(drag_image_);
image->SetBounds(0, 0, drag_image_.width(), drag_image_.height());
widget->SetContentsView(image);
widget->Show();
widget->GetNativeWindow()->layer()->SetFillsBoundsOpaquely(false);
drag_widget_.reset(widget);
}
bool X11WholeScreenMoveLoop::CheckIfIconValid() {
// TODO(erg): I've tried at least five different strategies for trying to
// build a mask based off the alpha channel. While all of them have worked,
// none of them have been performant and introduced multiple second
// delays. (I spent a day getting a rectangle segmentation algorithm polished
// here...and then found that even through I had the rectangle extraction
// down to mere milliseconds, SkRegion still fell over on the number of
// rectangles.)
//
// Creating a mask here near instantaneously should be possible, as GTK does
// it, but I've blown days on this and I'm punting now.
const SkBitmap* in_bitmap = drag_image_.bitmap();
SkAutoLockPixels in_lock(*in_bitmap);
for (int y = 0; y < in_bitmap->height(); ++y) {
uint32* in_row = in_bitmap->getAddr32(0, y);
for (int x = 0; x < in_bitmap->width(); ++x) {
char value = SkColorGetA(in_row[x]) > kMinAlpha;
if (value)
return true;
}
}
return false;
}
} // namespace views
<commit_msg>Fix some minor issues in x11_whole_screen_move_loop.cc.<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 "ui/views/widget/desktop_aura/x11_whole_screen_move_loop.h"
#include <X11/Xlib.h>
// Get rid of a macro from Xlib.h that conflicts with Aura's RootWindow class.
#undef RootWindow
#include "base/message_loop/message_loop.h"
#include "base/message_loop/message_pump_x11.h"
#include "base/run_loop.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/aura/env.h"
#include "ui/aura/window.h"
#include "ui/aura/window_event_dispatcher.h"
#include "ui/aura/window_tree_host.h"
#include "ui/base/x/x11_util.h"
#include "ui/events/event.h"
#include "ui/events/keycodes/keyboard_code_conversion_x.h"
#include "ui/gfx/point_conversions.h"
#include "ui/gfx/screen.h"
#include "ui/views/controls/image_view.h"
#include "ui/views/widget/widget.h"
namespace views {
namespace {
// The minimum alpha before we declare a pixel transparent when searching in
// our source image.
const uint32 kMinAlpha = 32;
class ScopedCapturer {
public:
explicit ScopedCapturer(aura::WindowTreeHost* host)
: host_(host) {
host_->SetCapture();
}
~ScopedCapturer() {
host_->ReleaseCapture();
}
private:
aura::WindowTreeHost* host_;
DISALLOW_COPY_AND_ASSIGN(ScopedCapturer);
};
} // namespace
X11WholeScreenMoveLoop::X11WholeScreenMoveLoop(
X11WholeScreenMoveLoopDelegate* delegate)
: delegate_(delegate),
in_move_loop_(false),
should_reset_mouse_flags_(false),
grab_input_window_(None) {
}
X11WholeScreenMoveLoop::~X11WholeScreenMoveLoop() {}
////////////////////////////////////////////////////////////////////////////////
// DesktopWindowTreeHostLinux, MessagePumpDispatcher implementation:
uint32_t X11WholeScreenMoveLoop::Dispatch(const base::NativeEvent& event) {
XEvent* xev = event;
// Note: the escape key is handled in the tab drag controller, which has
// keyboard focus even though we took pointer grab.
switch (xev->type) {
case MotionNotify: {
if (drag_widget_.get()) {
gfx::Screen* screen = gfx::Screen::GetNativeScreen();
gfx::Point location = gfx::ToFlooredPoint(
screen->GetCursorScreenPoint() - drag_offset_);
drag_widget_->SetBounds(gfx::Rect(location, drag_image_.size()));
}
delegate_->OnMouseMovement(&xev->xmotion);
break;
}
case ButtonRelease: {
if (xev->xbutton.button == Button1) {
// Assume that drags are being done with the left mouse button. Only
// break the drag if the left mouse button was released.
delegate_->OnMouseReleased();
}
break;
}
case KeyPress: {
if (ui::KeyboardCodeFromXKeyEvent(xev) == ui::VKEY_ESCAPE)
EndMoveLoop();
break;
}
}
return POST_DISPATCH_NONE;
}
////////////////////////////////////////////////////////////////////////////////
// DesktopWindowTreeHostLinux, aura::client::WindowMoveClient implementation:
bool X11WholeScreenMoveLoop::RunMoveLoop(aura::Window* source,
gfx::NativeCursor cursor) {
// Start a capture on the host, so that it continues to receive events during
// the drag. This may be second time we are capturing the mouse events - the
// first being when a mouse is first pressed. That first capture needs to be
// released before the call to GrabPointerAndKeyboard below, otherwise it may
// get released while we still need the pointer grab, which is why we restrict
// the scope here.
{
ScopedCapturer capturer(source->GetHost());
DCHECK(!in_move_loop_); // Can only handle one nested loop at a time.
in_move_loop_ = true;
XDisplay* display = gfx::GetXDisplay();
grab_input_window_ = CreateDragInputWindow(display);
if (!drag_image_.isNull() && CheckIfIconValid())
CreateDragImageWindow();
base::MessagePumpX11::Current()->AddDispatcherForWindow(
this, grab_input_window_);
// Releasing ScopedCapturer ensures that any other instance of
// X11ScopedCapture will not prematurely release grab that will be acquired
// below.
}
// TODO(varkha): Consider integrating GrabPointerAndKeyboard with
// ScopedCapturer to avoid possibility of logically keeping multiple grabs.
if (!GrabPointerAndKeyboard(cursor))
return false;
// We are handling a mouse drag outside of the aura::RootWindow system. We
// must manually make aura think that the mouse button is pressed so that we
// don't draw extraneous tooltips.
aura::Env* env = aura::Env::GetInstance();
if (!env->IsMouseButtonDown()) {
env->set_mouse_button_flags(ui::EF_LEFT_MOUSE_BUTTON);
should_reset_mouse_flags_ = true;
}
base::MessageLoopForUI* loop = base::MessageLoopForUI::current();
base::MessageLoop::ScopedNestableTaskAllower allow_nested(loop);
base::RunLoop run_loop;
quit_closure_ = run_loop.QuitClosure();
run_loop.Run();
return true;
}
void X11WholeScreenMoveLoop::UpdateCursor(gfx::NativeCursor cursor) {
if (in_move_loop_) {
// If we're still in the move loop, regrab the pointer with the updated
// cursor. Note: we can be called from handling an XdndStatus message after
// EndMoveLoop() was called, but before we return from the nested RunLoop.
GrabPointerAndKeyboard(cursor);
}
}
void X11WholeScreenMoveLoop::EndMoveLoop() {
if (!in_move_loop_)
return;
// We undo our emulated mouse click from RunMoveLoop();
if (should_reset_mouse_flags_) {
aura::Env::GetInstance()->set_mouse_button_flags(0);
should_reset_mouse_flags_ = false;
}
// TODO(erg): Is this ungrab the cause of having to click to give input focus
// on drawn out windows? Not ungrabbing here screws the X server until I kill
// the chrome process.
// Ungrab before we let go of the window.
XDisplay* display = gfx::GetXDisplay();
XUngrabPointer(display, CurrentTime);
XUngrabKeyboard(display, CurrentTime);
base::MessagePumpX11::Current()->RemoveDispatcherForWindow(
grab_input_window_);
drag_widget_.reset();
delegate_->OnMoveLoopEnded();
XDestroyWindow(display, grab_input_window_);
in_move_loop_ = false;
quit_closure_.Run();
}
void X11WholeScreenMoveLoop::SetDragImage(const gfx::ImageSkia& image,
gfx::Vector2dF offset) {
drag_image_ = image;
drag_offset_ = offset;
// Reset the Y offset, so that the drag-image is always just below the cursor,
// so that it is possible to see where the cursor is going.
drag_offset_.set_y(0.f);
}
bool X11WholeScreenMoveLoop::GrabPointerAndKeyboard(gfx::NativeCursor cursor) {
XDisplay* display = gfx::GetXDisplay();
XGrabServer(display);
XUngrabPointer(display, CurrentTime);
int ret = XGrabPointer(
display,
grab_input_window_,
False,
ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
GrabModeAsync,
GrabModeAsync,
None,
cursor.platform(),
CurrentTime);
if (ret != GrabSuccess) {
DLOG(ERROR) << "Grabbing pointer for dragging failed: "
<< ui::GetX11ErrorString(display, ret);
} else {
XUngrabKeyboard(display, CurrentTime);
ret = XGrabKeyboard(
display,
grab_input_window_,
False,
GrabModeAsync,
GrabModeAsync,
CurrentTime);
if (ret != GrabSuccess) {
DLOG(ERROR) << "Grabbing keyboard for dragging failed: "
<< ui::GetX11ErrorString(display, ret);
}
}
XUngrabServer(display);
return ret == GrabSuccess;
}
Window X11WholeScreenMoveLoop::CreateDragInputWindow(XDisplay* display) {
// Creates an invisible, InputOnly toplevel window. This window will receive
// all mouse movement for drags. It turns out that normal windows doing a
// grab doesn't redirect pointer motion events if the pointer isn't over the
// grabbing window. But InputOnly windows are able to grab everything. This
// is what GTK+ does, and I found a patch to KDE that did something similar.
unsigned long attribute_mask = CWEventMask | CWOverrideRedirect;
XSetWindowAttributes swa;
memset(&swa, 0, sizeof(swa));
swa.event_mask = ButtonPressMask | ButtonReleaseMask | PointerMotionMask |
KeyPressMask | KeyReleaseMask | StructureNotifyMask;
swa.override_redirect = True;
Window window = XCreateWindow(display,
DefaultRootWindow(display),
-100, -100, 10, 10,
0, CopyFromParent, InputOnly, CopyFromParent,
attribute_mask, &swa);
XMapRaised(display, window);
base::MessagePumpX11::Current()->BlockUntilWindowMapped(window);
return window;
}
void X11WholeScreenMoveLoop::CreateDragImageWindow() {
Widget* widget = new Widget;
Widget::InitParams params(Widget::InitParams::TYPE_DRAG);
params.opacity = Widget::InitParams::OPAQUE_WINDOW;
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.accept_events = false;
gfx::Point location = gfx::ToFlooredPoint(
gfx::Screen::GetNativeScreen()->GetCursorScreenPoint() - drag_offset_);
params.bounds = gfx::Rect(location, drag_image_.size());
widget->set_focus_on_creation(false);
widget->set_frame_type(Widget::FRAME_TYPE_FORCE_NATIVE);
widget->Init(params);
widget->GetNativeWindow()->SetName("DragWindow");
ImageView* image = new ImageView();
image->SetImage(drag_image_);
image->SetBounds(0, 0, drag_image_.width(), drag_image_.height());
widget->SetContentsView(image);
widget->Show();
widget->GetNativeWindow()->layer()->SetFillsBoundsOpaquely(false);
drag_widget_.reset(widget);
}
bool X11WholeScreenMoveLoop::CheckIfIconValid() {
// TODO(erg): I've tried at least five different strategies for trying to
// build a mask based off the alpha channel. While all of them have worked,
// none of them have been performant and introduced multiple second
// delays. (I spent a day getting a rectangle segmentation algorithm polished
// here...and then found that even through I had the rectangle extraction
// down to mere milliseconds, SkRegion still fell over on the number of
// rectangles.)
//
// Creating a mask here near instantaneously should be possible, as GTK does
// it, but I've blown days on this and I'm punting now.
const SkBitmap* in_bitmap = drag_image_.bitmap();
SkAutoLockPixels in_lock(*in_bitmap);
for (int y = 0; y < in_bitmap->height(); ++y) {
uint32* in_row = in_bitmap->getAddr32(0, y);
for (int x = 0; x < in_bitmap->width(); ++x) {
if (SkColorGetA(in_row[x]) > kMinAlpha)
return true;
}
}
return false;
}
} // namespace views
<|endoftext|> |
<commit_before>#include "PackNodeFactory.h"
// picture
#include "ImageBuilder.h"
#include "Scale9Builder.h"
#include <easyscale9.h>
#include "IconBuilder.h"
#include <easyicon.h>
#include "TextureBuilder.h"
#include <easytexture.h>
// label
#include "LabelBuilder.h"
// animation
#include "ComplexBuilder.h"
#include <easycomplex.h>
#include "AnimBuilder.h"
#include <easyanim.h>
#include "Terrain2DBuilder.h"
#include <easyterrain2d.h>
// particle3d
#include "Particle3DBuilder.h"
#include <easyparticle3d.h>
namespace libcoco
{
PackNodeFactory* PackNodeFactory::m_instance = NULL;
PackNodeFactory::PackNodeFactory()
{
// picture
m_builders.push_back(m_img_builder = new ImageBuilder);
m_builders.push_back(m_scale9_builder = new Scale9Builder);
m_builders.push_back(m_icon_builder = new IconBuilder);
m_builders.push_back(m_tex_builder = new TextureBuilder);
// label
m_builders.push_back(m_label_builder = new LabelBuilder);
// animation
m_builders.push_back(m_complex_builder = new ComplexBuilder(m_export_set));
m_builders.push_back(m_anim_builder = new AnimBuilder(m_export_set));
m_builders.push_back(m_terrain2d_builder = new Terrain2DBuilder);
// particle3d
m_builders.push_back(m_particle3d_builder = new Particle3DBuilder);
}
const IPackNode* PackNodeFactory::Create(const d2d::ISprite* spr)
{
const IPackNode* node = NULL;
// picture
if (const d2d::ImageSprite* image = dynamic_cast<const d2d::ImageSprite*>(spr)) {
node = m_img_builder->Create(image);
} else if (const escale9::Sprite* scale9 = dynamic_cast<const escale9::Sprite*>(spr)) {
node = m_scale9_builder->Create(scale9);
} else if (const eicon::Sprite* icon = dynamic_cast<const eicon::Sprite*>(spr)) {
node = m_icon_builder->Create(icon);
} else if (const etexture::Sprite* tex = dynamic_cast<const etexture::Sprite*>(spr)) {
node = m_tex_builder->Create(&tex->GetSymbol());
}
// label
else if (const d2d::FontSprite* font = dynamic_cast<const d2d::FontSprite*>(spr)) {
node = m_label_builder->Create(font);
}
// animation
else if (const ecomplex::Sprite* complex = dynamic_cast<const ecomplex::Sprite*>(spr)) {
node = m_complex_builder->Create(&complex->GetSymbol());
} else if (const libanim::Sprite* anim = dynamic_cast<const libanim::Sprite*>(spr)) {
node = m_anim_builder->Create(&anim->GetSymbol());
} else if (const eterrain2d::Sprite* terr2d = dynamic_cast<const eterrain2d::Sprite*>(spr)) {
node = m_terrain2d_builder->Create(&terr2d->GetSymbol());
}
// particle3d
else if (const eparticle3d::Sprite* p3d = dynamic_cast<const eparticle3d::Sprite*>(spr)) {
node = m_particle3d_builder->Create(&p3d->GetSymbol());
}
else {
throw d2d::Exception("PackNodeFactory::Create unknown sprite type.");
}
node->SetFilepath(d2d::FilenameTools::getRelativePath(m_files_dir, spr->GetSymbol().GetFilepath()).ToStdString());
return node;
}
const IPackNode* PackNodeFactory::Create(const d2d::ISymbol* symbol)
{
const IPackNode* node = NULL;
// picture
if (const etexture::Symbol* tex = dynamic_cast<const etexture::Symbol*>(symbol)) {
node = m_tex_builder->Create(tex);
}
// animation
else if (const ecomplex::Symbol* complex = dynamic_cast<const ecomplex::Symbol*>(symbol)) {
node = m_complex_builder->Create(complex);
} else if (const libanim::Symbol* anim = dynamic_cast<const libanim::Symbol*>(symbol)) {
node = m_anim_builder->Create(anim);
} else if (const eterrain2d::Symbol* terr2d = dynamic_cast<const eterrain2d::Symbol*>(symbol)) {
node = m_terrain2d_builder->Create(terr2d);
}
// particle3d
else if (const eparticle3d::Symbol* p3d = dynamic_cast<const eparticle3d::Symbol*>(symbol)) {
node = m_particle3d_builder->Create(p3d);
}
else {
throw d2d::Exception("PackNodeFactory::Create unknown symbol type.");
}
node->SetFilepath(d2d::FilenameTools::getRelativePath(m_files_dir, symbol->GetFilepath()).ToStdString());
return node;
}
void PackNodeFactory::GetAllNodes(std::vector<IPackNode*>& nodes) const
{
nodes.clear();
for (int i = 0, n = m_builders.size(); i < n; ++i) {
m_builders[i]->Traverse(d2d::FetchAllVisitor<IPackNode>(nodes));
}
}
PackNodeFactory* PackNodeFactory::Instance()
{
if (!m_instance) {
m_instance = new PackNodeFactory;
}
return m_instance;
}
}<commit_msg>[FIXED] PackNodeFactory::Create ImageSymbol<commit_after>#include "PackNodeFactory.h"
// picture
#include "ImageBuilder.h"
#include "Scale9Builder.h"
#include <easyscale9.h>
#include "IconBuilder.h"
#include <easyicon.h>
#include "TextureBuilder.h"
#include <easytexture.h>
// label
#include "LabelBuilder.h"
// animation
#include "ComplexBuilder.h"
#include <easycomplex.h>
#include "AnimBuilder.h"
#include <easyanim.h>
#include "Terrain2DBuilder.h"
#include <easyterrain2d.h>
// particle3d
#include "Particle3DBuilder.h"
#include <easyparticle3d.h>
namespace libcoco
{
PackNodeFactory* PackNodeFactory::m_instance = NULL;
PackNodeFactory::PackNodeFactory()
{
// picture
m_builders.push_back(m_img_builder = new ImageBuilder);
m_builders.push_back(m_scale9_builder = new Scale9Builder);
m_builders.push_back(m_icon_builder = new IconBuilder);
m_builders.push_back(m_tex_builder = new TextureBuilder);
// label
m_builders.push_back(m_label_builder = new LabelBuilder);
// animation
m_builders.push_back(m_complex_builder = new ComplexBuilder(m_export_set));
m_builders.push_back(m_anim_builder = new AnimBuilder(m_export_set));
m_builders.push_back(m_terrain2d_builder = new Terrain2DBuilder);
// particle3d
m_builders.push_back(m_particle3d_builder = new Particle3DBuilder);
}
const IPackNode* PackNodeFactory::Create(const d2d::ISprite* spr)
{
const IPackNode* node = NULL;
// picture
if (const d2d::ImageSprite* image = dynamic_cast<const d2d::ImageSprite*>(spr)) {
node = m_img_builder->Create(image);
} else if (const escale9::Sprite* scale9 = dynamic_cast<const escale9::Sprite*>(spr)) {
node = m_scale9_builder->Create(scale9);
} else if (const eicon::Sprite* icon = dynamic_cast<const eicon::Sprite*>(spr)) {
node = m_icon_builder->Create(icon);
} else if (const etexture::Sprite* tex = dynamic_cast<const etexture::Sprite*>(spr)) {
node = m_tex_builder->Create(&tex->GetSymbol());
}
// label
else if (const d2d::FontSprite* font = dynamic_cast<const d2d::FontSprite*>(spr)) {
node = m_label_builder->Create(font);
}
// animation
else if (const ecomplex::Sprite* complex = dynamic_cast<const ecomplex::Sprite*>(spr)) {
node = m_complex_builder->Create(&complex->GetSymbol());
} else if (const libanim::Sprite* anim = dynamic_cast<const libanim::Sprite*>(spr)) {
node = m_anim_builder->Create(&anim->GetSymbol());
} else if (const eterrain2d::Sprite* terr2d = dynamic_cast<const eterrain2d::Sprite*>(spr)) {
node = m_terrain2d_builder->Create(&terr2d->GetSymbol());
}
// particle3d
else if (const eparticle3d::Sprite* p3d = dynamic_cast<const eparticle3d::Sprite*>(spr)) {
node = m_particle3d_builder->Create(&p3d->GetSymbol());
}
else {
throw d2d::Exception("PackNodeFactory::Create unknown sprite type.");
}
node->SetFilepath(d2d::FilenameTools::getRelativePath(m_files_dir, spr->GetSymbol().GetFilepath()).ToStdString());
return node;
}
const IPackNode* PackNodeFactory::Create(const d2d::ISymbol* symbol)
{
const IPackNode* node = NULL;
// picture
if (const d2d::ImageSymbol* img_symbol = dynamic_cast<const d2d::ImageSymbol*>(symbol)) {
d2d::ImageSprite* img_spr = new d2d::ImageSprite(const_cast<d2d::ImageSymbol*>(img_symbol));
node = m_img_builder->Create(img_spr);
img_spr->Release();
} else if (const etexture::Symbol* tex = dynamic_cast<const etexture::Symbol*>(symbol)) {
node = m_tex_builder->Create(tex);
}
// animation
else if (const ecomplex::Symbol* complex = dynamic_cast<const ecomplex::Symbol*>(symbol)) {
node = m_complex_builder->Create(complex);
} else if (const libanim::Symbol* anim = dynamic_cast<const libanim::Symbol*>(symbol)) {
node = m_anim_builder->Create(anim);
} else if (const eterrain2d::Symbol* terr2d = dynamic_cast<const eterrain2d::Symbol*>(symbol)) {
node = m_terrain2d_builder->Create(terr2d);
}
// particle3d
else if (const eparticle3d::Symbol* p3d = dynamic_cast<const eparticle3d::Symbol*>(symbol)) {
node = m_particle3d_builder->Create(p3d);
}
else {
throw d2d::Exception("PackNodeFactory::Create unknown symbol type.");
}
node->SetFilepath(d2d::FilenameTools::getRelativePath(m_files_dir, symbol->GetFilepath()).ToStdString());
return node;
}
void PackNodeFactory::GetAllNodes(std::vector<IPackNode*>& nodes) const
{
nodes.clear();
for (int i = 0, n = m_builders.size(); i < n; ++i) {
m_builders[i]->Traverse(d2d::FetchAllVisitor<IPackNode>(nodes));
}
}
PackNodeFactory* PackNodeFactory::Instance()
{
if (!m_instance) {
m_instance = new PackNodeFactory;
}
return m_instance;
}
}<|endoftext|> |
<commit_before>//===-- RegisterContextMinidumpTest.cpp -------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "Plugins/Process/Utility/RegisterContextLinux_i386.h"
#include "Plugins/Process/Utility/RegisterContextLinux_x86_64.h"
#include "Plugins/Process/minidump/RegisterContextMinidump_x86_32.h"
#include "Plugins/Process/minidump/RegisterContextMinidump_x86_64.h"
#include "Plugins/Process/minidump/RegisterContextMinidump_ARM.h"
#include "lldb/Utility/DataBuffer.h"
#include "llvm/ADT/StringRef.h"
#include "gtest/gtest.h"
using namespace lldb_private;
using namespace lldb_private::minidump;
static uint32_t reg32(const DataBuffer &Buf, const RegisterInfo &Info) {
return *reinterpret_cast<const uint32_t *>(Buf.GetBytes() + Info.byte_offset);
}
static uint64_t reg64(const DataBuffer &Buf, const RegisterInfo &Info) {
return *reinterpret_cast<const uint64_t *>(Buf.GetBytes() + Info.byte_offset);
}
TEST(RegisterContextMinidump, ConvertMinidumpContext_x86_32) {
MinidumpContext_x86_32 Context;
Context.context_flags =
static_cast<uint32_t>(MinidumpContext_x86_32_Flags::x86_32_Flag |
MinidumpContext_x86_32_Flags::Control |
MinidumpContext_x86_32_Flags::Segments |
MinidumpContext_x86_32_Flags::Integer);
Context.eax = 0x00010203;
Context.ebx = 0x04050607;
Context.ecx = 0x08090a0b;
Context.edx = 0x0c0d0e0f;
Context.edi = 0x10111213;
Context.esi = 0x14151617;
Context.ebp = 0x18191a1b;
Context.esp = 0x1c1d1e1f;
Context.eip = 0x20212223;
Context.eflags = 0x24252627;
Context.cs = 0x2829;
Context.fs = 0x2a2b;
Context.gs = 0x2c2d;
Context.ss = 0x2e2f;
Context.ds = 0x3031;
Context.es = 0x3233;
llvm::ArrayRef<uint8_t> ContextRef(reinterpret_cast<uint8_t *>(&Context),
sizeof(Context));
ArchSpec arch("i386-pc-linux");
auto RegInterface = std::make_unique<RegisterContextLinux_i386>(arch);
lldb::DataBufferSP Buf =
ConvertMinidumpContext_x86_32(ContextRef, RegInterface.get());
ASSERT_EQ(RegInterface->GetGPRSize(), Buf->GetByteSize());
const RegisterInfo *Info = RegInterface->GetRegisterInfo();
ASSERT_NE(nullptr, Info);
EXPECT_EQ(Context.eax, reg32(*Buf, Info[lldb_eax_i386]));
EXPECT_EQ(Context.ebx, reg32(*Buf, Info[lldb_ebx_i386]));
EXPECT_EQ(Context.ecx, reg32(*Buf, Info[lldb_ecx_i386]));
EXPECT_EQ(Context.edx, reg32(*Buf, Info[lldb_edx_i386]));
EXPECT_EQ(Context.edi, reg32(*Buf, Info[lldb_edi_i386]));
EXPECT_EQ(Context.esi, reg32(*Buf, Info[lldb_esi_i386]));
EXPECT_EQ(Context.ebp, reg32(*Buf, Info[lldb_ebp_i386]));
EXPECT_EQ(Context.esp, reg32(*Buf, Info[lldb_esp_i386]));
EXPECT_EQ(Context.eip, reg32(*Buf, Info[lldb_eip_i386]));
EXPECT_EQ(Context.eflags, reg32(*Buf, Info[lldb_eflags_i386]));
EXPECT_EQ(Context.cs, reg32(*Buf, Info[lldb_cs_i386]));
EXPECT_EQ(Context.fs, reg32(*Buf, Info[lldb_fs_i386]));
EXPECT_EQ(Context.gs, reg32(*Buf, Info[lldb_gs_i386]));
EXPECT_EQ(Context.ss, reg32(*Buf, Info[lldb_ss_i386]));
EXPECT_EQ(Context.ds, reg32(*Buf, Info[lldb_ds_i386]));
EXPECT_EQ(Context.es, reg32(*Buf, Info[lldb_es_i386]));
}
TEST(RegisterContextMinidump, ConvertMinidumpContext_x86_64) {
MinidumpContext_x86_64 Context;
Context.context_flags =
static_cast<uint32_t>(MinidumpContext_x86_64_Flags::x86_64_Flag |
MinidumpContext_x86_64_Flags::Control |
MinidumpContext_x86_64_Flags::Segments |
MinidumpContext_x86_64_Flags::Integer);
Context.rax = 0x0001020304050607;
Context.rbx = 0x08090a0b0c0d0e0f;
Context.rcx = 0x1011121314151617;
Context.rdx = 0x18191a1b1c1d1e1f;
Context.rdi = 0x2021222324252627;
Context.rsi = 0x28292a2b2c2d2e2f;
Context.rbp = 0x3031323334353637;
Context.rsp = 0x38393a3b3c3d3e3f;
Context.r8 = 0x4041424344454647;
Context.r9 = 0x48494a4b4c4d4e4f;
Context.r10 = 0x5051525354555657;
Context.r11 = 0x58595a5b5c5d5e5f;
Context.r12 = 0x6061626364656667;
Context.r13 = 0x68696a6b6c6d6e6f;
Context.r14 = 0x7071727374757677;
Context.r15 = 0x78797a7b7c7d7e7f;
Context.rip = 0x8081828384858687;
Context.eflags = 0x88898a8b;
Context.cs = 0x8c8d;
Context.fs = 0x8e8f;
Context.gs = 0x9091;
Context.ss = 0x9293;
Context.ds = 0x9495;
Context.ss = 0x9697;
llvm::ArrayRef<uint8_t> ContextRef(reinterpret_cast<uint8_t *>(&Context),
sizeof(Context));
ArchSpec arch("x86_64-pc-linux");
auto RegInterface = std::make_unique<RegisterContextLinux_x86_64>(arch);
lldb::DataBufferSP Buf =
ConvertMinidumpContext_x86_64(ContextRef, RegInterface.get());
ASSERT_EQ(RegInterface->GetGPRSize(), Buf->GetByteSize());
const RegisterInfo *Info = RegInterface->GetRegisterInfo();
EXPECT_EQ(Context.rax, reg64(*Buf, Info[lldb_rax_x86_64]));
EXPECT_EQ(Context.rbx, reg64(*Buf, Info[lldb_rbx_x86_64]));
EXPECT_EQ(Context.rcx, reg64(*Buf, Info[lldb_rcx_x86_64]));
EXPECT_EQ(Context.rdx, reg64(*Buf, Info[lldb_rdx_x86_64]));
EXPECT_EQ(Context.rdi, reg64(*Buf, Info[lldb_rdi_x86_64]));
EXPECT_EQ(Context.rsi, reg64(*Buf, Info[lldb_rsi_x86_64]));
EXPECT_EQ(Context.rbp, reg64(*Buf, Info[lldb_rbp_x86_64]));
EXPECT_EQ(Context.rsp, reg64(*Buf, Info[lldb_rsp_x86_64]));
EXPECT_EQ(Context.r8, reg64(*Buf, Info[lldb_r8_x86_64]));
EXPECT_EQ(Context.r9, reg64(*Buf, Info[lldb_r9_x86_64]));
EXPECT_EQ(Context.r10, reg64(*Buf, Info[lldb_r10_x86_64]));
EXPECT_EQ(Context.r11, reg64(*Buf, Info[lldb_r11_x86_64]));
EXPECT_EQ(Context.r12, reg64(*Buf, Info[lldb_r12_x86_64]));
EXPECT_EQ(Context.r13, reg64(*Buf, Info[lldb_r13_x86_64]));
EXPECT_EQ(Context.r14, reg64(*Buf, Info[lldb_r14_x86_64]));
EXPECT_EQ(Context.r15, reg64(*Buf, Info[lldb_r15_x86_64]));
EXPECT_EQ(Context.rip, reg64(*Buf, Info[lldb_rip_x86_64]));
EXPECT_EQ(Context.eflags, reg64(*Buf, Info[lldb_rflags_x86_64]));
EXPECT_EQ(Context.cs, reg64(*Buf, Info[lldb_cs_x86_64]));
EXPECT_EQ(Context.fs, reg64(*Buf, Info[lldb_fs_x86_64]));
EXPECT_EQ(Context.gs, reg64(*Buf, Info[lldb_gs_x86_64]));
EXPECT_EQ(Context.ss, reg64(*Buf, Info[lldb_ss_x86_64]));
EXPECT_EQ(Context.ds, reg64(*Buf, Info[lldb_ds_x86_64]));
EXPECT_EQ(Context.es, reg64(*Buf, Info[lldb_es_x86_64]));
}
static void TestARMRegInfo(const lldb_private::RegisterInfo *info) {
// Make sure we have valid register numbers for eRegisterKindEHFrame and
// eRegisterKindDWARF for GPR registers r0-r15 so that we can unwind
// correctly when using this information.
llvm::StringRef name(info->name);
llvm::StringRef alt_name(info->alt_name);
if (name.startswith("r") || alt_name.startswith("r")) {
EXPECT_NE(info->kinds[lldb::eRegisterKindEHFrame], LLDB_INVALID_REGNUM);
EXPECT_NE(info->kinds[lldb::eRegisterKindDWARF], LLDB_INVALID_REGNUM);
}
// Verify generic register are set correctly
if (name == "r0")
EXPECT_EQ(info->kinds[lldb::eRegisterKindGeneric],
(uint32_t)LLDB_REGNUM_GENERIC_ARG1);
else if (name == "r1")
EXPECT_EQ(info->kinds[lldb::eRegisterKindGeneric],
(uint32_t)LLDB_REGNUM_GENERIC_ARG2);
else if (name == "r2")
EXPECT_EQ(info->kinds[lldb::eRegisterKindGeneric],
(uint32_t)LLDB_REGNUM_GENERIC_ARG3);
else if (name == "r3")
EXPECT_EQ(info->kinds[lldb::eRegisterKindGeneric],
(uint32_t)LLDB_REGNUM_GENERIC_ARG4);
else if (name == "sp")
EXPECT_EQ(info->kinds[lldb::eRegisterKindGeneric],
(uint32_t)LLDB_REGNUM_GENERIC_SP);
else if (name == "fp")
EXPECT_EQ(info->kinds[lldb::eRegisterKindGeneric],
(uint32_t)LLDB_REGNUM_GENERIC_FP);
else if (name == "lr")
EXPECT_EQ(info->kinds[lldb::eRegisterKindGeneric],
(uint32_t)LLDB_REGNUM_GENERIC_RA);
else if (name == "pc")
EXPECT_EQ(info->kinds[lldb::eRegisterKindGeneric],
(uint32_t)LLDB_REGNUM_GENERIC_PC);
else if (name == "cpsr")
EXPECT_EQ(info->kinds[lldb::eRegisterKindGeneric],
(uint32_t)LLDB_REGNUM_GENERIC_FLAGS);
}
TEST(RegisterContextMinidump, CheckRegisterContextMinidump_ARM) {
size_t num_regs = RegisterContextMinidump_ARM::GetRegisterCountStatic();
const lldb_private::RegisterInfo *reg_info;
for (size_t reg=0; reg<num_regs; ++reg) {
reg_info = RegisterContextMinidump_ARM::GetRegisterInfoAtIndexStatic(reg,
true);
TestARMRegInfo(reg_info);
reg_info = RegisterContextMinidump_ARM::GetRegisterInfoAtIndexStatic(reg,
false);
TestARMRegInfo(reg_info);
}
}
<commit_msg>Fix some dangling else warnings<commit_after>//===-- RegisterContextMinidumpTest.cpp -------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "Plugins/Process/Utility/RegisterContextLinux_i386.h"
#include "Plugins/Process/Utility/RegisterContextLinux_x86_64.h"
#include "Plugins/Process/minidump/RegisterContextMinidump_x86_32.h"
#include "Plugins/Process/minidump/RegisterContextMinidump_x86_64.h"
#include "Plugins/Process/minidump/RegisterContextMinidump_ARM.h"
#include "lldb/Utility/DataBuffer.h"
#include "llvm/ADT/StringRef.h"
#include "gtest/gtest.h"
using namespace lldb_private;
using namespace lldb_private::minidump;
static uint32_t reg32(const DataBuffer &Buf, const RegisterInfo &Info) {
return *reinterpret_cast<const uint32_t *>(Buf.GetBytes() + Info.byte_offset);
}
static uint64_t reg64(const DataBuffer &Buf, const RegisterInfo &Info) {
return *reinterpret_cast<const uint64_t *>(Buf.GetBytes() + Info.byte_offset);
}
TEST(RegisterContextMinidump, ConvertMinidumpContext_x86_32) {
MinidumpContext_x86_32 Context;
Context.context_flags =
static_cast<uint32_t>(MinidumpContext_x86_32_Flags::x86_32_Flag |
MinidumpContext_x86_32_Flags::Control |
MinidumpContext_x86_32_Flags::Segments |
MinidumpContext_x86_32_Flags::Integer);
Context.eax = 0x00010203;
Context.ebx = 0x04050607;
Context.ecx = 0x08090a0b;
Context.edx = 0x0c0d0e0f;
Context.edi = 0x10111213;
Context.esi = 0x14151617;
Context.ebp = 0x18191a1b;
Context.esp = 0x1c1d1e1f;
Context.eip = 0x20212223;
Context.eflags = 0x24252627;
Context.cs = 0x2829;
Context.fs = 0x2a2b;
Context.gs = 0x2c2d;
Context.ss = 0x2e2f;
Context.ds = 0x3031;
Context.es = 0x3233;
llvm::ArrayRef<uint8_t> ContextRef(reinterpret_cast<uint8_t *>(&Context),
sizeof(Context));
ArchSpec arch("i386-pc-linux");
auto RegInterface = std::make_unique<RegisterContextLinux_i386>(arch);
lldb::DataBufferSP Buf =
ConvertMinidumpContext_x86_32(ContextRef, RegInterface.get());
ASSERT_EQ(RegInterface->GetGPRSize(), Buf->GetByteSize());
const RegisterInfo *Info = RegInterface->GetRegisterInfo();
ASSERT_NE(nullptr, Info);
EXPECT_EQ(Context.eax, reg32(*Buf, Info[lldb_eax_i386]));
EXPECT_EQ(Context.ebx, reg32(*Buf, Info[lldb_ebx_i386]));
EXPECT_EQ(Context.ecx, reg32(*Buf, Info[lldb_ecx_i386]));
EXPECT_EQ(Context.edx, reg32(*Buf, Info[lldb_edx_i386]));
EXPECT_EQ(Context.edi, reg32(*Buf, Info[lldb_edi_i386]));
EXPECT_EQ(Context.esi, reg32(*Buf, Info[lldb_esi_i386]));
EXPECT_EQ(Context.ebp, reg32(*Buf, Info[lldb_ebp_i386]));
EXPECT_EQ(Context.esp, reg32(*Buf, Info[lldb_esp_i386]));
EXPECT_EQ(Context.eip, reg32(*Buf, Info[lldb_eip_i386]));
EXPECT_EQ(Context.eflags, reg32(*Buf, Info[lldb_eflags_i386]));
EXPECT_EQ(Context.cs, reg32(*Buf, Info[lldb_cs_i386]));
EXPECT_EQ(Context.fs, reg32(*Buf, Info[lldb_fs_i386]));
EXPECT_EQ(Context.gs, reg32(*Buf, Info[lldb_gs_i386]));
EXPECT_EQ(Context.ss, reg32(*Buf, Info[lldb_ss_i386]));
EXPECT_EQ(Context.ds, reg32(*Buf, Info[lldb_ds_i386]));
EXPECT_EQ(Context.es, reg32(*Buf, Info[lldb_es_i386]));
}
TEST(RegisterContextMinidump, ConvertMinidumpContext_x86_64) {
MinidumpContext_x86_64 Context;
Context.context_flags =
static_cast<uint32_t>(MinidumpContext_x86_64_Flags::x86_64_Flag |
MinidumpContext_x86_64_Flags::Control |
MinidumpContext_x86_64_Flags::Segments |
MinidumpContext_x86_64_Flags::Integer);
Context.rax = 0x0001020304050607;
Context.rbx = 0x08090a0b0c0d0e0f;
Context.rcx = 0x1011121314151617;
Context.rdx = 0x18191a1b1c1d1e1f;
Context.rdi = 0x2021222324252627;
Context.rsi = 0x28292a2b2c2d2e2f;
Context.rbp = 0x3031323334353637;
Context.rsp = 0x38393a3b3c3d3e3f;
Context.r8 = 0x4041424344454647;
Context.r9 = 0x48494a4b4c4d4e4f;
Context.r10 = 0x5051525354555657;
Context.r11 = 0x58595a5b5c5d5e5f;
Context.r12 = 0x6061626364656667;
Context.r13 = 0x68696a6b6c6d6e6f;
Context.r14 = 0x7071727374757677;
Context.r15 = 0x78797a7b7c7d7e7f;
Context.rip = 0x8081828384858687;
Context.eflags = 0x88898a8b;
Context.cs = 0x8c8d;
Context.fs = 0x8e8f;
Context.gs = 0x9091;
Context.ss = 0x9293;
Context.ds = 0x9495;
Context.ss = 0x9697;
llvm::ArrayRef<uint8_t> ContextRef(reinterpret_cast<uint8_t *>(&Context),
sizeof(Context));
ArchSpec arch("x86_64-pc-linux");
auto RegInterface = std::make_unique<RegisterContextLinux_x86_64>(arch);
lldb::DataBufferSP Buf =
ConvertMinidumpContext_x86_64(ContextRef, RegInterface.get());
ASSERT_EQ(RegInterface->GetGPRSize(), Buf->GetByteSize());
const RegisterInfo *Info = RegInterface->GetRegisterInfo();
EXPECT_EQ(Context.rax, reg64(*Buf, Info[lldb_rax_x86_64]));
EXPECT_EQ(Context.rbx, reg64(*Buf, Info[lldb_rbx_x86_64]));
EXPECT_EQ(Context.rcx, reg64(*Buf, Info[lldb_rcx_x86_64]));
EXPECT_EQ(Context.rdx, reg64(*Buf, Info[lldb_rdx_x86_64]));
EXPECT_EQ(Context.rdi, reg64(*Buf, Info[lldb_rdi_x86_64]));
EXPECT_EQ(Context.rsi, reg64(*Buf, Info[lldb_rsi_x86_64]));
EXPECT_EQ(Context.rbp, reg64(*Buf, Info[lldb_rbp_x86_64]));
EXPECT_EQ(Context.rsp, reg64(*Buf, Info[lldb_rsp_x86_64]));
EXPECT_EQ(Context.r8, reg64(*Buf, Info[lldb_r8_x86_64]));
EXPECT_EQ(Context.r9, reg64(*Buf, Info[lldb_r9_x86_64]));
EXPECT_EQ(Context.r10, reg64(*Buf, Info[lldb_r10_x86_64]));
EXPECT_EQ(Context.r11, reg64(*Buf, Info[lldb_r11_x86_64]));
EXPECT_EQ(Context.r12, reg64(*Buf, Info[lldb_r12_x86_64]));
EXPECT_EQ(Context.r13, reg64(*Buf, Info[lldb_r13_x86_64]));
EXPECT_EQ(Context.r14, reg64(*Buf, Info[lldb_r14_x86_64]));
EXPECT_EQ(Context.r15, reg64(*Buf, Info[lldb_r15_x86_64]));
EXPECT_EQ(Context.rip, reg64(*Buf, Info[lldb_rip_x86_64]));
EXPECT_EQ(Context.eflags, reg64(*Buf, Info[lldb_rflags_x86_64]));
EXPECT_EQ(Context.cs, reg64(*Buf, Info[lldb_cs_x86_64]));
EXPECT_EQ(Context.fs, reg64(*Buf, Info[lldb_fs_x86_64]));
EXPECT_EQ(Context.gs, reg64(*Buf, Info[lldb_gs_x86_64]));
EXPECT_EQ(Context.ss, reg64(*Buf, Info[lldb_ss_x86_64]));
EXPECT_EQ(Context.ds, reg64(*Buf, Info[lldb_ds_x86_64]));
EXPECT_EQ(Context.es, reg64(*Buf, Info[lldb_es_x86_64]));
}
static void TestARMRegInfo(const lldb_private::RegisterInfo *info) {
// Make sure we have valid register numbers for eRegisterKindEHFrame and
// eRegisterKindDWARF for GPR registers r0-r15 so that we can unwind
// correctly when using this information.
llvm::StringRef name(info->name);
llvm::StringRef alt_name(info->alt_name);
if (name.startswith("r") || alt_name.startswith("r")) {
EXPECT_NE(info->kinds[lldb::eRegisterKindEHFrame], LLDB_INVALID_REGNUM);
EXPECT_NE(info->kinds[lldb::eRegisterKindDWARF], LLDB_INVALID_REGNUM);
}
// Verify generic register are set correctly
if (name == "r0") {
EXPECT_EQ(info->kinds[lldb::eRegisterKindGeneric],
(uint32_t)LLDB_REGNUM_GENERIC_ARG1);
} else if (name == "r1") {
EXPECT_EQ(info->kinds[lldb::eRegisterKindGeneric],
(uint32_t)LLDB_REGNUM_GENERIC_ARG2);
} else if (name == "r2") {
EXPECT_EQ(info->kinds[lldb::eRegisterKindGeneric],
(uint32_t)LLDB_REGNUM_GENERIC_ARG3);
} else if (name == "r3") {
EXPECT_EQ(info->kinds[lldb::eRegisterKindGeneric],
(uint32_t)LLDB_REGNUM_GENERIC_ARG4);
} else if (name == "sp") {
EXPECT_EQ(info->kinds[lldb::eRegisterKindGeneric],
(uint32_t)LLDB_REGNUM_GENERIC_SP);
} else if (name == "fp") {
EXPECT_EQ(info->kinds[lldb::eRegisterKindGeneric],
(uint32_t)LLDB_REGNUM_GENERIC_FP);
} else if (name == "lr") {
EXPECT_EQ(info->kinds[lldb::eRegisterKindGeneric],
(uint32_t)LLDB_REGNUM_GENERIC_RA);
} else if (name == "pc") {
EXPECT_EQ(info->kinds[lldb::eRegisterKindGeneric],
(uint32_t)LLDB_REGNUM_GENERIC_PC);
} else if (name == "cpsr") {
EXPECT_EQ(info->kinds[lldb::eRegisterKindGeneric],
(uint32_t)LLDB_REGNUM_GENERIC_FLAGS);
}
}
TEST(RegisterContextMinidump, CheckRegisterContextMinidump_ARM) {
size_t num_regs = RegisterContextMinidump_ARM::GetRegisterCountStatic();
const lldb_private::RegisterInfo *reg_info;
for (size_t reg=0; reg<num_regs; ++reg) {
reg_info = RegisterContextMinidump_ARM::GetRegisterInfoAtIndexStatic(reg,
true);
TestARMRegInfo(reg_info);
reg_info = RegisterContextMinidump_ARM::GetRegisterInfoAtIndexStatic(reg,
false);
TestARMRegInfo(reg_info);
}
}
<|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 "views/events/event.h"
#include <windows.h>
#include "base/logging.h"
#include "ui/base/keycodes/keyboard_code_conversion_win.h"
namespace views {
namespace {
// Returns a mask corresponding to the set of modifier keys that are currently
// pressed. Windows key messages don't come with control key state as parameters
// as with mouse messages, so we need to explicitly ask for these states.
int GetKeyStateFlags() {
int flags = 0;
if (GetKeyState(VK_MENU) & 0x80)
flags |= ui::EF_ALT_DOWN;
if (GetKeyState(VK_SHIFT) & 0x80)
flags |= ui::EF_SHIFT_DOWN;
if (GetKeyState(VK_CONTROL) & 0x80)
flags |= ui::EF_CONTROL_DOWN;
return flags;
}
// Convert windows message identifiers to Event types.
ui::EventType EventTypeFromNative(NativeEvent native_event) {
switch (native_event.message) {
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
return ui::ET_KEY_PRESSED;
case WM_KEYUP:
case WM_SYSKEYUP:
return ui::ET_KEY_RELEASED;
case WM_LBUTTONDOWN:
case WM_MBUTTONDOWN:
case WM_NCLBUTTONDOWN:
case WM_NCMBUTTONDOWN:
case WM_NCRBUTTONDOWN:
case WM_RBUTTONDOWN:
return ui::ET_MOUSE_PRESSED;
case WM_LBUTTONDBLCLK:
case WM_LBUTTONUP:
case WM_MBUTTONDBLCLK:
case WM_MBUTTONUP:
case WM_NCLBUTTONDBLCLK:
case WM_NCLBUTTONUP:
case WM_NCMBUTTONDBLCLK:
case WM_NCMBUTTONUP:
case WM_NCRBUTTONDBLCLK:
case WM_NCRBUTTONUP:
case WM_RBUTTONDBLCLK:
case WM_RBUTTONUP:
return ui::ET_MOUSE_RELEASED;
case WM_MOUSEMOVE:
case WM_NCMOUSEMOVE:
return ui::ET_MOUSE_MOVED;
case WM_MOUSEWHEEL:
return ui::ET_MOUSEWHEEL;
case WM_MOUSELEAVE:
case WM_NCMOUSELEAVE:
return ui::ET_MOUSE_EXITED;
default:
NOTREACHED();
}
return ui::ET_UNKNOWN;
}
} // namespace
////////////////////////////////////////////////////////////////////////////////
// Event, public:
int Event::GetWindowsFlags() const {
// TODO: need support for x1/x2.
int result = 0;
result |= (flags_ & ui::EF_SHIFT_DOWN) ? MK_SHIFT : 0;
result |= (flags_ & ui::EF_CONTROL_DOWN) ? MK_CONTROL : 0;
result |= (flags_ & ui::EF_LEFT_BUTTON_DOWN) ? MK_LBUTTON : 0;
result |= (flags_ & ui::EF_MIDDLE_BUTTON_DOWN) ? MK_MBUTTON : 0;
result |= (flags_ & ui::EF_RIGHT_BUTTON_DOWN) ? MK_RBUTTON : 0;
return result;
}
//static
int Event::ConvertWindowsFlags(UINT win_flags) {
int r = 0;
if (win_flags & MK_CONTROL)
r |= ui::EF_CONTROL_DOWN;
if (win_flags & MK_SHIFT)
r |= ui::EF_SHIFT_DOWN;
if (GetKeyState(VK_MENU) < 0)
r |= ui::EF_ALT_DOWN;
if (win_flags & MK_LBUTTON)
r |= ui::EF_LEFT_BUTTON_DOWN;
if (win_flags & MK_MBUTTON)
r |= ui::EF_MIDDLE_BUTTON_DOWN;
if (win_flags & MK_RBUTTON)
r |= ui::EF_RIGHT_BUTTON_DOWN;
return r;
}
////////////////////////////////////////////////////////////////////////////////
// Event, private:
void Event::Init() {
ZeroMemory(&native_event_, sizeof(native_event_));
native_event_2_ = NULL;
}
void Event::InitWithNativeEvent(NativeEvent native_event) {
native_event_ = native_event;
// TODO(beng): remove once we rid views of Gtk/Gdk.
native_event_2_ = NULL;
}
void Event::InitWithNativeEvent2(NativeEvent2 native_event_2,
FromNativeEvent2) {
// No one should ever call this on Windows.
// TODO(beng): remove once we rid views of Gtk/Gdk.
NOTREACHED();
native_event_2_ = NULL;
}
////////////////////////////////////////////////////////////////////////////////
// KeyEvent, public:
KeyEvent::KeyEvent(NativeEvent native_event)
: Event(native_event,
EventTypeFromNative(native_event),
GetKeyStateFlags()),
key_code_(ui::KeyboardCodeForWindowsKeyCode(native_event.wParam)) {
}
KeyEvent::KeyEvent(NativeEvent2 native_event_2, FromNativeEvent2 from_native)
: Event(native_event_2, ui::ET_UNKNOWN, 0, from_native) {
// No one should ever call this on Windows.
// TODO(beng): remove once we rid views of Gtk/Gdk.
NOTREACHED();
}
} // namespace views
<commit_msg>NOTREACHED() was hit due to not handling WM_CHAR in EventTypeFromNative(). WM_CHAR is a translated WM_KEYDOWN, so we map it to ui::ET_KEY_PRESSED<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 "views/events/event.h"
#include <windows.h>
#include "base/logging.h"
#include "ui/base/keycodes/keyboard_code_conversion_win.h"
namespace views {
namespace {
// Returns a mask corresponding to the set of modifier keys that are currently
// pressed. Windows key messages don't come with control key state as parameters
// as with mouse messages, so we need to explicitly ask for these states.
int GetKeyStateFlags() {
int flags = 0;
if (GetKeyState(VK_MENU) & 0x80)
flags |= ui::EF_ALT_DOWN;
if (GetKeyState(VK_SHIFT) & 0x80)
flags |= ui::EF_SHIFT_DOWN;
if (GetKeyState(VK_CONTROL) & 0x80)
flags |= ui::EF_CONTROL_DOWN;
return flags;
}
// Convert windows message identifiers to Event types.
ui::EventType EventTypeFromNative(NativeEvent native_event) {
switch (native_event.message) {
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
case WM_CHAR:
return ui::ET_KEY_PRESSED;
case WM_KEYUP:
case WM_SYSKEYUP:
return ui::ET_KEY_RELEASED;
case WM_LBUTTONDOWN:
case WM_MBUTTONDOWN:
case WM_NCLBUTTONDOWN:
case WM_NCMBUTTONDOWN:
case WM_NCRBUTTONDOWN:
case WM_RBUTTONDOWN:
return ui::ET_MOUSE_PRESSED;
case WM_LBUTTONDBLCLK:
case WM_LBUTTONUP:
case WM_MBUTTONDBLCLK:
case WM_MBUTTONUP:
case WM_NCLBUTTONDBLCLK:
case WM_NCLBUTTONUP:
case WM_NCMBUTTONDBLCLK:
case WM_NCMBUTTONUP:
case WM_NCRBUTTONDBLCLK:
case WM_NCRBUTTONUP:
case WM_RBUTTONDBLCLK:
case WM_RBUTTONUP:
return ui::ET_MOUSE_RELEASED;
case WM_MOUSEMOVE:
case WM_NCMOUSEMOVE:
return ui::ET_MOUSE_MOVED;
case WM_MOUSEWHEEL:
return ui::ET_MOUSEWHEEL;
case WM_MOUSELEAVE:
case WM_NCMOUSELEAVE:
return ui::ET_MOUSE_EXITED;
default:
NOTREACHED();
}
return ui::ET_UNKNOWN;
}
} // namespace
////////////////////////////////////////////////////////////////////////////////
// Event, public:
int Event::GetWindowsFlags() const {
// TODO: need support for x1/x2.
int result = 0;
result |= (flags_ & ui::EF_SHIFT_DOWN) ? MK_SHIFT : 0;
result |= (flags_ & ui::EF_CONTROL_DOWN) ? MK_CONTROL : 0;
result |= (flags_ & ui::EF_LEFT_BUTTON_DOWN) ? MK_LBUTTON : 0;
result |= (flags_ & ui::EF_MIDDLE_BUTTON_DOWN) ? MK_MBUTTON : 0;
result |= (flags_ & ui::EF_RIGHT_BUTTON_DOWN) ? MK_RBUTTON : 0;
return result;
}
//static
int Event::ConvertWindowsFlags(UINT win_flags) {
int r = 0;
if (win_flags & MK_CONTROL)
r |= ui::EF_CONTROL_DOWN;
if (win_flags & MK_SHIFT)
r |= ui::EF_SHIFT_DOWN;
if (GetKeyState(VK_MENU) < 0)
r |= ui::EF_ALT_DOWN;
if (win_flags & MK_LBUTTON)
r |= ui::EF_LEFT_BUTTON_DOWN;
if (win_flags & MK_MBUTTON)
r |= ui::EF_MIDDLE_BUTTON_DOWN;
if (win_flags & MK_RBUTTON)
r |= ui::EF_RIGHT_BUTTON_DOWN;
return r;
}
////////////////////////////////////////////////////////////////////////////////
// Event, private:
void Event::Init() {
ZeroMemory(&native_event_, sizeof(native_event_));
native_event_2_ = NULL;
}
void Event::InitWithNativeEvent(NativeEvent native_event) {
native_event_ = native_event;
// TODO(beng): remove once we rid views of Gtk/Gdk.
native_event_2_ = NULL;
}
void Event::InitWithNativeEvent2(NativeEvent2 native_event_2,
FromNativeEvent2) {
// No one should ever call this on Windows.
// TODO(beng): remove once we rid views of Gtk/Gdk.
NOTREACHED();
native_event_2_ = NULL;
}
////////////////////////////////////////////////////////////////////////////////
// KeyEvent, public:
KeyEvent::KeyEvent(NativeEvent native_event)
: Event(native_event,
EventTypeFromNative(native_event),
GetKeyStateFlags()),
key_code_(ui::KeyboardCodeForWindowsKeyCode(native_event.wParam)) {
}
KeyEvent::KeyEvent(NativeEvent2 native_event_2, FromNativeEvent2 from_native)
: Event(native_event_2, ui::ET_UNKNOWN, 0, from_native) {
// No one should ever call this on Windows.
// TODO(beng): remove once we rid views of Gtk/Gdk.
NOTREACHED();
}
} // namespace views
<|endoftext|> |
<commit_before>#include "gui_web_cam_main_window.h"
#include "ui_gui_web_cam_main_window.h"
#include "../qt_utils/event_filter.h"
#include "../qt_utils/invoke_in_thread.h"
#include "../qt_utils/loop_thread.h"
#include "../cpp_utils/exception.h"
#include <cassert>
#include <QGraphicsScene>
#include <QGraphicsVideoItem>
#include <QPointer>
#include <QtMultimedia/QCameraInfo>
namespace gui {
struct WebCamMainWindow::Impl
{
Ui::WebCamMainWindow ui;
std::unique_ptr<QCamera> webCam;
QGraphicsScene scene;
QGraphicsVideoItem videoItem;
qu::LoopThread worker;
// Makes sure the scene is always shown as big as possible.
void makeSceneFitToView();
// Puts a video display into the scene.
void connectWebCamToVideoItemAsync();
};
WebCamMainWindow::WebCamMainWindow(QWidget *parent) :
QMainWindow(parent),
m(new Impl)
{
m->ui.setupUi(this);
m->connectWebCamToVideoItemAsync();
// put mirrored item into a QGraphicsScene.
m->videoItem.setMatrix( QMatrix(-1,0,0,1,0,0),true );
m->scene.addItem( &m->videoItem );
m->makeSceneFitToView();
// put scene into graphicsView.
m->ui.graphicsView->setScene(&m->scene);
}
WebCamMainWindow::~WebCamMainWindow()
{
}
void WebCamMainWindow::Impl::makeSceneFitToView()
{
auto view = QPointer<QGraphicsView>(ui.graphicsView);
qu::installEventFilter( ui.graphicsView,
[view]( QObject *, QEvent * event )
{
if ( event->type() == QEvent::Paint
&& view->scene() )
{
view->fitInView( view->sceneRect(),
Qt::KeepAspectRatio );
}
return false;
});
}
void WebCamMainWindow::Impl::connectWebCamToVideoItemAsync()
{
// switch to worker thread.
qu::invokeInThread( &worker, [this](){
const auto cams = QCameraInfo::availableCameras();
const auto nCams = cams.count();
CU_ENFORCE( nCams > 0, "No cameras could be detected." )
// initialize camera.
webCam.reset( new QCamera(cams.front()) );
webCam->moveToThread( QCoreApplication::instance()->thread() );
// switch back to gui thread
qu::invokeInGuiThread( [this,nCams](){
// set QGraphicsItem as view finder and start capturing images.
webCam->setViewfinder( &videoItem );
webCam->start();
} ); // end of gui thread execution
} ); // end of worker thread execution
}
} // namespace gui
<commit_msg>Added check for view being alive when changing its visible rectangle.<commit_after>#include "gui_web_cam_main_window.h"
#include "ui_gui_web_cam_main_window.h"
#include "../qt_utils/event_filter.h"
#include "../qt_utils/invoke_in_thread.h"
#include "../qt_utils/loop_thread.h"
#include "../cpp_utils/exception.h"
#include <cassert>
#include <QGraphicsScene>
#include <QGraphicsVideoItem>
#include <QPointer>
#include <QtMultimedia/QCameraInfo>
namespace gui {
struct WebCamMainWindow::Impl
{
Ui::WebCamMainWindow ui;
std::unique_ptr<QCamera> webCam;
QGraphicsScene scene;
QGraphicsVideoItem videoItem;
qu::LoopThread worker;
// Makes sure the scene is always shown as big as possible.
void makeSceneFitToView();
// Puts a video display into the scene.
void connectWebCamToVideoItemAsync();
};
WebCamMainWindow::WebCamMainWindow(QWidget *parent) :
QMainWindow(parent),
m(new Impl)
{
m->ui.setupUi(this);
m->connectWebCamToVideoItemAsync();
// put mirrored item into a QGraphicsScene.
m->videoItem.setMatrix( QMatrix(-1,0,0,1,0,0),true );
m->scene.addItem( &m->videoItem );
m->makeSceneFitToView();
// put scene into graphicsView.
m->ui.graphicsView->setScene(&m->scene);
}
WebCamMainWindow::~WebCamMainWindow()
{
}
void WebCamMainWindow::Impl::makeSceneFitToView()
{
auto view = QPointer<QGraphicsView>(ui.graphicsView);
qu::installEventFilter( ui.graphicsView,
[view]( QObject *, QEvent * event )
{
if ( event->type() == QEvent::Paint
&& !view.isNull()
&& view->scene() )
{
view->fitInView( view->sceneRect(),
Qt::KeepAspectRatio );
}
return false;
});
}
void WebCamMainWindow::Impl::connectWebCamToVideoItemAsync()
{
// switch to worker thread.
qu::invokeInThread( &worker, [this](){
const auto cams = QCameraInfo::availableCameras();
const auto nCams = cams.count();
CU_ENFORCE( nCams > 0, "No cameras could be detected." )
// initialize camera.
webCam.reset( new QCamera(cams.front()) );
webCam->moveToThread( QCoreApplication::instance()->thread() );
// switch back to gui thread
qu::invokeInGuiThread( [this,nCams](){
// set QGraphicsItem as view finder and start capturing images.
webCam->setViewfinder( &videoItem );
webCam->start();
} ); // end of gui thread execution
} ); // end of worker thread execution
}
} // namespace gui
<|endoftext|> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.