text
stringlengths
54
60.6k
<commit_before>97214a23-2747-11e6-88ce-e0f84713e7b8<commit_msg>Hey we can now do a thing<commit_after>972ffdc5-2747-11e6-ab08-e0f84713e7b8<|endoftext|>
<commit_before>/* * main.cpp * openc2e * * Created by Alyssa Milburn on Wed 02 Jun 2004. * Copyright (c) 2004-2008 Alyssa Milburn. All rights reserved. * Copyright (c) 2005-2008 Bryan Donlan. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ #include "openc2e.h" #include <iostream> #include "Engine.h" #include "World.h" #include "SDLBackend.h" #include "NullBackend.h" #include "OpenALBackend.h" #ifdef _WIN32 #include <shlobj.h> #endif extern "C" int main(int argc, char *argv[]) { try { std::cout << "openc2e (development build), built " __DATE__ " " __TIME__ "\nCopyright (c) 2004-2008 Alyssa Milburn and others\n\n"; engine.addPossibleBackend("sdl", shared_ptr<Backend>(new SDLBackend())); #ifdef OPENAL_SUPPORT engine.addPossibleAudioBackend("openal", shared_ptr<AudioBackend>(new OpenALBackend())); #endif // pass command-line flags to the engine, but do no other setup if (!engine.parseCommandLine(argc, argv)) return 1; // get the engine to do all the startup (read catalogue, loading world, etc) if (!engine.initialSetup()) return 0; // you *must* call this at least once before drawing, for initial creation of the window engine.backend->resize(800, 600); // do a first-pass draw of the world. TODO: correct? world.drawWorld(); while (!engine.done) { if (!engine.tick()) // if the engine didn't need an update.. SDL_Delay(10); // .. delay for a short while } // main loop // we're done, be sure to shut stuff down engine.shutdown(); } catch (std::exception &e) { #ifdef _WIN32 MessageBox(NULL, e.what(), "openc2e - Fatal exception encountered:", MB_ICONERROR); #else std::cerr << "Fatal exception encountered: " << e.what() << "\n"; #endif return 1; } return 0; } /* vim: set noet: */ <commit_msg>Fix brokenness with OpenAL disabled<commit_after>/* * main.cpp * openc2e * * Created by Alyssa Milburn on Wed 02 Jun 2004. * Copyright (c) 2004-2008 Alyssa Milburn. All rights reserved. * Copyright (c) 2005-2008 Bryan Donlan. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ #include "openc2e.h" #include <iostream> #include "Engine.h" #include "World.h" #include "SDLBackend.h" #include "NullBackend.h" #ifdef OPENAL_SUPPORT #include "OpenALBackend.h" #endif #ifdef _WIN32 #include <shlobj.h> #endif extern "C" int main(int argc, char *argv[]) { try { std::cout << "openc2e (development build), built " __DATE__ " " __TIME__ "\nCopyright (c) 2004-2008 Alyssa Milburn and others\n\n"; engine.addPossibleBackend("sdl", shared_ptr<Backend>(new SDLBackend())); #ifdef OPENAL_SUPPORT engine.addPossibleAudioBackend("openal", shared_ptr<AudioBackend>(new OpenALBackend())); #endif // pass command-line flags to the engine, but do no other setup if (!engine.parseCommandLine(argc, argv)) return 1; // get the engine to do all the startup (read catalogue, loading world, etc) if (!engine.initialSetup()) return 0; // you *must* call this at least once before drawing, for initial creation of the window engine.backend->resize(800, 600); // do a first-pass draw of the world. TODO: correct? world.drawWorld(); while (!engine.done) { if (!engine.tick()) // if the engine didn't need an update.. SDL_Delay(10); // .. delay for a short while } // main loop // we're done, be sure to shut stuff down engine.shutdown(); } catch (std::exception &e) { #ifdef _WIN32 MessageBox(NULL, e.what(), "openc2e - Fatal exception encountered:", MB_ICONERROR); #else std::cerr << "Fatal exception encountered: " << e.what() << "\n"; #endif return 1; } return 0; } /* vim: set noet: */ <|endoftext|>
<commit_before>fbe33f70-2d3e-11e5-9ab4-c82a142b6f9b<commit_msg>fc578007-2d3e-11e5-adb5-c82a142b6f9b<commit_after>fc578007-2d3e-11e5-adb5-c82a142b6f9b<|endoftext|>
<commit_before>f2087917-327f-11e5-84e4-9cf387a8033e<commit_msg>f20e1d9e-327f-11e5-bd75-9cf387a8033e<commit_after>f20e1d9e-327f-11e5-bd75-9cf387a8033e<|endoftext|>
<commit_before>d379ad9c-313a-11e5-a99c-3c15c2e10482<commit_msg>d3804e05-313a-11e5-8186-3c15c2e10482<commit_after>d3804e05-313a-11e5-8186-3c15c2e10482<|endoftext|>
<commit_before>// Copyright 2017 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "riegeli/bytes/message_parse.h" #include <stddef.h> #include <limits> #include <tuple> #include "absl/base/optimization.h" #include "absl/strings/str_cat.h" #include "google/protobuf/io/zero_copy_stream.h" #include "google/protobuf/message_lite.h" #include "riegeli/base/base.h" #include "riegeli/base/canonical_errors.h" #include "riegeli/base/chain.h" #include "riegeli/base/status.h" #include "riegeli/bytes/chain_reader.h" #include "riegeli/bytes/reader.h" namespace riegeli { namespace { // ReaderInputStream adapts a Reader to a ZeroCopyInputStream. class ReaderInputStream : public google::protobuf::io::ZeroCopyInputStream { public: explicit ReaderInputStream(Reader* src) : src_(RIEGELI_ASSERT_NOTNULL(src)), initial_pos_(src_->pos()) {} bool Next(const void** data, int* size) override; void BackUp(int length) override; bool Skip(int length) override; google::protobuf::int64 ByteCount() const override; private: Position relative_pos() const; Reader* src_; // Invariants: // src_->pos() >= initial_pos_ // src_->pos() - initial_pos_ <= // numeric_limits<google::protobuf::int64>::max() Position initial_pos_; }; inline Position ReaderInputStream::relative_pos() const { RIEGELI_ASSERT_GE(src_->pos(), initial_pos_) << "Failed invariant of ReaderInputStream: " "current position smaller than initial position"; const Position pos = src_->pos() - initial_pos_; RIEGELI_ASSERT_LE( pos, Position{std::numeric_limits<google::protobuf::int64>::max()}) << "Failed invariant of ReaderInputStream: " "relative position overflow"; return pos; } bool ReaderInputStream::Next(const void** data, int* size) { const Position pos = relative_pos(); if (ABSL_PREDICT_FALSE( pos == Position{std::numeric_limits<google::protobuf::int64>::max()})) { return false; } if (ABSL_PREDICT_FALSE(!src_->Pull())) return false; *data = src_->cursor(); *size = IntCast<int>(UnsignedMin( src_->available(), size_t{std::numeric_limits<int>::max()}, Position{std::numeric_limits<google::protobuf::int64>::max()} - pos)); src_->set_cursor(src_->cursor() + *size); return true; } void ReaderInputStream::BackUp(int length) { RIEGELI_ASSERT_GE(length, 0) << "Failed precondition of ZeroCopyInputStream::BackUp(): " "negative length"; RIEGELI_ASSERT_LE(IntCast<size_t>(length), src_->read_from_buffer()) << "Failed precondition of ZeroCopyInputStream::BackUp(): " "length larger than the amount of buffered data"; src_->set_cursor(src_->cursor() - length); } bool ReaderInputStream::Skip(int length) { RIEGELI_ASSERT_GE(length, 0) << "Failed precondition of ZeroCopyInputStream::Skip(): negative length"; const Position max_length = Position{std::numeric_limits<google::protobuf::int64>::max()} - relative_pos(); if (ABSL_PREDICT_FALSE(IntCast<size_t>(length) > max_length)) { src_->Skip(max_length); return false; } return src_->Skip(IntCast<size_t>(length)); } google::protobuf::int64 ReaderInputStream::ByteCount() const { return IntCast<google::protobuf::int64>(relative_pos()); } } // namespace namespace internal { Status ParseFromReaderImpl(google::protobuf::MessageLite* dest, Reader* src) { { const Status status = ParsePartialFromReaderImpl(dest, src); if (ABSL_PREDICT_FALSE(!status.ok())) return status; } if (ABSL_PREDICT_FALSE(!dest->IsInitialized())) { return DataLossError( absl::StrCat("Failed to parse message of type ", dest->GetTypeName(), " because it is missing required fields: ", dest->InitializationErrorString())); } return OkStatus(); } Status ParsePartialFromReaderImpl(google::protobuf::MessageLite* dest, Reader* src) { if (src->SupportsRandomAccess()) { Position size; if (ABSL_PREDICT_FALSE(!src->Size(&size))) return src->status(); src->Pull(); if (src->pos() + src->available() == size && ABSL_PREDICT_TRUE(src->available() <= size_t{std::numeric_limits<int>::max()})) { // The data are flat. ParsePartialFromArray() is faster than // ParsePartialFromZeroCopyStream(). bool ok = dest->ParsePartialFromArray(src->cursor(), IntCast<int>(src->available())); src->set_cursor(src->cursor() + src->available()); if (ABSL_PREDICT_FALSE(!ok)) { return DataLossError(absl::StrCat("Failed to parse message of type ", dest->GetTypeName())); } return OkStatus(); } } return ParsePartialFromReaderUsingInputStream(dest, src); } Status ParseFromReaderUsingInputStream(google::protobuf::MessageLite* dest, Reader* src) { { const Status status = ParsePartialFromReaderUsingInputStream(dest, src); if (ABSL_PREDICT_FALSE(!status.ok())) return status; } if (ABSL_PREDICT_FALSE(!dest->IsInitialized())) { return DataLossError( absl::StrCat("Failed to parse message of type ", dest->GetTypeName(), " because it is missing required fields: ", dest->InitializationErrorString())); } return OkStatus(); } Status ParsePartialFromReaderUsingInputStream( google::protobuf::MessageLite* dest, Reader* src) { ReaderInputStream input_stream(src); if (ABSL_PREDICT_FALSE( !dest->ParsePartialFromZeroCopyStream(&input_stream))) { if (ABSL_PREDICT_FALSE(!src->healthy())) return src->status(); return DataLossError( absl::StrCat("Failed to parse message of type ", dest->GetTypeName())); } return OkStatus(); } } // namespace internal Status ParseFromChain(google::protobuf::MessageLite* dest, const Chain& src) { { const Status status = ParsePartialFromChain(dest, src); if (ABSL_PREDICT_FALSE(!status.ok())) return status; } if (ABSL_PREDICT_FALSE(!dest->IsInitialized())) { return DataLossError( absl::StrCat("Failed to parse message of type ", dest->GetTypeName(), " because it is missing required fields: ", dest->InitializationErrorString())); } return OkStatus(); } Status ParsePartialFromChain(google::protobuf::MessageLite* dest, const Chain& src) { if (absl::optional<absl::string_view> flat = src.TryFlat()) { if (ABSL_PREDICT_TRUE(flat->size() <= size_t{std::numeric_limits<int>::max()})) { // The data are flat. ParsePartialFromArray() is faster than // ParsePartialFromZeroCopyStream(). if (ABSL_PREDICT_FALSE(!dest->ParsePartialFromArray( flat->data(), IntCast<int>(flat->size())))) { return DataLossError(absl::StrCat("Failed to parse message of type ", dest->GetTypeName())); } return OkStatus(); } } ChainReader<> reader(&src); return internal::ParsePartialFromReaderImpl(dest, &reader); } } // namespace riegeli <commit_msg>Explain why the ChainReader<> is not closed.<commit_after>// Copyright 2017 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "riegeli/bytes/message_parse.h" #include <stddef.h> #include <limits> #include <tuple> #include "absl/base/optimization.h" #include "absl/strings/str_cat.h" #include "google/protobuf/io/zero_copy_stream.h" #include "google/protobuf/message_lite.h" #include "riegeli/base/base.h" #include "riegeli/base/canonical_errors.h" #include "riegeli/base/chain.h" #include "riegeli/base/status.h" #include "riegeli/bytes/chain_reader.h" #include "riegeli/bytes/reader.h" namespace riegeli { namespace { // ReaderInputStream adapts a Reader to a ZeroCopyInputStream. class ReaderInputStream : public google::protobuf::io::ZeroCopyInputStream { public: explicit ReaderInputStream(Reader* src) : src_(RIEGELI_ASSERT_NOTNULL(src)), initial_pos_(src_->pos()) {} bool Next(const void** data, int* size) override; void BackUp(int length) override; bool Skip(int length) override; google::protobuf::int64 ByteCount() const override; private: Position relative_pos() const; Reader* src_; // Invariants: // src_->pos() >= initial_pos_ // src_->pos() - initial_pos_ <= // numeric_limits<google::protobuf::int64>::max() Position initial_pos_; }; inline Position ReaderInputStream::relative_pos() const { RIEGELI_ASSERT_GE(src_->pos(), initial_pos_) << "Failed invariant of ReaderInputStream: " "current position smaller than initial position"; const Position pos = src_->pos() - initial_pos_; RIEGELI_ASSERT_LE( pos, Position{std::numeric_limits<google::protobuf::int64>::max()}) << "Failed invariant of ReaderInputStream: " "relative position overflow"; return pos; } bool ReaderInputStream::Next(const void** data, int* size) { const Position pos = relative_pos(); if (ABSL_PREDICT_FALSE( pos == Position{std::numeric_limits<google::protobuf::int64>::max()})) { return false; } if (ABSL_PREDICT_FALSE(!src_->Pull())) return false; *data = src_->cursor(); *size = IntCast<int>(UnsignedMin( src_->available(), size_t{std::numeric_limits<int>::max()}, Position{std::numeric_limits<google::protobuf::int64>::max()} - pos)); src_->set_cursor(src_->cursor() + *size); return true; } void ReaderInputStream::BackUp(int length) { RIEGELI_ASSERT_GE(length, 0) << "Failed precondition of ZeroCopyInputStream::BackUp(): " "negative length"; RIEGELI_ASSERT_LE(IntCast<size_t>(length), src_->read_from_buffer()) << "Failed precondition of ZeroCopyInputStream::BackUp(): " "length larger than the amount of buffered data"; src_->set_cursor(src_->cursor() - length); } bool ReaderInputStream::Skip(int length) { RIEGELI_ASSERT_GE(length, 0) << "Failed precondition of ZeroCopyInputStream::Skip(): negative length"; const Position max_length = Position{std::numeric_limits<google::protobuf::int64>::max()} - relative_pos(); if (ABSL_PREDICT_FALSE(IntCast<size_t>(length) > max_length)) { src_->Skip(max_length); return false; } return src_->Skip(IntCast<size_t>(length)); } google::protobuf::int64 ReaderInputStream::ByteCount() const { return IntCast<google::protobuf::int64>(relative_pos()); } } // namespace namespace internal { Status ParseFromReaderImpl(google::protobuf::MessageLite* dest, Reader* src) { { const Status status = ParsePartialFromReaderImpl(dest, src); if (ABSL_PREDICT_FALSE(!status.ok())) return status; } if (ABSL_PREDICT_FALSE(!dest->IsInitialized())) { return DataLossError( absl::StrCat("Failed to parse message of type ", dest->GetTypeName(), " because it is missing required fields: ", dest->InitializationErrorString())); } return OkStatus(); } Status ParsePartialFromReaderImpl(google::protobuf::MessageLite* dest, Reader* src) { if (src->SupportsRandomAccess()) { Position size; if (ABSL_PREDICT_FALSE(!src->Size(&size))) return src->status(); src->Pull(); if (src->pos() + src->available() == size && ABSL_PREDICT_TRUE(src->available() <= size_t{std::numeric_limits<int>::max()})) { // The data are flat. ParsePartialFromArray() is faster than // ParsePartialFromZeroCopyStream(). bool ok = dest->ParsePartialFromArray(src->cursor(), IntCast<int>(src->available())); src->set_cursor(src->cursor() + src->available()); if (ABSL_PREDICT_FALSE(!ok)) { return DataLossError(absl::StrCat("Failed to parse message of type ", dest->GetTypeName())); } return OkStatus(); } } return ParsePartialFromReaderUsingInputStream(dest, src); } Status ParseFromReaderUsingInputStream(google::protobuf::MessageLite* dest, Reader* src) { { const Status status = ParsePartialFromReaderUsingInputStream(dest, src); if (ABSL_PREDICT_FALSE(!status.ok())) return status; } if (ABSL_PREDICT_FALSE(!dest->IsInitialized())) { return DataLossError( absl::StrCat("Failed to parse message of type ", dest->GetTypeName(), " because it is missing required fields: ", dest->InitializationErrorString())); } return OkStatus(); } Status ParsePartialFromReaderUsingInputStream( google::protobuf::MessageLite* dest, Reader* src) { ReaderInputStream input_stream(src); if (ABSL_PREDICT_FALSE( !dest->ParsePartialFromZeroCopyStream(&input_stream))) { if (ABSL_PREDICT_FALSE(!src->healthy())) return src->status(); return DataLossError( absl::StrCat("Failed to parse message of type ", dest->GetTypeName())); } return OkStatus(); } } // namespace internal Status ParseFromChain(google::protobuf::MessageLite* dest, const Chain& src) { { const Status status = ParsePartialFromChain(dest, src); if (ABSL_PREDICT_FALSE(!status.ok())) return status; } if (ABSL_PREDICT_FALSE(!dest->IsInitialized())) { return DataLossError( absl::StrCat("Failed to parse message of type ", dest->GetTypeName(), " because it is missing required fields: ", dest->InitializationErrorString())); } return OkStatus(); } Status ParsePartialFromChain(google::protobuf::MessageLite* dest, const Chain& src) { if (absl::optional<absl::string_view> flat = src.TryFlat()) { if (ABSL_PREDICT_TRUE(flat->size() <= size_t{std::numeric_limits<int>::max()})) { // The data are flat. ParsePartialFromArray() is faster than // ParsePartialFromZeroCopyStream(). if (ABSL_PREDICT_FALSE(!dest->ParsePartialFromArray( flat->data(), IntCast<int>(flat->size())))) { return DataLossError(absl::StrCat("Failed to parse message of type ", dest->GetTypeName())); } return OkStatus(); } } ChainReader<> reader(&src); return internal::ParsePartialFromReaderImpl(dest, &reader); // Do not bother closing the ChainReader<>, it can never fail. } } // namespace riegeli <|endoftext|>
<commit_before>// Test driver for the StreamReader classes. // Author: Eric McDonald #include <cerrno> #include <climits> extern "C" { #include <stdint.h> } //#define SSIZE_MAX (SIZE_MAX / 2) #include <cstring> #include <cstdio> #include <fcntl.h> #include <sys/stat.h> #include <cstdlib> #include <error.h> #include <getopt.h> #include "read_parsers.hh" using namespace khmer; using namespace khmer:: read_parsers; // t: Stream Type // s: Cache Size static char const * SHORT_OPTS = "t:s:"; int main( int argc, char * argv[ ] ) { int rc = 0; char * ifile_type = (char *)"raw"; uint64_t cache_size = 4L * 1024 * 1024 * 1024; uint8_t * cache = NULL; char * ifile_name = NULL; char * ofile_name = NULL; int ifd = -1; int ofd = -1; IStreamReader * sr = NULL; int opt = -1; char * conv_residue = NULL; while (-1 != (opt = getopt( argc, argv, SHORT_OPTS ))) { switch (opt) { case 't': if ( strcmp( optarg, "raw" ) && strcmp( optarg, "gz" ) && strcmp( optarg, "bz2" ) ) error( EINVAL, EINVAL, "Invalid file type" ); ifile_type = new char[ strlen( optarg ) ]; strcpy( ifile_type, optarg ); break; case 's': cache_size = strtoull( optarg, &conv_residue, 10 ); if (!strcmp( optarg, conv_residue )) error( EINVAL, EINVAL, "Invalid cache size" ); break; default: error( 0, 0, "Skipping unknown arg, '%c'", optopt ); } // option switch } // getopt loop if (optind < argc) ifile_name = argv[ optind++ ]; else error( EINVAL, 0, "Input file name required" ); if (optind < argc) ofile_name = argv[ optind++ ]; else error( EINVAL, 0, "Output file name required" ); // TODO: Handle stdin. // TODO: Play with O_DIRECT. if (-1 == (ifd = open( ifile_name, O_RDONLY ))) error( errno, errno, "Failed to open input file" ); // TODO: Handle stdout. if (-1 == (ofd = creat( ofile_name, 0644 ))) error( errno, errno, "Failed to open output file" ); try { if (!strcmp( "raw", ifile_type )) sr = new RawStreamReader( ifd ); else if (!strcmp( "gz", ifile_type )) sr = new GzStreamReader( ifd ); else if (!strcmp( "bz2", ifile_type )) sr = new Bz2StreamReader( ifd ); } catch (InvalidStreamBuffer & exc) { error( EBADF, EBADF, "Failed to initialize stream reader" ); } try { cache = new uint8_t[ cache_size ]; } catch (std:: bad_alloc & exc) { error( ENOMEM, ENOMEM, "Failed to allocate cache" ); } uint64_t nbread = 0; ssize_t nbwrote = 0; uint64_t nbread_total = 0; uint64_t nbwrote_total = 0; while (!sr->is_at_end_of_stream( )) { uint64_t nbwrote_subtotal = 0; try { nbread = sr->read_into_cache( cache, cache_size ); nbread_total += nbread; for ( uint64_t nbrem = nbread; 0 < nbrem; nbrem -= nbwrote ) { nbwrote = write( ofd, cache + nbwrote_subtotal, (nbrem > SSIZE_MAX ? SSIZE_MAX : nbrem) ); if (-1 == nbwrote) error( EIO, EIO, "Error during write of output stream" ); nbwrote_subtotal += nbwrote; } nbwrote_total += nbwrote_subtotal; } catch (StreamReadError & exc) { error( EIO, EIO, "Error during read of input stream" ); } catch (...) { throw; } fprintf( stdout, "Read %llu bytes from disk.\n", (long long unsigned int)nbread ); fprintf( stdout, "Wrote %llu bytes to disk.\n", (long long unsigned int)nbwrote_subtotal ); } // stream reader read loop fprintf( stdout, "Read %llu bytes in total from disk.\n", (long long unsigned int)nbread_total ); fprintf( stdout, "Wrote %llu bytes in total to disk.\n", (long long unsigned int)nbwrote_total ); close( ofd ); return rc; } // vim: set ft=cpp sts=4 sw=4 tw=80: <commit_msg>Petty cosmetic fix.<commit_after>// Test driver for the StreamReader classes. // Author: Eric McDonald #include <cerrno> #include <climits> extern "C" { #include <stdint.h> } //#define SSIZE_MAX (SIZE_MAX / 2) #include <cstring> #include <cstdio> #include <fcntl.h> #include <sys/stat.h> #include <cstdlib> #include <error.h> #include <getopt.h> #include "read_parsers.hh" using namespace khmer; using namespace khmer:: read_parsers; // t: Stream Type // s: Cache Size static char const * SHORT_OPTS = "t:s:"; int main( int argc, char * argv[ ] ) { int rc = 0; char * ifile_type = (char *)"raw"; uint64_t cache_size = 4L * 1024 * 1024 * 1024; uint8_t * cache = NULL; char * ifile_name = NULL; char * ofile_name = NULL; int ifd = -1; int ofd = -1; IStreamReader * sr = NULL; int opt = -1; char * conv_residue = NULL; while (-1 != (opt = getopt( argc, argv, SHORT_OPTS ))) { switch (opt) { case 't': if ( strcmp( optarg, "raw" ) && strcmp( optarg, "gz" ) && strcmp( optarg, "bz2" ) ) error( EINVAL, EINVAL, "Invalid file type" ); ifile_type = new char[ strlen( optarg ) ]; strcpy( ifile_type, optarg ); break; case 's': cache_size = strtoull( optarg, &conv_residue, 10 ); if (!strcmp( optarg, conv_residue )) error( EINVAL, EINVAL, "Invalid cache size" ); break; default: error( 0, 0, "Skipping unknown arg, '%c'", optopt ); } // option switch } // getopt loop if (optind < argc) ifile_name = argv[ optind++ ]; else error( EINVAL, 0, "Input file name required" ); if (optind < argc) ofile_name = argv[ optind++ ]; else error( EINVAL, 0, "Output file name required" ); // TODO: Handle stdin. // TODO: Play with O_DIRECT. if (-1 == (ifd = open( ifile_name, O_RDONLY ))) error( errno, errno, "Failed to open input file" ); // TODO: Handle stdout. if (-1 == (ofd = creat( ofile_name, 0644 ))) error( errno, errno, "Failed to open output file" ); try { if (!strcmp( "raw", ifile_type )) sr = new RawStreamReader( ifd ); else if (!strcmp( "gz", ifile_type )) sr = new GzStreamReader( ifd ); else if (!strcmp( "bz2", ifile_type )) sr = new Bz2StreamReader( ifd ); } catch (InvalidStreamBuffer & exc) { error( EBADF, EBADF, "Failed to initialize stream reader" ); } try { cache = new uint8_t[ cache_size ]; } catch (std:: bad_alloc & exc) { error( ENOMEM, ENOMEM, "Failed to allocate cache" ); } uint64_t nbread = 0; ssize_t nbwrote = 0; uint64_t nbread_total = 0; uint64_t nbwrote_total = 0; while (!sr->is_at_end_of_stream( )) { uint64_t nbwrote_subtotal = 0; try { nbread = sr->read_into_cache( cache, cache_size ); nbread_total += nbread; for ( uint64_t nbrem = nbread; 0 < nbrem; nbrem -= nbwrote ) { nbwrote = write( ofd, cache + nbwrote_subtotal, (nbrem > SSIZE_MAX ? SSIZE_MAX : nbrem) ); if (-1 == nbwrote) error( EIO, EIO, "Error during write of output stream" ); nbwrote_subtotal += nbwrote; } nbwrote_total += nbwrote_subtotal; } catch (StreamReadError & exc) { error( EIO, EIO, "Error during read of input stream" ); } catch (...) { throw; } fprintf( stdout, "Read %llu bytes from disk.\n", (long long unsigned int)nbread ); fprintf( stdout, "Wrote %llu bytes to disk.\n", (long long unsigned int)nbwrote_subtotal ); } // stream reader read loop fprintf( stdout, "Read %llu bytes in total from disk.\n", (long long unsigned int)nbread_total ); fprintf( stdout, "Wrote %llu bytes in total to disk.\n", (long long unsigned int)nbwrote_total ); close( ofd ); return rc; } // vim: set ft=cpp sts=4 sw=4 tw=80: <|endoftext|>
<commit_before>#include <cstdio> #include <random> #include <cmath> #include <string> #include <cstring> #include <stdexcept> #include <cassert> #include <iostream> #define TRACE(a) std::cout<<a<<std::endl; //------------------------------------------------------------------------------ namespace base91 { static const unsigned base=91; static const unsigned char_bits=8; static const unsigned digit_bits=13; static const unsigned digit_size=0x2000; static const unsigned digit_mask=0x1FFF; char hi[digit_size]={'~',}; char lo[digit_size]={'~',}; unsigned short hilo[base][base]={0,}; //------------------------------------------------------------------------------ void encode(const std::vector<unsigned char> & in,std::string & out) { out.clear(); out.reserve(digit_bits*in.size()/char_bits+2); unsigned acc=0; unsigned bitacc=0; for (auto & n:in) { acc |= n<<bitacc; bitacc+=char_bits; TRACE("added "<<static_cast<short>(n)<<" : "<<acc<<" , "<<bitacc); while(digit_bits<=bitacc) { const unsigned cod = digit_mask & acc; out.push_back(lo[cod]); out.push_back(hi[cod]); acc>>=digit_bits; bitacc-=digit_bits; TRACE("pushed "<<lo[cod]<<" : "<<hi[cod]<<" : "<<cod<<" , "<<acc<<" , "<<bitacc); } } if(0 != bitacc) { const unsigned cod = digit_mask & acc; out.push_back(lo[cod]); out.push_back(hi[cod]); TRACE("push_ "<<lo[cod]<<" : "<<hi[cod]<<" : "<<cod<<" , "<<acc<<" , "<<bitacc); } return; } //------------------------------------------------------------------------------ void decode(const std::string & in,std::vector<unsigned char> & out) { out.clear(); out.reserve(char_bits*in.size()/digit_bits); unsigned acc=0; int bitacc=0; short lower=-1; for (auto & n:in) { if(-1==lower) { lower=n-'!'; continue; } acc|=hilo[n-'!'][lower]<<bitacc; bitacc+=digit_bits; lower=-1; while(char_bits<=bitacc) { out.push_back(0xFF & acc); acc>>=char_bits; bitacc-=char_bits; } } if(-1!=lower) { acc<<=digit_bits; acc|=hilo[0][lower]; bitacc+=7; } while(char_bits<=bitacc) { out.push_back(0xFF & acc); acc>>=char_bits; bitacc-=char_bits; } return; } } //------------------------------------------------------------------------------ int main() { for(unsigned n=0, hi=0,lo=0;n<base91::digit_size;++n) { base91::lo[n]='!'+lo; base91::hi[n]='!'+hi; base91::hilo[hi][lo]=n; if(base91::base==(++lo)) { hi++; lo=0; } } srand(time(nullptr)); std::vector<unsigned char> in;//{0,143,10,15}; const unsigned size=10;//rand()%15; for (unsigned n=0;n<size;++n) in.push_back(rand()%256); std::string out; base91::encode(in,out); std::cout<<out<<std::endl; std::vector<unsigned char> test; base91::decode(out,test); if(in.size() != test.size()) { TRACE(in.size() <<"!="<< test.size()); return EXIT_FAILURE; } for (unsigned n=0;n<size;++n) { if(in[n]!=test[n]) { TRACE(n<<" ! "<<static_cast<short>(in[n])<<" != "<< static_cast<short>(test[n])); } else { TRACE(n<<" : "<<static_cast<short>(in[n])<<" == "<< static_cast<short>(test[n])); } } return EXIT_SUCCESS; } //------------------------------------------------------------------------------ <commit_msg>found bug with 10 input bytes<commit_after>#include <cstdio> #include <random> #include <cmath> #include <string> #include <cstring> #include <stdexcept> #include <cassert> #include <iostream> #define TRACE(a) std::cout<<a<<std::endl; //------------------------------------------------------------------------------ namespace base91 { static const unsigned base=91; static const unsigned char_bits=8; static const unsigned digit_bits=13; static const unsigned digit_size=0x2000; static const unsigned digit_mask=0x1FFF; char hi[digit_size]={'~',}; char lo[digit_size]={'~',}; unsigned short hilo[base][base]={0,}; //------------------------------------------------------------------------------ void encode(const std::vector<unsigned char> & in,std::string & out) { out.clear(); out.reserve(digit_bits*in.size()/char_bits+2); unsigned acc=0; unsigned bitacc=0; for (auto & n:in) { acc |= n<<bitacc; bitacc+=char_bits; TRACE("added "<<static_cast<short>(n)<<" : "<<acc<<" , "<<bitacc); while(digit_bits<=bitacc) { const unsigned cod = digit_mask & acc; out.push_back(lo[cod]); out.push_back(hi[cod]); acc>>=digit_bits; bitacc-=digit_bits; TRACE("pushed "<<lo[cod]<<" : "<<hi[cod]<<" : "<<cod<<" , "<<acc<<" , "<<bitacc); } } if(0 != bitacc) { const unsigned cod = digit_mask & acc; out.push_back(lo[cod]); if(7<=bitacc) { out.push_back(hi[cod]); TRACE("push_ "<<lo[cod]<<" : "<<hi[cod]<<" : "<<cod<<" , "<<acc<<" , "<<bitacc); } } return; } //------------------------------------------------------------------------------ void decode(const std::string & in,std::vector<unsigned char> & out) { out.clear(); out.reserve(char_bits*in.size()/digit_bits); TRACE("\ndecode\n"); unsigned acc=0; int bitacc=0; short lower=-1; for (auto & n:in) { if(-1==lower) { lower=n-'!'; continue; } acc|=hilo[n-'!'][lower]<<bitacc; bitacc+=digit_bits; lower=-1; while(char_bits<=bitacc) { out.push_back(0xFF & acc); acc>>=char_bits; bitacc-=char_bits; } } if(-1!=lower) { acc<<=digit_bits; acc|=hilo[0][lower]; bitacc+=7; } while(char_bits<=bitacc) { out.push_back(0xFF & acc); acc>>=char_bits; bitacc-=char_bits; } return; } } //------------------------------------------------------------------------------ int main() { for(unsigned n=0, hi=0,lo=0;n<base91::digit_size;++n) { base91::lo[n]='!'+lo; base91::hi[n]='!'+hi; base91::hilo[hi][lo]=n; if(base91::base==(++lo)) { hi++; lo=0; } } srand(time(nullptr)); std::vector<unsigned char> in;//{0,143,10,15}; const unsigned size=10;//rand()%15; for (unsigned n=0;n<size;++n) in.push_back(rand()%256); std::string out; base91::encode(in,out); std::cout<<out<<std::endl; std::vector<unsigned char> test; base91::decode(out,test); if(in.size() != test.size()) { TRACE(in.size() <<"!="<< test.size()); return EXIT_FAILURE; } for (unsigned n=0;n<size;++n) { if(in[n]!=test[n]) { TRACE(n<<" ! "<<static_cast<short>(in[n])<<" != "<< static_cast<short>(test[n])); } else { TRACE(n<<" : "<<static_cast<short>(in[n])<<" == "<< static_cast<short>(test[n])); } } return EXIT_SUCCESS; } //------------------------------------------------------------------------------ <|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 "sandbox/src/interceptors_64.h" #include "sandbox/src/interceptors.h" #include "sandbox/src/filesystem_interception.h" #include "sandbox/src/named_pipe_interception.h" #include "sandbox/src/policy_target.h" #include "sandbox/src/process_thread_interception.h" #include "sandbox/src/registry_interception.h" #include "sandbox/src/sandbox_nt_types.h" #include "sandbox/src/sandbox_types.h" #include "sandbox/src/sync_interception.h" #include "sandbox/src/target_interceptions.h" namespace sandbox { SANDBOX_INTERCEPT NtExports g_nt; SANDBOX_INTERCEPT OriginalFunctions g_originals; NTSTATUS WINAPI TargetNtMapViewOfSection64( HANDLE section, HANDLE process, PVOID *base, ULONG_PTR zero_bits, SIZE_T commit_size, PLARGE_INTEGER offset, PSIZE_T view_size, SECTION_INHERIT inherit, ULONG allocation_type, ULONG protect) { NtMapViewOfSectionFunction orig_fn = reinterpret_cast< NtMapViewOfSectionFunction>(g_originals[MAP_VIEW_OF_SECTION_ID]); return TargetNtMapViewOfSection(orig_fn, section, process, base, zero_bits, commit_size, offset, view_size, inherit, allocation_type, protect); } NTSTATUS WINAPI TargetNtUnmapViewOfSection64(HANDLE process, PVOID base) { NtUnmapViewOfSectionFunction orig_fn = reinterpret_cast< NtUnmapViewOfSectionFunction>(g_originals[UNMAP_VIEW_OF_SECTION_ID]); return TargetNtUnmapViewOfSection(orig_fn, process, base); } // ----------------------------------------------------------------------- NTSTATUS WINAPI TargetNtSetInformationThread64( HANDLE thread, THREAD_INFORMATION_CLASS thread_info_class, PVOID thread_information, ULONG thread_information_bytes) { NtSetInformationThreadFunction orig_fn = reinterpret_cast< NtSetInformationThreadFunction>(g_originals[SET_INFORMATION_THREAD_ID]); return TargetNtSetInformationThread(orig_fn, thread, thread_info_class, thread_information, thread_information_bytes); } NTSTATUS WINAPI TargetNtOpenThreadToken64( HANDLE thread, ACCESS_MASK desired_access, BOOLEAN open_as_self, PHANDLE token) { NtOpenThreadTokenFunction orig_fn = reinterpret_cast< NtOpenThreadTokenFunction>(g_originals[OPEN_THREAD_TOKEN_ID]); return TargetNtOpenThreadToken(orig_fn, thread, desired_access, open_as_self, token); } NTSTATUS WINAPI TargetNtOpenThreadTokenEx64( HANDLE thread, ACCESS_MASK desired_access, BOOLEAN open_as_self, ULONG handle_attributes, PHANDLE token) { NtOpenThreadTokenExFunction orig_fn = reinterpret_cast< NtOpenThreadTokenExFunction>(g_originals[OPEN_THREAD_TOKEN_EX_ID]); return TargetNtOpenThreadTokenEx(orig_fn, thread, desired_access, open_as_self, handle_attributes, token); } HANDLE WINAPI TargetCreateThread64(LPSECURITY_ATTRIBUTES thread_attributes, SIZE_T stack_size, LPTHREAD_START_ROUTINE start_address, PVOID parameter, DWORD creation_flags, LPDWORD thread_id) { CreateThreadFunction orig_fn = reinterpret_cast< CreateThreadFunction>(g_originals[CREATE_THREAD_ID]); return TargetCreateThread(orig_fn, thread_attributes, stack_size, start_address, parameter, creation_flags, thread_id); } // ----------------------------------------------------------------------- SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtCreateFile64( PHANDLE file, ACCESS_MASK desired_access, POBJECT_ATTRIBUTES object_attributes, PIO_STATUS_BLOCK io_status, PLARGE_INTEGER allocation_size, ULONG file_attributes, ULONG sharing, ULONG disposition, ULONG options, PVOID ea_buffer, ULONG ea_length) { NtCreateFileFunction orig_fn = reinterpret_cast< NtCreateFileFunction>(g_originals[CREATE_FILE_ID]); return TargetNtCreateFile(orig_fn, file, desired_access, object_attributes, io_status, allocation_size, file_attributes, sharing, disposition, options, ea_buffer, ea_length); } SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenFile64( PHANDLE file, ACCESS_MASK desired_access, POBJECT_ATTRIBUTES object_attributes, PIO_STATUS_BLOCK io_status, ULONG sharing, ULONG options) { NtOpenFileFunction orig_fn = reinterpret_cast< NtOpenFileFunction>(g_originals[OPEN_FILE_ID]); return TargetNtOpenFile(orig_fn, file, desired_access, object_attributes, io_status, sharing, options); } SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtQueryAttributesFile64( POBJECT_ATTRIBUTES object_attributes, PFILE_BASIC_INFORMATION file_attributes) { NtQueryAttributesFileFunction orig_fn = reinterpret_cast< NtQueryAttributesFileFunction>(g_originals[QUERY_ATTRIB_FILE_ID]); return TargetNtQueryAttributesFile(orig_fn, object_attributes, file_attributes); } SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtQueryFullAttributesFile64( POBJECT_ATTRIBUTES object_attributes, PFILE_NETWORK_OPEN_INFORMATION file_attributes) { NtQueryFullAttributesFileFunction orig_fn = reinterpret_cast< NtQueryFullAttributesFileFunction>( g_originals[QUERY_FULL_ATTRIB_FILE_ID]); return TargetNtQueryFullAttributesFile(orig_fn, object_attributes, file_attributes); } SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtSetInformationFile64( HANDLE file, PIO_STATUS_BLOCK io_status, PVOID file_information, ULONG length, FILE_INFORMATION_CLASS file_information_class) { NtSetInformationFileFunction orig_fn = reinterpret_cast< NtSetInformationFileFunction>(g_originals[SET_INFO_FILE_ID]); return TargetNtSetInformationFile(orig_fn, file, io_status, file_information, length, file_information_class); } // ----------------------------------------------------------------------- SANDBOX_INTERCEPT HANDLE WINAPI TargetCreateNamedPipeW64( LPCWSTR pipe_name, DWORD open_mode, DWORD pipe_mode, DWORD max_instance, DWORD out_buffer_size, DWORD in_buffer_size, DWORD default_timeout, LPSECURITY_ATTRIBUTES security_attributes) { CreateNamedPipeWFunction orig_fn = reinterpret_cast< CreateNamedPipeWFunction>(g_originals[CREATE_NAMED_PIPE_ID]); return TargetCreateNamedPipeW(orig_fn, pipe_name, open_mode, pipe_mode, max_instance, out_buffer_size, in_buffer_size, default_timeout, security_attributes); } // ----------------------------------------------------------------------- SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenThread64( PHANDLE thread, ACCESS_MASK desired_access, POBJECT_ATTRIBUTES object_attributes, PCLIENT_ID client_id) { NtOpenThreadFunction orig_fn = reinterpret_cast< NtOpenThreadFunction>(g_originals[OPEN_TREAD_ID]); return TargetNtOpenThread(orig_fn, thread, desired_access, object_attributes, client_id); } SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenProcess64( PHANDLE process, ACCESS_MASK desired_access, POBJECT_ATTRIBUTES object_attributes, PCLIENT_ID client_id) { NtOpenProcessFunction orig_fn = reinterpret_cast< NtOpenProcessFunction>(g_originals[OPEN_PROCESS_ID]); return TargetNtOpenProcess(orig_fn, process, desired_access, object_attributes, client_id); } SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenProcessToken64( HANDLE process, ACCESS_MASK desired_access, PHANDLE token) { NtOpenProcessTokenFunction orig_fn = reinterpret_cast< NtOpenProcessTokenFunction>(g_originals[OPEN_PROCESS_TOKEN_ID]); return TargetNtOpenProcessToken(orig_fn, process, desired_access, token); } SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenProcessTokenEx64( HANDLE process, ACCESS_MASK desired_access, ULONG handle_attributes, PHANDLE token) { NtOpenProcessTokenExFunction orig_fn = reinterpret_cast< NtOpenProcessTokenExFunction>(g_originals[OPEN_PROCESS_TOKEN_EX_ID]); return TargetNtOpenProcessTokenEx(orig_fn, process, desired_access, handle_attributes, token); } SANDBOX_INTERCEPT BOOL WINAPI TargetCreateProcessW64( LPCWSTR application_name, LPWSTR command_line, LPSECURITY_ATTRIBUTES process_attributes, LPSECURITY_ATTRIBUTES thread_attributes, BOOL inherit_handles, DWORD flags, LPVOID environment, LPCWSTR current_directory, LPSTARTUPINFOW startup_info, LPPROCESS_INFORMATION process_information) { CreateProcessWFunction orig_fn = reinterpret_cast< CreateProcessWFunction>(g_originals[CREATE_PROCESSW_ID]); return TargetCreateProcessW(orig_fn, application_name, command_line, process_attributes, thread_attributes, inherit_handles, flags, environment, current_directory, startup_info, process_information); } SANDBOX_INTERCEPT BOOL WINAPI TargetCreateProcessA64( LPCSTR application_name, LPSTR command_line, LPSECURITY_ATTRIBUTES process_attributes, LPSECURITY_ATTRIBUTES thread_attributes, BOOL inherit_handles, DWORD flags, LPVOID environment, LPCSTR current_directory, LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION process_information) { CreateProcessAFunction orig_fn = reinterpret_cast< CreateProcessAFunction>(g_originals[CREATE_PROCESSA_ID]); return TargetCreateProcessA(orig_fn, application_name, command_line, process_attributes, thread_attributes, inherit_handles, flags, environment, current_directory, startup_info, process_information); } // ----------------------------------------------------------------------- SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtCreateKey64( PHANDLE key, ACCESS_MASK desired_access, POBJECT_ATTRIBUTES object_attributes, ULONG title_index, PUNICODE_STRING class_name, ULONG create_options, PULONG disposition) { NtCreateKeyFunction orig_fn = reinterpret_cast< NtCreateKeyFunction>(g_originals[CREATE_KEY_ID]); return TargetNtCreateKey(orig_fn, key, desired_access, object_attributes, title_index, class_name, create_options, disposition); } SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenKey64( PHANDLE key, ACCESS_MASK desired_access, POBJECT_ATTRIBUTES object_attributes) { NtOpenKeyFunction orig_fn = reinterpret_cast< NtOpenKeyFunction>(g_originals[OPEN_KEY_ID]); return TargetNtOpenKey(orig_fn, key, desired_access, object_attributes); } SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenKeyEx64( PHANDLE key, ACCESS_MASK desired_access, POBJECT_ATTRIBUTES object_attributes, ULONG open_options) { NtOpenKeyExFunction orig_fn = reinterpret_cast< NtOpenKeyExFunction>(g_originals[OPEN_KEY_EX_ID]); return TargetNtOpenKeyEx(orig_fn, key, desired_access, object_attributes, open_options); } // ----------------------------------------------------------------------- SANDBOX_INTERCEPT HANDLE WINAPI TargetCreateEventW64( LPSECURITY_ATTRIBUTES security_attributes, BOOL manual_reset, BOOL initial_state, LPCWSTR name) { CreateEventWFunction orig_fn = reinterpret_cast< CreateEventWFunction>(g_originals[CREATE_EVENT_ID]); return TargetCreateEventW(orig_fn, security_attributes, manual_reset, initial_state, name); } SANDBOX_INTERCEPT HANDLE WINAPI TargetOpenEventW64( ACCESS_MASK desired_access, BOOL inherit_handle, LPCWSTR name) { OpenEventWFunction orig_fn = reinterpret_cast< OpenEventWFunction>(g_originals[OPEN_EVENT_ID]); return TargetOpenEventW(orig_fn, desired_access, inherit_handle, name); } } // namespace sandbox <commit_msg>Sandbox: Fix a style nit. No actual code change.<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 "sandbox/src/interceptors_64.h" #include "sandbox/src/interceptors.h" #include "sandbox/src/filesystem_interception.h" #include "sandbox/src/named_pipe_interception.h" #include "sandbox/src/policy_target.h" #include "sandbox/src/process_thread_interception.h" #include "sandbox/src/registry_interception.h" #include "sandbox/src/sandbox_nt_types.h" #include "sandbox/src/sandbox_types.h" #include "sandbox/src/sync_interception.h" #include "sandbox/src/target_interceptions.h" namespace sandbox { SANDBOX_INTERCEPT NtExports g_nt; SANDBOX_INTERCEPT OriginalFunctions g_originals; NTSTATUS WINAPI TargetNtMapViewOfSection64( HANDLE section, HANDLE process, PVOID *base, ULONG_PTR zero_bits, SIZE_T commit_size, PLARGE_INTEGER offset, PSIZE_T view_size, SECTION_INHERIT inherit, ULONG allocation_type, ULONG protect) { NtMapViewOfSectionFunction orig_fn = reinterpret_cast< NtMapViewOfSectionFunction>(g_originals[MAP_VIEW_OF_SECTION_ID]); return TargetNtMapViewOfSection(orig_fn, section, process, base, zero_bits, commit_size, offset, view_size, inherit, allocation_type, protect); } NTSTATUS WINAPI TargetNtUnmapViewOfSection64(HANDLE process, PVOID base) { NtUnmapViewOfSectionFunction orig_fn = reinterpret_cast< NtUnmapViewOfSectionFunction>(g_originals[UNMAP_VIEW_OF_SECTION_ID]); return TargetNtUnmapViewOfSection(orig_fn, process, base); } // ----------------------------------------------------------------------- NTSTATUS WINAPI TargetNtSetInformationThread64( HANDLE thread, THREAD_INFORMATION_CLASS thread_info_class, PVOID thread_information, ULONG thread_information_bytes) { NtSetInformationThreadFunction orig_fn = reinterpret_cast< NtSetInformationThreadFunction>(g_originals[SET_INFORMATION_THREAD_ID]); return TargetNtSetInformationThread(orig_fn, thread, thread_info_class, thread_information, thread_information_bytes); } NTSTATUS WINAPI TargetNtOpenThreadToken64( HANDLE thread, ACCESS_MASK desired_access, BOOLEAN open_as_self, PHANDLE token) { NtOpenThreadTokenFunction orig_fn = reinterpret_cast< NtOpenThreadTokenFunction>(g_originals[OPEN_THREAD_TOKEN_ID]); return TargetNtOpenThreadToken(orig_fn, thread, desired_access, open_as_self, token); } NTSTATUS WINAPI TargetNtOpenThreadTokenEx64( HANDLE thread, ACCESS_MASK desired_access, BOOLEAN open_as_self, ULONG handle_attributes, PHANDLE token) { NtOpenThreadTokenExFunction orig_fn = reinterpret_cast< NtOpenThreadTokenExFunction>(g_originals[OPEN_THREAD_TOKEN_EX_ID]); return TargetNtOpenThreadTokenEx(orig_fn, thread, desired_access, open_as_self, handle_attributes, token); } HANDLE WINAPI TargetCreateThread64( LPSECURITY_ATTRIBUTES thread_attributes, SIZE_T stack_size, LPTHREAD_START_ROUTINE start_address, PVOID parameter, DWORD creation_flags, LPDWORD thread_id) { CreateThreadFunction orig_fn = reinterpret_cast< CreateThreadFunction>(g_originals[CREATE_THREAD_ID]); return TargetCreateThread(orig_fn, thread_attributes, stack_size, start_address, parameter, creation_flags, thread_id); } // ----------------------------------------------------------------------- SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtCreateFile64( PHANDLE file, ACCESS_MASK desired_access, POBJECT_ATTRIBUTES object_attributes, PIO_STATUS_BLOCK io_status, PLARGE_INTEGER allocation_size, ULONG file_attributes, ULONG sharing, ULONG disposition, ULONG options, PVOID ea_buffer, ULONG ea_length) { NtCreateFileFunction orig_fn = reinterpret_cast< NtCreateFileFunction>(g_originals[CREATE_FILE_ID]); return TargetNtCreateFile(orig_fn, file, desired_access, object_attributes, io_status, allocation_size, file_attributes, sharing, disposition, options, ea_buffer, ea_length); } SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenFile64( PHANDLE file, ACCESS_MASK desired_access, POBJECT_ATTRIBUTES object_attributes, PIO_STATUS_BLOCK io_status, ULONG sharing, ULONG options) { NtOpenFileFunction orig_fn = reinterpret_cast< NtOpenFileFunction>(g_originals[OPEN_FILE_ID]); return TargetNtOpenFile(orig_fn, file, desired_access, object_attributes, io_status, sharing, options); } SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtQueryAttributesFile64( POBJECT_ATTRIBUTES object_attributes, PFILE_BASIC_INFORMATION file_attributes) { NtQueryAttributesFileFunction orig_fn = reinterpret_cast< NtQueryAttributesFileFunction>(g_originals[QUERY_ATTRIB_FILE_ID]); return TargetNtQueryAttributesFile(orig_fn, object_attributes, file_attributes); } SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtQueryFullAttributesFile64( POBJECT_ATTRIBUTES object_attributes, PFILE_NETWORK_OPEN_INFORMATION file_attributes) { NtQueryFullAttributesFileFunction orig_fn = reinterpret_cast< NtQueryFullAttributesFileFunction>( g_originals[QUERY_FULL_ATTRIB_FILE_ID]); return TargetNtQueryFullAttributesFile(orig_fn, object_attributes, file_attributes); } SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtSetInformationFile64( HANDLE file, PIO_STATUS_BLOCK io_status, PVOID file_information, ULONG length, FILE_INFORMATION_CLASS file_information_class) { NtSetInformationFileFunction orig_fn = reinterpret_cast< NtSetInformationFileFunction>(g_originals[SET_INFO_FILE_ID]); return TargetNtSetInformationFile(orig_fn, file, io_status, file_information, length, file_information_class); } // ----------------------------------------------------------------------- SANDBOX_INTERCEPT HANDLE WINAPI TargetCreateNamedPipeW64( LPCWSTR pipe_name, DWORD open_mode, DWORD pipe_mode, DWORD max_instance, DWORD out_buffer_size, DWORD in_buffer_size, DWORD default_timeout, LPSECURITY_ATTRIBUTES security_attributes) { CreateNamedPipeWFunction orig_fn = reinterpret_cast< CreateNamedPipeWFunction>(g_originals[CREATE_NAMED_PIPE_ID]); return TargetCreateNamedPipeW(orig_fn, pipe_name, open_mode, pipe_mode, max_instance, out_buffer_size, in_buffer_size, default_timeout, security_attributes); } // ----------------------------------------------------------------------- SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenThread64( PHANDLE thread, ACCESS_MASK desired_access, POBJECT_ATTRIBUTES object_attributes, PCLIENT_ID client_id) { NtOpenThreadFunction orig_fn = reinterpret_cast< NtOpenThreadFunction>(g_originals[OPEN_TREAD_ID]); return TargetNtOpenThread(orig_fn, thread, desired_access, object_attributes, client_id); } SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenProcess64( PHANDLE process, ACCESS_MASK desired_access, POBJECT_ATTRIBUTES object_attributes, PCLIENT_ID client_id) { NtOpenProcessFunction orig_fn = reinterpret_cast< NtOpenProcessFunction>(g_originals[OPEN_PROCESS_ID]); return TargetNtOpenProcess(orig_fn, process, desired_access, object_attributes, client_id); } SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenProcessToken64( HANDLE process, ACCESS_MASK desired_access, PHANDLE token) { NtOpenProcessTokenFunction orig_fn = reinterpret_cast< NtOpenProcessTokenFunction>(g_originals[OPEN_PROCESS_TOKEN_ID]); return TargetNtOpenProcessToken(orig_fn, process, desired_access, token); } SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenProcessTokenEx64( HANDLE process, ACCESS_MASK desired_access, ULONG handle_attributes, PHANDLE token) { NtOpenProcessTokenExFunction orig_fn = reinterpret_cast< NtOpenProcessTokenExFunction>(g_originals[OPEN_PROCESS_TOKEN_EX_ID]); return TargetNtOpenProcessTokenEx(orig_fn, process, desired_access, handle_attributes, token); } SANDBOX_INTERCEPT BOOL WINAPI TargetCreateProcessW64( LPCWSTR application_name, LPWSTR command_line, LPSECURITY_ATTRIBUTES process_attributes, LPSECURITY_ATTRIBUTES thread_attributes, BOOL inherit_handles, DWORD flags, LPVOID environment, LPCWSTR current_directory, LPSTARTUPINFOW startup_info, LPPROCESS_INFORMATION process_information) { CreateProcessWFunction orig_fn = reinterpret_cast< CreateProcessWFunction>(g_originals[CREATE_PROCESSW_ID]); return TargetCreateProcessW(orig_fn, application_name, command_line, process_attributes, thread_attributes, inherit_handles, flags, environment, current_directory, startup_info, process_information); } SANDBOX_INTERCEPT BOOL WINAPI TargetCreateProcessA64( LPCSTR application_name, LPSTR command_line, LPSECURITY_ATTRIBUTES process_attributes, LPSECURITY_ATTRIBUTES thread_attributes, BOOL inherit_handles, DWORD flags, LPVOID environment, LPCSTR current_directory, LPSTARTUPINFOA startup_info, LPPROCESS_INFORMATION process_information) { CreateProcessAFunction orig_fn = reinterpret_cast< CreateProcessAFunction>(g_originals[CREATE_PROCESSA_ID]); return TargetCreateProcessA(orig_fn, application_name, command_line, process_attributes, thread_attributes, inherit_handles, flags, environment, current_directory, startup_info, process_information); } // ----------------------------------------------------------------------- SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtCreateKey64( PHANDLE key, ACCESS_MASK desired_access, POBJECT_ATTRIBUTES object_attributes, ULONG title_index, PUNICODE_STRING class_name, ULONG create_options, PULONG disposition) { NtCreateKeyFunction orig_fn = reinterpret_cast< NtCreateKeyFunction>(g_originals[CREATE_KEY_ID]); return TargetNtCreateKey(orig_fn, key, desired_access, object_attributes, title_index, class_name, create_options, disposition); } SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenKey64( PHANDLE key, ACCESS_MASK desired_access, POBJECT_ATTRIBUTES object_attributes) { NtOpenKeyFunction orig_fn = reinterpret_cast< NtOpenKeyFunction>(g_originals[OPEN_KEY_ID]); return TargetNtOpenKey(orig_fn, key, desired_access, object_attributes); } SANDBOX_INTERCEPT NTSTATUS WINAPI TargetNtOpenKeyEx64( PHANDLE key, ACCESS_MASK desired_access, POBJECT_ATTRIBUTES object_attributes, ULONG open_options) { NtOpenKeyExFunction orig_fn = reinterpret_cast< NtOpenKeyExFunction>(g_originals[OPEN_KEY_EX_ID]); return TargetNtOpenKeyEx(orig_fn, key, desired_access, object_attributes, open_options); } // ----------------------------------------------------------------------- SANDBOX_INTERCEPT HANDLE WINAPI TargetCreateEventW64( LPSECURITY_ATTRIBUTES security_attributes, BOOL manual_reset, BOOL initial_state, LPCWSTR name) { CreateEventWFunction orig_fn = reinterpret_cast< CreateEventWFunction>(g_originals[CREATE_EVENT_ID]); return TargetCreateEventW(orig_fn, security_attributes, manual_reset, initial_state, name); } SANDBOX_INTERCEPT HANDLE WINAPI TargetOpenEventW64( ACCESS_MASK desired_access, BOOL inherit_handle, LPCWSTR name) { OpenEventWFunction orig_fn = reinterpret_cast< OpenEventWFunction>(g_originals[OPEN_EVENT_ID]); return TargetOpenEventW(orig_fn, desired_access, inherit_handle, name); } } // namespace sandbox <|endoftext|>
<commit_before>#include "catch.hpp" #include "ab.hpp" TEST_CASE("alpha beta size 1", "[alphabeta]") { AlphaBeta<1> ab; State<1> s; REQUIRE(ab.alphabeta(s, BLACK).get_minimax() == 0); } TEST_CASE("alpha beta size 2", "[alphabeta]") { AlphaBeta<2> ab; State<2> s; REQUIRE(ab.alphabeta(s, BLACK).get_minimax() == 0); } TEST_CASE("alpha beta size 3", "[alphabeta]") { AlphaBeta<3> ab; State<3> s; REQUIRE(ab.alphabeta(s, BLACK).get_minimax() == 3); } TEST_CASE("alpha beta size 4", "[alphabeta]") { AlphaBeta<4> ab; State<4> s; REQUIRE(ab.alphabeta(s, BLACK).get_minimax() == 4); } TEST_CASE("alpha beta size 5", "[alphabeta]") { AlphaBeta<5> ab; State<5> s; REQUIRE(ab.alphabeta(s, BLACK).get_minimax() == 0); } TEST_CASE("alpha beta size 6", "[alphabeta]") { AlphaBeta<6> ab; State<6> s; REQUIRE(ab.alphabeta(s, BLACK).get_minimax() == 1); } TEST_CASE("lgo_small pv 3:1", "[alphabeta]") { AlphaBeta<3> ab; State<3> s; s.play(Move(BLACK, 1)); REQUIRE(ab.alphabeta(s, WHITE).get_minimax() == 3); } TEST_CASE("lgo_small pv 3:0,1", "[alphabeta]") { AlphaBeta<3> ab; State<3> s; s.play(Move(BLACK, 0)); s.play(Move(WHITE, 1)); REQUIRE(ab.alphabeta(s, BLACK).get_minimax() == -3); } TEST_CASE("lgo_small pv 4:1", "[alphabeta]") { AlphaBeta<4> ab; State<4> s; s.play(Move(BLACK, 1)); REQUIRE(ab.alphabeta(s, WHITE).get_minimax() == 4); } TEST_CASE("lgo_small pv 4:0,2", "[alphabeta]") { AlphaBeta<4> ab; State<4> s; s.play(Move(BLACK, 0)); s.play(Move(WHITE, 2)); REQUIRE(ab.alphabeta(s, BLACK).get_minimax() == -4); } TEST_CASE("lgo_small pv 5:1,3", "[alphabeta]") { AlphaBeta<5> ab; State<5> s; s.play(Move(BLACK, 1)); s.play(Move(WHITE, 3)); REQUIRE(ab.alphabeta(s, BLACK).get_minimax() == 0); } TEST_CASE("lgo_small pv 5:2,1,3", "[alphabeta]") { AlphaBeta<5> ab; State<5> s; s.play(Move(BLACK, 2)); s.play(Move(WHITE, 1)); s.play(Move(BLACK, 3)); REQUIRE(ab.alphabeta(s, WHITE).get_minimax() == 0); } TEST_CASE("lgo_small pv 5:0,3", "[alphabeta]") { AlphaBeta<5> ab; State<5> s; s.play(Move(BLACK, 0)); s.play(Move(WHITE, 3)); REQUIRE(ab.alphabeta(s, BLACK).get_minimax() == -5); } TEST_CASE("lgo_small pv 6:1,4,2", "[alphabeta]") { AlphaBeta<6> ab; State<6> s; s.play(Move(BLACK, 1)); s.play(Move(WHITE, 4)); s.play(Move(BLACK, 2)); REQUIRE(ab.alphabeta(s, WHITE).get_minimax() == 1); } TEST_CASE("lgo_small pv 6:2,1", "[alphabeta]") { AlphaBeta<6> ab; State<6> s; s.play(Move(BLACK, 2)); s.play(Move(WHITE, 1)); REQUIRE(ab.alphabeta(s, BLACK).get_minimax() == -1); } TEST_CASE("lgo_small pv 6:0,4", "[alphabeta]") { AlphaBeta<6> ab; State<6> s; s.play(Move(BLACK, 0)); s.play(Move(WHITE, 4)); REQUIRE(ab.alphabeta(s, BLACK).get_minimax() == -6); } <commit_msg>Add a bunch more alphabeta tests<commit_after>#include "catch.hpp" #include "ab.hpp" TEST_CASE("alpha beta size 1", "[alphabeta]") { AlphaBeta<1> ab; State<1> s; REQUIRE(ab.alphabeta(s, BLACK).get_minimax() == 0); } TEST_CASE("alpha beta size 2", "[alphabeta]") { AlphaBeta<2> ab; State<2> s; REQUIRE(ab.alphabeta(s, BLACK).get_minimax() == 0); } TEST_CASE("alpha beta size 3", "[alphabeta]") { AlphaBeta<3> ab; State<3> s; REQUIRE(ab.alphabeta(s, BLACK).get_minimax() == 3); } TEST_CASE("alpha beta size 4", "[alphabeta]") { AlphaBeta<4> ab; State<4> s; REQUIRE(ab.alphabeta(s, BLACK).get_minimax() == 4); } TEST_CASE("alpha beta size 5", "[alphabeta]") { AlphaBeta<5> ab; State<5> s; REQUIRE(ab.alphabeta(s, BLACK).get_minimax() == 0); } TEST_CASE("alpha beta size 6", "[alphabeta]") { AlphaBeta<6> ab; State<6> s; REQUIRE(ab.alphabeta(s, BLACK).get_minimax() == 1); } TEST_CASE("lgo_small pv 3:1", "[alphabeta]") { AlphaBeta<3> ab; State<3> s; s.play(Move(BLACK, 1)); REQUIRE(ab.alphabeta(s, WHITE).get_minimax() == 3); } TEST_CASE("lgo_small pv 3:0,1", "[alphabeta]") { AlphaBeta<3> ab; State<3> s; s.play(Move(BLACK, 0)); s.play(Move(WHITE, 1)); REQUIRE(ab.alphabeta(s, BLACK).get_minimax() == -3); } TEST_CASE("lgo_small pv 4:1", "[alphabeta]") { AlphaBeta<4> ab; State<4> s; s.play(Move(BLACK, 1)); REQUIRE(ab.alphabeta(s, WHITE).get_minimax() == 4); } TEST_CASE("lgo_small pv 4:0,2", "[alphabeta]") { AlphaBeta<4> ab; State<4> s; s.play(Move(BLACK, 0)); s.play(Move(WHITE, 2)); REQUIRE(ab.alphabeta(s, BLACK).get_minimax() == -4); } TEST_CASE("lgo_small pv 5:1,3", "[alphabeta]") { AlphaBeta<5> ab; State<5> s; s.play(Move(BLACK, 1)); s.play(Move(WHITE, 3)); REQUIRE(ab.alphabeta(s, BLACK).get_minimax() == 0); } TEST_CASE("lgo_small pv 5:2,1,3", "[alphabeta]") { AlphaBeta<5> ab; State<5> s; s.play(Move(BLACK, 2)); s.play(Move(WHITE, 1)); s.play(Move(BLACK, 3)); REQUIRE(ab.alphabeta(s, WHITE).get_minimax() == 0); } TEST_CASE("lgo_small pv 5:0,3", "[alphabeta]") { AlphaBeta<5> ab; State<5> s; s.play(Move(BLACK, 0)); s.play(Move(WHITE, 3)); REQUIRE(ab.alphabeta(s, BLACK).get_minimax() == -5); } TEST_CASE("lgo_small pv 6:1,4,2", "[alphabeta]") { AlphaBeta<6> ab; State<6> s; s.play(Move(BLACK, 1)); s.play(Move(WHITE, 4)); s.play(Move(BLACK, 2)); REQUIRE(ab.alphabeta(s, WHITE).get_minimax() == 1); } TEST_CASE("lgo_small pv 6:2,1", "[alphabeta]") { AlphaBeta<6> ab; State<6> s; s.play(Move(BLACK, 2)); s.play(Move(WHITE, 1)); REQUIRE(ab.alphabeta(s, BLACK).get_minimax() == -1); } TEST_CASE("lgo_small pv 6:0,4", "[alphabeta]") { AlphaBeta<6> ab; State<6> s; s.play(Move(BLACK, 0)); s.play(Move(WHITE, 4)); REQUIRE(ab.alphabeta(s, BLACK).get_minimax() == -6); } TEST_CASE("lgo_small pv 6:1,2", "[alphabeta]") { AlphaBeta<6> ab; State<6> s; s.play(Move(BLACK, 1)); s.play(Move(WHITE, 2)); REQUIRE(ab.alphabeta(s, BLACK).get_minimax() == 6); } TEST_CASE("lgo_small pv 6:1,3", "[alphabeta]") { AlphaBeta<6> ab; State<6> s; s.play(Move(BLACK, 1)); s.play(Move(WHITE, 3)); REQUIRE(ab.alphabeta(s, BLACK).get_minimax() == 6); } TEST_CASE("lgo_small pv 6:0", "[alphabeta]") { AlphaBeta<6> ab; State<6> s; s.play(Move(BLACK, 0)); REQUIRE(ab.alphabeta(s, WHITE).get_minimax() == -6); } TEST_CASE("lgo_small pv 6:2", "[alphabeta]") { AlphaBeta<6> ab; State<6> s; s.play(Move(BLACK, 2)); REQUIRE(ab.alphabeta(s, WHITE).get_minimax() == -1); } TEST_CASE("lgo_small pv 6:2,1,3", "[alphabeta]") { AlphaBeta<6> ab; State<6> s; s.play(Move(BLACK, 2)); s.play(Move(WHITE, 1)); s.play(Move(BLACK, 3)); REQUIRE(ab.alphabeta(s, WHITE).get_minimax() == -6); } TEST_CASE("lgo_small pv 6:2,1,4", "[alphabeta]") { AlphaBeta<6> ab; State<6> s; s.play(Move(BLACK, 2)); s.play(Move(WHITE, 1)); s.play(Move(BLACK, 4)); REQUIRE(ab.alphabeta(s, WHITE).get_minimax() == -6); } TEST_CASE("lgo_small pv 6:2,1,5", "[alphabeta]") { AlphaBeta<6> ab; State<6> s; s.play(Move(BLACK, 2)); s.play(Move(WHITE, 1)); s.play(Move(BLACK, 5)); REQUIRE(ab.alphabeta(s, WHITE).get_minimax() == -6); } <|endoftext|>
<commit_before><commit_msg>Fix overflow in smoketest, promotion from sal_Int32 to sal_Int64 doesn't happen before assign<commit_after><|endoftext|>
<commit_before><commit_msg>we do have ValidCol(), so use it<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: undoutil.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: rt $ $Date: 2008-02-19 15:34:23 $ * * 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_sc.hxx" // System - Includes ----------------------------------------------------- // INCLUDE --------------------------------------------------------------- #include "undoutil.hxx" #include "docsh.hxx" #include "tabvwsh.hxx" #include "document.hxx" #include "dbcolect.hxx" #include "globstr.hrc" #include "global.hxx" void ScUndoUtil::MarkSimpleBlock( ScDocShell* /* pDocShell */, SCCOL nStartX, SCROW nStartY, SCTAB nStartZ, SCCOL nEndX, SCROW nEndY, SCTAB nEndZ ) { ScTabViewShell* pViewShell = ScTabViewShell::GetActiveViewShell(); if (pViewShell) { SCTAB nViewTab = pViewShell->GetViewData()->GetTabNo(); if ( nViewTab < nStartZ || nViewTab > nEndZ ) pViewShell->SetTabNo( nStartZ ); pViewShell->DoneBlockMode(); pViewShell->MoveCursorAbs( nStartX, nStartY, SC_FOLLOW_JUMP, FALSE, FALSE ); pViewShell->InitOwnBlockMode(); pViewShell->GetViewData()->GetMarkData(). SetMarkArea( ScRange( nStartX, nStartY, nStartZ, nEndX, nEndY, nEndZ ) ); pViewShell->MarkDataChanged(); } } void ScUndoUtil::MarkSimpleBlock( ScDocShell* pDocShell, const ScAddress& rBlockStart, const ScAddress& rBlockEnd ) { MarkSimpleBlock( pDocShell, rBlockStart.Col(), rBlockStart.Row(), rBlockStart.Tab(), rBlockEnd.Col(), rBlockEnd.Row(), rBlockEnd.Tab() ); } void ScUndoUtil::MarkSimpleBlock( ScDocShell* pDocShell, const ScRange& rRange ) { MarkSimpleBlock( pDocShell, rRange.aStart.Col(), rRange.aStart.Row(), rRange.aStart.Tab(), rRange.aEnd.Col(), rRange.aEnd.Row(), rRange.aEnd.Tab() ); } ScDBData* ScUndoUtil::GetOldDBData( ScDBData* pUndoData, ScDocument* pDoc, SCTAB nTab, SCCOL nCol1, SCROW nRow1, SCCOL nCol2, SCROW nRow2 ) { ScDBData* pRet = pDoc->GetDBAtArea( nTab, nCol1, nRow1, nCol2, nRow2 ); if (!pRet) { BOOL bWasTemp = FALSE; if ( pUndoData ) { String aName; pUndoData->GetName( aName ); if ( aName == ScGlobal::GetRscString( STR_DB_NONAME ) ) bWasTemp = TRUE; } DBG_ASSERT(bWasTemp, "Undo: didn't find database range"); USHORT nIndex; ScDBCollection* pColl = pDoc->GetDBCollection(); if (pColl->SearchName( ScGlobal::GetRscString( STR_DB_NONAME ), nIndex )) pRet = (*pColl)[nIndex]; else { pRet = new ScDBData( ScGlobal::GetRscString( STR_DB_NONAME ), nTab, nCol1,nRow1, nCol2,nRow2, TRUE, pDoc->HasColHeader( nCol1,nRow1,nCol2,nRow2,nTab ) ); pColl->Insert( pRet ); } } return pRet; } void ScUndoUtil::PaintMore( ScDocShell* pDocShell, const ScRange& rRange ) { SCCOL nCol1 = rRange.aStart.Col(); SCROW nRow1 = rRange.aStart.Row(); SCCOL nCol2 = rRange.aEnd.Col(); SCROW nRow2 = rRange.aEnd.Row(); if (nCol1 > 0) --nCol1; if (nRow1 > 0) --nRow1; if (nCol2<MAXCOL) ++nCol2; if (nRow2<MAXROW) ++nRow2; pDocShell->PostPaint( nCol1,nRow1,rRange.aStart.Tab(), nCol2,nRow2,rRange.aEnd.Tab(), PAINT_GRID ); } <commit_msg>INTEGRATION: CWS changefileheader (1.7.64); FILE MERGED 2008/03/31 17:19:32 rt 1.7.64.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: undoutil.cxx,v $ * $Revision: 1.8 $ * * 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_sc.hxx" // System - Includes ----------------------------------------------------- // INCLUDE --------------------------------------------------------------- #include "undoutil.hxx" #include "docsh.hxx" #include "tabvwsh.hxx" #include "document.hxx" #include "dbcolect.hxx" #include "globstr.hrc" #include "global.hxx" void ScUndoUtil::MarkSimpleBlock( ScDocShell* /* pDocShell */, SCCOL nStartX, SCROW nStartY, SCTAB nStartZ, SCCOL nEndX, SCROW nEndY, SCTAB nEndZ ) { ScTabViewShell* pViewShell = ScTabViewShell::GetActiveViewShell(); if (pViewShell) { SCTAB nViewTab = pViewShell->GetViewData()->GetTabNo(); if ( nViewTab < nStartZ || nViewTab > nEndZ ) pViewShell->SetTabNo( nStartZ ); pViewShell->DoneBlockMode(); pViewShell->MoveCursorAbs( nStartX, nStartY, SC_FOLLOW_JUMP, FALSE, FALSE ); pViewShell->InitOwnBlockMode(); pViewShell->GetViewData()->GetMarkData(). SetMarkArea( ScRange( nStartX, nStartY, nStartZ, nEndX, nEndY, nEndZ ) ); pViewShell->MarkDataChanged(); } } void ScUndoUtil::MarkSimpleBlock( ScDocShell* pDocShell, const ScAddress& rBlockStart, const ScAddress& rBlockEnd ) { MarkSimpleBlock( pDocShell, rBlockStart.Col(), rBlockStart.Row(), rBlockStart.Tab(), rBlockEnd.Col(), rBlockEnd.Row(), rBlockEnd.Tab() ); } void ScUndoUtil::MarkSimpleBlock( ScDocShell* pDocShell, const ScRange& rRange ) { MarkSimpleBlock( pDocShell, rRange.aStart.Col(), rRange.aStart.Row(), rRange.aStart.Tab(), rRange.aEnd.Col(), rRange.aEnd.Row(), rRange.aEnd.Tab() ); } ScDBData* ScUndoUtil::GetOldDBData( ScDBData* pUndoData, ScDocument* pDoc, SCTAB nTab, SCCOL nCol1, SCROW nRow1, SCCOL nCol2, SCROW nRow2 ) { ScDBData* pRet = pDoc->GetDBAtArea( nTab, nCol1, nRow1, nCol2, nRow2 ); if (!pRet) { BOOL bWasTemp = FALSE; if ( pUndoData ) { String aName; pUndoData->GetName( aName ); if ( aName == ScGlobal::GetRscString( STR_DB_NONAME ) ) bWasTemp = TRUE; } DBG_ASSERT(bWasTemp, "Undo: didn't find database range"); USHORT nIndex; ScDBCollection* pColl = pDoc->GetDBCollection(); if (pColl->SearchName( ScGlobal::GetRscString( STR_DB_NONAME ), nIndex )) pRet = (*pColl)[nIndex]; else { pRet = new ScDBData( ScGlobal::GetRscString( STR_DB_NONAME ), nTab, nCol1,nRow1, nCol2,nRow2, TRUE, pDoc->HasColHeader( nCol1,nRow1,nCol2,nRow2,nTab ) ); pColl->Insert( pRet ); } } return pRet; } void ScUndoUtil::PaintMore( ScDocShell* pDocShell, const ScRange& rRange ) { SCCOL nCol1 = rRange.aStart.Col(); SCROW nRow1 = rRange.aStart.Row(); SCCOL nCol2 = rRange.aEnd.Col(); SCROW nRow2 = rRange.aEnd.Row(); if (nCol1 > 0) --nCol1; if (nRow1 > 0) --nRow1; if (nCol2<MAXCOL) ++nCol2; if (nRow2<MAXROW) ++nRow2; pDocShell->PostPaint( nCol1,nRow1,rRange.aStart.Tab(), nCol2,nRow2,rRange.aEnd.Tab(), PAINT_GRID ); } <|endoftext|>
<commit_before><commit_msg>dr78: #i95280# read Excel view options in FillRenderMarkData if not done before<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: tabvwshd.cxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: hr $ $Date: 2000-09-18 16:45:10 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "ui_pch.hxx" #endif #pragma hdrstop //------------------------------------------------------------------ #ifdef WNT #pragma optimize ("", off) #endif // INCLUDE --------------------------------------------------------------- #include <sfx2/request.hxx> #include <sfx2/topfrm.hxx> #include <so3/ipenv.hxx> #include <vcl/svapp.hxx> #include <vcl/wrkwin.hxx> #include "tabvwsh.hxx" #include "global.hxx" #include "scmod.hxx" #include "docsh.hxx" #include "sc.hrc" // STATIC DATA ----------------------------------------------------------- //------------------------------------------------------------------ #define IS_AVAILABLE(WhichId,ppItem) \ (pReqArgs->GetItemState((WhichId), TRUE, ppItem ) == SFX_ITEM_SET) //! Parent-Window fuer Dialoge //! Problem: OLE Server! Window* ScTabViewShell::GetDialogParent() { ScDocShell* pDocSh = GetViewData()->GetDocShell(); if ( pDocSh->IsOle() ) { SvInPlaceEnvironment* pEnv = pDocSh->GetIPEnv(); if (pEnv) return pEnv->GetEditWin(); } #if 0 else if ( !GetViewFrame()->ISA(SfxTopViewFrame) ) // z.B. PlugIn { return GetActiveWin(); } #endif return GetActiveWin(); // for normal views, too } <commit_msg>#95513# GetDialogParent: if a ref-dialog is open, use it as parent<commit_after>/************************************************************************* * * $RCSfile: tabvwshd.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: nn $ $Date: 2001-12-03 20:32:45 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "ui_pch.hxx" #endif #pragma hdrstop //------------------------------------------------------------------ #ifdef WNT #pragma optimize ("", off) #endif // INCLUDE --------------------------------------------------------------- #include <sfx2/childwin.hxx> #include <sfx2/request.hxx> #include <sfx2/topfrm.hxx> #include <so3/ipenv.hxx> #include <vcl/svapp.hxx> #include <vcl/wrkwin.hxx> #include "tabvwsh.hxx" #include "global.hxx" #include "scmod.hxx" #include "docsh.hxx" #include "sc.hrc" // STATIC DATA ----------------------------------------------------------- //------------------------------------------------------------------ #define IS_AVAILABLE(WhichId,ppItem) \ (pReqArgs->GetItemState((WhichId), TRUE, ppItem ) == SFX_ITEM_SET) //! Parent-Window fuer Dialoge //! Problem: OLE Server! Window* ScTabViewShell::GetDialogParent() { // #95513# if a ref-input dialog is open, use it as parent // (necessary when a slot is executed from the dialog's OK handler) if ( nCurRefDlgId && nCurRefDlgId == SC_MOD()->GetCurRefDlgId() ) { SfxViewFrame* pViewFrm = GetViewFrame(); if ( pViewFrm->HasChildWindow(nCurRefDlgId) ) { SfxChildWindow* pChild = pViewFrm->GetChildWindow(nCurRefDlgId); if (pChild) { Window* pWin = pChild->GetWindow(); if (pWin && pWin->IsVisible()) return pWin; } } } ScDocShell* pDocSh = GetViewData()->GetDocShell(); if ( pDocSh->IsOle() ) { SvInPlaceEnvironment* pEnv = pDocSh->GetIPEnv(); if (pEnv) return pEnv->GetEditWin(); } #if 0 else if ( !GetViewFrame()->ISA(SfxTopViewFrame) ) // z.B. PlugIn { return GetActiveWin(); } #endif return GetActiveWin(); // for normal views, too } <|endoftext|>
<commit_before>/* Copyright 2016 Carnegie Mellon University * * 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 "scanner/engine/save_worker.h" #include "scanner/engine/metadata.h" #include "scanner/util/common.h" #include "scanner/util/storehouse.h" #include "scanner/video/h264_byte_stream_index_creator.h" #include "storehouse/storage_backend.h" #include <glog/logging.h> using storehouse::StoreResult; using storehouse::WriteFile; using storehouse::RandomReadFile; namespace scanner { namespace internal { SaveWorker::SaveWorker(const SaveWorkerArgs& args) : node_id_(args.node_id), worker_id_(args.worker_id), profiler_(args.profiler) { auto setup_start = now(); // Setup a distinct storage backend for each IO thread storage_.reset( storehouse::StorageBackend::make_from_config(args.storage_config)); args.profiler.add_interval("setup", setup_start, now()); } SaveWorker::~SaveWorker() { for (auto& file : output_) { file->save(); } for (auto& file : output_metadata_) { file->save(); } for (auto& meta : video_metadata_) { write_video_metadata(storage_.get(), meta); } output_.clear(); output_metadata_.clear(); video_metadata_.clear(); } void SaveWorker::feed(std::tuple<IOItem, EvalWorkEntry>& input_entry) { IOItem& io_item = std::get<0>(input_entry); EvalWorkEntry& work_entry = std::get<1>(input_entry); // Write out each output column to an individual data file i32 video_col_idx = 0; for (size_t out_idx = 0; out_idx < work_entry.columns.size(); ++out_idx) { u64 num_elements = static_cast<u64>(work_entry.columns[out_idx].size()); auto io_start = now(); WriteFile* output_file = output_[out_idx].get(); WriteFile* output_metadata_file = output_metadata_[out_idx].get(); if (work_entry.columns[out_idx].size() != num_elements) { LOG(FATAL) << "Output layer's element vector has wrong length"; } // Ensure the data is on the CPU move_if_different_address_space(profiler_, work_entry.column_handles[out_idx], CPU_DEVICE, work_entry.columns[out_idx]); bool compressed = work_entry.compressed[out_idx]; // If this is a video... i64 size_written = 0; if (work_entry.column_types[out_idx] == ColumnType::Video) { // Read frame info column assert(work_entry.columns[out_idx].size() > 0); FrameInfo frame_info = work_entry.frame_sizes[video_col_idx]; // Create index column VideoMetadata video_meta; proto::VideoDescriptor& video_descriptor = video_meta.get_descriptor(); video_descriptor.set_width(frame_info.width()); video_descriptor.set_height(frame_info.height()); video_descriptor.set_channels(frame_info.channels()); video_descriptor.set_frame_type(frame_info.type); video_descriptor.set_time_base_num(1); video_descriptor.set_time_base_denom(25); video_descriptor.set_num_encoded_videos( video_descriptor.num_encoded_videos() + 1); if (compressed && frame_info.type == FrameType::U8 && frame_info.channels() == 3) { H264ByteStreamIndexCreator index_creator(output_file); for (size_t i = 0; i < num_elements; ++i) { Element& element = work_entry.columns[out_idx][i]; if (!index_creator.feed_packet(element.buffer, element.size)) { LOG(FATAL) << "Error in save worker h264 index creator: " << index_creator.error_message(); } size_written += element.size; } i64 frame = index_creator.frames(); i32 num_non_ref_frames = index_creator.num_non_ref_frames(); const std::vector<u8>& metadata_bytes = index_creator.metadata_bytes(); const std::vector<i64>& keyframe_positions = index_creator.keyframe_positions(); const std::vector<i64>& keyframe_timestamps = index_creator.keyframe_timestamps(); const std::vector<i64>& keyframe_byte_offsets = index_creator.keyframe_byte_offsets(); video_descriptor.set_chroma_format(proto::VideoDescriptor::YUV_420); video_descriptor.set_codec_type(proto::VideoDescriptor::H264); video_descriptor.set_frames(video_descriptor.frames() + frame); video_descriptor.add_frames_per_video(frame); video_descriptor.add_keyframes_per_video(keyframe_positions.size()); video_descriptor.add_size_per_video(index_creator.bytestream_pos()); video_descriptor.set_metadata_packets(metadata_bytes.data(), metadata_bytes.size()); for (i64 v : keyframe_positions) { video_descriptor.add_keyframe_positions(v); } for (i64 v : keyframe_timestamps) { video_descriptor.add_keyframe_timestamps(v); } for (i64 v : keyframe_byte_offsets) { video_descriptor.add_keyframe_byte_offsets(v); } } else { // Non h264 compressible video column video_descriptor.set_codec_type(proto::VideoDescriptor::RAW); // Need to specify but not used for this type video_descriptor.set_chroma_format(proto::VideoDescriptor::YUV_420); video_descriptor.set_frames(video_descriptor.frames() + num_elements); // Write number of elements in the file s_write(output_metadata_file, num_elements); // Write out all output sizes first so we can easily index into the // file for (size_t i = 0; i < num_elements; ++i) { Frame* frame = work_entry.columns[out_idx][i].as_frame(); i64 buffer_size = frame->size(); s_write(output_metadata_file, buffer_size); size_written += sizeof(i64); } // Write actual output data for (size_t i = 0; i < num_elements; ++i) { Frame* frame = work_entry.columns[out_idx][i].as_frame(); i64 buffer_size = frame->size(); u8* buffer = frame->data; s_write(output_file, buffer, buffer_size); size_written += buffer_size; } } video_col_idx++; } else { // Write number of elements in the file s_write(output_metadata_file, num_elements); // Write out all output sizes to metadata file so we can easily index into the data file for (size_t i = 0; i < num_elements; ++i) { i64 buffer_size = work_entry.columns[out_idx][i].size; s_write(output_metadata_file, buffer_size); size_written += sizeof(i64); } // Write actual output data for (size_t i = 0; i < num_elements; ++i) { i64 buffer_size = work_entry.columns[out_idx][i].size; u8* buffer = work_entry.columns[out_idx][i].buffer; s_write(output_file, buffer, buffer_size); size_written += buffer_size; } } // TODO(apoms): For now, all evaluators are expected to return CPU // buffers as output so just assume CPU for (size_t i = 0; i < num_elements; ++i) { delete_element(CPU_DEVICE, work_entry.columns[out_idx][i]); } profiler_.add_interval("io", io_start, now()); profiler_.increment("io_write", size_written); } } void SaveWorker::new_task(IOItem item, std::vector<ColumnType> column_types) { auto io_start = now(); for (auto& file : output_) { file->save(); } for (auto& file : output_metadata_) { file->save(); } for (auto& meta : video_metadata_) { write_video_metadata(storage_.get(), meta); } output_.clear(); output_metadata_.clear(); video_metadata_.clear(); profiler_.add_interval("io", io_start, now()); for (size_t out_idx = 0; out_idx < column_types.size(); ++out_idx) { const std::string output_path = table_item_output_path(item.table_id(), out_idx, item.item_id()); const std::string output_metdata_path = table_item_metadata_path( item.table_id(), out_idx, item.item_id()); WriteFile* output_file = nullptr; BACKOFF_FAIL(storage_->make_write_file(output_path, output_file)); output_.emplace_back(output_file); BACKOFF_FAIL(storage_->make_write_file(output_metdata_path, output_file)); output_metadata_.emplace_back(output_file); if (column_types[out_idx] == ColumnType::Video) { video_metadata_.emplace_back(); VideoMetadata& video_meta = video_metadata_.back(); proto::VideoDescriptor& video_descriptor = video_meta.get_descriptor(); video_descriptor.set_table_id(item.table_id()); video_descriptor.set_column_id(out_idx); video_descriptor.set_item_id(item.item_id()); } } } } } <commit_msg>Fix build<commit_after>/* Copyright 2016 Carnegie Mellon University * * 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 "scanner/engine/save_worker.h" #include "scanner/engine/metadata.h" #include "scanner/util/common.h" #include "scanner/util/storehouse.h" #include "scanner/video/h264_byte_stream_index_creator.h" #include "storehouse/storage_backend.h" #include <glog/logging.h> using storehouse::StoreResult; using storehouse::WriteFile; using storehouse::RandomReadFile; namespace scanner { namespace internal { SaveWorker::SaveWorker(const SaveWorkerArgs& args) : node_id_(args.node_id), worker_id_(args.worker_id), profiler_(args.profiler) { auto setup_start = now(); // Setup a distinct storage backend for each IO thread storage_.reset( storehouse::StorageBackend::make_from_config(args.storage_config)); args.profiler.add_interval("setup", setup_start, now()); } SaveWorker::~SaveWorker() { for (auto& file : output_) { file->save(); } for (auto& file : output_metadata_) { file->save(); } for (auto& meta : video_metadata_) { write_video_metadata(storage_.get(), meta); } output_.clear(); output_metadata_.clear(); video_metadata_.clear(); } void SaveWorker::feed(std::tuple<IOItem, EvalWorkEntry>& input_entry) { IOItem& io_item = std::get<0>(input_entry); EvalWorkEntry& work_entry = std::get<1>(input_entry); // Write out each output column to an individual data file i32 video_col_idx = 0; for (size_t out_idx = 0; out_idx < work_entry.columns.size(); ++out_idx) { u64 num_elements = static_cast<u64>(work_entry.columns[out_idx].size()); auto io_start = now(); WriteFile* output_file = output_[out_idx].get(); WriteFile* output_metadata_file = output_metadata_[out_idx].get(); if (work_entry.columns[out_idx].size() != num_elements) { LOG(FATAL) << "Output layer's element vector has wrong length"; } // Ensure the data is on the CPU move_if_different_address_space(profiler_, work_entry.column_handles[out_idx], CPU_DEVICE, work_entry.columns[out_idx]); bool compressed = work_entry.compressed[out_idx]; // If this is a video... i64 size_written = 0; if (work_entry.column_types[out_idx] == ColumnType::Video) { // Read frame info column assert(work_entry.columns[out_idx].size() > 0); FrameInfo frame_info = work_entry.frame_sizes[video_col_idx]; // Create index column VideoMetadata& video_meta = video_metadata_[video_col_idx]; proto::VideoDescriptor& video_descriptor = video_meta.get_descriptor(); video_descriptor.set_width(frame_info.width()); video_descriptor.set_height(frame_info.height()); video_descriptor.set_channels(frame_info.channels()); video_descriptor.set_frame_type(frame_info.type); video_descriptor.set_time_base_num(1); video_descriptor.set_time_base_denom(25); video_descriptor.set_num_encoded_videos( video_descriptor.num_encoded_videos() + 1); if (compressed && frame_info.type == FrameType::U8 && frame_info.channels() == 3) { H264ByteStreamIndexCreator index_creator(output_file); for (size_t i = 0; i < num_elements; ++i) { Element& element = work_entry.columns[out_idx][i]; if (!index_creator.feed_packet(element.buffer, element.size)) { LOG(FATAL) << "Error in save worker h264 index creator: " << index_creator.error_message(); } size_written += element.size; } i64 frame = index_creator.frames(); i32 num_non_ref_frames = index_creator.num_non_ref_frames(); const std::vector<u8>& metadata_bytes = index_creator.metadata_bytes(); const std::vector<i64>& keyframe_positions = index_creator.keyframe_positions(); const std::vector<i64>& keyframe_timestamps = index_creator.keyframe_timestamps(); const std::vector<i64>& keyframe_byte_offsets = index_creator.keyframe_byte_offsets(); video_descriptor.set_chroma_format(proto::VideoDescriptor::YUV_420); video_descriptor.set_codec_type(proto::VideoDescriptor::H264); video_descriptor.set_frames(video_descriptor.frames() + frame); video_descriptor.add_frames_per_video(frame); video_descriptor.add_keyframes_per_video(keyframe_positions.size()); video_descriptor.add_size_per_video(index_creator.bytestream_pos()); video_descriptor.set_metadata_packets(metadata_bytes.data(), metadata_bytes.size()); for (i64 v : keyframe_positions) { video_descriptor.add_keyframe_positions(v); } for (i64 v : keyframe_timestamps) { video_descriptor.add_keyframe_timestamps(v); } for (i64 v : keyframe_byte_offsets) { video_descriptor.add_keyframe_byte_offsets(v); } } else { // Non h264 compressible video column video_descriptor.set_codec_type(proto::VideoDescriptor::RAW); // Need to specify but not used for this type video_descriptor.set_chroma_format(proto::VideoDescriptor::YUV_420); video_descriptor.set_frames(video_descriptor.frames() + num_elements); // Write number of elements in the file s_write(output_metadata_file, num_elements); // Write out all output sizes first so we can easily index into the // file for (size_t i = 0; i < num_elements; ++i) { Frame* frame = work_entry.columns[out_idx][i].as_frame(); i64 buffer_size = frame->size(); s_write(output_metadata_file, buffer_size); size_written += sizeof(i64); } // Write actual output data for (size_t i = 0; i < num_elements; ++i) { Frame* frame = work_entry.columns[out_idx][i].as_frame(); i64 buffer_size = frame->size(); u8* buffer = frame->data; s_write(output_file, buffer, buffer_size); size_written += buffer_size; } } video_col_idx++; } else { // Write number of elements in the file s_write(output_metadata_file, num_elements); // Write out all output sizes to metadata file so we can easily index into the data file for (size_t i = 0; i < num_elements; ++i) { i64 buffer_size = work_entry.columns[out_idx][i].size; s_write(output_metadata_file, buffer_size); size_written += sizeof(i64); } // Write actual output data for (size_t i = 0; i < num_elements; ++i) { i64 buffer_size = work_entry.columns[out_idx][i].size; u8* buffer = work_entry.columns[out_idx][i].buffer; s_write(output_file, buffer, buffer_size); size_written += buffer_size; } } // TODO(apoms): For now, all evaluators are expected to return CPU // buffers as output so just assume CPU for (size_t i = 0; i < num_elements; ++i) { delete_element(CPU_DEVICE, work_entry.columns[out_idx][i]); } profiler_.add_interval("io", io_start, now()); profiler_.increment("io_write", size_written); } } void SaveWorker::new_task(IOItem item, std::vector<ColumnType> column_types) { auto io_start = now(); for (auto& file : output_) { file->save(); } for (auto& file : output_metadata_) { file->save(); } for (auto& meta : video_metadata_) { write_video_metadata(storage_.get(), meta); } output_.clear(); output_metadata_.clear(); video_metadata_.clear(); profiler_.add_interval("io", io_start, now()); for (size_t out_idx = 0; out_idx < column_types.size(); ++out_idx) { const std::string output_path = table_item_output_path(item.table_id(), out_idx, item.item_id()); const std::string output_metdata_path = table_item_metadata_path( item.table_id(), out_idx, item.item_id()); WriteFile* output_file = nullptr; BACKOFF_FAIL(storage_->make_write_file(output_path, output_file)); output_.emplace_back(output_file); BACKOFF_FAIL(storage_->make_write_file(output_metdata_path, output_file)); output_metadata_.emplace_back(output_file); if (column_types[out_idx] == ColumnType::Video) { video_metadata_.emplace_back(); VideoMetadata& video_meta = video_metadata_.back(); proto::VideoDescriptor& video_descriptor = video_meta.get_descriptor(); video_descriptor.set_table_id(item.table_id()); video_descriptor.set_column_id(out_idx); video_descriptor.set_item_id(item.item_id()); } } } } } <|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 "content/browser/webui/web_ui.h" #include "base/i18n/rtl.h" #include "base/json/json_writer.h" #include "base/stl_util-inl.h" #include "base/string_number_conversions.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "chrome/common/extensions/extension_messages.h" #include "chrome/common/render_messages.h" #include "content/browser/renderer_host/render_view_host.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/browser/tab_contents/tab_contents_view.h" #include "content/browser/webui/generic_handler.h" #include "content/common/bindings_policy.h" namespace { string16 GetJavascript(const std::string& function_name, const std::vector<const Value*>& arg_list) { string16 parameters; std::string json; for (size_t i = 0; i < arg_list.size(); ++i) { if (i > 0) parameters += char16(','); base::JSONWriter::Write(arg_list[i], false, &json); parameters += UTF8ToUTF16(json); } return ASCIIToUTF16(function_name) + char16('(') + parameters + char16(')') + char16(';'); } } // namespace WebUI::WebUI(TabContents* contents) : hide_favicon_(false), force_bookmark_bar_visible_(false), focus_location_bar_by_default_(false), should_hide_url_(false), link_transition_type_(PageTransition::LINK), bindings_(BindingsPolicy::WEB_UI), register_callback_overwrites_(false), tab_contents_(contents) { GenericHandler* handler = new GenericHandler(); AddMessageHandler(handler->Attach(this)); } WebUI::~WebUI() { STLDeleteContainerPairSecondPointers(message_callbacks_.begin(), message_callbacks_.end()); STLDeleteContainerPointers(handlers_.begin(), handlers_.end()); } // WebUI, public: ------------------------------------------------------------- const WebUI::TypeID WebUI::kNoWebUI = NULL; void WebUI::ProcessWebUIMessage( const ExtensionHostMsg_DomMessage_Params& params) { // Look up the callback for this message. MessageCallbackMap::const_iterator callback = message_callbacks_.find(params.name); if (callback == message_callbacks_.end()) return; // Forward this message and content on. callback->second->Run(&params.arguments); } void WebUI::CallJavascriptFunction(const std::string& function_name) { DCHECK(IsStringASCII(function_name)); string16 javascript = ASCIIToUTF16(function_name + "();"); ExecuteJavascript(javascript); } void WebUI::CallJavascriptFunction(const std::string& function_name, const Value& arg) { DCHECK(IsStringASCII(function_name)); std::vector<const Value*> args; args.push_back(&arg); ExecuteJavascript(GetJavascript(function_name, args)); } void WebUI::CallJavascriptFunction( const std::string& function_name, const Value& arg1, const Value& arg2) { DCHECK(IsStringASCII(function_name)); std::vector<const Value*> args; args.push_back(&arg1); args.push_back(&arg2); ExecuteJavascript(GetJavascript(function_name, args)); } void WebUI::CallJavascriptFunction( const std::string& function_name, const Value& arg1, const Value& arg2, const Value& arg3) { DCHECK(IsStringASCII(function_name)); std::vector<const Value*> args; args.push_back(&arg1); args.push_back(&arg2); args.push_back(&arg3); ExecuteJavascript(GetJavascript(function_name, args)); } void WebUI::CallJavascriptFunction( const std::string& function_name, const Value& arg1, const Value& arg2, const Value& arg3, const Value& arg4) { DCHECK(IsStringASCII(function_name)); std::vector<const Value*> args; args.push_back(&arg1); args.push_back(&arg2); args.push_back(&arg3); args.push_back(&arg4); ExecuteJavascript(GetJavascript(function_name, args)); } void WebUI::CallJavascriptFunction( const std::string& function_name, const std::vector<const Value*>& args) { DCHECK(IsStringASCII(function_name)); ExecuteJavascript(GetJavascript(function_name, args)); } void WebUI::RegisterMessageCallback(const std::string &message, MessageCallback *callback) { std::pair<MessageCallbackMap::iterator, bool> result = message_callbacks_.insert(std::make_pair(message, callback)); // Overwrite preexisting message callback mappings. if (register_callback_overwrites() && !result.second) result.first->second = callback; } Profile* WebUI::GetProfile() const { DCHECK(tab_contents()); return tab_contents()->profile(); } RenderViewHost* WebUI::GetRenderViewHost() const { DCHECK(tab_contents()); return tab_contents()->render_view_host(); } // WebUI, protected: ---------------------------------------------------------- void WebUI::AddMessageHandler(WebUIMessageHandler* handler) { handlers_.push_back(handler); } void WebUI::ExecuteJavascript(const string16& javascript) { GetRenderViewHost()->ExecuteJavascriptInWebFrame(string16(), javascript); } /////////////////////////////////////////////////////////////////////////////// // WebUIMessageHandler WebUIMessageHandler::WebUIMessageHandler() : web_ui_(NULL) { } WebUIMessageHandler::~WebUIMessageHandler() { } WebUIMessageHandler* WebUIMessageHandler::Attach(WebUI* web_ui) { web_ui_ = web_ui; RegisterMessages(); return this; } // WebUIMessageHandler, protected: --------------------------------------------- void WebUIMessageHandler::SetURLAndTitle(DictionaryValue* dictionary, string16 title, const GURL& gurl) { dictionary->SetString("url", gurl.spec()); bool using_url_as_the_title = false; if (title.empty()) { using_url_as_the_title = true; title = UTF8ToUTF16(gurl.spec()); } // Since the title can contain BiDi text, we need to mark the text as either // RTL or LTR, depending on the characters in the string. If we use the URL // as the title, we mark the title as LTR since URLs are always treated as // left to right strings. string16 title_to_set(title); if (base::i18n::IsRTL()) { if (using_url_as_the_title) { base::i18n::WrapStringWithLTRFormatting(&title_to_set); } else { base::i18n::AdjustStringForLocaleDirection(&title_to_set); } } dictionary->SetString("title", title_to_set); } bool WebUIMessageHandler::ExtractIntegerValue(const ListValue* value, int* out_int) { std::string string_value; if (value->GetString(0, &string_value)) return base::StringToInt(string_value, out_int); NOTREACHED(); return false; } string16 WebUIMessageHandler::ExtractStringValue(const ListValue* value) { string16 string16_value; if (value->GetString(0, &string16_value)) return string16_value; NOTREACHED(); return string16(); } <commit_msg>UX: hide "chrome://newtab/" in location bar.<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 "content/browser/webui/web_ui.h" #include "base/i18n/rtl.h" #include "base/json/json_writer.h" #include "base/stl_util-inl.h" #include "base/string_number_conversions.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "chrome/common/extensions/extension_messages.h" #include "chrome/common/render_messages.h" #include "content/browser/renderer_host/render_view_host.h" #include "content/browser/tab_contents/tab_contents.h" #include "content/browser/tab_contents/tab_contents_view.h" #include "content/browser/webui/generic_handler.h" #include "content/common/bindings_policy.h" namespace { string16 GetJavascript(const std::string& function_name, const std::vector<const Value*>& arg_list) { string16 parameters; std::string json; for (size_t i = 0; i < arg_list.size(); ++i) { if (i > 0) parameters += char16(','); base::JSONWriter::Write(arg_list[i], false, &json); parameters += UTF8ToUTF16(json); } return ASCIIToUTF16(function_name) + char16('(') + parameters + char16(')') + char16(';'); } } // namespace WebUI::WebUI(TabContents* contents) : hide_favicon_(false), force_bookmark_bar_visible_(false), focus_location_bar_by_default_(false), #if defined(TOOLKIT_MEEGOTOUCH) should_hide_url_(true), #else should_hide_url_(false), #endif link_transition_type_(PageTransition::LINK), bindings_(BindingsPolicy::WEB_UI), register_callback_overwrites_(false), tab_contents_(contents) { GenericHandler* handler = new GenericHandler(); AddMessageHandler(handler->Attach(this)); } WebUI::~WebUI() { STLDeleteContainerPairSecondPointers(message_callbacks_.begin(), message_callbacks_.end()); STLDeleteContainerPointers(handlers_.begin(), handlers_.end()); } // WebUI, public: ------------------------------------------------------------- const WebUI::TypeID WebUI::kNoWebUI = NULL; void WebUI::ProcessWebUIMessage( const ExtensionHostMsg_DomMessage_Params& params) { // Look up the callback for this message. MessageCallbackMap::const_iterator callback = message_callbacks_.find(params.name); if (callback == message_callbacks_.end()) return; // Forward this message and content on. callback->second->Run(&params.arguments); } void WebUI::CallJavascriptFunction(const std::string& function_name) { DCHECK(IsStringASCII(function_name)); string16 javascript = ASCIIToUTF16(function_name + "();"); ExecuteJavascript(javascript); } void WebUI::CallJavascriptFunction(const std::string& function_name, const Value& arg) { DCHECK(IsStringASCII(function_name)); std::vector<const Value*> args; args.push_back(&arg); ExecuteJavascript(GetJavascript(function_name, args)); } void WebUI::CallJavascriptFunction( const std::string& function_name, const Value& arg1, const Value& arg2) { DCHECK(IsStringASCII(function_name)); std::vector<const Value*> args; args.push_back(&arg1); args.push_back(&arg2); ExecuteJavascript(GetJavascript(function_name, args)); } void WebUI::CallJavascriptFunction( const std::string& function_name, const Value& arg1, const Value& arg2, const Value& arg3) { DCHECK(IsStringASCII(function_name)); std::vector<const Value*> args; args.push_back(&arg1); args.push_back(&arg2); args.push_back(&arg3); ExecuteJavascript(GetJavascript(function_name, args)); } void WebUI::CallJavascriptFunction( const std::string& function_name, const Value& arg1, const Value& arg2, const Value& arg3, const Value& arg4) { DCHECK(IsStringASCII(function_name)); std::vector<const Value*> args; args.push_back(&arg1); args.push_back(&arg2); args.push_back(&arg3); args.push_back(&arg4); ExecuteJavascript(GetJavascript(function_name, args)); } void WebUI::CallJavascriptFunction( const std::string& function_name, const std::vector<const Value*>& args) { DCHECK(IsStringASCII(function_name)); ExecuteJavascript(GetJavascript(function_name, args)); } void WebUI::RegisterMessageCallback(const std::string &message, MessageCallback *callback) { std::pair<MessageCallbackMap::iterator, bool> result = message_callbacks_.insert(std::make_pair(message, callback)); // Overwrite preexisting message callback mappings. if (register_callback_overwrites() && !result.second) result.first->second = callback; } Profile* WebUI::GetProfile() const { DCHECK(tab_contents()); return tab_contents()->profile(); } RenderViewHost* WebUI::GetRenderViewHost() const { DCHECK(tab_contents()); return tab_contents()->render_view_host(); } // WebUI, protected: ---------------------------------------------------------- void WebUI::AddMessageHandler(WebUIMessageHandler* handler) { handlers_.push_back(handler); } void WebUI::ExecuteJavascript(const string16& javascript) { GetRenderViewHost()->ExecuteJavascriptInWebFrame(string16(), javascript); } /////////////////////////////////////////////////////////////////////////////// // WebUIMessageHandler WebUIMessageHandler::WebUIMessageHandler() : web_ui_(NULL) { } WebUIMessageHandler::~WebUIMessageHandler() { } WebUIMessageHandler* WebUIMessageHandler::Attach(WebUI* web_ui) { web_ui_ = web_ui; RegisterMessages(); return this; } // WebUIMessageHandler, protected: --------------------------------------------- void WebUIMessageHandler::SetURLAndTitle(DictionaryValue* dictionary, string16 title, const GURL& gurl) { dictionary->SetString("url", gurl.spec()); bool using_url_as_the_title = false; if (title.empty()) { using_url_as_the_title = true; title = UTF8ToUTF16(gurl.spec()); } // Since the title can contain BiDi text, we need to mark the text as either // RTL or LTR, depending on the characters in the string. If we use the URL // as the title, we mark the title as LTR since URLs are always treated as // left to right strings. string16 title_to_set(title); if (base::i18n::IsRTL()) { if (using_url_as_the_title) { base::i18n::WrapStringWithLTRFormatting(&title_to_set); } else { base::i18n::AdjustStringForLocaleDirection(&title_to_set); } } dictionary->SetString("title", title_to_set); } bool WebUIMessageHandler::ExtractIntegerValue(const ListValue* value, int* out_int) { std::string string_value; if (value->GetString(0, &string_value)) return base::StringToInt(string_value, out_int); NOTREACHED(); return false; } string16 WebUIMessageHandler::ExtractStringValue(const ListValue* value) { string16 string16_value; if (value->GetString(0, &string16_value)) return string16_value; NOTREACHED(); return string16(); } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkProjectedTexture.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2000 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 REGENTS 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 "vtkProjectedTexture.h" #include "vtkMath.h" #include "vtkTCoords.h" #include "vtkObjectFactory.h" //------------------------------------------------------------------------------ vtkProjectedTexture* vtkProjectedTexture::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkProjectedTexture"); if(ret) { return (vtkProjectedTexture*)ret; } // If the factory was unable to create the object, then create it here. return new vtkProjectedTexture; } // Description: // Initialize the projected texture filter with a position of (0, 0, 1), // a focal point of (0, 0, 0), an up vector on the +y axis, // an aspect ratio of the projection frustum of equal width, height, and focal // length, an S range of (0, 1) and a T range of (0, 1). vtkProjectedTexture::vtkProjectedTexture() { this->Position[0] = 0.0; this->Position[1] = 0.0; this->Position[2] = 1.0; this->Orientation[0] = this->Orientation[1] = this->Orientation[2] = 0.0; this->SetFocalPoint(0.0, 0.0, 0.0); this->Up[0] = 0.0; this->Up[1] = 1.0; this->Up[2] = 0.0; this->AspectRatio[0] = 0.0; this->AspectRatio[1] = 1.0; this->AspectRatio[2] = 0.0; this->SRange[0] = 0.0; this->SRange[1] = 1.0; this->TRange[0] = 0.0; this->TRange[1] = 1.0; } void vtkProjectedTexture::SetFocalPoint(float fp[3]) { this->SetFocalPoint(fp[0], fp[1], fp[2]); } void vtkProjectedTexture::SetFocalPoint(float x, float y, float z) { float orientation[3]; orientation[0] = x - this->Position[0]; orientation[1] = y - this->Position[1]; orientation[2] = z - this->Position[2]; vtkMath::Normalize(orientation); if (this->Orientation[0] != orientation[0] || this->Orientation[1] != orientation[1] || this->Orientation[2] != orientation[2]) { this->Orientation[0] = orientation[0]; this->Orientation[1] = orientation[1]; this->Orientation[2] = orientation[2]; this->Modified(); } this->FocalPoint[0] = x; this->FocalPoint[1] = y; this->FocalPoint[2] = z; } void vtkProjectedTexture::Execute() { float tcoords[2]; int numPts; vtkTCoords *newTCoords; int i, j; float proj; float rightv[3], upv[3], diff[3]; float sScale, tScale, sOffset, tOffset, sSize, tSize, s, t; vtkDataSet *input = this->GetInput(); float *p; vtkDataSet *output = this->GetOutput(); vtkDebugMacro(<<"Generating texture coordinates!"); // First, copy the input to the output as a starting point output->CopyStructure( input ); numPts=input->GetNumberOfPoints(); // // Allocate texture data // newTCoords = vtkTCoords::New(); newTCoords->SetNumberOfTCoords(numPts); vtkMath::Normalize (this->Orientation); vtkMath::Cross (this->Orientation, this->Up, rightv); vtkMath::Normalize (rightv); vtkMath::Cross (rightv, this->Orientation, upv); vtkMath::Normalize (upv); sSize = this->AspectRatio[0] / this->AspectRatio[2]; tSize = this->AspectRatio[1] / this->AspectRatio[2]; sScale = (this->SRange[1] - this->SRange[0])/sSize; tScale = (this->TRange[1] - this->TRange[0])/tSize; sOffset = (this->SRange[1] - this->SRange[0])/2.0 + this->SRange[0]; tOffset = (this->TRange[1] - this->TRange[0])/2.0 + this->TRange[0]; // compute s-t coordinates for (i = 0; i < numPts; i++) { p = output->GetPoint(i); for (j = 0; j < 3; j++) { diff[j] = p[j] - this->Position[j]; } proj = vtkMath::Dot(diff, this->Orientation); if(proj < 1.0e-10 && proj > -1.0e-10) { vtkWarningMacro(<<"Singularity: point located at frustum Position"); tcoords[0] = sOffset; tcoords[1] = tOffset; } else { for (j = 0; j < 3; j++) { diff[j] = diff[j]/proj - this->Orientation[j]; } s = vtkMath::Dot(diff, rightv); t = vtkMath::Dot(diff, upv); tcoords[0] = s * sScale + sOffset; tcoords[1] = t * tScale + tOffset; } newTCoords->SetTCoord(i,tcoords); } // // Update ourselves // output->GetPointData()->CopyTCoordsOff(); output->GetPointData()->PassData(input->GetPointData()); output->GetPointData()->SetTCoords(newTCoords); newTCoords->Delete(); } void vtkProjectedTexture::PrintSelf(ostream& os, vtkIndent indent) { vtkDataSetToDataSetFilter::PrintSelf(os,indent); os << indent << "S Range: (" << this->SRange[0] << ", " << this->SRange[1] << ")\n"; os << indent << "T Range: (" << this->TRange[0] << ", " << this->TRange[1] << ")\n"; os << indent << "Position: (" << this->Position[0] << ", " << this->Position[1] << ", " << this->Position[2] << ")\n"; os << indent << "Orientation: (" << this->Orientation[0] << ", " << this->Orientation[1] << ", " << this->Orientation[2] << ")\n"; os << indent << "Focal Point: (" << this->FocalPoint[0] << ", " << this->FocalPoint[1] << ", " << this->FocalPoint[2] << ")\n"; os << indent << "Up: (" << this->Up[0] << ", " << this->Up[1] << ", " << this->Up[2] << ")\n"; os << indent << "AspectRatio: (" << this->AspectRatio[0] << ", " << this->AspectRatio[1] << ", " << this->AspectRatio[2] << ")\n"; } <commit_msg>Made AspectRatio defaults be sensible.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkProjectedTexture.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2000 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 REGENTS 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 "vtkProjectedTexture.h" #include "vtkMath.h" #include "vtkTCoords.h" #include "vtkObjectFactory.h" //------------------------------------------------------------------------------ vtkProjectedTexture* vtkProjectedTexture::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkProjectedTexture"); if(ret) { return (vtkProjectedTexture*)ret; } // If the factory was unable to create the object, then create it here. return new vtkProjectedTexture; } // Description: // Initialize the projected texture filter with a position of (0, 0, 1), // a focal point of (0, 0, 0), an up vector on the +y axis, // an aspect ratio of the projection frustum of equal width, height, and focal // length, an S range of (0, 1) and a T range of (0, 1). vtkProjectedTexture::vtkProjectedTexture() { this->Position[0] = 0.0; this->Position[1] = 0.0; this->Position[2] = 1.0; this->Orientation[0] = this->Orientation[1] = this->Orientation[2] = 0.0; this->SetFocalPoint(0.0, 0.0, 0.0); this->Up[0] = 0.0; this->Up[1] = 1.0; this->Up[2] = 0.0; this->AspectRatio[0] = 1.0; this->AspectRatio[1] = 1.0; this->AspectRatio[2] = 1.0; this->SRange[0] = 0.0; this->SRange[1] = 1.0; this->TRange[0] = 0.0; this->TRange[1] = 1.0; } void vtkProjectedTexture::SetFocalPoint(float fp[3]) { this->SetFocalPoint(fp[0], fp[1], fp[2]); } void vtkProjectedTexture::SetFocalPoint(float x, float y, float z) { float orientation[3]; orientation[0] = x - this->Position[0]; orientation[1] = y - this->Position[1]; orientation[2] = z - this->Position[2]; vtkMath::Normalize(orientation); if (this->Orientation[0] != orientation[0] || this->Orientation[1] != orientation[1] || this->Orientation[2] != orientation[2]) { this->Orientation[0] = orientation[0]; this->Orientation[1] = orientation[1]; this->Orientation[2] = orientation[2]; this->Modified(); } this->FocalPoint[0] = x; this->FocalPoint[1] = y; this->FocalPoint[2] = z; } void vtkProjectedTexture::Execute() { float tcoords[2]; int numPts; vtkTCoords *newTCoords; int i, j; float proj; float rightv[3], upv[3], diff[3]; float sScale, tScale, sOffset, tOffset, sSize, tSize, s, t; vtkDataSet *input = this->GetInput(); float *p; vtkDataSet *output = this->GetOutput(); vtkDebugMacro(<<"Generating texture coordinates!"); // First, copy the input to the output as a starting point output->CopyStructure( input ); numPts=input->GetNumberOfPoints(); // // Allocate texture data // newTCoords = vtkTCoords::New(); newTCoords->SetNumberOfTCoords(numPts); vtkMath::Normalize (this->Orientation); vtkMath::Cross (this->Orientation, this->Up, rightv); vtkMath::Normalize (rightv); vtkMath::Cross (rightv, this->Orientation, upv); vtkMath::Normalize (upv); sSize = this->AspectRatio[0] / this->AspectRatio[2]; tSize = this->AspectRatio[1] / this->AspectRatio[2]; sScale = (this->SRange[1] - this->SRange[0])/sSize; tScale = (this->TRange[1] - this->TRange[0])/tSize; sOffset = (this->SRange[1] - this->SRange[0])/2.0 + this->SRange[0]; tOffset = (this->TRange[1] - this->TRange[0])/2.0 + this->TRange[0]; // compute s-t coordinates for (i = 0; i < numPts; i++) { p = output->GetPoint(i); for (j = 0; j < 3; j++) { diff[j] = p[j] - this->Position[j]; } proj = vtkMath::Dot(diff, this->Orientation); if(proj < 1.0e-10 && proj > -1.0e-10) { vtkWarningMacro(<<"Singularity: point located at frustum Position"); tcoords[0] = sOffset; tcoords[1] = tOffset; } else { for (j = 0; j < 3; j++) { diff[j] = diff[j]/proj - this->Orientation[j]; } s = vtkMath::Dot(diff, rightv); t = vtkMath::Dot(diff, upv); tcoords[0] = s * sScale + sOffset; tcoords[1] = t * tScale + tOffset; } newTCoords->SetTCoord(i,tcoords); } // // Update ourselves // output->GetPointData()->CopyTCoordsOff(); output->GetPointData()->PassData(input->GetPointData()); output->GetPointData()->SetTCoords(newTCoords); newTCoords->Delete(); } void vtkProjectedTexture::PrintSelf(ostream& os, vtkIndent indent) { vtkDataSetToDataSetFilter::PrintSelf(os,indent); os << indent << "S Range: (" << this->SRange[0] << ", " << this->SRange[1] << ")\n"; os << indent << "T Range: (" << this->TRange[0] << ", " << this->TRange[1] << ")\n"; os << indent << "Position: (" << this->Position[0] << ", " << this->Position[1] << ", " << this->Position[2] << ")\n"; os << indent << "Orientation: (" << this->Orientation[0] << ", " << this->Orientation[1] << ", " << this->Orientation[2] << ")\n"; os << indent << "Focal Point: (" << this->FocalPoint[0] << ", " << this->FocalPoint[1] << ", " << this->FocalPoint[2] << ")\n"; os << indent << "Up: (" << this->Up[0] << ", " << this->Up[1] << ", " << this->Up[2] << ")\n"; os << indent << "AspectRatio: (" << this->AspectRatio[0] << ", " << this->AspectRatio[1] << ", " << this->AspectRatio[2] << ")\n"; } <|endoftext|>
<commit_before>#pragma once #include "bits.hpp" #include <algorithm> namespace spn { //! 任意の型の縦横サイズ template <class T> struct _Size { T width, height; _Size() = default; _Size(const T& s): width(s), height(s) {} _Size(const T& w, const T& h): width(w), height(h) {} template <class T2> _Size(const _Size<T2>& s): width(s.width), height(s.height) {} _Size& operator *= (const T& s) { width *= s; height *= s; return *this; } template <class V> void shiftR(int n, typename std::enable_if<std::is_integral<V>::value>::type* = nullptr) { width >>= n; height >>= n; } template <class V> void shiftR(int n, typename std::enable_if<!std::is_integral<V>::value>::type* = nullptr) { *this *= std::pow(2.f, n); } _Size& operator >>= (int n) { shiftR<T>(n); return *this; } //! 指定したビット数分、右シフトしてもし値がゼロになったら1をセットする void shiftR_one(int n) { width >>= n; width |= ~Bit::ZeroOrFull(width) & 0x01; height >>= n; height |= ~Bit::ZeroOrFull(height) & 0x01; } }; using Size = _Size<uint32_t>; using SizeF = _Size<float>; //! 任意の型の2D矩形 template <class T> struct _Rect { union { struct { T x0, x1, y0, y1; }; T ar[4]; }; _Rect() = default; _Rect(const _Rect& r) = default; _Rect(const T& x_0, const T& x_1, const T& y_0, const T& y_1): x0(x_0), x1(x_1), y0(y_0), y1(y_1) {} T width() const { return x1-x0; } T height() const { return y1-y0; } void addOffset(const T& x, const T& y) { x0 += x; x1 += x; y0 += y; y1 += y; } bool hit(const _Rect& r) const { if(x1 < r.x0 || r.x1 < x0 || y1 < r.y0 || r.y1 < y0) return false; return true; } void shrinkRight(const T& s) { x1 = std::max(x0, x1-s); } void shrinkBottom(const T& s) { y1 = std::max(y0, y1-s); } void shrinkLeft(const T& s) { x0 = std::min(x1, x0+s); } void shrinkTop(const T& s) { y0 = std::min(y1, y0+s); } _Size<T> size() const { return _Size<T>(width(), height()); } template <class T2> _Rect& operator *= (const T2& t) { for(auto& a : ar) a *= t; return *this; } }; using Rect = _Rect<int>; using RectF = _Rect<float>; //! 値の低い方に補正 template <class T> struct PP_Lower { static T proc(const T& t) { T ret = spn::Bit::LowClear(t); return std::max(T(1), ret); } }; //! 値の高い方に補正 template <class T> struct PP_Higher { static T proc(const T& t) { T ret = spn::Bit::LowClear(t); if(t & ~ret) ret <<= 1; return std::max(T(1), ret); } }; //! 2の乗数しか代入できない型 /*! 0も許可されない */ template <class T, template <class> class Policy> class PowValue { using P = Policy<T>; T _value; public: //TODO: テンプレートによる静的な値補正 PowValue(const T& t): _value(P::proc(t)) {} PowValue(const PowValue& p) = default; PowValue& operator = (const PowValue& p) = default; PowValue& operator = (const T& t) { // 2の乗数に補正 (動的なチェック) _value = P::proc(t); return *this; } const T& get() const { return _value; } operator const T& () const { return _value; } }; using PowInt = PowValue<uint32_t, PP_Higher>; using PowSize = _Size<PowInt>; } <commit_msg>Size: 比較演算子の追加<commit_after>#pragma once #include "bits.hpp" #include <algorithm> namespace spn { //! 任意の型の縦横サイズ template <class T> struct _Size { T width, height; _Size() = default; _Size(const T& s): width(s), height(s) {} _Size(const T& w, const T& h): width(w), height(h) {} template <class T2> _Size(const _Size<T2>& s): width(s.width), height(s.height) {} _Size& operator *= (const T& s) { width *= s; height *= s; return *this; } template <class V> void shiftR(int n, typename std::enable_if<std::is_integral<V>::value>::type* = nullptr) { width >>= n; height >>= n; } template <class V> void shiftR(int n, typename std::enable_if<!std::is_integral<V>::value>::type* = nullptr) { *this *= std::pow(2.f, n); } _Size& operator >>= (int n) { shiftR<T>(n); return *this; } //! 指定したビット数分、右シフトしてもし値がゼロになったら1をセットする void shiftR_one(int n) { width >>= n; width |= ~Bit::ZeroOrFull(width) & 0x01; height >>= n; height |= ~Bit::ZeroOrFull(height) & 0x01; } bool operator == (const _Size& s) const { return width == s.width && height == s.height; } bool operator != (const _Size& s) const { return !(this->operator == (s)); } bool operator <= (const _Size& s) const { return width <= s.width && height <= s.height; } }; using Size = _Size<uint32_t>; using SizeF = _Size<float>; //! 任意の型の2D矩形 template <class T> struct _Rect { union { struct { T x0, x1, y0, y1; }; T ar[4]; }; _Rect() = default; _Rect(const _Rect& r) = default; _Rect(const T& x_0, const T& x_1, const T& y_0, const T& y_1): x0(x_0), x1(x_1), y0(y_0), y1(y_1) {} T width() const { return x1-x0; } T height() const { return y1-y0; } void addOffset(const T& x, const T& y) { x0 += x; x1 += x; y0 += y; y1 += y; } bool hit(const _Rect& r) const { if(x1 < r.x0 || r.x1 < x0 || y1 < r.y0 || r.y1 < y0) return false; return true; } void shrinkRight(const T& s) { x1 = std::max(x0, x1-s); } void shrinkBottom(const T& s) { y1 = std::max(y0, y1-s); } void shrinkLeft(const T& s) { x0 = std::min(x1, x0+s); } void shrinkTop(const T& s) { y0 = std::min(y1, y0+s); } _Size<T> size() const { return _Size<T>(width(), height()); } template <class T2> _Rect& operator *= (const T2& t) { for(auto& a : ar) a *= t; return *this; } }; using Rect = _Rect<int>; using RectF = _Rect<float>; //! 値の低い方に補正 template <class T> struct PP_Lower { static T proc(const T& t) { T ret = spn::Bit::LowClear(t); return std::max(T(1), ret); } }; //! 値の高い方に補正 template <class T> struct PP_Higher { static T proc(const T& t) { T ret = spn::Bit::LowClear(t); if(t & ~ret) ret <<= 1; return std::max(T(1), ret); } }; //! 2の乗数しか代入できない型 /*! 0も許可されない */ template <class T, template <class> class Policy> class PowValue { using P = Policy<T>; T _value; public: //TODO: テンプレートによる静的な値補正 PowValue(const T& t): _value(P::proc(t)) {} PowValue(const PowValue& p) = default; PowValue& operator = (const PowValue& p) = default; PowValue& operator = (const T& t) { // 2の乗数に補正 (動的なチェック) _value = P::proc(t); return *this; } const T& get() const { return _value; } operator const T& () const { return _value; } }; using PowInt = PowValue<uint32_t, PP_Higher>; using PowSize = _Size<PowInt>; } <|endoftext|>
<commit_before>/******************************************************************************* * sort.cpp * * Test runner * ******************************************************************************* * Copyright (C) 2016 Lorenz Hübschle-Schneider <lorenz@4z2.de> * * The MIT License (MIT) * * 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 <algorithm> #include <cassert> #include <cstdlib> #include <fstream> #include <iostream> #include <random> #include <sstream> #include "ssssort.h" #include "timer.h" #include "progress_bar.h" const bool debug = false; template <typename T, typename Sorter> double run(T* data, const T* const copy, T* out, size_t size, Sorter sorter, size_t iterations, const std::string &algoname, bool reset_out = true) { progress_bar bar(iterations + 1, algoname); // warmup sorter(data, out, size); ++bar; double time = 0.0; Timer timer; for (size_t it = 0; it < iterations; ++it) { // reset data and timer memcpy(data, copy, size * sizeof(T)); if (reset_out) memset(out, 0, size * sizeof(T)); timer.reset(); sorter(data, out, size); time += timer.get(); ++bar; } bar.undraw(); return time; } template <typename T, typename Generator> void benchmark(size_t size, size_t iterations, Generator generator, const std::string &name, std::ofstream *stat_stream) { T *data = new T[size], *out = new T[size], *copy = new T[size]; Timer timer; // Generate random numbers as input generator(data, size); // create a copy to be able to sort it multiple times memcpy(copy, data, size * sizeof(T)); double t_generate = timer.get_and_reset(); // 1. Super Scalar Sample Sort double t_ssssort = run(data, copy, out, size, [](T* data, T* out, size_t size) { ssssort(data, data + size, out); }, iterations, "ssssort: "); // 2. std::sort double t_stdsort = run(data, copy, out, size, [](T* data, T* /*ignored*/, size_t size) { std::sort(data, data + size); }, iterations, "std::sort: ", false); // verify timer.reset(); bool incorrect = !std::is_sorted(out, out + size); if (incorrect) { std::cerr << "Output data isn't sorted" << std::endl; } for (size_t i = 0; i < size; ++i) { incorrect |= (out[i] != data[i]); if (debug && out[i] != data[i]) { std::cerr << "Err at pos " << i << " expected " << data[i] << " got " << out[i] << std::endl; } } double t_verify = timer.get_and_reset(); delete[] out; delete[] data; delete[] copy; std::stringstream output; output << "RESULT algo=ssssort" << " name=" << name << " size=" << size << " iterations=" << iterations << " time=" << t_ssssort/iterations << " t_generate=" << t_generate << " t_verify=" << t_verify << " correct=" << !incorrect << std::endl << "RESULT algo=stdsort" << " name=" << name << " size=" << size << " iterations=" << iterations << " time=" << t_stdsort/iterations << " t_generate=" << t_generate << " t_verify=0" << " correct=1" << std::endl; auto result_str = output.str(); std::cout << result_str; if (stat_stream != nullptr) *stat_stream << result_str; } template <typename T, typename Generator> void benchmark_generator(Generator generator, const std::string &name, size_t iterations, std::ofstream *stat_stream) { for (size_t log_size = 10; log_size < 27; ++log_size) { size_t size = 1 << log_size; benchmark<T>(size, iterations, generator, name, stat_stream); } } int main(int argc, char *argv[]) { size_t iterations = 10; if (argc > 1) iterations = atoi(argv[1]); std::string stat_file = "stats.txt"; if (argc > 2) stat_file = std::string{argv[2]}; std::ofstream *stat_stream = nullptr; if (stat_file != "-") { stat_stream = new std::ofstream; stat_stream->open(stat_file); } using data_t = int; benchmark_generator<data_t>([](auto data, size_t size){ using T = std::remove_reference_t<decltype(*data)>; std::mt19937 rng{ std::random_device{}() }; for (size_t i = 0; i < size; ++i) { data[i] = static_cast<T>(rng()); } }, "random", iterations, stat_stream); // nearly sorted data generator factory auto nearly_sorted_gen = [](size_t rfrac) { return [rfrac=rfrac](auto data, size_t size) { using T = std::remove_reference_t<decltype(*data)>; std::mt19937 rng{ std::random_device{}() }; // fill with sorted data, using entire range of RNG T factor = static_cast<T>(static_cast<double>(rng.max()) / size); for (size_t i = 0; i < size; ++i) { data[i] = i * factor; } // set 1/rfrac of the items to random values for (size_t i = 0; i < size/rfrac; ++i) { data[rng() % size] = static_cast<T>(rng()); } }; }; benchmark_generator<data_t>(nearly_sorted_gen(5), "80pcsorted", iterations, stat_stream); benchmark_generator<data_t>(nearly_sorted_gen(10), "90pcsorted", iterations, stat_stream); benchmark_generator<data_t>(nearly_sorted_gen(100), "99pcsorted", iterations, stat_stream); benchmark_generator<data_t>(nearly_sorted_gen(1000), "99.9pcsorted", iterations, stat_stream); // nearly sorted data generator factory auto unsorted_tail_gen = [](size_t rfrac) { return [rfrac=rfrac](auto data, size_t size) { using T = std::remove_reference_t<decltype(*data)>; std::mt19937 rng{ std::random_device{}() }; // fill with sorted data, using entire range of RNG size_t ordered_max = size - (size / rfrac); T factor = static_cast<T>(static_cast<double>(rng.max()) / ordered_max); for (size_t i = 0; i < ordered_max; ++i) { data[i] = i * factor; } // set 1/rfrac of the items to random values for (size_t i = ordered_max; i < size; ++i) { data[i] = static_cast<T>(rng()); } }; }; benchmark_generator<data_t>(unsorted_tail_gen(10), "tail90", iterations, stat_stream); benchmark_generator<data_t>(unsorted_tail_gen(100), "tail99", iterations, stat_stream); benchmark_generator<data_t>([](auto data, size_t size){ using T = std::remove_reference_t<decltype(*data)>; for (size_t i = 0; i < size; ++i) { data[i] = static_cast<T>(i); } }, "sorted", iterations, stat_stream); benchmark_generator<data_t>([](auto data, size_t size){ using T = std::remove_reference_t<decltype(*data)>; for (size_t i = 0; i < size; ++i) { data[i] = static_cast<T>(size - i); } }, "reverse", iterations, stat_stream); benchmark_generator<data_t>([](auto data, size_t size){ for (size_t i = 0; i < size; ++i) { data[i] = 1; } }, "ones", iterations, stat_stream); if (stat_stream != nullptr) { stat_stream->close(); delete stat_stream; } } <commit_msg>Flush output stream<commit_after>/******************************************************************************* * sort.cpp * * Test runner * ******************************************************************************* * Copyright (C) 2016 Lorenz Hübschle-Schneider <lorenz@4z2.de> * * The MIT License (MIT) * * 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 <algorithm> #include <cassert> #include <cstdlib> #include <fstream> #include <iostream> #include <random> #include <sstream> #include "ssssort.h" #include "timer.h" #include "progress_bar.h" const bool debug = false; template <typename T, typename Sorter> double run(T* data, const T* const copy, T* out, size_t size, Sorter sorter, size_t iterations, const std::string &algoname, bool reset_out = true) { progress_bar bar(iterations + 1, algoname); // warmup sorter(data, out, size); ++bar; double time = 0.0; Timer timer; for (size_t it = 0; it < iterations; ++it) { // reset data and timer memcpy(data, copy, size * sizeof(T)); if (reset_out) memset(out, 0, size * sizeof(T)); timer.reset(); sorter(data, out, size); time += timer.get(); ++bar; } bar.undraw(); return time; } template <typename T, typename Generator> void benchmark(size_t size, size_t iterations, Generator generator, const std::string &name, std::ofstream *stat_stream) { T *data = new T[size], *out = new T[size], *copy = new T[size]; Timer timer; // Generate random numbers as input generator(data, size); // create a copy to be able to sort it multiple times memcpy(copy, data, size * sizeof(T)); double t_generate = timer.get_and_reset(); // 1. Super Scalar Sample Sort double t_ssssort = run(data, copy, out, size, [](T* data, T* out, size_t size) { ssssort(data, data + size, out); }, iterations, "ssssort: "); // 2. std::sort double t_stdsort = run(data, copy, out, size, [](T* data, T* /*ignored*/, size_t size) { std::sort(data, data + size); }, iterations, "std::sort: ", false); // verify timer.reset(); bool incorrect = !std::is_sorted(out, out + size); if (incorrect) { std::cerr << "Output data isn't sorted" << std::endl; } for (size_t i = 0; i < size; ++i) { incorrect |= (out[i] != data[i]); if (debug && out[i] != data[i]) { std::cerr << "Err at pos " << i << " expected " << data[i] << " got " << out[i] << std::endl; } } double t_verify = timer.get_and_reset(); delete[] out; delete[] data; delete[] copy; std::stringstream output; output << "RESULT algo=ssssort" << " name=" << name << " size=" << size << " iterations=" << iterations << " time=" << t_ssssort/iterations << " t_generate=" << t_generate << " t_verify=" << t_verify << " correct=" << !incorrect << std::endl << "RESULT algo=stdsort" << " name=" << name << " size=" << size << " iterations=" << iterations << " time=" << t_stdsort/iterations << " t_generate=" << t_generate << " t_verify=0" << " correct=1" << std::endl; auto result_str = output.str(); std::cout << result_str; if (stat_stream != nullptr) *stat_stream << result_str << std::flush; } template <typename T, typename Generator> void benchmark_generator(Generator generator, const std::string &name, size_t iterations, std::ofstream *stat_stream) { for (size_t log_size = 10; log_size < 27; ++log_size) { size_t size = 1 << log_size; benchmark<T>(size, iterations, generator, name, stat_stream); } } int main(int argc, char *argv[]) { size_t iterations = 10; if (argc > 1) iterations = atoi(argv[1]); std::string stat_file = "stats.txt"; if (argc > 2) stat_file = std::string{argv[2]}; std::ofstream *stat_stream = nullptr; if (stat_file != "-") { stat_stream = new std::ofstream; stat_stream->open(stat_file); } using data_t = int; benchmark_generator<data_t>([](auto data, size_t size){ using T = std::remove_reference_t<decltype(*data)>; std::mt19937 rng{ std::random_device{}() }; for (size_t i = 0; i < size; ++i) { data[i] = static_cast<T>(rng()); } }, "random", iterations, stat_stream); // nearly sorted data generator factory auto nearly_sorted_gen = [](size_t rfrac) { return [rfrac=rfrac](auto data, size_t size) { using T = std::remove_reference_t<decltype(*data)>; std::mt19937 rng{ std::random_device{}() }; // fill with sorted data, using entire range of RNG T factor = static_cast<T>(static_cast<double>(rng.max()) / size); for (size_t i = 0; i < size; ++i) { data[i] = i * factor; } // set 1/rfrac of the items to random values for (size_t i = 0; i < size/rfrac; ++i) { data[rng() % size] = static_cast<T>(rng()); } }; }; benchmark_generator<data_t>(nearly_sorted_gen(5), "80pcsorted", iterations, stat_stream); benchmark_generator<data_t>(nearly_sorted_gen(10), "90pcsorted", iterations, stat_stream); benchmark_generator<data_t>(nearly_sorted_gen(100), "99pcsorted", iterations, stat_stream); benchmark_generator<data_t>(nearly_sorted_gen(1000), "99.9pcsorted", iterations, stat_stream); // nearly sorted data generator factory auto unsorted_tail_gen = [](size_t rfrac) { return [rfrac=rfrac](auto data, size_t size) { using T = std::remove_reference_t<decltype(*data)>; std::mt19937 rng{ std::random_device{}() }; // fill with sorted data, using entire range of RNG size_t ordered_max = size - (size / rfrac); T factor = static_cast<T>(static_cast<double>(rng.max()) / ordered_max); for (size_t i = 0; i < ordered_max; ++i) { data[i] = i * factor; } // set 1/rfrac of the items to random values for (size_t i = ordered_max; i < size; ++i) { data[i] = static_cast<T>(rng()); } }; }; benchmark_generator<data_t>(unsorted_tail_gen(10), "tail90", iterations, stat_stream); benchmark_generator<data_t>(unsorted_tail_gen(100), "tail99", iterations, stat_stream); benchmark_generator<data_t>([](auto data, size_t size){ using T = std::remove_reference_t<decltype(*data)>; for (size_t i = 0; i < size; ++i) { data[i] = static_cast<T>(i); } }, "sorted", iterations, stat_stream); benchmark_generator<data_t>([](auto data, size_t size){ using T = std::remove_reference_t<decltype(*data)>; for (size_t i = 0; i < size; ++i) { data[i] = static_cast<T>(size - i); } }, "reverse", iterations, stat_stream); benchmark_generator<data_t>([](auto data, size_t size){ for (size_t i = 0; i < size; ++i) { data[i] = 1; } }, "ones", iterations, stat_stream); if (stat_stream != nullptr) { stat_stream->close(); delete stat_stream; } } <|endoftext|>
<commit_before>// Begin CVS Header // $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/layoutUI/CGraphCurve.cpp,v $ // $Revision: 1.8 $ // $Name: $ // $Author: urost $ // $Date: 2008/01/15 09:52:39 $ // End CVS Header // Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. // Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. // Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. // Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. #include "copasi.h" #include "CGraphCurve.h" CGraphCurve::CGraphCurve() : CLCurve() { mHasArrow = false; } CGraphCurve::CGraphCurve(const CLCurve & c) : CLCurve(c) { mHasArrow = false; } CGraphCurve::CGraphCurve(const CGraphCurve & c) : CLCurve(c) { mHasArrow = c.mHasArrow; mArrow = c.mArrow; mRole = c.mRole; } void CGraphCurve::scale (const double & scaleFactor) { unsigned int i; // scale all segments for (i = 0;i < mCurveSegments.size();i++) { mCurveSegments[i].scale(scaleFactor); } if (mHasArrow) mArrow.scale(scaleFactor); } void CGraphCurve::invertOrderOfPoints() { std::cout << " invertOrderOfPoints for " << mCurveSegments.size() << " segments" << std::endl; unsigned int i; // invert order of points in each segment CLPoint h; // puffer variable for (i = 0;i < mCurveSegments.size();i++) { h = mCurveSegments[i].getStart(); mCurveSegments[i].setStart(mCurveSegments[i].getEnd()); mCurveSegments[i].setEnd(h); if (mCurveSegments[i].isBezier()) { h = mCurveSegments[i].getBase1(); mCurveSegments[i].setBase1(mCurveSegments[i].getBase2()); mCurveSegments[i].setBase2(h); } } // now invert order of segments reverse(mCurveSegments.begin(), mCurveSegments.end()); if (mHasArrow) {} //???} <commit_msg>small fix<commit_after>// Begin CVS Header // $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/layoutUI/CGraphCurve.cpp,v $ // $Revision: 1.9 $ // $Name: $ // $Author: ssahle $ // $Date: 2008/01/15 15:15:28 $ // End CVS Header // Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. // Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. #include "copasi.h" #include "CGraphCurve.h" CGraphCurve::CGraphCurve() : CLCurve() { mHasArrow = false; } CGraphCurve::CGraphCurve(const CLCurve & c) : CLCurve(c) { mHasArrow = false; } CGraphCurve::CGraphCurve(const CGraphCurve & c) : CLCurve(c) { mHasArrow = c.mHasArrow; mArrow = c.mArrow; mRole = c.mRole; } void CGraphCurve::scale (const double & scaleFactor) { unsigned int i; // scale all segments for (i = 0;i < mCurveSegments.size();i++) { mCurveSegments[i].scale(scaleFactor); } if (mHasArrow) mArrow.scale(scaleFactor); } void CGraphCurve::invertOrderOfPoints() { std::cout << " invertOrderOfPoints for " << mCurveSegments.size() << " segments" << std::endl; unsigned int i; // invert order of points in each segment CLPoint h; // puffer variable for (i = 0;i < mCurveSegments.size();i++) { h = mCurveSegments[i].getStart(); mCurveSegments[i].setStart(mCurveSegments[i].getEnd()); mCurveSegments[i].setEnd(h); if (mCurveSegments[i].isBezier()) { h = mCurveSegments[i].getBase1(); mCurveSegments[i].setBase1(mCurveSegments[i].getBase2()); mCurveSegments[i].setBase2(h); } } // now invert order of segments reverse(mCurveSegments.begin(), mCurveSegments.end()); if (mHasArrow) {} //???} <|endoftext|>
<commit_before>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/plot/Attic/CPlotSpecVector.cpp,v $ $Revision: 1.10 $ $Name: $ $Author: ssahle $ $Date: 2004/05/27 11:59:10 $ End CVS Header */ #include "copasi.h" #include "CPlotSpecVector.h" #include "report/CKeyFactory.h" #include "report/CCopasiObjectReference.h" #include "model/CModel.h" //#include "CPlotSpec.h" #include "plotwindow.h" #include "utilities/CGlobals.h" CPlotSpecVector::CPlotSpecVector(const std::string & name, const CCopasiContainer * pParent): CCopasiVectorN< CPlotSpec >(name, pParent), mKey(GlobalKeys.add("CPlotSpecVector", this)), pSource(NULL), //ncols(0), mReport(), mRepDef(), inputFlag(NO_INPUT) { mReport.setReportDefinition(&mRepDef); //createDebugReport(); //for debugging only } CPlotSpecVector::~CPlotSpecVector() { cleanup(); } void CPlotSpecVector::cleanup() { GlobalKeys.remove(mKey); } const std::string& CPlotSpecVector::getKey() { return mKey; } CPlotSpec* CPlotSpecVector::createPlotSpec(const std::string & name) { unsigned C_INT32 i; for (i = 0; i < size(); i++) if ((*this)[i]->getObjectName() == name) return NULL; // duplicate name CPlotSpec* pNewPlotSpec = new CPlotSpec(name, this); pNewPlotSpec->setObjectName(name); add(pNewPlotSpec); return pNewPlotSpec; } bool CPlotSpecVector::removePlotSpec(const std::string & key) { CPlotSpec* pPl = dynamic_cast<CPlotSpec*>(GlobalKeys.get(key)); unsigned C_INT32 index = this->CCopasiVector<CPlotSpec>::getIndex(pPl); if (index == C_INVALID_INDEX) return false; this->CCopasiVector<CPlotSpec>::remove(index); //pdelete(pPl); //TODO: propably a memory leak, may be not return true; } bool CPlotSpecVector::initPlottingFromObjects() { // createDebugReport(); //for debugging only inputFlag = NO_INPUT; if (size() == 0) { std::cout << "plot: not plots defined" << std::endl; return false; } if (!compile()) //create mObjects; { std::cout << "plot: compile not successful" << std::endl; return false; } //ncols = mObjectNames.size(); if (mObjectNames.size() <= 0) { std::cout << "plot: number of objects <=0" << std::endl; return false; } data.resize(mObjectNames.size()); inputFlag = FROM_OBJECTS; return initAllPlots(); //return success; } bool CPlotSpecVector::sendDataToAllPlots() { std::vector<PlotWindow*>::const_iterator it; for (it = windows.begin(); it != windows.end(); ++it) { (*it)->takeData(data); } return true; } bool CPlotSpecVector::updateAllPlots() { std::vector<PlotWindow*>::const_iterator it; for (it = windows.begin(); it != windows.end(); ++it) { (*it)->updatePlot(); } return true; } bool CPlotSpecVector::initAllPlots() { //step through the vector of specifications and create the plot windows PlotWindow* pTemp; const_iterator it; std::vector<PlotWindow*>::iterator winit; windows.resize(size()); for (it = begin(), winit = windows.begin(); it != end(); ++it, ++winit) { if (*winit) {(*winit)->initFromSpec(*it);} else { pTemp = new PlotWindow(*it); *winit = pTemp; //pTemp->resize(600, 360); } (*winit)->show(); } return true; } bool CPlotSpecVector::doPlotting() { bool success = true; if (inputFlag == FROM_OBJECTS) { unsigned C_INT32 i = 0; std::vector<CCopasiObject*>::const_iterator it = mObjects.begin(); for (; it != mObjects.end(); ++it, ++i) { data[i] = *(C_FLOAT64*)(((CCopasiObjectReference<C_FLOAT64>*)(*it))->getReference()); //std::cout << "debug1: " << *(C_FLOAT64*)(((CCopasiObjectReference<C_FLOAT64>*)(*it))->getReference())<< std::endl; //std::cout << "debug2: " << data[i] << std::endl; //(*it)->print(&std::cout); } sendDataToAllPlots(); } else if (inputFlag == FROM_STREAM) { /*pSource->seekg(position); C_INT32 i; while (!(pSource->eof())) { for (i = 0; i < ncols; ++i) { if (!(*pSource >> data[i])) break; } if (i == ncols) //line was read completely sendDataToAllPlots(); }; position = pSource->tellg();*/ } else { std::cout << "doPlotting: no input method" << std::endl; return false; } //updateAllPlots(); return success; } bool CPlotSpecVector::finishPlotting() { return updateAllPlots(); } C_INT32 CPlotSpecVector::getIndexFromCN(const CCopasiObjectName & name) { //first look up the name in the vector std::vector<CCopasiObjectName>::const_iterator it; for (it = mObjectNames.begin(); it != mObjectNames.end(); ++it) if (*it == name) break; if (it != mObjectNames.end()) return (it - mObjectNames.begin()); //the name is not yet in the list mObjectNames.push_back(name); return mObjectNames.size() - 1; } bool CPlotSpecVector::compile() { //construct the mObjectNames and the indices CCopasiVectorN<CPlotSpec>::iterator psit; for (psit = begin(); psit != end(); ++psit) (*psit)->compile(this); bool success = true; mObjects.clear(); std::vector< CCopasiContainer * > ListOfContainer; CCopasiObject* pSelected; std::vector<CCopasiObjectName>::const_iterator it = mObjectNames.begin(); for (; it != mObjectNames.end(); ++it) { std::cout << "CPlotSpecVector::compile " << *it << std::endl; pSelected = CCopasiContainer::ObjectFromName(ListOfContainer, *it); if (!pSelected) { std::cout << "Object not found!" << std::endl; return false; } //add(pSelected); //what's this? //TODO check hasValue() std::cout << " compile: " << pSelected->getObjectName() << std::endl; mObjects.push_back(pSelected); } return success; } /*void CPlotSpecVector::createDebugReport() { std::cout << "Create Debug Report for Plot" << std::endl; mObjectNames.clear(); //std::cout << Copasi->pModel->getObject(CCopasiObjectName("Reference=Time"))->getCN() << std::endl; CCopasiObjectName name = Copasi->pModel->getObject(CCopasiObjectName("Reference=Time"))->getCN(); std::cout << name << std::endl; mObjectNames.push_back(name); name = Copasi->pModel->getMetabolites()[0]->getObject(CCopasiObjectName("Reference=Concentration"))->getCN(); std::cout << name << std::endl; mObjectNames.push_back(name); //mRepDef.getBodyAddr()->clear(); //mRepDef.getBodyAddr()->push_bMck(name); //mReport.compile(); }*/ <commit_msg>removed debugging output<commit_after>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/plot/Attic/CPlotSpecVector.cpp,v $ $Revision: 1.11 $ $Name: $ $Author: ssahle $ $Date: 2004/06/23 16:13:17 $ End CVS Header */ #include "copasi.h" #include "CPlotSpecVector.h" #include "report/CKeyFactory.h" #include "report/CCopasiObjectReference.h" #include "model/CModel.h" //#include "CPlotSpec.h" #include "plotwindow.h" #include "utilities/CGlobals.h" CPlotSpecVector::CPlotSpecVector(const std::string & name, const CCopasiContainer * pParent): CCopasiVectorN< CPlotSpec >(name, pParent), mKey(GlobalKeys.add("CPlotSpecVector", this)), pSource(NULL), //ncols(0), mReport(), mRepDef(), inputFlag(NO_INPUT) { mReport.setReportDefinition(&mRepDef); //createDebugReport(); //for debugging only } CPlotSpecVector::~CPlotSpecVector() { cleanup(); } void CPlotSpecVector::cleanup() { GlobalKeys.remove(mKey); } const std::string& CPlotSpecVector::getKey() { return mKey; } CPlotSpec* CPlotSpecVector::createPlotSpec(const std::string & name) { unsigned C_INT32 i; for (i = 0; i < size(); i++) if ((*this)[i]->getObjectName() == name) return NULL; // duplicate name CPlotSpec* pNewPlotSpec = new CPlotSpec(name, this); pNewPlotSpec->setObjectName(name); add(pNewPlotSpec); return pNewPlotSpec; } bool CPlotSpecVector::removePlotSpec(const std::string & key) { CPlotSpec* pPl = dynamic_cast<CPlotSpec*>(GlobalKeys.get(key)); unsigned C_INT32 index = this->CCopasiVector<CPlotSpec>::getIndex(pPl); if (index == C_INVALID_INDEX) return false; this->CCopasiVector<CPlotSpec>::remove(index); //pdelete(pPl); //TODO: propably a memory leak, may be not return true; } bool CPlotSpecVector::initPlottingFromObjects() { // createDebugReport(); //for debugging only inputFlag = NO_INPUT; if (size() == 0) { std::cout << "plot: not plots defined" << std::endl; return false; } if (!compile()) //create mObjects; { std::cout << "plot: compile not successful" << std::endl; return false; } //ncols = mObjectNames.size(); if (mObjectNames.size() <= 0) { std::cout << "plot: number of objects <=0" << std::endl; return false; } data.resize(mObjectNames.size()); inputFlag = FROM_OBJECTS; return initAllPlots(); //return success; } bool CPlotSpecVector::sendDataToAllPlots() { std::vector<PlotWindow*>::const_iterator it; for (it = windows.begin(); it != windows.end(); ++it) { (*it)->takeData(data); } return true; } bool CPlotSpecVector::updateAllPlots() { std::vector<PlotWindow*>::const_iterator it; for (it = windows.begin(); it != windows.end(); ++it) { (*it)->updatePlot(); } return true; } bool CPlotSpecVector::initAllPlots() { //step through the vector of specifications and create the plot windows PlotWindow* pTemp; const_iterator it; std::vector<PlotWindow*>::iterator winit; windows.resize(size()); for (it = begin(), winit = windows.begin(); it != end(); ++it, ++winit) { if (*winit) {(*winit)->initFromSpec(*it);} else { pTemp = new PlotWindow(*it); *winit = pTemp; //pTemp->resize(600, 360); } (*winit)->show(); } return true; } bool CPlotSpecVector::doPlotting() { bool success = true; if (inputFlag == FROM_OBJECTS) { unsigned C_INT32 i = 0; std::vector<CCopasiObject*>::const_iterator it = mObjects.begin(); for (; it != mObjects.end(); ++it, ++i) { data[i] = *(C_FLOAT64*)(((CCopasiObjectReference<C_FLOAT64>*)(*it))->getReference()); //std::cout << "debug1: " << *(C_FLOAT64*)(((CCopasiObjectReference<C_FLOAT64>*)(*it))->getReference())<< std::endl; //std::cout << "debug2: " << data[i] << std::endl; //(*it)->print(&std::cout); } sendDataToAllPlots(); } else if (inputFlag == FROM_STREAM) { /*pSource->seekg(position); C_INT32 i; while (!(pSource->eof())) { for (i = 0; i < ncols; ++i) { if (!(*pSource >> data[i])) break; } if (i == ncols) //line was read completely sendDataToAllPlots(); }; position = pSource->tellg();*/ } else { std::cout << "doPlotting: no input method" << std::endl; return false; } //updateAllPlots(); return success; } bool CPlotSpecVector::finishPlotting() { return updateAllPlots(); } C_INT32 CPlotSpecVector::getIndexFromCN(const CCopasiObjectName & name) { //first look up the name in the vector std::vector<CCopasiObjectName>::const_iterator it; for (it = mObjectNames.begin(); it != mObjectNames.end(); ++it) if (*it == name) break; if (it != mObjectNames.end()) return (it - mObjectNames.begin()); //the name is not yet in the list mObjectNames.push_back(name); return mObjectNames.size() - 1; } bool CPlotSpecVector::compile() { //construct the mObjectNames and the indices CCopasiVectorN<CPlotSpec>::iterator psit; for (psit = begin(); psit != end(); ++psit) (*psit)->compile(this); bool success = true; mObjects.clear(); std::vector< CCopasiContainer * > ListOfContainer; CCopasiObject* pSelected; std::vector<CCopasiObjectName>::const_iterator it = mObjectNames.begin(); for (; it != mObjectNames.end(); ++it) { //std::cout << "CPlotSpecVector::compile " << *it << std::endl; pSelected = CCopasiContainer::ObjectFromName(ListOfContainer, *it); if (!pSelected) { //std::cout << "Object not found!" << std::endl; return false; } //add(pSelected); //what's this? //TODO check hasValue() //std::cout << " compile: " << pSelected->getObjectName() << std::endl; mObjects.push_back(pSelected); } return success; } /*void CPlotSpecVector::createDebugReport() { std::cout << "Create Debug Report for Plot" << std::endl; mObjectNames.clear(); //std::cout << Copasi->pModel->getObject(CCopasiObjectName("Reference=Time"))->getCN() << std::endl; CCopasiObjectName name = Copasi->pModel->getObject(CCopasiObjectName("Reference=Time"))->getCN(); std::cout << name << std::endl; mObjectNames.push_back(name); name = Copasi->pModel->getMetabolites()[0]->getObject(CCopasiObjectName("Reference=Concentration"))->getCN(); std::cout << name << std::endl; mObjectNames.push_back(name); //mRepDef.getBodyAddr()->clear(); //mRepDef.getBodyAddr()->push_bMck(name); //mReport.compile(); }*/ <|endoftext|>
<commit_before>/* * Copyright (c) 2011-2012 by Michael Berlin, Zuse Institute Berlin * * Licensed under the BSD License, see LICENSE file for details. */ #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <boost/scoped_ptr.hpp> #include <CbFS.h> #include <vector> #include "cbfs/cbfs_adapter.h" #include "cbfs/cbfs_options.h" #include "libxtreemfs/client.h" #include "libxtreemfs/file_handle.h" #include "libxtreemfs/helper.h" #include "libxtreemfs/options.h" #include "libxtreemfs/volume.h" #include "libxtreemfs/xtreemfs_exception.h" #include "pbrpc/RPC.pb.h" // xtreemfs::pbrpc::UserCredentials #include "util/logging.h" #include "xtreemfs/MRC.pb.h" // xtreemfs::pbrpc::Stat #ifdef _MSC_VER // Disable "warning C4996: 'strdup': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _strdup. // NOLINT #pragma warning(push) #pragma warning(disable:4996) #endif // _MSC_VER using namespace std; using namespace xtreemfs; using namespace xtreemfs::util; int __cdecl wmain(ULONG argc, PWCHAR argv[]) { vector<char*> argv_utf8; argv_utf8.reserve(argc); for (ULONG i = 0; i < argc; i++) { argv_utf8.push_back(strdup(ConvertWindowsToUTF8(argv[i]).c_str())); } CbFSOptions cbfs_options; bool invalid_commandline_parameters = false; try { cbfs_options.ParseCommandLine(argv_utf8.size(), &argv_utf8[0]); } catch(const xtreemfs::XtreemFSException& e) { cout << "Invalid parameters found, error: " << e.what() << endl << endl; invalid_commandline_parameters = true; } for (size_t i = 0; i < argv_utf8.size(); i++) { delete[] argv_utf8[i]; } // Display help if needed. if (cbfs_options.empty_arguments_list || invalid_commandline_parameters) { cout << cbfs_options.ShowCommandLineUsage() << endl; return 1; } if (cbfs_options.show_help) { cout << cbfs_options.ShowCommandLineHelp() << endl; return 1; } // Show only the version. if (cbfs_options.show_version) { cout << cbfs_options.ShowVersion("mount.xtreemfs") << endl; return 1; } boost::scoped_ptr<CbFSAdapter> cbfs_adapter(new CbFSAdapter(&cbfs_options)); try { cbfs_adapter->Start(); cout << "Volume successfully mounted. Eject it in Windows to un-mount it." << endl; cbfs_adapter->WaitForEjection(); cbfs_adapter->StopWithoutUnmount(); if (Logging::log->loggingActive(LEVEL_DEBUG)) { Logging::log->getLog(LEVEL_DEBUG) << "Did shutdown the XtreemFS client." << endl; } } catch (const XtreemFSException& e) { Logging::log->getLog(LEVEL_ERROR) << "Failed to mount the volume. Error: " << e.what() << endl; } // libxtreemfs shuts down logger. return 0; } <commit_msg>client: cbfs/mount.xtreemfs.cpp: Fixed mixed new lines and changed to Unix only.<commit_after>/* * Copyright (c) 2011-2012 by Michael Berlin, Zuse Institute Berlin * * Licensed under the BSD License, see LICENSE file for details. */ #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <boost/scoped_ptr.hpp> #include <CbFS.h> #include <vector> #include "cbfs/cbfs_adapter.h" #include "cbfs/cbfs_options.h" #include "libxtreemfs/client.h" #include "libxtreemfs/file_handle.h" #include "libxtreemfs/helper.h" #include "libxtreemfs/options.h" #include "libxtreemfs/volume.h" #include "libxtreemfs/xtreemfs_exception.h" #include "pbrpc/RPC.pb.h" // xtreemfs::pbrpc::UserCredentials #include "util/logging.h" #include "xtreemfs/MRC.pb.h" // xtreemfs::pbrpc::Stat #ifdef _MSC_VER // Disable "warning C4996: 'strdup': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _strdup. // NOLINT #pragma warning(push) #pragma warning(disable:4996) #endif // _MSC_VER using namespace std; using namespace xtreemfs; using namespace xtreemfs::util; int __cdecl wmain(ULONG argc, PWCHAR argv[]) { vector<char*> argv_utf8; argv_utf8.reserve(argc); for (ULONG i = 0; i < argc; i++) { argv_utf8.push_back(strdup(ConvertWindowsToUTF8(argv[i]).c_str())); } CbFSOptions cbfs_options; bool invalid_commandline_parameters = false; try { cbfs_options.ParseCommandLine(argv_utf8.size(), &argv_utf8[0]); } catch(const xtreemfs::XtreemFSException& e) { cout << "Invalid parameters found, error: " << e.what() << endl << endl; invalid_commandline_parameters = true; } for (size_t i = 0; i < argv_utf8.size(); i++) { delete[] argv_utf8[i]; } // Display help if needed. if (cbfs_options.empty_arguments_list || invalid_commandline_parameters) { cout << cbfs_options.ShowCommandLineUsage() << endl; return 1; } if (cbfs_options.show_help) { cout << cbfs_options.ShowCommandLineHelp() << endl; return 1; } // Show only the version. if (cbfs_options.show_version) { cout << cbfs_options.ShowVersion("mount.xtreemfs") << endl; return 1; } boost::scoped_ptr<CbFSAdapter> cbfs_adapter(new CbFSAdapter(&cbfs_options)); try { cbfs_adapter->Start(); cout << "Volume successfully mounted. Eject it in Windows to un-mount it." << endl; cbfs_adapter->WaitForEjection(); cbfs_adapter->StopWithoutUnmount(); if (Logging::log->loggingActive(LEVEL_DEBUG)) { Logging::log->getLog(LEVEL_DEBUG) << "Did shutdown the XtreemFS client." << endl; } } catch (const XtreemFSException& e) { Logging::log->getLog(LEVEL_ERROR) << "Failed to mount the volume. Error: " << e.what() << endl; } // libxtreemfs shuts down logger. return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <unistd.h> #include <netinet/tcp.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <netdb.h> #include <pthread.h> #include <errno.h> #include <json/writer.h> #include <GridsDefine.h> #include <grids/GridsProtocol.h> namespace Grids { void *runEventLoopThreadEntryPoint(void *arg) { Protocol *gp = (Protocol *)arg; gp->runEventLoop(); } /* void *dispatchEventEntryPoint(void *arg) { Protocol *gp = (Protocol *)arg; gp->dispatchEvent(); } */ Protocol::Protocol() { sock = 0; finished = 0; pthread_mutex_init(&finishedMutex, NULL); eventLoopThread = (pthread_t)NULL; } bool Protocol::connectToNode(const char *address) { // look up host struct hostent *hp; struct sockaddr_in addr; int on = 1; if ((hp = gethostbyname(address)) == NULL) { herror("gethostbyname"); return 0; } bcopy(hp->h_addr, &addr.sin_addr, hp->h_length); addr.sin_port = htons(GRIDS_PORT); addr.sin_family = AF_INET; sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (const char *)&on, sizeof(int)); if (connect(sock, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)) == -1) { return 0; } // hooray we are connnected! initialize protocol sendProtocolInitiationString(); return 1; } void Protocol::sendProtocolInitiationString() { protocolWrite("==Grids/1.0/JSON"); } int Protocol::protocolWrite(const char *str) { uint32_t len = strlen(str); uint32_t len_net = htonl(len); unsigned int outstr_len = len + 4; char *outstr = (char *)malloc(outstr_len); memcpy(outstr, &len_net, 4); memcpy((outstr + 4), str, len); return write(sock, outstr, outstr_len); } void Protocol::closeConnection() { ::shutdown(sock, SHUT_RDWR); close(sock); } std::string Protocol::stringifyMap(gridsmap_t *m) { Json::FastWriter *writer = new Json::FastWriter(); Json::Value root = mapToJsonValue(m); return writer->write(root); } void Protocol::sendRequest(std::string evt) { sendRequest(evt, NULL); } void Protocol::sendRequest(std::string evt, gridsmap_t *args) { if (evt.empty()) return; if (args == NULL) { args = new gridsmap_t(); } const static std::string methodkey = "_method"; (*args)[methodkey] = evt; std::string msg = stringifyMap(args); protocolWrite(msg.c_str()); } Json::Value Protocol::mapToJsonValue(gridsmap_t *m) { giterator mapIterator; Json::Value jsonVal; for(mapIterator = m->begin(); mapIterator != m->end(); mapIterator++) { gridskey_t key = mapIterator->first; gridsval_t val = mapIterator->second; jsonVal[key] = val; } return jsonVal; } void Protocol::setEventCallback(gevent_callback_t cb) { eventCallback = cb; } void Protocol::runEventLoop() { int bytesRead; uint32_t incomingLength; char *buf; /* buf = (char*)malloc(100000); read(sock, buf, sizeof(buf)); read(sock, buf, sizeof(buf)); std::cout << "buf: " << buf; */ while (! finished && sock) { // read in 4 byte length of message bytesRead = read(sock, &incomingLength, 4); incomingLength = ntohl(incomingLength); std::cout << "bytesRead: " << bytesRead << " incoming: " << incomingLength << "\n"; if (bytesRead == -1) { // uh oh, socket read error std::cerr << "Socket read error: " << bytesRead << "\n"; break; } if (bytesRead != 4) { // wtf? try reading again continue; } if (incomingLength > 1024 * 1024 * 1024) { // not going to read in more than a gig, f that std::cerr << "Got incoming message size: " << incomingLength << ". Skipping\n"; continue; } // ok time to read some shit in buf = (char *)malloc(incomingLength); std::cout << "incoming: " << incomingLength << "\n"; uint32_t bytesRemaining = incomingLength; char *bufIncoming = buf; do { bytesRead = read(sock, bufIncoming, bytesRemaining); if (bytesRead > 0) { bytesRemaining -= bytesRead; bufIncoming += bytesRead; } std::cout << "read: " << bytesRead << "\n"; } while ((bytesRead > 0 || bytesRead != EAGAIN) && bytesRemaining); buf = bufIncoming; if (bytesRead == -1) { // o snap read error std::cerr << "Socket read error: " << bytesRead << "\n"; free(buf); break; } if (bytesRead = 0) { // not chill std::cerr << "Didn't read any data when expecting message of " << incomingLength << " bytes\n"; free(buf); continue; } if (bytesRead != incomingLength) { std::cerr << "Only read " << bytesRead << " bytes when expecting message of " << incomingLength << " bytes\n"; free(buf); continue; } std::cout << "Got message \"" << buf << "\"\n"; free(buf); } std::cout << "ended read thread\n"; } int Protocol::runEventLoopThreaded() { return pthread_create(&eventLoopThread, NULL, runEventLoopThreadEntryPoint, this); } void Protocol::stopEventLoopThread() { pthread_mutex_lock(&finishedMutex); finished = 1; pthread_mutex_unlock(&finishedMutex); if (eventLoopThread) pthread_join(eventLoopThread, NULL); } } <commit_msg>working reading from socket<commit_after>#include <iostream> #include <unistd.h> #include <netinet/tcp.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <netdb.h> #include <pthread.h> #include <errno.h> #include <json/writer.h> #include <GridsDefine.h> #include <grids/GridsProtocol.h> namespace Grids { void *runEventLoopThreadEntryPoint(void *arg) { Protocol *gp = (Protocol *)arg; gp->runEventLoop(); } /* void *dispatchEventEntryPoint(void *arg) { Protocol *gp = (Protocol *)arg; gp->dispatchEvent(); } */ Protocol::Protocol() { sock = 0; finished = 0; pthread_mutex_init(&finishedMutex, NULL); eventLoopThread = (pthread_t)NULL; } bool Protocol::connectToNode(const char *address) { // look up host struct hostent *hp; struct sockaddr_in addr; int on = 1; if ((hp = gethostbyname(address)) == NULL) { herror("gethostbyname"); return 0; } bcopy(hp->h_addr, &addr.sin_addr, hp->h_length); addr.sin_port = htons(GRIDS_PORT); addr.sin_family = AF_INET; sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (const char *)&on, sizeof(int)); if (connect(sock, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)) == -1) { return 0; } // hooray we are connnected! initialize protocol sendProtocolInitiationString(); return 1; } void Protocol::sendProtocolInitiationString() { protocolWrite("==Grids/1.0/JSON"); } int Protocol::protocolWrite(const char *str) { uint32_t len = strlen(str); uint32_t len_net = htonl(len); unsigned int outstr_len = len + 4; char *outstr = (char *)malloc(outstr_len); memcpy(outstr, &len_net, 4); memcpy((outstr + 4), str, len); return write(sock, outstr, outstr_len); } void Protocol::closeConnection() { ::shutdown(sock, SHUT_RDWR); close(sock); } std::string Protocol::stringifyMap(gridsmap_t *m) { Json::FastWriter *writer = new Json::FastWriter(); Json::Value root = mapToJsonValue(m); return writer->write(root); } void Protocol::sendRequest(std::string evt) { sendRequest(evt, NULL); } void Protocol::sendRequest(std::string evt, gridsmap_t *args) { if (evt.empty()) return; if (args == NULL) { args = new gridsmap_t(); } const static std::string methodkey = "_method"; (*args)[methodkey] = evt; std::string msg = stringifyMap(args); protocolWrite(msg.c_str()); } Json::Value Protocol::mapToJsonValue(gridsmap_t *m) { giterator mapIterator; Json::Value jsonVal; for(mapIterator = m->begin(); mapIterator != m->end(); mapIterator++) { gridskey_t key = mapIterator->first; gridsval_t val = mapIterator->second; jsonVal[key] = val; } return jsonVal; } void Protocol::setEventCallback(gevent_callback_t cb) { eventCallback = cb; } void Protocol::runEventLoop() { int bytesRead; uint32_t incomingLength; char *buf; char *bufIncoming; /* buf = (char*)malloc(100000); read(sock, buf, sizeof(buf)); read(sock, buf, sizeof(buf)); std::cout << "buf: " << buf; */ while (! finished && sock) { // read in 4 byte length of message bytesRead = read(sock, &incomingLength, 4); incomingLength = ntohl(incomingLength); //std::cout << "bytesRead: " << bytesRead << " incoming: " << incomingLength << "\n"; if (bytesRead == -1) { // uh oh, socket read error std::cerr << "Socket read error: " << bytesRead << "\n"; break; } if (bytesRead != 4) { // wtf? try reading again continue; } if (incomingLength > 1024 * 1024 * 1024) { // not going to read in more than a gig, f that std::cerr << "Got incoming message size: " << incomingLength << ". Skipping\n"; continue; } // ok time to read some shit in buf = (char *)malloc(incomingLength); //std::cout << "incoming: " << incomingLength << "\n"; uint32_t bytesRemaining = incomingLength; bufIncoming = buf; do { bytesRead = read(sock, bufIncoming, bytesRemaining); if (bytesRead > 0) { bytesRemaining -= bytesRead; bufIncoming += bytesRead; } //std::cout << "read: " << bytesRead << " remaining: " << bytesRemaining << "\n"; } while ((bytesRead > 0 || bytesRead != EAGAIN) && bytesRemaining); buf[incomingLength] = '\0'; if (bytesRead == -1) { // o snap read error std::cerr << "Socket read error: " << bytesRead << "\n"; free(buf); break; } if (bytesRead == 0) { // not chill std::cerr << "Didn't read any data when expecting message of " << incomingLength << " bytes\n"; free(buf); continue; } if (bytesRead != incomingLength) { std::cerr << "Only read " << bytesRead << " bytes when expecting message of " << incomingLength << " bytes\n"; free(buf); continue; } std::cout << "Got message \"" << buf << "\"\n"; free(buf); } std::cout << "ended read thread\n"; } int Protocol::runEventLoopThreaded() { return pthread_create(&eventLoopThread, NULL, runEventLoopThreadEntryPoint, this); } void Protocol::stopEventLoopThread() { pthread_mutex_lock(&finishedMutex); finished = 1; pthread_mutex_unlock(&finishedMutex); if (eventLoopThread) pthread_join(eventLoopThread, NULL); } } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * Version: MPL 1.1 / GPLv3+ / LGPLv3+ * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License or as specified alternatively below. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Major Contributor(s): * Copyright (C) 2012 Red Hat, Inc., Caolán McNamara <caolanm@redhat.com> * (initial developer) * * All Rights Reserved. * * For minor contributions see the git repository. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 3 or later (the "GPLv3+"), or * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"), * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable * instead of those above. */ #include <officecfg/Office/Common.hxx> #include <osl/file.hxx> #include <osl/security.hxx> #include <svtools/stdctrl.hxx> #include "svtools/treelistentry.hxx" #include <unotools/securityoptions.hxx> #include <cuires.hrc> #include "certpath.hxx" #include "certpath.hrc" #include "dialmgr.hxx" #include <com/sun/star/mozilla/XMozillaBootstrap.hpp> #include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp> #include <com/sun/star/ui/dialogs/FolderPicker.hpp> #include <comphelper/processfactory.hxx> using namespace ::com::sun::star; CertPathDialog::CertPathDialog( Window* pParent ) : ModalDialog( pParent, CUI_RES( RID_SVXDLG_CERTPATH ) ) , m_aCertPathFL ( this, CUI_RES( FL_CERTPATH ) ) , m_aCertPathFT ( this, CUI_RES( FT_CERTPATH ) ) , m_aCertPathListContainer( this, CUI_RES( LB_CERTPATH ) ) , m_aCertPathList( m_aCertPathListContainer ) , m_aAddBtn ( this, CUI_RES( PB_ADD ) ) , m_aButtonsFL ( this, CUI_RES( FL_BUTTONS ) ) , m_aOKBtn ( this, CUI_RES( PB_OK ) ) , m_aCancelBtn ( this, CUI_RES( PB_CANCEL ) ) , m_aHelpBtn ( this, CUI_RES( PB_HELP ) ) , m_sAddDialogText(CUI_RESSTR(STR_ADDDLGTEXT)) , m_sManual(CUI_RESSTR(STR_MANUAL)) { static long aStaticTabs[]= { 3, 0, 15, 75 }; m_aCertPathList.SvxSimpleTable::SetTabs( aStaticTabs ); rtl::OUString sProfile(CUI_RESSTR(STR_PROFILE)); rtl::OUString sDirectory(CUI_RESSTR(STR_DIRECTORY)); rtl::OUStringBuffer sHeader; sHeader.append('\t').append(sProfile).append('\t').append(sDirectory); m_aCertPathList.InsertHeaderEntry( sHeader.makeStringAndClear(), HEADERBAR_APPEND, HIB_LEFT ); m_aCertPathList.SetCheckButtonHdl( LINK( this, CertPathDialog, CheckHdl_Impl ) ); m_aAddBtn.SetClickHdl( LINK( this, CertPathDialog, AddHdl_Impl ) ); m_aOKBtn.SetClickHdl( LINK( this, CertPathDialog, OKHdl_Impl ) ); FreeResource(); try { mozilla::MozillaProductType productTypes[3] = { mozilla::MozillaProductType_Thunderbird, mozilla::MozillaProductType_Firefox, mozilla::MozillaProductType_Mozilla }; const char* productNames[3] = { "thunderbird", "firefox", "mozilla" }; sal_Int32 nProduct = SAL_N_ELEMENTS(productTypes); uno::Reference<uno::XInterface> xInstance = comphelper::getProcessServiceFactory()->createInstance( "com.sun.star.mozilla.MozillaBootstrap"); uno::Reference<mozilla::XMozillaBootstrap> xMozillaBootstrap(xInstance, uno::UNO_QUERY_THROW); for (sal_Int32 i = 0; i < nProduct; ++i) { ::rtl::OUString profile = xMozillaBootstrap->getDefaultProfile(productTypes[i]); if (!profile.isEmpty()) { ::rtl::OUString sProfilePath = xMozillaBootstrap->getProfilePath( productTypes[i], profile ); rtl::OUStringBuffer sEntry; sEntry.append('\t').appendAscii(productNames[i]).append(':').append(profile).append('\t').append(sProfilePath); SvTreeListEntry *pEntry = m_aCertPathList.InsertEntry(sEntry.makeStringAndClear()); rtl::OUString* pCertPath = new rtl::OUString(sProfilePath); pEntry->SetUserData(pCertPath); } } } catch (const uno::Exception&) { } SvTreeListEntry *pEntry = m_aCertPathList.GetEntry(0); if (pEntry) { m_aCertPathList.SetCheckButtonState(pEntry, SV_BUTTON_CHECKED); HandleCheckEntry(pEntry); } try { rtl::OUString sUserSetCertPath = officecfg::Office::Common::Security::Scripting::CertDir::get().get_value_or(rtl::OUString()); if (!sUserSetCertPath.isEmpty()) AddCertPath(m_sManual, sUserSetCertPath); } catch (const uno::Exception &e) { SAL_WARN("cui.options", "CertPathDialog::CertPathDialog(): caught exception" << e.Message); } const char* pEnv = getenv("MOZILLA_CERTIFICATE_FOLDER"); if (pEnv) AddCertPath("$MOZILLA_CERTIFICATE_FOLDER", rtl::OUString(pEnv, strlen(pEnv), osl_getThreadTextEncoding())); } IMPL_LINK_NOARG(CertPathDialog, OKHdl_Impl) { fprintf(stderr, "dir is %s\n", rtl::OUStringToOString(getDirectory(), RTL_TEXTENCODING_UTF8).getStr()); try { boost::shared_ptr< comphelper::ConfigurationChanges > batch( comphelper::ConfigurationChanges::create()); officecfg::Office::Common::Security::Scripting::CertDir::set( getDirectory(), batch); batch->commit(); } catch (const uno::Exception &e) { SAL_WARN("cui.options", "CertPathDialog::OKHdl_Impl(): caught exception" << e.Message); } EndDialog(true); return 0; } rtl::OUString CertPathDialog::getDirectory() const { SvTreeListEntry* pEntry = m_aCertPathList.FirstSelected(); void* pCertPath = pEntry ? pEntry->GetUserData() : NULL; return pCertPath ? *static_cast<rtl::OUString*>(pCertPath) : rtl::OUString(); } CertPathDialog::~CertPathDialog() { SvTreeListEntry* pEntry = m_aCertPathList.First(); while (pEntry) { rtl::OUString* pCertPath = static_cast<rtl::OUString*>(pEntry->GetUserData()); delete pCertPath; pEntry = m_aCertPathList.Next( pEntry ); } } IMPL_LINK( CertPathDialog, CheckHdl_Impl, SvxSimpleTable *, pList ) { SvTreeListEntry* pEntry = pList ? m_aCertPathList.GetEntry(m_aCertPathList.GetCurMousePoint()) : m_aCertPathList.FirstSelected(); if (pEntry) m_aCertPathList.HandleEntryChecked(pEntry); return 0; } void CertPathDialog::HandleCheckEntry( SvTreeListEntry* _pEntry ) { m_aCertPathList.Select( _pEntry, true ); SvButtonState eState = m_aCertPathList.GetCheckButtonState( _pEntry ); if (SV_BUTTON_CHECKED == eState) { // uncheck the other entries SvTreeListEntry* pEntry = m_aCertPathList.First(); while (pEntry) { if (pEntry != _pEntry) m_aCertPathList.SetCheckButtonState(pEntry, SV_BUTTON_UNCHECKED); pEntry = m_aCertPathList.Next(pEntry); } } else m_aCertPathList.SetCheckButtonState(_pEntry, SV_BUTTON_CHECKED); } void CertPathDialog::AddCertPath(const rtl::OUString &rProfile, const rtl::OUString &rPath) { SvTreeListEntry* pEntry = m_aCertPathList.First(); while (pEntry) { rtl::OUString* pCertPath = static_cast<rtl::OUString*>(pEntry->GetUserData()); //already exists, just select the original one if (pCertPath->equals(rPath)) { m_aCertPathList.SetCheckButtonState(pEntry, SV_BUTTON_CHECKED); HandleCheckEntry(pEntry); return; } pEntry = m_aCertPathList.Next(pEntry); } rtl::OUStringBuffer sEntry; sEntry.append('\t').append(rProfile).append('\t').append(rPath); pEntry = m_aCertPathList.InsertEntry(sEntry.makeStringAndClear()); rtl::OUString* pCertPath = new rtl::OUString(rPath); pEntry->SetUserData(pCertPath); m_aCertPathList.SetCheckButtonState(pEntry, SV_BUTTON_CHECKED); HandleCheckEntry(pEntry); } IMPL_LINK_NOARG(CertPathDialog, AddHdl_Impl) { try { uno::Reference<ui::dialogs::XFolderPicker2> xFolderPicker = ui::dialogs::FolderPicker::create(comphelper::getProcessComponentContext()); rtl::OUString sURL; osl::Security().getHomeDir(sURL); xFolderPicker->setDisplayDirectory(sURL); xFolderPicker->setDescription(m_sAddDialogText); if (xFolderPicker->execute() == ui::dialogs::ExecutableDialogResults::OK) { sURL = xFolderPicker->getDirectory(); rtl::OUString aPath; if (osl::FileBase::E_None == osl::FileBase::getSystemPathFromFileURL(sURL, aPath)) AddCertPath(m_sManual, aPath); } } catch (const uno::Exception&) { SAL_WARN( "cui.options", "CertPathDialog::AddHdl_Impl(): caught exception" ); } return 0; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Improve error reporting<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * Version: MPL 1.1 / GPLv3+ / LGPLv3+ * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License or as specified alternatively below. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * Major Contributor(s): * Copyright (C) 2012 Red Hat, Inc., Caolán McNamara <caolanm@redhat.com> * (initial developer) * * All Rights Reserved. * * For minor contributions see the git repository. * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 3 or later (the "GPLv3+"), or * the GNU Lesser General Public License Version 3 or later (the "LGPLv3+"), * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable * instead of those above. */ #include <officecfg/Office/Common.hxx> #include <osl/file.hxx> #include <osl/security.hxx> #include <svtools/stdctrl.hxx> #include "svtools/treelistentry.hxx" #include <unotools/securityoptions.hxx> #include <cuires.hrc> #include "certpath.hxx" #include "certpath.hrc" #include "dialmgr.hxx" #include <com/sun/star/mozilla/XMozillaBootstrap.hpp> #include <com/sun/star/ui/dialogs/ExecutableDialogResults.hpp> #include <com/sun/star/ui/dialogs/FolderPicker.hpp> #include <comphelper/processfactory.hxx> using namespace ::com::sun::star; CertPathDialog::CertPathDialog( Window* pParent ) : ModalDialog( pParent, CUI_RES( RID_SVXDLG_CERTPATH ) ) , m_aCertPathFL ( this, CUI_RES( FL_CERTPATH ) ) , m_aCertPathFT ( this, CUI_RES( FT_CERTPATH ) ) , m_aCertPathListContainer( this, CUI_RES( LB_CERTPATH ) ) , m_aCertPathList( m_aCertPathListContainer ) , m_aAddBtn ( this, CUI_RES( PB_ADD ) ) , m_aButtonsFL ( this, CUI_RES( FL_BUTTONS ) ) , m_aOKBtn ( this, CUI_RES( PB_OK ) ) , m_aCancelBtn ( this, CUI_RES( PB_CANCEL ) ) , m_aHelpBtn ( this, CUI_RES( PB_HELP ) ) , m_sAddDialogText(CUI_RESSTR(STR_ADDDLGTEXT)) , m_sManual(CUI_RESSTR(STR_MANUAL)) { static long aStaticTabs[]= { 3, 0, 15, 75 }; m_aCertPathList.SvxSimpleTable::SetTabs( aStaticTabs ); rtl::OUString sProfile(CUI_RESSTR(STR_PROFILE)); rtl::OUString sDirectory(CUI_RESSTR(STR_DIRECTORY)); rtl::OUStringBuffer sHeader; sHeader.append('\t').append(sProfile).append('\t').append(sDirectory); m_aCertPathList.InsertHeaderEntry( sHeader.makeStringAndClear(), HEADERBAR_APPEND, HIB_LEFT ); m_aCertPathList.SetCheckButtonHdl( LINK( this, CertPathDialog, CheckHdl_Impl ) ); m_aAddBtn.SetClickHdl( LINK( this, CertPathDialog, AddHdl_Impl ) ); m_aOKBtn.SetClickHdl( LINK( this, CertPathDialog, OKHdl_Impl ) ); FreeResource(); try { mozilla::MozillaProductType productTypes[3] = { mozilla::MozillaProductType_Thunderbird, mozilla::MozillaProductType_Firefox, mozilla::MozillaProductType_Mozilla }; const char* productNames[3] = { "thunderbird", "firefox", "mozilla" }; sal_Int32 nProduct = SAL_N_ELEMENTS(productTypes); uno::Reference<uno::XInterface> xInstance = comphelper::getProcessServiceFactory()->createInstance( "com.sun.star.mozilla.MozillaBootstrap"); uno::Reference<mozilla::XMozillaBootstrap> xMozillaBootstrap(xInstance, uno::UNO_QUERY_THROW); for (sal_Int32 i = 0; i < nProduct; ++i) { ::rtl::OUString profile = xMozillaBootstrap->getDefaultProfile(productTypes[i]); if (!profile.isEmpty()) { ::rtl::OUString sProfilePath = xMozillaBootstrap->getProfilePath( productTypes[i], profile ); rtl::OUStringBuffer sEntry; sEntry.append('\t').appendAscii(productNames[i]).append(':').append(profile).append('\t').append(sProfilePath); SvTreeListEntry *pEntry = m_aCertPathList.InsertEntry(sEntry.makeStringAndClear()); rtl::OUString* pCertPath = new rtl::OUString(sProfilePath); pEntry->SetUserData(pCertPath); } } } catch (const uno::Exception&) { } SvTreeListEntry *pEntry = m_aCertPathList.GetEntry(0); if (pEntry) { m_aCertPathList.SetCheckButtonState(pEntry, SV_BUTTON_CHECKED); HandleCheckEntry(pEntry); } try { rtl::OUString sUserSetCertPath = officecfg::Office::Common::Security::Scripting::CertDir::get().get_value_or(rtl::OUString()); if (!sUserSetCertPath.isEmpty()) AddCertPath(m_sManual, sUserSetCertPath); } catch (const uno::Exception &e) { SAL_WARN("cui.options", "CertPathDialog::CertPathDialog(): caught exception" << e.Message); } const char* pEnv = getenv("MOZILLA_CERTIFICATE_FOLDER"); if (pEnv) AddCertPath("$MOZILLA_CERTIFICATE_FOLDER", rtl::OUString(pEnv, strlen(pEnv), osl_getThreadTextEncoding())); } IMPL_LINK_NOARG(CertPathDialog, OKHdl_Impl) { fprintf(stderr, "dir is %s\n", rtl::OUStringToOString(getDirectory(), RTL_TEXTENCODING_UTF8).getStr()); try { boost::shared_ptr< comphelper::ConfigurationChanges > batch( comphelper::ConfigurationChanges::create()); officecfg::Office::Common::Security::Scripting::CertDir::set( getDirectory(), batch); batch->commit(); } catch (const uno::Exception &e) { SAL_WARN("cui.options", "CertPathDialog::OKHdl_Impl(): caught exception" << e.Message); } EndDialog(true); return 0; } rtl::OUString CertPathDialog::getDirectory() const { SvTreeListEntry* pEntry = m_aCertPathList.FirstSelected(); void* pCertPath = pEntry ? pEntry->GetUserData() : NULL; return pCertPath ? *static_cast<rtl::OUString*>(pCertPath) : rtl::OUString(); } CertPathDialog::~CertPathDialog() { SvTreeListEntry* pEntry = m_aCertPathList.First(); while (pEntry) { rtl::OUString* pCertPath = static_cast<rtl::OUString*>(pEntry->GetUserData()); delete pCertPath; pEntry = m_aCertPathList.Next( pEntry ); } } IMPL_LINK( CertPathDialog, CheckHdl_Impl, SvxSimpleTable *, pList ) { SvTreeListEntry* pEntry = pList ? m_aCertPathList.GetEntry(m_aCertPathList.GetCurMousePoint()) : m_aCertPathList.FirstSelected(); if (pEntry) m_aCertPathList.HandleEntryChecked(pEntry); return 0; } void CertPathDialog::HandleCheckEntry( SvTreeListEntry* _pEntry ) { m_aCertPathList.Select( _pEntry, true ); SvButtonState eState = m_aCertPathList.GetCheckButtonState( _pEntry ); if (SV_BUTTON_CHECKED == eState) { // uncheck the other entries SvTreeListEntry* pEntry = m_aCertPathList.First(); while (pEntry) { if (pEntry != _pEntry) m_aCertPathList.SetCheckButtonState(pEntry, SV_BUTTON_UNCHECKED); pEntry = m_aCertPathList.Next(pEntry); } } else m_aCertPathList.SetCheckButtonState(_pEntry, SV_BUTTON_CHECKED); } void CertPathDialog::AddCertPath(const rtl::OUString &rProfile, const rtl::OUString &rPath) { SvTreeListEntry* pEntry = m_aCertPathList.First(); while (pEntry) { rtl::OUString* pCertPath = static_cast<rtl::OUString*>(pEntry->GetUserData()); //already exists, just select the original one if (pCertPath->equals(rPath)) { m_aCertPathList.SetCheckButtonState(pEntry, SV_BUTTON_CHECKED); HandleCheckEntry(pEntry); return; } pEntry = m_aCertPathList.Next(pEntry); } rtl::OUStringBuffer sEntry; sEntry.append('\t').append(rProfile).append('\t').append(rPath); pEntry = m_aCertPathList.InsertEntry(sEntry.makeStringAndClear()); rtl::OUString* pCertPath = new rtl::OUString(rPath); pEntry->SetUserData(pCertPath); m_aCertPathList.SetCheckButtonState(pEntry, SV_BUTTON_CHECKED); HandleCheckEntry(pEntry); } IMPL_LINK_NOARG(CertPathDialog, AddHdl_Impl) { try { uno::Reference<ui::dialogs::XFolderPicker2> xFolderPicker = ui::dialogs::FolderPicker::create(comphelper::getProcessComponentContext()); rtl::OUString sURL; osl::Security().getHomeDir(sURL); xFolderPicker->setDisplayDirectory(sURL); xFolderPicker->setDescription(m_sAddDialogText); if (xFolderPicker->execute() == ui::dialogs::ExecutableDialogResults::OK) { sURL = xFolderPicker->getDirectory(); rtl::OUString aPath; if (osl::FileBase::E_None == osl::FileBase::getSystemPathFromFileURL(sURL, aPath)) AddCertPath(m_sManual, aPath); } } catch (uno::Exception & e) { SAL_WARN("cui.options", "caught UNO exception: " << e.Message); } return 0; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#include <cmath> #include "auto_timer.h" int main() { AutoTimer timer; for (double i = 0; i < 100000; ++i) { double root = sqrt(i); root *= root; } } <commit_msg>Makes the test take a little longer.<commit_after>#include <cmath> #include "auto_timer.h" int main() { AutoTimer timer; for (double i = 0; i < 100000000; ++i) { double root = sqrt(i); root *= root; } } <|endoftext|>
<commit_before>#include "xml11.hpp" #include <cassert> #include <iostream> #include <set> #include <cstring> #include <ctime> using std::cout; using std::endl; void test_fn1() { using namespace xml11; { const auto text = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<story><info id1=\"123456789\" id2=\"555\"><author id3=\"009\">John Fleck</author><date>June 2, 2002</date><keyword>example</keyword></info><body><headline>This is the headline</headline><para>Para1</para><para>Para2</para><para>Para3</para><nested1><nested2 id=\"\">nested2 text фыв</nested2></nested1></body><ebook/><ebook/></story>\n"; const auto node = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<story><info id1=\"123456789\" id2=\"555\"><author id3=\"009\">John Fleck</author><date>June 2, 2002</date><keyword>example</keyword></info><body><headline>This is the headline</headline><para>Para1</para><para>Para2</para><para>Para3</para><nested1><nested2 id=\"\">nested2 text фыв</nested2></nested1></body><ebook/><ebook/></story>\n"_xml; assert(node.toString(false) == text); assert(node[""].size() == 0); } { Node node { "root", { {"node1", "value1", Node::Type::ATTRIBUTE}, {"node2", "value2"}, {"node3", "value3"}, {"node4", "1123"}, {"Epmloyers", { {"Epmloyer", { {"name", "1"}, {"surname", "2"}, {"patronym", "3"} }}, {"Epmloyer", { {"name", "1"}, {"surname", "2"}, {"patronym", "3"} }}, {"Epmloyer", { {"name", "1"}, {"surname", "2"}, {"patronym", "3", Node::Type::ATTRIBUTE} }} }} } }; node("node2") += { "nodex", { {"nested1", "nested2"} }}; assert(node("node2")[Node::Type::TEXT].size() == 1); assert(node("node2")("nodex")); assert(node("node2")("nodex").type() == Node::Type::ELEMENT); assert(node("node2")("nodex")("nested1")); assert(node("node2")("nodex")("nested1").type() == Node::Type::ELEMENT); assert(node("node2")("nodex")("nested1")("")); assert(node("node2")("nodex")("nested1")(Node::Type::TEXT)); assert(node("node2")("nodex")("nested1")[""].size() == 1); assert(node("node2")("nodex")("nested1")[Node::Type::TEXT].size() == 1); node("node1").text("<aqwe><nested1/></aqwe>"); auto employers = node("Epmloyers"); if (employers) { auto employer = employers["Epmloyer"][1]; if (employer) { employer.value("<aqwe><nested1/></aqwe>"); } } node("Epmloyers")["Epmloyer"][0].value("new_my_value"); node("node3").value(Node {"new node3", "asdqwe123"}); assert(node); assert(node("Epmloyers")[Node::Type::ELEMENT].size() == 3); assert(node("Epmloyers")[Node::Type::TEXT].size() == 0); auto new_node = Node {"", "text_new_node"}; assert(node("node4")); assert(node("node4").nodes().size() == 1); assert(node("node4").text() == "1123"); node("node4").addNode(std::move(new_node)); assert(node("node4").nodes().size() == 2); assert(node("node4").text() == "1123text_new_node"); node("node4").text("replace_text"); assert(node("node4").text() == "replace_text"); assert(node.nodes().size() == 5); auto new_node2 = Node {"", ""}; node.addNode(new_node2); assert(node.nodes().size() == 5); node -= new_node2; assert(node.nodes().size() == 5); auto new_node3 = Node {"new3", "data3"}; node += new_node3; assert(node.nodes().size() == 6); node -= new_node3; assert(node.nodes().size() == 5); } { const auto node = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<root><nested></nested></roo>"_xml; assert(not node); assert(node.error()=="Fatal error: Entity: line 2, column: 33: Opening and ending tag mismatch: root line 2 and roo\n\n"); } { const auto node = "aqwe"_xml; assert(not node); assert(node.error()=="Fatal error: Entity: line 1, column: 1: Document is empty\n\n"); } { // Node constructors. const auto _2 = Node {"MyTag"}; assert(_2); const auto _3 = Node {"MyTag", "MyTagValue"}; assert(_3); auto _4 = _3; assert(_3); assert(_4); const auto _5 = std::move(_4); assert(not _4); assert(_5); auto node = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" "<story>" " 11111" " <info true=\"1\">" " <author>John Fleck</author>" " <date>June 2, 2002</date>" " <keyword>example</keyword>" " </info>" " 333333" " <body>" " <headline>This is the headline</headline>" " <para>Para1</para>" " <para>Para2</para>" " <para>Para3</para>" " <nested1>" " <nested2>nested2 text фыв</nested2>" " </nested1>" " </body>" " <ebook/>" " <ebook/>" " 22222" "</story>"_xml; assert(node); // Node has a name (if it is not a text node). assert(node.name() == "story"); node.name("new_story"); assert(node.name() == "new_story"); // Check the node type. assert(node.type() == Node::Type::ELEMENT); assert(node("").type() == Node::Type::TEXT); // Set value to the node (replace exists text nodes). assert(node[""].size() == 3); node.text("new_node_value"); assert(node[""].size() == 1); assert(node[""][0].text() == "new_node_value"); assert(node.text() == "new_node_value"); // Select Node child nodes. assert(node("info")); assert(node("body")); assert(node("ebook")); // Get the first one. assert(node["ebook"].size() == 2); assert(not node("abracadabra")); // This node does not exists. // Working with nested nodes. const auto body = node("body"); assert(body); assert(body.name() == "body"); auto body_headline = body("headline"); assert(body_headline); assert(body_headline.name() == "headline"); assert(body_headline.text() == "This is the headline"); body_headline.text(""); assert(body_headline.text() == ""); // Add a new node. body_headline.addNode(Node {"new_node", "new_node_text"}); assert(body_headline["new_node"].size() == 1); assert(body_headline["new_node"][0].name() == "new_node"); assert(body_headline("new_node").name() == "new_node"); auto new_node = body_headline("new_node"); assert(new_node); assert(new_node.text() == "new_node_text"); // Add a new node without value. body_headline.addNode(Node {"new_node2"}); assert(body_headline["new_node2"].size() == 1); assert(body_headline("new_node2").name() == "new_node2"); assert(body_headline("new_node2").text() == ""); // Constness. Can not access data via pointer. // body["para"][0].value(""); // Erase nodes. body_headline.eraseNode(body_headline("new_node2")); assert(not body_headline("new_node2")); assert(body_headline("new_node")); body_headline.eraseNode(std::move(new_node)); assert(not body_headline("new_node2")); // Get all nodes. assert(body.nodes().size() == 5); } { const clock_t begin = clock(); constexpr auto TIMES = 100000; std::vector<Node> nodes; for (size_t i = 0; i < TIMES; ++i) { nodes.push_back( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" "<story>" " 11111" " <info true=\"1\">" " <author>John Fleck</author>" " <date>June 2, 2002</date>" " <keyword>example</keyword>" " </info>" " 333333" " <body>" " <headline>This is the headline</headline>" " <para>Para1</para>" " <para>Para2</para>" " <para>Para3</para>" " <nested1>" " <nested2>nested2 text фыв</nested2>" " </nested1>" " </body>" " <ebook/>" " <ebook/>" " 22222" "</story>"_xml); } const clock_t end = clock(); const double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC; cout << "Result size: " << nodes.size() << endl; cout << "Average total parsing time " << TIMES << " times = " << elapsed_secs << " secs" << endl; cout << "Average one parsing time = " << elapsed_secs / TIMES << " secs" << endl; } { const auto node = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" "<story>" " 11111" " <info true=\"1\">" " <author>John Fleck</author>" " <date>June 2, 2002</date>" " <keyword>example</keyword>" " </info>" " 333333" " <body>" " <headline>This is the headline</headline>" " <para>Para1</para>" " <para>Para2</para>" " <para>Para3</para>" " <nested1>" " <nested2>nested2 text фыв</nested2>" " </nested1>" " </body>" " <ebook/>" " <ebook/>" " 22222" "</story>"_xml; const clock_t begin = clock(); constexpr auto TIMES = 100000; std::string result; for (size_t i = 0; i < TIMES; ++i) { result += node.toString(); } const clock_t end = clock(); const double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC; cout << "Result size: " << result.size() << endl; cout << "Average total serialize " << TIMES << " times = " << elapsed_secs << " secs" << endl; cout << "Average one serialization time = " << elapsed_secs / TIMES << " secs" << endl; } } int main() { test_fn1(); return 0; } <commit_msg>property test added<commit_after>#include "xml11.hpp" #include <cassert> #include <iostream> #include <set> #include <cstring> #include <ctime> using std::cout; using std::endl; void test_fn1() { using namespace xml11; { const auto text = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<story><info id1=\"123456789\" id2=\"555\"><author id3=\"009\">John Fleck</author><date>June 2, 2002</date><keyword>example</keyword></info><body><headline>This is the headline</headline><para>Para1</para><para>Para2</para><para>Para3</para><nested1><nested2 id=\"\">nested2 text фыв</nested2></nested1></body><ebook/><ebook/></story>\n"; const auto node = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<story><info id1=\"123456789\" id2=\"555\"><author id3=\"009\">John Fleck</author><date>June 2, 2002</date><keyword>example</keyword></info><body><headline>This is the headline</headline><para>Para1</para><para>Para2</para><para>Para3</para><nested1><nested2 id=\"\">nested2 text фыв</nested2></nested1></body><ebook/><ebook/></story>\n"_xml; assert(node.toString(false) == text); assert(node[""].size() == 0); } { Node node { "root", { {"node1", "value1", Node::Type::ATTRIBUTE}, {"node2", "value2"}, {"node3", "value3"}, {"node4", "1123"}, {"Epmloyers", { {"Epmloyer", { {"name", "1"}, {"surname", "2"}, {"patronym", "3"} }}, {"Epmloyer", { {"name", "1"}, {"surname", "2"}, {"patronym", "3"} }}, {"Epmloyer", { {"name", "1"}, {"surname", "2"}, {"patronym", "3", Node::Type::ATTRIBUTE} }} }} } }; node("node2") += { "nodex", { {"nested1", "nested2"} }}; assert(node("node2")[Node::Type::TEXT].size() == 1); assert(node("node2")("nodex")); assert(node("node2")("nodex").type() == Node::Type::ELEMENT); assert(node("node2")("nodex")("nested1")); assert(node("node2")("nodex")("nested1").type() == Node::Type::ELEMENT); assert(node("node2")("nodex")("nested1")("")); assert(node("node2")("nodex")("nested1")(Node::Type::TEXT)); assert(node("node2")("nodex")("nested1")[""].size() == 1); assert(node("node2")("nodex")("nested1")[Node::Type::TEXT].size() == 1); node("node1").text("<aqwe><nested1/></aqwe>"); auto employers = node("Epmloyers"); if (employers) { auto employer = employers["Epmloyer"][1]; if (employer) { employer.value("<aqwe><nested1/></aqwe>"); } } node("Epmloyers")["Epmloyer"][0].value("new_my_value"); node("node3").value(Node {"new node3", "asdqwe123"}); assert(node); assert(node("Epmloyers")[Node::Type::ELEMENT].size() == 3); assert(node("Epmloyers")[Node::Type::TEXT].size() == 0); auto new_node = Node {"", "text_new_node"}; assert(node("node4")); assert(node("node4").nodes().size() == 1); assert(node("node4").text() == "1123"); node("node4").addNode(std::move(new_node)); assert(node("node4").nodes().size() == 2); assert(node("node4").text() == "1123text_new_node"); node("node4").text("replace_text"); assert(node("node4").text() == "replace_text"); assert(node.nodes().size() == 5); auto new_node2 = Node {"", ""}; node.addNode(new_node2); assert(node.nodes().size() == 5); node -= new_node2; assert(node.nodes().size() == 5); auto new_node3 = Node {"new3", "data3"}; node += new_node3; assert(node.nodes().size() == 6); node -= new_node3; assert(node.nodes().size() == 5); } { const auto node = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<root><nested></nested></roo>"_xml; assert(not node); assert(node.error()=="Fatal error: Entity: line 2, column: 33: Opening and ending tag mismatch: root line 2 and roo\n\n"); } { const auto node = "aqwe"_xml; assert(not node); assert(node.error()=="Fatal error: Entity: line 1, column: 1: Document is empty\n\n"); } { // Node constructors. const auto _2 = Node {"MyTag"}; assert(_2); const auto _3 = Node {"MyTag", "MyTagValue"}; assert(_3); auto _4 = _3; assert(_3); assert(_4); const auto _5 = std::move(_4); assert(not _4); assert(_5); auto node = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" "<story>" " 11111" " <info my_property=\"prop_value\">" " <author>John Fleck</author>" " <date>June 2, 2002</date>" " <keyword>example</keyword>" " </info>" " 333333" " <body>" " <headline>This is the headline</headline>" " <para>Para1</para>" " <para>Para2</para>" " <para>Para3</para>" " <nested1>" " <nested2>nested2 text фыв</nested2>" " </nested1>" " </body>" " <ebook/>" " <ebook/>" " 22222" "</story>"_xml; assert(node); // Node has a name (if it is not a text node). assert(node.name() == "story"); node.name("new_story"); assert(node.name() == "new_story"); // Check the node type. assert(node.type() == Node::Type::ELEMENT); assert(node("").type() == Node::Type::TEXT); // Set value to the node (replace exists text nodes). assert(node[""].size() == 3); node.text("new_node_value"); assert(node[""].size() == 1); assert(node[""][0].text() == "new_node_value"); assert(node.text() == "new_node_value"); // Select Node child nodes. assert(node("info")); assert(node("body")); assert(node("ebook")); // Get the first one. assert(node["ebook"].size() == 2); assert(not node("abracadabra")); // This node does not exists. // Working with nested nodes. const auto body = node("body"); assert(body); assert(body.name() == "body"); auto body_headline = body("headline"); assert(body_headline); assert(body_headline.name() == "headline"); assert(body_headline.text() == "This is the headline"); body_headline.text(""); assert(body_headline.text() == ""); // Add a new node. body_headline.addNode(Node {"new_node", "new_node_text"}); assert(body_headline["new_node"].size() == 1); assert(body_headline["new_node"][0].name() == "new_node"); assert(body_headline("new_node").name() == "new_node"); auto new_node = body_headline("new_node"); assert(new_node); assert(new_node.text() == "new_node_text"); // Add a new node without value. body_headline.addNode(Node {"new_node2"}); assert(body_headline["new_node2"].size() == 1); assert(body_headline("new_node2").name() == "new_node2"); assert(body_headline("new_node2").text() == ""); // Constness. Can not access data via pointer. // body["para"][0].value(""); // Erase nodes. body_headline.eraseNode(body_headline("new_node2")); assert(not body_headline("new_node2")); assert(body_headline("new_node")); body_headline.eraseNode(std::move(new_node)); assert(not body_headline("new_node2")); // Get all nodes. assert(body.nodes().size() == 5); // property assert(node("info")("my_property").text() == "prop_value"); } { const clock_t begin = clock(); constexpr auto TIMES = 100000; std::vector<Node> nodes; for (size_t i = 0; i < TIMES; ++i) { nodes.push_back( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" "<story>" " 11111" " <info my_property=\"prop_value\">" " <author>John Fleck</author>" " <date>June 2, 2002</date>" " <keyword>example</keyword>" " </info>" " 333333" " <body>" " <headline>This is the headline</headline>" " <para>Para1</para>" " <para>Para2</para>" " <para>Para3</para>" " <nested1>" " <nested2>nested2 text фыв</nested2>" " </nested1>" " </body>" " <ebook/>" " <ebook/>" " 22222" "</story>"_xml); } const clock_t end = clock(); const double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC; cout << "Result size: " << nodes.size() << endl; cout << "Average total parsing time " << TIMES << " times = " << elapsed_secs << " secs" << endl; cout << "Average one parsing time = " << elapsed_secs / TIMES << " secs" << endl; } { const auto node = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" "<story>" " 11111" " <info my_property=\"prop_value\">" " <author>John Fleck</author>" " <date>June 2, 2002</date>" " <keyword>example</keyword>" " </info>" " 333333" " <body>" " <headline>This is the headline</headline>" " <para>Para1</para>" " <para>Para2</para>" " <para>Para3</para>" " <nested1>" " <nested2>nested2 text фыв</nested2>" " </nested1>" " </body>" " <ebook/>" " <ebook/>" " 22222" "</story>"_xml; const clock_t begin = clock(); constexpr auto TIMES = 100000; std::string result; for (size_t i = 0; i < TIMES; ++i) { result += node.toString(); } const clock_t end = clock(); const double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC; cout << "Result size: " << result.size() << endl; cout << "Average total serialize " << TIMES << " times = " << elapsed_secs << " secs" << endl; cout << "Average one serialization time = " << elapsed_secs / TIMES << " secs" << endl; } } int main() { test_fn1(); return 0; } <|endoftext|>
<commit_before>#include "config.h" #include "file_io_type_pel.hpp" #include "libpldm/base.h" #include "oem/ibm/libpldm/file_io.h" #include "common/utils.hpp" #include "xyz/openbmc_project/Common/error.hpp" #include <stdint.h> #include <systemd/sd-bus.h> #include <unistd.h> #include <sdbusplus/server.hpp> #include <xyz/openbmc_project/Logging/Entry/server.hpp> #include <exception> #include <filesystem> #include <fstream> #include <iostream> #include <vector> namespace pldm { namespace responder { using namespace sdbusplus::xyz::openbmc_project::Logging::server; namespace detail { /** * @brief Finds the Entry::Level value for the severity of the PEL * passed in. * * The severity byte is at offset 10 in the User Header section, * which is always after the 48 byte Private Header section. * * @param[in] pelFileName - The file containing the PEL * * @return Entry::Level - The severity value for the Entry */ Entry::Level getEntryLevelFromPEL(const std::string& pelFileName) { const std::map<uint8_t, Entry::Level> severityMap{ {0x00, Entry::Level::Informational}, // Informational event {0x10, Entry::Level::Warning}, // Recoverable error {0x20, Entry::Level::Warning}, // Predictive error {0x40, Entry::Level::Error}, // Unrecoverable error {0x50, Entry::Level::Error}, // Critical error {0x60, Entry::Level::Error}, // Error from a diagnostic test {0x70, Entry::Level::Warning} // Recoverable symptom }; const size_t severityOffset = 0x3A; size_t size = 0; if (fs::exists(pelFileName)) { size = fs::file_size(pelFileName); } if (size > severityOffset) { std::ifstream pel{pelFileName}; if (pel.good()) { pel.seekg(severityOffset); uint8_t sev; pel.read(reinterpret_cast<char*>(&sev), 1); // Get the type sev = sev & 0xF0; auto entry = severityMap.find(sev); if (entry != severityMap.end()) { return entry->second; } } else { std::cerr << "Unable to open PEL file " << pelFileName << "\n"; } } return Entry::Level::Error; } } // namespace detail int PelHandler::readIntoMemory(uint32_t offset, uint32_t& length, uint64_t address, oem_platform::Handler* /*oemPlatformHandler*/) { static constexpr auto logObjPath = "/xyz/openbmc_project/logging"; static constexpr auto logInterface = "org.open_power.Logging.PEL"; auto& bus = pldm::utils::DBusHandler::getBus(); try { auto service = pldm::utils::DBusHandler().getService(logObjPath, logInterface); auto method = bus.new_method_call(service.c_str(), logObjPath, logInterface, "GetPEL"); method.append(fileHandle); auto reply = bus.call(method); sdbusplus::message::unix_fd fd{}; reply.read(fd); auto rc = transferFileData(fd, true, offset, length, address); return rc; } catch (const std::exception& e) { std::cerr << "GetPEL D-Bus call failed, PEL id = " << fileHandle << ", error = " << e.what() << "\n"; return PLDM_ERROR; } return PLDM_SUCCESS; } int PelHandler::read(uint32_t offset, uint32_t& length, Response& response, oem_platform::Handler* /*oemPlatformHandler*/) { static constexpr auto logObjPath = "/xyz/openbmc_project/logging"; static constexpr auto logInterface = "org.open_power.Logging.PEL"; auto& bus = pldm::utils::DBusHandler::getBus(); try { auto service = pldm::utils::DBusHandler().getService(logObjPath, logInterface); auto method = bus.new_method_call(service.c_str(), logObjPath, logInterface, "GetPEL"); method.append(fileHandle); auto reply = bus.call(method); sdbusplus::message::unix_fd fd{}; reply.read(fd); off_t fileSize = lseek(fd, 0, SEEK_END); if (fileSize == -1) { std::cerr << "file seek failed"; return PLDM_ERROR; } if (offset >= fileSize) { std::cerr << "Offset exceeds file size, OFFSET=" << offset << " FILE_SIZE=" << fileSize << std::endl; return PLDM_DATA_OUT_OF_RANGE; } if (offset + length > fileSize) { length = fileSize - offset; } auto rc = lseek(fd, offset, SEEK_SET); if (rc == -1) { std::cerr << "file seek failed"; return PLDM_ERROR; } size_t currSize = response.size(); response.resize(currSize + length); auto filePos = reinterpret_cast<char*>(response.data()); filePos += currSize; rc = ::read(fd, filePos, length); if (rc == -1) { std::cerr << "file read failed"; return PLDM_ERROR; } if (rc != length) { std::cerr << "mismatch between number of characters to read and " << "the length read, LENGTH=" << length << " COUNT=" << rc << std::endl; return PLDM_ERROR; } } catch (const std::exception& e) { std::cerr << "GetPEL D-Bus call failed"; return PLDM_ERROR; } return PLDM_SUCCESS; } int PelHandler::writeFromMemory(uint32_t offset, uint32_t length, uint64_t address, oem_platform::Handler* /*oemPlatformHandler*/) { char tmpFile[] = "/tmp/pel.XXXXXX"; int fd = mkstemp(tmpFile); if (fd == -1) { std::cerr << "failed to create a temporary pel, ERROR=" << errno << "\n"; return PLDM_ERROR; } close(fd); fs::path path(tmpFile); auto rc = transferFileData(path, false, offset, length, address); if (rc == PLDM_SUCCESS) { rc = storePel(path.string()); } return rc; } int PelHandler::fileAck(uint8_t /*fileStatus*/) { static constexpr auto logObjPath = "/xyz/openbmc_project/logging"; static constexpr auto logInterface = "org.open_power.Logging.PEL"; auto& bus = pldm::utils::DBusHandler::getBus(); try { auto service = pldm::utils::DBusHandler().getService(logObjPath, logInterface); auto method = bus.new_method_call(service.c_str(), logObjPath, logInterface, "HostAck"); method.append(fileHandle); bus.call_noreply(method); } catch (const std::exception& e) { std::cerr << "HostAck D-Bus call failed"; return PLDM_ERROR; } return PLDM_SUCCESS; } int PelHandler::storePel(std::string&& pelFileName) { static constexpr auto logObjPath = "/xyz/openbmc_project/logging"; static constexpr auto logInterface = "xyz.openbmc_project.Logging.Create"; auto& bus = pldm::utils::DBusHandler::getBus(); try { auto service = pldm::utils::DBusHandler().getService(logObjPath, logInterface); using namespace sdbusplus::xyz::openbmc_project::Logging::server; std::map<std::string, std::string> addlData{}; auto severity = sdbusplus::xyz::openbmc_project::Logging::server::convertForMessage( detail::getEntryLevelFromPEL(pelFileName)); addlData.emplace("RAWPEL", std::move(pelFileName)); auto method = bus.new_method_call(service.c_str(), logObjPath, logInterface, "Create"); method.append("xyz.openbmc_project.Host.Error.Event", severity, addlData); bus.call_noreply(method); } catch (const std::exception& e) { std::cerr << "failed to make a d-bus call to PEL daemon, ERROR=" << e.what() << "\n"; return PLDM_ERROR; } return PLDM_SUCCESS; } int PelHandler::write(const char* buffer, uint32_t offset, uint32_t& length, oem_platform::Handler* /*oemPlatformHandler*/) { int rc = PLDM_SUCCESS; if (offset > 0) { std::cerr << "Offset is non zero \n"; return PLDM_ERROR; } char tmpFile[] = "/tmp/pel.XXXXXX"; auto fd = mkstemp(tmpFile); if (fd == -1) { std::cerr << "failed to create a temporary pel, ERROR=" << errno << "\n"; return PLDM_ERROR; } size_t written = 0; do { if ((rc = ::write(fd, buffer, length - written)) == -1) { break; } written += rc; buffer += rc; } while (rc && written < length); close(fd); if (rc == -1) { std::cerr << "file write failed, ERROR=" << errno << ", LENGTH=" << length << ", OFFSET=" << offset << "\n"; fs::remove(tmpFile); return PLDM_ERROR; } if (written == length) { fs::path path(tmpFile); rc = storePel(path.string()); if (rc != PLDM_SUCCESS) { std::cerr << "save PEL failed, ERROR = " << rc << "tmpFile = " << tmpFile << "\n"; } } return rc; } } // namespace responder } // namespace pldm <commit_msg>oem_ibm: Enhance PEL D-Bus call failure tracing<commit_after>#include "config.h" #include "file_io_type_pel.hpp" #include "libpldm/base.h" #include "oem/ibm/libpldm/file_io.h" #include "common/utils.hpp" #include "xyz/openbmc_project/Common/error.hpp" #include <stdint.h> #include <systemd/sd-bus.h> #include <unistd.h> #include <sdbusplus/server.hpp> #include <xyz/openbmc_project/Logging/Entry/server.hpp> #include <exception> #include <filesystem> #include <fstream> #include <iostream> #include <vector> namespace pldm { namespace responder { using namespace sdbusplus::xyz::openbmc_project::Logging::server; namespace detail { /** * @brief Finds the Entry::Level value for the severity of the PEL * passed in. * * The severity byte is at offset 10 in the User Header section, * which is always after the 48 byte Private Header section. * * @param[in] pelFileName - The file containing the PEL * * @return Entry::Level - The severity value for the Entry */ Entry::Level getEntryLevelFromPEL(const std::string& pelFileName) { const std::map<uint8_t, Entry::Level> severityMap{ {0x00, Entry::Level::Informational}, // Informational event {0x10, Entry::Level::Warning}, // Recoverable error {0x20, Entry::Level::Warning}, // Predictive error {0x40, Entry::Level::Error}, // Unrecoverable error {0x50, Entry::Level::Error}, // Critical error {0x60, Entry::Level::Error}, // Error from a diagnostic test {0x70, Entry::Level::Warning} // Recoverable symptom }; const size_t severityOffset = 0x3A; size_t size = 0; if (fs::exists(pelFileName)) { size = fs::file_size(pelFileName); } if (size > severityOffset) { std::ifstream pel{pelFileName}; if (pel.good()) { pel.seekg(severityOffset); uint8_t sev; pel.read(reinterpret_cast<char*>(&sev), 1); // Get the type sev = sev & 0xF0; auto entry = severityMap.find(sev); if (entry != severityMap.end()) { return entry->second; } } else { std::cerr << "Unable to open PEL file " << pelFileName << "\n"; } } return Entry::Level::Error; } } // namespace detail int PelHandler::readIntoMemory(uint32_t offset, uint32_t& length, uint64_t address, oem_platform::Handler* /*oemPlatformHandler*/) { static constexpr auto logObjPath = "/xyz/openbmc_project/logging"; static constexpr auto logInterface = "org.open_power.Logging.PEL"; auto& bus = pldm::utils::DBusHandler::getBus(); try { auto service = pldm::utils::DBusHandler().getService(logObjPath, logInterface); auto method = bus.new_method_call(service.c_str(), logObjPath, logInterface, "GetPEL"); method.append(fileHandle); auto reply = bus.call(method); sdbusplus::message::unix_fd fd{}; reply.read(fd); auto rc = transferFileData(fd, true, offset, length, address); return rc; } catch (const std::exception& e) { std::cerr << "GetPEL D-Bus call failed, PEL id = 0x" << std::hex << fileHandle << ", error = " << e.what() << "\n"; return PLDM_ERROR; } return PLDM_SUCCESS; } int PelHandler::read(uint32_t offset, uint32_t& length, Response& response, oem_platform::Handler* /*oemPlatformHandler*/) { static constexpr auto logObjPath = "/xyz/openbmc_project/logging"; static constexpr auto logInterface = "org.open_power.Logging.PEL"; auto& bus = pldm::utils::DBusHandler::getBus(); try { auto service = pldm::utils::DBusHandler().getService(logObjPath, logInterface); auto method = bus.new_method_call(service.c_str(), logObjPath, logInterface, "GetPEL"); method.append(fileHandle); auto reply = bus.call(method); sdbusplus::message::unix_fd fd{}; reply.read(fd); off_t fileSize = lseek(fd, 0, SEEK_END); if (fileSize == -1) { std::cerr << "file seek failed"; return PLDM_ERROR; } if (offset >= fileSize) { std::cerr << "Offset exceeds file size, OFFSET=" << offset << " FILE_SIZE=" << fileSize << std::endl; return PLDM_DATA_OUT_OF_RANGE; } if (offset + length > fileSize) { length = fileSize - offset; } auto rc = lseek(fd, offset, SEEK_SET); if (rc == -1) { std::cerr << "file seek failed"; return PLDM_ERROR; } size_t currSize = response.size(); response.resize(currSize + length); auto filePos = reinterpret_cast<char*>(response.data()); filePos += currSize; rc = ::read(fd, filePos, length); if (rc == -1) { std::cerr << "file read failed"; return PLDM_ERROR; } if (rc != length) { std::cerr << "mismatch between number of characters to read and " << "the length read, LENGTH=" << length << " COUNT=" << rc << std::endl; return PLDM_ERROR; } } catch (const std::exception& e) { std::cerr << "GetPEL D-Bus call failed on PEL ID 0x" << std::hex << fileHandle << ", error = " << e.what() << "\n"; return PLDM_ERROR; } return PLDM_SUCCESS; } int PelHandler::writeFromMemory(uint32_t offset, uint32_t length, uint64_t address, oem_platform::Handler* /*oemPlatformHandler*/) { char tmpFile[] = "/tmp/pel.XXXXXX"; int fd = mkstemp(tmpFile); if (fd == -1) { std::cerr << "failed to create a temporary pel, ERROR=" << errno << "\n"; return PLDM_ERROR; } close(fd); fs::path path(tmpFile); auto rc = transferFileData(path, false, offset, length, address); if (rc == PLDM_SUCCESS) { rc = storePel(path.string()); } return rc; } int PelHandler::fileAck(uint8_t /*fileStatus*/) { static constexpr auto logObjPath = "/xyz/openbmc_project/logging"; static constexpr auto logInterface = "org.open_power.Logging.PEL"; auto& bus = pldm::utils::DBusHandler::getBus(); try { auto service = pldm::utils::DBusHandler().getService(logObjPath, logInterface); auto method = bus.new_method_call(service.c_str(), logObjPath, logInterface, "HostAck"); method.append(fileHandle); bus.call_noreply(method); } catch (const std::exception& e) { std::cerr << "HostAck D-Bus call failed on PEL ID 0x" << std::hex << fileHandle << ", error = " << e.what() << "\n"; return PLDM_ERROR; } return PLDM_SUCCESS; } int PelHandler::storePel(std::string&& pelFileName) { static constexpr auto logObjPath = "/xyz/openbmc_project/logging"; static constexpr auto logInterface = "xyz.openbmc_project.Logging.Create"; auto& bus = pldm::utils::DBusHandler::getBus(); try { auto service = pldm::utils::DBusHandler().getService(logObjPath, logInterface); using namespace sdbusplus::xyz::openbmc_project::Logging::server; std::map<std::string, std::string> addlData{}; auto severity = sdbusplus::xyz::openbmc_project::Logging::server::convertForMessage( detail::getEntryLevelFromPEL(pelFileName)); addlData.emplace("RAWPEL", std::move(pelFileName)); auto method = bus.new_method_call(service.c_str(), logObjPath, logInterface, "Create"); method.append("xyz.openbmc_project.Host.Error.Event", severity, addlData); bus.call_noreply(method); } catch (const std::exception& e) { std::cerr << "failed to make a d-bus call to PEL daemon, ERROR=" << e.what() << "\n"; return PLDM_ERROR; } return PLDM_SUCCESS; } int PelHandler::write(const char* buffer, uint32_t offset, uint32_t& length, oem_platform::Handler* /*oemPlatformHandler*/) { int rc = PLDM_SUCCESS; if (offset > 0) { std::cerr << "Offset is non zero \n"; return PLDM_ERROR; } char tmpFile[] = "/tmp/pel.XXXXXX"; auto fd = mkstemp(tmpFile); if (fd == -1) { std::cerr << "failed to create a temporary pel, ERROR=" << errno << "\n"; return PLDM_ERROR; } size_t written = 0; do { if ((rc = ::write(fd, buffer, length - written)) == -1) { break; } written += rc; buffer += rc; } while (rc && written < length); close(fd); if (rc == -1) { std::cerr << "file write failed, ERROR=" << errno << ", LENGTH=" << length << ", OFFSET=" << offset << "\n"; fs::remove(tmpFile); return PLDM_ERROR; } if (written == length) { fs::path path(tmpFile); rc = storePel(path.string()); if (rc != PLDM_SUCCESS) { std::cerr << "save PEL failed, ERROR = " << rc << "tmpFile = " << tmpFile << "\n"; } } return rc; } } // namespace responder } // namespace pldm <|endoftext|>
<commit_before>#include "PopulatingNextRightPointersInEachNodeII.hpp" #include <queue> using namespace std; void PopulatingNextRightPointersInEachNodeII::connect(TreeLinkNode* root) { if (root == nullptr) return; queue<TreeLinkNode*> q; q.push(root); while (!q.empty()) { int k = q.size(); // number of nodes in this level for (int i = 0; i < k; i++) { TreeLinkNode* front = q.front(); q.pop(); if (i + 1 < k) front->next = q.front(); if (front->left != nullptr) q.push(front->left); if (front->right != nullptr) q.push(front->right); } } } <commit_msg>Refine Problem 117. Populating Next Right Pointers in Each Node II<commit_after>#include "PopulatingNextRightPointersInEachNodeII.hpp" void PopulatingNextRightPointersInEachNodeII::connect(TreeLinkNode* root) { TreeLinkNode* leftMost = root; while (leftMost) { root = leftMost; // root points to the left most node which has child node while (root && !root->left && !root->right) root = root->next; if (!root) return; leftMost = root->left ? root->left : root->right; TreeLinkNode* cur = leftMost; while (root) { if (cur == root->left) { if (root->right) { cur->next = root->right; cur = cur->next; } root = root->next; } else if (cur == root->right) root = root->next; else { // cur is the child of the previous node of root if (!root->left && !root->right) { root = root->next; continue; } cur->next = root->left ? root->left : root->right; cur = cur->next; } } } } <|endoftext|>
<commit_before>// // Copyright (C) 2006-2013 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include <assert.h> // APPLICATION INCLUDES #include "mp/MpRtpOutputConnection.h" #include "mp/MprToNet.h" #include "mp/MpFlowGraphBase.h" #include "mp/MprEncode.h" #include "mp/MpIntResourceMsg.h" #include "os/OsLock.h" #include "os/OsSysLog.h" #ifdef INCLUDE_RTCP /* [ */ #include "rtcp/INetDispatch.h" #include "rtcp/IRTPDispatch.h" #include "rtcp/ISetSenderStatistics.h" #include "rtcp/IRTCPSession.h" #include "rtcp/IRTCPConnection.h" #endif /* INCLUDE_RTCP ] */ #include "os/OsDateTime.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor MpRtpOutputConnection::MpRtpOutputConnection(const UtlString& resourceName, MpConnectionID myID, IRTCPSession *piRTCPSession) : MpResource(resourceName, 1, 1, 0, 0) ,mpToNet(NULL) , mOutRtpStarted(FALSE) #ifdef INCLUDE_RTCP /* [ */ , mpiRTCPConnection(NULL) #endif /* INCLUDE_RTCP ] */ { // Save connection ID mConnectionId = myID; // Create ToNet resource mpToNet = new MprToNet(); mpToNet->setSRAdjustUSecs(12345); // DEBUG: just to test/demo this, set to 12.345 milliseconds #ifndef INCLUDE_RTCP /* [ */ { OsDateTime date; OsTime now; int ssrc; OsDateTime::getCurTime(date); date.cvtToTimeSinceEpoch(now); ssrc = now.seconds() ^ now.usecs(); mpToNet->setSSRC(ssrc); } #endif /* INCLUDE_RTCP ] */ ////////////////////////////////////////////////////////////////////////// // connect ToNet -> FromNet for RTP synchronization // TODO: mpToNet->setRtpPal(mpFromNet); } // Destructor MpRtpOutputConnection::~MpRtpOutputConnection() { if (mpToNet != NULL) delete mpToNet; } /* ============================ MANIPULATORS ============================== */ void MpRtpOutputConnection::setSockets(OsSocket& rRtpSocket, OsSocket& rRtcpSocket) { mpToNet->setSockets(rRtpSocket, rRtcpSocket); // TODO: mpFromNet->setDestIp(rRtpSocket); #ifdef INCLUDE_RTCP /* [ */ // Associate the RTCP socket to be used by the RTCP Render portion of the // connection to write reports to the network if(mpiRTCPConnection) { // OsSysLog::add(FAC_MP, PRI_DEBUG, "MpRtpOutputConnection::setSockets: call mpiRTCPConnection->StartRenderer(%p)", &rRtcpSocket); mpiRTCPConnection->StartRenderer(rRtcpSocket); } #endif /* INCLUDE_RTCP ] */ mOutRtpStarted = TRUE; } void MpRtpOutputConnection::releaseSockets() { #ifdef INCLUDE_RTCP /* [ */ // Terminate the RTCP Connection which shall include stopping the RTCP // Render so that no additional reports are emitted if(mpiRTCPConnection) { mpiRTCPConnection->StopRenderer(); } #endif /* INCLUDE_RTCP ] */ mpToNet->resetSockets(); mOutRtpStarted = FALSE; } #ifdef INCLUDE_RTCP /* [ */ void MpRtpOutputConnection::reassignSSRC(int iSSRC) { // Set the new SSRC mpToNet->setSSRC(iSSRC); return; } #endif /* INCLUDE_RTCP ] */ UtlBoolean MpRtpOutputConnection::handleMessage(MpResourceMsg& message) { UtlBoolean handled = FALSE; switch (message.getMsg()) { case MprToNet::MPRM_SET_SR_ADJUST_USECS: { handled = TRUE; MpIntResourceMsg *pMsg = (MpIntResourceMsg*)&message; mpToNet->setSRAdjustUSecs(pMsg->getData()); } break; default: handled = MpResource::handleMessage(message); } return(handled); } /* ============================ ACCESSORS ================================= */ OsStatus MpRtpOutputConnection::setFlowGraph(MpFlowGraphBase* pFlowGraph) { OsStatus status = MpResource::setFlowGraph(pFlowGraph); if(mpToNet) { mpToNet->setFlowGraph(pFlowGraph); } #ifdef INCLUDE_RTCP /* [ */ if (pFlowGraph != NULL) { // Get the RTCP Connection object for this flowgraph connection mpiRTCPConnection = pFlowGraph->getRTCPConnectionPtr(getConnectionId(), 'A', getStreamId()); OsSysLog::add(FAC_MP, PRI_DEBUG, "MpRtpOutConn::setFlowGraph(%p) CID=%d, TC=%p", pFlowGraph, getConnectionId(), mpiRTCPConnection); // Let's use the Connection interface to acquire the constituent interfaces // required for dispatching RTP and RTCP packets received from the network as // well as the statistics interface tabulating RTP packets going to the network. INetDispatch *piRTCPDispatch = NULL; IRTPDispatch *piRTPDispatch = NULL; ISetSenderStatistics *piRTPAccumulator = NULL; if(mpiRTCPConnection) { mpiRTCPConnection->GetDispatchInterfaces(&piRTCPDispatch, &piRTPDispatch, &piRTPAccumulator); } // Set the Statistics interface to be used by the RTP stream to increment // packet and octet statistics mpToNet->setRTPAccumulator(piRTPAccumulator); // The RTP Stream associated with the MprToNet object must have its SSRC ID // set to the value generated from the Session. mpToNet->setSSRC(pFlowGraph->getRTCPSessionPtr()->GetSSRC(getConnectionId(), 'A', getStreamId())); } #endif /* INCLUDE_RTCP ] */ return(status); } #ifdef INCLUDE_RTCP /* [ */ IRTCPConnection *MpRtpOutputConnection::getRTCPConnection(void) { return(mpiRTCPConnection); } #endif /* INCLUDE_RTCP ] */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ UtlBoolean MpRtpOutputConnection::processFrame() { return TRUE; } UtlBoolean MpRtpOutputConnection::connectInput(MpResource& rFrom, int fromPortIdx, int toPortIdx) { // TODO:: Move this to MprEncode and implement disconnect! UtlBoolean res = MpResource::connectInput(rFrom, fromPortIdx, toPortIdx); if (res) { assert(rFrom.getContainableType() == MprEncode::TYPE); MprEncode *pEncode = (MprEncode*)&rFrom; pEncode->setMyToNet(mpToNet); } return res; } /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ <commit_msg>Disable hard coded RTCP time offset on audio stream<commit_after>// // Copyright (C) 2006-2013 SIPez LLC. All rights reserved. // // Copyright (C) 2004-2007 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. All rights reserved. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ /////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include <assert.h> // APPLICATION INCLUDES #include "mp/MpRtpOutputConnection.h" #include "mp/MprToNet.h" #include "mp/MpFlowGraphBase.h" #include "mp/MprEncode.h" #include "mp/MpIntResourceMsg.h" #include "os/OsLock.h" #include "os/OsSysLog.h" #ifdef INCLUDE_RTCP /* [ */ #include "rtcp/INetDispatch.h" #include "rtcp/IRTPDispatch.h" #include "rtcp/ISetSenderStatistics.h" #include "rtcp/IRTCPSession.h" #include "rtcp/IRTCPConnection.h" #endif /* INCLUDE_RTCP ] */ #include "os/OsDateTime.h" // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // STATIC VARIABLE INITIALIZATIONS /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor MpRtpOutputConnection::MpRtpOutputConnection(const UtlString& resourceName, MpConnectionID myID, IRTCPSession *piRTCPSession) : MpResource(resourceName, 1, 1, 0, 0) ,mpToNet(NULL) , mOutRtpStarted(FALSE) #ifdef INCLUDE_RTCP /* [ */ , mpiRTCPConnection(NULL) #endif /* INCLUDE_RTCP ] */ { // Save connection ID mConnectionId = myID; // Create ToNet resource mpToNet = new MprToNet(); //mpToNet->setSRAdjustUSecs(12345); // DEBUG: just to test/demo this, set to 12.345 milliseconds #ifndef INCLUDE_RTCP /* [ */ { OsDateTime date; OsTime now; int ssrc; OsDateTime::getCurTime(date); date.cvtToTimeSinceEpoch(now); ssrc = now.seconds() ^ now.usecs(); mpToNet->setSSRC(ssrc); } #endif /* INCLUDE_RTCP ] */ ////////////////////////////////////////////////////////////////////////// // connect ToNet -> FromNet for RTP synchronization // TODO: mpToNet->setRtpPal(mpFromNet); } // Destructor MpRtpOutputConnection::~MpRtpOutputConnection() { if (mpToNet != NULL) delete mpToNet; } /* ============================ MANIPULATORS ============================== */ void MpRtpOutputConnection::setSockets(OsSocket& rRtpSocket, OsSocket& rRtcpSocket) { mpToNet->setSockets(rRtpSocket, rRtcpSocket); // TODO: mpFromNet->setDestIp(rRtpSocket); #ifdef INCLUDE_RTCP /* [ */ // Associate the RTCP socket to be used by the RTCP Render portion of the // connection to write reports to the network if(mpiRTCPConnection) { // OsSysLog::add(FAC_MP, PRI_DEBUG, "MpRtpOutputConnection::setSockets: call mpiRTCPConnection->StartRenderer(%p)", &rRtcpSocket); mpiRTCPConnection->StartRenderer(rRtcpSocket); } #endif /* INCLUDE_RTCP ] */ mOutRtpStarted = TRUE; } void MpRtpOutputConnection::releaseSockets() { #ifdef INCLUDE_RTCP /* [ */ // Terminate the RTCP Connection which shall include stopping the RTCP // Render so that no additional reports are emitted if(mpiRTCPConnection) { mpiRTCPConnection->StopRenderer(); } #endif /* INCLUDE_RTCP ] */ mpToNet->resetSockets(); mOutRtpStarted = FALSE; } #ifdef INCLUDE_RTCP /* [ */ void MpRtpOutputConnection::reassignSSRC(int iSSRC) { // Set the new SSRC mpToNet->setSSRC(iSSRC); return; } #endif /* INCLUDE_RTCP ] */ UtlBoolean MpRtpOutputConnection::handleMessage(MpResourceMsg& message) { UtlBoolean handled = FALSE; switch (message.getMsg()) { case MprToNet::MPRM_SET_SR_ADJUST_USECS: { handled = TRUE; MpIntResourceMsg *pMsg = (MpIntResourceMsg*)&message; mpToNet->setSRAdjustUSecs(pMsg->getData()); } break; default: handled = MpResource::handleMessage(message); } return(handled); } /* ============================ ACCESSORS ================================= */ OsStatus MpRtpOutputConnection::setFlowGraph(MpFlowGraphBase* pFlowGraph) { OsStatus status = MpResource::setFlowGraph(pFlowGraph); if(mpToNet) { mpToNet->setFlowGraph(pFlowGraph); } #ifdef INCLUDE_RTCP /* [ */ if (pFlowGraph != NULL) { // Get the RTCP Connection object for this flowgraph connection mpiRTCPConnection = pFlowGraph->getRTCPConnectionPtr(getConnectionId(), 'A', getStreamId()); OsSysLog::add(FAC_MP, PRI_DEBUG, "MpRtpOutConn::setFlowGraph(%p) CID=%d, TC=%p", pFlowGraph, getConnectionId(), mpiRTCPConnection); // Let's use the Connection interface to acquire the constituent interfaces // required for dispatching RTP and RTCP packets received from the network as // well as the statistics interface tabulating RTP packets going to the network. INetDispatch *piRTCPDispatch = NULL; IRTPDispatch *piRTPDispatch = NULL; ISetSenderStatistics *piRTPAccumulator = NULL; if(mpiRTCPConnection) { mpiRTCPConnection->GetDispatchInterfaces(&piRTCPDispatch, &piRTPDispatch, &piRTPAccumulator); } // Set the Statistics interface to be used by the RTP stream to increment // packet and octet statistics mpToNet->setRTPAccumulator(piRTPAccumulator); // The RTP Stream associated with the MprToNet object must have its SSRC ID // set to the value generated from the Session. mpToNet->setSSRC(pFlowGraph->getRTCPSessionPtr()->GetSSRC(getConnectionId(), 'A', getStreamId())); } #endif /* INCLUDE_RTCP ] */ return(status); } #ifdef INCLUDE_RTCP /* [ */ IRTCPConnection *MpRtpOutputConnection::getRTCPConnection(void) { return(mpiRTCPConnection); } #endif /* INCLUDE_RTCP ] */ /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ UtlBoolean MpRtpOutputConnection::processFrame() { return TRUE; } UtlBoolean MpRtpOutputConnection::connectInput(MpResource& rFrom, int fromPortIdx, int toPortIdx) { // TODO:: Move this to MprEncode and implement disconnect! UtlBoolean res = MpResource::connectInput(rFrom, fromPortIdx, toPortIdx); if (res) { assert(rFrom.getContainableType() == MprEncode::TYPE); MprEncode *pEncode = (MprEncode*)&rFrom; pEncode->setMyToNet(mpToNet); } return res; } /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ <|endoftext|>
<commit_before>/* poedit, a wxWindows i18n catalogs editor --------------- findframe.cpp Find frame (c) Vaclav Slavik, 2001 */ #ifdef __GNUG__ #pragma implementation #endif #include <wx/wxprec.h> #include <wx/xrc/xmlres.h> #include <wx/config.h> #include <wx/button.h> #include <wx/textctrl.h> #include <wx/listctrl.h> #include <wx/checkbox.h> #include "catalog.h" #include "findframe.h" BEGIN_EVENT_TABLE(FindFrame, wxDialog) EVT_BUTTON(XMLID("find_next"), FindFrame::OnNext) EVT_BUTTON(XMLID("find_prev"), FindFrame::OnPrev) EVT_BUTTON(wxID_CANCEL, FindFrame::OnCancel) EVT_TEXT(XMLID("string_to_find"), FindFrame::OnTextChange) EVT_CHECKBOX(-1, FindFrame::OnCheckbox) EVT_CLOSE(FindFrame::OnCancel) END_EVENT_TABLE() FindFrame::FindFrame(wxWindow *parent, wxListCtrl *list, Catalog *c) : m_listCtrl(list), m_catalog(c), m_position(-1) { wxPoint p(wxConfig::Get()->Read(_T("find_pos_x"), -1), wxConfig::Get()->Read(_T("find_pos_y"), -1)); wxTheXmlResource->LoadDialog(this, parent, _T("find_frame")); if (p.x != -1) Move(p); m_btnNext = XMLCTRL(*this, "find_next", wxButton); m_btnPrev = XMLCTRL(*this, "find_prev", wxButton); XMLCTRL(*this, "in_orig", wxCheckBox)->SetValue( wxConfig::Get()->Read(_T("find_in_orig"), (long)true)); XMLCTRL(*this, "in_trans", wxCheckBox)->SetValue( wxConfig::Get()->Read(_T("find_in_trans"), (long)true)); XMLCTRL(*this, "case_sensitive", wxCheckBox)->SetValue( wxConfig::Get()->Read(_T("find_case_sensitive"), (long)false)); } FindFrame::~FindFrame() { wxConfig::Get()->Write(_T("find_pos_x"), (long)GetPosition().x); wxConfig::Get()->Write(_T("find_pos_y"), (long)GetPosition().y); wxConfig::Get()->Write(_T("find_in_orig"), XMLCTRL(*this, "in_orig", wxCheckBox)->GetValue()); wxConfig::Get()->Write(_T("find_in_trans"), XMLCTRL(*this, "in_trans", wxCheckBox)->GetValue()); wxConfig::Get()->Write(_T("find_case_sensitive"), XMLCTRL(*this, "case_sensitive", wxCheckBox)->GetValue()); } void FindFrame::Reset(Catalog *c) { m_catalog = c; m_position = -1; m_btnPrev->Enable(!!m_text); m_btnNext->Enable(!!m_text); } void FindFrame::OnCancel(wxCommandEvent &event) { Destroy(); } void FindFrame::OnTextChange(wxCommandEvent &event) { m_text = XMLCTRL(*this, "string_to_find", wxTextCtrl)->GetValue(); Reset(m_catalog); } void FindFrame::OnCheckbox(wxCommandEvent &event) { Reset(m_catalog); } void FindFrame::OnPrev(wxCommandEvent &event) { if (!DoFind(-1)) m_btnPrev->Enable(false); else m_btnNext->Enable(true); } void FindFrame::OnNext(wxCommandEvent &event) { if (!DoFind(+1)) m_btnNext->Enable(false); else m_btnPrev->Enable(true); } bool FindFrame::DoFind(int dir) { int cnt = m_listCtrl->GetItemCount(); bool inStr = XMLCTRL(*this, "in_orig", wxCheckBox)->GetValue(); bool inTrans = XMLCTRL(*this, "in_trans", wxCheckBox)->GetValue(); bool caseSens = XMLCTRL(*this, "case_sensitive", wxCheckBox)->GetValue(); int posOrig = m_position; bool found = false; wxString textc; wxString text(m_text); if (!caseSens) text.MakeLower(); printf("looking for: '%s'\n", text.c_str()); m_position += dir; while (m_position >= 0 && m_position < cnt) { CatalogData &dt = (*m_catalog)[m_listCtrl->GetItemData(m_position)]; if (inStr) { #if wxUSE_UNICODE textc = dt.GetString(); #else textc = wxString(dt.GetString().wc_str(wxConvUTF8), wxConvLocal); #endif if (!caseSens) textc.MakeLower(); if (textc.Contains(text)) { found = TRUE; break; } } if (inTrans) { #if wxUSE_UNICODE textc = dt.GetTranslation(); #else textc = wxString(dt.GetTranslation().wc_str(wxConvUTF8), wxConvLocal); #endif if (!caseSens) textc.MakeLower(); printf(" is?: '%s'\n", textc.c_str()); if (textc.Contains(text)) { found = TRUE; break; } } m_position += dir; } if (found) { m_listCtrl->SetItemState(m_position, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED); m_listCtrl->EnsureVisible(m_position); return true; } m_position = posOrig; return false; } <commit_msg>got rid of debug printfs<commit_after>/* poedit, a wxWindows i18n catalogs editor --------------- findframe.cpp Find frame (c) Vaclav Slavik, 2001 */ #ifdef __GNUG__ #pragma implementation #endif #include <wx/wxprec.h> #include <wx/xrc/xmlres.h> #include <wx/config.h> #include <wx/button.h> #include <wx/textctrl.h> #include <wx/listctrl.h> #include <wx/checkbox.h> #include "catalog.h" #include "findframe.h" BEGIN_EVENT_TABLE(FindFrame, wxDialog) EVT_BUTTON(XMLID("find_next"), FindFrame::OnNext) EVT_BUTTON(XMLID("find_prev"), FindFrame::OnPrev) EVT_BUTTON(wxID_CANCEL, FindFrame::OnCancel) EVT_TEXT(XMLID("string_to_find"), FindFrame::OnTextChange) EVT_CHECKBOX(-1, FindFrame::OnCheckbox) EVT_CLOSE(FindFrame::OnCancel) END_EVENT_TABLE() FindFrame::FindFrame(wxWindow *parent, wxListCtrl *list, Catalog *c) : m_listCtrl(list), m_catalog(c), m_position(-1) { wxPoint p(wxConfig::Get()->Read(_T("find_pos_x"), -1), wxConfig::Get()->Read(_T("find_pos_y"), -1)); wxTheXmlResource->LoadDialog(this, parent, _T("find_frame")); if (p.x != -1) Move(p); m_btnNext = XMLCTRL(*this, "find_next", wxButton); m_btnPrev = XMLCTRL(*this, "find_prev", wxButton); XMLCTRL(*this, "in_orig", wxCheckBox)->SetValue( wxConfig::Get()->Read(_T("find_in_orig"), (long)true)); XMLCTRL(*this, "in_trans", wxCheckBox)->SetValue( wxConfig::Get()->Read(_T("find_in_trans"), (long)true)); XMLCTRL(*this, "case_sensitive", wxCheckBox)->SetValue( wxConfig::Get()->Read(_T("find_case_sensitive"), (long)false)); } FindFrame::~FindFrame() { wxConfig::Get()->Write(_T("find_pos_x"), (long)GetPosition().x); wxConfig::Get()->Write(_T("find_pos_y"), (long)GetPosition().y); wxConfig::Get()->Write(_T("find_in_orig"), XMLCTRL(*this, "in_orig", wxCheckBox)->GetValue()); wxConfig::Get()->Write(_T("find_in_trans"), XMLCTRL(*this, "in_trans", wxCheckBox)->GetValue()); wxConfig::Get()->Write(_T("find_case_sensitive"), XMLCTRL(*this, "case_sensitive", wxCheckBox)->GetValue()); } void FindFrame::Reset(Catalog *c) { m_catalog = c; m_position = -1; m_btnPrev->Enable(!!m_text); m_btnNext->Enable(!!m_text); } void FindFrame::OnCancel(wxCommandEvent &event) { Destroy(); } void FindFrame::OnTextChange(wxCommandEvent &event) { m_text = XMLCTRL(*this, "string_to_find", wxTextCtrl)->GetValue(); Reset(m_catalog); } void FindFrame::OnCheckbox(wxCommandEvent &event) { Reset(m_catalog); } void FindFrame::OnPrev(wxCommandEvent &event) { if (!DoFind(-1)) m_btnPrev->Enable(false); else m_btnNext->Enable(true); } void FindFrame::OnNext(wxCommandEvent &event) { if (!DoFind(+1)) m_btnNext->Enable(false); else m_btnPrev->Enable(true); } bool FindFrame::DoFind(int dir) { int cnt = m_listCtrl->GetItemCount(); bool inStr = XMLCTRL(*this, "in_orig", wxCheckBox)->GetValue(); bool inTrans = XMLCTRL(*this, "in_trans", wxCheckBox)->GetValue(); bool caseSens = XMLCTRL(*this, "case_sensitive", wxCheckBox)->GetValue(); int posOrig = m_position; bool found = false; wxString textc; wxString text(m_text); if (!caseSens) text.MakeLower(); m_position += dir; while (m_position >= 0 && m_position < cnt) { CatalogData &dt = (*m_catalog)[m_listCtrl->GetItemData(m_position)]; if (inStr) { #if wxUSE_UNICODE textc = dt.GetString(); #else textc = wxString(dt.GetString().wc_str(wxConvUTF8), wxConvLocal); #endif if (!caseSens) textc.MakeLower(); if (textc.Contains(text)) { found = TRUE; break; } } if (inTrans) { #if wxUSE_UNICODE textc = dt.GetTranslation(); #else textc = wxString(dt.GetTranslation().wc_str(wxConvUTF8), wxConvLocal); #endif if (!caseSens) textc.MakeLower(); if (textc.Contains(text)) { found = TRUE; break; } } m_position += dir; } if (found) { m_listCtrl->SetItemState(m_position, wxLIST_STATE_FOCUSED, wxLIST_STATE_FOCUSED); m_listCtrl->EnsureVisible(m_position); return true; } m_position = posOrig; return false; } <|endoftext|>
<commit_before><commit_msg>deleted "ef bb bf" characters<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: displayinfo.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: rt $ $Date: 2005-09-09 00:02:17 $ * * 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 _SDR_CONTACT_DISPLAYINFO_HXX #include <svx/sdr/contact/displayinfo.hxx> #endif #ifndef _SV_OUTDEV_HXX #include <vcl/outdev.hxx> #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #ifndef _SVDOBJ_HXX #include <svdobj.hxx> #endif #ifndef _SV_GDIMTF_HXX #include <vcl/gdimtf.hxx> #endif #ifndef _SVDPAGV_HXX #include <svdpagv.hxx> #endif #define ALL_GHOSTED_DRAWMODES (DRAWMODE_GHOSTEDLINE|DRAWMODE_GHOSTEDFILL|DRAWMODE_GHOSTEDTEXT|DRAWMODE_GHOSTEDBITMAP|DRAWMODE_GHOSTEDGRADIENT) ////////////////////////////////////////////////////////////////////////////// namespace sdr { namespace contact { // This uses Application::AnyInput() and may change mbContinuePaint // to interrupt the paint void DisplayInfo::CheckContinuePaint() { // #111111# // INPUT_PAINT and INPUT_TIMER removed again since this leads to // problems under Linux and Solaris when painting slow objects // (e.g. bitmaps) // #114335# // INPUT_OTHER removed too, leads to problems with added controls // from the form layer. if(Application::AnyInput(INPUT_KEYBOARD)) { mbContinuePaint = sal_False; } } DisplayInfo::DisplayInfo(SdrPageView* pPageView) : mpPageView(pPageView), mpProcessedPage(0L), // init layer info with all bits set to draw everything on default maProcessLayers(sal_True), mpLastDisplayInfo(0L), mpOutputDevice(0L), mpExtOutputDevice(0L), mpPaintInfoRec(0L), mpRootVOC(0L), mbControlLayerPainting(sal_False), mbPagePainting(sal_True), mbGhostedDrawModeActive(sal_False), mbBufferingAllowed(sal_True), mbContinuePaint(sal_True), mbMasterPagePainting(sal_False), mbPreRenderingAllowed(sal_False) { } DisplayInfo::~DisplayInfo() { SetProcessedPage( 0L ); } // access to ProcessedPage, write for internal use only. void DisplayInfo::SetProcessedPage(SdrPage* pNew) { if(pNew != mpProcessedPage) { mpProcessedPage = pNew; if(mpPageView) { if( pNew == NULL ) { // DisplayInfo needs to be reset at PageView if set since DisplayInfo is no longer valid if(mpPageView && mpPageView->GetCurrentPaintingDisplayInfo()) { DBG_ASSERT( mpPageView->GetCurrentPaintingDisplayInfo() == this, "DisplayInfo::~DisplayInfo() : stack error!" ); // restore remembered DisplayInfo to build a stack, or delete mpPageView->SetCurrentPaintingDisplayInfo(mpLastDisplayInfo); } } else { // rescue current mpLastDisplayInfo = mpPageView->GetCurrentPaintingDisplayInfo(); // set at PageView when a page is set mpPageView->SetCurrentPaintingDisplayInfo(this); } } } } const SdrPage* DisplayInfo::GetProcessedPage() const { return mpProcessedPage; } // Access to LayerInfos (which layers to proccess) void DisplayInfo::SetProcessLayers(const SetOfByte& rSet) { maProcessLayers = rSet; } const SetOfByte& DisplayInfo::GetProcessLayers() const { return maProcessLayers; } // access to ExtendedOutputDevice void DisplayInfo::SetExtendedOutputDevice(XOutputDevice* pExtOut) { if(mpExtOutputDevice != pExtOut) { mpExtOutputDevice = pExtOut; } } XOutputDevice* DisplayInfo::GetExtendedOutputDevice() const { return mpExtOutputDevice; } // access to PaintInfoRec void DisplayInfo::SetPaintInfoRec(SdrPaintInfoRec* pInfoRec) { if(mpPaintInfoRec != pInfoRec) { mpPaintInfoRec = pInfoRec; } } SdrPaintInfoRec* DisplayInfo::GetPaintInfoRec() const { return mpPaintInfoRec; } // access to OutputDevice void DisplayInfo::SetOutputDevice(OutputDevice* pOutDev) { if(mpOutputDevice != pOutDev) { mpOutputDevice = pOutDev; } } OutputDevice* DisplayInfo::GetOutputDevice() const { return mpOutputDevice; } // access to RedrawArea void DisplayInfo::SetRedrawArea(const Region& rRegion) { maRedrawArea = rRegion; } const Region& DisplayInfo::GetRedrawArea() const { return maRedrawArea; } // Is OutDev a printer? sal_Bool DisplayInfo::OutputToPrinter() const { if(mpOutputDevice && OUTDEV_PRINTER == mpOutputDevice->GetOutDevType()) { return sal_True; } return sal_False; } // Is OutDev a window? sal_Bool DisplayInfo::OutputToWindow() const { if(mpOutputDevice && OUTDEV_WINDOW == mpOutputDevice->GetOutDevType()) { return sal_True; } return sal_False; } // Is OutDev a VirtualDevice? sal_Bool DisplayInfo::OutputToVirtualDevice() const { if(mpOutputDevice && OUTDEV_VIRDEV == mpOutputDevice->GetOutDevType()) { return sal_True; } return sal_False; } // Is OutDev a recording MetaFile? sal_Bool DisplayInfo::OutputToRecordingMetaFile() const { if(mpOutputDevice) { GDIMetaFile* pMetaFile = mpOutputDevice->GetConnectMetaFile(); if(pMetaFile) { sal_Bool bRecording = pMetaFile->IsRecord() && !pMetaFile->IsPause(); return bRecording; } } return sal_False; } void DisplayInfo::SetControlLayerPainting(sal_Bool bDoPaint) { if(mbControlLayerPainting != bDoPaint) { mbControlLayerPainting = bDoPaint; } } sal_Bool DisplayInfo::GetControlLayerPainting() const { return mbControlLayerPainting; } void DisplayInfo::SetPagePainting(sal_Bool bDoPaint) { if(mbPagePainting != bDoPaint) { mbPagePainting = bDoPaint; } } sal_Bool DisplayInfo::GetPagePainting() const { return mbPagePainting; } // Access to svtools::ColorConfig const svtools::ColorConfig& DisplayInfo::GetColorConfig() const { return maColorConfig; } sal_uInt32 DisplayInfo::GetOriginalDrawMode() const { // return DrawMode without ghosted stuff if(mpOutputDevice) { return (mpOutputDevice->GetDrawMode() & ~ALL_GHOSTED_DRAWMODES); } return 0L; } sal_uInt32 DisplayInfo::GetCurrentDrawMode() const { if(mpOutputDevice) { return mpOutputDevice->GetDrawMode(); } return 0L; } void DisplayInfo::ClearGhostedDrawMode() { if(mpOutputDevice) { mpOutputDevice->SetDrawMode(mpOutputDevice->GetDrawMode() & ~ALL_GHOSTED_DRAWMODES); } mbGhostedDrawModeActive = sal_False; } void DisplayInfo::SetGhostedDrawMode() { if(mpOutputDevice) { mpOutputDevice->SetDrawMode(mpOutputDevice->GetDrawMode() | ALL_GHOSTED_DRAWMODES); } mbGhostedDrawModeActive = sal_True; } sal_Bool DisplayInfo::IsGhostedDrawModeActive() const { return mbGhostedDrawModeActive; } // access to buffering allowed flag void DisplayInfo::SetBufferingAllowed(sal_Bool bNew) { if(mbBufferingAllowed != bNew) { mbBufferingAllowed = bNew; } } sal_Bool DisplayInfo::IsBufferingAllowed() const { return mbBufferingAllowed; } // Check if painting should be continued. If not, return from paint // as soon as possible. sal_Bool DisplayInfo::DoContinuePaint() { if(mbContinuePaint && mpOutputDevice && OUTDEV_WINDOW == mpOutputDevice->GetOutDevType()) { CheckContinuePaint(); } return mbContinuePaint; } sal_Bool DisplayInfo::GetMasterPagePainting() const { return mbMasterPagePainting; } void DisplayInfo::SetMasterPagePainting(sal_Bool bNew) { if(mbMasterPagePainting != bNew) { mbMasterPagePainting = bNew; } } // access to PreRendering flag sal_Bool DisplayInfo::IsPreRenderingAllowed() const { return mbPreRenderingAllowed; } void DisplayInfo::SetPreRenderingAllowed(sal_Bool bNew) { if(mbPreRenderingAllowed != bNew) { mbPreRenderingAllowed = bNew; } } // Infos about draft painting. These may get bitfield members later. sal_Bool DisplayInfo::IsDraftText() const { return (0 != (mpPaintInfoRec->nPaintMode & SDRPAINTMODE_DRAFTTEXT)); } sal_Bool DisplayInfo::IsDraftGraphic() const { return (0 != (mpPaintInfoRec->nPaintMode & SDRPAINTMODE_DRAFTGRAF)); } sal_Bool DisplayInfo::IsDraftLine() const { return (0 != (mpPaintInfoRec->nPaintMode & SDRPAINTMODE_DRAFTLINE)); } sal_Bool DisplayInfo::IsDraftFill() const { return (0 != (mpPaintInfoRec->nPaintMode & SDRPAINTMODE_DRAFTFILL)); } sal_Bool DisplayInfo::IsHideDraftGraphic() const { return (0 != (mpPaintInfoRec->nPaintMode & SDRPAINTMODE_HIDEDRAFTGRAF)); } } // end of namespace contact } // end of namespace sdr ////////////////////////////////////////////////////////////////////////////// // eof <commit_msg>INTEGRATION: CWS warnings01 (1.8.220); FILE MERGED 2006/02/21 16:41:10 aw 1.8.220.1: #i55991# Adaptions to warning free code<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: displayinfo.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: hr $ $Date: 2006-06-19 16:25:17 $ * * 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 _SDR_CONTACT_DISPLAYINFO_HXX #include <svx/sdr/contact/displayinfo.hxx> #endif #ifndef _SV_OUTDEV_HXX #include <vcl/outdev.hxx> #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #ifndef _SVDOBJ_HXX #include <svdobj.hxx> #endif #ifndef _SV_GDIMTF_HXX #include <vcl/gdimtf.hxx> #endif #ifndef _SVDPAGV_HXX #include <svdpagv.hxx> #endif #define ALL_GHOSTED_DRAWMODES (DRAWMODE_GHOSTEDLINE|DRAWMODE_GHOSTEDFILL|DRAWMODE_GHOSTEDTEXT|DRAWMODE_GHOSTEDBITMAP|DRAWMODE_GHOSTEDGRADIENT) ////////////////////////////////////////////////////////////////////////////// namespace sdr { namespace contact { // This uses Application::AnyInput() and may change mbContinuePaint // to interrupt the paint void DisplayInfo::CheckContinuePaint() { // #111111# // INPUT_PAINT and INPUT_TIMER removed again since this leads to // problems under Linux and Solaris when painting slow objects // (e.g. bitmaps) // #114335# // INPUT_OTHER removed too, leads to problems with added controls // from the form layer. if(Application::AnyInput(INPUT_KEYBOARD)) { mbContinuePaint = sal_False; } } DisplayInfo::DisplayInfo(SdrPageView* pPageView) : mpPageView(pPageView), mpProcessedPage(0L), mpLastDisplayInfo(0L), maProcessLayers(sal_True), // init layer info with all bits set to draw everything on default mpOutputDevice(0L), mpExtOutputDevice(0L), mpPaintInfoRec(0L), mpRootVOC(0L), mbControlLayerPainting(sal_False), mbPagePainting(sal_True), mbGhostedDrawModeActive(sal_False), mbBufferingAllowed(sal_True), mbContinuePaint(sal_True), mbMasterPagePainting(sal_False), mbPreRenderingAllowed(sal_False) { } DisplayInfo::~DisplayInfo() { SetProcessedPage( 0L ); } // access to ProcessedPage, write for internal use only. void DisplayInfo::SetProcessedPage(SdrPage* pNew) { if(pNew != mpProcessedPage) { mpProcessedPage = pNew; if(mpPageView) { if( pNew == NULL ) { // DisplayInfo needs to be reset at PageView if set since DisplayInfo is no longer valid if(mpPageView && mpPageView->GetCurrentPaintingDisplayInfo()) { DBG_ASSERT( mpPageView->GetCurrentPaintingDisplayInfo() == this, "DisplayInfo::~DisplayInfo() : stack error!" ); // restore remembered DisplayInfo to build a stack, or delete mpPageView->SetCurrentPaintingDisplayInfo(mpLastDisplayInfo); } } else { // rescue current mpLastDisplayInfo = mpPageView->GetCurrentPaintingDisplayInfo(); // set at PageView when a page is set mpPageView->SetCurrentPaintingDisplayInfo(this); } } } } const SdrPage* DisplayInfo::GetProcessedPage() const { return mpProcessedPage; } // Access to LayerInfos (which layers to proccess) void DisplayInfo::SetProcessLayers(const SetOfByte& rSet) { maProcessLayers = rSet; } const SetOfByte& DisplayInfo::GetProcessLayers() const { return maProcessLayers; } // access to ExtendedOutputDevice void DisplayInfo::SetExtendedOutputDevice(XOutputDevice* pExtOut) { if(mpExtOutputDevice != pExtOut) { mpExtOutputDevice = pExtOut; } } XOutputDevice* DisplayInfo::GetExtendedOutputDevice() const { return mpExtOutputDevice; } // access to PaintInfoRec void DisplayInfo::SetPaintInfoRec(SdrPaintInfoRec* pInfoRec) { if(mpPaintInfoRec != pInfoRec) { mpPaintInfoRec = pInfoRec; } } SdrPaintInfoRec* DisplayInfo::GetPaintInfoRec() const { return mpPaintInfoRec; } // access to OutputDevice void DisplayInfo::SetOutputDevice(OutputDevice* pOutDev) { if(mpOutputDevice != pOutDev) { mpOutputDevice = pOutDev; } } OutputDevice* DisplayInfo::GetOutputDevice() const { return mpOutputDevice; } // access to RedrawArea void DisplayInfo::SetRedrawArea(const Region& rRegion) { maRedrawArea = rRegion; } const Region& DisplayInfo::GetRedrawArea() const { return maRedrawArea; } // Is OutDev a printer? sal_Bool DisplayInfo::OutputToPrinter() const { if(mpOutputDevice && OUTDEV_PRINTER == mpOutputDevice->GetOutDevType()) { return sal_True; } return sal_False; } // Is OutDev a window? sal_Bool DisplayInfo::OutputToWindow() const { if(mpOutputDevice && OUTDEV_WINDOW == mpOutputDevice->GetOutDevType()) { return sal_True; } return sal_False; } // Is OutDev a VirtualDevice? sal_Bool DisplayInfo::OutputToVirtualDevice() const { if(mpOutputDevice && OUTDEV_VIRDEV == mpOutputDevice->GetOutDevType()) { return sal_True; } return sal_False; } // Is OutDev a recording MetaFile? sal_Bool DisplayInfo::OutputToRecordingMetaFile() const { if(mpOutputDevice) { GDIMetaFile* pMetaFile = mpOutputDevice->GetConnectMetaFile(); if(pMetaFile) { sal_Bool bRecording = pMetaFile->IsRecord() && !pMetaFile->IsPause(); return bRecording; } } return sal_False; } void DisplayInfo::SetControlLayerPainting(sal_Bool bDoPaint) { if(mbControlLayerPainting != bDoPaint) { mbControlLayerPainting = bDoPaint; } } sal_Bool DisplayInfo::GetControlLayerPainting() const { return mbControlLayerPainting; } void DisplayInfo::SetPagePainting(sal_Bool bDoPaint) { if(mbPagePainting != bDoPaint) { mbPagePainting = bDoPaint; } } sal_Bool DisplayInfo::GetPagePainting() const { return mbPagePainting; } // Access to svtools::ColorConfig const svtools::ColorConfig& DisplayInfo::GetColorConfig() const { return maColorConfig; } sal_uInt32 DisplayInfo::GetOriginalDrawMode() const { // return DrawMode without ghosted stuff if(mpOutputDevice) { return (mpOutputDevice->GetDrawMode() & ~ALL_GHOSTED_DRAWMODES); } return 0L; } sal_uInt32 DisplayInfo::GetCurrentDrawMode() const { if(mpOutputDevice) { return mpOutputDevice->GetDrawMode(); } return 0L; } void DisplayInfo::ClearGhostedDrawMode() { if(mpOutputDevice) { mpOutputDevice->SetDrawMode(mpOutputDevice->GetDrawMode() & ~ALL_GHOSTED_DRAWMODES); } mbGhostedDrawModeActive = sal_False; } void DisplayInfo::SetGhostedDrawMode() { if(mpOutputDevice) { mpOutputDevice->SetDrawMode(mpOutputDevice->GetDrawMode() | ALL_GHOSTED_DRAWMODES); } mbGhostedDrawModeActive = sal_True; } sal_Bool DisplayInfo::IsGhostedDrawModeActive() const { return mbGhostedDrawModeActive; } // access to buffering allowed flag void DisplayInfo::SetBufferingAllowed(sal_Bool bNew) { if(mbBufferingAllowed != bNew) { mbBufferingAllowed = bNew; } } sal_Bool DisplayInfo::IsBufferingAllowed() const { return mbBufferingAllowed; } // Check if painting should be continued. If not, return from paint // as soon as possible. sal_Bool DisplayInfo::DoContinuePaint() { if(mbContinuePaint && mpOutputDevice && OUTDEV_WINDOW == mpOutputDevice->GetOutDevType()) { CheckContinuePaint(); } return mbContinuePaint; } sal_Bool DisplayInfo::GetMasterPagePainting() const { return mbMasterPagePainting; } void DisplayInfo::SetMasterPagePainting(sal_Bool bNew) { if(mbMasterPagePainting != bNew) { mbMasterPagePainting = bNew; } } // access to PreRendering flag sal_Bool DisplayInfo::IsPreRenderingAllowed() const { return mbPreRenderingAllowed; } void DisplayInfo::SetPreRenderingAllowed(sal_Bool bNew) { if(mbPreRenderingAllowed != bNew) { mbPreRenderingAllowed = bNew; } } // Infos about draft painting. These may get bitfield members later. sal_Bool DisplayInfo::IsDraftText() const { return (0 != (mpPaintInfoRec->nPaintMode & SDRPAINTMODE_DRAFTTEXT)); } sal_Bool DisplayInfo::IsDraftGraphic() const { return (0 != (mpPaintInfoRec->nPaintMode & SDRPAINTMODE_DRAFTGRAF)); } sal_Bool DisplayInfo::IsDraftLine() const { return (0 != (mpPaintInfoRec->nPaintMode & SDRPAINTMODE_DRAFTLINE)); } sal_Bool DisplayInfo::IsDraftFill() const { return (0 != (mpPaintInfoRec->nPaintMode & SDRPAINTMODE_DRAFTFILL)); } sal_Bool DisplayInfo::IsHideDraftGraphic() const { return (0 != (mpPaintInfoRec->nPaintMode & SDRPAINTMODE_HIDEDRAFTGRAF)); } } // end of namespace contact } // end of namespace sdr ////////////////////////////////////////////////////////////////////////////// // eof <|endoftext|>
<commit_before>#include <cstddef> #include <vector> #include "aim.hpp" // Algorithm to be tested std::size_t largest_area(std::vector<std::vector<bool>> const& matrix) { std::size_t max_area = 0; std::vector<std::size_t> last_start(matrix[0].size(), 0); for (std::size_t idx {} ; idx != matrix.size() ; ++idx) { // for all i in [|0, matrix[0].size()-1|] // for all j such as last_start[i] <= j < idx // matrix[j][i] is true // update starts for (std::size_t i {} ; i != last_start.size() ; ++i) { if (! matrix[idx][i]) { last_start[i] = idx +1; } else if (last_start[i] >= idx) { last_start[i] = idx; } } // compute bars for (std::size_t i {} ; i != last_start.size() ; ++i) { if (last_start[i] > idx) { continue; } std::size_t starts_at = i; std::size_t ends_at = i; while (starts_at > 0 && last_start[starts_at-1] <= last_start[i]) { --starts_at; } while (ends_at+1 < last_start.size() && last_start[ends_at+1] <= last_start[i]) { ++ends_at; } max_area = std::max(max_area, (ends_at-starts_at+1)*(idx-last_start[i]+1)); } } return max_area; } <commit_msg>[maximal-rectangle] Add some comments<commit_after>#include <cstddef> #include <vector> #include "aim.hpp" // Algorithm to be tested std::size_t largest_area(std::vector<std::vector<bool>> const& matrix) { // Complexity in average: // Space: O(M) // Time : O(N * M^2) // With M = matrix[0].size() // and N = matrix.size() // This solution is inspired from the resolution // used by histogram problem // It can be enhanced and based itself upon histogram solution // in order to decrease its time complexity to O(N * M) std::size_t max_area = 0; std::vector<std::size_t> last_start(matrix[0].size(), 0); for (std::size_t idx {} ; idx != matrix.size() ; ++idx) { // for all i in [|0, matrix[0].size()-1|] // for all j such as last_start[i] <= j < idx // matrix[j][i] is true // update starts for (std::size_t i {} ; i != last_start.size() ; ++i) { if (! matrix[idx][i]) { last_start[i] = idx +1; } else if (last_start[i] >= idx) { last_start[i] = idx; } } // compute bars for (std::size_t i {} ; i != last_start.size() ; ++i) { if (last_start[i] > idx) { continue; } std::size_t starts_at = i; std::size_t ends_at = i; while (starts_at > 0 && last_start[starts_at-1] <= last_start[i]) { --starts_at; } while (ends_at+1 < last_start.size() && last_start[ends_at+1] <= last_start[i]) { ++ends_at; } max_area = std::max(max_area, (ends_at-starts_at+1)*(idx-last_start[i]+1)); } } return max_area; } <|endoftext|>
<commit_before>/** * @file src/mod_cardreader.cpp * @brief * * @addtogroup * @{ */ #include "mod_cardreader.h" #if MOD_CARDREADER #include <stdio.h> #include <string.h> #include <stdlib.h> #include "ch_tools.h" #include "chprintf.h" #include "qhal.h" #include "module_init_cpp.h" #include "watchdog.h" #include "board_buttons.h" #if HAL_USE_SDC #else #error "SDC driver must be specified" #endif template <> tmb_musicplayer::ModuleCardreader tmb_musicplayer::ModuleCardreaderSingelton::instance = tmb_musicplayer::ModuleCardreader(); namespace tmb_musicplayer { ModuleCardreader::ModuleCardreader() { } ModuleCardreader::~ModuleCardreader() { } void ModuleCardreader::Init() { } void ModuleCardreader::Start() { BaseClass::Start(); } void ModuleCardreader::Shutdown() { BaseClass::Shutdown(); } void ModuleCardreader::RegisterListener(chibios_rt::EvtListener* listener, eventmask_t mask) { m_evtSource.registerMask(listener, mask); } void ModuleCardreader::UnregisterListener(chibios_rt::EvtListener* listener) { m_evtSource.unregister(listener); } void ModuleCardreader::ThreadMain() { chRegSetThreadName("cardReader"); chibios_rt::EvtListener carddetectEvtListener; #if HAL_USE_BUTTONS BoardButtons::BtnCardDetect.RegisterListener(&carddetectEvtListener, EVENT_MASK(0)); #endif //if (m_carddetectButton->GetState() == false) { OnCardInserted(); } while (!chThdShouldTerminateX()) { eventmask_t evt = chEvtWaitAny(ALL_EVENTS); if (evt & EVENT_MASK(0)) { eventflags_t flags = carddetectEvtListener.getAndClearFlags(); if (flags & Button::Up) { OnCardInserted(); } else if (flags & Button::Down) { OnCardRemoved(); } } } OnCardRemoved(); #if HAL_USE_BUTTONS BoardButtons::BtnCardDetect.UnregisterListener(&carddetectEvtListener); #endif } void ModuleCardreader::OnCardRemoved() { chprintf(DEBUG_CANNEL, "Memory card removed.\r\n"); UnmountFilesystem(); m_evtSource.broadcastFlags(FilesystemUnmounted); SetCardDetectLed(false); } void ModuleCardreader::OnCardInserted() { chprintf(DEBUG_CANNEL, "Memory card inserted.\r\n"); if (MountFilesystem() == true) { m_evtSource.broadcastFlags(FilesystemMounted); SetCardDetectLed(true); } } bool ModuleCardreader::MountFilesystem() { if (sdcConnect(&SDCD1) == HAL_SUCCESS) { FRESULT err; err = f_mount(&m_filesystem, "/mount/", 1); if (err != FR_OK) { chprintf(DEBUG_CANNEL, "FS: f_mount() failed. Is the SD card inserted?\r\n"); PrintFilesystemError(DEBUG_CANNEL, err); return false; } chprintf(DEBUG_CANNEL, "FS: f_mount() succeeded\r\n"); return true; } chprintf(DEBUG_CANNEL, "Failed to connect sdc card.\r\n"); return false; } bool ModuleCardreader::UnmountFilesystem() { FRESULT err; err = f_mount(NULL, "/mount/", 0); sdcDisconnect(&SDCD1); if (err != FR_OK) { chprintf(DEBUG_CANNEL, "FS: f_mount() unmount failed\r\n"); PrintFilesystemError(DEBUG_CANNEL, err); return false; } chprintf(DEBUG_CANNEL, "FS: f_mount() unmount succeeded\r\n"); return true; } void ModuleCardreader::SetCardDetectLed(bool on) { #if HAL_USE_LED if (on == true) { ledOn(LED_CARDDETECT); } else { ledOff(LED_CARDDETECT); } #endif /* HAL_USE_LED */ } bool ModuleCardreader::CommandCD(const char* path) { DIR dir; FRESULT res = f_opendir(&dir, path); if (res == FR_OK) { return true; } chprintf(DEBUG_CANNEL, "FS: f_opendir \"%s\" failed\r\n", path); PrintFilesystemError(DEBUG_CANNEL, res); return false; } bool ModuleCardreader::CommandFind(DIR* dp, FILINFO* fno, const char* path, const char* pattern) { FRESULT res = f_findfirst(dp, fno, path, pattern); if (res == FR_OK) { return true; } chprintf(DEBUG_CANNEL, "FS: f_findfirst \"%s\" in path \"%s\" failed\r\n", pattern, path); PrintFilesystemError(DEBUG_CANNEL, res); return false; } void ModuleCardreader::PrintFilesystemError(BaseSequentialStream* chp, FRESULT err) { chprintf(chp, "\t%s.\r\n", FilesystemResultToString(err)); } const char* ModuleCardreader::FilesystemResultToString(FRESULT stat) { static const char* ErrorStrings[] = { "Succeeded", "A hard error occurred in the low level disk I/O layer", "Assertion failed", "The physical drive cannot work", "Could not find the file", "Could not find the path", "The path name format is invalid", "Access denied due to prohibited access or directory full", "Access denied due to prohibited access", "The file/directory object is invalid", "The physical drive is write protected", "The logical drive number is invalid", "The volume has no work area", "There is no valid FAT volume", "The f_mkfs() aborted due to any parameter error", "Could not get a grant to access the volume within defined period", "The operation is rejected according to the file sharing policy", "LFN working buffer could not be allocated", "Number of open files > _FS_SHARE", "Given parameter is invalid", "Unknown" }; if (stat > FR_INVALID_PARAMETER) { return ErrorStrings[20]; } return ErrorStrings[stat]; } } MODULE_INITCALL(3, qos::ModuleInit<tmb_musicplayer::ModuleCardreaderSingelton>::Init, qos::ModuleInit<tmb_musicplayer::ModuleCardreaderSingelton>::Start, qos::ModuleInit<tmb_musicplayer::ModuleCardreaderSingelton>::Shutdown) #endif /* MOD_CARDREADER */ /** @} */ <commit_msg>mod_cardreader: add debug messages<commit_after>/** * @file src/mod_cardreader.cpp * @brief * * @addtogroup * @{ */ #include "mod_cardreader.h" #if MOD_CARDREADER #include <stdio.h> #include <string.h> #include <stdlib.h> #include "ch_tools.h" #include "chprintf.h" #include "qhal.h" #include "module_init_cpp.h" #include "watchdog.h" #include "board_buttons.h" #if HAL_USE_SDC #else #error "SDC driver must be specified" #endif template <> tmb_musicplayer::ModuleCardreader tmb_musicplayer::ModuleCardreaderSingelton::instance = tmb_musicplayer::ModuleCardreader(); namespace tmb_musicplayer { ModuleCardreader::ModuleCardreader() { } ModuleCardreader::~ModuleCardreader() { } void ModuleCardreader::Init() { } void ModuleCardreader::Start() { BaseClass::Start(); } void ModuleCardreader::Shutdown() { BaseClass::Shutdown(); } void ModuleCardreader::RegisterListener(chibios_rt::EvtListener* listener, eventmask_t mask) { m_evtSource.registerMask(listener, mask); } void ModuleCardreader::UnregisterListener(chibios_rt::EvtListener* listener) { m_evtSource.unregister(listener); } void ModuleCardreader::ThreadMain() { chRegSetThreadName("cardReader"); chibios_rt::EvtListener carddetectEvtListener; #if HAL_USE_BUTTONS BoardButtons::BtnCardDetect.RegisterListener(&carddetectEvtListener, EVENT_MASK(0)); #endif //if (m_carddetectButton->GetState() == false) { OnCardInserted(); } while (!chThdShouldTerminateX()) { eventmask_t evt = chEvtWaitAny(ALL_EVENTS); if (evt & EVENT_MASK(0)) { eventflags_t flags = carddetectEvtListener.getAndClearFlags(); if (flags & Button::Up) { OnCardInserted(); } else if (flags & Button::Down) { OnCardRemoved(); } } } OnCardRemoved(); #if HAL_USE_BUTTONS BoardButtons::BtnCardDetect.UnregisterListener(&carddetectEvtListener); #endif } void ModuleCardreader::OnCardRemoved() { chprintf(DEBUG_CANNEL, "ModuleCardreader: Memory card removed.\r\n"); UnmountFilesystem(); m_evtSource.broadcastFlags(FilesystemUnmounted); SetCardDetectLed(false); } void ModuleCardreader::OnCardInserted() { chprintf(DEBUG_CANNEL, "ModuleCardreader: Memory card inserted.\r\n"); if (MountFilesystem() == true) { m_evtSource.broadcastFlags(FilesystemMounted); SetCardDetectLed(true); } } bool ModuleCardreader::MountFilesystem() { if (sdcConnect(&SDCD1) == HAL_SUCCESS) { FRESULT err; err = f_mount(&m_filesystem, "/mount/", 1); if (err != FR_OK) { chprintf(DEBUG_CANNEL, "ModuleCardreader: FS: f_mount() failed. Is the SD card inserted?\r\n"); PrintFilesystemError(DEBUG_CANNEL, err); return false; } chprintf(DEBUG_CANNEL, "ModuleCardreader: FS: f_mount() succeeded\r\n"); return true; } chprintf(DEBUG_CANNEL, "ModuleCardreader: Failed to connect sdc card.\r\n"); return false; } bool ModuleCardreader::UnmountFilesystem() { FRESULT err; err = f_mount(NULL, "/mount/", 0); sdcDisconnect(&SDCD1); if (err != FR_OK) { chprintf(DEBUG_CANNEL, "ModuleCardreader: FS: f_mount() unmount failed\r\n"); PrintFilesystemError(DEBUG_CANNEL, err); return false; } chprintf(DEBUG_CANNEL, "ModuleCardreader: FS: f_mount() unmount succeeded\r\n"); return true; } void ModuleCardreader::SetCardDetectLed(bool on) { #if HAL_USE_LED if (on == true) { ledOn(LED_CARDDETECT); } else { ledOff(LED_CARDDETECT); } #endif /* HAL_USE_LED */ } bool ModuleCardreader::CommandCD(const char* path) { DIR dir; FRESULT res = f_opendir(&dir, path); if (res == FR_OK) { return true; } chprintf(DEBUG_CANNEL, "ModuleCardreader: FS: f_opendir \"%s\" failed\r\n", path); PrintFilesystemError(DEBUG_CANNEL, res); return false; } bool ModuleCardreader::CommandFind(DIR* dp, FILINFO* fno, const char* path, const char* pattern) { FRESULT res = f_findfirst(dp, fno, path, pattern); if (res == FR_OK) { return true; } chprintf(DEBUG_CANNEL, "ModuleCardreader: FS: f_findfirst \"%s\" in path \"%s\" failed\r\n", pattern, path); PrintFilesystemError(DEBUG_CANNEL, res); return false; } void ModuleCardreader::PrintFilesystemError(BaseSequentialStream* chp, FRESULT err) { chprintf(chp, "ModuleCardreader: \t%s.\r\n", FilesystemResultToString(err)); } const char* ModuleCardreader::FilesystemResultToString(FRESULT stat) { static const char* ErrorStrings[] = { "Succeeded", "A hard error occurred in the low level disk I/O layer", "Assertion failed", "The physical drive cannot work", "Could not find the file", "Could not find the path", "The path name format is invalid", "Access denied due to prohibited access or directory full", "Access denied due to prohibited access", "The file/directory object is invalid", "The physical drive is write protected", "The logical drive number is invalid", "The volume has no work area", "There is no valid FAT volume", "The f_mkfs() aborted due to any parameter error", "Could not get a grant to access the volume within defined period", "The operation is rejected according to the file sharing policy", "LFN working buffer could not be allocated", "Number of open files > _FS_SHARE", "Given parameter is invalid", "Unknown" }; if (stat > FR_INVALID_PARAMETER) { return ErrorStrings[20]; } return ErrorStrings[stat]; } } MODULE_INITCALL(3, qos::ModuleInit<tmb_musicplayer::ModuleCardreaderSingelton>::Init, qos::ModuleInit<tmb_musicplayer::ModuleCardreaderSingelton>::Start, qos::ModuleInit<tmb_musicplayer::ModuleCardreaderSingelton>::Shutdown) #endif /* MOD_CARDREADER */ /** @} */ <|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 "ppapi/tests/test_case.h" #include <string.h> #include <sstream> #include "ppapi/cpp/core.h" #include "ppapi/cpp/module.h" #include "ppapi/tests/pp_thread.h" #include "ppapi/tests/test_utils.h" #include "ppapi/tests/testing_instance.h" namespace { std::string StripPrefix(const std::string& test_name) { const char* const prefixes[] = { "FAILS_", "FLAKY_", "DISABLED_" }; for (size_t i = 0; i < sizeof(prefixes)/sizeof(prefixes[0]); ++i) if (test_name.find(prefixes[i]) == 0) return test_name.substr(strlen(prefixes[i])); return test_name; } // Strip the TestCase name off and return the remainder (i.e., everything after // '_'). If there is no '_', assume only the TestCase was provided, and return // an empty string. // For example: // StripTestCase("TestCase_TestName"); // returns // "TestName" // while // StripTestCase("TestCase); // returns // "" std::string StripTestCase(const std::string& full_test_name) { size_t delim = full_test_name.find_first_of('_'); if (delim != std::string::npos) return full_test_name.substr(delim+1); // In this case, our "filter" is the empty string; the full test name is the // same as the TestCase name with which we were constructed. // TODO(dmichael): It might be nice to be able to PP_DCHECK against the // TestCase class name, but we'd have to plumb that name to TestCase somehow. return std::string(); } // Parse |test_filter|, which is a comma-delimited list of (possibly prefixed) // test names and insert the un-prefixed names into |remaining_tests|, with // the bool indicating whether the test should be run. void ParseTestFilter(const std::string& test_filter, std::map<std::string, bool>* remaining_tests) { // We can't use base/strings/string_util.h::Tokenize in ppapi, so we have to // do it ourselves. std::istringstream filter_stream(test_filter); std::string current_test; while (std::getline(filter_stream, current_test, ',')) { // |current_test| might include a prefix, like DISABLED_Foo_TestBar, so we // we strip it off if there is one. std::string stripped_test_name(StripPrefix(current_test)); // Strip off the test case and use the test name as a key, because the test // name ShouldRunTest wants to use to look up the test doesn't have the // TestCase name. std::string test_name_without_case(StripTestCase(stripped_test_name)); // If the test wasn't prefixed, it should be run. bool should_run_test = (current_test == stripped_test_name); PP_DCHECK(remaining_tests->count(test_name_without_case) == 0); remaining_tests->insert( std::make_pair(test_name_without_case, should_run_test)); } // There may be a trailing comma; ignore empty strings. remaining_tests->erase(std::string()); } } // namespace TestCase::TestCase(TestingInstance* instance) : instance_(instance), testing_interface_(NULL), callback_type_(PP_REQUIRED), have_populated_filter_tests_(false) { // Get the testing_interface_ if it is available, so that we can do Resource // and Var checks on shutdown (see CheckResourcesAndVars). If it is not // available, testing_interface_ will be NULL. Some tests do not require it. testing_interface_ = GetTestingInterface(); } TestCase::~TestCase() { } bool TestCase::Init() { return true; } // static std::string TestCase::MakeFailureMessage(const char* file, int line, const char* cmd) { // The mere presence of this local variable works around a gcc-4.2.4 // compiler bug in official Chrome Linux builds. If you remove it, // confirm this compile command still works: // GYP_DEFINES='branding=Chrome buildtype=Official target_arch=x64' // gclient runhooks // make -k -j4 BUILDTYPE=Release ppapi_tests std::string s; std::ostringstream output; output << "Failure in " << file << "(" << line << "): " << cmd; return output.str(); } #if !(defined __native_client__) pp::VarPrivate TestCase::GetTestObject() { if (test_object_.is_undefined()) { pp::deprecated::ScriptableObject* so = CreateTestObject(); if (so) { test_object_ = pp::VarPrivate(instance_, so); // Takes ownership. // CheckResourcesAndVars runs and looks for leaks before we've actually // completely shut down. Ignore the instance object, since it's not a real // leak. IgnoreLeakedVar(test_object_.pp_var().value.as_id); } } return test_object_; } #endif bool TestCase::CheckTestingInterface() { testing_interface_ = GetTestingInterface(); if (!testing_interface_) { // Give a more helpful error message for the testing interface being gone // since that needs special enabling in Chrome. instance_->AppendError("This test needs the testing interface, which is " "not currently available. In Chrome, use " "--enable-pepper-testing when launching."); return false; } return true; } void TestCase::HandleMessage(const pp::Var& message_data) { } void TestCase::DidChangeView(const pp::View& view) { } bool TestCase::HandleInputEvent(const pp::InputEvent& event) { return false; } void TestCase::IgnoreLeakedVar(int64_t id) { ignored_leaked_vars_.insert(id); } #if !(defined __native_client__) pp::deprecated::ScriptableObject* TestCase::CreateTestObject() { return NULL; } #endif bool TestCase::EnsureRunningOverHTTP() { if (instance_->protocol() != "http:") { instance_->AppendError("This test needs to be run over HTTP."); return false; } return true; } bool TestCase::ShouldRunAllTests(const std::string& filter) { // If only the TestCase is listed, we're running all the tests in RunTests. return (StripTestCase(filter) == std::string()); } bool TestCase::ShouldRunTest(const std::string& test_name, const std::string& filter) { if (ShouldRunAllTests(filter)) return true; // Lazily initialize our "filter_tests_" map. if (!have_populated_filter_tests_) { ParseTestFilter(filter, &filter_tests_); remaining_tests_ = filter_tests_; have_populated_filter_tests_ = true; } std::map<std::string, bool>::iterator iter = filter_tests_.find(test_name); if (iter == filter_tests_.end()) { // The test name wasn't listed in the filter. Don't run it, but store it // so TestingInstance::ExecuteTests can report an error later. skipped_tests_.insert(test_name); return false; } remaining_tests_.erase(test_name); return iter->second; } PP_TimeTicks TestCase::NowInTimeTicks() { return pp::Module::Get()->core()->GetTimeTicks(); } std::string TestCase::CheckResourcesAndVars(std::string errors) { if (!errors.empty()) return errors; if (testing_interface_) { // TODO(dmichael): Fix tests that leak resources and enable the following: /* uint32_t leaked_resources = testing_interface_->GetLiveObjectsForInstance(instance_->pp_instance()); if (leaked_resources) { std::ostringstream output; output << "FAILED: Test leaked " << leaked_resources << " resources.\n"; errors += output.str(); } */ const int kVarsToPrint = 100; PP_Var vars[kVarsToPrint]; int found_vars = testing_interface_->GetLiveVars(vars, kVarsToPrint); // This will undercount if we are told to ignore a Var which is then *not* // leaked. Worst case, we just won't print the little "Test leaked" message, // but we'll still print any non-ignored leaked vars we found. int leaked_vars = found_vars - static_cast<int>(ignored_leaked_vars_.size()); if (leaked_vars > 0) { std::ostringstream output; output << "Test leaked " << leaked_vars << " vars (printing at most " << kVarsToPrint <<"):<p>"; errors += output.str(); } for (int i = 0; i < std::min(found_vars, kVarsToPrint); ++i) { pp::Var leaked_var(pp::PASS_REF, vars[i]); if (ignored_leaked_vars_.count(leaked_var.pp_var().value.as_id) == 0) errors += leaked_var.DebugString() + "<p>"; } } return errors; } // static void TestCase::QuitMainMessageLoop(PP_Instance instance) { PP_Instance* heap_instance = new PP_Instance(instance); pp::CompletionCallback callback(&DoQuitMainMessageLoop, heap_instance); pp::Module::Get()->core()->CallOnMainThread(0, callback); } // static void TestCase::DoQuitMainMessageLoop(void* pp_instance, int32_t result) { PP_Instance* instance = static_cast<PP_Instance*>(pp_instance); GetTestingInterface()->QuitMessageLoop(*instance); delete instance; } void TestCase::RunOnThreadInternal(void (*thread_func)(void*), void* thread_param, const PPB_Testing_Dev* testing_interface) { PP_ThreadType thread; PP_CreateThread(&thread, thread_func, thread_param); // Run a message loop so pepper calls can be dispatched. The background // thread will set result_ and make us Quit when it's done. testing_interface->RunMessageLoop(instance_->pp_instance()); PP_JoinThread(thread); } <commit_msg>Remove unused variable declaration.<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 "ppapi/tests/test_case.h" #include <string.h> #include <sstream> #include "ppapi/cpp/core.h" #include "ppapi/cpp/module.h" #include "ppapi/tests/pp_thread.h" #include "ppapi/tests/test_utils.h" #include "ppapi/tests/testing_instance.h" namespace { std::string StripPrefix(const std::string& test_name) { const char* const prefixes[] = { "FAILS_", "FLAKY_", "DISABLED_" }; for (size_t i = 0; i < sizeof(prefixes)/sizeof(prefixes[0]); ++i) if (test_name.find(prefixes[i]) == 0) return test_name.substr(strlen(prefixes[i])); return test_name; } // Strip the TestCase name off and return the remainder (i.e., everything after // '_'). If there is no '_', assume only the TestCase was provided, and return // an empty string. // For example: // StripTestCase("TestCase_TestName"); // returns // "TestName" // while // StripTestCase("TestCase); // returns // "" std::string StripTestCase(const std::string& full_test_name) { size_t delim = full_test_name.find_first_of('_'); if (delim != std::string::npos) return full_test_name.substr(delim+1); // In this case, our "filter" is the empty string; the full test name is the // same as the TestCase name with which we were constructed. // TODO(dmichael): It might be nice to be able to PP_DCHECK against the // TestCase class name, but we'd have to plumb that name to TestCase somehow. return std::string(); } // Parse |test_filter|, which is a comma-delimited list of (possibly prefixed) // test names and insert the un-prefixed names into |remaining_tests|, with // the bool indicating whether the test should be run. void ParseTestFilter(const std::string& test_filter, std::map<std::string, bool>* remaining_tests) { // We can't use base/strings/string_util.h::Tokenize in ppapi, so we have to // do it ourselves. std::istringstream filter_stream(test_filter); std::string current_test; while (std::getline(filter_stream, current_test, ',')) { // |current_test| might include a prefix, like DISABLED_Foo_TestBar, so we // we strip it off if there is one. std::string stripped_test_name(StripPrefix(current_test)); // Strip off the test case and use the test name as a key, because the test // name ShouldRunTest wants to use to look up the test doesn't have the // TestCase name. std::string test_name_without_case(StripTestCase(stripped_test_name)); // If the test wasn't prefixed, it should be run. bool should_run_test = (current_test == stripped_test_name); PP_DCHECK(remaining_tests->count(test_name_without_case) == 0); remaining_tests->insert( std::make_pair(test_name_without_case, should_run_test)); } // There may be a trailing comma; ignore empty strings. remaining_tests->erase(std::string()); } } // namespace TestCase::TestCase(TestingInstance* instance) : instance_(instance), testing_interface_(NULL), callback_type_(PP_REQUIRED), have_populated_filter_tests_(false) { // Get the testing_interface_ if it is available, so that we can do Resource // and Var checks on shutdown (see CheckResourcesAndVars). If it is not // available, testing_interface_ will be NULL. Some tests do not require it. testing_interface_ = GetTestingInterface(); } TestCase::~TestCase() { } bool TestCase::Init() { return true; } // static std::string TestCase::MakeFailureMessage(const char* file, int line, const char* cmd) { // The mere presence of this local variable works around a gcc-4.2.4 // compiler bug in official Chrome Linux builds. If you remove it, // confirm this compile command still works: // GYP_DEFINES='branding=Chrome buildtype=Official target_arch=x64' // gclient runhooks // make -k -j4 BUILDTYPE=Release ppapi_tests std::ostringstream output; output << "Failure in " << file << "(" << line << "): " << cmd; return output.str(); } #if !(defined __native_client__) pp::VarPrivate TestCase::GetTestObject() { if (test_object_.is_undefined()) { pp::deprecated::ScriptableObject* so = CreateTestObject(); if (so) { test_object_ = pp::VarPrivate(instance_, so); // Takes ownership. // CheckResourcesAndVars runs and looks for leaks before we've actually // completely shut down. Ignore the instance object, since it's not a real // leak. IgnoreLeakedVar(test_object_.pp_var().value.as_id); } } return test_object_; } #endif bool TestCase::CheckTestingInterface() { testing_interface_ = GetTestingInterface(); if (!testing_interface_) { // Give a more helpful error message for the testing interface being gone // since that needs special enabling in Chrome. instance_->AppendError("This test needs the testing interface, which is " "not currently available. In Chrome, use " "--enable-pepper-testing when launching."); return false; } return true; } void TestCase::HandleMessage(const pp::Var& message_data) { } void TestCase::DidChangeView(const pp::View& view) { } bool TestCase::HandleInputEvent(const pp::InputEvent& event) { return false; } void TestCase::IgnoreLeakedVar(int64_t id) { ignored_leaked_vars_.insert(id); } #if !(defined __native_client__) pp::deprecated::ScriptableObject* TestCase::CreateTestObject() { return NULL; } #endif bool TestCase::EnsureRunningOverHTTP() { if (instance_->protocol() != "http:") { instance_->AppendError("This test needs to be run over HTTP."); return false; } return true; } bool TestCase::ShouldRunAllTests(const std::string& filter) { // If only the TestCase is listed, we're running all the tests in RunTests. return (StripTestCase(filter) == std::string()); } bool TestCase::ShouldRunTest(const std::string& test_name, const std::string& filter) { if (ShouldRunAllTests(filter)) return true; // Lazily initialize our "filter_tests_" map. if (!have_populated_filter_tests_) { ParseTestFilter(filter, &filter_tests_); remaining_tests_ = filter_tests_; have_populated_filter_tests_ = true; } std::map<std::string, bool>::iterator iter = filter_tests_.find(test_name); if (iter == filter_tests_.end()) { // The test name wasn't listed in the filter. Don't run it, but store it // so TestingInstance::ExecuteTests can report an error later. skipped_tests_.insert(test_name); return false; } remaining_tests_.erase(test_name); return iter->second; } PP_TimeTicks TestCase::NowInTimeTicks() { return pp::Module::Get()->core()->GetTimeTicks(); } std::string TestCase::CheckResourcesAndVars(std::string errors) { if (!errors.empty()) return errors; if (testing_interface_) { // TODO(dmichael): Fix tests that leak resources and enable the following: /* uint32_t leaked_resources = testing_interface_->GetLiveObjectsForInstance(instance_->pp_instance()); if (leaked_resources) { std::ostringstream output; output << "FAILED: Test leaked " << leaked_resources << " resources.\n"; errors += output.str(); } */ const int kVarsToPrint = 100; PP_Var vars[kVarsToPrint]; int found_vars = testing_interface_->GetLiveVars(vars, kVarsToPrint); // This will undercount if we are told to ignore a Var which is then *not* // leaked. Worst case, we just won't print the little "Test leaked" message, // but we'll still print any non-ignored leaked vars we found. int leaked_vars = found_vars - static_cast<int>(ignored_leaked_vars_.size()); if (leaked_vars > 0) { std::ostringstream output; output << "Test leaked " << leaked_vars << " vars (printing at most " << kVarsToPrint <<"):<p>"; errors += output.str(); } for (int i = 0; i < std::min(found_vars, kVarsToPrint); ++i) { pp::Var leaked_var(pp::PASS_REF, vars[i]); if (ignored_leaked_vars_.count(leaked_var.pp_var().value.as_id) == 0) errors += leaked_var.DebugString() + "<p>"; } } return errors; } // static void TestCase::QuitMainMessageLoop(PP_Instance instance) { PP_Instance* heap_instance = new PP_Instance(instance); pp::CompletionCallback callback(&DoQuitMainMessageLoop, heap_instance); pp::Module::Get()->core()->CallOnMainThread(0, callback); } // static void TestCase::DoQuitMainMessageLoop(void* pp_instance, int32_t result) { PP_Instance* instance = static_cast<PP_Instance*>(pp_instance); GetTestingInterface()->QuitMessageLoop(*instance); delete instance; } void TestCase::RunOnThreadInternal(void (*thread_func)(void*), void* thread_param, const PPB_Testing_Dev* testing_interface) { PP_ThreadType thread; PP_CreateThread(&thread, thread_func, thread_param); // Run a message loop so pepper calls can be dispatched. The background // thread will set result_ and make us Quit when it's done. testing_interface->RunMessageLoop(instance_->pp_instance()); PP_JoinThread(thread); } <|endoftext|>
<commit_before>/* Copyright 2016 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. ==============================================================================*/ // Make this file empty (or nearly empty) so that it can be compiled even when // libxsmm is not available. #ifndef TENSORFLOW_USE_LIBXSMM void dummy_xsmm_conv2d_ensure_file_is_not_empty(void); #else #define USE_EIGEN_TENSOR #define EIGEN_USE_THREADS #include "tensorflow/core/kernels/xsmm_conv2d.h" #include <stdlib.h> #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/lib/core/blocking_counter.h" #include "tensorflow/core/lib/core/threadpool.h" #include "include/libxsmm_cpuid.h" namespace tensorflow { // Xsmm*Conv2D are wrappers for libxsmm direct convolutions. typedef Eigen::ThreadPoolDevice CPUDevice; namespace functor { static void chk_libxsmm_err(libxsmm_dnn_err_t status, string msg) { if (status != LIBXSMM_DNN_SUCCESS) { VLOG(0) << msg << " failed: " << libxsmm_dnn_get_error(status); } } template <typename InputPtr, typename FilterPtr, typename OutputPtr> static bool CallLibxsmmConvGeneric(OpKernelContext* ctx, const libxsmm_dnn_conv_desc& desc, libxsmm_dnn_conv_kind kind, InputPtr input, FilterPtr filter, OutputPtr output) { libxsmm_dnn_err_t status; libxsmm_dnn_conv_handle* libxsmm_handle; libxsmm_handle = libxsmm_dnn_create_conv_handle_check(desc, &status); chk_libxsmm_err(status, "Create handle"); status = libxsmm_dnn_get_codegen_success(libxsmm_handle, kind); if (status == LIBXSMM_DNN_WARN_FALLBACK) { chk_libxsmm_err(libxsmm_dnn_destroy_conv_handle(libxsmm_handle), "Destroy handle"); return false; // Use non-libxsmm code } // libxsmm_dnn_get_codegen_success can return real errors as well chk_libxsmm_err(status, "Check codegen status"); libxsmm_dnn_buffer* libxsmm_input; libxsmm_dnn_buffer* libxsmm_output; libxsmm_dnn_filter* libxsmm_filter; libxsmm_input = libxsmm_dnn_link_input_buffer_check( libxsmm_handle, input, LIBXSMM_DNN_CONV_FORMAT_NHWC_PTR, &status); chk_libxsmm_err(status, "Link input buffer"); libxsmm_output = libxsmm_dnn_link_output_buffer_check( libxsmm_handle, output, LIBXSMM_DNN_CONV_FORMAT_NHWC_PTR, &status); chk_libxsmm_err(status, "Link output buffer"); libxsmm_filter = libxsmm_dnn_link_filter_check( libxsmm_handle, filter, LIBXSMM_DNN_CONV_FORMAT_RSCK_PTR, &status); chk_libxsmm_err(status, "Link filter"); chk_libxsmm_err(libxsmm_dnn_zero_buffer(libxsmm_output), "Zero output"); chk_libxsmm_err(libxsmm_dnn_bind_input_buffer(libxsmm_handle, libxsmm_input), "Bind input"); chk_libxsmm_err( libxsmm_dnn_bind_output_buffer(libxsmm_handle, libxsmm_output), "Bind output"); chk_libxsmm_err(libxsmm_dnn_bind_filter(libxsmm_handle, libxsmm_filter), "Bind filter"); if (kind == LIBXSMM_DNN_CONV_KIND_BWD) { libxsmm_dnn_transpose_filter(libxsmm_handle); } const CpuWorkerThreads* worker_threads = ctx->device()->tensorflow_cpu_worker_threads(); int num_threads = worker_threads->num_threads; BlockingCounter counter(num_threads); for (int i = 0; i < num_threads; ++i) { worker_threads->workers->Schedule([=, &counter]() { chk_libxsmm_err(libxsmm_dnn_convolve_st(libxsmm_handle, kind, 0, i), "Worker"); counter.DecrementCount(); }); } counter.Wait(); chk_libxsmm_err(libxsmm_dnn_destroy_buffer(libxsmm_input), "Destroy input"); chk_libxsmm_err(libxsmm_dnn_destroy_buffer(libxsmm_output), "Destroy output"); chk_libxsmm_err(libxsmm_dnn_destroy_filter(libxsmm_filter), "Destroy filter"); chk_libxsmm_err(libxsmm_dnn_destroy_conv_handle(libxsmm_handle), "Destroy handle"); return true; // Succeeded } template <typename T> struct XsmmFwdConv2D<CPUDevice, T> { bool operator()(OpKernelContext* ctx, const libxsmm_dnn_conv_desc& desc, const T* input, const T* filter, T* output) { return CallLibxsmmConvGeneric(ctx, desc, LIBXSMM_DNN_CONV_KIND_FWD, input, filter, output); } }; template <typename T> struct XsmmBkwInputConv2D<CPUDevice, T> { bool operator()(OpKernelContext* ctx, const libxsmm_dnn_conv_desc& desc, T* input, const T* filter, const T* output) { return CallLibxsmmConvGeneric(ctx, desc, LIBXSMM_DNN_CONV_KIND_BWD, input, filter, output); } }; template <typename T> struct XsmmBkwFilterConv2D<CPUDevice, T> { bool operator()(OpKernelContext* ctx, const libxsmm_dnn_conv_desc& desc, const T* input, T* filter, const T* output) { return CallLibxsmmConvGeneric(ctx, desc, LIBXSMM_DNN_CONV_KIND_UPD, input, filter, output); } }; } // namespace functor template struct functor::XsmmFwdConv2D<CPUDevice, float>; template struct functor::XsmmBkwInputConv2D<CPUDevice, float>; template struct functor::XsmmBkwFilterConv2D<CPUDevice, float>; } // namespace tensorflow #endif // TENSORFLOW_USE_LIBXSMM <commit_msg>Fixed a typo<commit_after>/* Copyright 2016 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. ==============================================================================*/ // Make this file empty (or nearly empty) so that it can be compiled even when // libxsmm is not available. #ifndef TENSORFLOW_USE_LIBXSMM void dummy_xsmm_conv2d_ensure_file_is_not_empty(void); #else #define USE_EIGEN_TENSOR #define EIGEN_USE_THREADS #include "tensorflow/core/kernels/xsmm_conv2d.h" #include <stdlib.h> #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/lib/core/blocking_counter.h" #include "tensorflow/core/lib/core/threadpool.h" #include "include/libxsmm_cpuid.h" namespace tensorflow { // Xsmm*Conv2D are wrappers for libxsmm direct convolutions. typedef Eigen::ThreadPoolDevice CPUDevice; namespace functor { static void chk_libxsmm_err(libxsmm_dnn_err_t status, string msg) { if (status != LIBXSMM_DNN_SUCCESS) { VLOG(0) << msg << " failed: " << libxsmm_dnn_get_error(status); } } template <typename InputPtr, typename FilterPtr, typename OutputPtr> static bool CallLibxsmmConvGeneric(OpKernelContext* ctx, const libxsmm_dnn_conv_desc& desc, libxsmm_dnn_conv_kind kind, InputPtr input, FilterPtr filter, OutputPtr output) { libxsmm_dnn_err_t status; libxsmm_dnn_conv_handle* libxsmm_handle; libxsmm_handle = libxsmm_dnn_create_conv_handle_check(desc, &status); chk_libxsmm_err(status, "Create handle"); status = libxsmm_dnn_get_codegen_success(libxsmm_handle, kind); if (status == LIBXSMM_DNN_WARN_FALLBACK) { chk_libxsmm_err(libxsmm_dnn_destroy_conv_handle(libxsmm_handle), "Destroy handle"); return false; // Use non-libxsmm code } // libxsmm_dnn_get_codegen_success can return real errors as well chk_libxsmm_err(status, "Check codegen status"); libxsmm_dnn_buffer* libxsmm_input; libxsmm_dnn_buffer* libxsmm_output; libxsmm_dnn_filter* libxsmm_filter; libxsmm_input = libxsmm_dnn_link_input_buffer_check( libxsmm_handle, input, LIBXSMM_DNN_CONV_FORMAT_NHWC_PTR, &status); chk_libxsmm_err(status, "Link input buffer"); libxsmm_output = libxsmm_dnn_link_output_buffer_check( libxsmm_handle, output, LIBXSMM_DNN_CONV_FORMAT_NHWC_PTR, &status); chk_libxsmm_err(status, "Link output buffer"); libxsmm_filter = libxsmm_dnn_link_filter_check( libxsmm_handle, filter, LIBXSMM_DNN_CONV_FORMAT_RSCK_PTR, &status); chk_libxsmm_err(status, "Link filter"); chk_libxsmm_err(libxsmm_dnn_zero_buffer(libxsmm_output), "Zero output"); chk_libxsmm_err(libxsmm_dnn_bind_input_buffer(libxsmm_handle, libxsmm_input), "Bind input"); chk_libxsmm_err( libxsmm_dnn_bind_output_buffer(libxsmm_handle, libxsmm_output), "Bind output"); chk_libxsmm_err(libxsmm_dnn_bind_filter(libxsmm_handle, libxsmm_filter), "Bind filter"); if (kind == LIBXSMM_DNN_CONV_KIND_BWD) { libxsmm_dnn_transpose_filter(libxsmm_handle); } const DeviceBase::CpuWorkerThreads* worker_threads = ctx->device()->tensorflow_cpu_worker_threads(); int num_threads = worker_threads->num_threads; BlockingCounter counter(num_threads); for (int i = 0; i < num_threads; ++i) { worker_threads->workers->Schedule([=, &counter]() { chk_libxsmm_err(libxsmm_dnn_convolve_st(libxsmm_handle, kind, 0, i), "Worker"); counter.DecrementCount(); }); } counter.Wait(); chk_libxsmm_err(libxsmm_dnn_destroy_buffer(libxsmm_input), "Destroy input"); chk_libxsmm_err(libxsmm_dnn_destroy_buffer(libxsmm_output), "Destroy output"); chk_libxsmm_err(libxsmm_dnn_destroy_filter(libxsmm_filter), "Destroy filter"); chk_libxsmm_err(libxsmm_dnn_destroy_conv_handle(libxsmm_handle), "Destroy handle"); return true; // Succeeded } template <typename T> struct XsmmFwdConv2D<CPUDevice, T> { bool operator()(OpKernelContext* ctx, const libxsmm_dnn_conv_desc& desc, const T* input, const T* filter, T* output) { return CallLibxsmmConvGeneric(ctx, desc, LIBXSMM_DNN_CONV_KIND_FWD, input, filter, output); } }; template <typename T> struct XsmmBkwInputConv2D<CPUDevice, T> { bool operator()(OpKernelContext* ctx, const libxsmm_dnn_conv_desc& desc, T* input, const T* filter, const T* output) { return CallLibxsmmConvGeneric(ctx, desc, LIBXSMM_DNN_CONV_KIND_BWD, input, filter, output); } }; template <typename T> struct XsmmBkwFilterConv2D<CPUDevice, T> { bool operator()(OpKernelContext* ctx, const libxsmm_dnn_conv_desc& desc, const T* input, T* filter, const T* output) { return CallLibxsmmConvGeneric(ctx, desc, LIBXSMM_DNN_CONV_KIND_UPD, input, filter, output); } }; } // namespace functor template struct functor::XsmmFwdConv2D<CPUDevice, float>; template struct functor::XsmmBkwInputConv2D<CPUDevice, float>; template struct functor::XsmmBkwFilterConv2D<CPUDevice, float>; } // namespace tensorflow #endif // TENSORFLOW_USE_LIBXSMM <|endoftext|>
<commit_before>#include <QtTest> #include <QtWidgets> #include <DO/Graphics/DerivedQObjects/PaintingWindow.hpp> using namespace DO; class TestPaintingWindowConstructors: public QObject { Q_OBJECT private slots: void test_construction_of_PaintingWindow_with_small_size() { int width = 50; int height = 50; QString windowName = "painting window"; int x = 200; int y = 300; PaintingWindow *window = new PaintingWindow(width, height, windowName, x, y); QCOMPARE(window->width(), width); QCOMPARE(window->height(), height); QCOMPARE(window->windowTitle(), windowName); QCOMPARE(window->x(), x); QCOMPARE(window->y(), y); QVERIFY(window->isVisible()); window->deleteLater(); } void test_construction_of_PaintingWindow_with_size_larger_than_desktop() { int width = qApp->desktop()->width(); int height = qApp->desktop()->height(); PaintingWindow *window = new PaintingWindow(width, height); QVERIFY(window->scrollArea()->isMaximized()); QVERIFY(window->isVisible()); window->deleteLater(); } }; class TestPaintingWindowDrawMethods: public QObject { Q_OBJECT private: // data members PaintingWindow *test_window_; QImage true_image_; QPainter painter_; private: // methods QImage get_image_from_window() { QImage image(test_window_->size(), QImage::Format_RGB32); test_window_->render(&image, QPoint(), QRegion(QRect(QPoint(), test_window_->size()))); return image; } private slots: void initTestCase() { test_window_ = new PaintingWindow(300, 300); true_image_ = QImage(test_window_->size(), QImage::Format_RGB32); } void init() { test_window_->clear(); true_image_.fill(Qt::white); painter_.begin(&true_image_); } void cleanup() { painter_.end(); } void cleanupTestCase() { test_window_->deleteLater(); } void test_drawPoint_using_integer_coordinates() { int x = 150, y = 100; QColor color(255, 0, 0); test_window_->drawPoint(x, y, color); painter_.setPen(color); painter_.drawPoint(QPoint(x, y)); QCOMPARE(get_image_from_window(), true_image_); } void test_drawPoint_using_QPointF() { double x = 150.95, y = 100.3333; QColor color(0, 225, 0); test_window_->drawPoint(QPointF(x, y), color); painter_.setPen(color); painter_.drawPoint(QPointF(x, y)); QCOMPARE(get_image_from_window(), true_image_); } void test_drawLine_using_integer_coordinates() { int x1 = 100, y1 = 100; int x2 = 200, y2 = 240; QColor color(0, 255, 0); int thickness = 3; test_window_->drawLine(x1, y1, x2, y2, color, thickness); painter_.setPen(QPen(color, thickness)); painter_.drawLine(x1, y1, x2, y2); QCOMPARE(get_image_from_window(), true_image_); } void test_drawLine_using_QPointF() { QPointF p1(100.350, 100.699); QPointF p2(203.645, 240.664); QColor color(0, 255, 123); int thickness = 4; test_window_->drawLine(p1, p2, color, thickness); painter_.setPen(QPen(color, thickness)); painter_.drawLine(p1, p2); QCOMPARE(get_image_from_window(), true_image_); } void test_drawCircle_using_integer_coordinates() { int xc = 150, yc = 123; int r = 39; QColor color(0, 255, 123); int thickness = 4; test_window_->drawCircle(xc, yc, r, color, thickness); painter_.setPen(QPen(color, thickness)); painter_.drawEllipse(QPoint(xc, yc), r, r); QCOMPARE(get_image_from_window(), true_image_); } void test_drawCircle_using_Circle_using_QPointF() { QPointF c(150.999, 123.231); int r = 39; QColor color(0, 255, 123); int thickness = 4; test_window_->drawCircle(c, r, color, thickness); painter_.setPen(QPen(color, thickness)); painter_.drawEllipse(c, r, r); QCOMPARE(get_image_from_window(), true_image_); } void test_drawEllipse_using_axis_aligned_bounding_box() { // Axis-aligned ellipse defined by the following axis-aligned bounding box. int x = 150, y = 123; int w = 39, h = 100; QColor color(0, 255, 123); int thickness = 4; test_window_->drawEllipse(x, y, w, h, color, thickness); painter_.setPen(QPen(color, thickness)); painter_.drawEllipse(x, y, w, h); QCOMPARE(get_image_from_window(), true_image_); } void test_drawEllipse_with_center_and_semi_axes_and_orientation() { QPointF center(123.123, 156.123); qreal r1 = 100.13, r2 = 40.12; qreal oriDegree = 48.65; QColor color(0, 255, 123); int thickness = 4; test_window_->drawEllipse(center, r1, r2, oriDegree, color, thickness); painter_.setPen(QPen(color, thickness)); painter_.translate(center); painter_.rotate(oriDegree); painter_.translate(-r1, -r2); painter_.drawEllipse(QRectF(0, 0, 2*r1, 2*r2)); QCOMPARE(get_image_from_window(), true_image_); } void test_drawRect() { int x = 150, y = 123; int w = 39, h = 100; QColor color(0, 255, 123); int thickness = 4; test_window_->clear(); test_window_->drawRect(x, y, w, h, color, thickness); painter_.setPen(QPen(color, thickness)); painter_.drawRect(x, y, w, h); QCOMPARE(get_image_from_window(), true_image_); } void test_drawPoly() { QPolygonF polygon; polygon << QPointF(10, 10) << QPointF(250, 20) << QPointF(150, 258); QColor color(0, 255, 123); int thickness = 4; test_window_->drawPoly(polygon, color, thickness); painter_.setPen(QPen(color, thickness)); painter_.drawPolygon(polygon); QCOMPARE(get_image_from_window(), true_image_); } void test_drawText() { // What text. QString text("DO-CV is awesome!"); // Where. int x = 130, y = 150; double orientation = 36.6; // Style. QColor color(0, 255, 123); int fontSize = 15; bool italic = true; bool bold = true; bool underline = true; test_window_->drawText(x, y, text, color, fontSize, orientation, italic, bold, underline); painter_.setPen(color); QFont font; font.setPointSize(fontSize); font.setItalic(italic); font.setBold(bold); font.setUnderline(underline); painter_.setFont(font); painter_.translate(x, y); painter_.rotate(orientation); painter_.drawText(0, 0, text); QCOMPARE(get_image_from_window(), true_image_); } // TODO: make this test more exhaustive. void test_drawArrow() { int x1 = 150, y1 = 150; int x2 = 200, y2 = 200; QColor color(0, 255, 123); int arrowWidth = 3, arrowHeight = 5; int style = 0; int width = 3; test_window_->drawArrow(x1, y1, x2, y2, color, arrowWidth, arrowHeight, style, width); QImage image(get_image_from_window()); for (int x = 150; x < 200; ++x) QCOMPARE(image.pixel(x,x), color.rgb()); } void test_display() { int w = 20, h = 20; QImage patch(QSize(w, h), QImage::Format_RGB32); patch.fill(Qt::red); int x_offset = 20, y_offset = 30; double zoom_factor = 2.; test_window_->display(patch, x_offset, y_offset, zoom_factor); QImage image(get_image_from_window()); for (int y = 0; y < image.height(); ++y) for (int x = 0; x < image.width(); ++x) if ( x >= x_offset && x < x_offset+zoom_factor*w && y >= y_offset && y < y_offset+zoom_factor*h ) QCOMPARE(image.pixel(x, y), QColor(Qt::red).rgb()); else QCOMPARE(image.pixel(x, y), QColor(Qt::white).rgb()); } }; class TestPaintingWindowEvents: public QObject { Q_OBJECT private: PaintingWindow *test_window_; private slots: void initTestCase() { qRegisterMetaType<Qt::MouseButtons>("Qt::MouseButtons"); test_window_ = new PaintingWindow(300, 300); } void cleanupTestCase() { test_window_->deleteLater(); } void test_mouse_move_event() { test_window_->setMouseTracking(true); QSignalSpy spy(test_window_, SIGNAL(movedMouse(int, int, Qt::MouseButtons))); QVERIFY(spy.isValid()); int x=10, y= 10; QTestEventList events; events.addMouseMove(QPoint(x, y)); events.addMouseMove(QPoint(x+1, y+1)); events.simulate(test_window_); QCOMPARE(spy.count(), 1); QList<QVariant> arguments = spy.takeFirst(); QCOMPARE(arguments.at(0).toInt(), x+1); QCOMPARE(arguments.at(1).toInt(), y+1); QCOMPARE(arguments.at(2).toInt(), int(Qt::NoButton)); } }; int main(int argc, char *argv[]) { QApplication app(argc, argv); app.setAttribute(Qt::AA_Use96Dpi, true); QTEST_DISABLE_KEYPAD_NAVIGATION; int num_failed_tests = 0; TestPaintingWindowConstructors test_painting_window_constructors; num_failed_tests += QTest::qExec(&test_painting_window_constructors); TestPaintingWindowDrawMethods test_painting_window_draw_methods; num_failed_tests += QTest::qExec(&test_painting_window_draw_methods); TestPaintingWindowEvents test_painting_window_events; num_failed_tests += QTest::qExec(&test_painting_window_events); return num_failed_tests; } #include "test_painting_window.moc" <commit_msg>MAINT: code cosmetics.<commit_after>#include <QtTest> #include <QtWidgets> #include <DO/Graphics/DerivedQObjects/PaintingWindow.hpp> using namespace DO; class TestPaintingWindowConstructors: public QObject { Q_OBJECT private slots: void test_construction_of_PaintingWindow_with_small_size() { int width = 50; int height = 50; QString windowName = "painting window"; int x = 200; int y = 300; PaintingWindow *window = new PaintingWindow(width, height, windowName, x, y); QCOMPARE(window->width(), width); QCOMPARE(window->height(), height); QCOMPARE(window->windowTitle(), windowName); QCOMPARE(window->x(), x); QCOMPARE(window->y(), y); QVERIFY(window->isVisible()); window->deleteLater(); } void test_construction_of_PaintingWindow_with_size_larger_than_desktop() { int width = qApp->desktop()->width(); int height = qApp->desktop()->height(); PaintingWindow *window = new PaintingWindow(width, height); QVERIFY(window->scrollArea()->isMaximized()); QVERIFY(window->isVisible()); window->deleteLater(); } }; class TestPaintingWindowDrawMethods: public QObject { Q_OBJECT private: // data members PaintingWindow *test_window_; QImage true_image_; QPainter painter_; private: // methods QImage get_image_from_window() { QImage image(test_window_->size(), QImage::Format_RGB32); test_window_->render(&image, QPoint(), QRegion(QRect(QPoint(), test_window_->size()))); return image; } private slots: void initTestCase() { test_window_ = new PaintingWindow(300, 300); true_image_ = QImage(test_window_->size(), QImage::Format_RGB32); } void init() { test_window_->clear(); true_image_.fill(Qt::white); painter_.begin(&true_image_); } void cleanup() { painter_.end(); } void cleanupTestCase() { test_window_->deleteLater(); } void test_drawPoint_using_integer_coordinates() { int x = 150, y = 100; QColor color(255, 0, 0); test_window_->drawPoint(x, y, color); painter_.setPen(color); painter_.drawPoint(QPoint(x, y)); QCOMPARE(get_image_from_window(), true_image_); } void test_drawPoint_using_QPointF() { double x = 150.95, y = 100.3333; QColor color(0, 225, 0); test_window_->drawPoint(QPointF(x, y), color); painter_.setPen(color); painter_.drawPoint(QPointF(x, y)); QCOMPARE(get_image_from_window(), true_image_); } void test_drawLine_using_integer_coordinates() { int x1 = 100, y1 = 100; int x2 = 200, y2 = 240; QColor color(0, 255, 0); int thickness = 3; test_window_->drawLine(x1, y1, x2, y2, color, thickness); painter_.setPen(QPen(color, thickness)); painter_.drawLine(x1, y1, x2, y2); QCOMPARE(get_image_from_window(), true_image_); } void test_drawLine_using_QPointF() { QPointF p1(100.350, 100.699); QPointF p2(203.645, 240.664); QColor color(0, 255, 123); int thickness = 4; test_window_->drawLine(p1, p2, color, thickness); painter_.setPen(QPen(color, thickness)); painter_.drawLine(p1, p2); QCOMPARE(get_image_from_window(), true_image_); } void test_drawCircle_using_integer_coordinates() { int xc = 150, yc = 123; int r = 39; QColor color(0, 255, 123); int thickness = 4; test_window_->drawCircle(xc, yc, r, color, thickness); painter_.setPen(QPen(color, thickness)); painter_.drawEllipse(QPoint(xc, yc), r, r); QCOMPARE(get_image_from_window(), true_image_); } void test_drawCircle_using_Circle_using_QPointF() { QPointF c(150.999, 123.231); int r = 39; QColor color(0, 255, 123); int thickness = 4; test_window_->drawCircle(c, r, color, thickness); painter_.setPen(QPen(color, thickness)); painter_.drawEllipse(c, r, r); QCOMPARE(get_image_from_window(), true_image_); } void test_drawEllipse_using_axis_aligned_bounding_box() { // Axis-aligned ellipse defined by the following axis-aligned bounding box. int x = 150, y = 123; int w = 39, h = 100; QColor color(0, 255, 123); int thickness = 4; test_window_->drawEllipse(x, y, w, h, color, thickness); painter_.setPen(QPen(color, thickness)); painter_.drawEllipse(x, y, w, h); QCOMPARE(get_image_from_window(), true_image_); } void test_drawEllipse_with_center_and_semi_axes_and_orientation() { QPointF center(123.123, 156.123); qreal r1 = 100.13, r2 = 40.12; qreal oriDegree = 48.65; QColor color(0, 255, 123); int thickness = 4; test_window_->drawEllipse(center, r1, r2, oriDegree, color, thickness); painter_.setPen(QPen(color, thickness)); painter_.translate(center); painter_.rotate(oriDegree); painter_.translate(-r1, -r2); painter_.drawEllipse(QRectF(0, 0, 2*r1, 2*r2)); QCOMPARE(get_image_from_window(), true_image_); } void test_drawRect() { int x = 150, y = 123; int w = 39, h = 100; QColor color(0, 255, 123); int thickness = 4; test_window_->clear(); test_window_->drawRect(x, y, w, h, color, thickness); painter_.setPen(QPen(color, thickness)); painter_.drawRect(x, y, w, h); QCOMPARE(get_image_from_window(), true_image_); } void test_drawPoly() { QPolygonF polygon; polygon << QPointF(10, 10) << QPointF(250, 20) << QPointF(150, 258); QColor color(0, 255, 123); int thickness = 4; test_window_->drawPoly(polygon, color, thickness); painter_.setPen(QPen(color, thickness)); painter_.drawPolygon(polygon); QCOMPARE(get_image_from_window(), true_image_); } void test_drawText() { // What text. QString text("DO-CV is awesome!"); // Where. int x = 130, y = 150; double orientation = 36.6; // Style. QColor color(0, 255, 123); int fontSize = 15; bool italic = true; bool bold = true; bool underline = true; test_window_->drawText(x, y, text, color, fontSize, orientation, italic, bold, underline); painter_.setPen(color); QFont font; font.setPointSize(fontSize); font.setItalic(italic); font.setBold(bold); font.setUnderline(underline); painter_.setFont(font); painter_.translate(x, y); painter_.rotate(orientation); painter_.drawText(0, 0, text); QCOMPARE(get_image_from_window(), true_image_); } // TODO: make this test more exhaustive. void test_drawArrow() { int x1 = 150, y1 = 150; int x2 = 200, y2 = 200; QColor color(0, 255, 123); int arrowWidth = 3, arrowHeight = 5; int style = 0; int width = 3; test_window_->drawArrow(x1, y1, x2, y2, color, arrowWidth, arrowHeight, style, width); QImage image(get_image_from_window()); for (int x = 150; x < 200; ++x) QCOMPARE(image.pixel(x,x), color.rgb()); } void test_display() { int w = 20, h = 20; QImage patch(QSize(w, h), QImage::Format_RGB32); patch.fill(Qt::red); int x_offset = 20, y_offset = 30; double zoom_factor = 2.; test_window_->display(patch, x_offset, y_offset, zoom_factor); QImage image(get_image_from_window()); for (int y = 0; y < image.height(); ++y) for (int x = 0; x < image.width(); ++x) if ( x >= x_offset && x < x_offset+zoom_factor*w && y >= y_offset && y < y_offset+zoom_factor*h ) QCOMPARE(image.pixel(x, y), QColor(Qt::red).rgb()); else QCOMPARE(image.pixel(x, y), QColor(Qt::white).rgb()); } }; class TestPaintingWindowEvents: public QObject { Q_OBJECT private: PaintingWindow *test_window_; private slots: void initTestCase() { qRegisterMetaType<Qt::MouseButtons>("Qt::MouseButtons"); test_window_ = new PaintingWindow(300, 300); } void cleanupTestCase() { test_window_->deleteLater(); } void test_mouse_move_event() { test_window_->setMouseTracking(true); QSignalSpy spy(test_window_, SIGNAL(movedMouse(int, int, Qt::MouseButtons))); QVERIFY(spy.isValid()); QTestEventList events; int x = 10, y = 10; events.addMouseMove(QPoint(x, y)); events.addMouseMove(QPoint(x+1, y+1)); events.simulate(test_window_); QCOMPARE(spy.count(), 1); QList<QVariant> arguments = spy.takeFirst(); QCOMPARE(arguments.at(0).toInt(), x+1); QCOMPARE(arguments.at(1).toInt(), y+1); QCOMPARE(arguments.at(2).toInt(), int(Qt::NoButton)); } }; int main(int argc, char *argv[]) { QApplication app(argc, argv); app.setAttribute(Qt::AA_Use96Dpi, true); QTEST_DISABLE_KEYPAD_NAVIGATION; int num_failed_tests = 0; TestPaintingWindowConstructors test_painting_window_constructors; num_failed_tests += QTest::qExec(&test_painting_window_constructors); TestPaintingWindowDrawMethods test_painting_window_draw_methods; num_failed_tests += QTest::qExec(&test_painting_window_draw_methods); TestPaintingWindowEvents test_painting_window_events; num_failed_tests += QTest::qExec(&test_painting_window_events); return num_failed_tests; } #include "test_painting_window.moc" <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: i_ce2s.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2008-01-04 12:56:12 $ * * 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 ARY_IDL_I_CE2S_HXX #define ARY_IDL_I_CE2S_HXX // USED SERVICES // BASE CLASSES // COMPONENTS // PARAMETERS #include <ary/idl/i_types4idl.hxx> namespace ary { namespace idl { /** Abstract base for all secondary productions of code entities */ class Ce_2s { public: // LIFECYCLE virtual ~Ce_2s(); static DYN Ce_2s * Create_( ClassId i_nCeClass ); // OPERATIONS void Add_Link2DescriptionInManual( const String & i_link, const String & i_linkUI ) { aDescriptionsInManual.push_back(i_link); aDescriptionsInManual.push_back(i_linkUI); } void Add_Link2RefInManual( const String & i_link, const String & i_linkUI ) { aRefsInManual.push_back(i_link); aRefsInManual.push_back(i_linkUI); } std::vector<Ce_id> & Access_List( int i_indexOfList ); // INQUIRY const StringVector & Links2DescriptionInManual() const { return aDescriptionsInManual; } const StringVector & Links2RefsInManual() const { return aRefsInManual; } int CountXrefLists() const { return aXrefLists.size(); } const std::vector<Ce_id> & List( int i_indexOfList ) const; private: typedef DYN std::vector<Ce_id> * ListPtr; // DATA StringVector aDescriptionsInManual; StringVector aRefsInManual; std::vector<ListPtr> aXrefLists; }; } // namespace idl } // namespace ary #endif <commit_msg>INTEGRATION: CWS changefileheader (1.5.12); FILE MERGED 2008/03/28 16:01:13 rt 1.5.12.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: i_ce2s.hxx,v $ * $Revision: 1.6 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef ARY_IDL_I_CE2S_HXX #define ARY_IDL_I_CE2S_HXX // USED SERVICES // BASE CLASSES // COMPONENTS // PARAMETERS #include <ary/idl/i_types4idl.hxx> namespace ary { namespace idl { /** Abstract base for all secondary productions of code entities */ class Ce_2s { public: // LIFECYCLE virtual ~Ce_2s(); static DYN Ce_2s * Create_( ClassId i_nCeClass ); // OPERATIONS void Add_Link2DescriptionInManual( const String & i_link, const String & i_linkUI ) { aDescriptionsInManual.push_back(i_link); aDescriptionsInManual.push_back(i_linkUI); } void Add_Link2RefInManual( const String & i_link, const String & i_linkUI ) { aRefsInManual.push_back(i_link); aRefsInManual.push_back(i_linkUI); } std::vector<Ce_id> & Access_List( int i_indexOfList ); // INQUIRY const StringVector & Links2DescriptionInManual() const { return aDescriptionsInManual; } const StringVector & Links2RefsInManual() const { return aRefsInManual; } int CountXrefLists() const { return aXrefLists.size(); } const std::vector<Ce_id> & List( int i_indexOfList ) const; private: typedef DYN std::vector<Ce_id> * ListPtr; // DATA StringVector aDescriptionsInManual; StringVector aRefsInManual; std::vector<ListPtr> aXrefLists; }; } // namespace idl } // namespace ary #endif <|endoftext|>
<commit_before>/** \copyright * Copyright (c) 2013, Balazs Racz * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * \file main.cxx * * An application for updating the firmware of a remote node on the bus. * * @author Balazs Racz * @date 3 Aug 2013 */ #include <fcntl.h> #include <getopt.h> #include <stdio.h> #include <unistd.h> #include <memory> #include "os/os.h" #include "utils/constants.hxx" #include "utils/Hub.hxx" #include "utils/GridConnectHub.hxx" #include "utils/GcTcpHub.hxx" #include "utils/Crc.hxx" #include "utils/FileUtils.hxx" #include "executor/Executor.hxx" #include "executor/Service.hxx" #include "openlcb/IfCan.hxx" #include "openlcb/DatagramCan.hxx" #include "openlcb/BootloaderClient.hxx" #include "openlcb/If.hxx" #include "openlcb/AliasAllocator.hxx" #include "openlcb/DefaultNode.hxx" #include "openlcb/NodeInitializeFlow.hxx" #include "openlcb/MemoryConfig.hxx" #include "openlcb/MemoryConfigClient.hxx" #include "utils/socket_listener.hxx" #include "freertos/bootloader_hal.h" NO_THREAD nt; Executor<1> g_executor(nt); Service g_service(&g_executor); CanHubFlow can_hub0(&g_service); static const openlcb::NodeID NODE_ID = 0x05010101181FULL; openlcb::IfCan g_if_can(&g_executor, &can_hub0, 3, 3, 2); openlcb::InitializeFlow g_init_flow{&g_service}; openlcb::CanDatagramService g_datagram_can(&g_if_can, 10, 2); static openlcb::AddAliasAllocator g_alias_allocator(NODE_ID, &g_if_can); openlcb::DefaultNode g_node(&g_if_can, NODE_ID); openlcb::MemoryConfigHandler g_memcfg(&g_datagram_can, &g_node, 10); openlcb::MemoryConfigClient g_memcfg_cli(&g_node, &g_memcfg); namespace openlcb { Pool *const g_incoming_datagram_allocator = mainBufferPool; } static int port = 12021; static const char *host = "localhost"; static const char *device_path = nullptr; static const char *filename = nullptr; static uint64_t destination_nodeid = 0; static uint64_t destination_alias = 0; static int memory_space_id = openlcb::MemoryConfigDefs::SPACE_CONFIG; static bool do_read = false; static bool do_write = false; void usage(const char *e) { fprintf(stderr, "Usage: %s ([-i destination_host] [-p port] | [-d device_path]) [-s " "memory_space_id] [-c csum_algo] (-r|-w) (-n nodeid | -a " "alias) -f filename\n", e); fprintf(stderr, "Connects to an openlcb bus and performs the " "bootloader protocol on openlcb node with id nodeid with " "the contents of a given file.\n"); fprintf(stderr, "The bus connection will be through an OpenLCB HUB on " "destination_host:port with OpenLCB over TCP " "(in GridConnect format) protocol, or through the CAN-USB device " "(also in GridConnect protocol) found at device_path. Device takes " "precedence over TCP host:port specification."); fprintf(stderr, "The default target is localhost:12021.\n"); fprintf(stderr, "nodeid should be a 12-char hex string with 0x prefix and " "no separators, like '-b 0x05010101141F'\n"); fprintf(stderr, "alias should be a 3-char hex string with 0x prefix and no " "separators, like '-a 0x3F9'\n"); fprintf(stderr, "memory_space_id defines which memory space to use " "data into. Default is '-s 0xF0'.\n"); fprintf(stderr, "-r or -w defines whether to read or write.\n"); exit(1); } void parse_args(int argc, char *argv[]) { int opt; while ((opt = getopt(argc, argv, "hp:d:n:a:s:f:rw")) >= 0) { switch (opt) { case 'h': usage(argv[0]); break; case 'p': port = atoi(optarg); break; case 'i': host = optarg; break; case 'd': device_path = optarg; break; case 'f': filename = optarg; break; case 'n': destination_nodeid = strtoll(optarg, nullptr, 16); break; case 'a': destination_alias = strtoul(optarg, nullptr, 16); break; case 's': memory_space_id = strtol(optarg, nullptr, 16); break; case 'r': do_read = true; break; case 'w': do_write = true; break; default: fprintf(stderr, "Unknown option %c\n", opt); usage(argv[0]); } } if (!filename || (!destination_nodeid && !destination_alias)) { usage(argv[0]); } if ((do_read ? 1 : 0) + (do_write ? 1 : 0) != 1) { fprintf(stderr, "Must set exactly one of option -r and option -w.\n\n"); usage(argv[0]); } } /* namespace openlcb { struct MemConfigUtilsResponse; struct MemConfigUtilsRequest { enum Command { READ, WRITE }; Command cmd; /// Node to send the bootload request to. NodeHandle dst; uint8_t memory_space; string payload; MemConfigUtilsResponse *response = nullptr; }; struct MemConfigUtilsResponse { int error_code = 0; string error_details; string payload; }; class MemConfigUtilsFlow : public StateFlow<Buffer<MemConfigUtilsRequest>, QList<1>> { static constexpr unsigned SIZE = 64; public: MemConfigUtilsFlow(Node *node, DatagramService *datagram_service) : StateFlow<Buffer<MemConfigUtilsRequest>, QList<1>>(datagram_service) , node_(node) , datagramService_(datagram_service) { } Action entry() override { return allocate_and_call( STATE(got_dg_client), datagramService_->client_allocator()); } Action got_dg_client() { dgClient_ = full_allocation_result(datagramService_->client_allocator()); offset = 0; if (request()->cmd == MemConfigUtilsRequest::READ) { return call_immediately(STATE(send_read_dg)); } else HASSERT(0); if (request()->cmd == MemConfigUtilsRequest::WRITE) { return call_immediately(STATE(send_write_dg)); } } /// Datagram handler that listens to the incoming memoryconfig datagram for /// the write stream response message. class ResponseHandler : public DefaultDatagramHandler { public: ResponseHandler(MemConfigUtilsFlow *parent) : DefaultDatagramHandler(parent->datagram_service()) , parent_(parent) { } Action entry() override { IncomingDatagram *datagram = message()->data(); if (datagram->dst != parent_->node() || !parent_->node()->iface()->matching_node( parent_->dst(), datagram->src) || datagram->payload.size() < 6 || datagram->payload[0] != DatagramDefs::CONFIGURATION || ((datagram->payload[1] & 0xF4) != MemoryConfigDefs::COMMAND_WRITE_STREAM_REPLY)) { // Uninteresting datagram. return respond_reject(DatagramDefs::PERMANENT_ERROR); } return respond_ok(DatagramDefs::FLAGS_NONE); } Action ok_response_sent() override { parent_->response_datagram_arrived(transfer_message()); return exit(); } private: MemConfigUtilsFlow *parent_; } responseHandler_{this}; void response_datagram_arrived(Buffer<IncomingDatagram> *datagram) { if (responseDatagram_) { LOG_ERROR("Multiple response datagrams arrived from the " "target node."); responseDatagram_->unref(); } responseDatagram_ = datagram; if (sleeping_) { timer_.trigger(); } // else we will be woken up by the datagram client. } void register_response_handler() { datagramService_->registry()->insert( node_, DatagramDefs::CONFIGURATION, &responseHandler_); responseRegistered_ = true; } void unregister_response_handler() { if (responseRegistered_) { responseRegistered_ = false; datagramService_->registry()->erase( node_, DatagramDefs::CONFIGURATION, &responseHandler_); } } Action send_read_dg() { if (offset >= request()->payload.size()) { return completed(); } Buffer<GenMessage> *b; mainBufferPool->alloc(&b); DatagramPayload payload; payload.push_back(DatagramDefs::CONFIGURATION); payload.push_back(MemoryConfigDefs::COMMAND_READ); payload.push_back(offset >> 24); payload.push_back(offset >> 16); payload.push_back(offset >> 8); payload.push_back(offset); payload.push_back(request()->memory_space); payload.push_back(SIZE); b->data()->reset(Defs::MTI_DATAGRAM, node_->node_id(), message()->data()->dst, payload); b->set_done(n_.reset(this)); register_response_handler(); dgClient_->write_datagram(b); return wait_and_call(STATE(read_sent)); } Action read_sent() { uint32_t dg_result = dgClient_->result() & DatagramClient::RESPONSE_CODE_MASK; if (dg_result != DatagramClient::OPERATION_SUCCESS) { return complete(dg_result, "Read rejected."); } if (responseDatagram_) { return call_immediately(STATE(read_done)); } else { sleeping_ = true; return sleep_and_call(&timer_, SEC_TO_NSEC(3), STATE(read_done)); } } Action read_done() { unregister_response_handler(); sleeping_ = false; if (!responseDatagram_) { return return_error(DatagramClient::RESEND_OK, "Timed out waiting for response datagram."); } const auto &payload = responseDatagram_->data()->payload; if ((payload[1] & 0xFC) == MemoryConfigDefs::COMMAND_READ_FAILED) { uint16_t error_code = DatagramClient::PERMANENT_ERROR; unsigned error_ofs = 6; if (payload[1] == MemoryConfigDefs::COMMAND_READ_FAILED) { ++error_ofs; } LOG(WARNING, "payload length %" PRIdPTR " error offset %u data %02x %02x", payload.size(), error_ofs, payload[error_ofs], payload[error_ofs + 1]); error_code = (payload[error_ofs] << 8) | ((uint8_t)payload[error_ofs + 1]); error_ofs += 2; return complete( error_code, "Read rejected " + payload.substr(error_ofs)); } if ((payload[1] & 0xFC) == MemoryConfigDefs::COMMAND_READ_REPLY) { unsigned data_ofs = (payload[1] == MemoryConfigDefs::COMMAND_READ_REPLY ? 7 : 6); string part = payload.substr(data_ofs); response()->payload.append(part); LOG(WARNING, "Offset %zd received data ", offset); offset = response()->payload.size(); return call_immediately(send_read_dg()); } } Action completed(int code = 0, string details = "") { datagramService_->client_allocator()->typed_insert(dgClient_); response()->error_code = code; response()->error_details = details; return release_and_exit(); } MemConfigUtilsRequest *request() { return message()->data(); } MemConfigUtilsRequest *response() { return request()->response; } const NodeHandle& dst() { return request()->dst; } Node* node() { return node_; } DatagramService *datagram_service() { return datagramService_; } private: Node *node_; DatagramService *datagramService_; DatagramClient* dgClient_; size_t offset; StateFlowTimer timer_{this}; Buffer<IncomingDatagram> *responseDatagram_ = nullptr; bool sleeping_ = false; }; } // namespace openlcb openlcb::MemConfigUtilsFlow flow(&g_node, &g_datagram_can); */ /** Entry point to application. * @param argc number of command line arguments * @param argv array of command line arguments * @return 0, should never return */ int appl_main(int argc, char *argv[]) { parse_args(argc, argv); int conn_fd = 0; if (device_path) { conn_fd = ::open(device_path, O_RDWR); } else { conn_fd = ConnectSocket(host, port); } HASSERT(conn_fd >= 0); create_gc_port_for_can_hub(&can_hub0, conn_fd); g_if_can.add_addressed_message_support(); // Bootstraps the alias allocation process. g_if_can.alias_allocator()->send(g_if_can.alias_allocator()->alloc()); g_executor.start_thread("g_executor", 0, 1024); usleep(400000); openlcb::NodeHandle dst; dst.alias = destination_alias; dst.id = destination_nodeid; HASSERT(do_read); auto b = invoke_flow(&g_memcfg_cli, openlcb::MemoryConfigClientRequest::READ, dst, memory_space_id); if (0 && do_write) { b->data()->payload = read_file_to_string(filename); //b->data()->cmd = openlcb::MemoryConfigClientRequest::WRITE; printf("Read %" PRIdPTR " bytes from file %s. Writing to memory space 0x%02x\n", b->data()->payload.size(), filename, memory_space_id); } printf("Result: %04x\n", b->data()->resultCode); if (do_read) { write_string_to_file(filename, b->data()->payload); fprintf(stderr, "Written %" PRIdPTR " bytes to file %s.\n", b->data()->payload.size(), filename); } return 0; } <commit_msg>update comments and remove deleted code.<commit_after>/** \copyright * Copyright (c) 2013 - 2017, Balazs Racz * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * \file main.cxx * * An application for downloading an entire memory space from a node. * * @author Balazs Racz * @date 7 Sep 2017 */ #include <fcntl.h> #include <getopt.h> #include <stdio.h> #include <unistd.h> #include <memory> #include "os/os.h" #include "utils/constants.hxx" #include "utils/Hub.hxx" #include "utils/GridConnectHub.hxx" #include "utils/GcTcpHub.hxx" #include "utils/Crc.hxx" #include "utils/FileUtils.hxx" #include "executor/Executor.hxx" #include "executor/Service.hxx" #include "openlcb/IfCan.hxx" #include "openlcb/DatagramCan.hxx" #include "openlcb/BootloaderClient.hxx" #include "openlcb/If.hxx" #include "openlcb/AliasAllocator.hxx" #include "openlcb/DefaultNode.hxx" #include "openlcb/NodeInitializeFlow.hxx" #include "openlcb/MemoryConfig.hxx" #include "openlcb/MemoryConfigClient.hxx" #include "utils/socket_listener.hxx" NO_THREAD nt; Executor<1> g_executor(nt); Service g_service(&g_executor); CanHubFlow can_hub0(&g_service); static const openlcb::NodeID NODE_ID = 0x05010101181FULL; openlcb::IfCan g_if_can(&g_executor, &can_hub0, 3, 3, 2); openlcb::InitializeFlow g_init_flow{&g_service}; openlcb::CanDatagramService g_datagram_can(&g_if_can, 10, 2); static openlcb::AddAliasAllocator g_alias_allocator(NODE_ID, &g_if_can); openlcb::DefaultNode g_node(&g_if_can, NODE_ID); openlcb::MemoryConfigHandler g_memcfg(&g_datagram_can, &g_node, 10); openlcb::MemoryConfigClient g_memcfg_cli(&g_node, &g_memcfg); namespace openlcb { Pool *const g_incoming_datagram_allocator = mainBufferPool; } static int port = 12021; static const char *host = "localhost"; static const char *device_path = nullptr; static const char *filename = nullptr; static uint64_t destination_nodeid = 0; static uint64_t destination_alias = 0; static int memory_space_id = openlcb::MemoryConfigDefs::SPACE_CONFIG; static bool do_read = false; static bool do_write = false; void usage(const char *e) { fprintf(stderr, "Usage: %s ([-i destination_host] [-p port] | [-d device_path]) [-s " "memory_space_id] [-c csum_algo] (-r|-w) (-n nodeid | -a " "alias) -f filename\n", e); fprintf(stderr, "Connects to an openlcb bus and performs the " "bootloader protocol on openlcb node with id nodeid with " "the contents of a given file.\n"); fprintf(stderr, "The bus connection will be through an OpenLCB HUB on " "destination_host:port with OpenLCB over TCP " "(in GridConnect format) protocol, or through the CAN-USB device " "(also in GridConnect protocol) found at device_path. Device takes " "precedence over TCP host:port specification."); fprintf(stderr, "The default target is localhost:12021.\n"); fprintf(stderr, "nodeid should be a 12-char hex string with 0x prefix and " "no separators, like '-b 0x05010101141F'\n"); fprintf(stderr, "alias should be a 3-char hex string with 0x prefix and no " "separators, like '-a 0x3F9'\n"); fprintf(stderr, "memory_space_id defines which memory space to use " "data into. Default is '-s 0xF0'.\n"); fprintf(stderr, "-r or -w defines whether to read or write.\n"); exit(1); } void parse_args(int argc, char *argv[]) { int opt; while ((opt = getopt(argc, argv, "hp:d:n:a:s:f:rw")) >= 0) { switch (opt) { case 'h': usage(argv[0]); break; case 'p': port = atoi(optarg); break; case 'i': host = optarg; break; case 'd': device_path = optarg; break; case 'f': filename = optarg; break; case 'n': destination_nodeid = strtoll(optarg, nullptr, 16); break; case 'a': destination_alias = strtoul(optarg, nullptr, 16); break; case 's': memory_space_id = strtol(optarg, nullptr, 16); break; case 'r': do_read = true; break; case 'w': do_write = true; break; default: fprintf(stderr, "Unknown option %c\n", opt); usage(argv[0]); } } if (!filename || (!destination_nodeid && !destination_alias)) { usage(argv[0]); } if ((do_read ? 1 : 0) + (do_write ? 1 : 0) != 1) { fprintf(stderr, "Must set exactly one of option -r and option -w.\n\n"); usage(argv[0]); } } /** Entry point to application. * @param argc number of command line arguments * @param argv array of command line arguments * @return 0, should never return */ int appl_main(int argc, char *argv[]) { parse_args(argc, argv); int conn_fd = 0; if (device_path) { conn_fd = ::open(device_path, O_RDWR); } else { conn_fd = ConnectSocket(host, port); } HASSERT(conn_fd >= 0); create_gc_port_for_can_hub(&can_hub0, conn_fd); g_if_can.add_addressed_message_support(); // Bootstraps the alias allocation process. g_if_can.alias_allocator()->send(g_if_can.alias_allocator()->alloc()); g_executor.start_thread("g_executor", 0, 1024); usleep(400000); openlcb::NodeHandle dst; dst.alias = destination_alias; dst.id = destination_nodeid; HASSERT(do_read); auto b = invoke_flow(&g_memcfg_cli, openlcb::MemoryConfigClientRequest::READ, dst, memory_space_id); if (0 && do_write) { b->data()->payload = read_file_to_string(filename); //b->data()->cmd = openlcb::MemoryConfigClientRequest::WRITE; printf("Read %" PRIdPTR " bytes from file %s. Writing to memory space 0x%02x\n", b->data()->payload.size(), filename, memory_space_id); } printf("Result: %04x\n", b->data()->resultCode); if (do_read) { write_string_to_file(filename, b->data()->payload); fprintf(stderr, "Written %" PRIdPTR " bytes to file %s.\n", b->data()->payload.size(), filename); } return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dlg_CreationWizard.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2007-07-25 08:32:28 $ * * 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_chart2.hxx" #include "dlg_CreationWizard.hxx" #include "dlg_CreationWizard.hrc" #include "ResId.hxx" #include "macros.hxx" #include "Strings.hrc" #include "HelpIds.hrc" #include "tp_ChartType.hxx" #include "tp_RangeChooser.hxx" #include "tp_Wizard_TitlesAndObjects.hxx" #include "tp_Location.hxx" #include "tp_DataSource.hxx" #include "ChartTypeTemplateProvider.hxx" #include "DialogModel.hxx" //............................................................................. namespace chart { //............................................................................. using namespace ::com::sun::star; //#define LOCATION_PAGE 1 #define PATH_FULL 1 #define STATE_FIRST 0 #define STATE_CHARTTYPE STATE_FIRST #define STATE_SIMPLE_RANGE 1 #define STATE_DATA_SERIES 2 #define STATE_OBJECTS 3 #define STATE_LOCATION 4 #ifdef LOCATION_PAGE #define STATE_LAST STATE_LOCATION #else #define STATE_LAST STATE_OBJECTS #endif namespace { #ifdef LOCATION_PAGE const sal_Int32 nPageCount = 5; #else const sal_Int32 nPageCount = 4; #endif } CreationWizard::CreationWizard( Window* pParent, const uno::Reference< frame::XModel >& xChartModel , const uno::Reference< uno::XComponentContext >& xContext , sal_Int32 nOnePageOnlyIndex ) : svt::RoadmapWizard( pParent, SchResId(DLG_CHART_WIZARD) , ( nOnePageOnlyIndex >= 0 && nOnePageOnlyIndex < nPageCount ) ? WZB_HELP | WZB_CANCEL | WZB_FINISH : WZB_HELP | WZB_CANCEL | WZB_PREVIOUS | WZB_NEXT | WZB_FINISH , SchResId( STR_WIZARD_ROADMAP_TITLE ) ) , m_xChartModel(xChartModel,uno::UNO_QUERY) , m_xCC( xContext ) , m_bIsClosable(true) , m_nOnePageOnlyIndex(nOnePageOnlyIndex) , m_pTemplateProvider(0) , m_nFirstState(STATE_FIRST) , m_nLastState(STATE_LAST) , m_aTimerTriggeredControllerLock( xChartModel ) , m_bCanTravel( true ) { m_apDialogModel.reset( new DialogModel( m_xChartModel, m_xCC )); // Do not call FreeResource(), because there are no sub-elements defined in // the dialog resource ShowButtonFixedLine( TRUE ); defaultButton( WZB_FINISH ); if( m_nOnePageOnlyIndex < 0 || m_nOnePageOnlyIndex >= nPageCount ) { m_nOnePageOnlyIndex = -1; this->setTitleBase(String(SchResId(STR_DLG_CHART_WIZARD))); } else this->setTitleBase(String()); declarePath( PATH_FULL , STATE_CHARTTYPE , STATE_SIMPLE_RANGE , STATE_DATA_SERIES , STATE_OBJECTS #ifdef LOCATION_PAGE , STATE_LOCATION #endif , WZS_INVALID_STATE ); this->SetRoadmapSmartHelpId( SmartId( HID_SCH_WIZARD_ROADMAP ) ); this->SetRoadmapInteractive( sal_True ); Size aAdditionalRoadmapSize( LogicToPixel( Size( 85, 0 ), MAP_APPFONT ) ); Size aSize( this->GetSizePixel() ); aSize.Width() += aAdditionalRoadmapSize.Width(); this->SetSizePixel( aSize ); uno::Reference< chart2::XChartDocument > xChartDoc( m_xChartModel, uno::UNO_QUERY ); bool bHasOwnData = (xChartDoc.is() && xChartDoc->hasInternalDataProvider()); if( bHasOwnData ) { this->enableState( STATE_SIMPLE_RANGE, false ); this->enableState( STATE_DATA_SERIES, false ); } // Call ActivatePage, to create and activate the first page ActivatePage(); } CreationWizard::~CreationWizard() { } svt::OWizardPage* CreationWizard::createPage(WizardState nState) { svt::OWizardPage* pRet = 0; if(m_nOnePageOnlyIndex!=-1 && m_nOnePageOnlyIndex!=nState) return pRet; bool bDoLiveUpdate = m_nOnePageOnlyIndex == -1; switch( nState ) { case STATE_CHARTTYPE: { m_aTimerTriggeredControllerLock.startTimer(); ChartTypeTabPage* pChartTypeTabPage = new ChartTypeTabPage(this,m_xChartModel,m_xCC,bDoLiveUpdate); pRet = pChartTypeTabPage; m_pTemplateProvider = pChartTypeTabPage; if( m_pTemplateProvider && m_apDialogModel.get() ) m_apDialogModel->setTemplate( m_pTemplateProvider->getCurrentTemplate()); } break; case STATE_SIMPLE_RANGE: { m_aTimerTriggeredControllerLock.startTimer(); pRet = new RangeChooserTabPage(this,*(m_apDialogModel.get()),m_pTemplateProvider,this); } break; case STATE_DATA_SERIES: { m_aTimerTriggeredControllerLock.startTimer(); pRet = new DataSourceTabPage(this,*(m_apDialogModel.get()),m_pTemplateProvider,this); } break; case STATE_OBJECTS: { pRet = new TitlesAndObjectsTabPage(this,m_xChartModel,m_xCC); m_aTimerTriggeredControllerLock.startTimer(); } break; #ifdef LOCATION_PAGE case STATE_LOCATION: { m_aTimerTriggeredControllerLock.startTimer(); pRet = new LocationTabPage(this,m_xChartModel,m_xCC); } break; #endif default: break; } if(pRet) pRet->SetText(String());//remove title of pages to not get them in the wizard title return pRet; } sal_Bool CreationWizard::leaveState( WizardState /*_nState*/ ) { return m_bCanTravel; } svt::WizardTypes::WizardState CreationWizard::determineNextState(WizardState nCurrentState) { if( !m_bCanTravel ) return WZS_INVALID_STATE; if( nCurrentState == m_nLastState ) return WZS_INVALID_STATE; svt::WizardTypes::WizardState nNextState = nCurrentState + 1; while( !isStateEnabled( nNextState ) && nNextState <= m_nLastState ) ++nNextState; return (nNextState==m_nLastState+1) ? WZS_INVALID_STATE : nNextState; } void CreationWizard::enterState(WizardState nState) { m_aTimerTriggeredControllerLock.startTimer(); enableButtons( WZB_PREVIOUS, bool( nState > m_nFirstState ) ); enableButtons( WZB_NEXT, bool( nState < m_nLastState ) ); if( isStateEnabled( nState )) svt::RoadmapWizard::enterState(nState); } bool CreationWizard::isClosable() { //@todo return m_bIsClosable; } void CreationWizard::setInvalidPage( TabPage * /* pTabPage */ ) { m_bCanTravel = false; } void CreationWizard::setValidPage( TabPage * /* pTabPage */ ) { m_bCanTravel = true; } String CreationWizard::getStateDisplayName( WizardState nState ) { USHORT nResId = 0; switch( nState ) { case STATE_CHARTTYPE: nResId = STR_PAGE_CHARTTYPE; break; case STATE_SIMPLE_RANGE: nResId = STR_PAGE_DATA_RANGE; break; case STATE_DATA_SERIES: nResId = STR_OBJECT_DATASERIES_PLURAL; break; case STATE_OBJECTS: nResId = STR_PAGE_CHART_ELEMENTS; break; #ifdef LOCATION_PAGE case STATE_LOCATION: nResId = STR_PAGE_CHART_LOCATION; break; #endif default: break; } return String(SchResId(nResId)); } //............................................................................. } //namespace chart //............................................................................. <commit_msg>INTEGRATION: CWS odbmacros2 (1.3.56); FILE MERGED 2008/01/15 09:55:46 fs 1.3.56.1: some re-factoring of OWizardMachine, RoadmapWizard and derived classes, to prepare the migration UI for #i49133#<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dlg_CreationWizard.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: kz $ $Date: 2008-03-06 19:16:35 $ * * 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_chart2.hxx" #include "dlg_CreationWizard.hxx" #include "dlg_CreationWizard.hrc" #include "ResId.hxx" #include "macros.hxx" #include "Strings.hrc" #include "HelpIds.hrc" #include "tp_ChartType.hxx" #include "tp_RangeChooser.hxx" #include "tp_Wizard_TitlesAndObjects.hxx" #include "tp_Location.hxx" #include "tp_DataSource.hxx" #include "ChartTypeTemplateProvider.hxx" #include "DialogModel.hxx" //............................................................................. namespace chart { //............................................................................. using namespace ::com::sun::star; //#define LOCATION_PAGE 1 #define PATH_FULL 1 #define STATE_FIRST 0 #define STATE_CHARTTYPE STATE_FIRST #define STATE_SIMPLE_RANGE 1 #define STATE_DATA_SERIES 2 #define STATE_OBJECTS 3 #define STATE_LOCATION 4 #ifdef LOCATION_PAGE #define STATE_LAST STATE_LOCATION #else #define STATE_LAST STATE_OBJECTS #endif namespace { #ifdef LOCATION_PAGE const sal_Int32 nPageCount = 5; #else const sal_Int32 nPageCount = 4; #endif } CreationWizard::CreationWizard( Window* pParent, const uno::Reference< frame::XModel >& xChartModel , const uno::Reference< uno::XComponentContext >& xContext , sal_Int32 nOnePageOnlyIndex ) : svt::RoadmapWizard( pParent, SchResId(DLG_CHART_WIZARD) , ( nOnePageOnlyIndex >= 0 && nOnePageOnlyIndex < nPageCount ) ? WZB_HELP | WZB_CANCEL | WZB_FINISH : WZB_HELP | WZB_CANCEL | WZB_PREVIOUS | WZB_NEXT | WZB_FINISH ) , m_xChartModel(xChartModel,uno::UNO_QUERY) , m_xCC( xContext ) , m_bIsClosable(true) , m_nOnePageOnlyIndex(nOnePageOnlyIndex) , m_pTemplateProvider(0) , m_nFirstState(STATE_FIRST) , m_nLastState(STATE_LAST) , m_aTimerTriggeredControllerLock( xChartModel ) , m_bCanTravel( true ) { m_apDialogModel.reset( new DialogModel( m_xChartModel, m_xCC )); // Do not call FreeResource(), because there are no sub-elements defined in // the dialog resource ShowButtonFixedLine( TRUE ); defaultButton( WZB_FINISH ); if( m_nOnePageOnlyIndex < 0 || m_nOnePageOnlyIndex >= nPageCount ) { m_nOnePageOnlyIndex = -1; this->setTitleBase(String(SchResId(STR_DLG_CHART_WIZARD))); } else this->setTitleBase(String()); declarePath( PATH_FULL , STATE_CHARTTYPE , STATE_SIMPLE_RANGE , STATE_DATA_SERIES , STATE_OBJECTS #ifdef LOCATION_PAGE , STATE_LOCATION #endif , WZS_INVALID_STATE ); this->SetRoadmapSmartHelpId( SmartId( HID_SCH_WIZARD_ROADMAP ) ); this->SetRoadmapInteractive( sal_True ); Size aAdditionalRoadmapSize( LogicToPixel( Size( 85, 0 ), MAP_APPFONT ) ); Size aSize( this->GetSizePixel() ); aSize.Width() += aAdditionalRoadmapSize.Width(); this->SetSizePixel( aSize ); uno::Reference< chart2::XChartDocument > xChartDoc( m_xChartModel, uno::UNO_QUERY ); bool bHasOwnData = (xChartDoc.is() && xChartDoc->hasInternalDataProvider()); if( bHasOwnData ) { this->enableState( STATE_SIMPLE_RANGE, false ); this->enableState( STATE_DATA_SERIES, false ); } // Call ActivatePage, to create and activate the first page ActivatePage(); } CreationWizard::~CreationWizard() { } svt::OWizardPage* CreationWizard::createPage(WizardState nState) { svt::OWizardPage* pRet = 0; if(m_nOnePageOnlyIndex!=-1 && m_nOnePageOnlyIndex!=nState) return pRet; bool bDoLiveUpdate = m_nOnePageOnlyIndex == -1; switch( nState ) { case STATE_CHARTTYPE: { m_aTimerTriggeredControllerLock.startTimer(); ChartTypeTabPage* pChartTypeTabPage = new ChartTypeTabPage(this,m_xChartModel,m_xCC,bDoLiveUpdate); pRet = pChartTypeTabPage; m_pTemplateProvider = pChartTypeTabPage; if( m_pTemplateProvider && m_apDialogModel.get() ) m_apDialogModel->setTemplate( m_pTemplateProvider->getCurrentTemplate()); } break; case STATE_SIMPLE_RANGE: { m_aTimerTriggeredControllerLock.startTimer(); pRet = new RangeChooserTabPage(this,*(m_apDialogModel.get()),m_pTemplateProvider,this); } break; case STATE_DATA_SERIES: { m_aTimerTriggeredControllerLock.startTimer(); pRet = new DataSourceTabPage(this,*(m_apDialogModel.get()),m_pTemplateProvider,this); } break; case STATE_OBJECTS: { pRet = new TitlesAndObjectsTabPage(this,m_xChartModel,m_xCC); m_aTimerTriggeredControllerLock.startTimer(); } break; #ifdef LOCATION_PAGE case STATE_LOCATION: { m_aTimerTriggeredControllerLock.startTimer(); pRet = new LocationTabPage(this,m_xChartModel,m_xCC); } break; #endif default: break; } if(pRet) pRet->SetText(String());//remove title of pages to not get them in the wizard title return pRet; } sal_Bool CreationWizard::leaveState( WizardState /*_nState*/ ) { return m_bCanTravel; } svt::WizardTypes::WizardState CreationWizard::determineNextState( WizardState nCurrentState ) const { if( !m_bCanTravel ) return WZS_INVALID_STATE; if( nCurrentState == m_nLastState ) return WZS_INVALID_STATE; svt::WizardTypes::WizardState nNextState = nCurrentState + 1; while( !isStateEnabled( nNextState ) && nNextState <= m_nLastState ) ++nNextState; return (nNextState==m_nLastState+1) ? WZS_INVALID_STATE : nNextState; } void CreationWizard::enterState(WizardState nState) { m_aTimerTriggeredControllerLock.startTimer(); enableButtons( WZB_PREVIOUS, bool( nState > m_nFirstState ) ); enableButtons( WZB_NEXT, bool( nState < m_nLastState ) ); if( isStateEnabled( nState )) svt::RoadmapWizard::enterState(nState); } bool CreationWizard::isClosable() { //@todo return m_bIsClosable; } void CreationWizard::setInvalidPage( TabPage * /* pTabPage */ ) { m_bCanTravel = false; } void CreationWizard::setValidPage( TabPage * /* pTabPage */ ) { m_bCanTravel = true; } String CreationWizard::getStateDisplayName( WizardState nState ) const { USHORT nResId = 0; switch( nState ) { case STATE_CHARTTYPE: nResId = STR_PAGE_CHARTTYPE; break; case STATE_SIMPLE_RANGE: nResId = STR_PAGE_DATA_RANGE; break; case STATE_DATA_SERIES: nResId = STR_OBJECT_DATASERIES_PLURAL; break; case STATE_OBJECTS: nResId = STR_PAGE_CHART_ELEMENTS; break; #ifdef LOCATION_PAGE case STATE_LOCATION: nResId = STR_PAGE_CHART_LOCATION; break; #endif default: break; } return String(SchResId(nResId)); } //............................................................................. } //namespace chart //............................................................................. <|endoftext|>
<commit_before>// -*- C++ -*- // The MIT License (MIT) // // Copyright (c) 2021 Alexander Samoilov // // 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 "ChebyshevDifferentiate.hpp" /// /// as \f$T_n(\cos\theta)=\cos n\theta\f$, then /// /// \f[ /// \frac{T'_{n+1}(x)}{n+1}-\frac{T'_{n-1}(x)}{n-1}=\frac2{c_n}T_n(x) /// \quad(n>=0) /// \f] /// /// where \f$c_0=2,\,c_n=1\,(n\le1)\f$ and \f$T'_0=T'_{-1}=0\f$, implies if /// /// \f[ /// \frac d{dx}\sum^N_{n=0}a_nT_n(x)=\sum^N_{n=0}b_nT_n(x) /// \f] /// /// then /// /// \f{align*}{ /// \sum^N_{n=0}a_nT'_n(x) /// &=\sum^N_{n=0}c_nb_n\left[T_n(x) /// \frac{T'_{n+1}(x)}{n+1}-\frac{T'_{n-1}(x)}{n-1}\right]\\ /// &=\sum^{N+1}_{n=0}[c_{n-1}b_{n-1}-b_{n+1}]T'_n(x)/n /// \f} /// /// equating \f$T'_n(x)\f$ for \f$n=1,\dots,N+1\f$ /// we derive requrrent equations for Chebyshev polynomials derivatives /// /// \f{alignat*}{{2} /// c_{n-1}b_{n-1}-b_{n+1} &= 2na_n &&\quad(1\le n\le N)\\ /// b_n &=0 &&\quad(n\ge N) /// \f} void SpectralDifferentiate(Eigen::Ref<RowVectorXd> data, Eigen::Ref<RowVectorXd> rslt, double span, unsigned n) { double temp1 = data[n-1], temp2 = data[n-2]; rslt[n-1] = 2.0*n*span*data[n]; rslt[n-2] = 2.0*(n-1)*span*temp1; for (unsigned j=n-3; j>0; j--) { temp1 = data[j]; rslt[j] = rslt[j+2]+2.0*(j+1)*span*temp2; temp2 = temp1; } rslt[0] = 0.5*rslt[2]+span*temp2; rslt[n] = 0.0; } void BoundaryConditions(Eigen::Ref<RowVectorXd> data, Eigen::Ref<RowVectorXd> rslt, unsigned n) { double evens,odds; for (unsigned i=0; i<=n; i++) { evens = odds = 0.0; for (unsigned j=1; j<=n-2; j+=2) { odds -= data(i, j); evens -= data(i, j+1); } for (unsigned j=0; j<=n-2; j++) { rslt(i, j) = data(i, j); } rslt(i, n-1) = odds; rslt(i, n ) = evens-data(i, 0); /* rslt(i, 0) = rslt(i, 1) = 0.0; */ } } <commit_msg>update docs on spectral differentiation.<commit_after>// -*- C++ -*- // The MIT License (MIT) // // Copyright (c) 2021 Alexander Samoilov // // 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 "ChebyshevDifferentiate.hpp" /// /// as \f$T_n(\cos\theta)=\cos n\theta\f$, then /// /// \f[ /// \frac{T'_{n+1}(x)}{n+1}-\frac{T'_{n-1}(x)}{n-1}=\frac2{c_n}T_n(x) /// \quad(n>=0) /// \f] /// /// where \f$c_0=2,\,c_n=1\,(n\le1)\f$ and \f$T'_0=T'_{-1}=0\f$, implies if /// /// \f[ /// \frac d{dx}\sum^N_{n=0}a_nT_n(x)=\sum^N_{n=0}b_nT_n(x) /// \f] /// /// then /// /// \f{align*}{ /// \sum^N_{n=0}a_nT'_n(x) /// &=\sum^N_{n=0}c_nb_n\left[T_n(x) /// \frac{T'_{n+1}(x)}{n+1}-\frac{T'_{n-1}(x)}{n-1}\right]\\ /// &=\sum^{N+1}_{n=0}[c_{n-1}b_{n-1}-b_{n+1}]T'_n(x)/n /// \f} /// /// equating \f$T'_n(x)\f$ for \f$n=1,\dots,N+1\f$ /// we derive recurrent equations for Chebyshev polynomials derivatives /// /// \f{alignat*}{{2} /// c_{n-1}b_{n-1}-b_{n+1} &= 2na_n &&\quad(1\le n\le N)\\ /// b_n &=0 &&\quad(n\ge N) /// \f} /// /// if approximate solution is at each collocation point \f$(x_j)\f$ /// /// \f[ /// u(x,t) = \sum_{k=1}^{N+1}a_{k}T_{k-1}(x) /// \f] /// /// then, in particular, spatial derivatives can be defined directly in terms /// of undifferentiated Chebyshev polynomials, i.e. /// /// \f[ /// \frac{\partial{u}}{\partial{x}} = \sum_{k=1}^{N}a_{k}^{(1)}T_{k-1}(x) /// \f] /// /// and /// /// \f[ /// \frac{\partial^2{u}}{\partial{x^2}} = \sum_{k=1}^{N-1}a_{k}^{(2)}T_{k-1}(x) /// \f] /// /// Specifically, the following recurrence relations permit all /// the \f$a_k^{(1)}, a_k^{(2)}\f$ coefficients to be obtained in \f$O(N)\f$ operations /// /// \f{alignat*}{{2} /// a_k^{(1)} &= a_{k+2}^{(1)} + 2k a_{k+1} &&\quad(2\le k\le N)\\ /// a_k^{(2)} &= a_{k+2}^{(2)} + 2k a_{k+1}^{(1)} &&\quad(2\le k\le N-1)\\ /// \f} /// /// and /// /// \f[ /// a_1^{(1)} = 0.5 a_3^{(1)} + 2k a_2, \quad a_1^{(2)} = 0.5 a_3^{(2)} + 2k a_2^{(1)} /// \f] /// /// and /// /// \f[ /// a_{N+1}^{(1)} = a_{N+2}^{(1)} = 0, \quad a_{N}^{(2)} = a_{N+1}^{(2)} = 0 /// \f] void SpectralDifferentiate(Eigen::Ref<RowVectorXd> data, Eigen::Ref<RowVectorXd> rslt, double span, unsigned n) { double temp1 = data[n-1], temp2 = data[n-2]; rslt[n-1] = 2.0*n*span*data[n]; rslt[n-2] = 2.0*(n-1)*span*temp1; for (unsigned j=n-3; j>0; j--) { temp1 = data[j]; rslt[j] = rslt[j+2]+2.0*(j+1)*span*temp2; temp2 = temp1; } rslt[0] = 0.5*rslt[2]+span*temp2; rslt[n] = 0.0; } void BoundaryConditions(Eigen::Ref<RowVectorXd> data, Eigen::Ref<RowVectorXd> rslt, unsigned n) { double evens,odds; for (unsigned i=0; i<=n; i++) { evens = odds = 0.0; for (unsigned j=1; j<=n-2; j+=2) { odds -= data(i, j); evens -= data(i, j+1); } for (unsigned j=0; j<=n-2; j++) { rslt(i, j) = data(i, j); } rslt(i, n-1) = odds; rslt(i, n ) = evens-data(i, 0); /* rslt(i, 0) = rslt(i, 1) = 0.0; */ } } <|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/ui/gtk/infobars/extension_infobar_gtk.h" #include "base/debug/trace_event.h" #include "chrome/browser/extensions/extension_context_menu_model.h" #include "chrome/browser/extensions/extension_host.h" #include "chrome/browser/extensions/image_loader.h" #include "chrome/browser/platform_util.h" #include "chrome/browser/ui/gtk/browser_window_gtk.h" #include "chrome/browser/ui/gtk/custom_button.h" #include "chrome/browser/ui/gtk/gtk_chrome_button.h" #include "chrome/browser/ui/gtk/gtk_util.h" #include "chrome/browser/ui/gtk/infobars/infobar_container_gtk.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/common/extensions/extension_icon_set.h" #include "chrome/common/extensions/manifest_handlers/icons_handler.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host_view.h" #include "extensions/common/extension_resource.h" #include "grit/theme_resources.h" #include "ui/base/gtk/gtk_signal_registrar.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/canvas.h" #include "ui/gfx/gtk_util.h" #include "ui/gfx/image/image.h" // ExtensionInfoBarDelegate --------------------------------------------------- InfoBar* ExtensionInfoBarDelegate::CreateInfoBar(InfoBarService* owner) { return new ExtensionInfoBarGtk(owner, this); } // ExtensionInfoBarGtk -------------------------------------------------------- ExtensionInfoBarGtk::ExtensionInfoBarGtk(InfoBarService* owner, ExtensionInfoBarDelegate* delegate) : InfoBarGtk(owner, delegate), delegate_(delegate), view_(NULL), button_(NULL), icon_(NULL), alignment_(NULL), weak_ptr_factory_(this) { GetDelegate()->set_observer(this); int height = GetDelegate()->height(); SetBarTargetHeight((height > 0) ? (height + kSeparatorLineHeight) : 0); } ExtensionInfoBarGtk::~ExtensionInfoBarGtk() { if (GetDelegate()) GetDelegate()->set_observer(NULL); } void ExtensionInfoBarGtk::PlatformSpecificHide(bool animate) { DCHECK(view_); DCHECK(alignment_); gtk_util::RemoveAllChildren(alignment_); } void ExtensionInfoBarGtk::GetTopColor(InfoBarDelegate::Type type, double* r, double* g, double* b) { // Extension infobars are always drawn with chrome-theme colors. *r = *g = *b = 233.0 / 255.0; } void ExtensionInfoBarGtk::GetBottomColor(InfoBarDelegate::Type type, double* r, double* g, double* b) { *r = *g = *b = 218.0 / 255.0; } void ExtensionInfoBarGtk::InitWidgets() { InfoBarGtk::InitWidgets(); // Always render the close button as if we were doing chrome style widget // rendering. For extension infobars, we force chrome style rendering because // extension authors are going to expect to match the declared gradient in // extensions_infobar.css, and the close button provided by some GTK+ themes // won't look good on this background. ForceCloseButtonToUseChromeTheme(); icon_ = gtk_image_new(); gtk_misc_set_alignment(GTK_MISC(icon_), 0.5, 0.5); extensions::ExtensionHost* extension_host = GetDelegate()->extension_host(); const extensions::Extension* extension = extension_host->extension(); if (extension->ShowConfigureContextMenus()) { button_ = gtk_chrome_button_new(); gtk_chrome_button_set_use_gtk_rendering(GTK_CHROME_BUTTON(button_), FALSE); g_object_set_data(G_OBJECT(button_), "left-align-popup", reinterpret_cast<void*>(true)); gtk_button_set_image(GTK_BUTTON(button_), icon_); gtk_util::CenterWidgetInHBox(hbox(), button_, false, 0); } else { gtk_util::CenterWidgetInHBox(hbox(), icon_, false, 0); } // Start loading the image for the menu button. extensions::ExtensionResource icon_resource = extensions::IconsInfo::GetIconResource( extension, extension_misc::EXTENSION_ICON_BITTY, ExtensionIconSet::MATCH_EXACTLY); // Load image asynchronously, calling back OnImageLoaded. extensions::ImageLoader* loader = extensions::ImageLoader::Get(extension_host->profile()); loader->LoadImageAsync(extension, icon_resource, gfx::Size(extension_misc::EXTENSION_ICON_BITTY, extension_misc::EXTENSION_ICON_BITTY), base::Bind(&ExtensionInfoBarGtk::OnImageLoaded, weak_ptr_factory_.GetWeakPtr())); // Pad the bottom of the infobar by one pixel for the border. alignment_ = gtk_alignment_new(0.0, 0.0, 1.0, 1.0); gtk_alignment_set_padding(GTK_ALIGNMENT(alignment_), 0, 1, 0, 0); gtk_box_pack_start(GTK_BOX(hbox()), alignment_, TRUE, TRUE, 0); view_ = extension_host->view(); if (gtk_widget_get_parent(view_->native_view())) { gtk_widget_reparent(view_->native_view(), alignment_); } else { gtk_container_add(GTK_CONTAINER(alignment_), view_->native_view()); } if (button_) { signals()->Connect(button_, "button-press-event", G_CALLBACK(&OnButtonPressThunk), this); } signals()->Connect(view_->native_view(), "expose-event", G_CALLBACK(&OnExposeThunk), this); signals()->Connect(view_->native_view(), "size_allocate", G_CALLBACK(&OnSizeAllocateThunk), this); } void ExtensionInfoBarGtk::StoppedShowing() { if (button_) gtk_chrome_button_unset_paint_state(GTK_CHROME_BUTTON(button_)); } void ExtensionInfoBarGtk::OnDelegateDeleted() { delegate_ = NULL; } void ExtensionInfoBarGtk::OnImageLoaded(const gfx::Image& image) { DCHECK(icon_); // TODO(erg): IDR_EXTENSIONS_SECTION should have an IDR_INFOBAR_EXTENSIONS // icon of the correct size with real subpixel shading and such. const gfx::ImageSkia* icon = NULL; ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); if (image.IsEmpty()) icon = rb.GetImageSkiaNamed(IDR_EXTENSIONS_SECTION); else icon = image.ToImageSkia(); SkBitmap bitmap; if (button_) { gfx::ImageSkia* drop_image = rb.GetImageSkiaNamed(IDR_APP_DROPARROW); int image_size = extension_misc::EXTENSION_ICON_BITTY; // The margin between the extension icon and the drop-down arrow bitmap. static const int kDropArrowLeftMargin = 3; scoped_ptr<gfx::Canvas> canvas(new gfx::Canvas( gfx::Size(image_size + kDropArrowLeftMargin + drop_image->width(), image_size), ui::SCALE_FACTOR_100P, false)); canvas->DrawImageInt(*icon, 0, 0, icon->width(), icon->height(), 0, 0, image_size, image_size, false); canvas->DrawImageInt(*drop_image, image_size + kDropArrowLeftMargin, image_size / 2); bitmap = canvas->ExtractImageRep().sk_bitmap(); } else { bitmap = *icon->bitmap(); } GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(bitmap); gtk_image_set_from_pixbuf(GTK_IMAGE(icon_), pixbuf); g_object_unref(pixbuf); } ExtensionInfoBarDelegate* ExtensionInfoBarGtk::GetDelegate() { return delegate_ ? delegate_->AsExtensionInfoBarDelegate() : NULL; } Browser* ExtensionInfoBarGtk::GetBrowser() { DCHECK(icon_); // Get the Browser object this infobar is attached to. GtkWindow* parent = platform_util::GetTopLevel(icon_); return parent ? BrowserWindowGtk::GetBrowserWindowForNativeWindow(parent)->browser() : NULL; } ExtensionContextMenuModel* ExtensionInfoBarGtk::BuildMenuModel() { const extensions::Extension* extension = GetDelegate()->extension(); if (!extension->ShowConfigureContextMenus()) return NULL; Browser* browser = GetBrowser(); if (!browser) return NULL; return new ExtensionContextMenuModel(extension, browser); } void ExtensionInfoBarGtk::OnSizeAllocate(GtkWidget* widget, GtkAllocation* allocation) { gfx::Size new_size(allocation->width, allocation->height); GetDelegate()->extension_host()->view()->render_view_host()->GetView()-> SetSize(new_size); } gboolean ExtensionInfoBarGtk::OnButtonPress(GtkWidget* widget, GdkEventButton* event) { if (event->button != 1) return FALSE; DCHECK(button_); context_menu_model_ = BuildMenuModel(); if (!context_menu_model_.get()) return FALSE; gtk_chrome_button_set_paint_state(GTK_CHROME_BUTTON(widget), GTK_STATE_ACTIVE); ShowMenuWithModel(widget, this, context_menu_model_.get()); return TRUE; } gboolean ExtensionInfoBarGtk::OnExpose(GtkWidget* sender, GdkEventExpose* event) { TRACE_EVENT0("ui::gtk", "ExtensionInfoBarGtk::OnExpose"); // We also need to draw our infobar arrows over the renderer. static_cast<InfoBarContainerGtk*>(container())-> PaintInfobarBitsOn(sender, event, this); return FALSE; } <commit_msg>Missed this linebreak in r212920<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/ui/gtk/infobars/extension_infobar_gtk.h" #include "base/debug/trace_event.h" #include "chrome/browser/extensions/extension_context_menu_model.h" #include "chrome/browser/extensions/extension_host.h" #include "chrome/browser/extensions/image_loader.h" #include "chrome/browser/platform_util.h" #include "chrome/browser/ui/gtk/browser_window_gtk.h" #include "chrome/browser/ui/gtk/custom_button.h" #include "chrome/browser/ui/gtk/gtk_chrome_button.h" #include "chrome/browser/ui/gtk/gtk_util.h" #include "chrome/browser/ui/gtk/infobars/infobar_container_gtk.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/extension_constants.h" #include "chrome/common/extensions/extension_icon_set.h" #include "chrome/common/extensions/manifest_handlers/icons_handler.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host_view.h" #include "extensions/common/extension_resource.h" #include "grit/theme_resources.h" #include "ui/base/gtk/gtk_signal_registrar.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/canvas.h" #include "ui/gfx/gtk_util.h" #include "ui/gfx/image/image.h" // ExtensionInfoBarDelegate --------------------------------------------------- InfoBar* ExtensionInfoBarDelegate::CreateInfoBar(InfoBarService* owner) { return new ExtensionInfoBarGtk(owner, this); } // ExtensionInfoBarGtk -------------------------------------------------------- ExtensionInfoBarGtk::ExtensionInfoBarGtk(InfoBarService* owner, ExtensionInfoBarDelegate* delegate) : InfoBarGtk(owner, delegate), delegate_(delegate), view_(NULL), button_(NULL), icon_(NULL), alignment_(NULL), weak_ptr_factory_(this) { GetDelegate()->set_observer(this); int height = GetDelegate()->height(); SetBarTargetHeight((height > 0) ? (height + kSeparatorLineHeight) : 0); } ExtensionInfoBarGtk::~ExtensionInfoBarGtk() { if (GetDelegate()) GetDelegate()->set_observer(NULL); } void ExtensionInfoBarGtk::PlatformSpecificHide(bool animate) { DCHECK(view_); DCHECK(alignment_); gtk_util::RemoveAllChildren(alignment_); } void ExtensionInfoBarGtk::GetTopColor(InfoBarDelegate::Type type, double* r, double* g, double* b) { // Extension infobars are always drawn with chrome-theme colors. *r = *g = *b = 233.0 / 255.0; } void ExtensionInfoBarGtk::GetBottomColor(InfoBarDelegate::Type type, double* r, double* g, double* b) { *r = *g = *b = 218.0 / 255.0; } void ExtensionInfoBarGtk::InitWidgets() { InfoBarGtk::InitWidgets(); // Always render the close button as if we were doing chrome style widget // rendering. For extension infobars, we force chrome style rendering because // extension authors are going to expect to match the declared gradient in // extensions_infobar.css, and the close button provided by some GTK+ themes // won't look good on this background. ForceCloseButtonToUseChromeTheme(); icon_ = gtk_image_new(); gtk_misc_set_alignment(GTK_MISC(icon_), 0.5, 0.5); extensions::ExtensionHost* extension_host = GetDelegate()->extension_host(); const extensions::Extension* extension = extension_host->extension(); if (extension->ShowConfigureContextMenus()) { button_ = gtk_chrome_button_new(); gtk_chrome_button_set_use_gtk_rendering(GTK_CHROME_BUTTON(button_), FALSE); g_object_set_data(G_OBJECT(button_), "left-align-popup", reinterpret_cast<void*>(true)); gtk_button_set_image(GTK_BUTTON(button_), icon_); gtk_util::CenterWidgetInHBox(hbox(), button_, false, 0); } else { gtk_util::CenterWidgetInHBox(hbox(), icon_, false, 0); } // Start loading the image for the menu button. extensions::ExtensionResource icon_resource = extensions::IconsInfo::GetIconResource( extension, extension_misc::EXTENSION_ICON_BITTY, ExtensionIconSet::MATCH_EXACTLY); // Load image asynchronously, calling back OnImageLoaded. extensions::ImageLoader* loader = extensions::ImageLoader::Get(extension_host->profile()); loader->LoadImageAsync(extension, icon_resource, gfx::Size(extension_misc::EXTENSION_ICON_BITTY, extension_misc::EXTENSION_ICON_BITTY), base::Bind(&ExtensionInfoBarGtk::OnImageLoaded, weak_ptr_factory_.GetWeakPtr())); // Pad the bottom of the infobar by one pixel for the border. alignment_ = gtk_alignment_new(0.0, 0.0, 1.0, 1.0); gtk_alignment_set_padding(GTK_ALIGNMENT(alignment_), 0, 1, 0, 0); gtk_box_pack_start(GTK_BOX(hbox()), alignment_, TRUE, TRUE, 0); view_ = extension_host->view(); if (gtk_widget_get_parent(view_->native_view())) { gtk_widget_reparent(view_->native_view(), alignment_); } else { gtk_container_add(GTK_CONTAINER(alignment_), view_->native_view()); } if (button_) { signals()->Connect(button_, "button-press-event", G_CALLBACK(&OnButtonPressThunk), this); } signals()->Connect(view_->native_view(), "expose-event", G_CALLBACK(&OnExposeThunk), this); signals()->Connect(view_->native_view(), "size_allocate", G_CALLBACK(&OnSizeAllocateThunk), this); } void ExtensionInfoBarGtk::StoppedShowing() { if (button_) gtk_chrome_button_unset_paint_state(GTK_CHROME_BUTTON(button_)); } void ExtensionInfoBarGtk::OnDelegateDeleted() { delegate_ = NULL; } void ExtensionInfoBarGtk::OnImageLoaded(const gfx::Image& image) { DCHECK(icon_); // TODO(erg): IDR_EXTENSIONS_SECTION should have an IDR_INFOBAR_EXTENSIONS // icon of the correct size with real subpixel shading and such. const gfx::ImageSkia* icon = NULL; ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); if (image.IsEmpty()) icon = rb.GetImageSkiaNamed(IDR_EXTENSIONS_SECTION); else icon = image.ToImageSkia(); SkBitmap bitmap; if (button_) { gfx::ImageSkia* drop_image = rb.GetImageSkiaNamed(IDR_APP_DROPARROW); int image_size = extension_misc::EXTENSION_ICON_BITTY; // The margin between the extension icon and the drop-down arrow bitmap. static const int kDropArrowLeftMargin = 3; scoped_ptr<gfx::Canvas> canvas(new gfx::Canvas( gfx::Size(image_size + kDropArrowLeftMargin + drop_image->width(), image_size), ui::SCALE_FACTOR_100P, false)); canvas->DrawImageInt(*icon, 0, 0, icon->width(), icon->height(), 0, 0, image_size, image_size, false); canvas->DrawImageInt(*drop_image, image_size + kDropArrowLeftMargin, image_size / 2); bitmap = canvas->ExtractImageRep().sk_bitmap(); } else { bitmap = *icon->bitmap(); } GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(bitmap); gtk_image_set_from_pixbuf(GTK_IMAGE(icon_), pixbuf); g_object_unref(pixbuf); } ExtensionInfoBarDelegate* ExtensionInfoBarGtk::GetDelegate() { return delegate_ ? delegate_->AsExtensionInfoBarDelegate() : NULL; } Browser* ExtensionInfoBarGtk::GetBrowser() { DCHECK(icon_); // Get the Browser object this infobar is attached to. GtkWindow* parent = platform_util::GetTopLevel(icon_); return parent ? BrowserWindowGtk::GetBrowserWindowForNativeWindow(parent)->browser() : NULL; } ExtensionContextMenuModel* ExtensionInfoBarGtk::BuildMenuModel() { const extensions::Extension* extension = GetDelegate()->extension(); if (!extension->ShowConfigureContextMenus()) return NULL; Browser* browser = GetBrowser(); if (!browser) return NULL; return new ExtensionContextMenuModel(extension, browser); } void ExtensionInfoBarGtk::OnSizeAllocate(GtkWidget* widget, GtkAllocation* allocation) { gfx::Size new_size(allocation->width, allocation->height); GetDelegate()->extension_host()->view()->render_view_host()->GetView()-> SetSize(new_size); } gboolean ExtensionInfoBarGtk::OnButtonPress(GtkWidget* widget, GdkEventButton* event) { if (event->button != 1) return FALSE; DCHECK(button_); context_menu_model_ = BuildMenuModel(); if (!context_menu_model_.get()) return FALSE; gtk_chrome_button_set_paint_state(GTK_CHROME_BUTTON(widget), GTK_STATE_ACTIVE); ShowMenuWithModel(widget, this, context_menu_model_.get()); return TRUE; } gboolean ExtensionInfoBarGtk::OnExpose(GtkWidget* sender, GdkEventExpose* event) { TRACE_EVENT0("ui::gtk", "ExtensionInfoBarGtk::OnExpose"); // We also need to draw our infobar arrows over the renderer. static_cast<InfoBarContainerGtk*>(container())-> PaintInfobarBitsOn(sender, event, this); return FALSE; } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/sync/one_click_signin_sync_starter.h" #include "base/prefs/pref_service.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser_process.h" #if defined(ENABLE_CONFIGURATION_POLICY) #include "chrome/browser/policy/cloud/user_policy_signin_service.h" #include "chrome/browser/policy/cloud/user_policy_signin_service_factory.h" #endif #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_info_cache.h" #include "chrome/browser/profiles/profile_io_data.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/signin/signin_manager.h" #include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/browser/sync/profile_sync_service.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/sync/sync_prefs.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_navigator.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/webui/signin/login_ui_service.h" #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h" #include "chrome/browser/ui/webui/signin/profile_signin_confirmation_dialog.h" #include "chrome/common/url_constants.h" OneClickSigninSyncStarter::OneClickSigninSyncStarter( Profile* profile, Browser* browser, const std::string& session_index, const std::string& email, const std::string& password, StartSyncMode start_mode, bool force_same_tab_navigation, bool confirmation_required) : start_mode_(start_mode), force_same_tab_navigation_(force_same_tab_navigation), confirmation_required_(confirmation_required), weak_pointer_factory_(this) { DCHECK(profile); Initialize(profile, browser); // Start the signin process using the cookies in the cookie jar. SigninManager* manager = SigninManagerFactory::GetForProfile(profile_); SigninManager::OAuthTokenFetchedCallback callback; // Policy is enabled, so pass in a callback to do extra policy-related UI // before signin completes. callback = base::Bind(&OneClickSigninSyncStarter::ConfirmSignin, weak_pointer_factory_.GetWeakPtr()); manager->StartSignInWithCredentials(session_index, email, password, callback); } OneClickSigninSyncStarter::~OneClickSigninSyncStarter() { } void OneClickSigninSyncStarter::Initialize(Profile* profile, Browser* browser) { DCHECK(profile); profile_ = profile; browser_ = browser; // Cache the parent desktop for the browser, so we can reuse that same // desktop for any UI we want to display. if (browser) desktop_type_ = browser->host_desktop_type(); signin_tracker_.reset(new SigninTracker(profile_, this)); // Let the sync service know that setup is in progress so it doesn't start // syncing until the user has finished any configuration. ProfileSyncService* profile_sync_service = GetProfileSyncService(); if (profile_sync_service) profile_sync_service->SetSetupInProgress(true); // Make sure the syncing is not suppressed, otherwise the SigninManager // will not be able to complete sucessfully. browser_sync::SyncPrefs sync_prefs(profile_->GetPrefs()); sync_prefs.SetStartSuppressed(false); } void OneClickSigninSyncStarter::GaiaCredentialsValid() { } void OneClickSigninSyncStarter::ConfirmSignin(const std::string& oauth_token) { DCHECK(!oauth_token.empty()); SigninManager* signin = SigninManagerFactory::GetForProfile(profile_); // If this is a new signin (no authenticated username yet) try loading // policy for this user now, before any signed in services are initialized. // This callback is only invoked for the web-based signin flow - for the old // ClientLogin flow, policy will get loaded once the TokenService finishes // initializing (not ideal, but it's a reasonable fallback). if (signin->GetAuthenticatedUsername().empty()) { #if defined(ENABLE_CONFIGURATION_POLICY) policy::UserPolicySigninService* policy_service = policy::UserPolicySigninServiceFactory::GetForProfile(profile_); policy_service->RegisterPolicyClient( signin->GetUsernameForAuthInProgress(), oauth_token, base::Bind(&OneClickSigninSyncStarter::OnRegisteredForPolicy, weak_pointer_factory_.GetWeakPtr())); return; #else SigninAfterSAMLConfirmation(); #endif } else { // The user is already signed in - just tell SigninManager to continue // with its re-auth flow. signin->CompletePendingSignin(); } } #if defined(ENABLE_CONFIGURATION_POLICY) void OneClickSigninSyncStarter::OnRegisteredForPolicy( scoped_ptr<policy::CloudPolicyClient> client) { SigninManager* signin = SigninManagerFactory::GetForProfile(profile_); // If there's no token for the user (policy registration did not succeed) just // finish signing in. if (!client.get()) { DVLOG(1) << "Policy registration failed"; SigninAfterSAMLConfirmation(); return; } DCHECK(client->is_registered()); DVLOG(1) << "Policy registration succeeded: dm_token=" << client->dm_token(); // Stash away a copy of our CloudPolicyClient (should not already have one). DCHECK(!policy_client_); policy_client_.swap(client); // Allow user to create a new profile before continuing with sign-in. ProfileSigninConfirmationDialog::ShowDialog( profile_, signin->GetUsernameForAuthInProgress(), base::Bind(&OneClickSigninSyncStarter::CancelSigninAndDelete, weak_pointer_factory_.GetWeakPtr()), base::Bind(&OneClickSigninSyncStarter::CreateNewSignedInProfile, weak_pointer_factory_.GetWeakPtr()), base::Bind(&OneClickSigninSyncStarter::LoadPolicyWithCachedClient, weak_pointer_factory_.GetWeakPtr())); } void OneClickSigninSyncStarter::CancelSigninAndDelete() { SigninManagerFactory::GetForProfile(profile_)->SignOut(); // The statement above results in a call to SigninFailed() which will free // this object, so do not refer to the OneClickSigninSyncStarter object // after this point. } void OneClickSigninSyncStarter::LoadPolicyWithCachedClient() { DCHECK(policy_client_); policy::UserPolicySigninService* policy_service = policy::UserPolicySigninServiceFactory::GetForProfile(profile_); policy_service->FetchPolicyForSignedInUser( policy_client_.Pass(), base::Bind(&OneClickSigninSyncStarter::OnPolicyFetchComplete, weak_pointer_factory_.GetWeakPtr())); } void OneClickSigninSyncStarter::OnPolicyFetchComplete(bool success) { // For now, we allow signin to complete even if the policy fetch fails. If // we ever want to change this behavior, we could call // SigninManager::SignOut() here instead. DLOG_IF(ERROR, !success) << "Error fetching policy for user"; DVLOG_IF(1, success) << "Policy fetch successful - completing signin"; SigninManagerFactory::GetForProfile(profile_)->CompletePendingSignin(); } void OneClickSigninSyncStarter::CreateNewSignedInProfile() { SigninManager* signin = SigninManagerFactory::GetForProfile(profile_); DCHECK(!signin->GetUsernameForAuthInProgress().empty()); DCHECK(policy_client_); // Create a new profile and have it call back when done so we can inject our // signin credentials. size_t icon_index = g_browser_process->profile_manager()-> GetProfileInfoCache().ChooseAvatarIconIndexForNewProfile(); ProfileManager::CreateMultiProfileAsync( UTF8ToUTF16(signin->GetUsernameForAuthInProgress()), UTF8ToUTF16(ProfileInfoCache::GetDefaultAvatarIconUrl(icon_index)), base::Bind(&OneClickSigninSyncStarter::CompleteSigninForNewProfile, weak_pointer_factory_.GetWeakPtr()), desktop_type_, false); } void OneClickSigninSyncStarter::CompleteSigninForNewProfile( Profile* new_profile, Profile::CreateStatus status) { DCHECK_NE(profile_, new_profile); if (status == Profile::CREATE_STATUS_FAIL) { // TODO(atwilson): On error, unregister the client to release the DMToken // and surface a better error for the user. NOTREACHED() << "Error creating new profile"; CancelSigninAndDelete(); return; } // Wait until the profile is initialized before we transfer credentials. if (status == Profile::CREATE_STATUS_INITIALIZED) { SigninManager* old_signin_manager = SigninManagerFactory::GetForProfile(profile_); SigninManager* new_signin_manager = SigninManagerFactory::GetForProfile(new_profile); DCHECK(!old_signin_manager->GetUsernameForAuthInProgress().empty()); DCHECK(old_signin_manager->GetAuthenticatedUsername().empty()); DCHECK(new_signin_manager->GetAuthenticatedUsername().empty()); DCHECK(policy_client_); // Copy credentials from the old profile to the just-created profile, // and switch over to tracking that profile. new_signin_manager->CopyCredentialsFrom(*old_signin_manager); ProfileSyncService* profile_sync_service = GetProfileSyncService(); if (profile_sync_service) profile_sync_service->SetSetupInProgress(false); Initialize(new_profile, NULL); DCHECK_EQ(profile_, new_profile); // We've transferred our credentials to the new profile - notify that // the signin for the original profile was cancelled (must do this after // we have called Initialize() with the new profile, as otherwise this // object will get freed when the signin on the old profile is cancelled. old_signin_manager->SignOut(); // Load policy for the just-created profile - once policy has finished // loading the signin process will complete. LoadPolicyWithCachedClient(); } } #endif void OneClickSigninSyncStarter::SigninAfterSAMLConfirmation() { SigninManager* signin = SigninManagerFactory::GetForProfile(profile_); // browser_ can be null for unit tests. if (!browser_ || !confirmation_required_) { // No confirmation required - just sign in the user. signin->CompletePendingSignin(); } else { // Display a confirmation dialog to the user. browser_->window()->ShowOneClickSigninBubble( BrowserWindow::ONE_CLICK_SIGNIN_BUBBLE_TYPE_SAML_MODAL_DIALOG, UTF8ToUTF16(signin->GetUsernameForAuthInProgress()), string16(), // No error message to display. base::Bind(&OneClickSigninSyncStarter::SigninConfirmationComplete, weak_pointer_factory_.GetWeakPtr())); } } void OneClickSigninSyncStarter::SigninConfirmationComplete( StartSyncMode response) { if (response == UNDO_SYNC) { CancelSigninAndDelete(); } else { // If the user clicked the "Advanced" link in the confirmation dialog, then // override the current start_mode_ to bring up the advanced sync settings. if (response == CONFIGURE_SYNC_FIRST) start_mode_ = response; SigninManager* signin = SigninManagerFactory::GetForProfile(profile_); signin->CompletePendingSignin(); } } void OneClickSigninSyncStarter::SigninFailed( const GoogleServiceAuthError& error) { ProfileSyncService* profile_sync_service = GetProfileSyncService(); if (profile_sync_service) profile_sync_service->SetSetupInProgress(false); delete this; } void OneClickSigninSyncStarter::SigninSuccess() { ProfileSyncService* profile_sync_service = GetProfileSyncService(); switch (start_mode_) { case SYNC_WITH_DEFAULT_SETTINGS: if (profile_sync_service) { // Just kick off the sync machine, no need to configure it first. profile_sync_service->OnUserChoseDatatypes(true, syncer::ModelTypeSet()); profile_sync_service->SetSyncSetupCompleted(); profile_sync_service->SetSetupInProgress(false); } break; case CONFIGURE_SYNC_FIRST: ConfigureSync(); default: NOTREACHED() << "Invalid start_mode=" << start_mode_; } delete this; } void OneClickSigninSyncStarter::ConfigureSync() { // Give the user a chance to configure things. We don't clear the // ProfileSyncService::setup_in_progress flag because we don't want sync // to start up until after the configure UI is displayed (the configure UI // will clear the flag when the user is done setting up sync). ProfileSyncService* profile_sync_service = GetProfileSyncService(); LoginUIService* login_ui = LoginUIServiceFactory::GetForProfile(profile_); if (login_ui->current_login_ui()) { login_ui->current_login_ui()->FocusUI(); } else { if (!browser_) { // The user just created a new profile so we need to figure out what // browser to use to display settings. Grab the most recently active // browser or else create a new one. browser_ = chrome::FindLastActiveWithProfile(profile_, desktop_type_); if (!browser_) { browser_ = new Browser(Browser::CreateParams(profile_, desktop_type_)); } browser_->window()->Show(); } if (profile_sync_service) { // Need to navigate to the settings page and display the sync UI. if (force_same_tab_navigation_) { ShowSyncSettingsPageOnSameTab(); } else { chrome::ShowSettingsSubPage(browser_, chrome::kSyncSetupSubPage); } } else { // Sync is disabled - just display the settings page. chrome::ShowSettings(browser_); } } } ProfileSyncService* OneClickSigninSyncStarter::GetProfileSyncService() { ProfileSyncService* service = NULL; if (profile_->IsSyncAccessible()) service = ProfileSyncServiceFactory::GetForProfile(profile_); return service; } void OneClickSigninSyncStarter::ShowSyncSettingsPageOnSameTab() { std::string url = std::string(chrome::kChromeUISettingsURL) + chrome::kSyncSetupSubPage; chrome::NavigateParams params( browser_, GURL(url), content::PAGE_TRANSITION_AUTO_TOPLEVEL); params.disposition = CURRENT_TAB; params.window_action = chrome::NavigateParams::SHOW_WINDOW; chrome::Navigate(&params); } <commit_msg>Fixed merge error - re-added missing break<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/ui/sync/one_click_signin_sync_starter.h" #include "base/prefs/pref_service.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser_process.h" #if defined(ENABLE_CONFIGURATION_POLICY) #include "chrome/browser/policy/cloud/user_policy_signin_service.h" #include "chrome/browser/policy/cloud/user_policy_signin_service_factory.h" #endif #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_info_cache.h" #include "chrome/browser/profiles/profile_io_data.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/signin/signin_manager.h" #include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/browser/sync/profile_sync_service.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/sync/sync_prefs.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_navigator.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/webui/signin/login_ui_service.h" #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h" #include "chrome/browser/ui/webui/signin/profile_signin_confirmation_dialog.h" #include "chrome/common/url_constants.h" OneClickSigninSyncStarter::OneClickSigninSyncStarter( Profile* profile, Browser* browser, const std::string& session_index, const std::string& email, const std::string& password, StartSyncMode start_mode, bool force_same_tab_navigation, bool confirmation_required) : start_mode_(start_mode), force_same_tab_navigation_(force_same_tab_navigation), confirmation_required_(confirmation_required), weak_pointer_factory_(this) { DCHECK(profile); Initialize(profile, browser); // Start the signin process using the cookies in the cookie jar. SigninManager* manager = SigninManagerFactory::GetForProfile(profile_); SigninManager::OAuthTokenFetchedCallback callback; // Policy is enabled, so pass in a callback to do extra policy-related UI // before signin completes. callback = base::Bind(&OneClickSigninSyncStarter::ConfirmSignin, weak_pointer_factory_.GetWeakPtr()); manager->StartSignInWithCredentials(session_index, email, password, callback); } OneClickSigninSyncStarter::~OneClickSigninSyncStarter() { } void OneClickSigninSyncStarter::Initialize(Profile* profile, Browser* browser) { DCHECK(profile); profile_ = profile; browser_ = browser; // Cache the parent desktop for the browser, so we can reuse that same // desktop for any UI we want to display. if (browser) desktop_type_ = browser->host_desktop_type(); signin_tracker_.reset(new SigninTracker(profile_, this)); // Let the sync service know that setup is in progress so it doesn't start // syncing until the user has finished any configuration. ProfileSyncService* profile_sync_service = GetProfileSyncService(); if (profile_sync_service) profile_sync_service->SetSetupInProgress(true); // Make sure the syncing is not suppressed, otherwise the SigninManager // will not be able to complete sucessfully. browser_sync::SyncPrefs sync_prefs(profile_->GetPrefs()); sync_prefs.SetStartSuppressed(false); } void OneClickSigninSyncStarter::GaiaCredentialsValid() { } void OneClickSigninSyncStarter::ConfirmSignin(const std::string& oauth_token) { DCHECK(!oauth_token.empty()); SigninManager* signin = SigninManagerFactory::GetForProfile(profile_); // If this is a new signin (no authenticated username yet) try loading // policy for this user now, before any signed in services are initialized. // This callback is only invoked for the web-based signin flow - for the old // ClientLogin flow, policy will get loaded once the TokenService finishes // initializing (not ideal, but it's a reasonable fallback). if (signin->GetAuthenticatedUsername().empty()) { #if defined(ENABLE_CONFIGURATION_POLICY) policy::UserPolicySigninService* policy_service = policy::UserPolicySigninServiceFactory::GetForProfile(profile_); policy_service->RegisterPolicyClient( signin->GetUsernameForAuthInProgress(), oauth_token, base::Bind(&OneClickSigninSyncStarter::OnRegisteredForPolicy, weak_pointer_factory_.GetWeakPtr())); return; #else SigninAfterSAMLConfirmation(); #endif } else { // The user is already signed in - just tell SigninManager to continue // with its re-auth flow. signin->CompletePendingSignin(); } } #if defined(ENABLE_CONFIGURATION_POLICY) void OneClickSigninSyncStarter::OnRegisteredForPolicy( scoped_ptr<policy::CloudPolicyClient> client) { SigninManager* signin = SigninManagerFactory::GetForProfile(profile_); // If there's no token for the user (policy registration did not succeed) just // finish signing in. if (!client.get()) { DVLOG(1) << "Policy registration failed"; SigninAfterSAMLConfirmation(); return; } DCHECK(client->is_registered()); DVLOG(1) << "Policy registration succeeded: dm_token=" << client->dm_token(); // Stash away a copy of our CloudPolicyClient (should not already have one). DCHECK(!policy_client_); policy_client_.swap(client); // Allow user to create a new profile before continuing with sign-in. ProfileSigninConfirmationDialog::ShowDialog( profile_, signin->GetUsernameForAuthInProgress(), base::Bind(&OneClickSigninSyncStarter::CancelSigninAndDelete, weak_pointer_factory_.GetWeakPtr()), base::Bind(&OneClickSigninSyncStarter::CreateNewSignedInProfile, weak_pointer_factory_.GetWeakPtr()), base::Bind(&OneClickSigninSyncStarter::LoadPolicyWithCachedClient, weak_pointer_factory_.GetWeakPtr())); } void OneClickSigninSyncStarter::CancelSigninAndDelete() { SigninManagerFactory::GetForProfile(profile_)->SignOut(); // The statement above results in a call to SigninFailed() which will free // this object, so do not refer to the OneClickSigninSyncStarter object // after this point. } void OneClickSigninSyncStarter::LoadPolicyWithCachedClient() { DCHECK(policy_client_); policy::UserPolicySigninService* policy_service = policy::UserPolicySigninServiceFactory::GetForProfile(profile_); policy_service->FetchPolicyForSignedInUser( policy_client_.Pass(), base::Bind(&OneClickSigninSyncStarter::OnPolicyFetchComplete, weak_pointer_factory_.GetWeakPtr())); } void OneClickSigninSyncStarter::OnPolicyFetchComplete(bool success) { // For now, we allow signin to complete even if the policy fetch fails. If // we ever want to change this behavior, we could call // SigninManager::SignOut() here instead. DLOG_IF(ERROR, !success) << "Error fetching policy for user"; DVLOG_IF(1, success) << "Policy fetch successful - completing signin"; SigninManagerFactory::GetForProfile(profile_)->CompletePendingSignin(); } void OneClickSigninSyncStarter::CreateNewSignedInProfile() { SigninManager* signin = SigninManagerFactory::GetForProfile(profile_); DCHECK(!signin->GetUsernameForAuthInProgress().empty()); DCHECK(policy_client_); // Create a new profile and have it call back when done so we can inject our // signin credentials. size_t icon_index = g_browser_process->profile_manager()-> GetProfileInfoCache().ChooseAvatarIconIndexForNewProfile(); ProfileManager::CreateMultiProfileAsync( UTF8ToUTF16(signin->GetUsernameForAuthInProgress()), UTF8ToUTF16(ProfileInfoCache::GetDefaultAvatarIconUrl(icon_index)), base::Bind(&OneClickSigninSyncStarter::CompleteSigninForNewProfile, weak_pointer_factory_.GetWeakPtr()), desktop_type_, false); } void OneClickSigninSyncStarter::CompleteSigninForNewProfile( Profile* new_profile, Profile::CreateStatus status) { DCHECK_NE(profile_, new_profile); if (status == Profile::CREATE_STATUS_FAIL) { // TODO(atwilson): On error, unregister the client to release the DMToken // and surface a better error for the user. NOTREACHED() << "Error creating new profile"; CancelSigninAndDelete(); return; } // Wait until the profile is initialized before we transfer credentials. if (status == Profile::CREATE_STATUS_INITIALIZED) { SigninManager* old_signin_manager = SigninManagerFactory::GetForProfile(profile_); SigninManager* new_signin_manager = SigninManagerFactory::GetForProfile(new_profile); DCHECK(!old_signin_manager->GetUsernameForAuthInProgress().empty()); DCHECK(old_signin_manager->GetAuthenticatedUsername().empty()); DCHECK(new_signin_manager->GetAuthenticatedUsername().empty()); DCHECK(policy_client_); // Copy credentials from the old profile to the just-created profile, // and switch over to tracking that profile. new_signin_manager->CopyCredentialsFrom(*old_signin_manager); ProfileSyncService* profile_sync_service = GetProfileSyncService(); if (profile_sync_service) profile_sync_service->SetSetupInProgress(false); Initialize(new_profile, NULL); DCHECK_EQ(profile_, new_profile); // We've transferred our credentials to the new profile - notify that // the signin for the original profile was cancelled (must do this after // we have called Initialize() with the new profile, as otherwise this // object will get freed when the signin on the old profile is cancelled. old_signin_manager->SignOut(); // Load policy for the just-created profile - once policy has finished // loading the signin process will complete. LoadPolicyWithCachedClient(); } } #endif void OneClickSigninSyncStarter::SigninAfterSAMLConfirmation() { SigninManager* signin = SigninManagerFactory::GetForProfile(profile_); // browser_ can be null for unit tests. if (!browser_ || !confirmation_required_) { // No confirmation required - just sign in the user. signin->CompletePendingSignin(); } else { // Display a confirmation dialog to the user. browser_->window()->ShowOneClickSigninBubble( BrowserWindow::ONE_CLICK_SIGNIN_BUBBLE_TYPE_SAML_MODAL_DIALOG, UTF8ToUTF16(signin->GetUsernameForAuthInProgress()), string16(), // No error message to display. base::Bind(&OneClickSigninSyncStarter::SigninConfirmationComplete, weak_pointer_factory_.GetWeakPtr())); } } void OneClickSigninSyncStarter::SigninConfirmationComplete( StartSyncMode response) { if (response == UNDO_SYNC) { CancelSigninAndDelete(); } else { // If the user clicked the "Advanced" link in the confirmation dialog, then // override the current start_mode_ to bring up the advanced sync settings. if (response == CONFIGURE_SYNC_FIRST) start_mode_ = response; SigninManager* signin = SigninManagerFactory::GetForProfile(profile_); signin->CompletePendingSignin(); } } void OneClickSigninSyncStarter::SigninFailed( const GoogleServiceAuthError& error) { ProfileSyncService* profile_sync_service = GetProfileSyncService(); if (profile_sync_service) profile_sync_service->SetSetupInProgress(false); delete this; } void OneClickSigninSyncStarter::SigninSuccess() { ProfileSyncService* profile_sync_service = GetProfileSyncService(); switch (start_mode_) { case SYNC_WITH_DEFAULT_SETTINGS: if (profile_sync_service) { // Just kick off the sync machine, no need to configure it first. profile_sync_service->OnUserChoseDatatypes(true, syncer::ModelTypeSet()); profile_sync_service->SetSyncSetupCompleted(); profile_sync_service->SetSetupInProgress(false); } break; case CONFIGURE_SYNC_FIRST: ConfigureSync(); break; default: NOTREACHED() << "Invalid start_mode=" << start_mode_; } delete this; } void OneClickSigninSyncStarter::ConfigureSync() { // Give the user a chance to configure things. We don't clear the // ProfileSyncService::setup_in_progress flag because we don't want sync // to start up until after the configure UI is displayed (the configure UI // will clear the flag when the user is done setting up sync). ProfileSyncService* profile_sync_service = GetProfileSyncService(); LoginUIService* login_ui = LoginUIServiceFactory::GetForProfile(profile_); if (login_ui->current_login_ui()) { login_ui->current_login_ui()->FocusUI(); } else { if (!browser_) { // The user just created a new profile so we need to figure out what // browser to use to display settings. Grab the most recently active // browser or else create a new one. browser_ = chrome::FindLastActiveWithProfile(profile_, desktop_type_); if (!browser_) { browser_ = new Browser(Browser::CreateParams(profile_, desktop_type_)); } browser_->window()->Show(); } if (profile_sync_service) { // Need to navigate to the settings page and display the sync UI. if (force_same_tab_navigation_) { ShowSyncSettingsPageOnSameTab(); } else { chrome::ShowSettingsSubPage(browser_, chrome::kSyncSetupSubPage); } } else { // Sync is disabled - just display the settings page. chrome::ShowSettings(browser_); } } } ProfileSyncService* OneClickSigninSyncStarter::GetProfileSyncService() { ProfileSyncService* service = NULL; if (profile_->IsSyncAccessible()) service = ProfileSyncServiceFactory::GetForProfile(profile_); return service; } void OneClickSigninSyncStarter::ShowSyncSettingsPageOnSameTab() { std::string url = std::string(chrome::kChromeUISettingsURL) + chrome::kSyncSetupSubPage; chrome::NavigateParams params( browser_, GURL(url), content::PAGE_TRANSITION_AUTO_TOPLEVEL); params.disposition = CURRENT_TAB; params.window_action = chrome::NavigateParams::SHOW_WINDOW; chrome::Navigate(&params); } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/views/content_blocked_bubble_contents.h" #if defined(OS_LINUX) #include <gdk/gdk.h> #endif #include "app/l10n_util.h" #include "chrome/browser/blocked_popup_container.h" #include "chrome/browser/content_setting_bubble_model.h" #include "chrome/browser/host_content_settings_map.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/views/browser_dialogs.h" #include "chrome/browser/views/info_bubble.h" #include "chrome/common/notification_source.h" #include "chrome/common/notification_type.h" #include "grit/generated_resources.h" #include "views/controls/button/native_button.h" #include "views/controls/button/radio_button.h" #include "views/controls/image_view.h" #include "views/controls/label.h" #include "views/controls/separator.h" #include "views/grid_layout.h" #include "views/standard_layout.h" class ContentSettingBubbleContents::Favicon : public views::ImageView { public: Favicon(const SkBitmap& image, ContentSettingBubbleContents* parent, views::Link* link); virtual ~Favicon(); private: #if defined(OS_WIN) static HCURSOR g_hand_cursor; #endif // views::View overrides: virtual bool OnMousePressed(const views::MouseEvent& event); virtual void OnMouseReleased(const views::MouseEvent& event, bool canceled); virtual gfx::NativeCursor GetCursorForPoint( views::Event::EventType event_type, const gfx::Point& p); ContentSettingBubbleContents* parent_; views::Link* link_; }; #if defined(OS_WIN) HCURSOR ContentSettingBubbleContents::Favicon::g_hand_cursor = NULL; #endif ContentSettingBubbleContents::Favicon::Favicon( const SkBitmap& image, ContentSettingBubbleContents* parent, views::Link* link) : parent_(parent), link_(link) { SetImage(image); } ContentSettingBubbleContents::Favicon::~Favicon() { } bool ContentSettingBubbleContents::Favicon::OnMousePressed( const views::MouseEvent& event) { return event.IsLeftMouseButton() || event.IsMiddleMouseButton(); } void ContentSettingBubbleContents::Favicon::OnMouseReleased( const views::MouseEvent& event, bool canceled) { if (!canceled && (event.IsLeftMouseButton() || event.IsMiddleMouseButton()) && HitTest(event.location())) parent_->LinkActivated(link_, event.GetFlags()); } gfx::NativeCursor ContentSettingBubbleContents::Favicon::GetCursorForPoint( views::Event::EventType event_type, const gfx::Point& p) { #if defined(OS_WIN) if (!g_hand_cursor) g_hand_cursor = LoadCursor(NULL, IDC_HAND); return g_hand_cursor; #elif defined(OS_LINUX) return gdk_cursor_new(GDK_HAND2); #endif } ContentSettingBubbleContents::ContentSettingBubbleContents( ContentSettingBubbleModel* content_setting_bubble_model, Profile* profile, TabContents* tab_contents) : content_setting_bubble_model_(content_setting_bubble_model), profile_(profile), tab_contents_(tab_contents), info_bubble_(NULL), close_button_(NULL), manage_link_(NULL), clear_link_(NULL) { registrar_.Add(this, NotificationType::TAB_CONTENTS_DESTROYED, Source<TabContents>(tab_contents)); } ContentSettingBubbleContents::~ContentSettingBubbleContents() { } void ContentSettingBubbleContents::ViewHierarchyChanged(bool is_add, View* parent, View* child) { if (is_add && (child == this)) InitControlLayout(); } void ContentSettingBubbleContents::ButtonPressed(views::Button* sender, const views::Event& event) { if (sender == close_button_) { info_bubble_->Close(); // CAREFUL: This deletes us. return; } for (RadioGroup::const_iterator i = radio_group_.begin(); i != radio_group_.end(); ++i) { if (sender == *i) { content_setting_bubble_model_->OnRadioClicked(i - radio_group_.begin()); return; } } NOTREACHED() << "unknown radio"; } void ContentSettingBubbleContents::LinkActivated(views::Link* source, int event_flags) { if (source == manage_link_) { content_setting_bubble_model_->OnManageLinkClicked(); // CAREFUL: Showing the settings window activates it, which deactivates the // info bubble, which causes it to close, which deletes us. return; } if (source == clear_link_) { content_setting_bubble_model_->OnClearLinkClicked(); info_bubble_->Close(); // CAREFUL: This deletes us. return; } PopupLinks::const_iterator i(popup_links_.find(source)); DCHECK(i != popup_links_.end()); content_setting_bubble_model_->OnPopupClicked(i->second); } void ContentSettingBubbleContents::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { DCHECK(type == NotificationType::TAB_CONTENTS_DESTROYED); DCHECK(source == Source<TabContents>(tab_contents_)); tab_contents_ = NULL; } void ContentSettingBubbleContents::InitControlLayout() { using views::GridLayout; GridLayout* layout = new views::GridLayout(this); SetLayoutManager(layout); const int single_column_set_id = 0; views::ColumnSet* column_set = layout->AddColumnSet(single_column_set_id); column_set->AddColumn(GridLayout::LEADING, GridLayout::FILL, 1, GridLayout::USE_PREF, 0, 0); const ContentSettingBubbleModel::BubbleContent& bubble_content = content_setting_bubble_model_->bubble_content(); if (!bubble_content.title.empty()) { views::Label* title_label = new views::Label(UTF8ToWide( bubble_content.title)); layout->StartRow(0, single_column_set_id); layout->AddView(title_label); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); } if (content_setting_bubble_model_->content_type() == CONTENT_SETTINGS_TYPE_POPUPS) { const int popup_column_set_id = 2; views::ColumnSet* popup_column_set = layout->AddColumnSet(popup_column_set_id); popup_column_set->AddColumn(GridLayout::LEADING, GridLayout::FILL, 0, GridLayout::USE_PREF, 0, 0); popup_column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing); popup_column_set->AddColumn(GridLayout::LEADING, GridLayout::FILL, 1, GridLayout::USE_PREF, 0, 0); for (std::vector<ContentSettingBubbleModel::PopupItem>::const_iterator i(bubble_content.popup_items.begin()); i != bubble_content.popup_items.end(); ++i) { if (i != bubble_content.popup_items.begin()) layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); layout->StartRow(0, popup_column_set_id); views::Link* link = new views::Link(UTF8ToWide(i->title)); link->SetController(this); popup_links_[link] = i - bubble_content.popup_items.begin(); layout->AddView(new Favicon((*i).bitmap, this, link)); layout->AddView(link); } layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); views::Separator* separator = new views::Separator; layout->StartRow(0, single_column_set_id); layout->AddView(separator); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); } const ContentSettingBubbleModel::RadioGroup& radio_group = bubble_content.radio_group; for (ContentSettingBubbleModel::RadioItems::const_iterator i = radio_group.radio_items.begin(); i != radio_group.radio_items.end(); ++i) { views::RadioButton* radio = new views::RadioButton( UTF8ToWide(*i), i - radio_group.radio_items.begin()); radio->set_listener(this); radio->SetEnabled(radio_group.is_mutable); radio_group_.push_back(radio); layout->StartRow(0, single_column_set_id); layout->AddView(radio); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); } if (!radio_group_.empty()) { views::Separator* separator = new views::Separator; layout->StartRow(0, single_column_set_id); layout->AddView(separator, 1, 1, GridLayout::FILL, GridLayout::FILL); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); // Now that the buttons have been added to the view hierarchy, it's safe // to call SetChecked() on them. radio_group_[radio_group.default_item]->SetChecked(true); } gfx::Font domain_font = views::Label().font().DeriveFont(0, gfx::Font::BOLD); const int indented_single_column_set_id = 3; // Insert a column set to indent the domain list. views::ColumnSet* indented_single_column_set = layout->AddColumnSet(indented_single_column_set_id); indented_single_column_set->AddPaddingColumn(0, kPanelHorizIndentation); indented_single_column_set->AddColumn(GridLayout::LEADING, GridLayout::FILL, 1, GridLayout::USE_PREF, 0, 0); for (std::vector<ContentSettingBubbleModel::DomainList>::const_iterator i = bubble_content.domain_lists.begin(); i != bubble_content.domain_lists.end(); ++i) { layout->StartRow(0, single_column_set_id); views::Label* section_title = new views::Label(UTF8ToWide(i->title)); section_title->SetMultiLine(true); // TODO(joth): Should need to have hard coded size here, but without it // we get empty space at very end of bubble (as it's initially sized really // tall & skinny but then widens once the link/buttons are added // at the end of this method). section_title->SizeToFit(256); section_title->SetHorizontalAlignment(views::Label::ALIGN_LEFT); layout->AddView(section_title, 1, 1, GridLayout::FILL, GridLayout::LEADING); for (std::set<std::string>::const_iterator j = i->hosts.begin(); j != i->hosts.end(); ++j) { layout->StartRow(0, indented_single_column_set_id); layout->AddView(new views::Label(UTF8ToWide(*j), domain_font)); } layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); } if (!bubble_content.clear_link.empty()) { clear_link_ = new views::Link(UTF8ToWide(bubble_content.clear_link)); clear_link_->SetController(this); layout->StartRow(0, single_column_set_id); layout->AddView(clear_link_); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); layout->StartRow(0, single_column_set_id); layout->AddView(new views::Separator, 1, 1, GridLayout::FILL, GridLayout::FILL); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); } const int double_column_set_id = 1; views::ColumnSet* double_column_set = layout->AddColumnSet(double_column_set_id); double_column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 1, GridLayout::USE_PREF, 0, 0); double_column_set->AddPaddingColumn(0, kUnrelatedControlHorizontalSpacing); double_column_set->AddColumn(GridLayout::TRAILING, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, double_column_set_id); manage_link_ = new views::Link(UTF8ToWide(bubble_content.manage_link)); manage_link_->SetController(this); layout->AddView(manage_link_); close_button_ = new views::NativeButton(this, l10n_util::GetString(IDS_DONE)); layout->AddView(close_button_); } <commit_msg>Make radios in the content bubble a radio group.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/views/content_blocked_bubble_contents.h" #if defined(OS_LINUX) #include <gdk/gdk.h> #endif #include "app/l10n_util.h" #include "chrome/browser/blocked_popup_container.h" #include "chrome/browser/content_setting_bubble_model.h" #include "chrome/browser/host_content_settings_map.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/views/browser_dialogs.h" #include "chrome/browser/views/info_bubble.h" #include "chrome/common/notification_source.h" #include "chrome/common/notification_type.h" #include "grit/generated_resources.h" #include "views/controls/button/native_button.h" #include "views/controls/button/radio_button.h" #include "views/controls/image_view.h" #include "views/controls/label.h" #include "views/controls/separator.h" #include "views/grid_layout.h" #include "views/standard_layout.h" class ContentSettingBubbleContents::Favicon : public views::ImageView { public: Favicon(const SkBitmap& image, ContentSettingBubbleContents* parent, views::Link* link); virtual ~Favicon(); private: #if defined(OS_WIN) static HCURSOR g_hand_cursor; #endif // views::View overrides: virtual bool OnMousePressed(const views::MouseEvent& event); virtual void OnMouseReleased(const views::MouseEvent& event, bool canceled); virtual gfx::NativeCursor GetCursorForPoint( views::Event::EventType event_type, const gfx::Point& p); ContentSettingBubbleContents* parent_; views::Link* link_; }; #if defined(OS_WIN) HCURSOR ContentSettingBubbleContents::Favicon::g_hand_cursor = NULL; #endif ContentSettingBubbleContents::Favicon::Favicon( const SkBitmap& image, ContentSettingBubbleContents* parent, views::Link* link) : parent_(parent), link_(link) { SetImage(image); } ContentSettingBubbleContents::Favicon::~Favicon() { } bool ContentSettingBubbleContents::Favicon::OnMousePressed( const views::MouseEvent& event) { return event.IsLeftMouseButton() || event.IsMiddleMouseButton(); } void ContentSettingBubbleContents::Favicon::OnMouseReleased( const views::MouseEvent& event, bool canceled) { if (!canceled && (event.IsLeftMouseButton() || event.IsMiddleMouseButton()) && HitTest(event.location())) parent_->LinkActivated(link_, event.GetFlags()); } gfx::NativeCursor ContentSettingBubbleContents::Favicon::GetCursorForPoint( views::Event::EventType event_type, const gfx::Point& p) { #if defined(OS_WIN) if (!g_hand_cursor) g_hand_cursor = LoadCursor(NULL, IDC_HAND); return g_hand_cursor; #elif defined(OS_LINUX) return gdk_cursor_new(GDK_HAND2); #endif } ContentSettingBubbleContents::ContentSettingBubbleContents( ContentSettingBubbleModel* content_setting_bubble_model, Profile* profile, TabContents* tab_contents) : content_setting_bubble_model_(content_setting_bubble_model), profile_(profile), tab_contents_(tab_contents), info_bubble_(NULL), close_button_(NULL), manage_link_(NULL), clear_link_(NULL) { registrar_.Add(this, NotificationType::TAB_CONTENTS_DESTROYED, Source<TabContents>(tab_contents)); } ContentSettingBubbleContents::~ContentSettingBubbleContents() { } void ContentSettingBubbleContents::ViewHierarchyChanged(bool is_add, View* parent, View* child) { if (is_add && (child == this)) InitControlLayout(); } void ContentSettingBubbleContents::ButtonPressed(views::Button* sender, const views::Event& event) { if (sender == close_button_) { info_bubble_->Close(); // CAREFUL: This deletes us. return; } for (RadioGroup::const_iterator i = radio_group_.begin(); i != radio_group_.end(); ++i) { if (sender == *i) { content_setting_bubble_model_->OnRadioClicked(i - radio_group_.begin()); return; } } NOTREACHED() << "unknown radio"; } void ContentSettingBubbleContents::LinkActivated(views::Link* source, int event_flags) { if (source == manage_link_) { content_setting_bubble_model_->OnManageLinkClicked(); // CAREFUL: Showing the settings window activates it, which deactivates the // info bubble, which causes it to close, which deletes us. return; } if (source == clear_link_) { content_setting_bubble_model_->OnClearLinkClicked(); info_bubble_->Close(); // CAREFUL: This deletes us. return; } PopupLinks::const_iterator i(popup_links_.find(source)); DCHECK(i != popup_links_.end()); content_setting_bubble_model_->OnPopupClicked(i->second); } void ContentSettingBubbleContents::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { DCHECK(type == NotificationType::TAB_CONTENTS_DESTROYED); DCHECK(source == Source<TabContents>(tab_contents_)); tab_contents_ = NULL; } void ContentSettingBubbleContents::InitControlLayout() { using views::GridLayout; GridLayout* layout = new views::GridLayout(this); SetLayoutManager(layout); const int single_column_set_id = 0; views::ColumnSet* column_set = layout->AddColumnSet(single_column_set_id); column_set->AddColumn(GridLayout::LEADING, GridLayout::FILL, 1, GridLayout::USE_PREF, 0, 0); const ContentSettingBubbleModel::BubbleContent& bubble_content = content_setting_bubble_model_->bubble_content(); if (!bubble_content.title.empty()) { views::Label* title_label = new views::Label(UTF8ToWide( bubble_content.title)); layout->StartRow(0, single_column_set_id); layout->AddView(title_label); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); } if (content_setting_bubble_model_->content_type() == CONTENT_SETTINGS_TYPE_POPUPS) { const int popup_column_set_id = 2; views::ColumnSet* popup_column_set = layout->AddColumnSet(popup_column_set_id); popup_column_set->AddColumn(GridLayout::LEADING, GridLayout::FILL, 0, GridLayout::USE_PREF, 0, 0); popup_column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing); popup_column_set->AddColumn(GridLayout::LEADING, GridLayout::FILL, 1, GridLayout::USE_PREF, 0, 0); for (std::vector<ContentSettingBubbleModel::PopupItem>::const_iterator i(bubble_content.popup_items.begin()); i != bubble_content.popup_items.end(); ++i) { if (i != bubble_content.popup_items.begin()) layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); layout->StartRow(0, popup_column_set_id); views::Link* link = new views::Link(UTF8ToWide(i->title)); link->SetController(this); popup_links_[link] = i - bubble_content.popup_items.begin(); layout->AddView(new Favicon((*i).bitmap, this, link)); layout->AddView(link); } layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); views::Separator* separator = new views::Separator; layout->StartRow(0, single_column_set_id); layout->AddView(separator); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); } const ContentSettingBubbleModel::RadioGroup& radio_group = bubble_content.radio_group; for (ContentSettingBubbleModel::RadioItems::const_iterator i = radio_group.radio_items.begin(); i != radio_group.radio_items.end(); ++i) { views::RadioButton* radio = new views::RadioButton(UTF8ToWide(*i), 0); radio->set_listener(this); radio->SetEnabled(radio_group.is_mutable); radio_group_.push_back(radio); layout->StartRow(0, single_column_set_id); layout->AddView(radio); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); } if (!radio_group_.empty()) { views::Separator* separator = new views::Separator; layout->StartRow(0, single_column_set_id); layout->AddView(separator, 1, 1, GridLayout::FILL, GridLayout::FILL); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); // Now that the buttons have been added to the view hierarchy, it's safe // to call SetChecked() on them. radio_group_[radio_group.default_item]->SetChecked(true); } gfx::Font domain_font = views::Label().font().DeriveFont(0, gfx::Font::BOLD); const int indented_single_column_set_id = 3; // Insert a column set to indent the domain list. views::ColumnSet* indented_single_column_set = layout->AddColumnSet(indented_single_column_set_id); indented_single_column_set->AddPaddingColumn(0, kPanelHorizIndentation); indented_single_column_set->AddColumn(GridLayout::LEADING, GridLayout::FILL, 1, GridLayout::USE_PREF, 0, 0); for (std::vector<ContentSettingBubbleModel::DomainList>::const_iterator i = bubble_content.domain_lists.begin(); i != bubble_content.domain_lists.end(); ++i) { layout->StartRow(0, single_column_set_id); views::Label* section_title = new views::Label(UTF8ToWide(i->title)); section_title->SetMultiLine(true); // TODO(joth): Should need to have hard coded size here, but without it // we get empty space at very end of bubble (as it's initially sized really // tall & skinny but then widens once the link/buttons are added // at the end of this method). section_title->SizeToFit(256); section_title->SetHorizontalAlignment(views::Label::ALIGN_LEFT); layout->AddView(section_title, 1, 1, GridLayout::FILL, GridLayout::LEADING); for (std::set<std::string>::const_iterator j = i->hosts.begin(); j != i->hosts.end(); ++j) { layout->StartRow(0, indented_single_column_set_id); layout->AddView(new views::Label(UTF8ToWide(*j), domain_font)); } layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); } if (!bubble_content.clear_link.empty()) { clear_link_ = new views::Link(UTF8ToWide(bubble_content.clear_link)); clear_link_->SetController(this); layout->StartRow(0, single_column_set_id); layout->AddView(clear_link_); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); layout->StartRow(0, single_column_set_id); layout->AddView(new views::Separator, 1, 1, GridLayout::FILL, GridLayout::FILL); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); } const int double_column_set_id = 1; views::ColumnSet* double_column_set = layout->AddColumnSet(double_column_set_id); double_column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 1, GridLayout::USE_PREF, 0, 0); double_column_set->AddPaddingColumn(0, kUnrelatedControlHorizontalSpacing); double_column_set->AddColumn(GridLayout::TRAILING, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, double_column_set_id); manage_link_ = new views::Link(UTF8ToWide(bubble_content.manage_link)); manage_link_->SetController(this); layout->AddView(manage_link_); close_button_ = new views::NativeButton(this, l10n_util::GetString(IDS_DONE)); layout->AddView(close_button_); } <|endoftext|>
<commit_before>/* * TrellisPath.cpp * * Created on: 16 Mar 2016 * Author: hieu */ #include <cassert> #include <sstream> #include "TrellisPath.h" #include "TrellisPaths.h" #include "Hypothesis.h" #include "../System.h" using namespace std; namespace Moses2 { void TrellisNode::Debug(std::ostream &out, const System &system) const { out << "arcList=" << arcList->size() << " " << ind; } ///////////////////////////////////////////////////////////////////////////////// TrellisPath::TrellisPath(const Hypothesis *hypo, const ArcLists &arcLists) : prevEdgeChanged(-1) { AddNodes(hypo, arcLists); m_scores = &hypo->GetScores(); } TrellisPath::TrellisPath(const TrellisPath &origPath, size_t edgeIndex, const TrellisNode &newNode, const ArcLists &arcLists, MemPool &pool, const System &system) : prevEdgeChanged(edgeIndex) { nodes.reserve(origPath.nodes.size()); for (size_t currEdge = 0; currEdge < edgeIndex; currEdge++) { // copy path from parent nodes.push_back(origPath.nodes[currEdge]); } // 1 deviation nodes.push_back(newNode); // rest of path comes from following best path backwards const Hypothesis *arc = static_cast<const Hypothesis*>(newNode.GetHypo()); const Hypothesis *prevHypo = arc->GetPrevHypo(); while (prevHypo != NULL) { const ArcList *arcList = arcLists.GetArcList(prevHypo); assert(arcList); TrellisNode node(*arcList, 0); nodes.push_back(node); prevHypo = prevHypo->GetPrevHypo(); } const TrellisNode &origNode = origPath.nodes[edgeIndex]; const HypothesisBase *origHypo = origNode.GetHypo(); const HypothesisBase *newHypo = newNode.GetHypo(); CalcScores(origPath.GetScores(), origHypo->GetScores(), newHypo->GetScores(), pool, system); } TrellisPath::~TrellisPath() { // TODO Auto-generated destructor stub } SCORE TrellisPath::GetFutureScore() const { return m_scores->GetTotalScore(); } void TrellisPath::Debug(std::ostream &out, const System &system) const { out << ToString(); out << "||| "; GetScores().Debug(out, system); out << "||| "; out << GetScores().GetTotalScore(); } std::string TrellisPath::ToString() const { //cerr << "path=" << this << " " << nodes.size() << endl; std::stringstream out; for (int i = nodes.size() - 1; i >= 0; --i) { const TrellisNode &node = nodes[i]; const Hypothesis *hypo = static_cast<const Hypothesis*>(node.GetHypo()); //cerr << "hypo=" << hypo << " " << *hypo << endl; hypo->GetTargetPhrase().Debug(out); out << " "; } return out.str(); } void TrellisPath::CreateDeviantPaths(TrellisPaths &paths, const ArcLists &arcLists, MemPool &pool, const System &system) const { const size_t sizePath = nodes.size(); //cerr << "prevEdgeChanged=" << prevEdgeChanged << endl; for (size_t currEdge = prevEdgeChanged + 1; currEdge < sizePath; currEdge++) { TrellisNode newNode = nodes[currEdge]; assert(newNode.ind == 0); const ArcList &arcList = *newNode.arcList; //cerr << "arcList=" << arcList.size() << endl; for (size_t i = 1; i < arcList.size(); ++i) { //cerr << "i=" << i << endl; newNode.ind = i; TrellisPath *deviantPath = new TrellisPath(*this, currEdge, newNode, arcLists, pool, system); //cerr << "deviantPath=" << deviantPath << endl; paths.Add(deviantPath); } } } void TrellisPath::CalcScores(const Scores &origScores, const Scores &origHypoScores, const Scores &newHypoScores, MemPool &pool, const System &system) { Scores *scores = new (pool.Allocate<Scores>()) Scores(system, pool, system.featureFunctions.GetNumScores(), origScores); scores->PlusEquals(system, newHypoScores); scores->MinusEquals(system, origHypoScores); m_scores = scores; } void TrellisPath::AddNodes(const Hypothesis *hypo, const ArcLists &arcLists) { if (hypo) { // add this hypo //cerr << "hypo=" << hypo << " " << flush; //cerr << *hypo << endl; const ArcList *list = arcLists.GetArcList(hypo); assert(list); TrellisNode node(*list, 0); nodes.push_back(node); // add prev hypos const Hypothesis *prev = hypo->GetPrevHypo(); AddNodes(prev, arcLists); } } } /* namespace Moses2 */ <commit_msg>consistent Debug()<commit_after>/* * TrellisPath.cpp * * Created on: 16 Mar 2016 * Author: hieu */ #include <cassert> #include <sstream> #include "TrellisPath.h" #include "TrellisPaths.h" #include "Hypothesis.h" #include "../System.h" using namespace std; namespace Moses2 { void TrellisNode::Debug(std::ostream &out, const System &system) const { out << "arcList=" << arcList->size() << " " << ind; } ///////////////////////////////////////////////////////////////////////////////// TrellisPath::TrellisPath(const Hypothesis *hypo, const ArcLists &arcLists) : prevEdgeChanged(-1) { AddNodes(hypo, arcLists); m_scores = &hypo->GetScores(); } TrellisPath::TrellisPath(const TrellisPath &origPath, size_t edgeIndex, const TrellisNode &newNode, const ArcLists &arcLists, MemPool &pool, const System &system) : prevEdgeChanged(edgeIndex) { nodes.reserve(origPath.nodes.size()); for (size_t currEdge = 0; currEdge < edgeIndex; currEdge++) { // copy path from parent nodes.push_back(origPath.nodes[currEdge]); } // 1 deviation nodes.push_back(newNode); // rest of path comes from following best path backwards const Hypothesis *arc = static_cast<const Hypothesis*>(newNode.GetHypo()); const Hypothesis *prevHypo = arc->GetPrevHypo(); while (prevHypo != NULL) { const ArcList *arcList = arcLists.GetArcList(prevHypo); assert(arcList); TrellisNode node(*arcList, 0); nodes.push_back(node); prevHypo = prevHypo->GetPrevHypo(); } const TrellisNode &origNode = origPath.nodes[edgeIndex]; const HypothesisBase *origHypo = origNode.GetHypo(); const HypothesisBase *newHypo = newNode.GetHypo(); CalcScores(origPath.GetScores(), origHypo->GetScores(), newHypo->GetScores(), pool, system); } TrellisPath::~TrellisPath() { // TODO Auto-generated destructor stub } SCORE TrellisPath::GetFutureScore() const { return m_scores->GetTotalScore(); } void TrellisPath::Debug(std::ostream &out, const System &system) const { out << ToString(); out << "||| "; GetScores().Debug(out, system); out << "||| "; out << GetScores().GetTotalScore(); } std::string TrellisPath::ToString() const { //cerr << "path=" << this << " " << nodes.size() << endl; std::stringstream out; for (int i = nodes.size() - 1; i >= 0; --i) { const TrellisNode &node = nodes[i]; const Hypothesis *hypo = static_cast<const Hypothesis*>(node.GetHypo()); //cerr << "hypo=" << hypo << " " << *hypo << endl; hypo->GetTargetPhrase().OutputToStream(out); out << " "; } return out.str(); } void TrellisPath::CreateDeviantPaths(TrellisPaths &paths, const ArcLists &arcLists, MemPool &pool, const System &system) const { const size_t sizePath = nodes.size(); //cerr << "prevEdgeChanged=" << prevEdgeChanged << endl; for (size_t currEdge = prevEdgeChanged + 1; currEdge < sizePath; currEdge++) { TrellisNode newNode = nodes[currEdge]; assert(newNode.ind == 0); const ArcList &arcList = *newNode.arcList; //cerr << "arcList=" << arcList.size() << endl; for (size_t i = 1; i < arcList.size(); ++i) { //cerr << "i=" << i << endl; newNode.ind = i; TrellisPath *deviantPath = new TrellisPath(*this, currEdge, newNode, arcLists, pool, system); //cerr << "deviantPath=" << deviantPath << endl; paths.Add(deviantPath); } } } void TrellisPath::CalcScores(const Scores &origScores, const Scores &origHypoScores, const Scores &newHypoScores, MemPool &pool, const System &system) { Scores *scores = new (pool.Allocate<Scores>()) Scores(system, pool, system.featureFunctions.GetNumScores(), origScores); scores->PlusEquals(system, newHypoScores); scores->MinusEquals(system, origHypoScores); m_scores = scores; } void TrellisPath::AddNodes(const Hypothesis *hypo, const ArcLists &arcLists) { if (hypo) { // add this hypo //cerr << "hypo=" << hypo << " " << flush; //cerr << *hypo << endl; const ArcList *list = arcLists.GetArcList(hypo); assert(list); TrellisNode node(*list, 0); nodes.push_back(node); // add prev hypos const Hypothesis *prev = hypo->GetPrevHypo(); AddNodes(prev, arcLists); } } } /* namespace Moses2 */ <|endoftext|>
<commit_before>#include <iostream> #include <sstream> #include <fstream> #include <string> #include <getopt.h> #include <atomic> #include <signal.h> #include <unistd.h> #include <zcm/zcm-cpp.hpp> #include "zcm/json/json.h" #include "util/TimeUtil.hpp" using namespace std; static atomic_int done {0}; static void sighandler(int signal) { done++; if (done == 3) exit(1); } struct Args { double speed = 1.0; bool verbose = false; string zcmUrlOut = ""; string filename = ""; string jslpFilename = ""; zcm::Json::Value jslpRoot; bool init(int argc, char *argv[]) { struct option long_opts[] = { { "help", no_argument, 0, 'h' }, { "speed", required_argument, 0, 's' }, { "zcm-url", required_argument, 0, 'u' }, { "verbose", no_argument, 0, 'v' }, { 0, 0, 0, 0 } }; int c; while ((c = getopt_long(argc, argv, "hs:vu:", long_opts, 0)) >= 0) { switch (c) { case 's': speed = strtod(optarg, NULL); break; case 'u': zcmUrlOut = string(optarg); break; case 'v': verbose = true; break; case 'h': default: return false; }; } if (optind != argc - 1) { cerr << "Please specify a logfile" << endl; return false; } filename = string(argv[optind]); jslpFilename = filename + ".jslp"; ifstream jslpFile { jslpFilename }; if (jslpFile.good()) { zcm::Json::Reader reader; if (!reader.parse(jslpFile, jslpRoot, false)) { if (verbose) { cerr << "Failed to parse jslp file " << endl; cerr << reader.getFormattedErrorMessages() << endl; return false; } } } else { if (verbose) cerr << "No jslp file specified" << endl; } return true; } }; struct LogPlayer { Args args; zcm::LogFile *zcmIn = nullptr; zcm::ZCM *zcmOut = nullptr; string startChan = ""; LogPlayer() { } ~LogPlayer() { if (zcmIn) delete zcmIn; if (zcmOut) delete zcmOut; } bool init(int argc, char *argv[]) { if (!args.init(argc, argv)) return false; zcmIn = new zcm::LogFile(args.filename, "r"); if (!zcmIn->good()) { cerr << "Error: Failed to open '" << args.filename << "'" << endl; return false; } zcmOut = new zcm::ZCM(args.zcmUrlOut); if (!zcmOut->good()) { cerr << "Error: Failed to create output ZCM" << endl; return false; } cout << "Using playback speed " << args.speed << endl; if (args.jslpRoot.isMember("START")) { if (args.jslpRoot["START"]["mode"] == "channel") startChan = args.jslpRoot["START"]["channel"].asString(); } return true; } void run() { uint64_t lastMsgUtime = 0; uint64_t lastDispatchUtime = 0; bool startedPub = false; if (startChan == "") startedPub = true; while (!done) { const zcm::LogEvent* le = zcmIn->readNextEvent(); if (!le) done = true; uint64_t now = TimeUtil::utime(); if (lastMsgUtime == 0) lastMsgUtime = le->timestamp; if (lastDispatchUtime == 0) lastDispatchUtime = now; uint64_t localDiff = now - lastDispatchUtime; uint64_t logDiff = le->timestamp - lastMsgUtime; uint64_t logDiffSpeed = logDiff / args.speed; uint64_t diff = logDiffSpeed > localDiff ? logDiffSpeed - localDiff : 0; if (diff > 0) usleep(diff); if (startedPub == false && startChan != "") if (le->channel == startChan) startedPub = true; auto publish = [&](){ if (args.verbose) printf("%.3f Channel %-20s size %d\n", le->timestamp / 1e6, le->channel.c_str(), le->datalen); zcmOut->publish(le->channel, le->data, le->datalen); }; if (startedPub) { if (args.jslpRoot.empty()) { publish(); } else if (args.jslpRoot.isMember("CHANNEL")) { if (!args.jslpRoot["CHANNEL"].isMember("mode")) { cerr << "Channel filter \"mode\" in jslp file unspecified" << endl; done = true; continue; } if (args.jslpRoot["CHANNEL"]["mode"] == "whitelist") { if (args.jslpRoot["CHANNEL"]["channels"].isArray()) { for (auto val : args.jslpRoot["CHANNEL"]["channels"]) if (val == le->channel) publish(); } else if (args.jslpRoot["CHANNEL"]["channels"].isMember(le->channel)) publish(); } else if (args.jslpRoot["CHANNEL"]["mode"] == "blacklist") { if (args.jslpRoot["CHANNEL"]["channels"].isArray()) { bool found = false; for (auto val : args.jslpRoot["CHANNEL"]["channels"]) if (val == le->channel) found = true; if (found == false) publish(); } else if (!args.jslpRoot["CHANNEL"]["channels"].isMember(le->channel)) publish(); } else if (args.jslpRoot["CHANNEL"]["mode"] == "specified") { if (!args.jslpRoot["CHANNEL"]["channels"].isMember(le->channel) || args.jslpRoot["CHANNEL"]["channels"][le->channel] != false) { publish(); } } else { cerr << "Channel filter \"mode\" unrecognized: " << args.jslpRoot["CHANNEL"]["mode"] << endl; done = true; continue; } } } lastDispatchUtime = TimeUtil::utime(); lastMsgUtime = le->timestamp; } } }; void usage(char * cmd) { cerr << "usage: zcm-logplayer [options] [FILE]" << endl << "" << endl << " Reads packets from an ZCM log file and publishes them to a " << endl << " ZCM transport." << endl << "" << endl << "Options:" << endl << "" << endl << " -s, --speed=NUM Playback speed multiplier. Default is 1." << endl << " -u, --zcm-url=URL Play logged messages on the specified ZCM URL." << endl << " -v, --verbose Print information about each packet." << endl << " -h, --help Shows some help text and exits." << endl << endl; } int main(int argc, char* argv[]) { LogPlayer lp; if (!lp.init(argc, argv)) { usage(argv[0]); return 1; } // Register signal handlers signal(SIGINT, sighandler); signal(SIGQUIT, sighandler); signal(SIGTERM, sighandler); lp.run(); cout << "zcm-logplayer exiting" << endl; return 0; } <commit_msg>A few more features. Now just to do output<commit_after>#include <iostream> #include <sstream> #include <fstream> #include <string> #include <getopt.h> #include <atomic> #include <signal.h> #include <unistd.h> #include <limits> #include <zcm/zcm-cpp.hpp> #include "zcm/json/json.h" #include "util/TimeUtil.hpp" using namespace std; static atomic_int done {0}; static void sighandler(int signal) { done++; if (done == 3) exit(1); } struct Args { double speed = 1.0; bool verbose = false; string zcmUrlOut = ""; string filename = ""; string jslpFilename = ""; zcm::Json::Value jslpRoot; bool init(int argc, char *argv[]) { struct option long_opts[] = { { "help", no_argument, 0, 'h' }, { "speed", required_argument, 0, 's' }, { "zcm-url", required_argument, 0, 'u' }, { "verbose", no_argument, 0, 'v' }, { 0, 0, 0, 0 } }; int c; while ((c = getopt_long(argc, argv, "hs:vu:", long_opts, 0)) >= 0) { switch (c) { case 's': speed = strtod(optarg, NULL); break; case 'u': zcmUrlOut = string(optarg); break; case 'v': verbose = true; break; case 'h': default: return false; }; } if (optind != argc - 1) { cerr << "Please specify a logfile" << endl; return false; } if (speed == 0) speed = std::numeric_limits<decltype(speed)>::infinity(); filename = string(argv[optind]); jslpFilename = filename + ".jslp"; ifstream jslpFile { jslpFilename }; if (jslpFile.good()) { zcm::Json::Reader reader; if (!reader.parse(jslpFile, jslpRoot, false)) { if (verbose) { cerr << "Failed to parse jslp file " << endl; cerr << reader.getFormattedErrorMessages() << endl; return false; } } } else { if (verbose) cerr << "No jslp file specified" << endl; } return true; } }; struct LogPlayer { Args args; zcm::LogFile *zcmIn = nullptr; zcm::ZCM *zcmOut = nullptr; string startMode = ""; string startChan = ""; uint64_t startDelayUs = 0; LogPlayer() { } ~LogPlayer() { if (zcmIn) delete zcmIn; if (zcmOut) delete zcmOut; } bool init(int argc, char *argv[]) { if (!args.init(argc, argv)) return false; zcmIn = new zcm::LogFile(args.filename, "r"); if (!zcmIn->good()) { cerr << "Error: Failed to open '" << args.filename << "'" << endl; return false; } zcmOut = new zcm::ZCM(args.zcmUrlOut); if (!zcmOut->good()) { cerr << "Error: Failed to create output ZCM" << endl; return false; } cout << "Using playback speed " << args.speed << endl; if (args.jslpRoot.isMember("START")) { if (!args.jslpRoot["START"].isMember("mode")) { cerr << "Start mode unspecified in jslp" << endl; return false; } startMode = args.jslpRoot["START"]["mode"].asString(); if (startMode == "channel") { if (!args.jslpRoot["START"].isMember("channel")) { cerr << "Start channel unspecified in jslp" << endl; return false; } startChan = args.jslpRoot["START"]["channel"].asString(); } else if (startMode == "us_delay") { if (!args.jslpRoot["START"].isMember("us")) { cerr << "Start channel unspecified in jslp" << endl; return false; } startDelayUs = args.jslpRoot["START"]["us"].asUInt64(); } else { cerr << "Start mode unrecognized in jslp: " << startMode << endl; return false; } } return true; } void run() { uint64_t firstMsgUtime = UINT64_MAX; uint64_t lastMsgUtime = 0; uint64_t lastDispatchUtime = 0; bool startedPub = false; if (startMode == "") startedPub = true; while (!done) { const zcm::LogEvent* le = zcmIn->readNextEvent(); if (!le) done = true; uint64_t now = TimeUtil::utime(); if (lastMsgUtime == 0) lastMsgUtime = le->timestamp; if (lastDispatchUtime == 0) lastDispatchUtime = now; if (firstMsgUtime == UINT64_MAX) firstMsgUtime = (uint64_t) le->timestamp; uint64_t localDiff = now - lastDispatchUtime; uint64_t logDiff = (uint64_t) le->timestamp - lastMsgUtime; uint64_t logDiffSpeed = logDiff / args.speed; uint64_t diff = logDiffSpeed > localDiff ? logDiffSpeed - localDiff : 0; if (diff > 0) usleep(diff); if (startedPub == false) { if (startMode == "channel") { if (le->channel == startChan) startedPub = true; } else if (startMode == "us_delay") { if ((uint64_t) le->timestamp > firstMsgUtime + startDelayUs) startedPub = true; } } auto publish = [&](){ if (args.verbose) printf("%.3f Channel %-20s size %d\n", le->timestamp / 1e6, le->channel.c_str(), le->datalen); zcmOut->publish(le->channel, le->data, le->datalen); }; if (startedPub) { if (args.jslpRoot.empty()) { publish(); } else if (args.jslpRoot.isMember("FILTER")) { if (!args.jslpRoot["FILTER"].isMember("type")) { cerr << "Filter \"type\" in jslp file unspecified" << endl; done = true; continue; } if (!args.jslpRoot["FILTER"].isMember("mode")) { cerr << "Filter \"mode\" in jslp file unspecified" << endl; done = true; continue; } if (args.jslpRoot["FILTER"]["type"] == "channels") { if (args.jslpRoot["FILTER"]["mode"] == "whitelist") { if (args.jslpRoot["FILTER"]["channels"].isArray()) { for (auto val : args.jslpRoot["FILTER"]["channels"]) if (val == le->channel) publish(); } else if (args.jslpRoot["FILTER"]["channels"].isMember(le->channel)) publish(); } else if (args.jslpRoot["FILTER"]["mode"] == "blacklist") { if (args.jslpRoot["FILTER"]["channels"].isArray()) { bool found = false; for (auto val : args.jslpRoot["FILTER"]["channels"]) if (val == le->channel) found = true; if (found == false) publish(); } else if (!args.jslpRoot["FILTER"]["channels"].isMember(le->channel)) publish(); } else if (args.jslpRoot["FILTER"]["mode"] == "specified") { if (!args.jslpRoot["FILTER"]["channels"].isMember(le->channel)) { cerr << "jslp file does not specify filtering behavior " << "for channel: " << le->channel << endl; done = true; continue; } if (args.jslpRoot["FILTER"]["channels"][le->channel] == true) publish(); } else { cerr << "Filter \"mode\" unrecognized: " << args.jslpRoot["FILTER"]["mode"] << endl; done = true; continue; } } else { cerr << "Filter \"type\" unrecognized: " << args.jslpRoot["FILTER"]["type"] << endl; done = true; continue; } } } lastDispatchUtime = TimeUtil::utime(); lastMsgUtime = le->timestamp; } } }; void usage(char * cmd) { cerr << "usage: zcm-logplayer [options] [FILE]" << endl << "" << endl << " Reads packets from an ZCM log file and publishes them to a " << endl << " ZCM transport." << endl << "" << endl << "Options:" << endl << "" << endl << " -s, --speed=NUM Playback speed multiplier. Default is 1." << endl << " -u, --zcm-url=URL Play logged messages on the specified ZCM URL." << endl << " -v, --verbose Print information about each packet." << endl << " -h, --help Shows some help text and exits." << endl << endl; } int main(int argc, char* argv[]) { LogPlayer lp; if (!lp.init(argc, argv)) { usage(argv[0]); return 1; } // Register signal handlers signal(SIGINT, sighandler); signal(SIGQUIT, sighandler); signal(SIGTERM, sighandler); lp.run(); cout << "zcm-logplayer exiting" << endl; return 0; } <|endoftext|>
<commit_before>#include "evpp/inner_pre.h" #include "evpp/libevent_headers.h" #include "evpp/sockets.h" namespace evpp { std::string strerror(int e) { #ifdef H_OS_WINDOWS LPVOID buf = NULL; ::FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, e, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL); if (buf) { std::string s = (char*)buf; LocalFree(buf); return s; } return std::string(); #else char buf[1024] = {}; return std::string(strerror_r(e, buf, sizeof buf)); #endif } namespace sock { int CreateNonblockingSocket() { int serrno = 0; //int on = 1; /* Create listen socket */ int fd = ::socket(AF_INET, SOCK_STREAM, 0); if (fd == -1) { serrno = errno; LOG_ERROR << "socket error " << strerror(serrno); return INVALID_SOCKET; } if (evutil_make_socket_nonblocking(fd) < 0) { goto out; } #ifndef H_OS_WINDOWS if (fcntl(fd, F_SETFD, 1) == -1) { serrno = errno; LOG_FATAL << "fcntl(F_SETFD)" << strerror(serrno); goto out; } #endif SetKeepAlive(fd); SetReuseAddr(fd); return fd; out: EVUTIL_CLOSESOCKET(fd); return INVALID_SOCKET; } int CreateUDPServer(int port) { int fd = ::socket(AF_INET, SOCK_DGRAM, 0); if (fd == -1) { int serrno = errno; LOG_ERROR << "socket error " << strerror(serrno); return INVALID_SOCKET; } SetReuseAddr(fd); std::string addr = std::string("0.0.0.0:") + std::to_string(port); struct sockaddr_in local = ParseFromIPPort(addr.c_str()); if (::bind(fd, (struct sockaddr*)&local, sizeof(local))) { int serrno = errno; LOG_ERROR << "socket bind error " << strerror(serrno); return INVALID_SOCKET; } return fd; } struct sockaddr_in ParseFromIPPort(const char* address/*ip:port*/) { struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); std::string a = address; size_t index = a.rfind(':'); if (index == std::string::npos) { LOG_FATAL << "Address specified error [" << address << "]"; } addr.sin_family = AF_INET; addr.sin_port = htons(::atoi(&a[index + 1])); a[index] = '\0'; if (::inet_pton(AF_INET, a.data(), &addr.sin_addr) <= 0) { int serrno = errno; if (serrno == 0) { LOG_INFO << "[" << a.data() << "] is not a IP address. Maybe it is a hostname."; } else { LOG_ERROR << "ParseFromIPPort inet_pton(AF_INET, '" << a.data() << "', ..) failed : " << strerror(serrno); } } //TODO add ipv6 support return addr; } struct sockaddr_in GetLocalAddr(int sockfd) { struct sockaddr_in laddr; memset(&laddr, 0, sizeof laddr); socklen_t addrlen = static_cast<socklen_t>(sizeof laddr); if (::getsockname(sockfd, sockaddr_cast(&laddr), &addrlen) < 0) { LOG_ERROR << "GetLocalAddr:" << strerror(errno); memset(&laddr, 0, sizeof laddr); } return laddr; } std::string ToIPPort(const struct sockaddr_storage* ss) { std::string saddr; int port = 0; if (ss->ss_family == AF_INET) { struct sockaddr_in* addr4 = const_cast<struct sockaddr_in*>(sockaddr_in_cast(ss)); char buf[INET_ADDRSTRLEN] = {}; const char* addr = ::inet_ntop(ss->ss_family, &addr4->sin_addr, buf, INET_ADDRSTRLEN); if (addr) { saddr = addr; } port = ntohs(addr4->sin_port); } else if (ss->ss_family == AF_INET6) { struct sockaddr_in6* addr6 = const_cast<struct sockaddr_in6*>(sockaddr_in6_cast(ss)); char buf[INET6_ADDRSTRLEN] = {}; const char* addr = ::inet_ntop(ss->ss_family, &addr6->sin6_addr, buf, INET6_ADDRSTRLEN); if (addr) { saddr = addr; } port = ntohs(addr6->sin6_port); } else { LOG_ERROR << "unknown socket family connected"; return std::string(); } if (!saddr.empty()) { saddr.append(":", 1).append(std::to_string(port)); } return saddr; } std::string ToIPPort(const struct sockaddr* ss) { return ToIPPort(sockaddr_storage_cast(ss)); } std::string ToIPPort(const struct sockaddr_in* ss) { return ToIPPort(sockaddr_storage_cast(ss)); } EVPP_EXPORT std::string ToIP(const struct sockaddr* s) { auto ss = sockaddr_storage_cast(s); if (ss->ss_family == AF_INET) { struct sockaddr_in* addr4 = const_cast<struct sockaddr_in*>(sockaddr_in_cast(ss)); char buf[INET_ADDRSTRLEN] = {}; const char* addr = ::inet_ntop(ss->ss_family, &addr4->sin_addr, buf, INET_ADDRSTRLEN); if (addr) { return std::string(addr); } } else if (ss->ss_family == AF_INET6) { struct sockaddr_in6* addr6 = const_cast<struct sockaddr_in6*>(sockaddr_in6_cast(ss)); char buf[INET6_ADDRSTRLEN] = {}; const char* addr = ::inet_ntop(ss->ss_family, &addr6->sin6_addr, buf, INET6_ADDRSTRLEN); if (addr) { return std::string(addr); } } else { LOG_ERROR << "unknown socket family connected"; } return std::string(); } void SetTimeout(int fd, uint32_t timeout_ms) { #ifdef H_OS_WINDOWS DWORD tv = timeout_ms; #else struct timeval tv; tv.tv_sec = timeout_ms / 1000; tv.tv_usec = (timeout_ms % 1000) * 1000; #endif int ret = setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof(tv)); assert(ret == 0); if (ret != 0) { int err = errno; LOG_ERROR << "setsockopt SO_RCVTIMEO ERROR " << err << strerror(err); } } void SetKeepAlive(int fd) { int on = 1; int rc = ::setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const char*)&on, sizeof(on)); assert(rc == 0); (void)rc; // avoid compile warning } void SetReuseAddr(int fd) { int on = 1; int rc = ::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on)); assert(rc == 0); (void)rc; // avoid compile warning } } } #ifdef H_OS_WINDOWS int readv(int sockfd, struct iovec* iov, int iovcnt) { DWORD readn = 0; DWORD flags = 0; if (::WSARecv(sockfd, iov, iovcnt, &readn, &flags, NULL, NULL) == 0) { return readn; } return -1; } #endif <commit_msg>modify the error log of ParseFromIPPort<commit_after>#include "evpp/inner_pre.h" #include "evpp/libevent_headers.h" #include "evpp/sockets.h" namespace evpp { std::string strerror(int e) { #ifdef H_OS_WINDOWS LPVOID buf = NULL; ::FormatMessageA( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, e, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL); if (buf) { std::string s = (char*)buf; LocalFree(buf); return s; } return std::string(); #else char buf[1024] = {}; return std::string(strerror_r(e, buf, sizeof buf)); #endif } namespace sock { int CreateNonblockingSocket() { int serrno = 0; //int on = 1; /* Create listen socket */ int fd = ::socket(AF_INET, SOCK_STREAM, 0); if (fd == -1) { serrno = errno; LOG_ERROR << "socket error " << strerror(serrno); return INVALID_SOCKET; } if (evutil_make_socket_nonblocking(fd) < 0) { goto out; } #ifndef H_OS_WINDOWS if (fcntl(fd, F_SETFD, 1) == -1) { serrno = errno; LOG_FATAL << "fcntl(F_SETFD)" << strerror(serrno); goto out; } #endif SetKeepAlive(fd); SetReuseAddr(fd); return fd; out: EVUTIL_CLOSESOCKET(fd); return INVALID_SOCKET; } int CreateUDPServer(int port) { int fd = ::socket(AF_INET, SOCK_DGRAM, 0); if (fd == -1) { int serrno = errno; LOG_ERROR << "socket error " << strerror(serrno); return INVALID_SOCKET; } SetReuseAddr(fd); std::string addr = std::string("0.0.0.0:") + std::to_string(port); struct sockaddr_in local = ParseFromIPPort(addr.c_str()); if (::bind(fd, (struct sockaddr*)&local, sizeof(local))) { int serrno = errno; LOG_ERROR << "socket bind error " << strerror(serrno); return INVALID_SOCKET; } return fd; } struct sockaddr_in ParseFromIPPort(const char* address/*ip:port*/) { struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); std::string a = address; size_t index = a.rfind(':'); if (index == std::string::npos) { LOG_FATAL << "Address specified error [" << address << "]"; } addr.sin_family = AF_INET; addr.sin_port = htons(::atoi(&a[index + 1])); a[index] = '\0'; int rc = ::inet_pton(AF_INET, a.data(), &addr.sin_addr); if (rc == 0) { LOG_INFO << "ParseFromIPPort inet_pton(AF_INET '" << a.data() << "', ...) rc=0. " << a.data() << " is not a valid IP address. Maybe it is a hostname."; } else if (rc < 0) { int serrno = errno; LOG_ERROR << "ParseFromIPPort inet_pton(AF_INET, '" << a.data() << "', ...) failed : " << strerror(serrno) << " rc=" << rc; } //TODO add ipv6 support return addr; } struct sockaddr_in GetLocalAddr(int sockfd) { struct sockaddr_in laddr; memset(&laddr, 0, sizeof laddr); socklen_t addrlen = static_cast<socklen_t>(sizeof laddr); if (::getsockname(sockfd, sockaddr_cast(&laddr), &addrlen) < 0) { LOG_ERROR << "GetLocalAddr:" << strerror(errno); memset(&laddr, 0, sizeof laddr); } return laddr; } std::string ToIPPort(const struct sockaddr_storage* ss) { std::string saddr; int port = 0; if (ss->ss_family == AF_INET) { struct sockaddr_in* addr4 = const_cast<struct sockaddr_in*>(sockaddr_in_cast(ss)); char buf[INET_ADDRSTRLEN] = {}; const char* addr = ::inet_ntop(ss->ss_family, &addr4->sin_addr, buf, INET_ADDRSTRLEN); if (addr) { saddr = addr; } port = ntohs(addr4->sin_port); } else if (ss->ss_family == AF_INET6) { struct sockaddr_in6* addr6 = const_cast<struct sockaddr_in6*>(sockaddr_in6_cast(ss)); char buf[INET6_ADDRSTRLEN] = {}; const char* addr = ::inet_ntop(ss->ss_family, &addr6->sin6_addr, buf, INET6_ADDRSTRLEN); if (addr) { saddr = addr; } port = ntohs(addr6->sin6_port); } else { LOG_ERROR << "unknown socket family connected"; return std::string(); } if (!saddr.empty()) { saddr.append(":", 1).append(std::to_string(port)); } return saddr; } std::string ToIPPort(const struct sockaddr* ss) { return ToIPPort(sockaddr_storage_cast(ss)); } std::string ToIPPort(const struct sockaddr_in* ss) { return ToIPPort(sockaddr_storage_cast(ss)); } EVPP_EXPORT std::string ToIP(const struct sockaddr* s) { auto ss = sockaddr_storage_cast(s); if (ss->ss_family == AF_INET) { struct sockaddr_in* addr4 = const_cast<struct sockaddr_in*>(sockaddr_in_cast(ss)); char buf[INET_ADDRSTRLEN] = {}; const char* addr = ::inet_ntop(ss->ss_family, &addr4->sin_addr, buf, INET_ADDRSTRLEN); if (addr) { return std::string(addr); } } else if (ss->ss_family == AF_INET6) { struct sockaddr_in6* addr6 = const_cast<struct sockaddr_in6*>(sockaddr_in6_cast(ss)); char buf[INET6_ADDRSTRLEN] = {}; const char* addr = ::inet_ntop(ss->ss_family, &addr6->sin6_addr, buf, INET6_ADDRSTRLEN); if (addr) { return std::string(addr); } } else { LOG_ERROR << "unknown socket family connected"; } return std::string(); } void SetTimeout(int fd, uint32_t timeout_ms) { #ifdef H_OS_WINDOWS DWORD tv = timeout_ms; #else struct timeval tv; tv.tv_sec = timeout_ms / 1000; tv.tv_usec = (timeout_ms % 1000) * 1000; #endif int ret = setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof(tv)); assert(ret == 0); if (ret != 0) { int err = errno; LOG_ERROR << "setsockopt SO_RCVTIMEO ERROR " << err << strerror(err); } } void SetKeepAlive(int fd) { int on = 1; int rc = ::setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, (const char*)&on, sizeof(on)); assert(rc == 0); (void)rc; // avoid compile warning } void SetReuseAddr(int fd) { int on = 1; int rc = ::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char*)&on, sizeof(on)); assert(rc == 0); (void)rc; // avoid compile warning } } } #ifdef H_OS_WINDOWS int readv(int sockfd, struct iovec* iov, int iovcnt) { DWORD readn = 0; DWORD flags = 0; if (::WSARecv(sockfd, iov, iovcnt, &readn, &flags, NULL, NULL) == 0) { return readn; } return -1; } #endif <|endoftext|>
<commit_before>/* * This file is part of the statismo library. * * Author: Marcel Luethi (marcel.luethi@unibas.ch) * * Copyright (c) 2011 University of Basel * 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 project's 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 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS addINTERRUPTION) 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 "statismo/CommonTypes.h" #include <iostream> using statismo::VectorType; /** * This class provides generic tests for representer. The tests need to hold for all representers. */ template <typename Representer> class GenericRepresenterTest { // we define typedefs for all required typenames, to force a compilation error if one of them // is not defined typedef typename Representer::DatasetConstPointerType DatasetConstPointerType; typedef typename Representer::DatasetPointerType DatasetPointerType; typedef typename Representer::PointType PointType; typedef typename Representer::ValueType ValueType; typedef typename Representer::DatasetInfo DatasetInfo; public: /// Create new test with the given representer. /// Tests are performed using the given testDataset and the pointValuePair. /// It is assumed that the PointValuePair is taken from the testDataset (otherwise some tests will fail). GenericRepresenterTest(const Representer* representer, DatasetConstPointerType testDataset, std::pair<PointType, ValueType> pointValuePair) : m_representer(representer), m_testDataset(testDataset), m_testPoint(pointValuePair.first), m_testValue(pointValuePair.second) {} /// test whether converting a sample to a vector and back to a sample yields the original sample bool testSampleToVectorAndBack() const { std::cout << "testSampleToVectorToSample" << std::endl; VectorType sampleVec = getSampleVectorFromTestDataset(); DatasetConstPointerType reconstructedSample = m_representer->SampleVectorToSample(sampleVec); // as we don't know anything about how to compare samples, we compare their vectorial representation VectorType reconstructedSampleAsVec = m_representer->SampleToSampleVector(reconstructedSample); bool isOkay = assertSampleVectorsEqual(sampleVec, reconstructedSampleAsVec); if (isOkay == false) { std::cout << "Error: the sample has changed by converting between the representations " << std::endl; } return true; } /// test if the pointSamples have the correct dimensionality bool testPointSampleDimension() const { std::cout << "testPointSampleDimension" << std::endl; VectorType valVec = m_representer->PointSampleToPointSampleVector(m_testValue); if (valVec.rows() != Representer::GetDimensions()) { std::cout << "Error: The dimensionality of the pointSampleVector is not the same as the Dimensionality of the representer" << std::endl; return false; } return true; } /// tests if the conversion from a pointSample and the pointSampleVector, and back to a pointSample /// yields the original sample. bool testPointSampleToPointSampleVectorAndBack() const { std::cout << "testPointSampleToPointSampleVectorAndBack" << std::endl; VectorType valVec = m_representer->PointSampleToPointSampleVector(m_testValue); ValueType recVal = m_representer->PointSampleVectorToPointSample(valVec); // we compare the vectors and not the points, as we don't know how to compare poitns. VectorType recValVec = m_representer->PointSampleToPointSampleVector(recVal); bool ok = assertSampleVectorsEqual(valVec, recValVec); if (!ok) { std::cout << "Error: the point sample has changed by converting between the representations" << std::endl; } return ok; } /// test if the testSample contains the same entries in the vector as those obtained by taking the /// pointSample at the corresponding position. bool testSampleVectorHasCorrectValueAtPoint() const { std::cout << "testSampleVectorHasCorrectValueAtPoint" << std::endl; unsigned ptId = m_representer->GetPointIdForPoint(m_testPoint); if (ptId < 0 || ptId >= m_representer->GetNumberOfPoints()) { std::cout << "Error: invalid point id for test point " << ptId << std::endl; return false; } // the value of the point in the sample vector needs to correspond the the value that was provided VectorType sampleVec = getSampleVectorFromTestDataset(); VectorType pointSampleVec = m_representer->PointSampleToPointSampleVector(m_testValue); for (unsigned d = 0; d < m_representer->GetDimensions(); ++d) { unsigned idx = m_representer->MapPointIdToInternalIdx(ptId, d); if (sampleVec[idx] != pointSampleVec[d]) { std::cout << "Error: the sample vector does not contain the correct value of the pointSample " << std::endl; return false; } } return true; } /// test whether the representer is correctly restored bool testSaveLoad() const { std::cout << "testSaveLoad" << std::endl; using namespace H5; std::string filename = statismo::Utils::CreateTmpName(".rep"); H5File file; try { file = H5File( filename, H5F_ACC_TRUNC ); } catch (Exception& e) { std::string msg(std::string("Error: Could not open HDF5 file for writing \n") + e.getCDetailMsg()); std::cout << msg << std::endl; return false; } m_representer->Save(file); try { file = H5File(filename.c_str(), H5F_ACC_RDONLY); } catch (Exception& e) { std::string msg(std::string("Error: could not open HDF5 file \n") + e.getCDetailMsg()); std::cout << msg << std::endl; return false; } Representer* newRep = Representer::Load(file); bool isOkay = assertRepresenterEqual(newRep, m_representer); newRep->Delete(); return isOkay; } /// test whether cloning a representer results in a representer with the same behaviour bool testClone() const { std::cout << "testClone" << std::endl; bool isOkay = true; Representer* rep = m_representer->Clone(); if (assertRepresenterEqual(rep, m_representer) == false) { std::cout << "Error: the clone of the representer is not the same as the representer " << std::endl; isOkay = false; } rep->Delete(); return isOkay; } /// test if the sample vector dimensions are correct bool testSampleVectorDimensions() const { std::cout << "testSampleVectorDimensions()" << std::endl; VectorType testSampleVec = getSampleVectorFromTestDataset(); bool isOk = Representer::GetDimensions() * m_representer->GetNumberOfPoints() == testSampleVec.rows(); if (!isOk) { std::cout << "Error: Dimensionality of the sample vector does not agree with the representer parameters " << "dimension and numberOfPoints" << std::endl; std::cout << testSampleVec.rows() << " != " << Representer::GetDimensions() << " * " << m_representer->GetNumberOfPoints() << std::endl; } return isOk; } /// test whether the name is defined bool testGetName() const { std::cout << "testGetName" << std::endl; if (m_representer->GetName() == "") { std::cout << "Error: representer name has to be non empty" << std::endl; return false; } return true; } /// test if the dimensionality is nonnegative bool testDimensions() const { std::cout << "testDimensions " << std::endl; if (Representer::GetDimensions() <= 0) { std::cout << "Error: Dimensionality of representer has to be > 0" << std::endl; return false; } return true; } /// run all the tests bool runAllTests() { bool ok = true; ok = testPointSampleDimension() and ok; ok = testPointSampleToPointSampleVectorAndBack() and ok; ok = testSampleVectorHasCorrectValueAtPoint() and ok; ok = testSampleToVectorAndBack() and ok; ok = testSaveLoad() and ok; ok = testClone() and ok; ok = testSampleVectorDimensions() and ok; ok = testGetName() and ok; ok = testDimensions() and ok; return ok; } private: bool assertRepresenterEqual(const Representer* representer1, const Representer* representer2) const { if (representer1->GetNumberOfPoints() != representer2->GetNumberOfPoints()) { std::cout << "the representers do not have the same nubmer of points " <<std::endl; return false; } VectorType sampleRep1 = getSampleVectorFromTestDataset(representer1); VectorType sampleRep2 = getSampleVectorFromTestDataset(representer2); if (assertSampleVectorsEqual(sampleRep1, sampleRep2) == false) { std::cout << "the representers produce different sample vectors for the same sample" << std::endl; return false; } return true; } bool assertSampleVectorsEqual(const VectorType& v1, const VectorType& v2) const { if (v1.rows() != v2.rows()) { std::cout << "dimensionality of SampleVectors do not agree" << std::endl; return false; } for (unsigned i = 0; i < v1.rows(); ++i) { if (v1[i] != v2[i]) { std::cout << "the sample vectors are not the same" << std::endl; return false; } } return true; } VectorType getSampleVectorFromTestDataset() const { return getSampleVectorFromTestDataset(m_representer); } VectorType getSampleVectorFromTestDataset(const Representer* representer) const { DatasetPointerType sample = representer->DatasetToSample(m_testDataset, 0); VectorType sampleVec = representer->SampleToSampleVector(sample); Representer::DeleteDataset(sample); return sampleVec; } const Representer* m_representer; DatasetConstPointerType m_testDataset; PointType m_testPoint; ValueType m_testValue; }; <commit_msg>replaced (mistakenly used) and by && in RepresenterTest<commit_after>/* * This file is part of the statismo library. * * Author: Marcel Luethi (marcel.luethi@unibas.ch) * * Copyright (c) 2011 University of Basel * 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 project's 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 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS addINTERRUPTION) 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 "statismo/CommonTypes.h" #include <iostream> using statismo::VectorType; /** * This class provides generic tests for representer. The tests need to hold for all representers. */ template <typename Representer> class GenericRepresenterTest { // we define typedefs for all required typenames, to force a compilation error if one of them // is not defined typedef typename Representer::DatasetConstPointerType DatasetConstPointerType; typedef typename Representer::DatasetPointerType DatasetPointerType; typedef typename Representer::PointType PointType; typedef typename Representer::ValueType ValueType; typedef typename Representer::DatasetInfo DatasetInfo; public: /// Create new test with the given representer. /// Tests are performed using the given testDataset and the pointValuePair. /// It is assumed that the PointValuePair is taken from the testDataset (otherwise some tests will fail). GenericRepresenterTest(const Representer* representer, DatasetConstPointerType testDataset, std::pair<PointType, ValueType> pointValuePair) : m_representer(representer), m_testDataset(testDataset), m_testPoint(pointValuePair.first), m_testValue(pointValuePair.second) {} /// test whether converting a sample to a vector and back to a sample yields the original sample bool testSampleToVectorAndBack() const { std::cout << "testSampleToVectorToSample" << std::endl; VectorType sampleVec = getSampleVectorFromTestDataset(); DatasetConstPointerType reconstructedSample = m_representer->SampleVectorToSample(sampleVec); // as we don't know anything about how to compare samples, we compare their vectorial representation VectorType reconstructedSampleAsVec = m_representer->SampleToSampleVector(reconstructedSample); bool isOkay = assertSampleVectorsEqual(sampleVec, reconstructedSampleAsVec); if (isOkay == false) { std::cout << "Error: the sample has changed by converting between the representations " << std::endl; } return true; } /// test if the pointSamples have the correct dimensionality bool testPointSampleDimension() const { std::cout << "testPointSampleDimension" << std::endl; VectorType valVec = m_representer->PointSampleToPointSampleVector(m_testValue); if (valVec.rows() != Representer::GetDimensions()) { std::cout << "Error: The dimensionality of the pointSampleVector is not the same as the Dimensionality of the representer" << std::endl; return false; } return true; } /// tests if the conversion from a pointSample and the pointSampleVector, and back to a pointSample /// yields the original sample. bool testPointSampleToPointSampleVectorAndBack() const { std::cout << "testPointSampleToPointSampleVectorAndBack" << std::endl; VectorType valVec = m_representer->PointSampleToPointSampleVector(m_testValue); ValueType recVal = m_representer->PointSampleVectorToPointSample(valVec); // we compare the vectors and not the points, as we don't know how to compare poitns. VectorType recValVec = m_representer->PointSampleToPointSampleVector(recVal); bool ok = assertSampleVectorsEqual(valVec, recValVec); if (!ok) { std::cout << "Error: the point sample has changed by converting between the representations" << std::endl; } return ok; } /// test if the testSample contains the same entries in the vector as those obtained by taking the /// pointSample at the corresponding position. bool testSampleVectorHasCorrectValueAtPoint() const { std::cout << "testSampleVectorHasCorrectValueAtPoint" << std::endl; unsigned ptId = m_representer->GetPointIdForPoint(m_testPoint); if (ptId < 0 || ptId >= m_representer->GetNumberOfPoints()) { std::cout << "Error: invalid point id for test point " << ptId << std::endl; return false; } // the value of the point in the sample vector needs to correspond the the value that was provided VectorType sampleVec = getSampleVectorFromTestDataset(); VectorType pointSampleVec = m_representer->PointSampleToPointSampleVector(m_testValue); for (unsigned d = 0; d < m_representer->GetDimensions(); ++d) { unsigned idx = m_representer->MapPointIdToInternalIdx(ptId, d); if (sampleVec[idx] != pointSampleVec[d]) { std::cout << "Error: the sample vector does not contain the correct value of the pointSample " << std::endl; return false; } } return true; } /// test whether the representer is correctly restored bool testSaveLoad() const { std::cout << "testSaveLoad" << std::endl; using namespace H5; std::string filename = statismo::Utils::CreateTmpName(".rep"); H5File file; try { file = H5File( filename, H5F_ACC_TRUNC ); } catch (Exception& e) { std::string msg(std::string("Error: Could not open HDF5 file for writing \n") + e.getCDetailMsg()); std::cout << msg << std::endl; return false; } m_representer->Save(file); try { file = H5File(filename.c_str(), H5F_ACC_RDONLY); } catch (Exception& e) { std::string msg(std::string("Error: could not open HDF5 file \n") + e.getCDetailMsg()); std::cout << msg << std::endl; return false; } Representer* newRep = Representer::Load(file); bool isOkay = assertRepresenterEqual(newRep, m_representer); newRep->Delete(); return isOkay; } /// test whether cloning a representer results in a representer with the same behaviour bool testClone() const { std::cout << "testClone" << std::endl; bool isOkay = true; Representer* rep = m_representer->Clone(); if (assertRepresenterEqual(rep, m_representer) == false) { std::cout << "Error: the clone of the representer is not the same as the representer " << std::endl; isOkay = false; } rep->Delete(); return isOkay; } /// test if the sample vector dimensions are correct bool testSampleVectorDimensions() const { std::cout << "testSampleVectorDimensions()" << std::endl; VectorType testSampleVec = getSampleVectorFromTestDataset(); bool isOk = Representer::GetDimensions() * m_representer->GetNumberOfPoints() == testSampleVec.rows(); if (!isOk) { std::cout << "Error: Dimensionality of the sample vector does not agree with the representer parameters " << "dimension and numberOfPoints" << std::endl; std::cout << testSampleVec.rows() << " != " << Representer::GetDimensions() << " * " << m_representer->GetNumberOfPoints() << std::endl; } return isOk; } /// test whether the name is defined bool testGetName() const { std::cout << "testGetName" << std::endl; if (m_representer->GetName() == "") { std::cout << "Error: representer name has to be non empty" << std::endl; return false; } return true; } /// test if the dimensionality is nonnegative bool testDimensions() const { std::cout << "testDimensions " << std::endl; if (Representer::GetDimensions() <= 0) { std::cout << "Error: Dimensionality of representer has to be > 0" << std::endl; return false; } return true; } /// run all the tests bool runAllTests() { bool ok = true; ok = testPointSampleDimension() && ok; ok = testPointSampleToPointSampleVectorAndBack() && ok; ok = testSampleVectorHasCorrectValueAtPoint() && ok; ok = testSampleToVectorAndBack() && ok; ok = testSaveLoad() && ok; ok = testClone() && ok; ok = testSampleVectorDimensions() && ok; ok = testGetName() && ok; ok = testDimensions() && ok; return ok; } private: bool assertRepresenterEqual(const Representer* representer1, const Representer* representer2) const { if (representer1->GetNumberOfPoints() != representer2->GetNumberOfPoints()) { std::cout << "the representers do not have the same nubmer of points " <<std::endl; return false; } VectorType sampleRep1 = getSampleVectorFromTestDataset(representer1); VectorType sampleRep2 = getSampleVectorFromTestDataset(representer2); if (assertSampleVectorsEqual(sampleRep1, sampleRep2) == false) { std::cout << "the representers produce different sample vectors for the same sample" << std::endl; return false; } return true; } bool assertSampleVectorsEqual(const VectorType& v1, const VectorType& v2) const { if (v1.rows() != v2.rows()) { std::cout << "dimensionality of SampleVectors do not agree" << std::endl; return false; } for (unsigned i = 0; i < v1.rows(); ++i) { if (v1[i] != v2[i]) { std::cout << "the sample vectors are not the same" << std::endl; return false; } } return true; } VectorType getSampleVectorFromTestDataset() const { return getSampleVectorFromTestDataset(m_representer); } VectorType getSampleVectorFromTestDataset(const Representer* representer) const { DatasetPointerType sample = representer->DatasetToSample(m_testDataset, 0); VectorType sampleVec = representer->SampleToSampleVector(sample); Representer::DeleteDataset(sample); return sampleVec; } const Representer* m_representer; DatasetConstPointerType m_testDataset; PointType m_testPoint; ValueType m_testValue; }; <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2013 Torus Knot Software Ltd 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 "OgreStableHeaders.h" #include "Compositor/OgreTextureDefinition.h" #include "Compositor/OgreCompositorNode.h" #include "Compositor/Pass/OgreCompositorPass.h" #include "OgreRenderTarget.h" #include "OgreHardwarePixelBuffer.h" #include "OgreRenderSystem.h" namespace Ogre { TextureDefinitionBase::TextureDefinitionBase( TextureSource defaultSource ) : mDefaultLocalTextureSource( defaultSource ) { assert( mDefaultLocalTextureSource == TEXTURE_LOCAL || mDefaultLocalTextureSource == TEXTURE_GLOBAL ); } //----------------------------------------------------------------------------------- size_t TextureDefinitionBase::getNumInputChannels(void) const { size_t numInputChannels = 0; NameToChannelMap::const_iterator itor = mNameToChannelMap.begin(); NameToChannelMap::const_iterator end = mNameToChannelMap.end(); while( itor != end ) { size_t index; TextureSource texSource; decodeTexSource( itor->second, index, texSource ); if( texSource == TEXTURE_INPUT ) ++numInputChannels; ++itor; } return numInputChannels; } //----------------------------------------------------------------------------------- uint32 TextureDefinitionBase::encodeTexSource( size_t index, TextureSource textureSource ) { assert( index <= 0x3FFFFFFF && "Texture Source Index out of supported range" ); return (index & 0x3FFFFFFF)|(textureSource<<30); } //----------------------------------------------------------------------------------- void TextureDefinitionBase::decodeTexSource( uint32 encodedVal, size_t &outIdx, TextureSource &outTexSource ) { uint32 texSource = (encodedVal & 0xC0000000) >> 30; assert( texSource < NUM_TEXTURES_SOURCES ); outIdx = encodedVal & 0x3FFFFFFF; outTexSource = static_cast<TextureSource>( texSource ); } //----------------------------------------------------------------------------------- IdString TextureDefinitionBase::addTextureSourceName( const String &name, size_t index, TextureSource textureSource ) { String::size_type findResult = name.find( "global_" ); if( textureSource == TEXTURE_LOCAL && findResult == 0 ) { OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "Local textures can't start with global_ prefix! '" + name + "'", "TextureDefinitionBase::addTextureSourceName" ); } else if( textureSource == TEXTURE_GLOBAL && findResult != 0 ) { OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "Global textures must start with global_ prefix! '" + name + "'", "TextureDefinitionBase::addTextureSourceName" ); } const uint32 value = encodeTexSource( index, textureSource ); IdString hashedName( name ); NameToChannelMap::const_iterator itor = mNameToChannelMap.find( hashedName ); if( itor != mNameToChannelMap.end() && itor->second != value ) { OGRE_EXCEPT( Exception::ERR_DUPLICATE_ITEM, "Texture with same name '" + name + "' in the same scope already exists", "TextureDefinitionBase::addTextureSourceName" ); } mNameToChannelMap[hashedName] = value; return hashedName; } //----------------------------------------------------------------------------------- void TextureDefinitionBase::getTextureSource( IdString name, size_t &index, TextureSource &textureSource ) const { NameToChannelMap::const_iterator itor = mNameToChannelMap.find( name ); if( itor == mNameToChannelMap.end() ) { OGRE_EXCEPT( Exception::ERR_ITEM_NOT_FOUND, "Can't find texture with name: '" + name.getFriendlyText() + "'" " If it's a global texture, trying to use it in the output channel will fail.", "CompositorNodeDef::getTextureSource" ); } decodeTexSource( itor->second, index, textureSource ); } //----------------------------------------------------------------------------------- TextureDefinitionBase::TextureDefinition* TextureDefinitionBase::addTextureDefinition ( const String &name ) { IdString hashedName = addTextureSourceName( name, mLocalTextureDefs.size(), mDefaultLocalTextureSource ); mLocalTextureDefs.push_back( TextureDefinition( hashedName ) ); return &mLocalTextureDefs.back(); } //----------------------------------------------------------------------------------- void TextureDefinitionBase::createTextures( const TextureDefinitionVec &textureDefs, CompositorChannelVec &inOutTexContainer, IdType id, bool uniqueNames, const RenderTarget *finalTarget, RenderSystem *renderSys ) { inOutTexContainer.reserve( textureDefs.size() ); //Create the local textures TextureDefinitionVec::const_iterator itor = textureDefs.begin(); TextureDefinitionVec::const_iterator end = textureDefs.end(); while( itor != end ) { String textureName; if( !uniqueNames ) textureName = (itor->name + IdString( id )).getFriendlyText(); else textureName = itor->name.getFriendlyText(); CompositorChannel newChannel = createTexture( *itor, textureName, finalTarget, renderSys ); inOutTexContainer.push_back( newChannel ); ++itor; } } //----------------------------------------------------------------------------------- CompositorChannel TextureDefinitionBase::createTexture( const TextureDefinition &textureDef, const String &texName, const RenderTarget *finalTarget, RenderSystem *renderSys ) { CompositorChannel newChannel; bool defaultHwGamma = false; uint defaultFsaa = 0; String defaultFsaaHint = StringUtil::BLANK; if( finalTarget ) { // Inherit settings from target defaultHwGamma = finalTarget->isHardwareGammaEnabled(); defaultFsaa = finalTarget->getFSAA(); defaultFsaaHint = finalTarget->getFSAAHint(); } //If undefined, use main target's hw gamma settings, else use explicit setting bool hwGamma = textureDef.hwGammaWrite == BoolUndefined ? defaultHwGamma : (textureDef.hwGammaWrite == BoolTrue); //If true, use main target's fsaa settings, else disable uint fsaa = textureDef.fsaa ? defaultFsaa : 0; const String &fsaaHint = textureDef.fsaa ? defaultFsaaHint : StringUtil::BLANK; uint width = textureDef.width; uint height = textureDef.height; if( finalTarget ) { if( textureDef.width == 0 ) width = static_cast<uint>( ceilf( finalTarget->getWidth() * textureDef.widthFactor ) ); if( textureDef.height == 0 ) height = static_cast<uint>( ceilf( finalTarget->getHeight() * textureDef.heightFactor ) ); } if( textureDef.formatList.size() == 1 ) { //Normal RT TexturePtr tex = TextureManager::getSingleton().createManual( texName, ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME, TEX_TYPE_2D, width, height, 0, textureDef.formatList[0], TU_RENDERTARGET, 0, hwGamma, fsaa, fsaaHint, textureDef.fsaaExplicitResolve ); RenderTexture* rt = tex->getBuffer()->getRenderTarget(); newChannel.target = rt; newChannel.textures.push_back( tex ); } else { //MRT MultiRenderTarget* mrt = renderSys->createMultiRenderTarget( texName ); PixelFormatList::const_iterator pixIt = textureDef.formatList.begin(); PixelFormatList::const_iterator pixEn = textureDef.formatList.end(); newChannel.target = mrt; while( pixIt != pixEn ) { size_t rtNum = pixIt - textureDef.formatList.begin(); TexturePtr tex = TextureManager::getSingleton().createManual( texName + StringConverter::toString( rtNum ), ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME, TEX_TYPE_2D, width, height, 0, *pixIt, TU_RENDERTARGET, 0, hwGamma, fsaa, fsaaHint, textureDef.fsaaExplicitResolve ); RenderTexture* rt = tex->getBuffer()->getRenderTarget(); mrt->bindSurface( rtNum, rt ); newChannel.textures.push_back( tex ); ++pixIt; } } return newChannel; } //----------------------------------------------------------------------------------- void TextureDefinitionBase::destroyTextures( CompositorChannelVec &inOutTexContainer, RenderSystem *renderSys ) { CompositorChannelVec::const_iterator itor = inOutTexContainer.begin(); CompositorChannelVec::const_iterator end = inOutTexContainer.end(); while( itor != end ) { if( itor->isValid() ) { if( !itor->isMrt() ) { //Normal RT. We don't hold any reference to, so just deregister from TextureManager TextureManager::getSingleton().remove( itor->textures[0]->getName() ); } else { //MRT. We need to destroy both the MultiRenderTarget ptr AND the textures renderSys->destroyRenderTarget( itor->target->getName() ); for( size_t i=0; i<itor->textures.size(); ++i ) TextureManager::getSingleton().remove( itor->textures[i]->getName() ); } } ++itor; } inOutTexContainer.clear(); } //----------------------------------------------------------------------------------- void TextureDefinitionBase::recreateResizableTextures( const TextureDefinitionVec &textureDefs, CompositorChannelVec &inOutTexContainer, const RenderTarget *finalTarget, RenderSystem *renderSys, const CompositorNodeVec &connectedNodes, const CompositorPassVec *passes ) { TextureDefinitionVec::const_iterator itor = textureDefs.begin(); TextureDefinitionVec::const_iterator end = textureDefs.end(); CompositorChannelVec::iterator itorTex = inOutTexContainer.begin(); while( itor != end ) { if( (itor->width == 0 || itor->height == 0) && itorTex->isValid() ) { for( size_t i=0; i<itorTex->textures.size(); ++i ) TextureManager::getSingleton().remove( itorTex->textures[i]->getName() ); CompositorChannel newChannel = createTexture( *itor, itorTex->target->getName(), finalTarget, renderSys ); if( passes ) { CompositorPassVec::const_iterator passIt = passes->begin(); CompositorPassVec::const_iterator passEn = passes->end(); while( passIt != passEn ) { (*passIt)->notifyRecreated( *itorTex, newChannel ); ++passIt; } } CompositorNodeVec::const_iterator itNodes = connectedNodes.begin(); CompositorNodeVec::const_iterator enNodes = connectedNodes.end(); while( itNodes != enNodes ) { (*itNodes)->notifyRecreated( *itorTex, newChannel ); ++itNodes; } if( !itorTex->isMrt() ) renderSys->destroyRenderTarget( itorTex->target->getName() ); *itorTex = newChannel; } ++itorTex; ++itor; } } } <commit_msg>Fixed a few merge issues. More remain.<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2013 Torus Knot Software Ltd 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 "OgreStableHeaders.h" #include "Compositor/OgreTextureDefinition.h" #include "Compositor/OgreCompositorNode.h" #include "Compositor/Pass/OgreCompositorPass.h" #include "OgreRenderTarget.h" #include "OgreHardwarePixelBuffer.h" #include "OgreRenderSystem.h" namespace Ogre { TextureDefinitionBase::TextureDefinitionBase( TextureSource defaultSource ) : mDefaultLocalTextureSource( defaultSource ) { assert( mDefaultLocalTextureSource == TEXTURE_LOCAL || mDefaultLocalTextureSource == TEXTURE_GLOBAL ); } //----------------------------------------------------------------------------------- size_t TextureDefinitionBase::getNumInputChannels(void) const { size_t numInputChannels = 0; NameToChannelMap::const_iterator itor = mNameToChannelMap.begin(); NameToChannelMap::const_iterator end = mNameToChannelMap.end(); while( itor != end ) { size_t index; TextureSource texSource; decodeTexSource( itor->second, index, texSource ); if( texSource == TEXTURE_INPUT ) ++numInputChannels; ++itor; } return numInputChannels; } //----------------------------------------------------------------------------------- void TextureDefinitionBase::decodeTexSource( uint32 encodedVal, size_t &outIdx, TextureSource &outTexSource ) { uint32 texSource = (encodedVal & 0xC0000000) >> 30; assert( texSource < NUM_TEXTURES_SOURCES ); outIdx = encodedVal & 0x3FFFFFFF; outTexSource = static_cast<TextureSource>( texSource ); } //----------------------------------------------------------------------------------- void TextureDefinitionBase::getTextureSource( IdString name, size_t &index, TextureSource &textureSource ) const { NameToChannelMap::const_iterator itor = mNameToChannelMap.find( name ); if( itor == mNameToChannelMap.end() ) { OGRE_EXCEPT( Exception::ERR_ITEM_NOT_FOUND, "Can't find texture with name: '" + name.getFriendlyText() + "'" " If it's a global texture, trying to use it in the output channel will fail.", "CompositorNodeDef::getTextureSource" ); } decodeTexSource( itor->second, index, textureSource ); } //----------------------------------------------------------------------------------- TextureDefinitionBase::TextureDefinition* TextureDefinitionBase::addTextureDefinition ( const String &name ) { IdString hashedName = addTextureSourceName( name, mLocalTextureDefs.size(), mDefaultLocalTextureSource ); mLocalTextureDefs.push_back( TextureDefinition( hashedName ) ); return &mLocalTextureDefs.back(); } //----------------------------------------------------------------------------------- void TextureDefinitionBase::createTextures( const TextureDefinitionVec &textureDefs, CompositorChannelVec &inOutTexContainer, IdType id, bool uniqueNames, const RenderTarget *finalTarget, RenderSystem *renderSys ) { inOutTexContainer.reserve( textureDefs.size() ); //Create the local textures TextureDefinitionVec::const_iterator itor = textureDefs.begin(); TextureDefinitionVec::const_iterator end = textureDefs.end(); while( itor != end ) { String textureName; if( !uniqueNames ) textureName = (itor->name + IdString( id )).getFriendlyText(); else textureName = itor->name.getFriendlyText(); CompositorChannel newChannel = createTexture( *itor, textureName, finalTarget, renderSys ); inOutTexContainer.push_back( newChannel ); ++itor; } } //----------------------------------------------------------------------------------- CompositorChannel TextureDefinitionBase::createTexture( const TextureDefinition &textureDef, const String &texName, const RenderTarget *finalTarget, RenderSystem *renderSys ) { CompositorChannel newChannel; bool defaultHwGamma = false; uint defaultFsaa = 0; String defaultFsaaHint = StringUtil::BLANK; if( finalTarget ) { // Inherit settings from target defaultHwGamma = finalTarget->isHardwareGammaEnabled(); defaultFsaa = finalTarget->getFSAA(); defaultFsaaHint = finalTarget->getFSAAHint(); } //If undefined, use main target's hw gamma settings, else use explicit setting bool hwGamma = textureDef.hwGammaWrite == BoolUndefined ? defaultHwGamma : (textureDef.hwGammaWrite == BoolTrue); //If true, use main target's fsaa settings, else disable uint fsaa = textureDef.fsaa ? defaultFsaa : 0; const String &fsaaHint = textureDef.fsaa ? defaultFsaaHint : StringUtil::BLANK; uint width = textureDef.width; uint height = textureDef.height; if( finalTarget ) { if( textureDef.width == 0 ) width = static_cast<uint>( ceilf( finalTarget->getWidth() * textureDef.widthFactor ) ); if( textureDef.height == 0 ) height = static_cast<uint>( ceilf( finalTarget->getHeight() * textureDef.heightFactor ) ); } if( textureDef.formatList.size() == 1 ) { //Normal RT TexturePtr tex = TextureManager::getSingleton().createManual( texName, ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME, TEX_TYPE_2D, width, height, 0, textureDef.formatList[0], TU_RENDERTARGET, 0, hwGamma, fsaa, fsaaHint, textureDef.fsaaExplicitResolve ); RenderTexture* rt = tex->getBuffer()->getRenderTarget(); newChannel.target = rt; newChannel.textures.push_back( tex ); } else { //MRT MultiRenderTarget* mrt = renderSys->createMultiRenderTarget( texName ); PixelFormatList::const_iterator pixIt = textureDef.formatList.begin(); PixelFormatList::const_iterator pixEn = textureDef.formatList.end(); newChannel.target = mrt; while( pixIt != pixEn ) { size_t rtNum = pixIt - textureDef.formatList.begin(); TexturePtr tex = TextureManager::getSingleton().createManual( texName + StringConverter::toString( rtNum ), ResourceGroupManager::INTERNAL_RESOURCE_GROUP_NAME, TEX_TYPE_2D, width, height, 0, *pixIt, TU_RENDERTARGET, 0, hwGamma, fsaa, fsaaHint, textureDef.fsaaExplicitResolve ); RenderTexture* rt = tex->getBuffer()->getRenderTarget(); mrt->bindSurface( rtNum, rt ); newChannel.textures.push_back( tex ); ++pixIt; } } return newChannel; } //----------------------------------------------------------------------------------- void TextureDefinitionBase::destroyTextures( CompositorChannelVec &inOutTexContainer, RenderSystem *renderSys ) { CompositorChannelVec::const_iterator itor = inOutTexContainer.begin(); CompositorChannelVec::const_iterator end = inOutTexContainer.end(); while( itor != end ) { if( itor->isValid() ) { if( !itor->isMrt() ) { //Normal RT. We don't hold any reference to, so just deregister from TextureManager TextureManager::getSingleton().remove( itor->textures[0]->getName() ); } else { //MRT. We need to destroy both the MultiRenderTarget ptr AND the textures renderSys->destroyRenderTarget( itor->target->getName() ); for( size_t i=0; i<itor->textures.size(); ++i ) TextureManager::getSingleton().remove( itor->textures[i]->getName() ); } } ++itor; } inOutTexContainer.clear(); } //----------------------------------------------------------------------------------- void TextureDefinitionBase::recreateResizableTextures( const TextureDefinitionVec &textureDefs, CompositorChannelVec &inOutTexContainer, const RenderTarget *finalTarget, RenderSystem *renderSys, const CompositorNodeVec &connectedNodes, const CompositorPassVec *passes ) { TextureDefinitionVec::const_iterator itor = textureDefs.begin(); TextureDefinitionVec::const_iterator end = textureDefs.end(); CompositorChannelVec::iterator itorTex = inOutTexContainer.begin(); while( itor != end ) { if( (itor->width == 0 || itor->height == 0) && itorTex->isValid() ) { for( size_t i=0; i<itorTex->textures.size(); ++i ) TextureManager::getSingleton().remove( itorTex->textures[i]->getName() ); CompositorChannel newChannel = createTexture( *itor, itorTex->target->getName(), finalTarget, renderSys ); if( passes ) { CompositorPassVec::const_iterator passIt = passes->begin(); CompositorPassVec::const_iterator passEn = passes->end(); while( passIt != passEn ) { (*passIt)->notifyRecreated( *itorTex, newChannel ); ++passIt; } } CompositorNodeVec::const_iterator itNodes = connectedNodes.begin(); CompositorNodeVec::const_iterator enNodes = connectedNodes.end(); while( itNodes != enNodes ) { (*itNodes)->notifyRecreated( *itorTex, newChannel ); ++itNodes; } if( !itorTex->isMrt() ) renderSys->destroyRenderTarget( itorTex->target->getName() ); *itorTex = newChannel; } ++itorTex; ++itor; } } } <|endoftext|>
<commit_before>/* -------------------------------------------------------------------------- * * OpenSim: ConditionalPathPoint.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2012 Stanford University and the Authors * * Author(s): Peter Loan * * * * 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. * * -------------------------------------------------------------------------- */ //============================================================================= // INCLUDES //============================================================================= #include "ConditionalPathPoint.h" #include <OpenSim/Common/XMLDocument.h> #include <OpenSim/Simulation/Model/Model.h> #include <OpenSim/Simulation/Model/GeometryPath.h> #include <OpenSim/Simulation/Model/CoordinateSet.h> #include <OpenSim/Simulation/SimbodyEngine/SimbodyEngine.h> #include <OpenSim/Simulation/SimbodyEngine/Body.h> #include <OpenSim/Simulation/SimbodyEngine/Coordinate.h> //============================================================================= // STATICS //============================================================================= using namespace std; using namespace OpenSim; //============================================================================= // CONSTRUCTOR(S) AND DESTRUCTOR //============================================================================= //_____________________________________________________________________________ /** * Default constructor. */ ConditionalPathPoint::ConditionalPathPoint() : PathPoint() { constructInfrastructure(); } //_____________________________________________________________________________ /** * Destructor. */ ConditionalPathPoint::~ConditionalPathPoint() {} //_____________________________________________________________________________ /** * Override default implementation by object to intercept and fix the XML node * underneath the model to match current version */ void ConditionalPathPoint::updateFromXMLNode(SimTK::Xml::Element& node, int versionNumber) { if (versionNumber <= 20001) { // Version has to be 1.6 or later, otherwise assert XMLDocument::renameChildNode(node, "coordinates", "coordinate"); } if (versionNumber < 30505) { // replace old properties with latest use of Connectors SimTK::Xml::element_iterator coord = node.element_begin("coordinate"); std::string coord_name(""); if (coord != node.element_end()) coord->getValueAs<std::string>(coord_name); XMLDocument::addConnector(node, "Connector_Coordinate_", "coordinate", coord_name); } // Call base class now assuming _node has been corrected for current version PathPoint::updateFromXMLNode(node, versionNumber); } //_____________________________________________________________________________ /** * Connect properties to local pointers. */ void ConditionalPathPoint::constructProperties() { Array<double> defaultRange(0.0, 2); //two values of the range constructProperty_range(defaultRange); } void ConditionalPathPoint::constructConnectors() { constructConnector<Coordinate>("coordinate"); } //_____________________________________________________________________________ /** * Set the coordinate that this point is linked to. * * @return Whether or not this point is active. */ void ConditionalPathPoint::setCoordinate(const Coordinate& coordinate) { updConnector<Coordinate>("coordinate").connect(coordinate); } bool ConditionalPathPoint::hasCoordinate() const { return getConnector<Coordinate>("coordinate").isConnected(); } const Coordinate& ConditionalPathPoint::getCoordinate() const { return getConnectee<Coordinate>("coordinate"); } //_____________________________________________________________________________ /** * Set the range min. * * @param aRange range min to change to. */ void ConditionalPathPoint::setRangeMin(double minVal) { set_range(0, minVal); } //_____________________________________________________________________________ /** * Set the range max. * * @param aRange range max to change to. */ void ConditionalPathPoint::setRangeMax(double maxVal) { set_range(1, maxVal); } //_____________________________________________________________________________ /** * Determine if this point is active by checking the value of the * coordinate that it is linked to. * * @return Whether or not this point is active. */ bool ConditionalPathPoint::isActive(const SimTK::State& s) const { if (getConnector<Coordinate>("coordinate").isConnected()) { double value = getConnectee<Coordinate>("coordinate").getValue(s); if (value >= get_range(0) - 1e-5 && value <= get_range(1) + 1e-5) return true; } return false; } <commit_msg>Remove invalid doxygen comment in .cpp<commit_after>/* -------------------------------------------------------------------------- * * OpenSim: ConditionalPathPoint.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2012 Stanford University and the Authors * * Author(s): Peter Loan * * * * 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. * * -------------------------------------------------------------------------- */ //============================================================================= // INCLUDES //============================================================================= #include "ConditionalPathPoint.h" #include <OpenSim/Common/XMLDocument.h> #include <OpenSim/Simulation/Model/Model.h> #include <OpenSim/Simulation/Model/GeometryPath.h> #include <OpenSim/Simulation/Model/CoordinateSet.h> #include <OpenSim/Simulation/SimbodyEngine/SimbodyEngine.h> #include <OpenSim/Simulation/SimbodyEngine/Body.h> #include <OpenSim/Simulation/SimbodyEngine/Coordinate.h> //============================================================================= // STATICS //============================================================================= using namespace std; using namespace OpenSim; //============================================================================= // CONSTRUCTOR(S) AND DESTRUCTOR //============================================================================= //_____________________________________________________________________________ /** * Default constructor. */ ConditionalPathPoint::ConditionalPathPoint() : PathPoint() { constructInfrastructure(); } //_____________________________________________________________________________ /** * Destructor. */ ConditionalPathPoint::~ConditionalPathPoint() {} //_____________________________________________________________________________ /** * Override default implementation by object to intercept and fix the XML node * underneath the model to match current version */ void ConditionalPathPoint::updateFromXMLNode(SimTK::Xml::Element& node, int versionNumber) { if (versionNumber <= 20001) { // Version has to be 1.6 or later, otherwise assert XMLDocument::renameChildNode(node, "coordinates", "coordinate"); } if (versionNumber < 30505) { // replace old properties with latest use of Connectors SimTK::Xml::element_iterator coord = node.element_begin("coordinate"); std::string coord_name(""); if (coord != node.element_end()) coord->getValueAs<std::string>(coord_name); XMLDocument::addConnector(node, "Connector_Coordinate_", "coordinate", coord_name); } // Call base class now assuming _node has been corrected for current version PathPoint::updateFromXMLNode(node, versionNumber); } //_____________________________________________________________________________ /** * Connect properties to local pointers. */ void ConditionalPathPoint::constructProperties() { Array<double> defaultRange(0.0, 2); //two values of the range constructProperty_range(defaultRange); } void ConditionalPathPoint::constructConnectors() { constructConnector<Coordinate>("coordinate"); } //_____________________________________________________________________________ /* * Set the coordinate that this point is linked to. */ void ConditionalPathPoint::setCoordinate(const Coordinate& coordinate) { updConnector<Coordinate>("coordinate").connect(coordinate); } bool ConditionalPathPoint::hasCoordinate() const { return getConnector<Coordinate>("coordinate").isConnected(); } const Coordinate& ConditionalPathPoint::getCoordinate() const { return getConnectee<Coordinate>("coordinate"); } //_____________________________________________________________________________ /** * Set the range min. * * @param aRange range min to change to. */ void ConditionalPathPoint::setRangeMin(double minVal) { set_range(0, minVal); } //_____________________________________________________________________________ /** * Set the range max. * * @param aRange range max to change to. */ void ConditionalPathPoint::setRangeMax(double maxVal) { set_range(1, maxVal); } //_____________________________________________________________________________ /** * Determine if this point is active by checking the value of the * coordinate that it is linked to. * * @return Whether or not this point is active. */ bool ConditionalPathPoint::isActive(const SimTK::State& s) const { if (getConnector<Coordinate>("coordinate").isConnected()) { double value = getConnectee<Coordinate>("coordinate").getValue(s); if (value >= get_range(0) - 1e-5 && value <= get_range(1) + 1e-5) return true; } return false; } <|endoftext|>
<commit_before>#include "UI/reversesearchwindow.h" #include "Models/reversesearchmodel.h" #include "Misc/shared.h" #include "Misc/track.h" #include "Misc/application.h" #include <QHeaderView> #include <QDebug> #include <QScrollBar> #include <QPalette> #include <QTextCursor> #include <QTextCharFormat> #include <QMessageBox> ReverseSearchWindow::ReverseSearchWindow(QWidget *parent) : QWidget(parent) { reverseSearchModel = new ReverseSearchModel; vbox = new QVBoxLayout; indexButton = new QPushButton("Update index"); connect(indexButton, &QPushButton::clicked, [&] { if (reverseIndexProgressDialog == nullptr) reverseIndexProgressDialog = new ReverseIndexProgressDialog(this); reverseIndexProgressDialog->setModal(true); connect(reverseIndexProgressDialog, &ReverseIndexProgressDialog::abortClicked, this, [&] { reverseSearchModel->abortIndexUpdate(); reverseIndexProgressDialog->hide(); }); reverseIndexProgressDialog->show(); reverseSearchModel->updateIndex(); Application::processEvents(); }); connect(reverseSearchModel, &ReverseSearchModel::indexingStarted, [&](int total) { reverseIndexProgressDialog->setProgress(0, total); Application::processEvents(); }); connect(reverseSearchModel, &ReverseSearchModel::indexingProgressUpdate, [&](int finished, int total) { reverseIndexProgressDialog->setProgress(finished, total); Application::processEvents(); }); connect(reverseSearchModel, &ReverseSearchModel::indexingFinished, [&] { reverseIndexProgressDialog->hide(); qDebug() << "Indexing finished"; }); searchString = new QLineEdit; searchString->setPlaceholderText("Enter search string..."); results = new QTreeWidget; lyricDisplay = new QPlainTextEdit; vbox->addWidget(indexButton); vbox->addWidget(searchString); vbox->addWidget(results); vbox->addWidget(lyricDisplay); vbox->setStretch(2, 2); vbox->setStretch(3, 5); setLayout(vbox); results->setIndentation(0); results->setColumnCount(2); results->setHeaderLabels({ "Artist", "Title" }); results->header()->setStretchLastSection(true); results->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents); results->header()->setMinimumSectionSize(75); results->header()->setSectionResizeMode(1, QHeaderView::ResizeToContents); results->header()->setStretchLastSection(true); connect(results, &QTreeWidget::currentItemChanged, [&](QTreeWidgetItem *current, QTreeWidgetItem *previous) { Q_UNUSED(previous); if (!current) return; QString lyricData = current->data(0, LyricsRole).toString(); lyricDisplay->document()->clear(); lyricDisplay->setPlainText(lyricData); lyricDisplay->setFocus(); // // Highlight all occurrences of the search string // QTextCharFormat fmt; fmt.setBackground(QColor(255, 127, 0)); fmt.setForeground(QColor(Qt::white)); int firstIndex = -1; int lastIndex = -1; int matchIndex = -1; while ((matchIndex = lyricData.indexOf(searchString->text(), lastIndex + 1, Qt::CaseInsensitive)) >= 0) { QTextCursor cursor(lyricDisplay->document()); cursor.setPosition(matchIndex, QTextCursor::MoveAnchor); cursor.setPosition(matchIndex + searchString->text().length(), QTextCursor::KeepAnchor); cursor.setCharFormat(fmt); if (firstIndex == -1) { // Move the cursor to the first hit firstIndex = matchIndex; lyricDisplay->setTextCursor(cursor); lyricDisplay->centerCursor(); } lastIndex = matchIndex; } }); QPalette pal = lyricDisplay->palette(); pal.setColor(QPalette::Highlight, QColor(255, 127, 0)); pal.setColor(QPalette::HighlightedText, QColor(Qt::white)); lyricDisplay->setPalette(pal); lyricDisplay->setReadOnly(true); connect(searchString, &QLineEdit::textEdited, this, &ReverseSearchWindow::searchStringUpdated); resize(600, 700); setWindowTitle("Lyricus - Reverse Lyric Search"); } void ReverseSearchWindow::searchStringUpdated(QString newString) { if (newString.length() <= 2) return; QList<Track> data = reverseSearchModel->tracksMatchingLyrics(newString); qDebug() << data.length() << "tracks matched"; results->clear(); QList<QTreeWidgetItem*> items; for (const Track &track : data) { auto *item = new QTreeWidgetItem({ track.artist, track.title }); item->setData(0, LyricsRole, track.lyrics); items.append(item); } results->addTopLevelItems(items); } void ReverseSearchWindow::checkIndex() { if (reverseSearchModel->numberOfTracksInIndex() <= 0) { QMessageBox::information(this, "The index is empty", "The reverse lyric search index is empty. You need to set the index paths in the Preferences window, " "and then update the index before this window will be useful.", QMessageBox::Ok); } } <commit_msg>Improve UI responsiveness by re-drawing the UI *prior* to starting work, not after<commit_after>#include "UI/reversesearchwindow.h" #include "Models/reversesearchmodel.h" #include "Misc/shared.h" #include "Misc/track.h" #include "Misc/application.h" #include <QHeaderView> #include <QDebug> #include <QScrollBar> #include <QPalette> #include <QTextCursor> #include <QTextCharFormat> #include <QMessageBox> ReverseSearchWindow::ReverseSearchWindow(QWidget *parent) : QWidget(parent) { reverseSearchModel = new ReverseSearchModel; vbox = new QVBoxLayout; indexButton = new QPushButton("Update index"); connect(indexButton, &QPushButton::clicked, [&] { if (reverseIndexProgressDialog == nullptr) reverseIndexProgressDialog = new ReverseIndexProgressDialog(this); reverseIndexProgressDialog->setModal(true); connect(reverseIndexProgressDialog, &ReverseIndexProgressDialog::abortClicked, this, [&] { reverseSearchModel->abortIndexUpdate(); reverseIndexProgressDialog->hide(); }); reverseIndexProgressDialog->show(); Application::processEvents(); reverseSearchModel->updateIndex(); }); connect(reverseSearchModel, &ReverseSearchModel::indexingStarted, [&](int total) { reverseIndexProgressDialog->setProgress(0, total); Application::processEvents(); }); connect(reverseSearchModel, &ReverseSearchModel::indexingProgressUpdate, [&](int finished, int total) { reverseIndexProgressDialog->setProgress(finished, total); Application::processEvents(); }); connect(reverseSearchModel, &ReverseSearchModel::indexingFinished, [&] { reverseIndexProgressDialog->hide(); qDebug() << "Indexing finished"; }); searchString = new QLineEdit; searchString->setPlaceholderText("Enter search string..."); results = new QTreeWidget; lyricDisplay = new QPlainTextEdit; vbox->addWidget(indexButton); vbox->addWidget(searchString); vbox->addWidget(results); vbox->addWidget(lyricDisplay); vbox->setStretch(2, 2); vbox->setStretch(3, 5); setLayout(vbox); results->setIndentation(0); results->setColumnCount(2); results->setHeaderLabels({ "Artist", "Title" }); results->header()->setStretchLastSection(true); results->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents); results->header()->setMinimumSectionSize(75); results->header()->setSectionResizeMode(1, QHeaderView::ResizeToContents); results->header()->setStretchLastSection(true); connect(results, &QTreeWidget::currentItemChanged, [&](QTreeWidgetItem *current, QTreeWidgetItem *previous) { Q_UNUSED(previous); if (!current) return; QString lyricData = current->data(0, LyricsRole).toString(); lyricDisplay->document()->clear(); lyricDisplay->setPlainText(lyricData); lyricDisplay->setFocus(); // // Highlight all occurrences of the search string // QTextCharFormat fmt; fmt.setBackground(QColor(255, 127, 0)); fmt.setForeground(QColor(Qt::white)); int firstIndex = -1; int lastIndex = -1; int matchIndex = -1; while ((matchIndex = lyricData.indexOf(searchString->text(), lastIndex + 1, Qt::CaseInsensitive)) >= 0) { QTextCursor cursor(lyricDisplay->document()); cursor.setPosition(matchIndex, QTextCursor::MoveAnchor); cursor.setPosition(matchIndex + searchString->text().length(), QTextCursor::KeepAnchor); cursor.setCharFormat(fmt); if (firstIndex == -1) { // Move the cursor to the first hit firstIndex = matchIndex; lyricDisplay->setTextCursor(cursor); lyricDisplay->centerCursor(); } lastIndex = matchIndex; } }); QPalette pal = lyricDisplay->palette(); pal.setColor(QPalette::Highlight, QColor(255, 127, 0)); pal.setColor(QPalette::HighlightedText, QColor(Qt::white)); lyricDisplay->setPalette(pal); lyricDisplay->setReadOnly(true); connect(searchString, &QLineEdit::textEdited, this, &ReverseSearchWindow::searchStringUpdated); resize(600, 700); setWindowTitle("Lyricus - Reverse Lyric Search"); } void ReverseSearchWindow::searchStringUpdated(QString newString) { if (newString.length() <= 2) return; QList<Track> data = reverseSearchModel->tracksMatchingLyrics(newString); qDebug() << data.length() << "tracks matched"; results->clear(); QList<QTreeWidgetItem*> items; for (const Track &track : data) { auto *item = new QTreeWidgetItem({ track.artist, track.title }); item->setData(0, LyricsRole, track.lyrics); items.append(item); } results->addTopLevelItems(items); } void ReverseSearchWindow::checkIndex() { if (reverseSearchModel->numberOfTracksInIndex() <= 0) { QMessageBox::information(this, "The index is empty", "The reverse lyric search index is empty. You need to set the index paths in the Preferences window, " "and then update the index before this window will be useful.", QMessageBox::Ok); } } <|endoftext|>
<commit_before>//------------------------------------------------------ // AliAnalysisTaskFemto - A task for the analysis framework // from the FEMTOSCOPY analysis of PWG2. Creates the necessary // connection between the ESD or AOD input and the femtoscopic // code. // Author: Adam Kisiel, OSU; Adam.Kisiel@cern.ch //------------------------------------------------------ #include "TROOT.h" #include "TChain.h" #include "TH1.h" #include "TCanvas.h" #include "TSystem.h" #include "TFile.h" #include "TInterpreter.h" #include "AliAnalysisTask.h" #include "AliESDEvent.h" #include "AliFemtoAnalysis.h" #include "AliAnalysisTaskFemto.h" #include "AliVHeader.h" #include "AliGenEventHeader.h" #include "AliGenHijingEventHeader.h" #include "AliGenCocktailEventHeader.h" ClassImp(AliAnalysisTaskFemto) // Default name for the setup macro of femto analysis // This function MUST be defined in the separate file !!! // extern AliFemtoManager *ConfigFemtoAnalysis(); //________________________________________________________________________ AliAnalysisTaskFemto::AliAnalysisTaskFemto(const char *name, const char *aConfigMacro="ConfigFemtoAnalysis.C"): AliAnalysisTask(name,""), fESD(0), fAOD(0), fStack(0), fOutputList(0), fReader(0x0), fManager(0x0), fAnalysisType(0), fConfigMacro(0) { // Constructor. // Input slot #0 works with an Ntuple DefineInput(0, TChain::Class()); // Output slot #0 writes into a TH1 container DefineOutput(0, TList::Class()); fConfigMacro = (char *) malloc(sizeof(char) * strlen(aConfigMacro)); strcpy(fConfigMacro, aConfigMacro); } AliAnalysisTaskFemto::AliAnalysisTaskFemto(const AliAnalysisTaskFemto& aFemtoTask): AliAnalysisTask(aFemtoTask), fESD(0), fAOD(0), fStack(0), fOutputList(0), fReader(0x0), fManager(0x0), fAnalysisType(0), fConfigMacro(0) { // copy constructor fESD = aFemtoTask.fESD; fAOD = aFemtoTask.fAOD; fStack = aFemtoTask.fStack; fOutputList = aFemtoTask.fOutputList; fReader = aFemtoTask.fReader; fManager = aFemtoTask.fManager; fAnalysisType = aFemtoTask.fAnalysisType; fConfigMacro = (char *) malloc(sizeof(char) * strlen(aFemtoTask.fConfigMacro)); strcpy(fConfigMacro, aFemtoTask.fConfigMacro); } AliAnalysisTaskFemto& AliAnalysisTaskFemto::operator=(const AliAnalysisTaskFemto& aFemtoTask){ // assignment operator if (this == &aFemtoTask) return *this; fESD = aFemtoTask.fESD; fAOD = aFemtoTask.fAOD; fStack = aFemtoTask.fStack; fOutputList = aFemtoTask.fOutputList; fReader = aFemtoTask.fReader; fManager = aFemtoTask.fManager; fAnalysisType = aFemtoTask.fAnalysisType; if (fConfigMacro) free(fConfigMacro); fConfigMacro = (char *) malloc(sizeof(char) * strlen(aFemtoTask.fConfigMacro)); strcpy(fConfigMacro, aFemtoTask.fConfigMacro); return *this; } AliAnalysisTaskFemto::~AliAnalysisTaskFemto() { if (fConfigMacro) free(fConfigMacro); } //________________________________________________________________________ void AliAnalysisTaskFemto::ConnectInputData(Option_t *) { printf(" ConnectInputData %s\n", GetName()); fESD = 0; fAOD = 0; fAnalysisType = 0; TTree* tree = dynamic_cast<TTree*> (GetInputData(0)); if (!tree) { Printf("ERROR: Could not read chain from input slot 0"); } else { AliESDInputHandler *esdH = dynamic_cast<AliESDInputHandler*> (AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()); if(esdH) { cout << "Selected ESD analysis" << endl; fAnalysisType = 1; if (!esdH) { Printf("ERROR: Could not get ESDInputHandler"); } else { fESD = esdH->GetEvent(); } } else { AliAODInputHandler *aodH = dynamic_cast<AliAODInputHandler*> (AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()); if (!aodH) { Printf("ERROR: Could not get AODInputHandler"); } else { cout << "Selected AOD analysis" << endl; fAnalysisType = 2; fAOD = aodH->GetEvent(); } } if ((!fAOD) && (!fESD)) { Printf("Wrong analysis type: Only ESD and AOD types are allowed!"); } } } //________________________________________________________________________ void AliAnalysisTaskFemto::CreateOutputObjects() { printf("Creating Femto Analysis objects\n"); gSystem->SetIncludePath("-I$ROOTSYS/include -I./STEERBase/ -I./ESD/ -I./AOD/ -I./ANALYSIS/ -I./ANALYSISalice/ -I./PWG2AOD/AOD -I./PWG2femtoscopy/FEMTOSCOPY/AliFemto -I./PWG2femtoscopyUser/FEMTOSCOPY/AliFemtoUser"); char fcm[2000]; // sprintf(fcm, "%s++", fConfigMacro); // gROOT->LoadMacro(fcm); gROOT->LoadMacro(fConfigMacro); // fJetFinder = (AliJetFinder*) gInterpreter->ProcessLine("ConfigJetAnalysis()"); SetFemtoManager((AliFemtoManager *) gInterpreter->ProcessLine("ConfigFemtoAnalysis()")); TList *tOL; fOutputList = fManager->Analysis(0)->GetOutputList(); for (unsigned int ian = 1; ian<fManager->AnalysisCollection()->size(); ian++) { tOL = fManager->Analysis(ian)->GetOutputList(); TIter nextListCf(tOL); while (TObject *obj = nextListCf()) { fOutputList->Add(obj); } delete tOL; } } //________________________________________________________________________ void AliAnalysisTaskFemto::Exec(Option_t *) { // Task making a femtoscopic analysis. if (fAnalysisType==1) { if (!fESD) { Printf("ERROR: fESD not available"); return; } //Get MC data AliMCEventHandler* mctruth = (AliMCEventHandler*) ((AliAnalysisManager::GetAnalysisManager())->GetMCtruthEventHandler()); AliGenHijingEventHeader *hdh = 0; if(mctruth) { fStack = mctruth->MCEvent()->Stack(); AliGenCocktailEventHeader *hd = dynamic_cast<AliGenCocktailEventHeader *> (mctruth->MCEvent()->GenEventHeader()); if (hd) { // printf ("Got MC cocktail event header %p\n", (void *) hd); TList *lhd = hd->GetHeaders(); // printf ("Got list of headers %d\n", lhd->GetEntries()); for (int iterh=0; iterh<lhd->GetEntries(); iterh++) { hdh = dynamic_cast<AliGenHijingEventHeader *> (lhd->At(iterh)); // printf ("HIJING header at %i is %p\n", iterh, (void *) hdh); } } } // Get ESD AliESDInputHandler *esdH = dynamic_cast<AliESDInputHandler*> (AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()); if (!esdH) { Printf("ERROR: Could not get ESDInputHandler"); return; } else { fESD = esdH->GetEvent(); } printf("Tracks in ESD: %d \n",fESD->GetNumberOfTracks()); if (fESD->GetNumberOfTracks() >= 0) { if (!fReader) { printf("ERROR: No ESD reader for ESD analysis !\n"); } AliFemtoEventReaderESDChain* fesdc = dynamic_cast<AliFemtoEventReaderESDChain *> (fReader); if (fesdc) { // Process the event with no Kine information fesdc->SetESDSource(fESD); fManager->ProcessEvent(); } AliFemtoEventReaderESDChainKine* fesdck = dynamic_cast<AliFemtoEventReaderESDChainKine *> (fReader); if (fesdck) { // Process the event with Kine information fesdck->SetESDSource(fESD); fesdck->SetStackSource(fStack); fesdck->SetGenEventHeader(hdh); fManager->ProcessEvent(); } AliFemtoEventReaderStandard* fstd = dynamic_cast<AliFemtoEventReaderStandard *> (fReader); if (fstd) { // Process the event with Kine information fstd->SetESDSource(fESD); if (mctruth) { fstd->SetStackSource(fStack); fstd->SetGenEventHeader(hdh); fstd->SetInputType(AliFemtoEventReaderStandard::kESDKine); } else fstd->SetInputType(AliFemtoEventReaderStandard::kESD); fManager->ProcessEvent(); } } // Post the output histogram list PostData(0, fOutputList); } if (fAnalysisType==2) { if (!fAOD) { Printf("ERROR: fAOD not available"); return; } // Get AOD AliAODInputHandler *aodH = dynamic_cast<AliAODInputHandler*> (AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()); if (!aodH) { Printf("ERROR: Could not get AODInputHandler"); return; } else { fAOD = aodH->GetEvent(); } printf("Tracks in AOD: %d \n",fAOD->GetNumberOfTracks()); if (fAOD->GetNumberOfTracks() > 0) { if (!fReader) { printf("ERROR: No AOD reader for AOD analysis! \n"); } else { AliFemtoEventReaderAODChain* faodc = dynamic_cast<AliFemtoEventReaderAODChain *> (fReader); if (faodc) { // Process the event faodc->SetAODSource(fAOD); fManager->ProcessEvent(); } AliFemtoEventReaderStandard* fstd = dynamic_cast<AliFemtoEventReaderStandard *> (fReader); if (fstd) { // Process the event fstd->SetAODSource(fAOD); fstd->SetInputType(AliFemtoEventReaderStandard::kAOD); fManager->ProcessEvent(); } } } // Post the output histogram list PostData(0, fOutputList); } } //________________________________________________________________________ void AliAnalysisTaskFemto::Terminate(Option_t *) { // Do the final processing if (fManager) { fManager->Finish(); } } //________________________________________________________________________ void AliAnalysisTaskFemto:: FinishTaskOutput() { // Do the final processing if (fManager) { fManager->Finish(); } } //________________________________________________________________________ void AliAnalysisTaskFemto::SetFemtoReaderESD(AliFemtoEventReaderESDChain *aReader) { printf("Selecting Femto reader for ESD\n"); fReader = aReader; } //________________________________________________________________________ void AliAnalysisTaskFemto::SetFemtoReaderESDKine(AliFemtoEventReaderESDChainKine *aReader) { printf("Selecting Femto reader for ESD with Kinematics information\n"); fReader = aReader; } //________________________________________________________________________ void AliAnalysisTaskFemto::SetFemtoReaderAOD(AliFemtoEventReaderAODChain *aReader) { printf("Selecting Femto reader for AOD\n"); fReader = aReader; } void AliAnalysisTaskFemto::SetFemtoReaderStandard(AliFemtoEventReaderStandard *aReader) { printf("Selecting Standard all-purpose Femto reader\n"); fReader = aReader; } //________________________________________________________________________ void AliAnalysisTaskFemto::SetFemtoManager(AliFemtoManager *aManager) { fManager = aManager; printf("Got reader %p\n", (void *) aManager->EventReader()); AliFemtoEventReaderESDChain *tReaderESDChain = dynamic_cast<AliFemtoEventReaderESDChain *> (aManager->EventReader()); AliFemtoEventReaderESDChainKine *tReaderESDChainKine = dynamic_cast<AliFemtoEventReaderESDChainKine *> (aManager->EventReader()); AliFemtoEventReaderAODChain *tReaderAODChain = dynamic_cast<AliFemtoEventReaderAODChain *> (aManager->EventReader()); AliFemtoEventReaderStandard *tReaderStandard = dynamic_cast<AliFemtoEventReaderStandard *> (aManager->EventReader()); if ((!tReaderESDChain) && (!tReaderESDChainKine) && (!tReaderAODChain) && (!tReaderStandard)) { printf("No AliFemto event reader created. Will not run femto analysis.\n"); return; } if (tReaderESDChain) SetFemtoReaderESD(tReaderESDChain); if (tReaderESDChainKine) SetFemtoReaderESDKine(tReaderESDChainKine); if (tReaderAODChain) SetFemtoReaderAOD(tReaderAODChain); if (tReaderStandard) SetFemtoReaderStandard(tReaderStandard); } <commit_msg>Fix warnings<commit_after>//------------------------------------------------------ // AliAnalysisTaskFemto - A task for the analysis framework // from the FEMTOSCOPY analysis of PWG2. Creates the necessary // connection between the ESD or AOD input and the femtoscopic // code. // Author: Adam Kisiel, OSU; Adam.Kisiel@cern.ch //------------------------------------------------------ #include "TROOT.h" #include "TChain.h" #include "TH1.h" #include "TCanvas.h" #include "TSystem.h" #include "TFile.h" #include "TInterpreter.h" #include "AliAnalysisTask.h" #include "AliESDEvent.h" #include "AliFemtoAnalysis.h" #include "AliAnalysisTaskFemto.h" #include "AliVHeader.h" #include "AliGenEventHeader.h" #include "AliGenHijingEventHeader.h" #include "AliGenCocktailEventHeader.h" ClassImp(AliAnalysisTaskFemto) // Default name for the setup macro of femto analysis // This function MUST be defined in the separate file !!! // extern AliFemtoManager *ConfigFemtoAnalysis(); //________________________________________________________________________ AliAnalysisTaskFemto::AliAnalysisTaskFemto(const char *name, const char *aConfigMacro="ConfigFemtoAnalysis.C"): AliAnalysisTask(name,""), fESD(0), fAOD(0), fStack(0), fOutputList(0), fReader(0x0), fManager(0x0), fAnalysisType(0), fConfigMacro(0) { // Constructor. // Input slot #0 works with an Ntuple DefineInput(0, TChain::Class()); // Output slot #0 writes into a TH1 container DefineOutput(0, TList::Class()); fConfigMacro = (char *) malloc(sizeof(char) * strlen(aConfigMacro)); strcpy(fConfigMacro, aConfigMacro); } AliAnalysisTaskFemto::AliAnalysisTaskFemto(const AliAnalysisTaskFemto& aFemtoTask): AliAnalysisTask(aFemtoTask), fESD(0), fAOD(0), fStack(0), fOutputList(0), fReader(0x0), fManager(0x0), fAnalysisType(0), fConfigMacro(0) { // copy constructor fESD = aFemtoTask.fESD; fAOD = aFemtoTask.fAOD; fStack = aFemtoTask.fStack; fOutputList = aFemtoTask.fOutputList; fReader = aFemtoTask.fReader; fManager = aFemtoTask.fManager; fAnalysisType = aFemtoTask.fAnalysisType; fConfigMacro = (char *) malloc(sizeof(char) * strlen(aFemtoTask.fConfigMacro)); strcpy(fConfigMacro, aFemtoTask.fConfigMacro); } AliAnalysisTaskFemto& AliAnalysisTaskFemto::operator=(const AliAnalysisTaskFemto& aFemtoTask){ // assignment operator if (this == &aFemtoTask) return *this; fESD = aFemtoTask.fESD; fAOD = aFemtoTask.fAOD; fStack = aFemtoTask.fStack; fOutputList = aFemtoTask.fOutputList; fReader = aFemtoTask.fReader; fManager = aFemtoTask.fManager; fAnalysisType = aFemtoTask.fAnalysisType; if (fConfigMacro) free(fConfigMacro); fConfigMacro = (char *) malloc(sizeof(char) * strlen(aFemtoTask.fConfigMacro)); strcpy(fConfigMacro, aFemtoTask.fConfigMacro); return *this; } AliAnalysisTaskFemto::~AliAnalysisTaskFemto() { if (fConfigMacro) free(fConfigMacro); } //________________________________________________________________________ void AliAnalysisTaskFemto::ConnectInputData(Option_t *) { printf(" ConnectInputData %s\n", GetName()); fESD = 0; fAOD = 0; fAnalysisType = 0; TTree* tree = dynamic_cast<TTree*> (GetInputData(0)); if (!tree) { Printf("ERROR: Could not read chain from input slot 0"); } else { AliESDInputHandler *esdH = dynamic_cast<AliESDInputHandler*> (AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()); if(esdH) { cout << "Selected ESD analysis" << endl; fAnalysisType = 1; if (!esdH) { Printf("ERROR: Could not get ESDInputHandler"); } else { fESD = esdH->GetEvent(); } } else { AliAODInputHandler *aodH = dynamic_cast<AliAODInputHandler*> (AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()); if (!aodH) { Printf("ERROR: Could not get AODInputHandler"); } else { cout << "Selected AOD analysis" << endl; fAnalysisType = 2; fAOD = aodH->GetEvent(); } } if ((!fAOD) && (!fESD)) { Printf("Wrong analysis type: Only ESD and AOD types are allowed!"); } } } //________________________________________________________________________ void AliAnalysisTaskFemto::CreateOutputObjects() { printf("Creating Femto Analysis objects\n"); gSystem->SetIncludePath("-I$ROOTSYS/include -I./STEERBase/ -I./ESD/ -I./AOD/ -I./ANALYSIS/ -I./ANALYSISalice/ -I./PWG2AOD/AOD -I./PWG2femtoscopy/FEMTOSCOPY/AliFemto -I./PWG2femtoscopyUser/FEMTOSCOPY/AliFemtoUser"); // char fcm[2000]; // sprintf(fcm, "%s++", fConfigMacro); // gROOT->LoadMacro(fcm); gROOT->LoadMacro(fConfigMacro); // fJetFinder = (AliJetFinder*) gInterpreter->ProcessLine("ConfigJetAnalysis()"); SetFemtoManager((AliFemtoManager *) gInterpreter->ProcessLine("ConfigFemtoAnalysis()")); TList *tOL; fOutputList = fManager->Analysis(0)->GetOutputList(); for (unsigned int ian = 1; ian<fManager->AnalysisCollection()->size(); ian++) { tOL = fManager->Analysis(ian)->GetOutputList(); TIter nextListCf(tOL); while (TObject *obj = nextListCf()) { fOutputList->Add(obj); } delete tOL; } } //________________________________________________________________________ void AliAnalysisTaskFemto::Exec(Option_t *) { // Task making a femtoscopic analysis. if (fAnalysisType==1) { if (!fESD) { Printf("ERROR: fESD not available"); return; } //Get MC data AliMCEventHandler* mctruth = (AliMCEventHandler*) ((AliAnalysisManager::GetAnalysisManager())->GetMCtruthEventHandler()); AliGenHijingEventHeader *hdh = 0; if(mctruth) { fStack = mctruth->MCEvent()->Stack(); AliGenCocktailEventHeader *hd = dynamic_cast<AliGenCocktailEventHeader *> (mctruth->MCEvent()->GenEventHeader()); if (hd) { // printf ("Got MC cocktail event header %p\n", (void *) hd); TList *lhd = hd->GetHeaders(); // printf ("Got list of headers %d\n", lhd->GetEntries()); for (int iterh=0; iterh<lhd->GetEntries(); iterh++) { hdh = dynamic_cast<AliGenHijingEventHeader *> (lhd->At(iterh)); // printf ("HIJING header at %i is %p\n", iterh, (void *) hdh); } } } // Get ESD AliESDInputHandler *esdH = dynamic_cast<AliESDInputHandler*> (AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()); if (!esdH) { Printf("ERROR: Could not get ESDInputHandler"); return; } else { fESD = esdH->GetEvent(); } printf("Tracks in ESD: %d \n",fESD->GetNumberOfTracks()); if (fESD->GetNumberOfTracks() >= 0) { if (!fReader) { printf("ERROR: No ESD reader for ESD analysis !\n"); } AliFemtoEventReaderESDChain* fesdc = dynamic_cast<AliFemtoEventReaderESDChain *> (fReader); if (fesdc) { // Process the event with no Kine information fesdc->SetESDSource(fESD); fManager->ProcessEvent(); } AliFemtoEventReaderESDChainKine* fesdck = dynamic_cast<AliFemtoEventReaderESDChainKine *> (fReader); if (fesdck) { // Process the event with Kine information fesdck->SetESDSource(fESD); fesdck->SetStackSource(fStack); fesdck->SetGenEventHeader(hdh); fManager->ProcessEvent(); } AliFemtoEventReaderStandard* fstd = dynamic_cast<AliFemtoEventReaderStandard *> (fReader); if (fstd) { // Process the event with Kine information fstd->SetESDSource(fESD); if (mctruth) { fstd->SetStackSource(fStack); fstd->SetGenEventHeader(hdh); fstd->SetInputType(AliFemtoEventReaderStandard::kESDKine); } else fstd->SetInputType(AliFemtoEventReaderStandard::kESD); fManager->ProcessEvent(); } } // Post the output histogram list PostData(0, fOutputList); } if (fAnalysisType==2) { if (!fAOD) { Printf("ERROR: fAOD not available"); return; } // Get AOD AliAODInputHandler *aodH = dynamic_cast<AliAODInputHandler*> (AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()); if (!aodH) { Printf("ERROR: Could not get AODInputHandler"); return; } else { fAOD = aodH->GetEvent(); } printf("Tracks in AOD: %d \n",fAOD->GetNumberOfTracks()); if (fAOD->GetNumberOfTracks() > 0) { if (!fReader) { printf("ERROR: No AOD reader for AOD analysis! \n"); } else { AliFemtoEventReaderAODChain* faodc = dynamic_cast<AliFemtoEventReaderAODChain *> (fReader); if (faodc) { // Process the event faodc->SetAODSource(fAOD); fManager->ProcessEvent(); } AliFemtoEventReaderStandard* fstd = dynamic_cast<AliFemtoEventReaderStandard *> (fReader); if (fstd) { // Process the event fstd->SetAODSource(fAOD); fstd->SetInputType(AliFemtoEventReaderStandard::kAOD); fManager->ProcessEvent(); } } } // Post the output histogram list PostData(0, fOutputList); } } //________________________________________________________________________ void AliAnalysisTaskFemto::Terminate(Option_t *) { // Do the final processing if (fManager) { fManager->Finish(); } } //________________________________________________________________________ void AliAnalysisTaskFemto:: FinishTaskOutput() { // Do the final processing if (fManager) { fManager->Finish(); } } //________________________________________________________________________ void AliAnalysisTaskFemto::SetFemtoReaderESD(AliFemtoEventReaderESDChain *aReader) { printf("Selecting Femto reader for ESD\n"); fReader = aReader; } //________________________________________________________________________ void AliAnalysisTaskFemto::SetFemtoReaderESDKine(AliFemtoEventReaderESDChainKine *aReader) { printf("Selecting Femto reader for ESD with Kinematics information\n"); fReader = aReader; } //________________________________________________________________________ void AliAnalysisTaskFemto::SetFemtoReaderAOD(AliFemtoEventReaderAODChain *aReader) { printf("Selecting Femto reader for AOD\n"); fReader = aReader; } void AliAnalysisTaskFemto::SetFemtoReaderStandard(AliFemtoEventReaderStandard *aReader) { printf("Selecting Standard all-purpose Femto reader\n"); fReader = aReader; } //________________________________________________________________________ void AliAnalysisTaskFemto::SetFemtoManager(AliFemtoManager *aManager) { fManager = aManager; printf("Got reader %p\n", (void *) aManager->EventReader()); AliFemtoEventReaderESDChain *tReaderESDChain = dynamic_cast<AliFemtoEventReaderESDChain *> (aManager->EventReader()); AliFemtoEventReaderESDChainKine *tReaderESDChainKine = dynamic_cast<AliFemtoEventReaderESDChainKine *> (aManager->EventReader()); AliFemtoEventReaderAODChain *tReaderAODChain = dynamic_cast<AliFemtoEventReaderAODChain *> (aManager->EventReader()); AliFemtoEventReaderStandard *tReaderStandard = dynamic_cast<AliFemtoEventReaderStandard *> (aManager->EventReader()); if ((!tReaderESDChain) && (!tReaderESDChainKine) && (!tReaderAODChain) && (!tReaderStandard)) { printf("No AliFemto event reader created. Will not run femto analysis.\n"); return; } if (tReaderESDChain) SetFemtoReaderESD(tReaderESDChain); if (tReaderESDChainKine) SetFemtoReaderESDKine(tReaderESDChainKine); if (tReaderAODChain) SetFemtoReaderAOD(tReaderAODChain); if (tReaderStandard) SetFemtoReaderStandard(tReaderStandard); } <|endoftext|>
<commit_before>Bool_t ConfigKstarLeading( AliRsnMiniAnalysisTask *task, Bool_t isMC = kFALSE, Bool_t isPP = kFALSE, Double_t nSigmaPart1TPC = -1, Double_t nSigmaPart2TPC = -1, Double_t nSigmaPart1TOF = -1, Double_t nSigmaPart2TOF = -1 ) { // -- Values ------------------------------------------------------------------------------------ /* invariant mass */ Int_t imID = task->CreateValue(AliRsnMiniValue::kInvMass, kFALSE); /* transv. momentum */ Int_t ptID = task->CreateValue(AliRsnMiniValue::kPt, kFALSE); /* angel to leading */ Int_t alID = task->CreateValue(AliRsnMiniValue::kAngleLeading, kFALSE); /* pt of leading */ Int_t ptlID = task->CreateValue(AliRsnMiniValue::kLeadingPt, kFALSE); /* multiplicity */ Int_t multID = task->CreateValue(AliRsnMiniValue::kMult,kFALSE); /* delta eta */ Int_t detaID = task->CreateValue(AliRsnMiniValue::kDeltaEta, kFALSE); // set daughter cuts AliRsnCutSetDaughterParticle* cutSetPi; AliRsnCutSetDaughterParticle* cutSetK; AliRsnCutTrackQuality *fQualityTrackCutPi = new AliRsnCutTrackQuality("AliRsnCutTrackQuality"); fQualityTrackCutPi->SetDefaults2011(kTRUE, kTRUE); AliRsnCutTrackQuality *fQualityTrackCutK = new AliRsnCutTrackQuality("AliRsnCutTrackQuality"); fQualityTrackCutK->SetDefaults2011(kTRUE, kTRUE); cutSetPi=new AliRsnCutSetDaughterParticle(Form("cutPi%i_%2.1fsigma",AliRsnCutSetDaughterParticle::kTPCpidTOFveto3s,nSigmaPart2TPC),fQualityTrackCutPi,AliRsnCutSetDaughterParticle::kTPCpidTOFveto3s,AliPID::kPion,nSigmaPart2TPC); cutSetK=new AliRsnCutSetDaughterParticle(Form("cutK%i_%2.1fsigma",AliRsnCutSetDaughterParticle::kTPCpidTOFveto3s, nSigmaPart1TPC),fQualityTrackCutK,AliRsnCutSetDaughterParticle::kTPCpidTOFveto3s,AliPID::kKaon,nSigmaPart1TPC); //cutSetPi=new AliRsnCutSetDaughterParticle(Form("cutPi%i_%2.1fsigma",cutKaCandidate,nsigmaPi),trkQualityCut,cutKaCandidate,AliPID::kPion,nsigmaPi, nsigmaTOF); //cutSetK=new AliRsnCutSetDaughterParticle(Form("cutK%i_%2.1fsigma",cutKaCandidate, nsigmaK),trkQualityCut,cutKaCandidate,AliPID::kKaon,nsigmaK, nsigmaTOF); Int_t iCutPi = task->AddTrackCuts(cutSetPi); Int_t iCutK = task->AddTrackCuts(cutSetK); // Defining output objects const Int_t dims = 8; Int_t useIM[dims] = { 1, 1, 0, 0, 1, 1, isMC, isMC}; TString name[dims] = { "UnlikePM", "UnlikeMP", "MixingPM", "MixingMP", "LikePP", "LikeMM", "True", "Mother"}; TString comp[dims] = { "PAIR", "PAIR", "MIX", "MIX", "PAIR", "PAIR", "TRUE", "MOTHER"}; TString output[dims] = { "SPARSE", "SPARSE", "SPARSE", "SPARSE", "SPARSE", "SPARSE", "SPARSE", "SPARSE"}; Char_t charge1[dims] = { '+', '-', '+', '-', '+', '-', '+', '+'}; Char_t charge2[dims] = { '-', '+', '-', '+', '+', '-', '-', '-'}; Int_t pdgCode[dims] = { 313, 313, 313, 313, 313, 313, 313, 313}; Double_t motherMass[dims] = { 0.896, 0.896, 0.896, 0.896, 0.896, 0.896, 0.896, 0.896}; for (Int_t i = 0; i < dims; i++) { if (!useIM[i]) continue; AliRsnMiniOutput *out = task->CreateOutput(name[i].Data(), output[i].Data(), comp[i].Data()); out->SetCutID(0, iCutK); out->SetCutID(1, iCutPi); out->SetDaughter(0, AliRsnDaughter::kKaon); out->SetDaughter(1, AliRsnDaughter::kPion); out->SetCharge(0, charge1[i]); out->SetCharge(1, charge2[i]); out->SetMotherPDG(pdgCode[i]); out->SetMotherMass(motherMass[i]); out->AddAxis(imID, 100, 0.75, 1.25); out->AddAxis(ptID, 1, 2., 10.); if(!isPP ) out->AddAxis(multID,5,0.,50.); else out->AddAxis(multID, 10, 0., 100.); out->AddAxis(alID, 36, -0.5 * TMath::Pi(), 1.5 * TMath::Pi()); out->AddAxis(ptlID, 26, 4., 30.); out->AddAxis(detaID, 16, -1.6, 1.6); } return kTRUE; } <commit_msg>Update ConfigKstarLeading.C<commit_after>Bool_t ConfigKstarLeading( AliRsnMiniAnalysisTask *task, Bool_t isMC = kFALSE, Bool_t isPP = kFALSE, Double_t nSigmaPart1TPC = -1, Double_t nSigmaPart2TPC = -1, Double_t nSigmaPart1TOF = -1, Double_t nSigmaPart2TOF = -1 ) { // -- Values ------------------------------------------------------------------------------------ /* invariant mass */ Int_t imID = task->CreateValue(AliRsnMiniValue::kInvMass, kFALSE); /* transv. momentum */ Int_t ptID = task->CreateValue(AliRsnMiniValue::kPt, kFALSE); /* angel to leading */ Int_t alID = task->CreateValue(AliRsnMiniValue::kAngleLeading, kFALSE); /* pt of leading */ Int_t ptlID = task->CreateValue(AliRsnMiniValue::kLeadingPt, kFALSE); /* multiplicity */ Int_t multID = task->CreateValue(AliRsnMiniValue::kMult,kFALSE); /* delta eta */ Int_t detaID = task->CreateValue(AliRsnMiniValue::kDeltaEta, kFALSE); // set daughter cuts AliRsnCutSetDaughterParticle* cutSetPi; AliRsnCutSetDaughterParticle* cutSetK; AliRsnCutTrackQuality *fQualityTrackCutPi = new AliRsnCutTrackQuality("AliRsnCutTrackQuality"); fQualityTrackCutPi->SetDefaults2011(kTRUE, kTRUE); AliRsnCutTrackQuality *fQualityTrackCutK = new AliRsnCutTrackQuality("AliRsnCutTrackQuality"); fQualityTrackCutK->SetDefaults2011(kTRUE, kTRUE); cutSetPi=new AliRsnCutSetDaughterParticle(Form("cutPi%i_%2.1fsigma",AliRsnCutSetDaughterParticle::kTPCpidTOFveto3s,nSigmaPart2TPC),fQualityTrackCutPi,AliRsnCutSetDaughterParticle::kTPCpidTOFveto3s,AliPID::kPion,nSigmaPart2TPC); cutSetK=new AliRsnCutSetDaughterParticle(Form("cutK%i_%2.1fsigma",AliRsnCutSetDaughterParticle::kTPCpidTOFveto3s, nSigmaPart1TPC),fQualityTrackCutK,AliRsnCutSetDaughterParticle::kTPCpidTOFveto3s,AliPID::kKaon,nSigmaPart1TPC); //cutSetPi=new AliRsnCutSetDaughterParticle(Form("cutPi%i_%2.1fsigma",cutKaCandidate,nsigmaPi),trkQualityCut,cutKaCandidate,AliPID::kPion,nsigmaPi, nsigmaTOF); //cutSetK=new AliRsnCutSetDaughterParticle(Form("cutK%i_%2.1fsigma",cutKaCandidate, nsigmaK),trkQualityCut,cutKaCandidate,AliPID::kKaon,nsigmaK, nsigmaTOF); Int_t iCutPi = task->AddTrackCuts(cutSetPi); Int_t iCutK = task->AddTrackCuts(cutSetK); // Defining output objects const Int_t dims = 8; Int_t useIM[dims] = { 1, 1, 1, 1, 0, 0, isMC, isMC}; TString name[dims] = { "UnlikePM", "UnlikeMP", "MixingPM", "MixingMP", "LikePP", "LikeMM", "True", "Mother"}; TString comp[dims] = { "PAIR", "PAIR", "MIX", "MIX", "PAIR", "PAIR", "TRUE", "MOTHER"}; TString output[dims] = { "SPARSE", "SPARSE", "SPARSE", "SPARSE", "SPARSE", "SPARSE", "SPARSE", "SPARSE"}; Char_t charge1[dims] = { '+', '-', '+', '-', '+', '-', '+', '+'}; Char_t charge2[dims] = { '-', '+', '-', '+', '+', '-', '-', '-'}; Int_t pdgCode[dims] = { 313, 313, 313, 313, 313, 313, 313, 313}; Double_t motherMass[dims] = { 0.896, 0.896, 0.896, 0.896, 0.896, 0.896, 0.896, 0.896}; for (Int_t i = 0; i < dims; i++) { if (!useIM[i]) continue; AliRsnMiniOutput *out = task->CreateOutput(name[i].Data(), output[i].Data(), comp[i].Data()); out->SetCutID(0, iCutK); out->SetCutID(1, iCutPi); out->SetDaughter(0, AliRsnDaughter::kKaon); out->SetDaughter(1, AliRsnDaughter::kPion); out->SetCharge(0, charge1[i]); out->SetCharge(1, charge2[i]); out->SetMotherPDG(pdgCode[i]); out->SetMotherMass(motherMass[i]); out->AddAxis(imID, 85, 0.77, 1.20); out->AddAxis(ptID, 4, 2., 10.); if(!isPP ) out->AddAxis(multID,9,0.,90.); else out->AddAxis(multID, 10, 0., 100.); out->AddAxis(alID, 36, -0.5 * TMath::Pi(), 1.5 * TMath::Pi()); out->AddAxis(ptlID, 26, 4., 30.); // out->AddAxis(detaID, 16, -1.6, 1.6); } return kTRUE; } <|endoftext|>
<commit_before>#include "S_Credits.h" #include "j1Window.h" #include "j1Render.h" S_Credits::S_Credits() { scene_str = "Credits"; } S_Credits::~S_Credits() { } bool S_Credits::Awake(pugi::xml_node& conf) { CreditsLogo_Rect = { 0,0,550,360 }; CreditsLogo_Y_Pos = App->win->GetWindowHHalf() - (int)(CreditsLogo_Rect.h * 0.5f) - 50; int X_pos = 31; CreditsLabel1 = App->gui->CreateButton(iPoint(X_pos, 31), &std::string("Lead - "), ButtonType::idle_only, &label_title_rec, false); CreditsLabel1->SetFont(App->font->Triforce48); ((Gui*)CreditsLabel1)->SetListener(this); CreditsLabel1->SetVisible(false); CreditsLabel2 = App->gui->CreateButton(iPoint(X_pos, 125), &std::string("Management - "), ButtonType::idle_only, &label_title_rec, false); CreditsLabel2->SetFont(App->font->Triforce48); ((Gui*)CreditsLabel2)->SetListener(this); CreditsLabel2->SetVisible(false); CreditsLabel3 = App->gui->CreateButton(iPoint(X_pos, 219), &std::string("Art - "), ButtonType::idle_only, &label_title_rec, false); CreditsLabel3->SetFont(App->font->Triforce48); ((Gui*)CreditsLabel3)->SetListener(this); CreditsLabel3->SetVisible(false); CreditsLabel4 = App->gui->CreateButton(iPoint(X_pos, 313), &std::string("Code - "), ButtonType::idle_only, &label_title_rec, false); CreditsLabel4->SetFont(App->font->Triforce48); ((Gui*)CreditsLabel4)->SetListener(this); CreditsLabel4->SetVisible(false); CreditsLabel5 = App->gui->CreateButton(iPoint(X_pos, 407), &std::string("UI - "), ButtonType::idle_only, &label_title_rec, false); CreditsLabel5->SetFont(App->font->Triforce48); ((Gui*)CreditsLabel5)->SetListener(this); CreditsLabel5->SetVisible(false); CreditsLabel6 = App->gui->CreateButton(iPoint(X_pos, 501), &std::string("QA - "), ButtonType::idle_only, &label_title_rec, false); CreditsLabel6->SetFont(App->font->Triforce48); ((Gui*)CreditsLabel6)->SetListener(this); CreditsLabel6->SetVisible(false); CreditsLabel7 = App->gui->CreateButton(iPoint(X_pos, 595), &std::string("Game Design - "), ButtonType::idle_only, &label_title_rec, false); CreditsLabel7->SetFont(App->font->Triforce48); ((Gui*)CreditsLabel7)->SetListener(this); CreditsLabel7->SetVisible(false); back = App->gui->CreateButton(iPoint(920, 600), &std::string(conf.child("back").attribute("value").as_string("Back")), ButtonType::idle_hover_pressed, &idle_button_rect, &hover_button_rect, &pressed_button_rect, false); back->SetFont(App->font->Sherwood20); ((Gui*)back)->SetListener(this); back->SetVisible(false); back->Focusable(true); buttons.push_back(back); return true; }; bool S_Credits::Start() { CreditsLogo = App->gui->CreateImage(iPoint( 675, CreditsLogo_Y_Pos), &CreditsLogo_Rect, false, AddGuiTo::none); CreditsLabel1->SetVisible(true); CreditsLabel2->SetVisible(true); CreditsLabel3->SetVisible(true); CreditsLabel4->SetVisible(true); CreditsLabel5->SetVisible(true); CreditsLabel6->SetVisible(true); CreditsLabel7->SetVisible(true); back->SetVisible(true); App->gui->SetFocus(buttons.front()); return true; } bool S_Credits::Update() { CreditsLogo->DrawWithAlternativeAtlas(App->scene->GetCredits_Logo_Atlas()); MenuInput(&buttons); return true; } bool S_Credits::Clean() { delete CreditsLogo; CreditsLabel1->SetVisible(false); CreditsLabel2->SetVisible(false); CreditsLabel3->SetVisible(false); CreditsLabel4->SetVisible(false); CreditsLabel5->SetVisible(false); CreditsLabel6->SetVisible(false); CreditsLabel7->SetVisible(false); back->SetVisible(false); return true; } void S_Credits::OnGui(Gui* ui, GuiEvent event) { if ((ui == (Gui*)back) && (event == GuiEvent::mouse_lclk_down)) { App->scene->Show(Scene_ID::mainmenu); } } bool S_Credits::Save(pugi::xml_node& node) const { return true; } bool S_Credits::Load(pugi::xml_node& node) { return true; }<commit_msg>Credits names<commit_after>#include "S_Credits.h" #include "j1Window.h" #include "j1Render.h" S_Credits::S_Credits() { scene_str = "Credits"; } S_Credits::~S_Credits() { } bool S_Credits::Awake(pugi::xml_node& conf) { CreditsLogo_Rect = { 0,0,550,360 }; CreditsLogo_Y_Pos = App->win->GetWindowHHalf() - (int)(CreditsLogo_Rect.h * 0.5f) - 50; int X_pos = 31; CreditsLabel1 = App->gui->CreateButton(iPoint(X_pos, 31), &std::string("Lead - Nico"), ButtonType::idle_only, &label_title_rec, false); CreditsLabel1->SetFont(App->font->Triforce48); ((Gui*)CreditsLabel1)->SetListener(this); CreditsLabel1->SetVisible(false); CreditsLabel2 = App->gui->CreateButton(iPoint(X_pos, 125), &std::string("Management - Guillermo"), ButtonType::idle_only, &label_title_rec, false); CreditsLabel2->SetFont(App->font->Triforce48); ((Gui*)CreditsLabel2)->SetListener(this); CreditsLabel2->SetVisible(false); CreditsLabel3 = App->gui->CreateButton(iPoint(X_pos, 219), &std::string("Art - Daniel"), ButtonType::idle_only, &label_title_rec, false); CreditsLabel3->SetFont(App->font->Triforce48); ((Gui*)CreditsLabel3)->SetListener(this); CreditsLabel3->SetVisible(false); CreditsLabel4 = App->gui->CreateButton(iPoint(X_pos, 313), &std::string("Code - Miquel"), ButtonType::idle_only, &label_title_rec, false); CreditsLabel4->SetFont(App->font->Triforce48); ((Gui*)CreditsLabel4)->SetListener(this); CreditsLabel4->SetVisible(false); CreditsLabel5 = App->gui->CreateButton(iPoint(X_pos, 407), &std::string("UI - Xavier"), ButtonType::idle_only, &label_title_rec, false); CreditsLabel5->SetFont(App->font->Triforce48); ((Gui*)CreditsLabel5)->SetListener(this); CreditsLabel5->SetVisible(false); CreditsLabel6 = App->gui->CreateButton(iPoint(X_pos, 501), &std::string("QA - Adrian"), ButtonType::idle_only, &label_title_rec, false); CreditsLabel6->SetFont(App->font->Triforce48); ((Gui*)CreditsLabel6)->SetListener(this); CreditsLabel6->SetVisible(false); CreditsLabel7 = App->gui->CreateButton(iPoint(X_pos, 595), &std::string("Design - Javier"), ButtonType::idle_only, &label_title_rec, false); CreditsLabel7->SetFont(App->font->Triforce48); ((Gui*)CreditsLabel7)->SetListener(this); CreditsLabel7->SetVisible(false); back = App->gui->CreateButton(iPoint(920, 600), &std::string(conf.child("back").attribute("value").as_string("Back")), ButtonType::idle_hover_pressed, &idle_button_rect, &hover_button_rect, &pressed_button_rect, false); back->SetFont(App->font->Sherwood20); ((Gui*)back)->SetListener(this); back->SetVisible(false); back->Focusable(true); buttons.push_back(back); return true; }; bool S_Credits::Start() { CreditsLogo = App->gui->CreateImage(iPoint( 675, CreditsLogo_Y_Pos), &CreditsLogo_Rect, false, AddGuiTo::none); CreditsLabel1->SetVisible(true); CreditsLabel2->SetVisible(true); CreditsLabel3->SetVisible(true); CreditsLabel4->SetVisible(true); CreditsLabel5->SetVisible(true); CreditsLabel6->SetVisible(true); CreditsLabel7->SetVisible(true); back->SetVisible(true); App->gui->SetFocus(buttons.front()); return true; } bool S_Credits::Update() { CreditsLogo->DrawWithAlternativeAtlas(App->scene->GetCredits_Logo_Atlas()); MenuInput(&buttons); return true; } bool S_Credits::Clean() { delete CreditsLogo; CreditsLabel1->SetVisible(false); CreditsLabel2->SetVisible(false); CreditsLabel3->SetVisible(false); CreditsLabel4->SetVisible(false); CreditsLabel5->SetVisible(false); CreditsLabel6->SetVisible(false); CreditsLabel7->SetVisible(false); back->SetVisible(false); return true; } void S_Credits::OnGui(Gui* ui, GuiEvent event) { if ((ui == (Gui*)back) && (event == GuiEvent::mouse_lclk_down)) { App->scene->Show(Scene_ID::mainmenu); } } bool S_Credits::Save(pugi::xml_node& node) const { return true; } bool S_Credits::Load(pugi::xml_node& node) { return true; }<|endoftext|>
<commit_before>/* * Copyright (c) 2020 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 "call/version.h" namespace webrtc { // The timestamp is always in UTC. const char* const kSourceTimestamp = "WebRTC source stamp 2021-01-06T04:02:29"; void LoadWebRTCVersionInRegister() { // Using volatile to instruct the compiler to not optimize `p` away even // if it looks unused. const char* volatile p = kSourceTimestamp; static_cast<void>(p); } } // namespace webrtc <commit_msg>Update WebRTC code version (2021-01-07T04:03:27).<commit_after>/* * Copyright (c) 2020 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 "call/version.h" namespace webrtc { // The timestamp is always in UTC. const char* const kSourceTimestamp = "WebRTC source stamp 2021-01-07T04:03:27"; void LoadWebRTCVersionInRegister() { // Using volatile to instruct the compiler to not optimize `p` away even // if it looks unused. const char* volatile p = kSourceTimestamp; static_cast<void>(p); } } // namespace webrtc <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_META_HPP #define STAN_MATH_PRIM_META_HPP #include <stan/math/prim/arr/meta/get.hpp> #include <stan/math/prim/arr/meta/index_type.hpp> #include <stan/math/prim/arr/meta/is_vector.hpp> #include <stan/math/prim/arr/meta/length.hpp> #include <stan/math/prim/mat/meta/as_array_or_scalar.hpp> #include <stan/math/prim/mat/meta/as_column_vector_or_scalar.hpp> #include <stan/math/prim/mat/meta/as_scalar.hpp> #include <stan/math/prim/mat/meta/broadcast_array.hpp> #include <stan/math/prim/mat/meta/get.hpp> #include <stan/math/prim/mat/meta/index_type.hpp> #include <stan/math/prim/mat/meta/is_constant_struct.hpp> #include <stan/math/prim/mat/meta/is_vector.hpp> #include <stan/math/prim/mat/meta/is_vector_like.hpp> #include <stan/math/prim/mat/meta/length.hpp> #include <stan/math/prim/mat/meta/length_mvt.hpp> #include <stan/math/prim/mat/meta/operands_and_partials.hpp> #include <stan/math/prim/mat/meta/scalar_type.hpp> #include <stan/math/prim/mat/meta/seq_view.hpp> #include <stan/math/prim/mat/meta/value_type.hpp> #include <stan/math/prim/mat/meta/vector_seq_view.hpp> #include <stan/math/prim/arr/meta/as_scalar.hpp> #include <stan/math/prim/arr/meta/contains_std_vector.hpp> #include <stan/math/prim/arr/meta/is_constant_struct.hpp> #include <stan/math/prim/arr/meta/scalar_type.hpp> #include <stan/math/prim/arr/meta/value_type.hpp> #include <stan/math/prim/arr/meta/VectorBuilderHelper.hpp> #include <stan/math/prim/scal/meta/ad_promotable.hpp> #include <stan/math/prim/scal/meta/as_array_or_scalar.hpp> #include <stan/math/prim/scal/meta/as_column_vector_or_scalar.hpp> #include <stan/math/prim/scal/meta/as_scalar.hpp> #include <stan/math/prim/scal/meta/child_type.hpp> #include <stan/math/prim/scal/meta/contains_fvar.hpp> #include <stan/math/prim/scal/meta/contains_nonconstant_struct.hpp> #include <stan/math/prim/scal/meta/contains_std_vector.hpp> #include <stan/math/prim/scal/meta/contains_vector.hpp> #include <stan/math/prim/scal/meta/error_index.hpp> #include <stan/math/prim/scal/meta/get.hpp> #include <stan/math/prim/scal/meta/include_summand.hpp> #include <stan/math/prim/scal/meta/index_type.hpp> #include <stan/math/prim/scal/meta/is_constant.hpp> #include <stan/math/prim/scal/meta/is_constant_struct.hpp> #include <stan/math/prim/scal/meta/is_nonconstant_struct.hpp> #include <stan/math/prim/scal/meta/is_fvar.hpp> #include <stan/math/prim/scal/meta/is_var.hpp> #include <stan/math/prim/scal/meta/is_var_or_arithmetic.hpp> #include <stan/math/prim/scal/meta/is_vector.hpp> #include <stan/math/prim/scal/meta/is_vector_like.hpp> #include <stan/math/prim/scal/meta/length.hpp> #include <stan/math/prim/scal/meta/length_mvt.hpp> #include <stan/math/prim/scal/meta/likely.hpp> #include <stan/math/prim/scal/meta/max_size.hpp> #include <stan/math/prim/scal/meta/max_size_mvt.hpp> #include <stan/math/prim/scal/meta/operands_and_partials.hpp> #include <stan/math/prim/scal/meta/partials_return_type.hpp> #include <stan/math/prim/scal/meta/partials_type.hpp> #include <stan/math/prim/scal/meta/return_type.hpp> #include <stan/math/prim/scal/meta/scalar_seq_view.hpp> #include <stan/math/prim/scal/meta/scalar_type.hpp> #include <stan/math/prim/scal/meta/scalar_type_pre.hpp> #include <stan/math/prim/scal/meta/size_of.hpp> #include <stan/math/prim/scal/meta/value_type.hpp> #include <stan/math/prim/scal/meta/StdVectorBuilder.hpp> #include <stan/math/prim/scal/meta/VectorBuilder.hpp> #endif <commit_msg>include append return type<commit_after>#ifndef STAN_MATH_PRIM_META_HPP #define STAN_MATH_PRIM_META_HPP #include <stan/math/prim/arr/meta/get.hpp> #include <stan/math/prim/arr/meta/index_type.hpp> #include <stan/math/prim/arr/meta/is_vector.hpp> #include <stan/math/prim/arr/meta/length.hpp> #include <stan/math/prim/mat/meta/append_return_type.hpp> #include <stan/math/prim/mat/meta/as_array_or_scalar.hpp> #include <stan/math/prim/mat/meta/as_column_vector_or_scalar.hpp> #include <stan/math/prim/mat/meta/as_scalar.hpp> #include <stan/math/prim/mat/meta/broadcast_array.hpp> #include <stan/math/prim/mat/meta/get.hpp> #include <stan/math/prim/mat/meta/index_type.hpp> #include <stan/math/prim/mat/meta/is_constant_struct.hpp> #include <stan/math/prim/mat/meta/is_vector.hpp> #include <stan/math/prim/mat/meta/is_vector_like.hpp> #include <stan/math/prim/mat/meta/length.hpp> #include <stan/math/prim/mat/meta/length_mvt.hpp> #include <stan/math/prim/mat/meta/operands_and_partials.hpp> #include <stan/math/prim/mat/meta/scalar_type.hpp> #include <stan/math/prim/mat/meta/seq_view.hpp> #include <stan/math/prim/mat/meta/value_type.hpp> #include <stan/math/prim/mat/meta/vector_seq_view.hpp> #include <stan/math/prim/arr/meta/as_scalar.hpp> #include <stan/math/prim/arr/meta/contains_std_vector.hpp> #include <stan/math/prim/arr/meta/is_constant_struct.hpp> #include <stan/math/prim/arr/meta/scalar_type.hpp> #include <stan/math/prim/arr/meta/value_type.hpp> #include <stan/math/prim/arr/meta/VectorBuilderHelper.hpp> #include <stan/math/prim/scal/meta/ad_promotable.hpp> #include <stan/math/prim/scal/meta/as_array_or_scalar.hpp> #include <stan/math/prim/scal/meta/as_column_vector_or_scalar.hpp> #include <stan/math/prim/scal/meta/as_scalar.hpp> #include <stan/math/prim/scal/meta/child_type.hpp> #include <stan/math/prim/scal/meta/contains_fvar.hpp> #include <stan/math/prim/scal/meta/contains_nonconstant_struct.hpp> #include <stan/math/prim/scal/meta/contains_std_vector.hpp> #include <stan/math/prim/scal/meta/contains_vector.hpp> #include <stan/math/prim/scal/meta/error_index.hpp> #include <stan/math/prim/scal/meta/get.hpp> #include <stan/math/prim/scal/meta/include_summand.hpp> #include <stan/math/prim/scal/meta/index_type.hpp> #include <stan/math/prim/scal/meta/is_constant.hpp> #include <stan/math/prim/scal/meta/is_constant_struct.hpp> #include <stan/math/prim/scal/meta/is_nonconstant_struct.hpp> #include <stan/math/prim/scal/meta/is_fvar.hpp> #include <stan/math/prim/scal/meta/is_var.hpp> #include <stan/math/prim/scal/meta/is_var_or_arithmetic.hpp> #include <stan/math/prim/scal/meta/is_vector.hpp> #include <stan/math/prim/scal/meta/is_vector_like.hpp> #include <stan/math/prim/scal/meta/length.hpp> #include <stan/math/prim/scal/meta/length_mvt.hpp> #include <stan/math/prim/scal/meta/likely.hpp> #include <stan/math/prim/scal/meta/max_size.hpp> #include <stan/math/prim/scal/meta/max_size_mvt.hpp> #include <stan/math/prim/scal/meta/operands_and_partials.hpp> #include <stan/math/prim/scal/meta/partials_return_type.hpp> #include <stan/math/prim/scal/meta/partials_type.hpp> #include <stan/math/prim/scal/meta/return_type.hpp> #include <stan/math/prim/scal/meta/scalar_seq_view.hpp> #include <stan/math/prim/scal/meta/scalar_type.hpp> #include <stan/math/prim/scal/meta/scalar_type_pre.hpp> #include <stan/math/prim/scal/meta/size_of.hpp> #include <stan/math/prim/scal/meta/value_type.hpp> #include <stan/math/prim/scal/meta/StdVectorBuilder.hpp> #include <stan/math/prim/scal/meta/VectorBuilder.hpp> #endif <|endoftext|>
<commit_before>/* * Copyright 2016-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/io/async/Request.h> #include <folly/tracing/StaticTracepoint.h> #include <glog/logging.h> #include <folly/MapUtil.h> #include <folly/SingletonThreadLocal.h> namespace folly { void RequestData::DestructPtr::operator()(RequestData* ptr) { if (ptr) { auto keepAliveCounter = ptr->keepAliveCounter_.fetch_sub(1, std::memory_order_acq_rel); // Note: this is the value before decrement, hence == 1 check DCHECK(keepAliveCounter > 0); if (keepAliveCounter == 1) { delete ptr; } } } /* static */ RequestData::SharedPtr RequestData::constructPtr( RequestData* ptr) { if (ptr) { auto keepAliveCounter = ptr->keepAliveCounter_.fetch_add(1, std::memory_order_relaxed); DCHECK(keepAliveCounter >= 0); } return SharedPtr(ptr); } bool RequestContext::doSetContextData( const std::string& val, std::unique_ptr<RequestData>& data, DoSetBehaviour behaviour) { auto ulock = state_.ulock(); bool conflict = false; auto it = ulock->requestData_.find(val); if (it != ulock->requestData_.end()) { if (behaviour == DoSetBehaviour::SET_IF_ABSENT) { return false; } else if (behaviour == DoSetBehaviour::SET) { LOG_FIRST_N(WARNING, 1) << "Calling RequestContext::setContextData for " << val << " but it is already set"; } conflict = true; } auto wlock = ulock.moveFromUpgradeToWrite(); if (conflict) { if (it->second) { if (it->second->hasCallback()) { it->second->onUnset(); wlock->callbackData_.erase(it->second.get()); } it->second.reset(nullptr); } if (behaviour == DoSetBehaviour::SET) { return true; } } if (data && data->hasCallback()) { wlock->callbackData_.insert(data.get()); data->onSet(); } wlock->requestData_[val] = RequestData::constructPtr(data.release()); return true; } void RequestContext::setContextData( const std::string& val, std::unique_ptr<RequestData> data) { doSetContextData(val, data, DoSetBehaviour::SET); } bool RequestContext::setContextDataIfAbsent( const std::string& val, std::unique_ptr<RequestData> data) { return doSetContextData(val, data, DoSetBehaviour::SET_IF_ABSENT); } void RequestContext::overwriteContextData( const std::string& val, std::unique_ptr<RequestData> data) { doSetContextData(val, data, DoSetBehaviour::OVERWRITE); } bool RequestContext::hasContextData(const std::string& val) const { return state_.rlock()->requestData_.count(val); } RequestData* RequestContext::getContextData(const std::string& val) { const RequestData::SharedPtr dflt{nullptr}; return get_ref_default(state_.rlock()->requestData_, val, dflt).get(); } const RequestData* RequestContext::getContextData( const std::string& val) const { const RequestData::SharedPtr dflt{nullptr}; return get_ref_default(state_.rlock()->requestData_, val, dflt).get(); } void RequestContext::onSet() { auto rlock = state_.rlock(); for (const auto& data : rlock->callbackData_) { data->onSet(); } } void RequestContext::onUnset() { auto rlock = state_.rlock(); for (const auto& data : rlock->callbackData_) { data->onUnset(); } } void RequestContext::clearContextData(const std::string& val) { RequestData::SharedPtr requestData; // Delete the RequestData after giving up the wlock just in case one of the // RequestData destructors will try to grab the lock again. { auto ulock = state_.ulock(); auto it = ulock->requestData_.find(val); if (it == ulock->requestData_.end()) { return; } auto wlock = ulock.moveFromUpgradeToWrite(); if (it->second && it->second->hasCallback()) { it->second->onUnset(); wlock->callbackData_.erase(it->second.get()); } requestData = std::move(it->second); wlock->requestData_.erase(it); } } std::shared_ptr<RequestContext> RequestContext::setContext( std::shared_ptr<RequestContext> ctx) { auto& curCtx = getStaticContext(); if (ctx != curCtx) { FOLLY_SDT(folly, request_context_switch_before, curCtx.get(), ctx.get()); if (curCtx) { curCtx->onUnset(); } std::swap(ctx, curCtx); if (curCtx) { curCtx->onSet(); } } return ctx; } std::shared_ptr<RequestContext>& RequestContext::getStaticContext() { using SingletonT = SingletonThreadLocal<std::shared_ptr<RequestContext>>; return SingletonT::get(); } /* static */ std::shared_ptr<RequestContext> RequestContext::setShallowCopyContext() { auto* parent = get(); auto child = std::make_shared<RequestContext>(); { auto parentLock = parent->state_.rlock(); auto childLock = child->state_.wlock(); childLock->callbackData_ = parentLock->callbackData_; for (const auto& entry : parentLock->requestData_) { childLock->requestData_[entry.first] = RequestData::constructPtr(entry.second.get()); } } // Do not use setContext to avoid global set/unset std::swap(child, getStaticContext()); return child; } /* static */ void RequestContext::unsetShallowCopyContext( std::shared_ptr<RequestContext> ctx) { // Do not use setContext to avoid set/unset std::swap(ctx, getStaticContext()); // For readability auto child = std::move(ctx); // Handle the case where parent is actually default context auto* parent = get(); // Call set/unset for all request data that differs { auto parentLock = parent->state_.rlock(); auto childLock = child->state_.rlock(); auto piter = parentLock->callbackData_.begin(); auto pend = parentLock->callbackData_.end(); auto citer = childLock->callbackData_.begin(); auto cend = childLock->callbackData_.end(); while (piter != pend || citer != cend) { if (piter == pend || *citer < *piter) { (*citer)->onUnset(); ++citer; } else if (citer == cend || *piter < *citer) { (*piter)->onSet(); ++piter; } else { DCHECK(*piter == *citer); ++piter; ++citer; } } } } RequestContext* RequestContext::get() { auto& context = getStaticContext(); if (!context) { static RequestContext defaultContext; return std::addressof(defaultContext); } return context.get(); } } // namespace folly <commit_msg>Fix shallow copy segfault<commit_after>/* * Copyright 2016-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/io/async/Request.h> #include <folly/tracing/StaticTracepoint.h> #include <glog/logging.h> #include <folly/MapUtil.h> #include <folly/SingletonThreadLocal.h> namespace folly { void RequestData::DestructPtr::operator()(RequestData* ptr) { if (ptr) { auto keepAliveCounter = ptr->keepAliveCounter_.fetch_sub(1, std::memory_order_acq_rel); // Note: this is the value before decrement, hence == 1 check DCHECK(keepAliveCounter > 0); if (keepAliveCounter == 1) { delete ptr; } } } /* static */ RequestData::SharedPtr RequestData::constructPtr( RequestData* ptr) { if (ptr) { auto keepAliveCounter = ptr->keepAliveCounter_.fetch_add(1, std::memory_order_relaxed); DCHECK(keepAliveCounter >= 0); } return SharedPtr(ptr); } bool RequestContext::doSetContextData( const std::string& val, std::unique_ptr<RequestData>& data, DoSetBehaviour behaviour) { auto ulock = state_.ulock(); bool conflict = false; auto it = ulock->requestData_.find(val); if (it != ulock->requestData_.end()) { if (behaviour == DoSetBehaviour::SET_IF_ABSENT) { return false; } else if (behaviour == DoSetBehaviour::SET) { LOG_FIRST_N(WARNING, 1) << "Calling RequestContext::setContextData for " << val << " but it is already set"; } conflict = true; } auto wlock = ulock.moveFromUpgradeToWrite(); if (conflict) { if (it->second) { if (it->second->hasCallback()) { it->second->onUnset(); wlock->callbackData_.erase(it->second.get()); } it->second.reset(nullptr); } if (behaviour == DoSetBehaviour::SET) { return true; } } if (data && data->hasCallback()) { wlock->callbackData_.insert(data.get()); data->onSet(); } wlock->requestData_[val] = RequestData::constructPtr(data.release()); return true; } void RequestContext::setContextData( const std::string& val, std::unique_ptr<RequestData> data) { doSetContextData(val, data, DoSetBehaviour::SET); } bool RequestContext::setContextDataIfAbsent( const std::string& val, std::unique_ptr<RequestData> data) { return doSetContextData(val, data, DoSetBehaviour::SET_IF_ABSENT); } void RequestContext::overwriteContextData( const std::string& val, std::unique_ptr<RequestData> data) { doSetContextData(val, data, DoSetBehaviour::OVERWRITE); } bool RequestContext::hasContextData(const std::string& val) const { return state_.rlock()->requestData_.count(val); } RequestData* RequestContext::getContextData(const std::string& val) { const RequestData::SharedPtr dflt{nullptr}; return get_ref_default(state_.rlock()->requestData_, val, dflt).get(); } const RequestData* RequestContext::getContextData( const std::string& val) const { const RequestData::SharedPtr dflt{nullptr}; return get_ref_default(state_.rlock()->requestData_, val, dflt).get(); } void RequestContext::onSet() { auto rlock = state_.rlock(); for (const auto& data : rlock->callbackData_) { data->onSet(); } } void RequestContext::onUnset() { auto rlock = state_.rlock(); for (const auto& data : rlock->callbackData_) { data->onUnset(); } } void RequestContext::clearContextData(const std::string& val) { RequestData::SharedPtr requestData; // Delete the RequestData after giving up the wlock just in case one of the // RequestData destructors will try to grab the lock again. { auto ulock = state_.ulock(); auto it = ulock->requestData_.find(val); if (it == ulock->requestData_.end()) { return; } auto wlock = ulock.moveFromUpgradeToWrite(); if (it->second && it->second->hasCallback()) { it->second->onUnset(); wlock->callbackData_.erase(it->second.get()); } requestData = std::move(it->second); wlock->requestData_.erase(it); } } std::shared_ptr<RequestContext> RequestContext::setContext( std::shared_ptr<RequestContext> ctx) { auto& curCtx = getStaticContext(); if (ctx != curCtx) { FOLLY_SDT(folly, request_context_switch_before, curCtx.get(), ctx.get()); if (curCtx) { curCtx->onUnset(); } std::swap(ctx, curCtx); if (curCtx) { curCtx->onSet(); } } return ctx; } std::shared_ptr<RequestContext>& RequestContext::getStaticContext() { using SingletonT = SingletonThreadLocal<std::shared_ptr<RequestContext>>; return SingletonT::get(); } /* static */ std::shared_ptr<RequestContext> RequestContext::setShallowCopyContext() { auto* parent = get(); auto child = std::make_shared<RequestContext>(); { auto parentLock = parent->state_.rlock(); auto childLock = child->state_.wlock(); childLock->callbackData_ = parentLock->callbackData_; for (const auto& entry : parentLock->requestData_) { childLock->requestData_[entry.first] = RequestData::constructPtr(entry.second.get()); } } // Do not use setContext to avoid global set/unset std::swap(child, getStaticContext()); return child; } /* static */ void RequestContext::unsetShallowCopyContext( std::shared_ptr<RequestContext> ctx) { // Do not use setContext to avoid set/unset std::swap(ctx, getStaticContext()); // For readability auto child = std::move(ctx); // Handle the case where parent is actually default context auto* parent = get(); // Call set/unset for all request data that differs { auto parentLock = parent->state_.rlock(); auto childLock = child->state_.rlock(); auto piter = parentLock->callbackData_.begin(); auto pend = parentLock->callbackData_.end(); auto citer = childLock->callbackData_.begin(); auto cend = childLock->callbackData_.end(); while (true) { if (piter == pend) { if (citer == cend) { break; } (*citer)->onUnset(); ++citer; } else if (citer == cend || *piter < *citer) { (*piter)->onSet(); ++piter; } else if (*citer < *piter) { (*citer)->onUnset(); ++citer; } else { DCHECK(*piter == *citer); ++piter; ++citer; } } } } RequestContext* RequestContext::get() { auto& context = getStaticContext(); if (!context) { static RequestContext defaultContext; return std::addressof(defaultContext); } return context.get(); } } // namespace folly <|endoftext|>
<commit_before>#include <QtCore/QFile> #include <QtCore/QStringList> #include <QtCore/QTextStream> #include <QtGui/QVector2D> #include "math.hpp" qreal Polynom::operator()(qreal x, qreal y) const { qreal result = 0; for (ConstIterator i = begin(); i != end(); ++i) { result += qPow(x, i->xPow) * qPow(y, i->yPow) * i->c; } return result; } qreal Polynom::operator()(QPointF point) const { return operator()(point.x(), point.y()); } QPointF PolynomSystem::getNextValue(QPointF point, qreal eps, bool useRungeKutta) const { QVector2D diff(first(point), second(point)); if (useRungeKutta) { qreal x = point.x(), y = point.y(); qreal first25 = first (x + eps * first(point) / 2, y + eps * second(point) / 2); qreal second25 = second(x + eps * first(point) / 2, y + eps * second(point) / 2); qreal first50 = first (x + eps * first25 / 2, y + eps * second25 / 2); qreal second50 = second(x + eps * first25 / 2, y + eps * second25 / 2); qreal first75 = first (x + eps * first50, y + eps * second50); qreal second75 = second(x + eps * first50, y + eps * second50); diff.setX((first (point) + 2 * first25 + 2 * first50 + first75 ) / 6); diff.setY((second(point) + 2 * second25 + 2 * second50 + second75) / 6); } if (diff.length() > 1) { diff /= diff.length(); } diff *= eps; return point + diff.toPointF(); } qreal PolynomSystem::poincareFunction(qreal p, qreal eps) const { QPointF point(p, 0); quint32 step = 0; while (step < 10 || point.x() < 0 || qAbs(point.y()) > eps) { point = getNextValue(point, eps); if (step > 1000) { return 0; } ++step; } return point.x(); } qreal PolynomSystem::findPoincareStaticPoint(qreal a, qreal b, qreal eps) const { qreal pdiffa = poincareFunction(a, eps) - a; qreal pdiffb = poincareFunction(b, eps) - b; if (pdiffa * pdiffb > 0) { return 0; } while (qAbs(b - a) > eps) { pdiffa = poincareFunction(a, eps) - a; pdiffb = poincareFunction(b, eps) - b; a = b - (b - a) * pdiffb / (pdiffb - pdiffa); pdiffa = poincareFunction(a, eps) - a; b = a - (a - b) * pdiffa / (pdiffa - pdiffb); } return b; } qreal PolynomSystem::getPeriod(qreal staticPoint, qreal eps) const { QPointF point(staticPoint, 0); quint32 step = 0; qreal diff = 0; while (step < 5 || qAbs(diff) > eps / 2) { point = getNextValue(point, eps, true); diff = qPow(point.x() - staticPoint, 2) + qPow(point.y(), 2); ++step; } return step * eps; } void fillPolynom(QString line, Polynom &polynom, qreal param) { QStringList parts = line.split(" "); QStringList subParts; Monom m; polynom.clear(); for (int i = 0; i < parts.size(); ++i) { subParts = parts.at(i).split(' '); m.xPow = subParts.at(1).toInt(); m.yPow = subParts.at(2).toInt(); m.c = subParts.at(0) == "c" ? param : subParts.at(0).toDouble(); polynom.append(m); } } ComplexPair PolynomSystem::getEigenValues() const { ComplexPair result; qreal a = 0, b = 0, c = 0, d = 0; Polynom::ConstIterator i; for (i = first.begin(); i != first.end(); ++i) { if (i->xPow == 1 && i->yPow == 0) { a = i->c; } else if (i->xPow == 0 && i->yPow == 1) { b = i->c; } } for (i = second.begin(); i != second.end(); ++i) { if (i->xPow == 1 && i->yPow == 0) { c = i->c; } else if (i->xPow == 0 && i->yPow == 1) { d = i->c; } } qreal determinant = (a - d) * (a - d) + 4 * b * c; Complex detSqrt = std::sqrt(Complex(determinant, 0)); result.first = (Complex(a + d, 0) + detSqrt) * Complex(.5, 0); result.second = (Complex(a + d, 0) - detSqrt) * Complex(.5, 0); return result; } PointType PolynomSystem::getPointType() const { ComplexPair eigenValues = getEigenValues(); Complex v1 = eigenValues.first, v2 = eigenValues.second; if (qFuzzyIsNull(v1.real()) && qFuzzyIsNull(v2.real())) { return PointCenter; } else if (qFuzzyIsNull(v1.imag()) && qFuzzyIsNull(v2.imag())) { if (qFuzzyCompare(v1.real(), v2.real())) { if (v1.real() > 0) { return PointKnotSingularUnstable; } else { return PointKnotSingularStable; } } else if (v1.real() > 0 && v2.real() > 0) { return PointKnotUnstable; } else if (v1.real() < 0 && v2.real() < 0) { return PointKnotStable; } else { return PointSaddle; } } else if (v1.real() > 0) { return PointFocusUnstable; } else { return PointFocusStable; } } void fillSystem(QString fileName, PolynomSystem &system, qreal param) { QFile inputFile(fileName); inputFile.open(QFile::ReadOnly); QTextStream input(&inputFile); fillPolynom(input.readLine(), system.first, param); fillPolynom(input.readLine(), system.second, param); inputFile.close(); } <commit_msg>Use 50 / eps in poincareFunction()<commit_after>#include <QtCore/QFile> #include <QtCore/QStringList> #include <QtCore/QTextStream> #include <QtGui/QVector2D> #include "math.hpp" qreal Polynom::operator()(qreal x, qreal y) const { qreal result = 0; for (ConstIterator i = begin(); i != end(); ++i) { result += qPow(x, i->xPow) * qPow(y, i->yPow) * i->c; } return result; } qreal Polynom::operator()(QPointF point) const { return operator()(point.x(), point.y()); } QPointF PolynomSystem::getNextValue(QPointF point, qreal eps, bool useRungeKutta) const { QVector2D diff(first(point), second(point)); if (useRungeKutta) { qreal x = point.x(), y = point.y(); qreal first25 = first (x + eps * first(point) / 2, y + eps * second(point) / 2); qreal second25 = second(x + eps * first(point) / 2, y + eps * second(point) / 2); qreal first50 = first (x + eps * first25 / 2, y + eps * second25 / 2); qreal second50 = second(x + eps * first25 / 2, y + eps * second25 / 2); qreal first75 = first (x + eps * first50, y + eps * second50); qreal second75 = second(x + eps * first50, y + eps * second50); diff.setX((first (point) + 2 * first25 + 2 * first50 + first75 ) / 6); diff.setY((second(point) + 2 * second25 + 2 * second50 + second75) / 6); } if (diff.length() > 1) { diff /= diff.length(); } diff *= eps; return point + diff.toPointF(); } qreal PolynomSystem::poincareFunction(qreal p, qreal eps) const { QPointF point(p, 0); quint32 step = 0; while (step < 10 || point.x() < 0 || qAbs(point.y()) > eps) { point = getNextValue(point, eps); if (step > 50. / eps) { return 0; } ++step; } return point.x(); } qreal PolynomSystem::findPoincareStaticPoint(qreal a, qreal b, qreal eps) const { qreal pdiffa = poincareFunction(a, eps) - a; qreal pdiffb = poincareFunction(b, eps) - b; if (pdiffa * pdiffb > 0) { return 0; } while (qAbs(b - a) > eps) { pdiffa = poincareFunction(a, eps) - a; pdiffb = poincareFunction(b, eps) - b; a = b - (b - a) * pdiffb / (pdiffb - pdiffa); pdiffa = poincareFunction(a, eps) - a; b = a - (a - b) * pdiffa / (pdiffa - pdiffb); } return b; } qreal PolynomSystem::getPeriod(qreal staticPoint, qreal eps) const { QPointF point(staticPoint, 0); quint32 step = 0; qreal diff = 0; while (step < 5 || qAbs(diff) > eps / 2) { point = getNextValue(point, eps, true); diff = qPow(point.x() - staticPoint, 2) + qPow(point.y(), 2); ++step; } return step * eps; } void fillPolynom(QString line, Polynom &polynom, qreal param) { QStringList parts = line.split(" "); QStringList subParts; Monom m; polynom.clear(); for (int i = 0; i < parts.size(); ++i) { subParts = parts.at(i).split(' '); m.xPow = subParts.at(1).toInt(); m.yPow = subParts.at(2).toInt(); m.c = subParts.at(0) == "c" ? param : subParts.at(0).toDouble(); polynom.append(m); } } ComplexPair PolynomSystem::getEigenValues() const { ComplexPair result; qreal a = 0, b = 0, c = 0, d = 0; Polynom::ConstIterator i; for (i = first.begin(); i != first.end(); ++i) { if (i->xPow == 1 && i->yPow == 0) { a = i->c; } else if (i->xPow == 0 && i->yPow == 1) { b = i->c; } } for (i = second.begin(); i != second.end(); ++i) { if (i->xPow == 1 && i->yPow == 0) { c = i->c; } else if (i->xPow == 0 && i->yPow == 1) { d = i->c; } } qreal determinant = (a - d) * (a - d) + 4 * b * c; Complex detSqrt = std::sqrt(Complex(determinant, 0)); result.first = (Complex(a + d, 0) + detSqrt) * Complex(.5, 0); result.second = (Complex(a + d, 0) - detSqrt) * Complex(.5, 0); return result; } PointType PolynomSystem::getPointType() const { ComplexPair eigenValues = getEigenValues(); Complex v1 = eigenValues.first, v2 = eigenValues.second; if (qFuzzyIsNull(v1.real()) && qFuzzyIsNull(v2.real())) { return PointCenter; } else if (qFuzzyIsNull(v1.imag()) && qFuzzyIsNull(v2.imag())) { if (qFuzzyCompare(v1.real(), v2.real())) { if (v1.real() > 0) { return PointKnotSingularUnstable; } else { return PointKnotSingularStable; } } else if (v1.real() > 0 && v2.real() > 0) { return PointKnotUnstable; } else if (v1.real() < 0 && v2.real() < 0) { return PointKnotStable; } else { return PointSaddle; } } else if (v1.real() > 0) { return PointFocusUnstable; } else { return PointFocusStable; } } void fillSystem(QString fileName, PolynomSystem &system, qreal param) { QFile inputFile(fileName); inputFile.open(QFile::ReadOnly); QTextStream input(&inputFile); fillPolynom(input.readLine(), system.first, param); fillPolynom(input.readLine(), system.second, param); inputFile.close(); } <|endoftext|>
<commit_before>#include <boost/assert.hpp> #include <boost/assign/list_of.hpp> #include <boost/assign/list_inserter.hpp> #include <boost/assign/std/vector.hpp> #include <boost/test/unit_test.hpp> #include <boost/foreach.hpp> #include "../main.h" #include "../script.h" #include "../wallet.h" using namespace std; // Test routines internal to script.cpp: extern uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType); extern bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, int& nSigOps, int nHashType, bool fStrictOpEval); BOOST_AUTO_TEST_SUITE(script_op_eval_tests) BOOST_AUTO_TEST_CASE(script_op_eval1) { // OP_EVAL looks like this: // scriptSig: <sig> <sig...> <serialized_script> // scriptPubKey: DUP HASH160 <hash> EQUALVERIFY EVAL // Test SignSignature() (and therefore the version of Solver() that signs transactions) CBasicKeyStore keystore; CKey key[4]; for (int i = 0; i < 4; i++) { key[i].MakeNewKey(); keystore.AddKey(key[i]); } // 8 Scripts: checking all combinations of // different keys, straight/EVAL, pubkey/pubkeyhash CScript standardScripts[4]; standardScripts[0] << key[0].GetPubKey() << OP_CHECKSIG; standardScripts[1].SetBitcoinAddress(key[1].GetPubKey()); standardScripts[2] << key[1].GetPubKey() << OP_CHECKSIG; standardScripts[3].SetBitcoinAddress(key[2].GetPubKey()); CScript evalScripts[4]; uint160 sigScriptHashes[4]; for (int i = 0; i < 4; i++) { sigScriptHashes[i] = Hash160(standardScripts[i]); keystore.AddCScript(sigScriptHashes[i], standardScripts[i]); evalScripts[i] << OP_DUP << OP_HASH160 << sigScriptHashes[i] << OP_EQUALVERIFY << OP_EVAL; } CTransaction txFrom; // Funding transaction: txFrom.vout.resize(8); for (int i = 0; i < 4; i++) { txFrom.vout[i].scriptPubKey = evalScripts[i]; txFrom.vout[i+4].scriptPubKey = standardScripts[i]; } BOOST_CHECK(txFrom.IsStandard()); CTransaction txTo[8]; // Spending transactions for (int i = 0; i < 8; i++) { txTo[i].vin.resize(1); txTo[i].vout.resize(1); txTo[i].vin[0].prevout.n = i; txTo[i].vin[0].prevout.hash = txFrom.GetHash(); txTo[i].vout[0].nValue = 1; BOOST_CHECK_MESSAGE(IsMine(keystore, txFrom.vout[i].scriptPubKey), strprintf("IsMine %d", i)); } for (int i = 0; i < 8; i++) { BOOST_CHECK_MESSAGE(SignSignature(keystore, txFrom, txTo[i], 0), strprintf("SignSignature %d", i)); } // All of the above should be OK, and the txTos have valid signatures // Check to make sure signature verification fails if we use the wrong ScriptSig: for (int i = 0; i < 8; i++) for (int j = 0; j < 8; j++) { CScript sigSave = txTo[i].vin[0].scriptSig; txTo[i].vin[0].scriptSig = txTo[j].vin[0].scriptSig; int nUnused = 0; bool sigOK = VerifySignature(txFrom, txTo[i], 0, nUnused); if (i == j) BOOST_CHECK_MESSAGE(sigOK, strprintf("VerifySignature %d %d", i, j)); else BOOST_CHECK_MESSAGE(!sigOK, strprintf("VerifySignature %d %d", i, j)); txTo[i].vin[0].scriptSig = sigSave; } } BOOST_AUTO_TEST_CASE(script_op_eval2) { // Test OP_EVAL edge cases CScript recurse; recurse << OP_DUP << OP_EVAL; uint160 recurseHash = Hash160(recurse); CScript fund; fund << OP_DUP << OP_HASH160 << recurseHash << OP_EQUALVERIFY << OP_EVAL; CTransaction txFrom; // Funding transaction: txFrom.vout.resize(1); txFrom.vout[0].scriptPubKey = fund; BOOST_CHECK(txFrom.IsStandard()); // Looks like a standard transaction until you try to spend it CTransaction txTo; txTo.vin.resize(1); txTo.vout.resize(1); txTo.vin[0].prevout.n = 0; txTo.vin[0].prevout.hash = txFrom.GetHash(); txTo.vin[0].scriptSig = CScript() << static_cast<std::vector<unsigned char> >(recurse); txTo.vout[0].nValue = 1; int nUnused = 0; BOOST_CHECK(!VerifyScript(txTo.vin[0].scriptSig, txFrom.vout[0].scriptPubKey, txTo, 0, nUnused, 0, true)); BOOST_CHECK(!VerifySignature(txFrom, txTo, 0, nUnused, true)); } BOOST_AUTO_TEST_CASE(script_op_eval3) { // Test the CScript::Set* methods CBasicKeyStore keystore; CKey key[4]; std::vector<CKey> keys; for (int i = 0; i < 4; i++) { key[i].MakeNewKey(); keystore.AddKey(key[i]); keys.push_back(key[i]); } CScript inner[4]; inner[0].SetBitcoinAddress(key[0].GetPubKey()); inner[1].SetMultisig(2, std::vector<CKey>(keys.begin(), keys.begin()+2)); inner[2].SetMultisig(1, std::vector<CKey>(keys.begin(), keys.begin()+2)); inner[3].SetMultisig(2, std::vector<CKey>(keys.begin(), keys.begin()+3)); CScript outer[4]; for (int i = 0; i < 4; i++) { outer[i].SetEval(inner[i]); keystore.AddCScript(Hash160(inner[i]), inner[i]); } CTransaction txFrom; // Funding transaction: txFrom.vout.resize(4); for (int i = 0; i < 4; i++) { txFrom.vout[i].scriptPubKey = outer[i]; } BOOST_CHECK(txFrom.IsStandard()); CTransaction txTo[4]; // Spending transactions for (int i = 0; i < 4; i++) { txTo[i].vin.resize(1); txTo[i].vout.resize(1); txTo[i].vin[0].prevout.n = i; txTo[i].vin[0].prevout.hash = txFrom.GetHash(); txTo[i].vout[0].nValue = 1; txTo[i].vout[0].scriptPubKey = inner[i]; BOOST_CHECK_MESSAGE(IsMine(keystore, txFrom.vout[i].scriptPubKey), strprintf("IsMine %d", i)); } for (int i = 0; i < 4; i++) { BOOST_CHECK_MESSAGE(SignSignature(keystore, txFrom, txTo[i], 0), strprintf("SignSignature %d", i)); BOOST_CHECK_MESSAGE(txTo[i].IsStandard(), strprintf("txTo[%d].IsStandard", i)); } } BOOST_AUTO_TEST_CASE(script_op_eval_backcompat1) { // Check backwards-incompatibility-testing code CScript returnsEleven; returnsEleven << OP_11; // This should validate on new clients, but will // be invalid on old clients (that interpret OP_EVAL as a no-op) // ... except there's a special rule that makes new clients reject // it. CScript fund; fund << OP_EVAL << OP_11 << OP_EQUAL; CTransaction txFrom; // Funding transaction: txFrom.vout.resize(1); txFrom.vout[0].scriptPubKey = fund; CTransaction txTo; txTo.vin.resize(1); txTo.vout.resize(1); txTo.vin[0].prevout.n = 0; txTo.vin[0].prevout.hash = txFrom.GetHash(); txTo.vin[0].scriptSig = CScript() << static_cast<std::vector<unsigned char> >(returnsEleven); txTo.vout[0].nValue = 1; int nUnused = 0; BOOST_CHECK(!VerifyScript(txTo.vin[0].scriptSig, txFrom.vout[0].scriptPubKey, txTo, 0, nUnused, 0, true)); BOOST_CHECK(!VerifySignature(txFrom, txTo, 0, nUnused, true)); } BOOST_AUTO_TEST_CASE(script_op_eval_switchover) { // Test OP_EVAL switchover code CScript notValid; notValid << OP_11 << OP_12 << OP_EQUALVERIFY; // This will be valid under old rules, invalid under new: CScript fund; fund << OP_EVAL; CTransaction txFrom; // Funding transaction: txFrom.vout.resize(1); txFrom.vout[0].scriptPubKey = fund; CTransaction txTo; txTo.vin.resize(1); txTo.vout.resize(1); txTo.vin[0].prevout.n = 0; txTo.vin[0].prevout.hash = txFrom.GetHash(); txTo.vin[0].scriptSig = CScript() << static_cast<std::vector<unsigned char> >(notValid); txTo.vout[0].nValue = 1; int nUnused = 0; BOOST_CHECK(VerifyScript(txTo.vin[0].scriptSig, txFrom.vout[0].scriptPubKey, txTo, 0, nUnused, 0, false)); // Under strict op_eval switchover, it should be considered invalid: BOOST_CHECK(!VerifyScript(txTo.vin[0].scriptSig, txFrom.vout[0].scriptPubKey, txTo, 0, nUnused, 0, true)); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Fixed OP_EVAL recursion unit test, checks for both infinite and exactly-3-deep recursion<commit_after>#include <boost/assert.hpp> #include <boost/assign/list_of.hpp> #include <boost/assign/list_inserter.hpp> #include <boost/assign/std/vector.hpp> #include <boost/test/unit_test.hpp> #include <boost/foreach.hpp> #include "../main.h" #include "../script.h" #include "../wallet.h" using namespace std; // Test routines internal to script.cpp: extern uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType); extern bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, int& nSigOps, int nHashType, bool fStrictOpEval); BOOST_AUTO_TEST_SUITE(script_op_eval_tests) BOOST_AUTO_TEST_CASE(script_op_eval1) { // OP_EVAL looks like this: // scriptSig: <sig> <sig...> <serialized_script> // scriptPubKey: DUP HASH160 <hash> EQUALVERIFY EVAL // Test SignSignature() (and therefore the version of Solver() that signs transactions) CBasicKeyStore keystore; CKey key[4]; for (int i = 0; i < 4; i++) { key[i].MakeNewKey(); keystore.AddKey(key[i]); } // 8 Scripts: checking all combinations of // different keys, straight/EVAL, pubkey/pubkeyhash CScript standardScripts[4]; standardScripts[0] << key[0].GetPubKey() << OP_CHECKSIG; standardScripts[1].SetBitcoinAddress(key[1].GetPubKey()); standardScripts[2] << key[1].GetPubKey() << OP_CHECKSIG; standardScripts[3].SetBitcoinAddress(key[2].GetPubKey()); CScript evalScripts[4]; uint160 sigScriptHashes[4]; for (int i = 0; i < 4; i++) { sigScriptHashes[i] = Hash160(standardScripts[i]); keystore.AddCScript(sigScriptHashes[i], standardScripts[i]); evalScripts[i] << OP_DUP << OP_HASH160 << sigScriptHashes[i] << OP_EQUALVERIFY << OP_EVAL; } CTransaction txFrom; // Funding transaction: txFrom.vout.resize(8); for (int i = 0; i < 4; i++) { txFrom.vout[i].scriptPubKey = evalScripts[i]; txFrom.vout[i+4].scriptPubKey = standardScripts[i]; } BOOST_CHECK(txFrom.IsStandard()); CTransaction txTo[8]; // Spending transactions for (int i = 0; i < 8; i++) { txTo[i].vin.resize(1); txTo[i].vout.resize(1); txTo[i].vin[0].prevout.n = i; txTo[i].vin[0].prevout.hash = txFrom.GetHash(); txTo[i].vout[0].nValue = 1; BOOST_CHECK_MESSAGE(IsMine(keystore, txFrom.vout[i].scriptPubKey), strprintf("IsMine %d", i)); } for (int i = 0; i < 8; i++) { BOOST_CHECK_MESSAGE(SignSignature(keystore, txFrom, txTo[i], 0), strprintf("SignSignature %d", i)); } // All of the above should be OK, and the txTos have valid signatures // Check to make sure signature verification fails if we use the wrong ScriptSig: for (int i = 0; i < 8; i++) for (int j = 0; j < 8; j++) { CScript sigSave = txTo[i].vin[0].scriptSig; txTo[i].vin[0].scriptSig = txTo[j].vin[0].scriptSig; int nUnused = 0; bool sigOK = VerifySignature(txFrom, txTo[i], 0, nUnused); if (i == j) BOOST_CHECK_MESSAGE(sigOK, strprintf("VerifySignature %d %d", i, j)); else BOOST_CHECK_MESSAGE(!sigOK, strprintf("VerifySignature %d %d", i, j)); txTo[i].vin[0].scriptSig = sigSave; } } BOOST_AUTO_TEST_CASE(script_op_eval2) { // Test OP_EVAL edge cases // Make sure infinite recursion fails to validate: CScript infiniteRecurse; infiniteRecurse << OP_DUP << OP_EVAL; uint160 infiniteRecurseHash = Hash160(infiniteRecurse); CScript fund1; fund1 << OP_DUP << OP_HASH160 << infiniteRecurseHash << OP_EQUALVERIFY << OP_EVAL; CTransaction txFrom1; // Funding transaction: txFrom1.vout.resize(1); txFrom1.vout[0].scriptPubKey = fund1; BOOST_CHECK(txFrom1.IsStandard()); // Looks like a standard transaction until you try to spend it std::vector<unsigned char> infiniteRecurseSerialized(infiniteRecurse); CTransaction txTo1; txTo1.vin.resize(1); txTo1.vout.resize(1); txTo1.vin[0].prevout.n = 0; txTo1.vin[0].prevout.hash = txFrom1.GetHash(); txTo1.vin[0].scriptSig = CScript() << infiniteRecurseSerialized << infiniteRecurseSerialized; txTo1.vout[0].nValue = 1; int nUnused1 = 0; BOOST_CHECK(!VerifyScript(txTo1.vin[0].scriptSig, txFrom1.vout[0].scriptPubKey, txTo1, 0, nUnused1, 0, true)); BOOST_CHECK(!VerifySignature(txFrom1, txTo1, 0, nUnused1, true)); // Make sure 3-level-deep recursion fails to validate: CScript recurse3; recurse3 << OP_EVAL; uint160 recurse3Hash = Hash160(recurse3); CScript fund2; fund2 << OP_DUP << OP_HASH160 << recurse3Hash << OP_EQUALVERIFY << OP_EVAL; CTransaction txFrom2; // Funding transaction: txFrom2.vout.resize(1); txFrom2.vout[0].scriptPubKey = fund2; BOOST_CHECK(txFrom2.IsStandard()); // Looks like a standard transaction until you try to spend it std::vector<unsigned char> recurse3Serialized(recurse3); CScript op1Script = CScript() << OP_1; std::vector<unsigned char> op1Serialized(op1Script); CTransaction txTo2; txTo2.vin.resize(1); txTo2.vout.resize(1); txTo2.vin[0].prevout.n = 0; txTo2.vin[0].prevout.hash = txFrom2.GetHash(); txTo2.vin[0].scriptSig = CScript() << op1Serialized << recurse3Serialized << recurse3Serialized; txTo2.vout[0].nValue = 1; int nUnused2 = 0; BOOST_CHECK(!VerifyScript(txTo2.vin[0].scriptSig, txFrom2.vout[0].scriptPubKey, txTo2, 0, nUnused2, 0, true)); BOOST_CHECK(!VerifySignature(txFrom2, txTo2, 0, nUnused2, true)); } BOOST_AUTO_TEST_CASE(script_op_eval3) { // Test the CScript::Set* methods CBasicKeyStore keystore; CKey key[4]; std::vector<CKey> keys; for (int i = 0; i < 4; i++) { key[i].MakeNewKey(); keystore.AddKey(key[i]); keys.push_back(key[i]); } CScript inner[4]; inner[0].SetBitcoinAddress(key[0].GetPubKey()); inner[1].SetMultisig(2, std::vector<CKey>(keys.begin(), keys.begin()+2)); inner[2].SetMultisig(1, std::vector<CKey>(keys.begin(), keys.begin()+2)); inner[3].SetMultisig(2, std::vector<CKey>(keys.begin(), keys.begin()+3)); CScript outer[4]; for (int i = 0; i < 4; i++) { outer[i].SetEval(inner[i]); keystore.AddCScript(Hash160(inner[i]), inner[i]); } CTransaction txFrom; // Funding transaction: txFrom.vout.resize(4); for (int i = 0; i < 4; i++) { txFrom.vout[i].scriptPubKey = outer[i]; } BOOST_CHECK(txFrom.IsStandard()); CTransaction txTo[4]; // Spending transactions for (int i = 0; i < 4; i++) { txTo[i].vin.resize(1); txTo[i].vout.resize(1); txTo[i].vin[0].prevout.n = i; txTo[i].vin[0].prevout.hash = txFrom.GetHash(); txTo[i].vout[0].nValue = 1; txTo[i].vout[0].scriptPubKey = inner[i]; BOOST_CHECK_MESSAGE(IsMine(keystore, txFrom.vout[i].scriptPubKey), strprintf("IsMine %d", i)); } for (int i = 0; i < 4; i++) { BOOST_CHECK_MESSAGE(SignSignature(keystore, txFrom, txTo[i], 0), strprintf("SignSignature %d", i)); BOOST_CHECK_MESSAGE(txTo[i].IsStandard(), strprintf("txTo[%d].IsStandard", i)); } } BOOST_AUTO_TEST_CASE(script_op_eval_backcompat1) { // Check backwards-incompatibility-testing code CScript returnsEleven; returnsEleven << OP_11; // This should validate on new clients, but will // be invalid on old clients (that interpret OP_EVAL as a no-op) // ... except there's a special rule that makes new clients reject // it. CScript fund; fund << OP_EVAL << OP_11 << OP_EQUAL; CTransaction txFrom; // Funding transaction: txFrom.vout.resize(1); txFrom.vout[0].scriptPubKey = fund; CTransaction txTo; txTo.vin.resize(1); txTo.vout.resize(1); txTo.vin[0].prevout.n = 0; txTo.vin[0].prevout.hash = txFrom.GetHash(); txTo.vin[0].scriptSig = CScript() << static_cast<std::vector<unsigned char> >(returnsEleven); txTo.vout[0].nValue = 1; int nUnused = 0; BOOST_CHECK(!VerifyScript(txTo.vin[0].scriptSig, txFrom.vout[0].scriptPubKey, txTo, 0, nUnused, 0, true)); BOOST_CHECK(!VerifySignature(txFrom, txTo, 0, nUnused, true)); } BOOST_AUTO_TEST_CASE(script_op_eval_switchover) { // Test OP_EVAL switchover code CScript notValid; notValid << OP_11 << OP_12 << OP_EQUALVERIFY; // This will be valid under old rules, invalid under new: CScript fund; fund << OP_EVAL; CTransaction txFrom; // Funding transaction: txFrom.vout.resize(1); txFrom.vout[0].scriptPubKey = fund; CTransaction txTo; txTo.vin.resize(1); txTo.vout.resize(1); txTo.vin[0].prevout.n = 0; txTo.vin[0].prevout.hash = txFrom.GetHash(); txTo.vin[0].scriptSig = CScript() << static_cast<std::vector<unsigned char> >(notValid); txTo.vout[0].nValue = 1; int nUnused = 0; BOOST_CHECK(VerifyScript(txTo.vin[0].scriptSig, txFrom.vout[0].scriptPubKey, txTo, 0, nUnused, 0, false)); // Under strict op_eval switchover, it should be considered invalid: BOOST_CHECK(!VerifyScript(txTo.vin[0].scriptSig, txFrom.vout[0].scriptPubKey, txTo, 0, nUnused, 0, true)); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>#include "DebugHandler.h" //DebugHandler* DebugHandler::m_instance = nullptr; DebugHandler::DebugHandler() { QueryPerformanceFrequency(&this->m_frequency); this->m_displayFPS = true; this->ClearConsole(); for (int i = 0; i < this->m_FRAMES_FOR_AVG; i++) { this->m_frameTimes[i] = 40; } this->m_minFPS = 999999; this->m_maxFPS = 0; } void DebugHandler::ClearConsole() { COORD topLeft = { 0, 0 }; HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO screen; DWORD written; GetConsoleScreenBufferInfo(console, &screen); FillConsoleOutputCharacterA( console, ' ', screen.dwSize.X * screen.dwSize.Y, topLeft, &written ); FillConsoleOutputAttribute( console, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE, screen.dwSize.X * screen.dwSize.Y, topLeft, &written ); SetConsoleCursorPosition(console, topLeft); } DebugHandler::~DebugHandler() { } DebugHandler* DebugHandler::instance() { static DebugHandler instance; return &instance; } int DebugHandler::SetComponentHandler(ComponentHandler * compHandler) { this->compHandler = compHandler; this->m_fpsTextComp = this->compHandler->GetTextComponent(); return 0; } int DebugHandler::StartTimer(size_t timerID) { int result = 0; if (timerID < this->m_timers.size()) { LARGE_INTEGER currTime; QueryPerformanceCounter(&currTime); this->m_timers.at(timerID).startTime = currTime; result = 1; } return result; } int DebugHandler::EndTimer(size_t timerID) { int result = 0; if (timerID < this->m_timers.size()) { LARGE_INTEGER currTime; QueryPerformanceCounter(&currTime); this->m_timers.at(timerID).endTime = currTime; result = 1; } return result; } int DebugHandler::CreateTimer(std::wstring label) { Timer timer; if (this->compHandler == nullptr) { return -1; } timer.textComp = this->compHandler->GetTextComponent(); timer.label = label; timer.textComp->text = label + L": [" + L"0" + L"] " + L"0" + L" [" + L"0" + L"] us, " + L"0.0" + L"%"; timer.textComp->active = false; this->m_timers.push_back(timer); return 0; } int DebugHandler::StartProgram() { QueryPerformanceCounter(&this->m_programStart); return 0; } int DebugHandler::EndProgram() { QueryPerformanceCounter(&this->m_programEnd); return 0; } int DebugHandler::ShowFPS(bool show) { this->m_displayFPS = show; return 0; } int DebugHandler::ToggleDebugInfo() { if (this->m_displayDebug) { this->m_displayDebug = false; for (std::vector<Timer>::iterator iter = this->m_timers.begin(); iter != this->m_timers.end(); iter++) { iter->textComp->active = false; } for (std::vector<Value>::iterator iter = this->m_values.begin(); iter != this->m_values.end(); iter++) { iter->textComp->active = false; } } else { this->m_displayDebug = true; for (std::vector<Timer>::iterator iter = this->m_timers.begin(); iter != this->m_timers.end(); iter++) { iter->textComp->active = true; } for (std::vector<Value>::iterator iter = this->m_values.begin(); iter != this->m_values.end(); iter++) { iter->textComp->active = true; } } this->ClearConsole(); return 0; } int DebugHandler::CreateCustomLabel(std::wstring label, float value) { Value tempValue; TextComponent* textComp = this->compHandler->GetTextComponent(); textComp->active = false; tempValue.textComp = textComp; tempValue.label = label; tempValue.value = value; this->m_values.push_back(tempValue); return 0; } int DebugHandler::UpdateCustomLabel(int labelID, float newValue) { if ((unsigned int)labelID < this->m_values.size()) { this->m_values.at(labelID).value = newValue; } else { return -1; } return 0; } int DebugHandler::UpdateCustomLabelIncrease(int labelID, float addValue) { if ((unsigned int)labelID < this->m_values.size()) { this->m_values.at(labelID).value += addValue; } else { return -1; } return 0; } int DebugHandler::ResetMinMax() { std::vector<Timer>::iterator iter; for (iter = this->m_timers.begin(); iter != this->m_timers.end(); iter++) { iter->maxTime = 0; iter->minTime = 999999; } this->m_minFPS = 999999; this->m_maxFPS = 0; return 0; } int DebugHandler::DisplayConsole(float dTime) { if (!this->m_displayDebug) { return 0; } COORD topLeft = { 0, 0 }; COORD FPSLocation = { 50, 0 }; HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO screen; DWORD written; //GetConsoleScreenBufferInfo(console, &screen); /*FillConsoleOutputCharacterA( console, ' ', toClear.X * toClear.Y, topLeft, &written );*/ /*FillConsoleOutputAttribute( console, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE, toClear.X * toClear.Y, topLeft, &written );*/ SetConsoleCursorPosition(console, topLeft); std::vector<Timer>::iterator iter; unsigned int time; int i; for (i = 0, iter = this->m_timers.begin(); iter != this->m_timers.end(); i++, iter++) { time = iter->GetTimeMS(this->m_frequency); LARGE_INTEGER elapsedTime; elapsedTime.QuadPart = this->m_programEnd.QuadPart - this->m_programStart.QuadPart; elapsedTime.QuadPart *= 1000000; elapsedTime.QuadPart /= this->m_frequency.QuadPart; std::wcout << std::fixed << std::setprecision(1) << iter->label << ": [" << iter->minTime << "] " << time << " [" << iter->maxTime << "] us, " << (float)((time / (float)elapsedTime.QuadPart) * 100) << "%"; GetConsoleScreenBufferInfo(console, &screen); FillConsoleOutputCharacterA( console, ' ', 5, screen.dwCursorPosition, &written ); std::cout << std::endl; } int nrOfCustomLabels = this->m_values.size(); for (int j = 0; j < nrOfCustomLabels; j++) { std::wcout << this->m_values.at(j).label << ": " << this->m_values.at(j).value; GetConsoleScreenBufferInfo(console, &screen); FillConsoleOutputCharacterA( console, ' ', 5, screen.dwCursorPosition, &written ); std::cout << std::endl; } if (this->m_displayFPS) { int sum = 0, avgFPS; this->m_currFrameTimesPtr = (this->m_currFrameTimesPtr >= this->m_FRAMES_FOR_AVG) ? 0 : this->m_currFrameTimesPtr; this->m_frameTimes[this->m_currFrameTimesPtr] = (unsigned int)(1000000 / dTime); for (int k = 0; k < this->m_FRAMES_FOR_AVG; k++) { sum += this->m_frameTimes[k]; } avgFPS = sum / this->m_FRAMES_FOR_AVG; this->m_minFPS = (this->m_minFPS < this->m_frameTimes[this->m_currFrameTimesPtr]) ? this->m_minFPS : this->m_frameTimes[this->m_currFrameTimesPtr]; this->m_maxFPS = (this->m_maxFPS > this->m_frameTimes[this->m_currFrameTimesPtr]) ? this->m_maxFPS : this->m_frameTimes[this->m_currFrameTimesPtr]; SetConsoleCursorPosition(console, FPSLocation); std::cout << "FPS: " << avgFPS << " [" << this->m_minFPS << "] (" << std::to_string(this->m_frameTimes[this->m_currFrameTimesPtr]) << ") [" << this->m_maxFPS << "]"; GetConsoleScreenBufferInfo(console, &screen); FillConsoleOutputCharacterA( console, ' ', 8, screen.dwCursorPosition, &written ); this->m_currFrameTimesPtr++; } COORD finishedCursonLoc = { (SHORT)0, (SHORT)(this->m_timers.size() + (size_t)nrOfCustomLabels + 1) }; SetConsoleCursorPosition(console, finishedCursonLoc); return 1; } int DebugHandler::DisplayOnScreen(float dTime) { std::vector<Timer>::iterator iter; unsigned int time; int i; float spacing = 30.f; for (i = 0, iter = this->m_timers.begin(); iter != this->m_timers.end(); i++, iter++) { time = iter->GetTimeMS(this->m_frequency); LARGE_INTEGER elapsedTime; elapsedTime.QuadPart = this->m_programEnd.QuadPart - this->m_programStart.QuadPart; elapsedTime.QuadPart *= 1000000; elapsedTime.QuadPart /= this->m_frequency.QuadPart; iter->textComp->text = iter->label + L": [" + std::to_wstring(iter->minTime) + L"] " + std::to_wstring(time) + L" [" + std::to_wstring(iter->maxTime) + L"] us, " + std::to_wstring((float)((time / (float)elapsedTime.QuadPart) * 100)) + L"%"; iter->textComp->position = DirectX::XMFLOAT2(20.f, 20.f + (i * spacing)); } int nrOfCustomLabels = this->m_values.size(); for (int j = 0; j < nrOfCustomLabels; j++) { this->m_values.at(j).textComp->text = this->m_values.at(j).label + L": " + std::to_wstring(this->m_values.at(j).value); } if (this->m_displayFPS) { int sum = 0, avgFPS; this->m_currFrameTimesPtr = (this->m_currFrameTimesPtr >= this->m_FRAMES_FOR_AVG) ? 0 : this->m_currFrameTimesPtr; this->m_frameTimes[this->m_currFrameTimesPtr] = (unsigned int)(1000000 / dTime); for (int k = 0; k < this->m_FRAMES_FOR_AVG; k++) { sum += this->m_frameTimes[k]; } avgFPS = sum / this->m_FRAMES_FOR_AVG; this->m_minFPS = (this->m_minFPS < this->m_frameTimes[this->m_currFrameTimesPtr]) ? this->m_minFPS : this->m_frameTimes[this->m_currFrameTimesPtr]; this->m_maxFPS = (this->m_maxFPS > this->m_frameTimes[this->m_currFrameTimesPtr]) ? this->m_maxFPS : this->m_frameTimes[this->m_currFrameTimesPtr]; this->m_fpsTextComp->text = L"FPS: " + std::to_wstring(avgFPS) + L" [" + std::to_wstring(this->m_minFPS) + L"] (" + std::to_wstring(this->m_frameTimes[this->m_currFrameTimesPtr]) + L") [" + std::to_wstring(this->m_maxFPS) + L"]"; this->m_currFrameTimesPtr++; } return 0; } void DebugHandler::Shutdown() { this->m_timers.clear(); this->m_values.clear(); } <commit_msg>UPDATE text spacing and scaling<commit_after>#include "DebugHandler.h" //DebugHandler* DebugHandler::m_instance = nullptr; DebugHandler::DebugHandler() { QueryPerformanceFrequency(&this->m_frequency); this->m_displayFPS = true; this->ClearConsole(); for (int i = 0; i < this->m_FRAMES_FOR_AVG; i++) { this->m_frameTimes[i] = 40; } this->m_minFPS = 999999; this->m_maxFPS = 0; } void DebugHandler::ClearConsole() { COORD topLeft = { 0, 0 }; HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO screen; DWORD written; GetConsoleScreenBufferInfo(console, &screen); FillConsoleOutputCharacterA( console, ' ', screen.dwSize.X * screen.dwSize.Y, topLeft, &written ); FillConsoleOutputAttribute( console, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE, screen.dwSize.X * screen.dwSize.Y, topLeft, &written ); SetConsoleCursorPosition(console, topLeft); } DebugHandler::~DebugHandler() { } DebugHandler* DebugHandler::instance() { static DebugHandler instance; return &instance; } int DebugHandler::SetComponentHandler(ComponentHandler * compHandler) { this->compHandler = compHandler; this->m_fpsTextComp = this->compHandler->GetTextComponent(); return 0; } int DebugHandler::StartTimer(size_t timerID) { int result = 0; if (timerID < this->m_timers.size()) { LARGE_INTEGER currTime; QueryPerformanceCounter(&currTime); this->m_timers.at(timerID).startTime = currTime; result = 1; } return result; } int DebugHandler::EndTimer(size_t timerID) { int result = 0; if (timerID < this->m_timers.size()) { LARGE_INTEGER currTime; QueryPerformanceCounter(&currTime); this->m_timers.at(timerID).endTime = currTime; result = 1; } return result; } int DebugHandler::CreateTimer(std::wstring label) { Timer timer; if (this->compHandler == nullptr) { return -1; } timer.textComp = this->compHandler->GetTextComponent(); timer.label = label; timer.textComp->text = label + L": [" + L"0" + L"] " + L"0" + L" [" + L"0" + L"] us, " + L"0.0" + L"%"; timer.textComp->active = false; timer.textComp->position = DirectX::XMFLOAT2(20.f, 20.f + (this->m_timers.size() * 30.f)); timer.textComp->scale = DirectX::XMFLOAT2(.4f, .4f); this->m_timers.push_back(timer); return 0; } int DebugHandler::StartProgram() { QueryPerformanceCounter(&this->m_programStart); return 0; } int DebugHandler::EndProgram() { QueryPerformanceCounter(&this->m_programEnd); return 0; } int DebugHandler::ShowFPS(bool show) { this->m_displayFPS = show; return 0; } int DebugHandler::ToggleDebugInfo() { if (this->m_displayDebug) { this->m_displayDebug = false; for (std::vector<Timer>::iterator iter = this->m_timers.begin(); iter != this->m_timers.end(); iter++) { iter->textComp->active = false; } for (std::vector<Value>::iterator iter = this->m_values.begin(); iter != this->m_values.end(); iter++) { iter->textComp->active = false; } } else { this->m_displayDebug = true; for (std::vector<Timer>::iterator iter = this->m_timers.begin(); iter != this->m_timers.end(); iter++) { iter->textComp->active = true; } for (std::vector<Value>::iterator iter = this->m_values.begin(); iter != this->m_values.end(); iter++) { iter->textComp->active = true; } } this->ClearConsole(); return 0; } int DebugHandler::CreateCustomLabel(std::wstring label, float value) { Value tempValue; TextComponent* textComp = this->compHandler->GetTextComponent(); textComp->active = false; tempValue.textComp = textComp; tempValue.textComp->position = DirectX::XMFLOAT2(20.f, 20.f + ((this->m_timers.size() + this->m_values.size()) * 30.f)); tempValue.textComp->scale = DirectX::XMFLOAT2(.4f, .4f); tempValue.label = label; tempValue.value = value; this->m_values.push_back(tempValue); return 0; } int DebugHandler::UpdateCustomLabel(int labelID, float newValue) { if ((unsigned int)labelID < this->m_values.size()) { this->m_values.at(labelID).value = newValue; } else { return -1; } return 0; } int DebugHandler::UpdateCustomLabelIncrease(int labelID, float addValue) { if ((unsigned int)labelID < this->m_values.size()) { this->m_values.at(labelID).value += addValue; } else { return -1; } return 0; } int DebugHandler::ResetMinMax() { std::vector<Timer>::iterator iter; for (iter = this->m_timers.begin(); iter != this->m_timers.end(); iter++) { iter->maxTime = 0; iter->minTime = 999999; } this->m_minFPS = 999999; this->m_maxFPS = 0; return 0; } int DebugHandler::DisplayConsole(float dTime) { if (!this->m_displayDebug) { return 0; } COORD topLeft = { 0, 0 }; COORD FPSLocation = { 50, 0 }; HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE); CONSOLE_SCREEN_BUFFER_INFO screen; DWORD written; //GetConsoleScreenBufferInfo(console, &screen); /*FillConsoleOutputCharacterA( console, ' ', toClear.X * toClear.Y, topLeft, &written );*/ /*FillConsoleOutputAttribute( console, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE, toClear.X * toClear.Y, topLeft, &written );*/ SetConsoleCursorPosition(console, topLeft); std::vector<Timer>::iterator iter; unsigned int time; int i; for (i = 0, iter = this->m_timers.begin(); iter != this->m_timers.end(); i++, iter++) { time = iter->GetTimeMS(this->m_frequency); LARGE_INTEGER elapsedTime; elapsedTime.QuadPart = this->m_programEnd.QuadPart - this->m_programStart.QuadPart; elapsedTime.QuadPart *= 1000000; elapsedTime.QuadPart /= this->m_frequency.QuadPart; std::wcout << std::fixed << std::setprecision(1) << iter->label << ": [" << iter->minTime << "] " << time << " [" << iter->maxTime << "] us, " << (float)((time / (float)elapsedTime.QuadPart) * 100) << "%"; GetConsoleScreenBufferInfo(console, &screen); FillConsoleOutputCharacterA( console, ' ', 5, screen.dwCursorPosition, &written ); std::cout << std::endl; } int nrOfCustomLabels = this->m_values.size(); for (int j = 0; j < nrOfCustomLabels; j++) { std::wcout << this->m_values.at(j).label << ": " << this->m_values.at(j).value; GetConsoleScreenBufferInfo(console, &screen); FillConsoleOutputCharacterA( console, ' ', 5, screen.dwCursorPosition, &written ); std::cout << std::endl; } if (this->m_displayFPS) { int sum = 0, avgFPS; this->m_currFrameTimesPtr = (this->m_currFrameTimesPtr >= this->m_FRAMES_FOR_AVG) ? 0 : this->m_currFrameTimesPtr; this->m_frameTimes[this->m_currFrameTimesPtr] = (unsigned int)(1000000 / dTime); for (int k = 0; k < this->m_FRAMES_FOR_AVG; k++) { sum += this->m_frameTimes[k]; } avgFPS = sum / this->m_FRAMES_FOR_AVG; this->m_minFPS = (this->m_minFPS < this->m_frameTimes[this->m_currFrameTimesPtr]) ? this->m_minFPS : this->m_frameTimes[this->m_currFrameTimesPtr]; this->m_maxFPS = (this->m_maxFPS > this->m_frameTimes[this->m_currFrameTimesPtr]) ? this->m_maxFPS : this->m_frameTimes[this->m_currFrameTimesPtr]; SetConsoleCursorPosition(console, FPSLocation); std::cout << "FPS: " << avgFPS << " [" << this->m_minFPS << "] (" << std::to_string(this->m_frameTimes[this->m_currFrameTimesPtr]) << ") [" << this->m_maxFPS << "]"; GetConsoleScreenBufferInfo(console, &screen); FillConsoleOutputCharacterA( console, ' ', 8, screen.dwCursorPosition, &written ); this->m_currFrameTimesPtr++; } COORD finishedCursonLoc = { (SHORT)0, (SHORT)(this->m_timers.size() + (size_t)nrOfCustomLabels + 1) }; SetConsoleCursorPosition(console, finishedCursonLoc); return 1; } int DebugHandler::DisplayOnScreen(float dTime) { std::vector<Timer>::iterator iter; unsigned int time; int i; for (i = 0, iter = this->m_timers.begin(); iter != this->m_timers.end(); i++, iter++) { time = iter->GetTimeMS(this->m_frequency); LARGE_INTEGER elapsedTime; elapsedTime.QuadPart = this->m_programEnd.QuadPart - this->m_programStart.QuadPart; elapsedTime.QuadPart *= 1000000; elapsedTime.QuadPart /= this->m_frequency.QuadPart; iter->textComp->text = iter->label + L": [" + std::to_wstring(iter->minTime) + L"] " + std::to_wstring(time) + L" [" + std::to_wstring(iter->maxTime) + L"] us, " + std::to_wstring((float)((time / (float)elapsedTime.QuadPart) * 100)) + L"%"; } int nrOfCustomLabels = this->m_values.size(); for (int j = 0; j < nrOfCustomLabels; j++) { this->m_values.at(j).textComp->text = this->m_values.at(j).label + L": " + std::to_wstring(this->m_values.at(j).value); } if (this->m_displayFPS) { int sum = 0, avgFPS; this->m_currFrameTimesPtr = (this->m_currFrameTimesPtr >= this->m_FRAMES_FOR_AVG) ? 0 : this->m_currFrameTimesPtr; this->m_frameTimes[this->m_currFrameTimesPtr] = (unsigned int)(1000000 / dTime); for (int k = 0; k < this->m_FRAMES_FOR_AVG; k++) { sum += this->m_frameTimes[k]; } avgFPS = sum / this->m_FRAMES_FOR_AVG; this->m_minFPS = (this->m_minFPS < this->m_frameTimes[this->m_currFrameTimesPtr]) ? this->m_minFPS : this->m_frameTimes[this->m_currFrameTimesPtr]; this->m_maxFPS = (this->m_maxFPS > this->m_frameTimes[this->m_currFrameTimesPtr]) ? this->m_maxFPS : this->m_frameTimes[this->m_currFrameTimesPtr]; this->m_fpsTextComp->text = L"FPS: " + std::to_wstring(avgFPS) + L" [" + std::to_wstring(this->m_minFPS) + L"] (" + std::to_wstring(this->m_frameTimes[this->m_currFrameTimesPtr]) + L") [" + std::to_wstring(this->m_maxFPS) + L"]"; this->m_currFrameTimesPtr++; } return 0; } void DebugHandler::Shutdown() { this->m_timers.clear(); this->m_values.clear(); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fuprlout.cxx,v $ * * $Revision: 1.11 $ * * last change: $Author: rt $ $Date: 2005-12-14 17:02:27 $ * * 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 * ************************************************************************/ #pragma hdrstop #include "fuprlout.hxx" #ifndef _SV_WRKWIN_HXX #include <vcl/wrkwin.hxx> #endif #ifndef _SFXDISPATCH_HXX //autogen #include <sfx2/dispatch.hxx> #endif #ifndef _SFXSMPLHINT_HXX //autogen #include <svtools/smplhint.hxx> #endif #ifndef _SFXITEMPOOL_HXX //autogen #include <svtools/itempool.hxx> #endif #include <sot/storage.hxx> #ifndef _SV_MSGBOX_HXX //autogen #include <vcl/msgbox.hxx> #endif #ifndef _SVDUNDO_HXX //autogen #include <svx/svdundo.hxx> #endif #include <sfx2/viewfrm.hxx> #include "drawdoc.hxx" #include "sdpage.hxx" #include "pres.hxx" #ifndef SD_DRAW_VIEW_SHELL_HXX #include "DrawViewShell.hxx" #endif #ifndef SD_FRAMW_VIEW_HXX #include "FrameView.hxx" #endif #include "stlpool.hxx" #ifndef SD_VIEW_HXX #include "View.hxx" #endif #include "glob.hrc" #include "glob.hxx" #include "strings.hrc" #include "strmname.h" #include "app.hrc" #include "DrawDocShell.hxx" #include "unprlout.hxx" #include "unchss.hxx" #include "unmovss.hxx" #include "sdattr.hxx" #include "sdresid.hxx" //CHINA001 #include "sdpreslt.hxx" #ifndef SD_DRAW_VIEW_HXX #include "drawview.hxx" #endif #include "eetext.hxx" #include <svx/editdata.hxx> #include "sdabstdlg.hxx" //CHINA001 #include "sdpreslt.hrc" //CHINA001 namespace sd { #ifndef SO2_DECL_SVSTORAGE_DEFINED #define SO2_DECL_SVSTORAGE_DEFINED SO2_DECL_REF(SvStorage) #endif TYPEINIT1( FuPresentationLayout, FuPoor ); #define POOL_BUFFER_SIZE (USHORT)32768 #define DOCUMENT_BUFFER_SIZE (USHORT)32768 #define DOCUMENT_TOKEN (sal_Unicode('#')) /************************************************************************* |* |* Konstruktor |* \************************************************************************/ FuPresentationLayout::FuPresentationLayout ( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq) : FuPoor(pViewSh, pWin, pView, pDoc, rReq) { } FunctionReference FuPresentationLayout::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq ) { FunctionReference xFunc( new FuPresentationLayout( pViewSh, pWin, pView, pDoc, rReq ) ); xFunc->DoExecute(rReq); return xFunc; } void FuPresentationLayout::DoExecute( SfxRequest& rReq ) { // damit nicht Objekte, die gerade editiert werden oder selektiert // sind , verschwinden pView->EndTextEdit(); USHORT nPgViewCount = pView->GetPageViewCount(); for (USHORT nPgView = 0; nPgView < nPgViewCount; nPgView++) { pView->UnmarkAll(); } BOOL bError = FALSE; // die aktive Seite ermitteln USHORT nSelectedPage = SDRPAGE_NOTFOUND; for (USHORT nPage = 0; nPage < pDoc->GetSdPageCount(PK_STANDARD); nPage++) { if (pDoc->GetSdPage(nPage, PK_STANDARD)->IsSelected()) { nSelectedPage = nPage; break; } } DBG_ASSERT(nSelectedPage != SDRPAGE_NOTFOUND, "keine selektierte Seite"); SdPage* pSelectedPage = pDoc->GetSdPage(nSelectedPage, PK_STANDARD); String aOldPageLayoutName(pSelectedPage->GetLayoutName()); String aOldLayoutName(aOldPageLayoutName); aOldLayoutName.Erase(aOldLayoutName.SearchAscii(SD_LT_SEPARATOR)); // wenn wir auf einer Masterpage sind, gelten die Aenderungen fuer alle // Seiten und Notizseiten, die das betreffende Layout benutzen BOOL bOnMaster = FALSE; if( pViewShell && pViewShell->ISA(DrawViewShell)) { EditMode eEditMode = static_cast<DrawViewShell*>(pViewShell)->GetEditMode(); if (eEditMode == EM_MASTERPAGE) bOnMaster = TRUE; } BOOL bMasterPage = bOnMaster; BOOL bCheckMasters = FALSE; // Dialog aufrufen BOOL bLoad = FALSE; // tauchen neue Masterpages auf? String aFile; SfxItemSet aSet(pDoc->GetPool(), ATTR_PRESLAYOUT_START, ATTR_PRESLAYOUT_END); aSet.Put( SfxBoolItem( ATTR_PRESLAYOUT_LOAD, bLoad)); aSet.Put( SfxBoolItem( ATTR_PRESLAYOUT_MASTER_PAGE, bMasterPage ) ); aSet.Put( SfxBoolItem( ATTR_PRESLAYOUT_CHECK_MASTERS, bCheckMasters ) ); aSet.Put( SfxStringItem( ATTR_PRESLAYOUT_NAME, aOldLayoutName)); //CHINA001 SdPresLayoutDlg* pDlg = new SdPresLayoutDlg( pDocSh, pViewSh, NULL, aSet); SdAbstractDialogFactory* pFact = SdAbstractDialogFactory::Create();//CHINA001 DBG_ASSERT(pFact, "SdAbstractDialogFactory fail!");//CHINA001 AbstractSdPresLayoutDlg* pDlg = pFact->CreateSdPresLayoutDlg(ResId( DLG_PRESLT ), pDocSh, pViewShell, NULL, aSet ); DBG_ASSERT(pDlg, "Dialogdiet fail!");//CHINA001 USHORT nResult = pDlg->Execute(); switch (nResult) { case RET_OK: { pDlg->GetAttr(aSet); if (aSet.GetItemState(ATTR_PRESLAYOUT_LOAD) == SFX_ITEM_SET) bLoad = ((SfxBoolItem&)aSet.Get(ATTR_PRESLAYOUT_LOAD)).GetValue(); if( aSet.GetItemState( ATTR_PRESLAYOUT_MASTER_PAGE ) == SFX_ITEM_SET ) bMasterPage = ( (SfxBoolItem&) aSet.Get( ATTR_PRESLAYOUT_MASTER_PAGE ) ).GetValue(); if( aSet.GetItemState( ATTR_PRESLAYOUT_CHECK_MASTERS ) == SFX_ITEM_SET ) bCheckMasters = ( (SfxBoolItem&) aSet.Get( ATTR_PRESLAYOUT_CHECK_MASTERS ) ).GetValue(); if (aSet.GetItemState(ATTR_PRESLAYOUT_NAME) == SFX_ITEM_SET) aFile = ((SfxStringItem&)aSet.Get(ATTR_PRESLAYOUT_NAME)).GetValue(); } break; default: bError = TRUE; } delete pDlg; if (!bError) { pDocSh->SetWaitCursor( TRUE ); // Hier werden nur Masterpages ausgewechselt, d.h. die aktuelle Seite // bleibt aktuell. Damit beim Ein- und Ausfuegen der Masterpages nicht // dauernd via PageOrderChangedHint die Methode ResetActualPage gerufen // wird, wird jetzt blockiert. // That isn't quitely right. If the masterpageview is active and you are // removing a masterpage, it's possible that you are removing the // current masterpage. So you have to call ResetActualPage ! if( pViewShell->ISA(DrawViewShell) && !bCheckMasters ) static_cast<DrawView*>(pView)->BlockPageOrderChangedHint(TRUE); if (bLoad) { String aFileName = aFile.GetToken( 0, DOCUMENT_TOKEN ); SdDrawDocument* pTempDoc = pDoc->OpenBookmarkDoc( aFileName ); // #69581: If I chosed the standard-template I got no filename and so I get no // SdDrawDocument-Pointer. But the method SetMasterPage is able to handle // a NULL-pointer as a Standard-template ( look at SdDrawDocument::SetMasterPage ) String aLayoutName; if( pTempDoc ) aLayoutName = aFile.GetToken( 1, DOCUMENT_TOKEN ); pDoc->SetMasterPage(nSelectedPage, aLayoutName, pTempDoc, bMasterPage, bCheckMasters); pDoc->CloseBookmarkDoc(); } else { // MasterPage mit dem LayoutNamen aFile aus aktuellem Doc verwenden pDoc->SetMasterPage(nSelectedPage, aFile, pDoc, bMasterPage, bCheckMasters); } // Blockade wieder aufheben if (pViewShell->ISA(DrawViewShell) && !bCheckMasters ) static_cast<DrawView*>(pView)->BlockPageOrderChangedHint(FALSE); /************************************************************************* |* Falls dargestellte Masterpage sichtbar war, neu darstellen \************************************************************************/ if (!bError && nSelectedPage != SDRPAGE_NOTFOUND) { if (bOnMaster) { if (pViewShell->ISA(DrawViewShell)) { ::sd::View* pView = static_cast<DrawViewShell*>(pViewShell)->GetView(); USHORT nPgNum = pSelectedPage->TRG_GetMasterPage().GetPageNum(); if (static_cast<DrawViewShell*>(pViewShell)->GetPageKind() == PK_NOTES) nPgNum++; pView->HideAllPages(); pView->ShowMasterPagePgNum(nPgNum, Point()); } // damit TabBar aktualisiert wird pViewShell->GetViewFrame()->GetDispatcher()->Execute(SID_MASTERPAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD); } else { pSelectedPage->SetAutoLayout(pSelectedPage->GetAutoLayout()); } } // fake a mode change to repaint the page tab bar if( pViewShell && pViewShell->ISA( DrawViewShell ) ) { DrawViewShell* pDrawViewSh = static_cast<DrawViewShell*>(pViewShell); EditMode eMode = pDrawViewSh->GetEditMode(); BOOL bLayer = pDrawViewSh->IsLayerModeActive(); pDrawViewSh->ChangeEditMode( eMode, !bLayer ); pDrawViewSh->ChangeEditMode( eMode, bLayer ); } pDocSh->SetWaitCursor( FALSE ); } } /************************************************************************* |* |* Layoutvorlage von einem StyleSheetPool in einen anderen uebertragen |* \************************************************************************/ void FuPresentationLayout::TransferLayoutTemplate(String aFromName, String aToName, SfxStyleSheetBasePool* pFrom, SfxStyleSheetBasePool* pTo) { SfxStyleSheetBase* pHis = pFrom->Find(aFromName,SD_LT_FAMILY); SfxStyleSheetBase* pMy = pTo->Find(aToName, SD_LT_FAMILY); DBG_ASSERT(pHis, "neue Layoutvorlage nicht gefunden"); // gibt's noch nicht: neu anlegen if (!pMy) { pMy = &(pTo->Make(aToName, SD_LT_FAMILY)); } // Inhalte neu setzen if (pHis) pMy->GetItemSet().Set(pHis->GetItemSet()); } } // end of namespace sd <commit_msg>INTEGRATION: CWS pchfix02 (1.11.212); FILE MERGED 2006/09/01 17:37:09 kaib 1.11.212.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: fuprlout.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: obo $ $Date: 2006-09-16 18:54:10 $ * * 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_sd.hxx" #include "fuprlout.hxx" #ifndef _SV_WRKWIN_HXX #include <vcl/wrkwin.hxx> #endif #ifndef _SFXDISPATCH_HXX //autogen #include <sfx2/dispatch.hxx> #endif #ifndef _SFXSMPLHINT_HXX //autogen #include <svtools/smplhint.hxx> #endif #ifndef _SFXITEMPOOL_HXX //autogen #include <svtools/itempool.hxx> #endif #include <sot/storage.hxx> #ifndef _SV_MSGBOX_HXX //autogen #include <vcl/msgbox.hxx> #endif #ifndef _SVDUNDO_HXX //autogen #include <svx/svdundo.hxx> #endif #include <sfx2/viewfrm.hxx> #include "drawdoc.hxx" #include "sdpage.hxx" #include "pres.hxx" #ifndef SD_DRAW_VIEW_SHELL_HXX #include "DrawViewShell.hxx" #endif #ifndef SD_FRAMW_VIEW_HXX #include "FrameView.hxx" #endif #include "stlpool.hxx" #ifndef SD_VIEW_HXX #include "View.hxx" #endif #include "glob.hrc" #include "glob.hxx" #include "strings.hrc" #include "strmname.h" #include "app.hrc" #include "DrawDocShell.hxx" #include "unprlout.hxx" #include "unchss.hxx" #include "unmovss.hxx" #include "sdattr.hxx" #include "sdresid.hxx" //CHINA001 #include "sdpreslt.hxx" #ifndef SD_DRAW_VIEW_HXX #include "drawview.hxx" #endif #include "eetext.hxx" #include <svx/editdata.hxx> #include "sdabstdlg.hxx" //CHINA001 #include "sdpreslt.hrc" //CHINA001 namespace sd { #ifndef SO2_DECL_SVSTORAGE_DEFINED #define SO2_DECL_SVSTORAGE_DEFINED SO2_DECL_REF(SvStorage) #endif TYPEINIT1( FuPresentationLayout, FuPoor ); #define POOL_BUFFER_SIZE (USHORT)32768 #define DOCUMENT_BUFFER_SIZE (USHORT)32768 #define DOCUMENT_TOKEN (sal_Unicode('#')) /************************************************************************* |* |* Konstruktor |* \************************************************************************/ FuPresentationLayout::FuPresentationLayout ( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq) : FuPoor(pViewSh, pWin, pView, pDoc, rReq) { } FunctionReference FuPresentationLayout::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq ) { FunctionReference xFunc( new FuPresentationLayout( pViewSh, pWin, pView, pDoc, rReq ) ); xFunc->DoExecute(rReq); return xFunc; } void FuPresentationLayout::DoExecute( SfxRequest& rReq ) { // damit nicht Objekte, die gerade editiert werden oder selektiert // sind , verschwinden pView->EndTextEdit(); USHORT nPgViewCount = pView->GetPageViewCount(); for (USHORT nPgView = 0; nPgView < nPgViewCount; nPgView++) { pView->UnmarkAll(); } BOOL bError = FALSE; // die aktive Seite ermitteln USHORT nSelectedPage = SDRPAGE_NOTFOUND; for (USHORT nPage = 0; nPage < pDoc->GetSdPageCount(PK_STANDARD); nPage++) { if (pDoc->GetSdPage(nPage, PK_STANDARD)->IsSelected()) { nSelectedPage = nPage; break; } } DBG_ASSERT(nSelectedPage != SDRPAGE_NOTFOUND, "keine selektierte Seite"); SdPage* pSelectedPage = pDoc->GetSdPage(nSelectedPage, PK_STANDARD); String aOldPageLayoutName(pSelectedPage->GetLayoutName()); String aOldLayoutName(aOldPageLayoutName); aOldLayoutName.Erase(aOldLayoutName.SearchAscii(SD_LT_SEPARATOR)); // wenn wir auf einer Masterpage sind, gelten die Aenderungen fuer alle // Seiten und Notizseiten, die das betreffende Layout benutzen BOOL bOnMaster = FALSE; if( pViewShell && pViewShell->ISA(DrawViewShell)) { EditMode eEditMode = static_cast<DrawViewShell*>(pViewShell)->GetEditMode(); if (eEditMode == EM_MASTERPAGE) bOnMaster = TRUE; } BOOL bMasterPage = bOnMaster; BOOL bCheckMasters = FALSE; // Dialog aufrufen BOOL bLoad = FALSE; // tauchen neue Masterpages auf? String aFile; SfxItemSet aSet(pDoc->GetPool(), ATTR_PRESLAYOUT_START, ATTR_PRESLAYOUT_END); aSet.Put( SfxBoolItem( ATTR_PRESLAYOUT_LOAD, bLoad)); aSet.Put( SfxBoolItem( ATTR_PRESLAYOUT_MASTER_PAGE, bMasterPage ) ); aSet.Put( SfxBoolItem( ATTR_PRESLAYOUT_CHECK_MASTERS, bCheckMasters ) ); aSet.Put( SfxStringItem( ATTR_PRESLAYOUT_NAME, aOldLayoutName)); //CHINA001 SdPresLayoutDlg* pDlg = new SdPresLayoutDlg( pDocSh, pViewSh, NULL, aSet); SdAbstractDialogFactory* pFact = SdAbstractDialogFactory::Create();//CHINA001 DBG_ASSERT(pFact, "SdAbstractDialogFactory fail!");//CHINA001 AbstractSdPresLayoutDlg* pDlg = pFact->CreateSdPresLayoutDlg(ResId( DLG_PRESLT ), pDocSh, pViewShell, NULL, aSet ); DBG_ASSERT(pDlg, "Dialogdiet fail!");//CHINA001 USHORT nResult = pDlg->Execute(); switch (nResult) { case RET_OK: { pDlg->GetAttr(aSet); if (aSet.GetItemState(ATTR_PRESLAYOUT_LOAD) == SFX_ITEM_SET) bLoad = ((SfxBoolItem&)aSet.Get(ATTR_PRESLAYOUT_LOAD)).GetValue(); if( aSet.GetItemState( ATTR_PRESLAYOUT_MASTER_PAGE ) == SFX_ITEM_SET ) bMasterPage = ( (SfxBoolItem&) aSet.Get( ATTR_PRESLAYOUT_MASTER_PAGE ) ).GetValue(); if( aSet.GetItemState( ATTR_PRESLAYOUT_CHECK_MASTERS ) == SFX_ITEM_SET ) bCheckMasters = ( (SfxBoolItem&) aSet.Get( ATTR_PRESLAYOUT_CHECK_MASTERS ) ).GetValue(); if (aSet.GetItemState(ATTR_PRESLAYOUT_NAME) == SFX_ITEM_SET) aFile = ((SfxStringItem&)aSet.Get(ATTR_PRESLAYOUT_NAME)).GetValue(); } break; default: bError = TRUE; } delete pDlg; if (!bError) { pDocSh->SetWaitCursor( TRUE ); // Hier werden nur Masterpages ausgewechselt, d.h. die aktuelle Seite // bleibt aktuell. Damit beim Ein- und Ausfuegen der Masterpages nicht // dauernd via PageOrderChangedHint die Methode ResetActualPage gerufen // wird, wird jetzt blockiert. // That isn't quitely right. If the masterpageview is active and you are // removing a masterpage, it's possible that you are removing the // current masterpage. So you have to call ResetActualPage ! if( pViewShell->ISA(DrawViewShell) && !bCheckMasters ) static_cast<DrawView*>(pView)->BlockPageOrderChangedHint(TRUE); if (bLoad) { String aFileName = aFile.GetToken( 0, DOCUMENT_TOKEN ); SdDrawDocument* pTempDoc = pDoc->OpenBookmarkDoc( aFileName ); // #69581: If I chosed the standard-template I got no filename and so I get no // SdDrawDocument-Pointer. But the method SetMasterPage is able to handle // a NULL-pointer as a Standard-template ( look at SdDrawDocument::SetMasterPage ) String aLayoutName; if( pTempDoc ) aLayoutName = aFile.GetToken( 1, DOCUMENT_TOKEN ); pDoc->SetMasterPage(nSelectedPage, aLayoutName, pTempDoc, bMasterPage, bCheckMasters); pDoc->CloseBookmarkDoc(); } else { // MasterPage mit dem LayoutNamen aFile aus aktuellem Doc verwenden pDoc->SetMasterPage(nSelectedPage, aFile, pDoc, bMasterPage, bCheckMasters); } // Blockade wieder aufheben if (pViewShell->ISA(DrawViewShell) && !bCheckMasters ) static_cast<DrawView*>(pView)->BlockPageOrderChangedHint(FALSE); /************************************************************************* |* Falls dargestellte Masterpage sichtbar war, neu darstellen \************************************************************************/ if (!bError && nSelectedPage != SDRPAGE_NOTFOUND) { if (bOnMaster) { if (pViewShell->ISA(DrawViewShell)) { ::sd::View* pView = static_cast<DrawViewShell*>(pViewShell)->GetView(); USHORT nPgNum = pSelectedPage->TRG_GetMasterPage().GetPageNum(); if (static_cast<DrawViewShell*>(pViewShell)->GetPageKind() == PK_NOTES) nPgNum++; pView->HideAllPages(); pView->ShowMasterPagePgNum(nPgNum, Point()); } // damit TabBar aktualisiert wird pViewShell->GetViewFrame()->GetDispatcher()->Execute(SID_MASTERPAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD); } else { pSelectedPage->SetAutoLayout(pSelectedPage->GetAutoLayout()); } } // fake a mode change to repaint the page tab bar if( pViewShell && pViewShell->ISA( DrawViewShell ) ) { DrawViewShell* pDrawViewSh = static_cast<DrawViewShell*>(pViewShell); EditMode eMode = pDrawViewSh->GetEditMode(); BOOL bLayer = pDrawViewSh->IsLayerModeActive(); pDrawViewSh->ChangeEditMode( eMode, !bLayer ); pDrawViewSh->ChangeEditMode( eMode, bLayer ); } pDocSh->SetWaitCursor( FALSE ); } } /************************************************************************* |* |* Layoutvorlage von einem StyleSheetPool in einen anderen uebertragen |* \************************************************************************/ void FuPresentationLayout::TransferLayoutTemplate(String aFromName, String aToName, SfxStyleSheetBasePool* pFrom, SfxStyleSheetBasePool* pTo) { SfxStyleSheetBase* pHis = pFrom->Find(aFromName,SD_LT_FAMILY); SfxStyleSheetBase* pMy = pTo->Find(aToName, SD_LT_FAMILY); DBG_ASSERT(pHis, "neue Layoutvorlage nicht gefunden"); // gibt's noch nicht: neu anlegen if (!pMy) { pMy = &(pTo->Make(aToName, SD_LT_FAMILY)); } // Inhalte neu setzen if (pHis) pMy->GetItemSet().Set(pHis->GetItemSet()); } } // end of namespace sd <|endoftext|>
<commit_before>#include "CoreAudio.h" #include "Functiondiscoverykeys_devpkey.h" #include "../../Logger.h" // {EC9CB649-7E84-4B42-B367-7FC39BE17806} static const GUID G3RVXCoreAudioEvent = { 0xec9cb649, 0x7e84, 0x4b42, { 0xb3, 0x67, 0x7f, 0xc3, 0x9b, 0xe1, 0x78, 0x6 } }; HRESULT CoreAudio::Init() { HRESULT hr; hr = CoCreateInstance( __uuidof(MMDeviceEnumerator), NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&_devEnumerator)); if (SUCCEEDED(hr)) { hr = _devEnumerator->RegisterEndpointNotificationCallback(this); if (SUCCEEDED(hr)) { hr = AttachDevice(); } } return hr; } HRESULT CoreAudio::Init(std::wstring deviceId) { _devId = deviceId; return Init(); } void CoreAudio::Dispose() { DetachDevice(); _devEnumerator->UnregisterEndpointNotificationCallback(this); } HRESULT CoreAudio::AttachDevice() { HRESULT hr; if (_devId.empty()) { /* Use default device */ hr = _devEnumerator->GetDefaultAudioEndpoint(eRender, eMultimedia, &_device); if (SUCCEEDED(hr)) { LPWSTR id; _device->GetId(&id); _devId = std::wstring(id); } } else { hr = _devEnumerator->GetDevice(_devId.c_str(), &_device); } if (SUCCEEDED(hr)) { hr = _device->Activate(__uuidof(_volumeControl), CLSCTX_INPROC_SERVER, NULL, (void **) &_volumeControl); CLOG(L"Attached to audio device: [%s]", DeviceName().c_str()); if (SUCCEEDED(hr)) { hr = _volumeControl->RegisterControlChangeNotify(this); _registeredNotifications = SUCCEEDED(hr); } } else { CLOG(L"Failed to find audio device!"); } return hr; } void CoreAudio::DetachDevice() { if (_volumeControl != NULL) { if (_registeredNotifications) { _volumeControl->UnregisterControlChangeNotify(this); _registeredNotifications = false; } _volumeControl->Release(); } if (_device != NULL) { _device->Release(); } } HRESULT CoreAudio::OnNotify(PAUDIO_VOLUME_NOTIFICATION_DATA pNotify) { if (pNotify->guidEventContext == G3RVXCoreAudioEvent) { PostMessage(_notifyHwnd, MSG_VOL_CHNG, (WPARAM) 1, NULL); } else { PostMessage(_notifyHwnd, MSG_VOL_CHNG, NULL, NULL); } return S_OK; } HRESULT CoreAudio::OnDefaultDeviceChanged( EDataFlow flow, ERole role, LPCWSTR pwstrDefaultDeviceId) { if (flow == eRender) { PostMessage(_notifyHwnd, MSG_VOL_DEVCHNG, 0, 0); } return S_OK; } HRESULT CoreAudio::SelectDevice(std::wstring deviceId) { HRESULT hr; _devId = deviceId; DetachDevice(); hr = AttachDevice(); return hr; } HRESULT CoreAudio::SelectDefaultDevice() { HRESULT hr; _devId = L""; DetachDevice(); hr = AttachDevice(); return hr; } std::list<VolumeController::DeviceInfo> CoreAudio::ListDevices() { std::list<VolumeController::DeviceInfo> devList; IMMDeviceCollection *devices; HRESULT hr = _devEnumerator->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE | DEVICE_STATE_UNPLUGGED, &devices); if (FAILED(hr)) { devices->Release(); return devList; } UINT numDevices = 0; devices->GetCount(&numDevices); LPWSTR devId; for (unsigned int i = 0; i < numDevices; ++i) { IMMDevice *device; HRESULT hr = devices->Item(i, &device); if (FAILED(hr)) { continue; } device->GetId(&devId); std::wstring idStr(devId); VolumeController::DeviceInfo devInfo = {}; devInfo.id = idStr; devInfo.name = DeviceName(idStr); devList.push_back(devInfo); device->Release(); } devices->Release(); return devList; } std::wstring CoreAudio::DeviceId() { return _devId; } std::wstring CoreAudio::DeviceName() { return DeviceName(_device); } std::wstring CoreAudio::DeviceDesc() { return DeviceDesc(_device); } std::wstring CoreAudio::DeviceName(std::wstring deviceId) { IMMDevice *device; HRESULT hr = _devEnumerator->GetDevice(deviceId.c_str(), &device); if (FAILED(hr)) { return L""; } std::wstring name = DeviceName(device); device->Release(); return name; } std::wstring CoreAudio::DeviceDesc(std::wstring deviceId) { IMMDevice *device; HRESULT hr = _devEnumerator->GetDevice(deviceId.c_str(), &device); if (FAILED(hr)) { return L""; } std::wstring name = DeviceName(device); device->Release(); return name; } std::wstring CoreAudio::DeviceName(IMMDevice *device) { if (device == NULL) { return L""; } IPropertyStore *props = NULL; HRESULT hr = device->OpenPropertyStore(STGM_READ, &props); if (FAILED(hr)) { return L""; } PROPVARIANT pvName; PropVariantInit(&pvName); props->GetValue(PKEY_Device_FriendlyName, &pvName); std::wstring str(pvName.pwszVal); PropVariantClear(&pvName); props->Release(); return str; } std::wstring CoreAudio::DeviceDesc(IMMDevice *device) { if (device == NULL) { return L""; } IPropertyStore *props = NULL; HRESULT hr = device->OpenPropertyStore(STGM_READ, &props); if (FAILED(hr)) { return L""; } PROPVARIANT pvDesc; PropVariantInit(&pvDesc); props->GetValue(PKEY_Device_DeviceDesc, &pvDesc); std::wstring str(pvDesc.pwszVal); PropVariantClear(&pvDesc); props->Release(); return str; } float CoreAudio::Volume() { float vol = 0.0f; if (_volumeControl) { _volumeControl->GetMasterVolumeLevelScalar(&vol); } return vol; } void CoreAudio::Volume(float vol) { if (vol > 1.0f) { vol = 1.0f; } if (vol < 0.0f) { vol = 0.0f; } if (_volumeControl) { _volumeControl->SetMasterVolumeLevelScalar(vol, &G3RVXCoreAudioEvent); } } bool CoreAudio::Muted() { if (_volumeControl == NULL) { return true; } BOOL muted = FALSE; _volumeControl->GetMute(&muted); return (muted == TRUE) ? true : false; } void CoreAudio::Muted(bool muted) { if (_volumeControl) { _volumeControl->SetMute(muted, &G3RVXCoreAudioEvent); } } ULONG CoreAudio::AddRef() { return InterlockedIncrement(&_refCount); } ULONG CoreAudio::Release() { long lRef = InterlockedDecrement(&_refCount); if (lRef == 0) { delete this; } return lRef; } HRESULT CoreAudio::QueryInterface(REFIID iid, void **ppUnk) { if ((iid == __uuidof(IUnknown)) || (iid == __uuidof(IMMNotificationClient))) { *ppUnk = static_cast<IMMNotificationClient*>(this); } else if (iid == __uuidof(IAudioEndpointVolumeCallback)) { *ppUnk = static_cast<IAudioEndpointVolumeCallback*>(this); } else { *ppUnk = NULL; return E_NOINTERFACE; } AddRef(); return S_OK; }<commit_msg>Fix memory leaks<commit_after>#include "CoreAudio.h" #include "Functiondiscoverykeys_devpkey.h" #include "../../Logger.h" // {EC9CB649-7E84-4B42-B367-7FC39BE17806} static const GUID G3RVXCoreAudioEvent = { 0xec9cb649, 0x7e84, 0x4b42, { 0xb3, 0x67, 0x7f, 0xc3, 0x9b, 0xe1, 0x78, 0x6 } }; HRESULT CoreAudio::Init() { HRESULT hr; hr = CoCreateInstance( __uuidof(MMDeviceEnumerator), NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&_devEnumerator)); if (SUCCEEDED(hr)) { hr = _devEnumerator->RegisterEndpointNotificationCallback(this); if (SUCCEEDED(hr)) { hr = AttachDevice(); } } return hr; } HRESULT CoreAudio::Init(std::wstring deviceId) { _devId = deviceId; return Init(); } void CoreAudio::Dispose() { DetachDevice(); _devEnumerator->UnregisterEndpointNotificationCallback(this); } HRESULT CoreAudio::AttachDevice() { HRESULT hr; if (_devId.empty()) { /* Use default device */ hr = _devEnumerator->GetDefaultAudioEndpoint(eRender, eMultimedia, &_device); if (SUCCEEDED(hr)) { LPWSTR id = NULL; _device->GetId(&id); if (id) { _devId = std::wstring(id); CoTaskMemFree(id); } } } else { hr = _devEnumerator->GetDevice(_devId.c_str(), &_device); } if (SUCCEEDED(hr)) { hr = _device->Activate(__uuidof(_volumeControl), CLSCTX_INPROC_SERVER, NULL, (void **) &_volumeControl); CLOG(L"Attached to audio device: [%s]", DeviceName().c_str()); if (SUCCEEDED(hr)) { hr = _volumeControl->RegisterControlChangeNotify(this); _registeredNotifications = SUCCEEDED(hr); } } else { CLOG(L"Failed to find audio device!"); } return hr; } void CoreAudio::DetachDevice() { if (_volumeControl != NULL) { if (_registeredNotifications) { _volumeControl->UnregisterControlChangeNotify(this); _registeredNotifications = false; } _volumeControl->Release(); } if (_device != NULL) { _device->Release(); } } HRESULT CoreAudio::OnNotify(PAUDIO_VOLUME_NOTIFICATION_DATA pNotify) { if (pNotify->guidEventContext == G3RVXCoreAudioEvent) { PostMessage(_notifyHwnd, MSG_VOL_CHNG, (WPARAM) 1, NULL); } else { PostMessage(_notifyHwnd, MSG_VOL_CHNG, NULL, NULL); } return S_OK; } HRESULT CoreAudio::OnDefaultDeviceChanged( EDataFlow flow, ERole role, LPCWSTR pwstrDefaultDeviceId) { if (flow == eRender) { PostMessage(_notifyHwnd, MSG_VOL_DEVCHNG, 0, 0); } return S_OK; } HRESULT CoreAudio::SelectDevice(std::wstring deviceId) { HRESULT hr; _devId = deviceId; DetachDevice(); hr = AttachDevice(); return hr; } HRESULT CoreAudio::SelectDefaultDevice() { HRESULT hr; _devId = L""; DetachDevice(); hr = AttachDevice(); return hr; } std::list<VolumeController::DeviceInfo> CoreAudio::ListDevices() { std::list<VolumeController::DeviceInfo> devList; IMMDeviceCollection *devices = NULL; HRESULT hr = _devEnumerator->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE | DEVICE_STATE_UNPLUGGED, &devices); if (FAILED(hr)) { if (devices) { devices->Release(); } return devList; } UINT numDevices = 0; devices->GetCount(&numDevices); LPWSTR devId; for (unsigned int i = 0; i < numDevices; ++i) { IMMDevice *device = NULL; HRESULT hr = devices->Item(i, &device); if (FAILED(hr)) { if (device) { device->Release(); } continue; } device->GetId(&devId); std::wstring idStr; if (devId) { idStr = std::wstring(devId); CoTaskMemFree(devId); } else { continue; } VolumeController::DeviceInfo devInfo = {}; devInfo.id = idStr; devInfo.name = DeviceName(idStr); devList.push_back(devInfo); device->Release(); } devices->Release(); return devList; } std::wstring CoreAudio::DeviceId() { return _devId; } std::wstring CoreAudio::DeviceName() { return DeviceName(_device); } std::wstring CoreAudio::DeviceDesc() { return DeviceDesc(_device); } std::wstring CoreAudio::DeviceName(std::wstring deviceId) { IMMDevice *device; HRESULT hr = _devEnumerator->GetDevice(deviceId.c_str(), &device); if (FAILED(hr)) { return L""; } std::wstring name = DeviceName(device); device->Release(); return name; } std::wstring CoreAudio::DeviceDesc(std::wstring deviceId) { IMMDevice *device; HRESULT hr = _devEnumerator->GetDevice(deviceId.c_str(), &device); if (FAILED(hr)) { return L""; } std::wstring name = DeviceName(device); device->Release(); return name; } std::wstring CoreAudio::DeviceName(IMMDevice *device) { if (device == NULL) { return L""; } IPropertyStore *props = NULL; HRESULT hr = device->OpenPropertyStore(STGM_READ, &props); if (FAILED(hr)) { return L""; } PROPVARIANT pvName; PropVariantInit(&pvName); props->GetValue(PKEY_Device_FriendlyName, &pvName); std::wstring str(pvName.pwszVal); PropVariantClear(&pvName); props->Release(); return str; } std::wstring CoreAudio::DeviceDesc(IMMDevice *device) { if (device == NULL) { return L""; } IPropertyStore *props = NULL; HRESULT hr = device->OpenPropertyStore(STGM_READ, &props); if (FAILED(hr)) { return L""; } PROPVARIANT pvDesc; PropVariantInit(&pvDesc); props->GetValue(PKEY_Device_DeviceDesc, &pvDesc); std::wstring str(pvDesc.pwszVal); PropVariantClear(&pvDesc); props->Release(); return str; } float CoreAudio::Volume() { float vol = 0.0f; if (_volumeControl) { _volumeControl->GetMasterVolumeLevelScalar(&vol); } return vol; } void CoreAudio::Volume(float vol) { if (vol > 1.0f) { vol = 1.0f; } if (vol < 0.0f) { vol = 0.0f; } if (_volumeControl) { _volumeControl->SetMasterVolumeLevelScalar(vol, &G3RVXCoreAudioEvent); } } bool CoreAudio::Muted() { if (_volumeControl == NULL) { return true; } BOOL muted = FALSE; _volumeControl->GetMute(&muted); return (muted == TRUE) ? true : false; } void CoreAudio::Muted(bool muted) { if (_volumeControl) { _volumeControl->SetMute(muted, &G3RVXCoreAudioEvent); } } ULONG CoreAudio::AddRef() { return InterlockedIncrement(&_refCount); } ULONG CoreAudio::Release() { long lRef = InterlockedDecrement(&_refCount); if (lRef == 0) { delete this; } return lRef; } HRESULT CoreAudio::QueryInterface(REFIID iid, void **ppUnk) { if ((iid == __uuidof(IUnknown)) || (iid == __uuidof(IMMNotificationClient))) { *ppUnk = static_cast<IMMNotificationClient*>(this); } else if (iid == __uuidof(IAudioEndpointVolumeCallback)) { *ppUnk = static_cast<IAudioEndpointVolumeCallback*>(this); } else { *ppUnk = NULL; return E_NOINTERFACE; } AddRef(); return S_OK; }<|endoftext|>
<commit_before>#include "CoreAudio.h" #include "Functiondiscoverykeys_devpkey.h" #include "../../Logger.h" HRESULT CoreAudio::Init() { HRESULT hr; hr = _devEnumerator.CoCreateInstance(__uuidof(MMDeviceEnumerator)); if (SUCCEEDED(hr)) { hr = _devEnumerator->RegisterEndpointNotificationCallback(this); if (SUCCEEDED(hr)) { hr = AttachDevice(); } } return hr; } HRESULT CoreAudio::Init(std::wstring deviceId) { _devId = deviceId; return Init(); } void CoreAudio::Dispose() { DetachDevice(); _devEnumerator->UnregisterEndpointNotificationCallback(this); } HRESULT CoreAudio::AttachDevice() { _critSect.Enter(); HRESULT hr; if (_devId.empty()) { /* Use default device */ hr = _devEnumerator->GetDefaultAudioEndpoint(eRender, eMultimedia, &_device); } else { hr = _devEnumerator->GetDevice(_devId.c_str(), &_device); } if (SUCCEEDED(hr)) { hr = _device->Activate(__uuidof(_volumeControl), CLSCTX_INPROC_SERVER, NULL, (void **) &_volumeControl); CLOG(L"Attached to audio device: [%s]", DeviceName().c_str()); if (SUCCEEDED(hr)) { hr = _volumeControl->RegisterControlChangeNotify(this); _registeredNotifications = SUCCEEDED(hr); } } else { CLOG(L"Failed to find audio device!"); } _critSect.Leave(); return hr; } void CoreAudio::DetachDevice() { _critSect.Enter(); if (_volumeControl != NULL) { if (_registeredNotifications) { _volumeControl->UnregisterControlChangeNotify(this); _registeredNotifications = false; } _volumeControl.Release(); } if (_device != NULL) { _device.Release(); } _critSect.Leave(); } HRESULT CoreAudio::OnNotify(PAUDIO_VOLUME_NOTIFICATION_DATA pNotify) { PostMessage(_notifyHwnd, MSG_VOL_CHNG, 0, 0); return S_OK; } HRESULT CoreAudio::OnDefaultDeviceChanged( EDataFlow flow, ERole role, LPCWSTR pwstrDefaultDeviceId) { if (flow == eRender) { PostMessage(_notifyHwnd, MSG_VOL_DEVCHNG, 0, 0); } return S_OK; } HRESULT CoreAudio::SelectDevice(std::wstring deviceId) { HRESULT hr; _devId = deviceId; DetachDevice(); hr = AttachDevice(); return hr; } HRESULT CoreAudio::SelectDefaultDevice() { HRESULT hr; _devId = L""; DetachDevice(); hr = AttachDevice(); return hr; } std::list<VolumeController::DeviceInfo> CoreAudio::ListDevices() { _critSect.Enter(); CComPtr<IMMDeviceCollection> devices; _devEnumerator->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE | DEVICE_STATE_UNPLUGGED, &devices); UINT numDevices = 0; devices->GetCount(&numDevices); CComPtr<IMMDevice> device; LPWSTR devId; std::list<VolumeController::DeviceInfo> devList; for (unsigned int i = 0; i < numDevices; ++i) { devices->Item(i, &device); device->GetId(&devId); std::wstring idStr(devId); VolumeController::DeviceInfo devInfo = {}; devInfo.id = idStr; devInfo.name = DeviceName(idStr); devList.push_back(devInfo); } return devList; _critSect.Leave(); } std::wstring CoreAudio::DeviceId() { return _devId; } std::wstring CoreAudio::DeviceName() { return DeviceName(_device); } std::wstring CoreAudio::DeviceName(std::wstring deviceId) { CComPtr<IMMDevice> device; _devEnumerator->GetDevice(deviceId.c_str(), &device); return DeviceName(device); } std::wstring CoreAudio::DeviceName(CComPtr<IMMDevice> device) { IPropertyStore *props = NULL; HRESULT hr = _device->OpenPropertyStore(STGM_READ, &props); if (FAILED(hr)) { return L""; } PROPVARIANT pvName; PropVariantInit(&pvName); props->GetValue(PKEY_Device_FriendlyName, &pvName); std::wstring str(pvName.pwszVal); PropVariantClear(&pvName); props->Release(); return str; } float CoreAudio::Volume() { float vol = 0.0f; _volumeControl->GetMasterVolumeLevelScalar(&vol); return vol; } void CoreAudio::Volume(float vol) { if (vol > 1.0f) { vol = 1.0f; } if (vol < 0.0f) { vol = 0.0f; } _volumeControl->SetMasterVolumeLevelScalar(vol, NULL); } bool CoreAudio::Muted() { BOOL muted = FALSE; _volumeControl->GetMute(&muted); return (muted == TRUE) ? true : false; } void CoreAudio::Muted(bool muted) { _volumeControl->SetMute(muted, NULL); } ULONG CoreAudio::AddRef() { return InterlockedIncrement(&_refCount); } ULONG CoreAudio::Release() { long lRef = InterlockedDecrement(&_refCount); if (lRef == 0) { delete this; } return lRef; } HRESULT CoreAudio::QueryInterface(REFIID iid, void **ppUnk) { if ((iid == __uuidof(IUnknown)) || (iid == __uuidof(IMMNotificationClient))) { *ppUnk = static_cast<IMMNotificationClient*>(this); } else if (iid == __uuidof(IAudioEndpointVolumeCallback)) { *ppUnk = static_cast<IAudioEndpointVolumeCallback*>(this); } else { *ppUnk = NULL; return E_NOINTERFACE; } AddRef(); return S_OK; }<commit_msg>Use *local* parameter, not member var<commit_after>#include "CoreAudio.h" #include "Functiondiscoverykeys_devpkey.h" #include "../../Logger.h" HRESULT CoreAudio::Init() { HRESULT hr; hr = _devEnumerator.CoCreateInstance(__uuidof(MMDeviceEnumerator)); if (SUCCEEDED(hr)) { hr = _devEnumerator->RegisterEndpointNotificationCallback(this); if (SUCCEEDED(hr)) { hr = AttachDevice(); } } return hr; } HRESULT CoreAudio::Init(std::wstring deviceId) { _devId = deviceId; return Init(); } void CoreAudio::Dispose() { DetachDevice(); _devEnumerator->UnregisterEndpointNotificationCallback(this); } HRESULT CoreAudio::AttachDevice() { _critSect.Enter(); HRESULT hr; if (_devId.empty()) { /* Use default device */ hr = _devEnumerator->GetDefaultAudioEndpoint(eRender, eMultimedia, &_device); } else { hr = _devEnumerator->GetDevice(_devId.c_str(), &_device); } if (SUCCEEDED(hr)) { hr = _device->Activate(__uuidof(_volumeControl), CLSCTX_INPROC_SERVER, NULL, (void **) &_volumeControl); CLOG(L"Attached to audio device: [%s]", DeviceName().c_str()); if (SUCCEEDED(hr)) { hr = _volumeControl->RegisterControlChangeNotify(this); _registeredNotifications = SUCCEEDED(hr); } } else { CLOG(L"Failed to find audio device!"); } _critSect.Leave(); return hr; } void CoreAudio::DetachDevice() { _critSect.Enter(); if (_volumeControl != NULL) { if (_registeredNotifications) { _volumeControl->UnregisterControlChangeNotify(this); _registeredNotifications = false; } _volumeControl.Release(); } if (_device != NULL) { _device.Release(); } _critSect.Leave(); } HRESULT CoreAudio::OnNotify(PAUDIO_VOLUME_NOTIFICATION_DATA pNotify) { PostMessage(_notifyHwnd, MSG_VOL_CHNG, 0, 0); return S_OK; } HRESULT CoreAudio::OnDefaultDeviceChanged( EDataFlow flow, ERole role, LPCWSTR pwstrDefaultDeviceId) { if (flow == eRender) { PostMessage(_notifyHwnd, MSG_VOL_DEVCHNG, 0, 0); } return S_OK; } HRESULT CoreAudio::SelectDevice(std::wstring deviceId) { HRESULT hr; _devId = deviceId; DetachDevice(); hr = AttachDevice(); return hr; } HRESULT CoreAudio::SelectDefaultDevice() { HRESULT hr; _devId = L""; DetachDevice(); hr = AttachDevice(); return hr; } std::list<VolumeController::DeviceInfo> CoreAudio::ListDevices() { _critSect.Enter(); CComPtr<IMMDeviceCollection> devices; _devEnumerator->EnumAudioEndpoints( eRender, DEVICE_STATE_ACTIVE | DEVICE_STATE_UNPLUGGED, &devices); UINT numDevices = 0; devices->GetCount(&numDevices); CComPtr<IMMDevice> device; LPWSTR devId; std::list<VolumeController::DeviceInfo> devList; for (unsigned int i = 0; i < numDevices; ++i) { devices->Item(i, &device); device->GetId(&devId); std::wstring idStr(devId); VolumeController::DeviceInfo devInfo = {}; devInfo.id = idStr; devInfo.name = DeviceName(idStr); devList.push_back(devInfo); } return devList; _critSect.Leave(); } std::wstring CoreAudio::DeviceId() { return _devId; } std::wstring CoreAudio::DeviceName() { return DeviceName(_device); } std::wstring CoreAudio::DeviceName(std::wstring deviceId) { CComPtr<IMMDevice> device; _devEnumerator->GetDevice(deviceId.c_str(), &device); return DeviceName(device); } std::wstring CoreAudio::DeviceName(CComPtr<IMMDevice> device) { IPropertyStore *props = NULL; HRESULT hr = device->OpenPropertyStore(STGM_READ, &props); if (FAILED(hr)) { return L""; } PROPVARIANT pvName; PropVariantInit(&pvName); props->GetValue(PKEY_Device_FriendlyName, &pvName); std::wstring str(pvName.pwszVal); PropVariantClear(&pvName); props->Release(); return str; } float CoreAudio::Volume() { float vol = 0.0f; _volumeControl->GetMasterVolumeLevelScalar(&vol); return vol; } void CoreAudio::Volume(float vol) { if (vol > 1.0f) { vol = 1.0f; } if (vol < 0.0f) { vol = 0.0f; } _volumeControl->SetMasterVolumeLevelScalar(vol, NULL); } bool CoreAudio::Muted() { BOOL muted = FALSE; _volumeControl->GetMute(&muted); return (muted == TRUE) ? true : false; } void CoreAudio::Muted(bool muted) { _volumeControl->SetMute(muted, NULL); } ULONG CoreAudio::AddRef() { return InterlockedIncrement(&_refCount); } ULONG CoreAudio::Release() { long lRef = InterlockedDecrement(&_refCount); if (lRef == 0) { delete this; } return lRef; } HRESULT CoreAudio::QueryInterface(REFIID iid, void **ppUnk) { if ((iid == __uuidof(IUnknown)) || (iid == __uuidof(IMMNotificationClient))) { *ppUnk = static_cast<IMMNotificationClient*>(this); } else if (iid == __uuidof(IAudioEndpointVolumeCallback)) { *ppUnk = static_cast<IAudioEndpointVolumeCallback*>(this); } else { *ppUnk = NULL; return E_NOINTERFACE; } AddRef(); return S_OK; }<|endoftext|>
<commit_before>/* * Copyright 2015 Cloudius Systems */ #pragma once #include "http/httpd.hh" #include "json/json_elements.hh" #include "database.hh" #include "service/storage_proxy.hh" #include <boost/lexical_cast.hpp> #include <boost/algorithm/string/split.hpp> #include <boost/algorithm/string/classification.hpp> #include "api/api-doc/utils.json.hh" #include "utils/histogram.hh" namespace api { struct http_context { sstring api_dir; httpd::http_server_control http_server; distributed<database>& db; distributed<service::storage_proxy>& sp; http_context(distributed<database>& _db, distributed<service::storage_proxy>& _sp) : db(_db), sp(_sp) {} }; future<> set_server(http_context& ctx); template<class T> std::vector<sstring> container_to_vec(const T& container) { std::vector<sstring> res; for (auto i : container) { res.push_back(boost::lexical_cast<std::string>(i)); } return res; } template<class T> std::vector<T> map_to_key_value(const std::map<sstring, sstring>& map) { std::vector<T> res; for (auto i : map) { res.push_back(T()); res.back().key = i.first; res.back().value = i.second; } return res; } template<class T, class MAP> std::vector<T>& map_to_key_value(const MAP& map, std::vector<T>& res) { for (auto i : map) { T val; val.key = boost::lexical_cast<std::string>(i.first); val.value = boost::lexical_cast<std::string>(i.second); res.push_back(val); } return res; } template <typename T, typename S = T> T map_sum(T&& dest, const S& src) { for (auto i : src) { dest[i.first] += i.second; } return dest; } template <typename MAP> std::vector<sstring> map_keys(const MAP& map) { std::vector<sstring> res; for (const auto& i : map) { res.push_back(boost::lexical_cast<std::string>(i.first)); } return res; } /** * General sstring splitting function */ inline std::vector<sstring> split(const sstring& text, const char* separator) { if (text == "") { return std::vector<sstring>(); } std::vector<sstring> tokens; return boost::split(tokens, text, boost::is_any_of(separator)); } /** * Split a column family parameter */ inline std::vector<sstring> split_cf(const sstring& cf) { return split(cf, ","); } /** * A helper function to sum values on an a distributed object that * has a get_stats method. * */ template<class T, class F, class V> future<json::json_return_type> sum_stats(distributed<T>& d, V F::*f) { return d.map_reduce0([f](const T& p) {return p.get_stats().*f;}, 0, std::plus<V>()).then([](V val) { return make_ready_future<json::json_return_type>(val); }); } inline double pow2(double a) { return a * a; } inline httpd::utils_json::histogram add_histogram(httpd::utils_json::histogram res, const utils::ihistogram& val) { if (!res.count._set) { res = val; return res; } if (val.count == 0) { return res; } if (res.min() > val.min) { res.min = val.min; } if (res.max() < val.max) { res.max = val.max; } double ncount = res.count() + val.count; res.sum = res.sum() + val.sum; double a = res.count()/ncount; double b = val.count/ncount; double mean = a * res.mean() + b * val.mean; res.variance = (res.variance() + pow2(res.mean() - mean) )* a + (val.variance + pow2(val.mean -mean))* b; res.mean = mean; res.count = res.count() + val.count; for (auto i : val.sample) { res.sample.push(i); } return res; } template<class T, class F> future<json::json_return_type> sum_histogram_stats(distributed<T>& d, utils::ihistogram F::*f) { return d.map_reduce0([f](const T& p) {return p.get_stats().*f;}, httpd::utils_json::histogram(), add_histogram).then([](const httpd::utils_json::histogram& val) { return make_ready_future<json::json_return_type>(val); }); } inline int64_t min_int64(int64_t a, int64_t b) { return std::min(a,b); } inline int64_t max_int64(int64_t a, int64_t b) { return std::max(a,b); } } <commit_msg>API: Add the ratio_holder helper struct to ratio calculation<commit_after>/* * Copyright 2015 Cloudius Systems */ #pragma once #include "http/httpd.hh" #include "json/json_elements.hh" #include "database.hh" #include "service/storage_proxy.hh" #include <boost/lexical_cast.hpp> #include <boost/algorithm/string/split.hpp> #include <boost/algorithm/string/classification.hpp> #include "api/api-doc/utils.json.hh" #include "utils/histogram.hh" namespace api { struct http_context { sstring api_dir; httpd::http_server_control http_server; distributed<database>& db; distributed<service::storage_proxy>& sp; http_context(distributed<database>& _db, distributed<service::storage_proxy>& _sp) : db(_db), sp(_sp) {} }; future<> set_server(http_context& ctx); template<class T> std::vector<sstring> container_to_vec(const T& container) { std::vector<sstring> res; for (auto i : container) { res.push_back(boost::lexical_cast<std::string>(i)); } return res; } template<class T> std::vector<T> map_to_key_value(const std::map<sstring, sstring>& map) { std::vector<T> res; for (auto i : map) { res.push_back(T()); res.back().key = i.first; res.back().value = i.second; } return res; } template<class T, class MAP> std::vector<T>& map_to_key_value(const MAP& map, std::vector<T>& res) { for (auto i : map) { T val; val.key = boost::lexical_cast<std::string>(i.first); val.value = boost::lexical_cast<std::string>(i.second); res.push_back(val); } return res; } template <typename T, typename S = T> T map_sum(T&& dest, const S& src) { for (auto i : src) { dest[i.first] += i.second; } return dest; } template <typename MAP> std::vector<sstring> map_keys(const MAP& map) { std::vector<sstring> res; for (const auto& i : map) { res.push_back(boost::lexical_cast<std::string>(i.first)); } return res; } /** * General sstring splitting function */ inline std::vector<sstring> split(const sstring& text, const char* separator) { if (text == "") { return std::vector<sstring>(); } std::vector<sstring> tokens; return boost::split(tokens, text, boost::is_any_of(separator)); } /** * Split a column family parameter */ inline std::vector<sstring> split_cf(const sstring& cf) { return split(cf, ","); } /** * A helper function to sum values on an a distributed object that * has a get_stats method. * */ template<class T, class F, class V> future<json::json_return_type> sum_stats(distributed<T>& d, V F::*f) { return d.map_reduce0([f](const T& p) {return p.get_stats().*f;}, 0, std::plus<V>()).then([](V val) { return make_ready_future<json::json_return_type>(val); }); } inline double pow2(double a) { return a * a; } inline httpd::utils_json::histogram add_histogram(httpd::utils_json::histogram res, const utils::ihistogram& val) { if (!res.count._set) { res = val; return res; } if (val.count == 0) { return res; } if (res.min() > val.min) { res.min = val.min; } if (res.max() < val.max) { res.max = val.max; } double ncount = res.count() + val.count; res.sum = res.sum() + val.sum; double a = res.count()/ncount; double b = val.count/ncount; double mean = a * res.mean() + b * val.mean; res.variance = (res.variance() + pow2(res.mean() - mean) )* a + (val.variance + pow2(val.mean -mean))* b; res.mean = mean; res.count = res.count() + val.count; for (auto i : val.sample) { res.sample.push(i); } return res; } template<class T, class F> future<json::json_return_type> sum_histogram_stats(distributed<T>& d, utils::ihistogram F::*f) { return d.map_reduce0([f](const T& p) {return p.get_stats().*f;}, httpd::utils_json::histogram(), add_histogram).then([](const httpd::utils_json::histogram& val) { return make_ready_future<json::json_return_type>(val); }); } inline int64_t min_int64(int64_t a, int64_t b) { return std::min(a,b); } inline int64_t max_int64(int64_t a, int64_t b) { return std::max(a,b); } /** * A helper struct for ratio calculation * It combine total and the sub set for the ratio and its * to_json method return the ration sub/total */ struct ratio_holder : public json::jsonable { double total = 0; double sub = 0; virtual std::string to_json() const { if (total == 0) { return "0"; } return std::to_string(sub/total); } ratio_holder() = default; ratio_holder& add(double _total, double _sub) { total += _total; sub += _sub; return *this; } ratio_holder(double _total, double _sub) { total = _total; sub = _sub; } ratio_holder& operator+=(const ratio_holder& a) { return add(a.total, a.sub); } friend ratio_holder operator+(ratio_holder a, const ratio_holder& b) { return a += b; } }; } <|endoftext|>
<commit_before>#include "basicplugin.h" Basicplugin::Basicplugin() { delegate = Q_NULLPTR; parameterForm = new ParameterDialog(); } Basicplugin::~Basicplugin(void) { } QString Basicplugin::getModuleInformation() { return QString("Test Detection Module"); } QDialog& Basicplugin::getParameterForm() { return *parameterForm; } bool Basicplugin::startAnalysis() { if (delegate) { delegate->statusChanged(DetectionModuleInterface::started); //to remove here for testing purpose delegate->statusChanged(DetectionModuleInterface::finished); } return true; } bool Basicplugin::stopAnalysis() { if (delegate) { delegate->statusChanged(DetectionModuleInterface::stopped); } return true; } bool Basicplugin::pauseAnalysis() { if (delegate) { delegate->statusChanged(DetectionModuleInterface::paused); } return true; } void Basicplugin::setSources(QList<QHash<QString, QVariant> > list) { sources = list; } QList<AnalysisResult *> Basicplugin::getAnalysisResults() { results.clear(); for (int i = 0; i < 5; ++i) { for (int j = i + 1; j < 5; ++j) { AnalysisResult *res = new AnalysisResult((i+1)*(j+1), QString::number(i), QString::number(j), QHash<QString, QVariant>()); results << res; } } return results; } void Basicplugin::setDelegate(DetectionModuleHolder *delegate) { this->delegate = delegate; } ParameterDialog::ParameterDialog(QWidget *parent) : QDialog(parent) { } <commit_msg>generates results based on the number of files passed<commit_after>#include "basicplugin.h" Basicplugin::Basicplugin() { delegate = Q_NULLPTR; parameterForm = new ParameterDialog(); } Basicplugin::~Basicplugin(void) { } QString Basicplugin::getModuleInformation() { return QString("Test Detection Module"); } QDialog& Basicplugin::getParameterForm() { return *parameterForm; } bool Basicplugin::startAnalysis() { if (delegate) { delegate->statusChanged(DetectionModuleInterface::started); //to remove here for testing purpose delegate->statusChanged(DetectionModuleInterface::finished); } return true; } bool Basicplugin::stopAnalysis() { if (delegate) { delegate->statusChanged(DetectionModuleInterface::stopped); } return true; } bool Basicplugin::pauseAnalysis() { if (delegate) { delegate->statusChanged(DetectionModuleInterface::paused); } return true; } void Basicplugin::setSources(QList<QHash<QString, QVariant> > list) { sources = list; } QList<AnalysisResult *> Basicplugin::getAnalysisResults() { results.clear(); for (int i = 0; i < sources.count(); ++i) { for (int j = i + 1; j < sources.count(); ++j) { AnalysisResult *res = new AnalysisResult((i+1)*(j+1), QString::number(i), QString::number(j), QHash<QString, QVariant>()); results << res; } } return results; } void Basicplugin::setDelegate(DetectionModuleHolder *delegate) { this->delegate = delegate; } ParameterDialog::ParameterDialog(QWidget *parent) : QDialog(parent) { } <|endoftext|>
<commit_before>// #include <vector> #include <iostream> #include <cmath> #include <CGAL/Nef_polyhedron_3.h> #include <CGAL/Aff_transformation_3.h> #include <CGAL/Exact_predicates_inexact_constructions_kernel.h> #include <CGAL/Mesh_triangulation_3.h> #include <CGAL/Mesh_complex_3_in_triangulation_3.h> #include <CGAL/Mesh_criteria_3.h> #include <CGAL/Mesh_polyhedron_3.h> #include <CGAL/Polyhedral_mesh_domain_with_features_3.h> #include <CGAL/Triangulation_vertex_base_with_info_3.h> #include <CGAL/Triangulation_cell_base_with_info_3.h> #include <CGAL/make_mesh_3.h> #include <CGAL/Cartesian_converter.h> #include <dolfin/common/MPI.h> #include <dolfin/log/log.h> #include <dolfin/mesh/Mesh.h> #include <dolfin/mesh/MeshEditor.h> #include <dolfin/mesh/MeshPartitioning.h> #include <dolfin/plot/plot.h> #define HAS_CGAL #include <dolfin/generation/CGALMeshBuilder.h> #include "cgal_triangulate_polyhedron.h" #include "cgal_copy_polygon_to.h" #include "cgal_csg3d.h" #include <dolfin.h> #include "model.h" using namespace dolfin; typedef CGAL::Simple_cartesian<double> IK; typedef CGAL::Cartesian_converter<IK,csg::Exact_Kernel> IK_to_EK; void build_mesh(const csg::C3t3& c3t3, Mesh& mesh) { typedef csg::C3t3 C3T3; typedef C3T3::Triangulation Triangulation; typedef Triangulation::Vertex_handle Vertex_handle; // CGAL triangulation const Triangulation& triangulation = c3t3.triangulation(); // Clear mesh mesh.clear(); // Count cells in complex std::size_t num_cells = 0; for(csg::C3t3::Cells_in_complex_iterator cit = c3t3.cells_in_complex_begin(); cit != c3t3.cells_in_complex_end(); ++cit) { num_cells++; } // Create and initialize mesh editor dolfin::MeshEditor mesh_editor; mesh_editor.open(mesh, 3, 3); mesh_editor.init_vertices(triangulation.number_of_vertices()); mesh_editor.init_cells(num_cells); // Add vertices to mesh std::size_t vertex_index = 0; std::map<Vertex_handle, std::size_t> vertex_id_map; for (Triangulation::Finite_vertices_iterator cgal_vertex = triangulation.finite_vertices_begin(); cgal_vertex != triangulation.finite_vertices_end(); ++cgal_vertex) { vertex_id_map[cgal_vertex] = vertex_index; // Get vertex coordinates and add vertex to the mesh Point p(cgal_vertex->point()[0], cgal_vertex->point()[1], cgal_vertex->point()[2]); mesh_editor.add_vertex(vertex_index, p); ++vertex_index; } // Add cells to mesh std::size_t cell_index = 0; for(csg::C3t3::Cells_in_complex_iterator cit = c3t3.cells_in_complex_begin(); cit != c3t3.cells_in_complex_end(); ++cit) { mesh_editor.add_cell(cell_index, vertex_id_map[cit->vertex(0)], vertex_id_map[cit->vertex(1)], vertex_id_map[cit->vertex(2)], vertex_id_map[cit->vertex(3)]); ++cell_index; } // Close mesh editor mesh_editor.close(); } void generate(Mesh& mesh, const csg::Polyhedron_3& p, double cell_size) { dolfin_assert(p.is_pure_triangle()); csg::Mesh_domain domain(p); domain.detect_features(); csg::Mesh_criteria criteria(CGAL::parameters::facet_angle = 25, CGAL::parameters::facet_size = cell_size, CGAL::parameters::cell_radius_edge_ratio = 3.0, CGAL::parameters::edge_size = cell_size); std::cout << "Generating mesh" << std::endl; csg::C3t3 c3t3 = CGAL::make_mesh_3<csg::C3t3>(domain, criteria, CGAL::parameters::no_perturb(), CGAL::parameters::no_exude()); // optimize mesh std::cout << "Optimizing mesh by odt optimization" << std::endl; odt_optimize_mesh_3(c3t3, domain); std::cout << "Optimizing mesh by lloyd optimization" << std::endl; lloyd_optimize_mesh_3(c3t3, domain); // This is too slow. Is it really needed? // std::cout << "Optimizing mesh by perturbation" << std::endl; // CGAL::perturb_mesh_3(c3t3, domain); std::cout << "Optimizing mesh by sliver exudation" << std::endl; exude_mesh_3(c3t3); build_mesh(c3t3, mesh); } // The transformation first scales the object by the vector (a, b, c), // then rotates it by the quaternion (x, y, z, w) and then shifts it // by the vector (t, u, v). template<class K> CGAL::Aff_transformation_3<K> trans(double a, double b, double c, double x, double y, double z, double w, double t, double u, double v) { double S = std::sin(w); double C = std::cos(w); // Scaling CGAL::Aff_transformation_3<K> scal(a, 0, 0, 0, b, 0, 0, 0, c); // Rotation CGAL::Aff_transformation_3<K> rot(C + x*x*(1-C), x*y*(1-C) - z*S, x*z*(1-C) + y*S, y*x*(1-C) + z*S, C + y*y*(1-C), y*z*(1-C) - x*S, z*x*(1-C) - y*S, z*y*(1-C) + x*S, C + z*z*(1-C)); // Translation CGAL::Aff_transformation_3<csg::Exact_Kernel> trans(1, 0, 0, t, 0, 1, 0, u, 0, 0, 1, v); return trans * rot * scal; } typedef CGAL::Aff_transformation_3<csg::Exact_Kernel> Aff_trans_3; // Test if Point p is on the boundary of the cube which is the // standard (-1, -1, -1) -- (1, 1, 1) cube transformed by the // transformation t, within a precision of eps bool is_on_boundary(const csg::Exact_Point_3& p, const Aff_trans_3& t, double eps = 1e-7) { csg::Exact_Point_3 q = t.inverse()(p); // Test if point is inside of a cube that is a bit larger if(!(CGAL::abs(q.x()) <= 1 + eps && CGAL::abs(q.y()) <= 1 + eps && CGAL::abs(q.z()) <= 1 + eps)) return false; // Test if point is outside of a cube that is a bit smaller if(!(CGAL::abs(q.x()) >= 1 - eps && CGAL::abs(q.y()) >= 1 - eps && CGAL::abs(q.z()) >= 1 - eps)) return false; return true; } struct CubeDomain : public SubDomain { Aff_trans_3 trans; CubeDomain(const Aff_trans_3& t) : trans(t) {} bool inside(const Array<double>& x, bool on_boundary) const { return is_on_boundary(csg::Exact_Point_3(x[0], x[1], x[2]), trans) && on_boundary; } }; // Evaluate the transformation from the boundary of one cube to the // boundary of a transformed cube. struct CubeToCube : public Expression { Aff_trans_3 first_cube; Aff_trans_3 second_cube; CubeToCube (const Aff_trans_3& a, const Aff_trans_3& b) : Expression(3), first_cube(a), second_cube(b) {} void eval(Array<double>& values, const Array<double>& x) const { IK_to_EK to_exact; csg::Exact_Point_3 p(to_exact(x[0]), to_exact(x[1]), to_exact(x[2])); (second_cube * first_cube.inverse())(p); values[0] = CGAL::to_double(p[0]); values[1] = CGAL::to_double(p[1]); values[2] = CGAL::to_double(p[2]); } }; int main() { std::string off_file = "../cube.off"; csg::Exact_Polyhedron_3 cube; // unit cube std::cout << "reading file " << off_file << std::endl; std::ifstream file(off_file.c_str()); file >> cube; std::cout << "done reading file." << std::endl; double cell_size = 0.5; bool detect_sharp_features = true; Mesh m; csg::Exact_Polyhedron_3 outer(cube); // scale the outer box CGAL::Aff_transformation_3<csg::Exact_Kernel> St(4, 0, 0, 0, 0, 3, 0, 0, 0, 0, 2.5, 0); std::transform(outer.points_begin(), outer.points_end(), outer.points_begin(), St); // scale the inner box CGAL::Aff_transformation_3<csg::Exact_Kernel> Et(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0); csg::Nef_polyhedron_3 Omega(outer); csg::Exact_Polyhedron_3 first_inner(cube); // csg::Exact_Polyhedron_3 second_inner(cube); // second_inner = transformed(second_inner, 0, 0, 1, 0.1, 1.5, 0, 0); Omega -= first_inner; // Omega -= second_inner; csg::Exact_Polyhedron_3 p; Omega.convert_to_polyhedron(p); csg::Polyhedron_3 q; copy_to(p, q); generate(m, q, cell_size); plot(m, "mesh of a cube"); interactive(true); std::cout << "Solving the variational problem" << std::endl; model::FunctionSpace V(m); CubeDomain first_inner_domain(Et); CubeToCube c2c(Et, Et); CubeDomain outer_domain(St); CubeToCube o2o(St, St); // Create Dirichlet boundary conditions DirichletBC bci(V, c2c, first_inner_domain); DirichletBC bco(V, o2o, outer_domain); std::vector<const DirichletBC*> bcs; bcs.push_back(&bci); bcs.push_back(&bco); // Define source and boundary traction functions Constant B(0.0, -0.5, 0.0); Constant T(0.1, 0.0, 0.0); // Define solution function Function u(V); // Set material parameters const double E = 10.0; const double nu = 0.3; Constant mu(E/(2*(1 + nu))); Constant lambda(E*nu/((1 + nu)*(1 - 2*nu))); // Create (linear) form defining (nonlinear) variational problem model::ResidualForm F(V); F.mu = mu; F.lmbda = lambda; F.B = B; F.T = T; F.u = u; // Create jacobian dF = F' (for use in nonlinear solver). model::JacobianForm J(V, V); J.mu = mu; J.lmbda = lambda; J.u = u; // Solve nonlinear variational problem F(u; v) = 0 solve(F == 0, u, bcs, J); // Plot solution plot(u); interactive(); std::getchar(); } <commit_msg>temporary change<commit_after>// #include <vector> #include <iostream> #include <cmath> #include <fstream> #include <CGAL/Nef_polyhedron_3.h> #include <CGAL/Aff_transformation_3.h> #include <CGAL/Exact_predicates_inexact_constructions_kernel.h> #include <CGAL/Mesh_triangulation_3.h> #include <CGAL/Mesh_complex_3_in_triangulation_3.h> #include <CGAL/Mesh_criteria_3.h> #include <CGAL/Mesh_polyhedron_3.h> #include <CGAL/Polyhedral_mesh_domain_with_features_3.h> #include <CGAL/Triangulation_vertex_base_with_info_3.h> #include <CGAL/Triangulation_cell_base_with_info_3.h> #include <CGAL/make_mesh_3.h> #include <CGAL/Cartesian_converter.h> #include <dolfin/common/MPI.h> #include <dolfin/log/log.h> #include <dolfin/mesh/Mesh.h> #include <dolfin/mesh/MeshEditor.h> #include <dolfin/mesh/MeshPartitioning.h> #include <dolfin/plot/plot.h> #define HAS_CGAL #include <dolfin/generation/CGALMeshBuilder.h> #include "cgal_triangulate_polyhedron.h" #include "cgal_copy_polygon_to.h" #include "cgal_csg3d.h" #include <dolfin.h> #include "model.h" using namespace dolfin; typedef CGAL::Simple_cartesian<double> IK; typedef CGAL::Cartesian_converter<IK,csg::Exact_Kernel> IK_to_EK; void build_mesh(const csg::C3t3& c3t3, Mesh& mesh) { typedef csg::C3t3 C3T3; typedef C3T3::Triangulation Triangulation; typedef Triangulation::Vertex_handle Vertex_handle; // CGAL triangulation const Triangulation& triangulation = c3t3.triangulation(); // Clear mesh mesh.clear(); // Count cells in complex std::size_t num_cells = 0; for(csg::C3t3::Cells_in_complex_iterator cit = c3t3.cells_in_complex_begin(); cit != c3t3.cells_in_complex_end(); ++cit) { num_cells++; } // Create and initialize mesh editor dolfin::MeshEditor mesh_editor; mesh_editor.open(mesh, 3, 3); mesh_editor.init_vertices(triangulation.number_of_vertices()); mesh_editor.init_cells(num_cells); // Add vertices to mesh std::size_t vertex_index = 0; std::map<Vertex_handle, std::size_t> vertex_id_map; for (Triangulation::Finite_vertices_iterator cgal_vertex = triangulation.finite_vertices_begin(); cgal_vertex != triangulation.finite_vertices_end(); ++cgal_vertex) { vertex_id_map[cgal_vertex] = vertex_index; // Get vertex coordinates and add vertex to the mesh Point p(cgal_vertex->point()[0], cgal_vertex->point()[1], cgal_vertex->point()[2]); mesh_editor.add_vertex(vertex_index, p); ++vertex_index; } // Add cells to mesh std::size_t cell_index = 0; for(csg::C3t3::Cells_in_complex_iterator cit = c3t3.cells_in_complex_begin(); cit != c3t3.cells_in_complex_end(); ++cit) { mesh_editor.add_cell(cell_index, vertex_id_map[cit->vertex(0)], vertex_id_map[cit->vertex(1)], vertex_id_map[cit->vertex(2)], vertex_id_map[cit->vertex(3)]); ++cell_index; } // Close mesh editor mesh_editor.close(); } void generate(Mesh& mesh, const csg::Polyhedron_3& p, double cell_size) { dolfin_assert(p.is_pure_triangle()); csg::Mesh_domain domain(p); domain.detect_features(); csg::Mesh_criteria criteria(CGAL::parameters::facet_angle = 25, CGAL::parameters::facet_size = cell_size, CGAL::parameters::cell_radius_edge_ratio = 3.0, CGAL::parameters::edge_size = cell_size); std::cout << "Generating mesh" << std::endl; csg::C3t3 c3t3 = CGAL::make_mesh_3<csg::C3t3>(domain, criteria, CGAL::parameters::no_perturb(), CGAL::parameters::no_exude()); // optimize mesh std::cout << "Optimizing mesh by odt optimization" << std::endl; odt_optimize_mesh_3(c3t3, domain); std::cout << "Optimizing mesh by lloyd optimization" << std::endl; lloyd_optimize_mesh_3(c3t3, domain); // This is too slow. Is it really needed? // std::cout << "Optimizing mesh by perturbation" << std::endl; // CGAL::perturb_mesh_3(c3t3, domain); std::cout << "Optimizing mesh by sliver exudation" << std::endl; exude_mesh_3(c3t3); std::fstream out; out.open("~/mesh.txt"); out << c3t3; out.close(); build_mesh(c3t3, mesh); } // The transformation first scales the object by the vector (a, b, c), // then rotates it by the quaternion (x, y, z, w) and then shifts it // by the vector (t, u, v). template<class K> CGAL::Aff_transformation_3<K> trans(double a, double b, double c, double x, double y, double z, double w, double t, double u, double v) { double S = std::sin(w); double C = std::cos(w); // Scaling CGAL::Aff_transformation_3<K> scal(a, 0, 0, 0, b, 0, 0, 0, c); // Rotation CGAL::Aff_transformation_3<K> rot(C + x*x*(1-C), x*y*(1-C) - z*S, x*z*(1-C) + y*S, y*x*(1-C) + z*S, C + y*y*(1-C), y*z*(1-C) - x*S, z*x*(1-C) - y*S, z*y*(1-C) + x*S, C + z*z*(1-C)); // Translation CGAL::Aff_transformation_3<csg::Exact_Kernel> trans(1, 0, 0, t, 0, 1, 0, u, 0, 0, 1, v); return trans * rot * scal; } typedef CGAL::Aff_transformation_3<csg::Exact_Kernel> Aff_trans_3; // Test if Point p is on the boundary of the cube which is the // standard (-1, -1, -1) -- (1, 1, 1) cube transformed by the // transformation t, within a precision of eps bool is_on_boundary(const csg::Exact_Point_3& p, const Aff_trans_3& t, double eps = 10000) { csg::Exact_Point_3 q = t.inverse()(p); // Test if point is inside of a cube that is a bit larger if(!((CGAL::abs(q.x()) <= 1 + eps) && (CGAL::abs(q.y()) <= 1 + eps) && (CGAL::abs(q.z()) <= 1 + eps))) return false; // Test if point is outside of a cube that is a bit smaller if(!((CGAL::abs(q.x()) >= 1 - eps) && (CGAL::abs(q.y()) >= 1 - eps) && (CGAL::abs(q.z()) >= 1 - eps))) return false; return true; } struct CubeDomain : public SubDomain { Aff_trans_3 trans; CubeDomain(const Aff_trans_3& t) : trans(t) {} bool inside(const Array<double>& x, bool on_boundary) const { return is_on_boundary(csg::Exact_Point_3(x[0], x[1], x[2]), trans) && on_boundary; } }; // Evaluate the transformation from the boundary of one cube to the // boundary of a transformed cube. struct CubeToCube : public Expression { Aff_trans_3 first_cube; Aff_trans_3 second_cube; CubeToCube (const Aff_trans_3& a, const Aff_trans_3& b) : Expression(3), first_cube(a), second_cube(b) {} void eval(Array<double>& values, const Array<double>& x) const { IK_to_EK to_exact; csg::Exact_Point_3 p(to_exact(x[0]), to_exact(x[1]), to_exact(x[2])); (second_cube * first_cube.inverse())(p); values[0] = CGAL::to_double(p[0]); values[1] = CGAL::to_double(p[1]); values[2] = CGAL::to_double(p[2]); } }; int main() { std::string off_file = "../cube.off"; csg::Exact_Polyhedron_3 cube; // unit cube std::cout << "reading file " << off_file << std::endl; std::ifstream file(off_file.c_str()); file >> cube; std::cout << "done reading file." << std::endl; double cell_size = 0.5; bool detect_sharp_features = true; Mesh m; csg::Exact_Polyhedron_3 outer(cube); // scale the outer box CGAL::Aff_transformation_3<csg::Exact_Kernel> St(4, 0, 0, 0, 0, 3, 0, 0, 0, 0, 2.5, 0); std::transform(outer.points_begin(), outer.points_end(), outer.points_begin(), St); // scale the inner box CGAL::Aff_transformation_3<csg::Exact_Kernel> Et(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0); csg::Nef_polyhedron_3 Omega(outer); csg::Exact_Polyhedron_3 first_inner(cube); // csg::Exact_Polyhedron_3 second_inner(cube); // second_inner = transformed(second_inner, 0, 0, 1, 0.1, 1.5, 0, 0); Omega -= first_inner; // Omega -= second_inner; csg::Exact_Polyhedron_3 p; Omega.convert_to_polyhedron(p); csg::Polyhedron_3 q; copy_to(p, q); generate(m, q, cell_size); plot(m, "mesh of a cube"); interactive(true); std::cout << "Solving the variational problem" << std::endl; model::FunctionSpace V(m); CubeDomain first_inner_domain(Et); CubeToCube c2c(Et, Et); CubeDomain outer_domain(St); CubeToCube o2o(St, St); // Create Dirichlet boundary conditions DirichletBC bci(V, c2c, first_inner_domain); DirichletBC bco(V, o2o, outer_domain); std::vector<const DirichletBC*> bcs; bcs.push_back(&bci); bcs.push_back(&bco); // Define source and boundary traction functions Constant B(0.0, -0.5, 0.0); Constant T(0.1, 0.0, 0.0); // Define solution function Function u(V); // Set material parameters const double E = 10.0; const double nu = 0.3; Constant mu(E/(2*(1 + nu))); Constant lambda(E*nu/((1 + nu)*(1 - 2*nu))); // Create (linear) form defining (nonlinear) variational problem model::ResidualForm F(V); F.mu = mu; F.lmbda = lambda; F.B = B; F.T = T; F.u = u; // Create jacobian dF = F' (for use in nonlinear solver). model::JacobianForm J(V, V); J.mu = mu; J.lmbda = lambda; J.u = u; // Solve nonlinear variational problem F(u; v) = 0 solve(F == 0, u, bcs, J); // Plot solution plot(u); interactive(); std::getchar(); } <|endoftext|>
<commit_before>#include "UT4WebAdmin.h" #include "UT4WebAdminGameInfo.h" #include "UT4WebAdminServerInfo.h" #include "UT4WebAdminUtils.h" #define UT4WA_WWW_FOLDER "www" #define IS_DEBUG 1 #define PAGE1 "<html><head><title>File not found</title></head><body>File not found</body></html>" #define DENIED "<html><head><title>Acces denied</title></head><body>Access denied</body></html>" #define OPAQUE1 "11733b200778ce33060f31c9af70a870ba96ddd4" UUT4WebAdminHttpServer::UUT4WebAdminHttpServer(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { // don't garbace collect me //SetFlags(RF_MarkAsRootSet); StopRequested.Reset(); WorkerThread = FRunnableThread::Create(this, TEXT("UUT4WebAdminHttpServer"), 8 * 1024, TPri_AboveNormal); } const FString wwwStr = FPaths::GamePluginsDir() + UT4WA_PLUGIN_FOLDER + "/" + UT4WA_WWW_FOLDER + "/"; static struct lws_protocols Protocols[] = { /* first protocol must always be HTTP handler */ { "http-only", UUT4WebAdminHttpServer::CallBack_HTTP, 0 }, { NULL, NULL, 0 } }; uint32 UUT4WebAdminHttpServer::Run() { // start servicing. // service libwebsocket context. while (!StopRequested.GetValue()) { // service libwebsocket, have a slight delay so it doesn't spin on zero load. lws_service(Context, 10); lws_callback_on_writable_all_protocol(Context, &Protocols[0]); } UE_LOG(UT4WebAdmin, Log, TEXT("UT4 WebAdmin Http Server is now Shutting down ")); return true; } // Called internally by FRunnableThread::Kill. void UUT4WebAdminHttpServer::Stop() { StopRequested.Set(true); } void UUT4WebAdminHttpServer::Exit() { lws_context_destroy(Context); Context = NULL; } int UUT4WebAdminHttpServer::CallBack_HTTP( struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len ) { UE_LOG(UT4WebAdmin, Log, TEXT("CallBack_HTTP")); switch (reason) { case LWS_CALLBACK_HTTP: { lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 60); // TODO useful? delete? char *requested_uri = (char *)in; // not a post request if (!lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI)) { char *path = NULL; const char *www = TCHAR_TO_ANSI(*wwwStr); // server index.html file if (FCString::Strcmp(ANSI_TO_TCHAR(requested_uri), TEXT("/")) == 0) { requested_uri = "index.html"; } // TODO handle else if (FCString::Strcmp(ANSI_TO_TCHAR(requested_uri), TEXT("/gameinfo")) == 0) { } // TODO handle else if (FCString::Strcmp(ANSI_TO_TCHAR(requested_uri), TEXT("/serverinfo")) == 0) { } path = (char *) malloc(strlen(www) + strlen(requested_uri)); sprintf(path, "%s%s", www, requested_uri); char *extension = strrchr(path, '.'); char *mime; // choose mime type based on the file extension if (extension == NULL) { mime = "text/plain"; } else if (strcmp(extension, ".png") == 0) { mime = "image/png"; } else if (strcmp(extension, ".jpg") == 0) { mime = "image/jpg"; } else if (strcmp(extension, ".gif") == 0) { mime = "image/gif"; } else if (strcmp(extension, ".html") == 0) { mime = "text/html"; } else if (strcmp(extension, ".css") == 0) { mime = "text/css"; } else if (strcmp(extension, ".ico") == 0) { mime = "image/x-icon"; } else { mime = "text/plain"; } lws_serve_http_file(wsi, path, mime, NULL, 0); } else { // we got a post request!, queue up a write callback. lws_callback_on_writable(wsi); } lws_close_reason( wsi, LWS_CLOSE_STATUS_NORMAL, (unsigned char *)"seeya", 5); break; } default: break; } return 0; } void lws_debugLog(int level, const char *line) { UE_LOG(UT4WebAdmin, Warning, TEXT(" LibWebsocket: %s"), ANSI_TO_TCHAR(line)); } bool started = false; bool UUT4WebAdminHttpServer::Init() { // FIXME for some unknow reason the init function is called 3 times then it crashes // this 'trick' prevents the crash if (started) { return false; } started = true; struct lws_context_creation_info ContextInfo = {}; lws_set_log_level(LLL_ERR | LLL_WARN | LLL_NOTICE | LLL_DEBUG, lws_debugLog); if (WebHttpPort == 0) { WebHttpPort = 8080; } /* BaseGameMode = Cast<AUTBaseGameMode>(GWorld->GetAuthGameMode()); bool IsGameInstanceServer = BaseGameMode->IsGameInstanceServer(); // for lobby instance server open http port at (instance port + 100) if (IsGameInstanceServer) { FString addressUrl = GWorld->GetAddressURL(); TArray<FString> PathItemList; addressUrl.ParseIntoArray(PathItemList, TEXT(":"), true); httpPort = FCString::Atoi(*PathItemList[PathItemList.Num() - 1]) + 100; } */ ContextInfo.port = WebHttpPort; ContextInfo.iface = NULL; ContextInfo.protocols = Protocols; ContextInfo.uid = -1; ContextInfo.gid = -1; ContextInfo.options = 0; //ContextInfo.user = this; ContextInfo.extensions = NULL; //ContextInfo.options |= LWS_SERVER_OPTION_PEER_CERT_NOT_REQUIRED | LWS_SERVER_OPTION_DISABLE_OS_CA_CERTS; //ContextInfo.ssl_cipher_list = nullptr; Context = lws_create_context(&ContextInfo); if (Context == NULL) { UE_LOG(UT4WebAdmin, Warning, TEXT(" * * * * * * * * * * * * * * * * * * * * * * *")); UE_LOG(UT4WebAdmin, Warning, TEXT(" UT4WebAdmin failed to start http(s) server at port: %i "), WebHttpPort); UE_LOG(UT4WebAdmin, Warning, TEXT(" * * * * * * * * * * * * * * * * * * * * * * *")); return false; } else { UE_LOG(UT4WebAdmin, Log, TEXT(" * * * * * * * * * * * * * * * * * * * * * * *")); UE_LOG(UT4WebAdmin, Log, TEXT(" UT4WebAdmin started at port: %i "), WebHttpPort); UE_LOG(UT4WebAdmin, Log, TEXT(" * * * * * * * * * * * * * * * * * * * * * * *")); } //Ready.Set(true); return true; } /* void UUT4WebAdminHttpServer::Tick(float DeltaTime) { } TStatId UUT4WebAdminHttpServer::GetStatId() const { RETURN_QUICK_DECLARE_CYCLE_STAT(UUT4WebAdminHttpServer, STATGROUP_Tickables); }*/<commit_msg>fixed linux build<commit_after>#include "UT4WebAdmin.h" #include "UT4WebAdminGameInfo.h" #include "UT4WebAdminServerInfo.h" #include "UT4WebAdminUtils.h" #define UT4WA_WWW_FOLDER "www" #define IS_DEBUG 1 #define PAGE1 "<html><head><title>File not found</title></head><body>File not found</body></html>" #define DENIED "<html><head><title>Acces denied</title></head><body>Access denied</body></html>" #define OPAQUE1 "11733b200778ce33060f31c9af70a870ba96ddd4" UUT4WebAdminHttpServer::UUT4WebAdminHttpServer(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { // don't garbace collect me //SetFlags(RF_MarkAsRootSet); StopRequested.Reset(); WorkerThread = FRunnableThread::Create(this, TEXT("UUT4WebAdminHttpServer"), 16 * 1024, TPri_SlightlyBelowNormal); } const FString wwwStr = FPaths::GamePluginsDir() + UT4WA_PLUGIN_FOLDER + "/" + UT4WA_WWW_FOLDER + "/"; static struct lws_protocols Protocols[] = { /* first protocol must always be HTTP handler */ { "http-only", UUT4WebAdminHttpServer::CallBack_HTTP, 0 }, { NULL, NULL, 0 } }; uint32 UUT4WebAdminHttpServer::Run() { // start servicing. // service libwebsocket context. while (!StopRequested.GetValue()) { // service libwebsocket, have a slight delay so it doesn't spin on zero load. lws_service(Context, 10); lws_callback_on_writable_all_protocol(Context, &Protocols[0]); } UE_LOG(UT4WebAdmin, Log, TEXT("UT4 WebAdmin Http Server is now Shutting down ")); return true; } // Called internally by FRunnableThread::Kill. void UUT4WebAdminHttpServer::Stop() { StopRequested.Set(true); } void UUT4WebAdminHttpServer::Exit() { lws_context_destroy(Context); Context = NULL; } int UUT4WebAdminHttpServer::CallBack_HTTP( struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len ) { //UE_LOG(UT4WebAdmin, Log, TEXT("CallBack_HTTP")); switch (reason) { case LWS_CALLBACK_HTTP: { //lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 60); // TODO useful? delete? char *requested_uri = (char *)in; // not a post request if (!lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI)) { char *path = NULL; const char *www = TCHAR_TO_ANSI(*wwwStr); // server index.html file if (FCString::Strcmp(ANSI_TO_TCHAR(requested_uri), TEXT("/")) == 0) { requested_uri = (char*) "index.html"; } // TODO handle else if (FCString::Strcmp(ANSI_TO_TCHAR(requested_uri), TEXT("/gameinfo")) == 0) { } // TODO handle else if (FCString::Strcmp(ANSI_TO_TCHAR(requested_uri), TEXT("/serverinfo")) == 0) { } path = (char *) malloc(strlen(www) + strlen(requested_uri)); sprintf(path, "%s%s", www, requested_uri); char *extension = strrchr(path, '.'); char *mime; // choose mime type based on the file extension if (extension == NULL) { mime = (char*) "text/plain"; } else if (strcmp(extension, ".png") == 0) { mime = (char*) "image/png"; } else if (strcmp(extension, ".jpg") == 0) { mime = (char*) "image/jpg"; } else if (strcmp(extension, ".gif") == 0) { mime = (char*) "image/gif"; } else if (strcmp(extension, ".html") == 0) { mime = (char*) "text/html"; } else if (strcmp(extension, ".css") == 0) { mime = (char*) "text/css"; } else if (strcmp(extension, ".ico") == 0) { mime = (char*) "image/x-icon"; } else { mime = (char*) "text/plain"; } lws_serve_http_file(wsi, path, mime, NULL, 0); } else { // we got a post request!, queue up a write callback. lws_callback_on_writable(wsi); } lws_close_reason(wsi, LWS_CLOSE_STATUS_NORMAL, (unsigned char *)"seeya", 5); break; } default: break; } return 0; } void lws_debugLog(int level, const char *line) { UE_LOG(UT4WebAdmin, Warning, TEXT(" LibWebsocket: %s"), ANSI_TO_TCHAR(line)); } bool started = false; bool UUT4WebAdminHttpServer::Init() { // FIXME for some unknow reason the init function is called 3 times then it crashes // this 'trick' prevents the crash if (started) { return false; } started = true; struct lws_context_creation_info ContextInfo = {}; lws_set_log_level(LLL_ERR | LLL_WARN | LLL_NOTICE | LLL_DEBUG, lws_debugLog); if (WebHttpPort == 0) { WebHttpPort = 8080; } /* BaseGameMode = Cast<AUTBaseGameMode>(GWorld->GetAuthGameMode()); bool IsGameInstanceServer = BaseGameMode->IsGameInstanceServer(); // for lobby instance server open http port at (instance port + 100) if (IsGameInstanceServer) { FString addressUrl = GWorld->GetAddressURL(); TArray<FString> PathItemList; addressUrl.ParseIntoArray(PathItemList, TEXT(":"), true); httpPort = FCString::Atoi(*PathItemList[PathItemList.Num() - 1]) + 100; } */ ContextInfo.port = WebHttpPort; ContextInfo.iface = NULL; ContextInfo.protocols = Protocols; ContextInfo.uid = -1; ContextInfo.gid = -1; ContextInfo.options = 0; //ContextInfo.user = this; ContextInfo.extensions = NULL; if (WebHttpsEnabled) { ContextInfo.ssl_cert_filepath = "D:\\server_certificate.pem"; ContextInfo.ssl_private_key_filepath = "D:\\server_key.pem"; } //ContextInfo.options |= LWS_SERVER_OPTION_PEER_CERT_NOT_REQUIRED | LWS_SERVER_OPTION_DISABLE_OS_CA_CERTS; ContextInfo.ssl_cipher_list = nullptr; Context = lws_create_context(&ContextInfo); if (Context == NULL) { UE_LOG(UT4WebAdmin, Warning, TEXT(" * * * * * * * * * * * * * * * * * * * * * * *")); UE_LOG(UT4WebAdmin, Warning, TEXT(" UT4WebAdmin failed to start http(s) server at port: %i "), WebHttpPort); UE_LOG(UT4WebAdmin, Warning, TEXT(" * * * * * * * * * * * * * * * * * * * * * * *")); return false; } else { UE_LOG(UT4WebAdmin, Log, TEXT(" * * * * * * * * * * * * * * * * * * * * * * *")); UE_LOG(UT4WebAdmin, Log, TEXT(" UT4WebAdmin started at port: %i "), WebHttpPort); UE_LOG(UT4WebAdmin, Log, TEXT(" * * * * * * * * * * * * * * * * * * * * * * *")); } //Ready.Set(true); return true; } /* void UUT4WebAdminHttpServer::Tick(float DeltaTime) { } TStatId UUT4WebAdminHttpServer::GetStatId() const { RETURN_QUICK_DECLARE_CYCLE_STAT(UUT4WebAdminHttpServer, STATGROUP_Tickables); }*/<|endoftext|>
<commit_before>#include "UnrealEnginePythonPrivatePCH.h" #include "PyCommandlet.h" #include "Regex.h" UPyCommandlet::UPyCommandlet(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { LogToConsole = 1; } int32 UPyCommandlet::Main(const FString& CommandLine) { TArray<FString> Tokens, Switches; TMap<FString, FString> Params; ParseCommandLine(*CommandLine, Tokens, Switches, Params); FString Filepath = Tokens[0]; if (!FPaths::FileExists(*Filepath)) { UE_LOG(LogPython, Error, TEXT("Python file could not be found: %s"), *Filepath); return -1; } FString RegexString = FString::Printf(TEXT("(?<=%s).*"), *(Filepath.Replace(TEXT("\\"), TEXT("\\\\")))); const FRegexPattern myPattern(RegexString); FRegexMatcher myMatcher(myPattern, *CommandLine); myMatcher.FindNext(); FString PyCommandLine = myMatcher.GetCaptureGroup(0).Trim().TrimTrailing(); TArray<FString> PyArgv; PyArgv.Add(FString()); bool escaped = false; for (int i = 0; i < PyCommandLine.Len(); i++) { if(PyCommandLine[i] == ' ') { PyArgv.Add(FString()); continue; } else if(PyCommandLine[i] == '\"' && !escaped) { i++; while(i < PyCommandLine.Len() && !(PyCommandLine[i] == '"')) { PyArgv[PyArgv.Num() - 1].AppendChar(PyCommandLine[i]); i++; if (i == PyCommandLine.Len()) { PyArgv[PyArgv.Num() - 1].InsertAt(0, "\""); } } } else { if (PyCommandLine[i] == '\\') escaped = true; else escaped = false; PyArgv[PyArgv.Num() - 1].AppendChar(PyCommandLine[i]); } } PyArgv.Insert(Filepath, 0); #if PY_MAJOR_VERSION >= 3 wchar_t **argv = (wchar_t **)malloc(PyArgv.Num() * sizeof(void*)); #else char **argv = (char **)malloc(PyArgv.Num() * sizeof(void*)); #endif for (int i=0; i<PyArgv.Num(); i++) { #if PY_MAJOR_VERSION >= 3 argv[i] = (wchar_t*)malloc(PyArgv[i].Len()+1); #if UNREAL_ENGINE_PYTHON_ON_MAC || UNREAL_ENGINE_PYTHON_ON_LINUX wcsncpy(argv[i], *PyArgv[i].ReplaceEscapedCharWithChar(), PyArgv[i].Len() + 1); #else wcscpy_s(argv[i], PyArgv[i].Len() + 1, *PyArgv[i].ReplaceEscapedCharWithChar()); #endif #else argv[i] = (char*)malloc(PyArgv[i].Len() + 1); #if UNREAL_ENGINE_PYTHON_ON_MAC || UNREAL_ENGINE_PYTHON_ON_LINUX strncpy(argv[i], TCHAR_TO_UTF8(*PyArgv[i].ReplaceEscapedCharWithChar()), PyArgv[i].Len()+1); #else strncpy_s(argv[i], PyArgv[i].Len()+1, TCHAR_TO_UTF8(*PyArgv[i].ReplaceEscapedCharWithChar())); #endif #endif } PySys_SetArgv(PyArgv.Num(), argv); FUnrealEnginePythonModule &PythonModule = FModuleManager::GetModuleChecked<FUnrealEnginePythonModule>("UnrealEnginePython"); PythonModule.RunFile(TCHAR_TO_UTF8(*Filepath)); return 0; } <commit_msg>Fix typo<commit_after>#include "UnrealEnginePythonPrivatePCH.h" #include "PyCommandlet.h" #include "Regex.h" UPyCommandlet::UPyCommandlet(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { LogToConsole = 1; } int32 UPyCommandlet::Main(const FString& CommandLine) { TArray<FString> Tokens, Switches; TMap<FString, FString> Params; ParseCommandLine(*CommandLine, Tokens, Switches, Params); FString Filepath = Tokens[0]; if (!FPaths::FileExists(*Filepath)) { UE_LOG(LogPython, Error, TEXT("Python file could not be found: %s"), *Filepath); return -1; } FString RegexString = FString::Printf(TEXT("(?<=%s).*"), *(Filepath.Replace(TEXT("\\"), TEXT("\\\\")))); const FRegexPattern myPattern(RegexString); FRegexMatcher myMatcher(myPattern, *CommandLine); myMatcher.FindNext(); FString PyCommandLine = myMatcher.GetCaptureGroup(0).Trim().TrimTrailing(); TArray<FString> PyArgv; PyArgv.Add(FString()); bool escaped = false; for (int i = 0; i < PyCommandLine.Len(); i++) { if(PyCommandLine[i] == ' ') { PyArgv.Add(FString()); continue; } else if(PyCommandLine[i] == '\"' && !escaped) { i++; while(i < PyCommandLine.Len() && !(PyCommandLine[i] == '"')) { PyArgv[PyArgv.Num() - 1].AppendChar(PyCommandLine[i]); i++; if (i == PyCommandLine.Len()) { PyArgv[PyArgv.Num() - 1].InsertAt(0, "\""); } } } else { if (PyCommandLine[i] == '\\') escaped = true; else escaped = false; PyArgv[PyArgv.Num() - 1].AppendChar(PyCommandLine[i]); } } PyArgv.Insert(Filepath, 0); #if PY_MAJOR_VERSION >= 3 wchar_t **argv = (wchar_t **)malloc(PyArgv.Num() * sizeof(void*)); #else char **argv = (char **)malloc(PyArgv.Num() * sizeof(void*)); #endif for (int i=0; i<PyArgv.Num(); i++) { #if PY_MAJOR_VERSION >= 3 argv[i] = (wchar_t*)malloc(PyArgv[i].Len()+1); #if UNREAL_ENGINE_PYTHON_ON_MAC || UNREAL_ENGINE_PYTHON_ON_LINUX wcsncpy(argv[i], *PyArgv[i].ReplaceEscapedCharWithChar(), PyArgv[i].Len() + 1); #else wcscpy_s(argv[i], PyArgv[i].Len() + 1, *PyArgv[i].ReplaceEscapedCharWithChar()); #endif #else argv[i] = (char*)malloc(PyArgv[i].Len() + 1); #if UNREAL_ENGINE_PYTHON_ON_MAC || UNREAL_ENGINE_PYTHON_ON_LINUX strncpy(argv[i], TCHAR_TO_UTF8(*PyArgv[i].ReplaceEscapedCharWithChar()), PyArgv[i].Len()+1); #else strcpy_s(argv[i], PyArgv[i].Len()+1, TCHAR_TO_UTF8(*PyArgv[i].ReplaceEscapedCharWithChar())); #endif #endif } PySys_SetArgv(PyArgv.Num(), argv); FUnrealEnginePythonModule &PythonModule = FModuleManager::GetModuleChecked<FUnrealEnginePythonModule>("UnrealEnginePython"); PythonModule.RunFile(TCHAR_TO_UTF8(*Filepath)); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: appedit.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: vg $ $Date: 2003-04-15 17:11:53 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _CONFIG_HXX #include <tools/config.hxx> #endif #ifndef _CTRLTOOL_HXX #include <svtools/ctrltool.hxx> #endif #ifndef _TEXTVIEW_HXX //autogen #include <svtools/textview.hxx> #endif #ifndef _TEXTENG_HXX //autogen #include <svtools/texteng.hxx> #endif #ifndef _UNDO_HXX #include <svtools/undo.hxx> #endif #ifndef _BASIC_TTRESHLP_HXX #include "ttstrhlp.hxx" #endif #include "basic.hrc" #include "appedit.hxx" #include "brkpnts.hxx" TYPEINIT1(AppEdit,AppWin); AppEdit::AppEdit( BasicFrame* pParent ) : AppWin( pParent ) , nCurTextWidth(5) , pVScroll( NULL ) , pHScroll( NULL ) { String aEmpty; // evtl. den Untitled-String laden: pDataEdit = new TextEdit( this, WB_LEFT ); LoadIniFile(); // Icon definieren: // pIcon = new Icon( ResId( RID_WORKICON ) ); // if( pIcon ) SetIcon( *pIcon ); pDataEdit->SetText( aEmpty ); pDataEdit->Show(); pVScroll = new ScrollBar( this, WB_VSCROLL|WB_DRAG ); pVScroll->Show(); pVScroll->SetScrollHdl( LINK( this, AppEdit, Scroll ) ); pHScroll = new ScrollBar( this, WB_HSCROLL|WB_DRAG ); pHScroll->Show(); pHScroll->SetScrollHdl( LINK( this, AppEdit, Scroll ) ); InitScrollBars(); } AppEdit::~AppEdit() { DataEdit *pHold = pDataEdit; pDataEdit = NULL; // Erst abklemmen, dann lschen delete pHold; delete pHScroll; delete pVScroll; } void AppEdit::LoadIniFile() { TextView *pTextView = ((TextEdit*)pDataEdit)->aEdit.pTextView; BOOL bWasModified = pTextView->GetTextEngine()->IsModified(); pTextView->GetTextEngine()->SetModified( FALSE ); FontList aFontList( pFrame ); // Just some Window is needed Config aConf(Config::GetConfigName( Config::GetDefDirectory(), CUniString("testtool") )); aConf.SetGroup("Misc"); String aFontName = String( aConf.ReadKey( "ScriptFontName", "Courier" ), RTL_TEXTENCODING_UTF8 ); String aFontStyle = String( aConf.ReadKey( "ScriptFontStyle", "normal" ), RTL_TEXTENCODING_UTF8 ); String aFontSize = String( aConf.ReadKey( "ScriptFontSize", "12" ), RTL_TEXTENCODING_UTF8 ); Font aFont = aFontList.Get( aFontName, aFontStyle ); // ULONG nFontSize = aFontSize.GetValue( FUNIT_POINT ); ULONG nFontSize = aFontSize.ToInt32(); // aFont.SetSize( Size( nFontSize, nFontSize ) ); aFont.SetHeight( nFontSize ); #if OSL_DEBUG_LEVEL > 1 { Font aFont( OutputDevice::GetDefaultFont( DEFAULTFONT_FIXED, Application::GetSettings().GetUILanguage(), 0, pFrame )); } #endif aFont.SetTransparent( FALSE ); // aFont.SetAlign( ALIGN_BOTTOM ); // aFont.SetHeight( aFont.GetHeight()+2 ); pDataEdit->SetFont( aFont ); if ( ((TextEdit*)pDataEdit)->GetBreakpointWindow() ) { ((TextEdit*)pDataEdit)->GetBreakpointWindow()->SetFont( aFont ); ((TextEdit*)pDataEdit)->GetBreakpointWindow()->Invalidate(); } pTextView->GetTextEngine()->SetModified( bWasModified ); // Eventuell wieder setzen } void AppEdit::Command( const CommandEvent& rCEvt ) { switch( rCEvt.GetCommand() ) { case COMMAND_WHEEL: { HandleScrollCommand( rCEvt, pHScroll, pVScroll ); } break; default: AppWin::Command( rCEvt ); } } IMPL_LINK( AppEdit, Scroll, ScrollBar*, pScroll ) { if ( !pHScroll || !pVScroll ) return 0; TextView *pTextView = ((TextEdit*)pDataEdit)->aEdit.pTextView; pTextView->SetStartDocPos( Point( pHScroll->GetThumbPos(), pVScroll->GetThumbPos() ) ); pTextView->Invalidate(); if ( ((TextEdit*)pDataEdit)->GetBreakpointWindow() ) ((TextEdit*)pDataEdit)->GetBreakpointWindow()->Scroll( 0, ((TextEdit*)pDataEdit)->GetBreakpointWindow()->GetCurYOffset() - pTextView->GetStartDocPos().Y() ); return 0L; } void AppEdit::InitScrollBars() { if ( !pHScroll || !pVScroll ) return; TextView *pTextView = ((TextEdit*)pDataEdit)->aEdit.pTextView; // Kopiert und angepasst. SetScrollBarRanges(); Size aOutSz( pTextView->GetWindow()->GetOutputSizePixel() ); pVScroll->SetVisibleSize( aOutSz.Height() ); pVScroll->SetPageSize( aOutSz.Height() * 8 / 10 ); pVScroll->SetLineSize( GetTextHeight() +2 ); // +2 is empirical. don't know why pVScroll->SetThumbPos( pTextView->GetStartDocPos().Y() ); pVScroll->Show(); pHScroll->SetVisibleSize( aOutSz.Width() ); pHScroll->SetPageSize( aOutSz.Width() * 8 / 10 ); pHScroll->SetLineSize( GetTextWidth( CUniString("x") ) ); pHScroll->SetThumbPos( pTextView->GetStartDocPos().X() ); pHScroll->Show(); } void AppEdit::SetScrollBarRanges() { // Extra-Methode, nicht InitScrollBars, da auch fuer EditEngine-Events. if ( !pHScroll || !pVScroll ) return; pHScroll->SetRange( Range( 0, nCurTextWidth ) ); pVScroll->SetRange( Range( 0, ((TextEdit*)pDataEdit)->aEdit.pTextEngine->GetTextHeight() ) ); } USHORT AppEdit::GetLineNr(){ return pDataEdit->GetLineNr(); } FileType AppEdit::GetFileType() { return FT_BASIC_SOURCE; } // Set up the menu long AppEdit::InitMenu( Menu* pMenu ) { AppWin::InitMenu (pMenu ); USHORT UndoCount = ((TextEdit*)pDataEdit)->aEdit.pTextEngine->GetUndoManager().GetUndoActionCount(); USHORT RedoCount = ((TextEdit*)pDataEdit)->aEdit.pTextEngine->GetUndoManager().GetRedoActionCount(); pMenu->EnableItem( RID_EDITUNDO, UndoCount > 0 ); pMenu->EnableItem( RID_EDITREDO, RedoCount > 0 ); return TRUE; } long AppEdit::DeInitMenu( Menu* pMenu ) { AppWin::DeInitMenu (pMenu ); pMenu->EnableItem( RID_EDITUNDO ); pMenu->EnableItem( RID_EDITREDO ); return TRUE; } // Sourcecode-Datei laden void AppEdit::Resize() { if( !pDataEdit ) return; Point rHStart,rVStart; Size rHSize,rVSize; Size rNewSize( GetOutputSizePixel() ); if ( pHScroll ) { rHSize = pHScroll->GetSizePixel(); ULONG nHieght = rHSize.Height(); rNewSize.Height() -= nHieght; rHStart.Y() = rNewSize.Height(); } if ( pVScroll ) { rVSize = pVScroll->GetSizePixel(); ULONG nWidth = rVSize.Width(); rNewSize.Width() -= nWidth; rVStart.X() = rNewSize.Width(); } rHSize.Width() = rNewSize.Width(); rVSize.Height() = rNewSize.Height(); if ( pHScroll ) { pHScroll->SetPosPixel( rHStart ); pHScroll->SetSizePixel( rHSize ); } if ( pVScroll ) { pVScroll->SetPosPixel( rVStart ); pVScroll->SetSizePixel( rVSize ); } pDataEdit->SetPosPixel( Point() ); pDataEdit->SetSizePixel( rNewSize ); TextView *pTextView = ((TextEdit*)pDataEdit)->aEdit.pTextView; // Kopiert und adaptiert long nVisY = pTextView->GetStartDocPos().Y(); pTextView->ShowCursor(); Size aOutSz( pTextView->GetWindow()->GetOutputSizePixel() ); long nMaxVisAreaStart = pTextView->GetTextEngine()->GetTextHeight() - aOutSz.Height(); if ( nMaxVisAreaStart < 0 ) nMaxVisAreaStart = 0; if ( pTextView->GetStartDocPos().Y() > nMaxVisAreaStart ) { Point aStartDocPos( pTextView->GetStartDocPos() ); aStartDocPos.Y() = nMaxVisAreaStart; pTextView->SetStartDocPos( aStartDocPos ); pTextView->ShowCursor(); // pModulWindow->GetBreakPointWindow().GetCurYOffset() = aStartDocPos.Y(); } InitScrollBars(); if ( nVisY != pTextView->GetStartDocPos().Y() ) pTextView->GetWindow()->Invalidate(); } void AppEdit::PostLoad() { } // mit neuem Namen speichern void AppEdit::PostSaveAs() { } void AppEdit::Highlight( USHORT nLine, USHORT nCol1, USHORT nCol2 ) { ((TextEdit*)pDataEdit)->Highlight( nLine, nCol1, nCol2 ); ToTop(); } <commit_msg>INTEGRATION: CWS ooo19126 (1.5.288); FILE MERGED 2005/09/05 14:35:48 rt 1.5.288.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: appedit.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-09-07 21:10:43 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _CONFIG_HXX #include <tools/config.hxx> #endif #ifndef _CTRLTOOL_HXX #include <svtools/ctrltool.hxx> #endif #ifndef _TEXTVIEW_HXX //autogen #include <svtools/textview.hxx> #endif #ifndef _TEXTENG_HXX //autogen #include <svtools/texteng.hxx> #endif #ifndef _UNDO_HXX #include <svtools/undo.hxx> #endif #ifndef _BASIC_TTRESHLP_HXX #include "ttstrhlp.hxx" #endif #include "basic.hrc" #include "appedit.hxx" #include "brkpnts.hxx" TYPEINIT1(AppEdit,AppWin); AppEdit::AppEdit( BasicFrame* pParent ) : AppWin( pParent ) , nCurTextWidth(5) , pVScroll( NULL ) , pHScroll( NULL ) { String aEmpty; // evtl. den Untitled-String laden: pDataEdit = new TextEdit( this, WB_LEFT ); LoadIniFile(); // Icon definieren: // pIcon = new Icon( ResId( RID_WORKICON ) ); // if( pIcon ) SetIcon( *pIcon ); pDataEdit->SetText( aEmpty ); pDataEdit->Show(); pVScroll = new ScrollBar( this, WB_VSCROLL|WB_DRAG ); pVScroll->Show(); pVScroll->SetScrollHdl( LINK( this, AppEdit, Scroll ) ); pHScroll = new ScrollBar( this, WB_HSCROLL|WB_DRAG ); pHScroll->Show(); pHScroll->SetScrollHdl( LINK( this, AppEdit, Scroll ) ); InitScrollBars(); } AppEdit::~AppEdit() { DataEdit *pHold = pDataEdit; pDataEdit = NULL; // Erst abklemmen, dann lschen delete pHold; delete pHScroll; delete pVScroll; } void AppEdit::LoadIniFile() { TextView *pTextView = ((TextEdit*)pDataEdit)->aEdit.pTextView; BOOL bWasModified = pTextView->GetTextEngine()->IsModified(); pTextView->GetTextEngine()->SetModified( FALSE ); FontList aFontList( pFrame ); // Just some Window is needed Config aConf(Config::GetConfigName( Config::GetDefDirectory(), CUniString("testtool") )); aConf.SetGroup("Misc"); String aFontName = String( aConf.ReadKey( "ScriptFontName", "Courier" ), RTL_TEXTENCODING_UTF8 ); String aFontStyle = String( aConf.ReadKey( "ScriptFontStyle", "normal" ), RTL_TEXTENCODING_UTF8 ); String aFontSize = String( aConf.ReadKey( "ScriptFontSize", "12" ), RTL_TEXTENCODING_UTF8 ); Font aFont = aFontList.Get( aFontName, aFontStyle ); // ULONG nFontSize = aFontSize.GetValue( FUNIT_POINT ); ULONG nFontSize = aFontSize.ToInt32(); // aFont.SetSize( Size( nFontSize, nFontSize ) ); aFont.SetHeight( nFontSize ); #if OSL_DEBUG_LEVEL > 1 { Font aFont( OutputDevice::GetDefaultFont( DEFAULTFONT_FIXED, Application::GetSettings().GetUILanguage(), 0, pFrame )); } #endif aFont.SetTransparent( FALSE ); // aFont.SetAlign( ALIGN_BOTTOM ); // aFont.SetHeight( aFont.GetHeight()+2 ); pDataEdit->SetFont( aFont ); if ( ((TextEdit*)pDataEdit)->GetBreakpointWindow() ) { ((TextEdit*)pDataEdit)->GetBreakpointWindow()->SetFont( aFont ); ((TextEdit*)pDataEdit)->GetBreakpointWindow()->Invalidate(); } pTextView->GetTextEngine()->SetModified( bWasModified ); // Eventuell wieder setzen } void AppEdit::Command( const CommandEvent& rCEvt ) { switch( rCEvt.GetCommand() ) { case COMMAND_WHEEL: { HandleScrollCommand( rCEvt, pHScroll, pVScroll ); } break; default: AppWin::Command( rCEvt ); } } IMPL_LINK( AppEdit, Scroll, ScrollBar*, pScroll ) { if ( !pHScroll || !pVScroll ) return 0; TextView *pTextView = ((TextEdit*)pDataEdit)->aEdit.pTextView; pTextView->SetStartDocPos( Point( pHScroll->GetThumbPos(), pVScroll->GetThumbPos() ) ); pTextView->Invalidate(); if ( ((TextEdit*)pDataEdit)->GetBreakpointWindow() ) ((TextEdit*)pDataEdit)->GetBreakpointWindow()->Scroll( 0, ((TextEdit*)pDataEdit)->GetBreakpointWindow()->GetCurYOffset() - pTextView->GetStartDocPos().Y() ); return 0L; } void AppEdit::InitScrollBars() { if ( !pHScroll || !pVScroll ) return; TextView *pTextView = ((TextEdit*)pDataEdit)->aEdit.pTextView; // Kopiert und angepasst. SetScrollBarRanges(); Size aOutSz( pTextView->GetWindow()->GetOutputSizePixel() ); pVScroll->SetVisibleSize( aOutSz.Height() ); pVScroll->SetPageSize( aOutSz.Height() * 8 / 10 ); pVScroll->SetLineSize( GetTextHeight() +2 ); // +2 is empirical. don't know why pVScroll->SetThumbPos( pTextView->GetStartDocPos().Y() ); pVScroll->Show(); pHScroll->SetVisibleSize( aOutSz.Width() ); pHScroll->SetPageSize( aOutSz.Width() * 8 / 10 ); pHScroll->SetLineSize( GetTextWidth( CUniString("x") ) ); pHScroll->SetThumbPos( pTextView->GetStartDocPos().X() ); pHScroll->Show(); } void AppEdit::SetScrollBarRanges() { // Extra-Methode, nicht InitScrollBars, da auch fuer EditEngine-Events. if ( !pHScroll || !pVScroll ) return; pHScroll->SetRange( Range( 0, nCurTextWidth ) ); pVScroll->SetRange( Range( 0, ((TextEdit*)pDataEdit)->aEdit.pTextEngine->GetTextHeight() ) ); } USHORT AppEdit::GetLineNr(){ return pDataEdit->GetLineNr(); } FileType AppEdit::GetFileType() { return FT_BASIC_SOURCE; } // Set up the menu long AppEdit::InitMenu( Menu* pMenu ) { AppWin::InitMenu (pMenu ); USHORT UndoCount = ((TextEdit*)pDataEdit)->aEdit.pTextEngine->GetUndoManager().GetUndoActionCount(); USHORT RedoCount = ((TextEdit*)pDataEdit)->aEdit.pTextEngine->GetUndoManager().GetRedoActionCount(); pMenu->EnableItem( RID_EDITUNDO, UndoCount > 0 ); pMenu->EnableItem( RID_EDITREDO, RedoCount > 0 ); return TRUE; } long AppEdit::DeInitMenu( Menu* pMenu ) { AppWin::DeInitMenu (pMenu ); pMenu->EnableItem( RID_EDITUNDO ); pMenu->EnableItem( RID_EDITREDO ); return TRUE; } // Sourcecode-Datei laden void AppEdit::Resize() { if( !pDataEdit ) return; Point rHStart,rVStart; Size rHSize,rVSize; Size rNewSize( GetOutputSizePixel() ); if ( pHScroll ) { rHSize = pHScroll->GetSizePixel(); ULONG nHieght = rHSize.Height(); rNewSize.Height() -= nHieght; rHStart.Y() = rNewSize.Height(); } if ( pVScroll ) { rVSize = pVScroll->GetSizePixel(); ULONG nWidth = rVSize.Width(); rNewSize.Width() -= nWidth; rVStart.X() = rNewSize.Width(); } rHSize.Width() = rNewSize.Width(); rVSize.Height() = rNewSize.Height(); if ( pHScroll ) { pHScroll->SetPosPixel( rHStart ); pHScroll->SetSizePixel( rHSize ); } if ( pVScroll ) { pVScroll->SetPosPixel( rVStart ); pVScroll->SetSizePixel( rVSize ); } pDataEdit->SetPosPixel( Point() ); pDataEdit->SetSizePixel( rNewSize ); TextView *pTextView = ((TextEdit*)pDataEdit)->aEdit.pTextView; // Kopiert und adaptiert long nVisY = pTextView->GetStartDocPos().Y(); pTextView->ShowCursor(); Size aOutSz( pTextView->GetWindow()->GetOutputSizePixel() ); long nMaxVisAreaStart = pTextView->GetTextEngine()->GetTextHeight() - aOutSz.Height(); if ( nMaxVisAreaStart < 0 ) nMaxVisAreaStart = 0; if ( pTextView->GetStartDocPos().Y() > nMaxVisAreaStart ) { Point aStartDocPos( pTextView->GetStartDocPos() ); aStartDocPos.Y() = nMaxVisAreaStart; pTextView->SetStartDocPos( aStartDocPos ); pTextView->ShowCursor(); // pModulWindow->GetBreakPointWindow().GetCurYOffset() = aStartDocPos.Y(); } InitScrollBars(); if ( nVisY != pTextView->GetStartDocPos().Y() ) pTextView->GetWindow()->Invalidate(); } void AppEdit::PostLoad() { } // mit neuem Namen speichern void AppEdit::PostSaveAs() { } void AppEdit::Highlight( USHORT nLine, USHORT nCol1, USHORT nCol2 ) { ((TextEdit*)pDataEdit)->Highlight( nLine, nCol1, nCol2 ); ToTop(); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tabcontr.cxx,v $ * * $Revision: 1.18 $ * * last change: $Author: ihi $ $Date: 2006-11-14 14:47:21 $ * * 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_sd.hxx" #include "TabControl.hxx" #include <sfx2/viewfrm.hxx> #ifndef _SVDLAYER_HXX #include <svx/svdlayer.hxx> #endif #ifndef _SVDPAGV_HXX //autogen #include <svx/svdpagv.hxx> #endif #ifndef _SFXDISPATCH_HXX //autogen #include <sfx2/dispatch.hxx> #endif #include "sdattr.hxx" #include "app.hxx" #include "app.hrc" #include "glob.hrc" #include "res_bmp.hrc" #ifndef SD_DRAW_VIEW_SHELL_HXX #include "DrawViewShell.hxx" #endif #ifndef SD_GRAPHIC_VIEW_SHELL_HXX #include "GraphicViewShell.hxx" #endif #include "helpids.h" #ifndef SD_VIEW_HXX #include "View.hxx" #endif #include "sdpage.hxx" #include "drawdoc.hxx" #ifndef SD_WINDOW_HXX #include "Window.hxx" #endif #include "unmodpg.hxx" #include "DrawDocShell.hxx" #include "sdresid.hxx" namespace sd { #define SWITCH_TIMEOUT 20 // ----------------------------------------- // - SdTabControl::SdPageObjsTransferable - // ----------------------------------------- TabControl::TabControlTransferable::~TabControlTransferable() { } // ----------------------------------------------------------------------------- void TabControl::TabControlTransferable::AddSupportedFormats() { AddFormat( SOT_FORMATSTR_ID_STARDRAW_TABBAR ); } // ----------------------------------------------------------------------------- sal_Bool TabControl::TabControlTransferable::GetData( const ::com::sun::star::datatransfer::DataFlavor& rFlavor ) { return sal_False; } // ----------------------------------------------------------------------------- void TabControl::TabControlTransferable::DragFinished( sal_Int8 nDropAction ) { mrParent.DragFinished( nDropAction ); } /************************************************************************* |* |* Standard-Konstruktor |* \************************************************************************/ TabControl::TabControl(DrawViewShell* pViewSh, Window* pParent) : TabBar( pParent, WinBits( WB_BORDER | WB_3DLOOK | WB_SCROLL | WB_SIZEABLE | WB_DRAG) ), DragSourceHelper( this ), DropTargetHelper( this ), pDrViewSh(pViewSh), bInternalMove(FALSE) { EnableEditMode(); SetSizePixel(Size(0, 0)); SetMaxPageWidth( 150 ); SetHelpId( HID_SD_TABBAR_PAGES ); } /************************************************************************* |* |* Destruktor |* \************************************************************************/ TabControl::~TabControl() { } /************************************************************************* |* \************************************************************************/ void TabControl::Select() { SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher(); pDispatcher->Execute(SID_SWITCHPAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD); } /************************************************************************* |* \************************************************************************/ void TabControl::MouseButtonDown(const MouseEvent& rMEvt) { if (rMEvt.IsLeft() && !rMEvt.IsMod1() && !rMEvt.IsMod2() && !rMEvt.IsShift()) { Point aPos = PixelToLogic( rMEvt.GetPosPixel() ); USHORT aPageId = GetPageId(aPos); if (aPageId == 0) { SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher(); pDispatcher->Execute(SID_INSERTPAGE_QUICK, SFX_CALLMODE_SYNCHRON | SFX_CALLMODE_RECORD); } } // A single left click with pressed control key on a tab page first // switches to that page before the usual handling (copying with drag // and drop) takes place. else if (rMEvt.IsLeft() && rMEvt.IsMod1() && !rMEvt.IsMod2() && !rMEvt.IsShift()) { pDrViewSh->SwitchPage (GetPageId (rMEvt.GetPosPixel()) - 1); } // When only the right button is pressed then first process a // synthesized left button click to make the page the current one // whose tab has been clicked. When then the actual right button // click is processed the resulting context menu relates to the // now current page. if (rMEvt.IsRight() && ! rMEvt.IsLeft()) { MouseEvent aSyntheticEvent ( rMEvt.GetPosPixel(), rMEvt.GetClicks(), rMEvt.GetMode(), MOUSE_LEFT, rMEvt.GetModifier()); TabBar::MouseButtonDown(aSyntheticEvent); } TabBar::MouseButtonDown(rMEvt); } /************************************************************************* |* \************************************************************************/ void TabControl::DoubleClick() { if (GetCurPageId() != 0) { SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher(); pDispatcher->Execute( SID_MODIFYPAGE, SFX_CALLMODE_SYNCHRON | SFX_CALLMODE_RECORD ); } } /************************************************************************* |* |* StartDrag-Request |* \************************************************************************/ void TabControl::StartDrag( sal_Int8 nAction, const Point& rPosPixel ) { bInternalMove = TRUE; // object is delete by reference mechanismn ( new TabControl::TabControlTransferable( *this ) )->StartDrag( this, DND_ACTION_COPYMOVE ); } /************************************************************************* |* |* DragFinished |* \************************************************************************/ void TabControl::DragFinished( sal_Int8 nDropAction ) { bInternalMove = FALSE; } /************************************************************************* |* |* AcceptDrop-Event |* \************************************************************************/ sal_Int8 TabControl::AcceptDrop( const AcceptDropEvent& rEvt ) { sal_Int8 nRet = DND_ACTION_NONE; if( rEvt.mbLeaving ) EndSwitchPage(); if( !pDrViewSh->GetDocSh()->IsReadOnly() ) { SdDrawDocument* pDoc = pDrViewSh->GetDoc(); Point aPos( rEvt.maPosPixel ); if( bInternalMove ) { if( rEvt.mbLeaving || ( pDrViewSh->GetEditMode() == EM_MASTERPAGE ) ) HideDropPos(); else { ShowDropPos( aPos ); nRet = rEvt.mnAction; } } else { HideDropPos(); USHORT nPageId = GetPageId( aPos ) - 1; if( ( nPageId >= 0 ) && pDoc->GetPage( nPageId ) ) { ::sd::Window* pWindow = NULL; nRet = pDrViewSh->AcceptDrop( rEvt, *this, NULL, nPageId, SDRLAYER_NOTFOUND ); SwitchPage( aPos ); } } } return nRet; } /************************************************************************* |* |* ExecuteDrop-Event |* \************************************************************************/ sal_Int8 TabControl::ExecuteDrop( const ExecuteDropEvent& rEvt ) { SdDrawDocument* pDoc = pDrViewSh->GetDoc(); Point aPos( rEvt.maPosPixel ); sal_Int8 nRet = DND_ACTION_NONE; if( bInternalMove ) { USHORT nPageId = ShowDropPos( aPos ) - 1; switch (rEvt.mnAction) { case DND_ACTION_MOVE: if( pDrViewSh->IsSwitchPageAllowed() && pDoc->MovePages( nPageId ) ) { SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher(); pDispatcher->Execute(SID_SWITCHPAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD); } break; case DND_ACTION_COPY: { // Copying the selected page to the place that rEvt points // takes place in three steps: // 1. Create a copy of the selected page. This copy will // lie directly behind the selected page. // 2. Move the copy to the desired place. // 3. Select the copy. if (pDrViewSh->IsSwitchPageAllowed()) { // 1. Create a copy. USHORT nPageNumOfCopy = pDoc->DuplicatePage (GetCurPageId() - 1); // 2. Move page. For this first switch to the copy: // MovePages operates on the currently selected page(s). pDrViewSh->SwitchPage (nPageNumOfCopy); // Adapt target page id when necessary, i.e. page copy // has been inserted in front of the target page. USHORT nPageNum = nPageId; if ((nPageNumOfCopy <= nPageNum) && (nPageNum != (USHORT)-1)) nPageNum += 1; if (pDoc->MovePages(nPageNum)) { // 3. Switch to the copy that has been moved to its // final destination. Use an asynchron slot call to // be executed after the still pending ones. if (nPageNumOfCopy >= nPageNum || (nPageNum == (USHORT)-1)) nPageNum += 1; SetCurPageId (GetPageId(nPageNum)); SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher(); pDispatcher->Execute(SID_SWITCHPAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD); } } break; } } nRet = rEvt.mnAction; } else { USHORT nPageId = GetPageId( aPos ) - 1; if( ( nPageId >= 0 ) && pDoc->GetPage( nPageId ) ) { nRet = pDrViewSh->ExecuteDrop( rEvt, *this, NULL, nPageId, SDRLAYER_NOTFOUND ); } } HideDropPos(); EndSwitchPage(); return nRet; } /************************************************************************* |* \************************************************************************/ void TabControl::Command(const CommandEvent& rCEvt) { USHORT nCmd = rCEvt.GetCommand(); if ( nCmd == COMMAND_CONTEXTMENU ) { BOOL bGraphicShell = pDrViewSh->ISA(GraphicViewShell); USHORT nResId = bGraphicShell ? RID_GRAPHIC_PAGETAB_POPUP : RID_DRAW_PAGETAB_POPUP; SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher(); pDispatcher->ExecutePopup( SdResId( nResId ) ); } } /************************************************************************* |* \************************************************************************/ long TabControl::StartRenaming() { BOOL bOK = FALSE; if (pDrViewSh->GetPageKind() == PK_STANDARD) { bOK = TRUE; ::sd::View* pView = pDrViewSh->GetView(); if ( pView->IsTextEdit() ) pView->SdrEndTextEdit(); } return( bOK ); } /************************************************************************* |* \************************************************************************/ long TabControl::AllowRenaming() { BOOL bOK = TRUE; String aNewName( GetEditText() ); String aCompareName( GetPageText( GetEditPageId() ) ); if( aCompareName != aNewName ) { // Seite umbenennen if( pDrViewSh->GetDocSh()->CheckPageName( this, aNewName ) ) { SetEditText( aNewName ); EndRenaming(); } else { bOK = FALSE; } } return( bOK ); } /************************************************************************* |* \************************************************************************/ void TabControl::EndRenaming() { if( !IsEditModeCanceled() ) pDrViewSh->RenameSlide( GetEditPageId(), GetEditText() ); } /************************************************************************* |* \************************************************************************/ void TabControl::ActivatePage() { if ( /*IsInSwitching && */ pDrViewSh->IsSwitchPageAllowed() ) { SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher(); pDispatcher->Execute(SID_SWITCHPAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD); } } /************************************************************************* |* \************************************************************************/ long TabControl::DeactivatePage() { return pDrViewSh->IsSwitchPageAllowed(); } void TabControl::SendActivatePageEvent (void) { CallEventListeners (VCLEVENT_TABBAR_PAGEACTIVATED, reinterpret_cast<void*>(GetCurPageId())); } void TabControl::SendDeactivatePageEvent (void) { CallEventListeners (VCLEVENT_TABBAR_PAGEDEACTIVATED, reinterpret_cast<void*>(GetCurPageId())); } } // end of namespace sd <commit_msg>INTEGRATION: CWS sdwarningsbegone (1.17.36); FILE MERGED 2006/11/22 15:17:22 cl 1.17.36.2: RESYNC: (1.17-1.18); FILE MERGED 2006/11/22 12:42:31 cl 1.17.36.1: #i69285# warning free code changes for unxlngi6.pro<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: tabcontr.cxx,v $ * * $Revision: 1.19 $ * * last change: $Author: kz $ $Date: 2006-12-12 19:22:49 $ * * 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_sd.hxx" #include "TabControl.hxx" #include <sfx2/viewfrm.hxx> #ifndef _SVDLAYER_HXX #include <svx/svdlayer.hxx> #endif #ifndef _SVDPAGV_HXX //autogen #include <svx/svdpagv.hxx> #endif #ifndef _SFXDISPATCH_HXX //autogen #include <sfx2/dispatch.hxx> #endif #include "sdattr.hxx" #include "app.hxx" #include "app.hrc" #include "glob.hrc" #include "res_bmp.hrc" #ifndef SD_DRAW_VIEW_SHELL_HXX #include "DrawViewShell.hxx" #endif #ifndef SD_GRAPHIC_VIEW_SHELL_HXX #include "GraphicViewShell.hxx" #endif #include "helpids.h" #ifndef SD_VIEW_HXX #include "View.hxx" #endif #include "sdpage.hxx" #include "drawdoc.hxx" #ifndef SD_WINDOW_HXX #include "Window.hxx" #endif #include "unmodpg.hxx" #include "DrawDocShell.hxx" #include "sdresid.hxx" namespace sd { #define SWITCH_TIMEOUT 20 // ----------------------------------------- // - SdTabControl::SdPageObjsTransferable - // ----------------------------------------- TabControl::TabControlTransferable::~TabControlTransferable() { } // ----------------------------------------------------------------------------- void TabControl::TabControlTransferable::AddSupportedFormats() { AddFormat( SOT_FORMATSTR_ID_STARDRAW_TABBAR ); } // ----------------------------------------------------------------------------- sal_Bool TabControl::TabControlTransferable::GetData( const ::com::sun::star::datatransfer::DataFlavor& ) { return sal_False; } // ----------------------------------------------------------------------------- void TabControl::TabControlTransferable::DragFinished( sal_Int8 nDropAction ) { mrParent.DragFinished( nDropAction ); } /************************************************************************* |* |* Standard-Konstruktor |* \************************************************************************/ TabControl::TabControl(DrawViewShell* pViewSh, Window* pParent) : TabBar( pParent, WinBits( WB_BORDER | WB_3DLOOK | WB_SCROLL | WB_SIZEABLE | WB_DRAG) ), DragSourceHelper( this ), DropTargetHelper( this ), pDrViewSh(pViewSh), bInternalMove(FALSE) { EnableEditMode(); SetSizePixel(Size(0, 0)); SetMaxPageWidth( 150 ); SetHelpId( HID_SD_TABBAR_PAGES ); } /************************************************************************* |* |* Destruktor |* \************************************************************************/ TabControl::~TabControl() { } /************************************************************************* |* \************************************************************************/ void TabControl::Select() { SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher(); pDispatcher->Execute(SID_SWITCHPAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD); } /************************************************************************* |* \************************************************************************/ void TabControl::MouseButtonDown(const MouseEvent& rMEvt) { if (rMEvt.IsLeft() && !rMEvt.IsMod1() && !rMEvt.IsMod2() && !rMEvt.IsShift()) { Point aPos = PixelToLogic( rMEvt.GetPosPixel() ); USHORT aPageId = GetPageId(aPos); if (aPageId == 0) { SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher(); pDispatcher->Execute(SID_INSERTPAGE_QUICK, SFX_CALLMODE_SYNCHRON | SFX_CALLMODE_RECORD); } } // A single left click with pressed control key on a tab page first // switches to that page before the usual handling (copying with drag // and drop) takes place. else if (rMEvt.IsLeft() && rMEvt.IsMod1() && !rMEvt.IsMod2() && !rMEvt.IsShift()) { pDrViewSh->SwitchPage (GetPageId (rMEvt.GetPosPixel()) - 1); } // When only the right button is pressed then first process a // synthesized left button click to make the page the current one // whose tab has been clicked. When then the actual right button // click is processed the resulting context menu relates to the // now current page. if (rMEvt.IsRight() && ! rMEvt.IsLeft()) { MouseEvent aSyntheticEvent ( rMEvt.GetPosPixel(), rMEvt.GetClicks(), rMEvt.GetMode(), MOUSE_LEFT, rMEvt.GetModifier()); TabBar::MouseButtonDown(aSyntheticEvent); } TabBar::MouseButtonDown(rMEvt); } /************************************************************************* |* \************************************************************************/ void TabControl::DoubleClick() { if (GetCurPageId() != 0) { SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher(); pDispatcher->Execute( SID_MODIFYPAGE, SFX_CALLMODE_SYNCHRON | SFX_CALLMODE_RECORD ); } } /************************************************************************* |* |* StartDrag-Request |* \************************************************************************/ void TabControl::StartDrag( sal_Int8, const Point& ) { bInternalMove = TRUE; // object is delete by reference mechanismn ( new TabControl::TabControlTransferable( *this ) )->StartDrag( this, DND_ACTION_COPYMOVE ); } /************************************************************************* |* |* DragFinished |* \************************************************************************/ void TabControl::DragFinished( sal_Int8 ) { bInternalMove = FALSE; } /************************************************************************* |* |* AcceptDrop-Event |* \************************************************************************/ sal_Int8 TabControl::AcceptDrop( const AcceptDropEvent& rEvt ) { sal_Int8 nRet = DND_ACTION_NONE; if( rEvt.mbLeaving ) EndSwitchPage(); if( !pDrViewSh->GetDocSh()->IsReadOnly() ) { SdDrawDocument* pDoc = pDrViewSh->GetDoc(); Point aPos( rEvt.maPosPixel ); if( bInternalMove ) { if( rEvt.mbLeaving || ( pDrViewSh->GetEditMode() == EM_MASTERPAGE ) ) HideDropPos(); else { ShowDropPos( aPos ); nRet = rEvt.mnAction; } } else { HideDropPos(); sal_Int32 nPageId = GetPageId( aPos ) - 1; if( ( nPageId >= 0 ) && pDoc->GetPage( (USHORT)nPageId ) ) { nRet = pDrViewSh->AcceptDrop( rEvt, *this, NULL, (USHORT)nPageId, SDRLAYER_NOTFOUND ); SwitchPage( aPos ); } } } return nRet; } /************************************************************************* |* |* ExecuteDrop-Event |* \************************************************************************/ sal_Int8 TabControl::ExecuteDrop( const ExecuteDropEvent& rEvt ) { SdDrawDocument* pDoc = pDrViewSh->GetDoc(); Point aPos( rEvt.maPosPixel ); sal_Int8 nRet = DND_ACTION_NONE; if( bInternalMove ) { USHORT nPageId = ShowDropPos( aPos ) - 1; switch (rEvt.mnAction) { case DND_ACTION_MOVE: if( pDrViewSh->IsSwitchPageAllowed() && pDoc->MovePages( nPageId ) ) { SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher(); pDispatcher->Execute(SID_SWITCHPAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD); } break; case DND_ACTION_COPY: { // Copying the selected page to the place that rEvt points // takes place in three steps: // 1. Create a copy of the selected page. This copy will // lie directly behind the selected page. // 2. Move the copy to the desired place. // 3. Select the copy. if (pDrViewSh->IsSwitchPageAllowed()) { // 1. Create a copy. USHORT nPageNumOfCopy = pDoc->DuplicatePage (GetCurPageId() - 1); // 2. Move page. For this first switch to the copy: // MovePages operates on the currently selected page(s). pDrViewSh->SwitchPage (nPageNumOfCopy); // Adapt target page id when necessary, i.e. page copy // has been inserted in front of the target page. USHORT nPageNum = nPageId; if ((nPageNumOfCopy <= nPageNum) && (nPageNum != (USHORT)-1)) nPageNum += 1; if (pDoc->MovePages(nPageNum)) { // 3. Switch to the copy that has been moved to its // final destination. Use an asynchron slot call to // be executed after the still pending ones. if (nPageNumOfCopy >= nPageNum || (nPageNum == (USHORT)-1)) nPageNum += 1; SetCurPageId (GetPageId(nPageNum)); SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher(); pDispatcher->Execute(SID_SWITCHPAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD); } } break; } } nRet = rEvt.mnAction; } else { sal_Int32 nPageId = GetPageId( aPos ) - 1; if( ( nPageId >= 0 ) && pDoc->GetPage( (USHORT)nPageId ) ) { nRet = pDrViewSh->ExecuteDrop( rEvt, *this, NULL, (USHORT)nPageId, SDRLAYER_NOTFOUND ); } } HideDropPos(); EndSwitchPage(); return nRet; } /************************************************************************* |* \************************************************************************/ void TabControl::Command(const CommandEvent& rCEvt) { USHORT nCmd = rCEvt.GetCommand(); if ( nCmd == COMMAND_CONTEXTMENU ) { BOOL bGraphicShell = pDrViewSh->ISA(GraphicViewShell); USHORT nResId = bGraphicShell ? RID_GRAPHIC_PAGETAB_POPUP : RID_DRAW_PAGETAB_POPUP; SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher(); pDispatcher->ExecutePopup( SdResId( nResId ) ); } } /************************************************************************* |* \************************************************************************/ long TabControl::StartRenaming() { BOOL bOK = FALSE; if (pDrViewSh->GetPageKind() == PK_STANDARD) { bOK = TRUE; ::sd::View* pView = pDrViewSh->GetView(); if ( pView->IsTextEdit() ) pView->SdrEndTextEdit(); } return( bOK ); } /************************************************************************* |* \************************************************************************/ long TabControl::AllowRenaming() { BOOL bOK = TRUE; String aNewName( GetEditText() ); String aCompareName( GetPageText( GetEditPageId() ) ); if( aCompareName != aNewName ) { // Seite umbenennen if( pDrViewSh->GetDocSh()->CheckPageName( this, aNewName ) ) { SetEditText( aNewName ); EndRenaming(); } else { bOK = FALSE; } } return( bOK ); } /************************************************************************* |* \************************************************************************/ void TabControl::EndRenaming() { if( !IsEditModeCanceled() ) pDrViewSh->RenameSlide( GetEditPageId(), GetEditText() ); } /************************************************************************* |* \************************************************************************/ void TabControl::ActivatePage() { if ( /*IsInSwitching && */ pDrViewSh->IsSwitchPageAllowed() ) { SfxDispatcher* pDispatcher = pDrViewSh->GetViewFrame()->GetDispatcher(); pDispatcher->Execute(SID_SWITCHPAGE, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD); } } /************************************************************************* |* \************************************************************************/ long TabControl::DeactivatePage() { return pDrViewSh->IsSwitchPageAllowed(); } void TabControl::SendActivatePageEvent (void) { CallEventListeners (VCLEVENT_TABBAR_PAGEACTIVATED, reinterpret_cast<void*>(GetCurPageId())); } void TabControl::SendDeactivatePageEvent (void) { CallEventListeners (VCLEVENT_TABBAR_PAGEDEACTIVATED, reinterpret_cast<void*>(GetCurPageId())); } } // end of namespace sd <|endoftext|>
<commit_before>#include <aleph/containers/PointCloud.hh> #include <aleph/geometry/BetaSkeleton.hh> #include <aleph/geometry/HeatKernel.hh> #include <aleph/geometry/distances/Euclidean.hh> #include <iostream> #include <unordered_map> #include <string> #include <vector> using DataType = double; using Distance = aleph::distances::Euclidean<DataType>; using PointCloud = aleph::containers::PointCloud<DataType>; struct ScaleEstimationFunctor { template <class SimplicialComplex> std::vector<DataType> operator()( const SimplicialComplex& K ) { using Simplex = typename SimplicialComplex::ValueType; using VertexType = typename Simplex::VertexType; using IndexType = std::size_t; std::unordered_map<VertexType, IndexType> vertex_to_index; { std::vector<VertexType> vertices; K.vertices( std::back_inserter( vertices ) ); IndexType index = IndexType(); for( auto&& vertex : vertices ) vertex_to_index[vertex] = index++; } std::vector<DataType> sumOfWeights( vertex_to_index.size() ); std::vector<DataType> degree( vertex_to_index.size() ); for( auto&& simplex : K ) { if( simplex.dimension() != 1 ) continue; auto&& u = simplex[0]; auto&& v = simplex[1]; auto&& w = simplex.data(); auto&& i = vertex_to_index.at(u); auto&& j = vertex_to_index.at(v); degree[i] += 1; degree[j] += 1; sumOfWeights[i] += w; sumOfWeights[j] += w; } std::vector<DataType> scales( vertex_to_index.size() ); for( std::size_t i = 0; i < vertex_to_index.size(); i++ ) scales[i] = sumOfWeights[i] / degree[i]; return scales; } }; int main( int argc, char** argv ) { if( argc <= 1 ) return -1; auto filename = std::string( argv[1] ); auto pointCloud = aleph::containers::load<DataType>( filename ); std::cerr << "* Loaded point cloud with " << pointCloud.size() << " points\n"; // Skeleton construction --------------------------------------------- // TODO: make configurable DataType beta = 1.0; std::cerr << "* Calculating beta-skeleton with beta = " << beta << "..."; auto betaSkeleton = aleph::geometry::buildBetaSkeletonNaive( pointCloud, beta, Distance() ); std::cerr << "...finished\n" << "* Simplical complex has " << betaSkeleton.size() << " simplices\n"; // Scale estimation -------------------------------------------------- ScaleEstimationFunctor sef; auto scalesBefore = sef( betaSkeleton ); std::cerr << "* Initial scale information: "; for( auto&& s : scalesBefore ) std::cerr << s << " "; std::cerr << "\n"; } <commit_msg>Basic heat kernel application<commit_after>#include <aleph/containers/PointCloud.hh> #include <aleph/geometry/BetaSkeleton.hh> #include <aleph/geometry/HeatKernel.hh> #include <aleph/geometry/distances/Euclidean.hh> #include <iostream> #include <unordered_map> #include <string> #include <vector> using DataType = double; using Distance = aleph::distances::Euclidean<DataType>; using PointCloud = aleph::containers::PointCloud<DataType>; struct ScaleEstimationFunctor { template <class SimplicialComplex> std::vector<DataType> operator()( const SimplicialComplex& K ) { using Simplex = typename SimplicialComplex::ValueType; using VertexType = typename Simplex::VertexType; using IndexType = std::size_t; std::unordered_map<VertexType, IndexType> vertex_to_index; { std::vector<VertexType> vertices; K.vertices( std::back_inserter( vertices ) ); IndexType index = IndexType(); for( auto&& vertex : vertices ) vertex_to_index[vertex] = index++; } std::vector<DataType> sumOfWeights( vertex_to_index.size() ); std::vector<DataType> degree( vertex_to_index.size() ); for( auto&& simplex : K ) { if( simplex.dimension() != 1 ) continue; auto&& u = simplex[0]; auto&& v = simplex[1]; auto&& w = simplex.data(); auto&& i = vertex_to_index.at(u); auto&& j = vertex_to_index.at(v); degree[i] += 1; degree[j] += 1; sumOfWeights[i] += w; sumOfWeights[j] += w; } std::vector<DataType> scales( vertex_to_index.size() ); for( std::size_t i = 0; i < vertex_to_index.size(); i++ ) scales[i] = sumOfWeights[i] / degree[i]; return scales; } }; int main( int argc, char** argv ) { if( argc <= 1 ) return -1; auto filename = std::string( argv[1] ); auto pointCloud = aleph::containers::load<DataType>( filename ); std::cerr << "* Loaded point cloud with " << pointCloud.size() << " points\n"; // Skeleton construction --------------------------------------------- // TODO: make configurable DataType beta = 1.0; std::cerr << "* Calculating beta-skeleton with beta = " << beta << "..."; auto betaSkeleton = aleph::geometry::buildBetaSkeletonNaive( pointCloud, beta, Distance() ); std::cerr << "...finished\n" << "* Simplical complex has " << betaSkeleton.size() << " simplices\n"; // Scale estimation -------------------------------------------------- ScaleEstimationFunctor sef; auto scalesBefore = sef( betaSkeleton ); std::cerr << "* Initial scale information: "; for( auto&& s : scalesBefore ) std::cerr << s << " "; std::cerr << "\n"; // Heat kernel application ------------------------------------------- aleph::geometry::HeatKernel hk( betaSkeleton ); auto h0 = hk( 0.001 ); auto h1 = hk( 0.010 ); auto h2 = hk( 0.100 ); for( auto&& h : {h0,h1,h2} ) { for( std::size_t i = 0; i < scalesBefore.size(); i++ ) std::cout << scalesBefore.at(i) * h.at(i) << "\n"; std::cout << "\n"; } } <|endoftext|>
<commit_before>#include <vector> #include <string> #include <cstdlib> #include <botan/botan.h> #include <botan/lookup.h> #include <botan/filters.h> #if defined(BOTAN_HAS_RANDPOOL) #include <botan/randpool.h> #endif #if defined(BOTAN_HAS_X931_RNG) #include <botan/x931_rng.h> #endif #include "common.h" using namespace Botan; /* A weird little hack to fit S2K algorithms into the validation suite You probably wouldn't ever want to actually use the S2K algorithms like this, the raw S2K interface is more convenient for actually using them */ class S2K_Filter : public Filter { public: void write(const byte in[], u32bit len) { passphrase += std::string(reinterpret_cast<const char*>(in), len); } void end_msg() { s2k->change_salt(salt, salt.size()); s2k->set_iterations(iterations); SymmetricKey x = s2k->derive_key(outlen, passphrase); send(x.bits_of()); } S2K_Filter(S2K* algo, const SymmetricKey& s, u32bit o, u32bit i) { s2k = algo; outlen = o; iterations = i; salt = s.bits_of(); } ~S2K_Filter() { delete s2k; } private: std::string passphrase; S2K* s2k; SecureVector<byte> salt; u32bit outlen, iterations; }; /* Not too useful generally; just dumps random bits for benchmarking */ class RNG_Filter : public Filter { public: void write(const byte[], u32bit); RNG_Filter(RandomNumberGenerator* r) : rng(r) {} ~RNG_Filter() { delete rng; } private: RandomNumberGenerator* rng; }; class KDF_Filter : public Filter { public: void write(const byte in[], u32bit len) { secret.append(in, len); } void end_msg() { SymmetricKey x = kdf->derive_key(outlen, secret, secret.size(), salt, salt.size()); send(x.bits_of(), x.length()); } KDF_Filter(KDF* algo, const SymmetricKey& s, u32bit o) { kdf = algo; outlen = o; salt = s.bits_of(); } ~KDF_Filter() { delete kdf; } private: SecureVector<byte> secret; SecureVector<byte> salt; KDF* kdf; u32bit outlen; }; Filter* lookup_s2k(const std::string& algname, const std::vector<std::string>& params) { S2K* s2k = 0; try { s2k = get_s2k(algname); } catch(...) { } if(s2k) return new S2K_Filter(s2k, params[0], to_u32bit(params[1]), to_u32bit(params[2])); return 0; } void RNG_Filter::write(const byte[], u32bit length) { if(length) { SecureVector<byte> out(length); rng->randomize(out, out.size()); send(out); } } Filter* lookup_rng(const std::string& algname, const std::string& key) { RandomNumberGenerator* prng = 0; #if defined(BOTAN_HAS_X931_RNG) if(algname == "X9.31-RNG(TripleDES)") prng = new ANSI_X931_RNG(get_block_cipher("TripleDES"), new Fixed_Output_RNG(decode_hex(key))); else if(algname == "X9.31-RNG(AES-128)") prng = new ANSI_X931_RNG(get_block_cipher("AES-128"), new Fixed_Output_RNG(decode_hex(key))); else if(algname == "X9.31-RNG(AES-192)") prng = new ANSI_X931_RNG(get_block_cipher("AES-192"), new Fixed_Output_RNG(decode_hex(key))); else if(algname == "X9.31-RNG(AES-256)") prng = new ANSI_X931_RNG(get_block_cipher("AES-256"), new Fixed_Output_RNG(decode_hex(key))); #endif #if defined(BOTAN_HAS_X931_RNG) and defined(BOTAN_HAS_RANDPOOL) // these are used for benchmarking: AES-256/SHA-256 matches library // defaults, so benchmark reflects real-world performance (maybe) if(!prng && (algname == "Randpool" || algname == "X9.31-RNG")) { Randpool* randpool = new Randpool(get_block_cipher("AES-256"), get_mac("HMAC(SHA-256)")); randpool->add_entropy(reinterpret_cast<const byte*>(key.c_str()), key.length()); if(algname == "Randpool") prng = randpool; else prng = new ANSI_X931_RNG(get_block_cipher("AES-256"), randpool); } #endif if(prng) return new RNG_Filter(prng); return 0; } Filter* lookup_kdf(const std::string& algname, const std::string& salt, const std::string& params) { KDF* kdf = 0; try { kdf = get_kdf(algname); } catch(...) { return 0; } if(kdf) return new KDF_Filter(kdf, salt, to_u32bit(params)); return 0; } <commit_msg>MSVC does not recognize and as equiv to && in a preprocessor statement<commit_after>#include <vector> #include <string> #include <cstdlib> #include <botan/botan.h> #include <botan/lookup.h> #include <botan/filters.h> #if defined(BOTAN_HAS_RANDPOOL) #include <botan/randpool.h> #endif #if defined(BOTAN_HAS_X931_RNG) #include <botan/x931_rng.h> #endif #include "common.h" using namespace Botan; /* A weird little hack to fit S2K algorithms into the validation suite You probably wouldn't ever want to actually use the S2K algorithms like this, the raw S2K interface is more convenient for actually using them */ class S2K_Filter : public Filter { public: void write(const byte in[], u32bit len) { passphrase += std::string(reinterpret_cast<const char*>(in), len); } void end_msg() { s2k->change_salt(salt, salt.size()); s2k->set_iterations(iterations); SymmetricKey x = s2k->derive_key(outlen, passphrase); send(x.bits_of()); } S2K_Filter(S2K* algo, const SymmetricKey& s, u32bit o, u32bit i) { s2k = algo; outlen = o; iterations = i; salt = s.bits_of(); } ~S2K_Filter() { delete s2k; } private: std::string passphrase; S2K* s2k; SecureVector<byte> salt; u32bit outlen, iterations; }; /* Not too useful generally; just dumps random bits for benchmarking */ class RNG_Filter : public Filter { public: void write(const byte[], u32bit); RNG_Filter(RandomNumberGenerator* r) : rng(r) {} ~RNG_Filter() { delete rng; } private: RandomNumberGenerator* rng; }; class KDF_Filter : public Filter { public: void write(const byte in[], u32bit len) { secret.append(in, len); } void end_msg() { SymmetricKey x = kdf->derive_key(outlen, secret, secret.size(), salt, salt.size()); send(x.bits_of(), x.length()); } KDF_Filter(KDF* algo, const SymmetricKey& s, u32bit o) { kdf = algo; outlen = o; salt = s.bits_of(); } ~KDF_Filter() { delete kdf; } private: SecureVector<byte> secret; SecureVector<byte> salt; KDF* kdf; u32bit outlen; }; Filter* lookup_s2k(const std::string& algname, const std::vector<std::string>& params) { S2K* s2k = 0; try { s2k = get_s2k(algname); } catch(...) { } if(s2k) return new S2K_Filter(s2k, params[0], to_u32bit(params[1]), to_u32bit(params[2])); return 0; } void RNG_Filter::write(const byte[], u32bit length) { if(length) { SecureVector<byte> out(length); rng->randomize(out, out.size()); send(out); } } Filter* lookup_rng(const std::string& algname, const std::string& key) { RandomNumberGenerator* prng = 0; #if defined(BOTAN_HAS_X931_RNG) if(algname == "X9.31-RNG(TripleDES)") prng = new ANSI_X931_RNG(get_block_cipher("TripleDES"), new Fixed_Output_RNG(decode_hex(key))); else if(algname == "X9.31-RNG(AES-128)") prng = new ANSI_X931_RNG(get_block_cipher("AES-128"), new Fixed_Output_RNG(decode_hex(key))); else if(algname == "X9.31-RNG(AES-192)") prng = new ANSI_X931_RNG(get_block_cipher("AES-192"), new Fixed_Output_RNG(decode_hex(key))); else if(algname == "X9.31-RNG(AES-256)") prng = new ANSI_X931_RNG(get_block_cipher("AES-256"), new Fixed_Output_RNG(decode_hex(key))); #endif #if defined(BOTAN_HAS_X931_RNG) && defined(BOTAN_HAS_RANDPOOL) // these are used for benchmarking: AES-256/SHA-256 matches library // defaults, so benchmark reflects real-world performance (maybe) if(!prng && (algname == "Randpool" || algname == "X9.31-RNG")) { Randpool* randpool = new Randpool(get_block_cipher("AES-256"), get_mac("HMAC(SHA-256)")); randpool->add_entropy(reinterpret_cast<const byte*>(key.c_str()), key.length()); if(algname == "Randpool") prng = randpool; else prng = new ANSI_X931_RNG(get_block_cipher("AES-256"), randpool); } #endif if(prng) return new RNG_Filter(prng); return 0; } Filter* lookup_kdf(const std::string& algname, const std::string& salt, const std::string& params) { KDF* kdf = 0; try { kdf = get_kdf(algname); } catch(...) { return 0; } if(kdf) return new KDF_Filter(kdf, salt, to_u32bit(params)); return 0; } <|endoftext|>
<commit_before>#ifndef __Z2H_BINDER__ #define __Z2H_BINDER__ = 1 #include <stddef.h> #include <functional> #include "token.hpp" #include "symbol.hpp" #include "parser.hpp" using namespace std::placeholders; namespace z2h { template <typename TAst> class Token; template <typename TAst> class Symbol; template <typename TAst, typename TParser> class Parser; template <typename TAst> using StdFunc = std::function<TAst()>; template <typename TAst> using NudFunc = std::function<TAst(Token<TAst> *token)>; template <typename TAst> using LedFunc = std::function<TAst(TAst left, Token<TAst> *token)>; template <typename TAst> using ScanFunc = std::function<long(Symbol<TAst> *symbol, const std::string &source, size_t lbp)>; template <typename TAst, typename TParser> using StdPtr = TAst (TParser::*)(); template <typename TAst, typename TParser> using NudPtr = TAst (TParser::*)(Token<TAst> *token); template <typename TAst , typename TParser> using LedPtr = TAst (TParser::*)(TAst left, Token<TAst> *token); template <typename TAst, typename TParser> using ScanPtr = long (TParser::*)(Symbol<TAst> *symbol, const std::string &source, size_t lbp); template <typename TAst, typename TParser> struct Binder { StdFunc<TAst> BindStd(nullptr_t method) { return nullptr; } StdFunc<TAst> BindStd(StdPtr<TAst, TParser> method) { return std::bind(method, static_cast<TParser *>(this)); } NudFunc<TAst> BindNud(nullptr_t method) { return nullptr; } NudFunc<TAst> BindNud(NudPtr<TAst, TParser> method) { return std::bind(method, static_cast<TParser *>(this), _1); } LedFunc<TAst> BindLed(nullptr_t method) { return nullptr; } LedFunc<TAst> BindLed(LedPtr<TAst, TParser> method) { return std::bind(method, static_cast<TParser *>(this), _1, _2); } ScanFunc<TAst> BindScan(nullptr_t method) { return nullptr; } ScanFunc<TAst> BindScan(ScanPtr<TAst, TParser> method) { return std::bind(method, static_cast<TParser *>(this), _1, _2, _3); } }; } #endif /*__Z2H_BINDER__*/ <commit_msg>added support Nullptr... -sai<commit_after>#ifndef __Z2H_BINDER__ #define __Z2H_BINDER__ = 1 #include <stddef.h> #include <functional> #include "token.hpp" #include "symbol.hpp" #include "parser.hpp" using namespace std::placeholders; namespace z2h { template <typename TAst> class Token; template <typename TAst> class Symbol; template <typename TAst, typename TParser> class Parser; template <typename TAst> using StdFunc = std::function<TAst()>; template <typename TAst> using NudFunc = std::function<TAst(Token<TAst> *token)>; template <typename TAst> using LedFunc = std::function<TAst(TAst left, Token<TAst> *token)>; template <typename TAst> using ScanFunc = std::function<long(Symbol<TAst> *symbol, const std::string &source, size_t lbp)>; template <typename TAst, typename TParser> using StdPtr = TAst (TParser::*)(); template <typename TAst, typename TParser> using NudPtr = TAst (TParser::*)(Token<TAst> *token); template <typename TAst , typename TParser> using LedPtr = TAst (TParser::*)(TAst left, Token<TAst> *token); template <typename TAst, typename TParser> using ScanPtr = long (TParser::*)(Symbol<TAst> *symbol, const std::string &source, size_t lbp); template <typename TAst, typename TParser> struct Binder { static constexpr nullptr_t Nullptr = nullptr; StdFunc<TAst> BindStd(nullptr_t method) { return nullptr; } StdFunc<TAst> BindStd(const nullptr_t *method) { return nullptr; } StdFunc<TAst> BindStd(StdPtr<TAst, TParser> method) { return std::bind(method, static_cast<TParser *>(this)); } NudFunc<TAst> BindNud(nullptr_t method) { return nullptr; } NudFunc<TAst> BindNud(const nullptr_t *method) { return nullptr; } NudFunc<TAst> BindNud(NudPtr<TAst, TParser> method) { return std::bind(method, static_cast<TParser *>(this), _1); } LedFunc<TAst> BindLed(nullptr_t method) { return nullptr; } LedFunc<TAst> BindLed(const nullptr_t *method) { return nullptr; } LedFunc<TAst> BindLed(LedPtr<TAst, TParser> method) { return std::bind(method, static_cast<TParser *>(this), _1, _2); } ScanFunc<TAst> BindScan(nullptr_t method) { return nullptr; } ScanFunc<TAst> BindScan(const nullptr_t *method) { return nullptr; } ScanFunc<TAst> BindScan(ScanPtr<TAst, TParser> method) { return std::bind(method, static_cast<TParser *>(this), _1, _2, _3); } }; template <typename TAst, typename TParser> constexpr nullptr_t Binder<TAst, TParser>::Nullptr; } #endif /*__Z2H_BINDER__*/ <|endoftext|>
<commit_before><commit_msg>coverity#1103652 Unchecked return value<commit_after><|endoftext|>
<commit_before><commit_msg>Try to get rid of the SVG export code when DISABLE_EXPORT<commit_after><|endoftext|>
<commit_before>/* * PKCS#11 Mechanism * (C) 2016 Daniel Neus, Sirrix AG * (C) 2016 Philipp Weber, Sirrix AG * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/internal/p11_mechanism.h> #include <botan/rfc6979.h> #include <botan/scan_name.h> #include <botan/emsa.h> #include <tuple> namespace Botan { namespace PKCS11 { namespace { using PSS_Params = std::tuple<size_t, MechanismType, MGF>; // maps a PSS mechanism type to the number of bytes used for the salt, the mechanism type of the underlying hash algorithm and the MGF static const std::map<MechanismType, PSS_Params> PssOptions = { { MechanismType::RsaPkcsPss, PSS_Params(0, MechanismType::Sha1, MGF::Mgf1Sha1) }, { MechanismType::Sha1RsaPkcsPss, PSS_Params(20, MechanismType::Sha1, MGF::Mgf1Sha1) }, { MechanismType::Sha224RsaPkcsPss, PSS_Params(28, MechanismType::Sha224, MGF::Mgf1Sha224) }, { MechanismType::Sha256RsaPkcsPss, PSS_Params(32, MechanismType::Sha256, MGF::Mgf1Sha256) }, { MechanismType::Sha384RsaPkcsPss, PSS_Params(48, MechanismType::Sha384, MGF::Mgf1Sha384) }, { MechanismType::Sha512RsaPkcsPss, PSS_Params(64, MechanismType::Sha512, MGF::Mgf1Sha512) } }; struct MechanismData { explicit MechanismData(MechanismType _type) : type(_type) {} virtual ~MechanismData() = default; // the mechanism to perform MechanismType type; }; struct RSA_SignMechanism : public MechanismData { explicit RSA_SignMechanism(MechanismType _type) : MechanismData(_type), hash(static_cast<MechanismType>(0)), mgf(static_cast<MGF>(0)), salt_size(0) { auto pss_option = PssOptions.find(type); if(pss_option != PssOptions.end()) { hash = std::get<1>(pss_option->second); mgf = std::get<2>(pss_option->second); salt_size = std::get<0>(pss_option->second); } } // hash algorithm used in the PSS encoding; if the signature mechanism does not include message hashing, // then this value must be the mechanism used by the application to generate the message hash; // if the signature mechanism includes hashing, then this value must match the hash algorithm indicated by the signature mechanism MechanismType hash; // mask generation function to use on the encoded block MGF mgf; // length, in bytes, of the salt value used in the PSS encoding; typical values are the length of the message hash and zero size_t salt_size; }; // note: when updating this map, update the documentation for `MechanismWrapper::create_rsa_sign_mechanism` static std::map<std::string, RSA_SignMechanism> SignMechanisms = { { "Raw", RSA_SignMechanism(MechanismType::RsaX509) }, { "EMSA2(Raw)", RSA_SignMechanism(MechanismType::RsaX931) }, { "EMSA2(SHA-1)", RSA_SignMechanism(MechanismType::Sha1RsaX931) }, // RSASSA PKCS#1 v1.5 { "EMSA3(Raw)", RSA_SignMechanism(MechanismType::RsaPkcs) }, { "EMSA3(SHA-1)", RSA_SignMechanism(MechanismType::Sha1RsaPkcs) }, { "EMSA3(SHA-224)", RSA_SignMechanism(MechanismType::Sha224RsaPkcs) }, { "EMSA3(SHA-256)", RSA_SignMechanism(MechanismType::Sha256RsaPkcs) }, { "EMSA3(SHA-384)", RSA_SignMechanism(MechanismType::Sha384RsaPkcs) }, { "EMSA3(SHA-512)", RSA_SignMechanism(MechanismType::Sha512RsaPkcs) }, // RSASSA PKCS#1 PSS { "EMSA4(Raw)", RSA_SignMechanism(MechanismType::RsaPkcsPss) }, { "EMSA4(SHA-1)", RSA_SignMechanism(MechanismType::Sha1RsaPkcsPss) }, { "EMSA4(SHA-224)", RSA_SignMechanism(MechanismType::Sha224RsaPkcsPss) }, { "EMSA4(SHA-256)", RSA_SignMechanism(MechanismType::Sha256RsaPkcsPss) }, { "EMSA4(SHA-384)", RSA_SignMechanism(MechanismType::Sha384RsaPkcsPss) }, { "EMSA4(SHA-512)", RSA_SignMechanism(MechanismType::Sha512RsaPkcsPss) }, { "ISO9796", RSA_SignMechanism(MechanismType::Rsa9796) } }; struct RSA_CryptMechanism : public MechanismData { RSA_CryptMechanism(MechanismType _type, size_t _padding_size, MechanismType _hash, MGF _mgf) : MechanismData(_type), hash(_hash), mgf(_mgf), padding_size(_padding_size) {} RSA_CryptMechanism(MechanismType _type, size_t _padding_size) : RSA_CryptMechanism(_type, _padding_size, static_cast<MechanismType>(0), static_cast<MGF>(0)) {} // mechanism ID of the message digest algorithm used to calculate the digest of the encoding parameter MechanismType hash; // mask generation function to use on the encoded block MGF mgf; // number of bytes required for the padding size_t padding_size; }; // note: when updating this map, update the documentation for `MechanismWrapper::create_rsa_crypt_mechanism` static const std::map<std::string, RSA_CryptMechanism> CryptMechanisms = { { "Raw", RSA_CryptMechanism(MechanismType::RsaX509, 0) }, { "EME-PKCS1-v1_5", RSA_CryptMechanism(MechanismType::RsaPkcs, 11) }, { "OAEP(SHA-1)", RSA_CryptMechanism(MechanismType::RsaPkcsOaep, 2 + 2 * 20, MechanismType::Sha1, MGF::Mgf1Sha1) }, { "OAEP(SHA-224)", RSA_CryptMechanism(MechanismType::RsaPkcsOaep, 2 + 2 * 28, MechanismType::Sha224, MGF::Mgf1Sha224) }, { "OAEP(SHA-256)", RSA_CryptMechanism(MechanismType::RsaPkcsOaep, 2 + 2 * 32, MechanismType::Sha256, MGF::Mgf1Sha256) }, { "OAEP(SHA-384)", RSA_CryptMechanism(MechanismType::RsaPkcsOaep, 2 + 2 * 48, MechanismType::Sha384, MGF::Mgf1Sha384) }, { "OAEP(SHA-512)", RSA_CryptMechanism(MechanismType::RsaPkcsOaep, 2 + 2 * 64, MechanismType::Sha512, MGF::Mgf1Sha512) } }; // note: when updating this map, update the documentation for `MechanismWrapper::create_ecdsa_mechanism` static std::map<std::string, MechanismType> EcdsaHash = { { "Raw", MechanismType::Ecdsa }, { "SHA-160", MechanismType::EcdsaSha1 }, { "SHA-224", MechanismType::EcdsaSha224 }, { "SHA-256", MechanismType::EcdsaSha256 }, { "SHA-384", MechanismType::EcdsaSha384 }, { "SHA-512", MechanismType::EcdsaSha512 } }; // note: when updating this map, update the documentation for `MechanismWrapper::create_ecdh_mechanism` static std::map<std::string, KeyDerivation> EcdhHash = { { "Raw", KeyDerivation::Null }, { "SHA-160", KeyDerivation::Sha1Kdf }, { "SHA-224", KeyDerivation::Sha224Kdf }, { "SHA-256", KeyDerivation::Sha256Kdf }, { "SHA-384", KeyDerivation::Sha384Kdf }, { "SHA-512", KeyDerivation::Sha512Kdf } }; } MechanismWrapper::MechanismWrapper(MechanismType mechanism_type) : m_mechanism( { static_cast<CK_MECHANISM_TYPE>(mechanism_type), nullptr, 0 }), m_parameters(nullptr) {} MechanismWrapper MechanismWrapper::create_rsa_crypt_mechanism(const std::string& padding) { auto mechanism_info_it = CryptMechanisms.find(padding); if(mechanism_info_it == CryptMechanisms.end()) { // at this point it would be possible to support additional configurations that are not predefined above by parsing `padding` throw Lookup_Error("PKCS#11 RSA encrypt/decrypt does not support EME " + padding); } RSA_CryptMechanism mechanism_info = mechanism_info_it->second; MechanismWrapper mech(mechanism_info.type); if(mechanism_info.type == MechanismType::RsaPkcsOaep) { mech.m_parameters = std::make_shared<MechanismParameters>(); mech.m_parameters->oaep_params.hashAlg = static_cast<CK_MECHANISM_TYPE>(mechanism_info.hash); mech.m_parameters->oaep_params.mgf = static_cast<CK_RSA_PKCS_MGF_TYPE>(mechanism_info.mgf); mech.m_parameters->oaep_params.source = CKZ_DATA_SPECIFIED; mech.m_parameters->oaep_params.pSourceData = nullptr; mech.m_parameters->oaep_params.ulSourceDataLen = 0; mech.m_mechanism.pParameter = mech.m_parameters.get(); mech.m_mechanism.ulParameterLen = sizeof(RsaPkcsOaepParams); } mech.m_padding_size = mechanism_info.padding_size; return mech; } MechanismWrapper MechanismWrapper::create_rsa_sign_mechanism(const std::string& padding) { auto mechanism_info_it = SignMechanisms.find(padding); if(mechanism_info_it == SignMechanisms.end()) { // at this point it would be possible to support additional configurations that are not predefined above by parsing `padding` throw Lookup_Error("PKCS#11 RSA sign/verify does not support EMSA " + padding); } RSA_SignMechanism mechanism_info = mechanism_info_it->second; MechanismWrapper mech(mechanism_info.type); if(PssOptions.find(mechanism_info.type) != PssOptions.end()) { mech.m_parameters = std::make_shared<MechanismParameters>(); mech.m_parameters->pss_params.hashAlg = static_cast<CK_MECHANISM_TYPE>(mechanism_info.hash); mech.m_parameters->pss_params.mgf = static_cast<CK_RSA_PKCS_MGF_TYPE>(mechanism_info.mgf); mech.m_parameters->pss_params.sLen = mechanism_info.salt_size; mech.m_mechanism.pParameter = mech.m_parameters.get(); mech.m_mechanism.ulParameterLen = sizeof(RsaPkcsPssParams); } return mech; } MechanismWrapper MechanismWrapper::create_ecdsa_mechanism(const std::string& hash) { std::string hash_name = hash; if(hash_name != "Raw") { hash_name = hash_for_emsa(hash); } auto mechanism_type = EcdsaHash.find(hash_name); if(mechanism_type == EcdsaHash.end()) { throw Lookup_Error("PKCS#11 ECDSA sign/verify does not support " + hash); } return MechanismWrapper(mechanism_type->second); } MechanismWrapper MechanismWrapper::create_ecdh_mechanism(const std::string& kdf_name, bool use_cofactor) { std::string hash = kdf_name; if(kdf_name != "Raw") { SCAN_Name kdf_hash(kdf_name); if(kdf_hash.arg_count() > 0) { hash = kdf_hash.arg(0); } } auto kdf = EcdhHash.find(hash); if(kdf == EcdhHash.end()) { throw Lookup_Error("PKCS#11 ECDH key derivation does not support KDF " + kdf_name); } MechanismWrapper mech(use_cofactor ? MechanismType::Ecdh1CofactorDerive : MechanismType::Ecdh1Derive); mech.m_parameters = std::make_shared<MechanismParameters>(); mech.m_parameters->ecdh_params.kdf = static_cast<CK_EC_KDF_TYPE>(kdf->second); mech.m_mechanism.pParameter = mech.m_parameters.get(); mech.m_mechanism.ulParameterLen = sizeof(Ecdh1DeriveParams); return mech; } } } <commit_msg>remove unnecessary include<commit_after>/* * PKCS#11 Mechanism * (C) 2016 Daniel Neus, Sirrix AG * (C) 2016 Philipp Weber, Sirrix AG * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/internal/p11_mechanism.h> #include <botan/scan_name.h> #include <botan/emsa.h> #include <tuple> namespace Botan { namespace PKCS11 { namespace { using PSS_Params = std::tuple<size_t, MechanismType, MGF>; // maps a PSS mechanism type to the number of bytes used for the salt, the mechanism type of the underlying hash algorithm and the MGF static const std::map<MechanismType, PSS_Params> PssOptions = { { MechanismType::RsaPkcsPss, PSS_Params(0, MechanismType::Sha1, MGF::Mgf1Sha1) }, { MechanismType::Sha1RsaPkcsPss, PSS_Params(20, MechanismType::Sha1, MGF::Mgf1Sha1) }, { MechanismType::Sha224RsaPkcsPss, PSS_Params(28, MechanismType::Sha224, MGF::Mgf1Sha224) }, { MechanismType::Sha256RsaPkcsPss, PSS_Params(32, MechanismType::Sha256, MGF::Mgf1Sha256) }, { MechanismType::Sha384RsaPkcsPss, PSS_Params(48, MechanismType::Sha384, MGF::Mgf1Sha384) }, { MechanismType::Sha512RsaPkcsPss, PSS_Params(64, MechanismType::Sha512, MGF::Mgf1Sha512) } }; struct MechanismData { explicit MechanismData(MechanismType _type) : type(_type) {} virtual ~MechanismData() = default; // the mechanism to perform MechanismType type; }; struct RSA_SignMechanism : public MechanismData { explicit RSA_SignMechanism(MechanismType _type) : MechanismData(_type), hash(static_cast<MechanismType>(0)), mgf(static_cast<MGF>(0)), salt_size(0) { auto pss_option = PssOptions.find(type); if(pss_option != PssOptions.end()) { hash = std::get<1>(pss_option->second); mgf = std::get<2>(pss_option->second); salt_size = std::get<0>(pss_option->second); } } // hash algorithm used in the PSS encoding; if the signature mechanism does not include message hashing, // then this value must be the mechanism used by the application to generate the message hash; // if the signature mechanism includes hashing, then this value must match the hash algorithm indicated by the signature mechanism MechanismType hash; // mask generation function to use on the encoded block MGF mgf; // length, in bytes, of the salt value used in the PSS encoding; typical values are the length of the message hash and zero size_t salt_size; }; // note: when updating this map, update the documentation for `MechanismWrapper::create_rsa_sign_mechanism` static std::map<std::string, RSA_SignMechanism> SignMechanisms = { { "Raw", RSA_SignMechanism(MechanismType::RsaX509) }, { "EMSA2(Raw)", RSA_SignMechanism(MechanismType::RsaX931) }, { "EMSA2(SHA-1)", RSA_SignMechanism(MechanismType::Sha1RsaX931) }, // RSASSA PKCS#1 v1.5 { "EMSA3(Raw)", RSA_SignMechanism(MechanismType::RsaPkcs) }, { "EMSA3(SHA-1)", RSA_SignMechanism(MechanismType::Sha1RsaPkcs) }, { "EMSA3(SHA-224)", RSA_SignMechanism(MechanismType::Sha224RsaPkcs) }, { "EMSA3(SHA-256)", RSA_SignMechanism(MechanismType::Sha256RsaPkcs) }, { "EMSA3(SHA-384)", RSA_SignMechanism(MechanismType::Sha384RsaPkcs) }, { "EMSA3(SHA-512)", RSA_SignMechanism(MechanismType::Sha512RsaPkcs) }, // RSASSA PKCS#1 PSS { "EMSA4(Raw)", RSA_SignMechanism(MechanismType::RsaPkcsPss) }, { "EMSA4(SHA-1)", RSA_SignMechanism(MechanismType::Sha1RsaPkcsPss) }, { "EMSA4(SHA-224)", RSA_SignMechanism(MechanismType::Sha224RsaPkcsPss) }, { "EMSA4(SHA-256)", RSA_SignMechanism(MechanismType::Sha256RsaPkcsPss) }, { "EMSA4(SHA-384)", RSA_SignMechanism(MechanismType::Sha384RsaPkcsPss) }, { "EMSA4(SHA-512)", RSA_SignMechanism(MechanismType::Sha512RsaPkcsPss) }, { "ISO9796", RSA_SignMechanism(MechanismType::Rsa9796) } }; struct RSA_CryptMechanism : public MechanismData { RSA_CryptMechanism(MechanismType _type, size_t _padding_size, MechanismType _hash, MGF _mgf) : MechanismData(_type), hash(_hash), mgf(_mgf), padding_size(_padding_size) {} RSA_CryptMechanism(MechanismType _type, size_t _padding_size) : RSA_CryptMechanism(_type, _padding_size, static_cast<MechanismType>(0), static_cast<MGF>(0)) {} // mechanism ID of the message digest algorithm used to calculate the digest of the encoding parameter MechanismType hash; // mask generation function to use on the encoded block MGF mgf; // number of bytes required for the padding size_t padding_size; }; // note: when updating this map, update the documentation for `MechanismWrapper::create_rsa_crypt_mechanism` static const std::map<std::string, RSA_CryptMechanism> CryptMechanisms = { { "Raw", RSA_CryptMechanism(MechanismType::RsaX509, 0) }, { "EME-PKCS1-v1_5", RSA_CryptMechanism(MechanismType::RsaPkcs, 11) }, { "OAEP(SHA-1)", RSA_CryptMechanism(MechanismType::RsaPkcsOaep, 2 + 2 * 20, MechanismType::Sha1, MGF::Mgf1Sha1) }, { "OAEP(SHA-224)", RSA_CryptMechanism(MechanismType::RsaPkcsOaep, 2 + 2 * 28, MechanismType::Sha224, MGF::Mgf1Sha224) }, { "OAEP(SHA-256)", RSA_CryptMechanism(MechanismType::RsaPkcsOaep, 2 + 2 * 32, MechanismType::Sha256, MGF::Mgf1Sha256) }, { "OAEP(SHA-384)", RSA_CryptMechanism(MechanismType::RsaPkcsOaep, 2 + 2 * 48, MechanismType::Sha384, MGF::Mgf1Sha384) }, { "OAEP(SHA-512)", RSA_CryptMechanism(MechanismType::RsaPkcsOaep, 2 + 2 * 64, MechanismType::Sha512, MGF::Mgf1Sha512) } }; // note: when updating this map, update the documentation for `MechanismWrapper::create_ecdsa_mechanism` static std::map<std::string, MechanismType> EcdsaHash = { { "Raw", MechanismType::Ecdsa }, { "SHA-160", MechanismType::EcdsaSha1 }, { "SHA-224", MechanismType::EcdsaSha224 }, { "SHA-256", MechanismType::EcdsaSha256 }, { "SHA-384", MechanismType::EcdsaSha384 }, { "SHA-512", MechanismType::EcdsaSha512 } }; // note: when updating this map, update the documentation for `MechanismWrapper::create_ecdh_mechanism` static std::map<std::string, KeyDerivation> EcdhHash = { { "Raw", KeyDerivation::Null }, { "SHA-160", KeyDerivation::Sha1Kdf }, { "SHA-224", KeyDerivation::Sha224Kdf }, { "SHA-256", KeyDerivation::Sha256Kdf }, { "SHA-384", KeyDerivation::Sha384Kdf }, { "SHA-512", KeyDerivation::Sha512Kdf } }; } MechanismWrapper::MechanismWrapper(MechanismType mechanism_type) : m_mechanism( { static_cast<CK_MECHANISM_TYPE>(mechanism_type), nullptr, 0 }), m_parameters(nullptr) {} MechanismWrapper MechanismWrapper::create_rsa_crypt_mechanism(const std::string& padding) { auto mechanism_info_it = CryptMechanisms.find(padding); if(mechanism_info_it == CryptMechanisms.end()) { // at this point it would be possible to support additional configurations that are not predefined above by parsing `padding` throw Lookup_Error("PKCS#11 RSA encrypt/decrypt does not support EME " + padding); } RSA_CryptMechanism mechanism_info = mechanism_info_it->second; MechanismWrapper mech(mechanism_info.type); if(mechanism_info.type == MechanismType::RsaPkcsOaep) { mech.m_parameters = std::make_shared<MechanismParameters>(); mech.m_parameters->oaep_params.hashAlg = static_cast<CK_MECHANISM_TYPE>(mechanism_info.hash); mech.m_parameters->oaep_params.mgf = static_cast<CK_RSA_PKCS_MGF_TYPE>(mechanism_info.mgf); mech.m_parameters->oaep_params.source = CKZ_DATA_SPECIFIED; mech.m_parameters->oaep_params.pSourceData = nullptr; mech.m_parameters->oaep_params.ulSourceDataLen = 0; mech.m_mechanism.pParameter = mech.m_parameters.get(); mech.m_mechanism.ulParameterLen = sizeof(RsaPkcsOaepParams); } mech.m_padding_size = mechanism_info.padding_size; return mech; } MechanismWrapper MechanismWrapper::create_rsa_sign_mechanism(const std::string& padding) { auto mechanism_info_it = SignMechanisms.find(padding); if(mechanism_info_it == SignMechanisms.end()) { // at this point it would be possible to support additional configurations that are not predefined above by parsing `padding` throw Lookup_Error("PKCS#11 RSA sign/verify does not support EMSA " + padding); } RSA_SignMechanism mechanism_info = mechanism_info_it->second; MechanismWrapper mech(mechanism_info.type); if(PssOptions.find(mechanism_info.type) != PssOptions.end()) { mech.m_parameters = std::make_shared<MechanismParameters>(); mech.m_parameters->pss_params.hashAlg = static_cast<CK_MECHANISM_TYPE>(mechanism_info.hash); mech.m_parameters->pss_params.mgf = static_cast<CK_RSA_PKCS_MGF_TYPE>(mechanism_info.mgf); mech.m_parameters->pss_params.sLen = mechanism_info.salt_size; mech.m_mechanism.pParameter = mech.m_parameters.get(); mech.m_mechanism.ulParameterLen = sizeof(RsaPkcsPssParams); } return mech; } MechanismWrapper MechanismWrapper::create_ecdsa_mechanism(const std::string& hash) { std::string hash_name = hash; if(hash_name != "Raw") { hash_name = hash_for_emsa(hash); } auto mechanism_type = EcdsaHash.find(hash_name); if(mechanism_type == EcdsaHash.end()) { throw Lookup_Error("PKCS#11 ECDSA sign/verify does not support " + hash); } return MechanismWrapper(mechanism_type->second); } MechanismWrapper MechanismWrapper::create_ecdh_mechanism(const std::string& kdf_name, bool use_cofactor) { std::string hash = kdf_name; if(kdf_name != "Raw") { SCAN_Name kdf_hash(kdf_name); if(kdf_hash.arg_count() > 0) { hash = kdf_hash.arg(0); } } auto kdf = EcdhHash.find(hash); if(kdf == EcdhHash.end()) { throw Lookup_Error("PKCS#11 ECDH key derivation does not support KDF " + kdf_name); } MechanismWrapper mech(use_cofactor ? MechanismType::Ecdh1CofactorDerive : MechanismType::Ecdh1Derive); mech.m_parameters = std::make_shared<MechanismParameters>(); mech.m_parameters->ecdh_params.kdf = static_cast<CK_EC_KDF_TYPE>(kdf->second); mech.m_mechanism.pParameter = mech.m_parameters.get(); mech.m_mechanism.ulParameterLen = sizeof(Ecdh1DeriveParams); return mech; } } } <|endoftext|>
<commit_before>// Copyright (2015) Gustav #include "finans/core/commandline.h" #include "gtest/gtest.h" #include "gmock/gmock.h" using namespace testing; class TestSubParser : public argparse::SubParser { public: TestSubParser() { } void AddParser(argparse::Parser& parser) override { parser("-name", name); } void ParseCompleted() override { } std::string name; }; struct CommandlineTest : public Test { std::ostringstream output; std::ostringstream error; argparse::Parser parser; std::string animal; std::string another; TestSubParser sp1; TestSubParser sp2; argparse::Parser sub; CommandlineTest() : parser("description"), sub("description") { parser("pos", animal)("-op", another); sub.AddSubParser("one", &sp1).AddSubParser("two", &sp2); } }; #define GTEST(x) TEST_F(CommandlineTest, x) GTEST(TestEmpty) { const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") .ParseArgs(argparse::Arguments("app.exe", {}), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); } GTEST(TestError) { const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") .ParseArgs(argparse::Arguments("app.exe", { "hello", "world" }), output, error); EXPECT_EQ(false, ok); EXPECT_EQ("Usage: [-h]\n", output.str()); EXPECT_EQ("error: All positional arguments have been consumed: hello\n", error.str()); } GTEST(TestOptionalDefault) { int op = 2; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") ("-op", op) .ParseArgs(argparse::Arguments("app.exe", {}), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ(2, op); } GTEST(TestOptionalValue) { int op = 2; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") ("-op", op) .ParseArgs(argparse::Arguments("app.exe", {"-op", "42"}), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ(42, op); } GTEST(TestPositionalValue) { int op = 2; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") ("op", op) .ParseArgs(argparse::Arguments("app.exe", { "42" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ(42, op); } GTEST(TestPositionalValueErr) { int op = 42; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") ("op", op) .ParseArgs(argparse::Arguments("app.exe", {}), output, error); EXPECT_EQ(false, ok); EXPECT_EQ("error: too few arguments.\n", error.str()); EXPECT_EQ("Usage: [-h] [op]\n", output.str()); EXPECT_EQ(42, op); // not touched } GTEST(TestStdVector) { std::vector<std::string> strings; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") .AddGreedy("-strings", strings, "string") .ParseArgs(argparse::Arguments("app.exe", {"-strings", "cat", "dog", "fish"}), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_THAT(strings, ElementsAre("cat", "dog", "fish")); } GTEST(TestStdVectorInts) { std::vector<int> ints; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") .AddGreedy("-ints", ints, "string") .ParseArgs(argparse::Arguments("app.exe", { "-ints", "2", "3", "-5", "4" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_THAT(ints, ElementsAre(2, 3, -5, 4)); } GTEST(TestNonGreedyVector) { std::vector<std::string> strings; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") ("-s", strings) .ParseArgs(argparse::Arguments("app.exe", { "-s", "cat", "-s", "dog", "-s", "fish" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_THAT(strings, ElementsAre("cat", "dog", "fish")); } enum class Day { TODAY, YESTERDAY, TOMORROW }; ARGPARSE_DEFINE_ENUM(Day, "day", ("Today", Day::TODAY)("Tomorrow", Day::TOMORROW)("Yesterday", Day::YESTERDAY) ) GTEST(TestEnum) { Day op = Day::TOMORROW; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") ("op", op) .ParseArgs(argparse::Arguments("app.exe", { "tod" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ(Day::TODAY, op); } GTEST(TestCommaOp) { int op = 2; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") ("-int,-i", op) .ParseArgs(argparse::Arguments("app.exe", { "-int", "42" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ(42, op); } GTEST(TestSpecifyTwice) { int op = 2; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") ("-int,-i", op) .ParseArgs(argparse::Arguments("app.exe", { "-int", "42", "-i", "50" }), output, error); EXPECT_EQ(false, ok); EXPECT_EQ("error: All positional arguments have been consumed: -i\n", error.str()); EXPECT_EQ("Usage: [-h] [-int,-i [int]]\n", output.str()); EXPECT_EQ(42, op); } GTEST(TestPrecedencePos) { const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", {"dog"}), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ("dog", animal); EXPECT_EQ("", another); } GTEST(TestPrecedencePosOp) { const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-dog", "-op", "cat" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ("-dog", animal); EXPECT_EQ("cat", another); } GTEST(TestPrecedenceOpPos) { const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-op", "cat", "dog" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ("dog", animal); EXPECT_EQ("cat", another); } GTEST(TestStoreConstInt) { int op = 12; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") .StoreConst("-store", op, 42) .ParseArgs(argparse::Arguments("app.exe", { "-store" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ(42, op); } GTEST(TestStoreConstString) { std::string op = ""; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") .StoreConst<std::string>("-store", op, "dog") .ParseArgs(argparse::Arguments("app.exe", { "-store" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ("dog", op); } GTEST(TestSubParserBasic) { const bool ok = argparse::Parser::ParseComplete == sub.ParseArgs(argparse::Arguments("app.exe", { "one", "-name", "dog" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ("dog", sp1.name); EXPECT_EQ("", sp2.name); } GTEST(TestSubParserOptional) { std::string op = ""; sub("-op", op); const bool ok = argparse::Parser::ParseComplete == sub.ParseArgs(argparse::Arguments("app.exe", { "-op", "cat", "on", "-name", "dog" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ("cat", op); EXPECT_EQ("dog", sp1.name); EXPECT_EQ("", sp2.name); } GTEST(TestSubParserPositional) { std::string op = ""; sub("op", op); const bool ok = argparse::Parser::ParseComplete == sub.ParseArgs(argparse::Arguments("app.exe", { "cat", "on", "-name", "dog" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ("cat", op); EXPECT_EQ("dog", sp1.name); EXPECT_EQ("", sp2.name); } // todo: test error // todo: test help string <commit_msg>added expected output error<commit_after>// Copyright (2015) Gustav #include "finans/core/commandline.h" #include "gtest/gtest.h" #include "gmock/gmock.h" using namespace testing; class TestSubParser : public argparse::SubParser { public: TestSubParser() { } void AddParser(argparse::Parser& parser) override { parser("-name", name); } void ParseCompleted() override { } std::string name; }; struct CommandlineTest : public Test { std::ostringstream output; std::ostringstream error; argparse::Parser parser; std::string animal; std::string another; TestSubParser sp1; TestSubParser sp2; argparse::Parser sub; CommandlineTest() : parser("description"), sub("description") { parser("pos", animal)("-op", another); sub.AddSubParser("one", &sp1).AddSubParser("two", &sp2); } }; #define GTEST(x) TEST_F(CommandlineTest, x) GTEST(TestEmpty) { const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") .ParseArgs(argparse::Arguments("app.exe", {}), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); } GTEST(TestError) { const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") .ParseArgs(argparse::Arguments("app.exe", { "hello", "world" }), output, error); EXPECT_EQ(false, ok); EXPECT_EQ("Usage: [-h]\n", output.str()); EXPECT_EQ("error: All positional arguments have been consumed: hello\n", error.str()); } GTEST(TestOptionalDefault) { int op = 2; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") ("-op", op) .ParseArgs(argparse::Arguments("app.exe", {}), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ(2, op); } GTEST(TestOptionalValue) { int op = 2; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") ("-op", op) .ParseArgs(argparse::Arguments("app.exe", {"-op", "42"}), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ(42, op); } GTEST(TestPositionalValue) { int op = 2; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") ("op", op) .ParseArgs(argparse::Arguments("app.exe", { "42" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ(42, op); } GTEST(TestPositionalValueErr) { int op = 42; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") ("op", op) .ParseArgs(argparse::Arguments("app.exe", {}), output, error); EXPECT_EQ(false, ok); EXPECT_EQ("error: too few arguments.\n", error.str()); EXPECT_EQ("Usage: [-h] [op]\n", output.str()); EXPECT_EQ(42, op); // not touched } GTEST(TestStdVector) { std::vector<std::string> strings; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") .AddGreedy("-strings", strings, "string") .ParseArgs(argparse::Arguments("app.exe", {"-strings", "cat", "dog", "fish"}), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_THAT(strings, ElementsAre("cat", "dog", "fish")); } GTEST(TestStdVectorInts) { std::vector<int> ints; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") .AddGreedy("-ints", ints, "string") .ParseArgs(argparse::Arguments("app.exe", { "-ints", "2", "3", "-5", "4" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_THAT(ints, ElementsAre(2, 3, -5, 4)); } GTEST(TestNonGreedyVector) { std::vector<std::string> strings; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") ("-s", strings) .ParseArgs(argparse::Arguments("app.exe", { "-s", "cat", "-s", "dog", "-s", "fish" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_THAT(strings, ElementsAre("cat", "dog", "fish")); } enum class Day { TODAY, YESTERDAY, TOMORROW }; ARGPARSE_DEFINE_ENUM(Day, "day", ("Today", Day::TODAY)("Tomorrow", Day::TOMORROW)("Yesterday", Day::YESTERDAY) ) GTEST(TestEnum) { Day op = Day::TOMORROW; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") ("op", op) .ParseArgs(argparse::Arguments("app.exe", { "tod" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ(Day::TODAY, op); } GTEST(TestCommaOp) { int op = 2; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") ("-int,-i", op) .ParseArgs(argparse::Arguments("app.exe", { "-int", "42" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ(42, op); } GTEST(TestSpecifyTwice) { int op = 2; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") ("-int,-i", op) .ParseArgs(argparse::Arguments("app.exe", { "-int", "42", "-i", "50" }), output, error); EXPECT_EQ(false, ok); EXPECT_EQ("error: All positional arguments have been consumed: -i\n", error.str()); EXPECT_EQ("Usage: [-h] [-int,-i [int]]\n", output.str()); EXPECT_EQ(42, op); } GTEST(TestPrecedencePos) { const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", {"dog"}), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ("dog", animal); EXPECT_EQ("", another); } GTEST(TestPrecedencePosOp) { const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-dog", "-op", "cat" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ("-dog", animal); EXPECT_EQ("cat", another); } GTEST(TestPrecedenceOpPos) { const bool ok = argparse::Parser::ParseComplete == parser.ParseArgs(argparse::Arguments("app.exe", { "-op", "cat", "dog" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", error.str()); EXPECT_EQ("", output.str()); EXPECT_EQ("dog", animal); EXPECT_EQ("cat", another); } GTEST(TestStoreConstInt) { int op = 12; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") .StoreConst("-store", op, 42) .ParseArgs(argparse::Arguments("app.exe", { "-store" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ(42, op); } GTEST(TestStoreConstString) { std::string op = ""; const bool ok = argparse::Parser::ParseComplete == argparse::Parser("description") .StoreConst<std::string>("-store", op, "dog") .ParseArgs(argparse::Arguments("app.exe", { "-store" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ("dog", op); } GTEST(TestSubParserBasic) { const bool ok = argparse::Parser::ParseComplete == sub.ParseArgs(argparse::Arguments("app.exe", { "one", "-name", "dog" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ("dog", sp1.name); EXPECT_EQ("", sp2.name); } GTEST(TestSubParserOptional) { std::string op = ""; sub("-op", op); const bool ok = argparse::Parser::ParseComplete == sub.ParseArgs(argparse::Arguments("app.exe", { "-op", "cat", "on", "-name", "dog" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ("cat", op); EXPECT_EQ("dog", sp1.name); EXPECT_EQ("", sp2.name); } GTEST(TestSubParserPositional) { std::string op = ""; sub("op", op); const bool ok = argparse::Parser::ParseComplete == sub.ParseArgs(argparse::Arguments("app.exe", { "cat", "on", "-name", "dog" }), output, error); EXPECT_EQ(true, ok); EXPECT_EQ("", output.str()); EXPECT_EQ("", error.str()); EXPECT_EQ("cat", op); EXPECT_EQ("dog", sp1.name); EXPECT_EQ("", sp2.name); } GTEST(TestSubParserCallbackError) { const bool ok = argparse::Parser::ParseComplete == sub.ParseArgs(argparse::Arguments("app.exe", { "on", "cat" }), output, error); EXPECT_EQ(false, ok); EXPECT_EQ("Usage: [-h] ONE [-h] [-name [name]]\n", output.str()); EXPECT_EQ("error: Failed to parse ONE:\nerror: All positional arguments have been consumed: cat\n", error.str()); EXPECT_EQ("", sp1.name); EXPECT_EQ("", sp2.name); } GTEST(TestSubParserInvalid) { const bool ok = argparse::Parser::ParseComplete == sub.ParseArgs(argparse::Arguments("app.exe", { "dog", "cat" }), output, error); EXPECT_EQ(false, ok); EXPECT_EQ("Usage: [-h] {ONE|TWO}\n", output.str()); EXPECT_EQ("error: Unable to match DOG as a subparser.\n", error.str()); EXPECT_EQ("", sp1.name); EXPECT_EQ("", sp2.name); } // todo: test help string <|endoftext|>
<commit_before>#include "scheduler.h" #include "../task/taskexecutor.h" #include "../log/logger.h" #include <QDir> #include <QTimer> #include <QCoreApplication> #include <QDebug> #include <QPointer> LOGGER(Scheduler) class Scheduler::Private : public QObject { Q_OBJECT public: Private(Scheduler* q) : q(q) , path(qApp->applicationDirPath()) { timer.setSingleShot(true); connect(&timer, SIGNAL(timeout()), this, SLOT(timeout())); } Scheduler* q; // Properties QDir path; QTimer timer; TestDefinitionList tests; QPointer<TaskExecutor> executor; // Functions void updateTimer(); int enqueue(const TestDefinitionPtr &testDefinition); public slots: void timeout(); }; void Scheduler::Private::updateTimer() { if (tests.isEmpty()) { timer.stop(); LOG_DEBUG("Scheduling timer stopped"); } else { const TestDefinitionPtr& td = tests.at(0); int ms = td->timing()->timeLeft(); if ( ms > 0 ) timer.start( ms ); else timeout(); LOG_DEBUG(QString("Scheduling timer executes %1 in %2 ms").arg(td->name()).arg(ms)); } } int Scheduler::Private::enqueue(const TestDefinitionPtr& testDefinition) { bool wasEmpty = tests.isEmpty(); int timeLeft = testDefinition->timing()->timeLeft(); for(int i=0; i < tests.size(); ++i) { const TestDefinitionPtr& td = tests.at(i); if (timeLeft < td->timing()->timeLeft()) { tests.insert(i, testDefinition); if ( wasEmpty || i == 0 ) updateTimer(); return i; } } tests.append(testDefinition); if ( wasEmpty ) updateTimer(); return tests.size()-1; } void Scheduler::Private::timeout() { for(int i=0; i < tests.size(); ++i) { TestDefinitionPtr td = tests.at(i); // We assume they are already sorted - WRONG, SO WRONG! if ( td->timing()->timeLeft() > 0 ) continue; q->execute(td); tests.removeAt(i); if (!td->timing()->reset()) { emit q->testRemoved(td, i); if (tests.isEmpty()) break; else --i; } else { int pos = enqueue(td); if (pos != i) { LOG_DEBUG(QString("%1 moved from %2 to %3").arg(td->name()).arg(i).arg(pos)); emit q->testMoved(td, i, pos); } } } updateTimer(); } Scheduler::Scheduler() : d(new Private(this)) { } Scheduler::~Scheduler() { delete d; } void Scheduler::setExecutor(TaskExecutor *executor) { d->executor = executor; } TaskExecutor *Scheduler::executor() const { return d->executor; } TestDefinitionList Scheduler::tests() const { return d->tests; } void Scheduler::enqueue(const TestDefinitionPtr &testDefinition) { int pos = d->enqueue(testDefinition); emit testAdded(testDefinition, pos); } void Scheduler::dequeue() { // Whatever } void Scheduler::execute(const TestDefinitionPtr &testDefinition) { d->executor->execute(testDefinition); } #include "scheduler.moc" <commit_msg>timeout() may delete scheduler entries, so better don't use a reference<commit_after>#include "scheduler.h" #include "../task/taskexecutor.h" #include "../log/logger.h" #include <QDir> #include <QTimer> #include <QCoreApplication> #include <QDebug> #include <QPointer> LOGGER(Scheduler) class Scheduler::Private : public QObject { Q_OBJECT public: Private(Scheduler* q) : q(q) , path(qApp->applicationDirPath()) { timer.setSingleShot(true); connect(&timer, SIGNAL(timeout()), this, SLOT(timeout())); } Scheduler* q; // Properties QDir path; QTimer timer; TestDefinitionList tests; QPointer<TaskExecutor> executor; // Functions void updateTimer(); int enqueue(const TestDefinitionPtr &testDefinition); public slots: void timeout(); }; void Scheduler::Private::updateTimer() { if (tests.isEmpty()) { timer.stop(); LOG_DEBUG("Scheduling timer stopped"); } else { const TestDefinitionPtr td = tests.at(0); int ms = td->timing()->timeLeft(); if ( ms > 0 ) timer.start( ms ); else timeout(); LOG_DEBUG(QString("Scheduling timer executes %1 in %2 ms").arg(td->name()).arg(ms)); } } int Scheduler::Private::enqueue(const TestDefinitionPtr& testDefinition) { bool wasEmpty = tests.isEmpty(); int timeLeft = testDefinition->timing()->timeLeft(); for(int i=0; i < tests.size(); ++i) { const TestDefinitionPtr& td = tests.at(i); if (timeLeft < td->timing()->timeLeft()) { tests.insert(i, testDefinition); if ( wasEmpty || i == 0 ) updateTimer(); return i; } } tests.append(testDefinition); if ( wasEmpty ) updateTimer(); return tests.size()-1; } void Scheduler::Private::timeout() { for(int i=0; i < tests.size(); ++i) { TestDefinitionPtr td = tests.at(i); // We assume they are already sorted - WRONG, SO WRONG! if ( td->timing()->timeLeft() > 0 ) continue; q->execute(td); tests.removeAt(i); if (!td->timing()->reset()) { emit q->testRemoved(td, i); if (tests.isEmpty()) break; else --i; } else { int pos = enqueue(td); if (pos != i) { LOG_DEBUG(QString("%1 moved from %2 to %3").arg(td->name()).arg(i).arg(pos)); emit q->testMoved(td, i, pos); } } } updateTimer(); } Scheduler::Scheduler() : d(new Private(this)) { } Scheduler::~Scheduler() { delete d; } void Scheduler::setExecutor(TaskExecutor *executor) { d->executor = executor; } TaskExecutor *Scheduler::executor() const { return d->executor; } TestDefinitionList Scheduler::tests() const { return d->tests; } void Scheduler::enqueue(const TestDefinitionPtr &testDefinition) { int pos = d->enqueue(testDefinition); emit testAdded(testDefinition, pos); } void Scheduler::dequeue() { // Whatever } void Scheduler::execute(const TestDefinitionPtr &testDefinition) { d->executor->execute(testDefinition); } #include "scheduler.moc" <|endoftext|>
<commit_before>#include "addsemestredialog.h" #include "ui_addsemestredialog.h" #include <QMessageBox> #include "src/uvmanager.hpp" #include "src/exceptions.hpp" #define UVM UvManager::getInstance() #define NUM NoteUVManager::getInstance() AddSemestreDialog::AddSemestreDialog(QWidget *parent) : QDialog(parent), ui(new Ui::AddSemestreDialog) { ui->setupUi(this); QStringList notes; std::vector<NoteUV> iterator = NUM->iterator(); for(auto it=iterator.begin(); it!=iterator.end(); it++) { notes<<it->nom; } ui->noteBox->addItems(notes); } void AddSemestreDialog::uvAdded() { QString code = ui->codeEdit->text(); QString note = ui->noteBox->currentText(); try { UVM->getItem(code); } catch(const Exception& e) { QMessageBox error(this); error.setText(e.getinfo()); error.exec(); return; } ui->widget->addUv(code); } AddSemestreDialog::~AddSemestreDialog() { delete ui; } <commit_msg>Modifs tableWidget<commit_after>#include "addsemestredialog.h" #include "ui_addsemestredialog.h" #include <QMessageBox> #include "src/uvmanager.hpp" #include "src/exceptions.hpp" #define UVM UvManager::getInstance() #define NUM NoteUVManager::getInstance() AddSemestreDialog::AddSemestreDialog(QWidget *parent) : QDialog(parent), ui(new Ui::AddSemestreDialog) { ui->setupUi(this); QStringList notes; std::vector<NoteUV> iterator = NUM->iterator(); for(auto it=iterator.begin(); it!=iterator.end(); it++) { notes<<it->nom; } ui->noteBox->addItems(notes); QStringList header; header << "Code" << "Note"; ui->tableWidget->setColumnCount(2); ui->tableWidget->setHorizontalHeaderLabels(header); ui->tableWidget->setRowCount(0); ui->tableWidget->setColumnCount(2); ui->tableWidget->verticalHeader()->setVisible(false); ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); } void AddSemestreDialog::uvAdded() { QString code = ui->codeEdit->text(); QString note = ui->noteBox->currentText(); ui->codeEdit->clear(); try { UVM->getItem(code); } catch(const Exception& e) { QMessageBox error(this); error.setText(e.getinfo()); error.exec(); return; } //Si cette UV a été rajoutée auparavant //On ignore l’ajout for(int i=0; i<ui->tableWidget->rowCount(); i++) { if(ui->tableWidget->item(i, 0)->text() == code) { return; } } ui->tableWidget->setRowCount(ui->tableWidget->rowCount() + 1); ui->tableWidget->setItem(ui->tableWidget->rowCount()-1, 0, new QTableWidgetItem(code)); ui->tableWidget->setItem(ui->tableWidget->rowCount()-1, 1, new QTableWidgetItem(note)); } AddSemestreDialog::~AddSemestreDialog() { delete ui; } <|endoftext|>
<commit_before>#include "qt/place_page_dialog.hpp" #include "map/place_page_info.hpp" // For search::AddressInfo. #include "search/result.hpp" #include <QtWidgets/QDialogButtonBox> #include <QtWidgets/QGridLayout> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QLabel> #include <QtWidgets/QPushButton> #include <QtWidgets/QVBoxLayout> string GenerateStars(int count) { string stars; for (int i = 0; i < count; ++i) stars.append("★"); return stars; } PlacePageDialog::PlacePageDialog(QWidget * parent, place_page::Info const & info, search::AddressInfo const & address) : QDialog(parent) { QGridLayout * grid = new QGridLayout(); int row = 0; { // Coordinates. grid->addWidget(new QLabel("lat lon"), row, 0); ms::LatLon const ll = info.GetLatLon(); string const llstr = strings::to_string_dac(ll.lat, 7) + ", " + strings::to_string_dac(ll.lon, 7); QLabel * label = new QLabel(llstr.c_str()); label->setTextInteractionFlags(Qt::TextSelectableByMouse); grid->addWidget(label, row++, 1); } { grid->addWidget(new QLabel("CountryId"), row, 0); QLabel * label = new QLabel(QString::fromStdString(info.GetCountryId())); label->setTextInteractionFlags(Qt::TextSelectableByMouse); grid->addWidget(label, row++, 1); } // Title/Name/Custom Name. if (!info.GetTitle().empty()) { grid->addWidget(new QLabel("Title"), row, 0); QLabel * label = new QLabel(QString::fromStdString(info.GetTitle())); label->setTextInteractionFlags(Qt::TextSelectableByMouse); grid->addWidget(label, row++, 1); } // Subtitle. if (info.IsFeature()) { grid->addWidget(new QLabel("Subtitle"), row, 0); QLabel * label = new QLabel(QString::fromStdString(info.GetSubtitle())); label->setTextInteractionFlags(Qt::TextSelectableByMouse); grid->addWidget(label, row++, 1); } { // Address. grid->addWidget(new QLabel("Address"), row, 0); QLabel * label = new QLabel(QString::fromStdString(address.FormatAddress())); label->setTextInteractionFlags(Qt::TextSelectableByMouse); grid->addWidget(label, row++, 1); } if (info.IsBookmark()) { grid->addWidget(new QLabel("Bookmark"), row, 0); grid->addWidget(new QLabel("Yes"), row++, 1); } if (info.IsMyPosition()) { grid->addWidget(new QLabel("MyPosition"), row, 0); grid->addWidget(new QLabel("Yes"), row++, 1); } if (info.HasApiUrl()) { grid->addWidget(new QLabel("Api URL"), row, 0); grid->addWidget(new QLabel(QString::fromStdString(info.GetApiUrl())), row++, 1); } if (info.IsFeature()) { grid->addWidget(new QLabel("Raw Types"), row, 0); QLabel * label = new QLabel(QString::fromStdString(DebugPrint(info.GetTypes()))); label->setTextInteractionFlags(Qt::TextSelectableByMouse); grid->addWidget(label, row++, 1); } for (auto const prop : info.AvailableProperties()) { QString k; string v; bool link = false; switch (prop) { case osm::Props::Phone: k = "Phone"; v = info.GetPhone(); break; case osm::Props::Fax: k = "Fax"; v = info.GetFax(); break; case osm::Props::Email: k = "Email"; v = info.GetEmail(); link = true; break; case osm::Props::Website: k = "Website"; v = info.GetWebsite(); link = true; break; case osm::Props::Internet: k = "Internet"; v = DebugPrint(info.GetInternet()); break; case osm::Props::Cuisine: k = "Cuisine"; v = strings::JoinStrings(info.GetCuisines(), ", "); break; case osm::Props::OpeningHours: k = "OpeningHours"; v = info.GetOpeningHours(); break; case osm::Props::Stars: k = "Stars"; v = GenerateStars(info.GetStars()); break; case osm::Props::Operator: k = "Operator"; v = info.GetOperator(); break; case osm::Props::Elevation: k = "Elevation"; v = info.GetElevationFormatted(); break; case osm::Props::Wikipedia: k = "Wikipedia"; v = info.GetWikipediaLink(); link = true; break; case osm::Props::Flats: k = "Flats"; v = info.GetFlats(); break; case osm::Props::BuildingLevels: k = "Building Levels"; v = info.GetBuildingLevels(); break; case osm::Props::Level: k = "Level"; v = info.GetLevel(); break; } grid->addWidget(new QLabel(k), row, 0); QLabel * label = new QLabel(QString::fromStdString(v)); label->setTextInteractionFlags(Qt::TextSelectableByMouse); if (link) { label->setOpenExternalLinks(true); label->setTextInteractionFlags(Qt::TextBrowserInteraction); label->setText(QString::fromStdString("<a href=\"" + v + "\">" + v + "</a>")); } grid->addWidget(label, row++, 1); } QDialogButtonBox * dbb = new QDialogButtonBox(); QPushButton * closeButton = new QPushButton("Close"); closeButton->setDefault(true); connect(closeButton, SIGNAL(clicked()), this, SLOT(OnClose())); dbb->addButton(closeButton, QDialogButtonBox::RejectRole); if (info.ShouldShowEditPlace()) { QPushButton * editButton = new QPushButton("Edit Place"); connect(editButton, SIGNAL(clicked()), this, SLOT(OnEdit())); dbb->addButton(editButton, QDialogButtonBox::AcceptRole); } grid->addWidget(dbb); setLayout(grid); string const title = string("Place Page") + (info.IsBookmark() ? " (bookmarked)" : ""); setWindowTitle(title.c_str()); } void PlacePageDialog::OnClose() { reject(); } void PlacePageDialog::OnEdit() { accept(); } <commit_msg>Update place_page_dialog.cpp<commit_after>#include "qt/place_page_dialog.hpp" #include "map/place_page_info.hpp" // For search::AddressInfo. #include "search/result.hpp" #include <QtWidgets/QDialogButtonBox> #include <QtWidgets/QGridLayout> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QLabel> #include <QtWidgets/QPushButton> #include <QtWidgets/QVBoxLayout> string GenerateStars(int count) { string stars; for (int i = 0; i < count; ++i) stars.append("★"); return stars; } PlacePageDialog::PlacePageDialog(QWidget * parent, place_page::Info const & info, search::AddressInfo const & address) : QDialog(parent) { QGridLayout * grid = new QGridLayout(); int row = 0; { // Coordinates. grid->addWidget(new QLabel("lat, lon"), row, 0); ms::LatLon const ll = info.GetLatLon(); string const llstr = strings::to_string_dac(ll.lat, 7) + ", " + strings::to_string_dac(ll.lon, 7); QLabel * label = new QLabel(llstr.c_str()); label->setTextInteractionFlags(Qt::TextSelectableByMouse); grid->addWidget(label, row++, 1); } { grid->addWidget(new QLabel("CountryId"), row, 0); QLabel * label = new QLabel(QString::fromStdString(info.GetCountryId())); label->setTextInteractionFlags(Qt::TextSelectableByMouse); grid->addWidget(label, row++, 1); } // Title/Name/Custom Name. if (!info.GetTitle().empty()) { grid->addWidget(new QLabel("Title"), row, 0); QLabel * label = new QLabel(QString::fromStdString(info.GetTitle())); label->setTextInteractionFlags(Qt::TextSelectableByMouse); grid->addWidget(label, row++, 1); } // Subtitle. if (info.IsFeature()) { grid->addWidget(new QLabel("Subtitle"), row, 0); QLabel * label = new QLabel(QString::fromStdString(info.GetSubtitle())); label->setTextInteractionFlags(Qt::TextSelectableByMouse); grid->addWidget(label, row++, 1); } { // Address. grid->addWidget(new QLabel("Address"), row, 0); QLabel * label = new QLabel(QString::fromStdString(address.FormatAddress())); label->setTextInteractionFlags(Qt::TextSelectableByMouse); grid->addWidget(label, row++, 1); } if (info.IsBookmark()) { grid->addWidget(new QLabel("Bookmark"), row, 0); grid->addWidget(new QLabel("Yes"), row++, 1); } if (info.IsMyPosition()) { grid->addWidget(new QLabel("MyPosition"), row, 0); grid->addWidget(new QLabel("Yes"), row++, 1); } if (info.HasApiUrl()) { grid->addWidget(new QLabel("Api URL"), row, 0); grid->addWidget(new QLabel(QString::fromStdString(info.GetApiUrl())), row++, 1); } if (info.IsFeature()) { grid->addWidget(new QLabel("Raw Types"), row, 0); QLabel * label = new QLabel(QString::fromStdString(DebugPrint(info.GetTypes()))); label->setTextInteractionFlags(Qt::TextSelectableByMouse); grid->addWidget(label, row++, 1); } for (auto const prop : info.AvailableProperties()) { QString k; string v; bool link = false; switch (prop) { case osm::Props::Phone: k = "Phone"; v = info.GetPhone(); break; case osm::Props::Fax: k = "Fax"; v = info.GetFax(); break; case osm::Props::Email: k = "Email"; v = info.GetEmail(); link = true; break; case osm::Props::Website: k = "Website"; v = info.GetWebsite(); link = true; break; case osm::Props::Internet: k = "Internet"; v = DebugPrint(info.GetInternet()); break; case osm::Props::Cuisine: k = "Cuisine"; v = strings::JoinStrings(info.GetCuisines(), ", "); break; case osm::Props::OpeningHours: k = "OpeningHours"; v = info.GetOpeningHours(); break; case osm::Props::Stars: k = "Stars"; v = GenerateStars(info.GetStars()); break; case osm::Props::Operator: k = "Operator"; v = info.GetOperator(); break; case osm::Props::Elevation: k = "Elevation"; v = info.GetElevationFormatted(); break; case osm::Props::Wikipedia: k = "Wikipedia"; v = info.GetWikipediaLink(); link = true; break; case osm::Props::Flats: k = "Flats"; v = info.GetFlats(); break; case osm::Props::BuildingLevels: k = "Building Levels"; v = info.GetBuildingLevels(); break; case osm::Props::Level: k = "Level"; v = info.GetLevel(); break; } grid->addWidget(new QLabel(k), row, 0); QLabel * label = new QLabel(QString::fromStdString(v)); label->setTextInteractionFlags(Qt::TextSelectableByMouse); if (link) { label->setOpenExternalLinks(true); label->setTextInteractionFlags(Qt::TextBrowserInteraction); label->setText(QString::fromStdString("<a href=\"" + v + "\">" + v + "</a>")); } grid->addWidget(label, row++, 1); } QDialogButtonBox * dbb = new QDialogButtonBox(); QPushButton * closeButton = new QPushButton("Close"); closeButton->setDefault(true); connect(closeButton, SIGNAL(clicked()), this, SLOT(OnClose())); dbb->addButton(closeButton, QDialogButtonBox::RejectRole); if (info.ShouldShowEditPlace()) { QPushButton * editButton = new QPushButton("Edit Place"); connect(editButton, SIGNAL(clicked()), this, SLOT(OnEdit())); dbb->addButton(editButton, QDialogButtonBox::AcceptRole); } grid->addWidget(dbb); setLayout(grid); string const title = string("Place Page") + (info.IsBookmark() ? " (bookmarked)" : ""); setWindowTitle(title.c_str()); } void PlacePageDialog::OnClose() { reject(); } void PlacePageDialog::OnEdit() { accept(); } <|endoftext|>
<commit_before>/*-------------------------------------------------------------------------- Copyright (c) 2014-2015, The Linux Foundation. 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 Linux Foundation 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 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT 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 <sensors_extension.h> #include "sensors_XML.h" #include <cutils/log.h> #include "unistd.h" #define SENSOR_XML_ROOT_ELEMENT "sensors" ANDROID_SINGLETON_STATIC_INSTANCE(sensors_XML); const static char *filepath[] = { "/persist/sensors/sensors_calibration_params.xml", "/data/sensors_calibration_param.xml" }; const char *sensor_param[] = {"offset_x", "offset_y", "offset_z", "threshold_h", "threshold_l", "bias"}; const char *cal_state[] = {"static","dynamic"}; sensors_XML :: sensors_XML() : mdoc(NULL) { } int sensors_XML :: write_sensors_params(struct sensor_t *sensor, struct cal_result_t *cal_result, int state) { xmlNodePtr rootNode, curNode, newNode; xmlAttrPtr value; bool newcreate = false; char string[33]; int fnum = 0; int i = 0, j, MAX = 0; if (state < CAL_STATIC || state > CAL_DYNAMIC) { ALOGE("state error\n"); return -1; } if (cal_result == NULL) { ALOGE("Null pointer parameter\n"); return -1; } if (state == 1) fnum = 1; if (!access(filepath[fnum], F_OK)) { if (!access(filepath[fnum], W_OK)) { mdoc = xmlReadFile(filepath[fnum], "UTF-8" , XML_PARSE_NOBLANKS); if (mdoc == NULL) { ALOGE("read calibration file error\n"); return -EINVAL; } } else { ALOGE("No permission write file %s\n", filepath[fnum]); return -1; } } else { mdoc = xmlNewDoc(BAD_CAST "1.0"); if (mdoc == NULL) { ALOGE("create sensor calibration file error\n"); return -EINVAL; } newcreate = true; } if(newcreate) { rootNode = xmlNewNode(NULL, BAD_CAST SENSOR_XML_ROOT_ELEMENT); xmlDocSetRootElement(mdoc, rootNode); curNode = xmlNewNode(NULL, BAD_CAST "sensor"); xmlAddChild(rootNode, curNode); xmlNewProp(curNode, BAD_CAST "name", BAD_CAST sensor->name); xmlNewProp(curNode, BAD_CAST "state", BAD_CAST cal_state[state]); } else { rootNode = xmlDocGetRootElement(mdoc); if (rootNode == NULL) { ALOGE("empty document\n"); xmlFreeDoc(mdoc); return -1; } if (xmlStrcmp(rootNode->name, BAD_CAST SENSOR_XML_ROOT_ELEMENT)) { ALOGE("root node != sensors\n"); xmlFreeDoc(mdoc); return -1; } curNode = rootNode->xmlChildrenNode; while(curNode != NULL) { if (!xmlStrcmp(xmlGetProp(curNode, BAD_CAST "name"), BAD_CAST sensor->name) && !xmlStrcmp(xmlGetProp(curNode, BAD_CAST "state"), BAD_CAST cal_state[state])) break; curNode = curNode->next; } } switch(sensor->type) { case SENSOR_TYPE_ACCELEROMETER: case SENSOR_TYPE_GYROSCOPE: i = 0; MAX = 3; break; case SENSOR_TYPE_PROXIMITY: i = 3; MAX = 6; break; case SENSOR_TYPE_LIGHT: case SENSOR_TYPE_MAGNETIC_FIELD: case SENSOR_TYPE_PRESSURE: case SENSOR_TYPE_TEMPERATURE: default: break; } if (newcreate) { for(j = 0; i < MAX; i++, j++) { snprintf(string, sizeof(string), "%d", cal_result->offset[j]); value = xmlNewProp(curNode, BAD_CAST sensor_param[i], BAD_CAST string); if (value == NULL) { ALOGE("write value in new create error\n"); xmlFreeDoc(mdoc); return -1; } } } else { if (curNode == NULL) { curNode = xmlNewNode(NULL, BAD_CAST "sensor"); xmlAddChild(rootNode, curNode); value = xmlNewProp(curNode, BAD_CAST "name", BAD_CAST sensor->name); if (value == NULL) { ALOGE("name is NULL\n"); xmlFreeDoc(mdoc); return -1; } value = xmlNewProp(curNode, BAD_CAST "state", BAD_CAST cal_state[state]); if (value == NULL) { ALOGE("state is NULL\n"); xmlFreeDoc(mdoc); return -1; } for(j = 0; i < MAX; i++, j++) { snprintf(string, sizeof(string), "%d", cal_result->offset[j]); value = xmlNewProp(curNode, BAD_CAST sensor_param[i], BAD_CAST string); if (value == NULL) { ALOGE("write value error\n"); xmlFreeDoc(mdoc); return -1; } } } else { for(j = 0; i < MAX; i++, j++) { snprintf(string, sizeof(string), "%d", cal_result->offset[j]); value = xmlSetProp(curNode, BAD_CAST sensor_param[i], BAD_CAST string); if (value == NULL) { ALOGE("set value error\n"); xmlFreeDoc(mdoc); return -1; } } } } if (xmlSaveFormatFileEnc(filepath[fnum], mdoc, "UTF-8", 1) == -1) { ALOGE("save %s failed %s\n", filepath[fnum], strerror(errno)); xmlFreeDoc(mdoc); return -1; } xmlFreeDoc(mdoc); return 0; } int sensors_XML :: read_sensors_params(struct sensor_t *sensor, struct cal_result_t *cal_result, int state) { xmlNodePtr rootNode, curNode; int i = 0, j, MAX = 0; if (state < CAL_STATIC || state > CAL_DYNAMIC) { ALOGE("state error\n"); return -1; } if (cal_result == NULL) { ALOGE("Null pointer parameter\n"); return -1; } if (!access(filepath[1], R_OK)) { mdoc = xmlReadFile(filepath[1], "UTF-8" , XML_PARSE_RECOVER); } else if (!access(filepath[0], F_OK)){ char buf[200]; snprintf(buf, sizeof(buf), "cp %s %s", filepath[0], filepath[1]); system(buf); if (!access(filepath[1], R_OK)) { mdoc = xmlReadFile(filepath[1], "UTF-8" , XML_PARSE_RECOVER); } else { ALOGE("file %s can't read\n", filepath[1]); return -1; } } else { ALOGE("file %s can't read\n", filepath[0]); return -1; } rootNode = xmlDocGetRootElement(mdoc); if (rootNode == NULL) { ALOGE("empty document\n"); xmlFreeDoc(mdoc); return -1; } if (xmlStrcmp(rootNode->name, BAD_CAST SENSOR_XML_ROOT_ELEMENT)) { ALOGE("root node != sensors\n"); xmlFreeDoc(mdoc); return -1; } curNode = rootNode->xmlChildrenNode; while(curNode != NULL) { if (!xmlStrcmp(xmlGetProp(curNode, BAD_CAST "name"), BAD_CAST sensor->name) && !xmlStrcmp(xmlGetProp(curNode, BAD_CAST "state"), BAD_CAST cal_state[state])) break; curNode = curNode->next; } switch(sensor->type) { case SENSOR_TYPE_ACCELEROMETER: case SENSOR_TYPE_GYROSCOPE: i = 0; MAX = 3; break; case SENSOR_TYPE_PROXIMITY: i = 3; MAX = 6; break; case SENSOR_TYPE_LIGHT: case SENSOR_TYPE_MAGNETIC_FIELD: case SENSOR_TYPE_PRESSURE: case SENSOR_TYPE_TEMPERATURE: default: break; } if (curNode != NULL) { xmlChar* value; for(j = 0; i < MAX; i++, j++) { value = xmlGetProp(curNode, BAD_CAST sensor_param[i]); if(value != NULL) { cal_result->offset[j] = atoi((char*)value); } } } else { for(j = 0; j < 3; j++) { cal_result->offset[j] = 0; } ALOGE("The sensor %s calibrate parameters is not found\n", sensor->name); xmlFreeDoc(mdoc); return -1; } xmlFreeDoc(mdoc); return 0; } int sensors_XML :: sensors_calibrate_reset() { int i; for(i=0; i < 2; i++) { if (access(filepath[i], F_OK)) { ALOGE("file is not exits\n"); return -1; } if (remove(filepath[i])) { ALOGE("reset calibrate error\n"); return -1; } } return 0; } int sensors_XML :: sensors_rm_file() { if (access(filepath[1], F_OK)) { return 0; } if (remove(filepath[1])) { ALOGE("reset calibrate error\n"); return -1; } return 0; } <commit_msg>sensors: modify sensor calibration profiles copy mode<commit_after>/*-------------------------------------------------------------------------- Copyright (c) 2014-2015, The Linux Foundation. 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 Linux Foundation 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 "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT 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 <sensors_extension.h> #include "sensors_XML.h" #include <cutils/log.h> #include "unistd.h" #include <fcntl.h> #include <sys/stat.h> #define SENSOR_XML_ROOT_ELEMENT "sensors" ANDROID_SINGLETON_STATIC_INSTANCE(sensors_XML); const static char *filepath[] = { "/persist/sensors/sensors_calibration_params.xml", "/data/sensors_calibration_params.xml" }; const char *sensor_param[] = {"offset_x", "offset_y", "offset_z", "threshold_h", "threshold_l", "bias"}; const char *cal_state[] = {"static","dynamic"}; sensors_XML :: sensors_XML() : mdoc(NULL) { } static int config_file_copy() { int bufsize; int fd[2]; off_t offset; char *ptr; char *wptr; int bytes_read, bytes_write; int err = 0; if ((fd[0] = open(filepath[0], O_RDONLY)) == -1) { ALOGE("open calibrate sensor config error %d", errno); return -errno; } if ((fd[1] = open(filepath[1], O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR)) == -1) { ALOGE("create calibrate sensor config error"); close(fd[0]); return -errno; } offset = lseek(fd[0], 0, SEEK_END); if (offset < 0) { ALOGE("lseek %s error %d", filepath[0], errno); err = -errno; goto close_fd; } bufsize = offset; ptr = (char*)malloc(bufsize); if (ptr == NULL) { ALOGE("malloc memory for %s error", filepath[1]); err = -errno; goto close_fd; } offset = lseek(fd[0], 0, SEEK_SET); if (offset < 0) { ALOGE("lseek %s error %d", filepath[0], errno); err = -errno; goto free_ptr; } bytes_read = read(fd[0], ptr, bufsize); if (bytes_read == -1 && errno != EINTR) { ALOGE("read calibrate sensor config error"); err = -errno; goto free_ptr; } wptr = ptr; while ((bytes_write = write(fd[1], wptr, bytes_read))) { if (bytes_write == -1 && errno != EINTR) { ALOGE("write calibrate sensor config error"); err = -errno; goto free_ptr; } else if (bytes_write == bytes_read) { break; }else if (bytes_write > 0) { wptr += bytes_write; bytes_read -= bytes_write; } } free_ptr: free(ptr); close_fd: close(fd[0]); close(fd[1]); return err; } int sensors_XML :: write_sensors_params(struct sensor_t *sensor, struct cal_result_t *cal_result, int state) { xmlNodePtr rootNode, curNode, newNode; xmlAttrPtr value; bool newcreate = false; char string[33]; int fnum = 0; int i = 0, j, MAX = 0; if (state < CAL_STATIC || state > CAL_DYNAMIC) { ALOGE("state error\n"); return -1; } if (cal_result == NULL) { ALOGE("Null pointer parameter\n"); return -1; } if (state == 1) fnum = 1; if (!access(filepath[fnum], F_OK)) { if (!access(filepath[fnum], W_OK)) { mdoc = xmlReadFile(filepath[fnum], "UTF-8" , XML_PARSE_NOBLANKS); if (mdoc == NULL) { ALOGE("read calibration file error\n"); return -EINVAL; } } else { ALOGE("No permission write file %s\n", filepath[fnum]); return -1; } } else { mdoc = xmlNewDoc(BAD_CAST "1.0"); if (mdoc == NULL) { ALOGE("create sensor calibration file error\n"); return -EINVAL; } newcreate = true; } if(newcreate) { rootNode = xmlNewNode(NULL, BAD_CAST SENSOR_XML_ROOT_ELEMENT); xmlDocSetRootElement(mdoc, rootNode); curNode = xmlNewNode(NULL, BAD_CAST "sensor"); xmlAddChild(rootNode, curNode); xmlNewProp(curNode, BAD_CAST "name", BAD_CAST sensor->name); xmlNewProp(curNode, BAD_CAST "state", BAD_CAST cal_state[state]); } else { rootNode = xmlDocGetRootElement(mdoc); if (rootNode == NULL) { ALOGE("empty document\n"); xmlFreeDoc(mdoc); return -1; } if (xmlStrcmp(rootNode->name, BAD_CAST SENSOR_XML_ROOT_ELEMENT)) { ALOGE("root node != sensors\n"); xmlFreeDoc(mdoc); return -1; } curNode = rootNode->xmlChildrenNode; while(curNode != NULL) { if (!xmlStrcmp(xmlGetProp(curNode, BAD_CAST "name"), BAD_CAST sensor->name) && !xmlStrcmp(xmlGetProp(curNode, BAD_CAST "state"), BAD_CAST cal_state[state])) break; curNode = curNode->next; } } switch(sensor->type) { case SENSOR_TYPE_ACCELEROMETER: case SENSOR_TYPE_GYROSCOPE: i = 0; MAX = 3; break; case SENSOR_TYPE_PROXIMITY: i = 3; MAX = 6; break; case SENSOR_TYPE_LIGHT: case SENSOR_TYPE_MAGNETIC_FIELD: case SENSOR_TYPE_PRESSURE: case SENSOR_TYPE_TEMPERATURE: default: break; } if (newcreate) { for(j = 0; i < MAX; i++, j++) { snprintf(string, sizeof(string), "%d", cal_result->offset[j]); value = xmlNewProp(curNode, BAD_CAST sensor_param[i], BAD_CAST string); if (value == NULL) { ALOGE("write value in new create error\n"); xmlFreeDoc(mdoc); return -1; } } } else { if (curNode == NULL) { curNode = xmlNewNode(NULL, BAD_CAST "sensor"); xmlAddChild(rootNode, curNode); value = xmlNewProp(curNode, BAD_CAST "name", BAD_CAST sensor->name); if (value == NULL) { ALOGE("name is NULL\n"); xmlFreeDoc(mdoc); return -1; } value = xmlNewProp(curNode, BAD_CAST "state", BAD_CAST cal_state[state]); if (value == NULL) { ALOGE("state is NULL\n"); xmlFreeDoc(mdoc); return -1; } for(j = 0; i < MAX; i++, j++) { snprintf(string, sizeof(string), "%d", cal_result->offset[j]); value = xmlNewProp(curNode, BAD_CAST sensor_param[i], BAD_CAST string); if (value == NULL) { ALOGE("write value error\n"); xmlFreeDoc(mdoc); return -1; } } } else { for(j = 0; i < MAX; i++, j++) { snprintf(string, sizeof(string), "%d", cal_result->offset[j]); value = xmlSetProp(curNode, BAD_CAST sensor_param[i], BAD_CAST string); if (value == NULL) { ALOGE("set value error\n"); xmlFreeDoc(mdoc); return -1; } } } } if (xmlSaveFormatFileEnc(filepath[fnum], mdoc, "UTF-8", 1) == -1) { ALOGE("save %s failed %s\n", filepath[fnum], strerror(errno)); xmlFreeDoc(mdoc); return -1; } xmlFreeDoc(mdoc); return 0; } int sensors_XML :: read_sensors_params(struct sensor_t *sensor, struct cal_result_t *cal_result, int state) { xmlNodePtr rootNode, curNode; int i = 0, j, MAX = 0; if (state < CAL_STATIC || state > CAL_DYNAMIC) { ALOGE("state error\n"); return -1; } if (cal_result == NULL) { ALOGE("Null pointer parameter\n"); return -1; } if (!access(filepath[1], R_OK)) { mdoc = xmlReadFile(filepath[1], "UTF-8" , XML_PARSE_RECOVER); } else if (!access(filepath[0], F_OK)){ int err; err = config_file_copy(); if (err < 0) { ALOGE("copy %s error", filepath[0]); return err; } if (!access(filepath[1], R_OK)) { mdoc = xmlReadFile(filepath[1], "UTF-8" , XML_PARSE_RECOVER); } else { ALOGE("file %s can't read\n", filepath[1]); return -1; } } else { ALOGE("file %s can't read\n", filepath[0]); return -1; } rootNode = xmlDocGetRootElement(mdoc); if (rootNode == NULL) { ALOGE("empty document\n"); xmlFreeDoc(mdoc); return -1; } if (xmlStrcmp(rootNode->name, BAD_CAST SENSOR_XML_ROOT_ELEMENT)) { ALOGE("root node != sensors\n"); xmlFreeDoc(mdoc); return -1; } curNode = rootNode->xmlChildrenNode; while(curNode != NULL) { if (!xmlStrcmp(xmlGetProp(curNode, BAD_CAST "name"), BAD_CAST sensor->name) && !xmlStrcmp(xmlGetProp(curNode, BAD_CAST "state"), BAD_CAST cal_state[state])) break; curNode = curNode->next; } switch(sensor->type) { case SENSOR_TYPE_ACCELEROMETER: case SENSOR_TYPE_GYROSCOPE: i = 0; MAX = 3; break; case SENSOR_TYPE_PROXIMITY: i = 3; MAX = 6; break; case SENSOR_TYPE_LIGHT: case SENSOR_TYPE_MAGNETIC_FIELD: case SENSOR_TYPE_PRESSURE: case SENSOR_TYPE_TEMPERATURE: default: break; } if (curNode != NULL) { xmlChar* value; for(j = 0; i < MAX; i++, j++) { value = xmlGetProp(curNode, BAD_CAST sensor_param[i]); if(value != NULL) { cal_result->offset[j] = atoi((char*)value); } } } else { for(j = 0; j < 3; j++) { cal_result->offset[j] = 0; } ALOGE("The sensor %s calibrate parameters is not found\n", sensor->name); xmlFreeDoc(mdoc); return -1; } xmlFreeDoc(mdoc); return 0; } int sensors_XML :: sensors_calibrate_reset() { int i; for(i=0; i < 2; i++) { if (access(filepath[i], F_OK)) { ALOGE("file is not exits\n"); return -1; } if (remove(filepath[i])) { ALOGE("reset calibrate error\n"); return -1; } } return 0; } int sensors_XML :: sensors_rm_file() { if (access(filepath[1], F_OK)) { return 0; } if (remove(filepath[1])) { ALOGE("reset calibrate error\n"); return -1; } return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2012, 2013 Pierre MOULON. // 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/. #ifndef OPENMVG_MATCHING_ARRAYMATCHER_KDTREE_FLANN_H_ #define OPENMVG_MATCHING_ARRAYMATCHER_KDTREE_FLANN_H_ #include "openMVG/matching/matching_interface.hpp" #include "flann/flann.hpp" #include <memory> namespace openMVG { namespace matching { /// Implement ArrayMatcher as a FLANN KDtree matcher. // http://www.cs.ubc.ca/~mariusm/index.php/FLANN/FLANN // David G. Lowe and Marius Muja // // By default use squared L2 metric (flann::L2<Scalar>) // sqrt is monotonic so for performance reason we do not compute it. template < typename Scalar = float, typename Metric = flann::L2<Scalar> > class ArrayMatcher_Kdtree_Flann : public ArrayMatcher<Scalar, Metric> { public: typedef typename Metric::ResultType DistanceType; ArrayMatcher_Kdtree_Flann() {} virtual ~ArrayMatcher_Kdtree_Flann() { _datasetM.reset(); _index.reset(); } /** * Build the matching structure * * \param[in] dataset Input data. * \param[in] nbRows The number of component. * \param[in] dimension Length of the data contained in the each * row of the dataset. * * \return True if success. */ bool Build( const Scalar * dataset, int nbRows, int dimension) { if (nbRows > 0) { _dimension = dimension; //-- Build Flann Matrix container (map to already allocated memory) _datasetM.reset( new flann::Matrix<Scalar>((Scalar*)dataset, nbRows, dimension)); //-- Build FLANN index _index.reset( new flann::Index<Metric> (*_datasetM, flann::KDTreeIndexParams(4))); _index->buildIndex(); return true; } return false; } /** * Search the nearest Neighbor of the scalar array query. * * \param[in] query The query array * \param[out] indice The indice of array in the dataset that * have been computed as the nearest array. * \param[out] distance The distance between the two arrays. * * \return True if success. */ bool SearchNeighbour( const Scalar * query, int * indice, DistanceType * distance) { if (_index.get() != NULL) { int * indicePTR = indice; DistanceType * distancePTR = distance; flann::Matrix<Scalar> queries((Scalar*)query, 1, _dimension); flann::Matrix<int> indices(indicePTR, 1, 1); flann::Matrix<DistanceType> dists(distancePTR, 1, 1); // do a knn search, using 128 checks return (_index->knnSearch(queries, indices, dists, 1, flann::SearchParams(128)) > 0); } else { return false; } } /** * Search the N nearest Neighbor of the scalar array query. * * \param[in] query The query array * \param[in] nbQuery The number of query rows * \param[out] indices The corresponding (query, neighbor) indices * \param[out] pvec_distances The distances between the matched arrays. * \param[out] NN The number of maximal neighbor that will be searched. * * \return True if success. */ bool SearchNeighbours ( const Scalar * query, int nbQuery, IndMatches * pvec_indices, std::vector<DistanceType> * pvec_distances, size_t NN ) { if (_index.get() != NULL && NN <= _datasetM->rows) { std::vector<DistanceType> vec_distances(nbQuery * NN); DistanceType * distancePTR = &(vec_distances[0]); flann::Matrix<DistanceType> dists(distancePTR, nbQuery, NN); std::vector<int> vec_indices(nbQuery * NN); int * indicePTR = &(vec_indices[0]); flann::Matrix<int> indices(indicePTR, nbQuery, NN); flann::Matrix<Scalar> queries((Scalar*)query, nbQuery, _dimension); // do a knn search, using 128 checks flann::SearchParams params(128); #ifdef OPENMVG_USE_OPENMP params.cores = omp_get_max_threads(); #endif if (_index->knnSearch(queries, indices, dists, NN, params)>0) { // Save the resulting found indices pvec_indices->reserve(nbQuery * NN); pvec_distances->reserve(nbQuery * NN); for (size_t i = 0; i < nbQuery; ++i) { for (size_t j = 0; j < NN; ++j) { if (indices[i] > 0) { pvec_indices->emplace_back(IndMatch(i, vec_indices[i*NN+j])); pvec_distances->emplace_back(vec_distances[i*NN+j]); } } } return true; } else { return false; } } else { return false; } } private : std::unique_ptr< flann::Matrix<Scalar> > _datasetM; std::unique_ptr< flann::Index<Metric> > _index; std::size_t _dimension; }; } // namespace matching } // namespace openMVG #endif // OPENMVG_MATCHING_ARRAYMATCHER_KDTREE_FLANN_H_ <commit_msg>[matching kdtree] formatting cleaning<commit_after>// Copyright (c) 2012, 2013 Pierre MOULON. // 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/. #ifndef OPENMVG_MATCHING_ARRAYMATCHER_KDTREE_FLANN_H_ #define OPENMVG_MATCHING_ARRAYMATCHER_KDTREE_FLANN_H_ #include "openMVG/matching/matching_interface.hpp" #include "flann/flann.hpp" #include <memory> namespace openMVG { namespace matching { /// Implement ArrayMatcher as a FLANN KDtree matcher. // http://www.cs.ubc.ca/~mariusm/index.php/FLANN/FLANN // David G. Lowe and Marius Muja // // By default use squared L2 metric (flann::L2<Scalar>) // sqrt is monotonic so for performance reason we do not compute it. template < typename Scalar = float, typename Metric = flann::L2<Scalar> > class ArrayMatcher_Kdtree_Flann : public ArrayMatcher<Scalar, Metric> { public: typedef typename Metric::ResultType DistanceType; ArrayMatcher_Kdtree_Flann() {} virtual ~ArrayMatcher_Kdtree_Flann() { _datasetM.reset(); _index.reset(); } /** * Build the matching structure * * \param[in] dataset Input data. * \param[in] nbRows The number of component. * \param[in] dimension Length of the data contained in the each * row of the dataset. * * \return True if success. */ bool Build( const Scalar * dataset, int nbRows, int dimension) { if (nbRows <= 0) return false; _dimension = dimension; //-- Build Flann Matrix container (map to already allocated memory) _datasetM.reset( new flann::Matrix<Scalar>((Scalar*)dataset, nbRows, dimension)); //-- Build FLANN index _index.reset( new flann::Index<Metric> (*_datasetM, flann::KDTreeIndexParams(4))); _index->buildIndex(); return true; } /** * Search the nearest Neighbor of the scalar array query. * * \param[in] query The query array * \param[out] indice The indice of array in the dataset that * have been computed as the nearest array. * \param[out] distance The distance between the two arrays. * * \return True if success. */ bool SearchNeighbour( const Scalar * query, int * indice, DistanceType * distance) { if (_index.get() == NULL) return false; int * indicePTR = indice; DistanceType * distancePTR = distance; flann::Matrix<Scalar> queries((Scalar*)query, 1, _dimension); flann::Matrix<int> indices(indicePTR, 1, 1); flann::Matrix<DistanceType> dists(distancePTR, 1, 1); // do a knn search, using 128 checks return (_index->knnSearch(queries, indices, dists, 1, flann::SearchParams(128)) > 0); } /** * Search the N nearest Neighbor of the scalar array query. * * \param[in] query The query array * \param[in] nbQuery The number of query rows * \param[out] indices The corresponding (query, neighbor) indices * \param[out] pvec_distances The distances between the matched arrays. * \param[out] NN The number of maximal neighbor that will be searched. * * \return True if success. */ bool SearchNeighbours ( const Scalar * query, int nbQuery, IndMatches * pvec_indices, std::vector<DistanceType> * pvec_distances, size_t NN ) { if (_index.get() == NULL || NN > _datasetM->rows) return false; std::vector<DistanceType> vec_distances(nbQuery * NN); DistanceType * distancePTR = &(vec_distances[0]); flann::Matrix<DistanceType> dists(distancePTR, nbQuery, NN); std::vector<int> vec_indices(nbQuery * NN); int * indicePTR = &(vec_indices[0]); flann::Matrix<int> indices(indicePTR, nbQuery, NN); flann::Matrix<Scalar> queries((Scalar*)query, nbQuery, _dimension); // do a knn search, using 128 checks flann::SearchParams params(128); #ifdef OPENMVG_USE_OPENMP params.cores = omp_get_max_threads(); #endif if (_index->knnSearch(queries, indices, dists, NN, params) <= 0) return false; // Save the resulting found indices pvec_indices->reserve(nbQuery * NN); pvec_distances->reserve(nbQuery * NN); for (size_t i = 0; i < nbQuery; ++i) { for (size_t j = 0; j < NN; ++j) { if (indices[i] > 0) { pvec_indices->emplace_back(IndMatch(i, vec_indices[i*NN+j])); pvec_distances->emplace_back(vec_distances[i*NN+j]); } } } return true; } private: std::unique_ptr< flann::Matrix<Scalar> > _datasetM; std::unique_ptr< flann::Index<Metric> > _index; std::size_t _dimension; }; } // namespace matching } // namespace openMVG #endif // OPENMVG_MATCHING_ARRAYMATCHER_KDTREE_FLANN_H_ <|endoftext|>
<commit_before>#define _USE_MATH_DEFINES #include <math.h> #include <RigAnimatedObject.h> #include <algorithm> #include "glm/gtc/matrix_transform.hpp" #include <glbinding/gl/enum.h> #include <globjects/globjects.h> #include <globjects/Program.h> #include <gloperate/primitives/AbstractDrawable.h> #include <gloperate/primitives/PolygonalDrawable.h> #include <gloperate/primitives/PolygonalGeometry.h> #include <gloperate-assimp/AssimpSceneLoader.h> #include <RiggedDrawable.h> using namespace gl; using namespace globjects; RigAnimatedObject::RigAnimatedObject(gloperate::Scene *animated, gloperate::Scene *animations) { for(gloperate::PolygonalGeometry* curDrawable : animated->meshes()) { m_animated.push_back(std::shared_ptr<RiggedDrawable>{new RiggedDrawable(*curDrawable)}); } m_animations = std::shared_ptr<gloperate::Scene>(animations); m_program = new Program{}; m_program->attach( Shader::fromFile(GL_VERTEX_SHADER, "data/animationexample/rigAnim.vert"), Shader::fromFile(GL_FRAGMENT_SHADER, "data/animationexample/rigAnim.frag")); m_transformLocation = m_program->getUniformLocation("transform"); m_bonesUniform = new globjects::Uniform<std::vector<glm::mat4>>{"bones"}; m_program->addUniform(m_bonesUniform); } void RigAnimatedObject::draw(float time, const glm::mat4 &viewProjection) { for(auto& curDrawable : m_animated) { std::vector<glm::mat4> current = interpolate(time, curDrawable); m_program->use(); m_program->setUniform(m_transformLocation, viewProjection); m_bonesUniform->set(current); curDrawable->draw(); } m_program->release(); } std::vector<glm::mat4> RigAnimatedObject::interpolate(float t, std::shared_ptr<RiggedDrawable> curAnimated) { std::vector<glm::mat4> boneTransforms{curAnimated->m_bindTransforms.size()}; interpolateRecursively(*(m_animations->boneHierarchy()), t, boneTransforms, glm::mat4(), curAnimated); return boneTransforms; } void RigAnimatedObject::interpolateRecursively(const BoneNode& Bone, float t, std::vector<glm::mat4> &into, glm::mat4 parentTransform, std::shared_ptr<RiggedDrawable> curAnimated) { //Of course sometimes the model and the animation have different views about the start of the hierarchy //if(Bone.boneName == "<MD5_Hierarchy>") //{ // interpolateRecursively(Bone.children[0],t,into,parentTransform,curAnimated); // return; //} gloperate::RigAnimationTrack* Animation = m_animations->animations()[0]; gloperate::Channel* BoneChannel = nullptr; for(size_t i = 0; i < Animation->boneChannels.size(); i++) { if(Animation->boneChannels.at(i).boneName == Bone.boneName) { BoneChannel = &(Animation->boneChannels[i]); } } if(!BoneChannel) { interpolateRecursively(Bone.children[0],t,into,parentTransform,curAnimated); return; } float ticks = t * Animation->ticksPerSecond; //Find the corresponding Translate key and interpolate glm::vec3 translation; if(BoneChannel->translation.size() > 1) { gloperate::TranslationKey first,second; for(size_t i = 0; i < BoneChannel->translation.size(); i++) { if(ticks < BoneChannel->translation[i].time) { second = BoneChannel->translation[i]; } else { first = BoneChannel->translation[i]; } } float dist = second.time - first.time; float pos = t - first.time; // The distance to the first frame float normPos = pos/dist; // Normalized position between 0 an 1 normPos = normPos < 0 ? 0 : normPos; normPos = normPos > 1 ? 1 : normPos; translation = glm::mix(first.translation,second.translation,normPos); } else { if(BoneChannel->translation.size() != 0) { translation = BoneChannel->translation[0].translation; } } glm::quat rotation; if(BoneChannel->rotation.size() > 1) { gloperate::RotationKey first,second; for(size_t i = 0; i < BoneChannel->rotation.size(); i++) { if(ticks < BoneChannel->rotation[i].time) { second = BoneChannel->rotation[i]; } else { first = BoneChannel->rotation[i]; } } float dist = second.time - first.time; float pos = t - first.time; // The distance to the first frame float normPos = pos/dist; // Normalized position between 0 an 1 normPos = normPos < 0 ? 0 : normPos; normPos = normPos > 1 ? 1 : normPos; rotation = glm::mix(first.rotation,second.rotation,normPos); } else { if(BoneChannel->rotation.size() != 0) { rotation = BoneChannel->rotation[0].rotation; } } glm::vec3 scale; if(BoneChannel->scale.size() > 1) { gloperate::ScaleKey first,second; for(size_t i = 0; i < BoneChannel->scale.size(); i++) { if(ticks < BoneChannel->scale[i].time) { second = BoneChannel->scale[i]; } else { first = BoneChannel->scale[i]; } } float dist = second.time - first.time; float pos = t - first.time; // The distance to the first frame float normPos = pos/dist; // Normalized position between 0 an 1 normPos = normPos < 0 ? 0 : normPos; normPos = normPos > 1 ? 1 : normPos; scale = glm::mix(first.scale,second.scale,normPos); } else { if(BoneChannel->scale.size() != 0) { scale = BoneChannel->scale[0].scale; } } glm::mat4 transform; transform = glm::translate(transform, translation); //transform = glm::scale(transform, scale); transform = transform * glm::mat4_cast(rotation); transform = parentTransform * transform; if(curAnimated->m_boneMapping.count(BoneChannel->boneName) == 1) { auto boneIndex = curAnimated->m_boneMapping.at(BoneChannel->boneName); into[boneIndex] = transform * curAnimated->m_bindTransforms[boneIndex]; } for (auto& child : Bone.children) { interpolateRecursively(child, t, into, transform, curAnimated); } } <commit_msg>adding scale support<commit_after>#define _USE_MATH_DEFINES #include <math.h> #include <RigAnimatedObject.h> #include <algorithm> #include "glm/gtc/matrix_transform.hpp" #include <glbinding/gl/enum.h> #include <globjects/globjects.h> #include <globjects/Program.h> #include <gloperate/primitives/AbstractDrawable.h> #include <gloperate/primitives/PolygonalDrawable.h> #include <gloperate/primitives/PolygonalGeometry.h> #include <gloperate-assimp/AssimpSceneLoader.h> #include <RiggedDrawable.h> using namespace gl; using namespace globjects; RigAnimatedObject::RigAnimatedObject(gloperate::Scene *animated, gloperate::Scene *animations) { for(gloperate::PolygonalGeometry* curDrawable : animated->meshes()) { m_animated.push_back(std::shared_ptr<RiggedDrawable>{new RiggedDrawable(*curDrawable)}); } m_animations = std::shared_ptr<gloperate::Scene>(animations); m_program = new Program{}; m_program->attach( Shader::fromFile(GL_VERTEX_SHADER, "data/animationexample/rigAnim.vert"), Shader::fromFile(GL_FRAGMENT_SHADER, "data/animationexample/rigAnim.frag")); m_transformLocation = m_program->getUniformLocation("transform"); m_bonesUniform = new globjects::Uniform<std::vector<glm::mat4>>{"bones"}; m_program->addUniform(m_bonesUniform); } void RigAnimatedObject::draw(float time, const glm::mat4 &viewProjection) { for(auto& curDrawable : m_animated) { std::vector<glm::mat4> current = interpolate(time, curDrawable); m_program->use(); m_program->setUniform(m_transformLocation, viewProjection); m_bonesUniform->set(current); curDrawable->draw(); } m_program->release(); } std::vector<glm::mat4> RigAnimatedObject::interpolate(float t, std::shared_ptr<RiggedDrawable> curAnimated) { std::vector<glm::mat4> boneTransforms{curAnimated->m_bindTransforms.size()}; interpolateRecursively(*(m_animations->boneHierarchy()), t, boneTransforms, glm::mat4(), curAnimated); return boneTransforms; } void RigAnimatedObject::interpolateRecursively(const BoneNode& Bone, float t, std::vector<glm::mat4> &into, glm::mat4 parentTransform, std::shared_ptr<RiggedDrawable> curAnimated) { //Of course sometimes the model and the animation have different views about the start of the hierarchy //if(Bone.boneName == "<MD5_Hierarchy>") //{ // interpolateRecursively(Bone.children[0],t,into,parentTransform,curAnimated); // return; //} gloperate::RigAnimationTrack* Animation = m_animations->animations()[0]; gloperate::Channel* BoneChannel = nullptr; for(size_t i = 0; i < Animation->boneChannels.size(); i++) { if(Animation->boneChannels.at(i).boneName == Bone.boneName) { BoneChannel = &(Animation->boneChannels[i]); } } if(!BoneChannel) { interpolateRecursively(Bone.children[0],t,into,parentTransform,curAnimated); return; } float ticks = t * Animation->ticksPerSecond; //Find the corresponding Translate key and interpolate glm::vec3 translation; if(BoneChannel->translation.size() > 1) { gloperate::TranslationKey first,second; for(size_t i = 0; i < BoneChannel->translation.size(); i++) { if(ticks < BoneChannel->translation[i].time) { second = BoneChannel->translation[i]; } else { first = BoneChannel->translation[i]; } } float dist = second.time - first.time; float pos = t - first.time; // The distance to the first frame float normPos = pos/dist; // Normalized position between 0 an 1 normPos = normPos < 0 ? 0 : normPos; normPos = normPos > 1 ? 1 : normPos; translation = glm::mix(first.translation,second.translation,normPos); } else { if(BoneChannel->translation.size() != 0) { translation = BoneChannel->translation[0].translation; } } glm::quat rotation; if(BoneChannel->rotation.size() > 1) { gloperate::RotationKey first,second; for(size_t i = 0; i < BoneChannel->rotation.size(); i++) { if(ticks < BoneChannel->rotation[i].time) { second = BoneChannel->rotation[i]; } else { first = BoneChannel->rotation[i]; } } float dist = second.time - first.time; float pos = t - first.time; // The distance to the first frame float normPos = pos/dist; // Normalized position between 0 an 1 normPos = normPos < 0 ? 0 : normPos; normPos = normPos > 1 ? 1 : normPos; rotation = glm::mix(first.rotation,second.rotation,normPos); } else { if(BoneChannel->rotation.size() != 0) { rotation = BoneChannel->rotation[0].rotation; } } glm::vec3 scale; if(BoneChannel->scale.size() > 1) { gloperate::ScaleKey first,second; for(size_t i = 0; i < BoneChannel->scale.size(); i++) { if(ticks < BoneChannel->scale[i].time) { second = BoneChannel->scale[i]; } else { first = BoneChannel->scale[i]; } } float dist = second.time - first.time; float pos = t - first.time; // The distance to the first frame float normPos = pos/dist; // Normalized position between 0 an 1 normPos = normPos < 0 ? 0 : normPos; normPos = normPos > 1 ? 1 : normPos; scale = glm::mix(first.scale,second.scale,normPos); } else { if(BoneChannel->scale.size() != 0) { scale = BoneChannel->scale[0].scale; } } glm::mat4 transform; transform = glm::translate(transform, translation); transform = glm::scale(transform, scale); transform = transform * glm::mat4_cast(rotation); transform = parentTransform * transform; if(curAnimated->m_boneMapping.count(BoneChannel->boneName) == 1) { auto boneIndex = curAnimated->m_boneMapping.at(BoneChannel->boneName); into[boneIndex] = transform * curAnimated->m_bindTransforms[boneIndex]; } for (auto& child : Bone.children) { interpolateRecursively(child, t, into, transform, curAnimated); } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: dlgeddef.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: tbe $ $Date: 2001-09-17 11:23:54 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _BASCTL_DLGEDDEF_HXX #define _BASCTL_DLGEDDEF_HXX #ifndef _SOLAR_H #include <tools/solar.h> #endif const UINT32 DlgInventor = UINT32('D')*0x00000001+ UINT32('L')*0x00000100+ UINT32('G')*0x00010000+ UINT32('1')*0x01000000; #define OBJ_DLG_CONTROL ((UINT16) 1) #define OBJ_DLG_DIALOG ((UINT16) 2) #define OBJ_DLG_PUSHBUTTON ((UINT16) 3) #define OBJ_DLG_RADIOBUTTON ((UINT16) 4) #define OBJ_DLG_CHECKBOX ((UINT16) 5) #define OBJ_DLG_LISTBOX ((UINT16) 6) #define OBJ_DLG_COMBOBOX ((UINT16) 7) #define OBJ_DLG_GROUPBOX ((UINT16) 8) #define OBJ_DLG_EDIT ((UINT16) 9) #define OBJ_DLG_FIXEDTEXT ((UINT16)10) #define OBJ_DLG_IMAGECONTROL ((UINT16)11) #define OBJ_DLG_PROGRESSBAR ((UINT16)12) #define OBJ_DLG_HSCROLLBAR ((UINT16)13) #define OBJ_DLG_VSCROLLBAR ((UINT16)14) #define OBJ_DLG_HFIXEDLINE ((UINT16)15) #define OBJ_DLG_VFIXEDLINE ((UINT16)16) #define OBJ_DLG_DATEFIELD ((UINT16)17) #define OBJ_DLG_TIMEFIELD ((UINT16)18) #define OBJ_DLG_NUMERICFIELD ((UINT16)19) #define OBJ_DLG_CURRENCYFIELD ((UINT16)20) #define OBJ_DLG_FORMATTEDFIELD ((UINT16)21) #define OBJ_DLG_PATTERNFIELD ((UINT16)22) #define OBJ_DLG_FILECONTROL ((UINT16)23) #endif // _BASCTL_DLGEDDEF_HXX <commit_msg>INTEGRATION: CWS tbe14 (1.3.300); FILE MERGED 2004/11/17 14:04:17 tbe 1.3.300.1: #i31563# scroll area too small<commit_after>/************************************************************************* * * $RCSfile: dlgeddef.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2004-12-10 17:02:58 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _BASCTL_DLGEDDEF_HXX #define _BASCTL_DLGEDDEF_HXX #ifndef _SOLAR_H #include <tools/solar.h> #endif const UINT32 DlgInventor = UINT32('D')*0x00000001+ UINT32('L')*0x00000100+ UINT32('G')*0x00010000+ UINT32('1')*0x01000000; #define OBJ_DLG_CONTROL ((UINT16) 1) #define OBJ_DLG_DIALOG ((UINT16) 2) #define OBJ_DLG_PUSHBUTTON ((UINT16) 3) #define OBJ_DLG_RADIOBUTTON ((UINT16) 4) #define OBJ_DLG_CHECKBOX ((UINT16) 5) #define OBJ_DLG_LISTBOX ((UINT16) 6) #define OBJ_DLG_COMBOBOX ((UINT16) 7) #define OBJ_DLG_GROUPBOX ((UINT16) 8) #define OBJ_DLG_EDIT ((UINT16) 9) #define OBJ_DLG_FIXEDTEXT ((UINT16)10) #define OBJ_DLG_IMAGECONTROL ((UINT16)11) #define OBJ_DLG_PROGRESSBAR ((UINT16)12) #define OBJ_DLG_HSCROLLBAR ((UINT16)13) #define OBJ_DLG_VSCROLLBAR ((UINT16)14) #define OBJ_DLG_HFIXEDLINE ((UINT16)15) #define OBJ_DLG_VFIXEDLINE ((UINT16)16) #define OBJ_DLG_DATEFIELD ((UINT16)17) #define OBJ_DLG_TIMEFIELD ((UINT16)18) #define OBJ_DLG_NUMERICFIELD ((UINT16)19) #define OBJ_DLG_CURRENCYFIELD ((UINT16)20) #define OBJ_DLG_FORMATTEDFIELD ((UINT16)21) #define OBJ_DLG_PATTERNFIELD ((UINT16)22) #define OBJ_DLG_FILECONTROL ((UINT16)23) // control properties #define DLGED_PROP_BACKGROUNDCOLOR ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "BackgroundColor" ) ) #define DLGED_PROP_DROPDOWN ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Dropdown" ) ) #define DLGED_PROP_FORMATSSUPPLIER ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "FormatsSupplier" ) ) #define DLGED_PROP_HEIGHT ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Height" ) ) #define DLGED_PROP_LABEL ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Label" ) ) #define DLGED_PROP_NAME ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Name" ) ) #define DLGED_PROP_ORIENTATION ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Orientation" ) ) #define DLGED_PROP_POSITIONX ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PositionX" ) ) #define DLGED_PROP_POSITIONY ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "PositionY" ) ) #define DLGED_PROP_STEP ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Step" ) ) #define DLGED_PROP_TABINDEX ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "TabIndex" ) ) #define DLGED_PROP_TEXTCOLOR ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "TextColor" ) ) #define DLGED_PROP_TEXTLINECOLOR ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "TextLineColor" ) ) #define DLGED_PROP_WIDTH ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Width" ) ) #endif // _BASCTL_DLGEDDEF_HXX <|endoftext|>
<commit_before>#pragma once #include "base/recurring_thread.hpp" #include "gtest/gtest.h" namespace principia { using namespace std::chrono_literals; namespace base { class RecurringThreadTest : public ::testing::Test { protected: using ToyRecurringThread = RecurringThread<int, double>; static double PoolingGet(ToyRecurringThread& thread) { std::optional<double> output; do { output = thread.Get(); std::this_thread::sleep_for(50us); } while (!output.has_value()); return output.value(); } }; TEST_F(RecurringThreadTest, Basic) { auto add_one_half = [](int const input) { return static_cast<double>(input) + 0.5; }; ToyRecurringThread thread(std::move(add_one_half), 1ms); thread.Put(3); { double const output = PoolingGet(thread); EXPECT_EQ(3.5, output); } EXPECT_FALSE(thread.Get().has_value()); thread.Put(4); { double const output = PoolingGet(thread); EXPECT_EQ(4.5, output); } } } // namespace base } // namespace principia <commit_msg>Fix a test.<commit_after>#pragma once #include "base/recurring_thread.hpp" #include "gtest/gtest.h" namespace principia { using namespace std::chrono_literals; namespace base { class RecurringThreadTest : public ::testing::Test { protected: using ToyRecurringThread = RecurringThread<int, double>; static double PoolingGet(ToyRecurringThread& thread) { std::optional<double> output; do { output = thread.Get(); std::this_thread::sleep_for(50us); } while (!output.has_value()); return output.value(); } }; TEST_F(RecurringThreadTest, Basic) { auto add_one_half = [](int const input) { return static_cast<double>(input) + 0.5; }; ToyRecurringThread thread(std::move(add_one_half), 1ms); thread.Start(); thread.Put(3); { double const output = PoolingGet(thread); EXPECT_EQ(3.5, output); } EXPECT_FALSE(thread.Get().has_value()); thread.Put(4); { double const output = PoolingGet(thread); EXPECT_EQ(4.5, output); } } } // namespace base } // namespace principia <|endoftext|>
<commit_before>#include <pcl/point_types.h> #include <pcl/io/pcd_io.h> #include <pcl/kdtree/kdtree_flann.h> #include <pcl/surface/mls.h> int main (int argc, char** argv) { // Load input file into a PointCloud<T> with an appropriate type pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ> ()); // Load bun0.pcd -- should be available with the PCL archive in test pcl::io::loadPCDFile ("bun0.pcd", *cloud); // Create a KD-Tree pcl::search::KdTree<pcl::PointXYZ>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZ>); // Output has the same type as the input one, it will be only smoothed pcl::PointCloud<pcl::PointXYZ> mls_points; // Init object (second point type is for the normals, even if unused) pcl::MovingLeastSquares<pcl::PointXYZ, pcl::Normal> mls; // Optionally, a pointer to a cloud can be provided, to be set by MLS pcl::PointCloud<pcl::Normal>::Ptr mls_normals (new pcl::PointCloud<pcl::Normal> ()); mls.setOutputNormals (mls_normals); // Set parameters mls.setInputCloud (cloud); mls.setPolynomialFit (true); mls.setSearchMethod (tree); mls.setSearchRadius (0.03); // Reconstruct mls.reconstruct (mls_points); // Concatenate fields for saving pcl::PointCloud<pcl::PointNormal> mls_cloud; pcl::concatenateFields (mls_points, *mls_normals, mls_cloud); // Save output pcl::io::savePCDFile ("bun0-mls.pcd", mls_cloud); } <commit_msg>fixing tutorials for the new MLS code<commit_after>#include <pcl/point_types.h> #include <pcl/io/pcd_io.h> #include <pcl/kdtree/kdtree_flann.h> #include <pcl/surface/mls.h> int main (int argc, char** argv) { // Load input file into a PointCloud<T> with an appropriate type pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ> ()); // Load bun0.pcd -- should be available with the PCL archive in test pcl::io::loadPCDFile ("bun0.pcd", *cloud); // Create a KD-Tree pcl::search::KdTree<pcl::PointXYZ>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZ>); // Output has the PointNormal type in order to store the normals calculated by MLS pcl::PointCloud<pcl::PointNormal> mls_points; // Init object (second point type is for the normals, even if unused) pcl::MovingLeastSquares<pcl::PointXYZ, pcl::PointNormal> mls; mls.setComputeNormals (true); // Set parameters mls.setInputCloud (cloud); mls.setPolynomialFit (true); mls.setSearchMethod (tree); mls.setSearchRadius (0.03); // Reconstruct mls.process (mls_points); // Save output pcl::io::savePCDFile ("bun0-mls.pcd", mls_points); } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "androidanalyzesupport.h" #include "androidrunner.h" #include "androidmanager.h" #include <analyzerbase/ianalyzertool.h> #include <analyzerbase/ianalyzerengine.h> #include <analyzerbase/analyzermanager.h> #include <analyzerbase/analyzerruncontrol.h> #include <analyzerbase/analyzerstartparameters.h> #include <projectexplorer/target.h> #include <projectexplorer/project.h> #include <qtsupport/qtkitinformation.h> #include <QDir> #include <QTcpServer> using namespace Analyzer; using namespace ProjectExplorer; namespace Android { namespace Internal { RunControl *AndroidAnalyzeSupport::createAnalyzeRunControl(AndroidRunConfiguration *runConfig, RunMode runMode, QString *errorMessage) { IAnalyzerTool *tool = AnalyzerManager::toolFromRunMode(runMode); if (!tool) { if (errorMessage) *errorMessage = tr("No analyzer tool selected."); return 0; } AnalyzerStartParameters params; params.toolId = tool->id(); params.startMode = StartQmlRemote; Target *target = runConfig->target(); params.displayName = AndroidManager::packageName(target); params.sysroot = SysRootKitInformation::sysRoot(target->kit()).toString(); // TODO: Not sure if these are the right paths. params.workingDirectory = target->project()->projectDirectory(); if (runMode == ProjectExplorer::QmlProfilerRunMode) { QTcpServer server; QTC_ASSERT(server.listen(QHostAddress::LocalHost) || server.listen(QHostAddress::LocalHostIPv6), return 0); params.analyzerHost = server.serverAddress().toString(); } AnalyzerRunControl * const analyzerRunControl = new AnalyzerRunControl(tool, params, runConfig); new AndroidAnalyzeSupport(runConfig, analyzerRunControl); return analyzerRunControl; } AndroidAnalyzeSupport::AndroidAnalyzeSupport(AndroidRunConfiguration *runConfig, AnalyzerRunControl *runControl) : AndroidRunSupport(runConfig, runControl), m_engine(0), m_qmlPort(0) { if (runControl) { m_engine = runControl->engine(); if (m_engine) { connect(m_engine, SIGNAL(starting(const Analyzer::IAnalyzerEngine*)), m_runner, SLOT(start())); } } connect(&m_outputParser, SIGNAL(waitingForConnectionOnPort(quint16)), SLOT(remoteIsRunning())); connect(m_runner, SIGNAL(remoteProcessStarted(int)), SLOT(handleRemoteProcessStarted(int))); connect(m_runner, SIGNAL(remoteProcessFinished(QString)), SLOT(handleRemoteProcessFinished(QString))); connect(m_runner, SIGNAL(remoteErrorOutput(QByteArray)), SLOT(handleRemoteErrorOutput(QByteArray))); connect(m_runner, SIGNAL(remoteOutput(QByteArray)), SLOT(handleRemoteOutput(QByteArray))); } void AndroidAnalyzeSupport::handleRemoteProcessStarted(int qmlPort) { m_qmlPort = qmlPort; } void AndroidAnalyzeSupport::handleRemoteOutput(const QByteArray &output) { const QString msg = QString::fromUtf8(output); if (m_engine) m_engine->logApplicationMessage(msg, Utils::StdOutFormatSameLine); else AndroidRunSupport::handleRemoteOutput(output); m_outputParser.processOutput(msg); } void AndroidAnalyzeSupport::handleRemoteErrorOutput(const QByteArray &output) { if (m_engine) m_engine->logApplicationMessage(QString::fromUtf8(output), Utils::StdErrFormatSameLine); else AndroidRunSupport::handleRemoteErrorOutput(output); } void AndroidAnalyzeSupport::remoteIsRunning() { if (m_engine) m_engine->notifyRemoteSetupDone(m_qmlPort); } } // namespace Internal } // namespace Android <commit_msg>AndroidAnalyzeSupport: Set start mode depending upon run mode<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "androidanalyzesupport.h" #include "androidrunner.h" #include "androidmanager.h" #include <analyzerbase/ianalyzertool.h> #include <analyzerbase/ianalyzerengine.h> #include <analyzerbase/analyzermanager.h> #include <analyzerbase/analyzerruncontrol.h> #include <analyzerbase/analyzerstartparameters.h> #include <projectexplorer/target.h> #include <projectexplorer/project.h> #include <qtsupport/qtkitinformation.h> #include <QDir> #include <QTcpServer> using namespace Analyzer; using namespace ProjectExplorer; namespace Android { namespace Internal { RunControl *AndroidAnalyzeSupport::createAnalyzeRunControl(AndroidRunConfiguration *runConfig, RunMode runMode, QString *errorMessage) { IAnalyzerTool *tool = AnalyzerManager::toolFromRunMode(runMode); if (!tool) { if (errorMessage) *errorMessage = tr("No analyzer tool selected."); return 0; } AnalyzerStartParameters params; params.toolId = tool->id(); Target *target = runConfig->target(); params.displayName = AndroidManager::packageName(target); params.sysroot = SysRootKitInformation::sysRoot(target->kit()).toString(); // TODO: Not sure if these are the right paths. params.workingDirectory = target->project()->projectDirectory(); if (runMode == ProjectExplorer::QmlProfilerRunMode) { QTcpServer server; QTC_ASSERT(server.listen(QHostAddress::LocalHost) || server.listen(QHostAddress::LocalHostIPv6), return 0); params.analyzerHost = server.serverAddress().toString(); params.startMode = StartQmlRemote; } AnalyzerRunControl * const analyzerRunControl = new AnalyzerRunControl(tool, params, runConfig); new AndroidAnalyzeSupport(runConfig, analyzerRunControl); return analyzerRunControl; } AndroidAnalyzeSupport::AndroidAnalyzeSupport(AndroidRunConfiguration *runConfig, AnalyzerRunControl *runControl) : AndroidRunSupport(runConfig, runControl), m_engine(0), m_qmlPort(0) { if (runControl) { m_engine = runControl->engine(); if (m_engine) { connect(m_engine, SIGNAL(starting(const Analyzer::IAnalyzerEngine*)), m_runner, SLOT(start())); } } connect(&m_outputParser, SIGNAL(waitingForConnectionOnPort(quint16)), SLOT(remoteIsRunning())); connect(m_runner, SIGNAL(remoteProcessStarted(int)), SLOT(handleRemoteProcessStarted(int))); connect(m_runner, SIGNAL(remoteProcessFinished(QString)), SLOT(handleRemoteProcessFinished(QString))); connect(m_runner, SIGNAL(remoteErrorOutput(QByteArray)), SLOT(handleRemoteErrorOutput(QByteArray))); connect(m_runner, SIGNAL(remoteOutput(QByteArray)), SLOT(handleRemoteOutput(QByteArray))); } void AndroidAnalyzeSupport::handleRemoteProcessStarted(int qmlPort) { m_qmlPort = qmlPort; } void AndroidAnalyzeSupport::handleRemoteOutput(const QByteArray &output) { const QString msg = QString::fromUtf8(output); if (m_engine) m_engine->logApplicationMessage(msg, Utils::StdOutFormatSameLine); else AndroidRunSupport::handleRemoteOutput(output); m_outputParser.processOutput(msg); } void AndroidAnalyzeSupport::handleRemoteErrorOutput(const QByteArray &output) { if (m_engine) m_engine->logApplicationMessage(QString::fromUtf8(output), Utils::StdErrFormatSameLine); else AndroidRunSupport::handleRemoteErrorOutput(output); } void AndroidAnalyzeSupport::remoteIsRunning() { if (m_engine) m_engine->notifyRemoteSetupDone(m_qmlPort); } } // namespace Internal } // namespace Android <|endoftext|>
<commit_before>/** * @file * * @brief Source for directoryvalue plugin * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) * */ #include "directoryvalue.hpp" #include "log.hpp" #include <kdbhelper.h> using ckdb::keyNew; using std::exception; using std::range_error; using elektra::DirectoryValueDelegate; using CppKey = kdb::Key; using CppKeySet = kdb::KeySet; namespace { /** * @brief This function returns a key set containing the plugin contract. * * @return A key set specifying the capabilities of the plugin */ CppKeySet getContract () { return CppKeySet{ 30, keyNew ("system/elektra/modules/directoryvalue", KEY_VALUE, "directoryvalue plugin waits for your orders", KEY_END), keyNew ("system/elektra/modules/directoryvalue/exports", KEY_END), keyNew ("system/elektra/modules/directoryvalue/exports/open", KEY_FUNC, elektraDirectoryValueOpen, KEY_END), keyNew ("system/elektra/modules/directoryvalue/exports/close", KEY_FUNC, elektraDirectoryValueClose, KEY_END), keyNew ("system/elektra/modules/directoryvalue/exports/get", KEY_FUNC, elektraDirectoryValueGet, KEY_END), keyNew ("system/elektra/modules/directoryvalue/exports/set", KEY_FUNC, elektraDirectoryValueSet, KEY_END), #include ELEKTRA_README keyNew ("system/elektra/modules/directoryvalue/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END }; } } // end namespace extern "C" { typedef Delegator<DirectoryValueDelegate> delegator; /** @see elektraDocOpen */ int elektraDirectoryValueOpen (Plugin * handle, Key * key) { return delegator::open (handle, key); } /** @see elektraDocClose */ int elektraDirectoryValueClose (Plugin * handle, Key * key) { return delegator::close (handle, key); } /** @see elektraDocGet */ int elektraDirectoryValueGet (Plugin * handle, KeySet * returned, Key * parentKey) { CppKeySet keys{ returned }; CppKey parent{ parentKey }; #ifdef HAVE_LOGGER ELEKTRA_LOG_DEBUG ("Convert keys:"); logKeySet (keys); #endif if (parent.getName () == "system/elektra/modules/directoryvalue") { keys.append (getContract ()); parent.release (); keys.release (); return ELEKTRA_PLUGIN_STATUS_SUCCESS; } int status = ELEKTRA_PLUGIN_STATUS_ERROR; try { status = delegator::get (handle)->convertToDirectories (keys); } catch (range_error const & error) { ELEKTRA_SET_VALIDATION_SYNTACTIC_ERRORF (*parent, "Unable to insert array value %s", error.what ()); } catch (exception const & error) { ELEKTRA_SET_PLUGIN_MISBEHAVIOR_ERRORF (*parent, "Uncaught Exception: %s", error.what ()); } #ifdef HAVE_LOGGER ELEKTRA_LOG_DEBUG ("Converted keys:"); logKeySet (keys); #endif parent.release (); keys.release (); return status; } /** @see elektraDocSet */ int elektraDirectoryValueSet (Plugin * handle, KeySet * returned, Key * parentKey) { CppKeySet keys{ returned }; CppKey parent{ parentKey }; int status = ELEKTRA_PLUGIN_STATUS_ERROR; #ifdef HAVE_LOGGER ELEKTRA_LOG_DEBUG ("Convert keys:"); logKeySet (keys); #endif try { status = delegator::get (handle)->convertToLeaves (keys); } catch (range_error const & error) { ELEKTRA_SET_VALIDATION_SYNTACTIC_ERRORF (*parent, "Unable to insert array value %s", error.what ()); } catch (exception const & error) { ELEKTRA_SET_PLUGIN_MISBEHAVIOR_ERRORF (*parent, "Uncaught exception: %s", error.what ()); } parent.release (); keys.release (); return status; } Plugin * ELEKTRA_PLUGIN_EXPORT { // clang-format off return elektraPluginExport ("directoryvalue", ELEKTRA_PLUGIN_OPEN, &elektraDirectoryValueOpen, ELEKTRA_PLUGIN_CLOSE, &elektraDirectoryValueClose, ELEKTRA_PLUGIN_GET, &elektraDirectoryValueGet, ELEKTRA_PLUGIN_SET, &elektraDirectoryValueSet, ELEKTRA_PLUGIN_END); } } // end extern "C" <commit_msg>Directory Value: Move logging code<commit_after>/** * @file * * @brief Source for directoryvalue plugin * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) * */ #include "directoryvalue.hpp" #include "log.hpp" #include <kdbhelper.h> using ckdb::keyNew; using std::exception; using std::range_error; using elektra::DirectoryValueDelegate; using CppKey = kdb::Key; using CppKeySet = kdb::KeySet; namespace { /** * @brief This function returns a key set containing the plugin contract. * * @return A key set specifying the capabilities of the plugin */ CppKeySet getContract () { return CppKeySet{ 30, keyNew ("system/elektra/modules/directoryvalue", KEY_VALUE, "directoryvalue plugin waits for your orders", KEY_END), keyNew ("system/elektra/modules/directoryvalue/exports", KEY_END), keyNew ("system/elektra/modules/directoryvalue/exports/open", KEY_FUNC, elektraDirectoryValueOpen, KEY_END), keyNew ("system/elektra/modules/directoryvalue/exports/close", KEY_FUNC, elektraDirectoryValueClose, KEY_END), keyNew ("system/elektra/modules/directoryvalue/exports/get", KEY_FUNC, elektraDirectoryValueGet, KEY_END), keyNew ("system/elektra/modules/directoryvalue/exports/set", KEY_FUNC, elektraDirectoryValueSet, KEY_END), #include ELEKTRA_README keyNew ("system/elektra/modules/directoryvalue/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END }; } } // end namespace extern "C" { typedef Delegator<DirectoryValueDelegate> delegator; /** @see elektraDocOpen */ int elektraDirectoryValueOpen (Plugin * handle, Key * key) { return delegator::open (handle, key); } /** @see elektraDocClose */ int elektraDirectoryValueClose (Plugin * handle, Key * key) { return delegator::close (handle, key); } /** @see elektraDocGet */ int elektraDirectoryValueGet (Plugin * handle, KeySet * returned, Key * parentKey) { CppKeySet keys{ returned }; CppKey parent{ parentKey }; if (parent.getName () == "system/elektra/modules/directoryvalue") { keys.append (getContract ()); parent.release (); keys.release (); return ELEKTRA_PLUGIN_STATUS_SUCCESS; } #ifdef HAVE_LOGGER ELEKTRA_LOG_DEBUG ("Convert keys:"); logKeySet (keys); #endif int status = ELEKTRA_PLUGIN_STATUS_ERROR; try { status = delegator::get (handle)->convertToDirectories (keys); } catch (range_error const & error) { ELEKTRA_SET_VALIDATION_SYNTACTIC_ERRORF (*parent, "Unable to insert array value %s", error.what ()); } catch (exception const & error) { ELEKTRA_SET_PLUGIN_MISBEHAVIOR_ERRORF (*parent, "Uncaught Exception: %s", error.what ()); } #ifdef HAVE_LOGGER ELEKTRA_LOG_DEBUG ("Converted keys:"); logKeySet (keys); #endif parent.release (); keys.release (); return status; } /** @see elektraDocSet */ int elektraDirectoryValueSet (Plugin * handle, KeySet * returned, Key * parentKey) { CppKeySet keys{ returned }; CppKey parent{ parentKey }; int status = ELEKTRA_PLUGIN_STATUS_ERROR; #ifdef HAVE_LOGGER ELEKTRA_LOG_DEBUG ("Convert keys:"); logKeySet (keys); #endif try { status = delegator::get (handle)->convertToLeaves (keys); } catch (range_error const & error) { ELEKTRA_SET_VALIDATION_SYNTACTIC_ERRORF (*parent, "Unable to insert array value %s", error.what ()); } catch (exception const & error) { ELEKTRA_SET_PLUGIN_MISBEHAVIOR_ERRORF (*parent, "Uncaught exception: %s", error.what ()); } parent.release (); keys.release (); return status; } Plugin * ELEKTRA_PLUGIN_EXPORT { // clang-format off return elektraPluginExport ("directoryvalue", ELEKTRA_PLUGIN_OPEN, &elektraDirectoryValueOpen, ELEKTRA_PLUGIN_CLOSE, &elektraDirectoryValueClose, ELEKTRA_PLUGIN_GET, &elektraDirectoryValueGet, ELEKTRA_PLUGIN_SET, &elektraDirectoryValueSet, ELEKTRA_PLUGIN_END); } } // end extern "C" <|endoftext|>
<commit_before>/** * The Seeks proxy and plugin framework are part of the SEEKS project. * Copyright (C) 2011 Emmanuel Benazera, ebenazer@seeks-project.info * Copyright (C) 2011 Stéphane Bonhomme <stephane.bonhomme@seeks.pro> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "xsl_serializer.h" #include "xml_renderer.h" #include "seeks_proxy.h" #include "miscutil.h" #include <string.h> #include <iostream> using namespace sp; namespace seeks_plugins { xsl_serializer::xsl_serializer() :plugin() { _name = "xsl-serializer"; _version_major = "0"; _version_minor = "1"; xmlSubstituteEntitiesDefault(1); xmlLoadExtDtdDefaultValue = 1; } xsl_serializer::~xsl_serializer() { xsltCleanupGlobals(); xmlCleanupParser(); } void xsl_serializer::start() { } void xsl_serializer::stop() { } /* public methods */ /* render_xsl_cached_queries render_xsl_clustered_results render_xsl_engines render_xsl_node_options render_xsl_recommendations render_xsl_results render_xsl_snippet render_xsl_suggested_queries render_xsl_words */ sp_err xsl_serializer::render_xsl_cached_queries(client_state *csp, http_response *rsp, const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters, const std::string &query, const int &nq) { sp_err res=SP_ERR_OK; xmlDocPtr doc=xmlNewDoc(BAD_CAST "1.0"); res = xml_renderer::render_xml_cached_queries(query,nq,doc); res = res || xsl_serializer::response(rsp,parameters,doc); xmlFreeDoc(doc); return res; } sp_err xsl_serializer::render_xsl_clustered_results(client_state *csp, http_response *rsp, const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters, const query_context *qc, cluster *clusters, const short &K, const double &qtime) { sp_err res=SP_ERR_OK; xmlDocPtr doc=xmlNewDoc(BAD_CAST "1.0"); res = xml_renderer::render_xml_clustered_results(qc, parameters,clusters,K,qtime, doc); res = res || xsl_serializer::response(rsp,parameters,doc); xmlFreeDoc(doc); return res; } sp_err xsl_serializer::render_xsl_engines(client_state *csp, http_response *rsp, const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters, const feeds &engines) { sp_err res=SP_ERR_OK; xmlDocPtr doc=xmlNewDoc(BAD_CAST "1.0"); res = xml_renderer::render_xml_engines(engines, doc); res = res || xsl_serializer::response(rsp,parameters,doc); xmlFreeDoc(doc); return res; } sp_err xsl_serializer::render_xsl_node_options(client_state *csp, http_response *rsp, const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters) { sp_err res=SP_ERR_OK; xmlDocPtr doc=xmlNewDoc(BAD_CAST "1.0"); res=xml_renderer::render_xml_node_options(csp, doc); res = res || xsl_serializer::response(rsp,parameters,doc); xmlFreeDoc(doc); return res; } sp_err xsl_serializer::render_xsl_recommendations(const client_state *csp, http_response *rsp, const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters, const query_context *qc, const double &qtime, const int &radius, const std::string &lang) { sp_err res=SP_ERR_OK; xmlDocPtr doc=xmlNewDoc(BAD_CAST "1.0"); res=xml_renderer::render_xml_recommendations(qc,parameters,qtime,radius,lang,doc); res = res || xsl_serializer::response(rsp,parameters,doc); xmlFreeDoc(doc); return res; } sp_err xsl_serializer::render_xsl_results(client_state *csp, http_response *rsp, const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters, const query_context *qc, const std::vector<search_snippet*> &snippets, const double &qtime, const bool &img) { sp_err res=SP_ERR_OK; xmlDocPtr doc=xmlNewDoc(BAD_CAST "1.0"); res=xml_renderer::render_xml_results(qc, parameters,snippets, qtime, img, doc); res = res || xsl_serializer::response(rsp,parameters,doc); xmlFreeDoc(doc); return res; } sp_err xsl_serializer::render_xsl_snippet(client_state *csp, http_response *rsp, const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters, query_context *qc, const search_snippet *sp) { sp_err res=SP_ERR_OK; xmlDocPtr doc=xmlNewDoc(BAD_CAST "1.0"); res=xml_renderer::render_xml_snippet(qc,sp,doc); res = res || xsl_serializer::response(rsp,parameters,doc); xmlFreeDoc(doc); return res; } sp_err xsl_serializer::render_xsl_suggested_queries(client_state *csp, http_response *rsp, const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters, const query_context *qc) { sp_err res=SP_ERR_OK; xmlDocPtr doc=xmlNewDoc(BAD_CAST "1.0"); res=xml_renderer::render_xml_suggested_queries(qc,parameters,doc); res = res || xsl_serializer::response(rsp,parameters,doc); xmlFreeDoc(doc); return res; } sp_err xsl_serializer::render_xsl_words(client_state *csp, http_response *rsp, const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters, const std::set<std::string> &words) { sp_err res=SP_ERR_OK; xmlDocPtr doc=xmlNewDoc(BAD_CAST "1.0"); res=xml_renderer::render_xml_words(words,doc); res = res || xsl_serializer::response(rsp,parameters,doc); xmlFreeDoc(doc); return res; } /* private */ sp_err xsl_serializer::response(http_response *rsp, const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters, xmlDocPtr doc) { sp_err res=SP_ERR_OK; // check for parameter stylesheet const char *stylesheet = miscutil::lookup(parameters,"stylesheet"); int buffersize; if (!stylesheet) { xmlChar *xmlbuff; xmlDocDumpFormatMemory(doc, &xmlbuff, &buffersize, 0); miscutil::enlist(&rsp->_headers, "Content-Type: text/xml"); rsp->_body = strdup((char *)xmlbuff); rsp->_content_length = buffersize; xmlFree(xmlbuff); } else { xsl_serializer::transform(rsp,doc,stylesheet); } rsp->_is_static = 1; return res; } void xsl_serializer::transform(http_response *rsp, xmlDocPtr doc, const std::string stylesheet) { xsltStylesheetPtr cur; xmlDocPtr stylesheet_doc,res_doc; xmlNodePtr root_element, cur_node; char *ct=NULL; xmlChar *buffer; int length; // parse the stylesheet as libxml2 Document stylesheet_doc=xsl_serializer::get_stylesheet(stylesheet); // get the content type // Get the root element node root_element = xmlDocGetRootElement(stylesheet_doc); for (cur_node = root_element->children; cur_node; cur_node = cur_node->next) { if (cur_node->type == XML_PI_NODE && !strcmp((char *)(cur_node->name), "Content-Type:")) { ct=strdup( (char *)cur_node->name); strcat(ct, (char *)cur_node->content); miscutil::enlist(&rsp->_headers, ct); } } if (!ct) { miscutil::enlist(&rsp->_headers, "Content-Type: text/xml"); } // prepare the xslt cur = xsltParseStylesheetDoc(stylesheet_doc); // apply the stylesheet const char **params=NULL; res_doc = xsltApplyStylesheet(cur, doc, params); xsltSaveResultToString(&buffer, &length, res_doc, cur); rsp->_content_length = length; rsp->_body = strdup((char *)buffer); free(buffer); xsltFreeStylesheet(cur); xmlFreeDoc(res_doc); xmlFreeDoc(stylesheet_doc); } xmlDocPtr xsl_serializer::get_stylesheet(const std::string stylesheet) { std::string stylesheet_path; xmlDocPtr xslt; // TODO : manage a cache of stylesheets if (seeks_proxy::_datadir.empty()) stylesheet_path = plugin_manager::_plugin_repository + "websearch/stylesheets/" + stylesheet + ".xsl"; else stylesheet_path = seeks_proxy::_datadir + "/plugins/websearch/stylesheets/" + stylesheet + ".xsl"; xslt=xmlParseFile(stylesheet_path.c_str()); return xslt; } /* plugin registration. */ extern "C" { plugin* maker() { return new xsl_serializer; } } } /* end of namespace */ <commit_msg>prevent form crash if stylesheet could not be loaded<commit_after>/** * The Seeks proxy and plugin framework are part of the SEEKS project. * Copyright (C) 2011 Emmanuel Benazera, ebenazer@seeks-project.info * Copyright (C) 2011 Stéphane Bonhomme <stephane.bonhomme@seeks.pro> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "xsl_serializer.h" #include "xml_renderer.h" #include "seeks_proxy.h" #include "miscutil.h" #include <string.h> #include <iostream> using namespace sp; namespace seeks_plugins { xsl_serializer::xsl_serializer() :plugin() { _name = "xsl-serializer"; _version_major = "0"; _version_minor = "1"; xmlSubstituteEntitiesDefault(1); xmlLoadExtDtdDefaultValue = 1; } xsl_serializer::~xsl_serializer() { xsltCleanupGlobals(); xmlCleanupParser(); } void xsl_serializer::start() { } void xsl_serializer::stop() { } /* public methods */ /* render_xsl_cached_queries render_xsl_clustered_results render_xsl_engines render_xsl_node_options render_xsl_recommendations render_xsl_results render_xsl_snippet render_xsl_suggested_queries render_xsl_words */ sp_err xsl_serializer::render_xsl_cached_queries(client_state *csp, http_response *rsp, const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters, const std::string &query, const int &nq) { sp_err res=SP_ERR_OK; xmlDocPtr doc=xmlNewDoc(BAD_CAST "1.0"); res = xml_renderer::render_xml_cached_queries(query,nq,doc); res = res || xsl_serializer::response(rsp,parameters,doc); xmlFreeDoc(doc); return res; } sp_err xsl_serializer::render_xsl_clustered_results(client_state *csp, http_response *rsp, const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters, const query_context *qc, cluster *clusters, const short &K, const double &qtime) { sp_err res=SP_ERR_OK; xmlDocPtr doc=xmlNewDoc(BAD_CAST "1.0"); res = xml_renderer::render_xml_clustered_results(qc, parameters,clusters,K,qtime, doc); res = res || xsl_serializer::response(rsp,parameters,doc); xmlFreeDoc(doc); return res; } sp_err xsl_serializer::render_xsl_engines(client_state *csp, http_response *rsp, const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters, const feeds &engines) { sp_err res=SP_ERR_OK; xmlDocPtr doc=xmlNewDoc(BAD_CAST "1.0"); res = xml_renderer::render_xml_engines(engines, doc); res = res || xsl_serializer::response(rsp,parameters,doc); xmlFreeDoc(doc); return res; } sp_err xsl_serializer::render_xsl_node_options(client_state *csp, http_response *rsp, const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters) { sp_err res=SP_ERR_OK; xmlDocPtr doc=xmlNewDoc(BAD_CAST "1.0"); res=xml_renderer::render_xml_node_options(csp, doc); res = res || xsl_serializer::response(rsp,parameters,doc); xmlFreeDoc(doc); return res; } sp_err xsl_serializer::render_xsl_recommendations(const client_state *csp, http_response *rsp, const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters, const query_context *qc, const double &qtime, const int &radius, const std::string &lang) { sp_err res=SP_ERR_OK; xmlDocPtr doc=xmlNewDoc(BAD_CAST "1.0"); res=xml_renderer::render_xml_recommendations(qc,parameters,qtime,radius,lang,doc); res = res || xsl_serializer::response(rsp,parameters,doc); xmlFreeDoc(doc); return res; } sp_err xsl_serializer::render_xsl_results(client_state *csp, http_response *rsp, const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters, const query_context *qc, const std::vector<search_snippet*> &snippets, const double &qtime, const bool &img) { sp_err res=SP_ERR_OK; xmlDocPtr doc=xmlNewDoc(BAD_CAST "1.0"); res=xml_renderer::render_xml_results(qc, parameters,snippets, qtime, img, doc); res = res || xsl_serializer::response(rsp,parameters,doc); xmlFreeDoc(doc); return res; } sp_err xsl_serializer::render_xsl_snippet(client_state *csp, http_response *rsp, const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters, query_context *qc, const search_snippet *sp) { sp_err res=SP_ERR_OK; xmlDocPtr doc=xmlNewDoc(BAD_CAST "1.0"); res=xml_renderer::render_xml_snippet(qc,sp,doc); res = res || xsl_serializer::response(rsp,parameters,doc); xmlFreeDoc(doc); return res; } sp_err xsl_serializer::render_xsl_suggested_queries(client_state *csp, http_response *rsp, const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters, const query_context *qc) { sp_err res=SP_ERR_OK; xmlDocPtr doc=xmlNewDoc(BAD_CAST "1.0"); res=xml_renderer::render_xml_suggested_queries(qc,parameters,doc); res = res || xsl_serializer::response(rsp,parameters,doc); xmlFreeDoc(doc); return res; } sp_err xsl_serializer::render_xsl_words(client_state *csp, http_response *rsp, const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters, const std::set<std::string> &words) { sp_err res=SP_ERR_OK; xmlDocPtr doc=xmlNewDoc(BAD_CAST "1.0"); res=xml_renderer::render_xml_words(words,doc); res = res || xsl_serializer::response(rsp,parameters,doc); xmlFreeDoc(doc); return res; } /* private */ sp_err xsl_serializer::response(http_response *rsp, const hash_map<const char*, const char*, hash<const char*>, eqstr> *parameters, xmlDocPtr doc) { sp_err res=SP_ERR_OK; // check for parameter stylesheet const char *stylesheet = miscutil::lookup(parameters,"stylesheet"); int buffersize; if (!stylesheet) { xmlChar *xmlbuff; xmlDocDumpFormatMemory(doc, &xmlbuff, &buffersize, 0); miscutil::enlist(&rsp->_headers, "Content-Type: text/xml"); rsp->_body = strdup((char *)xmlbuff); rsp->_content_length = buffersize; xmlFree(xmlbuff); } else { xsl_serializer::transform(rsp,doc,stylesheet); } rsp->_is_static = 1; return res; } void xsl_serializer::transform(http_response *rsp, xmlDocPtr doc, const std::string stylesheet) { xsltStylesheetPtr cur; xmlDocPtr stylesheet_doc,res_doc; xmlNodePtr root_element, cur_node; char *ct=NULL; xmlChar *buffer; int length; // parse the stylesheet as libxml2 Document stylesheet_doc=xsl_serializer::get_stylesheet(stylesheet); if (!stylesheet_doc) return; // get the content type // Get the root element node root_element = xmlDocGetRootElement(stylesheet_doc); for (cur_node = root_element->children; cur_node; cur_node = cur_node->next) { if (cur_node->type == XML_PI_NODE && !strcmp((char *)(cur_node->name), "Content-Type:")) { ct=strdup( (char *)cur_node->name); strcat(ct, (char *)cur_node->content); miscutil::enlist(&rsp->_headers, ct); } } if (!ct) { miscutil::enlist(&rsp->_headers, "Content-Type: text/xml"); } // prepare the xslt cur = xsltParseStylesheetDoc(stylesheet_doc); // apply the stylesheet const char **params=NULL; res_doc = xsltApplyStylesheet(cur, doc, params); xsltSaveResultToString(&buffer, &length, res_doc, cur); rsp->_content_length = length; rsp->_body = strdup((char *)buffer); free(buffer); xsltFreeStylesheet(cur); xmlFreeDoc(res_doc); xmlFreeDoc(stylesheet_doc); } xmlDocPtr xsl_serializer::get_stylesheet(const std::string stylesheet) { std::string stylesheet_path; xmlDocPtr xslt; // TODO : manage a cache of stylesheets if (seeks_proxy::_datadir.empty()) stylesheet_path = plugin_manager::_plugin_repository + "websearch/stylesheets/" + stylesheet + ".xsl"; else stylesheet_path = seeks_proxy::_datadir + "/plugins/websearch/stylesheets/" + stylesheet + ".xsl"; xslt=xmlParseFile(stylesheet_path.c_str()); return xslt; } /* plugin registration. */ extern "C" { plugin* maker() { return new xsl_serializer; } } } /* end of namespace */ <|endoftext|>
<commit_before><commit_msg>Add driver inputs in Polaris SPH vehicle output files<commit_after><|endoftext|>
<commit_before>#include "rift/bucket.hpp" #include <elliptics/session.hpp> #include <boost/algorithm/string.hpp> #include <boost/program_options.hpp> using namespace ioremap; int main(int argc, char *argv[]) { struct rift::bucket_meta_raw meta; std::vector<int> groups; std::string remote; std::string metadata_groups_str; std::string data_groups_str; std::string noauth; int log_level; namespace bpo = boost::program_options; bpo::variables_map vm; bpo::options_description generic("Bucket control options"); generic.add_options() ("help", "This help message") ("remote", bpo::value<std::string>(&remote), "Remote elliptics server address") ("log-level", bpo::value<int>(&log_level)->default_value(DNET_LOG_ERROR), "Elliptics message log level (messages will be written into stdout)") ("bucket", bpo::value<std::string>(&meta.key), "Bucket (namespace) name") ("metadata-groups", bpo::value<std::string>(&metadata_groups_str), "Metadata groups string (colon separated). These groups are used to store bucket info") ("read", "Read and print bucket metadata, all options below will be ignored") ("token", bpo::value<std::string>(&meta.token), "Secure token (can be empty for no authorization)") ("data-groups", bpo::value<std::string>(&data_groups_str), "Data groups string (colon separated). " "These groups are used to store real data written into this namespace/bucket") ("noauth", bpo::value<std::string>(&noauth), "Noauth option:\n" " 'read' means read requests (read, download-info, lookup and other GET requests) " "will bypass authentication check, POST upload requests will pass through proper auth check\n" " 'all' - all requests for this bucket will bypass auth checks") ("max-size", bpo::value<uint64_t>(&meta.max_size)->default_value(0), "Maximum object size (unsupported yet) in given bucket") ("max-key-num", bpo::value<uint64_t>(&meta.max_key_num)->default_value(0), "Maximum number of objects in given bucket (unsupported yet)") ; try { bpo::store(bpo::parse_command_line(argc, argv, generic), vm); bpo::notify(vm); } catch (const std::exception &e) { std::cerr << "Command line parsing error\n" << generic; return -1; } if (vm.count("help")) { std::cerr << generic; return -1; } if (!vm.count("metadata-groups") || !vm.count("bucket") || !vm.count("remote")) { std::cerr << "Remote server address, bucket name and metadata groups are required\n" << generic; return -1; } struct digitizer { int operator() (const std::string &str) { return atoi(str.c_str()); } }; std::vector<std::string> gr; boost::split(gr, metadata_groups_str, boost::is_any_of(":")); std::transform(gr.begin(), gr.end(), std::back_inserter<std::vector<int>>(groups), digitizer()); try { elliptics::file_logger log("/dev/stdout", log_level); elliptics::node node(log); node.add_remote(remote.c_str()); elliptics::session session(node); session.set_groups(groups); if (vm.count("read")) { try { elliptics::data_pointer data = session.read_data(meta.key, 0, 0).get_one().file(); msgpack::unpacked msg; msgpack::unpack(&msg, data.data<char>(), data.size()); msg.get().convert(&meta); std::ostringstream ss; for (auto gr = meta.groups.begin(); gr != meta.groups.end();) { ss << *gr; ++gr; if (gr != meta.groups.end()) ss << ":"; } data_groups_str = ss.str(); } catch (const std::exception &e) { std::cout << "Could not write bucket metadata: " << e.what() << std::endl; return -1; } } else { if (!vm.count("data-groups")) { std::cerr << "Data groups are required\n" << generic; return -1; } if (noauth == "read") meta.flags |= rift::bucket_meta_raw::flags_noauth_read; else if (noauth == "all") meta.flags |= rift::bucket_meta_raw::flags_noauth_all; gr.clear(); boost::split(gr, data_groups_str, boost::is_any_of(":")); std::transform(gr.begin(), gr.end(), std::back_inserter<std::vector<int>>(meta.groups), digitizer()); msgpack::sbuffer buf; msgpack::pack(buf, meta); try { session.write_data(meta.key, elliptics::data_pointer::copy(buf.data(), buf.size()), 0).wait(); } catch (const std::exception &e) { std::cout << "Could not write bucket metadata: " << e.what() << std::endl; return -1; } printf("Successfully written bucket metadata\n"); } } catch (const std::exception &e) { std::cout << "Failed to create elliptics client node and session: " << e.what() << std::endl; return -1; } printf("Metadata info:\n" " bucket: %s\n" " token: %s\n" " data groups: %s\n" " flags: 0x%lx\n" " maximum record size: %ld\n" " maximum number of keys: %ld\n" " metadata stored in the following groups: %s\n", meta.key.c_str(), meta.token.c_str(), data_groups_str.c_str(), meta.flags, meta.max_size, meta.max_key_num, metadata_groups_str.c_str()); return 0; } <commit_msg>bucket_ctl: added iostream header inclusion<commit_after>#include "rift/bucket.hpp" #include <iostream> #include <elliptics/session.hpp> #include <boost/algorithm/string.hpp> #include <boost/program_options.hpp> using namespace ioremap; int main(int argc, char *argv[]) { struct rift::bucket_meta_raw meta; std::vector<int> groups; std::string remote; std::string metadata_groups_str; std::string data_groups_str; std::string noauth; int log_level; namespace bpo = boost::program_options; bpo::variables_map vm; bpo::options_description generic("Bucket control options"); generic.add_options() ("help", "This help message") ("remote", bpo::value<std::string>(&remote), "Remote elliptics server address") ("log-level", bpo::value<int>(&log_level)->default_value(DNET_LOG_ERROR), "Elliptics message log level (messages will be written into stdout)") ("bucket", bpo::value<std::string>(&meta.key), "Bucket (namespace) name") ("metadata-groups", bpo::value<std::string>(&metadata_groups_str), "Metadata groups string (colon separated). These groups are used to store bucket info") ("read", "Read and print bucket metadata, all options below will be ignored") ("token", bpo::value<std::string>(&meta.token), "Secure token (can be empty for no authorization)") ("data-groups", bpo::value<std::string>(&data_groups_str), "Data groups string (colon separated). " "These groups are used to store real data written into this namespace/bucket") ("noauth", bpo::value<std::string>(&noauth), "Noauth option:\n" " 'read' means read requests (read, download-info, lookup and other GET requests) " "will bypass authentication check, POST upload requests will pass through proper auth check\n" " 'all' - all requests for this bucket will bypass auth checks") ("max-size", bpo::value<uint64_t>(&meta.max_size)->default_value(0), "Maximum object size (unsupported yet) in given bucket") ("max-key-num", bpo::value<uint64_t>(&meta.max_key_num)->default_value(0), "Maximum number of objects in given bucket (unsupported yet)") ; try { bpo::store(bpo::parse_command_line(argc, argv, generic), vm); bpo::notify(vm); } catch (const std::exception &e) { std::cerr << "Command line parsing error\n" << generic; return -1; } if (vm.count("help")) { std::cerr << generic; return -1; } if (!vm.count("metadata-groups") || !vm.count("bucket") || !vm.count("remote")) { std::cerr << "Remote server address, bucket name and metadata groups are required\n" << generic; return -1; } struct digitizer { int operator() (const std::string &str) { return atoi(str.c_str()); } }; std::vector<std::string> gr; boost::split(gr, metadata_groups_str, boost::is_any_of(":")); std::transform(gr.begin(), gr.end(), std::back_inserter<std::vector<int>>(groups), digitizer()); try { elliptics::file_logger log("/dev/stdout", log_level); elliptics::node node(log); node.add_remote(remote.c_str()); elliptics::session session(node); session.set_groups(groups); if (vm.count("read")) { try { elliptics::data_pointer data = session.read_data(meta.key, 0, 0).get_one().file(); msgpack::unpacked msg; msgpack::unpack(&msg, data.data<char>(), data.size()); msg.get().convert(&meta); std::ostringstream ss; for (auto gr = meta.groups.begin(); gr != meta.groups.end();) { ss << *gr; ++gr; if (gr != meta.groups.end()) ss << ":"; } data_groups_str = ss.str(); } catch (const std::exception &e) { std::cout << "Could not write bucket metadata: " << e.what() << std::endl; return -1; } } else { if (!vm.count("data-groups")) { std::cerr << "Data groups are required\n" << generic; return -1; } if (noauth == "read") meta.flags |= rift::bucket_meta_raw::flags_noauth_read; else if (noauth == "all") meta.flags |= rift::bucket_meta_raw::flags_noauth_all; gr.clear(); boost::split(gr, data_groups_str, boost::is_any_of(":")); std::transform(gr.begin(), gr.end(), std::back_inserter<std::vector<int>>(meta.groups), digitizer()); msgpack::sbuffer buf; msgpack::pack(buf, meta); try { session.write_data(meta.key, elliptics::data_pointer::copy(buf.data(), buf.size()), 0).wait(); } catch (const std::exception &e) { std::cout << "Could not write bucket metadata: " << e.what() << std::endl; return -1; } printf("Successfully written bucket metadata\n"); } } catch (const std::exception &e) { std::cout << "Failed to create elliptics client node and session: " << e.what() << std::endl; return -1; } printf("Metadata info:\n" " bucket: %s\n" " token: %s\n" " data groups: %s\n" " flags: 0x%lx\n" " maximum record size: %ld\n" " maximum number of keys: %ld\n" " metadata stored in the following groups: %s\n", meta.key.c_str(), meta.token.c_str(), data_groups_str.c_str(), meta.flags, meta.max_size, meta.max_key_num, metadata_groups_str.c_str()); return 0; } <|endoftext|>
<commit_before>#include "docopt/docopt.h" #include <iostream> #include <cstdlib> static const char USAGE[] = R"(Causal Dynamical Triangulations in C++ using CGAL. Copyright (c) 2014 Adam Getchell A program that generates d-dimensional triangulated spacetimes with a defined causal structure and evolves them according to the Metropolis algorithm. Usage:./cdt (--spherical | --toroidal) -n=SIMPLICES -t=TIMESLICES [-d=DIM] -k=K Options: -h --help Show this message --version Show program version -n SIMPLICES Approximate number of simplices -t TIMESLICES Number of timeslices -d DIM Dimensionality [default: 3] -k K K constant )"; int main (int argc, char const *argv[]) { std::map<std::string, docopt::value> args = docopt::docopt(USAGE, { argv + 1, argv + argc}, true, // print help message automatically "CDT 1.0"); // Version // Debugging for (auto const& arg : args) { std::cout << arg.first << arg.second << std::endl; } return 0; } <commit_msg>cdt-docopt now has same functionality as cdt<commit_after>/// Causal Dynamical Triangulations in C++ using CGAL /// /// Copyright (c) 2014 Adam Getchell /// /// A program that generates spacetimes /// /// Inspired by https://github.com/ucdavis/CDT /// CGAL headers #include <CGAL/Timer.h> /// C++ headers #include <iostream> #include <cstdlib> #include <map> #include <string> #include <vector> /// Docopt #include "docopt/docopt.h" /// CDT headers #include "./utilities.h" #include "S3Triangulation.h" /// Help message parsed by docopt into options static const char USAGE[] = R"(Causal Dynamical Triangulations in C++ using CGAL. Copyright (c) 2014 Adam Getchell A program that generates d-dimensional triangulated spacetimes with a defined causal structure and evolves them according to the Metropolis algorithm. Usage:./cdt-docopt (--spherical | --toroidal) -n SIMPLICES -t TIMESLICES [-d DIM] -k K --alpha ALPHA --lambda LAMBDA Examples: ./cdt-docopt --spherical -n 64000 -t 256 --alpha 1.1 -k 2.2 --lambda 3.3 ./cdt-docopt --s -n64000 -t256 -a1.1 -k2.2 -l3.3 Options: -h --help Show this message --version Show program version -n SIMPLICES Approximate number of simplices -t TIMESLICES Number of timeslices -d DIM Dimensionality [default: 3] -a --alpha ALPHA Alpha constant -k K K constant -l --lambda LAMBDA Lambda constant )"; int main(int argc, char const *argv[]) { /// Start running time CGAL::Timer t; t.start(); /// docopt option parser std::map<std::string, docopt::value> args = docopt::docopt(USAGE, { argv + 1, argv + argc}, true, // print help message automatically "CDT 1.0"); // Version enum topology_type { TOROIDAL, SPHERICAL}; /// These contain cell handles for the (3,1), (2,2), and (1,3) simplices std::vector<Cell_handle> three_one; std::vector<Cell_handle> two_two; std::vector<Cell_handle> one_three; /// Debugging for (auto const& arg : args) { std::cout << arg.first << " " << arg.second << std::endl; } /// Parse docopt::values in args map int simplices = std::stoi(args["-n"].asString()); int timeslices = std::stoi(args["-t"].asString()); int dimensions = std::stoi(args["-d"].asString()); double alpha = std::stod(args["--alpha"].asString()); double k = std::stod(args["-k"].asString()); double lambda = std::stod(args["--lambda"].asString()); // Topology of simulation topology_type topology; if (args["--spherical"].asBool() == true) { topology = SPHERICAL; } else { topology = TOROIDAL; } /// Display job parameters std::cout << "Topology is " << (topology == TOROIDAL ? " toroidal " : "spherical ") << std::endl; std::cout << "Number of dimensions = " << dimensions << std::endl; std::cout << "Number of simplices = " << simplices << std::endl; std::cout << "Number of timeslices = " << timeslices << std::endl; std::cout << "Alpha = " << alpha << std::endl; std::cout << "K = " << k << std::endl; std::cout << "Lambda = " << lambda << std::endl; std::cout << "User = " << getEnvVar("USER") << std::endl; std::cout << "Hostname = " << hostname() << std::endl; /// Initialize spherical Delaunay triangulation Delaunay Sphere3; switch (topology) { case SPHERICAL: make_S3_triangulation(&Sphere3, simplices, timeslices, false, &three_one, &two_two, &one_three); t.stop(); // End running time counter std::cout << "Final Delaunay triangulation has "; print_results(&Sphere3, &t); write_file(&Sphere3, 's', dimensions, Sphere3.number_of_finite_cells(), timeslices); break; case TOROIDAL: std::cout << "make_T3_triangulation not implemented yet." << std::endl; t.stop(); // End running time counter break; } return 0; } <|endoftext|>
<commit_before>/* **** **** **** **** **** **** **** **** * * * _/ _/ _/ * _/_/_/ _/_/_/ _/_/_/ * _/ _/ _/ _/ _/ _/ * _/ _/ _/ _/ _/ _/ * _/_/_/ _/_/_/ _/_/_/ * * bit by bit * bbb/function/lambda_symbol.hpp * * author: ISHII 2bit * mail: bit_by_bit@2bit.jp * * **** **** **** **** **** **** **** **** */ #pragma once #include <bbb/core.hpp> namespace bbb { namespace function { namespace lambda_symbol { namespace detail { template <typename server> struct subscript { private: const server &cont; public: subscript(const server &cont) : cont(cont) {}; template <typename subscript> constexpr auto operator()(subscript &&index) const -> decltype(cont[index]) { return cont[index]; }; }; template <typename callee> struct apply { private: const callee &f; public: apply(const callee &f) : f(f) {}; template <typename ... arguments> constexpr auto operator()(arguments && ... args) const -> decltype(f(args ...)) { return f(args ...); }; }; struct call { template <typename callee> constexpr auto operator()(callee &f) const -> decltype(f()) { return f(); } }; struct bnot_op { template <typename value_type> constexpr auto operator()(const value_type &v) const -> decltype(~v) { return ~v; } }; struct lnot_op { template <typename value_type> constexpr auto operator()(const value_type &v) const -> decltype(!v) { return !v; } }; struct pre_inc_op { template <typename value_type> constexpr auto operator()(value_type &v) const -> decltype(++v) { return v; } }; struct post_inc_op { template <typename value_type> constexpr auto operator()(value_type &v) const -> decltype(v++) { return v++; } }; struct pre_dec_op { template <typename value_type> constexpr auto operator()(value_type &v) const -> decltype(--v) { return v; } }; struct post_dec_op { template <typename value_type> constexpr auto operator()(value_type &v) const -> decltype(v--) { return v--; } }; }; constexpr struct { template <typename T> detail::subscript<T> operator[](const T &t) const { return detail::subscript<T>(t); } template <typename T> detail::apply<T> operator()(const T &t) const { return detail::apply<T>(t); } detail::call operator()() const { return {}; } detail::bnot_op operator~() const { return {}; } detail::lnot_op operator!() const { return {}; } detail::pre_inc_op operator++() const { return {}; } detail::post_inc_op operator++(int) const { return {}; } detail::pre_dec_op operator--() const { return {}; } detail::post_dec_op operator--(int) const { return {}; } } lambda{}; #define def_left_op(op, name)\ namespace detail {\ template <typename L>\ struct left_##name {\ private:\ const L &lhs;\ public:\ left_##name(const L &lhs) : lhs(lhs) {}\ template <typename R>\ constexpr auto operator()(const R & rhs) const -> decltype(lhs op rhs) { return lhs op rhs; };\ };\ };\ template <typename L>\ constexpr detail::left_##name<L> operator op(const L &lhs, const decltype(lambda) &) {\ return detail::left_##name<L>(lhs);\ }; #define def_right_op(op, name)\ namespace detail {\ template <typename R>\ struct right_##name {\ private:\ const R &rhs;\ public:\ right_##name(const R &rhs) : rhs(rhs) {}\ template <typename L>\ constexpr auto operator()(const L & lhs) const -> decltype(lhs op rhs) { return lhs op rhs; };\ };\ };\ template <typename R>\ constexpr detail::right_##name<R> operator op(const decltype(lambda) &, const R &rhs) {\ return detail::right_##name<R>(rhs);\ }; #define def_op(op, name)\ def_left_op(op, name);\ def_right_op(op, name); def_op(==, eq); def_op(!=, neq); def_op(<, lt); def_op(<=, lte); def_op(>, gt); def_op(>=, gte); def_op(&&, land); def_op(||, lor); def_op(+, plus); def_op(-, minus); def_op(*, mult); def_op(/, div); def_op(%, mod); def_op(&, band); def_op(|, bor); def_op(^, bxor); def_op(<<, lshift); def_op(>>, rshift); #undef def_op #undef def_left_op #undef def_right_op #define def_destructive_left_op(op, name)\ namespace detail {\ template <typename L>\ struct left_##name {\ private:\ L &lhs;\ public:\ left_##name(L &lhs) : lhs(lhs) {}\ template <typename R>\ constexpr auto operator()(const R & rhs) const -> decltype(lhs op rhs) { return lhs op rhs; };\ };\ };\ template <typename L>\ constexpr detail::left_##name<L> operator op(L &lhs, const decltype(lambda) &) {\ return detail::left_##name<L>(lhs);\ }; #define def_destructive_right_op(op, name)\ namespace detail {\ template <typename R>\ struct right_##name {\ private:\ const R &rhs;\ public:\ right_##name(const R &rhs) : rhs(rhs) {}\ template <typename L>\ constexpr auto operator()(L & lhs) const -> decltype(lhs op rhs) { return lhs op rhs; };\ };\ };\ template <typename R>\ constexpr detail::right_##name<R> operator op(const decltype(lambda) &, const R &rhs) {\ return detail::right_##name<R>(rhs);\ }; #define def_destructive_op(op, name)\ def_destructive_left_op(op, name);\ def_destructive_right_op(op, name); def_destructive_op(&=, band_eq); def_destructive_op(|=, bor_eq); def_destructive_op(^=, bxor_eq); def_destructive_op(+=, plus_eq); def_destructive_op(-=, miuns_eq); def_destructive_op(*=, mult_eq); def_destructive_op(/=, div_eq); def_destructive_op(%=, mod_eq); def_destructive_op(<<=, lshift_eq); def_destructive_op(>>=, rshift_eq); }; using namespace lambda_symbol; }; }; #define bbb_use_lambda_symbol(sym) decltype(bbb::function::lambda) & sym = bbb::function::lambda; <commit_msg>publish into bbb<commit_after>/* **** **** **** **** **** **** **** **** * * * _/ _/ _/ * _/_/_/ _/_/_/ _/_/_/ * _/ _/ _/ _/ _/ _/ * _/ _/ _/ _/ _/ _/ * _/_/_/ _/_/_/ _/_/_/ * * bit by bit * bbb/function/lambda_symbol.hpp * * author: ISHII 2bit * mail: bit_by_bit@2bit.jp * * **** **** **** **** **** **** **** **** */ #pragma once #include <bbb/core.hpp> namespace bbb { namespace function { namespace lambda_symbol { namespace detail { template <typename server> struct subscript { private: const server &cont; public: subscript(const server &cont) : cont(cont) {}; template <typename subscript> constexpr auto operator()(subscript &&index) const -> decltype(cont[index]) { return cont[index]; }; }; template <typename callee> struct apply { private: const callee &f; public: apply(const callee &f) : f(f) {}; template <typename ... arguments> constexpr auto operator()(arguments && ... args) const -> decltype(f(args ...)) { return f(args ...); }; }; struct call { template <typename callee> constexpr auto operator()(callee &f) const -> decltype(f()) { return f(); } }; struct bnot_op { template <typename value_type> constexpr auto operator()(const value_type &v) const -> decltype(~v) { return ~v; } }; struct lnot_op { template <typename value_type> constexpr auto operator()(const value_type &v) const -> decltype(!v) { return !v; } }; struct pre_inc_op { template <typename value_type> constexpr auto operator()(value_type &v) const -> decltype(++v) { return v; } }; struct post_inc_op { template <typename value_type> constexpr auto operator()(value_type &v) const -> decltype(v++) { return v++; } }; struct pre_dec_op { template <typename value_type> constexpr auto operator()(value_type &v) const -> decltype(--v) { return v; } }; struct post_dec_op { template <typename value_type> constexpr auto operator()(value_type &v) const -> decltype(v--) { return v--; } }; }; constexpr struct { template <typename T> detail::subscript<T> operator[](const T &t) const { return detail::subscript<T>(t); } template <typename T> detail::apply<T> operator()(const T &t) const { return detail::apply<T>(t); } detail::call operator()() const { return {}; } detail::bnot_op operator~() const { return {}; } detail::lnot_op operator!() const { return {}; } detail::pre_inc_op operator++() const { return {}; } detail::post_inc_op operator++(int) const { return {}; } detail::pre_dec_op operator--() const { return {}; } detail::post_dec_op operator--(int) const { return {}; } } lambda{}; #define def_left_op(op, name)\ namespace detail {\ template <typename L>\ struct left_##name {\ private:\ const L &lhs;\ public:\ left_##name(const L &lhs) : lhs(lhs) {}\ template <typename R>\ constexpr auto operator()(const R & rhs) const -> decltype(lhs op rhs) { return lhs op rhs; };\ };\ };\ template <typename L>\ constexpr detail::left_##name<L> operator op(const L &lhs, const decltype(lambda) &) {\ return detail::left_##name<L>(lhs);\ }; #define def_right_op(op, name)\ namespace detail {\ template <typename R>\ struct right_##name {\ private:\ const R &rhs;\ public:\ right_##name(const R &rhs) : rhs(rhs) {}\ template <typename L>\ constexpr auto operator()(const L & lhs) const -> decltype(lhs op rhs) { return lhs op rhs; };\ };\ };\ template <typename R>\ constexpr detail::right_##name<R> operator op(const decltype(lambda) &, const R &rhs) {\ return detail::right_##name<R>(rhs);\ }; #define def_op(op, name)\ def_left_op(op, name);\ def_right_op(op, name); def_op(==, eq); def_op(!=, neq); def_op(<, lt); def_op(<=, lte); def_op(>, gt); def_op(>=, gte); def_op(&&, land); def_op(||, lor); def_op(+, plus); def_op(-, minus); def_op(*, mult); def_op(/, div); def_op(%, mod); def_op(&, band); def_op(|, bor); def_op(^, bxor); def_op(<<, lshift); def_op(>>, rshift); #undef def_op #undef def_left_op #undef def_right_op #define def_destructive_left_op(op, name)\ namespace detail {\ template <typename L>\ struct left_##name {\ private:\ L &lhs;\ public:\ left_##name(L &lhs) : lhs(lhs) {}\ template <typename R>\ constexpr auto operator()(const R & rhs) const -> decltype(lhs op rhs) { return lhs op rhs; };\ };\ };\ template <typename L>\ constexpr detail::left_##name<L> operator op(L &lhs, const decltype(lambda) &) {\ return detail::left_##name<L>(lhs);\ }; #define def_destructive_right_op(op, name)\ namespace detail {\ template <typename R>\ struct right_##name {\ private:\ const R &rhs;\ public:\ right_##name(const R &rhs) : rhs(rhs) {}\ template <typename L>\ constexpr auto operator()(L & lhs) const -> decltype(lhs op rhs) { return lhs op rhs; };\ };\ };\ template <typename R>\ constexpr detail::right_##name<R> operator op(const decltype(lambda) &, const R &rhs) {\ return detail::right_##name<R>(rhs);\ }; #define def_destructive_op(op, name)\ def_destructive_left_op(op, name);\ def_destructive_right_op(op, name); def_destructive_op(&=, band_eq); def_destructive_op(|=, bor_eq); def_destructive_op(^=, bxor_eq); def_destructive_op(+=, plus_eq); def_destructive_op(-=, miuns_eq); def_destructive_op(*=, mult_eq); def_destructive_op(/=, div_eq); def_destructive_op(%=, mod_eq); def_destructive_op(<<=, lshift_eq); def_destructive_op(>>=, rshift_eq); }; using namespace lambda_symbol; }; using function::lambda_symbol::lambda; }; #define bbb_use_lambda_symbol(sym) decltype(bbb::function::lambda) & sym = bbb::function::lambda; <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: valuemembernode.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-08 04:35:43 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef CONFIGMGR_VALUEMEMBERNODE_HXX_ #define CONFIGMGR_VALUEMEMBERNODE_HXX_ #include "nodeimpl.hxx" #ifndef CONFIGMGR_VALUENODEACCESS_HXX #include "valuenodeaccess.hxx" #endif namespace configmgr { namespace configuration { //----------------------------------------------------------------------------- typedef com::sun::star::uno::Any UnoAny; typedef com::sun::star::uno::Type UnoType; class Name; //----------------------------------------------------------------------------- /// handle class for values that are not nodes themselves, but members of a group class ValueMemberNode { class DeferredImpl; typedef rtl::Reference<DeferredImpl> DeferredImplRef; data::ValueNodeAccess m_aNodeRef; DeferredImplRef m_xDeferredOperation; private: friend class GroupNodeImpl; friend class DeferredGroupNodeImpl; friend class ValueMemberUpdate; /// create a ValueMemberNode for a given node explicit ValueMemberNode(data::ValueNodeAccess const& _aNodeAccess); /// create a deferred ValueMemberNode (xOriginal must not be empty) ValueMemberNode(data::Accessor const& _aAccessor, DeferredImplRef const& _xDeferred); public: ValueMemberNode(ValueMemberNode const& rOriginal); ValueMemberNode& operator=(ValueMemberNode const& rOriginal); ~ValueMemberNode(); /// does this wrap a valid value ? bool isValid() const; /// does this wrap a change bool hasChange() const; /// retrieve the name of the underlying node Name getNodeName() const; /// retrieve the attributes node::Attributes getAttributes() const; /// Does this node assume its default value bool isDefault() const; /// is the default value of this node available bool canGetDefaultValue() const; /// retrieve the current value of this node UnoAny getValue() const; /// retrieve the default value of this node UnoAny getDefaultValue() const; UnoType getValueType() const; }; //------------------------------------------------------------------------- /// handle class for updating values that are members of a group class ValueMemberUpdate { ValueMemberNode m_aMemberNode; view::ViewStrategy * m_pStrategy; private: typedef ValueMemberNode::DeferredImplRef DeferredImplRef; friend class view::ViewStrategy; ValueMemberUpdate(ValueMemberNode const& rOriginal, view::ViewStrategy& _rStrategy) : m_aMemberNode(rOriginal), m_pStrategy(&_rStrategy) {} public: /// does this wrap a valid value ? bool isValid() const { return m_aMemberNode.isValid(); } /// get access to the wrapped data ValueMemberNode getNode() const { return m_aMemberNode; } /// Set this node to a new value void setValue(UnoAny const& aNewValue); /// Set this node to assume its default value void setDefault(); }; //----------------------------------------------------------------------------- } } #endif // CONFIGMGR_GROUPNODEBEHAVIOR_HXX_ <commit_msg>INTEGRATION: CWS configrefactor01 (1.5.84); FILE MERGED 2007/01/12 14:50:49 mmeeks 1.5.84.2: Another big prune of memory::Accessor ... 2007/01/08 20:49:05 mmeeks 1.5.84.1: Issue number: Submitted by: mmeeks Substantial configmgr re-factoring #1 ... + remove endless typedef chains + remove custom allocator & associated complexity + remove Pointer, and 'Address' classes<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: valuemembernode.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: ihi $ $Date: 2007-11-23 14:48:26 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef CONFIGMGR_VALUEMEMBERNODE_HXX_ #define CONFIGMGR_VALUEMEMBERNODE_HXX_ #include "nodeimpl.hxx" #ifndef CONFIGMGR_VALUENODEACCESS_HXX #include "valuenodeaccess.hxx" #endif namespace configmgr { namespace configuration { //----------------------------------------------------------------------------- typedef com::sun::star::uno::Any UnoAny; typedef com::sun::star::uno::Type UnoType; class Name; //----------------------------------------------------------------------------- /// handle class for values that are not nodes themselves, but members of a group class ValueMemberNode { class DeferredImpl; typedef rtl::Reference<DeferredImpl> DeferredImplRef; data::ValueNodeAccess m_aNodeRef; DeferredImplRef m_xDeferredOperation; private: friend class GroupNodeImpl; friend class DeferredGroupNodeImpl; friend class ValueMemberUpdate; /// create a ValueMemberNode for a given node explicit ValueMemberNode(data::ValueNodeAccess const& _aNodeAccess); /// create a deferred ValueMemberNode (xOriginal must not be empty) ValueMemberNode(DeferredImplRef const& _xDeferred); public: ValueMemberNode(ValueMemberNode const& rOriginal); ValueMemberNode& operator=(ValueMemberNode const& rOriginal); ~ValueMemberNode(); /// does this wrap a valid value ? bool isValid() const; /// does this wrap a change bool hasChange() const; /// retrieve the name of the underlying node Name getNodeName() const; /// retrieve the attributes node::Attributes getAttributes() const; /// Does this node assume its default value bool isDefault() const; /// is the default value of this node available bool canGetDefaultValue() const; /// retrieve the current value of this node UnoAny getValue() const; /// retrieve the default value of this node UnoAny getDefaultValue() const; UnoType getValueType() const; }; //------------------------------------------------------------------------- /// handle class for updating values that are members of a group class ValueMemberUpdate { ValueMemberNode m_aMemberNode; view::ViewStrategy * m_pStrategy; private: typedef ValueMemberNode::DeferredImplRef DeferredImplRef; friend class view::ViewStrategy; ValueMemberUpdate(ValueMemberNode const& rOriginal, view::ViewStrategy& _rStrategy) : m_aMemberNode(rOriginal), m_pStrategy(&_rStrategy) {} public: /// does this wrap a valid value ? bool isValid() const { return m_aMemberNode.isValid(); } /// get access to the wrapped data ValueMemberNode getNode() const { return m_aMemberNode; } /// Set this node to a new value void setValue(UnoAny const& aNewValue); /// Set this node to assume its default value void setDefault(); }; //----------------------------------------------------------------------------- } } #endif // CONFIGMGR_GROUPNODEBEHAVIOR_HXX_ <|endoftext|>
<commit_before><commit_msg>Fix GCC build bustage.<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: valuemembernode.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: ihi $ $Date: 2007-11-23 14:48:26 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef CONFIGMGR_VALUEMEMBERNODE_HXX_ #define CONFIGMGR_VALUEMEMBERNODE_HXX_ #include "nodeimpl.hxx" #ifndef CONFIGMGR_VALUENODEACCESS_HXX #include "valuenodeaccess.hxx" #endif namespace configmgr { namespace configuration { //----------------------------------------------------------------------------- typedef com::sun::star::uno::Any UnoAny; typedef com::sun::star::uno::Type UnoType; class Name; //----------------------------------------------------------------------------- /// handle class for values that are not nodes themselves, but members of a group class ValueMemberNode { class DeferredImpl; typedef rtl::Reference<DeferredImpl> DeferredImplRef; data::ValueNodeAccess m_aNodeRef; DeferredImplRef m_xDeferredOperation; private: friend class GroupNodeImpl; friend class DeferredGroupNodeImpl; friend class ValueMemberUpdate; /// create a ValueMemberNode for a given node explicit ValueMemberNode(data::ValueNodeAccess const& _aNodeAccess); /// create a deferred ValueMemberNode (xOriginal must not be empty) ValueMemberNode(DeferredImplRef const& _xDeferred); public: ValueMemberNode(ValueMemberNode const& rOriginal); ValueMemberNode& operator=(ValueMemberNode const& rOriginal); ~ValueMemberNode(); /// does this wrap a valid value ? bool isValid() const; /// does this wrap a change bool hasChange() const; /// retrieve the name of the underlying node Name getNodeName() const; /// retrieve the attributes node::Attributes getAttributes() const; /// Does this node assume its default value bool isDefault() const; /// is the default value of this node available bool canGetDefaultValue() const; /// retrieve the current value of this node UnoAny getValue() const; /// retrieve the default value of this node UnoAny getDefaultValue() const; UnoType getValueType() const; }; //------------------------------------------------------------------------- /// handle class for updating values that are members of a group class ValueMemberUpdate { ValueMemberNode m_aMemberNode; view::ViewStrategy * m_pStrategy; private: typedef ValueMemberNode::DeferredImplRef DeferredImplRef; friend class view::ViewStrategy; ValueMemberUpdate(ValueMemberNode const& rOriginal, view::ViewStrategy& _rStrategy) : m_aMemberNode(rOriginal), m_pStrategy(&_rStrategy) {} public: /// does this wrap a valid value ? bool isValid() const { return m_aMemberNode.isValid(); } /// get access to the wrapped data ValueMemberNode getNode() const { return m_aMemberNode; } /// Set this node to a new value void setValue(UnoAny const& aNewValue); /// Set this node to assume its default value void setDefault(); }; //----------------------------------------------------------------------------- } } #endif // CONFIGMGR_GROUPNODEBEHAVIOR_HXX_ <commit_msg>INTEGRATION: CWS changefileheader (1.6.16); FILE MERGED 2008/04/01 12:27:39 thb 1.6.16.2: #i85898# Stripping all external header guards 2008/03/31 12:22:57 rt 1.6.16.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: valuemembernode.hxx,v $ * $Revision: 1.7 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef CONFIGMGR_VALUEMEMBERNODE_HXX_ #define CONFIGMGR_VALUEMEMBERNODE_HXX_ #include "nodeimpl.hxx" #include "valuenodeaccess.hxx" namespace configmgr { namespace configuration { //----------------------------------------------------------------------------- typedef com::sun::star::uno::Any UnoAny; typedef com::sun::star::uno::Type UnoType; class Name; //----------------------------------------------------------------------------- /// handle class for values that are not nodes themselves, but members of a group class ValueMemberNode { class DeferredImpl; typedef rtl::Reference<DeferredImpl> DeferredImplRef; data::ValueNodeAccess m_aNodeRef; DeferredImplRef m_xDeferredOperation; private: friend class GroupNodeImpl; friend class DeferredGroupNodeImpl; friend class ValueMemberUpdate; /// create a ValueMemberNode for a given node explicit ValueMemberNode(data::ValueNodeAccess const& _aNodeAccess); /// create a deferred ValueMemberNode (xOriginal must not be empty) ValueMemberNode(DeferredImplRef const& _xDeferred); public: ValueMemberNode(ValueMemberNode const& rOriginal); ValueMemberNode& operator=(ValueMemberNode const& rOriginal); ~ValueMemberNode(); /// does this wrap a valid value ? bool isValid() const; /// does this wrap a change bool hasChange() const; /// retrieve the name of the underlying node Name getNodeName() const; /// retrieve the attributes node::Attributes getAttributes() const; /// Does this node assume its default value bool isDefault() const; /// is the default value of this node available bool canGetDefaultValue() const; /// retrieve the current value of this node UnoAny getValue() const; /// retrieve the default value of this node UnoAny getDefaultValue() const; UnoType getValueType() const; }; //------------------------------------------------------------------------- /// handle class for updating values that are members of a group class ValueMemberUpdate { ValueMemberNode m_aMemberNode; view::ViewStrategy * m_pStrategy; private: typedef ValueMemberNode::DeferredImplRef DeferredImplRef; friend class view::ViewStrategy; ValueMemberUpdate(ValueMemberNode const& rOriginal, view::ViewStrategy& _rStrategy) : m_aMemberNode(rOriginal), m_pStrategy(&_rStrategy) {} public: /// does this wrap a valid value ? bool isValid() const { return m_aMemberNode.isValid(); } /// get access to the wrapped data ValueMemberNode getNode() const { return m_aMemberNode; } /// Set this node to a new value void setValue(UnoAny const& aNewValue); /// Set this node to assume its default value void setDefault(); }; //----------------------------------------------------------------------------- } } #endif // CONFIGMGR_GROUPNODEBEHAVIOR_HXX_ <|endoftext|>
<commit_before>/*********************************************************************** row.cpp - Implements the Row class. Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by MySQL AB, and (c) 2004, 2005 by Educational Technology Resources, Inc. Others may also hold copyrights on code in this file. See the CREDITS file in the top directory of the distribution for details. This file is part of MySQL++. MySQL++ 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. MySQL++ 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 MySQL++; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include "row.h" #include "result.h" #include "exceptions.h" namespace mysqlpp { Row::Row(const MYSQL_ROW& d, const ResUse* r, unsigned long* jj, bool te) : OptionalExceptions(te), res_(r), initialized_(false) { if (!d || !r) { if (throw_exceptions()) { throw BadQuery("ROW or RES is NULL"); } else { return; } } data_.clear(); is_nulls_.clear(); initialized_ = true; for (unsigned int i = 0; i < size(); i++) { data_.insert(data_.end(), (d[i] ? std::string(d[i], jj[i]) : std::string("NULL"))); is_nulls_.insert(is_nulls_.end(), d[i] ? false : true); } } Row::~Row() { data_.clear(); is_nulls_.clear(); initialized_ = false; } Row::size_type Row::size() const { return res_->num_fields(); } const ColData Row::at(size_type i) const { if (initialized_) { const std::string& s = data_.at(i); return ColData(s.c_str(), s.length(), res_->types(i), is_nulls_[i]); } else { if (throw_exceptions()) throw std::out_of_range("Row not initialized"); else return ColData(); } } const ColData Row::operator [](const char* field) const { size_type si = res_->field_num(std::string(field)); if (si < size()) { return at(si); } else { throw BadFieldName(field); } } value_list_ba<FieldNames, do_nothing_type0> Row::field_list(const char* d) const { return value_list_ba<FieldNames, do_nothing_type0> (parent().names(), d, do_nothing); } template <class Manip> value_list_ba<FieldNames, Manip> Row::field_list(const char *d, Manip m) const { return value_list_ba<FieldNames, Manip>(parent().names(), d, m); } template <class Manip> value_list_b<FieldNames, Manip> Row::field_list(const char *d, Manip m, const std::vector<bool>& vb) const { return value_list_b<FieldNames, Manip>(parent().names(), vb, d, m); } value_list_b<FieldNames, quote_type0> Row::field_list(const char* d, const std::vector<bool>& vb) const { return value_list_b<FieldNames, quote_type0>(parent().names(), vb, d, quote); } value_list_b<FieldNames, quote_type0> Row::field_list(const std::vector<bool>& vb) const { return value_list_b<FieldNames, quote_type0>(parent().names(), vb, ",", quote); } template <class Manip> value_list_b<FieldNames, Manip> Row::field_list(const char* d, Manip m, bool t0, bool t1, bool t2, bool t3, bool t4, bool t5, bool t6, bool t7, bool t8, bool t9, bool ta, bool tb, bool tc) const { std::vector<bool> vb; create_vector(parent().names().size(), vb, t0, t1, t2, t3, t4, t5, t6, t7, t8, t9, ta, tb, tc); return value_list_b<FieldNames, Manip>(parent().names(), vb, d, m); } value_list_b<FieldNames, quote_type0> Row::field_list(const char *d, bool t0, bool t1, bool t2, bool t3, bool t4, bool t5, bool t6, bool t7, bool t8, bool t9, bool ta, bool tb, bool tc) const { std::vector<bool> vb; create_vector(parent().names().size(), vb, t0, t1, t2, t3, t4, t5, t6, t7, t8, t9, ta, tb, tc); return value_list_b<FieldNames, quote_type0>(parent().names(), vb, d, quote); } value_list_b<FieldNames, quote_type0> Row::field_list(bool t0, bool t1, bool t2, bool t3, bool t4, bool t5, bool t6, bool t7, bool t8, bool t9, bool ta, bool tb, bool tc) const { std::vector<bool> vb; create_vector(parent().names().size(), vb, t0, t1, t2, t3, t4, t5, t6, t7, t8, t9, ta, tb, tc); return value_list_b<FieldNames, quote_type0>(parent().names(), vb, ",", quote); } equal_list_ba<FieldNames, Row, quote_type0> Row::equal_list(const char* d, const char* e) const { return equal_list_ba<FieldNames, Row, quote_type0>( parent().names(), *this, d, e, quote); } template <class Manip> equal_list_ba<FieldNames, Row, Manip> Row::equal_list(const char* d, const char* e, Manip m) const { return equal_list_ba<FieldNames, Row, Manip>( parent().names(), *this, d, e, m); } } // end namespace mysqlpp <commit_msg>Minor speed optimizations in the Row() ctor that copies data from a MYSQL_ROW structure, and in Row::size(). Patch by Korolyov Ilya <breeze@begun.ru>.<commit_after>/*********************************************************************** row.cpp - Implements the Row class. Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by MySQL AB, and (c) 2004, 2005 by Educational Technology Resources, Inc. Others may also hold copyrights on code in this file. See the CREDITS file in the top directory of the distribution for details. This file is part of MySQL++. MySQL++ 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. MySQL++ 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 MySQL++; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include "row.h" #include "result.h" #include "exceptions.h" namespace mysqlpp { Row::Row(const MYSQL_ROW& d, const ResUse* r, unsigned long* jj, bool te) : OptionalExceptions(te), res_(r), initialized_(false) { if (!d || !r) { if (throw_exceptions()) { throw BadQuery("ROW or RES is NULL"); } else { return; } } data_.clear(); is_nulls_.clear(); initialized_ = true; size_type num_fields = size(); for (size_type i = 0; i < num_fields; ++i) { data_.insert(data_.end(), (d[i] ? std::string(d[i], jj[i]) : std::string("NULL"))); is_nulls_.insert(is_nulls_.end(), d[i] ? false : true); } } Row::~Row() { data_.clear(); is_nulls_.clear(); initialized_ = false; } Row::size_type Row::size() const { return data_.size(); } const ColData Row::at(size_type i) const { if (initialized_) { const std::string& s = data_.at(i); return ColData(s.c_str(), s.length(), res_->types(i), is_nulls_[i]); } else { if (throw_exceptions()) throw std::out_of_range("Row not initialized"); else return ColData(); } } const ColData Row::operator [](const char* field) const { size_type si = res_->field_num(std::string(field)); if (si < size()) { return at(si); } else { throw BadFieldName(field); } } value_list_ba<FieldNames, do_nothing_type0> Row::field_list(const char* d) const { return value_list_ba<FieldNames, do_nothing_type0> (parent().names(), d, do_nothing); } template <class Manip> value_list_ba<FieldNames, Manip> Row::field_list(const char *d, Manip m) const { return value_list_ba<FieldNames, Manip>(parent().names(), d, m); } template <class Manip> value_list_b<FieldNames, Manip> Row::field_list(const char *d, Manip m, const std::vector<bool>& vb) const { return value_list_b<FieldNames, Manip>(parent().names(), vb, d, m); } value_list_b<FieldNames, quote_type0> Row::field_list(const char* d, const std::vector<bool>& vb) const { return value_list_b<FieldNames, quote_type0>(parent().names(), vb, d, quote); } value_list_b<FieldNames, quote_type0> Row::field_list(const std::vector<bool>& vb) const { return value_list_b<FieldNames, quote_type0>(parent().names(), vb, ",", quote); } template <class Manip> value_list_b<FieldNames, Manip> Row::field_list(const char* d, Manip m, bool t0, bool t1, bool t2, bool t3, bool t4, bool t5, bool t6, bool t7, bool t8, bool t9, bool ta, bool tb, bool tc) const { std::vector<bool> vb; create_vector(parent().names().size(), vb, t0, t1, t2, t3, t4, t5, t6, t7, t8, t9, ta, tb, tc); return value_list_b<FieldNames, Manip>(parent().names(), vb, d, m); } value_list_b<FieldNames, quote_type0> Row::field_list(const char *d, bool t0, bool t1, bool t2, bool t3, bool t4, bool t5, bool t6, bool t7, bool t8, bool t9, bool ta, bool tb, bool tc) const { std::vector<bool> vb; create_vector(parent().names().size(), vb, t0, t1, t2, t3, t4, t5, t6, t7, t8, t9, ta, tb, tc); return value_list_b<FieldNames, quote_type0>(parent().names(), vb, d, quote); } value_list_b<FieldNames, quote_type0> Row::field_list(bool t0, bool t1, bool t2, bool t3, bool t4, bool t5, bool t6, bool t7, bool t8, bool t9, bool ta, bool tb, bool tc) const { std::vector<bool> vb; create_vector(parent().names().size(), vb, t0, t1, t2, t3, t4, t5, t6, t7, t8, t9, ta, tb, tc); return value_list_b<FieldNames, quote_type0>(parent().names(), vb, ",", quote); } equal_list_ba<FieldNames, Row, quote_type0> Row::equal_list(const char* d, const char* e) const { return equal_list_ba<FieldNames, Row, quote_type0>( parent().names(), *this, d, e, quote); } template <class Manip> equal_list_ba<FieldNames, Row, Manip> Row::equal_list(const char* d, const char* e, Manip m) const { return equal_list_ba<FieldNames, Row, Manip>( parent().names(), *this, d, e, m); } } // end namespace mysqlpp <|endoftext|>
<commit_before>#include "util.h" float *load_weights(string filename, int N) { float *ret = (float *) malloc(N * sizeof(float)); ifstream file(filename); float x; for (int i = 0; i < N; i++) { file >> x; cout << x << endl; ret[i] = x; } } float *load_weights_cuda(string filename, int N) { float *h_weights = load_weights(filename, N); float *d_weights; cudaMalloc(&d_weights, N * sizeof(float)); cudaMemcpy(d_weights, h_weights, N * sizeof(float), cudaMemcpyHostToDevice); return d_weights; } <commit_msg>easy util fixes<commit_after>#include "util.h" float *load_weights(string filename, int N) { float *ret = (float *) malloc(N * sizeof(float)); ifstream file(filename); float x; for (int i = 0; i < N; i++) { file >> x; cout << x << endl; ret[i] = x; } return ret; } float *load_weights_cuda(string filename, int N) { float *h_weights = load_weights(filename, N); float *d_weights; cudaMalloc(&d_weights, N * sizeof(float)); cudaMemcpy(d_weights, h_weights, N * sizeof(float), cudaMemcpyHostToDevice); free(h_weights); return d_weights; } <|endoftext|>
<commit_before>/* // Copyright (c) 2015 Pierre Guillot. // For information on usage and redistribution, and for a DISCLAIMER OF ALL // WARRANTIES, see the file, "LICENSE.txt," in this distribution. */ #ifndef XPD_ATOM_HPP #define XPD_ATOM_HPP #include "xpd_symbol.hpp" namespace xpd { typedef float float_t; // ==================================================================================== // // ATOM // // ==================================================================================== // //! @brief An atom is simple variant object that can be a float or a symbol. //! @details An atom is used to communicate with the objects and patches within the xpd //! environment. The interface mostly use a std::vector of atom. class atom { public: //! @brief The available type of an atom. //! @details For the moment it can be null_t, float_t or symbol_t #if (__cplusplus <= 199711L) enum type_t #else enum class type_t #endif { null_t, //!< @brief The atom is null or undefined. float_t, //!< @brief The atom owns a float value. symbol_t //!< @brief The atom owns a symbol. }; //! @brief The default constructor. //! @details Creates an null atom. inline xpd_constexpr atom() xpd_noexcept : m_type(type_t::null_t), m_word(0.f) {} //! @brief The float constructor. //! @details Creates an float atom. inline xpd_constexpr atom(xpd::float_t value) xpd_noexcept : m_type(type_t::float_t), m_word(value) {} //! @brief The symbol constructor. //! @details Creates an symbol atom. inline xpd_constexpr atom(symbol& symbol) xpd_noexcept : m_type(type_t::symbol_t), m_word(symbol) {} //! @brief The copy constructor. //! @details Creates an copy of another atom. inline xpd_constexpr atom(atom& other) xpd_noexcept : m_type(other.m_type), m_word(m_type == type_t::float_t ? other.m_word.w_float : other.m_word.w_symbol) {} //! @brief The float assignment. //! @details Sets the atom to a new float value. //! @param value The float value. //! @return The reference of the atom. inline atom& operator=(xpd::float_t value) xpd_noexcept {m_type = type_t::float_t; m_word.w_float = value; return *this;} //! @brief The symbol assignment. //! @details Sets the atom to a new symbol. //! @param symbol The symbol value. //! @return The reference of the atom. inline atom& operator=(symbol& symbol) xpd_noexcept {m_type = type_t::symbol_t; m_word.w_symbol = symbol; return *this;} //! @brief The copy assignment. //! @details Returns a copy of another atom. //! @param other The other atom. //! @return The reference of the atom. inline atom& operator=(atom& other) {m_type = other.m_type; m_type == type_t::float_t ? m_word.w_float = other.m_word.w_float : m_word.w_symbol = other.m_word.w_symbol; return *this;} //! @brief Gets the float value of the atom. //! @details Returns the float value of the atom if the type if float_t otherwise the //! behavior is undefined. //! @return The float value of the atom. inline xpd_constexpr operator xpd::float_t() const xpd_noexcept {return m_word.w_float;} //! @brief Gets the symbol of the atom. //! @details Returns the symbol of the atom if the type if symbol_t otherwise the //! behavior is undefined. //! @return The symbol of the atom. inline xpd_constexpr operator symbol() const xpd_noexcept {return m_word.w_symbol;} //! @brief Gets the type of the atom. //! @details Returns the current type of the atom. //! @return The type of the atom. inline xpd_constexpr type_t type() const xpd_noexcept {return m_type;} private: #if (__cplusplus <= 199711L) struct a_word { xpd::float_t w_float; symbol w_symbol; inline xpd_constexpr a_word() xpd_noexcept : w_float(0.f) {}; inline xpd_constexpr a_word(const xpd::float_t value) xpd_noexcept : w_float(value) {} inline xpd_constexpr a_word(symbol& symbol) xpd_noexcept : w_symbol(symbol) {} }; #else union a_word { float_t w_float; symbol w_symbol; inline xpd_constexpr a_word() xpd_noexcept : w_float(0.f) {}; inline xpd_constexpr a_word(const float_t value) xpd_noexcept : w_float(value) {} inline xpd_constexpr a_word(symbol& symbol) xpd_noexcept : w_symbol(symbol) {} }; #endif type_t m_type; a_word m_word; }; } #endif // XPD_ATOM_HPP <commit_msg>check atom mac<commit_after>/* // Copyright (c) 2015 Pierre Guillot. // For information on usage and redistribution, and for a DISCLAIMER OF ALL // WARRANTIES, see the file, "LICENSE.txt," in this distribution. */ #ifndef XPD_ATOM_HPP #define XPD_ATOM_HPP #include "xpd_symbol.hpp" namespace xpd { typedef float float_t; // ==================================================================================== // // ATOM // // ==================================================================================== // //! @brief An atom is simple variant object that can be a float or a symbol. //! @details An atom is used to communicate with the objects and patches within the xpd //! environment. The interface mostly use a std::vector of atom. class atom { public: //! @brief The available type of an atom. //! @details For the moment it can be null_t, float_t or symbol_t #if (__cplusplus <= 199711L) enum type_t #else enum class type_t #endif { null_t, //!< @brief The atom is null or undefined. float_t, //!< @brief The atom owns a float value. symbol_t //!< @brief The atom owns a symbol. }; //! @brief The default constructor. //! @details Creates an null atom. inline xpd_constexpr atom() xpd_noexcept : m_type(atom::type_t::null_t), m_word(0.f) {} //! @brief The float constructor. //! @details Creates an float atom. inline xpd_constexpr atom(xpd::float_t value) xpd_noexcept : m_type(atom::type_t::float_t), m_word(value) {} //! @brief The symbol constructor. //! @details Creates an symbol atom. inline xpd_constexpr atom(symbol& symbol) xpd_noexcept : m_type(atom::type_t::symbol_t), m_word(symbol) {} //! @brief The copy constructor. //! @details Creates an copy of another atom. inline xpd_constexpr atom(atom& other) xpd_noexcept : m_type(other.m_type), m_word(m_type == atom::type_t::float_t ? other.m_word.w_float : other.m_word.w_symbol) {} //! @brief The float assignment. //! @details Sets the atom to a new float value. //! @param value The float value. //! @return The reference of the atom. inline atom& operator=(xpd::float_t value) xpd_noexcept {m_type = atom::type_t::float_t; m_word.w_float = value; return *this;} //! @brief The symbol assignment. //! @details Sets the atom to a new symbol. //! @param symbol The symbol value. //! @return The reference of the atom. inline atom& operator=(symbol& symbol) xpd_noexcept {m_type = atom::type_t::symbol_t; m_word.w_symbol = symbol; return *this;} //! @brief The copy assignment. //! @details Returns a copy of another atom. //! @param other The other atom. //! @return The reference of the atom. inline atom& operator=(atom& other) {m_type = other.m_type; m_type == atom::type_t::float_t ? m_word.w_float = other.m_word.w_float : m_word.w_symbol = other.m_word.w_symbol; return *this;} //! @brief Gets the float value of the atom. //! @details Returns the float value of the atom if the type if float_t otherwise the //! behavior is undefined. //! @return The float value of the atom. inline xpd_constexpr operator xpd::float_t() const xpd_noexcept {return m_word.w_float;} //! @brief Gets the symbol of the atom. //! @details Returns the symbol of the atom if the type if symbol_t otherwise the //! behavior is undefined. //! @return The symbol of the atom. inline xpd_constexpr operator symbol() const xpd_noexcept {return m_word.w_symbol;} //! @brief Gets the type of the atom. //! @details Returns the current type of the atom. //! @return The type of the atom. inline xpd_constexpr atom::type_t type() const xpd_noexcept {return m_type;} private: #if (__cplusplus <= 199711L) struct a_word { xpd::float_t w_float; symbol w_symbol; inline xpd_constexpr a_word() xpd_noexcept : w_float(0.f) {}; inline xpd_constexpr a_word(const xpd::float_t value) xpd_noexcept : w_float(value) {} inline xpd_constexpr a_word(symbol& symbol) xpd_noexcept : w_symbol(symbol) {} }; #else union a_word { float_t w_float; symbol w_symbol; inline xpd_constexpr a_word() xpd_noexcept : w_float(0.f) {}; inline xpd_constexpr a_word(const float_t value) xpd_noexcept : w_float(value) {} inline xpd_constexpr a_word(symbol& symbol) xpd_noexcept : w_symbol(symbol) {} }; #endif atom::type_t m_type; a_word m_word; }; } #endif // XPD_ATOM_HPP <|endoftext|>