text
stringlengths 54
60.6k
|
|---|
<commit_before>#include "CopyOperation.h"
#include <boost/filesystem.hpp>
#include <sstream>
using file_system::operations::CopyOperation;
using file_system::Path;
CopyOperation::CopyOperation()
{
}
CopyOperation::~CopyOperation()
{
}
void CopyOperation::copy(const Path& sourceFile, const Path& destinationFolder)
{
boost::filesystem::path sourceFilePath(sourceFile.stringValue());
boost::filesystem::path destinationFilePath(destinationFolder.stringValue());
destinationFilePath.append(sourceFilePath.filename().c_str());
boost::filesystem::copy_file(sourceFilePath, destinationFilePath);
}
<commit_msg>make it work o nlinux<commit_after>#include "CopyOperation.h"
#include <boost/filesystem.hpp>
#include <sstream>
using file_system::operations::CopyOperation;
using file_system::Path;
CopyOperation::CopyOperation()
{
}
CopyOperation::~CopyOperation()
{
}
void CopyOperation::copy(const Path& sourceFile, const Path& destinationFolder)
{
boost::filesystem::path sourceFilePath(sourceFile.stringValue());
boost::filesystem::path destinationFilePath(destinationFolder.stringValue());
destinationFilePath /= sourceFilePath.filename();
boost::filesystem::copy_file(sourceFilePath, destinationFilePath);
}
<|endoftext|>
|
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved
*/
#include "../../StroikaPreComp.h"
#if qHasFeature_OpenSSL
#include <openssl/evp.h>
#if OPENSSL_VERSION_MAJOR >= 3
#include <openssl/provider.h>
#endif
#endif
#include "../../Debug/Assertions.h"
#include "../../Execution/Exceptions.h"
#include "LibraryContext.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Cryptography;
using namespace Stroika::Foundation::Cryptography::OpenSSL;
#if qHasFeature_OpenSSL && defined(_MSC_VER)
// Use #pragma comment lib instead of explicit entry in the lib entry of the project file
#if OPENSSL_VERSION_NUMBER < 0x1010000fL
#pragma comment(lib, "libeay32.lib")
#pragma comment(lib, "ssleay32.lib")
#else
#pragma comment(lib, "libcrypto.lib")
#pragma comment(lib, "libssl.lib")
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "crypt32.lib")
#endif
#endif
#if qHasFeature_OpenSSL
namespace {
void AccumulateIntoSetOfCipherNames_ (const ::EVP_CIPHER* ciph, Set<String>* ciphers)
{
RequireNotNull (ciphers);
if (ciph != nullptr) {
#if OPENSSL_VERSION_MAJOR >= 3
DbgTrace (L"cipher: %p (name: %s), provider: %p", ciph, CipherAlgorithm{ciph}.pName ().c_str (), ::EVP_CIPHER_get0_provider (ciph));
#else
DbgTrace (L"cipher: %p (name: %s)", ciph, CipherAlgorithm{ciph}.pName ().c_str ());
#endif
#if OPENSSL_VERSION_MAJOR >= 3
if (auto provider = ::EVP_CIPHER_get0_provider (ciph)) {
DbgTrace ("providername = %s", ::OSSL_PROVIDER_get0_name (provider));
}
#endif
#if 0
int flags = ::EVP_CIPHER_flags (ciph);
DbgTrace ("flags=%x", flags);
#endif
ciphers->Add (CipherAlgorithm{ciph}.pName ());
}
};
void AccumulateIntoSetOfDigestNames_ (const ::EVP_MD* digest, Set<String>* digestNames)
{
RequireNotNull (digestNames);
if (digest != nullptr) {
#if OPENSSL_VERSION_MAJOR >= 3
DbgTrace (L"digest: %p (name: %s), provider: %p", digest, DigestAlgorithm{digest}.pName ().c_str (), ::EVP_MD_get0_provider (digest));
#else
DbgTrace (L"digest: %p (name: %s)", digest, DigestAlgorithm{digest}.pName ().c_str ());
#endif
#if OPENSSL_VERSION_MAJOR >= 3
if (auto provider = ::EVP_MD_get0_provider (digest)) {
DbgTrace ("providername = %s", ::OSSL_PROVIDER_get0_name (provider));
}
#endif
digestNames->Add (DigestAlgorithm{digest}.pName ());
}
};
}
/*
********************************************************************************
******************* Cryptography::OpenSSL::LibraryContext **********************
********************************************************************************
*/
#if qCompiler_cpp17InlineStaticMemberOfClassDoubleDeleteAtExit_Buggy
LibraryContext LibraryContext::sDefault;
#endif
LibraryContext::LibraryContext ()
: pAvailableCipherAlgorithms{
[qStroika_Foundation_Common_Property_ExtraCaptureStuff] ([[maybe_unused]] const auto* property) -> Set<CipherAlgorithm> {
const LibraryContext* thisObj = qStroika_Foundation_Common_Property_OuterObjPtr (property, &LibraryContext::pAvailableCipherAlgorithms);
shared_lock<const AssertExternallySynchronizedLock> critSec{*thisObj};
Set<String> cipherNames;
#if OPENSSL_VERSION_MAJOR >= 3
::EVP_CIPHER_do_all_provided (
nullptr,
[] (::EVP_CIPHER* ciph, void* arg) { AccumulateIntoSetOfCipherNames_ (ciph, reinterpret_cast<Set<String>*> (arg)); },
&cipherNames);
#else
::EVP_CIPHER_do_all_sorted (
#if qCompilerAndStdLib_maybe_unused_in_lambda_ignored_Buggy
[] (const ::EVP_CIPHER* ciph, const char*, const char*, void* arg) { AccumulateIntoSetOfCipherNames_ (ciph, reinterpret_cast<Set<String>*> (arg)); },
#else
[] (const ::EVP_CIPHER* ciph, [[maybe_unused]] const char* from, [[maybe_unused]] const char* to, void* arg) { AccumulateIntoSetOfCipherNames_ (ciph, reinterpret_cast<Set<String>*> (arg)); },
#endif
&cipherNames);
#endif
DbgTrace (L"Found pAvailableCipherAlgorithms-FIRST-PASS (cnt=%d): %s", cipherNames.size (), Characters::ToString (cipherNames).c_str ());
Set<CipherAlgorithm> results{cipherNames.Select<CipherAlgorithm> ([] (const String& n) -> optional<CipherAlgorithm> { return OpenSSL::CipherAlgorithm::GetByNameQuietly (n); })};
DbgTrace (L"Found pAvailableCipherAlgorithms (cnt=%d): %s", results.size (), Characters::ToString (results).c_str ());
return results;
}}
, pStandardCipherAlgorithms{[qStroika_Foundation_Common_Property_ExtraCaptureStuff] ([[maybe_unused]] const auto* property) -> Set<CipherAlgorithm> {
const LibraryContext* thisObj = qStroika_Foundation_Common_Property_OuterObjPtr (property, &LibraryContext::pStandardCipherAlgorithms);
shared_lock<const AssertExternallySynchronizedLock> critSec{*thisObj};
Set<CipherAlgorithm> results;
results += CipherAlgorithms::kAES_128_CBC;
results += CipherAlgorithms::kAES_128_ECB;
results += CipherAlgorithms::kAES_128_OFB;
results += CipherAlgorithms::kAES_128_CFB1;
results += CipherAlgorithms::kAES_128_CFB8;
results += CipherAlgorithms::kAES_128_CFB128;
results += CipherAlgorithms::kAES_192_CBC;
results += CipherAlgorithms::kAES_192_ECB;
results += CipherAlgorithms::kAES_192_OFB;
results += CipherAlgorithms::kAES_192_CFB1;
results += CipherAlgorithms::kAES_192_CFB8;
results += CipherAlgorithms::kAES_192_CFB128;
results += CipherAlgorithms::kAES_256_CBC;
results += CipherAlgorithms::kAES_256_ECB;
results += CipherAlgorithms::kAES_256_OFB;
results += CipherAlgorithms::kAES_256_CFB1;
results += CipherAlgorithms::kAES_256_CFB8;
results += CipherAlgorithms::kAES_256_CFB128;
/*
* @todo mark these below as deprecated...??? in openssl3?
*/
#if OPENSSL_VERSION_MAJOR < 3
results += CipherAlgorithms::kBlowfish_CBC;
results += CipherAlgorithms::kBlowfish_ECB;
results += CipherAlgorithms::kBlowfish_CFB;
results += CipherAlgorithms::kBlowfish_OFB;
results += CipherAlgorithms::kBlowfish;
results += CipherAlgorithms::kRC2_CBC;
results += CipherAlgorithms::kRC2_ECB;
results += CipherAlgorithms::kRC2_CFB;
results += CipherAlgorithms::kRC2_OFB;
results += CipherAlgorithms::kRC4;
#endif
return results;
}}
, pAvailableDigestAlgorithms{[qStroika_Foundation_Common_Property_ExtraCaptureStuff] ([[maybe_unused]] const auto* property) -> Set<DigestAlgorithm> {
const LibraryContext* thisObj = qStroika_Foundation_Common_Property_OuterObjPtr (property, &LibraryContext::pAvailableDigestAlgorithms);
shared_lock<const AssertExternallySynchronizedLock> critSec{*thisObj};
Set<String> digestNames;
#if OPENSSL_VERSION_MAJOR >= 3
::EVP_MD_do_all_provided (
nullptr,
[] (::EVP_MD* md, void* arg) { AccumulateIntoSetOfDigestNames_ (md, reinterpret_cast<Set<String>*> (arg)); },
&digestNames);
#else
::EVP_MD_do_all_sorted (
#if qCompilerAndStdLib_maybe_unused_in_lambda_ignored_Buggy
[] (const ::EVP_MD* md, const char*, const char*, void* arg) { AccumulateIntoSetOfDigestNames_ (md, reinterpret_cast<Set<String>*> (arg)); },
#else
[] (const ::EVP_MD* md, [[maybe_unused]] const char* from, [[maybe_unused]] const char* to, void* arg) { AccumulateIntoSetOfDigestNames_ (md, reinterpret_cast<Set<String>*> (arg)); },
#endif
&digestNames);
#endif
DbgTrace (L"Found pAvailableDigestAlgorithms-FIRST-PASS (cnt=%d): %s", digestNames.size (), Characters::ToString (digestNames).c_str ());
Set<DigestAlgorithm> results{digestNames.Select<DigestAlgorithm> ([] (const String& n) -> optional<DigestAlgorithm> { return OpenSSL::DigestAlgorithm::GetByNameQuietly (n); })};
DbgTrace (L"Found pAvailableDigestAlgorithms (cnt=%d): %s", results.size (), Characters::ToString (results).c_str ());
return results;
}}
, pStandardDigestAlgorithms{[qStroika_Foundation_Common_Property_ExtraCaptureStuff] ([[maybe_unused]] const auto* property) -> Set<DigestAlgorithm> {
const LibraryContext* thisObj = qStroika_Foundation_Common_Property_OuterObjPtr (property, &LibraryContext::pStandardDigestAlgorithms);
shared_lock<const AssertExternallySynchronizedLock> critSec{*thisObj};
Set<DigestAlgorithm> results;
results += DigestAlgorithms::kMD5;
results += DigestAlgorithms::kSHA1;
results += DigestAlgorithms::kSHA224;
results += DigestAlgorithms::kSHA256;
results += DigestAlgorithms::kSHA384;
results += DigestAlgorithms::kSHA512;
return results;
}}
{
LoadProvider (kDefaultProvider);
}
LibraryContext ::~LibraryContext ()
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
#if OPENSSL_VERSION_MAJOR >= 3
for (auto i : fLoadedProviders_) {
Verify (::OSSL_PROVIDER_unload (i.fValue.first) == 1);
}
#endif
}
void LibraryContext::LoadProvider ([[maybe_unused]] const String& providerName)
{
Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"OpenSSL::LibraryContext::LoadProvider", L"%s", providerName.c_str ())};
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
#if OPENSSL_VERSION_MAJOR >= 3
if (auto l = fLoadedProviders_.Lookup (providerName)) {
l->second++;
fLoadedProviders_.Add (providerName, *l);
}
else {
OSSL_PROVIDER* p = ::OSSL_PROVIDER_load (nullptr, providerName.AsNarrowSDKString ().c_str ());
static const Execution::RuntimeErrorException kErr_{L"No such SSL provider"sv};
Execution::ThrowIfNull (p, kErr_);
fLoadedProviders_.Add (providerName, {p, 1});
DbgTrace (L"real load");
}
#else
Require (providerName == kDefaultProvider or providerName == kLegacyProvider);
#endif
}
void LibraryContext ::UnLoadProvider ([[maybe_unused]] const String& providerName)
{
Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"OpenSSL::LibraryContext::UnLoadProvider", L"%s", providerName.c_str ())};
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
#if OPENSSL_VERSION_MAJOR >= 3
Require (fLoadedProviders_.ContainsKey (providerName));
auto l = fLoadedProviders_.Lookup (providerName);
Assert (l);
l->second--;
if (l->second == 0) {
fLoadedProviders_.Remove (providerName);
Verify (::OSSL_PROVIDER_unload (l->first) == 1);
DbgTrace (L"real unload");
}
else {
fLoadedProviders_.Add (providerName, *l);
}
#endif
}
#endif
<commit_msg>cleanup debugtrace calls in openssl wrapper code<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved
*/
#include "../../StroikaPreComp.h"
#if qHasFeature_OpenSSL
#include <openssl/evp.h>
#if OPENSSL_VERSION_MAJOR >= 3
#include <openssl/provider.h>
#endif
#endif
#include "../../Debug/Assertions.h"
#include "../../Execution/Exceptions.h"
#include "LibraryContext.h"
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Cryptography;
using namespace Stroika::Foundation::Cryptography::OpenSSL;
#if qHasFeature_OpenSSL && defined(_MSC_VER)
// Use #pragma comment lib instead of explicit entry in the lib entry of the project file
#if OPENSSL_VERSION_NUMBER < 0x1010000fL
#pragma comment(lib, "libeay32.lib")
#pragma comment(lib, "ssleay32.lib")
#else
#pragma comment(lib, "libcrypto.lib")
#pragma comment(lib, "libssl.lib")
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "crypt32.lib")
#endif
#endif
#if qHasFeature_OpenSSL
namespace {
void AccumulateIntoSetOfCipherNames_ (const ::EVP_CIPHER* ciph, Set<String>* ciphers)
{
RequireNotNull (ciphers);
if (ciph != nullptr) {
#if OPENSSL_VERSION_MAJOR >= 3
DbgTrace (L"cipher: %p (name: %s), provider: %p (name %s)", ciph,
CipherAlgorithm{ciph}.pName ().c_str (),
::EVP_CIPHER_get0_provider (ciph),
(::EVP_CIPHER_get0_provider (ciph) == nullptr ? L"null" : String::FromNarrowSDKString (::OSSL_PROVIDER_get0_name (::EVP_CIPHER_get0_provider (ciph))).c_str ()));
#else
DbgTrace (L"cipher: %p (name: %s)", ciph, CipherAlgorithm{ciph}.pName ().c_str ());
#endif
#if 0
int flags = ::EVP_CIPHER_flags (ciph);
DbgTrace ("flags=%x", flags);
#endif
ciphers->Add (CipherAlgorithm{ciph}.pName ());
}
};
void AccumulateIntoSetOfDigestNames_ (const ::EVP_MD* digest, Set<String>* digestNames)
{
RequireNotNull (digestNames);
if (digest != nullptr) {
#if OPENSSL_VERSION_MAJOR >= 3
DbgTrace (L"digest: %p (name: %s), provider: %p (name %s)",
digest, DigestAlgorithm{digest}.pName ().c_str (),
::EVP_MD_get0_provider (digest),
(::EVP_MD_get0_provider (digest) == nullptr ? L"null" : String::FromNarrowSDKString (::OSSL_PROVIDER_get0_name (::EVP_MD_get0_provider (digest))).c_str ()));
#else
DbgTrace (L"digest: %p (name: %s)", digest, DigestAlgorithm{digest}.pName ().c_str ());
#endif
digestNames->Add (DigestAlgorithm{digest}.pName ());
}
};
}
/*
********************************************************************************
******************* Cryptography::OpenSSL::LibraryContext **********************
********************************************************************************
*/
#if qCompiler_cpp17InlineStaticMemberOfClassDoubleDeleteAtExit_Buggy
LibraryContext LibraryContext::sDefault;
#endif
LibraryContext::LibraryContext ()
: pAvailableCipherAlgorithms{
[qStroika_Foundation_Common_Property_ExtraCaptureStuff] ([[maybe_unused]] const auto* property) -> Set<CipherAlgorithm> {
const LibraryContext* thisObj = qStroika_Foundation_Common_Property_OuterObjPtr (property, &LibraryContext::pAvailableCipherAlgorithms);
shared_lock<const AssertExternallySynchronizedLock> critSec{*thisObj};
Set<String> cipherNames;
#if OPENSSL_VERSION_MAJOR >= 3
::EVP_CIPHER_do_all_provided (
nullptr,
[] (::EVP_CIPHER* ciph, void* arg) { AccumulateIntoSetOfCipherNames_ (ciph, reinterpret_cast<Set<String>*> (arg)); },
&cipherNames);
#else
::EVP_CIPHER_do_all_sorted (
#if qCompilerAndStdLib_maybe_unused_in_lambda_ignored_Buggy
[] (const ::EVP_CIPHER* ciph, const char*, const char*, void* arg) { AccumulateIntoSetOfCipherNames_ (ciph, reinterpret_cast<Set<String>*> (arg)); },
#else
[] (const ::EVP_CIPHER* ciph, [[maybe_unused]] const char* from, [[maybe_unused]] const char* to, void* arg) { AccumulateIntoSetOfCipherNames_ (ciph, reinterpret_cast<Set<String>*> (arg)); },
#endif
&cipherNames);
#endif
DbgTrace (L"Found pAvailableCipherAlgorithms-FIRST-PASS (cnt=%d): %s", cipherNames.size (), Characters::ToString (cipherNames).c_str ());
Set<CipherAlgorithm> results{cipherNames.Select<CipherAlgorithm> ([] (const String& n) -> optional<CipherAlgorithm> { return OpenSSL::CipherAlgorithm::GetByNameQuietly (n); })};
DbgTrace (L"Found pAvailableCipherAlgorithms (cnt=%d): %s", results.size (), Characters::ToString (results).c_str ());
return results;
}}
, pStandardCipherAlgorithms{[qStroika_Foundation_Common_Property_ExtraCaptureStuff] ([[maybe_unused]] const auto* property) -> Set<CipherAlgorithm> {
const LibraryContext* thisObj = qStroika_Foundation_Common_Property_OuterObjPtr (property, &LibraryContext::pStandardCipherAlgorithms);
shared_lock<const AssertExternallySynchronizedLock> critSec{*thisObj};
Set<CipherAlgorithm> results;
results += CipherAlgorithms::kAES_128_CBC;
results += CipherAlgorithms::kAES_128_ECB;
results += CipherAlgorithms::kAES_128_OFB;
results += CipherAlgorithms::kAES_128_CFB1;
results += CipherAlgorithms::kAES_128_CFB8;
results += CipherAlgorithms::kAES_128_CFB128;
results += CipherAlgorithms::kAES_192_CBC;
results += CipherAlgorithms::kAES_192_ECB;
results += CipherAlgorithms::kAES_192_OFB;
results += CipherAlgorithms::kAES_192_CFB1;
results += CipherAlgorithms::kAES_192_CFB8;
results += CipherAlgorithms::kAES_192_CFB128;
results += CipherAlgorithms::kAES_256_CBC;
results += CipherAlgorithms::kAES_256_ECB;
results += CipherAlgorithms::kAES_256_OFB;
results += CipherAlgorithms::kAES_256_CFB1;
results += CipherAlgorithms::kAES_256_CFB8;
results += CipherAlgorithms::kAES_256_CFB128;
/*
* @todo mark these below as deprecated...??? in openssl3?
*/
#if OPENSSL_VERSION_MAJOR < 3
results += CipherAlgorithms::kBlowfish_CBC;
results += CipherAlgorithms::kBlowfish_ECB;
results += CipherAlgorithms::kBlowfish_CFB;
results += CipherAlgorithms::kBlowfish_OFB;
results += CipherAlgorithms::kBlowfish;
results += CipherAlgorithms::kRC2_CBC;
results += CipherAlgorithms::kRC2_ECB;
results += CipherAlgorithms::kRC2_CFB;
results += CipherAlgorithms::kRC2_OFB;
results += CipherAlgorithms::kRC4;
#endif
return results;
}}
, pAvailableDigestAlgorithms{[qStroika_Foundation_Common_Property_ExtraCaptureStuff] ([[maybe_unused]] const auto* property) -> Set<DigestAlgorithm> {
const LibraryContext* thisObj = qStroika_Foundation_Common_Property_OuterObjPtr (property, &LibraryContext::pAvailableDigestAlgorithms);
shared_lock<const AssertExternallySynchronizedLock> critSec{*thisObj};
Set<String> digestNames;
#if OPENSSL_VERSION_MAJOR >= 3
::EVP_MD_do_all_provided (
nullptr,
[] (::EVP_MD* md, void* arg) { AccumulateIntoSetOfDigestNames_ (md, reinterpret_cast<Set<String>*> (arg)); },
&digestNames);
#else
::EVP_MD_do_all_sorted (
#if qCompilerAndStdLib_maybe_unused_in_lambda_ignored_Buggy
[] (const ::EVP_MD* md, const char*, const char*, void* arg) { AccumulateIntoSetOfDigestNames_ (md, reinterpret_cast<Set<String>*> (arg)); },
#else
[] (const ::EVP_MD* md, [[maybe_unused]] const char* from, [[maybe_unused]] const char* to, void* arg) { AccumulateIntoSetOfDigestNames_ (md, reinterpret_cast<Set<String>*> (arg)); },
#endif
&digestNames);
#endif
DbgTrace (L"Found pAvailableDigestAlgorithms-FIRST-PASS (cnt=%d): %s", digestNames.size (), Characters::ToString (digestNames).c_str ());
Set<DigestAlgorithm> results{digestNames.Select<DigestAlgorithm> ([] (const String& n) -> optional<DigestAlgorithm> { return OpenSSL::DigestAlgorithm::GetByNameQuietly (n); })};
DbgTrace (L"Found pAvailableDigestAlgorithms (cnt=%d): %s", results.size (), Characters::ToString (results).c_str ());
return results;
}}
, pStandardDigestAlgorithms{[qStroika_Foundation_Common_Property_ExtraCaptureStuff] ([[maybe_unused]] const auto* property) -> Set<DigestAlgorithm> {
const LibraryContext* thisObj = qStroika_Foundation_Common_Property_OuterObjPtr (property, &LibraryContext::pStandardDigestAlgorithms);
shared_lock<const AssertExternallySynchronizedLock> critSec{*thisObj};
Set<DigestAlgorithm> results;
results += DigestAlgorithms::kMD5;
results += DigestAlgorithms::kSHA1;
results += DigestAlgorithms::kSHA224;
results += DigestAlgorithms::kSHA256;
results += DigestAlgorithms::kSHA384;
results += DigestAlgorithms::kSHA512;
return results;
}}
{
LoadProvider (kDefaultProvider);
}
LibraryContext ::~LibraryContext ()
{
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
#if OPENSSL_VERSION_MAJOR >= 3
for (auto i : fLoadedProviders_) {
Verify (::OSSL_PROVIDER_unload (i.fValue.first) == 1);
}
#endif
}
void LibraryContext::LoadProvider ([[maybe_unused]] const String& providerName)
{
Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"OpenSSL::LibraryContext::LoadProvider", L"%s", providerName.c_str ())};
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
#if OPENSSL_VERSION_MAJOR >= 3
if (auto l = fLoadedProviders_.Lookup (providerName)) {
l->second++;
fLoadedProviders_.Add (providerName, *l);
}
else {
OSSL_PROVIDER* p = ::OSSL_PROVIDER_load (nullptr, providerName.AsNarrowSDKString ().c_str ());
static const Execution::RuntimeErrorException kErr_{L"No such SSL provider"sv};
Execution::ThrowIfNull (p, kErr_);
fLoadedProviders_.Add (providerName, {p, 1});
DbgTrace (L"real load");
}
#else
Require (providerName == kDefaultProvider or providerName == kLegacyProvider);
#endif
}
void LibraryContext ::UnLoadProvider ([[maybe_unused]] const String& providerName)
{
Debug::TraceContextBumper ctx{Stroika_Foundation_Debug_OptionalizeTraceArgs (L"OpenSSL::LibraryContext::UnLoadProvider", L"%s", providerName.c_str ())};
lock_guard<const AssertExternallySynchronizedLock> critSec{*this};
#if OPENSSL_VERSION_MAJOR >= 3
Require (fLoadedProviders_.ContainsKey (providerName));
auto l = fLoadedProviders_.Lookup (providerName);
Assert (l);
l->second--;
if (l->second == 0) {
fLoadedProviders_.Remove (providerName);
Verify (::OSSL_PROVIDER_unload (l->first) == 1);
DbgTrace (L"real unload");
}
else {
fLoadedProviders_.Add (providerName, *l);
}
#endif
}
#endif
<|endoftext|>
|
<commit_before>/* dtkDistributedMapper.cpp ---
*
* Author: Thibaud Kloczko
* Created: 2013 Thu Feb 7 10:55:57 (+0100)
*/
/* Commentary:
*
*/
/* Change log:
*
*/
#include "dtkDistributedMapper.h"
#include <QtCore>
// /////////////////////////////////////////////////////////////////
// dtkDistributedMapperPrivate interface
// /////////////////////////////////////////////////////////////////
class dtkDistributedMapperPrivate
{
public:
dtkDistributedMapperPrivate(void) {;}
~dtkDistributedMapperPrivate(void) {;}
public:
void setMapping(const qlonglong& id_number, const qlonglong& pu_number);
void initMap(const qlonglong& map_size, const qlonglong& pu_size);
void setMap(const qlonglong& local_map_size, const qlonglong& pu_id);
public:
qlonglong localToGlobal(const qlonglong& local_id, const qlonglong& pu_id) const;
qlonglong globalToLocal(const qlonglong& global_id) const;
qlonglong count(const qlonglong& pu_id) const;
qlonglong owner(const qlonglong& global_id) const;
QVector<qlonglong> readers(const qlonglong& global_id) const;
public:
qlonglong id_count;
qlonglong pu_count;
qlonglong step;
QVector<qlonglong> map;
};
// /////////////////////////////////////////////////////////////////
// dtkDistributedMapperPrivate implementation
// /////////////////////////////////////////////////////////////////
void dtkDistributedMapperPrivate::setMapping(const qlonglong& id_number, const qlonglong& pu_number)
{
this->id_count = id_number;
this->pu_count = pu_number;
this->map.reserve(this->pu_count + 1);
this->map.clear();
if (this->pu_count == 1) {
this->map << 0;
this->step = this->id_count;
} else if (this->id_count < this->pu_count ) {
qDebug() << "Number of ids less than process count: NOT YET IMPLEMENTED";
return;
} else if (this->id_count < this->pu_count * 2) {
for (qlonglong i = 0; i < this->id_count - this->pu_count; ++i)
this->map << i * 2;
qlonglong start = (this->id_count - this->pu_count) *2;
for (qlonglong i = this->id_count - this->pu_count; i < this->pu_count; ++i)
this->map << start++;
this->step = 0;
} else {
this->step = qRound(this->id_count / (1. * this->pu_count));
qlonglong last = qMin(this->id_count / this->step, this->pu_count -1);
for (qlonglong i = 0; i < last; ++i)
this->map << i * this->step;
qlonglong start = (last - 1) * this->step;
for (qlonglong i = last; i < this->pu_count; ++i) {
start += this->step -1;
this->map << qMin(start, this->id_count -1);
}
this->step = 0;
}
this->map << this->id_count;
}
void dtkDistributedMapperPrivate::initMap(const qlonglong& map_size, const qlonglong& pu_size)
{
this->id_count = map_size;
this->pu_count = pu_size;
this->map.resize(this->pu_count + 1);
this->map[this->pu_count] = map_size;
this->step = 0;
}
void dtkDistributedMapperPrivate::setMap(const qlonglong& offset, const qlonglong& pu_id)
{
this->map[pu_id] = offset;
}
qlonglong dtkDistributedMapperPrivate::localToGlobal(const qlonglong& local_id, const qlonglong& pu_id) const
{
return ( local_id + this->map.at(pu_id) );
}
qlonglong dtkDistributedMapperPrivate::globalToLocal(const qlonglong& global_id) const
{
qlonglong pu_id = this->owner(global_id);
return ( global_id - this->map.at(pu_id) );
}
qlonglong dtkDistributedMapperPrivate::count(const qlonglong& pu_id) const
{
return ( this->map.at(pu_id + 1) - this->map.at(pu_id) );
// if ( pu_id != (this->pu_count - 1) )
// return ( this->map.at(pu_id + 1) - this->map.at(pu_id) );
// else
// return ( this->id_count - this->map.at(pu_id) );
}
qlonglong dtkDistributedMapperPrivate::owner(const qlonglong& global_id) const
{
if (this->step > 0) {
return qMin((qlonglong)(global_id / this->step), this->pu_count-1);
} else {
qlonglong current_id = this->map[this->map.count() - 2];
qlonglong pid = this->pu_count-1;
while (global_id < current_id) {
current_id = this->map.at(--pid);
}
return pid;
}
}
// /////////////////////////////////////////////////////////////////
// dtkDistributedMapper implementation
// /////////////////////////////////////////////////////////////////
dtkDistributedMapper::dtkDistributedMapper(void) : QObject(), d(new dtkDistributedMapperPrivate)
{
}
dtkDistributedMapper::~dtkDistributedMapper(void)
{
delete d;
}
void dtkDistributedMapper::setMapping(const qlonglong& id_count, const qlonglong& pu_count)
{
d->setMapping(id_count, pu_count);
}
void dtkDistributedMapper::initMap(const qlonglong& map_size, const qlonglong& pu_size)
{
d->initMap(map_size, pu_size);
}
void dtkDistributedMapper::setMap(const qlonglong& offset, const qlonglong& pu_id)
{
d->setMap(offset, pu_id);
}
qlonglong dtkDistributedMapper::localToGlobal(const qlonglong& local_id, const qlonglong& pu_id) const
{
return d->localToGlobal(local_id, pu_id);
}
qlonglong dtkDistributedMapper::globalToLocal(const qlonglong& global_id) const
{
return d->globalToLocal(global_id);
}
qlonglong dtkDistributedMapper::count(const qlonglong& pu_id) const
{
return d->count(pu_id);
}
qlonglong dtkDistributedMapper::startIndex(const qlonglong& pu_id) const
{
return d->map[pu_id];
}
qlonglong dtkDistributedMapper::lastIndex(const qlonglong& pu_id) const
{
return d->map[pu_id + 1] - 1;
}
qlonglong dtkDistributedMapper::owner(const qlonglong& global_id) const
{
return d->owner(global_id);
}
<commit_msg>enchance default mapper<commit_after>/* dtkDistributedMapper.cpp ---
*
* Author: Thibaud Kloczko
* Created: 2013 Thu Feb 7 10:55:57 (+0100)
*/
/* Commentary:
*
*/
/* Change log:
*
*/
#include "dtkDistributedMapper.h"
#include <QtCore>
// /////////////////////////////////////////////////////////////////
// dtkDistributedMapperPrivate interface
// /////////////////////////////////////////////////////////////////
class dtkDistributedMapperPrivate
{
public:
dtkDistributedMapperPrivate(void) {;}
~dtkDistributedMapperPrivate(void) {;}
public:
void setMapping(const qlonglong& id_number, const qlonglong& pu_number);
void initMap(const qlonglong& map_size, const qlonglong& pu_size);
void setMap(const qlonglong& local_map_size, const qlonglong& pu_id);
public:
qlonglong localToGlobal(const qlonglong& local_id, const qlonglong& pu_id) const;
qlonglong globalToLocal(const qlonglong& global_id) const;
qlonglong count(const qlonglong& pu_id) const;
qlonglong owner(const qlonglong& global_id) const;
QVector<qlonglong> readers(const qlonglong& global_id) const;
public:
qlonglong id_count;
qlonglong pu_count;
qlonglong step;
QVector<qlonglong> map;
};
// /////////////////////////////////////////////////////////////////
// dtkDistributedMapperPrivate implementation
// /////////////////////////////////////////////////////////////////
void dtkDistributedMapperPrivate::setMapping(const qlonglong& id_number, const qlonglong& pu_number)
{
this->id_count = id_number;
this->pu_count = pu_number;
this->map.reserve(this->pu_count + 1);
this->map.clear();
if (this->pu_count == 1) {
this->map << 0;
this->step = this->id_count;
} else if (this->id_count < this->pu_count ) {
qDebug() << "Number of ids less than process count: NOT YET IMPLEMENTED";
return;
} else {
this->step = this->id_count / this->pu_count;
qlonglong rest = this->id_count % this->pu_count;
for (qlonglong i = 0; i < rest+1; ++i) {
this->map << i * (this->step+1);
}
qlonglong last = rest * (this->step +1);
for (qlonglong i = 1; i < this->pu_count-rest; ++i) {
this->map << last + i * this->step;
}
this->step = 0;
}
this->map << this->id_count;
}
void dtkDistributedMapperPrivate::initMap(const qlonglong& map_size, const qlonglong& pu_size)
{
this->id_count = map_size;
this->pu_count = pu_size;
this->map.resize(this->pu_count + 1);
this->map[this->pu_count] = map_size;
this->step = 0;
}
void dtkDistributedMapperPrivate::setMap(const qlonglong& offset, const qlonglong& pu_id)
{
this->map[pu_id] = offset;
}
qlonglong dtkDistributedMapperPrivate::localToGlobal(const qlonglong& local_id, const qlonglong& pu_id) const
{
return ( local_id + this->map.at(pu_id) );
}
qlonglong dtkDistributedMapperPrivate::globalToLocal(const qlonglong& global_id) const
{
qlonglong pu_id = this->owner(global_id);
return ( global_id - this->map.at(pu_id) );
}
qlonglong dtkDistributedMapperPrivate::count(const qlonglong& pu_id) const
{
return ( this->map.at(pu_id + 1) - this->map.at(pu_id) );
}
qlonglong dtkDistributedMapperPrivate::owner(const qlonglong& global_id) const
{
if (this->step > 0) {
return qMin((qlonglong)(global_id / this->step), this->pu_count-1);
} else {
qlonglong current_id = this->map[this->map.count() - 2];
qlonglong pid = this->pu_count-1;
while (global_id < current_id) {
current_id = this->map.at(--pid);
}
return pid;
}
}
// /////////////////////////////////////////////////////////////////
// dtkDistributedMapper implementation
// /////////////////////////////////////////////////////////////////
dtkDistributedMapper::dtkDistributedMapper(void) : QObject(), d(new dtkDistributedMapperPrivate)
{
}
dtkDistributedMapper::~dtkDistributedMapper(void)
{
delete d;
}
void dtkDistributedMapper::setMapping(const qlonglong& id_count, const qlonglong& pu_count)
{
d->setMapping(id_count, pu_count);
}
void dtkDistributedMapper::initMap(const qlonglong& map_size, const qlonglong& pu_size)
{
d->initMap(map_size, pu_size);
}
void dtkDistributedMapper::setMap(const qlonglong& offset, const qlonglong& pu_id)
{
d->setMap(offset, pu_id);
}
qlonglong dtkDistributedMapper::localToGlobal(const qlonglong& local_id, const qlonglong& pu_id) const
{
return d->localToGlobal(local_id, pu_id);
}
qlonglong dtkDistributedMapper::globalToLocal(const qlonglong& global_id) const
{
return d->globalToLocal(global_id);
}
qlonglong dtkDistributedMapper::count(const qlonglong& pu_id) const
{
return d->count(pu_id);
}
qlonglong dtkDistributedMapper::startIndex(const qlonglong& pu_id) const
{
return d->map[pu_id];
}
qlonglong dtkDistributedMapper::lastIndex(const qlonglong& pu_id) const
{
return d->map[pu_id + 1] - 1;
}
qlonglong dtkDistributedMapper::owner(const qlonglong& global_id) const
{
return d->owner(global_id);
}
<|endoftext|>
|
<commit_before>/*************************************************
* Pooling Allocator Source File *
* (C) 1999-2007 The Botan Project *
*************************************************/
#include <botan/mem_pool.h>
#include <botan/libstate.h>
#include <botan/config.h>
#include <botan/bit_ops.h>
#include <botan/util.h>
#include <algorithm>
namespace Botan {
namespace {
/*************************************************
* Decide how much memory to allocate at once *
*************************************************/
u32bit choose_pref_size(u32bit provided)
{
if(provided)
return provided;
u32bit result = global_config().option_as_u32bit("base/memory_chunk");
if(result)
return result;
return 16*1024;
}
}
/*************************************************
* Memory_Block Constructor *
*************************************************/
Pooling_Allocator::Memory_Block::Memory_Block(void* buf)
{
buffer = static_cast<byte*>(buf);
bitmap = 0;
buffer_end = buffer + (BLOCK_SIZE * BITMAP_SIZE);
}
/*************************************************
* Compare a Memory_Block with a void pointer *
*************************************************/
inline bool Pooling_Allocator::Memory_Block::operator<(const void* other) const
{
if(buffer <= other && other < buffer_end)
return false;
return (buffer < other);
}
/*************************************************
* See if ptr is contained by this block *
*************************************************/
bool Pooling_Allocator::Memory_Block::contains(void* ptr,
u32bit length) const throw()
{
return ((buffer <= ptr) &&
(buffer_end >= (byte*)ptr + length * BLOCK_SIZE));
}
/*************************************************
* Allocate some memory, if possible *
*************************************************/
byte* Pooling_Allocator::Memory_Block::alloc(u32bit n) throw()
{
if(n == 0 || n > BITMAP_SIZE)
return 0;
if(n == BITMAP_SIZE)
{
if(bitmap)
return 0;
else
{
bitmap = ~bitmap;
return buffer;
}
}
bitmap_type mask = ((bitmap_type)1 << n) - 1;
u32bit offset = 0;
while(bitmap & mask)
{
mask <<= 1;
++offset;
if((bitmap & mask) == 0)
break;
if(mask >> 63)
break;
}
if(bitmap & mask)
return 0;
bitmap |= mask;
return buffer + offset * BLOCK_SIZE;
}
/*************************************************
* Mark this memory as free, if we own it *
*************************************************/
void Pooling_Allocator::Memory_Block::free(void* ptr, u32bit blocks) throw()
{
clear_mem((byte*)ptr, blocks * BLOCK_SIZE);
const u32bit offset = ((byte*)ptr - buffer) / BLOCK_SIZE;
if(offset == 0 && blocks == BITMAP_SIZE)
bitmap = ~bitmap;
else
{
for(u32bit j = 0; j != blocks; ++j)
bitmap &= ~((bitmap_type)1 << (j+offset));
}
}
/*************************************************
* Pooling_Allocator Constructor *
*************************************************/
Pooling_Allocator::Pooling_Allocator(u32bit p_size, bool) :
PREF_SIZE(choose_pref_size(p_size))
{
mutex = global_state().get_mutex();
last_used = blocks.begin();
}
/*************************************************
* Pooling_Allocator Destructor *
*************************************************/
Pooling_Allocator::~Pooling_Allocator()
{
delete mutex;
if(blocks.size())
throw Invalid_State("Pooling_Allocator: Never released memory");
}
/*************************************************
* Free all remaining memory *
*************************************************/
void Pooling_Allocator::destroy()
{
Mutex_Holder lock(mutex);
blocks.clear();
for(u32bit j = 0; j != allocated.size(); ++j)
dealloc_block(allocated[j].first, allocated[j].second);
allocated.clear();
}
/*************************************************
* Allocation *
*************************************************/
void* Pooling_Allocator::allocate(u32bit n)
{
const u32bit BITMAP_SIZE = Memory_Block::bitmap_size();
const u32bit BLOCK_SIZE = Memory_Block::block_size();
Mutex_Holder lock(mutex);
if(n <= BITMAP_SIZE * BLOCK_SIZE)
{
const u32bit block_no = round_up(n, BLOCK_SIZE) / BLOCK_SIZE;
byte* mem = allocate_blocks(block_no);
if(mem)
return mem;
get_more_core(PREF_SIZE);
mem = allocate_blocks(block_no);
if(mem)
return mem;
throw Memory_Exhaustion();
}
void* new_buf = alloc_block(n);
if(new_buf)
return new_buf;
throw Memory_Exhaustion();
}
/*************************************************
* Deallocation *
*************************************************/
void Pooling_Allocator::deallocate(void* ptr, u32bit n)
{
const u32bit BITMAP_SIZE = Memory_Block::bitmap_size();
const u32bit BLOCK_SIZE = Memory_Block::block_size();
if(ptr == 0 && n == 0)
return;
Mutex_Holder lock(mutex);
if(n > BITMAP_SIZE * BLOCK_SIZE)
dealloc_block(ptr, n);
else
{
const u32bit block_no = round_up(n, BLOCK_SIZE) / BLOCK_SIZE;
std::vector<Memory_Block>::iterator i =
std::lower_bound(blocks.begin(), blocks.end(), Memory_Block(ptr));
if(i == blocks.end() || !i->contains(ptr, block_no))
throw Invalid_State("Pointer released to the wrong allocator");
i->free(ptr, block_no);
}
}
/*************************************************
* Try to get some memory from an existing block *
*************************************************/
byte* Pooling_Allocator::allocate_blocks(u32bit n)
{
if(blocks.empty())
return 0;
std::vector<Memory_Block>::iterator i = last_used;
do
{
byte* mem = i->alloc(n);
if(mem)
{
last_used = i;
return mem;
}
++i;
if(i == blocks.end())
i = blocks.begin();
}
while(i != last_used);
return 0;
}
/*************************************************
* Allocate more memory for the pool *
*************************************************/
void Pooling_Allocator::get_more_core(u32bit in_bytes)
{
const u32bit BITMAP_SIZE = Memory_Block::bitmap_size();
const u32bit BLOCK_SIZE = Memory_Block::block_size();
const u32bit TOTAL_BLOCK_SIZE = BLOCK_SIZE * BITMAP_SIZE;
const u32bit in_blocks = round_up(in_bytes, BLOCK_SIZE) / TOTAL_BLOCK_SIZE;
const u32bit to_allocate = in_blocks * TOTAL_BLOCK_SIZE;
void* ptr = alloc_block(to_allocate);
if(ptr == 0)
throw Memory_Exhaustion();
allocated.push_back(std::make_pair(ptr, to_allocate));
for(u32bit j = 0; j != in_blocks; ++j)
{
byte* byte_ptr = static_cast<byte*>(ptr);
blocks.push_back(Memory_Block(byte_ptr + j * TOTAL_BLOCK_SIZE));
}
std::sort(blocks.begin(), blocks.end());
last_used = std::lower_bound(blocks.begin(), blocks.end(),
Memory_Block(ptr));
}
}
<commit_msg>Revert the last change; it actually broke the memory allocators in a fairly massive way.<commit_after>/*************************************************
* Pooling Allocator Source File *
* (C) 1999-2007 The Botan Project *
*************************************************/
#include <botan/mem_pool.h>
#include <botan/libstate.h>
#include <botan/config.h>
#include <botan/bit_ops.h>
#include <botan/util.h>
#include <algorithm>
namespace Botan {
namespace {
/*************************************************
* Decide how much memory to allocate at once *
*************************************************/
u32bit choose_pref_size(u32bit provided)
{
if(provided)
return provided;
u32bit result = global_config().option_as_u32bit("base/memory_chunk");
if(result)
return result;
return 16*1024;
}
}
/*************************************************
* Memory_Block Constructor *
*************************************************/
Pooling_Allocator::Memory_Block::Memory_Block(void* buf)
{
buffer = static_cast<byte*>(buf);
bitmap = 0;
buffer_end = buffer + (BLOCK_SIZE * BITMAP_SIZE);
}
/*************************************************
* Compare a Memory_Block with a void pointer *
*************************************************/
inline bool Pooling_Allocator::Memory_Block::operator<(const void* other) const
{
if(buffer <= other && other < buffer_end)
return false;
return (buffer < other);
}
/*************************************************
* See if ptr is contained by this block *
*************************************************/
bool Pooling_Allocator::Memory_Block::contains(void* ptr,
u32bit length) const throw()
{
return ((buffer <= ptr) &&
(buffer_end >= (byte*)ptr + length * BLOCK_SIZE));
}
/*************************************************
* Allocate some memory, if possible *
*************************************************/
byte* Pooling_Allocator::Memory_Block::alloc(u32bit n) throw()
{
if(n == 0 || n > BITMAP_SIZE)
return 0;
if(n == BITMAP_SIZE)
{
if(bitmap)
return 0;
else
{
bitmap = ~bitmap;
return buffer;
}
}
bitmap_type mask = ((bitmap_type)1 << n) - 1;
u32bit offset = 0;
while(bitmap & mask)
{
mask <<= 1;
++offset;
if((bitmap & mask) == 0)
break;
if(mask >> 63)
break;
}
if(bitmap & mask)
return 0;
bitmap |= mask;
return buffer + offset * BLOCK_SIZE;
}
/*************************************************
* Mark this memory as free, if we own it *
*************************************************/
void Pooling_Allocator::Memory_Block::free(void* ptr, u32bit blocks) throw()
{
clear_mem((byte*)ptr, blocks * BLOCK_SIZE);
const u32bit offset = ((byte*)ptr - buffer) / BLOCK_SIZE;
if(offset == 0 && blocks == BITMAP_SIZE)
bitmap = ~bitmap;
else
{
for(u32bit j = 0; j != blocks; ++j)
bitmap &= ~((bitmap_type)1 << (j+offset));
}
}
/*************************************************
* Pooling_Allocator Constructor *
*************************************************/
Pooling_Allocator::Pooling_Allocator(u32bit p_size, bool) :
PREF_SIZE(choose_pref_size(p_size))
{
mutex = global_state().get_mutex();
last_used = blocks.begin();
}
/*************************************************
* Pooling_Allocator Destructor *
*************************************************/
Pooling_Allocator::~Pooling_Allocator()
{
delete mutex;
if(blocks.size())
throw Invalid_State("Pooling_Allocator: Never released memory");
}
/*************************************************
* Free all remaining memory *
*************************************************/
void Pooling_Allocator::destroy()
{
Mutex_Holder lock(mutex);
blocks.clear();
for(u32bit j = 0; j != allocated.size(); ++j)
dealloc_block(allocated[j].first, allocated[j].second);
allocated.clear();
}
/*************************************************
* Allocation *
*************************************************/
void* Pooling_Allocator::allocate(u32bit n)
{
const u32bit BITMAP_SIZE = Memory_Block::bitmap_size();
const u32bit BLOCK_SIZE = Memory_Block::block_size();
Mutex_Holder lock(mutex);
if(n <= BITMAP_SIZE * BLOCK_SIZE)
{
const u32bit block_no = round_up(n, BLOCK_SIZE) / BLOCK_SIZE;
byte* mem = allocate_blocks(block_no);
if(mem)
return mem;
get_more_core(PREF_SIZE);
mem = allocate_blocks(block_no);
if(mem)
return mem;
throw Memory_Exhaustion();
}
void* new_buf = alloc_block(n);
if(new_buf)
return new_buf;
throw Memory_Exhaustion();
}
/*************************************************
* Deallocation *
*************************************************/
void Pooling_Allocator::deallocate(void* ptr, u32bit n)
{
const u32bit BITMAP_SIZE = Memory_Block::bitmap_size();
const u32bit BLOCK_SIZE = Memory_Block::block_size();
if(ptr == 0 && n == 0)
return;
Mutex_Holder lock(mutex);
if(n > BITMAP_SIZE * BLOCK_SIZE)
dealloc_block(ptr, n);
else
{
const u32bit block_no = round_up(n, BLOCK_SIZE) / BLOCK_SIZE;
std::vector<Memory_Block>::iterator i =
std::lower_bound(blocks.begin(), blocks.end(), ptr);
if(i == blocks.end() || !i->contains(ptr, block_no))
throw Invalid_State("Pointer released to the wrong allocator");
i->free(ptr, block_no);
}
}
/*************************************************
* Try to get some memory from an existing block *
*************************************************/
byte* Pooling_Allocator::allocate_blocks(u32bit n)
{
if(blocks.empty())
return 0;
std::vector<Memory_Block>::iterator i = last_used;
do
{
byte* mem = i->alloc(n);
if(mem)
{
last_used = i;
return mem;
}
++i;
if(i == blocks.end())
i = blocks.begin();
}
while(i != last_used);
return 0;
}
/*************************************************
* Allocate more memory for the pool *
*************************************************/
void Pooling_Allocator::get_more_core(u32bit in_bytes)
{
const u32bit BITMAP_SIZE = Memory_Block::bitmap_size();
const u32bit BLOCK_SIZE = Memory_Block::block_size();
const u32bit TOTAL_BLOCK_SIZE = BLOCK_SIZE * BITMAP_SIZE;
const u32bit in_blocks = round_up(in_bytes, BLOCK_SIZE) / TOTAL_BLOCK_SIZE;
const u32bit to_allocate = in_blocks * TOTAL_BLOCK_SIZE;
void* ptr = alloc_block(to_allocate);
if(ptr == 0)
throw Memory_Exhaustion();
allocated.push_back(std::make_pair(ptr, to_allocate));
for(u32bit j = 0; j != in_blocks; ++j)
{
byte* byte_ptr = static_cast<byte*>(ptr);
blocks.push_back(Memory_Block(byte_ptr + j * TOTAL_BLOCK_SIZE));
}
std::sort(blocks.begin(), blocks.end());
last_used = std::lower_bound(blocks.begin(), blocks.end(),
Memory_Block(ptr));
}
}
<|endoftext|>
|
<commit_before>#include "metaenum_p.h"
#include "metacontainer_p.h"
namespace rtti {
MetaEnum::MetaEnum(std::string_view const &name, const MetaContainer &owner, MetaType_ID typeId)
: MetaItem{*new MetaEnumPrivate{name, owner, typeId}}
{}
MetaEnum *MetaEnum::create(std::string_view const &name, MetaContainer &owner, MetaType_ID typeId)
{
auto result = const_cast<MetaEnum*>(owner.getEnum(name));
if (!result)
{
result = new MetaEnum{name, owner, typeId};
INVOKE_PROTECTED(owner, addItem, result);
}
return result;
}
void MetaEnum::addElement(std::string_view const &name, variant &&value)
{
auto d = d_func();
d->m_elements.set(name, std::move(value));
}
MetaCategory MetaEnum::category() const
{
return mcatEnum;
}
std::size_t MetaEnum::elementCount() const
{
auto d = d_func();
return d->m_elements.size();
}
const variant& MetaEnum::element(std::size_t index) const
{
auto d = d_func();
return d->m_elements.get(index);
}
const std::string &MetaEnum::elementName(std::size_t index) const
{
auto d = d_func();
return d->m_elements.name(index);
}
const variant& MetaEnum::element(std::string_view const &name) const
{
auto d = d_func();
return d->m_elements.get(name);
}
void MetaEnum::for_each_element(enum_element_t const &func) const
{
if (!func)
return;
auto d = d_func();
d->m_elements.for_each([&func](std::string const &name, variant const &value) -> bool
{
return func(name, value);
});
}
} // namespace rtti
<commit_msg>C++17<commit_after>#include "metaenum_p.h"
#include "metacontainer_p.h"
namespace rtti {
MetaEnum::MetaEnum(std::string_view const &name, MetaContainer const &owner, MetaType_ID typeId)
: MetaItem{*new MetaEnumPrivate{name, owner, typeId}}
{}
MetaEnum *MetaEnum::create(std::string_view const &name, MetaContainer &owner, MetaType_ID typeId)
{
auto result = const_cast<MetaEnum*>(owner.getEnum(name));
if (!result)
{
result = new MetaEnum{name, owner, typeId};
INVOKE_PROTECTED(owner, addItem, result);
}
return result;
}
void MetaEnum::addElement(std::string_view const &name, variant &&value)
{
auto d = d_func();
d->m_elements.set(name, std::move(value));
}
MetaCategory MetaEnum::category() const
{
return mcatEnum;
}
std::size_t MetaEnum::elementCount() const
{
auto d = d_func();
return d->m_elements.size();
}
variant const& MetaEnum::element(std::size_t index) const
{
auto d = d_func();
return d->m_elements.get(index);
}
std::string const &MetaEnum::elementName(std::size_t index) const
{
auto d = d_func();
return d->m_elements.name(index);
}
variant const& MetaEnum::element(std::string_view const &name) const
{
auto d = d_func();
return d->m_elements.get(name);
}
void MetaEnum::for_each_element(enum_element_t const &func) const
{
if (!func)
return;
auto d = d_func();
d->m_elements.for_each([&func](std::string const &name, variant const &value) -> bool
{
return func(name, value);
});
}
} // namespace rtti
<|endoftext|>
|
<commit_before>/*
* MRustC - Rust Compiler
* - By John Hodge (Mutabah/thePowersGang)
*
* mir/dump.cpp
* - Dump MIR for functions (semi-flattened)
*/
#include "main_bindings.hpp"
#include <hir/visitor.hpp>
#include "mir.hpp"
namespace {
class TreeVisitor:
public ::HIR::Visitor
{
::std::ostream& m_os;
unsigned int m_indent_level;
public:
TreeVisitor(::std::ostream& os):
m_os(os),
m_indent_level(0)
{
}
void visit_type_impl(::HIR::TypeImpl& impl) override
{
m_os << indent() << "impl" << impl.m_params.fmt_args() << " " << impl.m_type << "\n";
if( ! impl.m_params.m_bounds.empty() )
{
m_os << indent() << " " << impl.m_params.fmt_bounds() << "\n";
}
m_os << indent() << "{\n";
inc_indent();
::HIR::Visitor::visit_type_impl(impl);
dec_indent();
m_os << indent() << "}\n";
}
virtual void visit_trait_impl(const ::HIR::SimplePath& trait_path, ::HIR::TraitImpl& impl) override
{
m_os << indent() << "impl" << impl.m_params.fmt_args() << " " << trait_path << impl.m_trait_args << " for " << impl.m_type << "\n";
if( ! impl.m_params.m_bounds.empty() )
{
m_os << indent() << " " << impl.m_params.fmt_bounds() << "\n";
}
m_os << indent() << "{\n";
inc_indent();
::HIR::Visitor::visit_trait_impl(trait_path, impl);
dec_indent();
m_os << indent() << "}\n";
}
void visit_marker_impl(const ::HIR::SimplePath& trait_path, ::HIR::MarkerImpl& impl) override
{
m_os << indent() << "impl" << impl.m_params.fmt_args() << " " << (impl.is_positive ? "" : "!") << trait_path << impl.m_trait_args << " for " << impl.m_type << "\n";
if( ! impl.m_params.m_bounds.empty() )
{
m_os << indent() << " " << impl.m_params.fmt_bounds() << "\n";
}
m_os << indent() << "{ }\n";
}
// - Type Items
void visit_type_alias(::HIR::ItemPath p, ::HIR::TypeAlias& item) override
{
m_os << indent() << "type " << p.get_name() << item.m_params.fmt_args() << " = " << item.m_type << item.m_params.fmt_bounds() << "\n";
}
void visit_trait(::HIR::ItemPath p, ::HIR::Trait& item) override
{
m_os << indent() << "trait " << p.get_name() << item.m_params.fmt_args() << "\n";
if( ! item.m_params.m_bounds.empty() )
{
m_os << indent() << " " << item.m_params.fmt_bounds() << "\n";
}
m_os << indent() << "{\n";
inc_indent();
::HIR::Visitor::visit_trait(p, item);
dec_indent();
m_os << indent() << "}\n";
}
void visit_function(::HIR::ItemPath p, ::HIR::Function& item) override
{
m_os << indent();
if( item.m_const )
m_os << "const ";
if( item.m_unsafe )
m_os << "unsafe ";
if( item.m_abi != "rust" )
m_os << "extern \"" << item.m_abi << "\" ";
m_os << "fn " << p.get_name() << item.m_params.fmt_args() << "(";
for(const auto& arg : item.m_args)
{
m_os << arg.first << ": " << arg.second << ", ";
}
m_os << ") -> " << item.m_return << "\n";
if( ! item.m_params.m_bounds.empty() )
{
m_os << indent() << " " << item.m_params.fmt_bounds() << "\n";
}
if( item.m_code )
{
m_os << indent() << "{\n";
inc_indent();
this->dump_mir(*item.m_code.m_mir);
dec_indent();
m_os << indent() << "}\n";
}
else
{
m_os << indent() << " ;\n";
}
}
void dump_mir(const ::MIR::Function& fcn)
{
for(unsigned int i = 0; i < fcn.named_variables.size(); i ++)
{
m_os << indent() << "let _#" << i << ": " << fcn.named_variables[i] << ";\n";
}
for(unsigned int i = 0; i < fcn.temporaries.size(); i ++)
{
m_os << indent() << "let tmp$" << i << ": " << fcn.temporaries[i] << ";\n";
}
#define FMT_M(x) FMT_CB(os, this->fmt_val(os,x);)
for(unsigned int i = 0; i < fcn.blocks.size(); i ++)
{
const auto& block = fcn.blocks[i];
m_os << indent() << "bb" << i << ": {\n";
inc_indent();
for(const auto& stmt : block.statements)
{
m_os << indent();
TU_MATCHA( (stmt), (e),
(Assign,
m_os << FMT_M(e.dst) << " = " << FMT_M(e.src) << ";\n";
),
(Drop,
m_os << "drop(" << FMT_M(e.slot) << ");\n";
)
)
}
m_os << indent();
TU_MATCHA( (block.terminator), (e),
(Incomplete,
m_os << "INVALID;\n";
),
(Return,
m_os << "return;\n";
),
(Diverge,
m_os << "diverge;\n";
),
(Goto,
m_os << "goto bb" << e << ";\n";
),
(Panic,
m_os << "panic bb" << e.dst << ";\n";
),
(If,
m_os << "if " << FMT_M(e.cond) << " { goto bb" << e.bb0 << "; } else { goto bb" << e.bb1 << "; }\n";
),
(Switch,
m_os << "switch " << FMT_M(e.val) << " {";
for(unsigned int j = 0; j < e.targets.size(); j ++)
m_os << j << " => bb" << e.targets[j] << ", ";
m_os << "}\n";
),
(Call,
m_os << FMT_M(e.ret_val) << " = (" << FMT_M(e.fcn_val) << ")( ";
for(const auto& arg : e.args)
m_os << FMT_M(arg) << ", ";
m_os << ") goto bb" << e.ret_block << " else bb" << e.panic_block << "\n";
)
)
dec_indent();
m_os << indent() << "}\n";
m_os.flush();
}
#undef FMT
}
void fmt_val(::std::ostream& os, const ::MIR::LValue& lval) {
TU_MATCHA( (lval), (e),
(Variable,
os << "_#" << e;
),
(Temporary,
os << "tmp$" << e.idx;
),
(Argument,
os << "arg$" << e.idx;
),
(Static,
os << e;
),
(Return,
os << "RETURN";
),
(Field,
os << "(";
fmt_val(os, *e.val);
os << ")." << e.field_index;
),
(Deref,
os << "*";
fmt_val(os, *e.val);
),
(Index,
os << "(";
fmt_val(os, *e.val);
os << ")[";
fmt_val(os, *e.idx);
os << "]";
),
(Downcast,
fmt_val(os, *e.val);
os << " as variant" << e.variant_index;
)
)
}
void fmt_val(::std::ostream& os, const ::MIR::RValue& rval) {
TU_MATCHA( (rval), (e),
(Use,
fmt_val(os, e);
),
(Constant,
TU_MATCHA( (e), (ce),
(Int,
os << ce;
),
(Uint,
os << "0x" << ::std::hex << ce << ::std::dec;
),
(Float,
os << ce;
),
(Bool,
os << (ce ? "true" : "false");
),
(Bytes,
os << "b\"" << ce << "\"";
),
(StaticString,
os << "\"" << ce << "\"";
),
(ItemAddr,
os << "addr " << ce;
)
)
),
(SizedArray,
os << "[";
fmt_val(os, e.val);
os << ";" << e.count << "]";
),
(Borrow,
os << "&";
//os << e.region;
switch(e.type) {
case ::HIR::BorrowType::Shared: break;
case ::HIR::BorrowType::Unique: os << "mut "; break;
case ::HIR::BorrowType::Owned: os << "move "; break;
}
os << "(";
fmt_val(os, e.val);
os << ")";
),
(Cast,
os << "(";
fmt_val(os, e.val);
os << ") as " << e.type;
),
(BinOp,
switch(e.op)
{
case ::MIR::eBinOp::ADD: os << "ADD"; break;
case ::MIR::eBinOp::SUB: os << "SUB"; break;
case ::MIR::eBinOp::MUL: os << "MUL"; break;
case ::MIR::eBinOp::DIV: os << "DIV"; break;
case ::MIR::eBinOp::MOD: os << "MOD"; break;
case ::MIR::eBinOp::ADD_OV: os << "ADD_OV"; break;
case ::MIR::eBinOp::SUB_OV: os << "SUB_OV"; break;
case ::MIR::eBinOp::MUL_OV: os << "MUL_OV"; break;
case ::MIR::eBinOp::DIV_OV: os << "DIV_OV"; break;
//case ::MIR::eBinOp::MOD_OV: os << "MOD_OV"; break;
case ::MIR::eBinOp::BIT_OR : os << "BIT_OR"; break;
case ::MIR::eBinOp::BIT_AND: os << "BIT_AND"; break;
case ::MIR::eBinOp::BIT_XOR: os << "BIT_XOR"; break;
case ::MIR::eBinOp::BIT_SHR: os << "BIT_SHR"; break;
case ::MIR::eBinOp::BIT_SHL: os << "BIT_SHL"; break;
case ::MIR::eBinOp::EQ: os << "EQ"; break;
case ::MIR::eBinOp::NE: os << "NE"; break;
case ::MIR::eBinOp::GT: os << "GT"; break;
case ::MIR::eBinOp::GE: os << "GE"; break;
case ::MIR::eBinOp::LT: os << "LT"; break;
case ::MIR::eBinOp::LE: os << "LE"; break;
}
os << "(";
fmt_val(os, e.val_l);
os << ", ";
fmt_val(os, e.val_r);
os << ")";
),
(UniOp,
switch(e.op)
{
case ::MIR::eUniOp::INV: os << "INV"; break;
case ::MIR::eUniOp::NEG: os << "NEG"; break;
}
os << "(";
fmt_val(os, e.val);
os << ")";
),
(DstMeta,
os << "META(";
fmt_val(os, e.val);
os << ")";
),
(MakeDst,
os << "DST(";
fmt_val(os, e.ptr_val);
os << ", ";
fmt_val(os, e.meta_val);
os << ")";
),
(Tuple,
os << "(";
for(const auto& v : e.vals) {
fmt_val(os, v);
os << ", ";
}
os << ")";
),
(Array,
os << "[";
for(const auto& v : e.vals) {
fmt_val(os, v);
os << ", ";
}
os << "]";
),
(Struct,
os << e.path << " { ";
for(const auto& v : e.vals) {
fmt_val(os, v);
os << ", ";
}
os << "}";
)
)
}
private:
RepeatLitStr indent() const {
return RepeatLitStr { " ", static_cast<int>(m_indent_level) };
}
void inc_indent() {
m_indent_level ++;
}
void dec_indent() {
m_indent_level --;
}
};
}
void MIR_Dump(::std::ostream& sink, const ::HIR::Crate& crate)
{
TreeVisitor tv { sink };
tv.visit_crate( const_cast< ::HIR::Crate&>(crate) );
}
<commit_msg>MIR Dump - Clean up output<commit_after>/*
* MRustC - Rust Compiler
* - By John Hodge (Mutabah/thePowersGang)
*
* mir/dump.cpp
* - Dump MIR for functions (semi-flattened)
*/
#include "main_bindings.hpp"
#include <hir/visitor.hpp>
#include "mir.hpp"
namespace {
class TreeVisitor:
public ::HIR::Visitor
{
::std::ostream& m_os;
unsigned int m_indent_level;
bool m_short_item_name = false;
public:
TreeVisitor(::std::ostream& os):
m_os(os),
m_indent_level(0)
{
}
void visit_type_impl(::HIR::TypeImpl& impl) override
{
m_short_item_name = true;
m_os << indent() << "impl" << impl.m_params.fmt_args() << " " << impl.m_type << "\n";
if( ! impl.m_params.m_bounds.empty() )
{
m_os << indent() << " " << impl.m_params.fmt_bounds() << "\n";
}
m_os << indent() << "{\n";
inc_indent();
::HIR::Visitor::visit_type_impl(impl);
dec_indent();
m_os << indent() << "}\n";
m_short_item_name = false;
}
virtual void visit_trait_impl(const ::HIR::SimplePath& trait_path, ::HIR::TraitImpl& impl) override
{
m_short_item_name = true;
m_os << indent() << "impl" << impl.m_params.fmt_args() << " " << trait_path << impl.m_trait_args << " for " << impl.m_type << "\n";
if( ! impl.m_params.m_bounds.empty() )
{
m_os << indent() << " " << impl.m_params.fmt_bounds() << "\n";
}
m_os << indent() << "{\n";
inc_indent();
::HIR::Visitor::visit_trait_impl(trait_path, impl);
dec_indent();
m_os << indent() << "}\n";
m_short_item_name = false;
}
void visit_marker_impl(const ::HIR::SimplePath& trait_path, ::HIR::MarkerImpl& impl) override
{
m_short_item_name = true;
m_os << indent() << "impl" << impl.m_params.fmt_args() << " " << (impl.is_positive ? "" : "!") << trait_path << impl.m_trait_args << " for " << impl.m_type << "\n";
if( ! impl.m_params.m_bounds.empty() )
{
m_os << indent() << " " << impl.m_params.fmt_bounds() << "\n";
}
m_os << indent() << "{ }\n";
m_short_item_name = false;
}
// - Type Items
void visit_trait(::HIR::ItemPath p, ::HIR::Trait& item) override
{
m_short_item_name = true;
m_os << indent() << "trait " << p << item.m_params.fmt_args() << "\n";
if( ! item.m_params.m_bounds.empty() )
{
m_os << indent() << " " << item.m_params.fmt_bounds() << "\n";
}
m_os << indent() << "{\n";
inc_indent();
::HIR::Visitor::visit_trait(p, item);
dec_indent();
m_os << indent() << "}\n";
m_short_item_name = false;
}
void visit_function(::HIR::ItemPath p, ::HIR::Function& item) override
{
m_os << indent();
if( item.m_const )
m_os << "const ";
if( item.m_unsafe )
m_os << "unsafe ";
if( item.m_abi != "rust" )
m_os << "extern \"" << item.m_abi << "\" ";
m_os << "fn ";
if( m_short_item_name )
m_os << p.get_name();
else
m_os << p;
m_os << item.m_params.fmt_args() << "(";
for(const auto& arg : item.m_args)
{
m_os << arg.first << ": " << arg.second << ", ";
}
m_os << ") -> " << item.m_return << "\n";
if( ! item.m_params.m_bounds.empty() )
{
m_os << indent() << " " << item.m_params.fmt_bounds() << "\n";
}
if( item.m_code )
{
m_os << indent() << "{\n";
inc_indent();
this->dump_mir(*item.m_code.m_mir);
dec_indent();
m_os << indent() << "}\n";
}
else
{
m_os << indent() << " ;\n";
}
}
void dump_mir(const ::MIR::Function& fcn)
{
for(unsigned int i = 0; i < fcn.named_variables.size(); i ++)
{
m_os << indent() << "let _#" << i << ": " << fcn.named_variables[i] << ";\n";
}
for(unsigned int i = 0; i < fcn.temporaries.size(); i ++)
{
m_os << indent() << "let tmp$" << i << ": " << fcn.temporaries[i] << ";\n";
}
#define FMT_M(x) FMT_CB(os, this->fmt_val(os,x);)
for(unsigned int i = 0; i < fcn.blocks.size(); i ++)
{
const auto& block = fcn.blocks[i];
m_os << indent() << "bb" << i << ": {\n";
inc_indent();
for(const auto& stmt : block.statements)
{
m_os << indent();
TU_MATCHA( (stmt), (e),
(Assign,
m_os << FMT_M(e.dst) << " = " << FMT_M(e.src) << ";\n";
),
(Drop,
m_os << "drop(" << FMT_M(e.slot) << ");\n";
)
)
}
m_os << indent();
TU_MATCHA( (block.terminator), (e),
(Incomplete,
m_os << "INVALID;\n";
),
(Return,
m_os << "return;\n";
),
(Diverge,
m_os << "diverge;\n";
),
(Goto,
m_os << "goto bb" << e << ";\n";
),
(Panic,
m_os << "panic bb" << e.dst << ";\n";
),
(If,
m_os << "if " << FMT_M(e.cond) << " { goto bb" << e.bb0 << "; } else { goto bb" << e.bb1 << "; }\n";
),
(Switch,
m_os << "switch " << FMT_M(e.val) << " {";
for(unsigned int j = 0; j < e.targets.size(); j ++)
m_os << j << " => bb" << e.targets[j] << ", ";
m_os << "}\n";
),
(Call,
m_os << FMT_M(e.ret_val) << " = (" << FMT_M(e.fcn_val) << ")( ";
for(const auto& arg : e.args)
m_os << FMT_M(arg) << ", ";
m_os << ") goto bb" << e.ret_block << " else bb" << e.panic_block << "\n";
)
)
dec_indent();
m_os << indent() << "}\n";
m_os.flush();
}
#undef FMT
}
void fmt_val(::std::ostream& os, const ::MIR::LValue& lval) {
TU_MATCHA( (lval), (e),
(Variable,
os << "_#" << e;
),
(Temporary,
os << "tmp$" << e.idx;
),
(Argument,
os << "arg$" << e.idx;
),
(Static,
os << e;
),
(Return,
os << "RETURN";
),
(Field,
os << "(";
fmt_val(os, *e.val);
os << ")." << e.field_index;
),
(Deref,
os << "*";
fmt_val(os, *e.val);
),
(Index,
os << "(";
fmt_val(os, *e.val);
os << ")[";
fmt_val(os, *e.idx);
os << "]";
),
(Downcast,
fmt_val(os, *e.val);
os << " as variant" << e.variant_index;
)
)
}
void fmt_val(::std::ostream& os, const ::MIR::RValue& rval) {
TU_MATCHA( (rval), (e),
(Use,
fmt_val(os, e);
),
(Constant,
TU_MATCHA( (e), (ce),
(Int,
os << ce;
),
(Uint,
os << "0x" << ::std::hex << ce << ::std::dec;
),
(Float,
os << ce;
),
(Bool,
os << (ce ? "true" : "false");
),
(Bytes,
os << "b\"" << ce << "\"";
),
(StaticString,
os << "\"" << ce << "\"";
),
(ItemAddr,
os << "addr " << ce;
)
)
),
(SizedArray,
os << "[";
fmt_val(os, e.val);
os << ";" << e.count << "]";
),
(Borrow,
os << "&";
//os << e.region;
switch(e.type) {
case ::HIR::BorrowType::Shared: break;
case ::HIR::BorrowType::Unique: os << "mut "; break;
case ::HIR::BorrowType::Owned: os << "move "; break;
}
os << "(";
fmt_val(os, e.val);
os << ")";
),
(Cast,
os << "(";
fmt_val(os, e.val);
os << ") as " << e.type;
),
(BinOp,
switch(e.op)
{
case ::MIR::eBinOp::ADD: os << "ADD"; break;
case ::MIR::eBinOp::SUB: os << "SUB"; break;
case ::MIR::eBinOp::MUL: os << "MUL"; break;
case ::MIR::eBinOp::DIV: os << "DIV"; break;
case ::MIR::eBinOp::MOD: os << "MOD"; break;
case ::MIR::eBinOp::ADD_OV: os << "ADD_OV"; break;
case ::MIR::eBinOp::SUB_OV: os << "SUB_OV"; break;
case ::MIR::eBinOp::MUL_OV: os << "MUL_OV"; break;
case ::MIR::eBinOp::DIV_OV: os << "DIV_OV"; break;
//case ::MIR::eBinOp::MOD_OV: os << "MOD_OV"; break;
case ::MIR::eBinOp::BIT_OR : os << "BIT_OR"; break;
case ::MIR::eBinOp::BIT_AND: os << "BIT_AND"; break;
case ::MIR::eBinOp::BIT_XOR: os << "BIT_XOR"; break;
case ::MIR::eBinOp::BIT_SHR: os << "BIT_SHR"; break;
case ::MIR::eBinOp::BIT_SHL: os << "BIT_SHL"; break;
case ::MIR::eBinOp::EQ: os << "EQ"; break;
case ::MIR::eBinOp::NE: os << "NE"; break;
case ::MIR::eBinOp::GT: os << "GT"; break;
case ::MIR::eBinOp::GE: os << "GE"; break;
case ::MIR::eBinOp::LT: os << "LT"; break;
case ::MIR::eBinOp::LE: os << "LE"; break;
}
os << "(";
fmt_val(os, e.val_l);
os << ", ";
fmt_val(os, e.val_r);
os << ")";
),
(UniOp,
switch(e.op)
{
case ::MIR::eUniOp::INV: os << "INV"; break;
case ::MIR::eUniOp::NEG: os << "NEG"; break;
}
os << "(";
fmt_val(os, e.val);
os << ")";
),
(DstMeta,
os << "META(";
fmt_val(os, e.val);
os << ")";
),
(MakeDst,
os << "DST(";
fmt_val(os, e.ptr_val);
os << ", ";
fmt_val(os, e.meta_val);
os << ")";
),
(Tuple,
os << "(";
for(const auto& v : e.vals) {
fmt_val(os, v);
os << ", ";
}
os << ")";
),
(Array,
os << "[";
for(const auto& v : e.vals) {
fmt_val(os, v);
os << ", ";
}
os << "]";
),
(Struct,
os << e.path << " { ";
for(const auto& v : e.vals) {
fmt_val(os, v);
os << ", ";
}
os << "}";
)
)
}
private:
RepeatLitStr indent() const {
return RepeatLitStr { " ", static_cast<int>(m_indent_level) };
}
void inc_indent() {
m_indent_level ++;
}
void dec_indent() {
m_indent_level --;
}
};
}
void MIR_Dump(::std::ostream& sink, const ::HIR::Crate& crate)
{
TreeVisitor tv { sink };
tv.visit_crate( const_cast< ::HIR::Crate&>(crate) );
}
<|endoftext|>
|
<commit_before>/*
* OtaLogger.hpp
* Wraps ArduinoOTA into a class and shows the OTA
* status on serial or an OLED display.
*
* Version: 1.0
* Author: Lübbe Onken (http://github.com/luebbe)
*/
#ifndef SRC_OTA_H
#define SRC_OTA_H
#include <Homie.h> // used for logger output
#include <OLEDDisplay.h> // used for display output
#include <ArduinoOTA.h>
// -----------------------------------------------------------------------------
// OTA info via Homie logger
// -----------------------------------------------------------------------------
class OtaLogger {
private:
protected:
String getErrorMessage(ota_error_t error);
public:
OtaLogger();
virtual void setup(uint16_t port = 8266, const char *password = "");
virtual void loop();
virtual void onStart();
virtual void onEnd();
virtual void onProgress(unsigned int progress, unsigned int total);
virtual void onError(ota_error_t error);
};
// -----------------------------------------------------------------------------
// OTA info via OLED Display
// -----------------------------------------------------------------------------
class OtaDisplay : public OtaLogger {
private:
OLEDDisplay *_display;
protected:
public:
OtaDisplay(OLEDDisplay *display);
void setup(uint16_t port = 8266, const char *password = "") override;
void onEnd();
void onProgress(unsigned int progress, unsigned int total) override;
};
#endif /* end of include guard: SRC_OTA_H */
<commit_msg>Move the on* Event handlers into the protected section<commit_after>/*
* OtaLogger.hpp
* Wraps ArduinoOTA into a class and shows the OTA
* status on serial or an OLED display.
*
* Version: 1.0
* Author: Lübbe Onken (http://github.com/luebbe)
*/
#ifndef SRC_OTA_H
#define SRC_OTA_H
#include <Homie.h> // used for logger output
#include <OLEDDisplay.h> // used for display output
#include <ArduinoOTA.h>
// -----------------------------------------------------------------------------
// OTA info via Homie logger
// -----------------------------------------------------------------------------
class OtaLogger {
private:
protected:
String getErrorMessage(ota_error_t error);
virtual void onStart();
virtual void onEnd();
virtual void onProgress(unsigned int progress, unsigned int total);
virtual void onError(ota_error_t error);
public:
OtaLogger();
virtual void setup(uint16_t port = 8266, const char *password = "");
virtual void loop();
};
// -----------------------------------------------------------------------------
// OTA info via OLED Display
// -----------------------------------------------------------------------------
class OtaDisplay : public OtaLogger {
private:
OLEDDisplay *_display;
protected:
void onEnd();
void onProgress(unsigned int progress, unsigned int total) override;
public:
OtaDisplay(OLEDDisplay *display);
void setup(uint16_t port = 8266, const char *password = "") override;
};
#endif /* end of include guard: SRC_OTA_H */
<|endoftext|>
|
<commit_before>#include "pjobrunnernetworkscanner.h"
#include <QtNetwork>
#include "pjobrunnersessionwrapper.h"
#include <iostream>
QList<PJobRunnerSessionWrapper*> PJobRunnerNetworkScanner::s_found_sessions;
bool PJobRunnerNetworkScanner::s_blocking_scan = false;
PJobRunnerNetworkScanner::PJobRunnerNetworkScanner()
: m_port(23023)
{
qRegisterMetaType<QHostAddress>("QHostAddress");
}
void PJobRunnerNetworkScanner::run(){
scan();
}
QList<PJobRunnerSessionWrapper*> PJobRunnerNetworkScanner::do_blocking_scan(){
s_found_sessions.clear();
s_blocking_scan = true;
PJobRunnerNetworkScanner scanner;
scanner.scan();
s_blocking_scan = false;
return s_found_sessions;
}
void PJobRunnerNetworkScanner::scan(){
foreach(const QNetworkInterface& interface, QNetworkInterface::allInterfaces()){
foreach(const QNetworkAddressEntry& address_entry, interface.addressEntries()){
quint32 netmask = address_entry.netmask().toIPv4Address();
quint32 local_ip = address_entry.ip().toIPv4Address();
quint32 address_to_try = (local_ip & netmask) + 1;
//quint32 inv_netmask = ~netmask;
if(interface.humanReadableName() == "lo"){
std::cout << "Skipping interface \"lo\"." << std::endl;
continue;
}
if(!interface.isValid()){
std::cout << "Skipping interface \"" << interface.humanReadableName().toStdString() << "\"." << std::endl;
continue;
}
if(address_entry.ip().protocol() != QAbstractSocket::IPv4Protocol){
std::cout << "Skipping non-IPv4 interface." << std::endl;
continue;
}
std::cout << "Probing interface " << interface.humanReadableName().toStdString() << std::endl;
std::cout << "Local address is " << interface.hardwareAddress().toStdString() << std::endl;
std::cout << "Netmask: " << address_entry.netmask().toString().toStdString() << std::endl;
std::cout << "Searching local network..." << std::endl;
while((address_to_try & netmask) == (local_ip & netmask)){
std::cout << "\r" << QHostAddress(address_to_try).toString().toStdString();
std::cout.flush();
emit probing_host(QHostAddress(address_to_try));
PJobRunnerSessionWrapper* session = new PJobRunnerSessionWrapper(QHostAddress(address_to_try), 200);
if(session->is_valid()) found(session);
else delete session;
address_to_try++;
}
}
}
emit finished_scanning();
}
void PJobRunnerNetworkScanner::found(PJobRunnerSessionWrapper* session){
emit found_pjob_runner(session);
if(s_blocking_scan){
s_found_sessions.append(session);
std::cout << "Found PJobRunner on " << session->peer().toString().toStdString() << "!" << std::endl;
}
}
<commit_msg>PJobClient network scanner: omit localhost interface.<commit_after>#include "pjobrunnernetworkscanner.h"
#include <QtNetwork>
#include "pjobrunnersessionwrapper.h"
#include <iostream>
QList<PJobRunnerSessionWrapper*> PJobRunnerNetworkScanner::s_found_sessions;
bool PJobRunnerNetworkScanner::s_blocking_scan = false;
PJobRunnerNetworkScanner::PJobRunnerNetworkScanner()
: m_port(23023)
{
qRegisterMetaType<QHostAddress>("QHostAddress");
}
void PJobRunnerNetworkScanner::run(){
scan();
}
QList<PJobRunnerSessionWrapper*> PJobRunnerNetworkScanner::do_blocking_scan(){
s_found_sessions.clear();
s_blocking_scan = true;
PJobRunnerNetworkScanner scanner;
scanner.scan();
s_blocking_scan = false;
return s_found_sessions;
}
void PJobRunnerNetworkScanner::scan(){
foreach(const QNetworkInterface& interface, QNetworkInterface::allInterfaces()){
foreach(const QNetworkAddressEntry& address_entry, interface.addressEntries()){
quint32 netmask = address_entry.netmask().toIPv4Address();
quint32 local_ip = address_entry.ip().toIPv4Address();
quint32 address_to_try = (local_ip & netmask) + 1;
//quint32 inv_netmask = ~netmask;
if(interface.humanReadableName() == "lo"){
std::cout << "Skipping interface \"lo\"." << std::endl;
continue;
}
if(!interface.isValid()){
std::cout << "Skipping interface \"" << interface.humanReadableName().toStdString() << "\"." << std::endl;
continue;
}
if(address_entry.ip().protocol() != QAbstractSocket::IPv4Protocol){
std::cout << "Skipping non-IPv4 interface." << std::endl;
continue;
}
if(address_entry.ip() == QHostAddress::LocalHost){
std::cout << "Skipping loopback interface." << std::endl;
continue;
}
std::cout << "Probing interface " << interface.humanReadableName().toStdString() << std::endl;
std::cout << "Local address is " << interface.hardwareAddress().toStdString() << std::endl;
std::cout << "Netmask: " << address_entry.netmask().toString().toStdString() << std::endl;
std::cout << "Searching local network..." << std::endl;
while((address_to_try & netmask) == (local_ip & netmask)){
std::cout << "\r" << QHostAddress(address_to_try).toString().toStdString();
std::cout.flush();
emit probing_host(QHostAddress(address_to_try));
PJobRunnerSessionWrapper* session = new PJobRunnerSessionWrapper(QHostAddress(address_to_try), 200);
if(session->is_valid()) found(session);
else delete session;
address_to_try++;
}
}
}
emit finished_scanning();
}
void PJobRunnerNetworkScanner::found(PJobRunnerSessionWrapper* session){
emit found_pjob_runner(session);
if(s_blocking_scan){
s_found_sessions.append(session);
std::cout << "Found PJobRunner on " << session->peer().toString().toStdString() << "!" << std::endl;
}
}
<|endoftext|>
|
<commit_before>#include "pjobrunnersessionwrapper.h"
#include <QtCore/QRegExp>
#include <iostream>
PJobRunnerSessionWrapper::PJobRunnerSessionWrapper(QHostAddress hostname, long timeout)
: m_peer(hostname)
{
m_valid = false;
m_socket.connectToHost(hostname, 23023);
if(!m_socket.waitForConnected(timeout)) return;
send("hello\n");
if(!m_socket.waitForBytesWritten(10000)) return;
if(!m_socket.waitForReadyRead(10000)) return;
QString hello_string;
do{
hello_string.append(m_socket.readAll());
}while(m_socket.waitForReadyRead(1000) && hello_string.size() < 1024);
received(hello_string);
if(hello_string.isEmpty()) return;
QRegExp reg_exp("This is ([^\\s]*) \\(.*\\) version ([^\\s]*) running on ([^\\s]*) \\(([^\\s]*)\\)");
if(reg_exp.indexIn(hello_string) == -1) return;
m_version = reg_exp.cap(2);
m_platform = reg_exp.cap(4);
m_hostname = reg_exp.cap(3);
m_valid = true;
}
PJobRunnerSessionWrapper::~PJobRunnerSessionWrapper(){
if(m_socket.state() == QAbstractSocket::ConnectedState){
send("exit()");
m_socket.waitForBytesWritten(100);
m_socket.close();
m_socket.waitForDisconnected(1000);
}
}
bool PJobRunnerSessionWrapper::is_valid(){
return m_valid;
}
QString PJobRunnerSessionWrapper::platform(){
return m_platform;
}
QString PJobRunnerSessionWrapper::version(){
return m_version;
}
QString PJobRunnerSessionWrapper::hostname(){
return m_hostname;
}
bool PJobRunnerSessionWrapper::upload_pjobfile(const QByteArray& content){
send("prepare_push_connection()\n");
if(!m_socket.waitForReadyRead(10000))return false;
QString line = m_socket.readLine();
received(line);
quint32 port = line.toInt();
std::cout << "Opening data connection to port " << port << "... ";
QTcpSocket push_connection;
push_connection.connectToHost(m_socket.peerAddress(), port);
if(!push_connection.waitForConnected(10000))return false;
std::cout << " done!" << std::endl;
qint64 bytes_send = 0;
qint64 all_bytes = content.size();
const char* data = content.data();
qint64 transfer_unit_size = 1024;
while(bytes_send != all_bytes){
qint64 bytes_written = push_connection.write(data, std::min(transfer_unit_size,all_bytes-bytes_send));
data += bytes_written;
bytes_send += bytes_written;
push_connection.flush();
push_connection.waitForBytesWritten();
std::cout << "\r" << bytes_send * 100 / all_bytes << "% done... ";
}
std::cout << std::endl;
push_connection.close();
push_connection.waitForDisconnected(10000);
std::cout << content.size() << " bytes uploaded!" << std::endl;
return true;
}
bool PJobRunnerSessionWrapper::download_results(QByteArray& data){
send("prepare_pull_connection_for_results()\n");
if(!m_socket.waitForReadyRead(10000)) exit(0);
QString line = m_socket.readLine();
received(line);
QString all = m_socket.readAll();
received(all);
quint32 port = line.toInt();
std::cout << " from port " << port << "...";
QTcpSocket pull_connection;
pull_connection.connectToHost(m_socket.peerAddress(), port);
if(!pull_connection.waitForConnected(10000)) exit(0);
if(!pull_connection.waitForReadyRead(10000)) exit(0);
while(true){
if(pull_connection.state() == QTcpSocket::UnconnectedState){
while(pull_connection.bytesAvailable())
data.append(pull_connection.readAll());
break;
}
if(pull_connection.waitForReadyRead(10)){
data.append(pull_connection.readAll());
}
}
return true;
}
bool PJobRunnerSessionWrapper::set_parameter(const QString& name, const double& value){
return false;
}
bool PJobRunnerSessionWrapper::run_job(){
send("open_pjob_from_received_data()\n");
if(!m_socket.waitForReadyRead(10000))exit(0);
send("run_job()\n");
bool ok=false;
bool want_exit=false;
while(!want_exit){
if(!m_socket.waitForReadyRead(10)) continue;
QString line = m_socket.readAll();
received(line);
if(line.contains("Process exited normally.")){ ok = true; want_exit = true; }
if(line.contains("Process crashed!")) want_exit = true;
std::cout << line.toStdString() << std::endl;
}
while(m_socket.waitForReadyRead(1000)){
received(m_socket.readAll());
}
std::cout << std::endl;
return ok;
}
bool PJobRunnerSessionWrapper::wait_for_job_finished(){
return false;
}
QHostAddress PJobRunnerSessionWrapper::peer(){
return m_peer;
}
bool PJobRunnerSessionWrapper::enqueue(){
send("enqueue();\n");
if(!m_socket.waitForReadyRead(10000)) return false;
QString line = m_socket.readAll();
received(line);
if(line.contains("Successfully added to queue.")) return true;
else return false;
}
bool PJobRunnerSessionWrapper::wait_till_its_your_turn(){
QString buffer;
while(m_socket.isReadable()){
if(m_socket.waitForReadyRead(5000)){
QByteArray read = m_socket.readAll();
buffer.append(read);
received(read);
if(buffer.contains("It's your turn now! Go!")) return true;
}
}
return false;
}
int PJobRunnerSessionWrapper::max_process_count(){
send("max_process_count();\n");
if(!m_socket.waitForReadyRead(10000)) throw QString("connection timeout");
bool ok;
QString line = m_socket.readAll();
received(line);
int value = line.toInt(&ok);
if(ok) return value;
else throw QString("connection problem");
}
int PJobRunnerSessionWrapper::process_count(){
send("process_count();\n");
if(!m_socket.waitForReadyRead(10000)) throw QString("connection timeout");
bool ok;
QString line = m_socket.readAll();
received(line);
int value = line.toInt(&ok);
if(ok) return value;
else throw QString("connection problem");
}
void PJobRunnerSessionWrapper::set_debug(bool b){
m_debug_mode = b;
}
void PJobRunnerSessionWrapper::send(const QString& data){
m_socket.write(data.toUtf8());
if(m_debug_mode) emit debug_out(QString("to %2 >>> %1").arg(data).arg(m_peer.toString()));
}
void PJobRunnerSessionWrapper::received(const QString& data){
if(m_debug_mode) emit debug_out(QString("from %2 <<< %1").arg(data).arg(m_peer.toString()));
}
<commit_msg>PJobClient: run_job() and wait_for_job_finished() fixed.<commit_after>#include "pjobrunnersessionwrapper.h"
#include <QtCore/QRegExp>
#include <iostream>
PJobRunnerSessionWrapper::PJobRunnerSessionWrapper(QHostAddress hostname, long timeout)
: m_peer(hostname)
{
m_valid = false;
m_socket.connectToHost(hostname, 23023);
if(!m_socket.waitForConnected(timeout)) return;
send("hello\n");
if(!m_socket.waitForBytesWritten(10000)) return;
if(!m_socket.waitForReadyRead(10000)) return;
QString hello_string;
do{
hello_string.append(m_socket.readAll());
}while(m_socket.waitForReadyRead(1000) && hello_string.size() < 1024);
received(hello_string);
if(hello_string.isEmpty()) return;
QRegExp reg_exp("This is ([^\\s]*) \\(.*\\) version ([^\\s]*) running on ([^\\s]*) \\(([^\\s]*)\\)");
if(reg_exp.indexIn(hello_string) == -1) return;
m_version = reg_exp.cap(2);
m_platform = reg_exp.cap(4);
m_hostname = reg_exp.cap(3);
m_valid = true;
}
PJobRunnerSessionWrapper::~PJobRunnerSessionWrapper(){
if(m_socket.state() == QAbstractSocket::ConnectedState){
send("exit()");
m_socket.waitForBytesWritten(100);
m_socket.close();
m_socket.waitForDisconnected(1000);
}
}
bool PJobRunnerSessionWrapper::is_valid(){
return m_valid;
}
QString PJobRunnerSessionWrapper::platform(){
return m_platform;
}
QString PJobRunnerSessionWrapper::version(){
return m_version;
}
QString PJobRunnerSessionWrapper::hostname(){
return m_hostname;
}
bool PJobRunnerSessionWrapper::upload_pjobfile(const QByteArray& content){
send("prepare_push_connection()\n");
if(!m_socket.waitForReadyRead(10000))return false;
QString line = m_socket.readLine();
received(line);
quint32 port = line.toInt();
std::cout << "Opening data connection to port " << port << "... ";
QTcpSocket push_connection;
push_connection.connectToHost(m_socket.peerAddress(), port);
if(!push_connection.waitForConnected(10000))return false;
std::cout << " done!" << std::endl;
qint64 bytes_send = 0;
qint64 all_bytes = content.size();
const char* data = content.data();
qint64 transfer_unit_size = 1024;
while(bytes_send != all_bytes){
qint64 bytes_written = push_connection.write(data, std::min(transfer_unit_size,all_bytes-bytes_send));
data += bytes_written;
bytes_send += bytes_written;
push_connection.flush();
push_connection.waitForBytesWritten();
std::cout << "\r" << bytes_send * 100 / all_bytes << "% done... ";
}
std::cout << std::endl;
push_connection.close();
push_connection.waitForDisconnected(10000);
std::cout << content.size() << " bytes uploaded!" << std::endl;
return true;
}
bool PJobRunnerSessionWrapper::download_results(QByteArray& data){
send("prepare_pull_connection_for_results()\n");
if(!m_socket.waitForReadyRead(10000)) exit(0);
QString line = m_socket.readLine();
received(line);
QString all = m_socket.readAll();
received(all);
quint32 port = line.toInt();
std::cout << " from port " << port << "...";
QTcpSocket pull_connection;
pull_connection.connectToHost(m_socket.peerAddress(), port);
if(!pull_connection.waitForConnected(10000)) exit(0);
if(!pull_connection.waitForReadyRead(10000)) exit(0);
while(true){
if(pull_connection.state() == QTcpSocket::UnconnectedState){
while(pull_connection.bytesAvailable())
data.append(pull_connection.readAll());
break;
}
if(pull_connection.waitForReadyRead(10)){
data.append(pull_connection.readAll());
}
}
return true;
}
bool PJobRunnerSessionWrapper::set_parameter(const QString& name, const double& value){
return false;
}
bool PJobRunnerSessionWrapper::run_job(){
send("open_pjob_from_received_data()\n");
if(!m_socket.waitForReadyRead(10000))exit(0);
send("run_job()\n");
if(!m_socket.waitForReadyRead(10000)) return false;
while(m_socket.waitForReadyRead(1000) && m_socket.state() == QTcpSocket::ConnectedState){
QString line = m_socket.readAll();
received(line);
if(line.contains("Starting process:")) return true;
if(line.contains("Starting process:")) return true;
if(line.contains("Can't")) return false;
}
return false;
}
bool PJobRunnerSessionWrapper::wait_for_job_finished(){
bool ok=false;
bool want_exit=false;
while(!want_exit && m_socket.state() == QTcpSocket::ConnectedState){
if(!m_socket.waitForReadyRead(10)) continue;
QString line = m_socket.readAll();
received(line);
if(line.contains("Process exited normally.")){ ok = true; want_exit = true; }
if(line.contains("Process crashed!")) want_exit = true;
}
while(m_socket.waitForReadyRead(1000)){
received(m_socket.readAll());
}
return ok;
}
QHostAddress PJobRunnerSessionWrapper::peer(){
return m_peer;
}
bool PJobRunnerSessionWrapper::enqueue(){
send("enqueue();\n");
if(!m_socket.waitForReadyRead(10000)) return false;
QString line = m_socket.readAll();
received(line);
if(line.contains("Successfully added to queue.")) return true;
else return false;
}
bool PJobRunnerSessionWrapper::wait_till_its_your_turn(){
QString buffer;
while(m_socket.isReadable()){
if(m_socket.waitForReadyRead(5000)){
QByteArray read = m_socket.readAll();
buffer.append(read);
received(read);
if(buffer.contains("It's your turn now! Go!")) return true;
}
}
return false;
}
int PJobRunnerSessionWrapper::max_process_count(){
send("max_process_count();\n");
if(!m_socket.waitForReadyRead(10000)) throw QString("connection timeout");
bool ok;
QString line = m_socket.readAll();
received(line);
int value = line.toInt(&ok);
if(ok) return value;
else throw QString("connection problem");
}
int PJobRunnerSessionWrapper::process_count(){
send("process_count();\n");
if(!m_socket.waitForReadyRead(10000)) throw QString("connection timeout");
bool ok;
QString line = m_socket.readAll();
received(line);
int value = line.toInt(&ok);
if(ok) return value;
else throw QString("connection problem");
}
void PJobRunnerSessionWrapper::set_debug(bool b){
m_debug_mode = b;
}
void PJobRunnerSessionWrapper::send(const QString& data){
m_socket.write(data.toUtf8());
if(m_debug_mode) emit debug_out(QString("to %2 >>> %1").arg(data).arg(m_peer.toString()));
}
void PJobRunnerSessionWrapper::received(const QString& data){
if(m_debug_mode) emit debug_out(QString("from %2 <<< %1").arg(data).arg(m_peer.toString()));
}
<|endoftext|>
|
<commit_before>#include "musicdownloadquerymgartistthread.h"
#include "musicnumberutils.h"
#///QJson import
#include "qjson/parser.h"
MusicDownLoadQueryMGArtistThread::MusicDownLoadQueryMGArtistThread(QObject *parent)
: MusicDownLoadQueryArtistThread(parent)
{
m_queryServer = "Migu";
}
QString MusicDownLoadQueryMGArtistThread::getClassName()
{
return staticMetaObject.className();
}
void MusicDownLoadQueryMGArtistThread::startToSearch(const QString &artist)
{
if(!m_manager)
{
return;
}
M_LOGGER_INFO(QString("%1 startToSearch %2").arg(getClassName()).arg(artist));
QUrl musicUrl = MusicUtils::Algorithm::mdII(MG_ARTIST_URL, false).arg(artist);
deleteAll();
m_interrupt = true;
m_searchText = artist;
qDebug() << musicUrl;
QNetworkRequest request;
request.setUrl(musicUrl);
request.setRawHeader("Content-Type", "application/x-www-form-urlencoded");
request.setRawHeader("User-Agent", MusicUtils::Algorithm::mdII(MG_UA_URL_1, ALG_UA_KEY, false).toUtf8());
#ifndef QT_NO_SSL
QSslConfiguration sslConfig = request.sslConfiguration();
sslConfig.setPeerVerifyMode(QSslSocket::VerifyNone);
request.setSslConfiguration(sslConfig);
#endif
m_reply = m_manager->get(request);
connect(m_reply, SIGNAL(finished()), SLOT(downLoadFinished()));
connect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(replyError(QNetworkReply::NetworkError)));
}
void MusicDownLoadQueryMGArtistThread::downLoadFinished()
{
if(!m_reply || !m_manager)
{
deleteAll();
return;
}
M_LOGGER_INFO(QString("%1 downLoadFinished").arg(getClassName()));
emit clearAllItems(); ///Clear origin items
m_musicSongInfos.clear(); ///Empty the last search to songsInfo
m_interrupt = false;
if(m_reply->error() == QNetworkReply::NoError)
{
QByteArray bytes = m_reply->readAll(); ///Get all the data obtained by request
QJson::Parser parser;
bool ok;
QVariant data = parser.parse(bytes, &ok);
if(ok)
{
QVariantMap value = data.toMap();
if(value["code"].toString() == "000000" && value.contains("songs"))
{
bool artistFlag = false;
QString description = value["detail"].toString();
////////////////////////////////////////////////////////////
QVariantList datas = value["songs"].toList();
foreach(const QVariant &var, datas)
{
if(var.isNull())
{
continue;
}
value = var.toMap();
MusicObject::MusicSongInformation musicInfo;
musicInfo.m_singerName = value["singer"].toString();
musicInfo.m_songName = value["title"].toString();
musicInfo.m_timeLength = "-";
musicInfo.m_songId = value["contentid"].toString();
musicInfo.m_artistId = value["singerid"].toString();
musicInfo.m_albumId = value["albumid"].toString();
musicInfo.m_lrcUrl = MusicUtils::Algorithm::mdII(MG_SONG_LRC_URL, false).arg(musicInfo.m_songId);
musicInfo.m_smallPicUrl = value["albumImg"].toString();
musicInfo.m_albumName = value["album"].toString();
if(m_interrupt || !m_manager || m_stateCode != MusicNetworkAbstract::Init) return;
readFromMusicSongAttribute(&musicInfo, value, m_searchQuality, true);
if(m_interrupt || !m_manager || m_stateCode != MusicNetworkAbstract::Init) return;
if(musicInfo.m_songAttrs.isEmpty())
{
continue;
}
////////////////////////////////////////////////////////////
if(!findUrlFileSize(&musicInfo.m_songAttrs)) return;
////////////////////////////////////////////////////////////
if(!artistFlag)
{
artistFlag = true;
MusicPlaylistItem info;
info.m_description = description;
info.m_id = m_searchText;
info.m_name = musicInfo.m_singerName;
info.m_coverUrl = musicInfo.m_smallPicUrl;
emit createArtistInfoItem(info);
}
////////////////////////////////////////////////////////////
MusicSearchedItem item;
item.m_songName = musicInfo.m_songName;
item.m_singerName = musicInfo.m_singerName;
item.m_albumName = musicInfo.m_albumName;
item.m_time = musicInfo.m_timeLength;
item.m_type = mapQueryServerString();
emit createSearchedItems(item);
m_musicSongInfos << musicInfo;
}
}
}
}
emit downLoadDataChanged(QString());
deleteAll();
M_LOGGER_INFO(QString("%1 downLoadFinished deleteAll").arg(getClassName()));
}
<commit_msg>Clean code[548321]<commit_after>#include "musicdownloadquerymgartistthread.h"
#include "musicnumberutils.h"
#///QJson import
#include "qjson/parser.h"
MusicDownLoadQueryMGArtistThread::MusicDownLoadQueryMGArtistThread(QObject *parent)
: MusicDownLoadQueryArtistThread(parent)
{
m_queryServer = "Migu";
}
QString MusicDownLoadQueryMGArtistThread::getClassName()
{
return staticMetaObject.className();
}
void MusicDownLoadQueryMGArtistThread::startToSearch(const QString &artist)
{
if(!m_manager)
{
return;
}
M_LOGGER_INFO(QString("%1 startToSearch %2").arg(getClassName()).arg(artist));
QUrl musicUrl = MusicUtils::Algorithm::mdII(MG_ARTIST_URL, false).arg(artist);
deleteAll();
m_interrupt = true;
m_searchText = artist;
QNetworkRequest request;
request.setUrl(musicUrl);
request.setRawHeader("Content-Type", "application/x-www-form-urlencoded");
request.setRawHeader("User-Agent", MusicUtils::Algorithm::mdII(MG_UA_URL_1, ALG_UA_KEY, false).toUtf8());
#ifndef QT_NO_SSL
QSslConfiguration sslConfig = request.sslConfiguration();
sslConfig.setPeerVerifyMode(QSslSocket::VerifyNone);
request.setSslConfiguration(sslConfig);
#endif
m_reply = m_manager->get(request);
connect(m_reply, SIGNAL(finished()), SLOT(downLoadFinished()));
connect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(replyError(QNetworkReply::NetworkError)));
}
void MusicDownLoadQueryMGArtistThread::downLoadFinished()
{
if(!m_reply || !m_manager)
{
deleteAll();
return;
}
M_LOGGER_INFO(QString("%1 downLoadFinished").arg(getClassName()));
emit clearAllItems(); ///Clear origin items
m_musicSongInfos.clear(); ///Empty the last search to songsInfo
m_interrupt = false;
if(m_reply->error() == QNetworkReply::NoError)
{
QByteArray bytes = m_reply->readAll(); ///Get all the data obtained by request
QJson::Parser parser;
bool ok;
QVariant data = parser.parse(bytes, &ok);
if(ok)
{
QVariantMap value = data.toMap();
if(value["code"].toString() == "000000" && value.contains("songs"))
{
bool artistFlag = false;
QString description = value["detail"].toString();
////////////////////////////////////////////////////////////
QVariantList datas = value["songs"].toList();
foreach(const QVariant &var, datas)
{
if(var.isNull())
{
continue;
}
value = var.toMap();
MusicObject::MusicSongInformation musicInfo;
musicInfo.m_singerName = value["singer"].toString();
musicInfo.m_songName = value["title"].toString();
musicInfo.m_timeLength = "-";
musicInfo.m_songId = value["contentid"].toString();
musicInfo.m_artistId = value["singerid"].toString();
musicInfo.m_albumId = value["albumid"].toString();
musicInfo.m_lrcUrl = MusicUtils::Algorithm::mdII(MG_SONG_LRC_URL, false).arg(musicInfo.m_songId);
musicInfo.m_smallPicUrl = value["albumImg"].toString();
musicInfo.m_albumName = value["album"].toString();
if(m_interrupt || !m_manager || m_stateCode != MusicNetworkAbstract::Init) return;
readFromMusicSongAttribute(&musicInfo, value, m_searchQuality, true);
if(m_interrupt || !m_manager || m_stateCode != MusicNetworkAbstract::Init) return;
if(musicInfo.m_songAttrs.isEmpty())
{
continue;
}
////////////////////////////////////////////////////////////
if(!findUrlFileSize(&musicInfo.m_songAttrs)) return;
////////////////////////////////////////////////////////////
if(!artistFlag)
{
artistFlag = true;
MusicPlaylistItem info;
info.m_description = description;
info.m_id = m_searchText;
info.m_name = musicInfo.m_singerName;
info.m_coverUrl = musicInfo.m_smallPicUrl;
emit createArtistInfoItem(info);
}
////////////////////////////////////////////////////////////
MusicSearchedItem item;
item.m_songName = musicInfo.m_songName;
item.m_singerName = musicInfo.m_singerName;
item.m_albumName = musicInfo.m_albumName;
item.m_time = musicInfo.m_timeLength;
item.m_type = mapQueryServerString();
emit createSearchedItems(item);
m_musicSongInfos << musicInfo;
}
}
}
}
emit downLoadDataChanged(QString());
deleteAll();
M_LOGGER_INFO(QString("%1 downLoadFinished deleteAll").arg(getClassName()));
}
<|endoftext|>
|
<commit_before>#include "includes_defines.h"
#include "types.h"
#include "global.h"
#include "utilities.cpp"
#include "load_scenarios.cpp"
#include "heuristic_function.cpp"
#include "custom_encoding.cpp"
#include "encoding_methods.cpp"
extern "C" {
int get_bit(int row, int col){
return ((int) opcodes[row][col]);
}
int get_codes_length(){
return bits;
}
int load_graphs_codes(char *file_in,
char *custom_file_name){
FILE *fp;
int trivial = 0;
int err=0;
int elements;
int min_disp;
if(first){
first = FALSE;
if(temporary_files_creation() != 0){
return -1;
}
}
if( (fpLOG = fopen(LOG,"w")) == NULL){
fprintf(stderr,"Error on opening LOG file for writing.\n");
}
fprintf(fpLOG,WELCOME_STRING);
// memory allocation
fprintf(fpLOG,"Allocating memory for vertex names and graphs...");
g = (GRAPH_TYPE *) malloc(sizeof(GRAPH_TYPE) * scenariosLimit);
fprintf(fpLOG,"DONE\n");
fflush(stdout);
//**********************************************************************
// Building CPOG Part
//**********************************************************************
// loading scenarios
fprintf(fpLOG,"\nOptimal scenarios encoding and CPOG synthesis.\n");
if(loadScenarios(file_in, fp) != 0){
fprintf(stderr,"Loading scenarios failed.\n");
return -1;
}
fprintf(fpLOG,"\n%d scenarios have been loaded.\n", n);
// looking for predicates
if(predicateSearch() != 0){
fprintf(stderr,"Predicate searching failed.\n");
return -1;
}
// looking for non-trivial constraints
if( (fp = fopen(CONSTRAINTS_FILE,"w")) == NULL){
fprintf(stderr,"Error on opening constraints file for writing.\n");
return -1;
}
if(nonTrivialConstraints(fp, &total, &trivial) != 0){
fprintf(stderr,"Non-trivial constraints searching failed.\n");
return -1;
}
fprintf(fpLOG,"\n%d non-trivial encoding constraints found:\n\n", total - trivial);
// writing non-trivial constraints into a file
if( (fp = fopen(TRIVIAL_ENCODING_FILE,"w")) == NULL){
fprintf(stderr,"Error on opening constraints file for writing.\n");
return -1;
}
for(int i = 0; i < total; i++)
if (!encodings[i].trivial) {
fprintf(fp,"%s\n",encodings[i].constraint.c_str());
}
fclose(fp);
fprintf(fpLOG,"\nBuilding conflict graph... ");
if(conflictGraph(&total) != 0){
fprintf(stderr,"Building conflict graph failed.\n");
return -1;
}
fprintf(fpLOG,"DONE.\n");
//**********************************************************************
// Reading encoding set by the user
//**********************************************************************
fprintf(fpLOG,"Reading encodings set... ");
fflush(stdout);
if(read_set_encoding(custom_file_name,n,&bits) != 0){
fprintf(stderr,"Error on reading encoding set.\n");
removeTempFiles();
return -1;
}
fprintf(fpLOG,"DONE\n");
fprintf(fpLOG,"Check correcteness of encoding set... ");
if(check_correctness(custom_file_name,n,tot_enc,bits) != 0){
removeTempFiles();
return -1;
}
fprintf(fpLOG,"DONE\n");
//**********************************************************************
// Variable preparation for encoding
//**********************************************************************
strcpy(file_in,TRIVIAL_ENCODING_FILE);
file_cons = strdup(CONSTRAINTS_FILE);
/*READ NON-TRIVIAL ENCODING FILE*/
fprintf(fpLOG,"Reading non-trivial encoding file... ");
if( (err = read_file(file_in)) ){
fprintf(stderr,"Error occured while reading non-trivial encoding file, error code: %d", err);
removeTempFiles();
return -1;
}
fprintf(fpLOG,"DONE\n");
/*SEED FOR RAND*/
srand(time(NULL));
/*ALLOCATING AND ZEROING DIFFERENCE MATRIX*/
opt_diff = (int**) calloc(n, sizeof(int*));
for(int i=0;i<n;i++)
opt_diff[i] = (int*) calloc(n, sizeof(int));
/*NUMBER OF POSSIBLE ENCODING*/
tot_enc = 1;
for(int i=0;i<bits;i++) tot_enc *= 2;
/*ANALYSIS IF IT'S A PERMUTATION OR A DISPOSITION*/
num_perm = 1;
if (n == tot_enc){
/*PERMUTATION*/
if(!unfix && !SET){
for(int i = 1; i< tot_enc; i++)
num_perm *= i;
}else{
for(int i = 1; i<= tot_enc; i++)
num_perm *= i;
}
fprintf(fpLOG,"Number of possible permutations by fixing first element: %lld\n", num_perm);
}
else{
/*DISPOSITION*/
if(!unfix && !SET){
elements = tot_enc-1;
min_disp = elements - (n- 1) + 1;
}else{
elements = tot_enc;
min_disp = elements - (n) + 1;
}
num_perm = 1;
for(int i=elements; i>= min_disp; i--)
num_perm *= i;
fprintf(fpLOG,"Number of possible dispositions by fixing first element: %lld\n", num_perm);
}
all_perm = num_perm;
// num_perm = EXHAUSTIVE_MAX_PERM;
/*PREPARATION DATA FOR ENCODING PERMUTATIONS*/
enc = (int*) calloc(tot_enc, sizeof(int));
/*First element is fixed*/
if (!unfix && !SET)
enc[0] = 1;
sol = (int*) calloc(tot_enc, sizeof(int));
if (sol == NULL){
fprintf(stderr,"solution variable = null\n");
removeTempFiles();
return -1;
}
/*BUILDING DIFFERENCE MATRIX*/
fprintf(fpLOG,"Building DM (=Difference Matrix)... ");
if( (err = difference_matrix(cpog_count)) ){
fprintf(stderr,"Error occurred while building difference matrix, error code: %d", err);
removeTempFiles();
return -1;
}
fprintf(fpLOG,"DONE\n");
fclose(fpLOG);
removeTempFiles();
return 0;
}
int unload_graphs_codes(){
if(g != NULL) free(g);
if(manual_file != NULL) free(manual_file);
if(manual_file_back != NULL) free(manual_file_back);
if(custom_perm != NULL) free(custom_perm);
if(custom_perm_back != NULL) free(custom_perm_back);
if(opt_diff != NULL) {
for(int i = 0; i<cpog_count; i++)
if(opt_diff[i] != NULL) free(opt_diff[i]);
free(opt_diff);
}
if(perm != NULL) {
for(long long int i = 0; i<num_perm; i++)
if(perm[i] != NULL )free(perm[i]);
free(perm);
}
if(file_cons != NULL) free(file_cons);
if(weights != NULL) free(weights);
if(diff != NULL){
for(int i = 0; i< len_sequence; i++)
if(diff[i] != NULL) free(diff[i]);
free(diff);
}
if(opcodes != NULL){
for(int i = 0; i < cpog_count; i++)
if(opcodes[i] != NULL) free(opcodes[i]);
}
if(enc != NULL) free(enc);
if(sol != NULL) free(sol);
cpog_count = 0;
n = 0;
len_sequence = 0;
// Andrey's tool
if( !eventNames.empty() ) eventNames.clear();
for(int i = 0; i<eventsLimit; i++)
if( !eventNames_str[i].empty() )eventNames_str[i].clear();
for(int i = 0; i<eventsLimit;i++)
if( !eventPredicates[i].empty() )
eventPredicates[i].clear();
if( !scenarioNames.empty() )scenarioNames.clear();
if( !scenarioOpcodes.empty() )scenarioOpcodes.clear();
for(int i = 0; i< eventsLimit; i++)
for(int j = 0; j< predicatesLimit; j++)
if(!ev[i][j].empty()) ev[i][j].clear();
for(int i = 0; i< eventsLimit; i++)
for(int j = 0; j< eventsLimit; j++)
if(!ee[i][j].empty()) ee[i][j].clear();
if(!constraints.empty()) constraints.clear();
if ( !encodings.empty() )encodings.clear();
if ( !cgv.empty() ) cgv.clear();
if ( !cge.empty() ) cge.clear();
if ( !literal.empty() ) literal.clear();
if ( !bestLiteral.empty() ) bestLiteral.clear();
for(int i = 0; i< eventsLimit; i++)
for(int j = 0; j< predicatesLimit; j++)
if(!vConditions[i][j].empty())
vConditions[i][j].clear();
for(int i = 0; i< eventsLimit; i++)
for(int j = 0; j< eventsLimit; j++)
if(!aConditions[i][j].empty())
aConditions[i][j].clear();
return 0;
}
int single_literal_encoding(){
if( (fpLOG = fopen(LOG,"a")) == NULL){
fprintf(stderr,"Error on opening LOG file for appending.\n");
}
fprintf(fpLOG,"Running single-literal encoding.\n");
if(singleLiteralEncoding(total) != 0){
fprintf(stderr,"Single-literal encoding failed.\n");
return -1;
}
if (export_variables(single_literal) != 0){
return -1;
}
fclose(fpLOG);
return 0;
}
int sequential_encoding(){
if( (fpLOG = fopen(LOG,"a")) == NULL){
fprintf(stderr,"Error on opening LOG file for appending.\n");
}
fprintf(fpLOG,"Running Sequential encoding.\n");
if(allocate_encodings_space(1) != 0){
fprintf(stderr,"Sequential encoding failed.\n");
return -1;
}
if(sequentialEncoding() != 0){
fprintf(stderr,"Sequential encoding failed.\n");
return -1;
}
if (export_variables(sequential) != 0){
return -1;
}
fclose(fpLOG);
return 0;
}
int random_encoding(int num_enc){
if( (fpLOG = fopen(LOG,"a")) == NULL){
fprintf(stderr,"Error on opening LOG file for appending.\n");
}
bits = bits_saved;
fprintf(fpLOG,"Running Random encoding.\n");
if(allocate_encodings_space(num_enc) != 0){
fprintf(stderr,"Encoding allocation failed.\n");
return -1;
}
if(randomEncoding() != 0){
fprintf(stderr,"Random encoding failed.\n");
return -1;
}
if(heuristic_choice() != 0) {
fprintf(stderr,"Computing heuristic encoding.\n");
return -1;
}
if (export_variables(randomE) != 0){
return -1;
}
fclose(fpLOG);
return 0;
}
int heuristic_encoding(int num_enc){
if( (fpLOG = fopen(LOG,"a")) == NULL){
fprintf(stderr,"Error on opening LOG file for appending.\n");
}
bits = bits_saved;
if(allocate_encodings_space(num_enc) != 0){
fprintf(stderr,"Encoding allocation failed.\n");
return -1;
}
fprintf(fpLOG,"Running Random generation... ");
if(randomEncoding() != 0){
fprintf(stderr,"Random encoding failed.\n");
return -1;
}
fprintf(fpLOG,"DONE.\n");
fprintf(fpLOG,"Running Heuristic optimisation... ");
if(start_simulated_annealing() != 0){
fprintf(stderr,"Heuristic optimisation failed.\n");
return -1;
}
fprintf(fpLOG,"DONE.\n");
if(heuristic_choice() != 0) {
fprintf(stderr,"Computing heuristic encoding.\n");
return -1;
}
if (export_variables(heuristic) != 0){
return -1;
}
fclose(fpLOG);
return 0;
}
int exhaustive_encoding(int num_enc){
if( (fpLOG = fopen(LOG,"a")) == NULL){
fprintf(stderr,"Error on opening LOG file for appending.\n");
}
if(allocate_encodings_space(num_enc) != 0){
fprintf(stderr,"Encoding allocation failed.\n");
return -1;
}
fprintf(fpLOG,"Running Exhaustive encoding.\n");
if(!unfix && !SET){
//permutation_stdalgo(cpog_count,tot_enc);
fprintf(fpLOG,"Permutation algorithm unconstrained... ");
exhaustiveEncoding(sol,0,enc,cpog_count, tot_enc);
fprintf(fpLOG,"DONE\n");
}else{
fprintf(fpLOG,"Permutation algorithm constrained... ");
exhaustiveEncoding(sol,-1,enc,cpog_count, tot_enc);
fprintf(fpLOG,"DONE\n");
fprintf(fpLOG,"Filtering encoding... ");
filter_encodings(cpog_count, bits, tot_enc);
fprintf(fpLOG,"DONE\n");
}
if(heuristic_choice() != 0) {
fprintf(stderr,"Computing heuristic encoding.\n");
return -1;
}
if (export_variables(exhaustive) != 0){
return -1;
}
fclose(fpLOG);
return 0;
}
}
<commit_msg>test print<commit_after>#include "includes_defines.h"
#include "types.h"
#include "global.h"
#include "utilities.cpp"
#include "load_scenarios.cpp"
#include "heuristic_function.cpp"
#include "custom_encoding.cpp"
#include "encoding_methods.cpp"
extern "C" {
int get_bit(int row, int col){
return ((int) opcodes[row][col]);
}
int get_codes_length(){
return bits;
}
int load_graphs_codes(char *file_in,
char *custom_file_name){
FILE *fp;
int trivial = 0;
int err=0;
int elements;
int min_disp;
printf("1-\n");
if(first){
first = FALSE;
if(temporary_files_creation() != 0){
return -1;
}
}
printf("2-\n");
if( (fpLOG = fopen(LOG,"w")) == NULL){
fprintf(stderr,"Error on opening LOG file for writing.\n");
}
fprintf(fpLOG,WELCOME_STRING);
printf("3-\n");
// memory allocation
fprintf(fpLOG,"Allocating memory for vertex names and graphs...");
g = (GRAPH_TYPE *) malloc(sizeof(GRAPH_TYPE) * scenariosLimit);
fprintf(fpLOG,"DONE\n");
fflush(stdout);
printf("4-\n");
//**********************************************************************
// Building CPOG Part
//**********************************************************************
// loading scenarios
fprintf(fpLOG,"\nOptimal scenarios encoding and CPOG synthesis.\n");
if(loadScenarios(file_in, fp) != 0){
fprintf(stderr,"Loading scenarios failed.\n");
return -1;
}
fprintf(fpLOG,"\n%d scenarios have been loaded.\n", n);
printf("5-\n");
// looking for predicates
if(predicateSearch() != 0){
fprintf(stderr,"Predicate searching failed.\n");
return -1;
}
printf("6-\n");
// looking for non-trivial constraints
if( (fp = fopen(CONSTRAINTS_FILE,"w")) == NULL){
fprintf(stderr,"Error on opening constraints file for writing.\n");
return -1;
}
if(nonTrivialConstraints(fp, &total, &trivial) != 0){
fprintf(stderr,"Non-trivial constraints searching failed.\n");
return -1;
}
fprintf(fpLOG,"\n%d non-trivial encoding constraints found:\n\n", total - trivial);
printf("7-\n");
// writing non-trivial constraints into a file
if( (fp = fopen(TRIVIAL_ENCODING_FILE,"w")) == NULL){
fprintf(stderr,"Error on opening constraints file for writing.\n");
return -1;
}
for(int i = 0; i < total; i++)
if (!encodings[i].trivial) {
fprintf(fp,"%s\n",encodings[i].constraint.c_str());
}
fclose(fp);
printf("8-\n");
fprintf(fpLOG,"\nBuilding conflict graph... ");
if(conflictGraph(&total) != 0){
fprintf(stderr,"Building conflict graph failed.\n");
return -1;
}
fprintf(fpLOG,"DONE.\n");
printf("8-\n");
//**********************************************************************
// Reading encoding set by the user
//**********************************************************************
fprintf(fpLOG,"Reading encodings set... ");
fflush(stdout);
if(read_set_encoding(custom_file_name,n,&bits) != 0){
fprintf(stderr,"Error on reading encoding set.\n");
removeTempFiles();
return -1;
}
fprintf(fpLOG,"DONE\n");
printf("9-\n");
fprintf(fpLOG,"Check correcteness of encoding set... ");
if(check_correctness(custom_file_name,n,tot_enc,bits) != 0){
removeTempFiles();
return -1;
}
fprintf(fpLOG,"DONE\n");
printf("10-\n");
//**********************************************************************
// Variable preparation for encoding
//**********************************************************************
strcpy(file_in,TRIVIAL_ENCODING_FILE);
file_cons = strdup(CONSTRAINTS_FILE);
/*READ NON-TRIVIAL ENCODING FILE*/
fprintf(fpLOG,"Reading non-trivial encoding file... ");
if( (err = read_file(file_in)) ){
fprintf(stderr,"Error occured while reading non-trivial encoding file, error code: %d", err);
removeTempFiles();
return -1;
}
fprintf(fpLOG,"DONE\n");
printf("11-\n");
/*SEED FOR RAND*/
srand(time(NULL));
printf("12-\n");
/*ALLOCATING AND ZEROING DIFFERENCE MATRIX*/
opt_diff = (int**) calloc(n, sizeof(int*));
for(int i=0;i<n;i++)
opt_diff[i] = (int*) calloc(n, sizeof(int));
printf("13-\n");
/*NUMBER OF POSSIBLE ENCODING*/
tot_enc = 1;
for(int i=0;i<bits;i++) tot_enc *= 2;
printf("14-\n");
/*ANALYSIS IF IT'S A PERMUTATION OR A DISPOSITION*/
num_perm = 1;
if (n == tot_enc){
/*PERMUTATION*/
if(!unfix && !SET){
for(int i = 1; i< tot_enc; i++)
num_perm *= i;
}else{
for(int i = 1; i<= tot_enc; i++)
num_perm *= i;
}
fprintf(fpLOG,"Number of possible permutations by fixing first element: %lld\n", num_perm);
}
else{
/*DISPOSITION*/
if(!unfix && !SET){
elements = tot_enc-1;
min_disp = elements - (n- 1) + 1;
}else{
elements = tot_enc;
min_disp = elements - (n) + 1;
}
num_perm = 1;
for(int i=elements; i>= min_disp; i--)
num_perm *= i;
fprintf(fpLOG,"Number of possible dispositions by fixing first element: %lld\n", num_perm);
}
printf("15-\n");
all_perm = num_perm;
// num_perm = EXHAUSTIVE_MAX_PERM;
/*PREPARATION DATA FOR ENCODING PERMUTATIONS*/
enc = (int*) calloc(tot_enc, sizeof(int));
/*First element is fixed*/
if (!unfix && !SET)
enc[0] = 1;
sol = (int*) calloc(tot_enc, sizeof(int));
if (sol == NULL){
fprintf(stderr,"solution variable = null\n");
removeTempFiles();
return -1;
}
printf("16-\n");
/*BUILDING DIFFERENCE MATRIX*/
fprintf(fpLOG,"Building DM (=Difference Matrix)... ");
if( (err = difference_matrix(cpog_count)) ){
fprintf(stderr,"Error occurred while building difference matrix, error code: %d", err);
removeTempFiles();
return -1;
}
fprintf(fpLOG,"DONE\n");
printf("17-\n");
fclose(fpLOG);
removeTempFiles();
return 0;
}
int unload_graphs_codes(){
if(g != NULL) free(g);
if(manual_file != NULL) free(manual_file);
if(manual_file_back != NULL) free(manual_file_back);
if(custom_perm != NULL) free(custom_perm);
if(custom_perm_back != NULL) free(custom_perm_back);
if(opt_diff != NULL) {
for(int i = 0; i<cpog_count; i++)
if(opt_diff[i] != NULL) free(opt_diff[i]);
free(opt_diff);
}
if(perm != NULL) {
for(long long int i = 0; i<num_perm; i++)
if(perm[i] != NULL )free(perm[i]);
free(perm);
}
if(file_cons != NULL) free(file_cons);
if(weights != NULL) free(weights);
if(diff != NULL){
for(int i = 0; i< len_sequence; i++)
if(diff[i] != NULL) free(diff[i]);
free(diff);
}
if(opcodes != NULL){
for(int i = 0; i < cpog_count; i++)
if(opcodes[i] != NULL) free(opcodes[i]);
}
if(enc != NULL) free(enc);
if(sol != NULL) free(sol);
cpog_count = 0;
n = 0;
len_sequence = 0;
// Andrey's tool
if( !eventNames.empty() ) eventNames.clear();
for(int i = 0; i<eventsLimit; i++)
if( !eventNames_str[i].empty() )eventNames_str[i].clear();
for(int i = 0; i<eventsLimit;i++)
if( !eventPredicates[i].empty() )
eventPredicates[i].clear();
if( !scenarioNames.empty() )scenarioNames.clear();
if( !scenarioOpcodes.empty() )scenarioOpcodes.clear();
for(int i = 0; i< eventsLimit; i++)
for(int j = 0; j< predicatesLimit; j++)
if(!ev[i][j].empty()) ev[i][j].clear();
for(int i = 0; i< eventsLimit; i++)
for(int j = 0; j< eventsLimit; j++)
if(!ee[i][j].empty()) ee[i][j].clear();
if(!constraints.empty()) constraints.clear();
if ( !encodings.empty() )encodings.clear();
if ( !cgv.empty() ) cgv.clear();
if ( !cge.empty() ) cge.clear();
if ( !literal.empty() ) literal.clear();
if ( !bestLiteral.empty() ) bestLiteral.clear();
for(int i = 0; i< eventsLimit; i++)
for(int j = 0; j< predicatesLimit; j++)
if(!vConditions[i][j].empty())
vConditions[i][j].clear();
for(int i = 0; i< eventsLimit; i++)
for(int j = 0; j< eventsLimit; j++)
if(!aConditions[i][j].empty())
aConditions[i][j].clear();
return 0;
}
int single_literal_encoding(){
if( (fpLOG = fopen(LOG,"a")) == NULL){
fprintf(stderr,"Error on opening LOG file for appending.\n");
}
fprintf(fpLOG,"Running single-literal encoding.\n");
if(singleLiteralEncoding(total) != 0){
fprintf(stderr,"Single-literal encoding failed.\n");
return -1;
}
if (export_variables(single_literal) != 0){
return -1;
}
fclose(fpLOG);
return 0;
}
int sequential_encoding(){
if( (fpLOG = fopen(LOG,"a")) == NULL){
fprintf(stderr,"Error on opening LOG file for appending.\n");
}
fprintf(fpLOG,"Running Sequential encoding.\n");
if(allocate_encodings_space(1) != 0){
fprintf(stderr,"Sequential encoding failed.\n");
return -1;
}
if(sequentialEncoding() != 0){
fprintf(stderr,"Sequential encoding failed.\n");
return -1;
}
if (export_variables(sequential) != 0){
return -1;
}
fclose(fpLOG);
return 0;
}
int random_encoding(int num_enc){
if( (fpLOG = fopen(LOG,"a")) == NULL){
fprintf(stderr,"Error on opening LOG file for appending.\n");
}
bits = bits_saved;
fprintf(fpLOG,"Running Random encoding.\n");
if(allocate_encodings_space(num_enc) != 0){
fprintf(stderr,"Encoding allocation failed.\n");
return -1;
}
if(randomEncoding() != 0){
fprintf(stderr,"Random encoding failed.\n");
return -1;
}
if(heuristic_choice() != 0) {
fprintf(stderr,"Computing heuristic encoding.\n");
return -1;
}
if (export_variables(randomE) != 0){
return -1;
}
fclose(fpLOG);
return 0;
}
int heuristic_encoding(int num_enc){
if( (fpLOG = fopen(LOG,"a")) == NULL){
fprintf(stderr,"Error on opening LOG file for appending.\n");
}
bits = bits_saved;
if(allocate_encodings_space(num_enc) != 0){
fprintf(stderr,"Encoding allocation failed.\n");
return -1;
}
fprintf(fpLOG,"Running Random generation... ");
if(randomEncoding() != 0){
fprintf(stderr,"Random encoding failed.\n");
return -1;
}
fprintf(fpLOG,"DONE.\n");
fprintf(fpLOG,"Running Heuristic optimisation... ");
if(start_simulated_annealing() != 0){
fprintf(stderr,"Heuristic optimisation failed.\n");
return -1;
}
fprintf(fpLOG,"DONE.\n");
if(heuristic_choice() != 0) {
fprintf(stderr,"Computing heuristic encoding.\n");
return -1;
}
if (export_variables(heuristic) != 0){
return -1;
}
fclose(fpLOG);
return 0;
}
int exhaustive_encoding(int num_enc){
if( (fpLOG = fopen(LOG,"a")) == NULL){
fprintf(stderr,"Error on opening LOG file for appending.\n");
}
if(allocate_encodings_space(num_enc) != 0){
fprintf(stderr,"Encoding allocation failed.\n");
return -1;
}
fprintf(fpLOG,"Running Exhaustive encoding.\n");
if(!unfix && !SET){
//permutation_stdalgo(cpog_count,tot_enc);
fprintf(fpLOG,"Permutation algorithm unconstrained... ");
exhaustiveEncoding(sol,0,enc,cpog_count, tot_enc);
fprintf(fpLOG,"DONE\n");
}else{
fprintf(fpLOG,"Permutation algorithm constrained... ");
exhaustiveEncoding(sol,-1,enc,cpog_count, tot_enc);
fprintf(fpLOG,"DONE\n");
fprintf(fpLOG,"Filtering encoding... ");
filter_encodings(cpog_count, bits, tot_enc);
fprintf(fpLOG,"DONE\n");
}
if(heuristic_choice() != 0) {
fprintf(stderr,"Computing heuristic encoding.\n");
return -1;
}
if (export_variables(exhaustive) != 0){
return -1;
}
fclose(fpLOG);
return 0;
}
}
<|endoftext|>
|
<commit_before>/*-----------------------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2015 OSRE ( Open Source Render Engine ) by Kim Kulling
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 "OGLShader.h"
#include <osre/Common/Logger.h>
#include <osre/IO/Stream.h>
namespace OSRE {
namespace RenderBackend {
static const GLint ErrorId = -1;
static const String Tag = "OGLShader";
static GLuint getOGLShaderType( ShaderType type ) {
switch( type ) {
case SH_VertexShaderType:
return GL_VERTEX_SHADER;
case SH_FragmentShaderType:
return GL_FRAGMENT_SHADER;
case SH_GeometryShaderType:
return GL_GEOMETRY_SHADER;
default:
break;
}
return 0;
}
OGLShader::OGLShader( const String &name )
: Object( name )
, m_shaderprog( 0 )
, m_numShader( 0 )
, m_attributeList()
, m_uniformLocationList() {
::memset( m_shaders, 0, sizeof( unsigned int ) * 3 );
}
OGLShader::~OGLShader( ) {
for ( unsigned int i=0; i<3; ++i ) {
if( m_shaders[ i ] ) {
glDeleteShader( m_shaders[ i ] );
m_shaders[ i ] = 0;
}
}
}
bool OGLShader::loadFromSource( ShaderType type, const String &src ) {
if ( src.empty() ) {
return false;
}
GLuint shader = glCreateShader( getOGLShaderType( type ) );
m_shaders[ type ] = shader;
const char *tmp = src.c_str();
glShaderSource( shader, 1, &tmp, nullptr );
return true;
}
bool OGLShader::loadFromFile(ShaderType type, IO::Stream &stream ) {
if ( !stream.isOpen() ) {
return false;
}
ui32 filesize(stream.getSize());
if ( 0 == filesize ) {
return true;
}
c8 *data = new c8[ filesize ];
stream.read( data, filesize);
const bool retCode( loadFromSource( type, String( data ) ) );
delete [] data;
return retCode;
}
bool OGLShader::createAndLink() {
m_shaderprog = glCreateProgram();
if ( 0 == m_shaderprog ) {
osre_error( Tag, "Error while creating shader program." );
return false;
}
if ( 0 != m_shaders[ SH_VertexShaderType ] ) {
glAttachShader( m_shaderprog, m_shaders[ SH_VertexShaderType ] );
}
if ( 0 != m_shaders[ SH_FragmentShaderType ] ) {
glAttachShader( m_shaderprog, m_shaders[ SH_FragmentShaderType ] );
}
if ( 0 != m_shaders[ SH_GeometryShaderType ] ) {
glAttachShader( m_shaderprog, m_shaders[ SH_GeometryShaderType ] );
}
bool result( true );
GLint status( 0 );
glLinkProgram( m_shaderprog );
glGetProgramiv( m_shaderprog, GL_LINK_STATUS, &status );
if (status == GL_FALSE) {
GLint infoLogLength( 0 );
glGetProgramiv( m_shaderprog, GL_INFO_LOG_LENGTH, &infoLogLength);
GLchar *infoLog= new GLchar[infoLogLength];
::memset( infoLog, 0, infoLogLength );
glGetProgramInfoLog( m_shaderprog, infoLogLength, NULL, infoLog);
String error( infoLog );
osre_debug( Tag, "Link log: " + error + "\n" );
delete [] infoLog;
result = false;
}
return result;
}
void OGLShader::use( ) {
glUseProgram( m_shaderprog );
}
void OGLShader::unuse( ) {
glUseProgram( 0 );
}
void OGLShader::addAttribute( const std::string& attribute ) {
const GLint location = glGetAttribLocation( m_shaderprog, attribute.c_str( ) );
m_attributeList[ attribute ] = location;
if( ErrorId == location ) {
osre_debug( Tag, "Cannot find attribute " + attribute + " in shader." );
}
}
void OGLShader::addUniform( const std::string& uniform ) {
const GLint location = glGetUniformLocation( m_shaderprog, uniform.c_str( ) );
m_uniformLocationList[ uniform ] = location;
if( ErrorId == location ) {
osre_debug( Tag, "Cannot find uniform variable " + uniform + " in shader." );
}
}
GLint OGLShader::operator[] ( const std::string &attribute ) {
const GLint loc( m_attributeList[ attribute ] );
return loc;
}
GLint OGLShader::operator() ( const std::string &uniform ) {
const GLint loc( m_uniformLocationList[ uniform ] );
return loc;
}
} // Namespace RenderBackend
} // Namespace OSRE
<commit_msg>Shader: reformat.<commit_after>/*-----------------------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2015 OSRE ( Open Source Render Engine ) by Kim Kulling
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 "OGLShader.h"
#include <osre/Common/Logger.h>
#include <osre/IO/Stream.h>
namespace OSRE {
namespace RenderBackend {
static const GLint ErrorId = -1;
static const String Tag = "OGLShader";
static GLuint getOGLShaderType( ShaderType type ) {
switch( type ) {
case SH_VertexShaderType:
return GL_VERTEX_SHADER;
case SH_FragmentShaderType:
return GL_FRAGMENT_SHADER;
case SH_GeometryShaderType:
return GL_GEOMETRY_SHADER;
default:
break;
}
return 0;
}
OGLShader::OGLShader( const String &name )
: Object( name )
, m_shaderprog( 0 )
, m_numShader( 0 )
, m_attributeList()
, m_uniformLocationList() {
::memset( m_shaders, 0, sizeof( unsigned int ) * 3 );
}
OGLShader::~OGLShader( ) {
for ( unsigned int i=0; i<3; ++i ) {
if( m_shaders[ i ] ) {
glDeleteShader( m_shaders[ i ] );
m_shaders[ i ] = 0;
}
}
}
bool OGLShader::loadFromSource( ShaderType type, const String &src ) {
if ( src.empty() ) {
return false;
}
GLuint shader = glCreateShader( getOGLShaderType( type ) );
m_shaders[ type ] = shader;
const char *tmp = src.c_str();
glShaderSource( shader, 1, &tmp, nullptr );
return true;
}
bool OGLShader::loadFromFile( ShaderType type, IO::Stream &stream ) {
if ( !stream.isOpen() ) {
return false;
}
ui32 filesize(stream.getSize());
if ( 0 == filesize ) {
return true;
}
c8 *data = new c8[ filesize ];
stream.read( data, filesize);
const bool retCode( loadFromSource( type, String( data ) ) );
delete [] data;
return retCode;
}
bool OGLShader::createAndLink() {
m_shaderprog = glCreateProgram();
if ( 0 == m_shaderprog ) {
osre_error( Tag, "Error while creating shader program." );
return false;
}
if ( 0 != m_shaders[ SH_VertexShaderType ] ) {
glAttachShader( m_shaderprog, m_shaders[ SH_VertexShaderType ] );
}
if ( 0 != m_shaders[ SH_FragmentShaderType ] ) {
glAttachShader( m_shaderprog, m_shaders[ SH_FragmentShaderType ] );
}
if ( 0 != m_shaders[ SH_GeometryShaderType ] ) {
glAttachShader( m_shaderprog, m_shaders[ SH_GeometryShaderType ] );
}
bool result( true );
GLint status( 0 );
glLinkProgram( m_shaderprog );
glGetProgramiv( m_shaderprog, GL_LINK_STATUS, &status );
if (status == GL_FALSE) {
GLint infoLogLength( 0 );
glGetProgramiv( m_shaderprog, GL_INFO_LOG_LENGTH, &infoLogLength);
GLchar *infoLog= new GLchar[infoLogLength];
::memset( infoLog, 0, infoLogLength );
glGetProgramInfoLog( m_shaderprog, infoLogLength, NULL, infoLog);
String error( infoLog );
osre_debug( Tag, "Link log: " + error + "\n" );
delete [] infoLog;
result = false;
}
return result;
}
void OGLShader::use( ) {
glUseProgram( m_shaderprog );
}
void OGLShader::unuse( ) {
glUseProgram( 0 );
}
void OGLShader::addAttribute( const std::string& attribute ) {
const GLint location = glGetAttribLocation( m_shaderprog, attribute.c_str( ) );
m_attributeList[ attribute ] = location;
if( ErrorId == location ) {
osre_debug( Tag, "Cannot find attribute " + attribute + " in shader." );
}
}
void OGLShader::addUniform( const std::string& uniform ) {
const GLint location = glGetUniformLocation( m_shaderprog, uniform.c_str( ) );
m_uniformLocationList[ uniform ] = location;
if( ErrorId == location ) {
osre_debug( Tag, "Cannot find uniform variable " + uniform + " in shader." );
}
}
GLint OGLShader::operator[] ( const std::string &attribute ) {
const GLint loc( m_attributeList[ attribute ] );
return loc;
}
GLint OGLShader::operator() ( const std::string &uniform ) {
const GLint loc( m_uniformLocationList[ uniform ] );
return loc;
}
} // Namespace RenderBackend
} // Namespace OSRE
<|endoftext|>
|
<commit_before>/**
* @file
*
* @brief Tests for the getenv library
*
* @copyright BSD License (see doc/COPYING or http://www.libelektra.org)
*
*/
#include <gtest/gtest.h>
#include <kdbgetenv.h>
TEST (GetEnv, NonExist)
{
EXPECT_EQ (getenv ("du4Maiwi/does-not-exist"), static_cast<char *> (nullptr));
}
TEST (GetEnv, ExistOverride)
{
using namespace ckdb;
elektraOpen (nullptr, nullptr);
ksAppendKey (elektraConfig, keyNew ("user/elektra/intercept/getenv/override/does-exist", KEY_VALUE, "hello", KEY_END));
ASSERT_NE (getenv ("does-exist"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist"), std::string ("hello"));
elektraClose ();
}
TEST (GetEnv, ExistOverrideFallback)
{
using namespace ckdb;
elektraOpen (nullptr, nullptr);
ksAppendKey (elektraConfig, keyNew ("user/env/override/does-exist-fb", KEY_VALUE, "hello", KEY_END));
ASSERT_NE (getenv ("does-exist-fb"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist-fb"), std::string ("hello"));
elektraClose ();
}
TEST (GetEnv, ExistEnv)
{
using namespace ckdb;
elektraOpen (nullptr, nullptr);
setenv ("does-exist", "hello", 1);
ASSERT_NE (getenv ("does-exist"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist"), std::string ("hello"));
elektraClose ();
}
TEST (GetEnv, ExistEnvFallback)
{
using namespace ckdb;
elektraOpen (nullptr, nullptr);
setenv ("does-exist-fb", "hello", 1);
ASSERT_NE (getenv ("does-exist-fb"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist-fb"), std::string ("hello"));
elektraClose ();
}
TEST (GetEnv, ExistFallback)
{
using namespace ckdb;
elektraOpen (nullptr, nullptr);
ksAppendKey (elektraConfig, keyNew ("user/elektra/intercept/getenv/fallback/does-exist", KEY_VALUE, "hello", KEY_END));
ASSERT_NE (getenv ("does-exist"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist"), std::string ("hello"));
elektraClose ();
}
TEST (GetEnv, ExistFallbackFallback)
{
using namespace ckdb;
elektraOpen (nullptr, nullptr);
ksAppendKey (elektraConfig, keyNew ("user/elektra/intercept/getenv/fallback/does-exist-fb", KEY_VALUE, "hello", KEY_END));
ASSERT_NE (getenv ("does-exist-fb"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist-fb"), std::string ("hello"));
elektraClose ();
}
TEST (GetEnv, OpenClose)
{
using namespace ckdb;
// KeySet *oldElektraConfig = elektraConfig;
elektraOpen (nullptr, nullptr);
// EXPECT_NE(elektraConfig, oldElektraConfig); // even its a new object, it might point to same address
EXPECT_EQ (getenv ("du4Maiwi/does-not-exist"), static_cast<char *> (nullptr));
ksAppendKey (elektraConfig, keyNew ("user/elektra/intercept/getenv/override/does-exist", KEY_VALUE, "hello", KEY_END));
ASSERT_NE (getenv ("does-exist"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist"), std::string ("hello"));
EXPECT_EQ (getenv ("du4Maiwi/does-not-exist"), static_cast<char *> (nullptr));
elektraClose ();
}
TEST (GetEnv, OpenCloseFallback)
{
using namespace ckdb;
// KeySet *oldElektraConfig = elektraConfig;
elektraOpen (nullptr, nullptr);
// EXPECT_NE(elektraConfig, oldElektraConfig); // even its a new object, it might point to same address
EXPECT_EQ (getenv ("du4Maiwi/does-not-exist-fb"), static_cast<char *> (nullptr));
ksAppendKey (elektraConfig, keyNew ("user/env/override/does-exist-fb", KEY_VALUE, "hello", KEY_END));
ASSERT_NE (getenv ("does-exist-fb"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist-fb"), std::string ("hello"));
EXPECT_EQ (getenv ("du4Maiwi/does-not-exist-fb"), static_cast<char *> (nullptr));
elektraClose ();
}
void elektraPrintConfig ()
{
using namespace ckdb;
Key * c;
ksRewind (elektraConfig);
while ((c = ksNext (elektraConfig)))
{
printf ("%s - %s\n", keyName (c), keyString (c));
}
}
TEST (GetEnv, ArgvParam)
{
const char * cargv[] = { "name", "--elektra:does-exist=hello", nullptr };
char ** argv = const_cast<char **> (cargv);
int argc = 2;
using namespace ckdb;
elektraOpen (&argc, argv);
EXPECT_EQ (argc, 1) << "elektra proc not consumed";
EXPECT_EQ (argv[0], std::string ("name"));
EXPECT_EQ (argv[1], static_cast<char *> (nullptr));
ckdb::Key * k = ksLookupByName (elektraConfig, "proc/elektra/intercept/getenv/override/does-exist", 0);
ASSERT_NE (k, static_cast<ckdb::Key *> (nullptr));
EXPECT_EQ (keyString (k), std::string ("hello"));
ASSERT_NE (getenv ("does-exist"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist"), std::string ("hello"));
elektraClose ();
}
TEST (GetEnv, ArgvParamUninvolved)
{
const char * cargv[] = { "name", "--uninvolved", "--not-used", "-L", "--elektra:does-exist=hello",
"--uninvolved", "--not-used", "-L", nullptr };
char ** argv = const_cast<char **> (cargv);
int argc = 8;
using namespace ckdb;
elektraOpen (&argc, argv);
EXPECT_EQ (argc, 7) << "elektra proc not consumed";
EXPECT_EQ (argv[0], std::string ("name"));
EXPECT_EQ (argv[1], std::string ("--uninvolved"));
EXPECT_EQ (argv[2], std::string ("--not-used"));
EXPECT_EQ (argv[3], std::string ("-L"));
EXPECT_EQ (argv[4], std::string ("--uninvolved"));
EXPECT_EQ (argv[5], std::string ("--not-used"));
EXPECT_EQ (argv[6], std::string ("-L"));
EXPECT_EQ (argv[7], static_cast<char *> (nullptr));
ckdb::Key * k = ksLookupByName (elektraConfig, "proc/elektra/intercept/getenv/override/does-exist", 0);
ASSERT_NE (k, static_cast<ckdb::Key *> (nullptr));
EXPECT_EQ (keyString (k), std::string ("hello"));
ASSERT_NE (getenv ("does-exist"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist"), std::string ("hello"));
elektraClose ();
}
TEST (GetEnv, NameArgv0)
{
using namespace ckdb;
int argc = 1;
const char * cargv[] = { "path/to/any-name", nullptr };
char ** argv = const_cast<char **> (cargv);
elektraOpen (&argc, argv);
ckdb::Key * k = ksLookupByName (elektraConfig, "proc/elektra/intercept/getenv/layer/name", 0);
ASSERT_NE (k, static_cast<ckdb::Key *> (nullptr));
EXPECT_EQ (keyString (k), std::string ("path/to/any-name"));
k = ksLookupByName (elektraConfig, "proc/elektra/intercept/getenv/layer/basename", 0);
ASSERT_NE (k, static_cast<ckdb::Key *> (nullptr));
EXPECT_EQ (keyString (k), std::string ("any-name"));
elektraClose ();
}
TEST (GetEnv, NameExplicit)
{
using namespace ckdb;
int argc = 2;
const char * cargv[] = { "any-name", "--elektra%name%=other-name" };
char ** argv = const_cast<char **> (cargv);
elektraOpen (&argc, argv);
ckdb::Key * k = ksLookupByName (elektraConfig, "proc/elektra/intercept/getenv/layer/name", 0);
ASSERT_NE (k, static_cast<ckdb::Key *> (nullptr));
EXPECT_EQ (keyString (k), std::string ("other-name"));
elektraClose ();
}
#include "main.cpp"
<commit_msg>test_getenv: fixed testcase<commit_after>/**
* @file
*
* @brief Tests for the getenv library
*
* @copyright BSD License (see doc/COPYING or http://www.libelektra.org)
*
*/
#include <gtest/gtest.h>
#include <kdbgetenv.h>
TEST (GetEnv, NonExist)
{
EXPECT_EQ (getenv ("du4Maiwi/does-not-exist"), static_cast<char *> (nullptr));
}
TEST (GetEnv, ExistOverride)
{
using namespace ckdb;
elektraOpen (nullptr, nullptr);
ksAppendKey (elektraConfig, keyNew ("user/elektra/intercept/getenv/override/does-exist", KEY_VALUE, "hello", KEY_END));
ASSERT_NE (getenv ("does-exist"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist"), std::string ("hello"));
elektraClose ();
}
TEST (GetEnv, ExistOverrideFallback)
{
using namespace ckdb;
elektraOpen (nullptr, nullptr);
ksAppendKey (elektraConfig, keyNew ("user/env/override/does-exist-fb", KEY_VALUE, "hello", KEY_END));
ASSERT_NE (getenv ("does-exist-fb"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist-fb"), std::string ("hello"));
elektraClose ();
}
TEST (GetEnv, ExistEnv)
{
using namespace ckdb;
elektraOpen (nullptr, nullptr);
setenv ("does-exist", "hello", 1);
ASSERT_NE (getenv ("does-exist"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist"), std::string ("hello"));
elektraClose ();
}
TEST (GetEnv, ExistEnvFallback)
{
using namespace ckdb;
elektraOpen (nullptr, nullptr);
setenv ("does-exist-fb", "hello", 1);
ASSERT_NE (getenv ("does-exist-fb"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist-fb"), std::string ("hello"));
elektraClose ();
}
TEST (GetEnv, ExistFallback)
{
using namespace ckdb;
elektraOpen (nullptr, nullptr);
ksAppendKey (elektraConfig, keyNew ("user/elektra/intercept/getenv/fallback/does-exist", KEY_VALUE, "hello", KEY_END));
ASSERT_NE (getenv ("does-exist"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist"), std::string ("hello"));
elektraClose ();
}
TEST (GetEnv, ExistFallbackFallback)
{
using namespace ckdb;
elektraOpen (nullptr, nullptr);
ksAppendKey (elektraConfig, keyNew ("user/env/fallback/does-exist-fb", KEY_VALUE, "hello", KEY_END));
ASSERT_NE (getenv ("does-exist-fb"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist-fb"), std::string ("hello"));
elektraClose ();
}
TEST (GetEnv, OpenClose)
{
using namespace ckdb;
// KeySet *oldElektraConfig = elektraConfig;
elektraOpen (nullptr, nullptr);
// EXPECT_NE(elektraConfig, oldElektraConfig); // even its a new object, it might point to same address
EXPECT_EQ (getenv ("du4Maiwi/does-not-exist"), static_cast<char *> (nullptr));
ksAppendKey (elektraConfig, keyNew ("user/elektra/intercept/getenv/override/does-exist", KEY_VALUE, "hello", KEY_END));
ASSERT_NE (getenv ("does-exist"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist"), std::string ("hello"));
EXPECT_EQ (getenv ("du4Maiwi/does-not-exist"), static_cast<char *> (nullptr));
elektraClose ();
}
TEST (GetEnv, OpenCloseFallback)
{
using namespace ckdb;
// KeySet *oldElektraConfig = elektraConfig;
elektraOpen (nullptr, nullptr);
// EXPECT_NE(elektraConfig, oldElektraConfig); // even its a new object, it might point to same address
EXPECT_EQ (getenv ("du4Maiwi/does-not-exist-fb"), static_cast<char *> (nullptr));
ksAppendKey (elektraConfig, keyNew ("user/env/override/does-exist-fb", KEY_VALUE, "hello", KEY_END));
ASSERT_NE (getenv ("does-exist-fb"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist-fb"), std::string ("hello"));
EXPECT_EQ (getenv ("du4Maiwi/does-not-exist-fb"), static_cast<char *> (nullptr));
elektraClose ();
}
void elektraPrintConfig ()
{
using namespace ckdb;
Key * c;
ksRewind (elektraConfig);
while ((c = ksNext (elektraConfig)))
{
printf ("%s - %s\n", keyName (c), keyString (c));
}
}
TEST (GetEnv, ArgvParam)
{
const char * cargv[] = { "name", "--elektra:does-exist=hello", nullptr };
char ** argv = const_cast<char **> (cargv);
int argc = 2;
using namespace ckdb;
elektraOpen (&argc, argv);
EXPECT_EQ (argc, 1) << "elektra proc not consumed";
EXPECT_EQ (argv[0], std::string ("name"));
EXPECT_EQ (argv[1], static_cast<char *> (nullptr));
ckdb::Key * k = ksLookupByName (elektraConfig, "proc/elektra/intercept/getenv/override/does-exist", 0);
ASSERT_NE (k, static_cast<ckdb::Key *> (nullptr));
EXPECT_EQ (keyString (k), std::string ("hello"));
ASSERT_NE (getenv ("does-exist"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist"), std::string ("hello"));
elektraClose ();
}
TEST (GetEnv, ArgvParamUninvolved)
{
const char * cargv[] = { "name", "--uninvolved", "--not-used", "-L", "--elektra:does-exist=hello",
"--uninvolved", "--not-used", "-L", nullptr };
char ** argv = const_cast<char **> (cargv);
int argc = 8;
using namespace ckdb;
elektraOpen (&argc, argv);
EXPECT_EQ (argc, 7) << "elektra proc not consumed";
EXPECT_EQ (argv[0], std::string ("name"));
EXPECT_EQ (argv[1], std::string ("--uninvolved"));
EXPECT_EQ (argv[2], std::string ("--not-used"));
EXPECT_EQ (argv[3], std::string ("-L"));
EXPECT_EQ (argv[4], std::string ("--uninvolved"));
EXPECT_EQ (argv[5], std::string ("--not-used"));
EXPECT_EQ (argv[6], std::string ("-L"));
EXPECT_EQ (argv[7], static_cast<char *> (nullptr));
ckdb::Key * k = ksLookupByName (elektraConfig, "proc/elektra/intercept/getenv/override/does-exist", 0);
ASSERT_NE (k, static_cast<ckdb::Key *> (nullptr));
EXPECT_EQ (keyString (k), std::string ("hello"));
ASSERT_NE (getenv ("does-exist"), static_cast<char *> (nullptr));
EXPECT_EQ (getenv ("does-exist"), std::string ("hello"));
elektraClose ();
}
TEST (GetEnv, NameArgv0)
{
using namespace ckdb;
int argc = 1;
const char * cargv[] = { "path/to/any-name", nullptr };
char ** argv = const_cast<char **> (cargv);
elektraOpen (&argc, argv);
ckdb::Key * k = ksLookupByName (elektraConfig, "proc/elektra/intercept/getenv/layer/name", 0);
ASSERT_NE (k, static_cast<ckdb::Key *> (nullptr));
EXPECT_EQ (keyString (k), std::string ("path/to/any-name"));
k = ksLookupByName (elektraConfig, "proc/elektra/intercept/getenv/layer/basename", 0);
ASSERT_NE (k, static_cast<ckdb::Key *> (nullptr));
EXPECT_EQ (keyString (k), std::string ("any-name"));
elektraClose ();
}
TEST (GetEnv, NameExplicit)
{
using namespace ckdb;
int argc = 2;
const char * cargv[] = { "any-name", "--elektra%name%=other-name" };
char ** argv = const_cast<char **> (cargv);
elektraOpen (&argc, argv);
ckdb::Key * k = ksLookupByName (elektraConfig, "proc/elektra/intercept/getenv/layer/name", 0);
ASSERT_NE (k, static_cast<ckdb::Key *> (nullptr));
EXPECT_EQ (keyString (k), std::string ("other-name"));
elektraClose ();
}
#include "main.cpp"
<|endoftext|>
|
<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: Factory_test.C,v 1.3 2002/12/18 16:00:39 sturm Exp $
#include <BALL/CONCEPT/classTest.h>
///////////////////////////
#include <BALL/CONCEPT/factory.h>
///////////////////////////
START_TEST(Factory, "$Id: Factory_test.C,v 1.3 2002/12/18 16:00:39 sturm Exp $")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace BALL;
CHECK(Factory::getDefault())
Size& def(const_cast<Size&>(Factory<Size>::getDefault()));
def = 1234;
TEST_EQUAL(Factory<Size>::getDefault(), def);
def = 3456;
TEST_EQUAL(Factory<Size>::getDefault(), def);
RESULT
CHECK(Factory::create())
Size* ptr = Factory<Size>::create();
TEST_NOT_EQUAL(ptr, 0)
Size* ptr2 = Factory<Size>::create();
TEST_NOT_EQUAL(ptr, 0)
TEST_NOT_EQUAL(ptr, ptr2)
delete ptr;
delete ptr2;
RESULT
CHECK(Factory::createVoid())
Size* ptr = (Size*)Factory<Size>::create();
TEST_NOT_EQUAL(ptr, 0)
Size* ptr2 = (Size*)Factory<Size>::create();
TEST_NOT_EQUAL(ptr, 0)
TEST_NOT_EQUAL(ptr, ptr2)
delete ptr;
delete ptr2;
RESULT
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<commit_msg>fixed: CHECK headers<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: Factory_test.C,v 1.4 2003/06/16 15:43:24 anker Exp $
#include <BALL/CONCEPT/classTest.h>
///////////////////////////
#include <BALL/CONCEPT/factory.h>
///////////////////////////
START_TEST(Factory, "$Id: Factory_test.C,v 1.4 2003/06/16 15:43:24 anker Exp $")
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
using namespace BALL;
CHECK(static const T& getDefault())
Size& def(const_cast<Size&>(Factory<Size>::getDefault()));
def = 1234;
TEST_EQUAL(Factory<Size>::getDefault(), def);
def = 3456;
TEST_EQUAL(Factory<Size>::getDefault(), def);
RESULT
CHECK(static T* create())
Size* ptr = Factory<Size>::create();
TEST_NOT_EQUAL(ptr, 0)
Size* ptr2 = Factory<Size>::create();
TEST_NOT_EQUAL(ptr, 0)
TEST_NOT_EQUAL(ptr, ptr2)
delete ptr;
delete ptr2;
RESULT
CHECK(static void* createVoid())
Size* ptr = (Size*)Factory<Size>::create();
TEST_NOT_EQUAL(ptr, 0)
Size* ptr2 = (Size*)Factory<Size>::create();
TEST_NOT_EQUAL(ptr, 0)
TEST_NOT_EQUAL(ptr, ptr2)
delete ptr;
delete ptr2;
RESULT
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<|endoftext|>
|
<commit_before>#include "localization.h"
#include "gui_msgs/ColorMsg.h"
#include "gui_msgs/GUIPointMsg.h"
#include "gui_msgs/GUIPolyMsg.h"
#include "rss_msgs/MotionMsg.h"
#include "rss_msgs/RobotLocation.h"
#include <random>
using namespace rss_msgs;
using namespace gui_msgs;
using namespace std;
typedef cgal_kernel K;
typedef K::Point_2 Point_2;
typedef K::Point_3 Point_3;
typedef K::Ray_2 Ray_2;
typedef K::Vector_2 Vector_2;
typedef CGAL::Polygon_2<K> Polygon_2;
namespace localization {
double curTime() {
return ros::Time::now().toSec();
}
Localization::Localization() {
ROS_DEBUG("Initializing localization module");
_time = curTime();
// Initializing the sonar locations.
SONAR_DIR = {
cgal_kernel::Vector_2(0.0, 1.0),
cgal_kernel::Vector_2(0.0, 1.0)
};
SONAR_POS = {
cgal_kernel::Vector_2(-0.28, 0.215),
cgal_kernel::Vector_2(0.025, 0.215)
};
ros::NodeHandle n;
// Initialize message publishers.
_location_pub = n.advertise<RobotLocation>("localization/update", 1000);
_guipoly_pub = n.advertise<GUIPolyMsg>("gui/Poly", 1000);
_guipoint_pub = n.advertise<GUIPointMsg>("gui/Point", 1000);
// Load map file location and initialize the map-handler class instance.
string mapfile_location;
assert(n.getParam("/loc/mapFileName", mapfile_location));
ROS_DEBUG("Got mapFileName: %s", mapfile_location.c_str());
_wall_map = make_shared<WallMap>(mapfile_location);
ROS_DEBUG("Initialized wall map.");
InitializeParticles();
// Test CASE 01
{
string res;
if (n.getParam("/loc/testTriangulation", res)) {
if (res == "yes") {
TestTriangulation();
}
}
}
// Test CASE 02
{
string res;
if (n.getParam("/loc/leaveBreadCrumbs", res)) {
if (res == "yes") {
_leaveBreadCrumbs = true;
}
}
}
}
// Initialize with N random points generated within a given tolerance (in 3-D
// space, it's a parallelipiped with sides equal to tolerance values)
void Localization::InitializeParticles() {
_particles.resize(N);
double sx = CGAL::to_double(_wall_map->GetRobotStart().x());
double dx = DISTANCE_TOLERANCE;
double sy = CGAL::to_double(_wall_map->GetRobotStart().y());
double dy = DISTANCE_TOLERANCE;
double st = 0.0;
double dt = HEADING_TOLERANCE;
default_random_engine generator;
uniform_real_distribution<double> xDist(sx-dx, sx+dx);
uniform_real_distribution<double> yDist(sy-dy, sy+dy);
uniform_real_distribution<double> tDist(st-dt, st+dt);
for (int i = 0; i < N; ++i) {
double x = xDist(generator);
double y = yDist(generator);
double t = tDist(generator);
_particles[i] = Particle(x, y, t, -log(1.0*N));
}
}
RobotLocation Localization::currentPositionBelief() const {
double x = 0, y = 0, t = 0;
double normalizer = 0.0;
for (auto par : _particles) {
double prob = exp(par.belief);
x += par.x*prob;
y += par.y*prob;
par.t = NormalizeRad(par.t);
t += par.t*prob;
normalizer += prob;
}
x /= normalizer;
y /= normalizer;
t /= normalizer;
t = NormalizeRad(t);
RobotLocation currentPosition;
currentPosition.x = x;
currentPosition.y = y;
currentPosition.theta = t;
return currentPosition;
}
void Localization::PublishLocation() {
RobotLocation currentBelief = currentPositionBelief();
// TODO: remove
currentBelief.x = _prev_odo_x;
currentBelief.y = _prev_odo_y;
currentBelief.theta = _prev_odo_t;
_location_pub.publish(currentBelief);
if (_leaveBreadCrumbs) {
GUIPointMsg crumb;
ColorMsg color;
color.r = 0;
color.g = 255;
color.b = 0;
crumb.color = color;
crumb.x = currentBelief.x;
crumb.y = currentBelief.y;
_guipoint_pub.publish(crumb);
}
}
void Localization::TestTriangulation() {
// TEST
ROS_DEBUG("Distance to wall from 0.0 0.0 in direction 1.0 0.0: %.3lf",
_wall_map->DistanceToWall(K::Ray_2(Point_2(0.0,0.0), K::Direction_2(1.0,1.00000))));
// Initialize distribution:
ros::Duration(5.0).sleep(); // Sleep for 5 sec to allow gui node to initialize.
for (const K::Triangle_2 &tri : _wall_map->_triangles) {
GUIPolyMsg new_poly;
new_poly.numVertices = 3;
for (int i = 0; i < 3; ++i) {
new_poly.x.push_back(CGAL::to_double(tri[i].x()));
new_poly.y.push_back(CGAL::to_double(tri[i].y()));
}
new_poly.c.r = 255;
new_poly.c.g = 0;
new_poly.c.b = 0;
new_poly.closed = 1;
_guipoly_pub.publish(new_poly);
}
}
double logGaussian(double x, double mu, double var) {
return -0.5*log(2.0*M_PI*var) - (x-mu)*(x-mu)/var/2.0;
}
double logGaussian(double x, double y, double mux, double muy, double var) {
return -0.5*log(2.0*M_PI*var) - ((x-mux)*(x-mux)+(y-muy)*(y-muy))/var/2.0;
}
void Localization::NormalizeBeliefs() {
// Normalize the result
double normalizer = 0.0;
for (const Particle &par : _particles) {
normalizer += exp(par.belief);
}
for (Particle &par : _particles) {
par.belief -= log(normalizer);
}
}
void Localization::onOdometryUpdate(const OdometryMsg::ConstPtr &odo) {
double dx = odo->x-_prev_odo_x;
double dy = odo->y-_prev_odo_y;
double dt = odo->theta-_prev_odo_t;
_prev_odo_x = odo->x;
_prev_odo_y = odo->y;
_prev_odo_t = odo->theta;
_prev_odo_time = curTime();
double start_time = curTime();
ROS_DEBUG_STREAM("onOdometryUpdate: " << dx << " " << dy << " dt: " << dt << " at time: " << curTime()-_time);
double varD = pow(min(0.03, 0.01 + sqrt(dx*dx+dy*dy)), 2.0);
double varT = pow(min(0.17453292519, 0.17453292519/20.0+fabs(dt)), 2.0);
default_random_engine gen;
normal_distribution<double> xyDist(0.0, varD);
normal_distribution<double> tDist(0.0, varT);
vector<Particle> new_particles;
for (const Particle &par : _particles) {
new_particles.push_back(Particle(par.x+dx, par.y+dy, par.t+dt,
par.belief + logGaussian(0.0, 0.0, 0.0, 0.0, varD) + logGaussian(0.0, 0.0, varT)));
// Generate 10 random points to account for noise.
for (int i = 0; i < 10; ++i) {
double x = xyDist(gen) + par.x+dx;
double y = xyDist(gen) + par.y+dy;
double t = tDist(gen) + par.t+dt;
new_particles.push_back(Particle(x, y, t,
par.belief + logGaussian(x-par.x-dx, 0.0, y-par.y-dy, 0.0, varD) + logGaussian(t-par.t-dt, 0.0, varT)));
}
}
ROS_DEBUG("onOdometryUpdate: time up to generation %.3lf sec.", curTime()-start_time);
// Substitute old particles with top #N new ones.
sort(new_particles.begin(), new_particles.end());
reverse(new_particles.begin(), new_particles.end());
new_particles.resize(N);
_particles = new_particles;
ROS_DEBUG("onOdometryUpdate: time up to sorting %.3lf sec.", curTime()-start_time);
NormalizeBeliefs();
PublishLocation();
ROS_DEBUG("onOdometryUpdate: time passed %.3lf sec.", curTime()-start_time);
}
Vector_2 Rotate(Vector_2 vec, double alfa) {
return Vector_2(vec.x()*cos(alfa) - vec.y()*sin(alfa),
vec.x()*sin(alfa) + vec.y()*cos(alfa));
}
void Localization::onSonarUpdate(const SonarMsg::ConstPtr &son) {
ROS_DEBUG_STREAM("Got sonar update: " << son->sonarId << " range: " << son->range);
return;
double start_time = curTime();
double varD = 0.01;
for (Particle &par : _particles) {
Vector_2 dir(Rotate(SONAR_DIR[son->sonarId], par.t));
Point_2 sonarLoc(Point_2(par.x, par.y) + Rotate(SONAR_POS[son->sonarId], par.t));
double mu = _wall_map->DistanceToWall(Ray_2(sonarLoc, dir));
par.belief += logGaussian(son->range, mu, varD);
}
NormalizeBeliefs();
PublishLocation();
ROS_DEBUG("onSonarUpdate: time passed %.3lf sec.", curTime()-start_time);
}
double NormalizeRad(double rad) {
rad = fmod(rad, 2*M_PI);
if (rad < 0) {
rad += 2*M_PI;
}
return rad;
}
} // namespace navigation
<commit_msg>Added new position of sonar<commit_after>#include "localization.h"
#include "gui_msgs/ColorMsg.h"
#include "gui_msgs/GUIPointMsg.h"
#include "gui_msgs/GUIPolyMsg.h"
#include "rss_msgs/MotionMsg.h"
#include "rss_msgs/RobotLocation.h"
#include <random>
using namespace rss_msgs;
using namespace gui_msgs;
using namespace std;
typedef cgal_kernel K;
typedef K::Point_2 Point_2;
typedef K::Point_3 Point_3;
typedef K::Ray_2 Ray_2;
typedef K::Vector_2 Vector_2;
typedef CGAL::Polygon_2<K> Polygon_2;
namespace localization {
double curTime() {
return ros::Time::now().toSec();
}
Localization::Localization() {
ROS_DEBUG("Initializing localization module");
_time = curTime();
// Initializing the sonar locations.
SONAR_DIR = {
cgal_kernel::Vector_2(0.0, -1.0),
cgal_kernel::Vector_2(0.0, 1.0)
};
SONAR_POS = {
cgal_kernel::Vector_2(-0.0975, -0.215),
cgal_kernel::Vector_2(0.025, 0.215)
};
ros::NodeHandle n;
// Initialize message publishers.
_location_pub = n.advertise<RobotLocation>("localization/update", 1000);
_guipoly_pub = n.advertise<GUIPolyMsg>("gui/Poly", 1000);
_guipoint_pub = n.advertise<GUIPointMsg>("gui/Point", 1000);
// Load map file location and initialize the map-handler class instance.
string mapfile_location;
assert(n.getParam("/loc/mapFileName", mapfile_location));
ROS_DEBUG("Got mapFileName: %s", mapfile_location.c_str());
_wall_map = make_shared<WallMap>(mapfile_location);
ROS_DEBUG("Initialized wall map.");
InitializeParticles();
// Test CASE 01
{
string res;
if (n.getParam("/loc/testTriangulation", res)) {
if (res == "yes") {
TestTriangulation();
}
}
}
// Test CASE 02
{
string res;
if (n.getParam("/loc/leaveBreadCrumbs", res)) {
if (res == "yes") {
_leaveBreadCrumbs = true;
}
}
}
}
// Initialize with N random points generated within a given tolerance (in 3-D
// space, it's a parallelipiped with sides equal to tolerance values)
void Localization::InitializeParticles() {
_particles.resize(N);
double sx = CGAL::to_double(_wall_map->GetRobotStart().x());
double dx = DISTANCE_TOLERANCE;
double sy = CGAL::to_double(_wall_map->GetRobotStart().y());
double dy = DISTANCE_TOLERANCE;
double st = 0.0;
double dt = HEADING_TOLERANCE;
default_random_engine generator;
uniform_real_distribution<double> xDist(sx-dx, sx+dx);
uniform_real_distribution<double> yDist(sy-dy, sy+dy);
uniform_real_distribution<double> tDist(st-dt, st+dt);
for (int i = 0; i < N; ++i) {
double x = xDist(generator);
double y = yDist(generator);
double t = tDist(generator);
_particles[i] = Particle(x, y, t, -log(1.0*N));
}
}
RobotLocation Localization::currentPositionBelief() const {
double x = 0, y = 0, t = 0;
double normalizer = 0.0;
for (auto par : _particles) {
double prob = exp(par.belief);
x += par.x*prob;
y += par.y*prob;
par.t = NormalizeRad(par.t);
t += par.t*prob;
normalizer += prob;
}
x /= normalizer;
y /= normalizer;
t /= normalizer;
t = NormalizeRad(t);
RobotLocation currentPosition;
currentPosition.x = x;
currentPosition.y = y;
currentPosition.theta = t;
return currentPosition;
}
void Localization::PublishLocation() {
RobotLocation currentBelief = currentPositionBelief();
// TODO: remove
currentBelief.x = _prev_odo_x;
currentBelief.y = _prev_odo_y;
currentBelief.theta = _prev_odo_t;
_location_pub.publish(currentBelief);
if (_leaveBreadCrumbs) {
GUIPointMsg crumb;
ColorMsg color;
color.r = 0;
color.g = 255;
color.b = 0;
crumb.color = color;
crumb.x = currentBelief.x;
crumb.y = currentBelief.y;
_guipoint_pub.publish(crumb);
}
}
void Localization::TestTriangulation() {
// TEST
ROS_DEBUG("Distance to wall from 0.0 0.0 in direction 1.0 0.0: %.3lf",
_wall_map->DistanceToWall(K::Ray_2(Point_2(0.0,0.0), K::Direction_2(1.0,1.00000))));
// Initialize distribution:
ros::Duration(5.0).sleep(); // Sleep for 5 sec to allow gui node to initialize.
for (const K::Triangle_2 &tri : _wall_map->_triangles) {
GUIPolyMsg new_poly;
new_poly.numVertices = 3;
for (int i = 0; i < 3; ++i) {
new_poly.x.push_back(CGAL::to_double(tri[i].x()));
new_poly.y.push_back(CGAL::to_double(tri[i].y()));
}
new_poly.c.r = 255;
new_poly.c.g = 0;
new_poly.c.b = 0;
new_poly.closed = 1;
_guipoly_pub.publish(new_poly);
}
}
double logGaussian(double x, double mu, double var) {
return -0.5*log(2.0*M_PI*var) - (x-mu)*(x-mu)/var/2.0;
}
double logGaussian(double x, double y, double mux, double muy, double var) {
return -0.5*log(2.0*M_PI*var) - ((x-mux)*(x-mux)+(y-muy)*(y-muy))/var/2.0;
}
void Localization::NormalizeBeliefs() {
// Normalize the result
double normalizer = 0.0;
for (const Particle &par : _particles) {
normalizer += exp(par.belief);
}
for (Particle &par : _particles) {
par.belief -= log(normalizer);
}
}
void Localization::onOdometryUpdate(const OdometryMsg::ConstPtr &odo) {
double dx = odo->x-_prev_odo_x;
double dy = odo->y-_prev_odo_y;
double dt = odo->theta-_prev_odo_t;
_prev_odo_x = odo->x;
_prev_odo_y = odo->y;
_prev_odo_t = odo->theta;
_prev_odo_time = curTime();
double start_time = curTime();
ROS_DEBUG_STREAM("onOdometryUpdate: " << dx << " " << dy << " dt: " << dt << " at time: " << curTime()-_time);
double varD = pow(min(0.03, 0.01 + sqrt(dx*dx+dy*dy)), 2.0);
double varT = pow(min(0.17453292519, 0.17453292519/20.0+fabs(dt)), 2.0);
default_random_engine gen;
normal_distribution<double> xyDist(0.0, varD);
normal_distribution<double> tDist(0.0, varT);
vector<Particle> new_particles;
for (const Particle &par : _particles) {
new_particles.push_back(Particle(par.x+dx, par.y+dy, par.t+dt,
par.belief + logGaussian(0.0, 0.0, 0.0, 0.0, varD) + logGaussian(0.0, 0.0, varT)));
// Generate 10 random points to account for noise.
for (int i = 0; i < 10; ++i) {
double x = xyDist(gen) + par.x+dx;
double y = xyDist(gen) + par.y+dy;
double t = tDist(gen) + par.t+dt;
new_particles.push_back(Particle(x, y, t,
par.belief + logGaussian(x-par.x-dx, 0.0, y-par.y-dy, 0.0, varD) + logGaussian(t-par.t-dt, 0.0, varT)));
}
}
ROS_DEBUG("onOdometryUpdate: time up to generation %.3lf sec.", curTime()-start_time);
// Substitute old particles with top #N new ones.
sort(new_particles.begin(), new_particles.end());
reverse(new_particles.begin(), new_particles.end());
new_particles.resize(N);
_particles = new_particles;
ROS_DEBUG("onOdometryUpdate: time up to sorting %.3lf sec.", curTime()-start_time);
NormalizeBeliefs();
PublishLocation();
ROS_DEBUG("onOdometryUpdate: time passed %.3lf sec.", curTime()-start_time);
}
Vector_2 Rotate(Vector_2 vec, double alfa) {
return Vector_2(vec.x()*cos(alfa) - vec.y()*sin(alfa),
vec.x()*sin(alfa) + vec.y()*cos(alfa));
}
void Localization::onSonarUpdate(const SonarMsg::ConstPtr &son) {
ROS_DEBUG_STREAM("Got sonar update: " << son->sonarId << " range: " << son->range);
return;
double start_time = curTime();
double varD = 0.01;
for (Particle &par : _particles) {
Vector_2 dir(Rotate(SONAR_DIR[son->sonarId], par.t));
Point_2 sonarLoc(Point_2(par.x, par.y) + Rotate(SONAR_POS[son->sonarId], par.t));
double mu = _wall_map->DistanceToWall(Ray_2(sonarLoc, dir));
par.belief += logGaussian(son->range, mu, varD);
}
NormalizeBeliefs();
PublishLocation();
ROS_DEBUG("onSonarUpdate: time passed %.3lf sec.", curTime()-start_time);
}
double NormalizeRad(double rad) {
rad = fmod(rad, 2*M_PI);
if (rad < 0) {
rad += 2*M_PI;
}
return rad;
}
} // namespace navigation
<|endoftext|>
|
<commit_before>/*
* (C) Copyright 2013 Kurento (http://kurento.org/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "classifier.h"
#define FACE_CASCADE "/usr/share/opencv/lbpcascades/lbpcascade_frontalface.xml"
#include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace cv;
class Classifier
{
public:
Classifier ();
~Classifier() {};
CascadeClassifier face_cascade;
};
Classifier::Classifier()
{
face_cascade.load ( FACE_CASCADE );
}
static Classifier lbpClassifier = Classifier ();
void classify_image (IplImage *img, CvSeq *facesList)
{
std::vector<Rect> faces;
Mat frame (img);
Mat frame_gray;
cvtColor ( frame, frame_gray, COLOR_BGR2GRAY );
equalizeHist ( frame_gray, frame_gray );
lbpClassifier.face_cascade.detectMultiScale ( frame_gray, faces, 1.2, 3, 0,
Size (frame.cols / 20, frame.rows / 20),
Size (frame.cols / 2, frame.rows / 2) );
for ( size_t i = 0; i < faces.size(); i++ ) {
CvRect aux = cvRect (faces[i].x, faces[i].y, faces[i].width, faces[i].height);
cvSeqPush (facesList, &aux);
}
faces.clear();
}
<commit_msg>clang-tidy fix: [modernize-loop-convert]<commit_after>/*
* (C) Copyright 2013 Kurento (http://kurento.org/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "classifier.h"
#define FACE_CASCADE "/usr/share/opencv/lbpcascades/lbpcascade_frontalface.xml"
#include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace cv;
class Classifier
{
public:
Classifier ();
~Classifier() {};
CascadeClassifier face_cascade;
};
Classifier::Classifier()
{
face_cascade.load ( FACE_CASCADE );
}
static Classifier lbpClassifier = Classifier ();
void classify_image (IplImage *img, CvSeq *facesList)
{
std::vector<Rect> faces;
Mat frame (img);
Mat frame_gray;
cvtColor ( frame, frame_gray, COLOR_BGR2GRAY );
equalizeHist ( frame_gray, frame_gray );
lbpClassifier.face_cascade.detectMultiScale ( frame_gray, faces, 1.2, 3, 0,
Size (frame.cols / 20, frame.rows / 20),
Size (frame.cols / 2, frame.rows / 2) );
for (auto &face : faces) {
CvRect aux = cvRect(face.x, face.y, face.width, face.height);
cvSeqPush (facesList, &aux);
}
faces.clear();
}
<|endoftext|>
|
<commit_before>/**
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under both the Apache 2.0 license (found in the
* LICENSE file in the root directory of this source tree) and the GPLv2 (found
* in the COPYING file in the root directory of this source tree).
* You may select, at your option, one of the above-listed licenses.
*/
#include <functional>
#include <string>
#include "osquery/core/conversions.h"
#include "osquery/core/hashing.h"
#include <sqlite3.h>
namespace osquery {
static void hashSqliteValue(sqlite3_context* ctx,
int argc,
sqlite3_value** argv,
HashType ht) {
if (argc == 0) {
return;
}
if (SQLITE_NULL == sqlite3_value_type(argv[0])) {
sqlite3_result_null(ctx);
return;
}
// Parse and verify the split input parameters.
std::string input((char*)sqlite3_value_text(argv[0]));
auto result = hashFromBuffer(ht, input.data(), input.size());
sqlite3_result_text(
ctx, result.c_str(), static_cast<int>(result.size()), SQLITE_TRANSIENT);
}
static void sqliteMD5Func(sqlite3_context* context,
int argc,
sqlite3_value** argv) {
hashSqliteValue(context, argc, argv, HASH_TYPE_MD5);
}
static void sqliteSHA1Func(sqlite3_context* context,
int argc,
sqlite3_value** argv) {
hashSqliteValue(context, argc, argv, HASH_TYPE_SHA1);
}
static void sqliteSHA256Func(sqlite3_context* context,
int argc,
sqlite3_value** argv) {
hashSqliteValue(context, argc, argv, HASH_TYPE_SHA256);
}
void registerHashingExtensions(sqlite3* db) {
sqlite3_create_function(db,
"md5",
1,
SQLITE_UTF8 | SQLITE_DETERMINISTIC,
nullptr,
sqliteMD5Func,
nullptr,
nullptr);
sqlite3_create_function(db,
"sha1",
1,
SQLITE_UTF8 | SQLITE_DETERMINISTIC,
nullptr,
sqliteSHA1Func,
nullptr,
nullptr);
sqlite3_create_function(db,
"sha256",
1,
SQLITE_UTF8 | SQLITE_DETERMINISTIC,
nullptr,
sqliteSHA256Func,
nullptr,
nullptr);
}
} // namespace osquery
<commit_msg>get rid of unnecessary string conversion (#4506)<commit_after>/**
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under both the Apache 2.0 license (found in the
* LICENSE file in the root directory of this source tree) and the GPLv2 (found
* in the COPYING file in the root directory of this source tree).
* You may select, at your option, one of the above-listed licenses.
*/
#include <functional>
#include <string>
#include "osquery/core/conversions.h"
#include "osquery/core/hashing.h"
#include <sqlite3.h>
namespace osquery {
static void hashSqliteValue(sqlite3_context* ctx,
int argc,
sqlite3_value** argv,
HashType ht) {
if (argc == 0) {
return;
}
if (SQLITE_NULL == sqlite3_value_type(argv[0])) {
sqlite3_result_null(ctx);
return;
}
// Parse and verify the split input parameters.
const char* input =
reinterpret_cast<const char*>(sqlite3_value_text(argv[0]));
auto result = hashFromBuffer(ht, input, strlen(input));
sqlite3_result_text(
ctx, result.c_str(), static_cast<int>(result.size()), SQLITE_TRANSIENT);
}
static void sqliteMD5Func(sqlite3_context* context,
int argc,
sqlite3_value** argv) {
hashSqliteValue(context, argc, argv, HASH_TYPE_MD5);
}
static void sqliteSHA1Func(sqlite3_context* context,
int argc,
sqlite3_value** argv) {
hashSqliteValue(context, argc, argv, HASH_TYPE_SHA1);
}
static void sqliteSHA256Func(sqlite3_context* context,
int argc,
sqlite3_value** argv) {
hashSqliteValue(context, argc, argv, HASH_TYPE_SHA256);
}
void registerHashingExtensions(sqlite3* db) {
sqlite3_create_function(db,
"md5",
1,
SQLITE_UTF8 | SQLITE_DETERMINISTIC,
nullptr,
sqliteMD5Func,
nullptr,
nullptr);
sqlite3_create_function(db,
"sha1",
1,
SQLITE_UTF8 | SQLITE_DETERMINISTIC,
nullptr,
sqliteSHA1Func,
nullptr,
nullptr);
sqlite3_create_function(db,
"sha256",
1,
SQLITE_UTF8 | SQLITE_DETERMINISTIC,
nullptr,
sqliteSHA256Func,
nullptr,
nullptr);
}
} // namespace osquery
<|endoftext|>
|
<commit_before>#include "rosplan_planning_system/ProblemGeneration/ProblemInterface.h"
#include <fstream>
#include <sstream>
#include <string>
#include <ctime>
#include <string>
#include <streambuf>
namespace KCL_rosplan {
/*-------------*/
/* constructor */
/*-------------*/
ProblemInterface::ProblemInterface(ros::NodeHandle& nh)
{
node_handle = &nh;
// connecting to KB
std::string kb = "knowledge_base";
node_handle->getParam("knowledge_base", kb);
// Check problem fle extension to select a problem generator
std::string planning_lang;
node_handle->param<std::string>("planning_language", planning_lang, "");
std::transform(planning_lang.begin(), planning_lang.end(), planning_lang.begin(), ::tolower); // Convert to lowercase
node_handle->param<std::string>("problem_path", problem_path, "");
if (problem_path.empty() and planning_lang.empty()) {
ROS_ERROR("KCL: (%s) Parameters problem_path and planning_language are both undefined. At least one of them must be defined.",
ros::this_node::getName().c_str());
ros::shutdown();
}
KCL_rosplan::ProblemGeneratorFactory::ProbGen pg_type;
if (not problem_path.empty()) {
std::string extension = (problem_path.size() > 5) ? problem_path.substr(problem_path.find_last_of('.')) : "";
if (extension == ".pddl" or extension == ".ppddl") pg_type = KCL_rosplan::ProblemGeneratorFactory::PDDL;
else if (extension == ".rddl") pg_type = KCL_rosplan::ProblemGeneratorFactory::RDDL;
else {
ROS_ERROR("KCL: (%s) Unexpected problem file extension %s. Please provide a problem file written in PDDL (.pddl extension) or RDDL (.rddl extension).",
ros::this_node::getName().c_str(), extension.c_str());
ros::shutdown();
}
}
else if (not planning_lang.empty()) {
if (planning_lang == "pddl" or planning_lang == "ppddl") pg_type = KCL_rosplan::ProblemGeneratorFactory::PDDL;
else if (planning_lang == "rddl") pg_type = KCL_rosplan::ProblemGeneratorFactory::RDDL;
else {
ROS_ERROR("KCL: (%s) Unexpected planning language %s. Please specify the planning language as either \"PDDL\" or \"RDDL\".",
ros::this_node::getName().c_str(), planning_lang.c_str());
ros::shutdown();
}
}
else {
ROS_ERROR("KCL: (%s) Neither problem file nor planning language was specified! Please specify the parameter to know the planning language.",
ros::this_node::getName().c_str());
ros::shutdown();
}
problem_generator = KCL_rosplan::ProblemGeneratorFactory::createProblemGenerator(pg_type, kb);
// publishing "problem"
std::string problem_instance = "problem_instance";
node_handle->getParam("problem_topic", problem_instance);
problem_publisher = node_handle->advertise<std_msgs::String>(problem_instance, 1, true);
}
ProblemInterface::~ProblemInterface()
{
}
/*--------------------*/
/* Problem interface */
/*--------------------*/
/**
* problem generation service method (1)
* loads parameters from param server
*/
bool ProblemInterface::runProblemServerDefault(std_srvs::Empty::Request &req, std_srvs::Empty::Response &res) {
// defaults
problem_path = "common/problem.pddl";
// load params
node_handle->getParam("problem_path", problem_path);
// call problem server
return runProblemServer(problem_path);
}
/**
* problem generation service method (2)
* loads parameters from service request
*/
bool ProblemInterface::runProblemServerParams(rosplan_dispatch_msgs::ProblemService::Request &req, rosplan_dispatch_msgs::ProblemService::Response &res) {
// call problem server
bool success = runProblemServer(req.problem_path);
if(req.problem_string_response) {
std::ifstream problemIn(req.problem_path.c_str());
if(problemIn) res.problem_string = std::string(std::istreambuf_iterator<char>(problemIn), std::istreambuf_iterator<char>());
}
return success;
}
/**
* planning system; prepares planning; calls planner; parses plan.
*/
bool ProblemInterface::runProblemServer(std::string problemPath) {
ros::NodeHandle nh("~");
// save parameter
problem_path = problemPath;
// set problem name for ROS_INFO
std::size_t lastDivide = problem_path.find_last_of("/\\");
if(lastDivide != std::string::npos) {
problem_name = problem_path.substr(lastDivide+1);
} else {
problem_name = problem_path;
}
ROS_INFO("KCL: (%s) (%s) Generating problem file.", ros::this_node::getName().c_str(), problem_name.c_str());
problem_generator->generateProblemFile(problem_path);
ROS_INFO("KCL: (%s) (%s) The problem was generated.", ros::this_node::getName().c_str(), problem_name.c_str());
// publish problem
std::ifstream problemIn(problem_path.c_str());
if(problemIn) {
std_msgs::String problemMsg;
problemMsg.data = std::string(std::istreambuf_iterator<char>(problemIn), std::istreambuf_iterator<char>());
problem_publisher.publish(problemMsg);
}
return true;
}
} // close namespace
/*-------------*/
/* Main method */
/*-------------*/
int main(int argc, char **argv) {
srand (static_cast <unsigned> (time(0)));
ros::init(argc,argv,"rosplan_problem_interface");
ros::NodeHandle nh("~");
KCL_rosplan::ProblemInterface ProblemInterface(nh);
// start the planning services
ros::ServiceServer service1 = nh.advertiseService("problem_generation_server", &KCL_rosplan::ProblemInterface::runProblemServerDefault, &ProblemInterface);
ros::ServiceServer service2 = nh.advertiseService("problem_generation_server_params", &KCL_rosplan::ProblemInterface::runProblemServerParams, &ProblemInterface);
ROS_INFO("KCL: (%s) Ready to receive", ros::this_node::getName().c_str());
ros::spin();
return 0;
}
<commit_msg>Changed precedence of problem generator parameters<commit_after>#include "rosplan_planning_system/ProblemGeneration/ProblemInterface.h"
#include <fstream>
#include <sstream>
#include <string>
#include <ctime>
#include <string>
#include <streambuf>
namespace KCL_rosplan {
/*-------------*/
/* constructor */
/*-------------*/
ProblemInterface::ProblemInterface(ros::NodeHandle& nh)
{
node_handle = &nh;
// connecting to KB
std::string kb = "knowledge_base";
node_handle->getParam("knowledge_base", kb);
// Check problem fle extension to select a problem generator
std::string planning_lang;
node_handle->param<std::string>("planning_language", planning_lang, "");
std::transform(planning_lang.begin(), planning_lang.end(), planning_lang.begin(), ::tolower); // Convert to lowercase
node_handle->param<std::string>("problem_path", problem_path, "");
if (problem_path.empty() and planning_lang.empty()) {
ROS_ERROR("KCL: (%s) Parameters problem_path and planning_language are both undefined. At least one of them must be defined.",
ros::this_node::getName().c_str());
ros::shutdown();
}
KCL_rosplan::ProblemGeneratorFactory::ProbGen pg_type;
if (not planning_lang.empty()) {
if (planning_lang == "pddl" or planning_lang == "ppddl") pg_type = KCL_rosplan::ProblemGeneratorFactory::PDDL;
else if (planning_lang == "rddl") pg_type = KCL_rosplan::ProblemGeneratorFactory::RDDL;
else {
ROS_WARN("KCL: (%s) Unexpected planning language %s. Please specify the planning language as either \"PDDL\" or \"RDDL\".",
ros::this_node::getName().c_str(), planning_lang.c_str());
}
} // If roblem path is specified, it'll overwrite the setting from the planning_lang parameter.
if (not problem_path.empty()) {
std::string extension = (problem_path.size() > 5) ? problem_path.substr(problem_path.find_last_of('.')) : "";
if (extension == ".pddl" or extension == ".ppddl") pg_type = KCL_rosplan::ProblemGeneratorFactory::PDDL;
else if (extension == ".rddl") pg_type = KCL_rosplan::ProblemGeneratorFactory::RDDL;
else {
ROS_ERROR("KCL: (%s) Unexpected problem file extension %s. Please provide a problem file written in PDDL (.pddl extension) or RDDL (.rddl extension).",
ros::this_node::getName().c_str(), extension.c_str());
ros::shutdown();
}
}
else {
ROS_ERROR("KCL: (%s) Neither problem file nor planning language was specified! Please specify the parameter to know the planning language.",
ros::this_node::getName().c_str());
ros::shutdown();
}
problem_generator = KCL_rosplan::ProblemGeneratorFactory::createProblemGenerator(pg_type, kb);
// publishing "problem"
std::string problem_instance = "problem_instance";
node_handle->getParam("problem_topic", problem_instance);
problem_publisher = node_handle->advertise<std_msgs::String>(problem_instance, 1, true);
}
ProblemInterface::~ProblemInterface()
{
}
/*--------------------*/
/* Problem interface */
/*--------------------*/
/**
* problem generation service method (1)
* loads parameters from param server
*/
bool ProblemInterface::runProblemServerDefault(std_srvs::Empty::Request &req, std_srvs::Empty::Response &res) {
// defaults
problem_path = "common/problem.pddl";
// load params
node_handle->getParam("problem_path", problem_path);
// call problem server
return runProblemServer(problem_path);
}
/**
* problem generation service method (2)
* loads parameters from service request
*/
bool ProblemInterface::runProblemServerParams(rosplan_dispatch_msgs::ProblemService::Request &req, rosplan_dispatch_msgs::ProblemService::Response &res) {
// call problem server
bool success = runProblemServer(req.problem_path);
if(req.problem_string_response) {
std::ifstream problemIn(req.problem_path.c_str());
if(problemIn) res.problem_string = std::string(std::istreambuf_iterator<char>(problemIn), std::istreambuf_iterator<char>());
}
return success;
}
/**
* planning system; prepares planning; calls planner; parses plan.
*/
bool ProblemInterface::runProblemServer(std::string problemPath) {
ros::NodeHandle nh("~");
// save parameter
problem_path = problemPath;
// set problem name for ROS_INFO
std::size_t lastDivide = problem_path.find_last_of("/\\");
if(lastDivide != std::string::npos) {
problem_name = problem_path.substr(lastDivide+1);
} else {
problem_name = problem_path;
}
ROS_INFO("KCL: (%s) (%s) Generating problem file.", ros::this_node::getName().c_str(), problem_name.c_str());
problem_generator->generateProblemFile(problem_path);
ROS_INFO("KCL: (%s) (%s) The problem was generated.", ros::this_node::getName().c_str(), problem_name.c_str());
// publish problem
std::ifstream problemIn(problem_path.c_str());
if(problemIn) {
std_msgs::String problemMsg;
problemMsg.data = std::string(std::istreambuf_iterator<char>(problemIn), std::istreambuf_iterator<char>());
problem_publisher.publish(problemMsg);
}
return true;
}
} // close namespace
/*-------------*/
/* Main method */
/*-------------*/
int main(int argc, char **argv) {
srand (static_cast <unsigned> (time(0)));
ros::init(argc,argv,"rosplan_problem_interface");
ros::NodeHandle nh("~");
KCL_rosplan::ProblemInterface ProblemInterface(nh);
// start the planning services
ros::ServiceServer service1 = nh.advertiseService("problem_generation_server", &KCL_rosplan::ProblemInterface::runProblemServerDefault, &ProblemInterface);
ros::ServiceServer service2 = nh.advertiseService("problem_generation_server_params", &KCL_rosplan::ProblemInterface::runProblemServerParams, &ProblemInterface);
ROS_INFO("KCL: (%s) Ready to receive", ros::this_node::getName().c_str());
ros::spin();
return 0;
}
<|endoftext|>
|
<commit_before>#include "node_map.hpp"
#include "node_file_source.hpp"
#include <mbgl/platform/default/headless_display.hpp>
#include <mbgl/map/still_image.hpp>
#include <mbgl/util/exception.hpp>
#include <unistd.h>
namespace node_mbgl {
struct NodeMap::RenderOptions {
double zoom = 0;
double bearing = 0;
double latitude = 0;
double longitude = 0;
unsigned int width = 512;
unsigned int height = 512;
float ratio = 1.0f;
std::vector<std::string> classes;
};
////////////////////////////////////////////////////////////////////////////////////////////////
// Static Node Methods
v8::Persistent<v8::FunctionTemplate> NodeMap::constructorTemplate;
void NodeMap::Init(v8::Handle<v8::Object> target) {
NanScope();
v8::Local<v8::FunctionTemplate> t = NanNew<v8::FunctionTemplate>(New);
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(NanNew("Map"));
NODE_SET_PROTOTYPE_METHOD(t, "setAccessToken", SetAccessToken);
NODE_SET_PROTOTYPE_METHOD(t, "load", Load);
NODE_SET_PROTOTYPE_METHOD(t, "render", Render);
NanAssignPersistent(constructorTemplate, t);
target->Set(NanNew("Map"), t->GetFunction());
}
NAN_METHOD(NodeMap::New) {
NanScope();
if (!args.IsConstructCall()) {
return NanThrowTypeError("Use the new operator to create new Map objects");
}
if (args.Length() < 1 || !NanHasInstance(NodeFileSource::constructorTemplate, args[0])) {
return NanThrowTypeError("Requires a FileSource as first argument");
}
auto source = args[0]->ToObject();
// Check that request() and cancel() are defined.
if (!source->Has(NanNew("request")) || !source->Get(NanNew("request"))->IsFunction()) {
return NanThrowError("FileSource must have a request member function");
}
if (!source->Has(NanNew("cancel")) || !source->Get(NanNew("cancel"))->IsFunction()) {
return NanThrowError("FileSource must have a cancel member function");
}
auto map = new NodeMap(args[0]->ToObject());
map->Wrap(args.This());
NanReturnValue(args.This());
}
NAN_METHOD(NodeMap::SetAccessToken) {
NanScope();
if (args.Length() < 1) {
return NanThrowError("Requires a string as first argument");
}
NanUtf8String token(args[0]);
auto nodeMap = node::ObjectWrap::Unwrap<NodeMap>(args.Holder());
if (nodeMap->map.isRendering()) {
return NanThrowError("Map object is currently in use");
}
try {
nodeMap->map.setAccessToken(std::string { *token, size_t(token.length()) });
} catch (const std::exception &ex) {
return NanThrowError(ex.what());
}
NanReturnUndefined();
}
const std::string StringifyStyle(v8::Handle<v8::Value> styleHandle) {
NanScope();
auto JSON = NanGetCurrentContext()->Global()->Get(NanNew("JSON"))->ToObject();
auto stringify = v8::Handle<v8::Function>::Cast(JSON->Get(NanNew("stringify")));
return *NanUtf8String(stringify->Call(JSON, 1, &styleHandle));
}
NAN_METHOD(NodeMap::Load) {
NanScope();
if (args.Length() < 1) {
return NanThrowError("Requires a map style as first argument");
}
std::string style;
if (args[0]->IsObject()) {
style = StringifyStyle(args[0]);
} else if (args[0]->IsString()) {
NanUtf8String string(args[0]);
style = { *string, size_t(string.length()) };
} else {
return NanThrowTypeError("First argument must be a string or object");
}
auto nodeMap = node::ObjectWrap::Unwrap<NodeMap>(args.Holder());
if (nodeMap->map.isRendering()) {
return NanThrowError("Map object is currently in use");
}
try {
nodeMap->map.setStyleJSON(style, ".");
} catch (const std::exception &ex) {
return NanThrowError(ex.what());
}
NanReturnUndefined();
}
std::unique_ptr<NodeMap::RenderOptions> NodeMap::ParseOptions(v8::Local<v8::Object> obj) {
NanScope();
auto options = mbgl::util::make_unique<RenderOptions>();
if (obj->Has(NanNew("zoom"))) { options->zoom = obj->Get(NanNew("zoom"))->NumberValue(); }
if (obj->Has(NanNew("bearing"))) { options->bearing = obj->Get(NanNew("bearing"))->NumberValue(); }
if (obj->Has(NanNew("center"))) {
auto center = obj->Get(NanNew("center")).As<v8::Array>();
if (center->Length() > 0) { options->latitude = center->Get(0)->NumberValue(); }
if (center->Length() > 1) { options->longitude = center->Get(1)->NumberValue(); }
}
if (obj->Has(NanNew("width"))) { options->width = obj->Get(NanNew("width"))->IntegerValue(); }
if (obj->Has(NanNew("height"))) { options->height = obj->Get(NanNew("height"))->IntegerValue(); }
if (obj->Has(NanNew("ratio"))) { options->ratio = obj->Get(NanNew("ratio"))->IntegerValue(); }
if (obj->Has(NanNew("classes"))) {
auto classes = obj->Get(NanNew("classes"))->ToObject().As<v8::Array>();
const int length = classes->Length();
options->classes.reserve(length);
for (int i = 0; i < length; i++) {
options->classes.push_back(std::string { *NanUtf8String(classes->Get(i)->ToString()) });
}
}
return options;
}
NAN_METHOD(NodeMap::Render) {
NanScope();
if (args.Length() <= 0 || !args[0]->IsObject()) {
return NanThrowTypeError("First argument must be an options object");
}
if (args.Length() <= 1 || !args[1]->IsFunction()) {
return NanThrowTypeError("Second argument must be a callback function");
}
auto options = ParseOptions(args[0]->ToObject());
auto nodeMap = node::ObjectWrap::Unwrap<NodeMap>(args.Holder());
if (nodeMap->map.isRendering()) {
return NanThrowError("Map object is currently in use");
}
assert(!nodeMap->callback);
assert(!nodeMap->image);
nodeMap->callback = std::unique_ptr<NanCallback>(new NanCallback(args[1].As<v8::Function>()));
try {
nodeMap->startRender(std::move(options));
} catch (mbgl::util::Exception &ex) {
return NanThrowError(ex.what());
}
NanReturnUndefined();
}
void NodeMap::startRender(std::unique_ptr<NodeMap::RenderOptions> options) {
view.resize(options->width, options->height, options->ratio);
map.setClasses(options->classes);
map.setLonLatZoom(options->longitude, options->latitude, options->zoom);
map.setBearing(options->bearing);
map.renderStill([this](std::unique_ptr<const mbgl::StillImage> result) {
assert(!image);
image = std::move(result);
uv_async_send(async);
});
// Retain this object, otherwise it might get destructed before we are finished rendering the
// still image.
Ref();
// Similarly, we're now waiting for the async to be called, so we need to make sure that it
// keeps the loop alive.
uv_ref(reinterpret_cast<uv_handle_t *>(async));
}
void NodeMap::renderFinished() {
NanScope();
// We're done with this render call, so we're unrefing so that the loop could close.
uv_unref(reinterpret_cast<uv_handle_t *>(async));
// There is no render pending anymore, we the GC could now delete this object if it went out
// of scope.
Unref();
// Move the callback and image out of the way so that the callback can start a new render call.
auto cb = std::move(callback);
auto img = std::move(image);
assert(cb);
// These have to be empty to be prepared for the next render call.
assert(!callback);
assert(!image);
if (img) {
v8::Local<v8::Object> result = v8::Object::New();
result->Set(NanNew("width"), NanNew(img->width));
result->Set(NanNew("height"), NanNew(img->height));
v8::Local<v8::Object> pixels = NanNewBufferHandle(
reinterpret_cast<char *>(img->pixels.get()),
size_t(img->width) * size_t(img->height) * sizeof(mbgl::StillImage::Pixel),
// Retain the StillImage object until the buffer is deleted.
[](char *, void *hint) {
delete reinterpret_cast<const mbgl::StillImage *>(hint);
},
const_cast<mbgl::StillImage *>(img.get())
);
img.release();
result->Set(NanNew("pixels"), pixels);
v8::Local<v8::Value> argv[] = {
NanNull(),
result,
};
cb->Call(2, argv);
} else {
v8::Local<v8::Value> argv[] = {
NanError("Didn't get an image")
};
cb->Call(1, argv);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Instance
std::shared_ptr<mbgl::HeadlessDisplay> sharedDisplay() {
static auto display = std::make_shared<mbgl::HeadlessDisplay>();
return display;
}
NodeMap::NodeMap(v8::Handle<v8::Object> source_) :
view(sharedDisplay()),
fs(*ObjectWrap::Unwrap<NodeFileSource>(source_)),
map(view, fs, mbgl::Map::RenderMode::Still),
async(new uv_async_t) {
source = v8::Persistent<v8::Object>::New(source_);
async->data = this;
uv_async_init(uv_default_loop(), async, [](uv_async_t *as, int) {
reinterpret_cast<NodeMap *>(as->data)->renderFinished();
});
// Make sure the async handle doesn't keep the loop alive.
uv_unref(reinterpret_cast<uv_handle_t *>(async));
}
NodeMap::~NodeMap() {
source.Dispose();
uv_close(reinterpret_cast<uv_handle_t *>(async), [] (uv_handle_t *handle) {
delete reinterpret_cast<uv_async_t *>(handle);
});
}
}
<commit_msg>fix setLatLngZooom<commit_after>#include "node_map.hpp"
#include "node_file_source.hpp"
#include <mbgl/platform/default/headless_display.hpp>
#include <mbgl/map/still_image.hpp>
#include <mbgl/util/exception.hpp>
#include <unistd.h>
namespace node_mbgl {
struct NodeMap::RenderOptions {
double zoom = 0;
double bearing = 0;
double latitude = 0;
double longitude = 0;
unsigned int width = 512;
unsigned int height = 512;
float ratio = 1.0f;
std::vector<std::string> classes;
};
////////////////////////////////////////////////////////////////////////////////////////////////
// Static Node Methods
v8::Persistent<v8::FunctionTemplate> NodeMap::constructorTemplate;
void NodeMap::Init(v8::Handle<v8::Object> target) {
NanScope();
v8::Local<v8::FunctionTemplate> t = NanNew<v8::FunctionTemplate>(New);
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(NanNew("Map"));
NODE_SET_PROTOTYPE_METHOD(t, "setAccessToken", SetAccessToken);
NODE_SET_PROTOTYPE_METHOD(t, "load", Load);
NODE_SET_PROTOTYPE_METHOD(t, "render", Render);
NanAssignPersistent(constructorTemplate, t);
target->Set(NanNew("Map"), t->GetFunction());
}
NAN_METHOD(NodeMap::New) {
NanScope();
if (!args.IsConstructCall()) {
return NanThrowTypeError("Use the new operator to create new Map objects");
}
if (args.Length() < 1 || !NanHasInstance(NodeFileSource::constructorTemplate, args[0])) {
return NanThrowTypeError("Requires a FileSource as first argument");
}
auto source = args[0]->ToObject();
// Check that request() and cancel() are defined.
if (!source->Has(NanNew("request")) || !source->Get(NanNew("request"))->IsFunction()) {
return NanThrowError("FileSource must have a request member function");
}
if (!source->Has(NanNew("cancel")) || !source->Get(NanNew("cancel"))->IsFunction()) {
return NanThrowError("FileSource must have a cancel member function");
}
auto map = new NodeMap(args[0]->ToObject());
map->Wrap(args.This());
NanReturnValue(args.This());
}
NAN_METHOD(NodeMap::SetAccessToken) {
NanScope();
if (args.Length() < 1) {
return NanThrowError("Requires a string as first argument");
}
NanUtf8String token(args[0]);
auto nodeMap = node::ObjectWrap::Unwrap<NodeMap>(args.Holder());
if (nodeMap->map.isRendering()) {
return NanThrowError("Map object is currently in use");
}
try {
nodeMap->map.setAccessToken(std::string { *token, size_t(token.length()) });
} catch (const std::exception &ex) {
return NanThrowError(ex.what());
}
NanReturnUndefined();
}
const std::string StringifyStyle(v8::Handle<v8::Value> styleHandle) {
NanScope();
auto JSON = NanGetCurrentContext()->Global()->Get(NanNew("JSON"))->ToObject();
auto stringify = v8::Handle<v8::Function>::Cast(JSON->Get(NanNew("stringify")));
return *NanUtf8String(stringify->Call(JSON, 1, &styleHandle));
}
NAN_METHOD(NodeMap::Load) {
NanScope();
if (args.Length() < 1) {
return NanThrowError("Requires a map style as first argument");
}
std::string style;
if (args[0]->IsObject()) {
style = StringifyStyle(args[0]);
} else if (args[0]->IsString()) {
NanUtf8String string(args[0]);
style = { *string, size_t(string.length()) };
} else {
return NanThrowTypeError("First argument must be a string or object");
}
auto nodeMap = node::ObjectWrap::Unwrap<NodeMap>(args.Holder());
if (nodeMap->map.isRendering()) {
return NanThrowError("Map object is currently in use");
}
try {
nodeMap->map.setStyleJSON(style, ".");
} catch (const std::exception &ex) {
return NanThrowError(ex.what());
}
NanReturnUndefined();
}
std::unique_ptr<NodeMap::RenderOptions> NodeMap::ParseOptions(v8::Local<v8::Object> obj) {
NanScope();
auto options = mbgl::util::make_unique<RenderOptions>();
if (obj->Has(NanNew("zoom"))) { options->zoom = obj->Get(NanNew("zoom"))->NumberValue(); }
if (obj->Has(NanNew("bearing"))) { options->bearing = obj->Get(NanNew("bearing"))->NumberValue(); }
if (obj->Has(NanNew("center"))) {
auto center = obj->Get(NanNew("center")).As<v8::Array>();
if (center->Length() > 0) { options->latitude = center->Get(0)->NumberValue(); }
if (center->Length() > 1) { options->longitude = center->Get(1)->NumberValue(); }
}
if (obj->Has(NanNew("width"))) { options->width = obj->Get(NanNew("width"))->IntegerValue(); }
if (obj->Has(NanNew("height"))) { options->height = obj->Get(NanNew("height"))->IntegerValue(); }
if (obj->Has(NanNew("ratio"))) { options->ratio = obj->Get(NanNew("ratio"))->IntegerValue(); }
if (obj->Has(NanNew("classes"))) {
auto classes = obj->Get(NanNew("classes"))->ToObject().As<v8::Array>();
const int length = classes->Length();
options->classes.reserve(length);
for (int i = 0; i < length; i++) {
options->classes.push_back(std::string { *NanUtf8String(classes->Get(i)->ToString()) });
}
}
return options;
}
NAN_METHOD(NodeMap::Render) {
NanScope();
if (args.Length() <= 0 || !args[0]->IsObject()) {
return NanThrowTypeError("First argument must be an options object");
}
if (args.Length() <= 1 || !args[1]->IsFunction()) {
return NanThrowTypeError("Second argument must be a callback function");
}
auto options = ParseOptions(args[0]->ToObject());
auto nodeMap = node::ObjectWrap::Unwrap<NodeMap>(args.Holder());
if (nodeMap->map.isRendering()) {
return NanThrowError("Map object is currently in use");
}
assert(!nodeMap->callback);
assert(!nodeMap->image);
nodeMap->callback = std::unique_ptr<NanCallback>(new NanCallback(args[1].As<v8::Function>()));
try {
nodeMap->startRender(std::move(options));
} catch (mbgl::util::Exception &ex) {
return NanThrowError(ex.what());
}
NanReturnUndefined();
}
void NodeMap::startRender(std::unique_ptr<NodeMap::RenderOptions> options) {
view.resize(options->width, options->height, options->ratio);
map.setClasses(options->classes);
map.setLatLngZoom(mbgl::LatLng(options->longitude, options->latitude), options->zoom);
map.setBearing(options->bearing);
map.renderStill([this](std::unique_ptr<const mbgl::StillImage> result) {
assert(!image);
image = std::move(result);
uv_async_send(async);
});
// Retain this object, otherwise it might get destructed before we are finished rendering the
// still image.
Ref();
// Similarly, we're now waiting for the async to be called, so we need to make sure that it
// keeps the loop alive.
uv_ref(reinterpret_cast<uv_handle_t *>(async));
}
void NodeMap::renderFinished() {
NanScope();
// We're done with this render call, so we're unrefing so that the loop could close.
uv_unref(reinterpret_cast<uv_handle_t *>(async));
// There is no render pending anymore, we the GC could now delete this object if it went out
// of scope.
Unref();
// Move the callback and image out of the way so that the callback can start a new render call.
auto cb = std::move(callback);
auto img = std::move(image);
assert(cb);
// These have to be empty to be prepared for the next render call.
assert(!callback);
assert(!image);
if (img) {
v8::Local<v8::Object> result = v8::Object::New();
result->Set(NanNew("width"), NanNew(img->width));
result->Set(NanNew("height"), NanNew(img->height));
v8::Local<v8::Object> pixels = NanNewBufferHandle(
reinterpret_cast<char *>(img->pixels.get()),
size_t(img->width) * size_t(img->height) * sizeof(mbgl::StillImage::Pixel),
// Retain the StillImage object until the buffer is deleted.
[](char *, void *hint) {
delete reinterpret_cast<const mbgl::StillImage *>(hint);
},
const_cast<mbgl::StillImage *>(img.get())
);
img.release();
result->Set(NanNew("pixels"), pixels);
v8::Local<v8::Value> argv[] = {
NanNull(),
result,
};
cb->Call(2, argv);
} else {
v8::Local<v8::Value> argv[] = {
NanError("Didn't get an image")
};
cb->Call(1, argv);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Instance
std::shared_ptr<mbgl::HeadlessDisplay> sharedDisplay() {
static auto display = std::make_shared<mbgl::HeadlessDisplay>();
return display;
}
NodeMap::NodeMap(v8::Handle<v8::Object> source_) :
view(sharedDisplay()),
fs(*ObjectWrap::Unwrap<NodeFileSource>(source_)),
map(view, fs, mbgl::Map::RenderMode::Still),
async(new uv_async_t) {
source = v8::Persistent<v8::Object>::New(source_);
async->data = this;
uv_async_init(uv_default_loop(), async, [](uv_async_t *as, int) {
reinterpret_cast<NodeMap *>(as->data)->renderFinished();
});
// Make sure the async handle doesn't keep the loop alive.
uv_unref(reinterpret_cast<uv_handle_t *>(async));
}
NodeMap::~NodeMap() {
source.Dispose();
uv_close(reinterpret_cast<uv_handle_t *>(async), [] (uv_handle_t *handle) {
delete reinterpret_cast<uv_async_t *>(handle);
});
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: rlrcitem.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2006-06-19 15:27: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
*
************************************************************************/
// INCLUDE ---------------------------------------------------------------
#ifndef _SFXRECTITEM_HXX
#include <svtools/rectitem.hxx>
#endif
#define ITEMID_LRSPACE 0
#define ITEMID_ULSPACE 0
#define ITEMID_TABSTOP 0
#define ITEMID_PROTECT 0
#include "dialogs.hrc"
#include "ruler.hxx"
#include "lrspitem.hxx"
#include "ulspitem.hxx"
#include "tstpitem.hxx"
#include "protitem.hxx"
#include "rlrcitem.hxx"
#include "rulritem.hxx"
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif
// class SvxRulerItem ----------------------------------------------------
SvxRulerItem::SvxRulerItem(USHORT _nId, SvxRuler &rRul, SfxBindings &rBindings)
: SfxControllerItem(_nId, rBindings),
rRuler(rRul)
{
}
// -----------------------------------------------------------------------
void SvxRulerItem::StateChanged( USHORT nSID, SfxItemState eState,
const SfxPoolItem* pState)
{
// SFX_ITEM_DONTCARE => pState == -1 => PTR_CAST buff
if ( eState != SFX_ITEM_AVAILABLE )
pState = 0;
switch(nSID)
{
// Linker / rechter Seitenrand
case SID_RULER_LR_MIN_MAX:
{
const SfxRectangleItem *pItem = PTR_CAST(SfxRectangleItem, pState);
rRuler.UpdateFrameMinMax(pItem);
break;
}
case SID_ATTR_LONG_LRSPACE:
{
const SvxLongLRSpaceItem *pItem = PTR_CAST(SvxLongLRSpaceItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxLRSpaceItem erwartet");
rRuler.UpdateFrame(pItem);
break;
}
case SID_ATTR_LONG_ULSPACE:
{
const SvxLongULSpaceItem *pItem = PTR_CAST(SvxLongULSpaceItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxULSpaceItem erwartet");
rRuler.UpdateFrame(pItem);
break;
}
case SID_ATTR_TABSTOP_VERTICAL:
case SID_ATTR_TABSTOP:
{
const SvxTabStopItem *pItem = PTR_CAST(SvxTabStopItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxTabStopItem erwartet");
rRuler.Update(pItem);
break;
}
case SID_ATTR_PARA_LRSPACE_VERTICAL:
case SID_ATTR_PARA_LRSPACE:
{
const SvxLRSpaceItem *pItem = PTR_CAST(SvxLRSpaceItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxLRSpaceItem erwartet");
rRuler.UpdatePara(pItem);
break;
}
case SID_RULER_BORDERS_VERTICAL:
case SID_RULER_BORDERS:
case SID_RULER_ROWS:
case SID_RULER_ROWS_VERTICAL:
{
const SvxColumnItem *pItem = PTR_CAST(SvxColumnItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxColumnItem erwartet");
#ifdef DBG_UTIL
if(pItem)
{
if(pItem->IsConsistent())
rRuler.Update(pItem, nSID);
else
DBG_ERROR("Spaltenitem corrupted");
}
else
rRuler.Update(pItem, nSID);
#else
rRuler.Update(pItem, nSID);
#endif
break;
}
case SID_RULER_PAGE_POS:
{ // Position Seite, Seitenbreite
const SvxPagePosSizeItem *pItem = PTR_CAST(SvxPagePosSizeItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxPagePosSizeItem erwartet");
rRuler.Update(pItem);
break;
}
case SID_RULER_OBJECT:
{ // Object-Selektion
const SvxObjectItem *pItem = PTR_CAST(SvxObjectItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxObjectItem erwartet");
rRuler.Update(pItem);
break;
}
case SID_RULER_PROTECT:
{
const SvxProtectItem *pItem = PTR_CAST(SvxProtectItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxProtectItem erwartet");
rRuler.Update(pItem);
break;
}
case SID_RULER_BORDER_DISTANCE:
{
const SvxLRSpaceItem *pItem = PTR_CAST(SvxLRSpaceItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxLRSpaceItem erwartet");
rRuler.UpdateParaBorder(pItem);
}
break;
case SID_RULER_TEXT_RIGHT_TO_LEFT :
{
const SfxBoolItem *pItem = PTR_CAST(SfxBoolItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SfxBoolItem erwartet");
rRuler.UpdateTextRTL(pItem);
}
break;
}
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.7.116); FILE MERGED 2006/09/01 17:46:22 kaib 1.7.116.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: rlrcitem.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: obo $ $Date: 2006-09-17 04:36:29 $
*
* 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_svx.hxx"
// INCLUDE ---------------------------------------------------------------
#ifndef _SFXRECTITEM_HXX
#include <svtools/rectitem.hxx>
#endif
#define ITEMID_LRSPACE 0
#define ITEMID_ULSPACE 0
#define ITEMID_TABSTOP 0
#define ITEMID_PROTECT 0
#include "dialogs.hrc"
#include "ruler.hxx"
#include "lrspitem.hxx"
#include "ulspitem.hxx"
#include "tstpitem.hxx"
#include "protitem.hxx"
#include "rlrcitem.hxx"
#include "rulritem.hxx"
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif
// class SvxRulerItem ----------------------------------------------------
SvxRulerItem::SvxRulerItem(USHORT _nId, SvxRuler &rRul, SfxBindings &rBindings)
: SfxControllerItem(_nId, rBindings),
rRuler(rRul)
{
}
// -----------------------------------------------------------------------
void SvxRulerItem::StateChanged( USHORT nSID, SfxItemState eState,
const SfxPoolItem* pState)
{
// SFX_ITEM_DONTCARE => pState == -1 => PTR_CAST buff
if ( eState != SFX_ITEM_AVAILABLE )
pState = 0;
switch(nSID)
{
// Linker / rechter Seitenrand
case SID_RULER_LR_MIN_MAX:
{
const SfxRectangleItem *pItem = PTR_CAST(SfxRectangleItem, pState);
rRuler.UpdateFrameMinMax(pItem);
break;
}
case SID_ATTR_LONG_LRSPACE:
{
const SvxLongLRSpaceItem *pItem = PTR_CAST(SvxLongLRSpaceItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxLRSpaceItem erwartet");
rRuler.UpdateFrame(pItem);
break;
}
case SID_ATTR_LONG_ULSPACE:
{
const SvxLongULSpaceItem *pItem = PTR_CAST(SvxLongULSpaceItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxULSpaceItem erwartet");
rRuler.UpdateFrame(pItem);
break;
}
case SID_ATTR_TABSTOP_VERTICAL:
case SID_ATTR_TABSTOP:
{
const SvxTabStopItem *pItem = PTR_CAST(SvxTabStopItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxTabStopItem erwartet");
rRuler.Update(pItem);
break;
}
case SID_ATTR_PARA_LRSPACE_VERTICAL:
case SID_ATTR_PARA_LRSPACE:
{
const SvxLRSpaceItem *pItem = PTR_CAST(SvxLRSpaceItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxLRSpaceItem erwartet");
rRuler.UpdatePara(pItem);
break;
}
case SID_RULER_BORDERS_VERTICAL:
case SID_RULER_BORDERS:
case SID_RULER_ROWS:
case SID_RULER_ROWS_VERTICAL:
{
const SvxColumnItem *pItem = PTR_CAST(SvxColumnItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxColumnItem erwartet");
#ifdef DBG_UTIL
if(pItem)
{
if(pItem->IsConsistent())
rRuler.Update(pItem, nSID);
else
DBG_ERROR("Spaltenitem corrupted");
}
else
rRuler.Update(pItem, nSID);
#else
rRuler.Update(pItem, nSID);
#endif
break;
}
case SID_RULER_PAGE_POS:
{ // Position Seite, Seitenbreite
const SvxPagePosSizeItem *pItem = PTR_CAST(SvxPagePosSizeItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxPagePosSizeItem erwartet");
rRuler.Update(pItem);
break;
}
case SID_RULER_OBJECT:
{ // Object-Selektion
const SvxObjectItem *pItem = PTR_CAST(SvxObjectItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxObjectItem erwartet");
rRuler.Update(pItem);
break;
}
case SID_RULER_PROTECT:
{
const SvxProtectItem *pItem = PTR_CAST(SvxProtectItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxProtectItem erwartet");
rRuler.Update(pItem);
break;
}
case SID_RULER_BORDER_DISTANCE:
{
const SvxLRSpaceItem *pItem = PTR_CAST(SvxLRSpaceItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SvxLRSpaceItem erwartet");
rRuler.UpdateParaBorder(pItem);
}
break;
case SID_RULER_TEXT_RIGHT_TO_LEFT :
{
const SfxBoolItem *pItem = PTR_CAST(SfxBoolItem, pState);
DBG_ASSERT(pState? 0 != pItem: TRUE, "SfxBoolItem erwartet");
rRuler.UpdateTextRTL(pItem);
}
break;
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/platform_thread.h"
#include "base/string_util.h"
#include "base/test_file_util.h"
#include "base/time.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
using base::TimeDelta;
using base::TimeTicks;
namespace {
class StartupTest : public UITest {
public:
StartupTest() {
show_window_ = true;
pages_ = "about:blank";
}
void SetUp() {}
void TearDown() {}
void RunStartupTest(const wchar_t* graph, const wchar_t* trace,
bool test_cold, bool important) {
const int kNumCycles = 20;
TimeDelta timings[kNumCycles];
for (int i = 0; i < kNumCycles; ++i) {
if (test_cold) {
FilePath dir_app;
ASSERT_TRUE(PathService::Get(chrome::DIR_APP, &dir_app));
FilePath chrome_exe(dir_app.Append(
FilePath::FromWStringHack(chrome::kBrowserProcessExecutableName)));
ASSERT_TRUE(file_util::EvictFileFromSystemCache(chrome_exe));
#if defined(OS_WIN)
// TODO(port): these files do not exist on other platforms.
// Decide what to do.
FilePath chrome_dll(dir_app.Append(FILE_PATH_LITERAL("chrome.dll")));
ASSERT_TRUE(file_util::EvictFileFromSystemCache(chrome_dll));
FilePath gears_dll;
ASSERT_TRUE(PathService::Get(chrome::FILE_GEARS_PLUGIN, &gears_dll));
ASSERT_TRUE(file_util::EvictFileFromSystemCache(gears_dll));
#endif // defined(OS_WIN)
}
UITest::SetUp();
TimeTicks end_time = TimeTicks::Now();
timings[i] = end_time - browser_launch_time_;
// TODO(beng): Can't shut down so quickly. Figure out why, and fix. If we
// do, we crash.
PlatformThread::Sleep(50);
UITest::TearDown();
if (i == 0) {
// Re-use the profile data after first run so that the noise from
// creating databases doesn't impact all the runs.
clear_profile_ = false;
}
}
std::wstring times;
for (int i = 0; i < kNumCycles; ++i)
StringAppendF(×, L"%.2f,", timings[i].InMillisecondsF());
PrintResultList(graph, L"", trace, times, L"ms", important);
}
protected:
std::string pages_;
};
class StartupReferenceTest : public StartupTest {
public:
// override the browser directory that is used by UITest::SetUp to cause it
// to use the reference build instead.
void SetUp() {
std::wstring dir;
PathService::Get(chrome::DIR_TEST_TOOLS, &dir);
file_util::AppendToPath(&dir, L"reference_build");
file_util::AppendToPath(&dir, L"chrome");
browser_directory_ = dir;
}
};
class StartupFileTest : public StartupTest {
public:
// Load a file on startup rather than about:blank. This tests a longer
// startup path, including resource loading and the loading of gears.dll.
void SetUp() {
std::wstring file_url;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &file_url));
file_util::AppendToPath(&file_url, L"empty.html");
ASSERT_TRUE(file_util::PathExists(file_url));
launch_arguments_.AppendLooseValue(file_url);
pages_ = WideToUTF8(file_url);
}
};
} // namespace
TEST_F(StartupTest, Perf) {
RunStartupTest(L"warm", L"t", false /* not cold */, true /* important */);
}
#if defined(OS_WIN)
// TODO(port): Enable reference tests on other platforms.
TEST_F(StartupReferenceTest, Perf) {
RunStartupTest(L"warm", L"t_ref", false /* not cold */,
true /* important */);
}
// TODO(mpcomplete): Should we have reference timings for all these?
TEST_F(StartupTest, PerfCold) {
RunStartupTest(L"cold", L"t", true /* cold */, false /* not important */);
}
TEST_F(StartupFileTest, PerfGears) {
RunStartupTest(L"warm", L"gears", false /* not cold */,
false /* not important */);
}
TEST_F(StartupFileTest, PerfColdGears) {
RunStartupTest(L"cold", L"gears", true /* cold */,
false /* not important */);
}
#endif // defined(OS_WIN)
<commit_msg>Fix startup_test failures on Windows buildbot.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/platform_thread.h"
#include "base/string_util.h"
#include "base/test_file_util.h"
#include "base/time.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
using base::TimeDelta;
using base::TimeTicks;
namespace {
// Wrapper around EvictFileFromSystemCache to retry 10 times in case of error.
// Apparently needed for Windows buildbots (to workaround an error when
// file is in use).
// TODO(phajdan.jr): Move to test_file_util if we need it in more places.
bool EvictFileFromSystemCacheWrapper(const FilePath& path) {
for (int i = 0; i < 10; i++) {
if (file_util::EvictFileFromSystemCache(path))
return true;
PlatformThread::Sleep(1000);
}
return false;
}
class StartupTest : public UITest {
public:
StartupTest() {
show_window_ = true;
pages_ = "about:blank";
}
void SetUp() {}
void TearDown() {}
void RunStartupTest(const wchar_t* graph, const wchar_t* trace,
bool test_cold, bool important) {
const int kNumCycles = 20;
TimeDelta timings[kNumCycles];
for (int i = 0; i < kNumCycles; ++i) {
if (test_cold) {
FilePath dir_app;
ASSERT_TRUE(PathService::Get(chrome::DIR_APP, &dir_app));
FilePath chrome_exe(dir_app.Append(
FilePath::FromWStringHack(chrome::kBrowserProcessExecutableName)));
ASSERT_TRUE(EvictFileFromSystemCacheWrapper(chrome_exe));
#if defined(OS_WIN)
// TODO(port): these files do not exist on other platforms.
// Decide what to do.
FilePath chrome_dll(dir_app.Append(FILE_PATH_LITERAL("chrome.dll")));
ASSERT_TRUE(EvictFileFromSystemCacheWrapper(chrome_dll));
FilePath gears_dll;
ASSERT_TRUE(PathService::Get(chrome::FILE_GEARS_PLUGIN, &gears_dll));
ASSERT_TRUE(EvictFileFromSystemCacheWrapper(gears_dll));
#endif // defined(OS_WIN)
}
UITest::SetUp();
TimeTicks end_time = TimeTicks::Now();
timings[i] = end_time - browser_launch_time_;
// TODO(beng): Can't shut down so quickly. Figure out why, and fix. If we
// do, we crash.
PlatformThread::Sleep(50);
UITest::TearDown();
if (i == 0) {
// Re-use the profile data after first run so that the noise from
// creating databases doesn't impact all the runs.
clear_profile_ = false;
}
}
std::wstring times;
for (int i = 0; i < kNumCycles; ++i)
StringAppendF(×, L"%.2f,", timings[i].InMillisecondsF());
PrintResultList(graph, L"", trace, times, L"ms", important);
}
protected:
std::string pages_;
};
class StartupReferenceTest : public StartupTest {
public:
// override the browser directory that is used by UITest::SetUp to cause it
// to use the reference build instead.
void SetUp() {
std::wstring dir;
PathService::Get(chrome::DIR_TEST_TOOLS, &dir);
file_util::AppendToPath(&dir, L"reference_build");
file_util::AppendToPath(&dir, L"chrome");
browser_directory_ = dir;
}
};
class StartupFileTest : public StartupTest {
public:
// Load a file on startup rather than about:blank. This tests a longer
// startup path, including resource loading and the loading of gears.dll.
void SetUp() {
std::wstring file_url;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &file_url));
file_util::AppendToPath(&file_url, L"empty.html");
ASSERT_TRUE(file_util::PathExists(file_url));
launch_arguments_.AppendLooseValue(file_url);
pages_ = WideToUTF8(file_url);
}
};
} // namespace
TEST_F(StartupTest, Perf) {
RunStartupTest(L"warm", L"t", false /* not cold */, true /* important */);
}
#if defined(OS_WIN)
// TODO(port): Enable reference tests on other platforms.
TEST_F(StartupReferenceTest, Perf) {
RunStartupTest(L"warm", L"t_ref", false /* not cold */,
true /* important */);
}
// TODO(mpcomplete): Should we have reference timings for all these?
TEST_F(StartupTest, PerfCold) {
RunStartupTest(L"cold", L"t", true /* cold */, false /* not important */);
}
TEST_F(StartupFileTest, PerfGears) {
RunStartupTest(L"warm", L"gears", false /* not cold */,
false /* not important */);
}
TEST_F(StartupFileTest, PerfColdGears) {
RunStartupTest(L"cold", L"gears", true /* cold */,
false /* not important */);
}
#endif // defined(OS_WIN)
<|endoftext|>
|
<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2009-2010 Bastian Holst <bastianholst@gmx.de>
//
#include "MarbleGraphicsItem.h"
#include "MarbleGraphicsItem_p.h"
// Marble
#include "MarbleDebug.h"
#include "ViewportParams.h"
// Qt
#include <QtCore/QList>
#include <QtCore/QSet>
#include <QtGui/QPainter>
#include <QtGui/QPixmap>
#include <QtGui/QPixmapCache>
#include <QtGui/QMouseEvent>
using namespace Marble;
MarbleGraphicsItem::MarbleGraphicsItem( MarbleGraphicsItemPrivate *d_ptr )
: d( d_ptr )
{
}
MarbleGraphicsItem::~MarbleGraphicsItem()
{
delete d;
}
bool MarbleGraphicsItem::paintEvent( QPainter *painter, const ViewportParams *viewport )
{
if ( !p()->m_visibility ) {
return true;
}
p()->setProjection( viewport );
// Remove the pixmap if it has been requested. This prevents QPixmapCache from being used
// outside the ui thread.
if ( p()->m_repaintNeeded ) {
p()->updateChildPositions();
p()->m_repaintNeeded = false;
QPixmapCache::remove( p()->m_cacheKey );
}
if ( p()->positions().size() == 0 ) {
return true;
}
// At the moment, as GraphicsItems can't be zoomed or rotated ItemCoordinateCache
// and DeviceCoordianteCache is exactly the same
if ( ItemCoordinateCache == cacheMode()
|| DeviceCoordinateCache == cacheMode() )
{
QPixmap cachePixmap;
bool pixmapAvailable = QPixmapCache::find( p()->m_cacheKey, &cachePixmap );
if ( !pixmapAvailable ) {
QSize neededPixmapSize = size().toSize() + QSize( 1, 1 ); // adding a pixel for rounding errors
if ( cachePixmap.size() != neededPixmapSize ) {
if ( size().isValid() && !size().isNull() ) {
cachePixmap = QPixmap( neededPixmapSize ).copy();
}
else {
mDebug() << "Warning: Invalid pixmap size suggested: " << d->m_size;
}
}
cachePixmap.fill( Qt::transparent );
QPainter pixmapPainter( &cachePixmap );
// We paint in best quality here, as we only have to paint once.
pixmapPainter.setRenderHint( QPainter::Antialiasing, true );
// The cache image will get a 0.5 pixel bounding to save antialiasing effects.
pixmapPainter.translate( 0.5, 0.5 );
paint( &pixmapPainter );
// Paint children
foreach ( MarbleGraphicsItem *item, p()->m_children ) {
item->paintEvent( &pixmapPainter, viewport );
}
// Update the pixmap in cache
p()->m_cacheKey = QPixmapCache::insert( cachePixmap );
}
foreach( const QPointF& position, p()->positions() ) {
painter->drawPixmap( position, cachePixmap );
}
}
else {
foreach( const QPointF& position, p()->positions() ) {
painter->save();
painter->translate( position );
paint( painter );
// Paint children
foreach ( MarbleGraphicsItem *item, p()->m_children ) {
item->paintEvent( painter, viewport );
}
painter->restore();
}
}
return true;
}
bool MarbleGraphicsItem::contains( const QPointF& point ) const
{
foreach( const QRectF& rect, d->boundingRects() ) {
if( rect.contains( point ) )
return true;
}
return false;
}
QRectF MarbleGraphicsItem::containsRect( const QPointF& point ) const
{
foreach( const QRectF& rect, d->boundingRects() ) {
if( rect.contains( point ) )
return rect;
}
return QRectF();
}
QList<QRectF> MarbleGraphicsItemPrivate::boundingRects() const
{
QList<QRectF> list;
foreach( QPointF point, positions() ) {
QRectF rect( point, m_size );
if( rect.x() < 0 )
rect.setLeft( 0 );
if( rect.y() < 0 )
rect.setTop( 0 );
list.append( rect );
}
return list;
}
QSizeF MarbleGraphicsItem::size() const
{
return p()->m_size;
}
AbstractMarbleGraphicsLayout *MarbleGraphicsItem::layout() const
{
return p()->m_layout;
}
void MarbleGraphicsItem::setLayout( AbstractMarbleGraphicsLayout *layout )
{
// Deleting the old layout
delete p()->m_layout;
p()->m_layout = layout;
update();
}
MarbleGraphicsItem::CacheMode MarbleGraphicsItem::cacheMode() const
{
return p()->m_cacheMode;
}
void MarbleGraphicsItem::setCacheMode( CacheMode mode )
{
p()->m_cacheMode = mode;
if ( p()->m_cacheMode == NoCache ) {
p()->m_repaintNeeded = true;
}
}
void MarbleGraphicsItem::update()
{
p()->m_repaintNeeded = true;
// Update the parent.
if ( p()->m_parent ) {
p()->m_parent->update();
}
}
bool MarbleGraphicsItem::visible() const
{
return p()->m_visibility;
}
void MarbleGraphicsItem::setVisible( bool visible )
{
p()->m_visibility = visible;
}
void MarbleGraphicsItem::hide()
{
setVisible( false );
}
void MarbleGraphicsItem::show()
{
setVisible( true );
}
void MarbleGraphicsItem::setSize( const QSizeF& size )
{
p()->m_size = size;
update();
}
QSizeF MarbleGraphicsItem::contentSize() const
{
return size();
}
void MarbleGraphicsItem::setContentSize( const QSizeF& size )
{
setSize( size );
}
QRectF MarbleGraphicsItem::contentRect() const
{
return QRectF( QPointF( 0, 0 ), contentSize() );
}
void MarbleGraphicsItem::paint( QPainter *painter )
{
Q_UNUSED( painter );
}
bool MarbleGraphicsItem::eventFilter( QObject *object, QEvent *e )
{
if ( ! ( e->type() == QEvent::MouseButtonDblClick
|| e->type() == QEvent::MouseMove
|| e->type() == QEvent::MouseButtonPress
|| e->type() == QEvent::MouseButtonRelease ) )
{
return false;
}
QMouseEvent *event = static_cast<QMouseEvent*> (e);
if( !p()->m_children.isEmpty() ) {
QList<QPointF> absolutePositions = p()->absolutePositions();
foreach( const QPointF& absolutePosition, absolutePositions ) {
QPoint shiftedPos = event->pos() - absolutePosition.toPoint();
if ( QRect( QPoint( 0, 0 ), size().toSize() ).contains( shiftedPos ) ) {
foreach( MarbleGraphicsItem *child, p()->m_children ) {
QList<QRectF> childRects = child->d->boundingRects();
foreach( const QRectF& childRect, childRects ) {
if( childRect.toRect().contains( shiftedPos ) ) {
if( child->eventFilter( object, e ) ) {
return true;
}
}
}
}
}
}
}
return false;
}
MarbleGraphicsItemPrivate *MarbleGraphicsItem::p() const
{
return d;
}
void MarbleGraphicsItem::setProjection( ViewportParams *viewport )
{
p()->setProjection( viewport );
}
<commit_msg>bail out earlier if item is outside viewport<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2009-2010 Bastian Holst <bastianholst@gmx.de>
//
#include "MarbleGraphicsItem.h"
#include "MarbleGraphicsItem_p.h"
// Marble
#include "MarbleDebug.h"
#include "ViewportParams.h"
// Qt
#include <QtCore/QList>
#include <QtCore/QSet>
#include <QtGui/QPainter>
#include <QtGui/QPixmap>
#include <QtGui/QPixmapCache>
#include <QtGui/QMouseEvent>
using namespace Marble;
MarbleGraphicsItem::MarbleGraphicsItem( MarbleGraphicsItemPrivate *d_ptr )
: d( d_ptr )
{
}
MarbleGraphicsItem::~MarbleGraphicsItem()
{
delete d;
}
bool MarbleGraphicsItem::paintEvent( QPainter *painter, const ViewportParams *viewport )
{
if ( !p()->m_visibility ) {
return true;
}
p()->setProjection( viewport );
if ( p()->positions().size() == 0 ) {
return true;
}
// Remove the pixmap if it has been requested. This prevents QPixmapCache from being used
// outside the ui thread.
if ( p()->m_repaintNeeded ) {
p()->updateChildPositions();
p()->m_repaintNeeded = false;
QPixmapCache::remove( p()->m_cacheKey );
}
// At the moment, as GraphicsItems can't be zoomed or rotated ItemCoordinateCache
// and DeviceCoordianteCache is exactly the same
if ( ItemCoordinateCache == cacheMode()
|| DeviceCoordinateCache == cacheMode() )
{
QPixmap cachePixmap;
bool pixmapAvailable = QPixmapCache::find( p()->m_cacheKey, &cachePixmap );
if ( !pixmapAvailable ) {
QSize neededPixmapSize = size().toSize() + QSize( 1, 1 ); // adding a pixel for rounding errors
if ( cachePixmap.size() != neededPixmapSize ) {
if ( size().isValid() && !size().isNull() ) {
cachePixmap = QPixmap( neededPixmapSize ).copy();
}
else {
mDebug() << "Warning: Invalid pixmap size suggested: " << d->m_size;
}
}
cachePixmap.fill( Qt::transparent );
QPainter pixmapPainter( &cachePixmap );
// We paint in best quality here, as we only have to paint once.
pixmapPainter.setRenderHint( QPainter::Antialiasing, true );
// The cache image will get a 0.5 pixel bounding to save antialiasing effects.
pixmapPainter.translate( 0.5, 0.5 );
paint( &pixmapPainter );
// Paint children
foreach ( MarbleGraphicsItem *item, p()->m_children ) {
item->paintEvent( &pixmapPainter, viewport );
}
// Update the pixmap in cache
p()->m_cacheKey = QPixmapCache::insert( cachePixmap );
}
foreach( const QPointF& position, p()->positions() ) {
painter->drawPixmap( position, cachePixmap );
}
}
else {
foreach( const QPointF& position, p()->positions() ) {
painter->save();
painter->translate( position );
paint( painter );
// Paint children
foreach ( MarbleGraphicsItem *item, p()->m_children ) {
item->paintEvent( painter, viewport );
}
painter->restore();
}
}
return true;
}
bool MarbleGraphicsItem::contains( const QPointF& point ) const
{
foreach( const QRectF& rect, d->boundingRects() ) {
if( rect.contains( point ) )
return true;
}
return false;
}
QRectF MarbleGraphicsItem::containsRect( const QPointF& point ) const
{
foreach( const QRectF& rect, d->boundingRects() ) {
if( rect.contains( point ) )
return rect;
}
return QRectF();
}
QList<QRectF> MarbleGraphicsItemPrivate::boundingRects() const
{
QList<QRectF> list;
foreach( QPointF point, positions() ) {
QRectF rect( point, m_size );
if( rect.x() < 0 )
rect.setLeft( 0 );
if( rect.y() < 0 )
rect.setTop( 0 );
list.append( rect );
}
return list;
}
QSizeF MarbleGraphicsItem::size() const
{
return p()->m_size;
}
AbstractMarbleGraphicsLayout *MarbleGraphicsItem::layout() const
{
return p()->m_layout;
}
void MarbleGraphicsItem::setLayout( AbstractMarbleGraphicsLayout *layout )
{
// Deleting the old layout
delete p()->m_layout;
p()->m_layout = layout;
update();
}
MarbleGraphicsItem::CacheMode MarbleGraphicsItem::cacheMode() const
{
return p()->m_cacheMode;
}
void MarbleGraphicsItem::setCacheMode( CacheMode mode )
{
p()->m_cacheMode = mode;
if ( p()->m_cacheMode == NoCache ) {
p()->m_repaintNeeded = true;
}
}
void MarbleGraphicsItem::update()
{
p()->m_repaintNeeded = true;
// Update the parent.
if ( p()->m_parent ) {
p()->m_parent->update();
}
}
bool MarbleGraphicsItem::visible() const
{
return p()->m_visibility;
}
void MarbleGraphicsItem::setVisible( bool visible )
{
p()->m_visibility = visible;
}
void MarbleGraphicsItem::hide()
{
setVisible( false );
}
void MarbleGraphicsItem::show()
{
setVisible( true );
}
void MarbleGraphicsItem::setSize( const QSizeF& size )
{
p()->m_size = size;
update();
}
QSizeF MarbleGraphicsItem::contentSize() const
{
return size();
}
void MarbleGraphicsItem::setContentSize( const QSizeF& size )
{
setSize( size );
}
QRectF MarbleGraphicsItem::contentRect() const
{
return QRectF( QPointF( 0, 0 ), contentSize() );
}
void MarbleGraphicsItem::paint( QPainter *painter )
{
Q_UNUSED( painter );
}
bool MarbleGraphicsItem::eventFilter( QObject *object, QEvent *e )
{
if ( ! ( e->type() == QEvent::MouseButtonDblClick
|| e->type() == QEvent::MouseMove
|| e->type() == QEvent::MouseButtonPress
|| e->type() == QEvent::MouseButtonRelease ) )
{
return false;
}
QMouseEvent *event = static_cast<QMouseEvent*> (e);
if( !p()->m_children.isEmpty() ) {
QList<QPointF> absolutePositions = p()->absolutePositions();
foreach( const QPointF& absolutePosition, absolutePositions ) {
QPoint shiftedPos = event->pos() - absolutePosition.toPoint();
if ( QRect( QPoint( 0, 0 ), size().toSize() ).contains( shiftedPos ) ) {
foreach( MarbleGraphicsItem *child, p()->m_children ) {
QList<QRectF> childRects = child->d->boundingRects();
foreach( const QRectF& childRect, childRects ) {
if( childRect.toRect().contains( shiftedPos ) ) {
if( child->eventFilter( object, e ) ) {
return true;
}
}
}
}
}
}
}
return false;
}
MarbleGraphicsItemPrivate *MarbleGraphicsItem::p() const
{
return d;
}
void MarbleGraphicsItem::setProjection( ViewportParams *viewport )
{
p()->setProjection( viewport );
}
<|endoftext|>
|
<commit_before>#include <algorithm>
#include <fstream>
#include <json/json.h>
#include <iostream>
#include <regex>
#include <utils.h>
#include "cmdparse.h"
#include "CmdHandler.h"
#include "lynxbot.h"
CmdHandler::CmdHandler(const char *name, const char *channel,
const char *token, Moderator *mod, URLParser *urlp,
EventManager *evtp, Giveaway *givp, ConfigReader *cfgr,
tw::Authenticator *auth)
: m_name(name), m_channel(channel), m_token(token), m_modp(mod),
m_parsep(urlp), m_customCmds(NULL), m_evtp(evtp), m_givp(givp),
m_cfgr(cfgr), m_auth(auth), m_counting(false), m_gen(m_rd()),
m_status(EXIT_SUCCESS)
{
populate_cmd();
m_poll[0] = '\0';
m_customCmds = new CustomHandler(&m_defaultCmds, &m_cooldowns,
m_wheel.cmd(), name, channel);
if (!m_customCmds->isActive()) {
fprintf(stderr, "Custom commands will be "
"disabled for this session\n");
WAIT_INPUT();
}
/* read all responses from file */
m_responding = utils::readJSON("responses.json", m_responses);
if (m_responding) {
/* add response cooldowns to TimerManager */
for (auto &val : m_responses["responses"])
m_cooldowns.add('_' + val["name"].asString(),
val["cooldown"].asInt());
} else {
fprintf(stderr, "Failed to read responses.json. "
"Responses disabled for this session\n");
WAIT_INPUT();
}
/* set all command cooldowns */
for (auto &p : m_defaultCmds)
m_cooldowns.add(p.first);
m_cooldowns.add(m_wheel.name());
/* read extra 8ball responses */
utils::split(m_cfgr->get("extra8ballresponses"), '\n', m_eightball);
/* read fashion.json */
if (!utils::readJSON("fashion.json", m_fashion))
fprintf(stderr, "Could not read fashion.json\n");
populate_help();
}
CmdHandler::~CmdHandler()
{
delete m_customCmds;
}
/* process_cmd: run message as a bot command and store output in out */
void CmdHandler::process_cmd(char *out, char *nick, char *cmdstr, perm_t p)
{
struct command c;
c.nick = nick;
c.privileges = p;
if (!parse_cmd(cmdstr, &c)) {
_sprintf(out, MAX_MSG, "%s", cmderr());
return;
}
switch (source(c.argv[0])) {
case DEFAULT:
process_default(out, &c);
break;
case CUSTOM:
process_custom(out, &c);
break;
default:
_sprintf(out, MAX_MSG, "/w %s not a bot command: %s",
nick, c.argv[0]);
break;
}
free_cmd(&c);
}
/* process_resp: test a message against auto response regexes */
int CmdHandler::process_resp(char *out, char *msg, char *nick)
{
const std::string message(msg);
std::regex respreg;
std::smatch match;
std::string name, regex;
*out = '\0';
if (!m_responding)
return 0;
/* test the message against all response regexes */
for (auto &val : m_responses["responses"]) {
name = '_' + val["name"].asString();
regex = val["regex"].asString();
respreg = std::regex(regex, std::regex::icase);
if (std::regex_search(message.begin(), message.end(), match,
respreg) && m_cooldowns.ready(name)) {
m_cooldowns.setUsed(name);
_sprintf(out, MAX_MSG, "@%s, %s", nick,
val["response"].asCString());
return 1;
}
}
return 0;
}
bool CmdHandler::counting() const
{
return m_counting;
}
/* count: count message in m_messageCounts */
void CmdHandler::count(const char *nick, const char *message)
{
std::string msg = message;
std::transform(msg.begin(), msg.end(), msg.begin(), tolower);
/* if nick is not found */
if (std::find(m_usersCounted.begin(), m_usersCounted.end(), nick)
== m_usersCounted.end()) {
m_usersCounted.push_back(nick);
if (m_messageCounts.find(msg) == m_messageCounts.end())
m_messageCounts.insert({ msg, 1 });
else
m_messageCounts.find(msg)->second++;
}
}
/* process_default: run a default command */
void CmdHandler::process_default(char *out, struct command *c)
{
if (P_ALSUB(c->privileges) || m_cooldowns.ready(c->argv[0])) {
m_status = (this->*m_defaultCmds[c->argv[0]])(out, c);
m_cooldowns.setUsed(c->argv[0]);
} else {
_sprintf(out, MAX_MSG, "/w %s command is on cooldown: %s",
c->nick, c->argv[0]);
m_status = EXIT_FAILURE;
}
}
/* process_custom: run a custom command */
void CmdHandler::process_custom(char *out, struct command *c)
{
Json::Value *ccmd;
ccmd = m_customCmds->getcom(c->argv[0]);
if ((*ccmd)["active"].asBool() && (P_ALSUB(c->privileges) ||
m_cooldowns.ready((*ccmd)["cmd"].asString()))) {
/* set access time and increase uses */
(*ccmd)["atime"] = (Json::Int64)time(nullptr);
(*ccmd)["uses"] = (*ccmd)["uses"].asInt() + 1;
_sprintf(out, MAX_MSG, "%s",
m_customCmds->format(ccmd, c->nick).c_str());
m_cooldowns.setUsed((*ccmd)["cmd"].asString());
m_customCmds->write();
m_status = EXIT_SUCCESS;
return;
}
if (!(*ccmd)["active"].asBool()) {
_sprintf(out, MAX_MSG, "/w %s command is currently inactive: %s",
c->nick, c->argv[0]);
m_status = EXIT_FAILURE;
return;
}
_sprintf(out, MAX_MSG, "/w %s command is on cooldown: %s",
c->nick, c->argv[0]);
m_status = EXIT_FAILURE;
}
/* source: determine whether cmd is a default or custom command */
uint8_t CmdHandler::source(const char *cmd)
{
if (m_defaultCmds.find(cmd) != m_defaultCmds.end())
return DEFAULT;
if (m_customCmds->isActive()) {
Json::Value *c;
if (!(c = m_customCmds->getcom(cmd))->empty())
return CUSTOM;
}
return 0;
}
/* getrsn: print the rsn referred to by text into out */
int CmdHandler::getrsn(char *out, size_t len, const char *text,
const char *nick, int username)
{
const char *rsn;
char *s;
if (username) {
if (!(rsn = m_rsns.rsn(text))) {
_sprintf(out, len, "no RSN set for user %s", text);
return 0;
}
} else {
if (strcmp(text, ".") == 0) {
if (!(rsn = m_rsns.rsn(nick))) {
_sprintf(out, len, "no RSN set for user %s",
nick);
return 0;
}
} else {
rsn = text;
}
}
_sprintf(out, len, "%s", rsn);
while ((s = strchr(out, ' ')))
*s = '_';
return 1;
}
/* populateCmds: initialize pointers to all default commands */
void CmdHandler::populate_cmd()
{
/* regular commands */
m_defaultCmds["8ball"] = &CmdHandler::eightball;
m_defaultCmds["about"] = &CmdHandler::about;
m_defaultCmds["active"] = &CmdHandler::active;
m_defaultCmds["age"] = &CmdHandler::age;
m_defaultCmds["calc"] = &CmdHandler::calc;
m_defaultCmds["cgrep"] = &CmdHandler::cgrep;
m_defaultCmds["cmdinfo"] = &CmdHandler::cmdinfo;
m_defaultCmds["cml"] = &CmdHandler::cml;
m_defaultCmds["commands"] = &CmdHandler::manual;
m_defaultCmds["duck"] = &CmdHandler::duck;
m_defaultCmds["ehp"] = &CmdHandler::ehp;
m_defaultCmds["fashiongen"] = &CmdHandler::fashiongen;
m_defaultCmds["ge"] = &CmdHandler::ge;
m_defaultCmds["help"] = &CmdHandler::man;
m_defaultCmds["level"] = &CmdHandler::level;
m_defaultCmds["lvl"] = &CmdHandler::level;
m_defaultCmds["man"] = &CmdHandler::man;
m_defaultCmds["manual"] = &CmdHandler::manual;
m_defaultCmds["rsn"] = &CmdHandler::rsn;
m_defaultCmds["submit"] = &CmdHandler::submit;
m_defaultCmds["twitter"] = &CmdHandler::twitter;
m_defaultCmds["uptime"] = &CmdHandler::uptime;
m_defaultCmds["xp"] = &CmdHandler::xp;
m_defaultCmds[m_wheel.cmd()] = &CmdHandler::wheel;
/* moderator commands */
m_defaultCmds["ac"] = &CmdHandler::addcom;
m_defaultCmds["addcom"] = &CmdHandler::addcom;
m_defaultCmds["addrec"] = &CmdHandler::addrec;
m_defaultCmds["ar"] = &CmdHandler::addrec;
m_defaultCmds["count"] = &CmdHandler::count;
m_defaultCmds["dc"] = &CmdHandler::delcom;
m_defaultCmds["delcom"] = &CmdHandler::delcom;
m_defaultCmds["delrec"] = &CmdHandler::delrec;
m_defaultCmds["dr"] = &CmdHandler::delrec;
m_defaultCmds["ec"] = &CmdHandler::editcom;
m_defaultCmds["editcom"] = &CmdHandler::editcom;
m_defaultCmds["er"] = &CmdHandler::editrec;
m_defaultCmds["editrec"] = &CmdHandler::editrec;
m_defaultCmds["mod"] = &CmdHandler::mod;
m_defaultCmds["permit"] = &CmdHandler::permit;
m_defaultCmds["setgiv"] = &CmdHandler::setgiv;
m_defaultCmds["setrec"] = &CmdHandler::setrec;
m_defaultCmds["showrec"] = &CmdHandler::showrec;
m_defaultCmds["sp"] = &CmdHandler::strawpoll;
m_defaultCmds["status"] = &CmdHandler::status;
m_defaultCmds["strawpoll"] = &CmdHandler::strawpoll;
m_defaultCmds["whitelist"] = &CmdHandler::whitelist;
}
/* populateHelp: fill m_help with manual page names */
void CmdHandler::populate_help()
{
m_help[m_wheel.cmd()] = "selection-wheel";
m_help["wheel"] = "selection-wheel";
m_help["ac"] = "addcom";
m_help["dc"] = "delcom";
m_help["ec"] = "editcom";
m_help["ar"] = "addrec";
m_help["dr"] = "delrec";
m_help["er"] = "editrec";
m_help["lvl"] = "level";
m_help["sp"] = "strawpoll";
m_help["automated-responses"] = "automated-responses";
m_help["responses"] = "automated-responses";
m_help["custom"] = "custom-commands";
m_help["custom-commands"] = "custom-commands";
m_help["giveaway"] = "giveaways";
m_help["giveaways"] = "giveaways";
m_help["help"] = "man";
m_help["mod"] = "moderation";
m_help["moderation"] = "moderation";
m_help["moderator"] = "moderation";
m_help["recurring"] = "recurring-messages";
m_help["recurring-messages"] = "recurring-messages";
m_help["rsns"] = "rsn-management";
m_help["rsn-management"] = "rsn-management";
m_help["submessage"] = "subscriber-message";
m_help["tweet"] = "tweet-reader";
m_help["tweet-reader"] = "tweet-reader";
m_help["twitter"] = "tweet-reader";
m_help["twitch"] = "twitch-authorization";
m_help["twitchauth"] = "twitch-authorization";
m_help["twitch-autorization"] = "twitch-authorization";
m_help["auth"] = "twitch-authorization";
m_help["authorization"] = "twitch-authorization";
}
<commit_msg>Change 'mod' man link to mod command<commit_after>#include <algorithm>
#include <fstream>
#include <json/json.h>
#include <iostream>
#include <regex>
#include <utils.h>
#include "cmdparse.h"
#include "CmdHandler.h"
#include "lynxbot.h"
CmdHandler::CmdHandler(const char *name, const char *channel,
const char *token, Moderator *mod, URLParser *urlp,
EventManager *evtp, Giveaway *givp, ConfigReader *cfgr,
tw::Authenticator *auth)
: m_name(name), m_channel(channel), m_token(token), m_modp(mod),
m_parsep(urlp), m_customCmds(NULL), m_evtp(evtp), m_givp(givp),
m_cfgr(cfgr), m_auth(auth), m_counting(false), m_gen(m_rd()),
m_status(EXIT_SUCCESS)
{
populate_cmd();
m_poll[0] = '\0';
m_customCmds = new CustomHandler(&m_defaultCmds, &m_cooldowns,
m_wheel.cmd(), name, channel);
if (!m_customCmds->isActive()) {
fprintf(stderr, "Custom commands will be "
"disabled for this session\n");
WAIT_INPUT();
}
/* read all responses from file */
m_responding = utils::readJSON("responses.json", m_responses);
if (m_responding) {
/* add response cooldowns to TimerManager */
for (auto &val : m_responses["responses"])
m_cooldowns.add('_' + val["name"].asString(),
val["cooldown"].asInt());
} else {
fprintf(stderr, "Failed to read responses.json. "
"Responses disabled for this session\n");
WAIT_INPUT();
}
/* set all command cooldowns */
for (auto &p : m_defaultCmds)
m_cooldowns.add(p.first);
m_cooldowns.add(m_wheel.name());
/* read extra 8ball responses */
utils::split(m_cfgr->get("extra8ballresponses"), '\n', m_eightball);
/* read fashion.json */
if (!utils::readJSON("fashion.json", m_fashion))
fprintf(stderr, "Could not read fashion.json\n");
populate_help();
}
CmdHandler::~CmdHandler()
{
delete m_customCmds;
}
/* process_cmd: run message as a bot command and store output in out */
void CmdHandler::process_cmd(char *out, char *nick, char *cmdstr, perm_t p)
{
struct command c;
c.nick = nick;
c.privileges = p;
if (!parse_cmd(cmdstr, &c)) {
_sprintf(out, MAX_MSG, "%s", cmderr());
return;
}
switch (source(c.argv[0])) {
case DEFAULT:
process_default(out, &c);
break;
case CUSTOM:
process_custom(out, &c);
break;
default:
_sprintf(out, MAX_MSG, "/w %s not a bot command: %s",
nick, c.argv[0]);
break;
}
free_cmd(&c);
}
/* process_resp: test a message against auto response regexes */
int CmdHandler::process_resp(char *out, char *msg, char *nick)
{
const std::string message(msg);
std::regex respreg;
std::smatch match;
std::string name, regex;
*out = '\0';
if (!m_responding)
return 0;
/* test the message against all response regexes */
for (auto &val : m_responses["responses"]) {
name = '_' + val["name"].asString();
regex = val["regex"].asString();
respreg = std::regex(regex, std::regex::icase);
if (std::regex_search(message.begin(), message.end(), match,
respreg) && m_cooldowns.ready(name)) {
m_cooldowns.setUsed(name);
_sprintf(out, MAX_MSG, "@%s, %s", nick,
val["response"].asCString());
return 1;
}
}
return 0;
}
bool CmdHandler::counting() const
{
return m_counting;
}
/* count: count message in m_messageCounts */
void CmdHandler::count(const char *nick, const char *message)
{
std::string msg = message;
std::transform(msg.begin(), msg.end(), msg.begin(), tolower);
/* if nick is not found */
if (std::find(m_usersCounted.begin(), m_usersCounted.end(), nick)
== m_usersCounted.end()) {
m_usersCounted.push_back(nick);
if (m_messageCounts.find(msg) == m_messageCounts.end())
m_messageCounts.insert({ msg, 1 });
else
m_messageCounts.find(msg)->second++;
}
}
/* process_default: run a default command */
void CmdHandler::process_default(char *out, struct command *c)
{
if (P_ALSUB(c->privileges) || m_cooldowns.ready(c->argv[0])) {
m_status = (this->*m_defaultCmds[c->argv[0]])(out, c);
m_cooldowns.setUsed(c->argv[0]);
} else {
_sprintf(out, MAX_MSG, "/w %s command is on cooldown: %s",
c->nick, c->argv[0]);
m_status = EXIT_FAILURE;
}
}
/* process_custom: run a custom command */
void CmdHandler::process_custom(char *out, struct command *c)
{
Json::Value *ccmd;
ccmd = m_customCmds->getcom(c->argv[0]);
if ((*ccmd)["active"].asBool() && (P_ALSUB(c->privileges) ||
m_cooldowns.ready((*ccmd)["cmd"].asString()))) {
/* set access time and increase uses */
(*ccmd)["atime"] = (Json::Int64)time(nullptr);
(*ccmd)["uses"] = (*ccmd)["uses"].asInt() + 1;
_sprintf(out, MAX_MSG, "%s",
m_customCmds->format(ccmd, c->nick).c_str());
m_cooldowns.setUsed((*ccmd)["cmd"].asString());
m_customCmds->write();
m_status = EXIT_SUCCESS;
return;
}
if (!(*ccmd)["active"].asBool()) {
_sprintf(out, MAX_MSG, "/w %s command is currently inactive: %s",
c->nick, c->argv[0]);
m_status = EXIT_FAILURE;
return;
}
_sprintf(out, MAX_MSG, "/w %s command is on cooldown: %s",
c->nick, c->argv[0]);
m_status = EXIT_FAILURE;
}
/* source: determine whether cmd is a default or custom command */
uint8_t CmdHandler::source(const char *cmd)
{
if (m_defaultCmds.find(cmd) != m_defaultCmds.end())
return DEFAULT;
if (m_customCmds->isActive()) {
Json::Value *c;
if (!(c = m_customCmds->getcom(cmd))->empty())
return CUSTOM;
}
return 0;
}
/* getrsn: print the rsn referred to by text into out */
int CmdHandler::getrsn(char *out, size_t len, const char *text,
const char *nick, int username)
{
const char *rsn;
char *s;
if (username) {
if (!(rsn = m_rsns.rsn(text))) {
_sprintf(out, len, "no RSN set for user %s", text);
return 0;
}
} else {
if (strcmp(text, ".") == 0) {
if (!(rsn = m_rsns.rsn(nick))) {
_sprintf(out, len, "no RSN set for user %s",
nick);
return 0;
}
} else {
rsn = text;
}
}
_sprintf(out, len, "%s", rsn);
while ((s = strchr(out, ' ')))
*s = '_';
return 1;
}
/* populateCmds: initialize pointers to all default commands */
void CmdHandler::populate_cmd()
{
/* regular commands */
m_defaultCmds["8ball"] = &CmdHandler::eightball;
m_defaultCmds["about"] = &CmdHandler::about;
m_defaultCmds["active"] = &CmdHandler::active;
m_defaultCmds["age"] = &CmdHandler::age;
m_defaultCmds["calc"] = &CmdHandler::calc;
m_defaultCmds["cgrep"] = &CmdHandler::cgrep;
m_defaultCmds["cmdinfo"] = &CmdHandler::cmdinfo;
m_defaultCmds["cml"] = &CmdHandler::cml;
m_defaultCmds["commands"] = &CmdHandler::manual;
m_defaultCmds["duck"] = &CmdHandler::duck;
m_defaultCmds["ehp"] = &CmdHandler::ehp;
m_defaultCmds["fashiongen"] = &CmdHandler::fashiongen;
m_defaultCmds["ge"] = &CmdHandler::ge;
m_defaultCmds["help"] = &CmdHandler::man;
m_defaultCmds["level"] = &CmdHandler::level;
m_defaultCmds["lvl"] = &CmdHandler::level;
m_defaultCmds["man"] = &CmdHandler::man;
m_defaultCmds["manual"] = &CmdHandler::manual;
m_defaultCmds["rsn"] = &CmdHandler::rsn;
m_defaultCmds["submit"] = &CmdHandler::submit;
m_defaultCmds["twitter"] = &CmdHandler::twitter;
m_defaultCmds["uptime"] = &CmdHandler::uptime;
m_defaultCmds["xp"] = &CmdHandler::xp;
m_defaultCmds[m_wheel.cmd()] = &CmdHandler::wheel;
/* moderator commands */
m_defaultCmds["ac"] = &CmdHandler::addcom;
m_defaultCmds["addcom"] = &CmdHandler::addcom;
m_defaultCmds["addrec"] = &CmdHandler::addrec;
m_defaultCmds["ar"] = &CmdHandler::addrec;
m_defaultCmds["count"] = &CmdHandler::count;
m_defaultCmds["dc"] = &CmdHandler::delcom;
m_defaultCmds["delcom"] = &CmdHandler::delcom;
m_defaultCmds["delrec"] = &CmdHandler::delrec;
m_defaultCmds["dr"] = &CmdHandler::delrec;
m_defaultCmds["ec"] = &CmdHandler::editcom;
m_defaultCmds["editcom"] = &CmdHandler::editcom;
m_defaultCmds["er"] = &CmdHandler::editrec;
m_defaultCmds["editrec"] = &CmdHandler::editrec;
m_defaultCmds["mod"] = &CmdHandler::mod;
m_defaultCmds["permit"] = &CmdHandler::permit;
m_defaultCmds["setgiv"] = &CmdHandler::setgiv;
m_defaultCmds["setrec"] = &CmdHandler::setrec;
m_defaultCmds["showrec"] = &CmdHandler::showrec;
m_defaultCmds["sp"] = &CmdHandler::strawpoll;
m_defaultCmds["status"] = &CmdHandler::status;
m_defaultCmds["strawpoll"] = &CmdHandler::strawpoll;
m_defaultCmds["whitelist"] = &CmdHandler::whitelist;
}
/* populateHelp: fill m_help with manual page names */
void CmdHandler::populate_help()
{
m_help[m_wheel.cmd()] = "selection-wheel";
m_help["wheel"] = "selection-wheel";
m_help["ac"] = "addcom";
m_help["dc"] = "delcom";
m_help["ec"] = "editcom";
m_help["ar"] = "addrec";
m_help["dr"] = "delrec";
m_help["er"] = "editrec";
m_help["lvl"] = "level";
m_help["sp"] = "strawpoll";
m_help["automated-responses"] = "automated-responses";
m_help["responses"] = "automated-responses";
m_help["custom"] = "custom-commands";
m_help["custom-commands"] = "custom-commands";
m_help["giveaway"] = "giveaways";
m_help["giveaways"] = "giveaways";
m_help["help"] = "man";
m_help["moderation"] = "moderation";
m_help["moderator"] = "moderation";
m_help["recurring"] = "recurring-messages";
m_help["recurring-messages"] = "recurring-messages";
m_help["rsns"] = "rsn-management";
m_help["rsn-management"] = "rsn-management";
m_help["submessage"] = "subscriber-message";
m_help["tweet"] = "tweet-reader";
m_help["tweet-reader"] = "tweet-reader";
m_help["twitter"] = "tweet-reader";
m_help["twitch"] = "twitch-authorization";
m_help["twitchauth"] = "twitch-authorization";
m_help["twitch-autorization"] = "twitch-authorization";
m_help["auth"] = "twitch-authorization";
m_help["authorization"] = "twitch-authorization";
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: svdtxhdl.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: pjunck $ $Date: 2004-11-03 11:06:17 $
*
* 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 _SVDTXHDL_HXX
#define _SVDTXHDL_HXX
#ifndef _VIRDEV_HXX //autogen
#include <vcl/virdev.hxx>
#endif
#ifndef _TL_POLY_HXX
#include <tools/poly.hxx>
#endif
#ifndef _LINK_HXX //autogen
#include <tools/link.hxx>
#endif
//************************************************************
// Vorausdeklarationen
//************************************************************
class SdrOutliner;
class DrawPortionInfo;
class SdrTextObj;
class SdrObjGroup;
class SdrModel;
class XOutputDevice;
//************************************************************
// ImpTextPortionHandler
//************************************************************
class ImpTextPortionHandler
{
VirtualDevice aVDev;
Rectangle aFormTextBoundRect;
SdrOutliner& rOutliner;
const SdrTextObj& rTextObj;
XOutputDevice* pXOut;
// Variablen fuer ConvertToPathObj
SdrObjGroup* pGroup;
SdrModel* pModel;
FASTBOOL bToPoly;
// Variablen fuer DrawFitText
Point aPos;
Fraction aXFact;
Fraction aYFact;
// Variablen fuer DrawTextToPath
// #101498#
//Polygon aPoly;
//long nTextWidth;
ULONG nParagraph;
BOOL bToLastPoint;
BOOL bDraw;
void* mpRecordPortions;
private:
// #101498#
void SortedAddFormTextRecordPortion(DrawPortionInfo* pInfo);
void DrawFormTextRecordPortions(Polygon aPoly);
void ClearFormTextRecordPortions();
sal_uInt32 GetFormTextPortionsLength(OutputDevice* pOut);
public:
ImpTextPortionHandler(SdrOutliner& rOutln, const SdrTextObj& rTxtObj);
void ConvertToPathObj(SdrObjGroup& rGroup, FASTBOOL bToPoly);
void DrawFitText(XOutputDevice& rXOut, const Point& rPos, const Fraction& rXFact);
void DrawTextToPath(XOutputDevice& rXOut, FASTBOOL bDrawEffect=TRUE);
// wird von DrawTextToPath() gesetzt:
const Rectangle& GetFormTextBoundRect() { return aFormTextBoundRect; }
DECL_LINK(ConvertHdl,DrawPortionInfo*);
DECL_LINK(FitTextDrawHdl,DrawPortionInfo*);
// #101498#
DECL_LINK(FormTextRecordPortionHdl, DrawPortionInfo*);
//DECL_LINK(FormTextWidthHdl,DrawPortionInfo*);
//DECL_LINK(FormTextDrawHdl,DrawPortionInfo*);
};
////////////////////////////////////////////////////////////////////////////////////////////////////
#endif //_SVDTXHDL_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.596); FILE MERGED 2005/09/05 14:27:28 rt 1.4.596.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: svdtxhdl.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-09 00:41:44 $
*
* 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 _SVDTXHDL_HXX
#define _SVDTXHDL_HXX
#ifndef _VIRDEV_HXX //autogen
#include <vcl/virdev.hxx>
#endif
#ifndef _TL_POLY_HXX
#include <tools/poly.hxx>
#endif
#ifndef _LINK_HXX //autogen
#include <tools/link.hxx>
#endif
//************************************************************
// Vorausdeklarationen
//************************************************************
class SdrOutliner;
class DrawPortionInfo;
class SdrTextObj;
class SdrObjGroup;
class SdrModel;
class XOutputDevice;
//************************************************************
// ImpTextPortionHandler
//************************************************************
class ImpTextPortionHandler
{
VirtualDevice aVDev;
Rectangle aFormTextBoundRect;
SdrOutliner& rOutliner;
const SdrTextObj& rTextObj;
XOutputDevice* pXOut;
// Variablen fuer ConvertToPathObj
SdrObjGroup* pGroup;
SdrModel* pModel;
FASTBOOL bToPoly;
// Variablen fuer DrawFitText
Point aPos;
Fraction aXFact;
Fraction aYFact;
// Variablen fuer DrawTextToPath
// #101498#
//Polygon aPoly;
//long nTextWidth;
ULONG nParagraph;
BOOL bToLastPoint;
BOOL bDraw;
void* mpRecordPortions;
private:
// #101498#
void SortedAddFormTextRecordPortion(DrawPortionInfo* pInfo);
void DrawFormTextRecordPortions(Polygon aPoly);
void ClearFormTextRecordPortions();
sal_uInt32 GetFormTextPortionsLength(OutputDevice* pOut);
public:
ImpTextPortionHandler(SdrOutliner& rOutln, const SdrTextObj& rTxtObj);
void ConvertToPathObj(SdrObjGroup& rGroup, FASTBOOL bToPoly);
void DrawFitText(XOutputDevice& rXOut, const Point& rPos, const Fraction& rXFact);
void DrawTextToPath(XOutputDevice& rXOut, FASTBOOL bDrawEffect=TRUE);
// wird von DrawTextToPath() gesetzt:
const Rectangle& GetFormTextBoundRect() { return aFormTextBoundRect; }
DECL_LINK(ConvertHdl,DrawPortionInfo*);
DECL_LINK(FitTextDrawHdl,DrawPortionInfo*);
// #101498#
DECL_LINK(FormTextRecordPortionHdl, DrawPortionInfo*);
//DECL_LINK(FormTextWidthHdl,DrawPortionInfo*);
//DECL_LINK(FormTextDrawHdl,DrawPortionInfo*);
};
////////////////////////////////////////////////////////////////////////////////////////////////////
#endif //_SVDTXHDL_HXX
<|endoftext|>
|
<commit_before>#include "DrawAttack.hpp"
#include "States/TitleState.hpp"
#include "States/ServerSelectState.hpp"
#include "States/PlayState.hpp"
#include "States/DisconnectedState.hpp"
#include "States/NameSelectState.hpp"
using namespace cpp3ds;
using namespace TweenEngine;
namespace DrawAttack {
DrawAttack::DrawAttack()
: m_stateStack(State::Context(m_client, m_name, m_data))
{
textFPS.setColor(Color::Blue);
m_stateStack.registerState<TitleState>(States::Title);
m_stateStack.registerState<ServerSelectState>(States::ServerSelect);
m_stateStack.registerState<NameSelectState>(States::NameSelect);
m_stateStack.registerState<PlayState>(States::Play);
m_stateStack.registerState<DisconnectedState>(States::Disconnected);
m_stateStack.pushState(States::ServerSelect);
}
DrawAttack::~DrawAttack()
{
// Destructor called when game exits
}
void DrawAttack::update(float delta)
{
if (m_stateStack.isEmpty())
exit();
static int i;
if (i++ % 10 == 0) {
textFPS.setString(_("%.1f fps", 1.f / delta));
textFPS.setPosition(395 - textFPS.getGlobalBounds().width, 200);
}
m_stateStack.update(delta);
}
void DrawAttack::processEvent(Event& event)
{
m_stateStack.processEvent(event);
}
void DrawAttack::renderTopScreen(Window& window)
{
window.clear(Color::White);
m_stateStack.renderTopScreen(window);
window.setView(window.getDefaultView());
window.draw(textFPS);
}
void DrawAttack::renderBottomScreen(Window& window)
{
window.clear(Color(100, 100, 220));
m_stateStack.renderBottomScreen(window);
}
} // namespace DrawAttack
<commit_msg>Fix state stack bug exiting prematurely<commit_after>#include "DrawAttack.hpp"
#include "States/TitleState.hpp"
#include "States/ServerSelectState.hpp"
#include "States/PlayState.hpp"
#include "States/DisconnectedState.hpp"
#include "States/NameSelectState.hpp"
using namespace cpp3ds;
using namespace TweenEngine;
namespace DrawAttack {
DrawAttack::DrawAttack()
: m_stateStack(State::Context(m_client, m_name, m_data))
{
textFPS.setColor(Color::Blue);
m_stateStack.registerState<TitleState>(States::Title);
m_stateStack.registerState<ServerSelectState>(States::ServerSelect);
m_stateStack.registerState<NameSelectState>(States::NameSelect);
m_stateStack.registerState<PlayState>(States::Play);
m_stateStack.registerState<DisconnectedState>(States::Disconnected);
m_stateStack.pushState(States::ServerSelect);
}
DrawAttack::~DrawAttack()
{
// Destructor called when game exits
}
void DrawAttack::update(float delta)
{
// Need to update before checking if empty
m_stateStack.update(delta);
if (m_stateStack.isEmpty())
exit();
static int i;
if (i++ % 10 == 0) {
textFPS.setString(_("%.1f fps", 1.f / delta));
textFPS.setPosition(395 - textFPS.getGlobalBounds().width, 200);
}
}
void DrawAttack::processEvent(Event& event)
{
m_stateStack.processEvent(event);
}
void DrawAttack::renderTopScreen(Window& window)
{
window.clear(Color::White);
m_stateStack.renderTopScreen(window);
window.setView(window.getDefaultView());
window.draw(textFPS);
}
void DrawAttack::renderBottomScreen(Window& window)
{
window.clear(Color(100, 100, 220));
m_stateStack.renderBottomScreen(window);
}
} // namespace DrawAttack
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: dflyobj.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: pjunck $ $Date: 2004-11-03 09:52:13 $
*
* 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 _DFLYOBJ_HXX
#define _DFLYOBJ_HXX
#ifndef _SVDOVIRT_HXX //autogen
#include <svx/svdovirt.hxx>
#endif
#ifndef _SVDOBJ_HXX //autogen
#include <svx/svdobj.hxx>
#endif
class SwFlyFrm;
class SwFrmFmt;
class SdrObjMacroHitRec;
const UINT32 SWGInventor = UINT32('S')*0x00000001+
UINT32('W')*0x00000100+
UINT32('G')*0x00010000;
const UINT16 SwFlyDrawObjIdentifier = 0x0001;
const UINT16 SwDrawFirst = 0x0001;
//---------------------------------------
//SwFlyDrawObj, Die DrawObjekte fuer Flys.
class SwFlyDrawObj : public SdrObject
{
virtual sdr::properties::BaseProperties* CreateObjectSpecificProperties();
public:
TYPEINFO();
SwFlyDrawObj();
~SwFlyDrawObj();
virtual sal_Bool DoPaintObject(XOutputDevice& rOut, const SdrPaintInfoRec& rInfoRec) const;
//Damit eine Instanz dieser Klasse beim laden erzeugt werden kann
//(per Factory).
virtual UINT32 GetObjInventor() const;
virtual UINT16 GetObjIdentifier() const;
virtual UINT16 GetObjVersion() const;
};
//---------------------------------------
//SwVirtFlyDrawObj, die virtuellen Objekte fuer Flys.
//Flys werden immer mit virtuellen Objekten angezeigt. Nur so koennen sie
//ggf. mehrfach angezeigt werden (Kopf-/Fusszeilen).
class SwVirtFlyDrawObj : public SdrVirtObj
{
SwFlyFrm *pFlyFrm;
public:
TYPEINFO();
SwVirtFlyDrawObj(SdrObject& rNew, SwFlyFrm* pFly);
~SwVirtFlyDrawObj();
//Ueberladene Methoden der Basisklasse SdrVirtObj
virtual SdrObject* CheckHit(const Point& rPnt, USHORT nTol, const SetOfByte* pVisiLayer) const;
virtual sal_Bool DoPaintObject(XOutputDevice& rOut, const SdrPaintInfoRec& rInfoRec) const;
virtual void TakeObjInfo( SdrObjTransformInfoRec& rInfo ) const;
//Wir nehemen die Groessenbehandlung vollstaendig selbst in die Hand.
virtual const Rectangle& GetCurrentBoundRect() const;
virtual void RecalcBoundRect();
virtual void RecalcSnapRect();
virtual const Rectangle& GetSnapRect() const;
virtual void SetSnapRect(const Rectangle& rRect);
virtual void NbcSetSnapRect(const Rectangle& rRect);
virtual const Rectangle& GetLogicRect() const;
virtual void SetLogicRect(const Rectangle& rRect);
virtual void NbcSetLogicRect(const Rectangle& rRect);
virtual void TakeXorPoly(XPolyPolygon& rPoly, FASTBOOL) const;
virtual void NbcMove (const Size& rSiz);
virtual void NbcResize(const Point& rRef, const Fraction& xFact,
const Fraction& yFact);
virtual void Move (const Size& rSiz);
virtual void Resize(const Point& rRef, const Fraction& xFact,
const Fraction& yFact);
const SwFrmFmt *GetFmt() const;
SwFrmFmt *GetFmt();
// Get Methoden fuer die Fly Verpointerung
SwFlyFrm* GetFlyFrm() { return pFlyFrm; }
const SwFlyFrm* GetFlyFrm() const { return pFlyFrm; }
void SetRect() const;
// ist eine URL an einer Grafik gesetzt, dann ist das ein Makro-Object
virtual FASTBOOL HasMacro() const;
virtual SdrObject* CheckMacroHit (const SdrObjMacroHitRec& rRec) const;
virtual Pointer GetMacroPointer (const SdrObjMacroHitRec& rRec) const;
};
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.6.484); FILE MERGED 2005/09/05 13:39:54 rt 1.6.484.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: dflyobj.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2005-09-09 03:44:25 $
*
* 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 _DFLYOBJ_HXX
#define _DFLYOBJ_HXX
#ifndef _SVDOVIRT_HXX //autogen
#include <svx/svdovirt.hxx>
#endif
#ifndef _SVDOBJ_HXX //autogen
#include <svx/svdobj.hxx>
#endif
class SwFlyFrm;
class SwFrmFmt;
class SdrObjMacroHitRec;
const UINT32 SWGInventor = UINT32('S')*0x00000001+
UINT32('W')*0x00000100+
UINT32('G')*0x00010000;
const UINT16 SwFlyDrawObjIdentifier = 0x0001;
const UINT16 SwDrawFirst = 0x0001;
//---------------------------------------
//SwFlyDrawObj, Die DrawObjekte fuer Flys.
class SwFlyDrawObj : public SdrObject
{
virtual sdr::properties::BaseProperties* CreateObjectSpecificProperties();
public:
TYPEINFO();
SwFlyDrawObj();
~SwFlyDrawObj();
virtual sal_Bool DoPaintObject(XOutputDevice& rOut, const SdrPaintInfoRec& rInfoRec) const;
//Damit eine Instanz dieser Klasse beim laden erzeugt werden kann
//(per Factory).
virtual UINT32 GetObjInventor() const;
virtual UINT16 GetObjIdentifier() const;
virtual UINT16 GetObjVersion() const;
};
//---------------------------------------
//SwVirtFlyDrawObj, die virtuellen Objekte fuer Flys.
//Flys werden immer mit virtuellen Objekten angezeigt. Nur so koennen sie
//ggf. mehrfach angezeigt werden (Kopf-/Fusszeilen).
class SwVirtFlyDrawObj : public SdrVirtObj
{
SwFlyFrm *pFlyFrm;
public:
TYPEINFO();
SwVirtFlyDrawObj(SdrObject& rNew, SwFlyFrm* pFly);
~SwVirtFlyDrawObj();
//Ueberladene Methoden der Basisklasse SdrVirtObj
virtual SdrObject* CheckHit(const Point& rPnt, USHORT nTol, const SetOfByte* pVisiLayer) const;
virtual sal_Bool DoPaintObject(XOutputDevice& rOut, const SdrPaintInfoRec& rInfoRec) const;
virtual void TakeObjInfo( SdrObjTransformInfoRec& rInfo ) const;
//Wir nehemen die Groessenbehandlung vollstaendig selbst in die Hand.
virtual const Rectangle& GetCurrentBoundRect() const;
virtual void RecalcBoundRect();
virtual void RecalcSnapRect();
virtual const Rectangle& GetSnapRect() const;
virtual void SetSnapRect(const Rectangle& rRect);
virtual void NbcSetSnapRect(const Rectangle& rRect);
virtual const Rectangle& GetLogicRect() const;
virtual void SetLogicRect(const Rectangle& rRect);
virtual void NbcSetLogicRect(const Rectangle& rRect);
virtual void TakeXorPoly(XPolyPolygon& rPoly, FASTBOOL) const;
virtual void NbcMove (const Size& rSiz);
virtual void NbcResize(const Point& rRef, const Fraction& xFact,
const Fraction& yFact);
virtual void Move (const Size& rSiz);
virtual void Resize(const Point& rRef, const Fraction& xFact,
const Fraction& yFact);
const SwFrmFmt *GetFmt() const;
SwFrmFmt *GetFmt();
// Get Methoden fuer die Fly Verpointerung
SwFlyFrm* GetFlyFrm() { return pFlyFrm; }
const SwFlyFrm* GetFlyFrm() const { return pFlyFrm; }
void SetRect() const;
// ist eine URL an einer Grafik gesetzt, dann ist das ein Makro-Object
virtual FASTBOOL HasMacro() const;
virtual SdrObject* CheckMacroHit (const SdrObjMacroHitRec& rRec) const;
virtual Pointer GetMacroPointer (const SdrObjMacroHitRec& rRec) const;
};
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: porexp.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: vg $ $Date: 2003-04-17 14:28:04 $
*
* 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): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _VIEWOPT_HXX
#include <viewopt.hxx> // SwViewOptions
#endif
#ifndef _SW_PORTIONHANDLER_HXX
#include <SwPortionHandler.hxx>
#endif
#ifndef _INFTXT_HXX
#include <inftxt.hxx>
#endif
#ifndef _POREXP_HXX
#include <porexp.hxx>
#endif
#ifndef _PORLAY_HXX
#include <porlay.hxx>
#endif
/*************************************************************************
* class SwExpandPortion
*************************************************************************/
xub_StrLen SwExpandPortion::GetCrsrOfst( const MSHORT nOfst ) const
{ return SwLinePortion::GetCrsrOfst( nOfst ); }
/*************************************************************************
* virtual SwExpandPortion::GetExpTxt()
*************************************************************************/
sal_Bool SwExpandPortion::GetExpTxt( const SwTxtSizeInfo &rInf,
XubString &rTxt ) const
{
rTxt.Erase();
// Nicht etwa: return 0 != rTxt.Len();
// Weil: leere Felder ersetzen CH_TXTATR gegen einen Leerstring
return sal_True;
}
/*************************************************************************
* virtual SwExpandPortion::HandlePortion()
*************************************************************************/
void SwExpandPortion::HandlePortion( SwPortionHandler& rPH ) const
{
String aString;
rPH.Special( GetLen(), aString, GetWhichPor() );
}
/*************************************************************************
* virtual SwExpandPortion::GetTxtSize()
*************************************************************************/
SwPosSize SwExpandPortion::GetTxtSize( const SwTxtSizeInfo &rInf ) const
{
SwTxtSlot aDiffTxt( &rInf, this );
return rInf.GetTxtSize();
}
/*************************************************************************
* virtual SwExpandPortion::Format()
*************************************************************************/
// 5010: Exp und Tabs
sal_Bool SwExpandPortion::Format( SwTxtFormatInfo &rInf )
{
SwTxtSlotLen aDiffTxt( &rInf, this );
const xub_StrLen nFullLen = rInf.GetLen();
// So komisch es aussieht, die Abfrage auf GetLen() muss wegen der
// ExpandPortions _hinter_ aDiffTxt (vgl. SoftHyphs)
// sal_False returnen wegen SetFull ...
if( !nFullLen )
{
// nicht Init(), weil wir Hoehe und Ascent brauchen
Width(0);
return sal_False;
}
return SwTxtPortion::Format( rInf );
}
/*************************************************************************
* virtual SwExpandPortion::Paint()
*************************************************************************/
void SwExpandPortion::Paint( const SwTxtPaintInfo &rInf ) const
{
SwTxtSlotLen aDiffTxt( &rInf, this );
rInf.DrawBackBrush( *this );
// do we have to repaint a post it portion?
if( rInf.OnWin() && pPortion && !pPortion->Width() )
pPortion->PrePaint( rInf, this );
// The contents of field portions is not considered during the
// calculation of the directions. Therefore we let vcl handle
// the calculation by removing the BIDI_STRONG_FLAG temporarily.
SwLayoutModeModifier aLayoutModeModifier( *rInf.GetOut() );
aLayoutModeModifier.SetAuto();
rInf.DrawText( *this, rInf.GetLen(), sal_False );
}
/*************************************************************************
* class SwBlankPortion
*************************************************************************/
SwLinePortion *SwBlankPortion::Compress() { return this; }
/*************************************************************************
* SwBlankPortion::MayUnderFlow()
*************************************************************************/
// 5497: Es gibt schon Gemeinheiten auf der Welt...
// Wenn eine Zeile voll mit HardBlanks ist und diese ueberlaeuft,
// dann duerfen keine Underflows generiert werden!
// Komplikationen bei Flys...
MSHORT SwBlankPortion::MayUnderFlow( const SwTxtFormatInfo &rInf,
xub_StrLen nIdx, sal_Bool bUnderFlow ) const
{
if( rInf.StopUnderFlow() )
return 0;
const SwLinePortion *pPos = rInf.GetRoot();
if( pPos->GetPortion() )
pPos = pPos->GetPortion();
while( pPos && pPos->IsBlankPortion() )
pPos = pPos->GetPortion();
if( !pPos || !rInf.GetIdx() || ( !pPos->GetLen() && pPos == rInf.GetRoot() ) )
return 0; // Nur noch BlankPortions unterwegs
// Wenn vor uns ein Blank ist, brauchen wir kein Underflow ausloesen,
// wenn hinter uns ein Blank ist, brauchen wir kein Underflow weiterreichen
if( bUnderFlow && CH_BLANK == rInf.GetTxt().GetChar( nIdx + 1) )
return 0;
if( nIdx && !((SwTxtFormatInfo&)rInf).GetFly() )
{
while( pPos && !pPos->IsFlyPortion() )
pPos = pPos->GetPortion();
if( !pPos )
{
//Hier wird ueberprueft, ob es in dieser Zeile noch sinnvolle Umbrueche
//gibt, Blanks oder Felder etc., wenn nicht, kein Underflow.
//Wenn Flys im Spiel sind, lassen wir das Underflow trotzdem zu.
xub_StrLen nBlank = nIdx;
while( --nBlank > rInf.GetLineStart() )
{
const xub_Unicode cCh = rInf.GetChar( nBlank );
if( CH_BLANK == cCh ||
(( CH_TXTATR_BREAKWORD == cCh || CH_TXTATR_INWORD == cCh )
&& rInf.HasHint( nBlank ) ) )
break;
}
if( nBlank <= rInf.GetLineStart() )
return 0;
}
}
xub_Unicode cCh;
if( nIdx < 2 || CH_BLANK == (cCh = rInf.GetChar( nIdx - 1 )) )
return 1;
if( CH_BREAK == cCh )
return 0;
return 2;
}
/*************************************************************************
* virtual SwBlankPortion::FormatEOL()
*************************************************************************/
// Format end of Line
void SwBlankPortion::FormatEOL( SwTxtFormatInfo &rInf )
{
MSHORT nMay = MayUnderFlow( rInf, rInf.GetIdx() - nLineLength, sal_True );
if( nMay )
{
if( nMay > 1 )
{
if( rInf.GetLast() == this )
rInf.SetLast( FindPrevPortion( rInf.GetRoot() ) );
rInf.X( rInf.X() - PrtWidth() );
rInf.SetIdx( rInf.GetIdx() - GetLen() );
}
Truncate();
rInf.SetUnderFlow( this );
if( rInf.GetLast()->IsKernPortion() )
rInf.SetUnderFlow( rInf.GetLast() );
}
}
/*************************************************************************
* virtual SwBlankPortion::Format()
*************************************************************************/
// 7771: UnderFlows weiterreichen und selbst ausloesen!
sal_Bool SwBlankPortion::Format( SwTxtFormatInfo &rInf )
{
const sal_Bool bFull = rInf.IsUnderFlow() || SwExpandPortion::Format( rInf );
if( bFull && MayUnderFlow( rInf, rInf.GetIdx(), rInf.IsUnderFlow() ) )
{
Truncate();
rInf.SetUnderFlow( this );
if( rInf.GetLast()->IsKernPortion() )
rInf.SetUnderFlow( rInf.GetLast() );
}
return bFull;
}
/*************************************************************************
* virtual SwBlankPortion::Paint()
*************************************************************************/
void SwBlankPortion::Paint( const SwTxtPaintInfo &rInf ) const
{
if( !bMulti ) // No gray background for multiportion brackets
rInf.DrawViewOpt( *this, POR_BLANK );
SwExpandPortion::Paint( rInf );
}
/*************************************************************************
* virtual SwBlankPortion::GetExpTxt()
*************************************************************************/
sal_Bool SwBlankPortion::GetExpTxt( const SwTxtSizeInfo &rInf, XubString &rTxt ) const
{
rTxt = cChar;
return sal_True;
}
/*************************************************************************
* virtual SwBlankPortion::HandlePortion()
*************************************************************************/
void SwBlankPortion::HandlePortion( SwPortionHandler& rPH ) const
{
String aString( cChar );
rPH.Special( GetLen(), aString, GetWhichPor() );
}
/*************************************************************************
* class SwPostItsPortion
*************************************************************************/
SwPostItsPortion::SwPostItsPortion( sal_Bool bScrpt )
: nViewWidth(0), bScript( bScrpt )
{
nLineLength = 1;
SetWhichPor( POR_POSTITS );
}
void SwPostItsPortion::Paint( const SwTxtPaintInfo &rInf ) const
{
if( rInf.OnWin() && Width() )
rInf.DrawPostIts( *this, IsScript() );
}
KSHORT SwPostItsPortion::GetViewWidth( const SwTxtSizeInfo &rInf ) const
{
// Nicht zu fassen: PostIts sind immer zu sehen.
return rInf.OnWin() ?
(KSHORT)rInf.GetOpt().GetPostItsWidth( rInf.GetOut() ) : 0;
}
/*************************************************************************
* virtual SwPostItsPortion::Format()
*************************************************************************/
sal_Bool SwPostItsPortion::Format( SwTxtFormatInfo &rInf )
{
sal_Bool bRet = SwLinePortion::Format( rInf );
// 32749: PostIts sollen keine Auswirkung auf Zeilenhoehe etc. haben
SetAscent( 1 );
Height( 1 );
return bRet;
}
/*************************************************************************
* virtual SwPostItsPortion::GetExpTxt()
*************************************************************************/
sal_Bool SwPostItsPortion::GetExpTxt( const SwTxtSizeInfo &rInf,
XubString &rTxt ) const
{
if( rInf.OnWin() && rInf.GetOpt().IsPostIts() )
rTxt = ' ';
else
rTxt.Erase();
return sal_True;
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.11.1254); FILE MERGED 2005/09/05 13:40:54 rt 1.11.1254.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: porexp.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: rt $ $Date: 2005-09-09 04:57:09 $
*
* 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
#ifndef _VIEWOPT_HXX
#include <viewopt.hxx> // SwViewOptions
#endif
#ifndef _SW_PORTIONHANDLER_HXX
#include <SwPortionHandler.hxx>
#endif
#ifndef _INFTXT_HXX
#include <inftxt.hxx>
#endif
#ifndef _POREXP_HXX
#include <porexp.hxx>
#endif
#ifndef _PORLAY_HXX
#include <porlay.hxx>
#endif
/*************************************************************************
* class SwExpandPortion
*************************************************************************/
xub_StrLen SwExpandPortion::GetCrsrOfst( const MSHORT nOfst ) const
{ return SwLinePortion::GetCrsrOfst( nOfst ); }
/*************************************************************************
* virtual SwExpandPortion::GetExpTxt()
*************************************************************************/
sal_Bool SwExpandPortion::GetExpTxt( const SwTxtSizeInfo &rInf,
XubString &rTxt ) const
{
rTxt.Erase();
// Nicht etwa: return 0 != rTxt.Len();
// Weil: leere Felder ersetzen CH_TXTATR gegen einen Leerstring
return sal_True;
}
/*************************************************************************
* virtual SwExpandPortion::HandlePortion()
*************************************************************************/
void SwExpandPortion::HandlePortion( SwPortionHandler& rPH ) const
{
String aString;
rPH.Special( GetLen(), aString, GetWhichPor() );
}
/*************************************************************************
* virtual SwExpandPortion::GetTxtSize()
*************************************************************************/
SwPosSize SwExpandPortion::GetTxtSize( const SwTxtSizeInfo &rInf ) const
{
SwTxtSlot aDiffTxt( &rInf, this );
return rInf.GetTxtSize();
}
/*************************************************************************
* virtual SwExpandPortion::Format()
*************************************************************************/
// 5010: Exp und Tabs
sal_Bool SwExpandPortion::Format( SwTxtFormatInfo &rInf )
{
SwTxtSlotLen aDiffTxt( &rInf, this );
const xub_StrLen nFullLen = rInf.GetLen();
// So komisch es aussieht, die Abfrage auf GetLen() muss wegen der
// ExpandPortions _hinter_ aDiffTxt (vgl. SoftHyphs)
// sal_False returnen wegen SetFull ...
if( !nFullLen )
{
// nicht Init(), weil wir Hoehe und Ascent brauchen
Width(0);
return sal_False;
}
return SwTxtPortion::Format( rInf );
}
/*************************************************************************
* virtual SwExpandPortion::Paint()
*************************************************************************/
void SwExpandPortion::Paint( const SwTxtPaintInfo &rInf ) const
{
SwTxtSlotLen aDiffTxt( &rInf, this );
rInf.DrawBackBrush( *this );
// do we have to repaint a post it portion?
if( rInf.OnWin() && pPortion && !pPortion->Width() )
pPortion->PrePaint( rInf, this );
// The contents of field portions is not considered during the
// calculation of the directions. Therefore we let vcl handle
// the calculation by removing the BIDI_STRONG_FLAG temporarily.
SwLayoutModeModifier aLayoutModeModifier( *rInf.GetOut() );
aLayoutModeModifier.SetAuto();
rInf.DrawText( *this, rInf.GetLen(), sal_False );
}
/*************************************************************************
* class SwBlankPortion
*************************************************************************/
SwLinePortion *SwBlankPortion::Compress() { return this; }
/*************************************************************************
* SwBlankPortion::MayUnderFlow()
*************************************************************************/
// 5497: Es gibt schon Gemeinheiten auf der Welt...
// Wenn eine Zeile voll mit HardBlanks ist und diese ueberlaeuft,
// dann duerfen keine Underflows generiert werden!
// Komplikationen bei Flys...
MSHORT SwBlankPortion::MayUnderFlow( const SwTxtFormatInfo &rInf,
xub_StrLen nIdx, sal_Bool bUnderFlow ) const
{
if( rInf.StopUnderFlow() )
return 0;
const SwLinePortion *pPos = rInf.GetRoot();
if( pPos->GetPortion() )
pPos = pPos->GetPortion();
while( pPos && pPos->IsBlankPortion() )
pPos = pPos->GetPortion();
if( !pPos || !rInf.GetIdx() || ( !pPos->GetLen() && pPos == rInf.GetRoot() ) )
return 0; // Nur noch BlankPortions unterwegs
// Wenn vor uns ein Blank ist, brauchen wir kein Underflow ausloesen,
// wenn hinter uns ein Blank ist, brauchen wir kein Underflow weiterreichen
if( bUnderFlow && CH_BLANK == rInf.GetTxt().GetChar( nIdx + 1) )
return 0;
if( nIdx && !((SwTxtFormatInfo&)rInf).GetFly() )
{
while( pPos && !pPos->IsFlyPortion() )
pPos = pPos->GetPortion();
if( !pPos )
{
//Hier wird ueberprueft, ob es in dieser Zeile noch sinnvolle Umbrueche
//gibt, Blanks oder Felder etc., wenn nicht, kein Underflow.
//Wenn Flys im Spiel sind, lassen wir das Underflow trotzdem zu.
xub_StrLen nBlank = nIdx;
while( --nBlank > rInf.GetLineStart() )
{
const xub_Unicode cCh = rInf.GetChar( nBlank );
if( CH_BLANK == cCh ||
(( CH_TXTATR_BREAKWORD == cCh || CH_TXTATR_INWORD == cCh )
&& rInf.HasHint( nBlank ) ) )
break;
}
if( nBlank <= rInf.GetLineStart() )
return 0;
}
}
xub_Unicode cCh;
if( nIdx < 2 || CH_BLANK == (cCh = rInf.GetChar( nIdx - 1 )) )
return 1;
if( CH_BREAK == cCh )
return 0;
return 2;
}
/*************************************************************************
* virtual SwBlankPortion::FormatEOL()
*************************************************************************/
// Format end of Line
void SwBlankPortion::FormatEOL( SwTxtFormatInfo &rInf )
{
MSHORT nMay = MayUnderFlow( rInf, rInf.GetIdx() - nLineLength, sal_True );
if( nMay )
{
if( nMay > 1 )
{
if( rInf.GetLast() == this )
rInf.SetLast( FindPrevPortion( rInf.GetRoot() ) );
rInf.X( rInf.X() - PrtWidth() );
rInf.SetIdx( rInf.GetIdx() - GetLen() );
}
Truncate();
rInf.SetUnderFlow( this );
if( rInf.GetLast()->IsKernPortion() )
rInf.SetUnderFlow( rInf.GetLast() );
}
}
/*************************************************************************
* virtual SwBlankPortion::Format()
*************************************************************************/
// 7771: UnderFlows weiterreichen und selbst ausloesen!
sal_Bool SwBlankPortion::Format( SwTxtFormatInfo &rInf )
{
const sal_Bool bFull = rInf.IsUnderFlow() || SwExpandPortion::Format( rInf );
if( bFull && MayUnderFlow( rInf, rInf.GetIdx(), rInf.IsUnderFlow() ) )
{
Truncate();
rInf.SetUnderFlow( this );
if( rInf.GetLast()->IsKernPortion() )
rInf.SetUnderFlow( rInf.GetLast() );
}
return bFull;
}
/*************************************************************************
* virtual SwBlankPortion::Paint()
*************************************************************************/
void SwBlankPortion::Paint( const SwTxtPaintInfo &rInf ) const
{
if( !bMulti ) // No gray background for multiportion brackets
rInf.DrawViewOpt( *this, POR_BLANK );
SwExpandPortion::Paint( rInf );
}
/*************************************************************************
* virtual SwBlankPortion::GetExpTxt()
*************************************************************************/
sal_Bool SwBlankPortion::GetExpTxt( const SwTxtSizeInfo &rInf, XubString &rTxt ) const
{
rTxt = cChar;
return sal_True;
}
/*************************************************************************
* virtual SwBlankPortion::HandlePortion()
*************************************************************************/
void SwBlankPortion::HandlePortion( SwPortionHandler& rPH ) const
{
String aString( cChar );
rPH.Special( GetLen(), aString, GetWhichPor() );
}
/*************************************************************************
* class SwPostItsPortion
*************************************************************************/
SwPostItsPortion::SwPostItsPortion( sal_Bool bScrpt )
: nViewWidth(0), bScript( bScrpt )
{
nLineLength = 1;
SetWhichPor( POR_POSTITS );
}
void SwPostItsPortion::Paint( const SwTxtPaintInfo &rInf ) const
{
if( rInf.OnWin() && Width() )
rInf.DrawPostIts( *this, IsScript() );
}
KSHORT SwPostItsPortion::GetViewWidth( const SwTxtSizeInfo &rInf ) const
{
// Nicht zu fassen: PostIts sind immer zu sehen.
return rInf.OnWin() ?
(KSHORT)rInf.GetOpt().GetPostItsWidth( rInf.GetOut() ) : 0;
}
/*************************************************************************
* virtual SwPostItsPortion::Format()
*************************************************************************/
sal_Bool SwPostItsPortion::Format( SwTxtFormatInfo &rInf )
{
sal_Bool bRet = SwLinePortion::Format( rInf );
// 32749: PostIts sollen keine Auswirkung auf Zeilenhoehe etc. haben
SetAscent( 1 );
Height( 1 );
return bRet;
}
/*************************************************************************
* virtual SwPostItsPortion::GetExpTxt()
*************************************************************************/
sal_Bool SwPostItsPortion::GetExpTxt( const SwTxtSizeInfo &rInf,
XubString &rTxt ) const
{
if( rInf.OnWin() && rInf.GetOpt().IsPostIts() )
rTxt = ' ';
else
rTxt.Erase();
return sal_True;
}
<|endoftext|>
|
<commit_before><commit_msg>coverity#708455 Uninitialized scalar field<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: portox.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: obo $ $Date: 2006-09-16 21:39:13 $
*
* 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_sw.hxx"
#ifndef _SW_PORTIONHANDLER_HXX
#include <SwPortionHandler.hxx>
#endif
#include "viewopt.hxx" // SwViewOptions
#include "txtcfg.hxx"
#include "portox.hxx"
#include "inftxt.hxx" // GetTxtSize()
/*************************************************************************
* virtual SwToxPortion::Paint()
*************************************************************************/
void SwToxPortion::Paint( const SwTxtPaintInfo &rInf ) const
{
if( Width() )
{
rInf.DrawViewOpt( *this, POR_TOX );
SwTxtPortion::Paint( rInf );
}
}
/*************************************************************************
* class SwIsoToxPortion
*************************************************************************/
SwLinePortion *SwIsoToxPortion::Compress() { return this; }
SwIsoToxPortion::SwIsoToxPortion() : nViewWidth(0)
{
SetLen(1);
SetWhichPor( POR_ISOTOX );
}
/*************************************************************************
* virtual SwIsoToxPortion::GetViewWidth()
*************************************************************************/
KSHORT SwIsoToxPortion::GetViewWidth( const SwTxtSizeInfo &rInf ) const
{
// Wir stehen zwar im const, aber nViewWidth sollte erst im letzten
// Moment errechnet werden:
SwIsoToxPortion* pThis = (SwIsoToxPortion*)this;
// nViewWidth muss errechnet werden.
if( !Width() && rInf.OnWin() &&
!rInf.GetOpt().IsPagePreview() &&
!rInf.GetOpt().IsReadonly() && SwViewOption::IsFieldShadings() )
{
if( !nViewWidth )
pThis->nViewWidth = rInf.GetTxtSize( ' ' ).Width();
}
else
pThis->nViewWidth = 0;
return nViewWidth;
}
/*************************************************************************
* virtual SwIsoToxPortion::Format()
*************************************************************************/
sal_Bool SwIsoToxPortion::Format( SwTxtFormatInfo &rInf )
{
const sal_Bool bFull = SwLinePortion::Format( rInf );
return bFull;
}
/*************************************************************************
* virtual SwIsoToxPortion::Paint()
*************************************************************************/
void SwIsoToxPortion::Paint( const SwTxtPaintInfo &rInf ) const
{
if( Width() )
rInf.DrawViewOpt( *this, POR_TOX );
}
/*************************************************************************
* virtual SwIsoToxPortion::HandlePortion()
*************************************************************************/
void SwIsoToxPortion::HandlePortion( SwPortionHandler& rPH ) const
{
String aString;
rPH.Special( GetLen(), aString, GetWhichPor() );
}
<commit_msg>INTEGRATION: CWS changefileheader (1.8.718); FILE MERGED 2008/04/01 12:54:24 thb 1.8.718.2: #i85898# Stripping all external header guards 2008/03/31 16:54:40 rt 1.8.718.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: portox.cxx,v $
* $Revision: 1.9 $
*
* 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_sw.hxx"
#include <SwPortionHandler.hxx>
#include "viewopt.hxx" // SwViewOptions
#include "txtcfg.hxx"
#include "portox.hxx"
#include "inftxt.hxx" // GetTxtSize()
/*************************************************************************
* virtual SwToxPortion::Paint()
*************************************************************************/
void SwToxPortion::Paint( const SwTxtPaintInfo &rInf ) const
{
if( Width() )
{
rInf.DrawViewOpt( *this, POR_TOX );
SwTxtPortion::Paint( rInf );
}
}
/*************************************************************************
* class SwIsoToxPortion
*************************************************************************/
SwLinePortion *SwIsoToxPortion::Compress() { return this; }
SwIsoToxPortion::SwIsoToxPortion() : nViewWidth(0)
{
SetLen(1);
SetWhichPor( POR_ISOTOX );
}
/*************************************************************************
* virtual SwIsoToxPortion::GetViewWidth()
*************************************************************************/
KSHORT SwIsoToxPortion::GetViewWidth( const SwTxtSizeInfo &rInf ) const
{
// Wir stehen zwar im const, aber nViewWidth sollte erst im letzten
// Moment errechnet werden:
SwIsoToxPortion* pThis = (SwIsoToxPortion*)this;
// nViewWidth muss errechnet werden.
if( !Width() && rInf.OnWin() &&
!rInf.GetOpt().IsPagePreview() &&
!rInf.GetOpt().IsReadonly() && SwViewOption::IsFieldShadings() )
{
if( !nViewWidth )
pThis->nViewWidth = rInf.GetTxtSize( ' ' ).Width();
}
else
pThis->nViewWidth = 0;
return nViewWidth;
}
/*************************************************************************
* virtual SwIsoToxPortion::Format()
*************************************************************************/
sal_Bool SwIsoToxPortion::Format( SwTxtFormatInfo &rInf )
{
const sal_Bool bFull = SwLinePortion::Format( rInf );
return bFull;
}
/*************************************************************************
* virtual SwIsoToxPortion::Paint()
*************************************************************************/
void SwIsoToxPortion::Paint( const SwTxtPaintInfo &rInf ) const
{
if( Width() )
rInf.DrawViewOpt( *this, POR_TOX );
}
/*************************************************************************
* virtual SwIsoToxPortion::HandlePortion()
*************************************************************************/
void SwIsoToxPortion::HandlePortion( SwPortionHandler& rPH ) const
{
String aString;
rPH.Special( GetLen(), aString, GetWhichPor() );
}
<|endoftext|>
|
<commit_before>// This file was developed by Thomas Müller <thomas94@gmx.net>.
// It is published under the BSD 3-Clause License within the LICENSE file.
#include <tev/HelpWindow.h>
#include <nanogui/button.h>
#include <nanogui/entypo.h>
#include <nanogui/label.h>
#include <nanogui/layout.h>
#include <nanogui/opengl.h>
#include <nanogui/window.h>
using namespace nanogui;
using namespace std;
TEV_NAMESPACE_BEGIN
#ifdef __APPLE__
string HelpWindow::COMMAND = "Cmd";
#else
string HelpWindow::COMMAND = "Ctrl";
#endif
#ifdef __APPLE__
string HelpWindow::ALT = "Opt";
#else
string HelpWindow::ALT = "Alt";
#endif
HelpWindow::HelpWindow(Widget *parent, function<void()> closeCallback)
: Window{parent, "Help – Keybindings"}, mCloseCallback{closeCallback} {
auto closeButton = new Button{buttonPanel(), "", ENTYPO_ICON_CROSS};
closeButton->setCallback(mCloseCallback);
setLayout(new GroupLayout{});
setFixedWidth(435);
auto addRow = [](Widget* current, string keys, string desc) {
auto row = new Widget{current};
row->setLayout(new BoxLayout{Orientation::Horizontal, Alignment::Fill, 0, 10});
auto descWidget = new Label{row, desc, "sans"};
descWidget->setFixedWidth(210);
new Label{row, keys, "sans-bold"};
};
auto addSpacer = [](Widget* current) {
auto row = new Widget{current};
row->setHeight(10);
};
new Label{this, "Image Loading", "sans-bold", 18};
auto imageLoading = new Widget{this};
imageLoading->setLayout(new BoxLayout{Orientation::Vertical, Alignment::Fill, 0, 0});
addRow(imageLoading, COMMAND + "+O", "Open Image");
addRow(imageLoading, COMMAND + "+R or F5", "Reload Image");
addRow(imageLoading, COMMAND + "+Shift+R or " + COMMAND + "+F5", "Reload All Images");
addRow(imageLoading, COMMAND + "+W", "Close Image");
new Label{this, "Image Options", "sans-bold", 18};
auto imageSelection = new Widget{this};
imageSelection->setLayout(new BoxLayout{Orientation::Vertical, Alignment::Fill, 0, 0});
addRow(imageSelection, "Left Click", "Select Hovered Image");
addRow(imageSelection, "1…9", "Select N-th Image");
addRow(imageSelection, "Down or S", "Select Next Image");
addRow(imageSelection, "Up or W", "Select Previous Image");
addSpacer(imageSelection);
addRow(imageSelection, "F", "Fit Image to Screen");
addRow(imageSelection, "N", "Normalize Image to [0, 1]");
addRow(imageSelection, "R", "Reset Image Parameters");
addSpacer(imageSelection);
addRow(imageSelection, "Shift+Right or Shift+D", "Select Next Tonemap");
addRow(imageSelection, "Shift+Left or Shift+A", "Select Previous Tonemap");
addSpacer(imageSelection);
addRow(imageSelection, "E", "Increase Exposure by 0.5");
addRow(imageSelection, "Shift+E", "Decrease Exposure by 0.5");
addRow(imageSelection, "O", "Increase Offset by 0.1");
addRow(imageSelection, "Shift+O", "Decrease Offset by 0.1");
new Label{this, "Reference Options", "sans-bold", 18};
auto referenceSelection = new Widget{this};
referenceSelection->setLayout(new BoxLayout{Orientation::Vertical, Alignment::Fill, 0, 0});
addRow(referenceSelection, "Shift+Left Click or Right Click", "Select Hovered Image as Reference");
addRow(referenceSelection, "Shift+1…9", "Select N-th Image as Reference");
addRow(referenceSelection, "Shift+Down or Shift+S", "Select Next Image as Reference");
addRow(referenceSelection, "Shift+Up or Shift+W", "Select Previous Image as Reference");
addSpacer(referenceSelection);
addRow(referenceSelection, "Ctrl+Right or Ctrl+D", "Select Next Error Metric");
addRow(referenceSelection, "Ctrl+Left or Ctrl+A", "Select Previous Error Metric");
new Label{this, "Layer Options", "sans-bold", 18};
auto layerSelection = new Widget{this};
layerSelection->setLayout(new BoxLayout{Orientation::Vertical, Alignment::Fill, 0, 0});
addRow(layerSelection, "Left Click", "Select Hovered Layer");
addRow(layerSelection, "Ctrl+1…9", "Select N-th Layer");
addRow(layerSelection, "Right or D", "Select Next Layer");
addRow(layerSelection, "Left or A", "Select Previous Layer");
new Label{this, "Interface", "sans-bold", 18};
auto ui = new Widget{this};
ui->setLayout(new BoxLayout{Orientation::Vertical, Alignment::Fill, 0, 0});
addRow(ui, ALT + "+Enter", "Maximize");
addRow(ui, COMMAND + "+B", "Toggle GUI");
addRow(ui, "H", "Show Help (this Window)");
addRow(ui, COMMAND + "+P", "Find Image or Layer");
addRow(ui, "Q or Esc", "Quit");
}
bool HelpWindow::keyboardEvent(int key, int scancode, int action, int modifiers) {
if (Window::keyboardEvent(key, scancode, action, modifiers)) {
return true;
}
if (key == GLFW_KEY_ESCAPE) {
mCloseCallback();
return true;
}
return false;
}
TEV_NAMESPACE_END
<commit_msg>Add save shortcut to help window<commit_after>// This file was developed by Thomas Müller <thomas94@gmx.net>.
// It is published under the BSD 3-Clause License within the LICENSE file.
#include <tev/HelpWindow.h>
#include <nanogui/button.h>
#include <nanogui/entypo.h>
#include <nanogui/label.h>
#include <nanogui/layout.h>
#include <nanogui/opengl.h>
#include <nanogui/window.h>
using namespace nanogui;
using namespace std;
TEV_NAMESPACE_BEGIN
#ifdef __APPLE__
string HelpWindow::COMMAND = "Cmd";
#else
string HelpWindow::COMMAND = "Ctrl";
#endif
#ifdef __APPLE__
string HelpWindow::ALT = "Opt";
#else
string HelpWindow::ALT = "Alt";
#endif
HelpWindow::HelpWindow(Widget *parent, function<void()> closeCallback)
: Window{parent, "Help – Keybindings"}, mCloseCallback{closeCallback} {
auto closeButton = new Button{buttonPanel(), "", ENTYPO_ICON_CROSS};
closeButton->setCallback(mCloseCallback);
setLayout(new GroupLayout{});
setFixedWidth(435);
auto addRow = [](Widget* current, string keys, string desc) {
auto row = new Widget{current};
row->setLayout(new BoxLayout{Orientation::Horizontal, Alignment::Fill, 0, 10});
auto descWidget = new Label{row, desc, "sans"};
descWidget->setFixedWidth(210);
new Label{row, keys, "sans-bold"};
};
auto addSpacer = [](Widget* current) {
auto row = new Widget{current};
row->setHeight(10);
};
new Label{this, "Image Loading", "sans-bold", 18};
auto imageLoading = new Widget{this};
imageLoading->setLayout(new BoxLayout{Orientation::Vertical, Alignment::Fill, 0, 0});
addRow(imageLoading, COMMAND + "+O", "Open Image");
addRow(imageLoading, COMMAND + "+S", "Save View as Image");
addRow(imageLoading, COMMAND + "+R or F5", "Reload Image");
addRow(imageLoading, COMMAND + "+Shift+R or " + COMMAND + "+F5", "Reload All Images");
addRow(imageLoading, COMMAND + "+W", "Close Image");
new Label{this, "Image Options", "sans-bold", 18};
auto imageSelection = new Widget{this};
imageSelection->setLayout(new BoxLayout{Orientation::Vertical, Alignment::Fill, 0, 0});
addRow(imageSelection, "Left Click", "Select Hovered Image");
addRow(imageSelection, "1…9", "Select N-th Image");
addRow(imageSelection, "Down or S", "Select Next Image");
addRow(imageSelection, "Up or W", "Select Previous Image");
addSpacer(imageSelection);
addRow(imageSelection, "F", "Fit Image to Screen");
addRow(imageSelection, "N", "Normalize Image to [0, 1]");
addRow(imageSelection, "R", "Reset Image Parameters");
addSpacer(imageSelection);
addRow(imageSelection, "Shift+Right or Shift+D", "Select Next Tonemap");
addRow(imageSelection, "Shift+Left or Shift+A", "Select Previous Tonemap");
addSpacer(imageSelection);
addRow(imageSelection, "E", "Increase Exposure by 0.5");
addRow(imageSelection, "Shift+E", "Decrease Exposure by 0.5");
addRow(imageSelection, "O", "Increase Offset by 0.1");
addRow(imageSelection, "Shift+O", "Decrease Offset by 0.1");
new Label{this, "Reference Options", "sans-bold", 18};
auto referenceSelection = new Widget{this};
referenceSelection->setLayout(new BoxLayout{Orientation::Vertical, Alignment::Fill, 0, 0});
addRow(referenceSelection, "Shift+Left Click or Right Click", "Select Hovered Image as Reference");
addRow(referenceSelection, "Shift+1…9", "Select N-th Image as Reference");
addRow(referenceSelection, "Shift+Down or Shift+S", "Select Next Image as Reference");
addRow(referenceSelection, "Shift+Up or Shift+W", "Select Previous Image as Reference");
addSpacer(referenceSelection);
addRow(referenceSelection, "Ctrl+Right or Ctrl+D", "Select Next Error Metric");
addRow(referenceSelection, "Ctrl+Left or Ctrl+A", "Select Previous Error Metric");
new Label{this, "Layer Options", "sans-bold", 18};
auto layerSelection = new Widget{this};
layerSelection->setLayout(new BoxLayout{Orientation::Vertical, Alignment::Fill, 0, 0});
addRow(layerSelection, "Left Click", "Select Hovered Layer");
addRow(layerSelection, "Ctrl+1…9", "Select N-th Layer");
addRow(layerSelection, "Right or D", "Select Next Layer");
addRow(layerSelection, "Left or A", "Select Previous Layer");
new Label{this, "Interface", "sans-bold", 18};
auto ui = new Widget{this};
ui->setLayout(new BoxLayout{Orientation::Vertical, Alignment::Fill, 0, 0});
addRow(ui, ALT + "+Enter", "Maximize");
addRow(ui, COMMAND + "+B", "Toggle GUI");
addRow(ui, "H", "Show Help (this Window)");
addRow(ui, COMMAND + "+P", "Find Image or Layer");
addRow(ui, "Q or Esc", "Quit");
}
bool HelpWindow::keyboardEvent(int key, int scancode, int action, int modifiers) {
if (Window::keyboardEvent(key, scancode, action, modifiers)) {
return true;
}
if (key == GLFW_KEY_ESCAPE) {
mCloseCallback();
return true;
}
return false;
}
TEV_NAMESPACE_END
<|endoftext|>
|
<commit_before>//
// QuestionGenerator.cpp
// mathgame1
//
// Created by Nicholas on 25/07/2015.
// Copyright (c) 2015 Nicholas. All rights reserved.
//
#include "QuestionGenerator.h"
#include "QuestionAnswer.h"
#include "RandomNumber.h"
#include <iostream>
struct QuestionAnswer QuestionGenerator(){
QuestionAnswer QA;
int min = 1, max = 10;
//generate 3 random numbers using min and max
int numSwitch = RandomNumber(1, 4);
double num2 = RandomNumber(min, max);
double num3 = RandomNumber(min, max);
int num2INT = num2;
int num3INT = num3;
//std::cout << num2 << "\t" << num3 << std::endl;
//for easy typing
using std::to_string;
//create switch statement that changes to different question
switch(numSwitch)
{
case 1:
QA.question = to_string(num2INT) + " + " + to_string(num3INT);
QA.answer = num2 + num3;
break;
case 2:
QA.question = to_string(num2INT) + " - " + to_string(num3INT);
QA.answer = num2 - num3;
break;
case 3:
QA.question = to_string(num2INT) + " x " + to_string(num3INT);
QA.answer = num2*num3;
break;
case 4:
QA.question = to_string(num2INT) + " / " + to_string(num3INT);
QA.answer = num2/num3;
break;
}
return QA;
}<commit_msg>removed question answer reference<commit_after>//
// QuestionGenerator.cpp
// mathgame1
//
// Created by Nicholas on 25/07/2015.
// Copyright (c) 2015 Nicholas. All rights reserved.
//
#include "QuestionGenerator.h"
#include "RandomNumber.h"
#include <iostream>
struct QuestionAnswer QuestionGenerator(){
QuestionAnswer QA;
int min = 1, max = 10;
//generate 3 random numbers using min and max
int numSwitch = RandomNumber(1, 4);
double num2 = RandomNumber(min, max);
double num3 = RandomNumber(min, max);
int num2INT = num2;
int num3INT = num3;
//std::cout << num2 << "\t" << num3 << std::endl;
//for easy typing
using std::to_string;
//create switch statement that changes to different question
switch(numSwitch)
{
case 1:
QA.question = to_string(num2INT) + " + " + to_string(num3INT);
QA.answer = num2 + num3;
break;
case 2:
QA.question = to_string(num2INT) + " - " + to_string(num3INT);
QA.answer = num2 - num3;
break;
case 3:
QA.question = to_string(num2INT) + " x " + to_string(num3INT);
QA.answer = num2*num3;
break;
case 4:
QA.question = to_string(num2INT) + " / " + to_string(num3INT);
QA.answer = num2/num3;
break;
}
return QA;
}<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: barcfg.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: vg $ $Date: 2003-04-17 15:16:48 $
*
* 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): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _WRTSH_HXX
#include <wrtsh.hxx>
#endif
#include "barcfg.hxx"
using namespace utl;
using namespace rtl;
using namespace com::sun::star::uno;
#define C2U(cChar) OUString::createFromAscii(cChar)
#define SEL_TYPE_TABLE_TEXT 0
#define SEL_TYPE_LIST_TEXT 1
#define SEL_TYPE_TABLE_LIST 2
#define SEL_TYPE_BEZIER 3
#define SEL_TYPE_GRAPHIC 4
/* ---------------------------------------------------------------------------
---------------------------------------------------------------------------*/
SwToolbarConfigItem::SwToolbarConfigItem( BOOL bWeb ) :
ConfigItem(bWeb ? C2U("Office.WriterWeb/ObjectBar") : C2U("Office.Writer/ObjectBar"),
CONFIG_MODE_DELAYED_UPDATE|CONFIG_MODE_RELEASE_TREE)
{
for(USHORT i = 0; i <= SEL_TYPE_GRAPHIC; i++ )
aTbxIdArray[i] = (USHORT)-1;
Sequence<OUString> aNames = GetPropertyNames();
Sequence<Any> aValues = GetProperties(aNames);
const Any* pValues = aValues.getConstArray();
DBG_ASSERT(aValues.getLength() == aNames.getLength(), "GetProperties failed")
if(aValues.getLength() == aNames.getLength())
{
for(int nProp = 0; nProp < aNames.getLength(); nProp++)
{
if(pValues[nProp].hasValue())
{
sal_Int32 nVal;
pValues[nProp] >>= nVal;
aTbxIdArray[nProp] = (sal_uInt16)nVal;
}
}
}
}
/* ---------------------------------------------------------------------------
---------------------------------------------------------------------------*/
SwToolbarConfigItem::~SwToolbarConfigItem()
{
}
/* ---------------------------------------------------------------------------
---------------------------------------------------------------------------*/
sal_Int32 lcl_getArrayIndex(int nSelType)
{
sal_Int32 nRet = -1;
if(nSelType & SwWrtShell::SEL_NUM)
{
if(nSelType & SwWrtShell::SEL_TBL)
nRet = SEL_TYPE_TABLE_LIST;
else
nRet = SEL_TYPE_LIST_TEXT;
}
else if(nSelType & SwWrtShell::SEL_TBL)
nRet = SEL_TYPE_TABLE_TEXT;
else if(nSelType & SwWrtShell::SEL_BEZ)
nRet = SEL_TYPE_BEZIER;
else if(nSelType & SwWrtShell::SEL_GRF)
nRet = SEL_TYPE_GRAPHIC;
return nRet;
}
/* -----------------------------10.10.00 14:38--------------------------------
---------------------------------------------------------------------------*/
void SwToolbarConfigItem::SetTopToolbar( sal_Int32 nSelType, USHORT nBarId )
{
sal_Int32 nProp = lcl_getArrayIndex(nSelType);
if(nProp >= 0)
{
aTbxIdArray[nProp] = nBarId;
SetModified();
}
}
/* ---------------------------------------------------------------------------
---------------------------------------------------------------------------*/
sal_uInt16 SwToolbarConfigItem::GetTopToolbar( sal_Int32 nSelType )
{
sal_Int32 nProp = lcl_getArrayIndex(nSelType);
if(nProp >= 0)
return aTbxIdArray[nProp];
else
return 0xffff;
}
/* -----------------------------10.10.00 13:33--------------------------------
---------------------------------------------------------------------------*/
Sequence<OUString> SwToolbarConfigItem::GetPropertyNames()
{
static const char* aPropNames[] =
{
"Selection/Table", // SEL_TYPE_TABLE_TEXT
"Selection/NumberedList", // SEL_TYPE_LIST_TEXT
"Selection/NumberedList_InTable", // SEL_TYPE_TABLE_LIST
"Selection/BezierObject", // SEL_TYPE_BEZIER
"Selection/Graphic" //SEL_TYPE_GRAPHIC
};
const int nCount = 5;
Sequence<OUString> aNames(nCount);
OUString* pNames = aNames.getArray();
for(int i = 0; i < nCount; i++)
pNames[i] = OUString::createFromAscii(aPropNames[i]);
return aNames;
}
/* -----------------------------10.10.00 13:36--------------------------------
---------------------------------------------------------------------------*/
void SwToolbarConfigItem::Commit()
{
Sequence<OUString> aNames = GetPropertyNames();
OUString* pNames = aNames.getArray();
Sequence<Any> aValues(aNames.getLength());
Any* pValues = aValues.getArray();
const Type& rType = ::getBooleanCppuType();
for(int nProp = 0; nProp < aNames.getLength(); nProp++)
pValues[nProp] <<= (sal_Int32) (aTbxIdArray[nProp] == 0xffff ? -1 : aTbxIdArray[nProp]);
PutProperties(aNames, aValues);
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.5.1254); FILE MERGED 2005/09/05 13:43:20 rt 1.5.1254.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: barcfg.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-09 06:40:50 $
*
* 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
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _WRTSH_HXX
#include <wrtsh.hxx>
#endif
#include "barcfg.hxx"
using namespace utl;
using namespace rtl;
using namespace com::sun::star::uno;
#define C2U(cChar) OUString::createFromAscii(cChar)
#define SEL_TYPE_TABLE_TEXT 0
#define SEL_TYPE_LIST_TEXT 1
#define SEL_TYPE_TABLE_LIST 2
#define SEL_TYPE_BEZIER 3
#define SEL_TYPE_GRAPHIC 4
/* ---------------------------------------------------------------------------
---------------------------------------------------------------------------*/
SwToolbarConfigItem::SwToolbarConfigItem( BOOL bWeb ) :
ConfigItem(bWeb ? C2U("Office.WriterWeb/ObjectBar") : C2U("Office.Writer/ObjectBar"),
CONFIG_MODE_DELAYED_UPDATE|CONFIG_MODE_RELEASE_TREE)
{
for(USHORT i = 0; i <= SEL_TYPE_GRAPHIC; i++ )
aTbxIdArray[i] = (USHORT)-1;
Sequence<OUString> aNames = GetPropertyNames();
Sequence<Any> aValues = GetProperties(aNames);
const Any* pValues = aValues.getConstArray();
DBG_ASSERT(aValues.getLength() == aNames.getLength(), "GetProperties failed")
if(aValues.getLength() == aNames.getLength())
{
for(int nProp = 0; nProp < aNames.getLength(); nProp++)
{
if(pValues[nProp].hasValue())
{
sal_Int32 nVal;
pValues[nProp] >>= nVal;
aTbxIdArray[nProp] = (sal_uInt16)nVal;
}
}
}
}
/* ---------------------------------------------------------------------------
---------------------------------------------------------------------------*/
SwToolbarConfigItem::~SwToolbarConfigItem()
{
}
/* ---------------------------------------------------------------------------
---------------------------------------------------------------------------*/
sal_Int32 lcl_getArrayIndex(int nSelType)
{
sal_Int32 nRet = -1;
if(nSelType & SwWrtShell::SEL_NUM)
{
if(nSelType & SwWrtShell::SEL_TBL)
nRet = SEL_TYPE_TABLE_LIST;
else
nRet = SEL_TYPE_LIST_TEXT;
}
else if(nSelType & SwWrtShell::SEL_TBL)
nRet = SEL_TYPE_TABLE_TEXT;
else if(nSelType & SwWrtShell::SEL_BEZ)
nRet = SEL_TYPE_BEZIER;
else if(nSelType & SwWrtShell::SEL_GRF)
nRet = SEL_TYPE_GRAPHIC;
return nRet;
}
/* -----------------------------10.10.00 14:38--------------------------------
---------------------------------------------------------------------------*/
void SwToolbarConfigItem::SetTopToolbar( sal_Int32 nSelType, USHORT nBarId )
{
sal_Int32 nProp = lcl_getArrayIndex(nSelType);
if(nProp >= 0)
{
aTbxIdArray[nProp] = nBarId;
SetModified();
}
}
/* ---------------------------------------------------------------------------
---------------------------------------------------------------------------*/
sal_uInt16 SwToolbarConfigItem::GetTopToolbar( sal_Int32 nSelType )
{
sal_Int32 nProp = lcl_getArrayIndex(nSelType);
if(nProp >= 0)
return aTbxIdArray[nProp];
else
return 0xffff;
}
/* -----------------------------10.10.00 13:33--------------------------------
---------------------------------------------------------------------------*/
Sequence<OUString> SwToolbarConfigItem::GetPropertyNames()
{
static const char* aPropNames[] =
{
"Selection/Table", // SEL_TYPE_TABLE_TEXT
"Selection/NumberedList", // SEL_TYPE_LIST_TEXT
"Selection/NumberedList_InTable", // SEL_TYPE_TABLE_LIST
"Selection/BezierObject", // SEL_TYPE_BEZIER
"Selection/Graphic" //SEL_TYPE_GRAPHIC
};
const int nCount = 5;
Sequence<OUString> aNames(nCount);
OUString* pNames = aNames.getArray();
for(int i = 0; i < nCount; i++)
pNames[i] = OUString::createFromAscii(aPropNames[i]);
return aNames;
}
/* -----------------------------10.10.00 13:36--------------------------------
---------------------------------------------------------------------------*/
void SwToolbarConfigItem::Commit()
{
Sequence<OUString> aNames = GetPropertyNames();
OUString* pNames = aNames.getArray();
Sequence<Any> aValues(aNames.getLength());
Any* pValues = aValues.getArray();
const Type& rType = ::getBooleanCppuType();
for(int nProp = 0; nProp < aNames.getLength(); nProp++)
pValues[nProp] <<= (sal_Int32) (aTbxIdArray[nProp] == 0xffff ? -1 : aTbxIdArray[nProp]);
PutProperties(aNames, aValues);
}
<|endoftext|>
|
<commit_before><commit_msg>OUString: remove temporaries and repeated expressions<commit_after><|endoftext|>
|
<commit_before>//
// Copyright (c) 2014 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core If not, see
// <http://www.gnu.org/licenses/>.
#include <hpp/core/weighed-distance.hh>
#include <hpp/core/problem.hh>
#include <limits>
#include <Eigen/SVD>
#include <pinocchio/algorithm/jacobian.hpp>
#include <hpp/util/debug.hh>
#include <hpp/pinocchio/body.hh>
#include <hpp/pinocchio/device.hh>
#include <hpp/pinocchio/joint.hh>
namespace hpp {
namespace core {
std::ostream& operator<< (std::ostream& os, const std::vector <value_type>& v)
{
for (std::size_t i=0; i<v.size (); ++i) {
os << v [i] << ",";
}
return os;
}
WeighedDistancePtr_t WeighedDistance::create (const DevicePtr_t& robot)
{
WeighedDistance* ptr = new WeighedDistance (robot);
WeighedDistancePtr_t shPtr (ptr);
ptr->init (shPtr);
return shPtr;
}
WeighedDistancePtr_t WeighedDistance::createFromProblem
(const ProblemPtr_t& problem)
{
WeighedDistance* ptr = new WeighedDistance (problem);
WeighedDistancePtr_t shPtr (ptr);
ptr->init (shPtr);
return shPtr;
}
WeighedDistancePtr_t
WeighedDistance::createWithWeight (const DevicePtr_t& robot,
const std::vector <value_type>& weights)
{
WeighedDistance* ptr = new WeighedDistance (robot, weights);
WeighedDistancePtr_t shPtr (ptr);
ptr->init (shPtr);
return shPtr;
}
WeighedDistancePtr_t WeighedDistance::createCopy
(const WeighedDistancePtr_t& distance)
{
WeighedDistance* ptr = new WeighedDistance (*distance);
WeighedDistancePtr_t shPtr (ptr);
ptr->init (shPtr);
return shPtr;
}
DistancePtr_t WeighedDistance::clone () const
{
return createCopy (weak_.lock ());
}
value_type WeighedDistance::getWeight( std::size_t rank ) const
{
return weights_[rank];
}
void WeighedDistance::setWeight (std::size_t rank, value_type weight )
{
if ( rank < weights_.size() )
{
weights_[rank] = weight;
}
else {
std::ostringstream oss;
oss << "Distance::setWeight : rank " << rank << " is out of range ("
<< weights_.size () << ").";
throw std::runtime_error(oss.str ());
}
}
void WeighedDistance::computeWeights ()
{
typedef Eigen::Matrix<value_type, 3, Eigen::Dynamic> BlockType;
typedef Eigen::JacobiSVD<BlockType> SVD_t;
// Store computation flag
Device_t::Computation_t flag = robot_->computationFlag ();
Device_t::Computation_t newflag = static_cast <Device_t::Computation_t>
(flag | Device_t::JACOBIAN);
robot_->controlComputation (newflag);
robot_->computeForwardKinematics ();
robot_->controlComputation (flag);
value_type minLength = std::numeric_limits <value_type>::infinity ();
JointJacobian_t jacobian(6, robot_->numberDof());
const se3::Model& model = robot_->model();
const se3::Data& data = robot_->data();
for (se3::JointIndex i = 1; i < model.joints.size(); ++i)
{
value_type length = 0;
std::size_t rank = model.joints[i].idx_v();
std::size_t ncol = model.joints[i].nv();
BlockType block;
for (se3::JointIndex j = i; j <= (se3::JointIndex)data.lastChild[i]; ++j)
{
// Get only three first lines of Jacobian
se3::getJacobian<true>(model, data, j, jacobian);
block = data.oMi[j].rotation() * jacobian.block<3, Eigen::Dynamic>(0, rank, 3, ncol);
SVD_t svd (block);
if (length < svd.singularValues () [0]) {
length = svd.singularValues () [0];
}
Body body (robot_, j);
value_type radius = body.radius();
block = data.oMi[j].rotation() * jacobian.block<3, Eigen::Dynamic>(3, rank, 3, ncol);
svd.compute(block);
if (length < radius*svd.singularValues () [0]) {
length = radius*svd.singularValues () [0];
}
}
if (minLength > length && length > 0) minLength = length;
weights_.push_back (length);
for (std::size_t k=0; k < weights_.size (); ++k) {
if (weights_ [k] == 0) {
weights_ [k] = minLength;
}
}
}
}
WeighedDistance::WeighedDistance (const DevicePtr_t& robot) :
robot_ (robot), weights_ ()
{
computeWeights ();
}
WeighedDistance::WeighedDistance (const ProblemPtr_t& problem) :
robot_ (problem->robot()), weights_ ()
{
computeWeights ();
}
WeighedDistance::WeighedDistance (const DevicePtr_t& robot,
const std::vector <value_type>& weights) :
robot_ (robot), weights_ (weights)
{
}
WeighedDistance::WeighedDistance (const WeighedDistance& distance) :
robot_ (distance.robot_),
weights_ (distance.weights_)
{
}
void WeighedDistance::init (WeighedDistanceWkPtr_t self)
{
weak_ = self;
}
value_type WeighedDistance::impl_distance (ConfigurationIn_t q1,
ConfigurationIn_t q2) const
{
// Loop over robot joint and interpolate
value_type res = 0;
const pinocchio::Model& model = robot_->model();
assert (model.joints.size() <= weights_.size () + 1);
for (std::size_t i = 1; i < model.joints.size(); ++i) {
value_type length = weights_ [i-1];
value_type distance = model.joints[i].distance(q1, q2);
res += length * length * distance * distance;
}
res+=(q1 - q2).tail (robot_->extraConfigSpace ().dimension()).squaredNorm ();
return sqrt (res);
}
} // namespace core
} // namespace hpp
<commit_msg>WeighedDistance puts weights on rotational part of SE2 and SE3<commit_after>//
// Copyright (c) 2014 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-core is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core If not, see
// <http://www.gnu.org/licenses/>.
#include <hpp/core/weighed-distance.hh>
#include <limits>
#include <Eigen/SVD>
#include <pinocchio/algorithm/joint-configuration.hpp>
#include <pinocchio/algorithm/jacobian.hpp>
#include <hpp/util/debug.hh>
#include <hpp/pinocchio/body.hh>
#include <hpp/pinocchio/device.hh>
#include <hpp/pinocchio/joint.hh>
#include <hpp/pinocchio/liegroup.hh>
#include <hpp/core/problem.hh>
namespace hpp {
namespace core {
namespace {
struct SquaredDistanceStep : public se3::fusion::JointModelVisitor<SquaredDistanceStep>
{
typedef boost::fusion::vector<const Configuration_t &,
const Configuration_t &,
const value_type &,
value_type &> ArgsType;
JOINT_MODEL_VISITOR_INIT(SquaredDistanceStep);
template<typename JointModel>
static void algo(const se3::JointModelBase<JointModel> & jmodel,
const Configuration_t & q0,
const Configuration_t & q1,
const value_type & w,
value_type & distance)
{
distance = ::hpp::pinocchio::LieGroupTpl::template operation<JointModel>::type
::squaredDistance(
jmodel.jointConfigSelector(q0),
jmodel.jointConfigSelector(q1),
w);
}
};
template <>
void SquaredDistanceStep::algo<se3::JointModelComposite>(
const se3::JointModelBase<se3::JointModelComposite> & jmodel,
const Configuration_t & q0,
const Configuration_t & q1,
const value_type & w,
value_type & distance)
{
se3::details::Dispatch<SquaredDistanceStep>::run(
jmodel.derived(),
ArgsType(q0, q1, w, distance));
}
}
std::ostream& operator<< (std::ostream& os, const std::vector <value_type>& v)
{
for (std::size_t i=0; i<v.size (); ++i) {
os << v [i] << ",";
}
return os;
}
WeighedDistancePtr_t WeighedDistance::create (const DevicePtr_t& robot)
{
WeighedDistance* ptr = new WeighedDistance (robot);
WeighedDistancePtr_t shPtr (ptr);
ptr->init (shPtr);
return shPtr;
}
WeighedDistancePtr_t WeighedDistance::createFromProblem
(const ProblemPtr_t& problem)
{
WeighedDistance* ptr = new WeighedDistance (problem);
WeighedDistancePtr_t shPtr (ptr);
ptr->init (shPtr);
return shPtr;
}
WeighedDistancePtr_t
WeighedDistance::createWithWeight (const DevicePtr_t& robot,
const std::vector <value_type>& weights)
{
WeighedDistance* ptr = new WeighedDistance (robot, weights);
WeighedDistancePtr_t shPtr (ptr);
ptr->init (shPtr);
return shPtr;
}
WeighedDistancePtr_t WeighedDistance::createCopy
(const WeighedDistancePtr_t& distance)
{
WeighedDistance* ptr = new WeighedDistance (*distance);
WeighedDistancePtr_t shPtr (ptr);
ptr->init (shPtr);
return shPtr;
}
DistancePtr_t WeighedDistance::clone () const
{
return createCopy (weak_.lock ());
}
value_type WeighedDistance::getWeight( std::size_t rank ) const
{
return weights_[rank];
}
void WeighedDistance::setWeight (std::size_t rank, value_type weight )
{
if ( rank < weights_.size() )
{
weights_[rank] = weight;
}
else {
std::ostringstream oss;
oss << "Distance::setWeight : rank " << rank << " is out of range ("
<< weights_.size () << ").";
throw std::runtime_error(oss.str ());
}
}
void WeighedDistance::computeWeights ()
{
typedef Eigen::Matrix<value_type, 3, Eigen::Dynamic> BlockType;
typedef Eigen::JacobiSVD<BlockType> SVD_t;
// Store computation flag
Device_t::Computation_t flag = robot_->computationFlag ();
Device_t::Computation_t newflag = static_cast <Device_t::Computation_t>
(flag | Device_t::JACOBIAN);
robot_->controlComputation (newflag);
robot_->computeForwardKinematics ();
robot_->controlComputation (flag);
value_type minLength = std::numeric_limits <value_type>::infinity ();
JointJacobian_t jacobian(6, robot_->numberDof());
const se3::Model& model = robot_->model();
const se3::Data& data = robot_->data();
for (se3::JointIndex i = 1; i < model.joints.size(); ++i)
{
value_type length = 0;
std::size_t rank = model.joints[i].idx_v();
std::size_t ncol = model.joints[i].nv();
BlockType block;
for (se3::JointIndex j = i; j <= (se3::JointIndex)data.lastChild[i]; ++j)
{
// Get only three first lines of Jacobian
se3::getJacobian<true>(model, data, j, jacobian);
block = data.oMi[j].rotation() * jacobian.block<3, Eigen::Dynamic>(0, rank, 3, ncol);
SVD_t svd (block);
if (length < svd.singularValues () [0]) {
length = svd.singularValues () [0];
}
Body body (robot_, j);
value_type radius = body.radius();
block = data.oMi[j].rotation() * jacobian.block<3, Eigen::Dynamic>(3, rank, 3, ncol);
svd.compute(block);
if (length < radius*svd.singularValues () [0]) {
length = radius*svd.singularValues () [0];
}
}
if (minLength > length && length > 0) minLength = length;
weights_.push_back (length);
for (std::size_t k=0; k < weights_.size (); ++k) {
if (weights_ [k] == 0) {
weights_ [k] = minLength;
}
}
}
}
WeighedDistance::WeighedDistance (const DevicePtr_t& robot) :
robot_ (robot), weights_ ()
{
computeWeights ();
}
WeighedDistance::WeighedDistance (const ProblemPtr_t& problem) :
robot_ (problem->robot()), weights_ ()
{
computeWeights ();
}
WeighedDistance::WeighedDistance (const DevicePtr_t& robot,
const std::vector <value_type>& weights) :
robot_ (robot), weights_ (weights)
{
}
WeighedDistance::WeighedDistance (const WeighedDistance& distance) :
robot_ (distance.robot_),
weights_ (distance.weights_)
{
}
void WeighedDistance::init (WeighedDistanceWkPtr_t self)
{
weak_ = self;
}
value_type WeighedDistance::impl_distance (ConfigurationIn_t q1,
ConfigurationIn_t q2) const
{
value_type res = 0, d;
const pinocchio::Model& model = robot_->model();
assert (model.joints.size() <= weights_.size () + 1);
// Loop over robot joint
for( se3::JointIndex i=1; i<(se3::JointIndex) model.njoints; ++i )
{
value_type length = weights_ [i-1];
SquaredDistanceStep::ArgsType args(q1, q2, length * length, d);
SquaredDistanceStep::run(model.joints[i], args);
res += d;
}
res+=(q1 - q2).tail (robot_->extraConfigSpace ().dimension()).squaredNorm ();
return sqrt (res);
}
} // namespace core
} // namespace hpp
<|endoftext|>
|
<commit_before>/* _______ __ __ __ ______ __ __ _______ __ __
* / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\
* / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
* / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / /
* / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / /
* /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
* \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
*
* Copyright (c) 2004, 2005 darkbits Js_./
* Per Larsson a.k.a finalman _RqZ{a<^_aa
* Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a//
* _Qhm`] _f "'c 1!5m
* Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[
* .)j(] .d_/ '-( P . S
* License: (BSD) <Td/Z <fP"5(\"??"\a. .L
* Redistribution and use in source and _dV>ws?a-?' ._/L #'
* binary forms, with or without )4d[#7r, . ' )d`)[
* modification, are permitted provided _Q-5'5W..j/?' -?!\)cam'
* that the following conditions are met: j<<WP+k/);. _W=j f
* 1. Redistributions of source code must .$%w\/]Q . ."' . mj$
* retain the above copyright notice, ]E.pYY(Q]>. a J@\
* this list of conditions and the j(]1u<sE"L,. . ./^ ]{a
* following disclaimer. 4'_uomm\. )L);-4 (3=
* 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[
* reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m
* this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/
* following disclaimer in the <B!</]C)d_, '(<' .f. =C+m
* documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]'
* provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W"
* 3. Neither the name of Guichan nor the :$we` _! + _/ . j?
* names of its contributors may be used =3)= _f (_yQmWW$#( "
* to endorse or promote products derived - W, sQQQQmZQ#Wwa]..
* from this software without specific (js, \[QQW$QWW#?!V"".
* prior written permission. ]y:.<\.. .
* -]n w/ ' [.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ !
* HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , '
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- %
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'.,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?"
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. .
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _,
* 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.
*/
/*
* For comments regarding functions please see the header file.
*/
#include "guichan/widgets/listbox.hpp"
#include "guichan/basiccontainer.hpp"
#include "guichan/font.hpp"
#include "guichan/graphics.hpp"
#include "guichan/key.hpp"
#include "guichan/listmodel.hpp"
#include "guichan/mouseinput.hpp"
namespace gcn
{
ListBox::ListBox()
{
mSelected = -1;
mListModel = NULL;
mWrappingKeyboardSelection = false;
setWidth(100);
setFocusable(true);
addMouseListener(this);
addKeyListener(this);
}
ListBox::ListBox(ListModel *listModel)
{
mSelected = -1;
mWrappingKeyboardSelection = false;
setWidth(100);
setListModel(listModel);
setFocusable(true);
addMouseListener(this);
addKeyListener(this);
}
void ListBox::draw(Graphics* graphics)
{
graphics->setColor(getBackgroundColor());
graphics->fillRectangle(Rectangle(0, 0, getWidth(), getHeight()));
if (mListModel == NULL)
{
return;
}
graphics->setColor(getForegroundColor());
graphics->setFont(getFont());
int i, fontHeight;
int y = 0;
fontHeight = getFont()->getHeight();
/**
* @todo Check cliprects so we do not have to iterate over elements in the list model
*/
for (i = 0; i < mListModel->getNumberOfElements(); ++i)
{
if (i == mSelected)
{
graphics->drawRectangle(Rectangle(0, y, getWidth(), fontHeight));
}
graphics->drawText(mListModel->getElementAt(i), 1, y);
y += fontHeight;
}
}
void ListBox::drawBorder(Graphics* graphics)
{
Color faceColor = getBaseColor();
Color highlightColor, shadowColor;
int alpha = getBaseColor().a;
int width = getWidth() + getBorderSize() * 2 - 1;
int height = getHeight() + getBorderSize() * 2 - 1;
highlightColor = faceColor + 0x303030;
highlightColor.a = alpha;
shadowColor = faceColor - 0x303030;
shadowColor.a = alpha;
unsigned int i;
for (i = 0; i < getBorderSize(); ++i)
{
graphics->setColor(shadowColor);
graphics->drawLine(i,i, width - i, i);
graphics->drawLine(i,i + 1, i, height - i - 1);
graphics->setColor(highlightColor);
graphics->drawLine(width - i,i + 1, width - i, height - i);
graphics->drawLine(i,height - i, width - i - 1, height - i);
}
}
void ListBox::logic()
{
adjustSize();
}
int ListBox::getSelected()
{
return mSelected;
}
void ListBox::setSelected(int selected)
{
if (mListModel == NULL)
{
mSelected = -1;
}
else
{
if (selected < 0)
{
mSelected = -1;
}
else if (selected >= mListModel->getNumberOfElements())
{
mSelected = mListModel->getNumberOfElements() - 1;
}
else
{
mSelected = selected;
}
BasicContainer *par = getParent();
if (par == NULL)
{
return;
}
Rectangle scroll;
if (mSelected < 0)
{
scroll.y = 0;
}
else
{
scroll.y = getFont()->getHeight() * mSelected;
}
scroll.y = getFont()->getHeight() * mSelected;
scroll.height = getFont()->getHeight();
par->showWidgetPart(this, scroll);
}
}
void ListBox::keyPress(const Key& key)
{
if (key.getValue() == Key::ENTER || key.getValue() == Key::SPACE)
{
generateAction();
}
else if (key.getValue() == Key::UP)
{
setSelected(mSelected - 1);
if (mSelected == -1)
{
if (isWrappingKeyboardSelection())
{
setSelected(getListModel().getNumberOfElements() - 1);
}
else
{
setSelected(0);
}
}
}
else if (key.getValue() == Key::DOWN)
{
if (isWrappingKeyboardSelection()
&& getSelected() == getListModel().getNumberOfElements() - 1)
{
setSelected(0);
}
else
{
setSelected(selected + 1);
}
}
}
void ListBox::mousePress(int x, int y, int button)
{
if (button == MouseInput::LEFT && hasMouse())
{
setSelected(y / getFont()->getHeight());
generateAction();
}
}
void ListBox::setListModel(ListModel *listModel)
{
mSelected = -1;
mListModel = listModel;
adjustSize();
}
ListModel* ListBox::getListModel()
{
return mListModel;
}
void ListBox::adjustSize()
{
if (mListModel != NULL)
{
setHeight(getFont()->getHeight() * mListModel->getNumberOfElements());
}
}
bool isWrappingKeyboardSelection()
{
return mWrappingKeyboardSelection;
}
void setWrappingKeyboardSelection(bool wrapping)
{
mWrappingKeyboardSelection = wrapping;
}
}
<commit_msg>Fixed compilation errors.<commit_after>/* _______ __ __ __ ______ __ __ _______ __ __
* / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\
* / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
* / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / /
* / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / /
* /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
* \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
*
* Copyright (c) 2004, 2005 darkbits Js_./
* Per Larsson a.k.a finalman _RqZ{a<^_aa
* Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a//
* _Qhm`] _f "'c 1!5m
* Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[
* .)j(] .d_/ '-( P . S
* License: (BSD) <Td/Z <fP"5(\"??"\a. .L
* Redistribution and use in source and _dV>ws?a-?' ._/L #'
* binary forms, with or without )4d[#7r, . ' )d`)[
* modification, are permitted provided _Q-5'5W..j/?' -?!\)cam'
* that the following conditions are met: j<<WP+k/);. _W=j f
* 1. Redistributions of source code must .$%w\/]Q . ."' . mj$
* retain the above copyright notice, ]E.pYY(Q]>. a J@\
* this list of conditions and the j(]1u<sE"L,. . ./^ ]{a
* following disclaimer. 4'_uomm\. )L);-4 (3=
* 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[
* reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m
* this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/
* following disclaimer in the <B!</]C)d_, '(<' .f. =C+m
* documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]'
* provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W"
* 3. Neither the name of Guichan nor the :$we` _! + _/ . j?
* names of its contributors may be used =3)= _f (_yQmWW$#( "
* to endorse or promote products derived - W, sQQQQmZQ#Wwa]..
* from this software without specific (js, \[QQW$QWW#?!V"".
* prior written permission. ]y:.<\.. .
* -]n w/ ' [.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ !
* HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , '
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- %
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'.,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?"
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. .
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _,
* 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.
*/
/*
* For comments regarding functions please see the header file.
*/
#include "guichan/widgets/listbox.hpp"
#include "guichan/basiccontainer.hpp"
#include "guichan/font.hpp"
#include "guichan/graphics.hpp"
#include "guichan/key.hpp"
#include "guichan/listmodel.hpp"
#include "guichan/mouseinput.hpp"
namespace gcn
{
ListBox::ListBox()
{
mSelected = -1;
mListModel = NULL;
mWrappingKeyboardSelection = false;
setWidth(100);
setFocusable(true);
addMouseListener(this);
addKeyListener(this);
}
ListBox::ListBox(ListModel *listModel)
{
mSelected = -1;
mWrappingKeyboardSelection = false;
setWidth(100);
setListModel(listModel);
setFocusable(true);
addMouseListener(this);
addKeyListener(this);
}
void ListBox::draw(Graphics* graphics)
{
graphics->setColor(getBackgroundColor());
graphics->fillRectangle(Rectangle(0, 0, getWidth(), getHeight()));
if (mListModel == NULL)
{
return;
}
graphics->setColor(getForegroundColor());
graphics->setFont(getFont());
int i, fontHeight;
int y = 0;
fontHeight = getFont()->getHeight();
/**
* @todo Check cliprects so we do not have to iterate over elements in the list model
*/
for (i = 0; i < mListModel->getNumberOfElements(); ++i)
{
if (i == mSelected)
{
graphics->drawRectangle(Rectangle(0, y, getWidth(), fontHeight));
}
graphics->drawText(mListModel->getElementAt(i), 1, y);
y += fontHeight;
}
}
void ListBox::drawBorder(Graphics* graphics)
{
Color faceColor = getBaseColor();
Color highlightColor, shadowColor;
int alpha = getBaseColor().a;
int width = getWidth() + getBorderSize() * 2 - 1;
int height = getHeight() + getBorderSize() * 2 - 1;
highlightColor = faceColor + 0x303030;
highlightColor.a = alpha;
shadowColor = faceColor - 0x303030;
shadowColor.a = alpha;
unsigned int i;
for (i = 0; i < getBorderSize(); ++i)
{
graphics->setColor(shadowColor);
graphics->drawLine(i,i, width - i, i);
graphics->drawLine(i,i + 1, i, height - i - 1);
graphics->setColor(highlightColor);
graphics->drawLine(width - i,i + 1, width - i, height - i);
graphics->drawLine(i,height - i, width - i - 1, height - i);
}
}
void ListBox::logic()
{
adjustSize();
}
int ListBox::getSelected()
{
return mSelected;
}
void ListBox::setSelected(int selected)
{
if (mListModel == NULL)
{
mSelected = -1;
}
else
{
if (selected < 0)
{
mSelected = -1;
}
else if (selected >= mListModel->getNumberOfElements())
{
mSelected = mListModel->getNumberOfElements() - 1;
}
else
{
mSelected = selected;
}
BasicContainer *par = getParent();
if (par == NULL)
{
return;
}
Rectangle scroll;
if (mSelected < 0)
{
scroll.y = 0;
}
else
{
scroll.y = getFont()->getHeight() * mSelected;
}
scroll.y = getFont()->getHeight() * mSelected;
scroll.height = getFont()->getHeight();
par->showWidgetPart(this, scroll);
}
}
void ListBox::keyPress(const Key& key)
{
if (key.getValue() == Key::ENTER || key.getValue() == Key::SPACE)
{
generateAction();
}
else if (key.getValue() == Key::UP)
{
setSelected(mSelected - 1);
if (mSelected == -1)
{
if (isWrappingKeyboardSelection())
{
setSelected(getListModel()->getNumberOfElements() - 1);
}
else
{
setSelected(0);
}
}
}
else if (key.getValue() == Key::DOWN)
{
if (isWrappingKeyboardSelection()
&& getSelected() == getListModel()->getNumberOfElements() - 1)
{
setSelected(0);
}
else
{
setSelected(getSelected() + 1);
}
}
}
void ListBox::mousePress(int x, int y, int button)
{
if (button == MouseInput::LEFT && hasMouse())
{
setSelected(y / getFont()->getHeight());
generateAction();
}
}
void ListBox::setListModel(ListModel *listModel)
{
mSelected = -1;
mListModel = listModel;
adjustSize();
}
ListModel* ListBox::getListModel()
{
return mListModel;
}
void ListBox::adjustSize()
{
if (mListModel != NULL)
{
setHeight(getFont()->getHeight() * mListModel->getNumberOfElements());
}
}
bool ListBox::isWrappingKeyboardSelection()
{
return mWrappingKeyboardSelection;
}
void ListBox::setWrappingKeyboardSelection(bool wrapping)
{
mWrappingKeyboardSelection = wrapping;
}
}
<|endoftext|>
|
<commit_before>/************************************
* file enc : utf8
* author : wuyanyi09@gmail.com
************************************/
#include "KeyWordExt.h"
namespace CppJieba
{
KeyWordExt::KeyWordExt()
{
}
KeyWordExt::~KeyWordExt()
{
}
bool KeyWordExt::init()
{
return _segment.init();
}
bool KeyWordExt::loadSegDict(const string& filePath)
{
return _segment.loadSegDict(filePath);
}
bool KeyWordExt::loadPriorSubWords(const string& filePath)
{
LogInfo(string_format("loadPriorSubWords(%s) start", filePath.c_str()));
if(!checkFileExist(filePath.c_str()))
{
LogError(string_format("cann't find file[%s].",filePath.c_str()));
return false;
}
if(!_priorSubWords.empty())
{
LogError("_priorSubWords has been initted before");
return false;
}
ifstream infile(filePath.c_str());
string subword;
while(getline(infile, subword))
{
_priorSubWords.push_back(subword);
}
LogInfo(string_format("loadPriorSubWords(%s) end", filePath.c_str()));
infile.close();
return true;
}
bool KeyWordExt::loadStopWords(const string& filePath)
{
LogInfo(string_format("loadStopWords(%s) start", filePath.c_str()));
if(!_stopWords.empty())
{
LogError("_stopWords has been loaded before! ");
return false;
}
if(!checkFileExist(filePath.c_str()))
{
LogError(string_format("cann't find file[%s].",filePath.c_str()));
return false;
}
ifstream ifile(filePath.c_str());
string line;
while(getline(ifile, line))
{
_stopWords.insert(line);
}
LogInfo(string_format("load stopwords[%d] finished.", _stopWords.size()));
return true;
}
bool KeyWordExt::dispose()
{
_segment.dispose();
return true;
}
bool KeyWordExt::_wordInfoCompare(const WordInfo& a, const WordInfo& b)
{
return a.weight > b.weight;
}
bool KeyWordExt::_sortWLIDF(vector<WordInfo>& wordInfos)
{
//size_t wLenSum = 0;
for(uint i = 0; i < wordInfos.size(); i++)
{
wordInfos[i].wLen = gEncoding.getWordLength(wordInfos[i].word);
if(0 == wordInfos[i].wLen)
{
LogFatal("wLen is 0");
return false;
}
//wLenSum += wordInfos[i].wLen;
}
/*
if(0 == wLenSum)
{
LogFatal("wLenSum == 0.");
return false;
}*/
for(uint i = 0; i < wordInfos.size(); i++)
{
WordInfo& wInfo = wordInfos[i];
double logWordFreq = _segment.getWordWeight(wInfo.word);
wInfo.idf = -logWordFreq;
size_t wLen = gEncoding.getWordLength(wInfo.word);
if(0 == wLen)
{
LogFatal("getUtf8WordLen(%s) return 0");
}
wInfo.weight = log(double(wLen + 1)) * wInfo.idf;
}
sort(wordInfos.begin(), wordInfos.end(), _wordInfoCompare);
return true;
}
bool KeyWordExt::_extractTopN(const vector<string>& words, vector<string>& keywords, uint topN)
{
keywords.clear();
vector<WordInfo> wordInfos;
for(uint i = 0; i < words.size(); i++)
{
WordInfo wInfo;
wInfo.word = words[i];
wordInfos.push_back(wInfo);
}
_sortWLIDF(wordInfos);
LogDebug(string_format("calc weight & sorted:%s",joinWordInfos(wordInfos).c_str()));
_prioritizeSubWords(wordInfos);
//LogDebug(string_format("_prioritizeSubWords res:%s", joinWordInfos(wordInfos).c_str()));
//extract TopN
for(uint i = 0; i < topN && i < wordInfos.size(); i++)
{
keywords.push_back(wordInfos[i].word);
}
return true;
}
bool KeyWordExt::extract(const string& title, vector<string>& keywords, uint topN)
{
LogDebug(string_format("title:[%s]",title.c_str()));
bool retFlag;
vector<string> words;
retFlag = _segment.cutDAG(title, words);
if(!retFlag)
{
LogError(string_format("cutDAG(%s) failed.", title.c_str()));
return false;
}
LogDebug(string_format("cutDAG result:[%s]", joinStr(words, ",").c_str()));
retFlag = _filter(words);
if(!retFlag)
{
LogError("_filter failed.");
return false;
}
LogDebug(string_format("_filter res:[%s]", joinStr(words, ",").c_str()));
retFlag = _extractTopN(words, keywords, topN);
if(!retFlag)
{
LogError("_extractTopN failed.");
return false;
}
//LogDebug("_extractTopN finished.");
LogDebug(string_format("ext res:[%s]", joinStr(keywords, ",").c_str()));
return true;
}
bool KeyWordExt::_filter(vector<string>& strs)
{
bool retFlag;
retFlag = _filterDuplicate(strs);
if(!retFlag)
{
LogError("_filterDuplicate failed.");
return false;
}
//LogDebug(string_format("_filterDuplicate res:[%s]", joinStr(strs, ",").c_str()));
retFlag = _filterSingleWord(strs);
if(!retFlag)
{
LogError("_filterSingleWord failed.");
return false;
}
//LogDebug(string_format("_filterSingleWord res:[%s]", joinStr(strs, ",").c_str()));
retFlag = _filterStopWords(strs);
if(!retFlag)
{
LogError("_filterStopWords failed.");
return false;
}
//LogDebug(string_format("_filterStopWords res:[%s]", joinStr(strs, ",").c_str()));
retFlag = _filterSubstr(strs);
if(!retFlag)
{
LogError("_filterSubstr failed.");
return false;
}
//LogDebug(string_format("_filterSubstr res:[%s]", joinStr(strs, ",").c_str()));
return true;
}
bool KeyWordExt::_filterStopWords(vector<string>& strs)
{
if(_stopWords.empty())
{
return true;
}
for(VSI it = strs.begin(); it != strs.end();)
{
if(_stopWords.find(*it) != _stopWords.end())
{
it = strs.erase(it);
}
else
{
it ++;
}
}
return true;
}
bool KeyWordExt::_filterDuplicate(vector<string>& strs)
{
set<string> st;
for(VSI it = strs.begin(); it != strs.end(); )
{
if(st.find(*it) != st.end())
{
it = strs.erase(it);
}
else
{
st.insert(*it);
it++;
}
}
return true;
}
bool KeyWordExt::_filterSingleWord(vector<string>& strs)
{
for(vector<string>::iterator it = strs.begin(); it != strs.end();)
{
// filter single word
if(1 == gEncoding.getWordLength(*it))
{
it = strs.erase(it);
}
else
{
it++;
}
}
return true;
}
bool KeyWordExt::_filterSubstr(vector<string>& strs)
{
vector<string> tmp = strs;
set<string> subs;
for(VSI it = strs.begin(); it != strs.end(); it ++)
{
for(uint j = 0; j < tmp.size(); j++)
{
if(*it != tmp[j] && string::npos != tmp[j].find(*it, 0))
{
subs.insert(*it);
}
}
}
//erase subs from strs
for(VSI it = strs.begin(); it != strs.end(); )
{
if(subs.end() != subs.find(*it))
{
LogDebug(string_format("_filterSubstr filter [%s].", it->c_str()));
it = strs.erase(it);
}
else
{
it ++;
}
}
return true;
}
bool KeyWordExt::_isContainSubWords(const string& word)
{
for(uint i = 0; i < _priorSubWords.size(); i++)
{
if(string::npos != word.find(_priorSubWords[i]))
{
return true;
}
}
return false;
}
bool KeyWordExt::_prioritizeSubWords(vector<WordInfo>& wordInfos)
{
if(2 > wordInfos.size())
{
return true;
}
WordInfo prior;
bool flag = false;
for(vector<WordInfo>::iterator it = wordInfos.begin(); it != wordInfos.end(); )
{
if(_isContainSubWords(it->word))
{
prior = *it;
it = wordInfos.erase(it);
flag = true;
break;
}
else
{
it ++;
}
}
if(flag)
{
wordInfos.insert(wordInfos.begin(), prior);
}
return true;
}
}
#ifdef KEYWORDEXT_UT
using namespace CppJieba;
int main()
{
gEncoding.setEncoding(GBKENC);
KeyWordExt ext;
ext.init();
if(!ext.loadSegDict("../dicts/segdict.gbk.v2.1"))
{
return 1;
}
ext.loadStopWords("stopwords.tmp");
if(!ext.loadPriorSubWords("prior.gbk"))
{
cerr<<"err"<<endl;
return 1;
}
ifstream ifile("testtitle.gbk");
vector<string> res;
string line;
while(getline(ifile, line))
{
cout<<line<<endl;
res.clear();
ext.extract(line, res, 20);
PRINT_VECTOR(res);
}
ext.dispose();
return 0;
}
#endif
<commit_msg>remove debug<commit_after>/************************************
* file enc : utf8
* author : wuyanyi09@gmail.com
************************************/
#include "KeyWordExt.h"
namespace CppJieba
{
KeyWordExt::KeyWordExt()
{
}
KeyWordExt::~KeyWordExt()
{
}
bool KeyWordExt::init()
{
return _segment.init();
}
bool KeyWordExt::loadSegDict(const string& filePath)
{
return _segment.loadSegDict(filePath);
}
bool KeyWordExt::loadPriorSubWords(const string& filePath)
{
LogInfo(string_format("loadPriorSubWords(%s) start", filePath.c_str()));
if(!checkFileExist(filePath.c_str()))
{
LogError(string_format("cann't find file[%s].",filePath.c_str()));
return false;
}
if(!_priorSubWords.empty())
{
LogError("_priorSubWords has been initted before");
return false;
}
ifstream infile(filePath.c_str());
string subword;
while(getline(infile, subword))
{
_priorSubWords.push_back(subword);
}
LogInfo(string_format("loadPriorSubWords(%s) end", filePath.c_str()));
infile.close();
return true;
}
bool KeyWordExt::loadStopWords(const string& filePath)
{
LogInfo(string_format("loadStopWords(%s) start", filePath.c_str()));
if(!_stopWords.empty())
{
LogError("_stopWords has been loaded before! ");
return false;
}
if(!checkFileExist(filePath.c_str()))
{
LogError(string_format("cann't find file[%s].",filePath.c_str()));
return false;
}
ifstream ifile(filePath.c_str());
string line;
while(getline(ifile, line))
{
_stopWords.insert(line);
}
LogInfo(string_format("load stopwords[%d] finished.", _stopWords.size()));
return true;
}
bool KeyWordExt::dispose()
{
_segment.dispose();
return true;
}
bool KeyWordExt::_wordInfoCompare(const WordInfo& a, const WordInfo& b)
{
return a.weight > b.weight;
}
bool KeyWordExt::_sortWLIDF(vector<WordInfo>& wordInfos)
{
//size_t wLenSum = 0;
for(uint i = 0; i < wordInfos.size(); i++)
{
wordInfos[i].wLen = gEncoding.getWordLength(wordInfos[i].word);
if(0 == wordInfos[i].wLen)
{
LogFatal("wLen is 0");
return false;
}
//wLenSum += wordInfos[i].wLen;
}
/*
if(0 == wLenSum)
{
LogFatal("wLenSum == 0.");
return false;
}*/
for(uint i = 0; i < wordInfos.size(); i++)
{
WordInfo& wInfo = wordInfos[i];
double logWordFreq = _segment.getWordWeight(wInfo.word);
wInfo.idf = -logWordFreq;
size_t wLen = gEncoding.getWordLength(wInfo.word);
if(0 == wLen)
{
LogFatal("getUtf8WordLen(%s) return 0");
}
wInfo.weight = log(double(wLen + 1)) * wInfo.idf;
}
sort(wordInfos.begin(), wordInfos.end(), _wordInfoCompare);
return true;
}
bool KeyWordExt::_extractTopN(const vector<string>& words, vector<string>& keywords, uint topN)
{
keywords.clear();
vector<WordInfo> wordInfos;
for(uint i = 0; i < words.size(); i++)
{
WordInfo wInfo;
wInfo.word = words[i];
wordInfos.push_back(wInfo);
}
_sortWLIDF(wordInfos);
//LogDebug(string_format("calc weight & sorted:%s",joinWordInfos(wordInfos).c_str()));
_prioritizeSubWords(wordInfos);
//LogDebug(string_format("_prioritizeSubWords res:%s", joinWordInfos(wordInfos).c_str()));
//extract TopN
for(uint i = 0; i < topN && i < wordInfos.size(); i++)
{
keywords.push_back(wordInfos[i].word);
}
return true;
}
bool KeyWordExt::extract(const string& title, vector<string>& keywords, uint topN)
{
//LogDebug(string_format("title:[%s]",title.c_str()));
bool retFlag;
vector<string> words;
retFlag = _segment.cutDAG(title, words);
if(!retFlag)
{
LogError(string_format("cutDAG(%s) failed.", title.c_str()));
return false;
}
//LogDebug(string_format("cutDAG result:[%s]", joinStr(words, ",").c_str()));
retFlag = _filter(words);
if(!retFlag)
{
LogError("_filter failed.");
return false;
}
//LogDebug(string_format("_filter res:[%s]", joinStr(words, ",").c_str()));
retFlag = _extractTopN(words, keywords, topN);
if(!retFlag)
{
LogError("_extractTopN failed.");
return false;
}
//LogDebug("_extractTopN finished.");
//LogDebug(string_format("ext res:[%s]", joinStr(keywords, ",").c_str()));
return true;
}
bool KeyWordExt::_filter(vector<string>& strs)
{
bool retFlag;
retFlag = _filterDuplicate(strs);
if(!retFlag)
{
LogError("_filterDuplicate failed.");
return false;
}
//LogDebug(string_format("_filterDuplicate res:[%s]", joinStr(strs, ",").c_str()));
retFlag = _filterSingleWord(strs);
if(!retFlag)
{
LogError("_filterSingleWord failed.");
return false;
}
//LogDebug(string_format("_filterSingleWord res:[%s]", joinStr(strs, ",").c_str()));
retFlag = _filterStopWords(strs);
if(!retFlag)
{
LogError("_filterStopWords failed.");
return false;
}
//LogDebug(string_format("_filterStopWords res:[%s]", joinStr(strs, ",").c_str()));
retFlag = _filterSubstr(strs);
if(!retFlag)
{
LogError("_filterSubstr failed.");
return false;
}
//LogDebug(string_format("_filterSubstr res:[%s]", joinStr(strs, ",").c_str()));
return true;
}
bool KeyWordExt::_filterStopWords(vector<string>& strs)
{
if(_stopWords.empty())
{
return true;
}
for(VSI it = strs.begin(); it != strs.end();)
{
if(_stopWords.find(*it) != _stopWords.end())
{
it = strs.erase(it);
}
else
{
it ++;
}
}
return true;
}
bool KeyWordExt::_filterDuplicate(vector<string>& strs)
{
set<string> st;
for(VSI it = strs.begin(); it != strs.end(); )
{
if(st.find(*it) != st.end())
{
it = strs.erase(it);
}
else
{
st.insert(*it);
it++;
}
}
return true;
}
bool KeyWordExt::_filterSingleWord(vector<string>& strs)
{
for(vector<string>::iterator it = strs.begin(); it != strs.end();)
{
// filter single word
if(1 == gEncoding.getWordLength(*it))
{
it = strs.erase(it);
}
else
{
it++;
}
}
return true;
}
bool KeyWordExt::_filterSubstr(vector<string>& strs)
{
vector<string> tmp = strs;
set<string> subs;
for(VSI it = strs.begin(); it != strs.end(); it ++)
{
for(uint j = 0; j < tmp.size(); j++)
{
if(*it != tmp[j] && string::npos != tmp[j].find(*it, 0))
{
subs.insert(*it);
}
}
}
//erase subs from strs
for(VSI it = strs.begin(); it != strs.end(); )
{
if(subs.end() != subs.find(*it))
{
//LogDebug(string_format("_filterSubstr filter [%s].", it->c_str()));
it = strs.erase(it);
}
else
{
it ++;
}
}
return true;
}
bool KeyWordExt::_isContainSubWords(const string& word)
{
for(uint i = 0; i < _priorSubWords.size(); i++)
{
if(string::npos != word.find(_priorSubWords[i]))
{
return true;
}
}
return false;
}
bool KeyWordExt::_prioritizeSubWords(vector<WordInfo>& wordInfos)
{
if(2 > wordInfos.size())
{
return true;
}
WordInfo prior;
bool flag = false;
for(vector<WordInfo>::iterator it = wordInfos.begin(); it != wordInfos.end(); )
{
if(_isContainSubWords(it->word))
{
prior = *it;
it = wordInfos.erase(it);
flag = true;
break;
}
else
{
it ++;
}
}
if(flag)
{
wordInfos.insert(wordInfos.begin(), prior);
}
return true;
}
}
#ifdef KEYWORDEXT_UT
using namespace CppJieba;
int main()
{
gEncoding.setEncoding(GBKENC);
KeyWordExt ext;
ext.init();
if(!ext.loadSegDict("../dicts/segdict.gbk.v2.1"))
{
return 1;
}
ext.loadStopWords("stopwords.tmp");
if(!ext.loadPriorSubWords("prior.gbk"))
{
cerr<<"err"<<endl;
return 1;
}
ifstream ifile("testtitle.gbk");
vector<string> res;
string line;
while(getline(ifile, line))
{
cout<<line<<endl;
res.clear();
ext.extract(line, res, 20);
PRINT_VECTOR(res);
}
ext.dispose();
return 0;
}
#endif
<|endoftext|>
|
<commit_before>/*
* This file is part of Poedit (http://poedit.net)
*
* Copyright (C) 2014-2015 Vaclav Slavik
*
* 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 "main_toolbar.h"
#include <wx/intl.h>
#include <wx/toolbar.h>
#include <wx/xrc/xmlres.h>
class WXMainToolbar : public MainToolbar
{
public:
WXMainToolbar(wxFrame *parent)
{
m_tb = wxXmlResource::Get()->LoadToolBar(parent, "toolbar");
m_idFuzzy = XRCID("menu_fuzzy");
m_idUpdate = XRCID("toolbar_update");
}
bool IsFuzzy() const override
{
return m_tb->GetToolState(m_idFuzzy);
}
void SetFuzzy(bool on) override
{
m_tb->ToggleTool(m_idFuzzy, on);
}
void EnableSyncWithCrowdin(bool on) override
{
auto tool = m_tb->FindById(m_idUpdate);
if (on)
{
tool->SetLabel(_("Sync"));
tool->SetShortHelp(_("Synchronize the translation with Crowdin."));
m_tb->SetToolNormalBitmap(m_idUpdate, wxArtProvider::GetBitmap("poedit-sync"));
}
else
{
tool->SetLabel(_("Update"));
tool->SetShortHelp(_("Update catalog - synchronize it with sources"));
m_tb->SetToolNormalBitmap(m_idUpdate, wxArtProvider::GetBitmap("poedit-update"));
}
}
private:
wxToolBar *m_tb;
int m_idFuzzy, m_idUpdate;
};
std::unique_ptr<MainToolbar> MainToolbar::CreateWX(wxFrame *parent)
{
return std::unique_ptr<MainToolbar>(new WXMainToolbar(parent));
}
std::unique_ptr<MainToolbar> MainToolbar::Create(wxFrame *parent)
{
return CreateWX(parent);
}
<commit_msg>Remove period from tooltip text<commit_after>/*
* This file is part of Poedit (http://poedit.net)
*
* Copyright (C) 2014-2015 Vaclav Slavik
*
* 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 "main_toolbar.h"
#include <wx/intl.h>
#include <wx/toolbar.h>
#include <wx/xrc/xmlres.h>
class WXMainToolbar : public MainToolbar
{
public:
WXMainToolbar(wxFrame *parent)
{
m_tb = wxXmlResource::Get()->LoadToolBar(parent, "toolbar");
m_idFuzzy = XRCID("menu_fuzzy");
m_idUpdate = XRCID("toolbar_update");
}
bool IsFuzzy() const override
{
return m_tb->GetToolState(m_idFuzzy);
}
void SetFuzzy(bool on) override
{
m_tb->ToggleTool(m_idFuzzy, on);
}
void EnableSyncWithCrowdin(bool on) override
{
auto tool = m_tb->FindById(m_idUpdate);
if (on)
{
tool->SetLabel(_("Sync"));
tool->SetShortHelp(_("Synchronize the translation with Crowdin"));
m_tb->SetToolNormalBitmap(m_idUpdate, wxArtProvider::GetBitmap("poedit-sync"));
}
else
{
tool->SetLabel(_("Update"));
tool->SetShortHelp(_("Update catalog - synchronize it with sources"));
m_tb->SetToolNormalBitmap(m_idUpdate, wxArtProvider::GetBitmap("poedit-update"));
}
}
private:
wxToolBar *m_tb;
int m_idFuzzy, m_idUpdate;
};
std::unique_ptr<MainToolbar> MainToolbar::CreateWX(wxFrame *parent)
{
return std::unique_ptr<MainToolbar>(new WXMainToolbar(parent));
}
std::unique_ptr<MainToolbar> MainToolbar::Create(wxFrame *parent)
{
return CreateWX(parent);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-2008 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/autofill_manager.h"
#include "base/string_util.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/web_contents.h"
#include "chrome/common/pref_names.h"
AutofillManager::AutofillManager(WebContents* web_contents) :
web_contents_(web_contents),
pending_query_handle_(0),
node_id_(0),
request_id_(0) {
form_autofill_enabled_.Init(prefs::kFormAutofillEnabled,
profile()->GetPrefs(), NULL);
}
AutofillManager::~AutofillManager() {
CancelPendingQuery();
}
void AutofillManager::CancelPendingQuery() {
if (pending_query_handle_) {
WebDataService* web_data_service =
profile()->GetWebDataService(Profile::EXPLICIT_ACCESS);
if (!web_data_service) {
NOTREACHED();
return;
}
web_data_service->CancelRequest(pending_query_handle_);
}
pending_query_handle_ = 0;
}
Profile* AutofillManager::profile() {
return web_contents_->profile();
}
void AutofillManager::AutofillFormSubmitted(const AutofillForm& form) {
StoreFormEntriesInWebDatabase(form);
}
void AutofillManager::FetchValuesForName(const std::wstring& name,
const std::wstring& prefix,
int limit,
int64 node_id,
int request_id) {
if (!*form_autofill_enabled_)
return;
WebDataService* web_data_service =
profile()->GetWebDataService(Profile::EXPLICIT_ACCESS);
if (!web_data_service) {
NOTREACHED();
return;
}
CancelPendingQuery();
node_id_ = node_id;
request_id_ = request_id;
pending_query_handle_ = web_data_service->
GetFormValuesForElementName(name, prefix, limit, this);
}
void AutofillManager::OnWebDataServiceRequestDone(WebDataService::Handle h,
const WDTypedResult* result) {
DCHECK(pending_query_handle_);
pending_query_handle_ = 0;
if (!*form_autofill_enabled_)
return;
DCHECK(result);
if (!result)
return;
switch (result->GetType()) {
case AUTOFILL_VALUE_RESULT: {
RenderViewHost* host = web_contents_->render_view_host();
if (!host)
return;
const WDResult<std::vector<std::wstring> >* r =
static_cast<const WDResult<std::vector<std::wstring> >*>(result);
std::vector<std::wstring> suggestions = r->GetValue();
host->AutofillSuggestionsReturned(suggestions, node_id_, request_id_, -1);
break;
}
default:
NOTREACHED();
break;
}
}
void AutofillManager::StoreFormEntriesInWebDatabase(
const AutofillForm& form) {
if (!*form_autofill_enabled_)
return;
if (profile()->IsOffTheRecord())
return;
profile()->GetWebDataService(Profile::EXPLICIT_ACCESS)->
AddAutofillFormElements(form.elements);
}
<commit_msg>NO CODE CHANGE. Fix EOL in autofill_manager.cc.<commit_after>// Copyright (c) 2006-2008 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/autofill_manager.h"
#include "base/string_util.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/web_contents.h"
#include "chrome/common/pref_names.h"
AutofillManager::AutofillManager(WebContents* web_contents) :
web_contents_(web_contents),
pending_query_handle_(0),
node_id_(0),
request_id_(0) {
form_autofill_enabled_.Init(prefs::kFormAutofillEnabled,
profile()->GetPrefs(), NULL);
}
AutofillManager::~AutofillManager() {
CancelPendingQuery();
}
void AutofillManager::CancelPendingQuery() {
if (pending_query_handle_) {
WebDataService* web_data_service =
profile()->GetWebDataService(Profile::EXPLICIT_ACCESS);
if (!web_data_service) {
NOTREACHED();
return;
}
web_data_service->CancelRequest(pending_query_handle_);
}
pending_query_handle_ = 0;
}
Profile* AutofillManager::profile() {
return web_contents_->profile();
}
void AutofillManager::AutofillFormSubmitted(const AutofillForm& form) {
StoreFormEntriesInWebDatabase(form);
}
void AutofillManager::FetchValuesForName(const std::wstring& name,
const std::wstring& prefix,
int limit,
int64 node_id,
int request_id) {
if (!*form_autofill_enabled_)
return;
WebDataService* web_data_service =
profile()->GetWebDataService(Profile::EXPLICIT_ACCESS);
if (!web_data_service) {
NOTREACHED();
return;
}
CancelPendingQuery();
node_id_ = node_id;
request_id_ = request_id;
pending_query_handle_ = web_data_service->
GetFormValuesForElementName(name, prefix, limit, this);
}
void AutofillManager::OnWebDataServiceRequestDone(WebDataService::Handle h,
const WDTypedResult* result) {
DCHECK(pending_query_handle_);
pending_query_handle_ = 0;
if (!*form_autofill_enabled_)
return;
DCHECK(result);
if (!result)
return;
switch (result->GetType()) {
case AUTOFILL_VALUE_RESULT: {
RenderViewHost* host = web_contents_->render_view_host();
if (!host)
return;
const WDResult<std::vector<std::wstring> >* r =
static_cast<const WDResult<std::vector<std::wstring> >*>(result);
std::vector<std::wstring> suggestions = r->GetValue();
host->AutofillSuggestionsReturned(suggestions, node_id_, request_id_, -1);
break;
}
default:
NOTREACHED();
break;
}
}
void AutofillManager::StoreFormEntriesInWebDatabase(
const AutofillForm& form) {
if (!*form_autofill_enabled_)
return;
if (profile()->IsOffTheRecord())
return;
profile()->GetWebDataService(Profile::EXPLICIT_ACCESS)->
AddAutofillFormElements(form.elements);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/string_util.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "chrome/browser/net/url_request_failed_dns_job.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "net/url_request/url_request_unittest.h"
class ErrorPageTest : public UITest {
protected:
bool WaitForTitleMatching(const std::wstring& title) {
for (int i = 0; i < 100; ++i) {
if (GetActiveTabTitle() == title)
return true;
PlatformThread::Sleep(sleep_timeout_ms() / 10);
}
return false;
}
bool WaitForTitleContaining(const std::string& title_substring) {
for (int i = 0; i < 100; ++i) {
std::wstring title = GetActiveTabTitle();
if (title.find(UTF8ToWide(title_substring)) != std::wstring::npos)
return true;
PlatformThread::Sleep(sleep_timeout_ms() / 10);
}
return false;
}
};
TEST_F(ErrorPageTest, DNSError_Basic) {
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleContaining(test_url.host()));
}
TEST_F(ErrorPageTest, DNSError_GoBack1) {
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(L"title2.html"));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleContaining(test_url.host()));
GetActiveTab()->GoBack();
EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
TEST_F(ErrorPageTest, DNSError_GoBack2) {
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(L"title2.html"));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleContaining(test_url.host()));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(L"title3.html"));
// The first navigation should fail, and the second one should be the error
// page.
GetActiveTab()->GoBackBlockUntilNavigationsComplete(2);
EXPECT_TRUE(WaitForTitleContaining(test_url.host()));
GetActiveTab()->GoBack();
EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
TEST_F(ErrorPageTest, DNSError_GoBack2AndForward) {
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(L"title2.html"));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleContaining(test_url.host()));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(L"title3.html"));
// The first navigation should fail, and the second one should be the error
// page.
GetActiveTab()->GoBackBlockUntilNavigationsComplete(2);
EXPECT_TRUE(WaitForTitleContaining(test_url.host()));
GetActiveTab()->GoBack();
// The first navigation should fail, and the second one should be the error
// page.
GetActiveTab()->GoForwardBlockUntilNavigationsComplete(2);
EXPECT_TRUE(WaitForTitleContaining(test_url.host()));
}
TEST_F(ErrorPageTest, DNSError_GoBack2Forward2) {
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(L"title3.html"));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleContaining(test_url.host()));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(L"title2.html"));
// The first navigation should fail, and the second one should be the error
// page.
GetActiveTab()->GoBackBlockUntilNavigationsComplete(2);
EXPECT_TRUE(WaitForTitleContaining(test_url.host()));
GetActiveTab()->GoBack();
// The first navigation should fail, and the second one should be the error
// page.
GetActiveTab()->GoForwardBlockUntilNavigationsComplete(2);
EXPECT_TRUE(WaitForTitleContaining(test_url.host()));
GetActiveTab()->GoForward();
EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
TEST_F(ErrorPageTest, IFrameDNSError_Basic) {
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(L"iframe_dns_error.html"));
EXPECT_TRUE(WaitForTitleMatching(L"Blah"));
}
TEST_F(ErrorPageTest, IFrameDNSError_GoBack) {
// Test that a DNS error occuring in an iframe does not result in an
// additional session history entry.
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(L"title2.html"));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(L"iframe_dns_error.html"));
GetActiveTab()->GoBack();
EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
TEST_F(ErrorPageTest, IFrameDNSError_GoBackAndForward) {
// Test that a DNS error occuring in an iframe does not result in an
// additional session history entry.
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(L"title2.html"));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(L"iframe_dns_error.html"));
GetActiveTab()->GoBack();
GetActiveTab()->GoForward();
EXPECT_TRUE(WaitForTitleMatching(L"Blah"));
}
TEST_F(ErrorPageTest, IFrame404) {
// iframes that have 404 pages should not trigger an alternate error page.
// In this test, the iframe sets the title of the parent page to "SUCCESS"
// when the iframe loads. If the iframe fails to load (because an alternate
// error page loads instead), then the title will remain as "FAIL".
scoped_refptr<HTTPTestServer> server =
HTTPTestServer::CreateServer(L"chrome/test/data", NULL);
ASSERT_TRUE(NULL != server.get());
GURL test_url = server->TestServerPage("files/iframe404.html");
NavigateToURL(test_url);
EXPECT_TRUE(WaitForTitleMatching(L"SUCCESS"));
}
TEST_F(ErrorPageTest, Page404) {
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(L"title2.html"));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(
URLRequestMockHTTPJob::GetMockUrl(L"page404.html"), 2);
EXPECT_TRUE(WaitForTitleContaining("page404.html"));
}
TEST_F(ErrorPageTest, Page404_GoBack) {
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(L"title2.html"));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(
URLRequestMockHTTPJob::GetMockUrl(L"page404.html"), 2);
EXPECT_TRUE(WaitForTitleContaining("page404.html"));
GetActiveTab()->GoBack();
EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
<commit_msg>Get more info in the logs when ErrorPageTest fails.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/string_util.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "chrome/browser/net/url_request_failed_dns_job.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "net/url_request/url_request_unittest.h"
class ErrorPageTest : public UITest {
protected:
bool WaitForTitleMatching(const std::wstring& title) {
for (int i = 0; i < 100; ++i) {
if (GetActiveTabTitle() == title)
return true;
PlatformThread::Sleep(sleep_timeout_ms() / 10);
}
EXPECT_EQ(title, GetActiveTabTitle());
return false;
}
bool WaitForTitleContaining(const std::string& title_substring) {
for (int i = 0; i < 100; ++i) {
std::wstring title = GetActiveTabTitle();
if (title.find(UTF8ToWide(title_substring)) != std::wstring::npos)
return true;
PlatformThread::Sleep(sleep_timeout_ms() / 10);
}
LOG(ERROR) << "Could not find " << title_substring << " in "
<< GetActiveTabTitle();
return false;
}
};
TEST_F(ErrorPageTest, DNSError_Basic) {
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleContaining(test_url.host()));
}
TEST_F(ErrorPageTest, DNSError_GoBack1) {
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(L"title2.html"));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleContaining(test_url.host()));
GetActiveTab()->GoBack();
EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
TEST_F(ErrorPageTest, DNSError_GoBack2) {
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(L"title2.html"));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleContaining(test_url.host()));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(L"title3.html"));
// The first navigation should fail, and the second one should be the error
// page.
GetActiveTab()->GoBackBlockUntilNavigationsComplete(2);
EXPECT_TRUE(WaitForTitleContaining(test_url.host()));
GetActiveTab()->GoBack();
EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
TEST_F(ErrorPageTest, DNSError_GoBack2AndForward) {
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(L"title2.html"));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleContaining(test_url.host()));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(L"title3.html"));
// The first navigation should fail, and the second one should be the error
// page.
GetActiveTab()->GoBackBlockUntilNavigationsComplete(2);
EXPECT_TRUE(WaitForTitleContaining(test_url.host()));
GetActiveTab()->GoBack();
// The first navigation should fail, and the second one should be the error
// page.
GetActiveTab()->GoForwardBlockUntilNavigationsComplete(2);
EXPECT_TRUE(WaitForTitleContaining(test_url.host()));
}
TEST_F(ErrorPageTest, DNSError_GoBack2Forward2) {
// Test that a DNS error occuring in the main frame does not result in an
// additional session history entry.
GURL test_url(URLRequestFailedDnsJob::kTestUrl);
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(L"title3.html"));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(test_url, 2);
EXPECT_TRUE(WaitForTitleContaining(test_url.host()));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(L"title2.html"));
// The first navigation should fail, and the second one should be the error
// page.
GetActiveTab()->GoBackBlockUntilNavigationsComplete(2);
EXPECT_TRUE(WaitForTitleContaining(test_url.host()));
GetActiveTab()->GoBack();
// The first navigation should fail, and the second one should be the error
// page.
GetActiveTab()->GoForwardBlockUntilNavigationsComplete(2);
EXPECT_TRUE(WaitForTitleContaining(test_url.host()));
GetActiveTab()->GoForward();
EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
TEST_F(ErrorPageTest, IFrameDNSError_Basic) {
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(L"iframe_dns_error.html"));
EXPECT_TRUE(WaitForTitleMatching(L"Blah"));
}
TEST_F(ErrorPageTest, IFrameDNSError_GoBack) {
// Test that a DNS error occuring in an iframe does not result in an
// additional session history entry.
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(L"title2.html"));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(L"iframe_dns_error.html"));
GetActiveTab()->GoBack();
EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
TEST_F(ErrorPageTest, IFrameDNSError_GoBackAndForward) {
// Test that a DNS error occuring in an iframe does not result in an
// additional session history entry.
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(L"title2.html"));
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(L"iframe_dns_error.html"));
GetActiveTab()->GoBack();
GetActiveTab()->GoForward();
EXPECT_TRUE(WaitForTitleMatching(L"Blah"));
}
TEST_F(ErrorPageTest, IFrame404) {
// iframes that have 404 pages should not trigger an alternate error page.
// In this test, the iframe sets the title of the parent page to "SUCCESS"
// when the iframe loads. If the iframe fails to load (because an alternate
// error page loads instead), then the title will remain as "FAIL".
scoped_refptr<HTTPTestServer> server =
HTTPTestServer::CreateServer(L"chrome/test/data", NULL);
ASSERT_TRUE(NULL != server.get());
GURL test_url = server->TestServerPage("files/iframe404.html");
NavigateToURL(test_url);
EXPECT_TRUE(WaitForTitleMatching(L"SUCCESS"));
}
TEST_F(ErrorPageTest, Page404) {
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(L"title2.html"));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(
URLRequestMockHTTPJob::GetMockUrl(L"page404.html"), 2);
EXPECT_TRUE(WaitForTitleContaining("page404.html"));
}
TEST_F(ErrorPageTest, Page404_GoBack) {
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(L"title2.html"));
// The first navigation should fail, and the second one should be the error
// page.
NavigateToURLBlockUntilNavigationsComplete(
URLRequestMockHTTPJob::GetMockUrl(L"page404.html"), 2);
EXPECT_TRUE(WaitForTitleContaining("page404.html"));
GetActiveTab()->GoBack();
EXPECT_TRUE(WaitForTitleMatching(L"Title Of Awesomeness"));
}
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <sys/time.h>
#include <cassert>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/Xutil.h>
#include <FWContextBase.h>
#include <FWPlatformBase.h>
#include <EventLoop.h>
#include <CurlClient.h>
#include <ContextCairo.h>
#include <iostream>
using namespace std;
bool XNextEventTimed(Display * dsp, XEvent * event_return, struct timeval * tv) {
// optimization
if (tv == NULL) {
XNextEvent(dsp, event_return);
return True;
}
// the real deal
if (XPending(dsp) == 0) {
int fd = ConnectionNumber(dsp);
cerr << "nothing pending, fd = " << fd << "\n";
fd_set readset;
FD_ZERO(&readset);
FD_SET(fd, &readset);
int r = select(fd+1, &readset, NULL, NULL, tv);
if (r == -1) {
cerr << "select failed\n";
return false;
} else if (r == 0) {
cerr << "nothing to select\n";
return false;
} else {
cerr << "getting event (r = " << r << ")\n";
if (XPending(dsp)) {
XNextEvent(dsp, event_return);
return true;
} else {
return false;
}
}
} else {
cerr << "pending\n";
XNextEvent(dsp, event_return);
return true;
}
}
class PlatformX11 : public FWPlatformBase {
public:
PlatformX11() : FWPlatformBase(1.0f,
// "#version 300 es",
"#version 100",
true) { }
double getTime() const override {
struct timeval tv;
struct timezone tz;
int r = gettimeofday(&tv, &tz);
double t = 0;
if (r == 0) {
t = (double)tv.tv_sec + tv.tv_usec / 1000000.0;
}
return t;
}
void showMessageBox(const string&, const string&) {
}
void postNotification(const string&, const string&) {
}
string getLocalFilename(const char * fn, FileType type) {
string s = "android_projects/assets/";
return s + fn;
}
std::shared_ptr<HTTPClientFactory> createHTTPClientFactory() const {
return std::make_shared<CurlClientFactory>();
}
int showActionSheet(const FWRect&, const FWActionSheet&) {
return 0;
}
bool createWindow(FWContextBase * context, const char* title) override {
Window root;
XSetWindowAttributes swa;
XSetWindowAttributes xattr;
Atom wm_state;
XWMHints hints;
XEvent xev;
EGLConfig ecfg;
EGLint num_config;
Window win;
/*
* X11 native display initialization
*/
x_display = XOpenDisplay(NULL);
if (x_display == NULL) {
return false;
}
root = DefaultRootWindow(x_display);
// esContext->getActualWidth(), esContext->getActualHeight()
int width = 800;
int height = 600;
swa.event_mask = ExposureMask | PointerMotionMask | KeyPressMask | ButtonPressMask | ButtonReleaseMask | StructureNotifyMask;
win = XCreateWindow(
x_display, root,
0, 0, width, height, 0,
CopyFromParent, InputOutput,
CopyFromParent, CWEventMask,
&swa );
xattr.override_redirect = 0;
XChangeWindowAttributes ( x_display, win, CWOverrideRedirect, &xattr );
XSelectInput(x_display, win,
ExposureMask | KeyPressMask | KeyReleaseMask | PointerMotionMask |
ButtonPressMask | ButtonReleaseMask | StructureNotifyMask
);
hints.input = 1;
hints.flags = InputHint;
XSetWMHints(x_display, win, &hints);
// make the window visible on the screen
XMapWindow (x_display, win);
XStoreName (x_display, win, title);
// get identifiers for the provided atom name strings
wm_state = XInternAtom (x_display, "_NET_WM_STATE", 0);
memset ( &xev, 0, sizeof(xev) );
xev.type = ClientMessage;
xev.xclient.window = win;
xev.xclient.message_type = wm_state;
xev.xclient.format = 32;
xev.xclient.data.l[0] = 1;
xev.xclient.data.l[1] = 0;
XSendEvent (
x_display,
DefaultRootWindow ( x_display ),
0,
SubstructureNotifyMask,
&xev );
eglNativeWindow = (EGLNativeWindowType) win;
eglNativeDisplay = (EGLNativeDisplayType) x_display;
cerr << "native display = " << x_display << endl;
XFlush(x_display);
return true;
}
std::shared_ptr<canvas::ContextFactory> createContextFactory() const {
return std::shared_ptr<canvas::ContextFactory>(new canvas::CairoContextFactory);
}
std::shared_ptr<EventLoop> createEventLoop() override;
void showMessageBox(const std::string & message) {
}
std::string showTextEntryDialog(const std::string & message) {
return "";
}
void postNotification(const std::string & message) {
}
void launchBrowser(const std::string & input_url) {
}
std::string getBundleFilename(const char * filename) {
string s = "android_project/assets/";
return s + filename;
}
void storeValue(const std::string & key, const std::string & value) {
}
std::string loadValue(const std::string & key) {
return "";
}
void swapBuffers() {
eglSwapBuffers(eglDisplay, eglSurface);
}
private:
// X11 related local variables
Display * x_display = NULL;
};
class PlatformX11;
class EventLoopX11 : public EventLoop {
public:
EventLoopX11( Display * _x_display,
PlatformX11 * _platform,
FWContextBase * _application
)
: EventLoop(_application), x_display(_x_display), platform(_platform) { }
void readEvents() {
XEvent xev;
cerr << "read pending\n";
while ( XPending(x_display) ) {
XNextEvent(x_display, &xev);
handleEvent(xev);
}
if (doKeepRunning()) {
sendEvents();
}
if (doKeepRunning()) {
cerr << "read all\n";
timeval tv = { 1, 0 }; // 1000000 / 50 };
if (XNextEventTimed(x_display, &xev, &tv)) {
handleEvent(xev);
sendEvents();
}
}
}
void run() override {
struct timeval t1, t2;
struct timezone tz;
float deltatime;
gettimeofday ( &t1 , &tz );
while (doKeepRunning()) {
readEvents();
getApplication()->loadEvents();
gettimeofday(&t2, &tz);
deltatime = (float)(t2.tv_sec - t1.tv_sec + (t2.tv_usec - t1.tv_usec) * 1e-6);
t1 = t2;
if (getApplication()->onUpdate(deltatime)) {
getApplication()->onDraw();
platform->swapBuffers();
}
}
}
protected:
void sendEvents() {
if (display_width && display_height &&
(display_width != getApplication()->getActualWidth() ||
display_height != getApplication()->getActualHeight())) {
getApplication()->onResize(display_width, display_height, display_width, display_height);
}
}
void handleEvent(XEvent & xev) {
KeySym key;
char text;
switch (xev.type) {
case KeyPress:
if (XLookupString(&xev.xkey, &text, 1, &key, 0) == 1) {
getApplication()->onKeyPress(text, getPlatform()->getTime(), 0, 0);
}
break;
case DestroyNotify:
stop();
break;
case MotionNotify:
// getApplication().onMouseMove(xev.xmotion.x, xev.xmotion.y);
if (button_pressed) {
getApplication()->touchesMoved(xev.xmotion.x, xev.xmotion.y, getPlatform()->getTime(), 0);
}
mouse_x = xev.xmotion.x;
mouse_y = xev.xmotion.y;
break;
case ButtonPress:
// getApplication().onMouseDown(xev.xbutton.button, 0, 0);
getApplication()->touchesBegin(mouse_x, mouse_y, getPlatform()->getTime(), 0);
button_pressed = true;
break;
case ButtonRelease:
// getApplication().onMouseUp(xev.xbutton.button, 0, 0);
getApplication()->touchesEnded(mouse_x, mouse_y, getPlatform()->getTime(), 0);
button_pressed = false;
break;
case ConfigureNotify:
{
XConfigureEvent xce = xev.xconfigure;
display_width = xce.width;
display_height = xce.height;
}
break;
}
}
PlatformX11 * getPlatform() { return platform; }
private:
Display * x_display;
PlatformX11 * platform;
int display_width = 0, display_height = 0;
bool button_pressed = false;
int mouse_x = 0, mouse_y = 0;
};
std::shared_ptr<EventLoop>
PlatformX11::createEventLoop() {
return std::make_shared<EventLoopX11>(x_display, this, &(getApplication()));
}
///
// Global extern. The application must declare this function
// that runs the application.
//
extern void applicationMain(FWPlatformBase * platform);
///
// main()
//
// Main entrypoint for application
//
int main(int argc, char *argv[]) {
PlatformX11 platform;
cerr << "starting\n";
applicationMain(&platform);
// platform.createWindow(&(platform.getApplication()), "App");
platform.createContext(&(platform.getApplication()), "App", 800, 600);
platform.getApplication().onCmdLine(argc, argv);
platform.getApplication().Init();
auto eventloop = platform.createEventLoop();
eventloop->run();
platform.getApplication().onShutdown();
return 0;
}
<commit_msg>remove debugs, fix asset directory, temporarily multiply time by 1000<commit_after>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <sys/time.h>
#include <cassert>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/Xutil.h>
#include <FWContextBase.h>
#include <FWPlatformBase.h>
#include <EventLoop.h>
#include <CurlClient.h>
#include <ContextCairo.h>
#include <iostream>
using namespace std;
bool XNextEventTimed(Display * dsp, XEvent * event_return, struct timeval * tv) {
// optimization
if (tv == NULL) {
XNextEvent(dsp, event_return);
return True;
}
// the real deal
if (XPending(dsp) == 0) {
int fd = ConnectionNumber(dsp);
// cerr << "nothing pending, fd = " << fd << "\n";
fd_set readset;
FD_ZERO(&readset);
FD_SET(fd, &readset);
int r = select(fd+1, &readset, NULL, NULL, tv);
if (r == -1) {
cerr << "select failed\n";
return false;
} else if (r == 0) {
cerr << "nothing to select\n";
return false;
} else {
// cerr << "getting event (r = " << r << ")\n";
if (XPending(dsp)) {
XNextEvent(dsp, event_return);
return true;
} else {
return false;
}
}
} else {
// cerr << "pending\n";
XNextEvent(dsp, event_return);
return true;
}
}
class PlatformX11 : public FWPlatformBase {
public:
PlatformX11() : FWPlatformBase(1.0f,
// "#version 300 es",
"#version 100",
true) { }
double getTime() const override {
struct timeval tv;
struct timezone tz;
int r = gettimeofday(&tv, &tz);
double t = 0;
if (r == 0) {
t = (double)tv.tv_sec + tv.tv_usec / 1000000.0;
}
return t;
}
void showMessageBox(const string&, const string&) {
}
void postNotification(const string&, const string&) {
}
string getLocalFilename(const char * fn, FileType type) {
string s = "android_projects/assets/";
return s + fn;
}
std::shared_ptr<HTTPClientFactory> createHTTPClientFactory() const {
return std::make_shared<CurlClientFactory>();
}
int showActionSheet(const FWRect&, const FWActionSheet&) {
return 0;
}
bool createWindow(FWContextBase * context, const char* title) override {
Window root;
XSetWindowAttributes swa;
XSetWindowAttributes xattr;
Atom wm_state;
XWMHints hints;
XEvent xev;
EGLConfig ecfg;
EGLint num_config;
Window win;
/*
* X11 native display initialization
*/
x_display = XOpenDisplay(NULL);
if (x_display == NULL) {
return false;
}
root = DefaultRootWindow(x_display);
// esContext->getActualWidth(), esContext->getActualHeight()
int width = 800;
int height = 600;
swa.event_mask = ExposureMask | PointerMotionMask | KeyPressMask | ButtonPressMask | ButtonReleaseMask | StructureNotifyMask;
win = XCreateWindow(
x_display, root,
0, 0, width, height, 0,
CopyFromParent, InputOutput,
CopyFromParent, CWEventMask,
&swa );
xattr.override_redirect = 0;
XChangeWindowAttributes ( x_display, win, CWOverrideRedirect, &xattr );
XSelectInput(x_display, win,
ExposureMask | KeyPressMask | KeyReleaseMask | PointerMotionMask |
ButtonPressMask | ButtonReleaseMask | StructureNotifyMask
);
hints.input = 1;
hints.flags = InputHint;
XSetWMHints(x_display, win, &hints);
// make the window visible on the screen
XMapWindow (x_display, win);
XStoreName (x_display, win, title);
// get identifiers for the provided atom name strings
wm_state = XInternAtom (x_display, "_NET_WM_STATE", 0);
memset ( &xev, 0, sizeof(xev) );
xev.type = ClientMessage;
xev.xclient.window = win;
xev.xclient.message_type = wm_state;
xev.xclient.format = 32;
xev.xclient.data.l[0] = 1;
xev.xclient.data.l[1] = 0;
XSendEvent (
x_display,
DefaultRootWindow ( x_display ),
0,
SubstructureNotifyMask,
&xev );
eglNativeWindow = (EGLNativeWindowType) win;
eglNativeDisplay = (EGLNativeDisplayType) x_display;
cerr << "native display = " << x_display << endl;
XFlush(x_display);
return true;
}
std::shared_ptr<canvas::ContextFactory> createContextFactory() const {
return std::shared_ptr<canvas::ContextFactory>(new canvas::CairoContextFactory);
}
std::shared_ptr<EventLoop> createEventLoop() override;
void showMessageBox(const std::string & message) {
}
std::string showTextEntryDialog(const std::string & message) {
return "";
}
void postNotification(const std::string & message) {
}
void launchBrowser(const std::string & input_url) {
}
std::string getBundleFilename(const char * filename) {
string s = "assets/";
return s + filename;
}
void storeValue(const std::string & key, const std::string & value) {
}
std::string loadValue(const std::string & key) {
return "";
}
void swapBuffers() {
eglSwapBuffers(eglDisplay, eglSurface);
}
private:
// X11 related local variables
Display * x_display = NULL;
};
class PlatformX11;
class EventLoopX11 : public EventLoop {
public:
EventLoopX11( Display * _x_display,
PlatformX11 * _platform,
FWContextBase * _application
)
: EventLoop(_application), x_display(_x_display), platform(_platform) { }
void readEvents() {
XEvent xev;
// cerr << "read pending\n";
while ( XPending(x_display) ) {
XNextEvent(x_display, &xev);
handleEvent(xev);
}
if (doKeepRunning()) {
sendEvents();
}
if (doKeepRunning()) {
// cerr << "read all\n";
timeval tv = { 1, 0 }; // 1000000 / 50 };
if (XNextEventTimed(x_display, &xev, &tv)) {
handleEvent(xev);
sendEvents();
}
}
}
void run() override {
struct timeval t1, t2;
struct timezone tz;
float deltatime;
gettimeofday ( &t1 , &tz );
while (doKeepRunning()) {
readEvents();
getApplication()->loadEvents();
#if 0
gettimeofday(&t2, &tz);
deltatime = (float)(t2.tv_sec - t1.tv_sec + (t2.tv_usec - t1.tv_usec) * 1e-6);
t1 = t2;
#endif
if (getApplication()->onUpdate(getPlatform()->getTime() * 1000)) {
getApplication()->onDraw();
platform->swapBuffers();
}
}
}
protected:
void sendEvents() {
if (display_width && display_height &&
(display_width != getApplication()->getActualWidth() ||
display_height != getApplication()->getActualHeight())) {
getApplication()->onResize(display_width, display_height, display_width, display_height);
}
}
void handleEvent(XEvent & xev) {
KeySym key;
char text;
switch (xev.type) {
case KeyPress:
if (XLookupString(&xev.xkey, &text, 1, &key, 0) == 1) {
getApplication()->onKeyPress(text, getPlatform()->getTime(), 0, 0);
}
break;
case DestroyNotify:
stop();
break;
case MotionNotify:
// getApplication().onMouseMove(xev.xmotion.x, xev.xmotion.y);
if (button_pressed) {
getApplication()->touchesMoved(xev.xmotion.x, xev.xmotion.y, getPlatform()->getTime(), 0);
}
mouse_x = xev.xmotion.x;
mouse_y = xev.xmotion.y;
break;
case ButtonPress:
// getApplication().onMouseDown(xev.xbutton.button, 0, 0);
getApplication()->touchesBegin(mouse_x, mouse_y, getPlatform()->getTime(), 0);
button_pressed = true;
break;
case ButtonRelease:
// getApplication().onMouseUp(xev.xbutton.button, 0, 0);
getApplication()->touchesEnded(mouse_x, mouse_y, getPlatform()->getTime(), 0);
button_pressed = false;
break;
case ConfigureNotify:
{
XConfigureEvent xce = xev.xconfigure;
display_width = xce.width;
display_height = xce.height;
}
break;
}
}
PlatformX11 * getPlatform() { return platform; }
private:
Display * x_display;
PlatformX11 * platform;
int display_width = 0, display_height = 0;
bool button_pressed = false;
int mouse_x = 0, mouse_y = 0;
};
std::shared_ptr<EventLoop>
PlatformX11::createEventLoop() {
return std::make_shared<EventLoopX11>(x_display, this, &(getApplication()));
}
///
// Global extern. The application must declare this function
// that runs the application.
//
extern void applicationMain(FWPlatformBase * platform);
///
// main()
//
// Main entrypoint for application
//
int main(int argc, char *argv[]) {
PlatformX11 platform;
cerr << "starting\n";
applicationMain(&platform);
// platform.createWindow(&(platform.getApplication()), "App");
platform.createContext(&(platform.getApplication()), "App", 800, 600);
platform.getApplication().onCmdLine(argc, argv);
platform.getApplication().Init();
auto eventloop = platform.createEventLoop();
eventloop->run();
platform.getApplication().onShutdown();
return 0;
}
<|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.
// Tests for the top plugins to catch regressions in our plugin host code, as
// well as in the out of process code. Currently this tests:
// Flash
// Real
// QuickTime
// Windows Media Player
// -this includes both WMP plugins. npdsplay.dll is the older one that
// comes with XP. np-mswmp.dll can be downloaded from Microsoft and
// needs SP2 or Vista.
#include "build/build_config.h"
#if defined(OS_WIN)
#include <windows.h>
#include <shellapi.h>
#include <shlobj.h>
#include <comutil.h>
#endif
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <string>
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "third_party/npapi/bindings/npapi.h"
#include "webkit/glue/plugins/plugin_constants_win.h"
#include "webkit/glue/plugins/plugin_list.h"
#if defined(OS_WIN)
#include "base/registry.h"
#endif
class PluginTest : public UITest {
protected:
#if defined(OS_WIN)
virtual void SetUp() {
const testing::TestInfo* const test_info =
testing::UnitTest::GetInstance()->current_test_info();
if (strcmp(test_info->name(), "MediaPlayerNew") == 0) {
// The installer adds our process names to the registry key below. Since
// the installer might not have run on this machine, add it manually.
RegKey regkey;
if (regkey.Open(HKEY_LOCAL_MACHINE,
L"Software\\Microsoft\\MediaPlayer\\ShimInclusionList",
KEY_WRITE)) {
regkey.CreateKey(L"CHROME.EXE", KEY_READ);
}
} else if (strcmp(test_info->name(), "MediaPlayerOld") == 0) {
// When testing the old WMP plugin, we need to force Chrome to not load
// the new plugin.
launch_arguments_.AppendSwitch(kUseOldWMPPluginSwitch);
} else if (strcmp(test_info->name(), "FlashSecurity") == 0) {
launch_arguments_.AppendSwitchASCII(switches::kTestSandbox,
"security_tests.dll");
}
UITest::SetUp();
}
#endif // defined(OS_WIN)
void TestPlugin(const std::string& test_case,
int timeout,
bool mock_http) {
GURL url = GetTestUrl(test_case, mock_http);
NavigateToURL(url);
WaitForFinish(timeout, mock_http);
}
// Generate the URL for testing a particular test.
// HTML for the tests is all located in test_directory\plugin\<testcase>
// Set |mock_http| to true to use mock HTTP server.
GURL GetTestUrl(const std::string &test_case, bool mock_http) {
static const FilePath::CharType kPluginPath[] = FILE_PATH_LITERAL("plugin");
if (mock_http) {
FilePath plugin_path = FilePath(kPluginPath).AppendASCII(test_case);
return URLRequestMockHTTPJob::GetMockUrl(plugin_path);
}
FilePath path;
PathService::Get(chrome::DIR_TEST_DATA, &path);
path = path.Append(kPluginPath).AppendASCII(test_case);
return net::FilePathToFileURL(path);
}
// Waits for the test case to finish.
void WaitForFinish(const int wait_time, bool mock_http) {
static const char kTestCompleteCookie[] = "status";
static const char kTestCompleteSuccess[] = "OK";
GURL url = GetTestUrl("done", mock_http);
scoped_refptr<TabProxy> tab(GetActiveTab());
const std::string result =
WaitUntilCookieNonEmpty(tab, url, kTestCompleteCookie, wait_time);
ASSERT_EQ(kTestCompleteSuccess, result);
}
};
TEST_F(PluginTest, Flash) {
// Note: This does not work with the npwrapper on 64-bit Linux. Install the
// native 64-bit Flash to run the test.
// TODO(thestig) Update this list if we decide to only test against internal
// Flash plugin in the future?
std::string kFlashQuery =
#if defined(OS_WIN)
"npswf32.dll"
#elif defined(OS_MACOSX)
"Flash Player.plugin"
#elif defined(OS_POSIX)
"libflashplayer.so"
#endif
;
TestPlugin("flash.html?" + kFlashQuery, action_max_timeout_ms(), false);
}
#if defined(OS_WIN)
// Windows only test
TEST_F(PluginTest, FlashSecurity) {
TestPlugin("flash.html", action_max_timeout_ms(), false);
}
#endif // defined(OS_WIN)
#if defined(OS_WIN)
// TODO(port) Port the following tests to platforms that have the required
// plugins.
TEST_F(PluginTest, Quicktime) {
TestPlugin("quicktime.html", action_max_timeout_ms(), false);
}
// Disabled on Release bots - http://crbug.com/44662
#if defined(NDEBUG)
#define MediaPlayerNew DISABLED_MediaPlayerNew
#endif
TEST_F(PluginTest, MediaPlayerNew) {
TestPlugin("wmp_new.html", action_max_timeout_ms(), false);
}
// http://crbug.com/4809
TEST_F(PluginTest, DISABLED_MediaPlayerOld) {
TestPlugin("wmp_old.html", action_max_timeout_ms(), false);
}
#if defined(NDEBUG)
#define Real DISABLED_Real
#endif
// Disabled on Release bots - http://crbug.com/44673
TEST_F(PluginTest, Real) {
TestPlugin("real.html", action_max_timeout_ms(), false);
}
TEST_F(PluginTest, FlashOctetStream) {
TestPlugin("flash-octet-stream.html", action_max_timeout_ms(), false);
}
// http://crbug.com/16114
TEST_F(PluginTest, FlashLayoutWhilePainting) {
TestPlugin("flash-layout-while-painting.html", action_max_timeout_ms(), true);
}
// http://crbug.com/8690
TEST_F(PluginTest, DISABLED_Java) {
TestPlugin("Java.html", action_max_timeout_ms(), false);
}
TEST_F(PluginTest, Silverlight) {
TestPlugin("silverlight.html", action_max_timeout_ms(), false);
}
#endif // defined(OS_WIN)
<commit_msg>Mark PluginTest.FlashLayoutWhilePainting as flaky on Windows.<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.
// Tests for the top plugins to catch regressions in our plugin host code, as
// well as in the out of process code. Currently this tests:
// Flash
// Real
// QuickTime
// Windows Media Player
// -this includes both WMP plugins. npdsplay.dll is the older one that
// comes with XP. np-mswmp.dll can be downloaded from Microsoft and
// needs SP2 or Vista.
#include "build/build_config.h"
#if defined(OS_WIN)
#include <windows.h>
#include <shellapi.h>
#include <shlobj.h>
#include <comutil.h>
#endif
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <string>
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "chrome/browser/net/url_request_mock_http_job.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "third_party/npapi/bindings/npapi.h"
#include "webkit/glue/plugins/plugin_constants_win.h"
#include "webkit/glue/plugins/plugin_list.h"
#if defined(OS_WIN)
#include "base/registry.h"
#endif
class PluginTest : public UITest {
protected:
#if defined(OS_WIN)
virtual void SetUp() {
const testing::TestInfo* const test_info =
testing::UnitTest::GetInstance()->current_test_info();
if (strcmp(test_info->name(), "MediaPlayerNew") == 0) {
// The installer adds our process names to the registry key below. Since
// the installer might not have run on this machine, add it manually.
RegKey regkey;
if (regkey.Open(HKEY_LOCAL_MACHINE,
L"Software\\Microsoft\\MediaPlayer\\ShimInclusionList",
KEY_WRITE)) {
regkey.CreateKey(L"CHROME.EXE", KEY_READ);
}
} else if (strcmp(test_info->name(), "MediaPlayerOld") == 0) {
// When testing the old WMP plugin, we need to force Chrome to not load
// the new plugin.
launch_arguments_.AppendSwitch(kUseOldWMPPluginSwitch);
} else if (strcmp(test_info->name(), "FlashSecurity") == 0) {
launch_arguments_.AppendSwitchASCII(switches::kTestSandbox,
"security_tests.dll");
}
UITest::SetUp();
}
#endif // defined(OS_WIN)
void TestPlugin(const std::string& test_case,
int timeout,
bool mock_http) {
GURL url = GetTestUrl(test_case, mock_http);
NavigateToURL(url);
WaitForFinish(timeout, mock_http);
}
// Generate the URL for testing a particular test.
// HTML for the tests is all located in test_directory\plugin\<testcase>
// Set |mock_http| to true to use mock HTTP server.
GURL GetTestUrl(const std::string &test_case, bool mock_http) {
static const FilePath::CharType kPluginPath[] = FILE_PATH_LITERAL("plugin");
if (mock_http) {
FilePath plugin_path = FilePath(kPluginPath).AppendASCII(test_case);
return URLRequestMockHTTPJob::GetMockUrl(plugin_path);
}
FilePath path;
PathService::Get(chrome::DIR_TEST_DATA, &path);
path = path.Append(kPluginPath).AppendASCII(test_case);
return net::FilePathToFileURL(path);
}
// Waits for the test case to finish.
void WaitForFinish(const int wait_time, bool mock_http) {
static const char kTestCompleteCookie[] = "status";
static const char kTestCompleteSuccess[] = "OK";
GURL url = GetTestUrl("done", mock_http);
scoped_refptr<TabProxy> tab(GetActiveTab());
const std::string result =
WaitUntilCookieNonEmpty(tab, url, kTestCompleteCookie, wait_time);
ASSERT_EQ(kTestCompleteSuccess, result);
}
};
TEST_F(PluginTest, Flash) {
// Note: This does not work with the npwrapper on 64-bit Linux. Install the
// native 64-bit Flash to run the test.
// TODO(thestig) Update this list if we decide to only test against internal
// Flash plugin in the future?
std::string kFlashQuery =
#if defined(OS_WIN)
"npswf32.dll"
#elif defined(OS_MACOSX)
"Flash Player.plugin"
#elif defined(OS_POSIX)
"libflashplayer.so"
#endif
;
TestPlugin("flash.html?" + kFlashQuery, action_max_timeout_ms(), false);
}
#if defined(OS_WIN)
// Windows only test
TEST_F(PluginTest, FlashSecurity) {
TestPlugin("flash.html", action_max_timeout_ms(), false);
}
#endif // defined(OS_WIN)
#if defined(OS_WIN)
// TODO(port) Port the following tests to platforms that have the required
// plugins.
TEST_F(PluginTest, Quicktime) {
TestPlugin("quicktime.html", action_max_timeout_ms(), false);
}
// Disabled on Release bots - http://crbug.com/44662
#if defined(NDEBUG)
#define MediaPlayerNew DISABLED_MediaPlayerNew
#endif
TEST_F(PluginTest, MediaPlayerNew) {
TestPlugin("wmp_new.html", action_max_timeout_ms(), false);
}
// http://crbug.com/4809
TEST_F(PluginTest, DISABLED_MediaPlayerOld) {
TestPlugin("wmp_old.html", action_max_timeout_ms(), false);
}
#if defined(NDEBUG)
#define Real DISABLED_Real
#endif
// Disabled on Release bots - http://crbug.com/44673
TEST_F(PluginTest, Real) {
TestPlugin("real.html", action_max_timeout_ms(), false);
}
TEST_F(PluginTest, FlashOctetStream) {
TestPlugin("flash-octet-stream.html", action_max_timeout_ms(), false);
}
#if defined(OS_WIN)
// http://crbug.com/53926
TEST_F(PluginTest, FLAKY_FlashLayoutWhilePainting) {
#else
TEST_F(PluginTest, FlashLayoutWhilePainting) {
#endif
TestPlugin("flash-layout-while-painting.html", action_max_timeout_ms(), true);
}
// http://crbug.com/8690
TEST_F(PluginTest, DISABLED_Java) {
TestPlugin("Java.html", action_max_timeout_ms(), false);
}
TEST_F(PluginTest, Silverlight) {
TestPlugin("silverlight.html", action_max_timeout_ms(), false);
}
#endif // defined(OS_WIN)
<|endoftext|>
|
<commit_before>// Local
#include "MainWindow.h"
#include "ui_MainWindow.h"
#include "ShadowSettings.h"
#include "GraphicsRoundedRectItem.h"
// Qt
#include <QGraphicsRectItem>
#include <QFileDialog>
#include <QMessageBox>
#include <QSettings>
#include <QMenu>
#include <QInputDialog>
#include <QDebug>
MainWindow::MainWindow(QWidget* parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
, m_settings(new QSettings)
, m_width(40)
, m_height(40)
, m_radius(0)
, m_scale(1)
{
ui->setupUi(this);
m_scene = new QGraphicsScene(this);
m_baseItem = new GraphicsRoundedRectItem();
m_baseItem->setBrush(QBrush(Qt::white));
m_baseItem->setPen(QPen(Qt::NoBrush, 0, Qt::NoPen));
m_baseItem->setZValue(1000);
m_scene->addItem(m_baseItem);
ui->graphicsView->setScene(m_scene);
addShadow();
connect(ui->scaleSlider, SIGNAL(valueChanged(int)), SLOT(userScaleChanged(int)));
connect(ui->widthBox, SIGNAL(valueChanged(int)), SLOT(userSourceChanged()));
connect(ui->heightBox, SIGNAL(valueChanged(int)), SLOT(userSourceChanged()));
connect(ui->radiusBox, SIGNAL(valueChanged(int)), SLOT(userSourceChanged()));
connect(ui->addShadowButton, SIGNAL(clicked()), SLOT(addShadow()));
connect(this, SIGNAL(sourceOptionsChanged(int,int,int)), SLOT(updateSource()));
connect(this, SIGNAL(scaleChanged(qreal)), SLOT(updateSource()));
// Hack: position view to the center of layout
//
// This is the only way I've found to ensure the item will be placed in the center of view: we simply make the view
// rectangle definitely larger than the view itself, turn off the scroll bars display (in the UI file) and forcing
// positioning on the center of the base item. If the scene rect is smaller than the view itself, QGraphicsView
// control simply ignores QGraphicsView::centerOn calls
ui->graphicsView->setSceneRect(-1000, -1000, 2000, 2000);
updateSource();
updatePresets();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_saveButton_clicked()
{
// File name
QString fileName = QFileDialog::getSaveFileName(this, tr("Save rendered image as..."), QString(),
"PNG image (*.png)");
if (fileName.isEmpty())
return;
if (!fileName.endsWith(".png", Qt::CaseInsensitive))
fileName.append(".png");
// Source scene rect to render
// We must use the aligned rectangle to not mess with the non-integer items coordinates
QRectF sourceRect = QRectF(m_scene->itemsBoundingRect().toAlignedRect());
QImage target(sourceRect.width(), sourceRect.height(), QImage::Format_ARGB32_Premultiplied);
target.fill(Qt::transparent);
QPainter p(&target);
p.setRenderHint(QPainter::Antialiasing);
p.setRenderHint(QPainter::SmoothPixmapTransform);
if (!ui->renderSourceCheckBox->isChecked())
m_baseItem->setVisible(false);
m_scene->render(&p, target.rect(), sourceRect);
m_baseItem->setVisible(true);
p.end();
// Determine the image rectangle filled by shadow and crop borders
QRect filled = filledRect(target);
target = target.copy(filled);
// Save file
bool saveResult = target.save(fileName);
if (!saveResult)
{
QMessageBox::critical(this, tr("Error saving file"), tr("Could not save file %1").arg(fileName));
return;
}
// Generate QML
if (ui->generateQmlCheckBox->isChecked())
{
QRectF baseItemRect = m_baseItem->boundingRect().translated(-sourceRect.topLeft()).translated(-filled.topLeft());
QFileInfo fileInfo(fileName);
QFile qmlFile(fileInfo.absolutePath() + "/" + fileInfo.completeBaseName() + ".qml");
if (!qmlFile.open(QIODevice::WriteOnly | QIODevice::Text))
{
QMessageBox::critical(this, tr("Error saving file"), tr("Could not save file %1").arg(qmlFile.fileName()));
return;
}
QTextStream stream(&qmlFile);
stream << "import QtQuick 2.0" << endl;
stream << endl;
stream << "Item {" << endl;
stream << " BorderImage {" << endl;
stream << " source: \"" << fileInfo.fileName() << "\"" << endl;
stream << endl;
stream << " anchors {" << endl;
stream << " fill: parent" << endl;
stream << " leftMargin: -border.left; topMargin: -border.top" << endl;
stream << " rightMargin: -border.right; bottomMargin: -border.bottom" << endl;
stream << " }" << endl;
stream << endl;
stream << " border.left: " << baseItemRect.left() << "; border.top: " << baseItemRect.top() << endl;
stream << " border.right: " << target.width() - baseItemRect.right()
<< "; border.bottom: " << target.height() - baseItemRect.bottom() << endl;
stream << " }" << endl;
stream << "}" << endl;
qmlFile.close();
}
}
void MainWindow::updateSource()
{
m_baseItem->setRect(0, 0, m_width * m_scale, m_height * m_scale);
m_baseItem->setRadiusX(m_radius * m_scale);
m_baseItem->setRadiusY(m_radius * m_scale);
ui->graphicsView->centerOn(m_baseItem);
}
void MainWindow::addShadow(int xOffset, int yOffset, int opacity, double blur)
{
QBoxLayout* shadowLayout = static_cast<QBoxLayout*>(ui->shadowsBox->layout());
ShadowSettings* settings = new ShadowSettings(m_scene);
settings->setSourceOptions(m_width, m_height, m_radius);
settings->setScale(m_scale);
connect(this, SIGNAL(sourceOptionsChanged(int,int,int)), settings, SLOT(setSourceOptions(int,int,int)));
connect(this, SIGNAL(scaleChanged(qreal)), settings, SLOT(setScale(qreal)));
connect(settings, &QObject::destroyed, [this](QObject* obj) { m_shadows.removeOne(qobject_cast<ShadowSettings*>(obj)); });
settings->setXOffset(xOffset);
settings->setYOffset(yOffset);
settings->setOpacity(opacity);
settings->setBlur(blur);
shadowLayout->insertWidget(shadowLayout->count() - 1, settings);
m_shadows.append(settings);
ui->graphicsView->centerOn(m_baseItem);
}
void MainWindow::userSourceChanged()
{
m_width = ui->widthBox->value();
m_height = ui->heightBox->value();
m_radius = ui->radiusBox->value();
ui->radiusBox->setMaximum(qMin(m_width, m_height) / 2);
emit sourceOptionsChanged(m_width, m_height, m_radius);
}
void MainWindow::userScaleChanged(int value)
{
// Calculate and display scale value
m_scale = qreal(value) * 0.25;
ui->scaleValueLabel->setText(tr("%1%").arg(m_scale * 100));
emit scaleChanged(m_scale);
}
void MainWindow::loadShadowPreset()
{
QAction* a = qobject_cast<QAction*>(sender());
if (!a)
{
qWarning("Unknown action source");
return;
}
QVariantList o = a->data().toList();
if (o.size() % 4)
{
qWarning() << "Incorrect preset data for preset" << a->text();
return;
}
qDeleteAll(m_shadows);
m_shadows.clear();
for (int i = 0; i < o.size() / 4; ++i)
addShadow(o.at(i * 4).toInt(), o.at(i * 4 + 1).toInt(), o.at(i * 4 + 2).toInt(), o.at(i * 4 + 3).toDouble());
}
QRect MainWindow::filledRect(const QImage& image)
{
QRect result = image.rect();
// Left border
while (result.left() < result.right())
{
bool hasFilledPixel = false;
for (int y = result.top(); y <= result.bottom(); y++)
{
if (qAlpha(image.pixel(result.left(), y)) > 0)
{
hasFilledPixel = true;
break;
}
}
if (hasFilledPixel)
break;
result.adjust(1, 0, 0, 0);
}
// Right border
while (result.right() > result.left())
{
bool hasFilledPixel = false;
for (int y = result.top(); y <= result.bottom(); y++)
{
if (qAlpha(image.pixel(result.right(), y)) > 0)
{
hasFilledPixel = true;
break;
}
}
if (hasFilledPixel)
break;
result.adjust(0, 0, -1, 0);
}
// Top border
while (result.top() < result.bottom())
{
bool hasFilledPixel = false;
for (int x = result.left(); x <= result.right(); x++)
{
if (qAlpha(image.pixel(x, result.top())) > 0)
{
hasFilledPixel = true;
break;
}
}
if (hasFilledPixel)
break;
result.adjust(0, 1, 0, 0);
}
// Top border
while (result.bottom() > result.top())
{
bool hasFilledPixel = false;
for (int x = result.left(); x <= result.right(); x++)
{
if (qAlpha(image.pixel(x, result.bottom())) > 0)
{
hasFilledPixel = true;
break;
}
}
if (hasFilledPixel)
break;
result.adjust(0, 0, 0, -1);
}
return result;
}
void MainWindow::updatePresets()
{
if (!ui->loadPresetButton->menu())
ui->loadPresetButton->setMenu(new QMenu);
QMenu* menu = ui->loadPresetButton->menu();
menu->clear();
// Default presets
QVariantList presets;
if (!m_settings->contains("ShadowPresets"))
{
QVariantMap d1;
d1[QStringLiteral("name")] = tr("Material design Z=1");
d1[QStringLiteral("options")] = QVariantList() << 0 << 1 << 12 << 1.5
<< 0 << 1 << 24 << 1.;
QVariantMap d2;
d2[QStringLiteral("name")] = tr("Material design Z=2");
d2[QStringLiteral("options")] = QVariantList() << 0 << 3 << 16 << 3.
<< 0 << 3 << 23 << 3.;
QVariantMap d3;
d3[QStringLiteral("name")] = tr("Material design Z=3");
d3[QStringLiteral("options")] = QVariantList() << 0 << 10 << 19 << 10.
<< 0 << 6 << 23 << 3.;
QVariantMap d4;
d4[QStringLiteral("name")] = tr("Material design Z=4");
d4[QStringLiteral("options")] = QVariantList() << 0 << 14 << 25 << 14.
<< 0 << 10 << 22 << 5.;
QVariantMap d5;
d5[QStringLiteral("name")] = tr("Material design Z=5");
d5[QStringLiteral("options")] = QVariantList() << 0 << 19 << 30 << 19.
<< 0 << 15 << 22 << 6.;
presets << d1 << d2 << d3 << d4 << d5;
m_settings->setValue(QStringLiteral("ShadowPresets"), presets);
}
else
{
presets = m_settings->value(QStringLiteral("ShadowPresets")).toList();
}
// Fill in the menu
for (auto p : presets)
{
if (!p.isValid())
{
qWarning() << "Failed to load preset";
continue;
}
QVariantMap preset = p.toMap();
auto action = menu->addAction(preset[QStringLiteral("name")].toString(), this, SLOT(loadShadowPreset()));
action->setData(preset[QStringLiteral("options")]);
}
}
void MainWindow::on_addPresetButton_clicked()
{
QString name = QInputDialog::getText(this, tr("Choose preset name"), tr("Preset name:"));
if (!name.isEmpty())
{
QVariantMap preset;
preset[QStringLiteral("name")] = name;
QVariantList options;
for (auto s : m_shadows)
options << s->xOffset() << s->yOffset() << s->opacity() << s->blur();
preset[QStringLiteral("options")] = options;
auto presets = m_settings->value(QStringLiteral("ShadowPresets")).toList();
presets.append(preset);
m_settings->setValue(QStringLiteral("ShadowPresets"), presets);
updatePresets();
}
}
<commit_msg>Fixed crash<commit_after>// Local
#include "MainWindow.h"
#include "ui_MainWindow.h"
#include "ShadowSettings.h"
#include "GraphicsRoundedRectItem.h"
// Qt
#include <QGraphicsRectItem>
#include <QFileDialog>
#include <QMessageBox>
#include <QSettings>
#include <QMenu>
#include <QInputDialog>
#include <QDebug>
MainWindow::MainWindow(QWidget* parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
, m_settings(new QSettings)
, m_width(40)
, m_height(40)
, m_radius(0)
, m_scale(1)
{
ui->setupUi(this);
m_scene = new QGraphicsScene(this);
m_baseItem = new GraphicsRoundedRectItem();
m_baseItem->setBrush(QBrush(Qt::white));
m_baseItem->setPen(QPen(Qt::NoBrush, 0, Qt::NoPen));
m_baseItem->setZValue(1000);
m_scene->addItem(m_baseItem);
ui->graphicsView->setScene(m_scene);
addShadow();
connect(ui->scaleSlider, SIGNAL(valueChanged(int)), SLOT(userScaleChanged(int)));
connect(ui->widthBox, SIGNAL(valueChanged(int)), SLOT(userSourceChanged()));
connect(ui->heightBox, SIGNAL(valueChanged(int)), SLOT(userSourceChanged()));
connect(ui->radiusBox, SIGNAL(valueChanged(int)), SLOT(userSourceChanged()));
connect(ui->addShadowButton, SIGNAL(clicked()), SLOT(addShadow()));
connect(this, SIGNAL(sourceOptionsChanged(int,int,int)), SLOT(updateSource()));
connect(this, SIGNAL(scaleChanged(qreal)), SLOT(updateSource()));
// Hack: position view to the center of layout
//
// This is the only way I've found to ensure the item will be placed in the center of view: we simply make the view
// rectangle definitely larger than the view itself, turn off the scroll bars display (in the UI file) and forcing
// positioning on the center of the base item. If the scene rect is smaller than the view itself, QGraphicsView
// control simply ignores QGraphicsView::centerOn calls
ui->graphicsView->setSceneRect(-1000, -1000, 2000, 2000);
updateSource();
updatePresets();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_saveButton_clicked()
{
// File name
QString fileName = QFileDialog::getSaveFileName(this, tr("Save rendered image as..."), QString(),
"PNG image (*.png)");
if (fileName.isEmpty())
return;
if (!fileName.endsWith(".png", Qt::CaseInsensitive))
fileName.append(".png");
// Source scene rect to render
// We must use the aligned rectangle to not mess with the non-integer items coordinates
QRectF sourceRect = QRectF(m_scene->itemsBoundingRect().toAlignedRect());
QImage target(sourceRect.width(), sourceRect.height(), QImage::Format_ARGB32_Premultiplied);
target.fill(Qt::transparent);
QPainter p(&target);
p.setRenderHint(QPainter::Antialiasing);
p.setRenderHint(QPainter::SmoothPixmapTransform);
if (!ui->renderSourceCheckBox->isChecked())
m_baseItem->setVisible(false);
m_scene->render(&p, target.rect(), sourceRect);
m_baseItem->setVisible(true);
p.end();
// Determine the image rectangle filled by shadow and crop borders
QRect filled = filledRect(target);
target = target.copy(filled);
// Save file
bool saveResult = target.save(fileName);
if (!saveResult)
{
QMessageBox::critical(this, tr("Error saving file"), tr("Could not save file %1").arg(fileName));
return;
}
// Generate QML
if (ui->generateQmlCheckBox->isChecked())
{
QRectF baseItemRect = m_baseItem->boundingRect().translated(-sourceRect.topLeft()).translated(-filled.topLeft());
QFileInfo fileInfo(fileName);
QFile qmlFile(fileInfo.absolutePath() + "/" + fileInfo.completeBaseName() + ".qml");
if (!qmlFile.open(QIODevice::WriteOnly | QIODevice::Text))
{
QMessageBox::critical(this, tr("Error saving file"), tr("Could not save file %1").arg(qmlFile.fileName()));
return;
}
QTextStream stream(&qmlFile);
stream << "import QtQuick 2.0" << endl;
stream << endl;
stream << "Item {" << endl;
stream << " BorderImage {" << endl;
stream << " source: \"" << fileInfo.fileName() << "\"" << endl;
stream << endl;
stream << " anchors {" << endl;
stream << " fill: parent" << endl;
stream << " leftMargin: -border.left; topMargin: -border.top" << endl;
stream << " rightMargin: -border.right; bottomMargin: -border.bottom" << endl;
stream << " }" << endl;
stream << endl;
stream << " border.left: " << baseItemRect.left() << "; border.top: " << baseItemRect.top() << endl;
stream << " border.right: " << target.width() - baseItemRect.right()
<< "; border.bottom: " << target.height() - baseItemRect.bottom() << endl;
stream << " }" << endl;
stream << "}" << endl;
qmlFile.close();
}
}
void MainWindow::updateSource()
{
m_baseItem->setRect(0, 0, m_width * m_scale, m_height * m_scale);
m_baseItem->setRadiusX(m_radius * m_scale);
m_baseItem->setRadiusY(m_radius * m_scale);
ui->graphicsView->centerOn(m_baseItem);
}
void MainWindow::addShadow(int xOffset, int yOffset, int opacity, double blur)
{
QBoxLayout* shadowLayout = static_cast<QBoxLayout*>(ui->shadowsBox->layout());
ShadowSettings* settings = new ShadowSettings(m_scene);
settings->setSourceOptions(m_width, m_height, m_radius);
settings->setScale(m_scale);
connect(this, SIGNAL(sourceOptionsChanged(int,int,int)), settings, SLOT(setSourceOptions(int,int,int)));
connect(this, SIGNAL(scaleChanged(qreal)), settings, SLOT(setScale(qreal)));
connect(settings, &QObject::destroyed,
[this](QObject* obj)
{
qDebug() << obj;
this->m_shadows.removeOne(static_cast<ShadowSettings*>(obj));
qDebug("remove");
});
settings->setXOffset(xOffset);
settings->setYOffset(yOffset);
settings->setOpacity(opacity);
settings->setBlur(blur);
shadowLayout->insertWidget(shadowLayout->count() - 1, settings);
m_shadows.append(settings);
ui->graphicsView->centerOn(m_baseItem);
}
void MainWindow::userSourceChanged()
{
m_width = ui->widthBox->value();
m_height = ui->heightBox->value();
m_radius = ui->radiusBox->value();
ui->radiusBox->setMaximum(qMin(m_width, m_height) / 2);
emit sourceOptionsChanged(m_width, m_height, m_radius);
}
void MainWindow::userScaleChanged(int value)
{
// Calculate and display scale value
m_scale = qreal(value) * 0.25;
ui->scaleValueLabel->setText(tr("%1%").arg(m_scale * 100));
emit scaleChanged(m_scale);
}
void MainWindow::loadShadowPreset()
{
QAction* a = qobject_cast<QAction*>(sender());
if (!a)
{
qWarning("Unknown action source");
return;
}
QVariantList o = a->data().toList();
if (o.size() % 4)
{
qWarning() << "Incorrect preset data for preset" << a->text();
return;
}
qDeleteAll(m_shadows);
m_shadows.clear();
for (int i = 0; i < o.size() / 4; ++i)
addShadow(o.at(i * 4).toInt(), o.at(i * 4 + 1).toInt(), o.at(i * 4 + 2).toInt(), o.at(i * 4 + 3).toDouble());
}
QRect MainWindow::filledRect(const QImage& image)
{
QRect result = image.rect();
// Left border
while (result.left() < result.right())
{
bool hasFilledPixel = false;
for (int y = result.top(); y <= result.bottom(); y++)
{
if (qAlpha(image.pixel(result.left(), y)) > 0)
{
hasFilledPixel = true;
break;
}
}
if (hasFilledPixel)
break;
result.adjust(1, 0, 0, 0);
}
// Right border
while (result.right() > result.left())
{
bool hasFilledPixel = false;
for (int y = result.top(); y <= result.bottom(); y++)
{
if (qAlpha(image.pixel(result.right(), y)) > 0)
{
hasFilledPixel = true;
break;
}
}
if (hasFilledPixel)
break;
result.adjust(0, 0, -1, 0);
}
// Top border
while (result.top() < result.bottom())
{
bool hasFilledPixel = false;
for (int x = result.left(); x <= result.right(); x++)
{
if (qAlpha(image.pixel(x, result.top())) > 0)
{
hasFilledPixel = true;
break;
}
}
if (hasFilledPixel)
break;
result.adjust(0, 1, 0, 0);
}
// Top border
while (result.bottom() > result.top())
{
bool hasFilledPixel = false;
for (int x = result.left(); x <= result.right(); x++)
{
if (qAlpha(image.pixel(x, result.bottom())) > 0)
{
hasFilledPixel = true;
break;
}
}
if (hasFilledPixel)
break;
result.adjust(0, 0, 0, -1);
}
return result;
}
void MainWindow::updatePresets()
{
if (!ui->loadPresetButton->menu())
ui->loadPresetButton->setMenu(new QMenu);
QMenu* menu = ui->loadPresetButton->menu();
menu->clear();
// Default presets
QVariantList presets;
if (!m_settings->contains("ShadowPresets"))
{
QVariantMap d1;
d1[QStringLiteral("name")] = tr("Material design Z=1");
d1[QStringLiteral("options")] = QVariantList() << 0 << 1 << 12 << 1.5
<< 0 << 1 << 24 << 1.;
QVariantMap d2;
d2[QStringLiteral("name")] = tr("Material design Z=2");
d2[QStringLiteral("options")] = QVariantList() << 0 << 3 << 16 << 3.
<< 0 << 3 << 23 << 3.;
QVariantMap d3;
d3[QStringLiteral("name")] = tr("Material design Z=3");
d3[QStringLiteral("options")] = QVariantList() << 0 << 10 << 19 << 10.
<< 0 << 6 << 23 << 3.;
QVariantMap d4;
d4[QStringLiteral("name")] = tr("Material design Z=4");
d4[QStringLiteral("options")] = QVariantList() << 0 << 14 << 25 << 14.
<< 0 << 10 << 22 << 5.;
QVariantMap d5;
d5[QStringLiteral("name")] = tr("Material design Z=5");
d5[QStringLiteral("options")] = QVariantList() << 0 << 19 << 30 << 19.
<< 0 << 15 << 22 << 6.;
presets << d1 << d2 << d3 << d4 << d5;
m_settings->setValue(QStringLiteral("ShadowPresets"), presets);
}
else
{
presets = m_settings->value(QStringLiteral("ShadowPresets")).toList();
}
// Fill in the menu
for (auto p : presets)
{
if (!p.isValid())
{
qWarning() << "Failed to load preset";
continue;
}
QVariantMap preset = p.toMap();
auto action = menu->addAction(preset[QStringLiteral("name")].toString(), this, SLOT(loadShadowPreset()));
action->setData(preset[QStringLiteral("options")]);
}
}
void MainWindow::on_addPresetButton_clicked()
{
QString name = QInputDialog::getText(this, tr("Choose preset name"), tr("Preset name:"));
if (!name.isEmpty())
{
QVariantMap preset;
preset[QStringLiteral("name")] = name;
QVariantList options;
for (auto s : m_shadows)
options << s->xOffset() << s->yOffset() << s->opacity() << s->blur();
preset[QStringLiteral("options")] = options;
auto presets = m_settings->value(QStringLiteral("ShadowPresets")).toList();
presets.append(preset);
m_settings->setValue(QStringLiteral("ShadowPresets"), presets);
updatePresets();
}
}
<|endoftext|>
|
<commit_before>/* Copyright 2017 R. Thomas
* Copyright 2017 Quarkslab
*
* 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 <stdexcept>
#include <string.h>
#include <iomanip>
#include <functional>
#include <algorithm>
#include <numeric>
#include <iterator>
#include "LIEF/PE/hash.hpp"
#include "LIEF/exception.hpp"
#include "LIEF/Abstract/Section.hpp"
#include "LIEF/PE/Section.hpp"
#include "LIEF/PE/EnumToString.hpp"
namespace LIEF {
namespace PE {
Section::~Section(void) = default;
Section::Section(void) :
LIEF::Section{},
virtualSize_{0},
content_{},
pointerToRelocations_{0},
pointerToLineNumbers_{0},
numberOfRelocations_{0},
numberOfLineNumbers_{0},
characteristics_{0},
types_{PE_SECTION_TYPES::UNKNOWN}
{}
Section& Section::operator=(const Section&) = default;
Section::Section(const Section&) = default;
Section::Section(const pe_section* header) :
virtualSize_{header->VirtualSize},
pointerToRelocations_{header->PointerToRelocations},
pointerToLineNumbers_{header->PointerToLineNumbers},
numberOfRelocations_{header->NumberOfRelocations},
numberOfLineNumbers_{header->NumberOfLineNumbers},
characteristics_{header->Characteristics},
types_{PE_SECTION_TYPES::UNKNOWN}
{
this->name_ = std::string(header->Name, sizeof(header->Name)).c_str();
this->virtual_address_ = header->VirtualAddress;
this->size_ = header->SizeOfRawData;
this->offset_ = header->PointerToRawData;
}
Section::Section(const std::vector<uint8_t>& data, const std::string& name, uint32_t characteristics) :
Section::Section{}
{
this->characteristics_ = characteristics;
this->name_ = name;
this->size_ = data.size();
this->content_ = data;
}
Section::Section(const std::string& name) :
Section::Section{}
{
this->name_ = name;
}
uint32_t Section::virtual_size(void) const {
return this->virtualSize_;
}
uint32_t Section::sizeof_raw_data(void) const {
return this->size();
}
std::vector<uint8_t> Section::content(void) const {
return this->content_;
}
std::vector<uint8_t>& Section::content_ref(void) {
return this->content_;
}
uint32_t Section::pointerto_raw_data(void) const {
return this->offset();
}
uint32_t Section::pointerto_relocation(void) const {
return this->pointerToRelocations_;
}
uint32_t Section::pointerto_line_numbers(void) const {
return this->pointerToLineNumbers_;
}
uint16_t Section::numberof_relocations(void) const {
return this->numberOfRelocations_;
}
uint16_t Section::numberof_line_numbers(void) const {
return this->numberOfLineNumbers_;
}
uint32_t Section::characteristics(void) const {
return this->characteristics_;
}
const std::set<PE_SECTION_TYPES>& Section::types(void) const {
return this->types_;
}
bool Section::is_type(PE_SECTION_TYPES type) const {
return this->types_.count(type) != 0;
}
void Section::name(const std::string& name) {
if (name.size() > STRUCT_SIZES::NameSize - 1) {
throw LIEF::pe_bad_section_name("Name is too big");
}
this->name_ = name;
}
bool Section::has_characteristic(SECTION_CHARACTERISTICS c) const {
return (this->characteristics_ & static_cast<uint32_t>(c)) > 0;
}
std::set<SECTION_CHARACTERISTICS> Section::characteristics_list(void) const {
std::set<SECTION_CHARACTERISTICS> charac;
std::copy_if(
std::begin(section_characteristics_array),
std::end(section_characteristics_array),
std::inserter(charac, std::begin(charac)),
std::bind(&Section::has_characteristic, this, std::placeholders::_1));
return charac;
}
void Section::content(const std::vector<uint8_t>& data) {
this->content_ = data;
}
void Section::virtual_size(uint32_t virtualSize) {
this->virtualSize_ = virtualSize;
}
void Section::pointerto_raw_data(uint32_t pointerToRawData) {
this->offset(pointerToRawData);
}
void Section::pointerto_relocation(uint32_t pointerToRelocation) {
this->pointerToRelocations_ = pointerToRelocation;
}
void Section::pointerto_line_numbers(uint32_t pointerToLineNumbers) {
this->pointerToLineNumbers_ = pointerToLineNumbers;
}
void Section::numberof_relocations(uint16_t numberOfRelocations) {
this->numberOfRelocations_ = numberOfRelocations;
}
void Section::numberof_line_numbers(uint16_t numberOfLineNumbers) {
this->numberOfLineNumbers_ = numberOfLineNumbers;
}
void Section::sizeof_raw_data(uint32_t sizeOfRawData) {
this->size(sizeOfRawData);
}
void Section::type(PE_SECTION_TYPES type) {
this->types_ = {type};
}
void Section::remove_type(PE_SECTION_TYPES type) {
this->types_.erase(type);
}
void Section::add_type(PE_SECTION_TYPES type) {
this->types_.insert(type);
}
void Section::characteristics(uint32_t characteristics) {
this->characteristics_ = characteristics;
}
void Section::remove_characteristic(SECTION_CHARACTERISTICS characteristic) {
this->characteristics_ &= ~ static_cast<uint32_t>(characteristic);
}
void Section::add_characteristic(SECTION_CHARACTERISTICS characteristic) {
this->characteristics_ |= static_cast<uint32_t>(characteristic);
}
void Section::accept(LIEF::Visitor& visitor) const {
visitor.visit(*this);
}
void Section::clear(uint8_t c) {
std::fill(
std::begin(this->content_),
std::end(this->content_),
c);
}
bool Section::operator==(const Section& rhs) const {
size_t hash_lhs = Hash::hash(*this);
size_t hash_rhs = Hash::hash(rhs);
return hash_lhs == hash_rhs;
}
bool Section::operator!=(const Section& rhs) const {
return not (*this == rhs);
}
std::ostream& operator<<(std::ostream& os, const Section& section) {
const auto& chara = section.characteristics_list();
std::string chara_str = std::accumulate(
std::begin(chara),
std::end(chara), std::string{},
[] (const std::string& a, SECTION_CHARACTERISTICS b) {
return a.empty() ?
to_string(b) :
a + " - " + to_string(b);
});
os << std::hex;
os << std::left
<< std::setw(10) << section.name()
<< std::setw(10) << section.virtual_size()
<< std::setw(10) << section.virtual_address()
<< std::setw(10) << section.size()
<< std::setw(10) << section.offset()
<< std::setw(10) << section.pointerto_relocation()
<< std::setw(10) << section.entropy()
<< std::setw(10) << chara_str;
return os;
}
}
}
<commit_msg>Fix (bad) bound checking<commit_after>/* Copyright 2017 R. Thomas
* Copyright 2017 Quarkslab
*
* 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 <stdexcept>
#include <string.h>
#include <iomanip>
#include <functional>
#include <algorithm>
#include <numeric>
#include <iterator>
#include "LIEF/PE/hash.hpp"
#include "LIEF/exception.hpp"
#include "LIEF/Abstract/Section.hpp"
#include "LIEF/PE/Section.hpp"
#include "LIEF/PE/EnumToString.hpp"
namespace LIEF {
namespace PE {
Section::~Section(void) = default;
Section::Section(void) :
LIEF::Section{},
virtualSize_{0},
content_{},
pointerToRelocations_{0},
pointerToLineNumbers_{0},
numberOfRelocations_{0},
numberOfLineNumbers_{0},
characteristics_{0},
types_{PE_SECTION_TYPES::UNKNOWN}
{}
Section& Section::operator=(const Section&) = default;
Section::Section(const Section&) = default;
Section::Section(const pe_section* header) :
virtualSize_{header->VirtualSize},
pointerToRelocations_{header->PointerToRelocations},
pointerToLineNumbers_{header->PointerToLineNumbers},
numberOfRelocations_{header->NumberOfRelocations},
numberOfLineNumbers_{header->NumberOfLineNumbers},
characteristics_{header->Characteristics},
types_{PE_SECTION_TYPES::UNKNOWN}
{
this->name_ = std::string(header->Name, sizeof(header->Name)).c_str();
this->virtual_address_ = header->VirtualAddress;
this->size_ = header->SizeOfRawData;
this->offset_ = header->PointerToRawData;
}
Section::Section(const std::vector<uint8_t>& data, const std::string& name, uint32_t characteristics) :
Section::Section{}
{
this->characteristics_ = characteristics;
this->name_ = name;
this->size_ = data.size();
this->content_ = data;
}
Section::Section(const std::string& name) :
Section::Section{}
{
this->name_ = name;
}
uint32_t Section::virtual_size(void) const {
return this->virtualSize_;
}
uint32_t Section::sizeof_raw_data(void) const {
return this->size();
}
std::vector<uint8_t> Section::content(void) const {
return this->content_;
}
std::vector<uint8_t>& Section::content_ref(void) {
return this->content_;
}
uint32_t Section::pointerto_raw_data(void) const {
return this->offset();
}
uint32_t Section::pointerto_relocation(void) const {
return this->pointerToRelocations_;
}
uint32_t Section::pointerto_line_numbers(void) const {
return this->pointerToLineNumbers_;
}
uint16_t Section::numberof_relocations(void) const {
return this->numberOfRelocations_;
}
uint16_t Section::numberof_line_numbers(void) const {
return this->numberOfLineNumbers_;
}
uint32_t Section::characteristics(void) const {
return this->characteristics_;
}
const std::set<PE_SECTION_TYPES>& Section::types(void) const {
return this->types_;
}
bool Section::is_type(PE_SECTION_TYPES type) const {
return this->types_.count(type) != 0;
}
void Section::name(const std::string& name) {
if (name.size() > STRUCT_SIZES::NameSize) {
throw LIEF::pe_bad_section_name("Name is too big");
}
this->name_ = name;
}
bool Section::has_characteristic(SECTION_CHARACTERISTICS c) const {
return (this->characteristics_ & static_cast<uint32_t>(c)) > 0;
}
std::set<SECTION_CHARACTERISTICS> Section::characteristics_list(void) const {
std::set<SECTION_CHARACTERISTICS> charac;
std::copy_if(
std::begin(section_characteristics_array),
std::end(section_characteristics_array),
std::inserter(charac, std::begin(charac)),
std::bind(&Section::has_characteristic, this, std::placeholders::_1));
return charac;
}
void Section::content(const std::vector<uint8_t>& data) {
this->content_ = data;
}
void Section::virtual_size(uint32_t virtualSize) {
this->virtualSize_ = virtualSize;
}
void Section::pointerto_raw_data(uint32_t pointerToRawData) {
this->offset(pointerToRawData);
}
void Section::pointerto_relocation(uint32_t pointerToRelocation) {
this->pointerToRelocations_ = pointerToRelocation;
}
void Section::pointerto_line_numbers(uint32_t pointerToLineNumbers) {
this->pointerToLineNumbers_ = pointerToLineNumbers;
}
void Section::numberof_relocations(uint16_t numberOfRelocations) {
this->numberOfRelocations_ = numberOfRelocations;
}
void Section::numberof_line_numbers(uint16_t numberOfLineNumbers) {
this->numberOfLineNumbers_ = numberOfLineNumbers;
}
void Section::sizeof_raw_data(uint32_t sizeOfRawData) {
this->size(sizeOfRawData);
}
void Section::type(PE_SECTION_TYPES type) {
this->types_ = {type};
}
void Section::remove_type(PE_SECTION_TYPES type) {
this->types_.erase(type);
}
void Section::add_type(PE_SECTION_TYPES type) {
this->types_.insert(type);
}
void Section::characteristics(uint32_t characteristics) {
this->characteristics_ = characteristics;
}
void Section::remove_characteristic(SECTION_CHARACTERISTICS characteristic) {
this->characteristics_ &= ~ static_cast<uint32_t>(characteristic);
}
void Section::add_characteristic(SECTION_CHARACTERISTICS characteristic) {
this->characteristics_ |= static_cast<uint32_t>(characteristic);
}
void Section::accept(LIEF::Visitor& visitor) const {
visitor.visit(*this);
}
void Section::clear(uint8_t c) {
std::fill(
std::begin(this->content_),
std::end(this->content_),
c);
}
bool Section::operator==(const Section& rhs) const {
size_t hash_lhs = Hash::hash(*this);
size_t hash_rhs = Hash::hash(rhs);
return hash_lhs == hash_rhs;
}
bool Section::operator!=(const Section& rhs) const {
return not (*this == rhs);
}
std::ostream& operator<<(std::ostream& os, const Section& section) {
const auto& chara = section.characteristics_list();
std::string chara_str = std::accumulate(
std::begin(chara),
std::end(chara), std::string{},
[] (const std::string& a, SECTION_CHARACTERISTICS b) {
return a.empty() ?
to_string(b) :
a + " - " + to_string(b);
});
os << std::hex;
os << std::left
<< std::setw(10) << section.name()
<< std::setw(10) << section.virtual_size()
<< std::setw(10) << section.virtual_address()
<< std::setw(10) << section.size()
<< std::setw(10) << section.offset()
<< std::setw(10) << section.pointerto_relocation()
<< std::setw(10) << section.entropy()
<< std::setw(10) << chara_str;
return os;
}
}
}
<|endoftext|>
|
<commit_before>//============================================================================
// Name : PinballBot.cpp
// Author : Nico Hauser, David Schmid
// Version : 0.1
// Description : A reinforcement learning agent that learns to play pinball
//============================================================================
#include <stdlib.h> /* atexit */
#include <cstdio>
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <numeric>
#include <ctime>
#include <SDL2/SDL.h>
#include <SDL2/SDL_main.h>
#include "PinballBot.h"
#include "action/ActionsSim.cpp"
#include "sim/Simulation.h"
#include "sim/Renderer.h"
#include "agent/Agent.h"
#include "agent/State.h"
#include "stats/StatsLogger.h"
const bool PinballBot::SIMULATION = true;
const bool PinballBot::RENDER = false;
const float PinballBot::FPS = 60.0f;
const float PinballBot::TIME_STEP = 1.0f / FPS;
const float PinballBot::TICK_INTERVAL = 1000.0f / FPS;
const unsigned long long PinballBot::SAVE_INTERVAL = 100000;
const unsigned long long PinballBot::STATS_INTERVAL = 50000;
const unsigned long long PinballBot::LOG_INTERVAL = 10000;
const unsigned long long PinballBot::OUTSIDE_CF_UNTIL_RESPAWN = 1800;//1 step ≈ 1/60 sec in-game, 1800 steps ≈ 30 secs in-game
const std::string PinballBot::STATS_FILE = "stats.csv";
const std::string PinballBot::POLICIES_FILE = "policies.csv";
PinballBot::PinballBot() : statsLogger(), rewardsCollected(0, 0.0f){
KEYS = SDL_GetKeyboardState(NULL);
pause = false;
quit = false;
nextTime = 0;
steps = 0;
statsRewardsCollected = 0;
timeLastLog = std::time(nullptr);
gameOvers = 0;
stepStartedBeingOutsideCF = 0;
rlAgent = nullptr;
renderer = nullptr;
statsLogger.registerLoggingColumn("STEPS", std::bind(&PinballBot::logSteps, this));
statsLogger.registerLoggingColumn("TIME", std::bind(&PinballBot::logTime, this));
statsLogger.registerLoggingColumn("AMOUNT_OF_STATES", std::bind(&PinballBot::logAmountOfStates, this));
statsLogger.registerLoggingColumn("AVERAGE_TIME_PER_LOOP", std::bind(&PinballBot::logAverageTimePerLoop, this));
statsLogger.registerLoggingColumn("REWARDS_COLLECTED", std::bind(&PinballBot::logRewardsCollected, this));
statsLogger.registerLoggingColumn("GAMEOVERS", std::bind(&PinballBot::logGameOvers, this));
statsLogger.initLog(STATS_FILE);
}
Uint32 PinballBot::timeLeft() {
Uint32 now = SDL_GetTicks();
if(nextTime <= now){
return 0;
}else{
return nextTime - now;
}
}
void PinballBot::capFramerate() {
SDL_Delay(timeLeft());
nextTime += TICK_INTERVAL;
}
void PinballBot::handleKeys(Simulation &sim, SDL_Event &e){
while( SDL_PollEvent( &e ) != 0 ){
if( e.type == SDL_QUIT ){
quit = true;
}
if (KEYS[SDL_SCANCODE_LEFT]){
sim.enableLeftFlipper();
}else{
sim.disableLeftFlipper();
}
if (KEYS[SDL_SCANCODE_RIGHT]){
sim.enableRightFlipper();
}else{
sim.disableRightFlipper();
}
if (KEYS[SDL_SCANCODE_SPACE]){
pause = true;
}else{
pause = false;
}
if (KEYS[SDL_SCANCODE_P]){
sim.generateRandomPinField();
}
if (KEYS[SDL_SCANCODE_S]){
rlAgent->savePoliciesToFile();
}
}
}
bool PinballBot::preventStablePositionsOutsideCF(Simulation &sim){
if(sim.isPlayingBallInsideCaptureFrame()){
stepStartedBeingOutsideCF = 0;
return true;
}else{
if(stepStartedBeingOutsideCF == 0){
//when does the ball leave the CF
stepStartedBeingOutsideCF = steps;
}else{
//if it stays out of it for too long, respawn it
if((steps - stepStartedBeingOutsideCF) > OUTSIDE_CF_UNTIL_RESPAWN){
printf("The ball was outside the capture frame for too long, respawn!\n");
sim.debugPlayingBall();
sim.respawnBall();
stepStartedBeingOutsideCF = 0;
}
}
return false;
}
}
void PinballBot::runSimulation(){
Simulation sim;
SDL_Event e;
std::vector<Action*> availableActions = ActionsSim::actionsAvailable(sim);
Agent agent(availableActions);
rlAgent = &agent;
if(RENDER){
renderer = new Renderer(320, 640, sim.getWorld());
}
while(!quit){
if(RENDER){
handleKeys(sim, e);
}
if(!pause){
sim.step(TIME_STEP);
//Ignore default rewards
if(sim.reward != Action::DEFAULT_REWARD){
rewardsCollected.push_back(sim.reward);
}
if(sim.reward == 0.0f){
gameOvers++;
}
if(preventStablePositionsOutsideCF(sim)){
rlAgent->think(sim.getCurrentState(availableActions), rewardsCollected);
statsRewardsCollected += std::accumulate(rewardsCollected.begin(), rewardsCollected.end(), 0.0f);
rewardsCollected.clear();
}
if(RENDER){
renderer->render();
capFramerate();
}
}else{
nextTime = SDL_GetTicks() + TICK_INTERVAL;
}
if(steps != 0){
if(steps % LOG_INTERVAL == 0){
printf("step #%lld | amount of states: %ld\n", steps, rlAgent->states.size());
if(steps % STATS_INTERVAL == 0){
statsLogger.log(STATS_FILE);
statsRewardsCollected = 0;
gameOvers = 0;
if(steps % SAVE_INTERVAL == 0){
rlAgent->savePoliciesToFile();
}
}
}
}
steps++;
}
}
void PinballBot::shutdownHook(){
rlAgent->savePoliciesToFile(); //doesn't work yet, vector empty :/
//archive previous log file
statsLogger.archiveLog(STATS_FILE);
}
std::string PinballBot::logSteps(){
return std::to_string(steps);
}
std::string PinballBot::logTime(){
return std::to_string(std::time(nullptr));
}
std::string PinballBot::logAmountOfStates(){
return std::to_string(rlAgent->states.size());
}
std::string PinballBot::logAverageTimePerLoop(){
return std::to_string(( ((double)(std::time(nullptr) - timeLastLog)) / ( (double)SAVE_INTERVAL) ));
}
std::string PinballBot::logRewardsCollected(){
return std::to_string(statsRewardsCollected);
}
std::string PinballBot::logGameOvers(){
return std::to_string(gameOvers);
}
void initLogFile(){
std::ofstream statsFile;
statsFile.open(PinballBot::STATS_FILE);
statsFile << "STEPS;TIME;AMOUNT_OF_STATES;AVERAGE_TIME_PER_LOOP;REWARDS_COLLECTED;GAMEOVERS" << std::endl;
}
int main(int argc, char** argv) {
PinballBot bot;
//atexit(shutdownHook);
if(PinballBot::SIMULATION){
bot.runSimulation();
}
return 0;
}
<commit_msg>Fixed stats error<commit_after>//============================================================================
// Name : PinballBot.cpp
// Author : Nico Hauser, David Schmid
// Version : 0.1
// Description : A reinforcement learning agent that learns to play pinball
//============================================================================
#include <stdlib.h> /* atexit */
#include <cstdio>
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <numeric>
#include <ctime>
#include <SDL2/SDL.h>
#include <SDL2/SDL_main.h>
#include "PinballBot.h"
#include "action/ActionsSim.cpp"
#include "sim/Simulation.h"
#include "sim/Renderer.h"
#include "agent/Agent.h"
#include "agent/State.h"
#include "stats/StatsLogger.h"
const bool PinballBot::SIMULATION = true;
const bool PinballBot::RENDER = false;
const float PinballBot::FPS = 60.0f;
const float PinballBot::TIME_STEP = 1.0f / FPS;
const float PinballBot::TICK_INTERVAL = 1000.0f / FPS;
const unsigned long long PinballBot::SAVE_INTERVAL = 100000;
const unsigned long long PinballBot::STATS_INTERVAL = 50000;
const unsigned long long PinballBot::LOG_INTERVAL = 10000;
const unsigned long long PinballBot::OUTSIDE_CF_UNTIL_RESPAWN = 1800;//1 step ≈ 1/60 sec in-game, 1800 steps ≈ 30 secs in-game
const std::string PinballBot::STATS_FILE = "stats.csv";
const std::string PinballBot::POLICIES_FILE = "policies.csv";
PinballBot::PinballBot() : statsLogger(), rewardsCollected(0, 0.0f){
KEYS = SDL_GetKeyboardState(NULL);
pause = false;
quit = false;
nextTime = 0;
steps = 0;
statsRewardsCollected = 0;
timeLastLog = std::time(nullptr);
gameOvers = 0;
stepStartedBeingOutsideCF = 0;
rlAgent = nullptr;
renderer = nullptr;
statsLogger.registerLoggingColumn("STEPS", std::bind(&PinballBot::logSteps, this));
statsLogger.registerLoggingColumn("TIME", std::bind(&PinballBot::logTime, this));
statsLogger.registerLoggingColumn("AMOUNT_OF_STATES", std::bind(&PinballBot::logAmountOfStates, this));
statsLogger.registerLoggingColumn("AVERAGE_TIME_PER_LOOP", std::bind(&PinballBot::logAverageTimePerLoop, this));
statsLogger.registerLoggingColumn("REWARDS_COLLECTED", std::bind(&PinballBot::logRewardsCollected, this));
statsLogger.registerLoggingColumn("GAMEOVERS", std::bind(&PinballBot::logGameOvers, this));
statsLogger.initLog(STATS_FILE);
}
Uint32 PinballBot::timeLeft() {
Uint32 now = SDL_GetTicks();
if(nextTime <= now){
return 0;
}else{
return nextTime - now;
}
}
void PinballBot::capFramerate() {
SDL_Delay(timeLeft());
nextTime += TICK_INTERVAL;
}
void PinballBot::handleKeys(Simulation &sim, SDL_Event &e){
while( SDL_PollEvent( &e ) != 0 ){
if( e.type == SDL_QUIT ){
quit = true;
}
if (KEYS[SDL_SCANCODE_LEFT]){
sim.enableLeftFlipper();
}else{
sim.disableLeftFlipper();
}
if (KEYS[SDL_SCANCODE_RIGHT]){
sim.enableRightFlipper();
}else{
sim.disableRightFlipper();
}
if (KEYS[SDL_SCANCODE_SPACE]){
pause = true;
}else{
pause = false;
}
if (KEYS[SDL_SCANCODE_P]){
sim.generateRandomPinField();
}
if (KEYS[SDL_SCANCODE_S]){
rlAgent->savePoliciesToFile();
}
}
}
bool PinballBot::preventStablePositionsOutsideCF(Simulation &sim){
if(sim.isPlayingBallInsideCaptureFrame()){
stepStartedBeingOutsideCF = 0;
return true;
}else{
if(stepStartedBeingOutsideCF == 0){
//when does the ball leave the CF
stepStartedBeingOutsideCF = steps;
}else{
//if it stays out of it for too long, respawn it
if((steps - stepStartedBeingOutsideCF) > OUTSIDE_CF_UNTIL_RESPAWN){
printf("The ball was outside the capture frame for too long, respawn!\n");
sim.debugPlayingBall();
sim.respawnBall();
stepStartedBeingOutsideCF = 0;
}
}
return false;
}
}
void PinballBot::runSimulation(){
Simulation sim;
SDL_Event e;
std::vector<Action*> availableActions = ActionsSim::actionsAvailable(sim);
Agent agent(availableActions);
rlAgent = &agent;
if(RENDER){
renderer = new Renderer(320, 640, sim.getWorld());
}
while(!quit){
if(RENDER){
handleKeys(sim, e);
}
if(!pause){
sim.step(TIME_STEP);
//Ignore default rewards
if(sim.reward != Action::DEFAULT_REWARD){
rewardsCollected.push_back(sim.reward);
}
if(sim.reward == 0.0f){
gameOvers++;
}
if(preventStablePositionsOutsideCF(sim)){
rlAgent->think(sim.getCurrentState(availableActions), rewardsCollected);
statsRewardsCollected += std::accumulate(rewardsCollected.begin(), rewardsCollected.end(), 0.0f);
rewardsCollected.clear();
}
if(RENDER){
renderer->render();
capFramerate();
}
}else{
nextTime = SDL_GetTicks() + TICK_INTERVAL;
}
if(steps != 0){
if(steps % LOG_INTERVAL == 0){
printf("step #%lld | amount of states: %ld\n", steps, rlAgent->states.size());
if(steps % STATS_INTERVAL == 0){
statsLogger.log(STATS_FILE);
statsRewardsCollected = 0;
gameOvers = 0;
if(steps % SAVE_INTERVAL == 0){
rlAgent->savePoliciesToFile();
}
}
}
}
steps++;
}
}
void PinballBot::shutdownHook(){
rlAgent->savePoliciesToFile(); //doesn't work yet, vector empty :/
//archive previous log file
statsLogger.archiveLog(STATS_FILE);
}
std::string PinballBot::logSteps(){
return std::to_string(steps);
}
std::string PinballBot::logTime(){
timeLastLog = std::time(nullptr);
return std::to_string(timeLastLog);
}
std::string PinballBot::logAmountOfStates(){
return std::to_string(rlAgent->states.size());
}
std::string PinballBot::logAverageTimePerLoop(){
return std::to_string(( ((double)(std::time(nullptr) - timeLastLog)) / ( (double)SAVE_INTERVAL) ));
}
std::string PinballBot::logRewardsCollected(){
return std::to_string(statsRewardsCollected);
}
std::string PinballBot::logGameOvers(){
return std::to_string(gameOvers);
}
void initLogFile(){
std::ofstream statsFile;
statsFile.open(PinballBot::STATS_FILE);
statsFile << "STEPS;TIME;AMOUNT_OF_STATES;AVERAGE_TIME_PER_LOOP;REWARDS_COLLECTED;GAMEOVERS" << std::endl;
}
int main(int argc, char** argv) {
PinballBot bot;
//atexit(shutdownHook);
if(PinballBot::SIMULATION){
bot.runSimulation();
}
return 0;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2017 Andrey Valyaev <dron.valyaev@gmail.com>
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
#include <TextReport.h>
#include <iostream>
#include <sstream>
#include <Report.h>
#include <Result.h>
#include <Test.h>
using namespace std;
using namespace oout;
class TextReportStream final : public Report {
public:
void preamble()
{
// @todo #57:15min Test counts show in preample
text << "[==========] Running" << endl;
}
void begin(const string &tag, const map<string, string> &attributes) override
{
if (tag == "testcase") {
text << "[ RUN ] " << attributes.at("name") << endl;
if (attributes.at("failures") == "0") {
text << "[ OK ] ";
} else {
text << "[ FAILED ] ";
}
text << attributes.at("name") << endl;
} else {
// @todo #53:15min gtest text format for "cases"
text << tag << ": ";
for (const auto &ap : attributes) {
text << ap.first << "='" << ap.second << "' ";
}
text << endl;
}
}
void end(const string &) override
{
}
// @todo #57:15min format portscrips and status
string asString() const
{
return text.str();
}
private:
ostringstream text;
};
TextReport::TextReport(const std::shared_ptr<const Result> &result)
: result(result)
{
}
string TextReport::asString() const
{
TextReportStream rep;
rep.preamble();
result->print(&rep);
return rep.asString();
}
<commit_msg>#57: Default ctor for TextReportStream<commit_after>// Copyright (c) 2017 Andrey Valyaev <dron.valyaev@gmail.com>
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
#include <TextReport.h>
#include <iostream>
#include <sstream>
#include <Report.h>
#include <Result.h>
#include <Test.h>
using namespace std;
using namespace oout;
// @todo #57:15min TextReportStream is a bad name
class TextReportStream final : public Report {
public:
TextReportStream()
: text()
{
}
void preamble()
{
// @todo #57:15min Test counts show in preample
text << "[==========] Running" << endl;
}
void begin(const string &tag, const map<string, string> &attributes) override
{
if (tag == "testcase") {
text << "[ RUN ] " << attributes.at("name") << endl;
if (attributes.at("failures") == "0") {
text << "[ OK ] ";
} else {
text << "[ FAILED ] ";
}
text << attributes.at("name") << endl;
} else {
// @todo #53:15min gtest text format for "cases"
text << tag << ": ";
for (const auto &ap : attributes) {
text << ap.first << "='" << ap.second << "' ";
}
text << endl;
}
}
void end(const string &) override
{
}
// @todo #57:15min format portscrips and status
string asString() const
{
return text.str();
}
private:
ostringstream text;
};
TextReport::TextReport(const std::shared_ptr<const Result> &result)
: result(result)
{
}
string TextReport::asString() const
{
TextReportStream rep;
rep.preamble();
result->print(&rep);
return rep.asString();
}
<|endoftext|>
|
<commit_before>#include "TpObserver.h"
TpObserver::TpObserver (const ChannelClassList &channelFilter,
QObject *parent )
: AbstractClientObserver(channelFilter)
, IObserver (parent)
, id(1) // Always ignore
{
}//TpObserver::TpObserver
void
TpObserver::setId (int i)
{
id = i;
}//TpObserver::setId
void
TpObserver::startMonitoring (const QString &strC)
{
strContact = strC;
}//TpObserver::startMonitoring
void
TpObserver::stopMonitoring ()
{
strContact.clear ();
}//TpObserver::stopMonitoring
void
TpObserver::observeChannels(
const MethodInvocationContextPtr<> & context,
const AccountPtr & account,
const ConnectionPtr & connection,
const QList <ChannelPtr> & channels,
const ChannelDispatchOperationPtr & dispatchOperation,
const QList <ChannelRequestPtr> & requestsSatisfied,
const QVariantMap & observerInfo)
{
bool bOk;
QString msg;
emit log ("Observer got something!");
if (strContact.isEmpty ())
{
context->setFinished ();
emit log ("But we weren't asked to notify anything, so go away");
return;
}
msg = QString("There are %1 channels in channels list")
.arg (channels.size ());
log (msg);
foreach (ChannelPtr channel, channels)
{
if (!channel->isReady ())
{
emit log ("Channel is not ready");
ChannelAccepter *closer = new ChannelAccepter(context,
account,
connection,
channels,
dispatchOperation,
requestsSatisfied,
observerInfo,
channel,
strContact,
this);
bOk =
QObject::connect (
closer, SIGNAL (log(const QString &, int)),
this , SIGNAL (log(const QString &, int)));
bOk =
QObject::connect (
closer, SIGNAL (callStarted ()),
this , SIGNAL (callStarted ()));
closer->init ();
break;
}
}
}//TpObserver::addDispatchOperation
ChannelAccepter::ChannelAccepter (
const MethodInvocationContextPtr<> & ctx,
const AccountPtr & act,
const ConnectionPtr & conn,
const QList <ChannelPtr> & chnls,
const ChannelDispatchOperationPtr & dispatchOp,
const QList <ChannelRequestPtr> & requestsSat,
const QVariantMap & obsInfo,
const ChannelPtr channel,
const QString & strNum,
QObject * parent)
: QObject(parent)
, context (ctx)
, account (act)
, connection (conn)
, channels (chnls)
, dispatchOperation (dispatchOp)
, requestsSatisfied (requestsSat)
, observerInfo (obsInfo)
, currentChannel (channel)
, strCheckNumber (strNum)
, mutex (QMutex::Recursive)
, nRefCount (0)
, bFailure (false)
{
}//ChannelAccepter::ChannelAccepter
bool
ChannelAccepter::init ()
{
bool bOk;
PendingReady *pendingReady;
QMutexLocker locker(&mutex);
nRefCount ++; // One for protection
nRefCount ++;
pendingReady = connection->becomeReady ();
bOk =
QObject::connect (
pendingReady, SIGNAL (finished (Tp::PendingOperation *)),
this , SLOT (onConnectionReady (Tp::PendingOperation *)));
if (bOk)
{
emit log ("Waiting for connection to become ready");
}
nRefCount ++;
pendingReady = account->becomeReady ();
bOk =
QObject::connect (
pendingReady, SIGNAL (finished (Tp::PendingOperation *)),
this , SLOT (onAccountReady (Tp::PendingOperation *)));
if (bOk)
{
emit log ("Waiting for account to become ready");
}
nRefCount ++;
pendingReady = currentChannel->becomeReady ();
bOk =
QObject::connect (
pendingReady, SIGNAL (finished (Tp::PendingOperation *)),
this , SLOT (onChannelReady (Tp::PendingOperation *)));
if (bOk)
{
emit log ("Waiting for channel to become ready");
}
emit log ("All become ready's sent");
decrefCleanup ();
return (bOk);
}//ChannelAccepter::init
void
ChannelAccepter::decrefCleanup ()
{
QMutexLocker locker(&mutex);
nRefCount--;
if (0 != nRefCount)
{
return;
}
emit log ("Everything ready. Cleaning up");
bool bCleanupLater = false;
do { // Not a loop
if (bFailure)
{
emit log ("Failed while waiting for something");
break;
}
QString msg;
msg = QString("Channel type = %1. isRequested = %2")
.arg (currentChannel->channelType ())
.arg (currentChannel->isRequested ());
emit log (msg);
ContactPtr contact = currentChannel->initiatorContact ();
msg = QString("Contact id = %1. alias = %2")
.arg (contact->id ())
.arg (contact->alias ());
emit log (msg);
int interested = 0;
if (0 == currentChannel->channelType().compare (
TELEPATHY_INTERFACE_CHANNEL_TYPE_STREAMED_MEDIA))
{
interested++;
}
if (!currentChannel->isRequested ())
{
interested++;
}
if (contact->id ().contains (strCheckNumber))
{
interested++;
}
if (3 != interested)
{
emit log ("Channel that we're not interested in");
break;
}
emit log ("Incoming call from our number!");
emit callStarted ();
} while (0); // Not a loop
if (!bCleanupLater)
{
context->setFinished ();
this->deleteLater ();
}
}//ChannelAccepter::decrefCleanup
void
ChannelAccepter::onCallAccepted (Tp::PendingOperation *operation)
{
if (operation->isError ())
{
emit log ("Failed to accept call");
}
else
{
emit log ("Call accepted");
}
context->setFinished ();
this->deleteLater ();
}//ChannelAccepter::onCallAccepted
void
ChannelAccepter::onChannelReady (Tp::PendingOperation *operation)
{
do { // Not a loop
if (operation->isError ())
{
emit log ("Channel could not become ready");
bFailure = true;
}
if (!currentChannel->isReady ())
{
emit log ("Dammit the channel is still not ready");
}
else
{
emit log ("Channel is ready");
}
decrefCleanup ();
} while (0); // Not a loop
operation->deleteLater ();
}//ChannelAccepter::onChannelReady
void
ChannelAccepter::onConnectionReady (Tp::PendingOperation *operation)
{
do { // Not a loop
if (operation->isError ())
{
emit log ("Connection could not become ready");
bFailure = true;
}
if (!connection->isReady ())
{
emit log ("Dammit the connection is still not ready");
}
else
{
emit log ("Connection is ready");
}
decrefCleanup ();
} while (0); // Not a loop
operation->deleteLater ();
}//ChannelAccepter::onConnectionReady
void
ChannelAccepter::onAccountReady (Tp::PendingOperation *operation)
{
do { // Not a loop
if (operation->isError ())
{
emit log ("Account could not become ready");
bFailure = true;
}
if (!account->isReady ())
{
emit log ("Dammit the account is still not ready");
}
else
{
emit log ("Account is ready");
}
decrefCleanup ();
} while (0); // Not a loop
operation->deleteLater ();
}//ChannelAccepter::onAccountReady
<commit_msg>fix one warning<commit_after>#include "TpObserver.h"
TpObserver::TpObserver (const ChannelClassList &channelFilter,
QObject *parent )
: IObserver (parent)
, AbstractClientObserver(channelFilter)
, id(1) // Always ignore
{
}//TpObserver::TpObserver
void
TpObserver::setId (int i)
{
id = i;
}//TpObserver::setId
void
TpObserver::startMonitoring (const QString &strC)
{
strContact = strC;
}//TpObserver::startMonitoring
void
TpObserver::stopMonitoring ()
{
strContact.clear ();
}//TpObserver::stopMonitoring
void
TpObserver::observeChannels(
const MethodInvocationContextPtr<> & context,
const AccountPtr & account,
const ConnectionPtr & connection,
const QList <ChannelPtr> & channels,
const ChannelDispatchOperationPtr & dispatchOperation,
const QList <ChannelRequestPtr> & requestsSatisfied,
const QVariantMap & observerInfo)
{
bool bOk;
QString msg;
emit log ("Observer got something!");
if (strContact.isEmpty ())
{
context->setFinished ();
emit log ("But we weren't asked to notify anything, so go away");
return;
}
msg = QString("There are %1 channels in channels list")
.arg (channels.size ());
log (msg);
foreach (ChannelPtr channel, channels)
{
if (!channel->isReady ())
{
emit log ("Channel is not ready");
ChannelAccepter *closer = new ChannelAccepter(context,
account,
connection,
channels,
dispatchOperation,
requestsSatisfied,
observerInfo,
channel,
strContact,
this);
bOk =
QObject::connect (
closer, SIGNAL (log(const QString &, int)),
this , SIGNAL (log(const QString &, int)));
bOk =
QObject::connect (
closer, SIGNAL (callStarted ()),
this , SIGNAL (callStarted ()));
closer->init ();
break;
}
}
}//TpObserver::addDispatchOperation
ChannelAccepter::ChannelAccepter (
const MethodInvocationContextPtr<> & ctx,
const AccountPtr & act,
const ConnectionPtr & conn,
const QList <ChannelPtr> & chnls,
const ChannelDispatchOperationPtr & dispatchOp,
const QList <ChannelRequestPtr> & requestsSat,
const QVariantMap & obsInfo,
const ChannelPtr channel,
const QString & strNum,
QObject * parent)
: QObject(parent)
, context (ctx)
, account (act)
, connection (conn)
, channels (chnls)
, dispatchOperation (dispatchOp)
, requestsSatisfied (requestsSat)
, observerInfo (obsInfo)
, currentChannel (channel)
, strCheckNumber (strNum)
, mutex (QMutex::Recursive)
, nRefCount (0)
, bFailure (false)
{
}//ChannelAccepter::ChannelAccepter
bool
ChannelAccepter::init ()
{
bool bOk;
PendingReady *pendingReady;
QMutexLocker locker(&mutex);
nRefCount ++; // One for protection
nRefCount ++;
pendingReady = connection->becomeReady ();
bOk =
QObject::connect (
pendingReady, SIGNAL (finished (Tp::PendingOperation *)),
this , SLOT (onConnectionReady (Tp::PendingOperation *)));
if (bOk)
{
emit log ("Waiting for connection to become ready");
}
nRefCount ++;
pendingReady = account->becomeReady ();
bOk =
QObject::connect (
pendingReady, SIGNAL (finished (Tp::PendingOperation *)),
this , SLOT (onAccountReady (Tp::PendingOperation *)));
if (bOk)
{
emit log ("Waiting for account to become ready");
}
nRefCount ++;
pendingReady = currentChannel->becomeReady ();
bOk =
QObject::connect (
pendingReady, SIGNAL (finished (Tp::PendingOperation *)),
this , SLOT (onChannelReady (Tp::PendingOperation *)));
if (bOk)
{
emit log ("Waiting for channel to become ready");
}
emit log ("All become ready's sent");
decrefCleanup ();
return (bOk);
}//ChannelAccepter::init
void
ChannelAccepter::decrefCleanup ()
{
QMutexLocker locker(&mutex);
nRefCount--;
if (0 != nRefCount)
{
return;
}
emit log ("Everything ready. Cleaning up");
bool bCleanupLater = false;
do { // Not a loop
if (bFailure)
{
emit log ("Failed while waiting for something");
break;
}
QString msg;
msg = QString("Channel type = %1. isRequested = %2")
.arg (currentChannel->channelType ())
.arg (currentChannel->isRequested ());
emit log (msg);
ContactPtr contact = currentChannel->initiatorContact ();
msg = QString("Contact id = %1. alias = %2")
.arg (contact->id ())
.arg (contact->alias ());
emit log (msg);
int interested = 0;
if (0 == currentChannel->channelType().compare (
TELEPATHY_INTERFACE_CHANNEL_TYPE_STREAMED_MEDIA))
{
interested++;
}
if (!currentChannel->isRequested ())
{
interested++;
}
if (contact->id ().contains (strCheckNumber))
{
interested++;
}
if (3 != interested)
{
emit log ("Channel that we're not interested in");
break;
}
emit log ("Incoming call from our number!");
emit callStarted ();
} while (0); // Not a loop
if (!bCleanupLater)
{
context->setFinished ();
this->deleteLater ();
}
}//ChannelAccepter::decrefCleanup
void
ChannelAccepter::onCallAccepted (Tp::PendingOperation *operation)
{
if (operation->isError ())
{
emit log ("Failed to accept call");
}
else
{
emit log ("Call accepted");
}
context->setFinished ();
this->deleteLater ();
}//ChannelAccepter::onCallAccepted
void
ChannelAccepter::onChannelReady (Tp::PendingOperation *operation)
{
do { // Not a loop
if (operation->isError ())
{
emit log ("Channel could not become ready");
bFailure = true;
}
if (!currentChannel->isReady ())
{
emit log ("Dammit the channel is still not ready");
}
else
{
emit log ("Channel is ready");
}
decrefCleanup ();
} while (0); // Not a loop
operation->deleteLater ();
}//ChannelAccepter::onChannelReady
void
ChannelAccepter::onConnectionReady (Tp::PendingOperation *operation)
{
do { // Not a loop
if (operation->isError ())
{
emit log ("Connection could not become ready");
bFailure = true;
}
if (!connection->isReady ())
{
emit log ("Dammit the connection is still not ready");
}
else
{
emit log ("Connection is ready");
}
decrefCleanup ();
} while (0); // Not a loop
operation->deleteLater ();
}//ChannelAccepter::onConnectionReady
void
ChannelAccepter::onAccountReady (Tp::PendingOperation *operation)
{
do { // Not a loop
if (operation->isError ())
{
emit log ("Account could not become ready");
bFailure = true;
}
if (!account->isReady ())
{
emit log ("Dammit the account is still not ready");
}
else
{
emit log ("Account is ready");
}
decrefCleanup ();
} while (0); // Not a loop
operation->deleteLater ();
}//ChannelAccepter::onAccountReady
<|endoftext|>
|
<commit_before>/*
* D-Bus AT-SPI, Qt Adaptor
*
* Copyright 2009-2011 Nokia Corporation and/or its subsidiary(-ies).
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#include "accessible.h"
#include <QDBusPendingReply>
#include <QDebug>
#include <QtGui/QWidget>
#include <QAccessibleValueInterface>
#include "adaptor.h"
#include "bridge.h"
#include "cache.h"
#include "constant_mappings.h"
#include "generated/accessible_adaptor.h"
#include "generated/action_adaptor.h"
#include "generated/component_adaptor.h"
#include "generated/editable_text_adaptor.h"
#include "generated/event_adaptor.h"
#include "generated/socket_proxy.h"
#include "generated/table_adaptor.h"
#include "generated/text_adaptor.h"
#include "generated/value_adaptor.h"
#define ACCESSIBLE_CREATION_DEBUG
#define QSPI_REGISTRY_NAME "org.a11y.atspi.Registry"
QString QSpiAccessible::pathForObject(QObject *object)
{
Q_ASSERT(object);
return QSPI_OBJECT_PATH_PREFIX + QString::number(reinterpret_cast<size_t>(object));
}
QString QSpiAccessible::pathForInterface(QAccessibleInterface *interface, int childIndex)
{
QString path;
QAccessibleInterface* interfaceWithObject = interface;
while(!interfaceWithObject->object()) {
QAccessibleInterface* parentInterface;
interfaceWithObject->navigate(QAccessible::Ancestor, 1, &parentInterface);
Q_ASSERT(parentInterface->isValid());
int index = parentInterface->indexOfChild(interfaceWithObject);
//Q_ASSERT(index >= 0);
// FIXME: This should never happen!
if (index < 0) {
index = 999;
path.prepend("/BROKEN_OBJECT_HIERARCHY");
qWarning() << "Object claims to have child that we cannot navigate to. FIX IT!" << parentInterface->object();
qDebug() << "Original interface: " << interface->object() << index;
qDebug() << "Parent interface: " << parentInterface->object() << " childcount:" << parentInterface->childCount();
QObject* p = parentInterface->object();
qDebug() << p->children();
QAccessibleInterface* tttt;
int id = parentInterface->navigate(QAccessible::Child, 1, &tttt);
qDebug() << "Nav child: " << id << tttt->object();
}
path.prepend('/' + QString::number(index));
interfaceWithObject = parentInterface;
}
path.prepend(QSPI_OBJECT_PATH_PREFIX + QString::number(reinterpret_cast<quintptr>(interfaceWithObject->object())));
if (childIndex > 0) {
path.append('/' + QString::number(childIndex));
}
return path;
}
QPair<QAccessibleInterface*, int> QSpiAccessible::interfaceFromPath(const QString& dbusPath)
{
QStringList parts = dbusPath.split('/');
Q_ASSERT(parts.size() > 5);
// ignore the first /org/a11y/atspi/accessible/
QString objectString = parts.at(5);
quintptr uintptr = objectString.toULongLong();
if (!uintptr)
return QPair<QAccessibleInterface*, int>(0, 0);
QObject* object = reinterpret_cast<QObject*>(uintptr);
qDebug() << object;
QAccessibleInterface* inter = QAccessible::queryAccessibleInterface(object);
QAccessibleInterface* childInter;
int index = 0;
for (int i = 6; i < parts.size(); ++i) {
index = inter->navigate(QAccessible::Child, parts.at(i).toInt(), &childInter);
if (index == 0) {
delete inter;
inter = childInter;
}
}
return QPair<QAccessibleInterface*, int>(inter, index);
}
QSpiAccessible::QSpiAccessible(QAccessibleInterface *interface, int index)
: QSpiAdaptor(interface, index)
{
QString path = pathForInterface(interface, index);
QDBusObjectPath dbusPath = QDBusObjectPath(path);
reference = QSpiObjectReference(spiBridge->dBusConnection(),
dbusPath);
#ifdef ACCESSIBLE_CREATION_DEBUG
qDebug() << "ACCESSIBLE: " << interface->object() << reference.path.path() << interface->text(QAccessible::Name, index) << qSpiRoleMapping[interface->role(index)].name();
#endif
new AccessibleAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_ACCESSIBLE;
if ( (!interface->rect(index).isEmpty()) ||
(interface->object() && interface->object()->isWidgetType()) ||
(interface->role(index) == QAccessible::ListItem) ||
(interface->role(index) == QAccessible::Cell) ||
(interface->role(index) == QAccessible::TreeItem) ||
(interface->role(index) == QAccessible::Row) ||
(interface->object() && interface->object()->inherits("QSGItem"))
) {
new ComponentAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_COMPONENT;
if (interface->object() && interface->object()->isWidgetType()) {
QWidget *w = qobject_cast<QWidget*>(interface->object());
if (w->isWindow()) {
new WindowAdaptor(this);
#ifdef ACCESSIBLE_CREATION_DEBUG
qDebug() << " IS a window";
#endif
}
}
}
#ifdef ACCESSIBLE_CREATION_DEBUG
else {
qDebug() << " IS NOT a component";
}
#endif
new ObjectAdaptor(this);
new FocusAdaptor(this);
if (interface->actionInterface())
{
new ActionAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_ACTION;
}
if (interface->textInterface())
{
new TextAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_TEXT;
oldText = interface->textInterface()->text(0, interface->textInterface()->characterCount());
}
if (interface->editableTextInterface())
{
new EditableTextAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_EDITABLE_TEXT;
}
if (interface->valueInterface())
{
new ValueAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_VALUE;
}
if (interface->table2Interface())
{
new TableAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_TABLE;
}
spiBridge->dBusConnection().registerObject(reference.path.path(),
this, QDBusConnection::ExportAdaptors);
state = interface->state(childIndex());
}
QSpiObjectReference QSpiAccessible::getParentReference() const
{
Q_ASSERT(interface);
if (interface->isValid()) {
QAccessibleInterface *parentInterface = 0;
interface->navigate(QAccessible::Ancestor, 1, &parentInterface);
if (parentInterface) {
QSpiAdaptor *parent = spiBridge->objectToAccessible(parentInterface->object());
delete parentInterface;
if (parent)
return parent->getReference();
}
}
qWarning() << "Invalid parent: " << interface << interface->object();
return QSpiObjectReference();
}
void QSpiAccessible::accessibleEvent(QAccessible::Event event)
{
Q_ASSERT(interface);
if (!interface->isValid()) {
spiBridge->removeAdaptor(this);
return;
}
switch (event) {
case QAccessible::NameChanged: {
QSpiObjectReference r = getReference();
QDBusVariant data;
data.setVariant(QVariant::fromValue(r));
emit PropertyChange("accessible-name", 0, 0, data, spiBridge->getRootReference());
break;
}
case QAccessible::DescriptionChanged: {
QSpiObjectReference r = getReference();
QDBusVariant data;
data.setVariant(QVariant::fromValue(r));
emit PropertyChange("accessible-description", 0, 0, data, spiBridge->getRootReference());
break;
}
case QAccessible::Focus: {
qDebug() << "Focus: " << getReference().path.path() << interface->object() << interface->text(QAccessible::Name, 0);
QDBusVariant data;
data.setVariant(QVariant::fromValue(getReference()));
emit StateChanged("focused", 1, 0, data, spiBridge->getRootReference());
emit Focus("", 0, 0, data, spiBridge->getRootReference());
break;
}
#if (QT_VERSION >= QT_VERSION_CHECK(4, 8, 0))
case QAccessible::TextUpdated: {
Q_ASSERT(interface->textInterface());
// at-spi doesn't have a proper text updated/changed, so remove all and re-add the new text
qDebug() << "Text changed: " << interface->object();
QDBusVariant data;
data.setVariant(QVariant::fromValue(oldText));
emit TextChanged("delete", 0, oldText.length(), data, spiBridge->getRootReference());
QString text = interface->textInterface()->text(0, interface->textInterface()->characterCount());
data.setVariant(QVariant::fromValue(text));
emit TextChanged("insert", 0, text.length(), data, spiBridge->getRootReference());
oldText = text;
QDBusVariant cursorData;
int pos = interface->textInterface()->cursorPosition();
cursorData.setVariant(QVariant::fromValue(pos));
emit TextCaretMoved(QString(), pos ,0, cursorData, spiBridge->getRootReference());
break;
}
case QAccessible::TextCaretMoved: {
Q_ASSERT(interface->textInterface());
qDebug() << "Text caret moved: " << interface->object();
QDBusVariant data;
int pos = interface->textInterface()->cursorPosition();
data.setVariant(QVariant::fromValue(pos));
emit TextCaretMoved(QString(), pos ,0, data, spiBridge->getRootReference());
break;
}
#endif
case QAccessible::ValueChanged: {
Q_ASSERT(interface->valueInterface());
QDBusVariant data;
data.setVariant(QVariant::fromValue(getReference()));
emit PropertyChange("accessible-value", 0, 0, data, spiBridge->getRootReference());
break;
}
case QAccessible::ObjectShow:
break;
case QAccessible::ObjectHide:
// TODO - send status changed
// qWarning() << "Object hide";
break;
case QAccessible::ObjectDestroyed:
// TODO - maybe send children-changed and cache Removed
// qWarning() << "Object destroyed";
break;
case QAccessible::StateChanged: {
QAccessible::State newState = interface->state(childIndex());
// qDebug() << "StateChanged: old: " << state << " new: " << newState << " xor: " << (state^newState);
if ((state^newState) & QAccessible::Checked) {
int checked = (newState & QAccessible::Checked) ? 1 : 0;
QDBusVariant data;
data.setVariant(QVariant::fromValue(getReference()));
emit StateChanged("checked", checked, 0, data, spiBridge->getRootReference());
}
state = newState;
break;
}
case QAccessible::TableModelChanged: {
// This is rather evil. We don't send data and hope that at-spi fetches the right child.
// This hack fails when a row gets removed and a different one added in its place.
QDBusVariant data;
emit ChildrenChanged("add", 0, 0, data, spiBridge->getRootReference());
break;
}
case QAccessible::ParentChanged:
// TODO - send parent changed
default:
// qWarning() << "QSpiAccessible::accessibleEvent not handled: " << QString::number(event, 16)
// << " obj: " << interface->object()
// << (interface->isValid() ? interface->object()->objectName() : " invalid interface!");
break;
}
}
void QSpiAccessible::windowActivated()
{
QDBusVariant data;
data.setVariant(QString());
emit Create("", 0, 0, data, spiBridge->getRootReference());
emit Restore("", 0, 0, data, spiBridge->getRootReference());
emit Activate("", 0, 0, data, spiBridge->getRootReference());
}
<commit_msg>Row/column headers are components.<commit_after>/*
* D-Bus AT-SPI, Qt Adaptor
*
* Copyright 2009-2011 Nokia Corporation and/or its subsidiary(-ies).
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#include "accessible.h"
#include <QDBusPendingReply>
#include <QDebug>
#include <QtGui/QWidget>
#include <QAccessibleValueInterface>
#include "adaptor.h"
#include "bridge.h"
#include "cache.h"
#include "constant_mappings.h"
#include "generated/accessible_adaptor.h"
#include "generated/action_adaptor.h"
#include "generated/component_adaptor.h"
#include "generated/editable_text_adaptor.h"
#include "generated/event_adaptor.h"
#include "generated/socket_proxy.h"
#include "generated/table_adaptor.h"
#include "generated/text_adaptor.h"
#include "generated/value_adaptor.h"
#define ACCESSIBLE_CREATION_DEBUG
#define QSPI_REGISTRY_NAME "org.a11y.atspi.Registry"
QString QSpiAccessible::pathForObject(QObject *object)
{
Q_ASSERT(object);
return QSPI_OBJECT_PATH_PREFIX + QString::number(reinterpret_cast<size_t>(object));
}
QString QSpiAccessible::pathForInterface(QAccessibleInterface *interface, int childIndex)
{
QString path;
QAccessibleInterface* interfaceWithObject = interface;
while(!interfaceWithObject->object()) {
QAccessibleInterface* parentInterface;
interfaceWithObject->navigate(QAccessible::Ancestor, 1, &parentInterface);
Q_ASSERT(parentInterface->isValid());
int index = parentInterface->indexOfChild(interfaceWithObject);
//Q_ASSERT(index >= 0);
// FIXME: This should never happen!
if (index < 0) {
index = 999;
path.prepend("/BROKEN_OBJECT_HIERARCHY");
qWarning() << "Object claims to have child that we cannot navigate to. FIX IT!" << parentInterface->object();
qDebug() << "Original interface: " << interface->object() << index;
qDebug() << "Parent interface: " << parentInterface->object() << " childcount:" << parentInterface->childCount();
QObject* p = parentInterface->object();
qDebug() << p->children();
QAccessibleInterface* tttt;
int id = parentInterface->navigate(QAccessible::Child, 1, &tttt);
qDebug() << "Nav child: " << id << tttt->object();
}
path.prepend('/' + QString::number(index));
interfaceWithObject = parentInterface;
}
path.prepend(QSPI_OBJECT_PATH_PREFIX + QString::number(reinterpret_cast<quintptr>(interfaceWithObject->object())));
if (childIndex > 0) {
path.append('/' + QString::number(childIndex));
}
return path;
}
QPair<QAccessibleInterface*, int> QSpiAccessible::interfaceFromPath(const QString& dbusPath)
{
QStringList parts = dbusPath.split('/');
Q_ASSERT(parts.size() > 5);
// ignore the first /org/a11y/atspi/accessible/
QString objectString = parts.at(5);
quintptr uintptr = objectString.toULongLong();
if (!uintptr)
return QPair<QAccessibleInterface*, int>(0, 0);
QObject* object = reinterpret_cast<QObject*>(uintptr);
qDebug() << object;
QAccessibleInterface* inter = QAccessible::queryAccessibleInterface(object);
QAccessibleInterface* childInter;
int index = 0;
for (int i = 6; i < parts.size(); ++i) {
index = inter->navigate(QAccessible::Child, parts.at(i).toInt(), &childInter);
if (index == 0) {
delete inter;
inter = childInter;
}
}
return QPair<QAccessibleInterface*, int>(inter, index);
}
QSpiAccessible::QSpiAccessible(QAccessibleInterface *interface, int index)
: QSpiAdaptor(interface, index)
{
QString path = pathForInterface(interface, index);
QDBusObjectPath dbusPath = QDBusObjectPath(path);
reference = QSpiObjectReference(spiBridge->dBusConnection(),
dbusPath);
#ifdef ACCESSIBLE_CREATION_DEBUG
qDebug() << "ACCESSIBLE: " << interface->object() << reference.path.path() << interface->text(QAccessible::Name, index) << qSpiRoleMapping[interface->role(index)].name();
#endif
new AccessibleAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_ACCESSIBLE;
if ( (!interface->rect(index).isEmpty()) ||
(interface->object() && interface->object()->isWidgetType()) ||
(interface->role(index) == QAccessible::ListItem) ||
(interface->role(index) == QAccessible::Cell) ||
(interface->role(index) == QAccessible::TreeItem) ||
(interface->role(index) == QAccessible::Row) ||
(interface->role(index) == QAccessible::RowHeader) ||
(interface->role(index) == QAccessible::ColumnHeader) ||
(interface->object() && interface->object()->inherits("QSGItem"))
) {
new ComponentAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_COMPONENT;
if (interface->object() && interface->object()->isWidgetType()) {
QWidget *w = qobject_cast<QWidget*>(interface->object());
if (w->isWindow()) {
new WindowAdaptor(this);
#ifdef ACCESSIBLE_CREATION_DEBUG
qDebug() << " IS a window";
#endif
}
}
}
#ifdef ACCESSIBLE_CREATION_DEBUG
else {
qDebug() << " IS NOT a component";
}
#endif
new ObjectAdaptor(this);
new FocusAdaptor(this);
if (interface->actionInterface())
{
new ActionAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_ACTION;
}
if (interface->textInterface())
{
new TextAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_TEXT;
oldText = interface->textInterface()->text(0, interface->textInterface()->characterCount());
}
if (interface->editableTextInterface())
{
new EditableTextAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_EDITABLE_TEXT;
}
if (interface->valueInterface())
{
new ValueAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_VALUE;
}
if (interface->table2Interface())
{
new TableAdaptor(this);
supportedInterfaces << QSPI_INTERFACE_TABLE;
}
spiBridge->dBusConnection().registerObject(reference.path.path(),
this, QDBusConnection::ExportAdaptors);
state = interface->state(childIndex());
}
QSpiObjectReference QSpiAccessible::getParentReference() const
{
Q_ASSERT(interface);
if (interface->isValid()) {
QAccessibleInterface *parentInterface = 0;
interface->navigate(QAccessible::Ancestor, 1, &parentInterface);
if (parentInterface) {
QSpiAdaptor *parent = spiBridge->objectToAccessible(parentInterface->object());
delete parentInterface;
if (parent)
return parent->getReference();
}
}
qWarning() << "Invalid parent: " << interface << interface->object();
return QSpiObjectReference();
}
void QSpiAccessible::accessibleEvent(QAccessible::Event event)
{
Q_ASSERT(interface);
if (!interface->isValid()) {
spiBridge->removeAdaptor(this);
return;
}
switch (event) {
case QAccessible::NameChanged: {
QSpiObjectReference r = getReference();
QDBusVariant data;
data.setVariant(QVariant::fromValue(r));
emit PropertyChange("accessible-name", 0, 0, data, spiBridge->getRootReference());
break;
}
case QAccessible::DescriptionChanged: {
QSpiObjectReference r = getReference();
QDBusVariant data;
data.setVariant(QVariant::fromValue(r));
emit PropertyChange("accessible-description", 0, 0, data, spiBridge->getRootReference());
break;
}
case QAccessible::Focus: {
qDebug() << "Focus: " << getReference().path.path() << interface->object() << interface->text(QAccessible::Name, 0);
QDBusVariant data;
data.setVariant(QVariant::fromValue(getReference()));
emit StateChanged("focused", 1, 0, data, spiBridge->getRootReference());
emit Focus("", 0, 0, data, spiBridge->getRootReference());
break;
}
#if (QT_VERSION >= QT_VERSION_CHECK(4, 8, 0))
case QAccessible::TextUpdated: {
Q_ASSERT(interface->textInterface());
// at-spi doesn't have a proper text updated/changed, so remove all and re-add the new text
qDebug() << "Text changed: " << interface->object();
QDBusVariant data;
data.setVariant(QVariant::fromValue(oldText));
emit TextChanged("delete", 0, oldText.length(), data, spiBridge->getRootReference());
QString text = interface->textInterface()->text(0, interface->textInterface()->characterCount());
data.setVariant(QVariant::fromValue(text));
emit TextChanged("insert", 0, text.length(), data, spiBridge->getRootReference());
oldText = text;
QDBusVariant cursorData;
int pos = interface->textInterface()->cursorPosition();
cursorData.setVariant(QVariant::fromValue(pos));
emit TextCaretMoved(QString(), pos ,0, cursorData, spiBridge->getRootReference());
break;
}
case QAccessible::TextCaretMoved: {
Q_ASSERT(interface->textInterface());
qDebug() << "Text caret moved: " << interface->object();
QDBusVariant data;
int pos = interface->textInterface()->cursorPosition();
data.setVariant(QVariant::fromValue(pos));
emit TextCaretMoved(QString(), pos ,0, data, spiBridge->getRootReference());
break;
}
#endif
case QAccessible::ValueChanged: {
Q_ASSERT(interface->valueInterface());
QDBusVariant data;
data.setVariant(QVariant::fromValue(getReference()));
emit PropertyChange("accessible-value", 0, 0, data, spiBridge->getRootReference());
break;
}
case QAccessible::ObjectShow:
break;
case QAccessible::ObjectHide:
// TODO - send status changed
// qWarning() << "Object hide";
break;
case QAccessible::ObjectDestroyed:
// TODO - maybe send children-changed and cache Removed
// qWarning() << "Object destroyed";
break;
case QAccessible::StateChanged: {
QAccessible::State newState = interface->state(childIndex());
// qDebug() << "StateChanged: old: " << state << " new: " << newState << " xor: " << (state^newState);
if ((state^newState) & QAccessible::Checked) {
int checked = (newState & QAccessible::Checked) ? 1 : 0;
QDBusVariant data;
data.setVariant(QVariant::fromValue(getReference()));
emit StateChanged("checked", checked, 0, data, spiBridge->getRootReference());
}
state = newState;
break;
}
case QAccessible::TableModelChanged: {
// This is rather evil. We don't send data and hope that at-spi fetches the right child.
// This hack fails when a row gets removed and a different one added in its place.
QDBusVariant data;
emit ChildrenChanged("add", 0, 0, data, spiBridge->getRootReference());
break;
}
case QAccessible::ParentChanged:
// TODO - send parent changed
default:
// qWarning() << "QSpiAccessible::accessibleEvent not handled: " << QString::number(event, 16)
// << " obj: " << interface->object()
// << (interface->isValid() ? interface->object()->objectName() : " invalid interface!");
break;
}
}
void QSpiAccessible::windowActivated()
{
QDBusVariant data;
data.setVariant(QString());
emit Create("", 0, 0, data, spiBridge->getRootReference());
emit Restore("", 0, 0, data, spiBridge->getRootReference());
emit Activate("", 0, 0, data, spiBridge->getRootReference());
}
<|endoftext|>
|
<commit_before>
#include "VM.h"
#include <libevm/VMFace.h>
#include "ExecutionEngine.h"
#include "Compiler.h"
namespace dev
{
namespace eth
{
namespace jit
{
bytesConstRef VM::go(ExtVMFace& _ext, OnOpFunc const& _onOp, uint64_t _steps)
{
auto module = Compiler().compile(_ext.code);
ExecutionEngine engine;
auto exitCode = engine.run(std::move(module), m_gas, &_ext);
switch (exitCode)
{
case 101:
BOOST_THROW_EXCEPTION(BadJumpDestination());
case 102:
BOOST_THROW_EXCEPTION(OutOfGas());
case 103:
BOOST_THROW_EXCEPTION(StackTooSmall(1,0));
}
m_output = std::move(engine.returnData);
return {m_output.data(), m_output.size()}; // TODO: This all bytesConstRef stuff sucks
}
}
}
}
<commit_msg>Try not to use JIT in any interactive mode<commit_after>
#include "VM.h"
#include <libevm/VMFace.h>
#include "ExecutionEngine.h"
#include "Compiler.h"
namespace dev
{
namespace eth
{
namespace jit
{
bytesConstRef VM::go(ExtVMFace& _ext, OnOpFunc const& _onOp, uint64_t _steps)
{
assert(_onOp == nullptr); // Parameter ignored
assert(_steps == (uint64_t)-1); // Parameter ignored
auto module = Compiler().compile(_ext.code);
ExecutionEngine engine;
auto exitCode = engine.run(std::move(module), m_gas, &_ext);
switch (exitCode)
{
case 101:
BOOST_THROW_EXCEPTION(BadJumpDestination());
case 102:
BOOST_THROW_EXCEPTION(OutOfGas());
case 103:
BOOST_THROW_EXCEPTION(StackTooSmall(1,0));
}
m_output = std::move(engine.returnData);
return {m_output.data(), m_output.size()}; // TODO: This all bytesConstRef stuff sucks
}
}
}
}
<|endoftext|>
|
<commit_before>#ifndef __CONSOLE_HPP_INCLUDED
#define __CONSOLE_HPP_INCLUDED
#include "code/ylikuutio/callback_system/key_and_callback_struct.hpp"
#include "code/ylikuutio/callback_system/callback_parameter.hpp"
#include "code/ylikuutio/callback_system/callback_object.hpp"
#include "code/ylikuutio/callback_system/callback_engine.hpp"
#include "code/ylikuutio/common/any_value.hpp"
#include "code/ylikuutio/ontology/font2D.hpp"
// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif
// Include standard headers
#include <list> // std::list
#include <stdint.h> // uint32_t etc.
#include <vector> // std::vector
namespace console
{
class Console
{
public:
// constructor.
Console(std::vector<KeyAndCallbackStruct>** current_keypress_callback_engine_vector_pointer_pointer,
std::vector<KeyAndCallbackStruct>** current_keyrelease_callback_engine_vector_pointer_pointer,
ontology::Font2D* text2D_pointer);
// destructor.
~Console();
void set_my_keypress_callback_engine_vector_pointer(std::vector<KeyAndCallbackStruct>* my_keypress_callback_engine_vector_pointer);
void set_my_keyrelease_callback_engine_vector_pointer(std::vector<KeyAndCallbackStruct>* my_keyrelease_callback_engine_vector_pointer);
void draw_console();
// callbacks.
static void charmods_callback(GLFWwindow* window, unsigned int codepoint, int mods);
static datatypes::AnyValue* enable_enter_console(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* enable_exit_console(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* release_left_control_in_console(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* release_right_control_in_console(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* release_left_alt_in_console(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* release_right_alt_in_console(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* release_left_shift_in_console(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* release_right_shift_in_console(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* enable_move_to_previous_input(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* enable_move_to_next_input(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* enable_backspace(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* enable_enter_key(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* enable_ctrl_c(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* enter_console(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* exit_console(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* press_left_control_in_console(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* press_right_control_in_console(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* press_left_alt_in_console(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* press_right_alt_in_console(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* press_left_shift_in_console(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* press_right_shift_in_console(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* move_to_previous_input(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* move_to_next_input(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* backspace(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* ctrl_c(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* enter_key(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
private:
void copy_historical_input_into_current_input();
bool exit_console();
void delete_character();
void move_cursor_left();
void move_cursor_right();
void move_cursor_to_start_of_line();
void move_cursor_to_end_of_line();
void page_up();
void page_down();
void home();
void end();
std::list<char> current_input; // This is used for actual inputs.
std::list<char>::iterator cursor_it;
uint32_t cursor_index;
bool in_console;
bool can_enter_console;
bool can_exit_console;
bool can_move_to_previous_input;
bool can_move_to_next_input;
bool can_backspace;
bool can_enter_key;
bool can_ctrl_c;
bool is_left_control_pressed;
bool is_right_control_pressed;
bool is_left_alt_pressed;
bool is_right_alt_pressed;
bool is_left_shift_pressed;
bool is_right_shift_pressed;
std::vector<std::list<char>> command_history;
bool in_historical_input;
uint32_t historical_input_i;
std::list<char> temp_input; // This is used for temporary storage of new input while modifying historical inputs.
// These are related to keypress callbacks.
std::vector<KeyAndCallbackStruct>** current_keypress_callback_engine_vector_pointer_pointer;
std::vector<KeyAndCallbackStruct>* previous_keypress_callback_engine_vector_pointer;
std::vector<KeyAndCallbackStruct>* my_keypress_callback_engine_vector_pointer;
// These are related to keyrelease callbacks.
std::vector<KeyAndCallbackStruct>** current_keyrelease_callback_engine_vector_pointer_pointer;
std::vector<KeyAndCallbackStruct>* previous_keyrelease_callback_engine_vector_pointer;
std::vector<KeyAndCallbackStruct>* my_keyrelease_callback_engine_vector_pointer;
// This is a pointer to `font2D::Font2D` instance that is used for printing.
ontology::Font2D* text2D_pointer;
};
}
#endif
<commit_msg>Reordered code lines and added comments.<commit_after>#ifndef __CONSOLE_HPP_INCLUDED
#define __CONSOLE_HPP_INCLUDED
#include "code/ylikuutio/callback_system/key_and_callback_struct.hpp"
#include "code/ylikuutio/callback_system/callback_parameter.hpp"
#include "code/ylikuutio/callback_system/callback_object.hpp"
#include "code/ylikuutio/callback_system/callback_engine.hpp"
#include "code/ylikuutio/common/any_value.hpp"
#include "code/ylikuutio/ontology/font2D.hpp"
// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif
// Include standard headers
#include <list> // std::list
#include <stdint.h> // uint32_t etc.
#include <vector> // std::vector
namespace console
{
class Console
{
public:
// constructor.
Console(std::vector<KeyAndCallbackStruct>** current_keypress_callback_engine_vector_pointer_pointer,
std::vector<KeyAndCallbackStruct>** current_keyrelease_callback_engine_vector_pointer_pointer,
ontology::Font2D* text2D_pointer);
// destructor.
~Console();
void set_my_keypress_callback_engine_vector_pointer(std::vector<KeyAndCallbackStruct>* my_keypress_callback_engine_vector_pointer);
void set_my_keyrelease_callback_engine_vector_pointer(std::vector<KeyAndCallbackStruct>* my_keyrelease_callback_engine_vector_pointer);
void draw_console();
// Callbacks.
static void charmods_callback(GLFWwindow* window, unsigned int codepoint, int mods);
// Action mode keyrelease callbacks begin here.
static datatypes::AnyValue* enable_enter_console(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
// Action mode keypress callbacks begin here.
static datatypes::AnyValue* enter_console(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
// Console mode keyrelease callbacks begin here.
static datatypes::AnyValue* enable_exit_console(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* release_left_control_in_console(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* release_right_control_in_console(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* release_left_alt_in_console(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* release_right_alt_in_console(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* release_left_shift_in_console(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* release_right_shift_in_console(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* enable_move_to_previous_input(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* enable_move_to_next_input(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* enable_backspace(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* enable_enter_key(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* enable_ctrl_c(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
// Console mode keypress callbacks begin here.
static datatypes::AnyValue* exit_console(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* press_left_control_in_console(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* press_right_control_in_console(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* press_left_alt_in_console(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* press_right_alt_in_console(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* press_left_shift_in_console(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* press_right_shift_in_console(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* move_to_previous_input(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* move_to_next_input(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* backspace(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* enter_key(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
static datatypes::AnyValue* ctrl_c(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*>&,
console::Console* console);
// Callbacks end here.
private:
void copy_historical_input_into_current_input();
bool exit_console();
void delete_character();
void move_cursor_left();
void move_cursor_right();
void move_cursor_to_start_of_line();
void move_cursor_to_end_of_line();
void page_up();
void page_down();
void home();
void end();
std::list<char> current_input; // This is used for actual inputs.
std::list<char>::iterator cursor_it;
uint32_t cursor_index;
bool in_console;
bool can_enter_console;
bool can_exit_console;
bool can_move_to_previous_input;
bool can_move_to_next_input;
bool can_backspace;
bool can_enter_key;
bool can_ctrl_c;
bool is_left_control_pressed;
bool is_right_control_pressed;
bool is_left_alt_pressed;
bool is_right_alt_pressed;
bool is_left_shift_pressed;
bool is_right_shift_pressed;
std::vector<std::list<char>> command_history;
bool in_historical_input;
uint32_t historical_input_i;
std::list<char> temp_input; // This is used for temporary storage of new input while modifying historical inputs.
// These are related to keypress callbacks.
std::vector<KeyAndCallbackStruct>** current_keypress_callback_engine_vector_pointer_pointer;
std::vector<KeyAndCallbackStruct>* previous_keypress_callback_engine_vector_pointer;
std::vector<KeyAndCallbackStruct>* my_keypress_callback_engine_vector_pointer;
// These are related to keyrelease callbacks.
std::vector<KeyAndCallbackStruct>** current_keyrelease_callback_engine_vector_pointer_pointer;
std::vector<KeyAndCallbackStruct>* previous_keyrelease_callback_engine_vector_pointer;
std::vector<KeyAndCallbackStruct>* my_keyrelease_callback_engine_vector_pointer;
// This is a pointer to `font2D::Font2D` instance that is used for printing.
ontology::Font2D* text2D_pointer;
};
}
#endif
<|endoftext|>
|
<commit_before><commit_msg>Bugfix: `Shader::get_number_of_apprentices`.<commit_after><|endoftext|>
|
<commit_before>#include <ast/op-expr.hh>
namespace ast
{
OpExpr::OpExpr(const yy::location& location,
Expr* lexpr,
OpExpr::Operator op,
Expr* rexpr)
: Expr(location)
, lexpr_(lexpr)
, rexpr_(rexpr)
, op_(op)
{}
OpExpr::~OpExpr()
{
delete lexpr_;
delete rexpr_;
}
const Expr* OpExpr::left_expr_get() const
{
return lexpr_;
}
Expr* OpExpr::left_expr_get()
{
return lexpr_;
}
const Expr* OpExpr::right_expr_get() const
{
return rexpr_;
}
Expr* OpExpr::right_expr_get()
{
return rexpr_;
}
OpExpr::Operator OpExpr::op_get() const
{
return op_;
}
std::string OpExpr::op_to_string() const
{
switch (op_)
{
case PLUS:
return "+";
case MINUS:
return "-";
case MULT:
return "*";
case DIV:
return "/";
case FDIV:
return "//";
case MOD:
return "%";
case POW:
return "**";
case RSHIFT:
return ">>";
case LSHIFT:
return "<<";
case XOR:
return "^";
case BOOL_AND:
return "and";
case BOOL_OR:
return "or";
case BIT_AND:
return "&";
case BIT_OR:
return "|";
case EQ:
return "==";
case NEQ:
return "!=";
case GT:
return ">";
case GE:
return ">=";
case LT:
return "<";
case LE:
return "<=";
case IN:
return "in";
case IS:
return "is";
case NOT_IN:
return "not in";
case IS_NOT:
return "is not";
}
return "";
}
std::string OpExpr::to_cpp() const
{
switch (op_)
{
case PLUS:
return "__repy::__add__";
case MINUS:
return "__repy::__sub__";
case MULT:
return "__repy::__mul__";
case DIV:
return "__repy::__divmod__";
case FDIV:
return "__repy::__floordiv__";
case MOD:
return "__repy::__mod__";
case POW:
return "__repy::__pow__";
case RSHIFT:
return "__repy::__lshift__";
case LSHIFT:
return "__repy::__rshift__";
case XOR:
return "__repy::__xor__";
case BIT_AND:
return "__repy::__and__";
case BIT_OR:
return "__repy::__or__";
case EQ:
return "__repy::__eq__";
case NEQ:
return "__repy::__ne__";
case GT:
return "__repy::__gt__";
case GE:
return "__repy::__ge__";
case LT:
return "__repy::__lt__";
case LE:
return "__repy::__le__";
default:
assert(false && "Internal compiler error");
break;
}
return "";
}
void OpExpr::set_left_expr(Expr* expr)
{
if (lexpr_ == nullptr)
{
lexpr_ = expr;
return;
}
OpExpr* e = dynamic_cast<OpExpr*> (lexpr_);
if (e)
e->set_left_expr(expr);
}
void OpExpr::accept(Visitor& v)
{
v(*this);
}
void OpExpr::accept(ConstVisitor& v) const
{
v(*this);
}
} // namespace ast
<commit_msg>[AST] Update operator generation<commit_after>#include <ast/op-expr.hh>
namespace ast
{
OpExpr::OpExpr(const yy::location& location,
Expr* lexpr,
OpExpr::Operator op,
Expr* rexpr)
: Expr(location)
, lexpr_(lexpr)
, rexpr_(rexpr)
, op_(op)
{}
OpExpr::~OpExpr()
{
delete lexpr_;
delete rexpr_;
}
const Expr* OpExpr::left_expr_get() const
{
return lexpr_;
}
Expr* OpExpr::left_expr_get()
{
return lexpr_;
}
const Expr* OpExpr::right_expr_get() const
{
return rexpr_;
}
Expr* OpExpr::right_expr_get()
{
return rexpr_;
}
OpExpr::Operator OpExpr::op_get() const
{
return op_;
}
std::string OpExpr::op_to_string() const
{
switch (op_)
{
case PLUS:
return "+";
case MINUS:
return "-";
case MULT:
return "*";
case DIV:
return "/";
case FDIV:
return "//";
case MOD:
return "%";
case POW:
return "**";
case RSHIFT:
return ">>";
case LSHIFT:
return "<<";
case XOR:
return "^";
case BOOL_AND:
return "and";
case BOOL_OR:
return "or";
case BIT_AND:
return "&";
case BIT_OR:
return "|";
case EQ:
return "==";
case NEQ:
return "!=";
case GT:
return ">";
case GE:
return ">=";
case LT:
return "<";
case LE:
return "<=";
case IN:
return "in";
case IS:
return "is";
case NOT_IN:
return "not in";
case IS_NOT:
return "is not";
}
return "";
}
std::string OpExpr::to_cpp() const
{
switch (op_)
{
case PLUS:
return "repy::__add__";
case MINUS:
return "repy::__sub__";
case MULT:
return "repy::__mul__";
case DIV:
return "repy::__divmod__";
case FDIV:
return "repy::__floordiv__";
case MOD:
return "repy::__mod__";
case POW:
return "repy::__pow__";
case RSHIFT:
return "repy::__lshift__";
case LSHIFT:
return "repy::__rshift__";
case XOR:
return "repy::__xor__";
case BIT_AND:
return "repy::__and__";
case BIT_OR:
return "repy::__or__";
case EQ:
return "repy::__eq__";
case NEQ:
return "repy::__ne__";
case GT:
return "repy::__gt__";
case GE:
return "repy::__ge__";
case LT:
return "repy::__lt__";
case LE:
return "repy::__le__";
default:
assert(false && "Internal compiler error");
break;
}
return "";
}
void OpExpr::set_left_expr(Expr* expr)
{
if (lexpr_ == nullptr)
{
lexpr_ = expr;
return;
}
OpExpr* e = dynamic_cast<OpExpr*> (lexpr_);
if (e)
e->set_left_expr(expr);
}
void OpExpr::accept(Visitor& v)
{
v(*this);
}
void OpExpr::accept(ConstVisitor& v) const
{
v(*this);
}
} // namespace ast
<|endoftext|>
|
<commit_before>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2010-2015 Belledonne Communications SARL, All rights reserved.
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/>.
*/
#define SU_MSG_ARG_T struct auth_splugin_t
#include "authdb.hh"
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
void FileAuthDb::parsePasswd(string *pass, string user, string domain, passwd_algo_t *password) {
// parse password and calcul passmd5, passsha256 if there is clrtxt pass.
int i;
for (i = 0; i < 3; i++) {
if (pass[i].substr(0, 7) == "clrtxt:") {
password->pass = pass[i].substr(7);
}
}
if (password->pass != "") {
string input;
input = user + ":" + domain + ":" + password->pass;
password->passmd5 = syncMd5(input.c_str(), 16);
password->passsha256 = syncSha256(input.c_str(), 32);
return;
}
for (i = 0; i < 3; i++) {
if (pass[i].substr(0, 4) == "md5:") {
password->passmd5 = pass[i].substr(4);
}
if (pass[i].substr(0, 7) == "sha256:") {
password->passsha256 = pass[i].substr(7);
}
}
}
FileAuthDb::FileAuthDb() {
GenericStruct *cr = GenericManager::get()->getRoot();
GenericStruct *ma = cr->get<GenericStruct>("module::Authentication");
mLastSync = 0;
mFileString = ma->get<ConfigString>("datasource")->read();
sync();
}
void FileAuthDb::getUserWithPhoneFromBackend(const std::string &phone, const std::string &domain, AuthDbListener *listener) {
AuthDbResult res = AuthDbResult::PASSWORD_NOT_FOUND;
if (mLastSync == 0) {
sync();
}
std::string user;
if (getCachedUserWithPhone(phone, domain, user) == VALID_PASS_FOUND) {
res = AuthDbResult::PASSWORD_FOUND;
}
if (listener) listener->onResult(res, user);
}
void FileAuthDb::getPasswordFromBackend(const std::string &id, const std::string &domain,
const std::string &authid, AuthDbListener *listener) {
AuthDbResult res = AuthDbResult::PASSWORD_NOT_FOUND;
time_t now = getCurrentTime();
if (difftime(now, mLastSync) >= mCacheExpire) {
sync();
}
string key(createPasswordKey(id, authid));
passwd_algo_t passwd;
if (getCachedPassword(key, domain, passwd) == VALID_PASS_FOUND) {
res = AuthDbResult::PASSWORD_FOUND;
}
if (listener) listener->onResult(res, passwd);
}
/*
* The following ABNF grammar should describe the syntax of the password file:
token = 1*(alphanum / "-" / "." / "!" / "%" / "*" / "_" / "+" / "`" / "'" / "~" )
user-id = token
phone = token
user = token
domain = token
algo = "clrtxt" / "md5" / "sha256"
identity = user "@" domain
auth-line = identity 1*WSP 1*(algo ":" token) 1*WSP ";" 1*WSP [user-id] 1*WSP [phone]
ctext = %x21-27 / %x2A-5B / %x5D-7E / UTF8-NONASCII
/ LWS
comment = "#" *ctext LF
void = *WSP LF
password-file = "version:0" LF *(comment | void | auth-line)
*/
void FileAuthDb::sync() {
LOGD("Syncing password file");
GenericStruct *cr = GenericManager::get()->getRoot();
GenericStruct *ma = cr->get<GenericStruct>("module::Authentication");
list<string> domains = ma->get<ConfigStringList>("auth-domains")->read();
bool firstTime = false;
if (mLastSync == 0) firstTime = true;
mLastSync = getCurrentTime();
ifstream file;
stringstream ss;
ss.exceptions(ifstream::failbit | ifstream::badbit);
string line;
string user;
string domain;
passwd_algo_t password;
string userid;
string phone;
string pass[3];
string version;
string passwd_tag;
int i;
if (mFileString.empty()){
LOGF("'file' authentication backend was requested but no path specified in datasource.");
return;
}
LOGD("Opening file %s", mFileString.c_str());
file.open(mFileString);
if (file.is_open()) {
while (file.good() && getline(file, line)) {
if (line.empty()) continue;
ss.clear();
ss.str(line);
version.clear();
getline(ss, version, ' ');
if (version.substr(0, 8) == "version:")
version = version.substr(8);
else
LOGF("%s file must start with version:X.", mFileString.c_str());
break;
}
if (version == "1") {
while (file.good() && getline(file, line)) {
if (line.empty()) continue;
ss.clear();
ss.str(line);
user.clear();
domain.clear();
pass[0].clear();
pass[1].clear();
pass[2].clear();
password.pass.clear();
password.passmd5.clear();
password.passsha256.clear();
userid.clear();
phone.clear();
try {
getline(ss, user, '@');
getline(ss, domain, ' ');
for (i = 0; i < 3 && (!ss.eof()); i++) {
passwd_tag.clear();
getline(ss, passwd_tag, ' ');
if (passwd_tag != ";")
pass[i] = passwd_tag;
else break;
}
if (passwd_tag != ";") {
if (ss.eof()){
LOGF("%s: unterminated password section at line '%s'. Missing ';'.", mFileString.c_str(), line.c_str());
}else {
passwd_tag.clear();
getline(ss, passwd_tag, ' ');
if ((!ss.eof()) && (passwd_tag != ";")){
LOGF("%s: unterminated password section at line '%s'. Missing ';'.", mFileString.c_str(), line.c_str());
}
}
}
// if user with space, replace %20 by space
string user_ref=user;
user_ref.reserve(user.size());
url_unescape(&user_ref[0], user.c_str());
if (!ss.eof()) {
// TODO read userid with space
getline(ss, userid, ' ');
if (!ss.eof()) {
getline(ss, phone);
} else {
phone = "";
}
} else {
userid = user_ref;
phone = "";
}
cacheUserWithPhone(phone, domain, user);
parsePasswd(pass, user_ref, domain, &password);
if (find(domains.begin(), domains.end(), domain) != domains.end()) {
string key(createPasswordKey(user, userid));
cachePassword(key, domain, password, mCacheExpire);
} else if (find(domains.begin(), domains.end(), "*") != domains.end()) {
string key(createPasswordKey(user, userid));
cachePassword(key, domain, password, mCacheExpire);
} else {
LOGW("Domain '%s' is not handled by Authentication module", domain.c_str());
}
} catch (const stringstream::failure &e) {
LOGW("Incorrect line format: %s (error: %s)", line.c_str(), e.what());
}
}
} else {
LOGF("Version %s is not supported for file %s", version.c_str(), mFileString.c_str());
}
} else {
if (firstTime){
LOGF("Can't open file %s", mFileString.c_str());
}else{
LOGE("Can't open file %s", mFileString.c_str());
}
}
LOGD("Syncing done");
}
<commit_msg>fix uninitialized username again<commit_after>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2010-2015 Belledonne Communications SARL, All rights reserved.
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/>.
*/
#define SU_MSG_ARG_T struct auth_splugin_t
#include "authdb.hh"
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
void FileAuthDb::parsePasswd(string *pass, string user, string domain, passwd_algo_t *password) {
// parse password and calcul passmd5, passsha256 if there is clrtxt pass.
int i;
for (i = 0; i < 3; i++) {
if (pass[i].substr(0, 7) == "clrtxt:") {
password->pass = pass[i].substr(7);
}
}
if (password->pass != "") {
string input;
input = user + ":" + domain + ":" + password->pass;
password->passmd5 = syncMd5(input.c_str(), 16);
password->passsha256 = syncSha256(input.c_str(), 32);
return;
}
for (i = 0; i < 3; i++) {
if (pass[i].substr(0, 4) == "md5:") {
password->passmd5 = pass[i].substr(4);
}
if (pass[i].substr(0, 7) == "sha256:") {
password->passsha256 = pass[i].substr(7);
}
}
}
FileAuthDb::FileAuthDb() {
GenericStruct *cr = GenericManager::get()->getRoot();
GenericStruct *ma = cr->get<GenericStruct>("module::Authentication");
mLastSync = 0;
mFileString = ma->get<ConfigString>("datasource")->read();
sync();
}
void FileAuthDb::getUserWithPhoneFromBackend(const std::string &phone, const std::string &domain, AuthDbListener *listener) {
AuthDbResult res = AuthDbResult::PASSWORD_NOT_FOUND;
if (mLastSync == 0) {
sync();
}
std::string user;
if (getCachedUserWithPhone(phone, domain, user) == VALID_PASS_FOUND) {
res = AuthDbResult::PASSWORD_FOUND;
}
if (listener) listener->onResult(res, user);
}
void FileAuthDb::getPasswordFromBackend(const std::string &id, const std::string &domain,
const std::string &authid, AuthDbListener *listener) {
AuthDbResult res = AuthDbResult::PASSWORD_NOT_FOUND;
time_t now = getCurrentTime();
if (difftime(now, mLastSync) >= mCacheExpire) {
sync();
}
string key(createPasswordKey(id, authid));
passwd_algo_t passwd;
if (getCachedPassword(key, domain, passwd) == VALID_PASS_FOUND) {
res = AuthDbResult::PASSWORD_FOUND;
}
if (listener) listener->onResult(res, passwd);
}
/*
* The following ABNF grammar should describe the syntax of the password file:
token = 1*(alphanum / "-" / "." / "!" / "%" / "*" / "_" / "+" / "`" / "'" / "~" )
user-id = token
phone = token
user = token
domain = token
algo = "clrtxt" / "md5" / "sha256"
identity = user "@" domain
auth-line = identity 1*WSP 1*(algo ":" token) 1*WSP ";" 1*WSP [user-id] 1*WSP [phone]
ctext = %x21-27 / %x2A-5B / %x5D-7E / UTF8-NONASCII
/ LWS
comment = "#" *ctext LF
void = *WSP LF
password-file = "version:0" LF *(comment | void | auth-line)
*/
void FileAuthDb::sync() {
LOGD("Syncing password file");
GenericStruct *cr = GenericManager::get()->getRoot();
GenericStruct *ma = cr->get<GenericStruct>("module::Authentication");
list<string> domains = ma->get<ConfigStringList>("auth-domains")->read();
bool firstTime = false;
if (mLastSync == 0) firstTime = true;
mLastSync = getCurrentTime();
ifstream file;
stringstream ss;
ss.exceptions(ifstream::failbit | ifstream::badbit);
string line;
string user;
string domain;
passwd_algo_t password;
string userid;
string phone;
string pass[3];
string version;
string passwd_tag;
int i;
if (mFileString.empty()){
LOGF("'file' authentication backend was requested but no path specified in datasource.");
return;
}
LOGD("Opening file %s", mFileString.c_str());
file.open(mFileString);
if (file.is_open()) {
while (file.good() && getline(file, line)) {
if (line.empty()) continue;
ss.clear();
ss.str(line);
version.clear();
getline(ss, version, ' ');
if (version.substr(0, 8) == "version:")
version = version.substr(8);
else
LOGF("%s file must start with version:X.", mFileString.c_str());
break;
}
if (version == "1") {
while (file.good() && getline(file, line)) {
if (line.empty()) continue;
ss.clear();
ss.str(line);
user.clear();
domain.clear();
pass[0].clear();
pass[1].clear();
pass[2].clear();
password.pass.clear();
password.passmd5.clear();
password.passsha256.clear();
userid.clear();
phone.clear();
try {
getline(ss, user, '@');
getline(ss, domain, ' ');
for (i = 0; i < 3 && (!ss.eof()); i++) {
passwd_tag.clear();
getline(ss, passwd_tag, ' ');
if (passwd_tag != ";")
pass[i] = passwd_tag;
else break;
}
if (passwd_tag != ";") {
if (ss.eof()){
LOGF("%s: unterminated password section at line '%s'. Missing ';'.", mFileString.c_str(), line.c_str());
}else {
passwd_tag.clear();
getline(ss, passwd_tag, ' ');
if ((!ss.eof()) && (passwd_tag != ";")){
LOGF("%s: unterminated password section at line '%s'. Missing ';'.", mFileString.c_str(), line.c_str());
}
}
}
// if user with space, replace %20 by space
string user_ref;
user_ref.resize(user.size());
url_unescape(&user_ref[0], user.c_str());
user_ref.resize(strlen(&user_ref[0]));
if (!ss.eof()) {
// TODO read userid with space
getline(ss, userid, ' ');
if (!ss.eof()) {
getline(ss, phone);
} else {
phone = "";
}
} else {
userid = user_ref;
phone = "";
}
cacheUserWithPhone(phone, domain, user);
parsePasswd(pass, user_ref, domain, &password);
if (find(domains.begin(), domains.end(), domain) != domains.end()) {
string key(createPasswordKey(user, userid));
cachePassword(key, domain, password, mCacheExpire);
} else if (find(domains.begin(), domains.end(), "*") != domains.end()) {
string key(createPasswordKey(user, userid));
cachePassword(key, domain, password, mCacheExpire);
} else {
LOGW("Domain '%s' is not handled by Authentication module", domain.c_str());
}
} catch (const stringstream::failure &e) {
LOGW("Incorrect line format: %s (error: %s)", line.c_str(), e.what());
}
}
} else {
LOGF("Version %s is not supported for file %s", version.c_str(), mFileString.c_str());
}
} else {
if (firstTime){
LOGF("Can't open file %s", mFileString.c_str());
}else{
LOGE("Can't open file %s", mFileString.c_str());
}
}
LOGD("Syncing done");
}
<|endoftext|>
|
<commit_before>/****************************************************************/
/* */
/* Implementation of Cardiac Tissue elasticity as given in */
/* [Whiteley2007] */
/* */
/****************************************************************/
#include "CardiacWhiteley2007Material.h"
#include "ColumnMajorMatrix.h"
#include "CardiacSolidMechanicsMaterial.h"
#include "SymmOrthotropicElasticityTensor.h"
#include "VolumetricModel.h"
template<>
InputParameters validParams<CardiacWhiteley2007Material>()
{
InputParameters params = validParams<CardiacSolidMechanicsMaterial>();
params.addRequiredParam<std::vector<Real> >("k_MN", "Material parameters k_MN in following order: k_11, k_22, k_33, k_12, k_23, k_13");
params.addRequiredParam<std::vector<Real> >("a_MN", "Material parameters a_MN in following order: a_11, a_22, a_33, a_12, a_23, a_13");
params.addRequiredParam<std::vector<Real> >("b_MN", "Material parameters b_MN in following order: b_11, b_22, b_33, b_12, b_23, b_13");
params.addCoupledVar("Ta", 0, "The (position dependent) active tension in fibre direction that will finally drive contraction, see (8) in [Whiteley 2007]. Default is Ta=0, i.e. no active tension anywhere.");
return params;
}
CardiacWhiteley2007Material::CardiacWhiteley2007Material(const std::string & name,
InputParameters parameters)
:CardiacSolidMechanicsMaterial(name, parameters),
_k(SymmTensor(getParam<std::vector<Real> >("k_MN"))),
_a(SymmTensor(getParam<std::vector<Real> >("a_MN"))),
_b(SymmTensor(getParam<std::vector<Real> >("b_MN"))),
_Rf(getMaterialProperty<RealTensorValue>("R_fibre")),
_has_Ta(isCoupled("Ta")),
_Ta(coupledValue("Ta")),
_id(1, 1, 1, 0, 0, 0)
{}
const RealTensorValue CardiacWhiteley2007Material::fromSymm(const SymmTensor & A)
{
RealTensorValue B;
B(1,1) = A(1,1);
B(2,2) = A(2,2);
B(3,3) = A(3,3);
B(1,2) = B(2,1) = A(1,2);
B(1,3) = B(3,1) = A(1,3);
B(2,3) = B(3,2) = A(2,3);
return B;
}
/*
* computes outer.transpose() * inner * outer
* TODO: this should be possible in a much more efficient way
*/
const SymmTensor CardiacWhiteley2007Material::symmProd(const RealTensorValue & outer, const SymmTensor & inner)
{
RealTensorValue in(fromSymm(inner));
RealTensorValue r(outer.transpose() * in * outer);
return SymmTensor(r(0,0), r(1,1), r(2,2), r(0,1), r(1,2), r(0,2) );
}
void
CardiacWhiteley2007Material::computeQpProperties()
{
// TODO: verify that all rotations are done in the correct direction, i.e. where do you have to use _Rf or _Rf.transpose() ?
// local deformation gradient tensor: insert displacement gradient row-wise
const RealTensorValue F(_grad_disp_x[_qp],
_grad_disp_y[_qp],
_grad_disp_z[_qp]);
// Cauchy-Green deformation tensor
const SymmTensor C(symmProd(F, _id));
// Lagrange-Green strain tensor
const SymmTensor E( (C - _id) * 0.5 );
// Lagrange-Green strain tensor in fibre coordinates
const SymmTensor Estar(symmProd(_Rf[_qp], E));
// Derivative of strain energy density W wrt Estar
SymmTensor dWdE;
for (int i=0;i<3;i++)
for (int j=i;j<3;j++)
if (Estar(i,j) > 0) {
const Real d(abs(_a(i,j) - Estar(i,j)));
dWdE(i,j) = _k(i, j) * Estar(i,j) / pow(d, _b(i,j)) * ( 2 + _b(i,j)*Estar(i,j)/d );
} else
dWdE(i,j) = 0.;
// rotate back into outer coordinate system
dWdE = symmProd(_Rf[_qp].transpose(), dWdE);
const Real p = 0; // TODO: p is the hydrostatic pressure / Lagrange multiplier to guarantee incompressibility
_stress[_qp] = _id*(-p) + symmProd(F.transpose(), dWdE);
// compute active tension in fibre direction, rotate into outer coordinates and add to stress if necessary
if (_has_Ta) {
SymmTensor Ta( symmProd( _Rf[_qp], SymmTensor(_Ta[_qp], 0, 0, 0, 0, 0) ) );
_stress[_qp] += Ta;
}
/* TODO: currently, though being possibly required (e.g. by the StressDivergence kernel), we do not set the following
// store elasticity tensor as material property...
_elasticity_tensor[_qp] =
//Jacobian multiplier of the stress
_Jacobian_mult[_qp] =
// Save off the elastic strain
_elastic_strain[_qp] = SymmTensor( _grad_disp_x[_qp](0),
_grad_disp_y[_qp](1),
_grad_disp_z[_qp](2),
0.5*(_grad_disp_x[_qp](1)+_grad_disp_y[_qp](0)),
0.5*(_grad_disp_y[_qp](2)+_grad_disp_z[_qp](1)),
0.5*(_grad_disp_z[_qp](0)+_grad_disp_x[_qp](2)) );;
*/
}
<commit_msg>fixed indexing error: Fortran starts with one, but who cares for Fortran - we are in C++here...<commit_after>/****************************************************************/
/* */
/* Implementation of Cardiac Tissue elasticity as given in */
/* [Whiteley2007] */
/* */
/****************************************************************/
#include "CardiacWhiteley2007Material.h"
#include "ColumnMajorMatrix.h"
#include "CardiacSolidMechanicsMaterial.h"
#include "SymmOrthotropicElasticityTensor.h"
#include "VolumetricModel.h"
template<>
InputParameters validParams<CardiacWhiteley2007Material>()
{
InputParameters params = validParams<CardiacSolidMechanicsMaterial>();
params.addRequiredParam<std::vector<Real> >("k_MN", "Material parameters k_MN in following order: k_11, k_22, k_33, k_12, k_23, k_13");
params.addRequiredParam<std::vector<Real> >("a_MN", "Material parameters a_MN in following order: a_11, a_22, a_33, a_12, a_23, a_13");
params.addRequiredParam<std::vector<Real> >("b_MN", "Material parameters b_MN in following order: b_11, b_22, b_33, b_12, b_23, b_13");
params.addCoupledVar("Ta", 0, "The (position dependent) active tension in fibre direction that will finally drive contraction, see (8) in [Whiteley 2007]. Default is Ta=0, i.e. no active tension anywhere.");
return params;
}
CardiacWhiteley2007Material::CardiacWhiteley2007Material(const std::string & name,
InputParameters parameters)
:CardiacSolidMechanicsMaterial(name, parameters),
_k(SymmTensor(getParam<std::vector<Real> >("k_MN"))),
_a(SymmTensor(getParam<std::vector<Real> >("a_MN"))),
_b(SymmTensor(getParam<std::vector<Real> >("b_MN"))),
_Rf(getMaterialProperty<RealTensorValue>("R_fibre")),
_has_Ta(isCoupled("Ta")),
_Ta(coupledValue("Ta")),
_id(1, 1, 1, 0, 0, 0)
{}
const RealTensorValue CardiacWhiteley2007Material::fromSymm(const SymmTensor & A)
{
RealTensorValue B;
B(0,0) = A(0,0);
B(1,1) = A(1,1);
B(2,2) = A(2,2);
B(0,1) = B(1,0) = A(0,1);
B(0,2) = B(2,0) = A(0,2);
B(1,2) = B(2,1) = A(1,2);
return B;
}
/*
* computes outer.transpose() * inner * outer
* TODO: this should be possible in a much more efficient way
*/
const SymmTensor CardiacWhiteley2007Material::symmProd(const RealTensorValue & outer, const SymmTensor & inner)
{
RealTensorValue in(fromSymm(inner));
RealTensorValue r(outer.transpose() * in * outer);
return SymmTensor(r(0,0), r(1,1), r(2,2), r(0,1), r(1,2), r(0,2) );
}
void
CardiacWhiteley2007Material::computeQpProperties()
{
// TODO: verify that all rotations are done in the correct direction, i.e. where do you have to use _Rf or _Rf.transpose() ?
// local deformation gradient tensor: insert displacement gradient row-wise
const RealTensorValue F(_grad_disp_x[_qp],
_grad_disp_y[_qp],
_grad_disp_z[_qp]);
// Cauchy-Green deformation tensor
const SymmTensor C(symmProd(F, _id));
// Lagrange-Green strain tensor
const SymmTensor E( (C - _id) * 0.5 );
// Lagrange-Green strain tensor in fibre coordinates
const SymmTensor Estar(symmProd(_Rf[_qp], E));
// Derivative of strain energy density W wrt Estar
SymmTensor dWdE;
for (int i=0;i<3;i++)
for (int j=i;j<3;j++)
if (Estar(i,j) > 0) {
const Real d(abs(_a(i,j) - Estar(i,j)));
dWdE(i,j) = _k(i, j) * Estar(i,j) / pow(d, _b(i,j)) * ( 2 + _b(i,j)*Estar(i,j)/d );
} else
dWdE(i,j) = 0.;
// rotate back into outer coordinate system
dWdE = symmProd(_Rf[_qp].transpose(), dWdE);
const Real p = 0; // TODO: p is the hydrostatic pressure / Lagrange multiplier to guarantee incompressibility
_stress[_qp] = _id*(-p) + symmProd(F.transpose(), dWdE);
// compute active tension in fibre direction, rotate into outer coordinates and add to stress if necessary
if (_has_Ta) {
SymmTensor Ta( symmProd( _Rf[_qp], SymmTensor(_Ta[_qp], 0, 0, 0, 0, 0) ) );
_stress[_qp] += Ta;
}
/* TODO: currently, though being possibly required (e.g. by the StressDivergence kernel), we do not set the following
// store elasticity tensor as material property...
_elasticity_tensor[_qp] =
//Jacobian multiplier of the stress
_Jacobian_mult[_qp] =
// Save off the elastic strain
_elastic_strain[_qp] = SymmTensor( _grad_disp_x[_qp](0),
_grad_disp_y[_qp](1),
_grad_disp_z[_qp](2),
0.5*(_grad_disp_x[_qp](1)+_grad_disp_y[_qp](0)),
0.5*(_grad_disp_y[_qp](2)+_grad_disp_z[_qp](1)),
0.5*(_grad_disp_z[_qp](0)+_grad_disp_x[_qp](2)) );;
*/
}
<|endoftext|>
|
<commit_before>#include "dlib/bam_util.h"
#include "dlib/bed_util.h"
#include <getopt.h>
#include <functional>
int usage(char **argv, int retcode=EXIT_FAILURE) {
fprintf(stderr, "bmftools %s <-l output_compression_level> in.bam out.bam\n"
"Use - for stdin or stdout.\n"
"Flags-\n"
"-F\t\tSkip all reads with any bits in parameter set.\n"
"-f\t\tSkip reads sharing no bits in parameter set.\n"
"-b\t\tPath to bed file with which to filter.\n"
"-P\t\tNumber of bases around bed file regions to pad.\n"
"-s\t\tMinimum family size for inclusion.\n"
"-r\t\tIf set, writes failed reads to this file.\n"
"-v\t\tInvert pass/fail, analogous to grep.\n"
, argv[0]);
return retcode;
}
struct opts {
uint32_t minFM:14;
uint32_t v:1;
uint32_t skip_flag:16;
uint32_t require_flag:16;
uint32_t minMQ:8;
khash_t(bed) *bed;
};
#define TEST(b, data, options) \
(\
(((data = bam_aux_get(b, "FM")) != NULL) ? bam_aux2i(data) : 1 >= (int)((opts *)options)->minFM) &&\
b->core.qual >= ((opts *)options)->minMQ &&\
((b->core.flag & ((opts *)options)->skip_flag) == 0) &&\
((b->core.flag & ((opts *)options)->require_flag)) &&\
bed_test(b, ((opts *)options)->bed)\
)
int bam_test(bam1_t *b, void *options) {
uint8_t *data;
return ((opts *)options)->v ? !TEST(b, data, options): TEST(b, data, options);
}
#undef TEST
int filter_main(int argc, char *argv[]) {
if(argc < 3)
return usage(argv);
if(strcmp(argv[1], "--help") == 0)
return usage(argv, EXIT_SUCCESS);
int c;
char out_mode[4] = "wb";
opts param = {0};
char *bedpath = NULL;
int padding = DEFAULT_PADDING;
std::string refused_path("");
while((c = getopt(argc, argv, "r:P:b:m:F:f:l:hv?")) > -1) {
switch(c) {
case 'P': padding = atoi(optarg); break;
case 'b': bedpath = optarg; break;
case 'm': param.minMQ = strtoul(optarg, NULL, 0); break;
case 's': param.minFM = strtoul(optarg, NULL, 0); break;
case 'F': param.skip_flag = strtoul(optarg, NULL, 0); break;
case 'f': param.require_flag = strtoul(optarg, NULL, 0); break;
case 'v': param.v = 1; break;
case 'r': refused_path = optarg; break;
case 'l': out_mode[2] = atoi(optarg) % 10 + '0'; break;
case 'h': case '?': return usage(argv, EXIT_SUCCESS);
}
}
check_bam_tag_exit(argv[optind], "FM");
if(argc - 2 != optind) {
LOG_EXIT("Required: precisely two positional arguments (in bam, out bam).\n");
}
dlib::BamHandle in(argv[optind]);
if(bedpath) {
param.bed = parse_bed_hash(bedpath, in.header, padding);
}
dlib::BamHandle out(argv[optind] + 1, in.header, out_mode);
// Core
if(!refused_path.size()) {
in.for_each(bam_test, out, (void *)¶m);
} else {
dlib::BamHandle refused(refused_path.c_str(), in.header, out_mode);
while(in.next() >= 0) {
if(bam_test(in.rec, (void *)¶m))
out.write(in.rec);
else
refused.write(in.rec);
}
}
// Clean up.
if(param.bed) bed_destroy_hash((void *)param.bed);
return EXIT_SUCCESS;
}
<commit_msg>filter_split_core might contain the most offensive line of code I've ever written.<commit_after>#include "dlib/bam_util.h"
#include "dlib/bed_util.h"
#include <getopt.h>
#include <functional>
int usage(char **argv, int retcode=EXIT_FAILURE) {
fprintf(stderr, "bmftools %s <-l output_compression_level> in.bam out.bam\n"
"Use - for stdin or stdout.\n"
"Flags-\n"
"-F\t\tSkip all reads with any bits in parameter set.\n"
"-f\t\tSkip reads sharing no bits in parameter set.\n"
"-b\t\tPath to bed file with which to filter.\n"
"-P\t\tNumber of bases around bed file regions to pad.\n"
"-s\t\tMinimum family size for inclusion.\n"
"-r\t\tIf set, writes failed reads to this file.\n"
"-v\t\tInvert pass/fail, analogous to grep.\n"
, argv[0]);
return retcode;
}
struct opts {
uint32_t minFM:14;
uint32_t v:1;
uint32_t skip_flag:16;
uint32_t require_flag:16;
uint32_t minMQ:8;
float minAF;
khash_t(bed) *bed;
};
#define TEST(b, data, options) \
(\
(((data = bam_aux_get(b, "FM")) != NULL) ? bam_aux2i(data) : 1 >= (int)((opts *)options)->minFM) &&\
b->core.qual >= ((opts *)options)->minMQ &&\
((b->core.flag & ((opts *)options)->skip_flag) == 0) &&\
((b->core.flag & ((opts *)options)->require_flag)) &&\
bed_test(b, ((opts *)options)->bed)\
)
int bam_test(bam1_t *b, void *options) {
uint8_t *data;
return ((opts *)options)->v ? !TEST(b, data, options): TEST(b, data, options);
}
#undef TEST
int filter_split_core(dlib::BamHandle& in, dlib::BamHandle& out, dlib::BamHandle& refused, opts *param)
{
while(in.next() >= 0) (bam_test(in.rec, (void *)param) ? out: refused).write(in.rec);
return EXIT_SUCCESS;
}
int filter_main(int argc, char *argv[]) {
if(argc < 3)
return usage(argv);
if(strcmp(argv[1], "--help") == 0)
return usage(argv, EXIT_SUCCESS);
int c;
char out_mode[4] = "wb";
opts param = {0};
char *bedpath = NULL;
int padding = DEFAULT_PADDING;
std::string refused_path("");
while((c = getopt(argc, argv, "a:r:P:b:m:F:f:l:hv?")) > -1) {
switch(c) {
case 'a': param.minAF = atof(optarg); break;
case 'P': padding = atoi(optarg); break;
case 'b': bedpath = optarg; break;
case 'm': param.minMQ = strtoul(optarg, NULL, 0); break;
case 's': param.minFM = strtoul(optarg, NULL, 0); break;
case 'F': param.skip_flag = strtoul(optarg, NULL, 0); break;
case 'f': param.require_flag = strtoul(optarg, NULL, 0); break;
case 'v': param.v = 1; break;
case 'r': refused_path = optarg; break;
case 'l': out_mode[2] = atoi(optarg) % 10 + '0'; break;
case 'h': case '?': return usage(argv, EXIT_SUCCESS);
}
}
check_bam_tag_exit(argv[optind], "FM");
if(argc - 2 != optind) {
LOG_EXIT("Required: precisely two positional arguments (in bam, out bam).\n");
}
dlib::BamHandle in(argv[optind]);
if(bedpath) {
param.bed = parse_bed_hash(bedpath, in.header, padding);
}
dlib::BamHandle out(argv[optind] + 1, in.header, out_mode);
// Core
if(refused_path.size()) { // refused path is set.
dlib::BamHandle refused(refused_path.c_str(), in.header, out_mode);
filter_split_core(in, out, refused, ¶m);
} else in.for_each(bam_test, out, (void *)¶m);
// Clean up.
if(param.bed) bed_destroy_hash((void *)param.bed);
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2016 musikcube team
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of the author nor the names of other contributors may
// be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include <core/support/Common.h>
#include <cursespp/ScrollAdapterBase.h>
#include <cursespp/SingleLineEntry.h>
#include "DirectoryAdapter.h"
using namespace musik::box;
using namespace cursespp;
using namespace boost::filesystem;
#ifdef WIN32
void buildDriveList(std::vector<std::string>& target) {
target.clear();
static char buffer[4096];
DWORD result = ::GetLogicalDriveStringsA(4096, buffer);
if (result) {
char* current = buffer;
while (*current) {
target.push_back(std::string(current));
current += strlen(current) + 1;
}
}
}
#endif
void buildDirectoryList(const path& p, std::vector<std::string>& target)
{
target.clear();
try {
directory_iterator end;
directory_iterator file(p);
while (file != end) {
if (is_directory(file->status())) {
std::string leaf = file->path().leaf().string();
if (leaf[0] != '.') {
target.push_back(leaf);
}
}
++file;
}
}
catch (...) {
/* todo: log maybe? */
}
}
DirectoryAdapter::DirectoryAdapter() {
this->dir = musik::core::GetHomeDirectory();
buildDirectoryList(this->dir, this->subdirs);
}
DirectoryAdapter::~DirectoryAdapter() {
}
void DirectoryAdapter::Select(size_t index) {
bool hasParent = dir.has_parent_path();
if (hasParent && index == 0) {
this->dir = this->dir.parent_path();
}
else {
dir /= this->subdirs[hasParent ? index - 1 : index];
}
#ifdef WIN32
std::string pathstr = this->dir.string();
if ((pathstr.size() == 2 && pathstr[1] == ':') ||
(pathstr.size() == 3 && pathstr[2] == ':'))
{
dir = path();
buildDriveList(subdirs);
return;
}
#endif
buildDirectoryList(dir, subdirs);
}
std::string DirectoryAdapter::GetFullPathAt(size_t index) {
bool hasParent = dir.has_parent_path();
if (hasParent && index == 0) {
return "";
}
index = (hasParent ? index - 1 : index);
return (dir / this->subdirs[index]).string();
}
size_t DirectoryAdapter::GetEntryCount() {
size_t count = subdirs.size();
return dir.has_parent_path() ? count + 1 : count;
}
IScrollAdapter::EntryPtr DirectoryAdapter::GetEntry(size_t index) {
if (dir.has_parent_path()) {
if (index == 0) {
return IScrollAdapter::EntryPtr(new SingleLineEntry(".."));
}
--index;
}
return IScrollAdapter::EntryPtr(new SingleLineEntry(this->subdirs[index]));
}
<commit_msg>Added sorting to the directory browser<commit_after>//////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2007-2016 musikcube team
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of the author nor the names of other contributors may
// be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include <core/support/Common.h>
#include <cursespp/ScrollAdapterBase.h>
#include <cursespp/SingleLineEntry.h>
#include "DirectoryAdapter.h"
using namespace musik::box;
using namespace cursespp;
using namespace boost::filesystem;
#ifdef WIN32
void buildDriveList(std::vector<std::string>& target) {
target.clear();
static char buffer[4096];
DWORD result = ::GetLogicalDriveStringsA(4096, buffer);
if (result) {
char* current = buffer;
while (*current) {
target.push_back(std::string(current));
current += strlen(current) + 1;
}
}
}
#endif
void buildDirectoryList(const path& p, std::vector<std::string>& target)
{
target.clear();
try {
directory_iterator end;
directory_iterator file(p);
while (file != end) {
if (is_directory(file->status())) {
std::string leaf = file->path().leaf().string();
if (leaf[0] != '.') {
target.push_back(leaf);
}
}
++file;
}
}
catch (...) {
/* todo: log maybe? */
}
std::sort(target.begin(), target.end(), std::locale(""));
}
DirectoryAdapter::DirectoryAdapter() {
this->dir = musik::core::GetHomeDirectory();
buildDirectoryList(this->dir, this->subdirs);
}
DirectoryAdapter::~DirectoryAdapter() {
}
void DirectoryAdapter::Select(size_t index) {
bool hasParent = dir.has_parent_path();
if (hasParent && index == 0) {
this->dir = this->dir.parent_path();
}
else {
dir /= this->subdirs[hasParent ? index - 1 : index];
}
#ifdef WIN32
std::string pathstr = this->dir.string();
if ((pathstr.size() == 2 && pathstr[1] == ':') ||
(pathstr.size() == 3 && pathstr[2] == ':'))
{
dir = path();
buildDriveList(subdirs);
return;
}
#endif
buildDirectoryList(dir, subdirs);
}
std::string DirectoryAdapter::GetFullPathAt(size_t index) {
bool hasParent = dir.has_parent_path();
if (hasParent && index == 0) {
return "";
}
index = (hasParent ? index - 1 : index);
return (dir / this->subdirs[index]).string();
}
size_t DirectoryAdapter::GetEntryCount() {
size_t count = subdirs.size();
return dir.has_parent_path() ? count + 1 : count;
}
IScrollAdapter::EntryPtr DirectoryAdapter::GetEntry(size_t index) {
if (dir.has_parent_path()) {
if (index == 0) {
return IScrollAdapter::EntryPtr(new SingleLineEntry(".."));
}
--index;
}
return IScrollAdapter::EntryPtr(new SingleLineEntry(this->subdirs[index]));
}
<|endoftext|>
|
<commit_before>// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: lsong@google.com (Libo Song)
// jmarantz@google.com (Joshua Marantz)
#include "net/instaweb/apache/instaweb_handler.h"
#include "apr_strings.h"
#include "base/basictypes.h"
#include "base/scoped_ptr.h"
#include "net/instaweb/apache/apache_slurp.h"
#include "net/instaweb/apache/apr_statistics.h"
#include "net/instaweb/apache/apr_timer.h"
#include "net/instaweb/apache/header_util.h"
#include "net/instaweb/apache/instaweb_context.h"
#include "net/instaweb/apache/serf_async_callback.h"
#include "net/instaweb/apache/serf_url_async_fetcher.h"
#include "net/instaweb/apache/mod_instaweb.h"
#include "net/instaweb/rewriter/public/add_instrumentation_filter.h"
#include "net/instaweb/rewriter/public/output_resource.h"
#include "net/instaweb/rewriter/public/rewrite_driver.h"
#include "net/instaweb/util/public/google_message_handler.h"
#include "net/instaweb/util/public/message_handler.h"
#include "net/instaweb/util/public/simple_meta_data.h"
#include "net/instaweb/util/public/string_util.h"
#include "net/instaweb/util/public/string_writer.h"
#include "http_config.h"
#include "http_core.h"
#include "http_log.h"
#include "http_protocol.h"
namespace net_instaweb {
namespace {
const char kStatisticsHandler[] = "mod_pagespeed_statistics";
const char kBeaconHandler[] = "mod_pagespeed_beacon";
bool IsCompressibleContentType(const char* content_type) {
if (content_type == NULL) {
return false;
}
std::string type = content_type;
size_t separator_idx = type.find(";");
if (separator_idx != std::string::npos) {
type.erase(separator_idx);
}
bool res = false;
if (type.find("text/") == 0) {
res = true;
} else if (type.find("application/") == 0) {
if (type.find("javascript") != type.npos ||
type.find("json") != type.npos ||
type.find("ecmascript") != type.npos ||
type == "application/livescript" ||
type == "application/js" ||
type == "application/jscript" ||
type == "application/x-js" ||
type == "application/xhtml+xml" ||
type == "application/xml") {
res = true;
}
}
return res;
}
// Default handler when the file is not found
void instaweb_default_handler(const std::string& url, request_rec* request) {
request->status = HTTP_NOT_FOUND;
ap_set_content_type(request, "text/html; charset=utf-8");
ap_rputs("<html><head><title>Not Found</title></head>", request);
ap_rputs("<body><h1>Apache server with mod_pagespeed</h1>OK", request);
ap_rputs("<hr>NOT FOUND:", request);
ap_rputs(url.c_str(), request);
ap_rputs("</body></html>", request);
}
// predeclare to minimize diffs for now. TODO(jmarantz): reorder
void send_out_headers_and_body(
request_rec* request,
const SimpleMetaData& response_headers,
const std::string& output);
// Determines whether the url can be handled as a mod_pagespeed resource,
// and handles it, returning true. A 'true' routine means that this
// method believed the URL was a mod_pagespeed resource -- it does not
// imply that it was handled successfully. That information will be
// in the status code in the response headers.
bool handle_as_resource(ApacheRewriteDriverFactory* factory,
request_rec* request,
const std::string& url) {
RewriteDriver* rewrite_driver = factory->NewRewriteDriver();
SimpleMetaData request_headers, response_headers;
int n = arraysize(RewriteDriver::kPassThroughRequestAttributes);
for (int i = 0; i < n; ++i) {
const char* value = apr_table_get(
request->headers_in,
RewriteDriver::kPassThroughRequestAttributes[i]);
if (value != NULL) {
request_headers.Add(RewriteDriver::kPassThroughRequestAttributes[i],
value);
}
}
std::string output; // TODO(jmarantz): quit buffering resource output
StringWriter writer(&output);
MessageHandler* message_handler = factory->message_handler();
SerfAsyncCallback* callback = new SerfAsyncCallback(
&response_headers, &writer);
bool handled = rewrite_driver->FetchResource(
url, request_headers, callback->response_headers(), callback->writer(),
message_handler, callback);
if (handled) {
message_handler->Message(kInfo, "Fetching resource %s...", url.c_str());
if (!callback->done()) {
SerfUrlAsyncFetcher* serf_async_fetcher =
factory->serf_url_async_fetcher();
AprTimer timer;
int64 max_ms = factory->fetcher_time_out_ms();
for (int64 start_ms = timer.NowMs(), now_ms = start_ms;
!callback->done() && now_ms - start_ms < max_ms;
now_ms = timer.NowMs()) {
int64 remaining_us = max_ms - (now_ms - start_ms);
serf_async_fetcher->Poll(remaining_us);
}
if (!callback->done()) {
message_handler->Message(kError, "Timeout on url %s", url.c_str());
}
}
if (callback->success()) {
message_handler->Message(kInfo, "Fetch succeeded for %s, status=%d",
url.c_str(), response_headers.status_code());
send_out_headers_and_body(request, response_headers, output);
} else {
message_handler->Message(kError, "Fetch failed for %s, status=%d",
url.c_str(), response_headers.status_code());
factory->Increment404Count();
instaweb_default_handler(url, request);
}
} else {
callback->Done(false);
}
callback->Release();
factory->ReleaseRewriteDriver(rewrite_driver);
return handled;
}
void send_out_headers_and_body(
request_rec* request,
const SimpleMetaData& response_headers,
const std::string& output) {
if (response_headers.status_code() != 0) {
request->status = response_headers.status_code();
}
for (int idx = 0; idx < response_headers.NumAttributes(); ++idx) {
const char* name = response_headers.Name(idx);
const char* value = response_headers.Value(idx);
if (strcasecmp(name, HttpAttributes::kContentType) == 0) {
// ap_set_content_type does not make a copy of the string, we need
// to duplicate it.
char* ptr = apr_pstrdup(request->pool, value);
ap_set_content_type(request, ptr);
} else {
if (strcasecmp(name, HttpAttributes::kCacheControl) == 0) {
SetupCacheRepair(value, request);
}
// apr_table_add makes copies of both head key and value, so we do not
// have to duplicate them.
apr_table_add(request->headers_out, name, value);
}
}
if (response_headers.status_code() == HttpStatus::kOK &&
IsCompressibleContentType(request->content_type)) {
// Make sure compression is enabled for this response.
ap_add_output_filter("DEFLATE", NULL, request, request->connection);
}
// Recompute the content-length, because the content may have changed.
ap_set_content_length(request, output.size());
// Send the body
ap_rwrite(output.c_str(), output.size(), request);
}
} // namespace
apr_status_t repair_caching_header(ap_filter_t *filter,
apr_bucket_brigade *bb) {
request_rec* request = filter->r;
RepairCachingHeaders(request);
ap_remove_output_filter(filter);
return ap_pass_brigade(filter->next, bb);
}
std::string get_request_url(request_rec* request) {
/*
* In some contexts we are seeing relative URLs passed
* into request->unparsed_uri. But when using mod_slurp, the rewritten
* HTML contains complete URLs, so this construction yields the host:port
* prefix twice.
*
* TODO(jmarantz): Figure out how to do this correctly at all times.
*/
std::string url;
if (strncmp(request->unparsed_uri, "http://", 7) == 0) {
url = request->unparsed_uri;
} else {
url = ap_construct_url(request->pool, request->unparsed_uri, request);
}
return url;
}
int instaweb_handler(request_rec* request) {
ApacheRewriteDriverFactory* factory =
InstawebContext::Factory(request->server);
int ret = OK;
// Only handle GET request
if (request->method_number != M_GET) {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, APR_SUCCESS, request,
"Not GET request: %d.", request->method_number);
ret = DECLINED;
} else if (strcmp(request->handler, kStatisticsHandler) == 0) {
std::string output;
SimpleMetaData response_headers;
StringWriter writer(&output);
AprStatistics* statistics = factory->statistics();
if (statistics) {
statistics->Dump(&writer, factory->message_handler());
}
send_out_headers_and_body(request, response_headers, output);
} else if (strcmp(request->handler, kBeaconHandler) == 0) {
RewriteDriver* driver = factory->NewRewriteDriver();
AddInstrumentationFilter* aif = driver->add_instrumentation_filter();
if (aif && aif->HandleBeacon(request->unparsed_uri)) {
ret = HTTP_NO_CONTENT;
} else {
ret = DECLINED;
}
factory->ReleaseRewriteDriver(driver);
} else {
std::string url = get_request_url(request);
if (!handle_as_resource(factory, request, url)) {
if (factory->slurping_enabled()) {
SlurpUrl(url, factory, request);
if (request->status == HTTP_NOT_FOUND) {
factory->IncrementSlurpCount();
}
} else {
ret = DECLINED;
}
}
}
return ret;
}
// This translator must be inserted into the translate_name chain
// prior to mod_rewrite. By responding "OK" we prevent mod_rewrite
// from running on this request and borking URL names that need to be
// handled by mod_pagespeed.
apr_status_t bypass_translators_for_pagespeed_resources(request_rec *request) {
std::string url = get_request_url(request);
StringPiece url_piece(url);
apr_status_t handled = DECLINED;
if (url_piece.ends_with(kStatisticsHandler) ||
url_piece.ends_with(kBeaconHandler)) {
handled = OK;
} else {
ApacheRewriteDriverFactory* factory =
InstawebContext::Factory(request->server);
RewriteDriver* rewrite_driver = factory->NewRewriteDriver();
RewriteFilter* filter;
scoped_ptr<OutputResource> output_resource(
rewrite_driver->DecodeOutputResource(url, &filter));
if (output_resource.get() != NULL) {
handled = OK;
request->filename = apr_pstrcat(
request->pool, "mod_pagespeed:", request->unparsed_uri, NULL);
}
factory->ReleaseRewriteDriver(rewrite_driver);
}
return handled;
}
} // namespace net_instaweb
<commit_msg>Avoid 403s when serving mod_pagespeed resources due to bogus request->filename.<commit_after>// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: lsong@google.com (Libo Song)
// jmarantz@google.com (Joshua Marantz)
#include "net/instaweb/apache/instaweb_handler.h"
#include "apr_strings.h"
#include "base/basictypes.h"
#include "base/scoped_ptr.h"
#include "net/instaweb/apache/apache_slurp.h"
#include "net/instaweb/apache/apr_statistics.h"
#include "net/instaweb/apache/apr_timer.h"
#include "net/instaweb/apache/header_util.h"
#include "net/instaweb/apache/instaweb_context.h"
#include "net/instaweb/apache/serf_async_callback.h"
#include "net/instaweb/apache/serf_url_async_fetcher.h"
#include "net/instaweb/apache/mod_instaweb.h"
#include "net/instaweb/rewriter/public/add_instrumentation_filter.h"
#include "net/instaweb/rewriter/public/output_resource.h"
#include "net/instaweb/rewriter/public/rewrite_driver.h"
#include "net/instaweb/util/public/google_message_handler.h"
#include "net/instaweb/util/public/message_handler.h"
#include "net/instaweb/util/public/simple_meta_data.h"
#include "net/instaweb/util/public/string_util.h"
#include "net/instaweb/util/public/string_writer.h"
#include "http_config.h"
#include "http_core.h"
#include "http_log.h"
#include "http_protocol.h"
namespace net_instaweb {
namespace {
const char kStatisticsHandler[] = "mod_pagespeed_statistics";
const char kBeaconHandler[] = "mod_pagespeed_beacon";
bool IsCompressibleContentType(const char* content_type) {
if (content_type == NULL) {
return false;
}
std::string type = content_type;
size_t separator_idx = type.find(";");
if (separator_idx != std::string::npos) {
type.erase(separator_idx);
}
bool res = false;
if (type.find("text/") == 0) {
res = true;
} else if (type.find("application/") == 0) {
if (type.find("javascript") != type.npos ||
type.find("json") != type.npos ||
type.find("ecmascript") != type.npos ||
type == "application/livescript" ||
type == "application/js" ||
type == "application/jscript" ||
type == "application/x-js" ||
type == "application/xhtml+xml" ||
type == "application/xml") {
res = true;
}
}
return res;
}
// Default handler when the file is not found
void instaweb_default_handler(const std::string& url, request_rec* request) {
request->status = HTTP_NOT_FOUND;
ap_set_content_type(request, "text/html; charset=utf-8");
ap_rputs("<html><head><title>Not Found</title></head>", request);
ap_rputs("<body><h1>Apache server with mod_pagespeed</h1>OK", request);
ap_rputs("<hr>NOT FOUND:", request);
ap_rputs(url.c_str(), request);
ap_rputs("</body></html>", request);
}
// predeclare to minimize diffs for now. TODO(jmarantz): reorder
void send_out_headers_and_body(
request_rec* request,
const SimpleMetaData& response_headers,
const std::string& output);
// Determines whether the url can be handled as a mod_pagespeed resource,
// and handles it, returning true. A 'true' routine means that this
// method believed the URL was a mod_pagespeed resource -- it does not
// imply that it was handled successfully. That information will be
// in the status code in the response headers.
bool handle_as_resource(ApacheRewriteDriverFactory* factory,
request_rec* request,
const std::string& url) {
RewriteDriver* rewrite_driver = factory->NewRewriteDriver();
SimpleMetaData request_headers, response_headers;
int n = arraysize(RewriteDriver::kPassThroughRequestAttributes);
for (int i = 0; i < n; ++i) {
const char* value = apr_table_get(
request->headers_in,
RewriteDriver::kPassThroughRequestAttributes[i]);
if (value != NULL) {
request_headers.Add(RewriteDriver::kPassThroughRequestAttributes[i],
value);
}
}
std::string output; // TODO(jmarantz): quit buffering resource output
StringWriter writer(&output);
MessageHandler* message_handler = factory->message_handler();
SerfAsyncCallback* callback = new SerfAsyncCallback(
&response_headers, &writer);
bool handled = rewrite_driver->FetchResource(
url, request_headers, callback->response_headers(), callback->writer(),
message_handler, callback);
if (handled) {
message_handler->Message(kInfo, "Fetching resource %s...", url.c_str());
if (!callback->done()) {
SerfUrlAsyncFetcher* serf_async_fetcher =
factory->serf_url_async_fetcher();
AprTimer timer;
int64 max_ms = factory->fetcher_time_out_ms();
for (int64 start_ms = timer.NowMs(), now_ms = start_ms;
!callback->done() && now_ms - start_ms < max_ms;
now_ms = timer.NowMs()) {
int64 remaining_us = max_ms - (now_ms - start_ms);
serf_async_fetcher->Poll(remaining_us);
}
if (!callback->done()) {
message_handler->Message(kError, "Timeout on url %s", url.c_str());
}
}
if (callback->success()) {
message_handler->Message(kInfo, "Fetch succeeded for %s, status=%d",
url.c_str(), response_headers.status_code());
send_out_headers_and_body(request, response_headers, output);
} else {
message_handler->Message(kError, "Fetch failed for %s, status=%d",
url.c_str(), response_headers.status_code());
factory->Increment404Count();
instaweb_default_handler(url, request);
}
} else {
callback->Done(false);
}
callback->Release();
factory->ReleaseRewriteDriver(rewrite_driver);
return handled;
}
void send_out_headers_and_body(
request_rec* request,
const SimpleMetaData& response_headers,
const std::string& output) {
if (response_headers.status_code() != 0) {
request->status = response_headers.status_code();
}
for (int idx = 0; idx < response_headers.NumAttributes(); ++idx) {
const char* name = response_headers.Name(idx);
const char* value = response_headers.Value(idx);
if (strcasecmp(name, HttpAttributes::kContentType) == 0) {
// ap_set_content_type does not make a copy of the string, we need
// to duplicate it.
char* ptr = apr_pstrdup(request->pool, value);
ap_set_content_type(request, ptr);
} else {
if (strcasecmp(name, HttpAttributes::kCacheControl) == 0) {
SetupCacheRepair(value, request);
}
// apr_table_add makes copies of both head key and value, so we do not
// have to duplicate them.
apr_table_add(request->headers_out, name, value);
}
}
if (response_headers.status_code() == HttpStatus::kOK &&
IsCompressibleContentType(request->content_type)) {
// Make sure compression is enabled for this response.
ap_add_output_filter("DEFLATE", NULL, request, request->connection);
}
// Recompute the content-length, because the content may have changed.
ap_set_content_length(request, output.size());
// Send the body
ap_rwrite(output.c_str(), output.size(), request);
}
} // namespace
apr_status_t repair_caching_header(ap_filter_t *filter,
apr_bucket_brigade *bb) {
request_rec* request = filter->r;
RepairCachingHeaders(request);
ap_remove_output_filter(filter);
return ap_pass_brigade(filter->next, bb);
}
std::string get_request_url(request_rec* request) {
/*
* In some contexts we are seeing relative URLs passed
* into request->unparsed_uri. But when using mod_slurp, the rewritten
* HTML contains complete URLs, so this construction yields the host:port
* prefix twice.
*
* TODO(jmarantz): Figure out how to do this correctly at all times.
*/
std::string url;
if (strncmp(request->unparsed_uri, "http://", 7) == 0) {
url = request->unparsed_uri;
} else {
url = ap_construct_url(request->pool, request->unparsed_uri, request);
}
return url;
}
int instaweb_handler(request_rec* request) {
ApacheRewriteDriverFactory* factory =
InstawebContext::Factory(request->server);
int ret = OK;
// Only handle GET request
if (request->method_number != M_GET) {
ap_log_rerror(APLOG_MARK, APLOG_DEBUG, APR_SUCCESS, request,
"Not GET request: %d.", request->method_number);
ret = DECLINED;
} else if (strcmp(request->handler, kStatisticsHandler) == 0) {
std::string output;
SimpleMetaData response_headers;
StringWriter writer(&output);
AprStatistics* statistics = factory->statistics();
if (statistics) {
statistics->Dump(&writer, factory->message_handler());
}
send_out_headers_and_body(request, response_headers, output);
} else if (strcmp(request->handler, kBeaconHandler) == 0) {
RewriteDriver* driver = factory->NewRewriteDriver();
AddInstrumentationFilter* aif = driver->add_instrumentation_filter();
if (aif && aif->HandleBeacon(request->unparsed_uri)) {
ret = HTTP_NO_CONTENT;
} else {
ret = DECLINED;
}
factory->ReleaseRewriteDriver(driver);
} else {
std::string url = get_request_url(request);
if (!handle_as_resource(factory, request, url)) {
if (factory->slurping_enabled()) {
SlurpUrl(url, factory, request);
if (request->status == HTTP_NOT_FOUND) {
factory->IncrementSlurpCount();
}
} else {
ret = DECLINED;
}
}
}
return ret;
}
// This translator must be inserted into the translate_name chain
// prior to mod_rewrite. By responding "OK" we prevent mod_rewrite
// from running on this request and borking URL names that need to be
// handled by mod_pagespeed.
apr_status_t bypass_translators_for_pagespeed_resources(request_rec *request) {
std::string url = get_request_url(request);
StringPiece url_piece(url);
apr_status_t handled = DECLINED;
if (url_piece.ends_with(kStatisticsHandler) ||
url_piece.ends_with(kBeaconHandler)) {
handled = OK;
} else {
ApacheRewriteDriverFactory* factory =
InstawebContext::Factory(request->server);
RewriteDriver* rewrite_driver = factory->NewRewriteDriver();
RewriteFilter* filter;
scoped_ptr<OutputResource> output_resource(
rewrite_driver->DecodeOutputResource(url, &filter));
if (output_resource.get() != NULL) {
handled = OK;
// TODO(jmarantz): What should these lines really be? Deleting
// "mod_pagespeed:", doesn't help matters any: we always obtain a 403 for
// any resource request. By contrast, the present form yields results
// reliably, at the cost of 4 error_log entries for each bogus URL lookup
// we encounter. Those *are* requests for bogus URLs, but the intent is
// clearly to avoid DoS when our logs are exhausted by a shower of junk
// requests. That said:
// 1) no setting of request->filename based on request->unparsed_uri
// appears to work.
// 2) We get an error_log entry when we fetch an ordinary bogus url,
// too, we just don't get 4 of them.
// request->filename = NULL; // Also serves data, but fills logs.
// request->filename = apr_pstrcat(
// request->pool, "mod_pagespeed:", request->unparsed_uri, NULL);
}
factory->ReleaseRewriteDriver(rewrite_driver);
}
return handled;
}
} // namespace net_instaweb
<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "androidpotentialkit.h"
#include "androidconstants.h"
#include "androidconfigurations.h"
#include <utils/detailswidget.h>
#include <coreplugin/icore.h>
#include <projectexplorer/kitmanager.h>
#include <projectexplorer/kit.h>
#include <projectexplorer/kitinformation.h>
#include <qtsupport/qtversionmanager.h>
#include <qtsupport/baseqtversion.h>
#include <QGridLayout>
#include <QLabel>
#include <QPushButton>
using namespace Android;
using namespace Android::Internal;
QString AndroidPotentialKit::displayName() const
{
return tr("Configure Android...");
}
void Android::Internal::AndroidPotentialKit::executeFromMenu()
{
Core::ICore::showOptionsDialog(Constants::ANDROID_SETTINGS_CATEGORY,
Constants::ANDROID_SETTINGS_ID);
}
QWidget *AndroidPotentialKit::createWidget(QWidget *parent) const
{
if (!isEnabled())
return 0;
return new AndroidPotentialKitWidget(parent);
}
bool AndroidPotentialKit::isEnabled() const
{
QList<ProjectExplorer::Kit *> kits = ProjectExplorer::KitManager::kits();
foreach (ProjectExplorer::Kit *kit, kits) {
Core::Id deviceId = ProjectExplorer::DeviceKitInformation::deviceId(kit);
if (kit->isAutoDetected()
&& deviceId == Core::Id(Constants::ANDROID_DEVICE_ID)
&& !kit->isSdkProvided()) {
return false;
}
}
bool found = false;
foreach (QtSupport::BaseQtVersion *version, QtSupport::QtVersionManager::validVersions()) {
if (version->type() == QLatin1String(Constants::ANDROIDQT)) {
found = true;
break;
}
}
return found;
}
AndroidPotentialKitWidget::AndroidPotentialKitWidget(QWidget *parent)
: Utils::DetailsWidget(parent)
{
setSummaryText(QLatin1String("<b>Create Android Kits</b>"));
setIcon(QIcon(QLatin1String(Constants::ANDROID_SETTINGS_CATEGORY_ICON)));
//detailsWidget->setState(Utils::DetailsWidget::NoSummary);
QWidget *mainWidget = new QWidget(this);
setWidget(mainWidget);
QGridLayout *layout = new QGridLayout(mainWidget);
layout->setMargin(0);
QLabel *label = new QLabel;
label->setText(tr("Qt Creator needs additional settings to enable Android support."
" You can configure those settings in the Options dialog."));
label->setWordWrap(true);
layout->addWidget(label, 0, 0, 1, 2);
QPushButton *openOptions = new QPushButton;
openOptions->setText(tr("Open Settings"));
openOptions->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(openOptions, 1, 1);
connect(openOptions, SIGNAL(clicked()),
this, SLOT(openOptions()));
connect(AndroidConfigurations::instance(), SIGNAL(updated()),
this, SLOT(recheck()));
}
void AndroidPotentialKitWidget::openOptions()
{
Core::ICore::showOptionsDialog(Constants::ANDROID_SETTINGS_CATEGORY,
Constants::ANDROID_SETTINGS_ID);
}
void AndroidPotentialKitWidget::recheck()
{
QList<ProjectExplorer::Kit *> kits = ProjectExplorer::KitManager::kits();
foreach (ProjectExplorer::Kit *kit, kits) {
Core::Id deviceId = ProjectExplorer::DeviceKitInformation::deviceId(kit);
if (kit->isAutoDetected()
&& deviceId == Core::Id(Constants::ANDROID_DEVICE_ID)
&& !kit->isSdkProvided()) {
setVisible(false);
return;
}
}
}
<commit_msg>Give Android potential kit a warning icon<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "androidpotentialkit.h"
#include "androidconstants.h"
#include "androidconfigurations.h"
#include <utils/detailswidget.h>
#include <coreplugin/icore.h>
#include <projectexplorer/kitmanager.h>
#include <projectexplorer/kit.h>
#include <projectexplorer/kitinformation.h>
#include <qtsupport/qtversionmanager.h>
#include <qtsupport/baseqtversion.h>
#include <QGridLayout>
#include <QLabel>
#include <QPushButton>
using namespace Android;
using namespace Android::Internal;
QString AndroidPotentialKit::displayName() const
{
return tr("Configure Android...");
}
void Android::Internal::AndroidPotentialKit::executeFromMenu()
{
Core::ICore::showOptionsDialog(Constants::ANDROID_SETTINGS_CATEGORY,
Constants::ANDROID_SETTINGS_ID);
}
QWidget *AndroidPotentialKit::createWidget(QWidget *parent) const
{
if (!isEnabled())
return 0;
return new AndroidPotentialKitWidget(parent);
}
bool AndroidPotentialKit::isEnabled() const
{
QList<ProjectExplorer::Kit *> kits = ProjectExplorer::KitManager::kits();
foreach (ProjectExplorer::Kit *kit, kits) {
Core::Id deviceId = ProjectExplorer::DeviceKitInformation::deviceId(kit);
if (kit->isAutoDetected()
&& deviceId == Core::Id(Constants::ANDROID_DEVICE_ID)
&& !kit->isSdkProvided()) {
return false;
}
}
bool found = false;
foreach (QtSupport::BaseQtVersion *version, QtSupport::QtVersionManager::validVersions()) {
if (version->type() == QLatin1String(Constants::ANDROIDQT)) {
found = true;
break;
}
}
return found;
}
AndroidPotentialKitWidget::AndroidPotentialKitWidget(QWidget *parent)
: Utils::DetailsWidget(parent)
{
setSummaryText(QLatin1String("<b>Android has not been configured. Create Android kits.</b>"));
setIcon(QIcon(QLatin1String(":/projectexplorer/images/compile_warning.png")));
//detailsWidget->setState(Utils::DetailsWidget::NoSummary);
QWidget *mainWidget = new QWidget(this);
setWidget(mainWidget);
QGridLayout *layout = new QGridLayout(mainWidget);
layout->setMargin(0);
QLabel *label = new QLabel;
label->setText(tr("Qt Creator needs additional settings to enable Android support."
" You can configure those settings in the Options dialog."));
label->setWordWrap(true);
layout->addWidget(label, 0, 0, 1, 2);
QPushButton *openOptions = new QPushButton;
openOptions->setText(tr("Open Settings"));
openOptions->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
layout->addWidget(openOptions, 1, 1);
connect(openOptions, SIGNAL(clicked()),
this, SLOT(openOptions()));
connect(AndroidConfigurations::instance(), SIGNAL(updated()),
this, SLOT(recheck()));
}
void AndroidPotentialKitWidget::openOptions()
{
Core::ICore::showOptionsDialog(Constants::ANDROID_SETTINGS_CATEGORY,
Constants::ANDROID_SETTINGS_ID);
}
void AndroidPotentialKitWidget::recheck()
{
QList<ProjectExplorer::Kit *> kits = ProjectExplorer::KitManager::kits();
foreach (ProjectExplorer::Kit *kit, kits) {
Core::Id deviceId = ProjectExplorer::DeviceKitInformation::deviceId(kit);
if (kit->isAutoDetected()
&& deviceId == Core::Id(Constants::ANDROID_DEVICE_ID)
&& !kit->isSdkProvided()) {
setVisible(false);
return;
}
}
}
<|endoftext|>
|
<commit_before>#include "tools/cabana/messageswidget.h"
#include <QCompleter>
#include <QDialogButtonBox>
#include <QFontDatabase>
#include <QHeaderView>
#include <QLineEdit>
#include <QPushButton>
#include <QSortFilterProxyModel>
#include <QTextEdit>
#include <QVBoxLayout>
#include "tools/cabana/dbcmanager.h"
MessagesWidget::MessagesWidget(QWidget *parent) : QWidget(parent) {
QVBoxLayout *main_layout = new QVBoxLayout(this);
// DBC file selector
QHBoxLayout *dbc_file_layout = new QHBoxLayout();
dbc_combo = new QComboBox(this);
auto dbc_names = dbc()->allDBCNames();
for (const auto &name : dbc_names) {
dbc_combo->addItem(QString::fromStdString(name));
}
dbc_combo->model()->sort(0);
dbc_combo->setEditable(true);
dbc_combo->setCurrentText(QString());
dbc_combo->setInsertPolicy(QComboBox::NoInsert);
dbc_combo->completer()->setCompletionMode(QCompleter::PopupCompletion);
QFont font;
font.setBold(true);
dbc_combo->lineEdit()->setFont(font);
dbc_file_layout->addWidget(dbc_combo);
QPushButton *load_from_paste = new QPushButton(tr("Load from paste"), this);
dbc_file_layout->addWidget(load_from_paste);
dbc_file_layout->addStretch();
QPushButton *save_btn = new QPushButton(tr("Save DBC"), this);
dbc_file_layout->addWidget(save_btn);
main_layout->addLayout(dbc_file_layout);
// message filter
QLineEdit *filter = new QLineEdit(this);
filter->setPlaceholderText(tr("filter messages"));
main_layout->addWidget(filter);
// message table
table_widget = new QTableView(this);
model = new MessageListModel(this);
QSortFilterProxyModel *proxy_model = new QSortFilterProxyModel(this);
proxy_model->setSourceModel(model);
proxy_model->setFilterCaseSensitivity(Qt::CaseInsensitive);
proxy_model->setDynamicSortFilter(false);
table_widget->setModel(proxy_model);
table_widget->setSelectionBehavior(QAbstractItemView::SelectRows);
table_widget->setSelectionMode(QAbstractItemView::SingleSelection);
table_widget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
table_widget->setSortingEnabled(true);
table_widget->setColumnWidth(0, 250);
table_widget->setColumnWidth(1, 80);
table_widget->setColumnWidth(2, 80);
table_widget->horizontalHeader()->setStretchLastSection(true);
table_widget->verticalHeader()->hide();
table_widget->sortByColumn(0, Qt::AscendingOrder);
main_layout->addWidget(table_widget);
// signals/slots
QObject::connect(filter, &QLineEdit::textChanged, proxy_model, &QSortFilterProxyModel::setFilterFixedString);
QObject::connect(can, &CANMessages::updated, model, &MessageListModel::updateState);
QObject::connect(dbc_combo, SIGNAL(activated(const QString &)), SLOT(dbcSelectionChanged(const QString &)));
QObject::connect(load_from_paste, &QPushButton::clicked, this, &MessagesWidget::loadFromPaste);
QObject::connect(save_btn, &QPushButton::clicked, [=]() {
// TODO: save DBC to file
});
QObject::connect(table_widget->selectionModel(), &QItemSelectionModel::currentChanged, [=](const QModelIndex ¤t, const QModelIndex &previous) {
if (current.isValid()) {
emit msgSelectionChanged(current.data(Qt::UserRole).toString());
}
});
// For test purpose
dbc_combo->setCurrentText("toyota_nodsu_pt_generated");
}
void MessagesWidget::dbcSelectionChanged(const QString &dbc_file) {
dbc()->open(dbc_file);
// TODO: reset model?
table_widget->sortByColumn(0, Qt::AscendingOrder);
}
void MessagesWidget::loadFromPaste() {
LoadDBCDialog dlg(this);
if (dlg.exec()) {
dbc()->open("from paste", dlg.dbc_edit->toPlainText());
dbc_combo->setCurrentText("loaded from paste");
}
}
// MessageListModel
QVariant MessageListModel::headerData(int section, Qt::Orientation orientation, int role) const {
if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
return (QString[]){"Name", "ID", "Count", "Bytes"}[section];
return {};
}
QVariant MessageListModel::data(const QModelIndex &index, int role) const {
if (role == Qt::DisplayRole) {
auto it = std::next(can->can_msgs.begin(), index.row());
if (it != can->can_msgs.end() && !it.value().empty()) {
const QString &msg_id = it.key();
switch (index.column()) {
case 0: {
auto msg = dbc()->msg(msg_id);
return msg ? msg->name.c_str() : "untitled";
}
case 1: return msg_id;
case 2: return can->counters[msg_id];
case 3: return toHex(it.value().front().dat);
}
}
} else if (role == Qt::UserRole) {
return std::next(can->can_msgs.begin(), index.row()).key();
} else if (role == Qt::FontRole) {
if (index.column() == 3) {
return QFontDatabase::systemFont(QFontDatabase::FixedFont);
}
}
return {};
}
void MessageListModel::updateState() {
int prev_row_count = row_count;
row_count = can->can_msgs.size();
int delta = row_count - prev_row_count;
if (delta > 0) {
beginInsertRows({}, prev_row_count, row_count - 1);
endInsertRows();
} else if (delta < 0) {
beginRemoveRows({}, row_count, prev_row_count - 1);
endRemoveRows();
}
if (row_count > 0) {
emit dataChanged(index(0, 0), index(row_count - 1, 3), {Qt::DisplayRole});
}
}
LoadDBCDialog::LoadDBCDialog(QWidget *parent) : QDialog(parent) {
QVBoxLayout *main_layout = new QVBoxLayout(this);
dbc_edit = new QTextEdit(this);
dbc_edit->setAcceptRichText(false);
dbc_edit->setPlaceholderText(tr("paste DBC file here"));
main_layout->addWidget(dbc_edit);
auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
main_layout->addWidget(buttonBox);
setFixedWidth(640);
connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
}
<commit_msg>cabana: display a clear button in filter string edit box (#26152)<commit_after>#include "tools/cabana/messageswidget.h"
#include <QCompleter>
#include <QDialogButtonBox>
#include <QFontDatabase>
#include <QHeaderView>
#include <QLineEdit>
#include <QPushButton>
#include <QSortFilterProxyModel>
#include <QTextEdit>
#include <QVBoxLayout>
#include "tools/cabana/dbcmanager.h"
MessagesWidget::MessagesWidget(QWidget *parent) : QWidget(parent) {
QVBoxLayout *main_layout = new QVBoxLayout(this);
// DBC file selector
QHBoxLayout *dbc_file_layout = new QHBoxLayout();
dbc_combo = new QComboBox(this);
auto dbc_names = dbc()->allDBCNames();
for (const auto &name : dbc_names) {
dbc_combo->addItem(QString::fromStdString(name));
}
dbc_combo->model()->sort(0);
dbc_combo->setEditable(true);
dbc_combo->setCurrentText(QString());
dbc_combo->setInsertPolicy(QComboBox::NoInsert);
dbc_combo->completer()->setCompletionMode(QCompleter::PopupCompletion);
QFont font;
font.setBold(true);
dbc_combo->lineEdit()->setFont(font);
dbc_file_layout->addWidget(dbc_combo);
QPushButton *load_from_paste = new QPushButton(tr("Load from paste"), this);
dbc_file_layout->addWidget(load_from_paste);
dbc_file_layout->addStretch();
QPushButton *save_btn = new QPushButton(tr("Save DBC"), this);
dbc_file_layout->addWidget(save_btn);
main_layout->addLayout(dbc_file_layout);
// message filter
QLineEdit *filter = new QLineEdit(this);
filter->setClearButtonEnabled(true);
filter->setPlaceholderText(tr("filter messages"));
main_layout->addWidget(filter);
// message table
table_widget = new QTableView(this);
model = new MessageListModel(this);
QSortFilterProxyModel *proxy_model = new QSortFilterProxyModel(this);
proxy_model->setSourceModel(model);
proxy_model->setFilterCaseSensitivity(Qt::CaseInsensitive);
proxy_model->setDynamicSortFilter(false);
table_widget->setModel(proxy_model);
table_widget->setSelectionBehavior(QAbstractItemView::SelectRows);
table_widget->setSelectionMode(QAbstractItemView::SingleSelection);
table_widget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
table_widget->setSortingEnabled(true);
table_widget->setColumnWidth(0, 250);
table_widget->setColumnWidth(1, 80);
table_widget->setColumnWidth(2, 80);
table_widget->horizontalHeader()->setStretchLastSection(true);
table_widget->verticalHeader()->hide();
table_widget->sortByColumn(0, Qt::AscendingOrder);
main_layout->addWidget(table_widget);
// signals/slots
QObject::connect(filter, &QLineEdit::textChanged, proxy_model, &QSortFilterProxyModel::setFilterFixedString);
QObject::connect(can, &CANMessages::updated, model, &MessageListModel::updateState);
QObject::connect(dbc_combo, SIGNAL(activated(const QString &)), SLOT(dbcSelectionChanged(const QString &)));
QObject::connect(load_from_paste, &QPushButton::clicked, this, &MessagesWidget::loadFromPaste);
QObject::connect(save_btn, &QPushButton::clicked, [=]() {
// TODO: save DBC to file
});
QObject::connect(table_widget->selectionModel(), &QItemSelectionModel::currentChanged, [=](const QModelIndex ¤t, const QModelIndex &previous) {
if (current.isValid()) {
emit msgSelectionChanged(current.data(Qt::UserRole).toString());
}
});
// For test purpose
dbc_combo->setCurrentText("toyota_nodsu_pt_generated");
}
void MessagesWidget::dbcSelectionChanged(const QString &dbc_file) {
dbc()->open(dbc_file);
// TODO: reset model?
table_widget->sortByColumn(0, Qt::AscendingOrder);
}
void MessagesWidget::loadFromPaste() {
LoadDBCDialog dlg(this);
if (dlg.exec()) {
dbc()->open("from paste", dlg.dbc_edit->toPlainText());
dbc_combo->setCurrentText("loaded from paste");
}
}
// MessageListModel
QVariant MessageListModel::headerData(int section, Qt::Orientation orientation, int role) const {
if (orientation == Qt::Horizontal && role == Qt::DisplayRole)
return (QString[]){"Name", "ID", "Count", "Bytes"}[section];
return {};
}
QVariant MessageListModel::data(const QModelIndex &index, int role) const {
if (role == Qt::DisplayRole) {
auto it = std::next(can->can_msgs.begin(), index.row());
if (it != can->can_msgs.end() && !it.value().empty()) {
const QString &msg_id = it.key();
switch (index.column()) {
case 0: {
auto msg = dbc()->msg(msg_id);
return msg ? msg->name.c_str() : "untitled";
}
case 1: return msg_id;
case 2: return can->counters[msg_id];
case 3: return toHex(it.value().front().dat);
}
}
} else if (role == Qt::UserRole) {
return std::next(can->can_msgs.begin(), index.row()).key();
} else if (role == Qt::FontRole) {
if (index.column() == 3) {
return QFontDatabase::systemFont(QFontDatabase::FixedFont);
}
}
return {};
}
void MessageListModel::updateState() {
int prev_row_count = row_count;
row_count = can->can_msgs.size();
int delta = row_count - prev_row_count;
if (delta > 0) {
beginInsertRows({}, prev_row_count, row_count - 1);
endInsertRows();
} else if (delta < 0) {
beginRemoveRows({}, row_count, prev_row_count - 1);
endRemoveRows();
}
if (row_count > 0) {
emit dataChanged(index(0, 0), index(row_count - 1, 3), {Qt::DisplayRole});
}
}
LoadDBCDialog::LoadDBCDialog(QWidget *parent) : QDialog(parent) {
QVBoxLayout *main_layout = new QVBoxLayout(this);
dbc_edit = new QTextEdit(this);
dbc_edit->setAcceptRichText(false);
dbc_edit->setPlaceholderText(tr("paste DBC file here"));
main_layout->addWidget(dbc_edit);
auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
main_layout->addWidget(buttonBox);
setFixedWidth(640);
connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: command.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: vg $ $Date: 2007-04-11 20:06:36 $
*
* 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 COMMAND_HXX
#define COMMAND_HXX
#include <iostream.h>
#include <tools/stream.hxx>
#define STRLEN 100
#ifndef UNX
#define TMPNAME "\\command.tmp"
#else
#define TMPNAME "/tmp/command.tmp"
#endif
/** Different types of spawnable programs
*/
enum ExeType
{
EXE, /// programm is a native executable
BAT, /// programm is a DOS-Batch
BTM /// programm is a 4DOS-Batch
};
#define COMMAND_NOTFOUND 0x0001
#define COMMAND_TOOBIG 0x0002
#define COMMAND_INVALID 0x0004
#define COMMAND_NOEXEC 0x0008
#define COMMAND_NOMEM 0x0010
#define COMMAND_UNKNOWN 0x0020
#ifdef WNT
#define COMMAND_SHELL "4nt.exe"
#endif
#ifdef UNX
#define COMMAND_SHELL "csh"
#endif
class CommandLine;
class LogWindow;
class CommandLine
{
friend class ChildProcess;
private:
char *CommandBuffer;
char *ComShell;
char **ppArgv;
BOOL bTmpWrite;
public:
CommandLine(BOOL bTmpWrite = FALSE);
CommandLine(const char *, BOOL bTmpWrite = FALSE);
CommandLine(const CommandLine&, BOOL bTmpWrite = FALSE);
virtual ~CommandLine();
int nArgc;
CommandLine& operator=(const CommandLine&);
CommandLine& operator=(const char *);
void BuildCommand(const char *);
char** GetCommand(void) { return ppArgv; }
void Strtokens(const char *);
void Print();
};
static ByteString thePath( "PATH" );
/** Declares and spawns a child process.
The spawned programm could be a native executable or a schell script.
*/
class CCommand
{
private:
ByteString aCommandLine;
ByteString aCommand;
char *pArgv;
char **ppArgv;
ULONG nArgc;
int nError;
protected:
void ImplInit();
void Initpp( ULONG nCount, ByteString &rStr );
public:
/** Creates the process specified without spawning it
@param rString specifies the programm or shell scrip
*/
CCommand( ByteString &rString );
/** Creates the process specified without spawning it
@param pChar specifies the programm or shell scrip
*/
CCommand( const char *pChar );
/** Try to find the given programm in specified path
@param sEnv specifies the current search path, defaulted by environment
@param sItem specifies the system shell
@return the Location (when programm was found)
*/
static ByteString Search( ByteString sEnv = thePath,
ByteString sItem = COMMAND_SHELL );
/** Spawns the Process
@return 0 when spawned without errors, otherwise a error code
*/
operator const int();
ByteString GetCommandLine_() { return aCommandLine; }
ByteString GetCommand() { return aCommand; }
char** GetCommandStr() { return ppArgv; }
};
#define COMMAND_EXECUTE_WINDOW 0x0000001
#define COMMAND_EXECUTE_CONSOLE 0x0000002
#define COMMAND_EXECUTE_HIDDEN 0x0000004
#define COMMAND_EXECUTE_START 0x0000008
#define COMMAND_EXECUTE_WAIT 0x0000010
#define COMMAND_EXECUTE_REMOTE 0x1000000
typedef ULONG CommandBits;
/** Allowes to spawn programms hidden, waiting etc.
@see CCommand
*/
class CCommandd : public CCommand
{
CommandBits nFlag;
public:
CCommandd( ByteString &rString, CommandBits nBits );
CCommandd( const char *pChar, CommandBits nBits );
operator const int();
};
#endif
<commit_msg>INTEGRATION: CWS os2port02 (1.3.68); FILE MERGED 2007/09/30 12:08:49 ydario 1.3.68.1: Issue number: i82034 Submitted by: ydario Reviewed by: ydario Commit of changes for OS/2 CWS source code integration.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: command.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2007-11-02 12:59:41 $
*
* 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 COMMAND_HXX
#define COMMAND_HXX
#include <iostream.h>
#include <tools/stream.hxx>
#define STRLEN 100
#ifndef UNX
#define TMPNAME "\\command.tmp"
#else
#define TMPNAME "/tmp/command.tmp"
#endif
/** Different types of spawnable programs
*/
enum ExeType
{
EXE, /// programm is a native executable
BAT, /// programm is a DOS-Batch
BTM /// programm is a 4DOS-Batch
};
#define COMMAND_NOTFOUND 0x0001
#define COMMAND_TOOBIG 0x0002
#define COMMAND_INVALID 0x0004
#define COMMAND_NOEXEC 0x0008
#define COMMAND_NOMEM 0x0010
#define COMMAND_UNKNOWN 0x0020
#ifdef WNT
#define COMMAND_SHELL "4nt.exe"
#endif
#ifdef OS2
#define COMMAND_SHELL "4os2.exe"
#endif
#ifdef UNX
#define COMMAND_SHELL "csh"
#endif
class CommandLine;
class LogWindow;
class CommandLine
{
friend class ChildProcess;
private:
char *CommandBuffer;
char *ComShell;
char **ppArgv;
BOOL bTmpWrite;
public:
CommandLine(BOOL bTmpWrite = FALSE);
CommandLine(const char *, BOOL bTmpWrite = FALSE);
CommandLine(const CommandLine&, BOOL bTmpWrite = FALSE);
virtual ~CommandLine();
int nArgc;
CommandLine& operator=(const CommandLine&);
CommandLine& operator=(const char *);
void BuildCommand(const char *);
char** GetCommand(void) { return ppArgv; }
void Strtokens(const char *);
void Print();
};
static ByteString thePath( "PATH" );
/** Declares and spawns a child process.
The spawned programm could be a native executable or a schell script.
*/
class CCommand
{
private:
ByteString aCommandLine;
ByteString aCommand;
char *pArgv;
char **ppArgv;
ULONG nArgc;
int nError;
protected:
void ImplInit();
void Initpp( ULONG nCount, ByteString &rStr );
public:
/** Creates the process specified without spawning it
@param rString specifies the programm or shell scrip
*/
CCommand( ByteString &rString );
/** Creates the process specified without spawning it
@param pChar specifies the programm or shell scrip
*/
CCommand( const char *pChar );
/** Try to find the given programm in specified path
@param sEnv specifies the current search path, defaulted by environment
@param sItem specifies the system shell
@return the Location (when programm was found)
*/
static ByteString Search( ByteString sEnv = thePath,
ByteString sItem = COMMAND_SHELL );
/** Spawns the Process
@return 0 when spawned without errors, otherwise a error code
*/
operator const int();
ByteString GetCommandLine_() { return aCommandLine; }
ByteString GetCommand() { return aCommand; }
char** GetCommandStr() { return ppArgv; }
};
#define COMMAND_EXECUTE_WINDOW 0x0000001
#define COMMAND_EXECUTE_CONSOLE 0x0000002
#define COMMAND_EXECUTE_HIDDEN 0x0000004
#define COMMAND_EXECUTE_START 0x0000008
#define COMMAND_EXECUTE_WAIT 0x0000010
#define COMMAND_EXECUTE_REMOTE 0x1000000
typedef ULONG CommandBits;
/** Allowes to spawn programms hidden, waiting etc.
@see CCommand
*/
class CCommandd : public CCommand
{
CommandBits nFlag;
public:
CCommandd( ByteString &rString, CommandBits nBits );
CCommandd( const char *pChar, CommandBits nBits );
operator const int();
};
#endif
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension.h"
#include "base/file_path.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "net/base/net_util.h"
#include "chrome/common/extensions/user_script.h"
#include "chrome/common/url_constants.h"
const char Extension::kManifestFilename[] = "manifest.json";
const wchar_t* Extension::kContentScriptsKey = L"content_scripts";
const wchar_t* Extension::kDescriptionKey = L"description";
const wchar_t* Extension::kFormatVersionKey = L"format_version";
const wchar_t* Extension::kIdKey = L"id";
const wchar_t* Extension::kJsKey = L"js";
const wchar_t* Extension::kMatchesKey = L"matches";
const wchar_t* Extension::kNameKey = L"name";
const wchar_t* Extension::kRunAtKey = L"run_at";
const wchar_t* Extension::kVersionKey = L"version";
const wchar_t* Extension::kZipHashKey = L"zip_hash";
const wchar_t* Extension::kPluginsDirKey = L"plugins_dir";
const char* Extension::kRunAtDocumentStartValue = "document_start";
const char* Extension::kRunAtDocumentEndValue = "document_end";
// Extension-related error messages. Some of these are simple patterns, where a
// '*' is replaced at runtime with a specific value. This is used instead of
// printf because we want to unit test them and scanf is hard to make
// cross-platform.
const char* Extension::kInvalidContentScriptError =
"Invalid value for 'content_scripts[*]'.";
const char* Extension::kInvalidContentScriptsListError =
"Invalid value for 'content_scripts'.";
const char* Extension::kInvalidDescriptionError =
"Invalid value for 'description'.";
const char* Extension::kInvalidFormatVersionError =
"Required value 'format_version' is missing or invalid.";
const char* Extension::kInvalidIdError =
"Required value 'id' is missing or invalid.";
const char* Extension::kInvalidJsCountError =
"Invalid value for 'content_scripts[*].js. Only one js file is currently "
"supported per-content script.";
const char* Extension::kInvalidJsError =
"Invalid value for 'content_scripts[*].js[*]'.";
const char* Extension::kInvalidJsListError =
"Required value 'content_scripts[*].js is missing or invalid.";
const char* Extension::kInvalidManifestError =
"Manifest is missing or invalid.";
const char* Extension::kInvalidMatchCountError =
"Invalid value for 'content_scripts[*].matches. There must be at least one "
"match specified.";
const char* Extension::kInvalidMatchError =
"Invalid value for 'content_scripts[*].matches[*]'.";
const char* Extension::kInvalidMatchesError =
"Required value 'content_scripts[*].matches' is missing or invalid.";
const char* Extension::kInvalidNameError =
"Required value 'name' is missing or invalid.";
const char* Extension::kInvalidRunAtError =
"Invalid value for 'content_scripts[*].run_at'.";
const char* Extension::kInvalidVersionError =
"Required value 'version' is missing or invalid.";
const char* Extension::kInvalidZipHashError =
"Required key 'zip_hash' is missing or invalid.";
const char* Extension::kInvalidPluginsDirError =
"Invalid value for 'plugins_dir'.";
const int Extension::kIdSize = 20; // SHA1 (160 bits) == 20 bytes
const std::string Extension::VersionString() const {
return version_->GetString();
}
// static
GURL Extension::GetResourceURL(const GURL& extension_url,
const std::string& relative_path) {
DCHECK(extension_url.SchemeIs(chrome::kExtensionScheme));
DCHECK(extension_url.path() == "/");
GURL ret_val = GURL(extension_url.spec() + relative_path);
DCHECK(StartsWithASCII(ret_val.spec(), extension_url.spec(), false));
return ret_val;
}
// static
FilePath Extension::GetResourcePath(const FilePath& extension_path,
const std::string& relative_path) {
// Build up a file:// URL and convert that back to a FilePath. This avoids
// URL encoding and path separator issues.
// Convert the extension's root to a file:// URL.
GURL extension_url = net::FilePathToFileURL(extension_path);
if (!extension_url.is_valid())
return FilePath();
// Append the requested path.
GURL::Replacements replacements;
std::string new_path(extension_url.path());
new_path += "/";
new_path += relative_path;
replacements.SetPathStr(new_path);
GURL file_url = extension_url.ReplaceComponents(replacements);
if (!file_url.is_valid())
return FilePath();
// Convert the result back to a FilePath.
FilePath ret_val;
if (!net::FileURLToFilePath(file_url, &ret_val))
return FilePath();
// Double-check that the path we ended up with is actually inside the
// extension root. We can do this with a simple prefix match because:
// a) We control the prefix on both sides, and they should match.
// b) GURL normalizes things like "../" and "//" before it gets to us.
if (ret_val.value().find(extension_path.value() +
FilePath::kSeparators[0]) != 0)
return FilePath();
return ret_val;
}
// Creates an error messages from a pattern.
static std::string FormatErrorMessage(const std::string& format,
const std::string s1) {
std::string ret_val = format;
ReplaceFirstSubstringAfterOffset(&ret_val, 0, "*", s1);
return ret_val;
}
static std::string FormatErrorMessage(const std::string& format,
const std::string s1,
const std::string s2) {
std::string ret_val = format;
ReplaceFirstSubstringAfterOffset(&ret_val, 0, "*", s1);
ReplaceFirstSubstringAfterOffset(&ret_val, 0, "*", s2);
return ret_val;
}
Extension::Extension(const FilePath& path) {
DCHECK(path.IsAbsolute());
#if defined(OS_WIN)
// Normalize any drive letter to upper-case. We do this for consistency with
// net_utils::FilePathToFileURL(), which does the same thing, to make string
// comparisons simpler.
std::wstring path_str = path.value();
if (path_str.size() >= 2 && path_str[0] >= L'a' && path_str[0] <= L'z' &&
path_str[1] == ':')
path_str[0] += ('A' - 'a');
path_ = FilePath(path_str);
#else
path_ = path;
#endif
}
bool Extension::InitFromValue(const DictionaryValue& source,
std::string* error) {
// Check format version.
int format_version = 0;
if (!source.GetInteger(kFormatVersionKey, &format_version) ||
static_cast<uint32>(format_version) != kExpectedFormatVersion) {
*error = kInvalidFormatVersionError;
return false;
}
// Initialize id.
if (!source.GetString(kIdKey, &id_)) {
*error = kInvalidIdError;
return false;
}
// Verify that the id is legal. The id is a hex string of the SHA-1 hash of
// the public key.
std::vector<uint8> id_bytes;
if (!HexStringToBytes(id_, &id_bytes) || id_bytes.size() != kIdSize) {
*error = kInvalidIdError;
return false;
}
// Initialize URL.
extension_url_ = GURL(std::string(chrome::kExtensionScheme) +
chrome::kStandardSchemeSeparator + id_ + "/");
// Initialize version.
std::string version_str;
if (!source.GetString(kVersionKey, &version_str)) {
*error = kInvalidVersionError;
return false;
}
version_.reset(Version::GetVersionFromString(version_str));
if (!version_.get()) {
*error = kInvalidVersionError;
return false;
}
// Initialize name.
if (!source.GetString(kNameKey, &name_)) {
*error = kInvalidNameError;
return false;
}
// Initialize description (optional).
if (source.HasKey(kDescriptionKey)) {
if (!source.GetString(kDescriptionKey, &description_)) {
*error = kInvalidDescriptionError;
return false;
}
}
// Initialize zip hash (only present in zip)
// There's no need to verify it at this point. If it's in a bogus format
// it won't pass the hash verify step.
if (source.HasKey(kZipHashKey)) {
if (!source.GetString(kZipHashKey, &zip_hash_)) {
*error = kInvalidZipHashError;
return false;
}
}
// Initialize plugins dir (optional).
if (source.HasKey(kPluginsDirKey)) {
std::string plugins_dir;
if (!source.GetString(kPluginsDirKey, &plugins_dir)) {
*error = kInvalidPluginsDirError;
return false;
}
plugins_dir_ = path_.AppendASCII(plugins_dir);
}
// Initialize content scripts (optional).
if (source.HasKey(kContentScriptsKey)) {
ListValue* list_value;
if (!source.GetList(kContentScriptsKey, &list_value)) {
*error = kInvalidContentScriptsListError;
return false;
}
for (size_t i = 0; i < list_value->GetSize(); ++i) {
DictionaryValue* content_script;
if (!list_value->GetDictionary(i, &content_script)) {
*error = FormatErrorMessage(kInvalidContentScriptError, IntToString(i));
return false;
}
ListValue* matches;
ListValue* js;
if (!content_script->GetList(kMatchesKey, &matches)) {
*error = FormatErrorMessage(kInvalidMatchesError, IntToString(i));
return false;
}
if (!content_script->GetList(kJsKey, &js)) {
*error = FormatErrorMessage(kInvalidJsListError, IntToString(i));
return false;
}
if (matches->GetSize() == 0) {
*error = FormatErrorMessage(kInvalidMatchCountError, IntToString(i));
return false;
}
// NOTE: Only one file is supported right now.
if (js->GetSize() != 1) {
*error = FormatErrorMessage(kInvalidJsCountError, IntToString(i));
return false;
}
UserScript script;
if (content_script->HasKey(kRunAtKey)) {
std::string run_location;
if (!content_script->GetString(kRunAtKey, &run_location)) {
*error = FormatErrorMessage(kInvalidRunAtError, IntToString(i));
return false;
}
if (run_location == kRunAtDocumentStartValue) {
script.set_run_location(UserScript::DOCUMENT_START);
} else if (run_location == kRunAtDocumentEndValue) {
script.set_run_location(UserScript::DOCUMENT_END);
} else {
*error = FormatErrorMessage(kInvalidRunAtError, IntToString(i));
return false;
}
}
for (size_t j = 0; j < matches->GetSize(); ++j) {
std::string match_str;
if (!matches->GetString(j, &match_str)) {
*error = FormatErrorMessage(kInvalidMatchError, IntToString(i),
IntToString(j));
return false;
}
URLPattern pattern;
if (!pattern.Parse(match_str)) {
*error = FormatErrorMessage(kInvalidMatchError, IntToString(i),
IntToString(j));
return false;
}
script.add_url_pattern(pattern);
}
// TODO(aa): Support multiple files.
std::string file;
if (!js->GetString(0, &file)) {
*error = FormatErrorMessage(kInvalidJsError, IntToString(i),
IntToString(0));
return false;
}
script.set_path(Extension::GetResourcePath(path(), file));
script.set_url(Extension::GetResourceURL(url(), file));
content_scripts_.push_back(script);
}
}
return true;
}
<commit_msg>Fix the linux modules build. Comparision between signed and unsigned integers. Review URL: http://codereview.chromium.org/28232<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/extension.h"
#include "base/file_path.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "net/base/net_util.h"
#include "chrome/common/extensions/user_script.h"
#include "chrome/common/url_constants.h"
const char Extension::kManifestFilename[] = "manifest.json";
const wchar_t* Extension::kContentScriptsKey = L"content_scripts";
const wchar_t* Extension::kDescriptionKey = L"description";
const wchar_t* Extension::kFormatVersionKey = L"format_version";
const wchar_t* Extension::kIdKey = L"id";
const wchar_t* Extension::kJsKey = L"js";
const wchar_t* Extension::kMatchesKey = L"matches";
const wchar_t* Extension::kNameKey = L"name";
const wchar_t* Extension::kRunAtKey = L"run_at";
const wchar_t* Extension::kVersionKey = L"version";
const wchar_t* Extension::kZipHashKey = L"zip_hash";
const wchar_t* Extension::kPluginsDirKey = L"plugins_dir";
const char* Extension::kRunAtDocumentStartValue = "document_start";
const char* Extension::kRunAtDocumentEndValue = "document_end";
// Extension-related error messages. Some of these are simple patterns, where a
// '*' is replaced at runtime with a specific value. This is used instead of
// printf because we want to unit test them and scanf is hard to make
// cross-platform.
const char* Extension::kInvalidContentScriptError =
"Invalid value for 'content_scripts[*]'.";
const char* Extension::kInvalidContentScriptsListError =
"Invalid value for 'content_scripts'.";
const char* Extension::kInvalidDescriptionError =
"Invalid value for 'description'.";
const char* Extension::kInvalidFormatVersionError =
"Required value 'format_version' is missing or invalid.";
const char* Extension::kInvalidIdError =
"Required value 'id' is missing or invalid.";
const char* Extension::kInvalidJsCountError =
"Invalid value for 'content_scripts[*].js. Only one js file is currently "
"supported per-content script.";
const char* Extension::kInvalidJsError =
"Invalid value for 'content_scripts[*].js[*]'.";
const char* Extension::kInvalidJsListError =
"Required value 'content_scripts[*].js is missing or invalid.";
const char* Extension::kInvalidManifestError =
"Manifest is missing or invalid.";
const char* Extension::kInvalidMatchCountError =
"Invalid value for 'content_scripts[*].matches. There must be at least one "
"match specified.";
const char* Extension::kInvalidMatchError =
"Invalid value for 'content_scripts[*].matches[*]'.";
const char* Extension::kInvalidMatchesError =
"Required value 'content_scripts[*].matches' is missing or invalid.";
const char* Extension::kInvalidNameError =
"Required value 'name' is missing or invalid.";
const char* Extension::kInvalidRunAtError =
"Invalid value for 'content_scripts[*].run_at'.";
const char* Extension::kInvalidVersionError =
"Required value 'version' is missing or invalid.";
const char* Extension::kInvalidZipHashError =
"Required key 'zip_hash' is missing or invalid.";
const char* Extension::kInvalidPluginsDirError =
"Invalid value for 'plugins_dir'.";
const size_t Extension::kIdSize = 20; // SHA1 (160 bits) == 20 bytes
const std::string Extension::VersionString() const {
return version_->GetString();
}
// static
GURL Extension::GetResourceURL(const GURL& extension_url,
const std::string& relative_path) {
DCHECK(extension_url.SchemeIs(chrome::kExtensionScheme));
DCHECK(extension_url.path() == "/");
GURL ret_val = GURL(extension_url.spec() + relative_path);
DCHECK(StartsWithASCII(ret_val.spec(), extension_url.spec(), false));
return ret_val;
}
// static
FilePath Extension::GetResourcePath(const FilePath& extension_path,
const std::string& relative_path) {
// Build up a file:// URL and convert that back to a FilePath. This avoids
// URL encoding and path separator issues.
// Convert the extension's root to a file:// URL.
GURL extension_url = net::FilePathToFileURL(extension_path);
if (!extension_url.is_valid())
return FilePath();
// Append the requested path.
GURL::Replacements replacements;
std::string new_path(extension_url.path());
new_path += "/";
new_path += relative_path;
replacements.SetPathStr(new_path);
GURL file_url = extension_url.ReplaceComponents(replacements);
if (!file_url.is_valid())
return FilePath();
// Convert the result back to a FilePath.
FilePath ret_val;
if (!net::FileURLToFilePath(file_url, &ret_val))
return FilePath();
// Double-check that the path we ended up with is actually inside the
// extension root. We can do this with a simple prefix match because:
// a) We control the prefix on both sides, and they should match.
// b) GURL normalizes things like "../" and "//" before it gets to us.
if (ret_val.value().find(extension_path.value() +
FilePath::kSeparators[0]) != 0)
return FilePath();
return ret_val;
}
// Creates an error messages from a pattern.
static std::string FormatErrorMessage(const std::string& format,
const std::string s1) {
std::string ret_val = format;
ReplaceFirstSubstringAfterOffset(&ret_val, 0, "*", s1);
return ret_val;
}
static std::string FormatErrorMessage(const std::string& format,
const std::string s1,
const std::string s2) {
std::string ret_val = format;
ReplaceFirstSubstringAfterOffset(&ret_val, 0, "*", s1);
ReplaceFirstSubstringAfterOffset(&ret_val, 0, "*", s2);
return ret_val;
}
Extension::Extension(const FilePath& path) {
DCHECK(path.IsAbsolute());
#if defined(OS_WIN)
// Normalize any drive letter to upper-case. We do this for consistency with
// net_utils::FilePathToFileURL(), which does the same thing, to make string
// comparisons simpler.
std::wstring path_str = path.value();
if (path_str.size() >= 2 && path_str[0] >= L'a' && path_str[0] <= L'z' &&
path_str[1] == ':')
path_str[0] += ('A' - 'a');
path_ = FilePath(path_str);
#else
path_ = path;
#endif
}
bool Extension::InitFromValue(const DictionaryValue& source,
std::string* error) {
// Check format version.
int format_version = 0;
if (!source.GetInteger(kFormatVersionKey, &format_version) ||
static_cast<uint32>(format_version) != kExpectedFormatVersion) {
*error = kInvalidFormatVersionError;
return false;
}
// Initialize id.
if (!source.GetString(kIdKey, &id_)) {
*error = kInvalidIdError;
return false;
}
// Verify that the id is legal. The id is a hex string of the SHA-1 hash of
// the public key.
std::vector<uint8> id_bytes;
if (!HexStringToBytes(id_, &id_bytes) || id_bytes.size() != kIdSize) {
*error = kInvalidIdError;
return false;
}
// Initialize URL.
extension_url_ = GURL(std::string(chrome::kExtensionScheme) +
chrome::kStandardSchemeSeparator + id_ + "/");
// Initialize version.
std::string version_str;
if (!source.GetString(kVersionKey, &version_str)) {
*error = kInvalidVersionError;
return false;
}
version_.reset(Version::GetVersionFromString(version_str));
if (!version_.get()) {
*error = kInvalidVersionError;
return false;
}
// Initialize name.
if (!source.GetString(kNameKey, &name_)) {
*error = kInvalidNameError;
return false;
}
// Initialize description (optional).
if (source.HasKey(kDescriptionKey)) {
if (!source.GetString(kDescriptionKey, &description_)) {
*error = kInvalidDescriptionError;
return false;
}
}
// Initialize zip hash (only present in zip)
// There's no need to verify it at this point. If it's in a bogus format
// it won't pass the hash verify step.
if (source.HasKey(kZipHashKey)) {
if (!source.GetString(kZipHashKey, &zip_hash_)) {
*error = kInvalidZipHashError;
return false;
}
}
// Initialize plugins dir (optional).
if (source.HasKey(kPluginsDirKey)) {
std::string plugins_dir;
if (!source.GetString(kPluginsDirKey, &plugins_dir)) {
*error = kInvalidPluginsDirError;
return false;
}
plugins_dir_ = path_.AppendASCII(plugins_dir);
}
// Initialize content scripts (optional).
if (source.HasKey(kContentScriptsKey)) {
ListValue* list_value;
if (!source.GetList(kContentScriptsKey, &list_value)) {
*error = kInvalidContentScriptsListError;
return false;
}
for (size_t i = 0; i < list_value->GetSize(); ++i) {
DictionaryValue* content_script;
if (!list_value->GetDictionary(i, &content_script)) {
*error = FormatErrorMessage(kInvalidContentScriptError, IntToString(i));
return false;
}
ListValue* matches;
ListValue* js;
if (!content_script->GetList(kMatchesKey, &matches)) {
*error = FormatErrorMessage(kInvalidMatchesError, IntToString(i));
return false;
}
if (!content_script->GetList(kJsKey, &js)) {
*error = FormatErrorMessage(kInvalidJsListError, IntToString(i));
return false;
}
if (matches->GetSize() == 0) {
*error = FormatErrorMessage(kInvalidMatchCountError, IntToString(i));
return false;
}
// NOTE: Only one file is supported right now.
if (js->GetSize() != 1) {
*error = FormatErrorMessage(kInvalidJsCountError, IntToString(i));
return false;
}
UserScript script;
if (content_script->HasKey(kRunAtKey)) {
std::string run_location;
if (!content_script->GetString(kRunAtKey, &run_location)) {
*error = FormatErrorMessage(kInvalidRunAtError, IntToString(i));
return false;
}
if (run_location == kRunAtDocumentStartValue) {
script.set_run_location(UserScript::DOCUMENT_START);
} else if (run_location == kRunAtDocumentEndValue) {
script.set_run_location(UserScript::DOCUMENT_END);
} else {
*error = FormatErrorMessage(kInvalidRunAtError, IntToString(i));
return false;
}
}
for (size_t j = 0; j < matches->GetSize(); ++j) {
std::string match_str;
if (!matches->GetString(j, &match_str)) {
*error = FormatErrorMessage(kInvalidMatchError, IntToString(i),
IntToString(j));
return false;
}
URLPattern pattern;
if (!pattern.Parse(match_str)) {
*error = FormatErrorMessage(kInvalidMatchError, IntToString(i),
IntToString(j));
return false;
}
script.add_url_pattern(pattern);
}
// TODO(aa): Support multiple files.
std::string file;
if (!js->GetString(0, &file)) {
*error = FormatErrorMessage(kInvalidJsError, IntToString(i),
IntToString(0));
return false;
}
script.set_path(Extension::GetResourcePath(path(), file));
script.set_url(Extension::GetResourceURL(url(), file));
content_scripts_.push_back(script);
}
}
return true;
}
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <SFML/Graphics/Color.hpp>
#include <SFML/Graphics/VertexArray.hpp>
// #include <SFML/Graphics/Vertex.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include "gui/cursor.hpp"
namespace qrw
{
Cursor* Cursor::cursor = 0;
Cursor::Cursor()
: position(0, 0),
child(0)
{}
Cursor::~Cursor()
{}
Cursor* Cursor::getCursor()
{
if(cursor == 0)
cursor = new Cursor();
return cursor;
}
void Cursor::setBoard(Board* board)
{
this->board = board;
}
sf::Vector2i Cursor::getPosition()
{
return position;
}
bool Cursor::move(int dx, int dy)
{
if(child != 0)
{
return child->move(dx, dy);
}
if(board == 0)
return false;
if(board->getSquare(position.x + dx, position.y + dy) == 0)
return false;
position.x += dx;
position.y += dy;
return true;
}
bool Cursor::setPosition(int x, int y)
{
if(board == 0)
return false;
if(board->getSquare(x, y) == 0)
return false;
position.x = x;
position.y = y;
return true;
}
bool Cursor::setPosition(sf::Vector2i pos)
{
return setPosition(pos.x, pos.y);
}
Cursor* Cursor::spawnChild()
{
if(child != 0)
return 0;
else
{
child = new Cursor();
child->setBoard(board);
child->setPosition(position.x, position.y);
}
return child;
}
Cursor* Cursor::getChild()
{
return child;
}
void Cursor::despawnChild()
{
if(child != 0)
{
delete child;
child = 0;
}
}
void Cursor::draw(sf::RenderTarget& target, sf::Vector2f position, float size)
{
sf::Color col(218, 0, 0, 120);
// Change color if child is present
if(getChild() == 0)
col += sf::Color(0, 218, 0, 0);
sf::VertexArray quad(sf::Quads);
quad.append(sf::Vertex(sf::Vector2f(position.x, position.y), col));
quad.append(sf::Vertex(sf::Vector2f(position.x + size, position.y), col));
quad.append(sf::Vertex(sf::Vector2f(position.x + size, position.y + size), col));
quad.append(sf::Vertex(sf::Vector2f(position.x, position.y + size), col));
target.draw(quad);
}
void Cursor::drawChild(sf::RenderTarget& target, sf::Vector2f position, float size)
{
if(getChild())
{
sf::Color col(218, 218, 0, 120);
sf::VertexArray quad(sf::Quads);
quad.append(sf::Vertex(sf::Vector2f(position.x, position.y), col));
quad.append(sf::Vertex(sf::Vector2f(position.x + size, position.y), col));
quad.append(sf::Vertex(sf::Vector2f(position.x + size, position.y + size), col));
quad.append(sf::Vertex(sf::Vector2f(position.x, position.y + size), col));
target.draw(quad);
}
}
}<commit_msg>Cursor::move() now uses setPosition() for updating cursor position.<commit_after>#include <stdio.h>
#include <SFML/Graphics/Color.hpp>
#include <SFML/Graphics/VertexArray.hpp>
// #include <SFML/Graphics/Vertex.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include "gui/cursor.hpp"
namespace qrw
{
Cursor* Cursor::cursor = 0;
Cursor::Cursor()
: position(0, 0),
child(0)
{}
Cursor::~Cursor()
{}
Cursor* Cursor::getCursor()
{
if(cursor == 0)
cursor = new Cursor();
return cursor;
}
void Cursor::setBoard(Board* board)
{
this->board = board;
}
sf::Vector2i Cursor::getPosition()
{
return position;
}
bool Cursor::move(int dx, int dy)
{
if(child != 0)
{
return child->move(dx, dy);
}
if(board == 0)
return false;
if(board->getSquare(position.x + dx, position.y + dy) == 0)
return false;
setPosition(position.x + dx, position.y + dy);
return true;
}
bool Cursor::setPosition(int x, int y)
{
if(board == 0)
return false;
if(board->getSquare(x, y) == 0)
return false;
position.x = x;
position.y = y;
return true;
}
bool Cursor::setPosition(sf::Vector2i pos)
{
return setPosition(pos.x, pos.y);
}
Cursor* Cursor::spawnChild()
{
if(child != 0)
return 0;
else
{
child = new Cursor();
child->setBoard(board);
child->setPosition(position.x, position.y);
}
return child;
}
Cursor* Cursor::getChild()
{
return child;
}
void Cursor::despawnChild()
{
if(child != 0)
{
delete child;
child = 0;
}
}
void Cursor::draw(sf::RenderTarget& target, sf::Vector2f position, float size)
{
sf::Color col(218, 0, 0, 120);
// Change color if child is present
if(getChild() == 0)
col += sf::Color(0, 218, 0, 0);
sf::VertexArray quad(sf::Quads);
quad.append(sf::Vertex(sf::Vector2f(position.x, position.y), col));
quad.append(sf::Vertex(sf::Vector2f(position.x + size, position.y), col));
quad.append(sf::Vertex(sf::Vector2f(position.x + size, position.y + size), col));
quad.append(sf::Vertex(sf::Vector2f(position.x, position.y + size), col));
target.draw(quad);
}
void Cursor::drawChild(sf::RenderTarget& target, sf::Vector2f position, float size)
{
if(getChild())
{
sf::Color col(218, 218, 0, 120);
sf::VertexArray quad(sf::Quads);
quad.append(sf::Vertex(sf::Vector2f(position.x, position.y), col));
quad.append(sf::Vertex(sf::Vector2f(position.x + size, position.y), col));
quad.append(sf::Vertex(sf::Vector2f(position.x + size, position.y + size), col));
quad.append(sf::Vertex(sf::Vector2f(position.x, position.y + size), col));
target.draw(quad);
}
}
}<|endoftext|>
|
<commit_before>// @(#)root/tree:$Name: $:$Id: TTreeFilePrefetch.cxx,v 1.10 2006/06/15 10:02:13 brun Exp $
// Author: Rene Brun 04/06/2006
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TTreeFilePrefetch //
// //
// A specialized TFilePrefetch object for a TTree //
// This class acts as a file cache, registering automatically the //
// baskets from the branches being processed (TTree::Draw or //
// TTree::Process and TSelectors) when in the learning phase. //
// The learning phase is by default 100 entries. //
// It can be changed via TTreeFileFrefetch::SetLearnEntries. //
// //
// This cache speeds-up considerably the performance, in particular //
// when the Tree is accessed remotely via a high latency network. //
// //
// The default cache size (10 Mbytes) may be changed via the function //
// TTreeFilePrefetch::SetCacheSize //
// //
// Only the baskets for the requested entry range are put in the cache //
// //
// For each Tree being processed a TTreeFilePrefetch object is created.//
// This object is automatically deleted when the Tree is deleted or //
// when the file is deleted. //
// //
// -Special case of a TChain //
// Once the training is done on the first Tree, the list of branches //
// in the cache is kept for the following files. //
// //
// -Special case of a TEventlist //
// if the Tree or TChain has a TEventlist, only the buffers //
// referenced by the list are put in the cache. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TTreeFilePrefetch.h"
#include "TChain.h"
#include "TBranch.h"
#include "TEventList.h"
#include "TObjString.h"
Int_t TTreeFilePrefetch::fgLearnEntries = 100;
ClassImp(TTreeFilePrefetch)
//______________________________________________________________________________
TTreeFilePrefetch::TTreeFilePrefetch() : TFilePrefetch(),
fEntryMin(0),
fEntryMax(1),
fEntryNext(1),
fZipBytes(0),
fNbranches(0),
fBranches(0),
fBrNames(0),
fOwner(0),
fTree(0),
fIsLearning(kTRUE)
{
// Default Constructor.
}
//______________________________________________________________________________
TTreeFilePrefetch::TTreeFilePrefetch(TTree *tree, Int_t buffersize) : TFilePrefetch(tree->GetCurrentFile(),buffersize),
fEntryMin(0),
fEntryMax(tree->GetEntries()),
fEntryNext(0),
fZipBytes(0),
fNbranches(0),
fBranches(0),
fBrNames(new TList),
fOwner(tree),
fTree(0),
fIsLearning(kTRUE)
{
// Constructor.
fEntryNext = fEntryMin + fgLearnEntries;
Int_t nleaves = tree->GetListOfLeaves()->GetEntries();
fBranches = new TBranch*[nleaves+10]; //add a margin just in case in a TChain?
}
//______________________________________________________________________________
TTreeFilePrefetch::TTreeFilePrefetch(const TTreeFilePrefetch &pf) : TFilePrefetch(pf)
{
// Copy Constructor.
}
//______________________________________________________________________________
TTreeFilePrefetch::~TTreeFilePrefetch()
{
// destructor. (in general called by the TFile destructor
delete [] fBranches;
if (fBrNames) {fBrNames->Delete(); delete fBrNames;}
}
//______________________________________________________________________________
TTreeFilePrefetch& TTreeFilePrefetch::operator=(const TTreeFilePrefetch& pf)
{
// Assignment.
if (this != &pf) TFilePrefetch::operator=(pf);
return *this;
}
//_____________________________________________________________________________
void TTreeFilePrefetch::AddBranch(TBranch *b)
{
//add a branch to the list of branches to be stored in the cache
//this function is called by TBranch::GetBasket
if (!fIsLearning) return;
//Is branch already in the cache?
Bool_t isNew = kTRUE;
for (int i=0;i<fNbranches;i++) {
if (fBranches[i] == b) {isNew = kFALSE; break;}
}
if (isNew) {
fTree = b->GetTree();
fBranches[fNbranches] = b;
fBrNames->Add(new TObjString(b->GetName()));
fZipBytes += b->GetZipBytes();
fNbranches++;
if (gDebug > 0) printf("Entry: %lld, registering branch: %s\n",b->GetTree()->GetReadEntry(),b->GetName());
}
}
//_____________________________________________________________________________
Bool_t TTreeFilePrefetch::FillBuffer()
{
//Fill the cache buffer with the branchse in the cache
if (fNbranches <= 0) return kFALSE;
TTree *tree = fBranches[0]->GetTree();
Long64_t entry = tree->GetReadEntry();
if (entry < fEntryNext) return kFALSE;
//estimate number of entries that can fit in the cache
fEntryNext = entry + tree->GetEntries()*fBufferSize/fZipBytes;
if (fEntryNext > fEntryMax) fEntryNext = fEntryMax+1;
//check if owner has a TEventList set. If yes we optimize for this special case
//reading only the baskets containing entries in the list
TEventList *elist = fOwner->GetEventList();
Long64_t chainOffset = 0;
if (elist) {
fEntryNext = fTree->GetEntries();
if (fOwner->IsA() ==TChain::Class()) {
TChain *chain = (TChain*)fOwner;
Int_t t = chain->GetTreeNumber();
chainOffset = chain->GetTreeOffset()[t];
}
}
//clear cache buffer
TFilePrefetch::Prefetch(0,0);
//store baskets
for (Int_t i=0;i<fNbranches;i++) {
TBranch *b = fBranches[i];
Int_t nb = b->GetMaxBaskets();
Int_t *lbaskets = b->GetBasketBytes();
Long64_t *entries = b->GetBasketEntry();
if (!lbaskets || !entries) continue;
//we have found the branch. We now register all its baskets
//from the requested offset to the basket below fEntrymax
for (Int_t j=0;j<nb;j++) {
Long64_t pos = b->GetBasketSeek(j);
Int_t len = lbaskets[j];
if (pos <= 0 || len <= 0) continue;
if (entries[j] > fEntryNext) continue;
if (entries[j] < entry && (j<nb-1 && entries[j+1] < entry)) continue;
if (elist) {
Long64_t emax = fEntryMax;
if (j<nb-1) emax = entries[j+1]-1;
if (!elist->ContainsRange(entries[j]+chainOffset,emax+chainOffset)) continue;
}
TFilePrefetch::Prefetch(pos,len);
}
if (gDebug > 0) printf("Entry: %lld, registering baskets branch %s, fEntryNext=%lld, fNseek=%d, fNtot=%d\n",entry,fBranches[i]->GetName(),fEntryNext,fNseek,fNtot);
}
fIsLearning = kFALSE;
return kTRUE;
}
//_____________________________________________________________________________
Int_t TTreeFilePrefetch::GetLearnEntries()
{
//static function returning the number of entries used to train the cache
//see SetLearnEntries
return fgLearnEntries;
}
//_____________________________________________________________________________
TTree *TTreeFilePrefetch::GetTree() const
{
//return Tree in the cache
if (fNbranches <= 0) return 0;
return fBranches[0]->GetTree();
}
//_____________________________________________________________________________
Bool_t TTreeFilePrefetch::ReadBuffer(char *buf, Long64_t pos, Int_t len)
{
// Read buffer at position pos.
// If pos is in the list of prefetched blocks read from fBuffer,
// then try to fill the cache from the list of selected branches,
// otherwise normal read from file. Returns kTRUE in case of failure.
// This function overloads TFilePrefetch::ReadBuffer.
// It returns kFALSE if the requested block is in the cache
//Is request already in the cache?
Bool_t inCache = !TFilePrefetch::ReadBuffer(buf,pos,len);
if (inCache) return kFALSE;
//not found in cache. Do we need to fill the cache?
Bool_t bufferFilled = FillBuffer();
if (bufferFilled) return TFilePrefetch::ReadBuffer(buf,pos,len);
return kTRUE;
}
//_____________________________________________________________________________
void TTreeFilePrefetch::SetEntryRange(Long64_t emin, Long64_t emax)
{
// Set the minimum and maximum entry number to be processed
// this information helps to optimize the number of baskets to read
// when prefetching the branch buffers.
fEntryMin = emin;
fEntryMax = emax;
fEntryNext = fEntryMin + fgLearnEntries;
fIsLearning = kTRUE;
fNbranches = 0;
fZipBytes = 0;
if (fBrNames) fBrNames->Delete();
if (gDebug > 0) printf("SetEntryRange: fEntryMin=%lld, fEntryMax=%lld, fEntryNext=%lld\n",fEntryMin,fEntryMax,fEntryNext);
}
//_____________________________________________________________________________
void TTreeFilePrefetch::SetLearnEntries(Int_t n)
{
// Static function to set the number of entries to be used in learning mode
// The default value for n is 10. n must be >= 1
if (n < 1) n = 1;
fgLearnEntries = n;
}
//_____________________________________________________________________________
void TTreeFilePrefetch::UpdateBranches(TTree *tree)
{
//update pointer to current Tree and recompute pointers to the branches in the cache
fTree = tree;
Prefetch(0,0);
fEntryMin = 0;
fEntryMax = fTree->GetEntries();
fEntryNext = fEntryMin + fgLearnEntries;
fZipBytes = 0;
fNbranches = 0;
TIter next(fBrNames);
TObjString *os;
while ((os = (TObjString*)next())) {
TBranch *b = fTree->GetBranch(os->GetName());
if (!b) continue;
fBranches[fNbranches] = b;
fZipBytes += b->GetZipBytes();
fNbranches++;
}
}
<commit_msg>Use GetEntriesFast instead of GetEntries in the constructor. This prevents a recursive call to TChain::LoadTree.<commit_after>// @(#)root/tree:$Name: $:$Id: TTreeFilePrefetch.cxx,v 1.11 2006/06/16 11:01:16 brun Exp $
// Author: Rene Brun 04/06/2006
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TTreeFilePrefetch //
// //
// A specialized TFilePrefetch object for a TTree //
// This class acts as a file cache, registering automatically the //
// baskets from the branches being processed (TTree::Draw or //
// TTree::Process and TSelectors) when in the learning phase. //
// The learning phase is by default 100 entries. //
// It can be changed via TTreeFileFrefetch::SetLearnEntries. //
// //
// This cache speeds-up considerably the performance, in particular //
// when the Tree is accessed remotely via a high latency network. //
// //
// The default cache size (10 Mbytes) may be changed via the function //
// TTreeFilePrefetch::SetCacheSize //
// //
// Only the baskets for the requested entry range are put in the cache //
// //
// For each Tree being processed a TTreeFilePrefetch object is created.//
// This object is automatically deleted when the Tree is deleted or //
// when the file is deleted. //
// //
// -Special case of a TChain //
// Once the training is done on the first Tree, the list of branches //
// in the cache is kept for the following files. //
// //
// -Special case of a TEventlist //
// if the Tree or TChain has a TEventlist, only the buffers //
// referenced by the list are put in the cache. //
// //
//////////////////////////////////////////////////////////////////////////
#include "TTreeFilePrefetch.h"
#include "TChain.h"
#include "TBranch.h"
#include "TEventList.h"
#include "TObjString.h"
Int_t TTreeFilePrefetch::fgLearnEntries = 100;
ClassImp(TTreeFilePrefetch)
//______________________________________________________________________________
TTreeFilePrefetch::TTreeFilePrefetch() : TFilePrefetch(),
fEntryMin(0),
fEntryMax(1),
fEntryNext(1),
fZipBytes(0),
fNbranches(0),
fBranches(0),
fBrNames(0),
fOwner(0),
fTree(0),
fIsLearning(kTRUE)
{
// Default Constructor.
}
//______________________________________________________________________________
TTreeFilePrefetch::TTreeFilePrefetch(TTree *tree, Int_t buffersize) : TFilePrefetch(tree->GetCurrentFile(),buffersize),
fEntryMin(0),
fEntryMax(tree->GetEntriesFast()),
fEntryNext(0),
fZipBytes(0),
fNbranches(0),
fBranches(0),
fBrNames(new TList),
fOwner(tree),
fTree(0),
fIsLearning(kTRUE)
{
// Constructor.
fEntryNext = fEntryMin + fgLearnEntries;
Int_t nleaves = tree->GetListOfLeaves()->GetEntries();
fBranches = new TBranch*[nleaves+10]; //add a margin just in case in a TChain?
}
//______________________________________________________________________________
TTreeFilePrefetch::TTreeFilePrefetch(const TTreeFilePrefetch &pf) : TFilePrefetch(pf)
{
// Copy Constructor.
}
//______________________________________________________________________________
TTreeFilePrefetch::~TTreeFilePrefetch()
{
// destructor. (in general called by the TFile destructor
delete [] fBranches;
if (fBrNames) {fBrNames->Delete(); delete fBrNames;}
}
//______________________________________________________________________________
TTreeFilePrefetch& TTreeFilePrefetch::operator=(const TTreeFilePrefetch& pf)
{
// Assignment.
if (this != &pf) TFilePrefetch::operator=(pf);
return *this;
}
//_____________________________________________________________________________
void TTreeFilePrefetch::AddBranch(TBranch *b)
{
//add a branch to the list of branches to be stored in the cache
//this function is called by TBranch::GetBasket
if (!fIsLearning) return;
//Is branch already in the cache?
Bool_t isNew = kTRUE;
for (int i=0;i<fNbranches;i++) {
if (fBranches[i] == b) {isNew = kFALSE; break;}
}
if (isNew) {
fTree = b->GetTree();
fBranches[fNbranches] = b;
fBrNames->Add(new TObjString(b->GetName()));
fZipBytes += b->GetZipBytes();
fNbranches++;
if (gDebug > 0) printf("Entry: %lld, registering branch: %s\n",b->GetTree()->GetReadEntry(),b->GetName());
}
}
//_____________________________________________________________________________
Bool_t TTreeFilePrefetch::FillBuffer()
{
//Fill the cache buffer with the branchse in the cache
if (fNbranches <= 0) return kFALSE;
TTree *tree = fBranches[0]->GetTree();
Long64_t entry = tree->GetReadEntry();
if (entry < fEntryNext) return kFALSE;
//estimate number of entries that can fit in the cache
fEntryNext = entry + tree->GetEntries()*fBufferSize/fZipBytes;
if (fEntryNext > fEntryMax) fEntryNext = fEntryMax+1;
//check if owner has a TEventList set. If yes we optimize for this special case
//reading only the baskets containing entries in the list
TEventList *elist = fOwner->GetEventList();
Long64_t chainOffset = 0;
if (elist) {
fEntryNext = fTree->GetEntries();
if (fOwner->IsA() ==TChain::Class()) {
TChain *chain = (TChain*)fOwner;
Int_t t = chain->GetTreeNumber();
chainOffset = chain->GetTreeOffset()[t];
}
}
//clear cache buffer
TFilePrefetch::Prefetch(0,0);
//store baskets
for (Int_t i=0;i<fNbranches;i++) {
TBranch *b = fBranches[i];
Int_t nb = b->GetMaxBaskets();
Int_t *lbaskets = b->GetBasketBytes();
Long64_t *entries = b->GetBasketEntry();
if (!lbaskets || !entries) continue;
//we have found the branch. We now register all its baskets
//from the requested offset to the basket below fEntrymax
for (Int_t j=0;j<nb;j++) {
Long64_t pos = b->GetBasketSeek(j);
Int_t len = lbaskets[j];
if (pos <= 0 || len <= 0) continue;
if (entries[j] > fEntryNext) continue;
if (entries[j] < entry && (j<nb-1 && entries[j+1] < entry)) continue;
if (elist) {
Long64_t emax = fEntryMax;
if (j<nb-1) emax = entries[j+1]-1;
if (!elist->ContainsRange(entries[j]+chainOffset,emax+chainOffset)) continue;
}
TFilePrefetch::Prefetch(pos,len);
}
if (gDebug > 0) printf("Entry: %lld, registering baskets branch %s, fEntryNext=%lld, fNseek=%d, fNtot=%d\n",entry,fBranches[i]->GetName(),fEntryNext,fNseek,fNtot);
}
fIsLearning = kFALSE;
return kTRUE;
}
//_____________________________________________________________________________
Int_t TTreeFilePrefetch::GetLearnEntries()
{
//static function returning the number of entries used to train the cache
//see SetLearnEntries
return fgLearnEntries;
}
//_____________________________________________________________________________
TTree *TTreeFilePrefetch::GetTree() const
{
//return Tree in the cache
if (fNbranches <= 0) return 0;
return fBranches[0]->GetTree();
}
//_____________________________________________________________________________
Bool_t TTreeFilePrefetch::ReadBuffer(char *buf, Long64_t pos, Int_t len)
{
// Read buffer at position pos.
// If pos is in the list of prefetched blocks read from fBuffer,
// then try to fill the cache from the list of selected branches,
// otherwise normal read from file. Returns kTRUE in case of failure.
// This function overloads TFilePrefetch::ReadBuffer.
// It returns kFALSE if the requested block is in the cache
//Is request already in the cache?
Bool_t inCache = !TFilePrefetch::ReadBuffer(buf,pos,len);
if (inCache) return kFALSE;
//not found in cache. Do we need to fill the cache?
Bool_t bufferFilled = FillBuffer();
if (bufferFilled) return TFilePrefetch::ReadBuffer(buf,pos,len);
return kTRUE;
}
//_____________________________________________________________________________
void TTreeFilePrefetch::SetEntryRange(Long64_t emin, Long64_t emax)
{
// Set the minimum and maximum entry number to be processed
// this information helps to optimize the number of baskets to read
// when prefetching the branch buffers.
fEntryMin = emin;
fEntryMax = emax;
fEntryNext = fEntryMin + fgLearnEntries;
fIsLearning = kTRUE;
fNbranches = 0;
fZipBytes = 0;
if (fBrNames) fBrNames->Delete();
if (gDebug > 0) printf("SetEntryRange: fEntryMin=%lld, fEntryMax=%lld, fEntryNext=%lld\n",fEntryMin,fEntryMax,fEntryNext);
}
//_____________________________________________________________________________
void TTreeFilePrefetch::SetLearnEntries(Int_t n)
{
// Static function to set the number of entries to be used in learning mode
// The default value for n is 10. n must be >= 1
if (n < 1) n = 1;
fgLearnEntries = n;
}
//_____________________________________________________________________________
void TTreeFilePrefetch::UpdateBranches(TTree *tree)
{
//update pointer to current Tree and recompute pointers to the branches in the cache
fTree = tree;
Prefetch(0,0);
fEntryMin = 0;
fEntryMax = fTree->GetEntries();
fEntryNext = fEntryMin + fgLearnEntries;
fZipBytes = 0;
fNbranches = 0;
TIter next(fBrNames);
TObjString *os;
while ((os = (TObjString*)next())) {
TBranch *b = fTree->GetBranch(os->GetName());
if (!b) continue;
fBranches[fNbranches] = b;
fZipBytes += b->GetZipBytes();
fNbranches++;
}
}
<|endoftext|>
|
<commit_before>#include "world.h"
#include "roomsmodel.h"
World::World(const QString &name, const QSize &size, QObject *parent) :
QObject(parent)
{
this->name = name;
this->size = size;
rooms = new RoomsModel(this);
}
void World::addRoom(QString const& name)
{
Room *room = new Room(name);
rooms->appendRoom(room);
}
int World::countRooms() const
{
return rooms->rowCount(QModelIndex());
}
Room *World::getRoom(int index) const
{
return rooms->at(index);
}
QVector<Room*> *World::getRooms() const
{
return rooms;
}
QSize World::getSize() const
{
return size;
}
QAbstractItemModel *World::roomsModel() const
{
return rooms;
}
<commit_msg>removing getRooms(): useless<commit_after>#include "world.h"
#include "roomsmodel.h"
World::World(const QString &name, const QSize &size, QObject *parent) :
QObject(parent)
{
this->name = name;
this->size = size;
rooms = new RoomsModel(this);
}
void World::addRoom(QString const& name)
{
Room *room = new Room(name);
rooms->appendRoom(room);
}
int World::countRooms() const
{
return rooms->rowCount(QModelIndex());
}
Room *World::getRoom(int index) const
{
return rooms->at(index);
}
QSize World::getSize() const
{
return size;
}
QAbstractItemModel *World::roomsModel() const
{
return rooms;
}
<|endoftext|>
|
<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
// Model matrix sliders
ui->modelScaleXSlider->init();
ui->modelScaleYSlider->init();
ui->modelScaleZSlider->init();
ui->modelRotateXSlider->init(1.0f, 0, "°");
ui->modelRotateYSlider->init(1.0f, 0, "°");
ui->modelRotateZSlider->init(1.0f, 0, "°");
ui->modelTranslateXSlider->init();
ui->modelTranslateYSlider->init();
ui->modelTranslateZSlider->init();
}
MainWindow::~MainWindow()
{
delete ui;
}
<commit_msg>Added initialisation of view widgets<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
// Model matrix sliders
ui->modelScaleXSlider->init();
ui->modelScaleYSlider->init();
ui->modelScaleZSlider->init();
ui->modelRotateXSlider->init(1.0f, 0, "°");
ui->modelRotateYSlider->init(1.0f, 0, "°");
ui->modelRotateZSlider->init(1.0f, 0, "°");
ui->modelTranslateXSlider->init();
ui->modelTranslateYSlider->init();
ui->modelTranslateZSlider->init();
// View matrix sliders
ui->viewPositionXSlider->init();
ui->viewPositionYSlider->init();
ui->viewPositionZSlider->init();
ui->viewTargetXSlider->init();
ui->viewTargetYSlider->init();
ui->viewTargetZSlider->init();
ui->viewUpXSlider->init();
ui->viewUpYSlider->init();
ui->viewUpZSlider->init();
}
MainWindow::~MainWindow()
{
delete ui;
}
<|endoftext|>
|
<commit_before>#include "mainwindow.hpp"
#include <QDebug>
#include <QComboBox>
#include "menupage.hpp"
#include "game_window.hpp"
#include "settingspage.hpp"
#include "gameoverpage.hpp"
#include "settings.hpp"
#include "except.hpp"
#include "scorespage.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
setMinimumSize(Globals::Width, Globals::Height);
rootPageWidget = new QWidget;
layoutRootPageWidget = new QVBoxLayout(rootPageWidget);
pageWidget = new MenuPage(this);
layoutRootPageWidget->addWidget(pageWidget);
setCentralWidget(rootPageWidget);
}
MainWindow::~MainWindow()
{
}
void MainWindow::setCurrentIndex(int value)
{
qDebug() << value;
if (!layoutRootPageWidget->isEmpty())
{
layoutRootPageWidget->removeWidget(pageWidget);
pageWidget->deleteLater();
pageWidget = nullptr;
}
switch (value) {
case 0:
pageWidget = new MenuPage(this);
break;
case 1:
pageWidget = new GameWindow(this, m_currentLevel);
break;
case 2:
pageWidget = new SettingsPage(this);
break;
case 3:
pageWidget = new GameOverPage(this, m_message);
m_finalScore = 0;
break;
case 4:
pageWidget = new ScoresPage(this);
break;
default:
break;
}
if (pageWidget)
{
layoutRootPageWidget->addWidget(pageWidget);
}
}
void MainWindow::moveToGamePage()
{
qDebug() << "moveToGamePage";
setCurrentIndex(1);
}
void MainWindow::exitFromGame()
{
qDebug() << "exitFromGame";
this->close();
}
void MainWindow::moveToMenuPage()
{
qDebug() << "moveToMenuPage";
m_currentLevel = 1;
setCurrentIndex(0);
}
void MainWindow::moveToSettingsPage()
{
qDebug() << "moveToSettingsPage";
setCurrentIndex(2);
}
void MainWindow::moveToNextLevel()
{
qDebug() << "moveToNextLevel";
// Increase game level number.
m_currentLevel++;
// Load the next game level.
setCurrentIndex(1);
}
void MainWindow::finishGame(GameState gameState, size_t score)
{
switch (gameState)
{
case GameState::WIN:
{
m_finalScore += score;
// Move to next level.
if (m_currentLevel < Settings::Instance().m_mainParameters.m_levelsNumber)
{
moveToNextLevel();
}
else
{
m_message = "Game over. Congratulations! You win!\nYour score: " \
+ QString::number(m_finalScore);
m_currentLevel = 1;
m_finalScore = 0;
// Stop the game.
setCurrentIndex(3);
}
return;
}
case GameState::LOSE:
{
m_message = "Game over. You lose!\nYour score: " \
+ QString::number(m_finalScore);
m_currentLevel = 1;
m_finalScore = 0;
// Stop the game.
setCurrentIndex(3);
return;
}
case GameState::MENU:
{
moveToMenuPage();
return;
}
case GameState::PAUSE:
{
return;
}
}
}
void MainWindow::moveToScoresPage()
{
qDebug() << "moveToScoresPage";
setCurrentIndex(4);
}
<commit_msg>fix final score in case of failure<commit_after>#include "mainwindow.hpp"
#include <QDebug>
#include <QComboBox>
#include "menupage.hpp"
#include "game_window.hpp"
#include "settingspage.hpp"
#include "gameoverpage.hpp"
#include "settings.hpp"
#include "except.hpp"
#include "scorespage.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
setMinimumSize(Globals::Width, Globals::Height);
rootPageWidget = new QWidget;
layoutRootPageWidget = new QVBoxLayout(rootPageWidget);
pageWidget = new MenuPage(this);
layoutRootPageWidget->addWidget(pageWidget);
setCentralWidget(rootPageWidget);
}
MainWindow::~MainWindow()
{
}
void MainWindow::setCurrentIndex(int value)
{
qDebug() << value;
if (!layoutRootPageWidget->isEmpty())
{
layoutRootPageWidget->removeWidget(pageWidget);
pageWidget->deleteLater();
pageWidget = nullptr;
}
switch (value) {
case 0:
pageWidget = new MenuPage(this);
break;
case 1:
pageWidget = new GameWindow(this, m_currentLevel);
break;
case 2:
pageWidget = new SettingsPage(this);
break;
case 3:
pageWidget = new GameOverPage(this, m_message);
m_finalScore = 0;
break;
case 4:
pageWidget = new ScoresPage(this);
break;
default:
break;
}
if (pageWidget)
{
layoutRootPageWidget->addWidget(pageWidget);
}
}
void MainWindow::moveToGamePage()
{
qDebug() << "moveToGamePage";
setCurrentIndex(1);
}
void MainWindow::exitFromGame()
{
qDebug() << "exitFromGame";
this->close();
}
void MainWindow::moveToMenuPage()
{
qDebug() << "moveToMenuPage";
m_currentLevel = 1;
setCurrentIndex(0);
}
void MainWindow::moveToSettingsPage()
{
qDebug() << "moveToSettingsPage";
setCurrentIndex(2);
}
void MainWindow::moveToNextLevel()
{
qDebug() << "moveToNextLevel";
// Increase game level number.
m_currentLevel++;
// Load the next game level.
setCurrentIndex(1);
}
void MainWindow::finishGame(GameState gameState, size_t score)
{
m_finalScore += score;
switch (gameState)
{
case GameState::WIN:
{
// Move to next level.
if (m_currentLevel < Settings::Instance().m_mainParameters.m_levelsNumber)
{
moveToNextLevel();
}
else
{
m_message = "Game over. Congratulations! You win!\nYour score: " \
+ QString::number(m_finalScore);
m_currentLevel = 1;
m_finalScore = 0;
// Stop the game.
setCurrentIndex(3);
}
return;
}
case GameState::LOSE:
{
m_message = "Game over. You lose!\nYour score: " \
+ QString::number(m_finalScore);
m_currentLevel = 1;
m_finalScore = 0;
// Stop the game.
setCurrentIndex(3);
return;
}
case GameState::MENU:
{
moveToMenuPage();
return;
}
case GameState::PAUSE:
{
return;
}
}
}
void MainWindow::moveToScoresPage()
{
qDebug() << "moveToScoresPage";
setCurrentIndex(4);
}
<|endoftext|>
|
<commit_before>//This tutorial illustrates how to create an histogram with polygonal
//bins (TH2Poly), fill it and draw it. The initial data are stored
//in TMultiGraphs. They represent the european countries.
//The histogram filling is done according to a Mercator projection,
//therefore the bin contains should be proportional to the real surface
//of the countries.
//
//The initial data have been downloaded from: http://www.maproom.psu.edu/dcw/
//This database was developed in 1991/1992 and national boundaries reflect
//political reality as of that time.
//
//Author: Olivier Couet
void th2polyEurope()
{
Int_t i,j;
Double_t lon1 = -25;
Double_t lon2 = 35;
Double_t lat1 = 34;
Double_t lat2 = 72;
Double_t R = (lat2-lat1)/(lon2-lon1);
Int_t W = 800;
Int_t H = (Int_t)(R*800);
gStyle->SetTitleX(0.2);
gStyle->SetStatY(0.89);
gStyle->SetStatW(0.15);
// Canvas used to draw TH2Poly (the map)
TCanvas *ce = new TCanvas("ce", "ce",0,0,W,H);
ce->ToggleEventStatus();
ce->SetGridx();
ce->SetGridy();
// Real surfaces taken from Wikipedia.
const Int_t nx = 36;
// see http://en.wikipedia.org/wiki/Area_and_population_of_European_countries
char *countries[nx] = { "france", "spain", "sweden", "germany", "finland",
"norway", "poland", "italy", "yugoslavia", "united_kingdom",
"romania", "belarus","greece", "czechoslovakia","bulgaria",
"iceland", "hungary","portugal","austria", "ireland",
"lithuania", "latvia", "estonia", "denmark", "netherlands",
"switzerland","moldova","belgium", "albania", "cyprus",
"luxembourg", "andorra","malta", "liechtenstein", "san_marino",
"monaco" };
Float_t surfaces[nx] = { 547030, 505580, 449964, 357021, 338145,
324220, 312685, 301230, 255438, 244820,
237500, 207600, 131940, 127711, 110910,
103000, 93030, 89242, 83870, 70280,
65200, 64589, 45226, 43094, 41526,
41290, 33843, 30528, 28748, 9250,
2586, 468, 316, 160, 61,
2};
TH1F *h = new TH1F("h","Countries surfaces (in km^{2})",3,0,3);
for (i=0; i<nx; i++) h->Fill(countries[i], surfaces[i]);
h->LabelsDeflate();
TFile::SetCacheFileDir(".");
TFile *f;
f = TFile::Open("http://root.cern.ch/files/europe.root","cacheread");
TH2Poly *p = new TH2Poly(
"Europe",
"Europe (bin contents are normalized to the surfaces in km^{2})",
lon1,lon2,lat1,lat2);
p->GetXaxis()->SetNdivisions(520);
p->GetXaxis()->SetTitle("longitude");
p->GetYaxis()->SetTitle("latitude");
TMultiGraph *mg;
TKey *key;
TIter nextkey(gDirectory->GetListOfKeys());
while (key = (TKey*)nextkey()) {
obj = key->ReadObj();
if (obj->InheritsFrom("TMultiGraph")) {
mg = (TMultiGraph*)obj;
p->AddBin(mg);
}
}
TRandom r;
Double_t longitude, latitude;
Double_t x, y, pi4 = TMath::Pi()/4, alpha = TMath::Pi()/360;
gBenchmark->Start("Partitioning");
p->ChangePartition(100, 100);
gBenchmark->Show("Partitioning");
// Fill TH2Poly according to a Mercator projection.
gBenchmark->Start("Filling");
for (i=0; i<500000; i++) {
longitude = r.Uniform(lon1,lon2);
latitude = r.Uniform(lat1,lat2);
x = longitude;
y = 38*TMath::Log(TMath::Tan(pi4+alpha*latitude));
p->Fill(x,y);
}
gBenchmark->Show("Filling");
Int_t nbins = p->GetNumberOfBins();
Double_t maximum = p->GetMaximum();
printf("Nbins = %d Minimum = %g Maximum = %g Integral = %f \n",
nbins,
p->GetMinimum(),
maximum,
p->Integral());
// h2 contains the surfaces computed from TH2Poly.
TH1F *h2 = h->Clone("h2");
h2->Reset();
for (j=0; j<nx; j++) {
for (i=0; i<nbins; i++) {
if (strstr(countries[j],p->GetBinName(i+1))) {
h2->Fill(countries[j],p->GetBinContent(i+1));
h2->SetBinError(j, p->GetBinError(i+1));
}
}
}
// Normalize the TH2Poly bin contents to the real surfaces.
Double_t scale = surfaces[0]/maximum;
for (i=0; i<nbins; i++) p->SetBinContent(i+1, scale*p->GetBinContent(i+1));
gStyle->SetOptStat(1111);
gStyle->SetPalette(1);
p->Draw("COL");
TCanvas *c1 = new TCanvas("c1", "c1",W+10,0,W-20,H);
c1->SetRightMargin(0.047);
Double_t scale = h->GetMaximum()/h2->GetMaximum();
h->SetStats(0);
h->SetLineColor(kRed-3);
h->SetLineWidth(2);
h->SetMarkerStyle(20);
h->SetMarkerColor(kBlue);
h->SetMarkerSize(0.8);
h->Draw("LP");
h->GetXaxis()->SetLabelFont(42);
h->GetXaxis()->SetLabelSize(0.03);
h->GetYaxis()->SetLabelFont(42);
h2->Scale(scale);
Double_t scale2=TMath::Sqrt(scale);
for (i=0; i<nx; i++) h2->SetBinError(i+1, scale2*h2->GetBinError(i+1));
h2->Draw("E SAME");
h2->SetMarkerStyle(20);
h2->SetMarkerSize(0.8);
TLegend *leg = new TLegend(0.5,0.67,0.92,0.8,NULL,"NDC");
leg->SetTextFont(42);
leg->SetTextSize(0.025);
leg->AddEntry(h,"Real countries surfaces from Wikipedia (in km^{2})","lp");
leg->AddEntry(h2,"Countries surfaces from TH2Poly (with errors)","lp");
leg->Draw();
}
<commit_msg>More improvements. Now printing an estimated error compared to wikipedia. the number of points is a script argument.<commit_after>//This tutorial illustrates how to create an histogram with polygonal
//bins (TH2Poly), fill it and draw it. The initial data are stored
//in TMultiGraphs. They represent the european countries.
//The histogram filling is done according to a Mercator projection,
//therefore the bin contains should be proportional to the real surface
//of the countries.
//
//The initial data have been downloaded from: http://www.maproom.psu.edu/dcw/
//This database was developed in 1991/1992 and national boundaries reflect
//political reality as of that time.
//
//The script is shooting npoints (script argument) randomly over the Europe area.
//The number of points inside the countries should be proportional to the country surface
//The estimated surface is compared to the surfaces taken from wikipedia.
//Author: Olivier Couet
void th2polyEurope(Int_t npoints=500000)
{
Int_t i,j;
Double_t lon1 = -25;
Double_t lon2 = 35;
Double_t lat1 = 34;
Double_t lat2 = 72;
Double_t R = (lat2-lat1)/(lon2-lon1);
Int_t W = 800;
Int_t H = (Int_t)(R*800);
gStyle->SetTitleX(0.2);
gStyle->SetStatY(0.89);
gStyle->SetStatW(0.15);
// Canvas used to draw TH2Poly (the map)
TCanvas *ce = new TCanvas("ce", "ce",0,0,W,H);
ce->ToggleEventStatus();
ce->SetGridx();
ce->SetGridy();
// Real surfaces taken from Wikipedia.
const Int_t nx = 36;
// see http://en.wikipedia.org/wiki/Area_and_population_of_European_countries
char *countries[nx] = { "france", "spain", "sweden", "germany", "finland",
"norway", "poland", "italy", "yugoslavia", "united_kingdom",
"romania", "belarus","greece", "czechoslovakia","bulgaria",
"iceland", "hungary","portugal","austria", "ireland",
"lithuania", "latvia", "estonia", "denmark", "netherlands",
"switzerland","moldova","belgium", "albania", "cyprus",
"luxembourg", "andorra","malta", "liechtenstein", "san_marino",
"monaco" };
Float_t surfaces[nx] = { 547030, 505580, 449964, 357021, 338145,
324220, 312685, 301230, 255438, 244820,
237500, 207600, 131940, 127711, 110910,
103000, 93030, 89242, 83870, 70280,
65200, 64589, 45226, 43094, 41526,
41290, 33843, 30528, 28748, 9250,
2586, 468, 316, 160, 61,
2};
TH1F *h = new TH1F("h","Countries surfaces (in km^{2})",3,0,3);
for (i=0; i<nx; i++) h->Fill(countries[i], surfaces[i]);
h->LabelsDeflate();
TFile::SetCacheFileDir(".");
TFile *f;
f = TFile::Open("http://root.cern.ch/files/europe.root","cacheread");
TH2Poly *p = new TH2Poly(
"Europe",
"Europe (bin contents are normalized to the surfaces in km^{2})",
lon1,lon2,lat1,lat2);
p->GetXaxis()->SetNdivisions(520);
p->GetXaxis()->SetTitle("longitude");
p->GetYaxis()->SetTitle("latitude");
TMultiGraph *mg;
TKey *key;
TIter nextkey(gDirectory->GetListOfKeys());
while (key = (TKey*)nextkey()) {
obj = key->ReadObj();
if (obj->InheritsFrom("TMultiGraph")) {
mg = (TMultiGraph*)obj;
p->AddBin(mg);
}
}
TRandom r;
Double_t longitude, latitude;
Double_t x, y, pi4 = TMath::Pi()/4, alpha = TMath::Pi()/360;
gBenchmark->Start("Partitioning");
p->ChangePartition(100, 100);
gBenchmark->Show("Partitioning");
// Fill TH2Poly according to a Mercator projection.
gBenchmark->Start("Filling");
for (i=0; i<npoints; i++) {
longitude = r.Uniform(lon1,lon2);
latitude = r.Uniform(lat1,lat2);
x = longitude;
y = 38*TMath::Log(TMath::Tan(pi4+alpha*latitude));
p->Fill(x,y);
}
gBenchmark->Show("Filling");
Int_t nbins = p->GetNumberOfBins();
Double_t maximum = p->GetMaximum();
// h2 contains the surfaces computed from TH2Poly.
TH1F *h2 = h->Clone("h2");
h2->Reset();
for (j=0; j<nx; j++) {
for (i=0; i<nbins; i++) {
if (strstr(countries[j],p->GetBinName(i+1))) {
h2->Fill(countries[j],p->GetBinContent(i+1));
h2->SetBinError(j, p->GetBinError(i+1));
}
}
}
// Normalize the TH2Poly bin contents to the real surfaces.
Double_t scale = surfaces[0]/maximum;
for (i=0; i<nbins; i++) p->SetBinContent(i+1, scale*p->GetBinContent(i+1));
gStyle->SetOptStat(1111);
gStyle->SetPalette(1);
p->Draw("COL");
TCanvas *c1 = new TCanvas("c1", "c1",W+10,0,W-20,H);
c1->SetRightMargin(0.047);
Double_t scale = h->GetMaximum()/h2->GetMaximum();
h->SetStats(0);
h->SetLineColor(kRed-3);
h->SetLineWidth(2);
h->SetMarkerStyle(20);
h->SetMarkerColor(kBlue);
h->SetMarkerSize(0.8);
h->Draw("LP");
h->GetXaxis()->SetLabelFont(42);
h->GetXaxis()->SetLabelSize(0.03);
h->GetYaxis()->SetLabelFont(42);
h2->Scale(scale);
Double_t scale2=TMath::Sqrt(scale);
for (i=0; i<nx; i++) h2->SetBinError(i+1, scale2*h2->GetBinError(i+1));
h2->Draw("E SAME");
h2->SetMarkerStyle(20);
h2->SetMarkerSize(0.8);
TLegend *leg = new TLegend(0.5,0.67,0.92,0.8,NULL,"NDC");
leg->SetTextFont(42);
leg->SetTextSize(0.025);
leg->AddEntry(h,"Real countries surfaces from Wikipedia (in km^{2})","lp");
leg->AddEntry(h2,"Countries surfaces from TH2Poly (with errors)","lp");
leg->Draw();
leg->Draw();
Double_t wikiSum = h->Integral();
Double_t polySum = h2->Integral();
Double_t error = TMath::Abs(wikiSum-polySum)/wikiSum;
printf("THPoly Europe surface estimation error wrt wikipedia = %f per cent when using %d points\n",100*error,npoints);
}
<|endoftext|>
|
<commit_before>// @(#)root/cintex:$Id$
// Author: Pere Mato 2005
// Copyright CERN, CH-1211 Geneva 23, 2004-2005, All rights reserved.
//
// Permission to use, copy, modify, and distribute this software for any
// purpose is hereby granted without fee, provided that this copyright and
// permissions notice appear in all copies and derivatives.
//
// This software is provided "as is" without express or implied warranty.
#include "Reflex/Reflex.h"
#include "Reflex/Tools.h"
#include "Cintex/Cintex.h"
#include "CINTdefs.h"
#include "CINTScopeBuilder.h"
#include "CINTClassBuilder.h"
#include "CINTTypedefBuilder.h"
#include "Api.h"
using namespace ROOT::Reflex;
using namespace std;
namespace ROOT {
namespace Cintex {
int CINTTypedefBuilder::Setup(const Type& t) {
// Setup typedef info.
if ( t.IsTypedef() ) {
std::string nam = CintName(t.Name(SCOPED));
Type rt(t);
Scope scope = rt.DeclaringScope();
CINTScopeBuilder::Setup( scope );
while ( rt.IsTypedef() ) rt = rt.ToType();
Indirection indir = IndirectionGet(rt);
Scope rscope = indir.second.DeclaringScope();
if ( scope != rscope ) {
if ( rscope ) CINTScopeBuilder::Setup(rscope);
else {
rscope = Scope::ByName(Tools::GetScopeName(indir.second.Name(SCOPED)));
CINTScopeBuilder::Setup(rscope);
}
}
if( -1 != G__defined_typename(nam.c_str()) ) return -1;
if ( Cintex::Debug() ) {
std::cout << "Cintex: Building typedef " << nam << std::endl;
}
int rtypenum;
int rtagnum;
CintType(rt, rtypenum, rtagnum );
int stagnum = -1;
if ( !scope.IsTopScope() ) stagnum = ::G__defined_tagname(CintName(scope.Name(SCOPED)).c_str(), 1);
int r = ::G__search_typename2( t.Name().c_str(), rtypenum, rtagnum, 0, stagnum);
::G__setnewtype(-1,NULL,0);
return r;
}
return -1;
}
void CINTTypedefBuilder::Set(const char* name, const char* value) {
// As the function name indicates
G__linked_taginfo taginfo;
taginfo.tagnum = -1; // >> need to be pre-initialized to be understood by CINT
taginfo.tagtype = 'c';
taginfo.tagname = value;
G__search_typename2(name, 117, G__get_linked_tagnum(&taginfo),0,-1);
G__setnewtype(-1,NULL,0);
}
}
}
<commit_msg>Prevent Cintex from declaring typedef that are harmful to CINT<commit_after>// @(#)root/cintex:$Id$
// Author: Pere Mato 2005
// Copyright CERN, CH-1211 Geneva 23, 2004-2005, All rights reserved.
//
// Permission to use, copy, modify, and distribute this software for any
// purpose is hereby granted without fee, provided that this copyright and
// permissions notice appear in all copies and derivatives.
//
// This software is provided "as is" without express or implied warranty.
#include "Reflex/Reflex.h"
#include "Reflex/Tools.h"
#include "Cintex/Cintex.h"
#include "CINTdefs.h"
#include "CINTScopeBuilder.h"
#include "CINTClassBuilder.h"
#include "CINTTypedefBuilder.h"
#include "Api.h"
#include <set>
using namespace ROOT::Reflex;
using namespace std;
namespace ROOT {
namespace Cintex {
int CINTTypedefBuilder::Setup(const Type& t) {
// Setup typedef info.
if ( t.IsTypedef() ) {
std::string nam = CintName(t.Name(SCOPED));
static bool init = false;
static std::set<std::string> exclusionList;
if (!init) {
exclusionList.insert("stringstream");
init = true;
}
if ( exclusionList.find(nam) != exclusionList.end() ) {
return -1;
}
Type rt(t);
Scope scope = rt.DeclaringScope();
CINTScopeBuilder::Setup( scope );
while ( rt.IsTypedef() ) rt = rt.ToType();
Indirection indir = IndirectionGet(rt);
Scope rscope = indir.second.DeclaringScope();
if ( scope != rscope ) {
if ( rscope ) CINTScopeBuilder::Setup(rscope);
else {
rscope = Scope::ByName(Tools::GetScopeName(indir.second.Name(SCOPED)));
CINTScopeBuilder::Setup(rscope);
}
}
if( -1 != G__defined_typename(nam.c_str()) ) return -1;
if ( Cintex::Debug() ) {
std::cout << "Cintex: Building typedef " << nam << std::endl;
}
int rtypenum;
int rtagnum;
CintType(rt, rtypenum, rtagnum );
int stagnum = -1;
if ( !scope.IsTopScope() ) stagnum = ::G__defined_tagname(CintName(scope.Name(SCOPED)).c_str(), 1);
int r = ::G__search_typename2( t.Name().c_str(), rtypenum, rtagnum, 0, stagnum);
::G__setnewtype(-1,NULL,0);
return r;
}
return -1;
}
void CINTTypedefBuilder::Set(const char* name, const char* value) {
// As the function name indicates
G__linked_taginfo taginfo;
taginfo.tagnum = -1; // >> need to be pre-initialized to be understood by CINT
taginfo.tagtype = 'c';
taginfo.tagname = value;
G__search_typename2(name, 117, G__get_linked_tagnum(&taginfo),0,-1);
G__setnewtype(-1,NULL,0);
}
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <vector>
#include "PosixTimespec.hpp"
int main(int argc, char** argv)
{
std::vector<timespec> timespecs;
timespec tp;
tp.tv_sec = 0;
tp.tv_nsec = 0;
timespecs.push_back(tp);
tp.tv_sec = 1;
tp.tv_nsec = 1;
timespecs.push_back(tp);
tp.tv_sec = 857693847;
tp.tv_nsec = 736486;
timespecs.push_back(tp);
tp.tv_sec = 85769;
tp.tv_nsec = 566486;
timespecs.push_back(tp);
std::vector<std::pair<unsigned int, unsigned int> > failed_cases;
for (unsigned int i = 0; i < timespecs.size(); i++)
{
PosixTimespec ts1(timespecs[i]);
for (unsigned int j = 0; j < timespecs.size(); j++)
{
PosixTimespec ts2(timespecs[j]);
// Test addition
PosixTimespec ts_sum1 = ts1 + ts2;
PosixTimespec ts_sum2 = ts2 + ts1;
if (!(ts_sum1 == ts_sum2 && ts_sum2 == ts_sum1))
{
failed_cases.push_back(
std::pair<unsigned int, unsigned int>(i, j));
continue;
}
// Test equality and inequality
if (i == j)
{
if (!(ts1 == ts2 && ts2 == ts1 &&
timespecs[i] == ts2 && ts2 == timespecs[i] &&
ts1 == timespecs[j] && timespecs[j] == ts1))
{
failed_cases.push_back(
std::pair<unsigned int, unsigned int>(i, j));
}
}
else
{
if (!(ts1 != ts2 && ts2 != ts1 &&
timespecs[i] != ts2 && ts2 != timespecs[i] &&
ts1 != timespecs[j] && timespecs[j] != ts1))
{
failed_cases.push_back(
std::pair<unsigned int, unsigned int>(i, j));
}
}
}
}
std::cout << "Failed cases: " << failed_cases.size() << "\n";
// This unit test passes if no failed cases were recorded; remember that a
// zero return value means success
return failed_cases.size() != 0;
}
<commit_msg>Testing unit testing script in jenkins<commit_after>#include <iostream>
#include <vector>
#include "PosixTimespec.hpp"
int main(int argc, char** argv)
{
std::vector<timespec> timespecs;
timespec tp;
tp.tv_sec = 0;
tp.tv_nsec = 0;
timespecs.push_back(tp);
tp.tv_sec = 1;
tp.tv_nsec = 1;
timespecs.push_back(tp);
tp.tv_sec = 857693847;
tp.tv_nsec = 736486;
timespecs.push_back(tp);
tp.tv_sec = 85769;
tp.tv_nsec = 566486;
timespecs.push_back(tp);
std::vector<std::pair<unsigned int, unsigned int> > failed_cases;
for (unsigned int i = 0; i < timespecs.size(); i++)
{
PosixTimespec ts1(timespecs[i]);
for (unsigned int j = 0; j < timespecs.size(); j++)
{
PosixTimespec ts2(timespecs[j]);
// Test addition
PosixTimespec ts_sum1 = ts1 + ts2;
PosixTimespec ts_sum2 = ts2 + ts1;
if (!(ts_sum1 == ts_sum2 && ts_sum2 == ts_sum1))
{
failed_cases.push_back(
std::pair<unsigned int, unsigned int>(i, j));
continue;
}
// Test equality and inequality
if (i == j)
{
if (!(ts1 == ts2 && ts2 == ts1 &&
timespecs[i] == ts2 && ts2 == timespecs[i] &&
ts1 == timespecs[j] && timespecs[j] == ts1))
{
failed_cases.push_back(
std::pair<unsigned int, unsigned int>(i, j));
}
}
else
{
if (!(ts1 != ts2 && ts2 != ts1 &&
timespecs[i] != ts2 && ts2 != timespecs[i] &&
ts1 != timespecs[j] && timespecs[j] != ts1))
{
failed_cases.push_back(
std::pair<unsigned int, unsigned int>(i, j));
}
}
}
}
std::cout << "Failed cases: " << failed_cases.size() << "\n";
// This unit test passes if no failed cases were recorded; remember that a
// zero return value means success
return failed_cases.size() == 0;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: saldata.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: vg $ $Date: 2003-04-01 14:07:44 $
*
* 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 _SVWIN_H
#include <tools/svwin.h>
#endif
#include "rtl/tencinfo.h"
#define _SV_SALDATA_CXX
#ifndef _SV_SALDATA_HXX
#include <saldata.hxx>
#endif
#include <svapp.hxx>
// =======================================================================
rtl_TextEncoding ImplSalGetSystemEncoding()
{
static UINT nOldAnsiCodePage = 0;
static rtl_TextEncoding eEncoding = RTL_TEXTENCODING_MS_1252;
UINT nAnsiCodePage = GetACP();
if ( nAnsiCodePage != nOldAnsiCodePage )
{
rtl_TextEncoding nEnc
= rtl_getTextEncodingFromWindowsCodePage(nAnsiCodePage);
if (nEnc != RTL_TEXTENCODING_DONTKNOW)
eEncoding = nEnc;
}
return eEncoding;
}
// -----------------------------------------------------------------------
ByteString ImplSalGetWinAnsiString( const UniString& rStr, BOOL bFileName )
{
rtl_TextEncoding eEncoding = ImplSalGetSystemEncoding();
if ( bFileName )
{
return ByteString( rStr, eEncoding,
RTL_UNICODETOTEXT_FLAGS_UNDEFINED_UNDERLINE |
RTL_UNICODETOTEXT_FLAGS_INVALID_UNDERLINE |
RTL_UNICODETOTEXT_FLAGS_UNDEFINED_REPLACE |
RTL_UNICODETOTEXT_FLAGS_UNDEFINED_REPLACESTR |
RTL_UNICODETOTEXT_FLAGS_PRIVATE_MAPTO0 );
}
else
{
return ByteString( rStr, eEncoding,
RTL_UNICODETOTEXT_FLAGS_UNDEFINED_DEFAULT |
RTL_UNICODETOTEXT_FLAGS_INVALID_DEFAULT |
RTL_UNICODETOTEXT_FLAGS_UNDEFINED_REPLACE |
RTL_UNICODETOTEXT_FLAGS_UNDEFINED_REPLACESTR |
RTL_UNICODETOTEXT_FLAGS_PRIVATE_MAPTO0 );
}
}
// -----------------------------------------------------------------------
UniString ImplSalGetUniString( const sal_Char* pStr, xub_StrLen nLen )
{
return UniString( pStr, nLen, ImplSalGetSystemEncoding(),
RTL_TEXTTOUNICODE_FLAGS_UNDEFINED_DEFAULT |
RTL_TEXTTOUNICODE_FLAGS_MBUNDEFINED_DEFAULT |
RTL_TEXTTOUNICODE_FLAGS_INVALID_DEFAULT );
}
// =======================================================================
int ImplSalWICompareAscii( const wchar_t* pStr1, const char* pStr2 )
{
int nRet;
wchar_t c1;
char c2;
do
{
// Ist das Zeichen zwischen 'A' und 'Z' dann umwandeln
c1 = *pStr1;
c2 = *pStr2;
if ( (c1 >= 65) && (c1 <= 90) )
c1 += 32;
if ( (c2 >= 65) && (c2 <= 90) )
c2 += 32;
nRet = ((sal_Int32)c1)-((sal_Int32)((unsigned char)c2));
if ( nRet != 0 )
break;
pStr1++;
pStr2++;
}
while ( c2 );
return nRet;
}
// =======================================================================
LONG ImplSetWindowLong( HWND hWnd, int nIndex, DWORD dwNewLong )
{
if ( aSalShlData.mbWNT )
return SetWindowLongW( hWnd, nIndex, dwNewLong );
else
return SetWindowLongA( hWnd, nIndex, dwNewLong );
}
// -----------------------------------------------------------------------
LONG ImplGetWindowLong( HWND hWnd, int nIndex )
{
if ( aSalShlData.mbWNT )
return GetWindowLongW( hWnd, nIndex );
else
return GetWindowLongA( hWnd, nIndex );
}
// -----------------------------------------------------------------------
WIN_BOOL ImplPostMessage( HWND hWnd, UINT nMsg, WPARAM wParam, LPARAM lParam )
{
if ( aSalShlData.mbWNT )
return PostMessageW( hWnd, nMsg, wParam, lParam );
else
return PostMessageA( hWnd, nMsg, wParam, lParam );
}
// -----------------------------------------------------------------------
WIN_BOOL ImplSendMessage( HWND hWnd, UINT nMsg, WPARAM wParam, LPARAM lParam )
{
WIN_BOOL bRet;
if ( aSalShlData.mbWNT )
bRet = SendMessageW( hWnd, nMsg, wParam, lParam );
else
bRet = SendMessageA( hWnd, nMsg, wParam, lParam );
return bRet;
}
// -----------------------------------------------------------------------
WIN_BOOL ImplGetMessage( LPMSG lpMsg, HWND hWnd, UINT wMsgFilterMin, UINT wMsgFilterMax )
{
if ( aSalShlData.mbWNT )
return GetMessageW( lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax );
else
return GetMessageA( lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax );
}
// -----------------------------------------------------------------------
WIN_BOOL ImplPeekMessage( LPMSG lpMsg, HWND hWnd, UINT wMsgFilterMin, UINT wMsgFilterMax, UINT wRemoveMsg )
{
if ( aSalShlData.mbWNT )
return PeekMessageW( lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax, wRemoveMsg );
else
return PeekMessageA( lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax, wRemoveMsg );
}
// -----------------------------------------------------------------------
LONG ImplDispatchMessage( CONST MSG *lpMsg )
{
if ( aSalShlData.mbWNT )
return DispatchMessageW( lpMsg );
else
return DispatchMessageA( lpMsg );
}
<commit_msg>INTEGRATION: CWS vclcleanup02 (1.4.228); FILE MERGED 2003/12/18 09:45:41 mt 1.4.228.1: #i23061# header cleanup, remove #ifdef ???_CXX and #define ???_CXX, also removed .impl files and fixed some windows compiler warnings<commit_after>/*************************************************************************
*
* $RCSfile: saldata.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: vg $ $Date: 2004-01-06 14:51:01 $
*
* 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 _SVWIN_H
#include <tools/svwin.h>
#endif
#include "rtl/tencinfo.h"
#ifndef _SV_SALDATA_HXX
#include <saldata.hxx>
#endif
#include <svapp.hxx>
// =======================================================================
rtl_TextEncoding ImplSalGetSystemEncoding()
{
static UINT nOldAnsiCodePage = 0;
static rtl_TextEncoding eEncoding = RTL_TEXTENCODING_MS_1252;
UINT nAnsiCodePage = GetACP();
if ( nAnsiCodePage != nOldAnsiCodePage )
{
rtl_TextEncoding nEnc
= rtl_getTextEncodingFromWindowsCodePage(nAnsiCodePage);
if (nEnc != RTL_TEXTENCODING_DONTKNOW)
eEncoding = nEnc;
}
return eEncoding;
}
// -----------------------------------------------------------------------
ByteString ImplSalGetWinAnsiString( const UniString& rStr, BOOL bFileName )
{
rtl_TextEncoding eEncoding = ImplSalGetSystemEncoding();
if ( bFileName )
{
return ByteString( rStr, eEncoding,
RTL_UNICODETOTEXT_FLAGS_UNDEFINED_UNDERLINE |
RTL_UNICODETOTEXT_FLAGS_INVALID_UNDERLINE |
RTL_UNICODETOTEXT_FLAGS_UNDEFINED_REPLACE |
RTL_UNICODETOTEXT_FLAGS_UNDEFINED_REPLACESTR |
RTL_UNICODETOTEXT_FLAGS_PRIVATE_MAPTO0 );
}
else
{
return ByteString( rStr, eEncoding,
RTL_UNICODETOTEXT_FLAGS_UNDEFINED_DEFAULT |
RTL_UNICODETOTEXT_FLAGS_INVALID_DEFAULT |
RTL_UNICODETOTEXT_FLAGS_UNDEFINED_REPLACE |
RTL_UNICODETOTEXT_FLAGS_UNDEFINED_REPLACESTR |
RTL_UNICODETOTEXT_FLAGS_PRIVATE_MAPTO0 );
}
}
// -----------------------------------------------------------------------
UniString ImplSalGetUniString( const sal_Char* pStr, xub_StrLen nLen )
{
return UniString( pStr, nLen, ImplSalGetSystemEncoding(),
RTL_TEXTTOUNICODE_FLAGS_UNDEFINED_DEFAULT |
RTL_TEXTTOUNICODE_FLAGS_MBUNDEFINED_DEFAULT |
RTL_TEXTTOUNICODE_FLAGS_INVALID_DEFAULT );
}
// =======================================================================
int ImplSalWICompareAscii( const wchar_t* pStr1, const char* pStr2 )
{
int nRet;
wchar_t c1;
char c2;
do
{
// Ist das Zeichen zwischen 'A' und 'Z' dann umwandeln
c1 = *pStr1;
c2 = *pStr2;
if ( (c1 >= 65) && (c1 <= 90) )
c1 += 32;
if ( (c2 >= 65) && (c2 <= 90) )
c2 += 32;
nRet = ((sal_Int32)c1)-((sal_Int32)((unsigned char)c2));
if ( nRet != 0 )
break;
pStr1++;
pStr2++;
}
while ( c2 );
return nRet;
}
// =======================================================================
LONG ImplSetWindowLong( HWND hWnd, int nIndex, DWORD dwNewLong )
{
if ( aSalShlData.mbWNT )
return SetWindowLongW( hWnd, nIndex, dwNewLong );
else
return SetWindowLongA( hWnd, nIndex, dwNewLong );
}
// -----------------------------------------------------------------------
LONG ImplGetWindowLong( HWND hWnd, int nIndex )
{
if ( aSalShlData.mbWNT )
return GetWindowLongW( hWnd, nIndex );
else
return GetWindowLongA( hWnd, nIndex );
}
// -----------------------------------------------------------------------
WIN_BOOL ImplPostMessage( HWND hWnd, UINT nMsg, WPARAM wParam, LPARAM lParam )
{
if ( aSalShlData.mbWNT )
return PostMessageW( hWnd, nMsg, wParam, lParam );
else
return PostMessageA( hWnd, nMsg, wParam, lParam );
}
// -----------------------------------------------------------------------
WIN_BOOL ImplSendMessage( HWND hWnd, UINT nMsg, WPARAM wParam, LPARAM lParam )
{
WIN_BOOL bRet;
if ( aSalShlData.mbWNT )
bRet = SendMessageW( hWnd, nMsg, wParam, lParam );
else
bRet = SendMessageA( hWnd, nMsg, wParam, lParam );
return bRet;
}
// -----------------------------------------------------------------------
WIN_BOOL ImplGetMessage( LPMSG lpMsg, HWND hWnd, UINT wMsgFilterMin, UINT wMsgFilterMax )
{
if ( aSalShlData.mbWNT )
return GetMessageW( lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax );
else
return GetMessageA( lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax );
}
// -----------------------------------------------------------------------
WIN_BOOL ImplPeekMessage( LPMSG lpMsg, HWND hWnd, UINT wMsgFilterMin, UINT wMsgFilterMax, UINT wRemoveMsg )
{
if ( aSalShlData.mbWNT )
return PeekMessageW( lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax, wRemoveMsg );
else
return PeekMessageA( lpMsg, hWnd, wMsgFilterMin, wMsgFilterMax, wRemoveMsg );
}
// -----------------------------------------------------------------------
LONG ImplDispatchMessage( CONST MSG *lpMsg )
{
if ( aSalShlData.mbWNT )
return DispatchMessageW( lpMsg );
else
return DispatchMessageA( lpMsg );
}
<|endoftext|>
|
<commit_before><commit_msg>Guard against wrap-around in SvxFontHeightItem<commit_after><|endoftext|>
|
<commit_before>#include "audio_facade.h"
#include "audio_engine.h"
#include "audio_handle_impl.h"
#include "audio_source_behaviour.h"
using namespace Halley;
constexpr bool ownAudioThread = false;
AudioFacade::AudioFacade(AudioOutputAPI& output)
: output(output)
, running(false)
{
}
AudioFacade::~AudioFacade()
{
AudioFacade::stopPlayback();
}
void AudioFacade::init()
{
}
void AudioFacade::deInit()
{
stopPlayback();
}
Vector<std::unique_ptr<const AudioDevice>> AudioFacade::getAudioDevices()
{
return output.getAudioDevices();
}
void AudioFacade::startPlayback(int deviceNumber)
{
if (running) {
stopPlayback();
}
auto devices = getAudioDevices();
if (int(devices.size()) > deviceNumber) {
engine = std::make_unique<AudioEngine>();
AudioSpec format;
format.bufferSize = 2048;
format.format = AudioSampleFormat::Int16;
format.numChannels = 2;
format.sampleRate = 48000;
AudioSpec obtained = output.openAudioDevice(format, devices.at(deviceNumber).get(), [this]() { onNeedBuffer(); });
engine->start(obtained, output);
running = true;
if (ownAudioThread) {
audioThread = std::thread([this]() { run(); });
}
output.startPlayback();
}
}
void AudioFacade::stopPlayback()
{
if (running) {
{
std::unique_lock<std::mutex> lock(audioMutex);
musicTracks.clear();
running = false;
engine->stop();
}
if (ownAudioThread) {
audioThread.join();
}
output.stopPlayback();
engine.reset();
}
}
AudioHandle AudioFacade::playUI(std::shared_ptr<const AudioClip> clip, float volume, float pan, bool loop)
{
return play(clip, AudioSourcePosition::makeUI(pan), volume, loop);
}
AudioHandle AudioFacade::playMusic(std::shared_ptr<const AudioClip> clip, int track, float fadeInTime, bool loop)
{
bool hasFade = fadeInTime > 0.0001f;
stopMusic(track, fadeInTime);
auto handle = play(clip, AudioSourcePosition::makeFixed(), hasFade ? 0.0f : 1.0f, true);
musicTracks[track] = handle;
if (hasFade) {
handle->setBehaviour(std::make_unique<AudioSourceFadeBehaviour>(fadeInTime, 1.0f, false));
}
return handle;
}
AudioHandle AudioFacade::play(std::shared_ptr<const AudioClip> clip, AudioSourcePosition position, float volume, bool loop)
{
size_t id = uniqueId++;
enqueue([=] () {
engine->play(id, clip, position, volume, loop);
});
return std::make_shared<AudioHandleImpl>(*this, id);
}
AudioHandle AudioFacade::getMusic(int track)
{
auto iter = musicTracks.find(track);
if (iter != musicTracks.end()) {
return iter->second;
} else {
return AudioHandle();
}
}
void AudioFacade::stopMusic(int track, float fadeOutTime)
{
auto iter = musicTracks.find(track);
if (iter != musicTracks.end()) {
stopMusic(iter->second, fadeOutTime);
musicTracks.erase(iter);
}
}
void AudioFacade::stopAllMusic(float fadeOutTime)
{
for (auto& m: musicTracks) {
stopMusic(m.second, fadeOutTime);
}
musicTracks.clear();
}
void AudioFacade::stopMusic(AudioHandle& handle, float fadeOutTime)
{
if (fadeOutTime > 0.001f) {
handle->setBehaviour(std::make_unique<AudioSourceFadeBehaviour>(fadeOutTime, 0.0f, true));
} else {
handle->stop();
}
}
void AudioFacade::onNeedBuffer()
{
if (!ownAudioThread) {
stepAudio();
}
}
void AudioFacade::setGroupVolume(String groupName, float gain)
{
// TODO
}
void AudioFacade::setListener(AudioListenerData listener)
{
enqueue([=] () {
engine->setListener(listener);
});
}
void AudioFacade::run()
{
while (running) {
stepAudio();
}
}
void AudioFacade::stepAudio()
{
std::vector<std::function<void()>> toDo;
{
std::unique_lock<std::mutex> lock(audioMutex);
if (!running) {
return;
}
toDo = std::move(inbox);
inbox.clear();
playingSoundsNext = engine->getPlayingSounds();
}
for (auto& action : toDo) {
action();
}
if (ownAudioThread) {
engine->run();
} else {
engine->generateBuffer();
}
}
void AudioFacade::enqueue(std::function<void()> action)
{
if (running) {
outbox.push_back(action);
}
}
void AudioFacade::pump()
{
if (running) {
std::unique_lock<std::mutex> lock(audioMutex);
if (!outbox.empty()) {
size_t i = inbox.size();
inbox.resize(i + outbox.size());
for (auto& o: outbox) {
inbox[i++] = std::move(o);
}
outbox.clear();
}
playingSounds = playingSoundsNext;
} else {
inbox.clear();
outbox.clear();
}
}
<commit_msg>Print available audio devices.<commit_after>#include "audio_facade.h"
#include "audio_engine.h"
#include "audio_handle_impl.h"
#include "audio_source_behaviour.h"
#include "halley/support/console.h"
using namespace Halley;
constexpr bool ownAudioThread = false;
AudioFacade::AudioFacade(AudioOutputAPI& output)
: output(output)
, running(false)
{
}
AudioFacade::~AudioFacade()
{
AudioFacade::stopPlayback();
}
void AudioFacade::init()
{
std::cout << ConsoleColour(Console::GREEN) << "\nInitializing audio...\n" << ConsoleColour();
std::cout << "Audio devices available:" << std::endl;
int i = 0;
for (auto& device: getAudioDevices()) {
std::cout << "\t" << i++ << ": " << device->getName() << std::endl;
}
}
void AudioFacade::deInit()
{
stopPlayback();
}
Vector<std::unique_ptr<const AudioDevice>> AudioFacade::getAudioDevices()
{
return output.getAudioDevices();
}
void AudioFacade::startPlayback(int deviceNumber)
{
std::cout << "Using audio device: " << deviceNumber << std::endl;
if (running) {
stopPlayback();
}
auto devices = getAudioDevices();
if (int(devices.size()) > deviceNumber) {
engine = std::make_unique<AudioEngine>();
AudioSpec format;
format.bufferSize = 2048;
format.format = AudioSampleFormat::Int16;
format.numChannels = 2;
format.sampleRate = 48000;
AudioSpec obtained = output.openAudioDevice(format, devices.at(deviceNumber).get(), [this]() { onNeedBuffer(); });
engine->start(obtained, output);
running = true;
if (ownAudioThread) {
audioThread = std::thread([this]() { run(); });
}
output.startPlayback();
}
}
void AudioFacade::stopPlayback()
{
if (running) {
{
std::unique_lock<std::mutex> lock(audioMutex);
musicTracks.clear();
running = false;
engine->stop();
}
if (ownAudioThread) {
audioThread.join();
}
output.stopPlayback();
engine.reset();
}
}
AudioHandle AudioFacade::playUI(std::shared_ptr<const AudioClip> clip, float volume, float pan, bool loop)
{
return play(clip, AudioSourcePosition::makeUI(pan), volume, loop);
}
AudioHandle AudioFacade::playMusic(std::shared_ptr<const AudioClip> clip, int track, float fadeInTime, bool loop)
{
bool hasFade = fadeInTime > 0.0001f;
stopMusic(track, fadeInTime);
auto handle = play(clip, AudioSourcePosition::makeFixed(), hasFade ? 0.0f : 1.0f, true);
musicTracks[track] = handle;
if (hasFade) {
handle->setBehaviour(std::make_unique<AudioSourceFadeBehaviour>(fadeInTime, 1.0f, false));
}
return handle;
}
AudioHandle AudioFacade::play(std::shared_ptr<const AudioClip> clip, AudioSourcePosition position, float volume, bool loop)
{
size_t id = uniqueId++;
enqueue([=] () {
engine->play(id, clip, position, volume, loop);
});
return std::make_shared<AudioHandleImpl>(*this, id);
}
AudioHandle AudioFacade::getMusic(int track)
{
auto iter = musicTracks.find(track);
if (iter != musicTracks.end()) {
return iter->second;
} else {
return AudioHandle();
}
}
void AudioFacade::stopMusic(int track, float fadeOutTime)
{
auto iter = musicTracks.find(track);
if (iter != musicTracks.end()) {
stopMusic(iter->second, fadeOutTime);
musicTracks.erase(iter);
}
}
void AudioFacade::stopAllMusic(float fadeOutTime)
{
for (auto& m: musicTracks) {
stopMusic(m.second, fadeOutTime);
}
musicTracks.clear();
}
void AudioFacade::stopMusic(AudioHandle& handle, float fadeOutTime)
{
if (fadeOutTime > 0.001f) {
handle->setBehaviour(std::make_unique<AudioSourceFadeBehaviour>(fadeOutTime, 0.0f, true));
} else {
handle->stop();
}
}
void AudioFacade::onNeedBuffer()
{
if (!ownAudioThread) {
stepAudio();
}
}
void AudioFacade::setGroupVolume(String groupName, float gain)
{
// TODO
}
void AudioFacade::setListener(AudioListenerData listener)
{
enqueue([=] () {
engine->setListener(listener);
});
}
void AudioFacade::run()
{
while (running) {
stepAudio();
}
}
void AudioFacade::stepAudio()
{
std::vector<std::function<void()>> toDo;
{
std::unique_lock<std::mutex> lock(audioMutex);
if (!running) {
return;
}
toDo = std::move(inbox);
inbox.clear();
playingSoundsNext = engine->getPlayingSounds();
}
for (auto& action : toDo) {
action();
}
if (ownAudioThread) {
engine->run();
} else {
engine->generateBuffer();
}
}
void AudioFacade::enqueue(std::function<void()> action)
{
if (running) {
outbox.push_back(action);
}
}
void AudioFacade::pump()
{
if (running) {
std::unique_lock<std::mutex> lock(audioMutex);
if (!outbox.empty()) {
size_t i = inbox.size();
inbox.resize(i + outbox.size());
for (auto& o: outbox) {
inbox[i++] = std::move(o);
}
outbox.clear();
}
playingSounds = playingSoundsNext;
} else {
inbox.clear();
outbox.clear();
}
}
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software 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:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* @author <a href="mailto:david_n_bertoni@lotus.com">David N. Bertoni</a>
*/
#include "XSLTProcessorEnvSupportDefault.hpp"
#include <algorithm>
#include <util/XMLURL.hpp>
#include <PlatformSupport/DOMStringHelper.hpp>
#include <PlatformSupport/STLHelper.hpp>
#include <XPath/ElementPrefixResolverProxy.hpp>
#include <XPath/XPathExecutionContext.hpp>
#include <XMLSupport/XMLParserLiaison.hpp>
#include "KeyTable.hpp"
#include "StylesheetRoot.hpp"
#include "XSLTProcessor.hpp"
#include "XSLTInputSource.hpp"
XSLTProcessorEnvSupportDefault::XSLTProcessorEnvSupportDefault(XSLTProcessor* theProcessor) :
XSLTProcessorEnvSupport(),
m_defaultSupport(),
m_processor(theProcessor),
m_keyTables(),
m_xlocatorTable()
{
}
XSLTProcessorEnvSupportDefault::~XSLTProcessorEnvSupportDefault()
{
reset();
}
void
XSLTProcessorEnvSupportDefault::installExternalFunctionGlobal(
const XalanDOMString& theNamespace,
const XalanDOMString& extensionName,
const Function& function)
{
XPathEnvSupportDefault::installExternalFunctionGlobal(theNamespace, extensionName, function);
}
void
XSLTProcessorEnvSupportDefault::uninstallExternalFunctionGlobal(
const XalanDOMString& theNamespace,
const XalanDOMString& extensionName)
{
XPathEnvSupportDefault::uninstallExternalFunctionGlobal(theNamespace, extensionName);
}
void
XSLTProcessorEnvSupportDefault::installExternalFunctionLocal(
const XalanDOMString& theNamespace,
const XalanDOMString& extensionName,
const Function& function)
{
m_defaultSupport.installExternalFunctionLocal(theNamespace, extensionName, function);
}
void
XSLTProcessorEnvSupportDefault::uninstallExternalFunctionLocal(
const XalanDOMString& theNamespace,
const XalanDOMString& extensionName)
{
m_defaultSupport.uninstallExternalFunctionLocal(theNamespace, extensionName);
}
void
XSLTProcessorEnvSupportDefault::reset()
{
#if !defined(XALAN_NO_NAMESPACES)
using std::for_each;
#endif
// Clean up the key table vector
for_each(m_keyTables.begin(),
m_keyTables.end(),
makeMapValueDeleteFunctor(m_keyTables));
m_keyTables.clear();
m_xlocatorTable.clear();
}
KeyTable*
XSLTProcessorEnvSupportDefault::getKeyTable(const XalanNode* doc) const
{
const KeyTablesTableType::const_iterator i =
m_keyTables.find(doc);
if (i == m_keyTables.end())
{
return 0;
}
else
{
return i->second;
}
}
void
XSLTProcessorEnvSupportDefault::setKeyTable(
KeyTable* keytable,
const XalanNode* doc)
{
// Get rid of any existing keytable
delete m_keyTables[doc];
m_keyTables[doc] = keytable;
}
const NodeRefListBase*
XSLTProcessorEnvSupportDefault::getNodeSetByKey(
const XalanNode& doc,
const XalanDOMString& name,
const XalanDOMString& ref,
const PrefixResolver& resolver,
XPathExecutionContext& executionContext) const
{
if (m_processor == 0)
{
return m_defaultSupport.getNodeSetByKey(doc,
name,
ref,
resolver,
executionContext);
}
else
{
const NodeRefListBase* nl = 0;
const Stylesheet* const theStylesheet =
m_processor->getStylesheetRoot();
if (theStylesheet != 0)
{
// $$$ ToDo: Figure out this const stuff!!!
nl = theStylesheet->getNodeSetByKey(&const_cast<XalanNode&>(doc),
name,
ref,
resolver,
executionContext,
#if defined(XALAN_NO_MUTABLE)
(KeysTableType&)m_keyTables);
#else
m_keyTables);
#endif
}
if(0 == nl)
{
m_processor->error(XalanDOMString("There is no xsl:key declaration for '") + name + XalanDOMString("'!"));
}
return nl;
}
}
XObject*
XSLTProcessorEnvSupportDefault::getVariable(
XObjectFactory& factory,
const QName& name) const
{
if (m_processor == 0)
{
return m_defaultSupport.getVariable(factory,
name);
}
else
{
return m_processor->getVariable(name);
}
}
XalanDocument*
XSLTProcessorEnvSupportDefault::parseXML(
const XalanDOMString& urlString,
const XalanDOMString& base)
{
if (m_processor == 0)
{
return m_defaultSupport.parseXML(urlString, base);
}
else
{
XMLParserLiaison& parserLiaison = m_processor->getXMLParserLiaison();
const XMLURL xslURL(c_wstr(base), c_wstr(urlString));
const XMLCh* const urlText = xslURL.getURLText();
XSLTInputSource inputSource(urlText);
XalanDocument* theDocument =
parserLiaison.parseXMLStream(inputSource);
setSourceDocument(urlText, theDocument);
return theDocument;
}
}
XalanDocument*
XSLTProcessorEnvSupportDefault::getSourceDocument(const XalanDOMString& theURI) const
{
return m_defaultSupport.getSourceDocument(theURI);
}
void
XSLTProcessorEnvSupportDefault::setSourceDocument(
const XalanDOMString& theURI,
XalanDocument* theDocument)
{
m_defaultSupport.setSourceDocument(theURI, theDocument);
}
XalanDOMString
XSLTProcessorEnvSupportDefault::findURIFromDoc(const XalanDocument* owner) const
{
return m_defaultSupport.findURIFromDoc(owner);
}
XalanDocument*
XSLTProcessorEnvSupportDefault::getDOMFactory() const
{
if (m_processor == 0)
{
return m_defaultSupport.getDOMFactory();
}
else
{
return m_processor->getDOMFactory();
}
}
bool
XSLTProcessorEnvSupportDefault::elementAvailable(
const XalanDOMString& theNamespace,
const XalanDOMString& extensionName) const
{
return m_defaultSupport.elementAvailable(theNamespace,
extensionName);
}
bool
XSLTProcessorEnvSupportDefault::functionAvailable(
const XalanDOMString& theNamespace,
const XalanDOMString& extensionName) const
{
return m_defaultSupport.functionAvailable(theNamespace,
extensionName);
}
XObject*
XSLTProcessorEnvSupportDefault::extFunction(
XPathExecutionContext& executionContext,
const XalanDOMString& theNamespace,
const XalanDOMString& extensionName,
XalanNode* context,
const XObjectArgVectorType& argVec) const
{
return m_defaultSupport.extFunction(executionContext,
theNamespace,
extensionName,
context,
argVec);
}
XLocator*
XSLTProcessorEnvSupportDefault::getXLocatorFromNode(const XalanNode* node) const
{
const XLocatorTableType::const_iterator i =
m_xlocatorTable.find(node);
if (i == m_xlocatorTable.end())
{
return 0;
}
else
{
return i->second;
}
}
void
XSLTProcessorEnvSupportDefault::associateXLocatorToNode(
const XalanNode* node,
XLocator* xlocator)
{
m_xlocatorTable[node] = xlocator;
}
bool
XSLTProcessorEnvSupportDefault::shouldStripSourceNode(const XalanNode& node) const
{
if (m_processor == 0)
{
return m_defaultSupport.shouldStripSourceNode(node);
}
else
{
return m_processor->shouldStripSourceNode(node);
}
}
bool
XSLTProcessorEnvSupportDefault::problem(
eSource where,
eClassification classification,
const XalanNode* styleNode,
const XalanNode* sourceNode,
const XalanDOMString& msg,
int lineNo,
int charOffset) const
{
return m_defaultSupport.problem(where,
classification,
styleNode,
sourceNode,
msg,
lineNo,
charOffset);
}
bool
XSLTProcessorEnvSupportDefault::problem(
eSource where,
eClassification classification,
const PrefixResolver* resolver,
const XalanNode* sourceNode,
const XalanDOMString& msg,
int lineNo,
int charOffset) const
{
return m_defaultSupport.problem(where,
classification,
resolver,
sourceNode,
msg,
lineNo,
charOffset);
}
<commit_msg>Added some special-case code for URL handling.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software 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:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* @author <a href="mailto:david_n_bertoni@lotus.com">David N. Bertoni</a>
*/
#include "XSLTProcessorEnvSupportDefault.hpp"
#include <algorithm>
#include <util/XMLURL.hpp>
#include <PlatformSupport/DOMStringHelper.hpp>
#include <PlatformSupport/STLHelper.hpp>
#include <XPath/ElementPrefixResolverProxy.hpp>
#include <XPath/XPathExecutionContext.hpp>
#include <XMLSupport/XMLParserLiaison.hpp>
#include "KeyTable.hpp"
#include "StylesheetRoot.hpp"
#include "XSLTProcessor.hpp"
#include "XSLTInputSource.hpp"
XSLTProcessorEnvSupportDefault::XSLTProcessorEnvSupportDefault(XSLTProcessor* theProcessor) :
XSLTProcessorEnvSupport(),
m_defaultSupport(),
m_processor(theProcessor),
m_keyTables(),
m_xlocatorTable()
{
}
XSLTProcessorEnvSupportDefault::~XSLTProcessorEnvSupportDefault()
{
reset();
}
void
XSLTProcessorEnvSupportDefault::installExternalFunctionGlobal(
const XalanDOMString& theNamespace,
const XalanDOMString& extensionName,
const Function& function)
{
XPathEnvSupportDefault::installExternalFunctionGlobal(theNamespace, extensionName, function);
}
void
XSLTProcessorEnvSupportDefault::uninstallExternalFunctionGlobal(
const XalanDOMString& theNamespace,
const XalanDOMString& extensionName)
{
XPathEnvSupportDefault::uninstallExternalFunctionGlobal(theNamespace, extensionName);
}
void
XSLTProcessorEnvSupportDefault::installExternalFunctionLocal(
const XalanDOMString& theNamespace,
const XalanDOMString& extensionName,
const Function& function)
{
m_defaultSupport.installExternalFunctionLocal(theNamespace, extensionName, function);
}
void
XSLTProcessorEnvSupportDefault::uninstallExternalFunctionLocal(
const XalanDOMString& theNamespace,
const XalanDOMString& extensionName)
{
m_defaultSupport.uninstallExternalFunctionLocal(theNamespace, extensionName);
}
void
XSLTProcessorEnvSupportDefault::reset()
{
#if !defined(XALAN_NO_NAMESPACES)
using std::for_each;
#endif
// Clean up the key table vector
for_each(m_keyTables.begin(),
m_keyTables.end(),
makeMapValueDeleteFunctor(m_keyTables));
m_keyTables.clear();
m_xlocatorTable.clear();
}
KeyTable*
XSLTProcessorEnvSupportDefault::getKeyTable(const XalanNode* doc) const
{
const KeyTablesTableType::const_iterator i =
m_keyTables.find(doc);
if (i == m_keyTables.end())
{
return 0;
}
else
{
return i->second;
}
}
void
XSLTProcessorEnvSupportDefault::setKeyTable(
KeyTable* keytable,
const XalanNode* doc)
{
// Get rid of any existing keytable
delete m_keyTables[doc];
m_keyTables[doc] = keytable;
}
const NodeRefListBase*
XSLTProcessorEnvSupportDefault::getNodeSetByKey(
const XalanNode& doc,
const XalanDOMString& name,
const XalanDOMString& ref,
const PrefixResolver& resolver,
XPathExecutionContext& executionContext) const
{
if (m_processor == 0)
{
return m_defaultSupport.getNodeSetByKey(doc,
name,
ref,
resolver,
executionContext);
}
else
{
const NodeRefListBase* nl = 0;
const Stylesheet* const theStylesheet =
m_processor->getStylesheetRoot();
if (theStylesheet != 0)
{
// $$$ ToDo: Figure out this const stuff!!!
nl = theStylesheet->getNodeSetByKey(&const_cast<XalanNode&>(doc),
name,
ref,
resolver,
executionContext,
#if defined(XALAN_NO_MUTABLE)
(KeysTableType&)m_keyTables);
#else
m_keyTables);
#endif
}
if(0 == nl)
{
m_processor->error(XalanDOMString("There is no xsl:key declaration for '") + name + XalanDOMString("'!"));
}
return nl;
}
}
XObject*
XSLTProcessorEnvSupportDefault::getVariable(
XObjectFactory& factory,
const QName& name) const
{
if (m_processor == 0)
{
return m_defaultSupport.getVariable(factory,
name);
}
else
{
return m_processor->getVariable(name);
}
}
XalanDocument*
XSLTProcessorEnvSupportDefault::parseXML(
const XalanDOMString& urlString,
const XalanDOMString& base)
{
if (m_processor == 0)
{
return m_defaultSupport.parseXML(urlString, base);
}
else
{
XMLParserLiaison& parserLiaison =
m_processor->getXMLParserLiaison();
// $$$ ToDo: we should re-work this code to only use
// XMLRUL when necessary.
XMLURL xslURL;
// This is a work-around for what I believe is a bug in the
// Xerces URL code. If a base identifier ends in a slash,
// they chop of characters back to the _previous_ slash.
// So, for instance, a base of "/foo/foo/foo/" and a
// urlString of file.xml would become /foo/foo/file.xml,
// instead of /foo/foo/foo/file.xml.
const unsigned int indexOfSlash = lastIndexOf(base, '/');
if (indexOfSlash == length(base) - 1)
{
xslURL.setURL(c_wstr(base + urlString));
}
else
{
xslURL.setURL(c_wstr(base), c_wstr(urlString));
}
const XMLCh* const urlText = xslURL.getURLText();
XSLTInputSource inputSource(urlText);
XalanDocument* theDocument =
parserLiaison.parseXMLStream(inputSource);
setSourceDocument(urlText, theDocument);
return theDocument;
}
}
XalanDocument*
XSLTProcessorEnvSupportDefault::getSourceDocument(const XalanDOMString& theURI) const
{
return m_defaultSupport.getSourceDocument(theURI);
}
void
XSLTProcessorEnvSupportDefault::setSourceDocument(
const XalanDOMString& theURI,
XalanDocument* theDocument)
{
m_defaultSupport.setSourceDocument(theURI, theDocument);
}
XalanDOMString
XSLTProcessorEnvSupportDefault::findURIFromDoc(const XalanDocument* owner) const
{
return m_defaultSupport.findURIFromDoc(owner);
}
XalanDocument*
XSLTProcessorEnvSupportDefault::getDOMFactory() const
{
if (m_processor == 0)
{
return m_defaultSupport.getDOMFactory();
}
else
{
return m_processor->getDOMFactory();
}
}
bool
XSLTProcessorEnvSupportDefault::elementAvailable(
const XalanDOMString& theNamespace,
const XalanDOMString& extensionName) const
{
return m_defaultSupport.elementAvailable(theNamespace,
extensionName);
}
bool
XSLTProcessorEnvSupportDefault::functionAvailable(
const XalanDOMString& theNamespace,
const XalanDOMString& extensionName) const
{
return m_defaultSupport.functionAvailable(theNamespace,
extensionName);
}
XObject*
XSLTProcessorEnvSupportDefault::extFunction(
XPathExecutionContext& executionContext,
const XalanDOMString& theNamespace,
const XalanDOMString& extensionName,
XalanNode* context,
const XObjectArgVectorType& argVec) const
{
return m_defaultSupport.extFunction(executionContext,
theNamespace,
extensionName,
context,
argVec);
}
XLocator*
XSLTProcessorEnvSupportDefault::getXLocatorFromNode(const XalanNode* node) const
{
const XLocatorTableType::const_iterator i =
m_xlocatorTable.find(node);
if (i == m_xlocatorTable.end())
{
return 0;
}
else
{
return i->second;
}
}
void
XSLTProcessorEnvSupportDefault::associateXLocatorToNode(
const XalanNode* node,
XLocator* xlocator)
{
m_xlocatorTable[node] = xlocator;
}
bool
XSLTProcessorEnvSupportDefault::shouldStripSourceNode(const XalanNode& node) const
{
if (m_processor == 0)
{
return m_defaultSupport.shouldStripSourceNode(node);
}
else
{
return m_processor->shouldStripSourceNode(node);
}
}
bool
XSLTProcessorEnvSupportDefault::problem(
eSource where,
eClassification classification,
const XalanNode* styleNode,
const XalanNode* sourceNode,
const XalanDOMString& msg,
int lineNo,
int charOffset) const
{
return m_defaultSupport.problem(where,
classification,
styleNode,
sourceNode,
msg,
lineNo,
charOffset);
}
bool
XSLTProcessorEnvSupportDefault::problem(
eSource where,
eClassification classification,
const PrefixResolver* resolver,
const XalanNode* sourceNode,
const XalanDOMString& msg,
int lineNo,
int charOffset) const
{
return m_defaultSupport.problem(where,
classification,
resolver,
sourceNode,
msg,
lineNo,
charOffset);
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ChartTypeHelper.hxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: ihi $ $Date: 2007-11-23 11:55:59 $
*
* 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 _CHART2_CHARTTYPEHELPER_HXX
#define _CHART2_CHARTTYPEHELPER_HXX
#ifndef _COM_SUN_STAR_CHART2_XCHARTTYPE_HPP_
#include <com/sun/star/chart2/XChartType.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_AXISTYPE_HPP_
#include <com/sun/star/chart2/AxisType.hpp>
#endif
#include <com/sun/star/chart2/XDataSeries.hpp>
#include <com/sun/star/chart2/XDiagram.hpp>
#ifndef _COM_SUN_STAR_DRAWING_DIRECTION3D_HPP_
#include <com/sun/star/drawing/Direction3D.hpp>
#endif
//.............................................................................
namespace chart
{
//.............................................................................
//-----------------------------------------------------------------------------
/**
*/
class ChartTypeHelper
{
public:
static sal_Bool isSupportingGeometryProperties( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType, sal_Int32 nDimensionCount );
static sal_Bool isSupportingStatisticProperties( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType, sal_Int32 nDimensionCount );
static sal_Bool isSupportingRegressionProperties(const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType, sal_Int32 nDimensionCount );
static sal_Bool isSupportingMainAxis( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType, sal_Int32 nDimensionCount, sal_Int32 nDimensionIndex );
static sal_Bool isSupportingSecondaryAxis( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType, sal_Int32 nDimensionCount, sal_Int32 nDimensionIndex );
static sal_Bool isSupportingAreaProperties( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType, sal_Int32 nDimensionCount );
static sal_Bool isSupportingSymbolProperties( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType, sal_Int32 nDimensionCount );
static sal_Bool isSupportingOverlapAndGapWidthProperties( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType, sal_Int32 nDimensionCount );
static sal_Bool isSupportingBarConnectors( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType, sal_Int32 nDimensionCount );
static sal_Bool isSupportingRightAngledAxes( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType );
static bool isSupportingAxisSideBySide( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType, sal_Int32 nDimensionCount );
//returns sequence of ::com::sun::star::chart::DataLabelPlacement
static ::com::sun::star::uno::Sequence < sal_Int32 > getSupportedLabelPlacements(
const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType, sal_Int32 nDimensionCount, sal_Bool bSwapXAndY
, const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries >& xSeries );
static ::com::sun::star::drawing::Direction3D getDefaultSimpleLightDirection( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType );
static ::com::sun::star::drawing::Direction3D getDefaultRealisticLightDirection( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType );
static sal_Int32 getDefaultDirectLightColor( bool bSimple, const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType );
static sal_Int32 getDefaultAmbientLightColor( bool bSimple, const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType );
static sal_Int32 getNumberOfDisplayedSeries( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType, sal_Int32 nNumberOfSeries );
static bool noBordersForSimpleScheme( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType );
static sal_Int32 //one of ::com::sun::star::chart2::AxisType
getAxisType( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType
, sal_Int32 nDimensionIndex );
/** Determines if all data series of a chart type are attached to the same
axis.
@param rOutAxisIndex If, and only if, </TRUE> is returned this
out-parameter is filled with the index (0 or 1) of the axis to
which all series are attached.
*/
static bool allSeriesAttachedToSameAxis(
const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType,
sal_Int32 & rOutAxisIndex );
};
//.............................................................................
} //namespace chart
//.............................................................................
#endif
<commit_msg>INTEGRATION: CWS chart19 (1.11.12); FILE MERGED 2007/12/18 13:46:19 bm 1.11.12.2: RESYNC: (1.11-1.12); FILE MERGED 2007/12/15 13:05:10 iha 1.11.12.1: #i16776# starting angle for pie charts<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ChartTypeHelper.hxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: rt $ $Date: 2008-02-18 15:59:02 $
*
* 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 _CHART2_CHARTTYPEHELPER_HXX
#define _CHART2_CHARTTYPEHELPER_HXX
#ifndef _COM_SUN_STAR_CHART2_XCHARTTYPE_HPP_
#include <com/sun/star/chart2/XChartType.hpp>
#endif
#ifndef _COM_SUN_STAR_CHART2_AXISTYPE_HPP_
#include <com/sun/star/chart2/AxisType.hpp>
#endif
#include <com/sun/star/chart2/XDataSeries.hpp>
#include <com/sun/star/chart2/XDiagram.hpp>
#ifndef _COM_SUN_STAR_DRAWING_DIRECTION3D_HPP_
#include <com/sun/star/drawing/Direction3D.hpp>
#endif
//.............................................................................
namespace chart
{
//.............................................................................
//-----------------------------------------------------------------------------
/**
*/
class ChartTypeHelper
{
public:
static sal_Bool isSupportingGeometryProperties( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType, sal_Int32 nDimensionCount );
static sal_Bool isSupportingStatisticProperties( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType, sal_Int32 nDimensionCount );
static sal_Bool isSupportingRegressionProperties(const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType, sal_Int32 nDimensionCount );
static sal_Bool isSupportingMainAxis( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType, sal_Int32 nDimensionCount, sal_Int32 nDimensionIndex );
static sal_Bool isSupportingSecondaryAxis( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType, sal_Int32 nDimensionCount, sal_Int32 nDimensionIndex );
static sal_Bool isSupportingAreaProperties( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType, sal_Int32 nDimensionCount );
static sal_Bool isSupportingSymbolProperties( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType, sal_Int32 nDimensionCount );
static sal_Bool isSupportingOverlapAndGapWidthProperties( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType, sal_Int32 nDimensionCount );
static sal_Bool isSupportingBarConnectors( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType, sal_Int32 nDimensionCount );
static sal_Bool isSupportingRightAngledAxes( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType );
static bool isSupportingAxisSideBySide( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType, sal_Int32 nDimensionCount );
static bool isSupportingStartingAngle( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType );
//returns sequence of ::com::sun::star::chart::DataLabelPlacement
static ::com::sun::star::uno::Sequence < sal_Int32 > getSupportedLabelPlacements(
const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType, sal_Int32 nDimensionCount, sal_Bool bSwapXAndY
, const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries >& xSeries );
static ::com::sun::star::drawing::Direction3D getDefaultSimpleLightDirection( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType );
static ::com::sun::star::drawing::Direction3D getDefaultRealisticLightDirection( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType );
static sal_Int32 getDefaultDirectLightColor( bool bSimple, const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType );
static sal_Int32 getDefaultAmbientLightColor( bool bSimple, const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType );
static sal_Int32 getNumberOfDisplayedSeries( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType, sal_Int32 nNumberOfSeries );
static bool noBordersForSimpleScheme( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType );
static sal_Int32 //one of ::com::sun::star::chart2::AxisType
getAxisType( const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType
, sal_Int32 nDimensionIndex );
/** Determines if all data series of a chart type are attached to the same
axis.
@param rOutAxisIndex If, and only if, </TRUE> is returned this
out-parameter is filled with the index (0 or 1) of the axis to
which all series are attached.
*/
static bool allSeriesAttachedToSameAxis(
const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType >& xChartType,
sal_Int32 & rOutAxisIndex );
};
//.............................................................................
} //namespace chart
//.............................................................................
#endif
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/file_path.h"
#include "chrome/test/ui/ui_layout_test.h"
namespace {
const char* kResources[] = {
"content",
"media-file.js",
"video-test.js",
};
} // anonymous namespace
class AudioUILayoutTest : public UILayoutTest {
protected:
virtual ~AudioUILayoutTest() { }
void RunMediaLayoutTest(const std::string& test_case_file_name) {
FilePath test_dir;
FilePath media_test_dir;
media_test_dir = media_test_dir.AppendASCII("media");
InitializeForLayoutTest(test_dir, media_test_dir, kNoHttpPort);
// Copy resources first.
for (size_t i = 0; i < arraysize(kResources); ++i) {
AddResourceForLayoutTest(
test_dir, media_test_dir.AppendASCII(kResources[i]));
}
printf("Test: %s\n", test_case_file_name.c_str());
RunLayoutTest(test_case_file_name, kNoHttpPort);
}
};
TEST_F(AudioUILayoutTest, AudioConstructorPreload) {
RunMediaLayoutTest("audio-constructor-preload.html");
}
TEST_F(AudioUILayoutTest, AudioConstructor) {
RunMediaLayoutTest("audio-constructor.html");
}
TEST_F(AudioUILayoutTest, AudioConstructorSrc) {
RunMediaLayoutTest("audio-constructor-src.html");
}
TEST_F(AudioUILayoutTest, AudioDataUrl) {
RunMediaLayoutTest("audio-data-url.html");
}
// The test fails since there is no real audio device on the build bots to get
// the ended event fired. Should pass once we run it on bots with audio devices.
TEST_F(AudioUILayoutTest, DISABLED_AudioGarbageCollect) {
RunMediaLayoutTest("audio-garbage-collect.html");
}
TEST_F(AudioUILayoutTest, AudioNoInstalledEngines) {
RunMediaLayoutTest("audio-no-installed-engines.html");
}
#if defined(OS_CHROMEOS) && defined(USE_AURA)
// http://crbug.com/115530
#define MAYBE_AudioOnlyVideoIntrinsicSize FLAKY_AudioOnlyVideoIntrinsicSize
#else
#define MAYBE_AudioOnlyVideoIntrinsicSize AudioOnlyVideoIntrinsicSize
#endif
TEST_F(AudioUILayoutTest, MAYBE_AudioOnlyVideoIntrinsicSize) {
RunMediaLayoutTest("audio-only-video-intrinsic-size.html");
}
TEST_F(AudioUILayoutTest, AudioPlayEvent) {
RunMediaLayoutTest("audio-play-event.html");
}
TEST_F(AudioUILayoutTest, MediaCanPlayWavAudio) {
RunMediaLayoutTest("media-can-play-wav-audio.html");
}
TEST_F(AudioUILayoutTest, MediaDocumentAudioSize) {
RunMediaLayoutTest("media-document-audio-size.html");
}
<commit_msg>Disable AudioUILayoutTest.AudioOnlyVideoIntrinsicSize on Aura ChromeOS.<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 "base/file_path.h"
#include "chrome/test/ui/ui_layout_test.h"
namespace {
const char* kResources[] = {
"content",
"media-file.js",
"video-test.js",
};
} // anonymous namespace
class AudioUILayoutTest : public UILayoutTest {
protected:
virtual ~AudioUILayoutTest() { }
void RunMediaLayoutTest(const std::string& test_case_file_name) {
FilePath test_dir;
FilePath media_test_dir;
media_test_dir = media_test_dir.AppendASCII("media");
InitializeForLayoutTest(test_dir, media_test_dir, kNoHttpPort);
// Copy resources first.
for (size_t i = 0; i < arraysize(kResources); ++i) {
AddResourceForLayoutTest(
test_dir, media_test_dir.AppendASCII(kResources[i]));
}
printf("Test: %s\n", test_case_file_name.c_str());
RunLayoutTest(test_case_file_name, kNoHttpPort);
}
};
TEST_F(AudioUILayoutTest, AudioConstructorPreload) {
RunMediaLayoutTest("audio-constructor-preload.html");
}
TEST_F(AudioUILayoutTest, AudioConstructor) {
RunMediaLayoutTest("audio-constructor.html");
}
TEST_F(AudioUILayoutTest, AudioConstructorSrc) {
RunMediaLayoutTest("audio-constructor-src.html");
}
TEST_F(AudioUILayoutTest, AudioDataUrl) {
RunMediaLayoutTest("audio-data-url.html");
}
// The test fails since there is no real audio device on the build bots to get
// the ended event fired. Should pass once we run it on bots with audio devices.
TEST_F(AudioUILayoutTest, DISABLED_AudioGarbageCollect) {
RunMediaLayoutTest("audio-garbage-collect.html");
}
TEST_F(AudioUILayoutTest, AudioNoInstalledEngines) {
RunMediaLayoutTest("audio-no-installed-engines.html");
}
#if defined(OS_CHROMEOS) && defined(USE_AURA)
// http://crbug.com/115530
#define MAYBE_AudioOnlyVideoIntrinsicSize DISABLED_AudioOnlyVideoIntrinsicSize
#else
#define MAYBE_AudioOnlyVideoIntrinsicSize AudioOnlyVideoIntrinsicSize
#endif
TEST_F(AudioUILayoutTest, MAYBE_AudioOnlyVideoIntrinsicSize) {
RunMediaLayoutTest("audio-only-video-intrinsic-size.html");
}
TEST_F(AudioUILayoutTest, AudioPlayEvent) {
RunMediaLayoutTest("audio-play-event.html");
}
TEST_F(AudioUILayoutTest, MediaCanPlayWavAudio) {
RunMediaLayoutTest("media-can-play-wav-audio.html");
}
TEST_F(AudioUILayoutTest, MediaDocumentAudioSize) {
RunMediaLayoutTest("media-document-audio-size.html");
}
<|endoftext|>
|
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010 Francois Beaune
//
// 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.
//
// Interface header.
#include "appleseed.h"
namespace foundation
{
//
// Library information.
//
// Return the name of the library.
const char* Appleseed::get_lib_name()
{
// Windows.
#if defined _WIN32
return "appleseed.dll";
// Mac OS X.
#elif defined __APPLE__
return "appleseed.dylib";
// Other operating system.
#else
return "appleseed.so";
#endif
}
// Return the version string of the library.
const char* Appleseed::get_lib_version()
{
return "1.1.0-UNOFFICIAL";
}
// Return the maturity level of the library.
const char* Appleseed::get_lib_maturity_level()
{
return "pre-alpha";
}
// Return the build number of the library.
size_t Appleseed::get_lib_build_number()
{
// This works as follow: the build number is stored in a static variable
// whose name is unique (the text after build_number_ is a GUID).
// Before compilation begins, a tool searches for this variable declaration
// (in this file) and increases the build number by 1.
static const size_t build_number_335A07D9_68C1_4E21_86FA_60C64BD6FE6C = 7599;
return build_number_335A07D9_68C1_4E21_86FA_60C64BD6FE6C;
}
// Return the configuration of the library.
const char* Appleseed::get_lib_configuration()
{
#ifdef DEBUG
return "Debug";
#else
return "Release";
#endif
}
// Return the compilation date of the library.
const char* Appleseed::get_lib_compilation_date()
{
return __DATE__;
}
// Return the compilation time of the library.
const char* Appleseed::get_lib_compilation_time()
{
return __TIME__;
}
} // namespace foundation
<commit_msg>changed library maturity level from "pre-alpha" to "alpha".<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010 Francois Beaune
//
// 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.
//
// Interface header.
#include "appleseed.h"
namespace foundation
{
//
// Library information.
//
// Return the name of the library.
const char* Appleseed::get_lib_name()
{
// Windows.
#if defined _WIN32
return "appleseed.dll";
// Mac OS X.
#elif defined __APPLE__
return "appleseed.dylib";
// Other operating system.
#else
return "appleseed.so";
#endif
}
// Return the version string of the library.
const char* Appleseed::get_lib_version()
{
return "1.1.0-UNOFFICIAL";
}
// Return the maturity level of the library.
const char* Appleseed::get_lib_maturity_level()
{
return "alpha";
}
// Return the build number of the library.
size_t Appleseed::get_lib_build_number()
{
// This works as follow: the build number is stored in a static variable
// whose name is unique (the text after build_number_ is a GUID).
// Before compilation begins, a tool searches for this variable declaration
// (in this file) and increases the build number by 1.
static const size_t build_number_335A07D9_68C1_4E21_86FA_60C64BD6FE6C = 7605;
return build_number_335A07D9_68C1_4E21_86FA_60C64BD6FE6C;
}
// Return the configuration of the library.
const char* Appleseed::get_lib_configuration()
{
#ifdef DEBUG
return "Debug";
#else
return "Release";
#endif
}
// Return the compilation date of the library.
const char* Appleseed::get_lib_compilation_date()
{
return __DATE__;
}
// Return the compilation time of the library.
const char* Appleseed::get_lib_compilation_time()
{
return __TIME__;
}
} // namespace foundation
<|endoftext|>
|
<commit_before>// Copyright (c) 2006-2008 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/common/notification_service.h"
#include "base/lazy_instance.h"
#include "base/thread_local.h"
static base::LazyInstance<base::ThreadLocalPointer<NotificationService> >
lazy_tls_ptr(base::LINKER_INITIALIZED);
// static
NotificationService* NotificationService::current() {
return lazy_tls_ptr.Pointer()->Get();
}
// static
bool NotificationService::HasKey(const NotificationSourceMap& map,
const NotificationSource& source) {
return map.find(source.map_key()) != map.end();
}
NotificationService::NotificationService() {
DCHECK(current() == NULL);
#ifndef NDEBUG
memset(observer_counts_, 0, sizeof(observer_counts_));
#endif
lazy_tls_ptr.Pointer()->Set(this);
}
void NotificationService::AddObserver(NotificationObserver* observer,
NotificationType type,
const NotificationSource& source) {
DCHECK(type.value < NotificationType::NOTIFICATION_TYPE_COUNT);
// We have gotten some crashes where the observer pointer is NULL. The problem
// is that this happens when we actually execute a notification, so have no
// way of knowing who the bad observer was. We want to know when this happens
// in release mode so we know what code to blame the crash on (since this is
// guaranteed to crash later).
CHECK(observer);
NotificationObserverList* observer_list;
if (HasKey(observers_[type.value], source)) {
observer_list = observers_[type.value][source.map_key()];
} else {
observer_list = new NotificationObserverList;
observers_[type.value][source.map_key()] = observer_list;
}
observer_list->AddObserver(observer);
#ifndef NDEBUG
++observer_counts_[type.value];
#endif
}
void NotificationService::RemoveObserver(NotificationObserver* observer,
NotificationType type,
const NotificationSource& source) {
DCHECK(type.value < NotificationType::NOTIFICATION_TYPE_COUNT);
DCHECK(HasKey(observers_[type.value], source));
NotificationObserverList* observer_list =
observers_[type.value][source.map_key()];
if (observer_list) {
observer_list->RemoveObserver(observer);
#ifndef NDEBUG
--observer_counts_[type.value];
#endif
}
// TODO(jhughes): Remove observer list from map if empty?
}
void NotificationService::Notify(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK(type.value > NotificationType::ALL) <<
"Allowed for observing, but not posting.";
DCHECK(type.value < NotificationType::NOTIFICATION_TYPE_COUNT);
// There's no particular reason for the order in which the different
// classes of observers get notified here.
// Notify observers of all types and all sources
if (HasKey(observers_[NotificationType::ALL], AllSources()) &&
source != AllSources()) {
FOR_EACH_OBSERVER(NotificationObserver,
*observers_[NotificationType::ALL][AllSources().map_key()],
Observe(type, source, details));
}
// Notify observers of all types and the given source
if (HasKey(observers_[NotificationType::ALL], source)) {
FOR_EACH_OBSERVER(NotificationObserver,
*observers_[NotificationType::ALL][source.map_key()],
Observe(type, source, details));
}
// Notify observers of the given type and all sources
if (HasKey(observers_[type.value], AllSources()) &&
source != AllSources()) {
FOR_EACH_OBSERVER(NotificationObserver,
*observers_[type.value][AllSources().map_key()],
Observe(type, source, details));
}
// Notify observers of the given type and the given source
if (HasKey(observers_[type.value], source)) {
FOR_EACH_OBSERVER(NotificationObserver,
*observers_[type.value][source.map_key()],
Observe(type, source, details));
}
}
NotificationService::~NotificationService() {
lazy_tls_ptr.Pointer()->Set(NULL);
#ifndef NDEBUG
for (int i = 0; i < NotificationType::NOTIFICATION_TYPE_COUNT; i++) {
if (observer_counts_[i] > 0) {
LOG(WARNING) << observer_counts_[i] << " notification observer(s) leaked"
<< " of notification type " << i;
}
}
#endif
for (int i = 0; i < NotificationType::NOTIFICATION_TYPE_COUNT; i++) {
NotificationSourceMap omap = observers_[i];
for (NotificationSourceMap::iterator it = omap.begin();
it != omap.end(); ++it) {
delete it->second;
}
}
}
NotificationObserver::~NotificationObserver() {}
<commit_msg>Add a note pointing at a bug so others don't waste time.<commit_after>// Copyright (c) 2006-2008 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/common/notification_service.h"
#include "base/lazy_instance.h"
#include "base/thread_local.h"
static base::LazyInstance<base::ThreadLocalPointer<NotificationService> >
lazy_tls_ptr(base::LINKER_INITIALIZED);
// static
NotificationService* NotificationService::current() {
return lazy_tls_ptr.Pointer()->Get();
}
// static
bool NotificationService::HasKey(const NotificationSourceMap& map,
const NotificationSource& source) {
return map.find(source.map_key()) != map.end();
}
NotificationService::NotificationService() {
DCHECK(current() == NULL);
#ifndef NDEBUG
memset(observer_counts_, 0, sizeof(observer_counts_));
#endif
lazy_tls_ptr.Pointer()->Set(this);
}
void NotificationService::AddObserver(NotificationObserver* observer,
NotificationType type,
const NotificationSource& source) {
DCHECK(type.value < NotificationType::NOTIFICATION_TYPE_COUNT);
// We have gotten some crashes where the observer pointer is NULL. The problem
// is that this happens when we actually execute a notification, so have no
// way of knowing who the bad observer was. We want to know when this happens
// in release mode so we know what code to blame the crash on (since this is
// guaranteed to crash later).
CHECK(observer);
NotificationObserverList* observer_list;
if (HasKey(observers_[type.value], source)) {
observer_list = observers_[type.value][source.map_key()];
} else {
observer_list = new NotificationObserverList;
observers_[type.value][source.map_key()] = observer_list;
}
observer_list->AddObserver(observer);
#ifndef NDEBUG
++observer_counts_[type.value];
#endif
}
void NotificationService::RemoveObserver(NotificationObserver* observer,
NotificationType type,
const NotificationSource& source) {
DCHECK(type.value < NotificationType::NOTIFICATION_TYPE_COUNT);
DCHECK(HasKey(observers_[type.value], source));
NotificationObserverList* observer_list =
observers_[type.value][source.map_key()];
if (observer_list) {
observer_list->RemoveObserver(observer);
#ifndef NDEBUG
--observer_counts_[type.value];
#endif
}
// TODO(jhughes): Remove observer list from map if empty?
}
void NotificationService::Notify(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK(type.value > NotificationType::ALL) <<
"Allowed for observing, but not posting.";
DCHECK(type.value < NotificationType::NOTIFICATION_TYPE_COUNT);
// There's no particular reason for the order in which the different
// classes of observers get notified here.
// Notify observers of all types and all sources
if (HasKey(observers_[NotificationType::ALL], AllSources()) &&
source != AllSources()) {
FOR_EACH_OBSERVER(NotificationObserver,
*observers_[NotificationType::ALL][AllSources().map_key()],
Observe(type, source, details));
}
// Notify observers of all types and the given source
if (HasKey(observers_[NotificationType::ALL], source)) {
FOR_EACH_OBSERVER(NotificationObserver,
*observers_[NotificationType::ALL][source.map_key()],
Observe(type, source, details));
}
// Notify observers of the given type and all sources
if (HasKey(observers_[type.value], AllSources()) &&
source != AllSources()) {
FOR_EACH_OBSERVER(NotificationObserver,
*observers_[type.value][AllSources().map_key()],
Observe(type, source, details));
}
// Notify observers of the given type and the given source
if (HasKey(observers_[type.value], source)) {
FOR_EACH_OBSERVER(NotificationObserver,
*observers_[type.value][source.map_key()],
Observe(type, source, details));
}
}
NotificationService::~NotificationService() {
lazy_tls_ptr.Pointer()->Set(NULL);
#ifndef NDEBUG
for (int i = 0; i < NotificationType::NOTIFICATION_TYPE_COUNT; i++) {
if (observer_counts_[i] > 0) {
// This may not be completely fixable -- see
// http://code.google.com/p/chromium/issues/detail?id=11010 .
// But any new leaks should be fixed.
LOG(WARNING) << observer_counts_[i] << " notification observer(s) leaked"
<< " of notification type " << i;
}
}
#endif
for (int i = 0; i < NotificationType::NOTIFICATION_TYPE_COUNT; i++) {
NotificationSourceMap omap = observers_[i];
for (NotificationSourceMap::iterator it = omap.begin();
it != omap.end(); ++it) {
delete it->second;
}
}
}
NotificationObserver::~NotificationObserver() {}
<|endoftext|>
|
<commit_before>// Copyright (c) 2016, Joseph Mirabel
// Authors: Joseph Mirabel (joseph.mirabel@laas.fr)
//
// This file is part of hpp-pinocchio.
// hpp-pinocchio is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-pinocchio is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-pinocchio. If not, see <http://www.gnu.org/licenses/>.
#include "pinocchio/multibody/visitor.hpp"
#include "pinocchio/multibody/model.hpp"
#include "pinocchio/algorithm/jacobian.hpp"
namespace se3
{
// Compute the vector of joint index of the subtree.
// inline void
// subtreeIndexes(const Model & model, SubtreeModel & stModel)
// {
// JointIndex root = stModel.root;
// const size_t shift = root;
// std::vector<bool> shouldInclude (model.nbody-shift, true);
// for( Model::JointIndex i= (Model::JointIndex) (model.nbody-1);i>root;--i )
// {
// if (!shouldInclude[i - shift]) continue;
// Model::JointIndex j = i;
// while (j > root) j = model.parents[j];
// if (j == root) continue;
// j = i;
// while (j > root) {
// shouldInclude[j - shift] = false;
// j = model.parents[j];
// }
// }
// stModel.joints.clear();
// for(int i=(int)shouldInclude.size()-1; i>=0;--i)
// if (shouldInclude[i]) stModel.joints.push_back(i+shift);
// }
// struct SubtreeJacobianCenterOfMassBackwardStep
// : public fusion::JointVisitor<SubtreeJacobianCenterOfMassBackwardStep>
// {
// typedef boost::fusion::vector<const se3::Model &,
// se3::Data &,
// JointIndex
// > ArgsType;
// JOINT_VISITOR_INIT(SubtreeJacobianCenterOfMassBackwardStep);
// template<typename JointModel>
// static void algo(const se3::JointModelBase<JointModel> & jmodel,
// se3::JointDataBase<typename JointModel::JointDataDerived> & jdata,
// const se3::Model& model,
// se3::Data& data,
// const JointIndex& r )
// {
// const Model::JointIndex & i = (Model::JointIndex) jmodel.id();
// const Model::JointIndex & parent = model.parents[i];
// if (i != r) {
// data.com[parent] += data.com[i];
// data.mass[parent] += data.mass[i];
// }
// typedef Data::Matrix6x Matrix6x;
// typedef typename SizeDepType<JointModel::NV>::template ColsReturn<Matrix6x>::Type ColBlock;
// ColBlock Jcols = jmodel.jointCols(data.J);
// Jcols = data.oMi[i].act(jdata.S());
// if( JointModel::NV==1 )
// data.Jcom.col(jmodel.idx_v())
// = data.mass[i] * Jcols.template topLeftCorner<3,1>()
// - data.com[i].cross(Jcols.template bottomLeftCorner<3,1>());
// else
// jmodel.jointCols(data.Jcom)
// = data.mass[i] * Jcols.template topRows<3>()
// - skew(data.com[i]) * Jcols.template bottomRows<3>();
// data.com[i] /= data.mass[i];
// }
// } ;
inline void
subtreeCenterOfMass(const Model & model, Data & data,
const std::vector <JointIndex>& roots)
{
data.com[0].setZero ();
data.mass[0] = 0;
for(Model::JointIndex i=1;i<(Model::JointIndex)(model.nbody);++i)
{
const double mass = model.inertias[i].mass();
const SE3::Vector3 & lever = model.inertias[i].lever();
data.mass[i] = mass;
data.com[i] = mass*data.oMi[i].act(lever);
}
// Assume root is sorted from largest id.
// Nasty cast below, from (u-long) size_t to int.
for( int root=int(roots.size()-1); root>=0; --root )
{
se3::JointIndex rootId = roots[root];
// Backward loop on descendents
for( se3::JointIndex jid = data.lastChild[rootId];jid>=rootId;--jid )
{
const Model::JointIndex & parent = model.parents[jid];
data.com [parent] += data.com [jid];
data.mass[parent] += data.mass[jid];
} // end for jid
// Backward loop on ancestors
se3::JointIndex jid = model.parents[rootId];
rootId = (root>0) ? roots[root-1] : 0;
while (jid>rootId) // stopping when meeting the next subtree
{
const Model::JointIndex & parent = model.parents[jid];
data.com [parent] += data.com [jid];
data.mass[parent] += data.mass[jid];
jid = parent;
} // end while
} // end for i
data.com[0] /= data.mass[0];
data.Jcom /= data.mass[0];
}
inline void
subtreeJacobianCenterOfMass(const Model & model, Data & data,
const std::vector <JointIndex>& roots)
{
data.com[0].setZero ();
data.mass[0] = 0;
for(Model::JointIndex i=1;i<(Model::JointIndex)(model.nbody);++i)
{
const double mass = model.inertias[i].mass();
const SE3::Vector3 & lever = model.inertias[i].lever();
data.mass[i] = mass;
data.com[i] = mass*data.oMi[i].act(lever);
}
// Assume root is sorted from largest id.
// Nasty cast below, from (u-long) size_t to int.
for( int root=int(roots.size()-1); root>=0; --root )
{
se3::JointIndex rootId = roots[root];
// Backward loop on descendents
for( se3::JointIndex jid = data.lastChild[rootId];jid>=rootId;--jid )
{
std::cout << "Bwd1 " << jid << std::endl;
se3::JacobianCenterOfMassBackwardStep
::run(model.joints[jid],data.joints[jid],
JacobianCenterOfMassBackwardStep::ArgsType(model,data,false));
std::cout << data.oMi [jid] << std::endl;
std::cout << data.mass[jid] << std::endl;
std::cout << data.com [jid].transpose() << std::endl;
} // end for jid
// Backward loop on ancestors
se3::JointIndex jid = model.parents[rootId];
rootId = (root>0) ? roots[root-1] : 0;
while (jid>rootId) // stopping when meeting the next subtree
{
std::cout << "Bwd2 " << jid << std::endl;
se3::JacobianCenterOfMassBackwardStep
::run(model.joints[jid],data.joints[jid],
JacobianCenterOfMassBackwardStep::ArgsType(model,data,false));
jid = model.parents[jid];
} // end while
} // end for i
data.com[0] /= data.mass[0];
data.Jcom /= data.mass[0];
}
} // namespace se3
<commit_msg>Clean code.<commit_after>// Copyright (c) 2016, Joseph Mirabel
// Authors: Joseph Mirabel (joseph.mirabel@laas.fr)
//
// This file is part of hpp-pinocchio.
// hpp-pinocchio is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-pinocchio is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-pinocchio. If not, see <http://www.gnu.org/licenses/>.
#include "pinocchio/multibody/visitor.hpp"
#include "pinocchio/multibody/model.hpp"
#include "pinocchio/algorithm/jacobian.hpp"
namespace se3
{
inline void
subtreeCenterOfMass(const Model & model, Data & data,
const std::vector <JointIndex>& roots)
{
data.com[0].setZero ();
data.mass[0] = 0;
for(Model::JointIndex i=1;i<(Model::JointIndex)(model.nbody);++i)
{
const double mass = model.inertias[i].mass();
const SE3::Vector3 & lever = model.inertias[i].lever();
data.mass[i] = mass;
data.com[i] = mass*data.oMi[i].act(lever);
}
// Assume root is sorted from largest id.
// Nasty cast below, from (u-long) size_t to int.
for( int root=int(roots.size()-1); root>=0; --root )
{
se3::JointIndex rootId = roots[root];
// Backward loop on descendents
for( se3::JointIndex jid = data.lastChild[rootId];jid>=rootId;--jid )
{
const Model::JointIndex & parent = model.parents[jid];
data.com [parent] += data.com [jid];
data.mass[parent] += data.mass[jid];
} // end for jid
// Backward loop on ancestors
se3::JointIndex jid = model.parents[rootId];
rootId = (root>0) ? roots[root-1] : 0;
while (jid>rootId) // stopping when meeting the next subtree
{
const Model::JointIndex & parent = model.parents[jid];
data.com [parent] += data.com [jid];
data.mass[parent] += data.mass[jid];
jid = parent;
} // end while
} // end for i
data.com[0] /= data.mass[0];
data.Jcom /= data.mass[0];
}
inline void
subtreeJacobianCenterOfMass(const Model & model, Data & data,
const std::vector <JointIndex>& roots)
{
data.com[0].setZero ();
data.mass[0] = 0;
for(Model::JointIndex i=1;i<(Model::JointIndex)(model.nbody);++i)
{
const double mass = model.inertias[i].mass();
const SE3::Vector3 & lever = model.inertias[i].lever();
data.mass[i] = mass;
data.com[i] = mass*data.oMi[i].act(lever);
}
// Assume root is sorted from largest id.
// Nasty cast below, from (u-long) size_t to int.
for( int root=int(roots.size()-1); root>=0; --root )
{
se3::JointIndex rootId = roots[root];
// Backward loop on descendents
for( se3::JointIndex jid = data.lastChild[rootId];jid>=rootId;--jid )
{
std::cout << "Bwd1 " << jid << std::endl;
se3::JacobianCenterOfMassBackwardStep
::run(model.joints[jid],data.joints[jid],
JacobianCenterOfMassBackwardStep::ArgsType(model,data,false));
std::cout << data.oMi [jid] << std::endl;
std::cout << data.mass[jid] << std::endl;
std::cout << data.com [jid].transpose() << std::endl;
} // end for jid
// Backward loop on ancestors
se3::JointIndex jid = model.parents[rootId];
rootId = (root>0) ? roots[root-1] : 0;
while (jid>rootId) // stopping when meeting the next subtree
{
std::cout << "Bwd2 " << jid << std::endl;
se3::JacobianCenterOfMassBackwardStep
::run(model.joints[jid],data.joints[jid],
JacobianCenterOfMassBackwardStep::ArgsType(model,data,false));
jid = model.parents[jid];
} // end while
} // end for i
data.com[0] /= data.mass[0];
data.Jcom /= data.mass[0];
}
} // namespace se3
<|endoftext|>
|
<commit_before>#include <catch.hpp>
#include <pmath/Vector.hpp>
using namespace pmath;
TEST_CASE("Vector2 tests", "[vector]")
{
SECTION("Boolean tests")
{
CHECK(Vec2(1, 1) != Vec2(2, 1));
CHECK(Vec2(2, 2) == Vec2(2, 2));
CHECK_FALSE(Vec2(2, 2) == Vec2(1, 2));
CHECK_FALSE(Vec2(2, 2) != Vec2(2, 2));
}
SECTION("Basic operators")
{
Vec2 vec1(5, 10);
Vec2 vec2(2, 4);
CHECK((vec1 - vec2) == Vec2(3, 6));
CHECK((vec1 + vec2) == Vec2(7, 14));
CHECK((vec1 * 2) == Vec2(10, 20));
CHECK((vec2 / 2) == Vec2(1, 2));
vec1 *= 2;
CHECK(vec1 == Vec2(10, 20));
vec2 /= 2;
CHECK(vec2 == Vec2(1, 2));
vec1 = Vec2(5, 10);
vec2 = Vec2(2, 4);
CHECK(vec1 == Vec2(5, 10));
CHECK(vec2 == Vec2(2, 4));
vec1 += Vec2(5, 5);
vec2 -= Vec2(2, 4);
CHECK(vec1 == Vec2(10, 15));
CHECK(vec2 == Vec2());
CHECK(Vec2(1, 2) > Vec2(1, 1));
CHECK(Vec2(1, 2) >= Vec2(1, 2));
CHECK(Vec2(1, 2) <= Vec2(2, 2));
CHECK(Vec2(1, 2) < Vec2(-2, -2));
vec1 = Vec2(1, 2);
CHECK(vec1[0] == 1);
CHECK(vec1[1] == 2);
}
SECTION("Dot, cross and length")
{
Vec2 vec1(2, 2);
Vec2 vec2(5, 5);
CHECK(vec1.dot(vec2) == 20);
CHECK(Vec2::dot(vec1, vec2) == 20);
CHECK(vec1.length() == sqrt(8.0));
CHECK(vec2.lengthSquared() == 50);
Vec2 a(1,2), b(9,8);
CHECK(a.cross(b) == -10);
CHECK(Vec2::cross(b, a) == 10);
CHECK(Vec2::distance(Vec2(1, 2), Vec2(2,1)) == sqrt(2.0));
}
SECTION("Normals")
{
Vec2 vec(5, 9);
CHECK(vec.unitVector() == Vec2(5 / sqrt(106.f), 9 / sqrt(106.f)));
CHECK(vec.normalize() == Vec2(5 / sqrt(106.f), 9 / sqrt(106.f)));
}
}
TEST_CASE("Vector3 tests", "[vector]")
{
SECTION("Boolean tests")
{
Vec3 vec1(1, 2, 3);
Vec3 vec2(3, 2, 1);
CHECK(vec1 == Vec3(1, 2, 3));
CHECK(vec1 != vec2);
CHECK_FALSE(vec1 == vec2);
CHECK_FALSE(vec2 != vec2);
}
SECTION("Basic operators")
{
Vec3 vec1(5, 10, 15);
Vec3 vec2(2, 4, 8);
CHECK(-vec1 == Vec3(-5, -10, -15));
CHECK((vec1 - vec2) == Vec3(3, 6, 7));
CHECK_FALSE((vec1 - vec2) == Vec3(7, 6, 3));
CHECK((vec1 + vec2) == Vec3(7, 14, 23));
CHECK_FALSE((vec1 + vec2) == Vec3(23, 14, 7));
CHECK((vec1 * 2) == Vec3(10, 20, 30));
CHECK((vec2 / 2) == Vec3(1, 2, 4));
vec1 *= 2;
CHECK(vec1 == Vec3(10, 20, 30));
vec2 /= 2;
CHECK(vec2 == Vec3(1, 2, 4));
vec1 = Vec3(5, 10, 15);
vec2 = Vec3(2, 4, 8);
REQUIRE(vec1 == Vec3(5, 10, 15));
REQUIRE(vec2 == Vec3(2, 4, 8));
vec1 += Vec3(5, 5, 5);
vec2 -= Vec3(2, 4, 8);
CHECK(vec1 == Vec3(10, 15, 20));
CHECK(vec2 == Vec3());
CHECK(Vec3(1, 2, 3) > Vec3(1, 2, 2));
CHECK(Vec3(1, 2, 3) >= Vec3(1, 2, 3));
CHECK(Vec3(1, 2, 3) <= Vec3(2, 2, 3));
CHECK(Vec3(1, 2, 3) < Vec3(-2, -2, -4));
vec1 = Vec3(1, 2, 3);
CHECK(vec1[1] == 2);
CHECK(vec1[2] == 3);
}
SECTION("Dot, cross and length")
{
Vec3 vec1(1, 2, 3);
Vec3 vec2(7, 8, 9);
CHECK(vec1.dot(vec2) == 50);
CHECK(Vec3::dot(vec2, vec1) == 50);
CHECK(vec1.length() == sqrt(14.0));
CHECK(vec2.lengthSquared() == 194);
CHECK(vec1.cross(vec2) == Vec3(-6, 12, -6));
CHECK(Vec3::cross(vec2, vec1) == Vec3(6, -12, 6));
CHECK(Vec3::distance(Vec3(1, 2, 3), Vec3(3, 2, 1)) == 2*sqrt(2.0));
}
SECTION("Normals")
{
Vec3 vec(5, 9, 7);
CHECK(vec.unitVector() == Vec3(sqrt(5.f / 31.f), 9 / sqrt(155.f), 7 / sqrt(155.f)));
CHECK(vec.normalize() == Vec3(sqrt(5.f / 31.f), 9 / sqrt(155.f), 7 / sqrt(155.f)));
}
}
TEST_CASE("Vector4 tests", "[vector]")
{
SECTION("Boolean tests")
{
Vec4 vec1(1, 2, 3, 4);
Vec4 vec2(4, 3, 2, 1);
CHECK(vec1 == Vec4(1, 2, 3, 4));
CHECK(vec1 != vec2);
CHECK_FALSE(vec1 == vec2);
CHECK_FALSE(vec2 != vec2);
}
SECTION("Basic operators")
{
Vec4 vec1(5, 10, 15, 20);
Vec4 vec2(2, 4, 8, 16);
CHECK(-vec1 == Vec4(-5, -10, -15, -20));
CHECK((vec1 - vec2) == Vec4(3, 6, 7, 4));
CHECK_FALSE((vec1 - vec2) == Vec4(4, 7, 6, 3));
CHECK((vec1 + vec2) == Vec4(7, 14, 23, 36));
CHECK_FALSE((vec1 + vec2) == Vec4(36, 23, 14, 7));
CHECK((vec1 * 2) == Vec4(10, 20, 30, 40));
CHECK((vec2 / 2) == Vec4(1, 2, 4, 8));
vec1 *= 2;
CHECK(vec1 == Vec4(10, 20, 30, 40));
vec2 /= 2;
CHECK(vec2 == Vec4(1, 2, 4, 8));
vec1 = Vec4(5, 10, 15, 20);
vec2 = Vec4(2, 4, 8, 16);
REQUIRE(vec1 == Vec4(5, 10, 15, 20));
REQUIRE(vec2 == Vec4(2, 4, 8, 16));
vec1 += Vec4(5, 5, 5, 5);
vec2 -= Vec4(2, 4, 8, 16);
CHECK(vec1 == Vec4(10, 15, 20, 25));
CHECK(vec2 == Vec4());
CHECK(Vec4(1, 2, 3, 4) > Vec4(1, 2, 2, 3));
CHECK(Vec4(1, 2, 3, 4) >= Vec4(1, 2, 3, 4));
CHECK(Vec4(1, 2, 3, 4) <= Vec4(2, 2, 3, 4));
CHECK(Vec4(1, 2, 3, 4) < Vec4(-2, -2, -4, -4));
vec1 = Vec4(1, 2, 3, 4);
CHECK(vec1[1] == 2);
CHECK(vec1[3] == 4);
}
SECTION("Dot and length")
{
Vec4 vec1(1, 2, 3, 4);
Vec4 vec2(7, 8, 9, 10);
CHECK(vec1.dot(vec2) == 90);
CHECK(Vec4::dot(vec2, vec1) == 90);
CHECK(vec2.length() == sqrt(294.0));
CHECK(vec1.lengthSquared() == 30);
CHECK(Vec4::distance(Vec4(1, 2, 3, 4), Vec4(4,3,2,1)) == 2*sqrt(5.0));
}
SECTION("Normals")
{
Vec4 vec(5, 9, 3, 1);
Vec4 result(5 / (2 * sqrt(29.f)), 9 / (2 * sqrt(29.f)),
3 / (2 * sqrt(29.f)), 1 / (2 * sqrt(29.f)));
CHECK(vec.unitVector() == result);
CHECK(vec.normalize() == result);
}
}<commit_msg>Fix tabs<commit_after>#include <catch.hpp>
#include <pmath/Vector.hpp>
using namespace pmath;
TEST_CASE("Vector2 tests", "[vector]")
{
SECTION("Boolean tests")
{
CHECK(Vec2(1, 1) != Vec2(2, 1));
CHECK(Vec2(2, 2) == Vec2(2, 2));
CHECK_FALSE(Vec2(2, 2) == Vec2(1, 2));
CHECK_FALSE(Vec2(2, 2) != Vec2(2, 2));
}
SECTION("Basic operators")
{
Vec2 vec1(5, 10);
Vec2 vec2(2, 4);
CHECK((vec1 - vec2) == Vec2(3, 6));
CHECK((vec1 + vec2) == Vec2(7, 14));
CHECK((vec1 * 2) == Vec2(10, 20));
CHECK((vec2 / 2) == Vec2(1, 2));
vec1 *= 2;
CHECK(vec1 == Vec2(10, 20));
vec2 /= 2;
CHECK(vec2 == Vec2(1, 2));
vec1 = Vec2(5, 10);
vec2 = Vec2(2, 4);
CHECK(vec1 == Vec2(5, 10));
CHECK(vec2 == Vec2(2, 4));
vec1 += Vec2(5, 5);
vec2 -= Vec2(2, 4);
CHECK(vec1 == Vec2(10, 15));
CHECK(vec2 == Vec2());
CHECK(Vec2(1, 2) > Vec2(1, 1));
CHECK(Vec2(1, 2) >= Vec2(1, 2));
CHECK(Vec2(1, 2) <= Vec2(2, 2));
CHECK(Vec2(1, 2) < Vec2(-2, -2));
vec1 = Vec2(1, 2);
CHECK(vec1[0] == 1);
CHECK(vec1[1] == 2);
}
SECTION("Dot, cross and length")
{
Vec2 vec1(2, 2);
Vec2 vec2(5, 5);
CHECK(vec1.dot(vec2) == 20);
CHECK(Vec2::dot(vec1, vec2) == 20);
CHECK(vec1.length() == sqrt(8.0));
CHECK(vec2.lengthSquared() == 50);
Vec2 a(1,2), b(9,8);
CHECK(a.cross(b) == -10);
CHECK(Vec2::cross(b, a) == 10);
CHECK(Vec2::distance(Vec2(1, 2), Vec2(2,1)) == sqrt(2.0));
}
SECTION("Normals")
{
Vec2 vec(5, 9);
CHECK(vec.unitVector() == Vec2(5 / sqrt(106.f), 9 / sqrt(106.f)));
CHECK(vec.normalize() == Vec2(5 / sqrt(106.f), 9 / sqrt(106.f)));
}
}
TEST_CASE("Vector3 tests", "[vector]")
{
SECTION("Boolean tests")
{
Vec3 vec1(1, 2, 3);
Vec3 vec2(3, 2, 1);
CHECK(vec1 == Vec3(1, 2, 3));
CHECK(vec1 != vec2);
CHECK_FALSE(vec1 == vec2);
CHECK_FALSE(vec2 != vec2);
}
SECTION("Basic operators")
{
Vec3 vec1(5, 10, 15);
Vec3 vec2(2, 4, 8);
CHECK(-vec1 == Vec3(-5, -10, -15));
CHECK((vec1 - vec2) == Vec3(3, 6, 7));
CHECK_FALSE((vec1 - vec2) == Vec3(7, 6, 3));
CHECK((vec1 + vec2) == Vec3(7, 14, 23));
CHECK_FALSE((vec1 + vec2) == Vec3(23, 14, 7));
CHECK((vec1 * 2) == Vec3(10, 20, 30));
CHECK((vec2 / 2) == Vec3(1, 2, 4));
vec1 *= 2;
CHECK(vec1 == Vec3(10, 20, 30));
vec2 /= 2;
CHECK(vec2 == Vec3(1, 2, 4));
vec1 = Vec3(5, 10, 15);
vec2 = Vec3(2, 4, 8);
REQUIRE(vec1 == Vec3(5, 10, 15));
REQUIRE(vec2 == Vec3(2, 4, 8));
vec1 += Vec3(5, 5, 5);
vec2 -= Vec3(2, 4, 8);
CHECK(vec1 == Vec3(10, 15, 20));
CHECK(vec2 == Vec3());
CHECK(Vec3(1, 2, 3) > Vec3(1, 2, 2));
CHECK(Vec3(1, 2, 3) >= Vec3(1, 2, 3));
CHECK(Vec3(1, 2, 3) <= Vec3(2, 2, 3));
CHECK(Vec3(1, 2, 3) < Vec3(-2, -2, -4));
vec1 = Vec3(1, 2, 3);
CHECK(vec1[1] == 2);
CHECK(vec1[2] == 3);
}
SECTION("Dot, cross and length")
{
Vec3 vec1(1, 2, 3);
Vec3 vec2(7, 8, 9);
CHECK(vec1.dot(vec2) == 50);
CHECK(Vec3::dot(vec2, vec1) == 50);
CHECK(vec1.length() == sqrt(14.0));
CHECK(vec2.lengthSquared() == 194);
CHECK(vec1.cross(vec2) == Vec3(-6, 12, -6));
CHECK(Vec3::cross(vec2, vec1) == Vec3(6, -12, 6));
CHECK(Vec3::distance(Vec3(1, 2, 3), Vec3(3, 2, 1)) == 2*sqrt(2.0));
}
SECTION("Normals")
{
Vec3 vec(5, 9, 7);
CHECK(vec.unitVector() == Vec3(sqrt(5.f / 31.f), 9 / sqrt(155.f), 7 / sqrt(155.f)));
CHECK(vec.normalize() == Vec3(sqrt(5.f / 31.f), 9 / sqrt(155.f), 7 / sqrt(155.f)));
}
}
TEST_CASE("Vector4 tests", "[vector]")
{
SECTION("Boolean tests")
{
Vec4 vec1(1, 2, 3, 4);
Vec4 vec2(4, 3, 2, 1);
CHECK(vec1 == Vec4(1, 2, 3, 4));
CHECK(vec1 != vec2);
CHECK_FALSE(vec1 == vec2);
CHECK_FALSE(vec2 != vec2);
}
SECTION("Basic operators")
{
Vec4 vec1(5, 10, 15, 20);
Vec4 vec2(2, 4, 8, 16);
CHECK(-vec1 == Vec4(-5, -10, -15, -20));
CHECK((vec1 - vec2) == Vec4(3, 6, 7, 4));
CHECK_FALSE((vec1 - vec2) == Vec4(4, 7, 6, 3));
CHECK((vec1 + vec2) == Vec4(7, 14, 23, 36));
CHECK_FALSE((vec1 + vec2) == Vec4(36, 23, 14, 7));
CHECK((vec1 * 2) == Vec4(10, 20, 30, 40));
CHECK((vec2 / 2) == Vec4(1, 2, 4, 8));
vec1 *= 2;
CHECK(vec1 == Vec4(10, 20, 30, 40));
vec2 /= 2;
CHECK(vec2 == Vec4(1, 2, 4, 8));
vec1 = Vec4(5, 10, 15, 20);
vec2 = Vec4(2, 4, 8, 16);
REQUIRE(vec1 == Vec4(5, 10, 15, 20));
REQUIRE(vec2 == Vec4(2, 4, 8, 16));
vec1 += Vec4(5, 5, 5, 5);
vec2 -= Vec4(2, 4, 8, 16);
CHECK(vec1 == Vec4(10, 15, 20, 25));
CHECK(vec2 == Vec4());
CHECK(Vec4(1, 2, 3, 4) > Vec4(1, 2, 2, 3));
CHECK(Vec4(1, 2, 3, 4) >= Vec4(1, 2, 3, 4));
CHECK(Vec4(1, 2, 3, 4) <= Vec4(2, 2, 3, 4));
CHECK(Vec4(1, 2, 3, 4) < Vec4(-2, -2, -4, -4));
vec1 = Vec4(1, 2, 3, 4);
CHECK(vec1[1] == 2);
CHECK(vec1[3] == 4);
}
SECTION("Dot and length")
{
Vec4 vec1(1, 2, 3, 4);
Vec4 vec2(7, 8, 9, 10);
CHECK(vec1.dot(vec2) == 90);
CHECK(Vec4::dot(vec2, vec1) == 90);
CHECK(vec2.length() == sqrt(294.0));
CHECK(vec1.lengthSquared() == 30);
CHECK(Vec4::distance(Vec4(1, 2, 3, 4), Vec4(4,3,2,1)) == 2*sqrt(5.0));
}
SECTION("Normals")
{
Vec4 vec(5, 9, 3, 1);
Vec4 result(5 / (2 * sqrt(29.f)), 9 / (2 * sqrt(29.f)),
3 / (2 * sqrt(29.f)), 1 / (2 * sqrt(29.f)));
CHECK(vec.unitVector() == result);
CHECK(vec.normalize() == result);
}
}<|endoftext|>
|
<commit_before>#pragma once
#include <csv.h>
#include <iostream>
#include <boost/lexical_cast.hpp>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <typeinfo>
namespace csv {
namespace detail {
struct Result {
int number{0};
std::string message{"success"};
operator bool() const { return number == 0; }
};
class MappedFile {
private:
int fd_;
size_t size_;
char* data_;
public:
MappedFile(const std::string& filename) : fd_(0), size_(0), data_(NULL) {
fd_ = ::open(filename.c_str(), O_RDONLY);
if (fd_ < 0) {
set_error();
return;
}
struct stat statbuf;
if (::fstat(fd_, &statbuf) < 0) {
set_error();
return;
}
size_ = statbuf.st_size;
data_ = (char*)::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
if (data_ == NULL) {
set_error();
return;
}
}
~MappedFile() {
::munmap(data_, size_);
::close(fd_);
}
const char* begin() const { return data_; }
const char* end() const { return data_ + size_; }
operator bool() { return status; }
detail::Result status;
private:
void set_error() {
status.number = errno;
status.message = strerror(errno);
}
};
// generates sequence numbers used in template expansion
namespace sequence {
template <int... Is>
struct index {};
template <int N, int... Is>
struct generate : generate<N - 1, N - 1, Is...> {};
template <int... Is>
struct generate<0, Is...> : index<Is...> {};
} // namespace sequence
namespace meta {
template <class F>
class fields;
// function pointer
template <class R, class... Args>
class fields<R (*)(Args...)> : public fields<R(Args...)> {};
// member function pointer
template <class C, class R, class... Args>
class fields<R (C::*)(Args...)> : public fields<R(Args...)> {};
// const member function pointer
template <class C, class R, class... Args>
class fields<R (C::*)(Args...) const> : public fields<R(Args...)> {};
// member object pointer
template <class C, class R>
class fields<R(C::*)> : public fields<R(C&)> {};
// functor
template <class F>
class fields : public fields<decltype(&F::operator())> {};
// reference
template <class F>
class fields<F&> : public fields<F> {};
// perfect reference
template <class F>
class fields<F&&> : public fields<F> {};
// impl
template <class R, class... Args>
class fields<R(Args...)> {
using mutator_t = std::function<void(const char* buf, size_t len)>;
public:
fields() {
setupFieldHandlers(
typename detail::sequence::generate<sizeof...(Args)>::index());
}
void accept_field(size_t field_pos, const char* buf, size_t len) {
if (field_pos < mutators.size()) {
mutators[field_pos](buf, len);
}
}
template <typename F>
void accept_row(F& sink) {
call_func(sink,
typename detail::sequence::generate<sizeof...(Args)>::index());
}
template <typename F, int... S>
void call_func(F& sink, detail::sequence::index<S...>) {
sink(std::get<S>(values)...);
}
private:
std::tuple<typename std::decay<Args>::type...> values;
std::vector<mutator_t> mutators;
private:
template <int... S>
void setupFieldHandlers(detail::sequence::index<S...>) {
setupFieldHandlers(std::get<S>(values)...);
}
template <typename F, typename... Fa>
void setupFieldHandlers(F& arg, Fa&... args) {
size_t field_num = mutators.size();
mutators.push_back([field_num, &arg](const char* buf, size_t len) {
if (len > 0) {
arg = boost::lexical_cast<F>(buf, len);
} else {
arg = F();
}
});
setupFieldHandlers(args...);
}
void setupFieldHandlers() {
// this is the terminal function for recursive template expansion
}
};
} // namespace meta
} // detail
/* A C++ wrapper around libcsv, see `make_parser` below */
struct filter_result {
bool drop;
constexpr filter_result(bool b) : drop(b) {}
operator bool() const { return drop; }
};
static constexpr filter_result ROW_DROP{true};
static constexpr filter_result ROW_OK{false};
template <typename F>
class CsvParser {
using this_type = CsvParser<F>;
public:
// return true if field should cause row to be ignored
using filter_function_type = std::function<
filter_result(size_t field_num, const char* buf, size_t len)>;
using error_callback_type = std::function<
filter_result(size_t line_number, size_t field_number,
const std::string& error_message, std::exception_ptr ex)>;
CsvParser(const F& sink) : sink{sink} { csv_init(&parser, 0); }
~CsvParser() { csv_free(&parser); }
//
void set_delim_char(unsigned char delim) { parser.delim_char = delim; }
void set_quote_char(unsigned char quote) { parser.quote_char = quote; }
void set_skip_header() { skip_row = true; }
void set_error_func(const error_callback_type func) { error_func = func; }
void set_comment_mark(const std::string& prefix) {
auto is_comment = [prefix](size_t field_num, const char* buf, size_t len) {
return field_num == 0 && //
len >= prefix.length() && //
std::equal(prefix.begin(), prefix.end(), buf);
};
return add_row_filter(is_comment);
}
/* Limitation: Fields are coerced to their types as they are
* encountered, so these filters can't prevent conversion by
* looking at data later in the same row. */
void add_row_filter(const filter_function_type filter) {
auto orig = filter_func;
filter_func = [orig, filter](size_t field_num, const char* buf,
size_t len) {
return orig(field_num, buf, len) || filter(field_num, buf, len);
};
}
//
bool ParseFile(const std::string& filename) {
detail::MappedFile data(filename);
if (!data) {
return status = data.status;
}
return Parse(data.begin(), data.end()) && Finish();
}
template <typename T>
bool Parse(const T& str) {
return Parse(str.data(), str.data() + str.length());
}
template <typename It>
bool Parse(const It& begin, const It& end) {
csv_parse(&parser, begin, end - begin, on_field, on_record, this);
return update_status();
}
template <typename IoStream>
bool ParseStream(IoStream& input) {
char buf[4096];
do {
input.read(buf, sizeof(buf));
csv_parse(&parser, buf, input.gcount(), on_field, on_record, this);
} while (input && update_status());
return Finish();
}
bool Finish() {
csv_fini(&parser, on_field, on_record, this);
return update_status();
}
const std::string& ErrorString() { return status.message; }
operator bool() { return status; }
private:
static void on_field(void* data, size_t len, void* this_ptr) {
this_type* t = reinterpret_cast<this_type*>(this_ptr);
t->accept_field((char*)data, len);
}
static void on_record(int, void* this_ptr) {
this_type* t = reinterpret_cast<this_type*>(this_ptr);
t->accept_row();
};
private:
detail::meta::fields<F> fields;
csv_parser parser;
const F& sink;
detail::Result status;
filter_function_type filter_func = [](size_t, const char*,
size_t) { return ROW_OK; };
error_callback_type error_func = [](size_t row, size_t column,
const std::string& err,
const std::exception_ptr) {
std::cerr << "[csv.hpp] Exception at row " << row << ", column " << column
<< ": " << err << "\n";
return ROW_DROP;
};
bool skip_row{false};
size_t current_line = 0;
size_t current_field = 0;
private:
void accept_field(const char* buf, size_t len) {
skip_row = skip_row || filter_func(current_field, buf, len);
if (!skip_row) {
try {
fields.accept_field(current_field, buf, len);
}
catch (std::exception& e) {
skip_row = error_func(current_line + 1, current_field + 1, e.what(),
std::current_exception());
}
}
++current_field;
}
void accept_row() {
if (!skip_row) {
fields.accept_row(sink);
} else {
skip_row = false;
}
current_field = 0;
++current_line;
}
const detail::Result& update_status() {
if (status.number == 0 && parser.status != 0) {
status.number = parser.status;
status.message = csv_error(&parser);
}
return status;
}
};
template <typename F>
CsvParser<F> make_parser(F&& f) {
return CsvParser<F>(f);
}
// used to ignore input fields
struct ignore {};
} // namespace csv
namespace boost {
template <>
csv::ignore lexical_cast(const char*, size_t) {
static csv::ignore instance;
return instance;
}
}
<commit_msg>Add missing include vector<commit_after>#pragma once
#include <csv.h>
#include <vector>
#include <iostream>
#include <boost/lexical_cast.hpp>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <typeinfo>
namespace csv {
namespace detail {
struct Result {
int number{0};
std::string message{"success"};
operator bool() const { return number == 0; }
};
class MappedFile {
private:
int fd_;
size_t size_;
char* data_;
public:
MappedFile(const std::string& filename) : fd_(0), size_(0), data_(NULL) {
fd_ = ::open(filename.c_str(), O_RDONLY);
if (fd_ < 0) {
set_error();
return;
}
struct stat statbuf;
if (::fstat(fd_, &statbuf) < 0) {
set_error();
return;
}
size_ = statbuf.st_size;
data_ = (char*)::mmap(NULL, size_, PROT_READ, MAP_PRIVATE, fd_, 0);
if (data_ == NULL) {
set_error();
return;
}
}
~MappedFile() {
::munmap(data_, size_);
::close(fd_);
}
const char* begin() const { return data_; }
const char* end() const { return data_ + size_; }
operator bool() { return status; }
detail::Result status;
private:
void set_error() {
status.number = errno;
status.message = strerror(errno);
}
};
// generates sequence numbers used in template expansion
namespace sequence {
template <int... Is>
struct index {};
template <int N, int... Is>
struct generate : generate<N - 1, N - 1, Is...> {};
template <int... Is>
struct generate<0, Is...> : index<Is...> {};
} // namespace sequence
namespace meta {
template <class F>
class fields;
// function pointer
template <class R, class... Args>
class fields<R (*)(Args...)> : public fields<R(Args...)> {};
// member function pointer
template <class C, class R, class... Args>
class fields<R (C::*)(Args...)> : public fields<R(Args...)> {};
// const member function pointer
template <class C, class R, class... Args>
class fields<R (C::*)(Args...) const> : public fields<R(Args...)> {};
// member object pointer
template <class C, class R>
class fields<R(C::*)> : public fields<R(C&)> {};
// functor
template <class F>
class fields : public fields<decltype(&F::operator())> {};
// reference
template <class F>
class fields<F&> : public fields<F> {};
// perfect reference
template <class F>
class fields<F&&> : public fields<F> {};
// impl
template <class R, class... Args>
class fields<R(Args...)> {
using mutator_t = std::function<void(const char* buf, size_t len)>;
public:
fields() {
setupFieldHandlers(
typename detail::sequence::generate<sizeof...(Args)>::index());
}
void accept_field(size_t field_pos, const char* buf, size_t len) {
if (field_pos < mutators.size()) {
mutators[field_pos](buf, len);
}
}
template <typename F>
void accept_row(F& sink) {
call_func(sink,
typename detail::sequence::generate<sizeof...(Args)>::index());
}
template <typename F, int... S>
void call_func(F& sink, detail::sequence::index<S...>) {
sink(std::get<S>(values)...);
}
private:
std::tuple<typename std::decay<Args>::type...> values;
std::vector<mutator_t> mutators;
private:
template <int... S>
void setupFieldHandlers(detail::sequence::index<S...>) {
setupFieldHandlers(std::get<S>(values)...);
}
template <typename F, typename... Fa>
void setupFieldHandlers(F& arg, Fa&... args) {
size_t field_num = mutators.size();
mutators.push_back([field_num, &arg](const char* buf, size_t len) {
if (len > 0) {
arg = boost::lexical_cast<F>(buf, len);
} else {
arg = F();
}
});
setupFieldHandlers(args...);
}
void setupFieldHandlers() {
// this is the terminal function for recursive template expansion
}
};
} // namespace meta
} // detail
/* A C++ wrapper around libcsv, see `make_parser` below */
struct filter_result {
bool drop;
constexpr filter_result(bool b) : drop(b) {}
operator bool() const { return drop; }
};
static constexpr filter_result ROW_DROP{true};
static constexpr filter_result ROW_OK{false};
template <typename F>
class CsvParser {
using this_type = CsvParser<F>;
public:
// return true if field should cause row to be ignored
using filter_function_type = std::function<
filter_result(size_t field_num, const char* buf, size_t len)>;
using error_callback_type = std::function<
filter_result(size_t line_number, size_t field_number,
const std::string& error_message, std::exception_ptr ex)>;
CsvParser(const F& sink) : sink{sink} { csv_init(&parser, 0); }
~CsvParser() { csv_free(&parser); }
//
void set_delim_char(unsigned char delim) { parser.delim_char = delim; }
void set_quote_char(unsigned char quote) { parser.quote_char = quote; }
void set_skip_header() { skip_row = true; }
void set_error_func(const error_callback_type func) { error_func = func; }
void set_comment_mark(const std::string& prefix) {
auto is_comment = [prefix](size_t field_num, const char* buf, size_t len) {
return field_num == 0 && //
len >= prefix.length() && //
std::equal(prefix.begin(), prefix.end(), buf);
};
return add_row_filter(is_comment);
}
/* Limitation: Fields are coerced to their types as they are
* encountered, so these filters can't prevent conversion by
* looking at data later in the same row. */
void add_row_filter(const filter_function_type filter) {
auto orig = filter_func;
filter_func = [orig, filter](size_t field_num, const char* buf,
size_t len) {
return orig(field_num, buf, len) || filter(field_num, buf, len);
};
}
//
bool ParseFile(const std::string& filename) {
detail::MappedFile data(filename);
if (!data) {
return status = data.status;
}
return Parse(data.begin(), data.end()) && Finish();
}
template <typename T>
bool Parse(const T& str) {
return Parse(str.data(), str.data() + str.length());
}
template <typename It>
bool Parse(const It& begin, const It& end) {
csv_parse(&parser, begin, end - begin, on_field, on_record, this);
return update_status();
}
template <typename IoStream>
bool ParseStream(IoStream& input) {
char buf[4096];
do {
input.read(buf, sizeof(buf));
csv_parse(&parser, buf, input.gcount(), on_field, on_record, this);
} while (input && update_status());
return Finish();
}
bool Finish() {
csv_fini(&parser, on_field, on_record, this);
return update_status();
}
const std::string& ErrorString() { return status.message; }
operator bool() { return status; }
private:
static void on_field(void* data, size_t len, void* this_ptr) {
this_type* t = reinterpret_cast<this_type*>(this_ptr);
t->accept_field((char*)data, len);
}
static void on_record(int, void* this_ptr) {
this_type* t = reinterpret_cast<this_type*>(this_ptr);
t->accept_row();
};
private:
detail::meta::fields<F> fields;
csv_parser parser;
const F& sink;
detail::Result status;
filter_function_type filter_func = [](size_t, const char*,
size_t) { return ROW_OK; };
error_callback_type error_func = [](size_t row, size_t column,
const std::string& err,
const std::exception_ptr) {
std::cerr << "[csv.hpp] Exception at row " << row << ", column " << column
<< ": " << err << "\n";
return ROW_DROP;
};
bool skip_row{false};
size_t current_line = 0;
size_t current_field = 0;
private:
void accept_field(const char* buf, size_t len) {
skip_row = skip_row || filter_func(current_field, buf, len);
if (!skip_row) {
try {
fields.accept_field(current_field, buf, len);
}
catch (std::exception& e) {
skip_row = error_func(current_line + 1, current_field + 1, e.what(),
std::current_exception());
}
}
++current_field;
}
void accept_row() {
if (!skip_row) {
fields.accept_row(sink);
} else {
skip_row = false;
}
current_field = 0;
++current_line;
}
const detail::Result& update_status() {
if (status.number == 0 && parser.status != 0) {
status.number = parser.status;
status.message = csv_error(&parser);
}
return status;
}
};
template <typename F>
CsvParser<F> make_parser(F&& f) {
return CsvParser<F>(f);
}
// used to ignore input fields
struct ignore {};
} // namespace csv
namespace boost {
template <>
csv::ignore lexical_cast(const char*, size_t) {
static csv::ignore instance;
return instance;
}
}
<|endoftext|>
|
<commit_before>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "PackedColumn.h"
template<>
InputParameters validParams<PackedColumn>()
{
InputParameters params = validParams<Material>();
// Add a parameter to get the radius of the balls in the column
// (used later to interpolate permeability).
params.addParam<Real>("ball_radius",
"The radius of the steel balls that are packed in the column. "
"Used to interpolate _permeability.");
return params;
}
PackedColumn::PackedColumn(const InputParameters & parameters) :
Material(parameters),
// Get the one parameter from the input file
_ball_radius(getParam<Real>("ball_radius")),
// Declare two material properties. This returns references that
// we hold onto as member variables.
_permeability(declareProperty<Real>("permeability")),
_porosity(declareProperty<Real>("porosity")),
_viscosity(declareProperty<Real>("viscosity")),
_thermal_conductivity(declareProperty<Real>("thermal_conductivity")),
_heat_capacity(declareProperty<Real>("heat_capacity")),
_density(declareProperty<Real>("density"))
{
// The media is modeled by spheres with different radii.
std::vector<Real> ball_sizes(2);
ball_sizes[0] = 1;
ball_sizes[1] = 3;
// From the paper: Table 1
std::vector<Real> permeability(2);
permeability[0] = 0.8451e-9;
permeability[1] = 8.968e-9;
// Set the x,y data on the LinearInterpolation object.
_permeability_interpolation.setData(ball_sizes, permeability);
}
void
PackedColumn::computeQpProperties()
{
// Viscosity of Water in Pa*s at 30 degrees C (Wikipedia)
_viscosity[_qp] = 7.98e-4;
// Sample the LinearInterpolation object to get the permeability for the ball size
_permeability[_qp] = _permeability_interpolation.sample(_ball_radius);
// Compute the heat conduction material properties as a linear combination of
// the material properties for water and steel.
// We're assuming close packing, so the porosity will be
// approximately 1 - 0.74048 = 0.25952. See:
// http://en.wikipedia.org/wiki/Close-packing_of_equal_spheres
_porosity[_qp] = 0.25952;
// We will compute "bulk" thermal conductivity, specific heat, and
// density as linear combinations of the water and steel (all values
// are from Wikipedia).
Real water_k = 0.6; // (W/m*K)
Real water_cp = 4181.3; // (J/kg*K)
Real water_rho = 995.6502; // (kg/m^3 @ 303K)
Real steel_k = 18; // (W/m*K)
Real steel_cp = 466; // (J/kg*K)
Real steel_rho = 8000; // (kg/m^3)
// Now actually set the value at the quadrature point
_thermal_conductivity[_qp] = _porosity[_qp]*water_k + (1.0-_porosity[_qp])*steel_k;
_density[_qp] = _porosity[_qp]*water_rho + (1.0-_porosity[_qp])*steel_rho;
_heat_capacity[_qp] = _porosity[_qp]*water_cp*water_rho + (1.0-_porosity[_qp])*steel_cp*steel_rho;
}
<commit_msg>Tutorial: Use C++11 vector initialization in step06.<commit_after>/****************************************************************/
/* DO NOT MODIFY THIS HEADER */
/* MOOSE - Multiphysics Object Oriented Simulation Environment */
/* */
/* (c) 2010 Battelle Energy Alliance, LLC */
/* ALL RIGHTS RESERVED */
/* */
/* Prepared by Battelle Energy Alliance, LLC */
/* Under Contract No. DE-AC07-05ID14517 */
/* With the U. S. Department of Energy */
/* */
/* See COPYRIGHT for full restrictions */
/****************************************************************/
#include "PackedColumn.h"
template<>
InputParameters validParams<PackedColumn>()
{
InputParameters params = validParams<Material>();
// Add a parameter to get the radius of the balls in the column
// (used later to interpolate permeability).
params.addParam<Real>("ball_radius",
"The radius of the steel balls that are packed in the column. "
"Used to interpolate _permeability.");
return params;
}
PackedColumn::PackedColumn(const InputParameters & parameters) :
Material(parameters),
// Get the one parameter from the input file
_ball_radius(getParam<Real>("ball_radius")),
// Declare two material properties. This returns references that
// we hold onto as member variables.
_permeability(declareProperty<Real>("permeability")),
_porosity(declareProperty<Real>("porosity")),
_viscosity(declareProperty<Real>("viscosity")),
_thermal_conductivity(declareProperty<Real>("thermal_conductivity")),
_heat_capacity(declareProperty<Real>("heat_capacity")),
_density(declareProperty<Real>("density"))
{
std::vector<Real> ball_sizes = {1, 3};
// From the paper: Table 1
std::vector<Real> permeability = {0.8451e-9, 8.968e-9};
// Set the x,y data on the LinearInterpolation object.
_permeability_interpolation.setData(ball_sizes, permeability);
}
void
PackedColumn::computeQpProperties()
{
// Viscosity of Water in Pa*s at 30 degrees C (Wikipedia)
_viscosity[_qp] = 7.98e-4;
// Sample the LinearInterpolation object to get the permeability for the ball size
_permeability[_qp] = _permeability_interpolation.sample(_ball_radius);
// Compute the heat conduction material properties as a linear combination of
// the material properties for water and steel.
// We're assuming close packing, so the porosity will be
// approximately 1 - 0.74048 = 0.25952. See:
// http://en.wikipedia.org/wiki/Close-packing_of_equal_spheres
_porosity[_qp] = 0.25952;
// We will compute "bulk" thermal conductivity, specific heat, and
// density as linear combinations of the water and steel (all values
// are from Wikipedia).
Real water_k = 0.6; // (W/m*K)
Real water_cp = 4181.3; // (J/kg*K)
Real water_rho = 995.6502; // (kg/m^3 @ 303K)
Real steel_k = 18; // (W/m*K)
Real steel_cp = 466; // (J/kg*K)
Real steel_rho = 8000; // (kg/m^3)
// Now actually set the value at the quadrature point
_thermal_conductivity[_qp] = _porosity[_qp]*water_k + (1.0-_porosity[_qp])*steel_k;
_density[_qp] = _porosity[_qp]*water_rho + (1.0-_porosity[_qp])*steel_rho;
_heat_capacity[_qp] = _porosity[_qp]*water_cp*water_rho + (1.0-_porosity[_qp])*steel_cp*steel_rho;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <sstream>
#include <map>
#include <unordered_map>
#include <vector>
#include <string>
#include "dict.h"
#include "dictglobal.h"
typedef std::unordered_map<std::string, std::string> Dict;
typedef unsigned long IdentificatorType;
// consider map<unsigned long, unordered_map>
// somehow initialize dictglobal dictionary
std::map<IdentificatorType, Dict> dictionaries;
IdentificatorType dictCounter = dict_global();
static std::string parse_char_param(std::string param) {
if (param != "")
return "\"" + param + "\"";
else
return "NULL";
}
static void function_called_msg(std::string funcName,
std::string params) {
std::cerr << funcName << "(" << params << ")" << std::endl;
}
static void dict_new_msg(IdentificatorType id) {
std::cerr << "dict_new: dict " << id
<< " has been created" << std::endl;
}
static void dict_delete_success_msg(IdentificatorType id) {
std::cerr << "dict_delete: dict " << id
<< " has been deleted" << std::endl;
}
static void dict_delete_error_msg() {
std::cerr << "dict_delete: an attempt to remove the Global Dictionary"
<< std::endl;
}
static void dict_description_msg(IdentificatorType id) {
if (id == dict_global())
std::cerr << "dict " << id;
else
std::cerr << "the Global Dictionary";
}
static void dict_size_msg(IdentificatorType id, size_t size) {
std::cerr << "dict_size: ";
dict_description_msg(id);
std::cerr << " contains " << size << " element(s)" << std::endl;
}
static void dict_insert_success_msg(IdentificatorType id,
std::string key,
std::string value) {
std::cerr << "dict_insert: ";
dict_description_msg(id);
std::cerr << ", the pair (" << key << ", " << value << ")"
<< "has been inserted" << std::endl;
}
static void dict_insert_error_msg(IdentificatorType id, std::string param) {
std::cerr << "dict_insert: dict " << id
<< " an attempt to insert NULL " << param << std::endl;
}
static void dict_not_found_msg(std::string funcName, IdentificatorType id) {
std::cerr << funcName << ": dict " << id << " does not exist" << "\n";
}
static void key_not_found_msg(std::string funcName,
IdentificatorType id,
const char* key) {
std::cerr << funcName << ": dict " << id
<< " does not contain the key " << key << "\"\n";
}
static void key_removed_msg(std::string funcName,
IdentificatorType id,
const char* key) {
std::cerr << funcName << ": dict " << id
<< ", the key \"" << key << "\" has been removed\n";
}
static void value_found_msg(std::string funcName,
IdentificatorType id,
const char* key,
std::string value) {
std::cerr << funcName << ": dict " << id
<< ", the key \"" << key
<< "\" has the value \"" << value << "\"\n";
}
static void dict_copied_msg(std::string funcName,
IdentificatorType src_id,
IdentificatorType dst_id) {
std::cerr << funcName << ": dict " << src_id
<< " has been copied into dict " << dst_id << "\n";
}
static void search_global_dict_msg(std::string funcName) {
std::cerr << funcName << ": looking up the Global Dictionary\n";
}
static void dict_cleared_msg(std::string funcName, IdentificatorType id) {
std::cerr << funcName << ": dict " << id << " has been cleared\n";
}
IdentificatorType dict_new() {
function_called_msg("dict_new", "");
dictionaries.insert(std::make_pair(++dictCounter, Dict()));
dict_new_msg(dictCounter);
return dictCounter;
}
void dict_delete(unsigned long id) {
std::stringstream ss;
ss << id;
function_called_msg("dict_delete", ss.str());
auto dictionaryIt = dictionaries.find(id);
if (dictionaryIt != dictionaries.end()) {
if (id == dict_global()) {
dict_delete_error_msg();
}
else {
dictionaries.erase(id);
dict_delete_success_msg(id);
}
}
}
size_t dict_size(unsigned long id) {
std::stringstream ss;
ss << id;
function_called_msg("dict_size", ss.str());
auto dictionaryIt = dictionaries.find(id);
if (dictionaryIt != dictionaries.end()) {
size_t dictSize = dictionaryIt->second.size();
dict_size_msg(id, dictSize);
return dictSize;
}
else {
dict_not_found_msg("dict_size", id);
return 0;
}
}
void dict_insert(unsigned long id, const char* key, const char* value) {
std::stringstream ss;
std::string keyStr, valueStr;
keyStr = parse_char_param(key);
valueStr = parse_char_param(value);
ss << id << ", " << keyStr << ", " << valueStr;
function_called_msg("dict_insert", ss.str());
auto dictionaryIt = dictionaries.find(id);
if (dictionaryIt != dictionaries.end()) {
if (key == NULL) {
dict_insert_error_msg(id, "key");
}
else if (value == NULL) {
dict_insert_error_msg(id, "value");
}
else {
dictionaryIt->second.insert(std::make_pair(key, value));
dict_insert_success_msg(id, keyStr, valueStr);
}
}
else
dict_not_found_msg("dict_insert", id);
}
void dict_remove(IdentificatorType id, const char* key) {
auto dictionaryIt = dictionaries.find(id);
if (dictionaryIt != dictionaries.end()) {
if (dictionaryIt->second.erase(key) > 0) {
key_removed_msg("dict_remove", id, key);
}
else {
key_not_found_msg("dict_remove", id, key);
}
}
else {
dict_not_found_msg("dict_remove", id);
}
}
const char* dict_find(IdentificatorType id, const char* key) {
auto dictionaryIt = dictionaries.find(id);
if (dictionaryIt != dictionaries.end()) {
auto stringIt = dictionaryIt->second.find(key);
if (stringIt != dictionaryIt->second.end()) {
value_found_msg("dict_find", id, key, stringIt->second);
return stringIt->second.c_str();
}
else {
key_not_found_msg("dict_find", id, key);
}
}
else {
dict_not_found_msg("dict_find", id);
}
search_global_dict_msg("dict_find");
auto stringIt = dictionaries.at(dict_global()).find(key);
if (stringIt != dictionaries.at(dict_global()).end()) {
value_found_msg("dict_find", dict_global(), key, stringIt->second);
return stringIt->second.c_str();
}
else {
key_not_found_msg("dict_find", dict_global(), key);
}
return NULL;
}
void dict_clear(IdentificatorType id) {
auto dictionaryIt = dictionaries.find(id);
if (dictionaryIt != dictionaries.end()) {
dict_cleared_msg("dict_clear", id);
dictionaryIt->second.clear();
}
else {
dict_not_found_msg("dict_clear", id);
}
}
void dict_copy(IdentificatorType src_id, IdentificatorType dst_id) {
auto srcDictionaryIt = dictionaries.find(src_id);
auto dstDictionaryIt = dictionaries.find(dst_id);
if (srcDictionaryIt != dictionaries.end() &&
dstDictionaryIt != dictionaries.end()) {
// do not copy if destination dictionary is dictglobal and amount of keys exceeds size
// copy contents
}
}<commit_msg>Fixed dict_insert<commit_after>#include <iostream>
#include <sstream>
#include <map>
#include <unordered_map>
#include <vector>
#include <string>
#include "dict.h"
#include "dictglobal.h"
typedef std::unordered_map<std::string, std::string> Dict;
typedef unsigned long IdentificatorType;
// consider map<unsigned long, unordered_map>
// somehow initialize dictglobal dictionary
std::map<IdentificatorType, Dict> dictionaries;
IdentificatorType dictCounter = dict_global();
static std::string parse_char_param(std::string param) {
if (param != "")
return "\"" + param + "\"";
else
return "NULL";
}
static void function_called_msg(std::string funcName,
std::string params) {
std::cerr << funcName << "(" << params << ")" << std::endl;
}
static void dict_new_msg(IdentificatorType id) {
std::cerr << "dict_new: dict " << id
<< " has been created" << std::endl;
}
static void dict_delete_success_msg(IdentificatorType id) {
std::cerr << "dict_delete: dict " << id
<< " has been deleted" << std::endl;
}
static void dict_delete_error_msg() {
std::cerr << "dict_delete: an attempt to remove the Global Dictionary"
<< std::endl;
}
static void dict_description_msg(IdentificatorType id) {
if (id == dict_global())
std::cerr << "dict " << id;
else
std::cerr << "the Global Dictionary";
}
static void dict_size_msg(IdentificatorType id, size_t size) {
std::cerr << "dict_size: ";
dict_description_msg(id);
std::cerr << " contains " << size << " element(s)" << std::endl;
}
static void dict_insert_success_msg(IdentificatorType id,
std::string key,
std::string value) {
std::cerr << "dict_insert: ";
dict_description_msg(id);
std::cerr << ", the pair (" << key << ", " << value << ")"
<< "has been inserted" << std::endl;
}
static void dict_insert_error_msg(IdentificatorType id, std::string param) {
std::cerr << "dict_insert: dict " << id
<< " an attempt to insert NULL " << param << std::endl;
}
static void dict_not_found_msg(std::string funcName, IdentificatorType id) {
std::cerr << funcName << ": dict " << id << " does not exist" << "\n";
}
static void key_not_found_msg(std::string funcName,
IdentificatorType id,
const char* key) {
std::cerr << funcName << ": dict " << id
<< " does not contain the key " << key << "\"\n";
}
static void key_removed_msg(std::string funcName,
IdentificatorType id,
const char* key) {
std::cerr << funcName << ": dict " << id
<< ", the key \"" << key << "\" has been removed\n";
}
static void value_found_msg(std::string funcName,
IdentificatorType id,
const char* key,
std::string value) {
std::cerr << funcName << ": dict " << id
<< ", the key \"" << key
<< "\" has the value \"" << value << "\"\n";
}
static void dict_copied_msg(std::string funcName,
IdentificatorType src_id,
IdentificatorType dst_id) {
std::cerr << funcName << ": dict " << src_id
<< " has been copied into dict " << dst_id << "\n";
}
static void search_global_dict_msg(std::string funcName) {
std::cerr << funcName << ": looking up the Global Dictionary\n";
}
static void dict_cleared_msg(std::string funcName, IdentificatorType id) {
std::cerr << funcName << ": dict " << id << " has been cleared\n";
}
IdentificatorType dict_new() {
function_called_msg("dict_new", "");
dictionaries.insert(std::make_pair(++dictCounter, Dict()));
dict_new_msg(dictCounter);
return dictCounter;
}
void dict_delete(unsigned long id) {
std::stringstream ss;
ss << id;
function_called_msg("dict_delete", ss.str());
auto dictionaryIt = dictionaries.find(id);
if (dictionaryIt != dictionaries.end()) {
if (id == dict_global()) {
dict_delete_error_msg();
}
else {
dictionaries.erase(id);
dict_delete_success_msg(id);
}
}
}
size_t dict_size(unsigned long id) {
std::stringstream ss;
ss << id;
function_called_msg("dict_size", ss.str());
auto dictionaryIt = dictionaries.find(id);
if (dictionaryIt != dictionaries.end()) {
size_t dictSize = dictionaryIt->second.size();
dict_size_msg(id, dictSize);
return dictSize;
}
else {
dict_not_found_msg("dict_size", id);
return 0;
}
}
void dict_insert(unsigned long id, const char* key, const char* value) {
std::stringstream ss;
std::string keyDescription, valueDescription;
keyDescription = parse_char_param(key);
valueDescription = parse_char_param(value);
ss << id << ", " << keyDescription << ", " << valueDescription;
function_called_msg("dict_insert", ss.str());
auto dictionaryIt = dictionaries.find(id);
if (dictionaryIt != dictionaries.end()) {
if (key == NULL) {
dict_insert_error_msg(id, "key");
}
else if (value == NULL) {
dict_insert_error_msg(id, "value");
}
else {
std::string keyStr(key);
std::string valueStr(value);
dictionaryIt->second.insert(std::make_pair(keyStr, valueStr));
dict_insert_success_msg(id, keyDescription, valueDescription);
}
}
else
dict_not_found_msg("dict_insert", id);
}
void dict_remove(IdentificatorType id, const char* key) {
auto dictionaryIt = dictionaries.find(id);
if (dictionaryIt != dictionaries.end()) {
if (dictionaryIt->second.erase(key) > 0) {
key_removed_msg("dict_remove", id, key);
}
else {
key_not_found_msg("dict_remove", id, key);
}
}
else {
dict_not_found_msg("dict_remove", id);
}
}
const char* dict_find(IdentificatorType id, const char* key) {
auto dictionaryIt = dictionaries.find(id);
if (dictionaryIt != dictionaries.end()) {
auto stringIt = dictionaryIt->second.find(key);
if (stringIt != dictionaryIt->second.end()) {
value_found_msg("dict_find", id, key, stringIt->second);
return stringIt->second.c_str();
}
else {
key_not_found_msg("dict_find", id, key);
}
}
else {
dict_not_found_msg("dict_find", id);
}
search_global_dict_msg("dict_find");
auto stringIt = dictionaries.at(dict_global()).find(key);
if (stringIt != dictionaries.at(dict_global()).end()) {
value_found_msg("dict_find", dict_global(), key, stringIt->second);
return stringIt->second.c_str();
}
else {
key_not_found_msg("dict_find", dict_global(), key);
}
return NULL;
}
void dict_clear(IdentificatorType id) {
auto dictionaryIt = dictionaries.find(id);
if (dictionaryIt != dictionaries.end()) {
dict_cleared_msg("dict_clear", id);
dictionaryIt->second.clear();
}
else {
dict_not_found_msg("dict_clear", id);
}
}
void dict_copy(IdentificatorType src_id, IdentificatorType dst_id) {
auto srcDictionaryIt = dictionaries.find(src_id);
auto dstDictionaryIt = dictionaries.find(dst_id);
if (srcDictionaryIt != dictionaries.end() &&
dstDictionaryIt != dictionaries.end()) {
// do not copy if destination dictionary is dictglobal and amount of keys exceeds size
// copy contents
}
}<|endoftext|>
|
<commit_before>/**
* \file
* \brief Reset_Handler() for ARMv6-M and ARMv7-M
*
* \author Copyright (C) 2014-2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* 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/.
*/
#include "distortos/chip/CMSIS-proxy.h"
extern "C"
{
/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/
// weak definition of lowLevelInitialization0() called at the very beginning of Reset_Handler()
__attribute__ ((weak)) void lowLevelInitialization0()
{
}
/**
* \brief Reset_Handler() for ARMv6-M and ARMv7-M
*/
__attribute__ ((naked)) void Reset_Handler()
{
asm volatile
(
" ldr r0, =lowLevelInitialization0 \n" // call lowLevelInitialization0() (PSP not set,
" blx r0 \n" // CONTROL not modified, memory not initialized)
" \n"
" ldr r0, =__process_stack_end \n" // initialize PSP
" msr psp, r0 \n"
" \n"
" movs r0, %[controlSpselMsk] \n" // thread mode uses PSP and is privileged
" msr control, r0 \n"
" isb \n"
" \n"
" ldr r4, =__data_array_start \n" // initialize data_array (including .data)
" ldr r5, =__data_array_end \n"
" \n"
#ifdef __ARM_ARCH_6M__
"1: cmp r4, r5 \n" // outer loop - addresses from data_array
" bhs 4f \n"
" ldmia r4!, {r1-r3} \n" // r1 - start of source, r2 - start of destination,
" \n" // r3 - end of destination
" b 3f \n"
"2: ldmia r1!, {r0} \n" // inner loop - section initialization
" stmia r2!, {r0} \n"
"3: cmp r2, r3 \n"
" bne 2b \n"
" \n"
" b 1b \n" // go back to start
" \n"
"4: \n"
" \n"
#else // !def __ARM_ARCH_6M__
"1: cmp r4, r5 \n" // outer loop - addresses from data_array
" ite lo \n"
" ldmialo r4!, {r1-r3} \n" // r1 - start of source, r2 - start of destination,
" bhs 3f \n" // r3 - end of destination
" \n"
"2: cmp r2, r3 \n" // inner loop - section initialization
" ittt lo \n"
" ldrlo r0, [r1], #4 \n"
" strlo r0, [r2], #4 \n"
" blo 2b \n"
" \n"
" b 1b \n" // go back to start
" \n"
"3: \n"
" \n"
#endif // !def __ARM_ARCH_6M__
" ldr r3, =__bss_array_start \n" // initialize bss_array (including .bss)
" ldr r4, =__bss_array_end \n"
" \n"
#ifdef __ARM_ARCH_6M__
"1: cmp r3, r4 \n" // outer loop - addresses from bss_array
" bhs 4f \n"
" ldmia r3!, {r0-r2} \n" // r0 - value, r1 - start of destination, r2 - end
" \n" // of destination
" b 3f \n"
"2: stmia r1!, {r0} \n" // inner loop - section initialization
"3: cmp r1, r2 \n"
" bne 2b \n"
" \n"
" b 1b \n" // go back to start
" \n"
"4: \n"
" \n"
#else // !def __ARM_ARCH_6M__
"1: cmp r3, r4 \n" // outer loop - addresses from bss_array
" ite lo \n"
" ldmialo r3!, {r0-r2} \n" // r0 - value, r1 - start of destination, r2 - end
" bhs 3f \n" // of destination
" \n"
"2: cmp r1, r2 \n" // inner loop - section initialization
" itt lo \n"
" strlo r0, [r1], #4 \n"
" blo 2b \n"
" \n"
" b 1b \n" // go back to start
" \n"
"3: \n"
" \n"
#endif // !def __ARM_ARCH_6M__
" ldr r0, =__libc_init_array \n" // call constructors for global and static objects
" blx r0 \n"
" \n"
" ldr r0, =main \n" // call main()
" blx r0 \n"
" \n"
" ldr r0, =__libc_fini_array \n" // call destructors for global and static objects
" blx r0 \n"
" \n"
" b . \n" // on return - loop till the end of the world
:: [controlSpselMsk] "i" (CONTROL_SPSEL_Msk)
);
__builtin_unreachable();
}
} // extern "C"
<commit_msg>Force dumping of literal pool in Reset_Handler()<commit_after>/**
* \file
* \brief Reset_Handler() for ARMv6-M and ARMv7-M
*
* \author Copyright (C) 2014-2017 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* 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/.
*/
#include "distortos/chip/CMSIS-proxy.h"
extern "C"
{
/*---------------------------------------------------------------------------------------------------------------------+
| global functions
+---------------------------------------------------------------------------------------------------------------------*/
// weak definition of lowLevelInitialization0() called at the very beginning of Reset_Handler()
__attribute__ ((weak)) void lowLevelInitialization0()
{
}
/**
* \brief Reset_Handler() for ARMv6-M and ARMv7-M
*/
__attribute__ ((naked)) void Reset_Handler()
{
asm volatile
(
" ldr r0, =lowLevelInitialization0 \n" // call lowLevelInitialization0() (PSP not set,
" blx r0 \n" // CONTROL not modified, memory not initialized)
" \n"
" ldr r0, =__process_stack_end \n" // initialize PSP
" msr psp, r0 \n"
" \n"
" movs r0, %[controlSpselMsk] \n" // thread mode uses PSP and is privileged
" msr control, r0 \n"
" isb \n"
" \n"
" ldr r4, =__data_array_start \n" // initialize data_array (including .data)
" ldr r5, =__data_array_end \n"
" \n"
#ifdef __ARM_ARCH_6M__
"1: cmp r4, r5 \n" // outer loop - addresses from data_array
" bhs 4f \n"
" ldmia r4!, {r1-r3} \n" // r1 - start of source, r2 - start of destination,
" \n" // r3 - end of destination
" b 3f \n"
"2: ldmia r1!, {r0} \n" // inner loop - section initialization
" stmia r2!, {r0} \n"
"3: cmp r2, r3 \n"
" bne 2b \n"
" \n"
" b 1b \n" // go back to start
" \n"
"4: \n"
" \n"
#else // !def __ARM_ARCH_6M__
"1: cmp r4, r5 \n" // outer loop - addresses from data_array
" ite lo \n"
" ldmialo r4!, {r1-r3} \n" // r1 - start of source, r2 - start of destination,
" bhs 3f \n" // r3 - end of destination
" \n"
"2: cmp r2, r3 \n" // inner loop - section initialization
" ittt lo \n"
" ldrlo r0, [r1], #4 \n"
" strlo r0, [r2], #4 \n"
" blo 2b \n"
" \n"
" b 1b \n" // go back to start
" \n"
"3: \n"
" \n"
#endif // !def __ARM_ARCH_6M__
" ldr r3, =__bss_array_start \n" // initialize bss_array (including .bss)
" ldr r4, =__bss_array_end \n"
" \n"
#ifdef __ARM_ARCH_6M__
"1: cmp r3, r4 \n" // outer loop - addresses from bss_array
" bhs 4f \n"
" ldmia r3!, {r0-r2} \n" // r0 - value, r1 - start of destination, r2 - end
" \n" // of destination
" b 3f \n"
"2: stmia r1!, {r0} \n" // inner loop - section initialization
"3: cmp r1, r2 \n"
" bne 2b \n"
" \n"
" b 1b \n" // go back to start
" \n"
"4: \n"
" \n"
#else // !def __ARM_ARCH_6M__
"1: cmp r3, r4 \n" // outer loop - addresses from bss_array
" ite lo \n"
" ldmialo r3!, {r0-r2} \n" // r0 - value, r1 - start of destination, r2 - end
" bhs 3f \n" // of destination
" \n"
"2: cmp r1, r2 \n" // inner loop - section initialization
" itt lo \n"
" strlo r0, [r1], #4 \n"
" blo 2b \n"
" \n"
" b 1b \n" // go back to start
" \n"
"3: \n"
" \n"
#endif // !def __ARM_ARCH_6M__
" ldr r0, =__libc_init_array \n" // call constructors for global and static objects
" blx r0 \n"
" \n"
" ldr r0, =main \n" // call main()
" blx r0 \n"
" \n"
" ldr r0, =__libc_fini_array \n" // call destructors for global and static objects
" blx r0 \n"
" \n"
" b . \n" // on return - loop till the end of the world
" \n"
".ltorg \n" // force dumping of literal pool
:: [controlSpselMsk] "i" (CONTROL_SPSEL_Msk)
);
__builtin_unreachable();
}
} // extern "C"
<|endoftext|>
|
<commit_before>/*
* BBGHHibe.cpp
*
* Created on: Dec 21, 2014
* Author: imiers
*/
#include <assert.h>
#include "BBGHibe.h"
namespace forwardsec{
using namespace std;
void Bbghibe::setup(const unsigned int & l, BbhHIBEPublicKey & pk, G2 & msk) const
{
ZR alpha = group.randomZR();
pk.gG1 = group.randomG1();
pk.gG2 = group.randomG2();
pk.hibeg1 = group.exp(pk.gG2, alpha);
pk.l = l;
const ZR r = group.randomZR();
pk.g2G1 = group.exp(pk.gG1, r);
pk.g2G2 = group.exp(pk.gG2, r);
const ZR r1 = group.randomZR();
pk.g3G1 = group.exp(pk.gG1, r1);
pk.g3G2 = group.exp(pk.gG2, r1);
for (unsigned int i = 0; i < l; i++)
{
ZR h = group.randomZR();
pk.hG1.push_back(group.exp(pk.gG1, h));
pk.hG2.push_back(group.exp(pk.gG2, h));
}
msk = group.exp(pk.g2G2, alpha);
return;
}
void Bbghibe::keygen(const BbhHIBEPublicKey & pk, const G2 & msk, const std::vector<ZR> & id, BbghPrivatekey & sk) const
{
const ZR r = group.randomZR();
const unsigned int k = id.size();
for (unsigned int i = 0; i < k; i++)
{
sk.a0 = group.mul(sk.a0, group.exp(pk.hG2[i], id[i]));
}
sk.a0 = group.exp(group.mul(sk.a0, pk.g3G2), r);
sk.a0 = group.mul(msk, sk.a0);
sk.a1 = group.exp(pk.gG2, r);
sk.b.resize(pk.l);
sk.bG2.resize(pk.l);
for (unsigned int i = k;i < pk.l; i++)
{
sk.b[i] = group.exp(pk.hG1[i], r);
sk.bG2[i] = group.exp(pk.hG2[i], r);
}
return;
}
void Bbghibe::keygen(const BbhHIBEPublicKey & pk,const BbghPrivatekey & sk, const std::vector<ZR> &id,BbghPrivatekey & skout) const{
const unsigned int k = id.size();
ZR t = group.randomZR();
G2 hprod;
for (unsigned int i = 0; i < k ; i++)
{
hprod = group.mul(hprod, group.exp(pk.hG2[i], id[i]));
}
hprod = group.exp(group.mul(hprod, pk.g3G2), t);
hprod = group.mul(hprod,group.exp(sk.bG2[k-1],(id[k-1])));
skout.a0 = group.mul(hprod,sk.a0);
skout.a1 = group.mul(sk.a1,group.exp(pk.gG2,t));
skout.b.resize(pk.l);
skout.bG2.resize(pk.l);
assert(skout.b.size() == sk.b.size());
assert(skout.bG2.size() == sk.bG2.size());
for (unsigned int i = k ; i < pk.l; i++)
{
skout.b[i] = group.mul(sk.b[i],group.exp(pk.hG1[i],t));
skout.bG2[i] = group.mul(sk.bG2[i],group.exp(pk.hG2[i],t));
}
return;
}
BbghCT Bbghibe::encrypt(const BbhHIBEPublicKey & pk, const GT & M, const std::vector<ZR> & id) const{
ZR s = group.randomZR();
BbghCT ct =blind(pk,s,id);
ct.A = group.mul(group.exp(group.pair(pk.g2G1, pk.hibeg1), s), M);
return ct;
}
PartialBbghCT Bbghibe::blind(const BbhHIBEPublicKey & pk, const ZR & s,const std::vector<ZR> & id) const
{
PartialBbghCT ct;
const unsigned int k = id.size();
assert(k<=pk.l);
ct.B = group.exp(pk.gG1, s);
G1 dotProd2;
for (unsigned int i = 0; i < k; i++)
{
dotProd2 = group.mul(dotProd2,group.exp(pk.hG1[i], id[i]));
}
ct.C = group.exp(group.mul(dotProd2, pk.g3G1), s);
return ct;
}
GT Bbghibe::recoverBlind(const BbghPrivatekey & sk, const PartialBbghCT & ct) const{
// This is inverted so that decrypt is ct/result. I.e. it aligns with the ppke scheme.
return group.div(group.pair(ct.B, sk.a0),group.pair(ct.C, sk.a1));
}
GT Bbghibe::decrypt(const BbghPrivatekey & sk, const BbghCT & ct) const
{
return group.div(ct.A, recoverBlind(sk,ct));
}
}
<commit_msg>HIBE KEYS GET SMALLER ON FURTHER DERIVATIONS<commit_after>/*
* BBGHHibe.cpp
*
* Created on: Dec 21, 2014
* Author: imiers
*/
#include <assert.h>
#include "BBGHibe.h"
namespace forwardsec{
using namespace std;
void Bbghibe::setup(const unsigned int & l, BbhHIBEPublicKey & pk, G2 & msk) const
{
ZR alpha = group.randomZR();
pk.gG1 = group.randomG1();
pk.gG2 = group.randomG2();
pk.hibeg1 = group.exp(pk.gG2, alpha);
pk.l = l;
const ZR r = group.randomZR();
pk.g2G1 = group.exp(pk.gG1, r);
pk.g2G2 = group.exp(pk.gG2, r);
const ZR r1 = group.randomZR();
pk.g3G1 = group.exp(pk.gG1, r1);
pk.g3G2 = group.exp(pk.gG2, r1);
for (unsigned int i = 0; i < l; i++)
{
ZR h = group.randomZR();
pk.hG1.push_back(group.exp(pk.gG1, h));
pk.hG2.push_back(group.exp(pk.gG2, h));
}
msk = group.exp(pk.g2G2, alpha);
return;
}
void Bbghibe::keygen(const BbhHIBEPublicKey & pk, const G2 & msk, const std::vector<ZR> & id, BbghPrivatekey & sk) const
{
const ZR r = group.randomZR();
const unsigned int k = id.size();
for (unsigned int i = 0; i < k; i++)
{
sk.a0 = group.mul(sk.a0, group.exp(pk.hG2[i], id[i]));
}
sk.a0 = group.exp(group.mul(sk.a0, pk.g3G2), r);
sk.a0 = group.mul(msk, sk.a0);
sk.a1 = group.exp(pk.gG2, r);
sk.b.resize(pk.l);
sk.bG2.resize(pk.l);
for (unsigned int i = k;i < pk.l; i++)
{
sk.b[i-(k-1)] = group.exp(pk.hG1[i], r);
sk.bG2[i-(k-1)] = group.exp(pk.hG2[i], r);
}
return;
}
void Bbghibe::keygen(const BbhHIBEPublicKey & pk,const BbghPrivatekey & sk, const std::vector<ZR> &id,BbghPrivatekey & skout) const{
const unsigned int k = id.size();
ZR t = group.randomZR();
G2 hprod;
for (unsigned int i = 0; i < k ; i++)
{
hprod = group.mul(hprod, group.exp(pk.hG2[i], id[i]));
}
hprod = group.exp(group.mul(hprod, pk.g3G2), t);
hprod = group.mul(hprod,group.exp(sk.bG2[k-1],(id[k-1])));
skout.a0 = group.mul(hprod,sk.a0);
skout.a1 = group.mul(sk.a1,group.exp(pk.gG2,t));
const unsigned int kk = k-2;
skout.b.resize(pk.l-kk);
skout.bG2.resize(pk.l-kk);
for (unsigned int i = k ; i < pk.l; i++)
{
skout.b[i-kk] = group.mul(sk.b[i-kk],group.exp(pk.hG1[i],t));
skout.bG2[i-kk] = group.mul(sk.bG2[i-kk],group.exp(pk.hG2[i],t));
}
return;
}
BbghCT Bbghibe::encrypt(const BbhHIBEPublicKey & pk, const GT & M, const std::vector<ZR> & id) const{
ZR s = group.randomZR();
BbghCT ct =blind(pk,s,id);
ct.A = group.mul(group.exp(group.pair(pk.g2G1, pk.hibeg1), s), M);
return ct;
}
PartialBbghCT Bbghibe::blind(const BbhHIBEPublicKey & pk, const ZR & s,const std::vector<ZR> & id) const
{
PartialBbghCT ct;
const unsigned int k = id.size();
assert(k<=pk.l);
ct.B = group.exp(pk.gG1, s);
G1 dotProd2;
for (unsigned int i = 0; i < k; i++)
{
dotProd2 = group.mul(dotProd2,group.exp(pk.hG1[i], id[i]));
}
ct.C = group.exp(group.mul(dotProd2, pk.g3G1), s);
return ct;
}
GT Bbghibe::recoverBlind(const BbghPrivatekey & sk, const PartialBbghCT & ct) const{
// This is inverted so that decrypt is ct/result. I.e. it aligns with the ppke scheme.
return group.div(group.pair(ct.B, sk.a0),group.pair(ct.C, sk.a1));
}
GT Bbghibe::decrypt(const BbghPrivatekey & sk, const BbghCT & ct) const
{
return group.div(ct.A, recoverBlind(sk,ct));
}
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkImageToStructuredPoints.cxx
Language: C++
Date: $Date$
Version: $Revision$
Thanks: Thanks to C. Charles Law who developed this class.
Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include <math.h>
#include "vtkImageToStructuredPoints.h"
#include "vtkScalars.h"
#include "vtkStructuredPoints.h"
//----------------------------------------------------------------------------
vtkImageToStructuredPoints::vtkImageToStructuredPoints()
{
int idx;
this->Translate[0] = this->Translate[1] = this->Translate[2] = 0;
this->SetOutput(0,vtkStructuredPoints::New());
}
//----------------------------------------------------------------------------
vtkImageToStructuredPoints::~vtkImageToStructuredPoints()
{
}
//----------------------------------------------------------------------------
void vtkImageToStructuredPoints::PrintSelf(ostream& os, vtkIndent indent)
{
vtkSource::PrintSelf(os,indent);
}
//----------------------------------------------------------------------------
vtkStructuredPoints *vtkImageToStructuredPoints::GetOutput()
{
if (this->NumberOfOutputs < 1)
{
return NULL;
}
return (vtkStructuredPoints *)(this->Outputs[0]);
}
//----------------------------------------------------------------------------
void vtkImageToStructuredPoints::SetInput(vtkImageData *input)
{
this->vtkProcessObject::SetInput(0, input);
}
//----------------------------------------------------------------------------
vtkImageData *vtkImageToStructuredPoints::GetInput()
{
if (this->NumberOfInputs < 1)
{
return NULL;
}
return (vtkImageData *)(this->Inputs[0]);
}
//----------------------------------------------------------------------------
void vtkImageToStructuredPoints::SetVectorInput(vtkImageData *input)
{
this->vtkProcessObject::SetInput(1, input);
}
//----------------------------------------------------------------------------
vtkImageData *vtkImageToStructuredPoints::GetVectorInput()
{
if (this->NumberOfInputs < 2)
{
return NULL;
}
return (vtkImageData *)(this->Inputs[1]);
}
//----------------------------------------------------------------------------
void vtkImageToStructuredPoints::Execute()
{
int uExtent[6];
int *wExtent;
int idxX, idxY, idxZ, maxX, maxY, maxZ;
int inIncX, inIncY, inIncZ, rowLength;
unsigned char *inPtr1, *inPtr, *outPtr;
vtkStructuredPoints *output = this->GetOutput();
vtkImageData *data = this->GetInput();
vtkImageData *vData = this->GetVectorInput();
if (!data)
{
vtkErrorMacro("Unable to generate data!");
return;
}
output->GetUpdateExtent(uExtent);
output->SetExtent(uExtent);
uExtent[0] += this->Translate[0];
uExtent[1] += this->Translate[0];
uExtent[2] += this->Translate[1];
uExtent[3] += this->Translate[1];
uExtent[4] += this->Translate[2];
uExtent[5] += this->Translate[2];
// if the data extent matches the update extent then just pass the data
// otherwise we must reformat and copy the data
wExtent = data->GetExtent();
if (wExtent[0] == uExtent[0] && wExtent[1] == uExtent[1] &&
wExtent[2] == uExtent[2] && wExtent[3] == uExtent[3] &&
wExtent[4] == uExtent[4] && wExtent[5] == uExtent[5])
{
output->GetPointData()->PassData(data->GetPointData());
}
else
{
inPtr = (unsigned char *) data->GetScalarPointerForExtent(uExtent);
outPtr = (unsigned char *) output->GetScalarPointer();
// Get increments to march through data
data->GetIncrements(inIncX, inIncY, inIncZ);
// find the region to loop over
rowLength = (uExtent[1] - uExtent[0]+1)*inIncX*data->GetScalarSize();
maxX = uExtent[1] - uExtent[0];
maxY = uExtent[3] - uExtent[2];
maxZ = uExtent[5] - uExtent[4];
inIncY *= data->GetScalarSize();
inIncZ *= data->GetScalarSize();
// Loop through output pixels
for (idxZ = 0; idxZ <= maxZ; idxZ++)
{
inPtr1 = inPtr + idxZ*inIncZ;
for (idxY = 0; idxY <= maxY; idxY++)
{
memcpy(outPtr,inPtr1,rowLength);
inPtr1 += inIncY;
outPtr += rowLength;
}
}
}
if (!vData)
{
return;
}
// if the data extent matches the update extent then just pass the data
// otherwise we must reformat and copy the data
wExtent = vData->GetExtent();
if (wExtent[0] == uExtent[0] && wExtent[1] == uExtent[1] &&
wExtent[2] == uExtent[2] && wExtent[3] == uExtent[3] &&
wExtent[4] == uExtent[4] && wExtent[5] == uExtent[5])
{
vtkVectors *fv = vtkVectors::New(vData->GetScalarType());
output->GetPointData()->SetVectors(fv);
fv->SetData(vData->GetPointData()->GetScalars()->GetData());
fv->Delete();
}
else
{
vtkVectors *fv = vtkVectors::New(vData->GetScalarType());
output->GetPointData()->SetVectors(fv);
float *inPtr2 = (float *)(vData->GetScalarPointerForExtent(uExtent));
fv->SetNumberOfVectors((maxZ+1)*(maxY+1)*(maxX+1));
vData->GetContinuousIncrements(uExtent, inIncX, inIncY, inIncZ);
int numComp = vData->GetNumberOfScalarComponents();
int idx = 0;
// Loop through ouput pixels
for (idxZ = 0; idxZ <= maxZ; idxZ++)
{
for (idxY = 0; idxY <= maxY; idxY++)
{
for (idxX = 0; idxX <= maxX; idxX++)
{
fv->SetVector(idx,inPtr2);
inPtr2 += numComp;
idx++;
}
inPtr2 += inIncY;
}
inPtr2 += inIncZ;
}
fv->Delete();
}
}
//----------------------------------------------------------------------------
// Copy WholeExtent, Spacing and Origin.
void vtkImageToStructuredPoints::ExecuteInformation()
{
vtkImageData *input = this->GetInput();
vtkImageData *vInput = this->GetVectorInput();
vtkStructuredPoints *output = this->GetOutput();
int whole[6], *tmp;
float *spacing, origin[3];
if (output == NULL || input == NULL)
{
return;
}
output->SetScalarType(input->GetScalarType());
output->SetNumberOfScalarComponents(input->GetNumberOfScalarComponents());
// intersections for whole extent
input->GetWholeExtent(whole);
if (vInput)
{
tmp = vInput->GetWholeExtent();
if (tmp[0] > whole[0]) {whole[0] = tmp[0];}
if (tmp[2] > whole[2]) {whole[2] = tmp[2];}
if (tmp[4] > whole[4]) {whole[4] = tmp[4];}
if (tmp[1] < whole[1]) {whole[1] = tmp[1];}
if (tmp[3] < whole[1]) {whole[3] = tmp[3];}
if (tmp[5] < whole[1]) {whole[5] = tmp[5];}
}
spacing = input->GetSpacing();
input->GetOrigin(origin);
// slide min extent to 0,0,0 (I Hate this !!!!)
this->Translate[0] = whole[0];
this->Translate[1] = whole[2];
this->Translate[2] = whole[4];
origin[0] += spacing[0] * whole[0];
origin[1] += spacing[1] * whole[2];
origin[2] += spacing[2] * whole[4];
whole[1] -= whole[0];
whole[3] -= whole[2];
whole[5] -= whole[4];
whole[0] = whole[2] = whole[4];
output->SetWholeExtent(whole);
// Now should Origin and Spacing really be part of information?
// How about xyx arrays in RectilinearGrid of Points in StructuredGrid?
output->SetOrigin(origin);
output->SetSpacing(spacing);
}
//----------------------------------------------------------------------------
int vtkImageToStructuredPoints::ComputeInputUpdateExtents(vtkDataObject *data)
{
vtkStructuredPoints *output = (vtkStructuredPoints*)data;
int ext[6];
vtkImageData *input;
output->GetUpdateExtent(ext);
ext[0] += this->Translate[0];
ext[1] += this->Translate[0];
ext[2] += this->Translate[1];
ext[3] += this->Translate[1];
ext[4] += this->Translate[2];
ext[5] += this->Translate[2];
input = this->GetInput();
if (input)
{
input->SetUpdateExtent(ext);
}
input = this->GetVectorInput();
if (input)
{
input->SetUpdateExtent(ext);
}
return 1;
}
<commit_msg>Translate extent bug<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkImageToStructuredPoints.cxx
Language: C++
Date: $Date$
Version: $Revision$
Thanks: Thanks to C. Charles Law who developed this class.
Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include <math.h>
#include "vtkImageToStructuredPoints.h"
#include "vtkScalars.h"
#include "vtkStructuredPoints.h"
//----------------------------------------------------------------------------
vtkImageToStructuredPoints::vtkImageToStructuredPoints()
{
int idx;
this->Translate[0] = this->Translate[1] = this->Translate[2] = 0;
this->SetOutput(0,vtkStructuredPoints::New());
}
//----------------------------------------------------------------------------
vtkImageToStructuredPoints::~vtkImageToStructuredPoints()
{
}
//----------------------------------------------------------------------------
void vtkImageToStructuredPoints::PrintSelf(ostream& os, vtkIndent indent)
{
vtkSource::PrintSelf(os,indent);
}
//----------------------------------------------------------------------------
vtkStructuredPoints *vtkImageToStructuredPoints::GetOutput()
{
if (this->NumberOfOutputs < 1)
{
return NULL;
}
return (vtkStructuredPoints *)(this->Outputs[0]);
}
//----------------------------------------------------------------------------
void vtkImageToStructuredPoints::SetInput(vtkImageData *input)
{
this->vtkProcessObject::SetInput(0, input);
}
//----------------------------------------------------------------------------
vtkImageData *vtkImageToStructuredPoints::GetInput()
{
if (this->NumberOfInputs < 1)
{
return NULL;
}
return (vtkImageData *)(this->Inputs[0]);
}
//----------------------------------------------------------------------------
void vtkImageToStructuredPoints::SetVectorInput(vtkImageData *input)
{
this->vtkProcessObject::SetInput(1, input);
}
//----------------------------------------------------------------------------
vtkImageData *vtkImageToStructuredPoints::GetVectorInput()
{
if (this->NumberOfInputs < 2)
{
return NULL;
}
return (vtkImageData *)(this->Inputs[1]);
}
//----------------------------------------------------------------------------
void vtkImageToStructuredPoints::Execute()
{
int uExtent[6];
int *wExtent;
int idxX, idxY, idxZ, maxX, maxY, maxZ;
int inIncX, inIncY, inIncZ, rowLength;
unsigned char *inPtr1, *inPtr, *outPtr;
vtkStructuredPoints *output = this->GetOutput();
vtkImageData *data = this->GetInput();
vtkImageData *vData = this->GetVectorInput();
if (!data)
{
vtkErrorMacro("Unable to generate data!");
return;
}
output->GetUpdateExtent(uExtent);
output->SetExtent(uExtent);
uExtent[0] += this->Translate[0];
uExtent[1] += this->Translate[0];
uExtent[2] += this->Translate[1];
uExtent[3] += this->Translate[1];
uExtent[4] += this->Translate[2];
uExtent[5] += this->Translate[2];
// if the data extent matches the update extent then just pass the data
// otherwise we must reformat and copy the data
wExtent = data->GetExtent();
if (wExtent[0] == uExtent[0] && wExtent[1] == uExtent[1] &&
wExtent[2] == uExtent[2] && wExtent[3] == uExtent[3] &&
wExtent[4] == uExtent[4] && wExtent[5] == uExtent[5])
{
output->GetPointData()->PassData(data->GetPointData());
}
else
{
inPtr = (unsigned char *) data->GetScalarPointerForExtent(uExtent);
outPtr = (unsigned char *) output->GetScalarPointer();
// Get increments to march through data
data->GetIncrements(inIncX, inIncY, inIncZ);
// find the region to loop over
rowLength = (uExtent[1] - uExtent[0]+1)*inIncX*data->GetScalarSize();
maxX = uExtent[1] - uExtent[0];
maxY = uExtent[3] - uExtent[2];
maxZ = uExtent[5] - uExtent[4];
inIncY *= data->GetScalarSize();
inIncZ *= data->GetScalarSize();
// Loop through output pixels
for (idxZ = 0; idxZ <= maxZ; idxZ++)
{
inPtr1 = inPtr + idxZ*inIncZ;
for (idxY = 0; idxY <= maxY; idxY++)
{
memcpy(outPtr,inPtr1,rowLength);
inPtr1 += inIncY;
outPtr += rowLength;
}
}
}
if (!vData)
{
return;
}
// if the data extent matches the update extent then just pass the data
// otherwise we must reformat and copy the data
wExtent = vData->GetExtent();
if (wExtent[0] == uExtent[0] && wExtent[1] == uExtent[1] &&
wExtent[2] == uExtent[2] && wExtent[3] == uExtent[3] &&
wExtent[4] == uExtent[4] && wExtent[5] == uExtent[5])
{
vtkVectors *fv = vtkVectors::New(vData->GetScalarType());
output->GetPointData()->SetVectors(fv);
fv->SetData(vData->GetPointData()->GetScalars()->GetData());
fv->Delete();
}
else
{
vtkVectors *fv = vtkVectors::New(vData->GetScalarType());
output->GetPointData()->SetVectors(fv);
float *inPtr2 = (float *)(vData->GetScalarPointerForExtent(uExtent));
fv->SetNumberOfVectors((maxZ+1)*(maxY+1)*(maxX+1));
vData->GetContinuousIncrements(uExtent, inIncX, inIncY, inIncZ);
int numComp = vData->GetNumberOfScalarComponents();
int idx = 0;
// Loop through ouput pixels
for (idxZ = 0; idxZ <= maxZ; idxZ++)
{
for (idxY = 0; idxY <= maxY; idxY++)
{
for (idxX = 0; idxX <= maxX; idxX++)
{
fv->SetVector(idx,inPtr2);
inPtr2 += numComp;
idx++;
}
inPtr2 += inIncY;
}
inPtr2 += inIncZ;
}
fv->Delete();
}
}
//----------------------------------------------------------------------------
// Copy WholeExtent, Spacing and Origin.
void vtkImageToStructuredPoints::ExecuteInformation()
{
vtkImageData *input = this->GetInput();
vtkImageData *vInput = this->GetVectorInput();
vtkStructuredPoints *output = this->GetOutput();
int whole[6], *tmp;
float *spacing, origin[3];
if (output == NULL || input == NULL)
{
return;
}
output->SetScalarType(input->GetScalarType());
output->SetNumberOfScalarComponents(input->GetNumberOfScalarComponents());
// intersections for whole extent
input->GetWholeExtent(whole);
if (vInput)
{
tmp = vInput->GetWholeExtent();
if (tmp[0] > whole[0]) {whole[0] = tmp[0];}
if (tmp[2] > whole[2]) {whole[2] = tmp[2];}
if (tmp[4] > whole[4]) {whole[4] = tmp[4];}
if (tmp[1] < whole[1]) {whole[1] = tmp[1];}
if (tmp[3] < whole[1]) {whole[3] = tmp[3];}
if (tmp[5] < whole[1]) {whole[5] = tmp[5];}
}
spacing = input->GetSpacing();
input->GetOrigin(origin);
// slide min extent to 0,0,0 (I Hate this !!!!)
this->Translate[0] = whole[0];
this->Translate[1] = whole[2];
this->Translate[2] = whole[4];
origin[0] += spacing[0] * whole[0];
origin[1] += spacing[1] * whole[2];
origin[2] += spacing[2] * whole[4];
whole[1] -= whole[0];
whole[3] -= whole[2];
whole[5] -= whole[4];
whole[0] = whole[2] = whole[4] = 0;
output->SetWholeExtent(whole);
// Now should Origin and Spacing really be part of information?
// How about xyx arrays in RectilinearGrid of Points in StructuredGrid?
output->SetOrigin(origin);
output->SetSpacing(spacing);
}
//----------------------------------------------------------------------------
int vtkImageToStructuredPoints::ComputeInputUpdateExtents(vtkDataObject *data)
{
vtkStructuredPoints *output = (vtkStructuredPoints*)data;
int ext[6];
vtkImageData *input;
output->GetUpdateExtent(ext);
ext[0] += this->Translate[0];
ext[1] += this->Translate[0];
ext[2] += this->Translate[1];
ext[3] += this->Translate[1];
ext[4] += this->Translate[2];
ext[5] += this->Translate[2];
input = this->GetInput();
if (input)
{
input->SetUpdateExtent(ext);
}
input = this->GetVectorInput();
if (input)
{
input->SetUpdateExtent(ext);
}
return 1;
}
<|endoftext|>
|
<commit_before>///
/// @file BitSieve.cpp
/// @brief Bit array for prime sieving.
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#if !defined(__STDC_CONSTANT_MACROS)
#define __STDC_CONSTANT_MACROS
#endif
#include <stdint.h>
#include <algorithm>
#include <cassert>
#include <vector>
#include <BitSieve.hpp>
#include <popcount.hpp>
#include <pmath.hpp>
namespace primecount {
const uint64_t BitSieve::unset_bit_[64] =
{
~(UINT64_C(1) << 0), ~(UINT64_C(1) << 1), ~(UINT64_C(1) << 2),
~(UINT64_C(1) << 3), ~(UINT64_C(1) << 4), ~(UINT64_C(1) << 5),
~(UINT64_C(1) << 6), ~(UINT64_C(1) << 7), ~(UINT64_C(1) << 8),
~(UINT64_C(1) << 9), ~(UINT64_C(1) << 10), ~(UINT64_C(1) << 11),
~(UINT64_C(1) << 12), ~(UINT64_C(1) << 13), ~(UINT64_C(1) << 14),
~(UINT64_C(1) << 15), ~(UINT64_C(1) << 16), ~(UINT64_C(1) << 17),
~(UINT64_C(1) << 18), ~(UINT64_C(1) << 19), ~(UINT64_C(1) << 20),
~(UINT64_C(1) << 21), ~(UINT64_C(1) << 22), ~(UINT64_C(1) << 23),
~(UINT64_C(1) << 24), ~(UINT64_C(1) << 25), ~(UINT64_C(1) << 26),
~(UINT64_C(1) << 27), ~(UINT64_C(1) << 28), ~(UINT64_C(1) << 29),
~(UINT64_C(1) << 30), ~(UINT64_C(1) << 31), ~(UINT64_C(1) << 32),
~(UINT64_C(1) << 33), ~(UINT64_C(1) << 34), ~(UINT64_C(1) << 35),
~(UINT64_C(1) << 36), ~(UINT64_C(1) << 37), ~(UINT64_C(1) << 38),
~(UINT64_C(1) << 39), ~(UINT64_C(1) << 40), ~(UINT64_C(1) << 41),
~(UINT64_C(1) << 42), ~(UINT64_C(1) << 43), ~(UINT64_C(1) << 44),
~(UINT64_C(1) << 45), ~(UINT64_C(1) << 46), ~(UINT64_C(1) << 47),
~(UINT64_C(1) << 48), ~(UINT64_C(1) << 49), ~(UINT64_C(1) << 50),
~(UINT64_C(1) << 51), ~(UINT64_C(1) << 52), ~(UINT64_C(1) << 53),
~(UINT64_C(1) << 54), ~(UINT64_C(1) << 55), ~(UINT64_C(1) << 56),
~(UINT64_C(1) << 57), ~(UINT64_C(1) << 58), ~(UINT64_C(1) << 59),
~(UINT64_C(1) << 60), ~(UINT64_C(1) << 61), ~(UINT64_C(1) << 62),
~(UINT64_C(1) << 63)
};
BitSieve::BitSieve(std::size_t size) :
bits_(ceil_div(size, 64)),
size_(size)
{ }
/// Set all bits to 1, except bits corresponding
/// to 0, 1 and even numbers > 2.
///
void BitSieve::memset(uint64_t low)
{
std::fill(bits_.begin(), bits_.end(), (low & 1)
? UINT64_C(0x5555555555555555) : UINT64_C(0xAAAAAAAAAAAAAAAA));
// correct 0, 1 and 2
if (low <= 2)
{
uint64_t bit = 1 << (2 - low);
bits_[0] &= ~(bit - 1);
bits_[0] |= bit;
}
}
/// Count the number of 1 bits inside [start, stop]
uint64_t BitSieve::count(uint64_t start, uint64_t stop) const
{
if (start > stop)
return 0;
assert(stop < size_);
uint64_t bit_count = count_edges(start, stop);
uint64_t start_idx = (start >> 6) + 1;
uint64_t limit = stop >> 6;
for (uint64_t i = start_idx; i < limit; i++)
bit_count += popcount64(bits_[i]);
return bit_count;
}
uint64_t BitSieve::count_edges(uint64_t start, uint64_t stop) const
{
uint64_t index1 = start >> 6;
uint64_t index2 = stop >> 6;
uint64_t mask1 = UINT64_C(0xffffffffffffffff) << (start & 63);
uint64_t mask2 = UINT64_C(0xffffffffffffffff) >> (63 - (stop & 63));
uint64_t count = 0;
if (index1 == index2)
count += popcount64(bits_[index1] & (mask1 & mask2));
else
{
count += popcount64(bits_[index1] & mask1);
count += popcount64(bits_[index2] & mask2);
}
return count;
}
} // namespace
<commit_msg>Add comment<commit_after>///
/// @file BitSieve.cpp
/// @brief The BitSieve class is a bit array for use with
/// Eratosthenes-like prime sieving algorithms. BitSieve
/// assigns 64 numbers to the bits of an 8 byte word thus
/// reducing the memory usage by a factor of 8.
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#if !defined(__STDC_CONSTANT_MACROS)
#define __STDC_CONSTANT_MACROS
#endif
#include <stdint.h>
#include <algorithm>
#include <cassert>
#include <vector>
#include <BitSieve.hpp>
#include <popcount.hpp>
#include <pmath.hpp>
namespace primecount {
const uint64_t BitSieve::unset_bit_[64] =
{
~(UINT64_C(1) << 0), ~(UINT64_C(1) << 1), ~(UINT64_C(1) << 2),
~(UINT64_C(1) << 3), ~(UINT64_C(1) << 4), ~(UINT64_C(1) << 5),
~(UINT64_C(1) << 6), ~(UINT64_C(1) << 7), ~(UINT64_C(1) << 8),
~(UINT64_C(1) << 9), ~(UINT64_C(1) << 10), ~(UINT64_C(1) << 11),
~(UINT64_C(1) << 12), ~(UINT64_C(1) << 13), ~(UINT64_C(1) << 14),
~(UINT64_C(1) << 15), ~(UINT64_C(1) << 16), ~(UINT64_C(1) << 17),
~(UINT64_C(1) << 18), ~(UINT64_C(1) << 19), ~(UINT64_C(1) << 20),
~(UINT64_C(1) << 21), ~(UINT64_C(1) << 22), ~(UINT64_C(1) << 23),
~(UINT64_C(1) << 24), ~(UINT64_C(1) << 25), ~(UINT64_C(1) << 26),
~(UINT64_C(1) << 27), ~(UINT64_C(1) << 28), ~(UINT64_C(1) << 29),
~(UINT64_C(1) << 30), ~(UINT64_C(1) << 31), ~(UINT64_C(1) << 32),
~(UINT64_C(1) << 33), ~(UINT64_C(1) << 34), ~(UINT64_C(1) << 35),
~(UINT64_C(1) << 36), ~(UINT64_C(1) << 37), ~(UINT64_C(1) << 38),
~(UINT64_C(1) << 39), ~(UINT64_C(1) << 40), ~(UINT64_C(1) << 41),
~(UINT64_C(1) << 42), ~(UINT64_C(1) << 43), ~(UINT64_C(1) << 44),
~(UINT64_C(1) << 45), ~(UINT64_C(1) << 46), ~(UINT64_C(1) << 47),
~(UINT64_C(1) << 48), ~(UINT64_C(1) << 49), ~(UINT64_C(1) << 50),
~(UINT64_C(1) << 51), ~(UINT64_C(1) << 52), ~(UINT64_C(1) << 53),
~(UINT64_C(1) << 54), ~(UINT64_C(1) << 55), ~(UINT64_C(1) << 56),
~(UINT64_C(1) << 57), ~(UINT64_C(1) << 58), ~(UINT64_C(1) << 59),
~(UINT64_C(1) << 60), ~(UINT64_C(1) << 61), ~(UINT64_C(1) << 62),
~(UINT64_C(1) << 63)
};
BitSieve::BitSieve(std::size_t size) :
bits_(ceil_div(size, 64)),
size_(size)
{ }
/// Set all bits to 1, except bits corresponding
/// to 0, 1 and even numbers > 2.
///
void BitSieve::memset(uint64_t low)
{
std::fill(bits_.begin(), bits_.end(), (low & 1)
? UINT64_C(0x5555555555555555) : UINT64_C(0xAAAAAAAAAAAAAAAA));
// correct 0, 1 and 2
if (low <= 2)
{
uint64_t bit = 1 << (2 - low);
bits_[0] &= ~(bit - 1);
bits_[0] |= bit;
}
}
/// Count the number of 1 bits inside [start, stop]
uint64_t BitSieve::count(uint64_t start, uint64_t stop) const
{
if (start > stop)
return 0;
assert(stop < size_);
uint64_t bit_count = count_edges(start, stop);
uint64_t start_idx = (start >> 6) + 1;
uint64_t limit = stop >> 6;
for (uint64_t i = start_idx; i < limit; i++)
bit_count += popcount64(bits_[i]);
return bit_count;
}
uint64_t BitSieve::count_edges(uint64_t start, uint64_t stop) const
{
uint64_t index1 = start >> 6;
uint64_t index2 = stop >> 6;
uint64_t mask1 = UINT64_C(0xffffffffffffffff) << (start & 63);
uint64_t mask2 = UINT64_C(0xffffffffffffffff) >> (63 - (stop & 63));
uint64_t count = 0;
if (index1 == index2)
count += popcount64(bits_[index1] & (mask1 & mask2));
else
{
count += popcount64(bits_[index1] & mask1);
count += popcount64(bits_[index2] & mask2);
}
return count;
}
} // namespace
<|endoftext|>
|
<commit_before>#include "../include/BlueFile.h"
//Prpare pour la lecture
BlueFile::BlueFile(string nom_fichier) : nom_fichier(nom_fichier)
{
bits.reserve(BLOCK_SIZE);
determineTaille();
fichier_lecture = NULL;
fichier_ecriture = NULL;
cout << "__________/_\\__________" << endl;
cout << "CRYPTAGE/DECRYPTAGE DE " << nom_fichier << endl;
cout << "TAILLE: " << taille << endl << endl;
}
//Dtruit les donnes
BlueFile::~BlueFile()
{
fichier_lecture->close();
delete fichier_lecture;
delete fichier_ecriture;
}
//Dtermine la taille du fichier
void BlueFile::determineTaille()
{
ifstream in("" DOSSIER_EFFECTIF "/" + nom_fichier, ifstream::ate | ifstream::binary);
taille = in.tellg();
}
//Lecture en binaire d'un fichier
void BlueFile::lireBinaire()
{
if(fichier_lecture == NULL)
fichier_lecture = new ifstream("" DOSSIER_EFFECTIF "/" + nom_fichier, ios::binary);
//lecture caractre par caractre
char c = '_';
while(bits.size() < BLOCK_SIZE && (int)fichier_lecture->tellg() != taille)
{
*fichier_lecture >> noskipws >> c;
//lecture bit par bit
for(int i = 7; i >= 0; i--)
bits.push_back(((c >> i) & 1));
}
}
//Dtecte si le fichier a fini d'tre crypt
int BlueFile::procedureFinie()
{
int position = (int)fichier_lecture->tellg();
bool end = position == taille;
//message de fin / progression
if(end)
cout << "CRYPTAGE/DECRYPTAGE FINI" << endl << "__________\\_/__________" << endl << endl;
else
cout << "Progression : " << (float)fichier_lecture->tellg() / (float) taille << "%" << endl;
if(end)
return 1;
else if(position == -1)
return -1;
else return 0;
}
//Crypte l'ensemble des bits courants
void BlueFile::crypter()
{
//cryptage basique: inverser les bits deux deux
for(size_t i = 0; i < bits.size() -1; i+=2)
{
char c1 = bits[i];
bits[i] = bits[i + 1];
bits[i + 1] = c1;
}
}
//Dcrypte l'ensemble des bits courants
void BlueFile::decrypter()
{
//dcryptage basique: inverser les bits deux deux
for(size_t i = 0; i < bits.size() - 1; i+=2)
{
char c1 = bits[i];
bits[i] = bits[i + 1];
bits[i + 1] = c1;
}
}
//Rcris l'ensemble des bits courants dans le fichier en binaire
void BlueFile::ecrireBinaire()
{
if(!fichier_ecriture)
fichier_ecriture = new ofstream("" DOSSIER_EFFECTIF "/" + nom_fichier, ios::binary);
//lecture des bits
for(size_t i = 0; i < bits.size(); i+=8)
{
//regroupement en caractre
char c = 0;
for(int j = 0; j < 8; j++)
c ^= (-(int)bits[i + j] ^ c) & (1 << (7 - j));
//si non saut de ligne spcial
*fichier_ecriture << c;
}
bits.clear();
}
//Affiche les bits
void BlueFile::afficherBits()
{
cout << endl << "AFFICHAGE BITS:" << endl;
for(size_t i = 0; i < bits.size(); i++)
{
if(i % 8 == 0)
cout << endl;
char bit = (bits[i] ? '1' : '0');
cout << bit;
}
cout << endl << "______" << endl << endl;
}
//Whiax<commit_msg>correction mineure<commit_after>#include "../include/BlueFile.h"
//Prpare pour la lecture
BlueFile::BlueFile(string nom_fichier) : nom_fichier(nom_fichier)
{
bits.reserve(BLOCK_SIZE);
determineTaille();
fichier_lecture = NULL;
fichier_ecriture = NULL;
cout << "__________/_\\__________" << endl;
cout << "CRYPTAGE/DECRYPTAGE DE " << nom_fichier << endl;
cout << "TAILLE: " << taille << endl << endl;
}
//Dtruit les donnes
BlueFile::~BlueFile()
{
fichier_lecture->close();
fichier_ecriture->close();
delete fichier_lecture;
delete fichier_ecriture;
}
//Dtermine la taille du fichier
void BlueFile::determineTaille()
{
ifstream in("" DOSSIER_EFFECTIF "/" + nom_fichier, ifstream::ate | ifstream::binary);
taille = in.tellg();
}
//Lecture en binaire d'un fichier
void BlueFile::lireBinaire()
{
if(fichier_lecture == NULL)
fichier_lecture = new ifstream("" DOSSIER_EFFECTIF "/" + nom_fichier, ios::binary);
//lecture caractre par caractre
char c = '_';
while(bits.size() < BLOCK_SIZE && (int)fichier_lecture->tellg() != taille)
{
*fichier_lecture >> noskipws >> c;
//lecture bit par bit
for(int i = 7; i >= 0; i--)
bits.push_back(((c >> i) & 1));
}
}
//Dtecte si le fichier a fini d'tre crypt
int BlueFile::procedureFinie()
{
int position = (int)fichier_lecture->tellg();
bool end = position == taille;
//message de fin / progression
if(end)
cout << "CRYPTAGE/DECRYPTAGE FINI" << endl << "__________\\_/__________" << endl << endl;
else
cout << "Progression : " << (float)fichier_lecture->tellg() / (float) taille << "%" << endl;
if(end)
return 1;
else if(position == -1)
return -1;
else return 0;
}
//Crypte l'ensemble des bits courants
void BlueFile::crypter()
{
//cryptage basique: inverser les bits deux deux
for(size_t i = 0; i < bits.size() -1; i+=2)
{
char c1 = bits[i];
bits[i] = bits[i + 1];
bits[i + 1] = c1;
}
}
//Dcrypte l'ensemble des bits courants
void BlueFile::decrypter()
{
//dcryptage basique: inverser les bits deux deux
for(size_t i = 0; i < bits.size() - 1; i+=2)
{
char c1 = bits[i];
bits[i] = bits[i + 1];
bits[i + 1] = c1;
}
}
//Rcris l'ensemble des bits courants dans le fichier en binaire
void BlueFile::ecrireBinaire()
{
if(!fichier_ecriture)
fichier_ecriture = new ofstream("" DOSSIER_EFFECTIF "/" + nom_fichier, ios::binary);
//lecture des bits
for(size_t i = 0; i < bits.size(); i+=8)
{
//regroupement en caractre
char c = 0;
for(int j = 0; j < 8; j++)
c ^= (-(int)bits[i + j] ^ c) & (1 << (7 - j));
//si non saut de ligne spcial
*fichier_ecriture << c;
}
bits.clear();
}
//Affiche les bits
void BlueFile::afficherBits()
{
cout << endl << "AFFICHAGE BITS:" << endl;
for(size_t i = 0; i < bits.size(); i++)
{
if(i % 8 == 0)
cout << endl;
char bit = (bits[i] ? '1' : '0');
cout << bit;
}
cout << endl << "______" << endl << endl;
}
//Whiax<|endoftext|>
|
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qmldebugclient_p.h"
#include <private/qobject_p.h>
#include <private/qpacketprotocol_p.h>
#include <QtCore/qdebug.h>
#include <QtCore/qstringlist.h>
QT_BEGIN_NAMESPACE
class QmlDebugConnectionPrivate : public QObject
{
Q_OBJECT
public:
QmlDebugConnectionPrivate(QmlDebugConnection *c);
QmlDebugConnection *q;
QPacketProtocol *protocol;
QStringList enabled;
QHash<QString, QmlDebugClient *> plugins;
public Q_SLOTS:
void connected();
void readyRead();
};
QmlDebugConnectionPrivate::QmlDebugConnectionPrivate(QmlDebugConnection *c)
: QObject(c), q(c), protocol(0)
{
protocol = new QPacketProtocol(q, this);
QObject::connect(c, SIGNAL(connected()), this, SLOT(connected()));
QObject::connect(protocol, SIGNAL(readyRead()), this, SLOT(readyRead()));
}
void QmlDebugConnectionPrivate::connected()
{
QPacket pack;
pack << QString(QLatin1String("QmlDebugServer")) << enabled;
protocol->send(pack);
}
void QmlDebugConnectionPrivate::readyRead()
{
QPacket pack = protocol->read();
QString name; QByteArray message;
pack >> name >> message;
QHash<QString, QmlDebugClient *>::Iterator iter =
plugins.find(name);
if (iter == plugins.end()) {
qWarning() << "QmlDebugConnection: Message received for missing plugin" << name;
} else {
(*iter)->messageReceived(message);
}
}
QmlDebugConnection::QmlDebugConnection(QObject *parent)
: QTcpSocket(parent), d(new QmlDebugConnectionPrivate(this))
{
}
bool QmlDebugConnection::isConnected() const
{
return state() == ConnectedState;
}
class QmlDebugClientPrivate : public QObjectPrivate
{
Q_DECLARE_PUBLIC(QmlDebugClient)
public:
QmlDebugClientPrivate();
QString name;
QmlDebugConnection *client;
bool enabled;
};
QmlDebugClientPrivate::QmlDebugClientPrivate()
: client(0), enabled(false)
{
}
QmlDebugClient::QmlDebugClient(const QString &name,
QmlDebugConnection *parent)
: QObject(*(new QmlDebugClientPrivate), parent)
{
Q_D(QmlDebugClient);
d->name = name;
d->client = parent;
if (!d->client)
return;
if (d->client->d->plugins.contains(name)) {
qWarning() << "QmlDebugClient: Conflicting plugin name" << name;
d->client = 0;
} else {
d->client->d->plugins.insert(name, this);
}
}
QString QmlDebugClient::name() const
{
Q_D(const QmlDebugClient);
return d->name;
}
bool QmlDebugClient::isEnabled() const
{
Q_D(const QmlDebugClient);
return d->enabled;
}
void QmlDebugClient::setEnabled(bool e)
{
Q_D(QmlDebugClient);
if (e == d->enabled)
return;
d->enabled = e;
if (d->client) {
if (e)
d->client->d->enabled.append(d->name);
else
d->client->d->enabled.removeAll(d->name);
if (d->client->state() == QTcpSocket::ConnectedState) {
QPacket pack;
pack << QString(QLatin1String("QmlDebugServer"));
if (e) pack << (int)1;
else pack << (int)2;
pack << d->name;
d->client->d->protocol->send(pack);
}
}
}
bool QmlDebugClient::isConnected() const
{
Q_D(const QmlDebugClient);
return d->client->isConnected();
}
void QmlDebugClient::sendMessage(const QByteArray &message)
{
Q_D(QmlDebugClient);
if (!d->client || !d->client->isConnected())
return;
QPacket pack;
pack << d->name << message;
d->client->d->protocol->send(pack);
}
void QmlDebugClient::messageReceived(const QByteArray &)
{
}
QT_END_NAMESPACE
#include "qmldebugclient.moc"
<commit_msg>Fix crash bug where socket is 0.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qmldebugclient_p.h"
#include <private/qobject_p.h>
#include <private/qpacketprotocol_p.h>
#include <QtCore/qdebug.h>
#include <QtCore/qstringlist.h>
QT_BEGIN_NAMESPACE
class QmlDebugConnectionPrivate : public QObject
{
Q_OBJECT
public:
QmlDebugConnectionPrivate(QmlDebugConnection *c);
QmlDebugConnection *q;
QPacketProtocol *protocol;
QStringList enabled;
QHash<QString, QmlDebugClient *> plugins;
public Q_SLOTS:
void connected();
void readyRead();
};
QmlDebugConnectionPrivate::QmlDebugConnectionPrivate(QmlDebugConnection *c)
: QObject(c), q(c), protocol(0)
{
protocol = new QPacketProtocol(q, this);
QObject::connect(c, SIGNAL(connected()), this, SLOT(connected()));
QObject::connect(protocol, SIGNAL(readyRead()), this, SLOT(readyRead()));
}
void QmlDebugConnectionPrivate::connected()
{
QPacket pack;
pack << QString(QLatin1String("QmlDebugServer")) << enabled;
protocol->send(pack);
}
void QmlDebugConnectionPrivate::readyRead()
{
QPacket pack = protocol->read();
QString name; QByteArray message;
pack >> name >> message;
QHash<QString, QmlDebugClient *>::Iterator iter =
plugins.find(name);
if (iter == plugins.end()) {
qWarning() << "QmlDebugConnection: Message received for missing plugin" << name;
} else {
(*iter)->messageReceived(message);
}
}
QmlDebugConnection::QmlDebugConnection(QObject *parent)
: QTcpSocket(parent), d(new QmlDebugConnectionPrivate(this))
{
}
bool QmlDebugConnection::isConnected() const
{
return state() == ConnectedState;
}
class QmlDebugClientPrivate : public QObjectPrivate
{
Q_DECLARE_PUBLIC(QmlDebugClient)
public:
QmlDebugClientPrivate();
QString name;
QmlDebugConnection *client;
bool enabled;
};
QmlDebugClientPrivate::QmlDebugClientPrivate()
: client(0), enabled(false)
{
}
QmlDebugClient::QmlDebugClient(const QString &name,
QmlDebugConnection *parent)
: QObject(*(new QmlDebugClientPrivate), parent)
{
Q_D(QmlDebugClient);
d->name = name;
d->client = parent;
if (!d->client)
return;
if (d->client->d->plugins.contains(name)) {
qWarning() << "QmlDebugClient: Conflicting plugin name" << name;
d->client = 0;
} else {
d->client->d->plugins.insert(name, this);
}
}
QString QmlDebugClient::name() const
{
Q_D(const QmlDebugClient);
return d->name;
}
bool QmlDebugClient::isEnabled() const
{
Q_D(const QmlDebugClient);
return d->enabled;
}
void QmlDebugClient::setEnabled(bool e)
{
Q_D(QmlDebugClient);
if (e == d->enabled)
return;
d->enabled = e;
if (d->client) {
if (e)
d->client->d->enabled.append(d->name);
else
d->client->d->enabled.removeAll(d->name);
if (d->client->state() == QTcpSocket::ConnectedState) {
QPacket pack;
pack << QString(QLatin1String("QmlDebugServer"));
if (e) pack << (int)1;
else pack << (int)2;
pack << d->name;
d->client->d->protocol->send(pack);
}
}
}
bool QmlDebugClient::isConnected() const
{
Q_D(const QmlDebugClient);
if (!d->client)
return false;
return d->client->isConnected();
}
void QmlDebugClient::sendMessage(const QByteArray &message)
{
Q_D(QmlDebugClient);
if (!d->client || !d->client->isConnected())
return;
QPacket pack;
pack << d->name << message;
d->client->d->protocol->send(pack);
}
void QmlDebugClient::messageReceived(const QByteArray &)
{
}
QT_END_NAMESPACE
#include "qmldebugclient.moc"
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2010-2014, Mathieu Labbe - IntRoLab - Universite de Sherbrooke
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 Universite de Sherbrooke nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "CoreWrapper.h"
#include <rtabmap/utilite/ULogger.h>
#include <rtabmap/utilite/UDirectory.h>
#include <rtabmap/utilite/UStl.h>
#include <rtabmap/utilite/UFile.h>
#include <rtabmap/core/Version.h>
int main(int argc, char** argv)
{
ROS_INFO("Starting node...");
ULogger::setType(ULogger::kTypeConsole);
ULogger::setLevel(ULogger::kInfo);
ros::init(argc, argv, "rtabmap");
bool deleteDbOnStart = false;
for(int i=1;i<argc;++i)
{
if(strcmp(argv[i], "--delete_db_on_start") == 0)
{
deleteDbOnStart = true;
}
else if(strcmp(argv[i], "--udebug") == 0)
{
ULogger::setLevel(ULogger::kDebug);
}
else if(strcmp(argv[i], "--uinfo") == 0)
{
ULogger::setLevel(ULogger::kInfo);
}
else if(strcmp(argv[i], "--params") == 0 || strcmp(argv[i], "--params-all") == 0)
{
rtabmap::ParametersMap parameters = rtabmap::Parameters::getDefaultParameters();
uInsert(parameters,
std::make_pair(rtabmap::Parameters::kRtabmapWorkingDirectory(),
UDirectory::homeDir()+"/.ros")); // change default to ~/.ros
if(strcmp(argv[i], "--params") == 0)
{
// hide specific parameters
for(rtabmap::ParametersMap::iterator iter=parameters.begin(); iter!=parameters.end();)
{
if(iter->first.find("Odom") == 0)
{
parameters.erase(iter++);
}
else
{
++iter;
}
}
}
for(rtabmap::ParametersMap::iterator iter=parameters.begin(); iter!=parameters.end(); ++iter)
{
std::string str = "Param: " + iter->first + " = \"" + iter->second + "\"";
std::cout <<
str <<
std::setw(60 - str.size()) <<
" [" <<
rtabmap::Parameters::getDescription(iter->first).c_str() <<
"]" <<
std::endl;
}
ROS_WARN("Node will now exit after showing default RTAB-Map parameters because "
"argument \"--params\" is detected!");
exit(0);
}
else
{
ROS_ERROR("Not recognized argument \"%s\"", argv[i]);
exit(-1);
}
}
CoreWrapper * rtabmap = new CoreWrapper(deleteDbOnStart);
ROS_INFO("rtabmap %s started...", RTABMAP_VERSION);
ros::spin();
delete rtabmap;
return 0;
}
<commit_msg>CoreNode: Log Info->Warning level<commit_after>/*
Copyright (c) 2010-2014, Mathieu Labbe - IntRoLab - Universite de Sherbrooke
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 Universite de Sherbrooke nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "CoreWrapper.h"
#include <rtabmap/utilite/ULogger.h>
#include <rtabmap/utilite/UDirectory.h>
#include <rtabmap/utilite/UStl.h>
#include <rtabmap/utilite/UFile.h>
#include <rtabmap/core/Version.h>
int main(int argc, char** argv)
{
ROS_INFO("Starting node...");
ULogger::setType(ULogger::kTypeConsole);
ULogger::setLevel(ULogger::kWarning);
ros::init(argc, argv, "rtabmap");
bool deleteDbOnStart = false;
for(int i=1;i<argc;++i)
{
if(strcmp(argv[i], "--delete_db_on_start") == 0)
{
deleteDbOnStart = true;
}
else if(strcmp(argv[i], "--udebug") == 0)
{
ULogger::setLevel(ULogger::kDebug);
}
else if(strcmp(argv[i], "--uinfo") == 0)
{
ULogger::setLevel(ULogger::kInfo);
}
else if(strcmp(argv[i], "--params") == 0 || strcmp(argv[i], "--params-all") == 0)
{
rtabmap::ParametersMap parameters = rtabmap::Parameters::getDefaultParameters();
uInsert(parameters,
std::make_pair(rtabmap::Parameters::kRtabmapWorkingDirectory(),
UDirectory::homeDir()+"/.ros")); // change default to ~/.ros
if(strcmp(argv[i], "--params") == 0)
{
// hide specific parameters
for(rtabmap::ParametersMap::iterator iter=parameters.begin(); iter!=parameters.end();)
{
if(iter->first.find("Odom") == 0)
{
parameters.erase(iter++);
}
else
{
++iter;
}
}
}
for(rtabmap::ParametersMap::iterator iter=parameters.begin(); iter!=parameters.end(); ++iter)
{
std::string str = "Param: " + iter->first + " = \"" + iter->second + "\"";
std::cout <<
str <<
std::setw(60 - str.size()) <<
" [" <<
rtabmap::Parameters::getDescription(iter->first).c_str() <<
"]" <<
std::endl;
}
ROS_WARN("Node will now exit after showing default RTAB-Map parameters because "
"argument \"--params\" is detected!");
exit(0);
}
else
{
ROS_ERROR("Not recognized argument \"%s\"", argv[i]);
exit(-1);
}
}
CoreWrapper * rtabmap = new CoreWrapper(deleteDbOnStart);
ROS_INFO("rtabmap %s started...", RTABMAP_VERSION);
ros::spin();
delete rtabmap;
return 0;
}
<|endoftext|>
|
<commit_before>/**************************************************************************
The MIT License (MIT)
Copyright (c) 2015 Dmitry Sovetov
https://github.com/dmsovetov
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 "Physics.h"
DC_BEGIN_DREEMCHEST
namespace Scene {
// ------------------------------------------- Shape2D ------------------------------------------- //
// ** Shape2D::clear
void Shape2D::clear( void )
{
m_parts.clear();
}
// ** Shape2D::partCount
u32 Shape2D::partCount( void ) const
{
return ( u32 )m_parts.size();
}
// ** Shape2D::part
const Shape2D::Part& Shape2D::part( u32 index ) const
{
DC_BREAK_IF( index >= partCount() )
return m_parts[index];
}
// ** Shape2D::addPart
void Shape2D::addPart( const Part& part )
{
m_parts.push_back( part );
}
// ** Shape2D::addCircle
void Shape2D::addCircle( f32 radius, f32 x, f32 y, const Material& material )
{
Part part;
part.type = Circle;
part.material = material;
part.circle.radius = radius;
part.circle.x = x;
part.circle.y = y;
addPart( part );
}
// ** Shape2D::addRect
void Shape2D::addRect( f32 width, f32 height, f32 x, f32 y, const Material& material )
{
Part part;
part.type = Rect;
part.material = material;
part.rect.width = width;
part.rect.height = height;
part.rect.x = x;
part.rect.y = y;
addPart( part );
}
// ** Shape2D::addPolygon
void Shape2D::addPolygon( const Vec2* vertices, u32 count, const Material& material )
{
DC_BREAK_IF( count > Part::MaxVertices );
Part part;
part.type = Polygon;
part.material = material;
part.polygon.count = count;
for( u32 i = 0; i < count; i++ ) {
part.polygon.vertices[i * 2 + 0] = vertices[i].x;
part.polygon.vertices[i * 2 + 1] = vertices[i].y;
}
addPart( part );
}
// ** Shape2D::serialize
void Shape2D::serialize( Ecs::SerializationContext& ctx, Io::KeyValue& ar ) const
{
switch( m_parts[0].type ) {
case Polygon: {
Io::KeyValue vertices = Io::KeyValue::array();
for( u32 i = 0; i < m_parts[0].polygon.count; i++ ) {
vertices << m_parts[0].polygon.vertices[i * 2 + 0] << m_parts[0].polygon.vertices[i * 2 + 1];
}
ar = Io::KeyValue::object() << "type" << "polygon" << "vertices" << vertices;
}
break;
default: DC_BREAK;
}
}
// ** Shape2D::deserialize
void Shape2D::deserialize( Ecs::SerializationContext& ctx, const Io::KeyValue& ar )
{
// Get shape type
const String& type = ar.get( "type", "" ).asString();
if( type == "polygon" ) {
const Io::KeyValue& vertices = ar.get( "vertices" );
Array<Vec2> points;
for( s32 i = 0, n = vertices.size() / 2; i < n; i++ ) {
points.push_back( Vec2( vertices[i * 2 + 0].asFloat(), vertices[i * 2 + 1].asFloat() ) );
}
addPolygon( &points[0], points.size() );
}
else {
DC_BREAK;
}
}
// ----------------------------------------- RigidBody2D ----------------------------------------- //
// ** RigidBody2D::RigidBody2D
RigidBody2D::RigidBody2D( f32 mass, Type type, u16 category, u16 collisionMask, bool isBullet )
: m_mass( mass ), m_type( type ), m_linearDamping( 0.0f ), m_angularDamping( 0.0f ), m_torque( 0.0f ), m_category( category ), m_collisionMask( collisionMask ), m_gravityScale( 1.0f )
{
m_flags.set( IsBullet, isBullet );
}
// ** RigidBody2D::mass
f32 RigidBody2D::mass( void ) const
{
return m_mass;
}
// ** RigidBody2D::type
RigidBody2D::Type RigidBody2D::type( void ) const
{
return m_type;
}
// ** RigidBody2D::linearDamping
f32 RigidBody2D::linearDamping( void ) const
{
return m_linearDamping;
}
// ** RigidBody2D::setLinearDamping
void RigidBody2D::setLinearDamping( f32 value )
{
m_linearDamping = value;
}
// ** RigidBody2D::angularDamping
f32 RigidBody2D::angularDamping( void ) const
{
return m_angularDamping;
}
// ** RigidBody2D::setAngularDamping
void RigidBody2D::setAngularDamping( f32 value )
{
m_angularDamping = value;
}
// ** RigidBody2D::gravityScale
f32 RigidBody2D::gravityScale( void ) const
{
return m_gravityScale;
}
// ** RigidBody2D::setGravityScale
void RigidBody2D::setGravityScale( f32 value )
{
m_gravityScale = value;
}
// ** RigidBody2D::moveTo
void RigidBody2D::moveTo( const Vec2& position )
{
m_movedTo = position;
m_flags.on( WasMoved );
}
// ** RigidBody2D::movedTo
const Vec2& RigidBody2D::movedTo( void ) const
{
return m_movedTo;
}
// ** RigidBody2D::wasMoved
bool RigidBody2D::wasMoved( void ) const
{
return m_flags.is( WasMoved );
}
// ** RigidBody2D::putToRest
void RigidBody2D::putToRest( void )
{
m_flags.on( WasPutToRest );
}
// ** RigidBody2D::wasPutToRest
bool RigidBody2D::wasPutToRest( void ) const
{
return m_flags.is( WasPutToRest );
}
// ** RigidBody2D::isBullet
bool RigidBody2D::isBullet( void ) const
{
return m_flags.is( IsBullet );
}
// ** RigidBody2D::torque
f32 RigidBody2D::torque( void ) const
{
return m_torque;
}
// ** RigidBody2D::applyTorque
void RigidBody2D::applyTorque( f32 value )
{
m_torque += value;
}
// ** RigidBody2D::force
const Vec2& RigidBody2D::force( void ) const
{
return m_force;
}
// ** RigidBody2D::applyForc
void RigidBody2D::applyForce( const Vec2& value )
{
m_force += value;
}
// ** RigidBody2D::category
u16 RigidBody2D::category( void ) const
{
return m_category;
}
// ** RigidBody2D::collisionMask
u16 RigidBody2D::collisionMask( void ) const
{
return m_collisionMask;
}
// ** RigidBody2D::applyForceToPoint
void RigidBody2D::applyForceToPoint( const Vec2& value, const Vec2& point )
{
m_forces.push_back( AppliedForce( value, point ) );
}
// ** RigidBody2D::applyImpulse
void RigidBody2D::applyImpulse( const Vec2& value )
{
m_impulses.push_back( AppliedForce( value, Vec2( 0.0f, 0.0f ) ) );
}
// ** RigidBody2D::applyImpulseToPoint
void RigidBody2D::applyImpulseToPoint( const Vec2& value, const Vec2& point )
{
m_impulses.push_back( AppliedForce( value, point ) );
}
// ** RigidBody2D::appliedForceCount
u32 RigidBody2D::appliedForceCount( void ) const
{
return ( u32 )m_forces.size();
}
// ** RigidBody2D::appliedImpulse
const RigidBody2D::AppliedForce& RigidBody2D::appliedImpulse( u32 index ) const
{
DC_BREAK_IF( index >= appliedImpulseCount() );
return m_impulses[index];
}
// ** RigidBody2D::appliedImpulseCount
u32 RigidBody2D::appliedImpulseCount( void ) const
{
return ( u32 )m_impulses.size();
}
// ** RigidBody2D::appliedForce
const RigidBody2D::AppliedForce& RigidBody2D::appliedForce( u32 index ) const
{
DC_BREAK_IF( index >= appliedForceCount() );
return m_forces[index];
}
// ** RigidBody2D::collisionEventCount
u32 RigidBody2D::collisionEventCount( void ) const
{
return ( u32 )m_collisionEvents.size();
}
// ** RigidBody2D::collisionEvent
const RigidBody2D::CollisionEvent& RigidBody2D::collisionEvent( u32 index ) const
{
DC_BREAK_IF( index < 0 || index >= collisionEventCount() );
return m_collisionEvents[index];
}
// ** RigidBody2D::queueCollisionEvent
void RigidBody2D::queueCollisionEvent( const CollisionEvent& e )
{
m_collisionEvents.push_back( e );
}
// ** RigidBody2D::clear
void RigidBody2D::clear( void )
{
m_torque = 0.0f;
m_force = Vec2( 0.0f, 0.0f );
m_flags.off( WasPutToRest | WasMoved );
m_forces.clear();
m_impulses.clear();
}
// ** RigidBody2D::clearEvents
void RigidBody2D::clearEvents( void )
{
m_collisionEvents.clear();
}
// ** RigidBody2D::linearVelocity
const Vec2& RigidBody2D::linearVelocity( void ) const
{
return m_linearVelocity;
}
// ** RigidBody2D::setLinearVelocity
void RigidBody2D::setLinearVelocity( const Vec2& value )
{
m_linearVelocity = value;
}
// ** RigidBody2D::updateMass
void RigidBody2D::updateMass( f32 value )
{
m_mass = value;
}
} // namespace Scene
DC_END_DREEMCHEST<commit_msg>Improved: Shape2D serialization<commit_after>/**************************************************************************
The MIT License (MIT)
Copyright (c) 2015 Dmitry Sovetov
https://github.com/dmsovetov
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 "Physics.h"
DC_BEGIN_DREEMCHEST
namespace Scene {
// ------------------------------------------- Shape2D ------------------------------------------- //
// ** Shape2D::clear
void Shape2D::clear( void )
{
m_parts.clear();
}
// ** Shape2D::partCount
u32 Shape2D::partCount( void ) const
{
return ( u32 )m_parts.size();
}
// ** Shape2D::part
const Shape2D::Part& Shape2D::part( u32 index ) const
{
DC_BREAK_IF( index >= partCount() )
return m_parts[index];
}
// ** Shape2D::addPart
void Shape2D::addPart( const Part& part )
{
m_parts.push_back( part );
}
// ** Shape2D::addCircle
void Shape2D::addCircle( f32 radius, f32 x, f32 y, const Material& material )
{
Part part;
part.type = Circle;
part.material = material;
part.circle.radius = radius;
part.circle.x = x;
part.circle.y = y;
addPart( part );
}
// ** Shape2D::addRect
void Shape2D::addRect( f32 width, f32 height, f32 x, f32 y, const Material& material )
{
Part part;
part.type = Rect;
part.material = material;
part.rect.width = width;
part.rect.height = height;
part.rect.x = x;
part.rect.y = y;
addPart( part );
}
// ** Shape2D::addPolygon
void Shape2D::addPolygon( const Vec2* vertices, u32 count, const Material& material )
{
DC_BREAK_IF( count > Part::MaxVertices );
Part part;
part.type = Polygon;
part.material = material;
part.polygon.count = count;
for( u32 i = 0; i < count; i++ ) {
part.polygon.vertices[i * 2 + 0] = vertices[i].x;
part.polygon.vertices[i * 2 + 1] = vertices[i].y;
}
addPart( part );
}
// ** Shape2D::serialize
void Shape2D::serialize( Ecs::SerializationContext& ctx, Io::KeyValue& ar ) const
{
Io::KeyValue material = Io::KeyValue::object() << "density" << m_parts[0].material.density << "friction" << m_parts[0].material.friction << "restitution" << m_parts[0].material.restitution;
switch( m_parts[0].type ) {
case Polygon: {
Io::KeyValue vertices = Io::KeyValue::array();
for( u32 i = 0; i < m_parts[0].polygon.count; i++ ) {
vertices << m_parts[0].polygon.vertices[i * 2 + 0] << m_parts[0].polygon.vertices[i * 2 + 1];
}
ar = Io::KeyValue::object() << "type" << "polygon" << "vertices" << vertices << "material" << material;
}
break;
case Circle: {
ar = Io::KeyValue::object() << "type" << "circle" << "radius" << m_parts[0].circle.radius << "material" << material;
}
break;
default: DC_BREAK;
}
}
// ** Shape2D::deserialize
void Shape2D::deserialize( Ecs::SerializationContext& ctx, const Io::KeyValue& ar )
{
// Get shape type
const String& type = ar.get( "type", "" ).asString();
// Get material
Io::KeyValue material = ar.get( "material" );
// Parse material
Material shapeMaterial;
if( material.isObject() ) {
shapeMaterial.density = material.get( "density", 1.0f ).asFloat();
shapeMaterial.friction = material.get( "friction", 0.2f ).asFloat();
shapeMaterial.restitution = material.get( "restitution", 0.0f ).asFloat();
}
if( type == "polygon" ) {
const Io::KeyValue& vertices = ar.get( "vertices" );
Array<Vec2> points;
for( s32 i = 0, n = vertices.size() / 2; i < n; i++ ) {
points.push_back( Vec2( vertices[i * 2 + 0].asFloat(), vertices[i * 2 + 1].asFloat() ) );
}
addPolygon( &points[0], points.size(), shapeMaterial );
}
else if( type == "circle" ) {
addCircle( ar.get( "radius", 0.0f ).asFloat(), 0.0f, 0.0f, shapeMaterial );
}
else {
DC_BREAK;
}
}
// ----------------------------------------- RigidBody2D ----------------------------------------- //
// ** RigidBody2D::RigidBody2D
RigidBody2D::RigidBody2D( f32 mass, Type type, u16 category, u16 collisionMask, bool isBullet )
: m_mass( mass ), m_type( type ), m_linearDamping( 0.0f ), m_angularDamping( 0.0f ), m_torque( 0.0f ), m_category( category ), m_collisionMask( collisionMask ), m_gravityScale( 1.0f )
{
m_flags.set( IsBullet, isBullet );
}
// ** RigidBody2D::mass
f32 RigidBody2D::mass( void ) const
{
return m_mass;
}
// ** RigidBody2D::type
RigidBody2D::Type RigidBody2D::type( void ) const
{
return m_type;
}
// ** RigidBody2D::linearDamping
f32 RigidBody2D::linearDamping( void ) const
{
return m_linearDamping;
}
// ** RigidBody2D::setLinearDamping
void RigidBody2D::setLinearDamping( f32 value )
{
m_linearDamping = value;
}
// ** RigidBody2D::angularDamping
f32 RigidBody2D::angularDamping( void ) const
{
return m_angularDamping;
}
// ** RigidBody2D::setAngularDamping
void RigidBody2D::setAngularDamping( f32 value )
{
m_angularDamping = value;
}
// ** RigidBody2D::gravityScale
f32 RigidBody2D::gravityScale( void ) const
{
return m_gravityScale;
}
// ** RigidBody2D::setGravityScale
void RigidBody2D::setGravityScale( f32 value )
{
m_gravityScale = value;
}
// ** RigidBody2D::moveTo
void RigidBody2D::moveTo( const Vec2& position )
{
m_movedTo = position;
m_flags.on( WasMoved );
}
// ** RigidBody2D::movedTo
const Vec2& RigidBody2D::movedTo( void ) const
{
return m_movedTo;
}
// ** RigidBody2D::wasMoved
bool RigidBody2D::wasMoved( void ) const
{
return m_flags.is( WasMoved );
}
// ** RigidBody2D::putToRest
void RigidBody2D::putToRest( void )
{
m_flags.on( WasPutToRest );
}
// ** RigidBody2D::wasPutToRest
bool RigidBody2D::wasPutToRest( void ) const
{
return m_flags.is( WasPutToRest );
}
// ** RigidBody2D::isBullet
bool RigidBody2D::isBullet( void ) const
{
return m_flags.is( IsBullet );
}
// ** RigidBody2D::torque
f32 RigidBody2D::torque( void ) const
{
return m_torque;
}
// ** RigidBody2D::applyTorque
void RigidBody2D::applyTorque( f32 value )
{
m_torque += value;
}
// ** RigidBody2D::force
const Vec2& RigidBody2D::force( void ) const
{
return m_force;
}
// ** RigidBody2D::applyForc
void RigidBody2D::applyForce( const Vec2& value )
{
m_force += value;
}
// ** RigidBody2D::category
u16 RigidBody2D::category( void ) const
{
return m_category;
}
// ** RigidBody2D::collisionMask
u16 RigidBody2D::collisionMask( void ) const
{
return m_collisionMask;
}
// ** RigidBody2D::applyForceToPoint
void RigidBody2D::applyForceToPoint( const Vec2& value, const Vec2& point )
{
m_forces.push_back( AppliedForce( value, point ) );
}
// ** RigidBody2D::applyImpulse
void RigidBody2D::applyImpulse( const Vec2& value )
{
m_impulses.push_back( AppliedForce( value, Vec2( 0.0f, 0.0f ) ) );
}
// ** RigidBody2D::applyImpulseToPoint
void RigidBody2D::applyImpulseToPoint( const Vec2& value, const Vec2& point )
{
m_impulses.push_back( AppliedForce( value, point ) );
}
// ** RigidBody2D::appliedForceCount
u32 RigidBody2D::appliedForceCount( void ) const
{
return ( u32 )m_forces.size();
}
// ** RigidBody2D::appliedImpulse
const RigidBody2D::AppliedForce& RigidBody2D::appliedImpulse( u32 index ) const
{
DC_BREAK_IF( index >= appliedImpulseCount() );
return m_impulses[index];
}
// ** RigidBody2D::appliedImpulseCount
u32 RigidBody2D::appliedImpulseCount( void ) const
{
return ( u32 )m_impulses.size();
}
// ** RigidBody2D::appliedForce
const RigidBody2D::AppliedForce& RigidBody2D::appliedForce( u32 index ) const
{
DC_BREAK_IF( index >= appliedForceCount() );
return m_forces[index];
}
// ** RigidBody2D::collisionEventCount
u32 RigidBody2D::collisionEventCount( void ) const
{
return ( u32 )m_collisionEvents.size();
}
// ** RigidBody2D::collisionEvent
const RigidBody2D::CollisionEvent& RigidBody2D::collisionEvent( u32 index ) const
{
DC_BREAK_IF( index < 0 || index >= collisionEventCount() );
return m_collisionEvents[index];
}
// ** RigidBody2D::queueCollisionEvent
void RigidBody2D::queueCollisionEvent( const CollisionEvent& e )
{
m_collisionEvents.push_back( e );
}
// ** RigidBody2D::clear
void RigidBody2D::clear( void )
{
m_torque = 0.0f;
m_force = Vec2( 0.0f, 0.0f );
m_flags.off( WasPutToRest | WasMoved );
m_forces.clear();
m_impulses.clear();
}
// ** RigidBody2D::clearEvents
void RigidBody2D::clearEvents( void )
{
m_collisionEvents.clear();
}
// ** RigidBody2D::linearVelocity
const Vec2& RigidBody2D::linearVelocity( void ) const
{
return m_linearVelocity;
}
// ** RigidBody2D::setLinearVelocity
void RigidBody2D::setLinearVelocity( const Vec2& value )
{
m_linearVelocity = value;
}
// ** RigidBody2D::updateMass
void RigidBody2D::updateMass( f32 value )
{
m_mass = value;
}
} // namespace Scene
DC_END_DREEMCHEST<|endoftext|>
|
<commit_before>#include "Debugger.h"
#include "Cpu.h"
#include "CpuHelpers.h"
#include "CpuOpCodes.h"
#include "MemoryBus.h"
#include "Platform.h"
#include <array>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <vector>
namespace {
template <typename T>
T HexStringToIntegral(const char* s) {
std::stringstream converter(s);
T value;
converter >> std::hex >> value;
return value;
}
std::vector<std::string> Tokenize(const std::string& s) {
std::vector<std::string> result;
const char* whitespace = " \t";
size_t startIndex = 0;
while ((startIndex = s.find_first_not_of(whitespace, startIndex)) != std::string::npos) {
size_t endIndex = s.find_first_of(whitespace, startIndex + 1);
if (endIndex == std::string::npos) {
result.emplace_back(s.substr(startIndex));
break;
} else {
result.emplace_back(s.substr(startIndex, endIndex - startIndex));
startIndex = endIndex;
}
}
return result;
}
struct Instruction {
const CpuOp& cpuOp;
int page;
std::array<uint8_t, 2> operands;
};
Instruction ReadInstruction(uint16_t opAddr, const MemoryBus& memoryBus) {
int cpuOpPage = 0;
uint8_t opCodeByte = memoryBus.Read(opAddr++);
if (IsOpCodePage1(opCodeByte)) {
cpuOpPage = 1;
opCodeByte = memoryBus.Read(opAddr++);
} else if (IsOpCodePage2(opCodeByte)) {
cpuOpPage = 2;
opCodeByte = memoryBus.Read(opAddr++);
}
const auto& cpuOp = LookupCpuOpRuntime(cpuOpPage, opCodeByte);
const int numOperands = cpuOp.size - 1 - (cpuOpPage == 0 ? 0 : 1);
Instruction result = {cpuOp, cpuOpPage};
for (int i = 0; i < numOperands; ++i) {
result.operands[i] = memoryBus.Read(opAddr++);
}
return result;
}
std::string DisassembleOp(const CpuRegisters& reg, const MemoryBus& memoryBus) {
uint16_t opAddr = reg.PC;
auto instruction = ReadInstruction(opAddr, memoryBus);
const auto& cpuOp = instruction.cpuOp;
std::string hexInstruction;
// Output instruction in hex
for (uint16_t i = 0; i < cpuOp.size; ++i)
hexInstruction += FormattedString<>("%02x", memoryBus.Read(opAddr + i));
std::string disasmInstruction, comment;
switch (cpuOp.addrMode) {
case AddressingMode::Inherent: {
// Handle specific instructions that take operands (most inherent instructions don't)
if (cpuOp.opCode == 0x1E /*EXG*/ || cpuOp.opCode == 0x1F /*TFR*/) {
uint8_t postbyte = instruction.operands[0];
uint8_t src = (postbyte >> 4) & 0b111;
uint8_t dst = postbyte & 0b111;
if (postbyte & BITS(3)) {
char* const regName[]{"A", "B", "CC", "DP"};
disasmInstruction =
FormattedString<>("%s %s,%s", cpuOp.name, regName[src], regName[dst]);
} else {
char* const regName[]{"D", "X", "Y", "U", "S", "PC"};
disasmInstruction =
FormattedString<>("%s %s,%s", cpuOp.name, regName[src], regName[dst]);
}
} else {
disasmInstruction = cpuOp.name;
}
} break;
case AddressingMode::Immediate: {
if (cpuOp.size == 2) {
auto value = instruction.operands[0];
disasmInstruction = FormattedString<>("%s #$%02x", cpuOp.name, value);
comment = FormattedString<>("(%d)", value);
} else {
auto value = CombineToU16(instruction.operands[0], instruction.operands[1]);
disasmInstruction = FormattedString<>("%s #$%04x", cpuOp.name, value);
comment = FormattedString<>("(%d)", value);
}
} break;
case AddressingMode::Extended: {
auto msb = instruction.operands[0];
auto lsb = instruction.operands[1];
uint16_t EA = CombineToU16(msb, lsb);
uint8_t value = memoryBus.Read(EA);
disasmInstruction = FormattedString<>("%s $%04x", cpuOp.name, EA);
comment = FormattedString<>("$%02x (%d)", value, value);
} break;
case AddressingMode::Direct: {
uint16_t EA = CombineToU16(reg.DP, instruction.operands[0]);
uint8_t value = memoryBus.Read(EA);
disasmInstruction = FormattedString<>("%s $%02x", cpuOp.name, instruction.operands[0]);
comment = FormattedString<>("DP:(PC) = $%02x = $%02x (%d)", EA, value, value);
} break;
case AddressingMode::Indexed: { //@TODO
disasmInstruction = cpuOp.name;
} break;
case AddressingMode::Relative: {
// Branch instruction with 8 or 16 bit signed relative offset
auto nextPC = reg.PC + cpuOp.size;
if (cpuOp.size == 2) {
auto offset = static_cast<int8_t>(instruction.operands[0]);
disasmInstruction = FormattedString<>("%s $%02x", cpuOp.name, U16(offset) & 0x00FF);
comment = FormattedString<>("(%d), PC + offset = $%04x", offset, nextPC + offset);
} else {
assert(cpuOp.size == 3);
auto offset = static_cast<int16_t>(
CombineToU16(instruction.operands[0], instruction.operands[1]));
disasmInstruction = FormattedString<>("%s $%04x", cpuOp.name, offset);
comment = FormattedString<>("(%d), PC + offset = $%04x", offset, nextPC + offset);
}
} break;
case AddressingMode::Illegal: {
case AddressingMode::Variant:
assert(false);
} break;
}
std::string result =
FormattedString<>("%-10s %-10s %s", hexInstruction.c_str(), disasmInstruction.c_str(),
comment.size() > 0 ? ("# " + comment).c_str() : "");
return result;
};
void PrintOp(const CpuRegisters& reg, const MemoryBus& memoryBus) {
std::string op = DisassembleOp(reg, memoryBus);
std::cout << FormattedString<>("[$%x] %s", reg.PC, op.c_str()) << std::endl;
}
void PrintRegisters(const CpuRegisters& reg) {
const auto& cc = reg.CC;
std::string CC = FormattedString<>(
"%c%c%c%c%c%c%c%c", cc.Carry ? 'C' : 'c', cc.Overflow ? 'V' : 'v', cc.Zero ? 'Z' : 'z',
cc.Negative ? 'N' : 'n', cc.InterruptMask ? 'I' : 'i', cc.HalfCarry ? 'H' : 'h',
cc.FastInterruptMask ? 'F' : 'f', cc.Entire ? 'E' : 'e');
std::cout << FormattedString<>("A=$%02x (%d) B=$%02x (%d) D=$%04x (%d) X=$%04x (%d) "
"Y=$%04x (%d) U=$%04x S=$%04x DP=$%02x PC=$%04x CC=%s",
reg.A, reg.A, reg.B, reg.B, reg.D, reg.D, reg.X, reg.X,
reg.Y, reg.Y, reg.U, reg.S, reg.DP, reg.PC, CC.c_str())
<< std::endl;
}
void PrintHelp() {
std::cout << "s[tep] step instruction\n"
"c[continue] continue running\n"
"info reg[isters] display register values\n"
"p[rint] <address> display value add address\n"
"q[uit] quit\n"
"h[help] display this help text\n"
<< std::flush;
}
} // namespace
void Debugger::Init(MemoryBus& memoryBus, Cpu& cpu) {
m_memoryBus = &memoryBus;
m_cpu = &cpu;
Platform::SetConsoleCtrlHandler([this] {
m_breakIntoDebugger = true;
return true;
});
}
void Debugger::Run() {
m_lastCommand = "step"; // Reasonable default
// Break on start
m_breakIntoDebugger = true;
// Enable trace when running normally
m_traceEnabled = true;
while (true) {
if (m_breakIntoDebugger) {
std::cout << FormattedString<>("$%04x (%s)>", m_cpu->Registers().PC,
m_lastCommand.c_str())
<< std::flush;
std::string input;
const auto& stream = std::getline(std::cin, input);
if (!stream) {
// getline will fail under certain conditions, like when Ctrl+C is pressed, in which
// case we just clear the stream status and restart the loop.
std::cin.clear();
std::cout << std::endl;
continue;
}
auto tokens = Tokenize(input);
// If no input, repeat last command
if (tokens.size() == 0) {
input = m_lastCommand;
tokens = Tokenize(m_lastCommand);
}
bool validCommand = true;
if (tokens.size() == 0) {
// Don't do anything (no command entered yet)
} else if (tokens[0] == "quit" || tokens[0] == "q") {
return;
} else if (tokens[0] == "help" || tokens[0] == "h") {
PrintHelp();
} else if (tokens[0] == "continue" || tokens[0] == "c") {
m_breakIntoDebugger = false;
} else if (tokens[0] == "step" || tokens[0] == "s") {
// "Step into"
PrintOp(m_cpu->Registers(), *m_memoryBus);
m_cpu->ExecuteInstruction();
} else if (tokens[0] == "info") {
if (tokens.size() > 1 && (tokens[1] == "registers" || tokens[1] == "reg")) {
PrintRegisters(m_cpu->Registers());
} else {
validCommand = false;
}
} else if (tokens[0] == "print" || tokens[0] == "p") {
if (tokens.size() > 1 && tokens[1][0] == '$') {
uint16_t address = HexStringToIntegral<uint16_t>(tokens[1].substr(1).c_str());
uint8_t value = m_memoryBus->Read(address);
std::cout << FormattedString<>("$%04x = $%02x (%d)", address, value, value)
<< std::endl;
} else {
validCommand = false;
}
} else {
validCommand = false;
}
if (validCommand) {
m_lastCommand = input;
} else {
std::cout << "Invalid command: " << input << std::endl;
}
} else {
if (m_traceEnabled)
PrintOp(m_cpu->Registers(), *m_memoryBus);
m_cpu->ExecuteInstruction();
}
}
}
<commit_msg>Disassemble indexed addressing mode instructions<commit_after>#include "Debugger.h"
#include "Cpu.h"
#include "CpuHelpers.h"
#include "CpuOpCodes.h"
#include "MemoryBus.h"
#include "Platform.h"
#include <array>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <vector>
namespace {
template <typename T>
T HexStringToIntegral(const char* s) {
std::stringstream converter(s);
T value;
converter >> std::hex >> value;
return value;
}
std::vector<std::string> Tokenize(const std::string& s) {
std::vector<std::string> result;
const char* whitespace = " \t";
size_t startIndex = 0;
while ((startIndex = s.find_first_not_of(whitespace, startIndex)) != std::string::npos) {
size_t endIndex = s.find_first_of(whitespace, startIndex + 1);
if (endIndex == std::string::npos) {
result.emplace_back(s.substr(startIndex));
break;
} else {
result.emplace_back(s.substr(startIndex, endIndex - startIndex));
startIndex = endIndex;
}
}
return result;
}
const char* GetRegisterName(const CpuRegisters& cpuRegisters, const uint8_t& r) {
ptrdiff_t offset =
reinterpret_cast<const uint8_t*>(&r) - reinterpret_cast<const uint8_t*>(&cpuRegisters);
switch (offset) {
case offsetof(CpuRegisters, A):
return "A";
case offsetof(CpuRegisters, B):
return "B";
case offsetof(CpuRegisters, DP):
return "DP";
case offsetof(CpuRegisters, CC):
return "CC";
default:
assert(false);
return "INVALID";
}
};
const char* GetRegisterName(const CpuRegisters& cpuRegisters, const uint16_t& r) {
ptrdiff_t offset =
reinterpret_cast<const uint8_t*>(&r) - reinterpret_cast<const uint8_t*>(&cpuRegisters);
switch (offset) {
case offsetof(CpuRegisters, X):
return "X";
case offsetof(CpuRegisters, Y):
return "Y";
case offsetof(CpuRegisters, U):
return "U";
case offsetof(CpuRegisters, S):
return "S";
case offsetof(CpuRegisters, PC):
return "PC";
case offsetof(CpuRegisters, D):
return "D";
default:
assert(false);
return "INVALID";
}
};
struct Instruction {
const CpuOp& cpuOp;
int page;
std::array<uint8_t, 3> operands;
};
Instruction ReadInstruction(uint16_t opAddr, const MemoryBus& memoryBus) {
int cpuOpPage = 0;
uint8_t opCodeByte = memoryBus.Read(opAddr++);
if (IsOpCodePage1(opCodeByte)) {
cpuOpPage = 1;
opCodeByte = memoryBus.Read(opAddr++);
} else if (IsOpCodePage2(opCodeByte)) {
cpuOpPage = 2;
opCodeByte = memoryBus.Read(opAddr++);
}
const auto& cpuOp = LookupCpuOpRuntime(cpuOpPage, opCodeByte);
Instruction result = {cpuOp, cpuOpPage};
// Always read max operand bytes, even if they're not used. We would want to only read as
// many operands as stipulated by the opcode's size - 1 (or 2 if not on page 0), but
// unfortunately, indexed instructions sometimes read an extra operand byte, determined
// dynamically. So for disassembling purposes, we just read 3 bytes and call it a day.
for (auto& operand : result.operands) {
operand = memoryBus.Read(opAddr++);
}
return result;
}
void DisassembleIndexedInstruction(const Instruction& instruction,
const CpuRegisters& cpuRegisters, const MemoryBus& memoryBus,
std::string& disasmInstruction, std::string& comment) {
auto RegisterSelect = [&cpuRegisters](uint8_t postbyte) -> const uint16_t& {
switch ((postbyte >> 5) & 0b11) {
case 0b00:
return cpuRegisters.X;
case 0b01:
return cpuRegisters.Y;
case 0b10:
return cpuRegisters.U;
default: // 0b11:
return cpuRegisters.S;
}
};
uint16_t EA = 0;
uint8_t postbyte = instruction.operands[0];
bool supportsIndirect = true;
std::string operands;
if ((postbyte & BITS(7)) == 0) // (+/- 4 bit offset),R
{
// postbyte is a 5 bit two's complement number we convert to 8 bit.
// So if bit 4 is set (sign bit), we extend the sign bit by turning on bits 6,7,8;
uint8_t offset = postbyte & 0b0000'1111;
if (postbyte & BITS(4))
offset |= 0b1110'0000;
auto& reg = RegisterSelect(postbyte);
EA = reg + S16(offset);
supportsIndirect = false;
operands = FormattedString<>("%d,%s", offset, GetRegisterName(cpuRegisters, reg));
comment = FormattedString<>("%d,$%04x", offset, reg);
} else {
switch (postbyte & 0b1111) {
case 0b0000: { // ,R+
auto reg = RegisterSelect(postbyte);
EA = reg;
reg += 1;
supportsIndirect = false;
operands = FormattedString<>(",%s+", GetRegisterName(cpuRegisters, reg));
comment = FormattedString<>(",$%04x", reg);
} break;
case 0b0001: { // ,R++
auto reg = RegisterSelect(postbyte);
EA = reg;
reg += 2;
operands = FormattedString<>(",%s++", GetRegisterName(cpuRegisters, reg));
comment = FormattedString<>(",$%04x", reg);
} break;
case 0b0010: { // ,-R
auto reg = RegisterSelect(postbyte);
reg -= 1;
EA = reg;
supportsIndirect = false;
operands = FormattedString<>(",-%s", GetRegisterName(cpuRegisters, reg));
comment = FormattedString<>(",$%04x", reg);
} break;
case 0b0011: { // ,--R
auto reg = RegisterSelect(postbyte);
reg -= 2;
EA = reg;
operands = FormattedString<>(",--%s", GetRegisterName(cpuRegisters, reg));
comment = FormattedString<>(",$%04x", reg);
} break;
case 0b0100: { // ,R
auto& reg = RegisterSelect(postbyte);
EA = reg;
operands = FormattedString<>(",%s", GetRegisterName(cpuRegisters, reg));
comment = FormattedString<>(",$%04x", reg);
} break;
case 0b0101: { // (+/- B),R
auto& reg = RegisterSelect(postbyte);
auto offset = S16(cpuRegisters.B);
EA = reg + offset;
operands = FormattedString<>("B,%s", GetRegisterName(cpuRegisters, reg));
comment = FormattedString<>("%d,$%04x", offset, reg);
} break;
case 0b0110: { // (+/- A),R
auto& reg = RegisterSelect(postbyte);
auto offset = S16(cpuRegisters.A);
EA = reg + offset;
operands = FormattedString<>("A,%s", GetRegisterName(cpuRegisters, reg));
comment = FormattedString<>("%d,$%04x", offset, reg);
} break;
case 0b0111:
FAIL("Illegal");
break;
case 0b1000: { // (+/- 7 bit offset),R
auto& reg = RegisterSelect(postbyte);
uint8_t postbyte2 = instruction.operands[2];
auto offset = S16(postbyte2);
EA = reg + offset;
operands = FormattedString<>("%d,%s", offset, GetRegisterName(cpuRegisters, reg));
comment = FormattedString<>("%d,$%04x", offset, reg);
} break;
case 0b1001: { // (+/- 15 bit offset),R
uint8_t postbyte2 = instruction.operands[2];
uint8_t postbyte3 = instruction.operands[3];
auto& reg = RegisterSelect(postbyte);
auto offset = CombineToS16(postbyte2, postbyte3);
EA = reg + offset;
operands = FormattedString<>("%d,%s", offset, GetRegisterName(cpuRegisters, reg));
comment = FormattedString<>("%d,$%04x", offset, reg);
} break;
case 0b1010:
FAIL("Illegal");
break;
case 0b1011: { // (+/- D),R
auto& reg = RegisterSelect(postbyte);
auto offset = S16(cpuRegisters.D);
EA = reg + offset;
operands = FormattedString<>("D,%s", GetRegisterName(cpuRegisters, reg));
comment = FormattedString<>("%d,$%04x", offset, reg);
} break;
case 0b1100: { // (+/- 7 bit offset),PC
uint8_t postbyte2 = instruction.operands[2];
auto offset = S16(postbyte2);
EA = cpuRegisters.PC + offset;
operands = FormattedString<>("%d,PC", offset);
comment = FormattedString<>("%d,$%04x", offset, cpuRegisters.PC);
} break;
case 0b1101: { // (+/- 15 bit offset),PC
uint8_t postbyte2 = instruction.operands[2];
uint8_t postbyte3 = instruction.operands[3];
auto offset = CombineToS16(postbyte2, postbyte3);
EA = cpuRegisters.PC + offset;
operands = FormattedString<>("%d,PC", offset);
comment = FormattedString<>("%d,$%04x", offset, cpuRegisters.PC);
} break;
case 0b1110:
FAIL("Illegal");
break;
case 0b1111: { // [address] (Indirect-only)
uint8_t postbyte2 = instruction.operands[2];
uint8_t postbyte3 = instruction.operands[3];
EA = CombineToS16(postbyte2, postbyte3);
} break;
default:
FAIL("Illegal");
break;
}
}
if (supportsIndirect && (postbyte & BITS(4))) {
uint8_t msb = memoryBus.Read(EA);
uint8_t lsb = memoryBus.Read(EA + 1);
EA = CombineToU16(lsb, msb);
operands = "[" + operands + "]";
}
disasmInstruction = std::string(instruction.cpuOp.name) + " " + operands;
uint8_t value = memoryBus.Read(EA);
comment += FormattedString<>(" = $%04x = $%02x (%d)", EA, value, value);
}
std::string DisassembleOp(const CpuRegisters& cpuRegisters, const MemoryBus& memoryBus) {
uint16_t opAddr = cpuRegisters.PC;
auto instruction = ReadInstruction(opAddr, memoryBus);
const auto& cpuOp = instruction.cpuOp;
std::string hexInstruction;
// Output instruction in hex
for (uint16_t i = 0; i < cpuOp.size; ++i)
hexInstruction += FormattedString<>("%02x", memoryBus.Read(opAddr + i));
std::string disasmInstruction, comment;
switch (cpuOp.addrMode) {
case AddressingMode::Inherent: {
// Handle specific instructions that take operands (most inherent instructions don't)
if (cpuOp.opCode == 0x1E /*EXG*/ || cpuOp.opCode == 0x1F /*TFR*/) {
uint8_t postbyte = instruction.operands[0];
uint8_t src = (postbyte >> 4) & 0b111;
uint8_t dst = postbyte & 0b111;
if (postbyte & BITS(3)) {
char* const regName[]{"A", "B", "CC", "DP"};
disasmInstruction =
FormattedString<>("%s %s,%s", cpuOp.name, regName[src], regName[dst]);
} else {
char* const regName[]{"D", "X", "Y", "U", "S", "PC"};
disasmInstruction =
FormattedString<>("%s %s,%s", cpuOp.name, regName[src], regName[dst]);
}
} else {
disasmInstruction = cpuOp.name;
}
} break;
case AddressingMode::Immediate: {
if (cpuOp.size == 2) {
auto value = instruction.operands[0];
disasmInstruction = FormattedString<>("%s #$%02x", cpuOp.name, value);
comment = FormattedString<>("(%d)", value);
} else {
auto value = CombineToU16(instruction.operands[0], instruction.operands[1]);
disasmInstruction = FormattedString<>("%s #$%04x", cpuOp.name, value);
comment = FormattedString<>("(%d)", value);
}
} break;
case AddressingMode::Extended: {
auto msb = instruction.operands[0];
auto lsb = instruction.operands[1];
uint16_t EA = CombineToU16(msb, lsb);
uint8_t value = memoryBus.Read(EA);
disasmInstruction = FormattedString<>("%s $%04x", cpuOp.name, EA);
comment = FormattedString<>("$%02x (%d)", value, value);
} break;
case AddressingMode::Direct: {
uint16_t EA = CombineToU16(cpuRegisters.DP, instruction.operands[0]);
uint8_t value = memoryBus.Read(EA);
disasmInstruction = FormattedString<>("%s $%02x", cpuOp.name, instruction.operands[0]);
comment = FormattedString<>("DP:(PC) = $%02x = $%02x (%d)", EA, value, value);
} break;
case AddressingMode::Indexed: {
DisassembleIndexedInstruction(instruction, cpuRegisters, memoryBus, disasmInstruction,
comment);
} break;
case AddressingMode::Relative: {
// Branch instruction with 8 or 16 bit signed relative offset
auto nextPC = cpuRegisters.PC + cpuOp.size;
if (cpuOp.size == 2) {
auto offset = static_cast<int8_t>(instruction.operands[0]);
disasmInstruction = FormattedString<>("%s $%02x", cpuOp.name, U16(offset) & 0x00FF);
comment = FormattedString<>("(%d), PC + offset = $%04x", offset, nextPC + offset);
} else {
assert(cpuOp.size == 3);
auto offset = static_cast<int16_t>(
CombineToU16(instruction.operands[0], instruction.operands[1]));
disasmInstruction = FormattedString<>("%s $%04x", cpuOp.name, offset);
comment = FormattedString<>("(%d), PC + offset = $%04x", offset, nextPC + offset);
}
} break;
case AddressingMode::Illegal: {
case AddressingMode::Variant:
assert(false);
} break;
}
std::string result =
FormattedString<>("%-10s %-10s %s", hexInstruction.c_str(), disasmInstruction.c_str(),
comment.size() > 0 ? ("# " + comment).c_str() : "");
return result;
};
void PrintOp(const CpuRegisters& cpuRegisters, const MemoryBus& memoryBus) {
std::string op = DisassembleOp(cpuRegisters, memoryBus);
std::cout << FormattedString<>("[$%x] %s", cpuRegisters.PC, op.c_str()) << std::endl;
}
void PrintRegisters(const CpuRegisters& cpuRegisters) {
const auto& cc = cpuRegisters.CC;
std::string CC = FormattedString<>(
"%c%c%c%c%c%c%c%c", cc.Carry ? 'C' : 'c', cc.Overflow ? 'V' : 'v', cc.Zero ? 'Z' : 'z',
cc.Negative ? 'N' : 'n', cc.InterruptMask ? 'I' : 'i', cc.HalfCarry ? 'H' : 'h',
cc.FastInterruptMask ? 'F' : 'f', cc.Entire ? 'E' : 'e');
const auto& r = cpuRegisters;
std::cout << FormattedString<>("A=$%02x (%d) B=$%02x (%d) D=$%04x (%d) X=$%04x (%d) "
"Y=$%04x (%d) U=$%04x S=$%04x DP=$%02x PC=$%04x CC=%s",
r.A, r.A, r.B, r.B, r.D, r.D, r.X, r.X, r.Y, r.Y, r.U, r.S,
r.DP, r.PC, CC.c_str())
<< std::endl;
}
void PrintHelp() {
std::cout << "s[tep] step instruction\n"
"c[continue] continue running\n"
"info reg[isters] display register values\n"
"p[rint] <address> display value add address\n"
"q[uit] quit\n"
"h[help] display this help text\n"
<< std::flush;
}
} // namespace
void Debugger::Init(MemoryBus& memoryBus, Cpu& cpu) {
m_memoryBus = &memoryBus;
m_cpu = &cpu;
Platform::SetConsoleCtrlHandler([this] {
m_breakIntoDebugger = true;
return true;
});
}
void Debugger::Run() {
m_lastCommand = "step"; // Reasonable default
// Break on start
m_breakIntoDebugger = true;
// Enable trace when running normally
m_traceEnabled = true;
while (true) {
if (m_breakIntoDebugger) {
std::cout << FormattedString<>("$%04x (%s)>", m_cpu->Registers().PC,
m_lastCommand.c_str())
<< std::flush;
std::string input;
const auto& stream = std::getline(std::cin, input);
if (!stream) {
// getline will fail under certain conditions, like when Ctrl+C is pressed, in which
// case we just clear the stream status and restart the loop.
std::cin.clear();
std::cout << std::endl;
continue;
}
auto tokens = Tokenize(input);
// If no input, repeat last command
if (tokens.size() == 0) {
input = m_lastCommand;
tokens = Tokenize(m_lastCommand);
}
bool validCommand = true;
if (tokens.size() == 0) {
// Don't do anything (no command entered yet)
} else if (tokens[0] == "quit" || tokens[0] == "q") {
return;
} else if (tokens[0] == "help" || tokens[0] == "h") {
PrintHelp();
} else if (tokens[0] == "continue" || tokens[0] == "c") {
m_breakIntoDebugger = false;
} else if (tokens[0] == "step" || tokens[0] == "s") {
// "Step into"
PrintOp(m_cpu->Registers(), *m_memoryBus);
m_cpu->ExecuteInstruction();
} else if (tokens[0] == "info") {
if (tokens.size() > 1 && (tokens[1] == "registers" || tokens[1] == "reg")) {
PrintRegisters(m_cpu->Registers());
} else {
validCommand = false;
}
} else if (tokens[0] == "print" || tokens[0] == "p") {
if (tokens.size() > 1 && tokens[1][0] == '$') {
uint16_t address = HexStringToIntegral<uint16_t>(tokens[1].substr(1).c_str());
uint8_t value = m_memoryBus->Read(address);
std::cout << FormattedString<>("$%04x = $%02x (%d)", address, value, value)
<< std::endl;
} else {
validCommand = false;
}
} else {
validCommand = false;
}
if (validCommand) {
m_lastCommand = input;
} else {
std::cout << "Invalid command: " << input << std::endl;
}
} else {
if (m_traceEnabled)
PrintOp(m_cpu->Registers(), *m_memoryBus);
m_cpu->ExecuteInstruction();
}
}
}
<|endoftext|>
|
<commit_before>
#include "GameCtrl.h"
#include "util/util.h"
#include <stdexcept>
#include <cstdio>
#include <chrono>
#include <cstdlib>
#ifdef _WIN32
#include <Windows.h>
#endif
using std::string;
using std::list;
// Error statements
const string GameCtrl::MSG_BAD_ALLOC = "Not enough memory to run the game.";
const string GameCtrl::MSG_LOSE = "Oops! You lose!";
const string GameCtrl::MSG_WIN = "Congratulations! You Win!";
const string GameCtrl::MSG_ESC = "Game ended.";
const string GameCtrl::MAP_INFO_FILENAME = "movements.txt";
int select_path=0; //Select Min Path or Max Path
GameCtrl::GameCtrl() {}
// class Destroyer
GameCtrl::~GameCtrl() {
delete map;
map = nullptr;
if (movementFile) {
fclose(movementFile);
movementFile = nullptr;
}
}
// Return the class instance's address
// Return instance will be used for creating and running game in main function
GameCtrl* GameCtrl::getInstance() {
=======
GameCtrl* GameCtrl::getInstance(int n) {
static GameCtrl instance;
select_path=n;
return &instance;
}
void GameCtrl::setFPS(const double fps_) {
fps = fps_;
}
// set program enable AI based search to decide next point to visit
// enableAI_(parameter) is boolean type whether the program use AI based search or not
void GameCtrl::setEnableAI(const bool enableAI_) {
enableAI = enableAI_;
}
// set program enable Hamilton search to decide next point to visit
// enableHamilton_(parameter) is boolean type whether the program use Hamilton based search or not
void GameCtrl::setEnableHamilton(const bool enableHamilton_) {
enableHamilton = enableHamilton_;
}
void GameCtrl::setMoveInterval(const long ms) {
moveInterval = ms;
}
// set program records the snake's movement in text file
// b(parameter) is boolean type whether the program record snake's movement or not
void GameCtrl::setRecordMovements(const bool b) {
recordMovements = b;
}
void GameCtrl::setRunTest(const bool b) {
runTest = b;
}
void GameCtrl::setMapRow(const SizeType n) {
mapRowCnt = n;
}
void GameCtrl::setMapCol(const SizeType n) {
mapColCnt = n;
}
// essential function to working the program. this function call init() to initialize some variables to start game
// return 0 : successfully exit game
// return 1 : error is occured during game is running
int GameCtrl::run() {
try {
init();
if (runTest) {
test();
}
while (runMainThread) {}
return 0;
} catch (const std::exception &e) {
exitGameErr(e.what());
return -1;
}
}
void GameCtrl::sleepFPS() const {
util::sleep((long)((1.0 / fps) * 1000));
}
// this function is called when the program is needed to end
// msg(parameter) contains error message
// this function use mutex lock because when a thread access critical section, other two thread must not access same crtical section.
// ex) when draw thread is errored, and at the same time , search thread is also errored,
// the first errored thread access critical section, and then search thread access critical section
void GameCtrl::exitGame(const std::string &msg) {
mutexExit.lock();
if (runMainThread) {
util::sleep(100);
runSubThread = false;
util::sleep(100);
printMsg(msg);
}
mutexExit.unlock();
runMainThread = false;
}
void GameCtrl::exitGameErr(const std::string &err) {
exitGame("ERROR: " + err);
}
void GameCtrl::printMsg(const std::string &msg) {
Console::setCursor(0, (int)mapRowCnt);
Console::writeWithColor(msg + "\n", ConsoleColor(WHITE, BLACK, true, false));
}
// this function is for moving snake one step more closer to food
// this function also use mutex lock because manually moving mode,
// user input many keys, but the process must execute move(), writeMapToFile(), CreateRandFood() one by one
void GameCtrl::moveSnake() {
mutexMove.lock();
if (map->isAllBody()) {
mutexMove.unlock();
exitGame(MSG_WIN);
} else if (snake.isDead()) {
mutexMove.unlock();
exitGame(MSG_LOSE);
} else {
try {
snake.move();
if (recordMovements && snake.getDirection() != NONE) {
writeMapToFile();
}
if (!map->hasFood()) {
map->createRandFood();
}
mutexMove.unlock();
} catch (const std::exception) {
mutexMove.unlock();
throw;
}
}
}
// this function is for writing snake's movement to text file format
void GameCtrl::writeMapToFile() const {
if (!movementFile) {
return;
}
SizeType rows = map->getRowCount();
SizeType cols = map->getColCount();
for (SizeType i = 0; i < rows; ++i) {
for (SizeType j = 0; j < cols; ++j) {
switch (map->getPoint(Pos(i, j)).getType()) {
case Point::Type::EMPTY:
fwrite(" ", sizeof(char), 2, movementFile); break;
case Point::Type::WALL:
fwrite("# ", sizeof(char), 2, movementFile); break;
case Point::Type::FOOD:
fwrite("F ", sizeof(char), 2, movementFile); break;
case Point::Type::SNAKE_HEAD:
fwrite("H ", sizeof(char), 2, movementFile); break;
case Point::Type::SNAKE_BODY:
fwrite("B ", sizeof(char), 2, movementFile); break;
case Point::Type::SNAKE_TAIL:
fwrite("T ", sizeof(char), 2, movementFile); break;
default:
break;
}
}
fwrite("\n", sizeof(char), 1, movementFile);
}
fwrite("\n", sizeof(char), 1, movementFile);
}
// this function is calling functions to initialize map and snake, and optionally calling initFiles()
void GameCtrl::init() {
Console::clear();
initMap();
if (!runTest) {
initSnake();
if (recordMovements) {
initFiles();
}
}
startThreads();
}
// this function is for initialize map
void GameCtrl::initMap() {
if (mapRowCnt < 5 || mapColCnt < 5) {
string msg = "GameCtrl.initMap(): Map size at least 5*5. Current size "
+ util::toString(mapRowCnt) + "*" + util::toString(mapColCnt) + ".";
throw std::range_error(msg.c_str());
}
map = new Map(mapRowCnt, mapColCnt);
if (!map) {
exitGameErr(MSG_BAD_ALLOC);
} else {
// Add some extra walls manully
}
}
// this function is for initialize snake and optionally call snake.hamilton search
void GameCtrl::initSnake() {
snake.setMap(map);
snake.addBody(Pos(1, 3));
snake.addBody(Pos(1, 2));
snake.addBody(Pos(1, 1));
if (enableHamilton) {
snake.enableHamilton();
}
}
// this function is for initialize movement file to record snake's movement
// initializing file's main work is write content type description to file
void GameCtrl::initFiles() {
movementFile = fopen(MAP_INFO_FILENAME.c_str(), "w");
if (!movementFile) {
throw std::runtime_error("GameCtrl.initFiles(): Fail to open file: " + MAP_INFO_FILENAME);
} else {
// Write content description to the file
string str = "Content description:\n";
str += "#: wall\nH: snake head\nB: snake body\nT: snake tail\nF: food\n\n";
str += "Movements:\n\n";
fwrite(str.c_str(), sizeof(char), str.length(), movementFile);
}
}
// this function creates three thrads which are necessary to run the game
// the three thread is drawThread, keyboardThread, moveThread
// drawThread's main work is draw map in console
// keyboardThread's main work is inputing key and calling function to move snake position
// moveThread's main work is to move snake position based on auto search methods(Hamilton, graph search, BFS)
// runSubThread is very important thing to run program. as long as this value is true, each thread is keep running and it means no error is occured.
void GameCtrl::startThreads() {
runSubThread = true;
drawThread = std::thread(&GameCtrl::draw, this);
drawThread.detach();
keyboardThread = std::thread(&GameCtrl::keyboard, this);
keyboardThread.detach();
if (!runTest) {
moveThread = std::thread(&GameCtrl::autoMove, this);
moveThread.detach();
}
}
// this function calls drawMapContent() function to draw Map
void GameCtrl::draw() {
try {
while (runSubThread) {
drawMapContent();
sleepFPS();
}
} catch (const std::exception &e) {
exitGameErr(e.what());
}
}
// this function draws Map in console according to point type
// setCursor needs x,y parameter, but when parameter is no, the default is x,y = 0 and this function just position console's cursor to write map
void GameCtrl::drawMapContent() const {
Console::setCursor();
SizeType row = map->getRowCount();
SizeType col = map->getColCount();
for (SizeType i = 0; i < row; ++i) {
for (SizeType j = 0; j < col; ++j) {
const Point &point = map->getPoint(Pos(i, j));
switch (point.getType()) {
case Point::Type::EMPTY:
Console::writeWithColor(" ", ConsoleColor(BLACK, BLACK));
break;
case Point::Type::WALL:
Console::writeWithColor(" ", ConsoleColor(WHITE, WHITE, true, true));
break;
case Point::Type::FOOD:
Console::writeWithColor(" ", ConsoleColor(YELLOW, YELLOW, true, true));
break;
case Point::Type::SNAKE_HEAD:
Console::writeWithColor(" ", ConsoleColor(RED, RED, true, true));
break;
case Point::Type::SNAKE_BODY:
Console::writeWithColor(" ", ConsoleColor(GREEN, GREEN, true, true));
break;
case Point::Type::SNAKE_TAIL:
Console::writeWithColor(" ", ConsoleColor(BLUE, BLUE, true, true));
break;
case Point::Type::TEST_VISIT:
drawTestPoint(point, ConsoleColor(BLUE, GREEN, true, true));
break;
case Point::Type::TEST_PATH:
drawTestPoint(point, ConsoleColor(BLUE, RED, true, true));
break;
default:
break;
}
}
Console::write("\n");
}
}
// this function is for drawing point in test mode
// after debugging, I notice that the code never enter the MAX_VALUE
void GameCtrl::drawTestPoint(const Point &p, const ConsoleColor &consoleColor) const {
string pointStr = "";
if (p.getDist() == Point::MAX_VALUE) {
pointStr = "In";
} else if (p.getDist() == EMPTY_VALUE) {
pointStr = " ";
} else {
Point::ValueType dist = p.getDist();
pointStr = util::toString(p.getDist());
if (dist / 10 == 0) {
pointStr.insert(0, " ");
}
}
Console::writeWithColor(pointStr, consoleColor);
}
// this function is call keyboardMove function according to key
void GameCtrl::keyboard() {
try {
while (runSubThread) {
if (Console::kbhit()) {
switch (Console::getch()) {
case 'w':
keyboardMove(snake, Direction::UP);
break;
case 'a':
keyboardMove(snake, Direction::LEFT);
break;
case 's':
keyboardMove(snake, Direction::DOWN);
break;
case 'd':
keyboardMove(snake, Direction::RIGHT);
break;
case ' ':
pause = !pause; // Pause or resume game
break;
case 27: // Esc
exitGame(MSG_ESC);
break;
default:
break;
}
}
sleepFPS();
}
} catch (const std::exception &e) {
exitGameErr(e.what());
}
}
// this function is for moving snake 1 step toward manual input key
// when pause mode, snake moves toward manual input key or
// when not pause mode and when BFS mode(not AI search mode), move snake toward input key
void GameCtrl::keyboardMove(Snake &s, const Direction d) {
if (pause) {
s.setDirection(d);
moveSnake();
} else if (!enableAI) {
if (s.getDirection() == d) {
moveSnake(); // Accelerate
} else {
s.setDirection(d);
}
}
}
// this function is for auto moving snake 1 step toward AI based search path
// snake.cpp's decideNext function is only for AI based search(hamilton, graph)
// when enableAI == False, it determine path using BFS search method.
void GameCtrl::autoMove() {
try {
while (runSubThread) {
util::sleep(moveInterval);
if (!pause) {
if (enableAI) {
snake.decideNext();
}
moveSnake();
}
}
} catch (const std::exception &e) {
exitGameErr(e.what());
}
}
// this function is for testing several tests such as Food creating test, searching minimum/maximum path test, search using Hamilton test
void GameCtrl::test() {
//testFood();
testSearch();
//testHamilton();
}
// this function is for creating food randomly test
void GameCtrl::testFood() {
SizeType cnt = 0;
while (runMainThread && cnt++ < map->getSize()) {
map->createRandFood();
sleepFPS();
}
exitGame("testFood() finished.");
}
// this function is for searching minimum/maximum path test calling snake.testMinPath
// you can choose BFS method with minimum path search or search maximum path using BFS method and extra extension algorithm.
void GameCtrl::testSearch() {
if (mapRowCnt != 20 || mapColCnt != 20) {
throw std::range_error("GameCtrl.testSearch(): Require map size 20*20.");
}
list<Direction> path;
snake.setMap(map);
// Add walls for testing
for (int i = 4; i < 16; ++i) {
map->getPoint(Pos(i, 9)).setType(Point::Type::WALL); // vertical
map->getPoint(Pos(4, i)).setType(Point::Type::WALL); // horizontal #1
map->getPoint(Pos(15, i)).setType(Point::Type::WALL); // horizontal #2
}
Pos from(6, 7);
Pos to(14, 13);
if(select_path==0) snake.testMinPath(from, to, path);
else if(select_path==1) snake.testMaxPath(from, to, path);
// Print path info
string info = "Path from " + from.toString() + " to " + to.toString()
+ " of length " + util::toString(path.size()) + ":\n";
for (const Direction &d : path) {
switch (d) {
case LEFT:
info += "L "; break;
case UP:
info += "U "; break;
case RIGHT:
info += "R "; break;
case DOWN:
info += "D "; break;
case NONE:
default:
info += "NONE "; break;
}
}
info += "\ntestSearch() finished.";
exitGame(info);
}
// this function is for testing hamilton path search
void GameCtrl::testHamilton() {
snake.setMap(map);
snake.addBody(Pos(1, 3));
snake.addBody(Pos(1, 2));
snake.addBody(Pos(1, 1));
snake.testHamilton();
exitGame("testHamilton() finished.");
}
<commit_msg>Modify direction key to code #1<commit_after>#include "GameCtrl.h"
#include "util/util.h"
#include <stdexcept>
#include <cstdio>
#include <chrono>
#include <cstdlib>
#ifdef _WIN32
#include <Windows.h>
#endif
using std::string;
using std::list;
// Error statements
const string GameCtrl::MSG_BAD_ALLOC = "Not enough memory to run the game.";
const string GameCtrl::MSG_LOSE = "Oops! You lose!";
const string GameCtrl::MSG_WIN = "Congratulations! You Win!";
const string GameCtrl::MSG_ESC = "Game ended.";
const string GameCtrl::MAP_INFO_FILENAME = "movements.txt";
int select_path=0; //Select Min Path or Max Path
GameCtrl::GameCtrl() {}
// class Destroyer
GameCtrl::~GameCtrl() {
delete map;
map = nullptr;
if (movementFile) {
fclose(movementFile);
movementFile = nullptr;
}
}
// Return the class instance's address
// Return instance will be used for creating and running game in main function
GameCtrl* GameCtrl::getInstance() {
=======
GameCtrl* GameCtrl::getInstance(int n) {
static GameCtrl instance;
select_path=n;
return &instance;
}
void GameCtrl::setFPS(const double fps_) {
fps = fps_;
}
// set program enable AI based search to decide next point to visit
// enableAI_(parameter) is boolean type whether the program use AI based search or not
void GameCtrl::setEnableAI(const bool enableAI_) {
enableAI = enableAI_;
}
// set program enable Hamilton search to decide next point to visit
// enableHamilton_(parameter) is boolean type whether the program use Hamilton based search or not
void GameCtrl::setEnableHamilton(const bool enableHamilton_) {
enableHamilton = enableHamilton_;
}
void GameCtrl::setMoveInterval(const long ms) {
moveInterval = ms;
}
// set program records the snake's movement in text file
// b(parameter) is boolean type whether the program record snake's movement or not
void GameCtrl::setRecordMovements(const bool b) {
recordMovements = b;
}
void GameCtrl::setRunTest(const bool b) {
runTest = b;
}
void GameCtrl::setMapRow(const SizeType n) {
mapRowCnt = n;
}
void GameCtrl::setMapCol(const SizeType n) {
mapColCnt = n;
}
// essential function to working the program. this function call init() to initialize some variables to start game
// return 0 : successfully exit game
// return 1 : error is occured during game is running
int GameCtrl::run() {
try {
init();
if (runTest) {
test();
}
while (runMainThread) {}
return 0;
} catch (const std::exception &e) {
exitGameErr(e.what());
return -1;
}
}
void GameCtrl::sleepFPS() const {
util::sleep((long)((1.0 / fps) * 1000));
}
// this function is called when the program is needed to end
// msg(parameter) contains error message
// this function use mutex lock because when a thread access critical section, other two thread must not access same crtical section.
// ex) when draw thread is errored, and at the same time , search thread is also errored,
// the first errored thread access critical section, and then search thread access critical section
void GameCtrl::exitGame(const std::string &msg) {
mutexExit.lock();
if (runMainThread) {
util::sleep(100);
runSubThread = false;
util::sleep(100);
printMsg(msg);
}
mutexExit.unlock();
runMainThread = false;
}
void GameCtrl::exitGameErr(const std::string &err) {
exitGame("ERROR: " + err);
}
void GameCtrl::printMsg(const std::string &msg) {
Console::setCursor(0, (int)mapRowCnt);
Console::writeWithColor(msg + "\n", ConsoleColor(WHITE, BLACK, true, false));
}
// this function is for moving snake one step more closer to food
// this function also use mutex lock because manually moving mode,
// user input many keys, but the process must execute move(), writeMapToFile(), CreateRandFood() one by one
void GameCtrl::moveSnake() {
mutexMove.lock();
if (map->isAllBody()) {
mutexMove.unlock();
exitGame(MSG_WIN);
} else if (snake.isDead()) {
mutexMove.unlock();
exitGame(MSG_LOSE);
} else {
try {
snake.move();
if (recordMovements && snake.getDirection() != NONE) {
writeMapToFile();
}
if (!map->hasFood()) {
map->createRandFood();
}
mutexMove.unlock();
} catch (const std::exception) {
mutexMove.unlock();
throw;
}
}
}
// this function is for writing snake's movement to text file format
void GameCtrl::writeMapToFile() const {
if (!movementFile) {
return;
}
SizeType rows = map->getRowCount();
SizeType cols = map->getColCount();
for (SizeType i = 0; i < rows; ++i) {
for (SizeType j = 0; j < cols; ++j) {
switch (map->getPoint(Pos(i, j)).getType()) {
case Point::Type::EMPTY:
fwrite(" ", sizeof(char), 2, movementFile); break;
case Point::Type::WALL:
fwrite("# ", sizeof(char), 2, movementFile); break;
case Point::Type::FOOD:
fwrite("F ", sizeof(char), 2, movementFile); break;
case Point::Type::SNAKE_HEAD:
fwrite("H ", sizeof(char), 2, movementFile); break;
case Point::Type::SNAKE_BODY:
fwrite("B ", sizeof(char), 2, movementFile); break;
case Point::Type::SNAKE_TAIL:
fwrite("T ", sizeof(char), 2, movementFile); break;
default:
break;
}
}
fwrite("\n", sizeof(char), 1, movementFile);
}
fwrite("\n", sizeof(char), 1, movementFile);
}
// this function is calling functions to initialize map and snake, and optionally calling initFiles()
void GameCtrl::init() {
Console::clear();
initMap();
if (!runTest) {
initSnake();
if (recordMovements) {
initFiles();
}
}
startThreads();
}
// this function is for initialize map
void GameCtrl::initMap() {
if (mapRowCnt < 5 || mapColCnt < 5) {
string msg = "GameCtrl.initMap(): Map size at least 5*5. Current size "
+ util::toString(mapRowCnt) + "*" + util::toString(mapColCnt) + ".";
throw std::range_error(msg.c_str());
}
map = new Map(mapRowCnt, mapColCnt);
if (!map) {
exitGameErr(MSG_BAD_ALLOC);
} else {
// Add some extra walls manully
}
}
// this function is for initialize snake and optionally call snake.hamilton search
void GameCtrl::initSnake() {
snake.setMap(map);
snake.addBody(Pos(1, 3));
snake.addBody(Pos(1, 2));
snake.addBody(Pos(1, 1));
if (enableHamilton) {
snake.enableHamilton();
}
}
// this function is for initialize movement file to record snake's movement
// initializing file's main work is write content type description to file
void GameCtrl::initFiles() {
movementFile = fopen(MAP_INFO_FILENAME.c_str(), "w");
if (!movementFile) {
throw std::runtime_error("GameCtrl.initFiles(): Fail to open file: " + MAP_INFO_FILENAME);
} else {
// Write content description to the file
string str = "Content description:\n";
str += "#: wall\nH: snake head\nB: snake body\nT: snake tail\nF: food\n\n";
str += "Movements:\n\n";
fwrite(str.c_str(), sizeof(char), str.length(), movementFile);
}
}
// this function creates three thrads which are necessary to run the game
// the three thread is drawThread, keyboardThread, moveThread
// drawThread's main work is draw map in console
// keyboardThread's main work is inputing key and calling function to move snake position
// moveThread's main work is to move snake position based on auto search methods(Hamilton, graph search, BFS)
// runSubThread is very important thing to run program. as long as this value is true, each thread is keep running and it means no error is occured.
void GameCtrl::startThreads() {
runSubThread = true;
drawThread = std::thread(&GameCtrl::draw, this);
drawThread.detach();
keyboardThread = std::thread(&GameCtrl::keyboard, this);
keyboardThread.detach();
if (!runTest) {
moveThread = std::thread(&GameCtrl::autoMove, this);
moveThread.detach();
}
}
// this function calls drawMapContent() function to draw Map
void GameCtrl::draw() {
try {
while (runSubThread) {
drawMapContent();
sleepFPS();
}
} catch (const std::exception &e) {
exitGameErr(e.what());
}
}
// this function draws Map in console according to point type
// setCursor needs x,y parameter, but when parameter is no, the default is x,y = 0 and this function just position console's cursor to write map
void GameCtrl::drawMapContent() const {
Console::setCursor();
SizeType row = map->getRowCount();
SizeType col = map->getColCount();
for (SizeType i = 0; i < row; ++i) {
for (SizeType j = 0; j < col; ++j) {
const Point &point = map->getPoint(Pos(i, j));
switch (point.getType()) {
case Point::Type::EMPTY:
Console::writeWithColor(" ", ConsoleColor(BLACK, BLACK));
break;
case Point::Type::WALL:
Console::writeWithColor(" ", ConsoleColor(WHITE, WHITE, true, true));
break;
case Point::Type::FOOD:
Console::writeWithColor(" ", ConsoleColor(YELLOW, YELLOW, true, true));
break;
case Point::Type::SNAKE_HEAD:
Console::writeWithColor(" ", ConsoleColor(RED, RED, true, true));
break;
case Point::Type::SNAKE_BODY:
Console::writeWithColor(" ", ConsoleColor(GREEN, GREEN, true, true));
break;
case Point::Type::SNAKE_TAIL:
Console::writeWithColor(" ", ConsoleColor(BLUE, BLUE, true, true));
break;
case Point::Type::TEST_VISIT:
drawTestPoint(point, ConsoleColor(BLUE, GREEN, true, true));
break;
case Point::Type::TEST_PATH:
drawTestPoint(point, ConsoleColor(BLUE, RED, true, true));
break;
default:
break;
}
}
Console::write("\n");
}
}
// this function is for drawing point in test mode
// after debugging, I notice that the code never enter the MAX_VALUE
void GameCtrl::drawTestPoint(const Point &p, const ConsoleColor &consoleColor) const {
string pointStr = "";
if (p.getDist() == Point::MAX_VALUE) {
pointStr = "In";
} else if (p.getDist() == EMPTY_VALUE) {
pointStr = " ";
} else {
Point::ValueType dist = p.getDist();
pointStr = util::toString(p.getDist());
if (dist / 10 == 0) {
pointStr.insert(0, " ");
}
}
Console::writeWithColor(pointStr, consoleColor);
}
// this function is call keyboardMove function according to key
void GameCtrl::keyboard() {
try {
while (runSubThread) {
if (Console::kbhit()) {
switch (Console::getch()) {
case 'w':
keyboardMove(snake, Direction::UP);
break;
case 'a':
keyboardMove(snake, Direction::LEFT);
break;
case 's':
keyboardMove(snake, Direction::DOWN);
break;
case 'd':
keyboardMove(snake, Direction::RIGHT);
break;
case ' ':
pause = !pause; // Pause or resume game
break;
case 27: // Esc
exitGame(MSG_ESC);
break;
default:
break;
}
}
sleepFPS();
}
} catch (const std::exception &e) {
exitGameErr(e.what());
}
}
// this function is for moving snake 1 step toward manual input key
// when pause mode, snake moves toward manual input key or
// when not pause mode and when BFS mode(not AI search mode), move snake toward input key
void GameCtrl::keyboardMove(Snake &s, const Direction d) {
if (pause) {
s.setDirection(d);
moveSnake();
} else if (!enableAI) {
if (s.getDirection() == d) {
moveSnake(); // Accelerate
} else {
s.setDirection(d);
}
}
}
// this function is for auto moving snake 1 step toward AI based search path
// snake.cpp's decideNext function is only for AI based search(hamilton, graph)
// when enableAI == False, it determine path using BFS search method.
void GameCtrl::autoMove() {
try {
while (runSubThread) {
util::sleep(moveInterval);
if (!pause) {
if (enableAI) {
snake.decideNext();
}
moveSnake();
}
}
} catch (const std::exception &e) {
exitGameErr(e.what());
}
}
// this function is for testing several tests such as Food creating test, searching minimum/maximum path test, search using Hamilton test
void GameCtrl::test() {
//testFood();
testSearch();
//testHamilton();
}
// this function is for creating food randomly test
void GameCtrl::testFood() {
SizeType cnt = 0;
while (runMainThread && cnt++ < map->getSize()) {
map->createRandFood();
sleepFPS();
}
exitGame("testFood() finished.");
}
// this function is for searching minimum/maximum path test calling snake.testMinPath
// you can choose BFS method with minimum path search or search maximum path using BFS method and extra extension algorithm.
void GameCtrl::testSearch() {
if (mapRowCnt != 20 || mapColCnt != 20) {
throw std::range_error("GameCtrl.testSearch(): Require map size 20*20.");
}
list<Direction> path;
snake.setMap(map);
// Add walls for testing
for (int i = 4; i < 16; ++i) {
map->getPoint(Pos(i, 9)).setType(Point::Type::WALL); // vertical
map->getPoint(Pos(4, i)).setType(Point::Type::WALL); // horizontal #1
map->getPoint(Pos(15, i)).setType(Point::Type::WALL); // horizontal #2
}
Pos from(6, 7);
Pos to(14, 13);
if(select_path==0) snake.testMinPath(from, to, path);
else if(select_path==1) snake.testMaxPath(from, to, path);
// Print path info
string info = "Path from " + from.toString() + " to " + to.toString()
+ " of length " + util::toString(path.size()) + ":\n";
for (const Direction &d : path) {
switch (d) {
case LEFT:
info += "L "; break;
case UP:
info += "U "; break;
case RIGHT:
info += "R "; break;
case DOWN:
info += "D "; break;
case NONE:
default:
info += "NONE "; break;
}
}
info += "\ntestSearch() finished.";
exitGame(info);
}
// this function is for testing hamilton path search
void GameCtrl::testHamilton() {
snake.setMap(map);
snake.addBody(Pos(1, 3));
snake.addBody(Pos(1, 2));
snake.addBody(Pos(1, 1));
snake.testHamilton();
exitGame("testHamilton() finished.");
}
<|endoftext|>
|
<commit_before>#include <limits>
#include <iostream>
#include <iomanip>
#include <unistd.h>
#include <libpstack/util.h>
#include <libpstack/elf.h>
#include <algorithm>
using std::string;
using std::make_shared;
using std::shared_ptr;
std::ostream *debug;
static uint32_t elf_hash(string);
bool noDebugLibs;
GlobalDebugDirectories globalDebugDirectories;
GlobalDebugDirectories::GlobalDebugDirectories()
{
add("/usr/lib/debug");
add("/usr/lib/debug/usr"); // Add as a hack for when linker loads from /lib, but package has /usr/lib
}
void
GlobalDebugDirectories::add(const std::string &str)
{
dirs.push_back(str);
}
ElfNoteIter
ElfNotes::begin() const
{
return ElfNoteIter(object, object->getSegments().begin());
}
ElfNoteIter
ElfNotes::end() const
{
return ElfNoteIter(object, object->getSegments().end());
}
std::string
ElfNoteDesc::name() const
{
char *buf = new char[note.n_namesz + 1];
object->io->readObj(offset + sizeof note, buf, note.n_namesz);
buf[note.n_namesz] = 0;
std::string s = buf;
delete[] buf;
return s;
}
const unsigned char *
ElfNoteDesc::data() const
{
if (databuf == 0) {
databuf = new unsigned char[note.n_descsz];
object->io->readObj(roundup2(offset + sizeof note + note.n_namesz, 4),
databuf, note.n_descsz);
}
return databuf;
}
size_t
ElfNoteDesc::size() const
{
return note.n_descsz;
}
/*
* Parse out an ELF file into an ElfObject structure.
*/
const Elf_Phdr *
ElfObject::findHeaderForAddress(Elf_Off a) const
{
for (auto &hdr : programHeaders)
if (hdr.p_vaddr <= a && hdr.p_vaddr + hdr.p_memsz > a && hdr.p_type == PT_LOAD)
return &hdr;
return 0;
}
ElfObject::ElfObject(const string &name_)
: name(name_)
, notes(this)
{
init(make_shared<CacheReader>(make_shared<FileReader>(name)));
}
ElfObject::ElfObject(shared_ptr<Reader> io_)
: notes(this)
{
name = io_->describe();
init(io_);
}
Elf_Addr
ElfObject::getBase() const
{
auto base = std::numeric_limits<Elf_Off>::max();
auto &segments = getSegments();
for (auto &seg : segments)
if (seg.p_type == PT_LOAD && Elf_Off(seg.p_vaddr) <= base)
base = Elf_Off(seg.p_vaddr);
return base;
}
std::string
ElfObject::getInterpreter() const
{
for (auto &seg : getSegments())
if (seg.p_type == PT_INTERP)
return io->readString(seg.p_offset);
return "";
}
void
ElfObject::init(const shared_ptr<Reader> &io_)
{
debugLoaded = false;
io = io_;
int i;
size_t off;
io->readObj(0, &elfHeader);
/* Validate the ELF header */
if (!IS_ELF(elfHeader) || elfHeader.e_ident[EI_VERSION] != EV_CURRENT)
throw Exception() << io->describe() << ": content is not an ELF image";
for (off = elfHeader.e_phoff, i = 0; i < elfHeader.e_phnum; i++) {
programHeaders.push_back(Elf_Phdr());
io->readObj(off, &programHeaders.back());
off += elfHeader.e_phentsize;
}
for (off = elfHeader.e_shoff, i = 0; i < elfHeader.e_shnum; i++) {
sectionHeaders.push_back(Elf_Shdr());
io->readObj(off, §ionHeaders.back());
off += elfHeader.e_shentsize;
}
if (elfHeader.e_shstrndx != SHN_UNDEF) {
auto sshdr = sectionHeaders[elfHeader.e_shstrndx];
for (auto &h : sectionHeaders) {
auto name = io->readString(sshdr.sh_offset + h.sh_name);
namedSection[name] = &h;
}
auto tab = getSection(".hash", SHT_HASH);
if (tab)
hash.reset(new ElfSymHash(tab));
} else {
hash = 0;
}
}
std::pair<const Elf_Sym, const string>
SymbolIterator::operator *()
{
Elf_Sym sym;
io->readObj(off, &sym);
string name = io->readString(sym.st_name + stroff);
return std::make_pair(sym, name);
}
/*
* Find the symbol that represents a particular address.
* If we fail to find a symbol whose virtual range includes our target address
* we will accept a symbol with the highest address less than or equal to our
* target. This allows us to match the dynamic "stubs" in code.
* A side-effect is a few false-positives: A stripped, dynamically linked,
* executable will typically report functions as being "_init", because it is
* the only symbol in the image, and it has no size.
*/
bool
ElfObject::findSymbolByAddress(Elf_Addr addr, int type, Elf_Sym &sym, string &name)
{
/* Try to find symbols in these sections */
static const char *sectionNames[] = {
".symtab", ".dynsym", 0
};
bool exact = false;
Elf_Addr lowest = 0;
for (size_t i = 0; sectionNames[i] && !exact; i++) {
const auto symSection = getSection(sectionNames[i], SHT_NULL);
if (symSection == 0 || symSection->sh_type == SHT_NOBITS)
continue;
SymbolSection syms(symSection);
for (auto syminfo : syms) {
auto &candidate = syminfo.first;
if (candidate.st_shndx >= sectionHeaders.size())
continue;
auto shdr = sectionHeaders[candidate.st_shndx];
if (!(shdr.sh_flags & SHF_ALLOC))
continue;
if (type != STT_NOTYPE && ELF_ST_TYPE(candidate.st_info) != type)
continue;
if (candidate.st_value > addr)
continue;
if (candidate.st_size) {
// symbol has a size: we can check if our address lies within it.
if (candidate.st_size + candidate.st_value > addr) {
// yep: return this one.
sym = candidate;
name = syminfo.second;
return true;
}
} else if (lowest < candidate.st_value) {
/*
* No size, but hold on to it as a possibility. We'll return
* the symbol with the highest value not aabove the required
* value
*/
sym = candidate;
name = syminfo.second;
lowest = candidate.st_value;
}
}
}
return lowest != 0;
}
const ElfSection
ElfObject::getSection(const std::string &name, Elf_Word type)
{
auto s = namedSection.find(name);
return ElfSection(*this, s != namedSection.end() && (s->second->sh_type == type || type == SHT_NULL) ? s->second : 0);
}
SymbolSection
ElfObject::getSymbols(const std::string &table)
{
return SymbolSection(getSection(table, SHT_NULL));
}
bool
linearSymSearch(ElfSection §ion, const string &name, Elf_Sym &sym)
{
SymbolSection sec(section);
for (const auto &info : sec) {
if (name == info.second) {
sym = info.first;
return true;
}
}
return false;
}
ElfSymHash::ElfSymHash(ElfSection &hash_)
: hash(hash_)
, syms(hash.obj, hash.getLink())
{
// read the hash table into local memory.
size_t words = hash->sh_size / sizeof (Elf_Word);
data.resize(words);
hash.obj.io->readObj(hash->sh_offset, &data[0], words);
nbucket = data[0];
nchain = data[1];
buckets = &data[0] + 2;
chains = buckets + nbucket;
strings = syms.getLink()->sh_offset;
}
bool
ElfSymHash::findSymbol(Elf_Sym &sym, const string &name)
{
uint32_t bucket = elf_hash(name) % nbucket;
for (Elf_Word i = buckets[bucket]; i != STN_UNDEF; i = chains[i]) {
Elf_Sym candidate;
syms.obj.io->readObj(syms->sh_offset + i * sizeof candidate, &candidate);
string candidateName = syms.obj.io->readString(strings + candidate.st_name);
if (candidateName == name) {
sym = candidate;
return true;
}
}
return false;
}
/*
* Locate a named symbol in an ELF image.
*/
bool
ElfObject::findSymbolByName(const string &name, Elf_Sym &sym)
{
if (hash && hash->findSymbol(sym, name))
return true;
auto dyn = getSection(".dynsym", SHT_DYNSYM);
if (dyn && linearSymSearch(dyn, name, sym))
return true;
auto symtab = getSection(".symtab", SHT_SYMTAB);
return symtab && linearSymSearch(symtab, name, sym);
}
/*
* Get the data and length from a specific "note" in the ELF file
*/
#ifdef __FreeBSD__
/*
* Try to work out the name of the executable from a core file
* XXX: This is not particularly useful, because the pathname appears to get
* stripped.
*/
static enum NoteIter
elfImageNote(void *cookie, const char *name, u_int32_t type,
const void *data, size_t len)
{
const char **exename;
const prpsinfo_t *psinfo;
exename = (const char **)cookie;
psinfo = (const prpsinfo_t *)data;
if (!strcmp(name, "FreeBSD") && type == NT_PRPSINFO &&
psinfo->pr_version == PRPSINFO_VERSION) {
*exename = psinfo->pr_fname;
return NOTE_DONE;
}
return NOTE_CONTIN;
}
#endif
ElfObject::~ElfObject()
{
}
std::shared_ptr<ElfObject>
ElfObject::getDebug(std::shared_ptr<ElfObject> &in)
{
auto sp = in->getDebug();
return sp ? sp : in;
}
static std::shared_ptr<ElfObject>
tryLoad(const std::string &name) {
// XXX: verify checksum.
for (auto dir : globalDebugDirectories.dirs) {
try {
auto debugObject = make_shared<ElfObject>(dir + "/" + name);
return debugObject;
}
catch (const std::exception &ex) {
continue;
}
}
return std::shared_ptr<ElfObject>();
}
std::shared_ptr<ElfObject>
ElfObject::getDebug()
{
if (noDebugLibs)
return std::shared_ptr<ElfObject>();
if (!debugLoaded) {
debugLoaded = true;
if (debug) {
for (auto note : notes) {
if (note.name() == "GNU" && note.type() == GNU_BUILD_ID) {
*debug << "GNU buildID: ";
auto data = note.data();
for (size_t i = 0; i < note.size(); ++i)
*debug << std::hex << std::setw(2) << std::setfill('0') << int(data[i]);
*debug << "\n";
break;
}
}
}
std::ostringstream stream;
stream << io->describe();
std::string oldname = stream.str();
auto hdr = getSection(".gnu_debuglink", SHT_PROGBITS);
if (hdr == 0)
return std::shared_ptr<ElfObject>();
std::vector<char> buf(hdr->sh_size);
std::string link = io->readString(hdr->sh_offset);
auto dir = dirname(oldname);
debugObject = tryLoad(dir + "/" + link);
if (!debugObject) {
for (auto note : notes) {
if (note.name() == "GNU" && note.type() == GNU_BUILD_ID) {
std::ostringstream dir;
dir << ".build-id/";
size_t i;
auto data = note.data();
dir << std::hex << std::setw(2) << std::setfill('0') << int(data[0]);
dir << "/";
for (i = 1; i < note.size(); ++i)
dir << std::hex << std::setw(2) << std::setfill('0') << int(data[i]);
dir << ".debug";
debugObject = tryLoad(dir.str());
break;
}
}
}
}
return debugObject;
}
/*
* Culled from System V Application Binary Interface
*/
static uint32_t
elf_hash(string name)
{
uint32_t h = 0, g;
for (auto c : name) {
h = (h << 4) + c;
if ((g = h & 0xf0000000) != 0)
h ^= g >> 24;
h &= ~g;
}
return (h);
}
const Elf_Shdr *ElfSection::getLink() const
{
return &obj.sectionHeaders[shdr->sh_link];
}
<commit_msg>Show name of lib we calculate gnu hash for<commit_after>#include <limits>
#include <iostream>
#include <iomanip>
#include <unistd.h>
#include <libpstack/util.h>
#include <libpstack/elf.h>
#include <algorithm>
using std::string;
using std::make_shared;
using std::shared_ptr;
std::ostream *debug;
static uint32_t elf_hash(string);
bool noDebugLibs;
GlobalDebugDirectories globalDebugDirectories;
GlobalDebugDirectories::GlobalDebugDirectories()
{
add("/usr/lib/debug");
add("/usr/lib/debug/usr"); // Add as a hack for when linker loads from /lib, but package has /usr/lib
}
void
GlobalDebugDirectories::add(const std::string &str)
{
dirs.push_back(str);
}
ElfNoteIter
ElfNotes::begin() const
{
return ElfNoteIter(object, object->getSegments().begin());
}
ElfNoteIter
ElfNotes::end() const
{
return ElfNoteIter(object, object->getSegments().end());
}
std::string
ElfNoteDesc::name() const
{
char *buf = new char[note.n_namesz + 1];
object->io->readObj(offset + sizeof note, buf, note.n_namesz);
buf[note.n_namesz] = 0;
std::string s = buf;
delete[] buf;
return s;
}
const unsigned char *
ElfNoteDesc::data() const
{
if (databuf == 0) {
databuf = new unsigned char[note.n_descsz];
object->io->readObj(roundup2(offset + sizeof note + note.n_namesz, 4),
databuf, note.n_descsz);
}
return databuf;
}
size_t
ElfNoteDesc::size() const
{
return note.n_descsz;
}
/*
* Parse out an ELF file into an ElfObject structure.
*/
const Elf_Phdr *
ElfObject::findHeaderForAddress(Elf_Off a) const
{
for (auto &hdr : programHeaders)
if (hdr.p_vaddr <= a && hdr.p_vaddr + hdr.p_memsz > a && hdr.p_type == PT_LOAD)
return &hdr;
return 0;
}
ElfObject::ElfObject(const string &name_)
: name(name_)
, notes(this)
{
init(make_shared<CacheReader>(make_shared<FileReader>(name)));
}
ElfObject::ElfObject(shared_ptr<Reader> io_)
: notes(this)
{
name = io_->describe();
init(io_);
}
Elf_Addr
ElfObject::getBase() const
{
auto base = std::numeric_limits<Elf_Off>::max();
auto &segments = getSegments();
for (auto &seg : segments)
if (seg.p_type == PT_LOAD && Elf_Off(seg.p_vaddr) <= base)
base = Elf_Off(seg.p_vaddr);
return base;
}
std::string
ElfObject::getInterpreter() const
{
for (auto &seg : getSegments())
if (seg.p_type == PT_INTERP)
return io->readString(seg.p_offset);
return "";
}
void
ElfObject::init(const shared_ptr<Reader> &io_)
{
debugLoaded = false;
io = io_;
int i;
size_t off;
io->readObj(0, &elfHeader);
/* Validate the ELF header */
if (!IS_ELF(elfHeader) || elfHeader.e_ident[EI_VERSION] != EV_CURRENT)
throw Exception() << io->describe() << ": content is not an ELF image";
for (off = elfHeader.e_phoff, i = 0; i < elfHeader.e_phnum; i++) {
programHeaders.push_back(Elf_Phdr());
io->readObj(off, &programHeaders.back());
off += elfHeader.e_phentsize;
}
for (off = elfHeader.e_shoff, i = 0; i < elfHeader.e_shnum; i++) {
sectionHeaders.push_back(Elf_Shdr());
io->readObj(off, §ionHeaders.back());
off += elfHeader.e_shentsize;
}
if (elfHeader.e_shstrndx != SHN_UNDEF) {
auto sshdr = sectionHeaders[elfHeader.e_shstrndx];
for (auto &h : sectionHeaders) {
auto name = io->readString(sshdr.sh_offset + h.sh_name);
namedSection[name] = &h;
}
auto tab = getSection(".hash", SHT_HASH);
if (tab)
hash.reset(new ElfSymHash(tab));
} else {
hash = 0;
}
}
std::pair<const Elf_Sym, const string>
SymbolIterator::operator *()
{
Elf_Sym sym;
io->readObj(off, &sym);
string name = io->readString(sym.st_name + stroff);
return std::make_pair(sym, name);
}
/*
* Find the symbol that represents a particular address.
* If we fail to find a symbol whose virtual range includes our target address
* we will accept a symbol with the highest address less than or equal to our
* target. This allows us to match the dynamic "stubs" in code.
* A side-effect is a few false-positives: A stripped, dynamically linked,
* executable will typically report functions as being "_init", because it is
* the only symbol in the image, and it has no size.
*/
bool
ElfObject::findSymbolByAddress(Elf_Addr addr, int type, Elf_Sym &sym, string &name)
{
/* Try to find symbols in these sections */
static const char *sectionNames[] = {
".symtab", ".dynsym", 0
};
bool exact = false;
Elf_Addr lowest = 0;
for (size_t i = 0; sectionNames[i] && !exact; i++) {
const auto symSection = getSection(sectionNames[i], SHT_NULL);
if (symSection == 0 || symSection->sh_type == SHT_NOBITS)
continue;
SymbolSection syms(symSection);
for (auto syminfo : syms) {
auto &candidate = syminfo.first;
if (candidate.st_shndx >= sectionHeaders.size())
continue;
auto shdr = sectionHeaders[candidate.st_shndx];
if (!(shdr.sh_flags & SHF_ALLOC))
continue;
if (type != STT_NOTYPE && ELF_ST_TYPE(candidate.st_info) != type)
continue;
if (candidate.st_value > addr)
continue;
if (candidate.st_size) {
// symbol has a size: we can check if our address lies within it.
if (candidate.st_size + candidate.st_value > addr) {
// yep: return this one.
sym = candidate;
name = syminfo.second;
return true;
}
} else if (lowest < candidate.st_value) {
/*
* No size, but hold on to it as a possibility. We'll return
* the symbol with the highest value not aabove the required
* value
*/
sym = candidate;
name = syminfo.second;
lowest = candidate.st_value;
}
}
}
return lowest != 0;
}
const ElfSection
ElfObject::getSection(const std::string &name, Elf_Word type)
{
auto s = namedSection.find(name);
return ElfSection(*this, s != namedSection.end() && (s->second->sh_type == type || type == SHT_NULL) ? s->second : 0);
}
SymbolSection
ElfObject::getSymbols(const std::string &table)
{
return SymbolSection(getSection(table, SHT_NULL));
}
bool
linearSymSearch(ElfSection §ion, const string &name, Elf_Sym &sym)
{
SymbolSection sec(section);
for (const auto &info : sec) {
if (name == info.second) {
sym = info.first;
return true;
}
}
return false;
}
ElfSymHash::ElfSymHash(ElfSection &hash_)
: hash(hash_)
, syms(hash.obj, hash.getLink())
{
// read the hash table into local memory.
size_t words = hash->sh_size / sizeof (Elf_Word);
data.resize(words);
hash.obj.io->readObj(hash->sh_offset, &data[0], words);
nbucket = data[0];
nchain = data[1];
buckets = &data[0] + 2;
chains = buckets + nbucket;
strings = syms.getLink()->sh_offset;
}
bool
ElfSymHash::findSymbol(Elf_Sym &sym, const string &name)
{
uint32_t bucket = elf_hash(name) % nbucket;
for (Elf_Word i = buckets[bucket]; i != STN_UNDEF; i = chains[i]) {
Elf_Sym candidate;
syms.obj.io->readObj(syms->sh_offset + i * sizeof candidate, &candidate);
string candidateName = syms.obj.io->readString(strings + candidate.st_name);
if (candidateName == name) {
sym = candidate;
return true;
}
}
return false;
}
/*
* Locate a named symbol in an ELF image.
*/
bool
ElfObject::findSymbolByName(const string &name, Elf_Sym &sym)
{
if (hash && hash->findSymbol(sym, name))
return true;
auto dyn = getSection(".dynsym", SHT_DYNSYM);
if (dyn && linearSymSearch(dyn, name, sym))
return true;
auto symtab = getSection(".symtab", SHT_SYMTAB);
return symtab && linearSymSearch(symtab, name, sym);
}
/*
* Get the data and length from a specific "note" in the ELF file
*/
#ifdef __FreeBSD__
/*
* Try to work out the name of the executable from a core file
* XXX: This is not particularly useful, because the pathname appears to get
* stripped.
*/
static enum NoteIter
elfImageNote(void *cookie, const char *name, u_int32_t type,
const void *data, size_t len)
{
const char **exename;
const prpsinfo_t *psinfo;
exename = (const char **)cookie;
psinfo = (const prpsinfo_t *)data;
if (!strcmp(name, "FreeBSD") && type == NT_PRPSINFO &&
psinfo->pr_version == PRPSINFO_VERSION) {
*exename = psinfo->pr_fname;
return NOTE_DONE;
}
return NOTE_CONTIN;
}
#endif
ElfObject::~ElfObject()
{
}
std::shared_ptr<ElfObject>
ElfObject::getDebug(std::shared_ptr<ElfObject> &in)
{
auto sp = in->getDebug();
return sp ? sp : in;
}
static std::shared_ptr<ElfObject>
tryLoad(const std::string &name) {
// XXX: verify checksum.
for (auto dir : globalDebugDirectories.dirs) {
try {
auto debugObject = make_shared<ElfObject>(dir + "/" + name);
return debugObject;
}
catch (const std::exception &ex) {
continue;
}
}
return std::shared_ptr<ElfObject>();
}
std::shared_ptr<ElfObject>
ElfObject::getDebug()
{
if (noDebugLibs)
return std::shared_ptr<ElfObject>();
if (!debugLoaded) {
debugLoaded = true;
if (debug) {
for (auto note : notes) {
if (note.name() == "GNU" && note.type() == GNU_BUILD_ID) {
*debug << "GNU buildID for " << io->describe() << ": ";
auto data = note.data();
for (size_t i = 0; i < note.size(); ++i)
*debug << std::hex << std::setw(2) << std::setfill('0') << int(data[i]);
*debug << "\n";
break;
}
}
}
std::ostringstream stream;
stream << io->describe();
std::string oldname = stream.str();
auto hdr = getSection(".gnu_debuglink", SHT_PROGBITS);
if (hdr == 0)
return std::shared_ptr<ElfObject>();
std::vector<char> buf(hdr->sh_size);
std::string link = io->readString(hdr->sh_offset);
auto dir = dirname(oldname);
debugObject = tryLoad(dir + "/" + link);
if (!debugObject) {
for (auto note : notes) {
if (note.name() == "GNU" && note.type() == GNU_BUILD_ID) {
std::ostringstream dir;
dir << ".build-id/";
size_t i;
auto data = note.data();
dir << std::hex << std::setw(2) << std::setfill('0') << int(data[0]);
dir << "/";
for (i = 1; i < note.size(); ++i)
dir << std::hex << std::setw(2) << std::setfill('0') << int(data[i]);
dir << ".debug";
debugObject = tryLoad(dir.str());
break;
}
}
}
}
return debugObject;
}
/*
* Culled from System V Application Binary Interface
*/
static uint32_t
elf_hash(string name)
{
uint32_t h = 0, g;
for (auto c : name) {
h = (h << 4) + c;
if ((g = h & 0xf0000000) != 0)
h ^= g >> 24;
h &= ~g;
}
return (h);
}
const Elf_Shdr *ElfSection::getLink() const
{
return &obj.sectionHeaders[shdr->sh_link];
}
<|endoftext|>
|
<commit_before>/**
* A class which describes the properties of a MySQL database connection.
*
* @date Jul 21, 2013
* @author Joeri HERMANS
* @version 0.1
*
* Copyright 2013 Joeri HERMANS
*
* 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.
*/
// BEGIN Includes. ///////////////////////////////////////////////////
// System dependencies.
#include <assert.h>
#include <stdio.h>
#include <syslog.h>
// Application dependencies.
#include <ias/database/interface/database_connection.h>
#include <ias/database/mysql/mysql_connection.h>
#include <ias/database/mysql/mysql_statement.h>
#include <ias/database/mysql/mysql_driver.h>
// END Includes. /////////////////////////////////////////////////////
inline void MySqlConnection::initialize( void ) {
// Initialize the members of the class.
mConnection = mysql_init( nullptr );
}
MySqlConnection::MySqlConnection( const std::string & username,
const std::string & password,
const std::string & schema,
const std::string & host )
: DatabaseConnection(username,password,schema,host) {
// Nothing to do here.
initialize();
}
MySqlConnection::~MySqlConnection( void ) {
mysql_close( mConnection );
mysql_library_end();
}
bool MySqlConnection::isConnected( void ) const
{
return ( mConnection != nullptr );
}
bool MySqlConnection::connect( void ) {
bool connected;
my_bool argument;
// Enable automatic reconnection by default.
argument = 1;
// Enable the automatic reconnect option.
mysql_options(mConnection,MYSQL_OPT_RECONNECT,&argument);
// Try to connect to the MySQL server.
connected = ( mysql_real_connect(mConnection,
getHost().c_str(),
getUsername().c_str(),
getPassword().c_str(),
getSchema().c_str(),
3306,nullptr,0) != nullptr );
return ( connected );
}
DatabaseStatement * MySqlConnection::createStatement( const std::string & sql ) {
DatabaseStatement * statement;
// Checking the precondition.
assert( sql.length() > 0 );
// // Check if the connection with the server is still active.
// if( mysql_ping(mConnection) == 0 )
// Allocate a new mysql statement.
statement = new MySqlStatement(this,sql);
// else
// No statement should be allocated.
// statement = nullptr;
return ( statement );
}
DatabasePreparedStatement * MySqlConnection::prepareStatement(
const std::string & sql ) {
// Checking the precondition.
assert( sql.length() > 0 );
// TODO Implement.
return ( nullptr );
}
void * MySqlConnection::getLink( void )
{
return ( static_cast<void *>(mConnection) );
}
<commit_msg>Add debugging information.<commit_after>/**
* A class which describes the properties of a MySQL database connection.
*
* @date Jul 21, 2013
* @author Joeri HERMANS
* @version 0.1
*
* Copyright 2013 Joeri HERMANS
*
* 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.
*/
// BEGIN Includes. ///////////////////////////////////////////////////
// System dependencies.
#include <cassert>
#include <cstdio>
#include <syslog.h>
#include <iostream>
// Application dependencies.
#include <ias/database/interface/database_connection.h>
#include <ias/database/mysql/mysql_connection.h>
#include <ias/database/mysql/mysql_statement.h>
#include <ias/database/mysql/mysql_driver.h>
// END Includes. /////////////////////////////////////////////////////
inline void MySqlConnection::initialize( void ) {
// Initialize the members of the class.
mConnection = mysql_init( nullptr );
}
MySqlConnection::MySqlConnection( const std::string & username,
const std::string & password,
const std::string & schema,
const std::string & host )
: DatabaseConnection(username,password,schema,host) {
// Nothing to do here.
initialize();
}
MySqlConnection::~MySqlConnection( void ) {
mysql_close( mConnection );
mysql_library_end();
}
bool MySqlConnection::isConnected( void ) const
{
return ( mConnection != nullptr );
}
bool MySqlConnection::connect( void ) {
bool connected;
my_bool argument;
// Enable automatic reconnection by default.
argument = 1;
// Enable the automatic reconnect option.
mysql_options(mConnection,MYSQL_OPT_RECONNECT,&argument);
// Try to connect to the MySQL server.
connected = ( mysql_real_connect(mConnection,
getHost().c_str(),
getUsername().c_str(),
getPassword().c_str(),
getSchema().c_str(),
3306,nullptr,0) != nullptr );
return ( connected );
}
DatabaseStatement * MySqlConnection::createStatement( const std::string & sql ) {
DatabaseStatement * statement;
// Checking the precondition.
assert( sql.length() > 0 );
// Check if the connection with the server is still active.
if( mysql_ping(mConnection) == 0 ) {
std::cout << "Statement allocated" << std::endl;
statement = new MySqlStatement(this,sql);
} else {
statement = nullptr;
}
return ( statement );
}
DatabasePreparedStatement * MySqlConnection::prepareStatement(
const std::string & sql ) {
// Checking the precondition.
assert( sql.length() > 0 );
// TODO Implement.
return ( nullptr );
}
void * MySqlConnection::getLink( void )
{
return ( static_cast<void *>(mConnection) );
}
<|endoftext|>
|
<commit_before>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Written (W) 1999-2007 Gunnar Raetsch
* Written (W) 1999-2007 Soeren Sonnenburg
* Copyright (C) 1999-2007 Fraunhofer Institute FIRST and Max-Planck-Society
*/
#include "lib/common.h"
#include "lib/io.h"
#include "kernel/LocalityImprovedStringKernel.h"
#include "features/Features.h"
#include "features/StringFeatures.h"
CLocalityImprovedStringKernel::CLocalityImprovedStringKernel(LONG size, INT l, INT d1, INT d2)
: CStringKernel<CHAR>(size),length(l),inner_degree(d1),outer_degree(d2),match(NULL)
{
SG_INFO( "LIK with parms: l=%d, d1=%d, d2=%d created!\n", l, d1, d2);
}
CLocalityImprovedStringKernel::~CLocalityImprovedStringKernel()
{
cleanup();
}
bool CLocalityImprovedStringKernel::init(CFeatures* l, CFeatures* r)
{
bool result = CStringKernel<CHAR>::init(l,r);
if (!result)
return false;
match = new CHAR[((CStringFeatures<CHAR>*) l)->get_max_vector_length()];
return match? true : false;
}
void CLocalityImprovedStringKernel::cleanup()
{
delete[] match;
match = NULL;
}
bool CLocalityImprovedStringKernel::load_init(FILE* src)
{
return false;
}
bool CLocalityImprovedStringKernel::save_init(FILE* dest)
{
return false;
}
DREAL CLocalityImprovedStringKernel::compute(INT idx_a, INT idx_b)
{
INT alen, blen;
CHAR* avec=((CStringFeatures<CHAR>*) lhs)->get_feature_vector(idx_a, alen);
CHAR* bvec=((CStringFeatures<CHAR>*) rhs)->get_feature_vector(idx_b, blen);
// can only deal with strings of same length
ASSERT(alen==blen);
INT i,j,t;
// initialize match table 1 -> match; 0 -> no match
for (i=0; i<alen; i++)
{
if (avec[i]==bvec[i])
match[i]=1;
else
match[i]=0;
}
DREAL outer_sum=0;
for (t=0; t<alen-length; t++)
{
INT sum=0;
for (i=0; i<length; i++)
sum+=(i+1)*match[t+i]+(length-i)*match[t+i+length+1];
//add middle element + normalize with sum_i=0^2l+1 i = (2l+1)(l+1)
DREAL inner_sum= ((DREAL) sum + (length+1)*match[t+length]) / ((2*length+1)*(length+1));
DREAL s=inner_sum;
for (j=1; j<inner_degree; j++)
inner_sum*=s;
outer_sum+=inner_sum;
}
double result=outer_sum;
for (i=1; i<outer_degree; i++)
result*=outer_sum;
return (double) result;
}
<commit_msg>LocalityImprovedStringKernel: Simplify for loop<commit_after>/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Written (W) 1999-2007 Gunnar Raetsch
* Written (W) 1999-2007 Soeren Sonnenburg
* Copyright (C) 1999-2007 Fraunhofer Institute FIRST and Max-Planck-Society
*/
#include "lib/common.h"
#include "lib/io.h"
#include "kernel/LocalityImprovedStringKernel.h"
#include "features/Features.h"
#include "features/StringFeatures.h"
CLocalityImprovedStringKernel::CLocalityImprovedStringKernel(LONG size, INT l, INT d1, INT d2)
: CStringKernel<CHAR>(size),length(l),inner_degree(d1),outer_degree(d2),match(NULL)
{
SG_INFO( "LIK with parms: l=%d, d1=%d, d2=%d created!\n", l, d1, d2);
}
CLocalityImprovedStringKernel::~CLocalityImprovedStringKernel()
{
cleanup();
}
bool CLocalityImprovedStringKernel::init(CFeatures* l, CFeatures* r)
{
bool result = CStringKernel<CHAR>::init(l,r);
if (!result)
return false;
match = new CHAR[((CStringFeatures<CHAR>*) l)->get_max_vector_length()];
return match? true : false;
}
void CLocalityImprovedStringKernel::cleanup()
{
delete[] match;
match = NULL;
}
bool CLocalityImprovedStringKernel::load_init(FILE* src)
{
return false;
}
bool CLocalityImprovedStringKernel::save_init(FILE* dest)
{
return false;
}
DREAL CLocalityImprovedStringKernel::compute(INT idx_a, INT idx_b)
{
INT alen, blen;
CHAR* avec=((CStringFeatures<CHAR>*) lhs)->get_feature_vector(idx_a, alen);
CHAR* bvec=((CStringFeatures<CHAR>*) rhs)->get_feature_vector(idx_b, blen);
// can only deal with strings of same length
ASSERT(alen==blen);
INT i,j,t;
// initialize match table 1 -> match; 0 -> no match
for (i=0; i<alen; i++)
match[i] = (avec[i] == bvec[i])? 1 : 0;
DREAL outer_sum=0;
for (t=0; t<alen-length; t++)
{
INT sum=0;
for (i=0; i<length; i++)
sum+=(i+1)*match[t+i]+(length-i)*match[t+i+length+1];
//add middle element + normalize with sum_i=0^2l+1 i = (2l+1)(l+1)
DREAL inner_sum= ((DREAL) sum + (length+1)*match[t+length]) / ((2*length+1)*(length+1));
DREAL s=inner_sum;
for (j=1; j<inner_degree; j++)
inner_sum*=s;
outer_sum+=inner_sum;
}
double result=outer_sum;
for (i=1; i<outer_degree; i++)
result*=outer_sum;
return (double) result;
}
<|endoftext|>
|
<commit_before>#include "batch-downloader.h"
#include <QCoreApplication>
#include <QSettings>
#include <QTimer>
#include "commands/commands.h"
#include "downloader/download-query-group.h"
#include "downloader/download-query-image.h"
#include "downloader/image-downloader.h"
#include "loader/pack-loader.h"
#include "models/profile.h"
#include "models/site.h"
BatchDownloader::BatchDownloader(DownloadQuery *query, Profile *profile, QObject *parent)
: QObject(parent), m_query(query), m_profile(profile), m_settings(profile->getSettings()), m_step(BatchDownloadStep::NotStarted)
{}
void BatchDownloader::setCurrentStep(BatchDownloadStep step)
{
emit stepChanged(step);
m_step = step;
}
BatchDownloader::BatchDownloadStep BatchDownloader::currentStep() const
{
return m_step;
}
int BatchDownloader::totalCount() const
{
return m_totalCount;
}
int BatchDownloader::downloadedCount() const
{
return m_counterSum;
}
int BatchDownloader::downloadedCount(Counter counter) const
{
return m_counters[counter];
}
DownloadQuery *BatchDownloader::query() const
{
return m_query;
}
void BatchDownloader::start()
{
// Resume download
if (m_step == BatchDownloadStep::Aborted) {
if (!m_imageDownloaders.isEmpty()) {
setCurrentStep(BatchDownloadStep::ImageDownload);
for (auto it = m_imageDownloaders.constBegin(); it != m_imageDownloaders.constEnd(); ++it) {
it.value()->save();
}
return;
} else if (m_packLoader != nullptr) {
nextPack();
return;
}
}
// Invalid step
else if (m_step != BatchDownloadStep::NotStarted) {
return;
}
// Reset counters
m_counters.clear();
m_counterSum = 0;
// Reset total
auto *group = dynamic_cast<DownloadQueryGroup*>(m_query);
m_totalCount = group != nullptr ? group->total : 1;
// m_profile->getCommands().before();
login();
}
void BatchDownloader::abort()
{
setCurrentStep(BatchDownloadStep::Aborted);
if (!m_imageDownloaders.isEmpty()) {
for (auto it = m_imageDownloaders.constBegin(); it != m_imageDownloaders.constEnd(); ++it) {
it.value()->abort();
}
} else if (m_packLoader != nullptr) {
m_packLoader->abort();
}
}
void BatchDownloader::login()
{
setCurrentStep(BatchDownloadStep::Login);
Site *site = m_query->site;
connect(site, &Site::loggedIn, this, &BatchDownloader::loginFinished, Qt::QueuedConnection);
site->login();
}
void BatchDownloader::loginFinished()
{
disconnect(m_query->site, &Site::loggedIn, this, &BatchDownloader::loginFinished);
auto *group = dynamic_cast<DownloadQueryGroup*>(m_query);
if (group != nullptr) {
bool usePacking = m_settings->value("packing_enable", true).toBool();
int imagesPerPack = m_settings->value("packing_size", 1000).toInt();
m_packLoader = new PackLoader(m_profile, *group, usePacking ? imagesPerPack : -1, this);
m_packLoader->start();
nextPack();
} else {
auto *img = dynamic_cast<DownloadQueryImage*>(m_query);
m_pendingDownloads.append(img->image);
nextImages();
}
}
void BatchDownloader::nextPack()
{
if (!m_packLoader->hasNext()) {
allFinished();
return;
}
setCurrentStep(BatchDownloadStep::PageDownload);
int packSize = m_packLoader->nextPackSize();
auto images = m_packLoader->next();
// Check missing images from the pack (if we expected 1000 but only got 900, we should consider 100 missing)
m_counters[Counter::Missing] += packSize - images.count();
m_pendingDownloads.append(images);
nextImages();
}
void BatchDownloader::nextImages()
{
setCurrentStep(BatchDownloadStep::ImageDownload);
// Start the simultaneous downloads
int count = qMax(1, qMin(m_settings->value("Save/simultaneous").toInt(), 10));
m_currentlyProcessing.storeRelaxed(count); // TODO: this should be shared amongst instances
for (int i = 0; i < count; ++i) {
nextImage();
}
}
void BatchDownloader::nextImage()
{
// We quit as soon as the user cancels
if (m_step != BatchDownloadStep::ImageDownload) {
return;
}
// If we already finished
if (m_pendingDownloads.empty()) {
if (m_currentlyProcessing.fetchAndAddRelaxed(-1) == 1) {
allFinished();
}
return;
}
// We take the first image to download
QSharedPointer<Image> img = m_pendingDownloads.dequeue();
loadImage(img);
}
void BatchDownloader::loadImage(QSharedPointer<Image> img)
{
// If there is already a downloader for this image, we simply restart it
if (m_imageDownloaders.contains(img)) {
m_imageDownloaders[img]->save();
return;
}
// Path
QString filename = m_query->filename;
QString path = m_query->path;
auto *group = dynamic_cast<DownloadQueryGroup*>(m_query);
// Start loading and saving image
int count = m_counterSum + 1;
bool getBlacklisted = group == nullptr || group->getBlacklisted;
auto imgDownloader = new ImageDownloader(m_profile, img, filename, path, count, true, false, this);
if (!getBlacklisted) {
imgDownloader->setBlacklist(&m_profile->getBlacklist());
}
connect(imgDownloader, &ImageDownloader::saved, this, &BatchDownloader::loadImageFinished, Qt::UniqueConnection);
m_imageDownloaders[img] = imgDownloader;
imgDownloader->save();
}
void BatchDownloader::loadImageFinished(const QSharedPointer<Image> &img, QList<ImageSaveResult> result)
{
// Delete ImageDownloader to prevent leaks
m_imageDownloaders[img]->deleteLater();
m_imageDownloaders.remove(img);
// Save error count to compare it later on
bool diskError = false;
const auto res = result.first().result;
// Disk writing errors
for (const ImageSaveResult &re : result) {
if (re.result == Image::SaveResult::Error) {
// TODO: detect disk error
// TODO: report errors somehos
}
}
// Increase counters
if (res == Image::SaveResult::NetworkError) {
m_counters[Counter::Errors]++;
m_failedDownloads.append(img);
} else if (res == Image::SaveResult::NotFound) {
m_counters[Counter::NotFound]++;
} else if (res == Image::SaveResult::AlreadyExistsDisk) {
m_counters[Counter::AlreadyExists]++;
} else if (res == Image::SaveResult::Blacklisted || res == Image::SaveResult::AlreadyExistsMd5 || res == Image::SaveResult::AlreadyExistsDeletedMd5) {
m_counters[Counter::Ignored]++;
} else if (!diskError) {
m_counters[Counter::Downloaded]++;
}
// Start downloading the next image
if (!diskError) {
m_counterSum++;
QCoreApplication::processEvents();
QTimer::singleShot(0, this, SLOT(nextImage()));
}
}
void BatchDownloader::allFinished()
{
// If we didn't really finish yet
if (m_packLoader != nullptr && m_packLoader->hasNext()) {
nextPack();
return;
}
// Cleanup
if (m_packLoader != nullptr) {
m_packLoader->deleteLater();
m_packLoader = nullptr;
}
// m_profile->getCommands().after();
setCurrentStep(BatchDownloadStep::Finished);
emit finished();
}
<commit_msg>Fix issue with dynamic cast in BatchDownloader class (PR #2538)<commit_after>#include "batch-downloader.h"
#include <QCoreApplication>
#include <QSettings>
#include <QTimer>
#include "commands/commands.h"
#include "downloader/download-query-group.h"
#include "downloader/download-query-image.h"
#include "downloader/image-downloader.h"
#include "loader/pack-loader.h"
#include "models/profile.h"
#include "models/site.h"
BatchDownloader::BatchDownloader(DownloadQuery *query, Profile *profile, QObject *parent)
: QObject(parent), m_query(query), m_profile(profile), m_settings(profile->getSettings()), m_step(BatchDownloadStep::NotStarted)
{}
void BatchDownloader::setCurrentStep(BatchDownloadStep step)
{
emit stepChanged(step);
m_step = step;
}
BatchDownloader::BatchDownloadStep BatchDownloader::currentStep() const
{
return m_step;
}
int BatchDownloader::totalCount() const
{
return m_totalCount;
}
int BatchDownloader::downloadedCount() const
{
return m_counterSum;
}
int BatchDownloader::downloadedCount(Counter counter) const
{
return m_counters[counter];
}
DownloadQuery *BatchDownloader::query() const
{
return m_query;
}
void BatchDownloader::start()
{
// Resume download
if (m_step == BatchDownloadStep::Aborted) {
if (!m_imageDownloaders.isEmpty()) {
setCurrentStep(BatchDownloadStep::ImageDownload);
for (auto it = m_imageDownloaders.constBegin(); it != m_imageDownloaders.constEnd(); ++it) {
it.value()->save();
}
return;
} else if (m_packLoader != nullptr) {
nextPack();
return;
}
}
// Invalid step
else if (m_step != BatchDownloadStep::NotStarted) {
return;
}
// Reset counters
m_counters.clear();
m_counterSum = 0;
// Reset total
auto *group = dynamic_cast<DownloadQueryGroup*>(m_query);
m_totalCount = group != nullptr ? group->total : 1;
// m_profile->getCommands().before();
login();
}
void BatchDownloader::abort()
{
setCurrentStep(BatchDownloadStep::Aborted);
if (!m_imageDownloaders.isEmpty()) {
for (auto it = m_imageDownloaders.constBegin(); it != m_imageDownloaders.constEnd(); ++it) {
it.value()->abort();
}
} else if (m_packLoader != nullptr) {
m_packLoader->abort();
}
}
void BatchDownloader::login()
{
setCurrentStep(BatchDownloadStep::Login);
Site *site = m_query->site;
connect(site, &Site::loggedIn, this, &BatchDownloader::loginFinished, Qt::QueuedConnection);
site->login();
}
void BatchDownloader::loginFinished()
{
disconnect(m_query->site, &Site::loggedIn, this, &BatchDownloader::loginFinished);
auto *group = dynamic_cast<DownloadQueryGroup*>(m_query);
if (group != nullptr) {
bool usePacking = m_settings->value("packing_enable", true).toBool();
int imagesPerPack = m_settings->value("packing_size", 1000).toInt();
m_packLoader = new PackLoader(m_profile, *group, usePacking ? imagesPerPack : -1, this);
m_packLoader->start();
nextPack();
} else {
auto *img = dynamic_cast<DownloadQueryImage*>(m_query);
if (!img) {
return;
}
m_pendingDownloads.append(img->image);
nextImages();
}
}
void BatchDownloader::nextPack()
{
if (!m_packLoader->hasNext()) {
allFinished();
return;
}
setCurrentStep(BatchDownloadStep::PageDownload);
int packSize = m_packLoader->nextPackSize();
auto images = m_packLoader->next();
// Check missing images from the pack (if we expected 1000 but only got 900, we should consider 100 missing)
m_counters[Counter::Missing] += packSize - images.count();
m_pendingDownloads.append(images);
nextImages();
}
void BatchDownloader::nextImages()
{
setCurrentStep(BatchDownloadStep::ImageDownload);
// Start the simultaneous downloads
int count = qMax(1, qMin(m_settings->value("Save/simultaneous").toInt(), 10));
m_currentlyProcessing.storeRelaxed(count); // TODO: this should be shared amongst instances
for (int i = 0; i < count; ++i) {
nextImage();
}
}
void BatchDownloader::nextImage()
{
// We quit as soon as the user cancels
if (m_step != BatchDownloadStep::ImageDownload) {
return;
}
// If we already finished
if (m_pendingDownloads.empty()) {
if (m_currentlyProcessing.fetchAndAddRelaxed(-1) == 1) {
allFinished();
}
return;
}
// We take the first image to download
QSharedPointer<Image> img = m_pendingDownloads.dequeue();
loadImage(img);
}
void BatchDownloader::loadImage(QSharedPointer<Image> img)
{
// If there is already a downloader for this image, we simply restart it
if (m_imageDownloaders.contains(img)) {
m_imageDownloaders[img]->save();
return;
}
// Path
QString filename = m_query->filename;
QString path = m_query->path;
auto *group = dynamic_cast<DownloadQueryGroup*>(m_query);
// Start loading and saving image
int count = m_counterSum + 1;
bool getBlacklisted = group == nullptr || group->getBlacklisted;
auto imgDownloader = new ImageDownloader(m_profile, img, filename, path, count, true, false, this);
if (!getBlacklisted) {
imgDownloader->setBlacklist(&m_profile->getBlacklist());
}
connect(imgDownloader, &ImageDownloader::saved, this, &BatchDownloader::loadImageFinished, Qt::UniqueConnection);
m_imageDownloaders[img] = imgDownloader;
imgDownloader->save();
}
void BatchDownloader::loadImageFinished(const QSharedPointer<Image> &img, QList<ImageSaveResult> result)
{
// Delete ImageDownloader to prevent leaks
m_imageDownloaders[img]->deleteLater();
m_imageDownloaders.remove(img);
// Save error count to compare it later on
bool diskError = false;
const auto res = result.first().result;
// Disk writing errors
for (const ImageSaveResult &re : result) {
if (re.result == Image::SaveResult::Error) {
// TODO: detect disk error
// TODO: report errors somehos
}
}
// Increase counters
if (res == Image::SaveResult::NetworkError) {
m_counters[Counter::Errors]++;
m_failedDownloads.append(img);
} else if (res == Image::SaveResult::NotFound) {
m_counters[Counter::NotFound]++;
} else if (res == Image::SaveResult::AlreadyExistsDisk) {
m_counters[Counter::AlreadyExists]++;
} else if (res == Image::SaveResult::Blacklisted || res == Image::SaveResult::AlreadyExistsMd5 || res == Image::SaveResult::AlreadyExistsDeletedMd5) {
m_counters[Counter::Ignored]++;
} else if (!diskError) {
m_counters[Counter::Downloaded]++;
}
// Start downloading the next image
if (!diskError) {
m_counterSum++;
QCoreApplication::processEvents();
QTimer::singleShot(0, this, SLOT(nextImage()));
}
}
void BatchDownloader::allFinished()
{
// If we didn't really finish yet
if (m_packLoader != nullptr && m_packLoader->hasNext()) {
nextPack();
return;
}
// Cleanup
if (m_packLoader != nullptr) {
m_packLoader->deleteLater();
m_packLoader = nullptr;
}
// m_profile->getCommands().after();
setCurrentStep(BatchDownloadStep::Finished);
emit finished();
}
<|endoftext|>
|
<commit_before>#include <algorithm>
#include <cmath>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
#include <popt.h>
#include "defs.hh"
#include "StringSet.hh"
#include "FactorEncoder.hh"
#include "Unigrams.hh"
#include "Bigrams.hh"
using namespace std;
void
assert_single_chars(map<string, flt_type> &vocab,
const map<string, flt_type> &chars,
flt_type val)
{
for (auto it = chars.cbegin(); it != chars.cend(); ++it)
if (vocab.find(it->first) == vocab.end())
vocab[it->first] = val;
}
int main(int argc, char* argv[]) {
int iter_amount = 10;
int least_common = 0;
int target_vocab_size = 30000;
float cutoff_value = 0.0;
flt_type one_char_min_lp = -25.0;
string vocab_fname;
string wordlist_fname;
string msfg_fname;
string transition_fname;
// Popt documentation:
// http://linux.die.net/man/3/popt
// http://privatemisc.blogspot.fi/2012/12/popt-basic-example.html
poptContext pc;
struct poptOption po[] = {
{"iter", 'i', POPT_ARG_INT, &iter_amount, 11001, NULL, "How many iterations"},
{"least-common", 'l', POPT_ARG_INT, &least_common, 11001, NULL, "Remove least common strings"},
{"vocab_size", 'g', POPT_ARG_INT, &target_vocab_size, 11007, NULL, "Target vocabulary size (stopping criterion)"},
{"cutoff", 'u', POPT_ARG_FLOAT, &cutoff_value, 11001, NULL, "Cutoff value for each iteration"},
POPT_AUTOHELP
{NULL}
};
pc = poptGetContext(NULL, argc, (const char **)argv, po, 0);
poptSetOtherOptionHelp(pc, "[INITIAL VOCABULARY] [WORDLIST] [MSFG_IN] [TRANSITIONS]");
int val;
while ((val = poptGetNextOpt(pc)) >= 0)
continue;
// poptGetNextOpt returns -1 when the final argument has been parsed
// otherwise an error occured
if (val != -1) {
switch (val) {
case POPT_ERROR_NOARG:
cerr << "Argument missing for an option" << endl;
exit(1);
case POPT_ERROR_BADOPT:
cerr << "Option's argument could not be parsed" << endl;
exit(1);
case POPT_ERROR_BADNUMBER:
case POPT_ERROR_OVERFLOW:
cerr << "Option could not be converted to number" << endl;
exit(1);
default:
cerr << "Unknown error in option processing" << endl;
exit(1);
}
}
// Handle ARG part of command line
if (poptPeekArg(pc) != NULL)
vocab_fname.assign((char*)poptGetArg(pc));
else {
cerr << "Initial vocabulary file not set" << endl;
exit(1);
}
if (poptPeekArg(pc) != NULL)
wordlist_fname.assign((char*)poptGetArg(pc));
else {
cerr << "Wordlist file not set" << endl;
exit(1);
}
if (poptPeekArg(pc) != NULL)
msfg_fname.assign((char*)poptGetArg(pc));
else {
cerr << "Input MSFG file not set" << endl;
exit(1);
}
if (poptPeekArg(pc) != NULL)
transition_fname.assign((char*)poptGetArg(pc));
else {
cerr << "Transition file not set" << endl;
exit(1);
}
cerr << "parameters, initial vocabulary: " << vocab_fname << endl;
cerr << "parameters, wordlist: " << wordlist_fname << endl;
cerr << "parameters, msfg: " << msfg_fname << endl;
cerr << "parameters, transitions: " << transition_fname << endl;
cerr << "parameters, cutoff: " << setprecision(15) << cutoff_value << endl;
cerr << "parameters, iterations: " << iter_amount << endl;
cerr << "parameters, target vocab size: " << target_vocab_size << endl;
cerr << "parameters, least common subwords to remove: " << least_common << endl;
int maxlen, word_maxlen;
map<string, flt_type> all_chars;
map<string, flt_type> vocab;
map<string, flt_type> freqs;
map<string, flt_type> words;
cerr << "Reading vocabulary " << vocab_fname << endl;
int retval = read_vocab(vocab_fname, vocab, maxlen);
if (retval < 0) {
cerr << "something went wrong reading vocabulary" << endl;
exit(0);
}
cerr << "\t" << "size: " << vocab.size() << endl;
cerr << "\t" << "maximum string length: " << maxlen << endl;
for (auto it = vocab.cbegin(); it != vocab.end(); ++it)
if (it->first.length() == 1)
all_chars[it->first] = 0.0;
cerr << "Reading word list " << wordlist_fname << endl;
retval = read_vocab(wordlist_fname, words, word_maxlen);
if (retval < 0) {
cerr << "something went wrong reading word list" << endl;
exit(0);
}
cerr << "\t" << "wordlist size: " << words.size() << endl;
cerr << "\t" << "maximum word length: " << word_maxlen << endl;
Unigrams ug;
ug.set_segmentation_method(forward_backward);
cerr << "Initial cutoff" << endl;
ug.resegment_words(words, vocab, freqs);
flt_type densum = ug.get_sum(freqs);
flt_type cost = ug.get_cost(freqs, densum);
cerr << "unigram cost without word end symbols: " << cost << endl;
ug.cutoff(freqs, (flt_type)cutoff_value);
cerr << "\tcutoff: " << cutoff_value << "\t" << "vocabulary size: " << freqs.size() << endl;
vocab = freqs;
densum = ug.get_sum(vocab);
ug.freqs_to_logprobs(vocab, densum);
assert_single_chars(vocab, all_chars, one_char_min_lp);
string start_end_symbol("*");
StringSet<flt_type> ss_vocab(vocab);
map<string, FactorGraph*> fg_words;
MultiStringFactorGraph msfg(start_end_symbol);
msfg.read(msfg_fname);
transitions_t transitions;
transitions_t trans_stats;
map<string, flt_type> trans_normalizers;
map<string, flt_type> unigram_stats;
vocab[start_end_symbol] = 0.0;
// Initial segmentation using unigram model
Bigrams::collect_trans_stats(vocab, words, msfg, trans_stats, trans_normalizers, unigram_stats);
// Unigram cost with word end markers
densum = ug.get_sum(unigram_stats);
cost = ug.get_cost(unigram_stats, densum);
cerr << "unigram cost with word end symbols: " << cost << endl;
// Initial bigram cost
transitions = trans_stats;
Bigrams::normalize(transitions, trans_normalizers);
cerr << "bigram cost: " << Bigrams::bigram_cost(transitions, trans_stats) << endl;
cerr << "\tamount of transitions: " << Bigrams::transition_count(transitions) << endl;
cerr << "\tvocab size: " << unigram_stats.size() << endl;
int co_removed = Bigrams::cutoff(unigram_stats, cutoff_value, transitions, msfg);
cerr << "\tremoved by cutoff: " << co_removed << endl;
// Re-estimate using bigram stats
int vocab_size = unigram_stats.size();
for (int i=0; i<iter_amount; i++) {
Bigrams::collect_trans_stats(transitions, words, msfg, trans_stats, trans_normalizers, unigram_stats);
transitions = trans_stats;
Bigrams::normalize(transitions, trans_normalizers);
vocab_size = unigram_stats.size();
cerr << "bigram cost: " << Bigrams::bigram_cost(transitions, trans_stats) << endl;
cerr << "\tamount of transitions: " << Bigrams::transition_count(transitions) << endl;
cerr << "\tvocab size: " << vocab_size << endl;
// Write temp transitions
ostringstream transitions_temp;
transitions_temp << "transitions.iter" << i+1;
Bigrams::write_transitions(transitions, transitions_temp.str());
int curr_least_common = least_common + (vocab_size % 1000);
int lc_removed = Bigrams::remove_least_common(unigram_stats, curr_least_common, transitions, msfg);
cerr << "\tremoved " << lc_removed << " least common subwords" << endl;
vocab_size = transitions.size();
if (vocab_size < target_vocab_size) break;
}
// Write transitions
Bigrams::write_transitions(transitions, transition_fname);
Bigrams::write_transitions(trans_stats, "debug.trans_stats.out");
write_vocab("debug.unigram.out", unigram_stats);
exit(1);
}
<commit_msg>Minor fix.<commit_after>#include <algorithm>
#include <cmath>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
#include <popt.h>
#include "defs.hh"
#include "StringSet.hh"
#include "FactorEncoder.hh"
#include "Unigrams.hh"
#include "Bigrams.hh"
using namespace std;
void
assert_single_chars(map<string, flt_type> &vocab,
const map<string, flt_type> &chars,
flt_type val)
{
for (auto it = chars.cbegin(); it != chars.cend(); ++it)
if (vocab.find(it->first) == vocab.end())
vocab[it->first] = val;
}
int main(int argc, char* argv[]) {
int iter_amount = 10;
int least_common = 0;
int target_vocab_size = 30000;
float cutoff_value = 0.0;
flt_type one_char_min_lp = -25.0;
string vocab_fname;
string wordlist_fname;
string msfg_fname;
string transition_fname;
// Popt documentation:
// http://linux.die.net/man/3/popt
// http://privatemisc.blogspot.fi/2012/12/popt-basic-example.html
poptContext pc;
struct poptOption po[] = {
{"iter", 'i', POPT_ARG_INT, &iter_amount, 11001, NULL, "How many iterations"},
{"least-common", 'l', POPT_ARG_INT, &least_common, 11001, NULL, "Remove least common strings"},
{"vocab_size", 'g', POPT_ARG_INT, &target_vocab_size, 11007, NULL, "Target vocabulary size (stopping criterion)"},
{"cutoff", 'u', POPT_ARG_FLOAT, &cutoff_value, 11001, NULL, "Cutoff value for each iteration"},
POPT_AUTOHELP
{NULL}
};
pc = poptGetContext(NULL, argc, (const char **)argv, po, 0);
poptSetOtherOptionHelp(pc, "[INITIAL VOCABULARY] [WORDLIST] [MSFG_IN] [TRANSITIONS]");
int val;
while ((val = poptGetNextOpt(pc)) >= 0)
continue;
// poptGetNextOpt returns -1 when the final argument has been parsed
// otherwise an error occured
if (val != -1) {
switch (val) {
case POPT_ERROR_NOARG:
cerr << "Argument missing for an option" << endl;
exit(1);
case POPT_ERROR_BADOPT:
cerr << "Option's argument could not be parsed" << endl;
exit(1);
case POPT_ERROR_BADNUMBER:
case POPT_ERROR_OVERFLOW:
cerr << "Option could not be converted to number" << endl;
exit(1);
default:
cerr << "Unknown error in option processing" << endl;
exit(1);
}
}
// Handle ARG part of command line
if (poptPeekArg(pc) != NULL)
vocab_fname.assign((char*)poptGetArg(pc));
else {
cerr << "Initial vocabulary file not set" << endl;
exit(1);
}
if (poptPeekArg(pc) != NULL)
wordlist_fname.assign((char*)poptGetArg(pc));
else {
cerr << "Wordlist file not set" << endl;
exit(1);
}
if (poptPeekArg(pc) != NULL)
msfg_fname.assign((char*)poptGetArg(pc));
else {
cerr << "Input MSFG file not set" << endl;
exit(1);
}
if (poptPeekArg(pc) != NULL)
transition_fname.assign((char*)poptGetArg(pc));
else {
cerr << "Transition file not set" << endl;
exit(1);
}
cerr << "parameters, initial vocabulary: " << vocab_fname << endl;
cerr << "parameters, wordlist: " << wordlist_fname << endl;
cerr << "parameters, msfg: " << msfg_fname << endl;
cerr << "parameters, transitions: " << transition_fname << endl;
cerr << "parameters, cutoff: " << setprecision(15) << cutoff_value << endl;
cerr << "parameters, iterations: " << iter_amount << endl;
cerr << "parameters, target vocab size: " << target_vocab_size << endl;
cerr << "parameters, least common subwords to remove: " << least_common << endl;
int maxlen, word_maxlen;
map<string, flt_type> all_chars;
map<string, flt_type> vocab;
map<string, flt_type> freqs;
map<string, flt_type> words;
cerr << "Reading vocabulary " << vocab_fname << endl;
int retval = read_vocab(vocab_fname, vocab, maxlen);
if (retval < 0) {
cerr << "something went wrong reading vocabulary" << endl;
exit(0);
}
cerr << "\t" << "size: " << vocab.size() << endl;
cerr << "\t" << "maximum string length: " << maxlen << endl;
for (auto it = vocab.cbegin(); it != vocab.end(); ++it)
if (it->first.length() == 1)
all_chars[it->first] = 0.0;
cerr << "Reading word list " << wordlist_fname << endl;
retval = read_vocab(wordlist_fname, words, word_maxlen);
if (retval < 0) {
cerr << "something went wrong reading word list" << endl;
exit(0);
}
cerr << "\t" << "wordlist size: " << words.size() << endl;
cerr << "\t" << "maximum word length: " << word_maxlen << endl;
Unigrams ug;
ug.set_segmentation_method(forward_backward);
cerr << "Initial cutoff" << endl;
ug.resegment_words(words, vocab, freqs);
flt_type densum = ug.get_sum(freqs);
flt_type cost = ug.get_cost(freqs, densum);
cerr << "unigram cost without word end symbols: " << cost << endl;
ug.cutoff(freqs, (flt_type)cutoff_value);
cerr << "\tcutoff: " << cutoff_value << "\t" << "vocabulary size: " << freqs.size() << endl;
vocab = freqs;
densum = ug.get_sum(vocab);
ug.freqs_to_logprobs(vocab, densum);
assert_single_chars(vocab, all_chars, one_char_min_lp);
string start_end_symbol("*");
StringSet<flt_type> ss_vocab(vocab);
map<string, FactorGraph*> fg_words;
MultiStringFactorGraph msfg(start_end_symbol);
msfg.read(msfg_fname);
transitions_t transitions;
transitions_t trans_stats;
map<string, flt_type> trans_normalizers;
map<string, flt_type> unigram_stats;
vocab[start_end_symbol] = 0.0;
// Initial segmentation using unigram model
Bigrams::collect_trans_stats(vocab, words, msfg, trans_stats, trans_normalizers, unigram_stats);
// Unigram cost with word end markers
densum = ug.get_sum(unigram_stats);
cost = ug.get_cost(unigram_stats, densum);
cerr << "unigram cost with word end symbols: " << cost << endl;
// Initial bigram cost
transitions = trans_stats;
Bigrams::normalize(transitions, trans_normalizers);
cerr << "bigram cost: " << Bigrams::bigram_cost(transitions, trans_stats) << endl;
cerr << "\tamount of transitions: " << Bigrams::transition_count(transitions) << endl;
cerr << "\tvocab size: " << unigram_stats.size() << endl;
int co_removed = Bigrams::cutoff(unigram_stats, cutoff_value, transitions, msfg);
cerr << "\tremoved by cutoff: " << co_removed << endl;
// Re-estimate using bigram stats
int vocab_size = unigram_stats.size();
for (int i=0; i<iter_amount; i++) {
Bigrams::collect_trans_stats(transitions, words, msfg, trans_stats, trans_normalizers, unigram_stats);
transitions = trans_stats;
Bigrams::normalize(transitions, trans_normalizers);
vocab_size = unigram_stats.size();
cerr << "bigram cost: " << Bigrams::bigram_cost(transitions, trans_stats) << endl;
cerr << "\tamount of transitions: " << Bigrams::transition_count(transitions) << endl;
cerr << "\tvocab size: " << vocab_size << endl;
// Write temp transitions
ostringstream transitions_temp;
transitions_temp << "transitions.iter" << i+1;
Bigrams::write_transitions(transitions, transitions_temp.str());
if (least_common > 0) {
int curr_least_common = least_common + (vocab_size % 1000);
int lc_removed = Bigrams::remove_least_common(unigram_stats, curr_least_common, transitions, msfg);
cerr << "\tremoved " << lc_removed << " least common subwords" << endl;
vocab_size = transitions.size();
}
if (vocab_size < target_vocab_size) break;
}
// Write transitions
Bigrams::write_transitions(transitions, transition_fname);
Bigrams::write_transitions(trans_stats, "debug.trans_stats.out");
write_vocab("debug.unigram.out", unigram_stats);
exit(1);
}
<|endoftext|>
|
<commit_before>/*-
* Copyright (c) 2016 Frederic Culot <culot@FreeBSD.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer
* in this position and unchanged.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR(S) 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 <stdexcept>
#include "gfx.h"
namespace portal {
namespace gfx {
void Gfx::init() {
initscr();
if (has_colors() && start_color() == OK) {
init_pair(Style::Color::none, 0, 0);
init_pair(Style::Color::black, COLOR_BLACK, 0);
init_pair(Style::Color::cyan, COLOR_CYAN, 0);
init_pair(Style::Color::magenta, COLOR_MAGENTA, 0);
init_pair(Style::Color::red, COLOR_RED, 0);
init_pair(Style::Color::yellow, COLOR_YELLOW, 0);
init_pair(Style::Color::blue, COLOR_BLUE, 0);
init_pair(Style::Color::cyanOnBlue, COLOR_CYAN, COLOR_BLUE);
} else {
// XXX Need to deal with B&W terminals
throw std::runtime_error("Sorry, B&W terminals not supported yet");
}
raw();
noecho();
keypad(stdscr, TRUE);
curs_set(0);
refresh(); // A refresh might seem unnecessary here, but user input is
// gathered from stdscr via a call to getch, which does an
// implicit refresh first (don't ask me why...). Hence doing
// this refresh explicitly avoids a black screen when portal
// starts. The black screen does not appear afterwards as
// stdscr is never touched by portal, so curses detects it
// does not need any subsequent refreshes.
}
// The curses library fails to handle two concurrent threads trying to
// update the display at the same time. This creates a single point of
// entry that prevents this case from happening. Morevover, a try_lock
// is used here instead of just lock, as if a thread is already
// updating the display, we assume there is no need to update it again
// right after, so we skip an update to avoir too frequent refreshes.
void Gfx::update() {
if (mutex_.try_lock()) {
doupdate();
mutex_.unlock();
}
}
void Gfx::terminate() {
clear();
endwin();
}
}
}
<commit_msg>Add support for transparent terminals<commit_after>/*-
* Copyright (c) 2016 Frederic Culot <culot@FreeBSD.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer
* in this position and unchanged.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR(S) 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 <stdexcept>
#include "gfx.h"
namespace portal {
namespace gfx {
void Gfx::init() {
initscr();
if (has_colors() && start_color() == OK) {
use_default_colors();
init_pair(Style::Color::none, -1, -1);
init_pair(Style::Color::black, COLOR_BLACK, -1);
init_pair(Style::Color::cyan, COLOR_CYAN, -1);
init_pair(Style::Color::magenta, COLOR_MAGENTA, -1);
init_pair(Style::Color::red, COLOR_RED, -1);
init_pair(Style::Color::yellow, COLOR_YELLOW, -1);
init_pair(Style::Color::blue, COLOR_BLUE, -1);
init_pair(Style::Color::cyanOnBlue, COLOR_CYAN, COLOR_BLUE);
} else {
// XXX Need to deal with B&W terminals
throw std::runtime_error("Sorry, B&W terminals not supported yet");
}
raw();
noecho();
keypad(stdscr, TRUE);
curs_set(0);
refresh(); // A refresh might seem unnecessary here, but user input is
// gathered from stdscr via a call to getch, which does an
// implicit refresh first (don't ask me why...). Hence doing
// this refresh explicitly avoids a black screen when portal
// starts. The black screen does not appear afterwards as
// stdscr is never touched by portal, so curses detects it
// does not need any subsequent refreshes.
}
// The curses library fails to handle two concurrent threads trying to
// update the display at the same time. This creates a single point of
// entry that prevents this case from happening. Morevover, a try_lock
// is used here instead of just lock, as if a thread is already
// updating the display, we assume there is no need to update it again
// right after, so we skip an update to avoir too frequent refreshes.
void Gfx::update() {
if (mutex_.try_lock()) {
doupdate();
mutex_.unlock();
}
}
void Gfx::terminate() {
clear();
endwin();
}
}
}
<|endoftext|>
|
<commit_before>#include <algorithm>
#include <map>
#include <string>
#include <limits>
#include "Prefetch.h"
#include "CodeGen_Internal.h"
#include "IRMutator.h"
#include "IROperator.h"
#include "Bounds.h"
#include "Scope.h"
#include "Simplify.h"
#include "Substitute.h"
#include "Util.h"
namespace Halide {
namespace Internal {
using std::map;
using std::string;
using std::vector;
using std::stack;
// Prefetch debug levels
int dbg_prefetch0 = 1;
int dbg_prefetch1 = 2;
int dbg_prefetch2 = 3;
int dbg_prefetch3 = 10;
#define MIN(x,y) (((x)<(y)) ? (x) : (y))
#define MAX(x,y) (((x)>(y)) ? (x) : (y))
class InjectPrefetch : public IRMutator {
public:
InjectPrefetch(const map<string, Function> &e)
: env(e) { }
private:
const map<string, Function> &env;
Scope<Interval> scope;
unsigned long ptmp = 0; // ID for all tmp vars in a prefetch op
private:
using IRMutator::visit;
// Strip down the tuple name, e.g. f.*.var into f
string tuple_func(const string &name) {
vector<string> v = split_string(name, ".");
internal_assert(v.size() > 0);
return v[0];
}
// Strip down the tuple name, e.g. f.*.var into var
string tuple_var(const string &name) {
vector<string> v = split_string(name, ".");
internal_assert(v.size() > 0);
return v[v.size()-1];
}
// Lookup a function in the environment
Function get_func(const string &name) {
map<string, Function>::const_iterator iter = env.find(name);
internal_assert(iter != env.end()) << "function not in environment.\n";
return iter->second;
}
// Determine the static type of a named buffer (if available)
// Note: the type of input is only known at runtime (use input.elem_size)
Type get_type(string varname, bool &has_static_type) {
debug(dbg_prefetch2) << " getType(" << varname << ")\n";
Type t = UInt(8);
map<string, Function>::const_iterator varit = env.find(varname);
if (varit != env.end()) {
Function varf = varit->second;
debug(dbg_prefetch2) << " found: " << varit->first << "\n";
if (varf.outputs()) {
vector<Type> varts = varf.output_types();
t = varts[0];
debug(dbg_prefetch2) << " type: " << t << "\n";
}
has_static_type = true;
} else {
debug(dbg_prefetch2) << " could not statically determine type of " << varname
<< ", temporarily using: " << t << "\n";
has_static_type = false;
}
return t;
}
void visit(const Let *op) {
Interval in = bounds_of_expr_in_scope(op->value, scope);
scope.push(op->name, in);
IRMutator::visit(op);
scope.pop(op->name);
}
void visit(const LetStmt *op) {
Interval in = bounds_of_expr_in_scope(op->value, scope);
scope.push(op->name, in);
IRMutator::visit(op);
scope.pop(op->name);
}
void visit(const For *op) {
Stmt body = op->body;
string func_name = tuple_func(op->name);
string ivar_name = tuple_var(op->name);
vector<Prefetch> &prefetches = get_func(func_name).schedule().prefetches();
if (prefetches.empty()) {
debug(dbg_prefetch2) << "InjectPrefetch: " << op->name << " " << func_name << " " << ivar_name;
debug(dbg_prefetch2) << " No prefetch\n";
} else {
debug(dbg_prefetch1) << "InjectPrefetch: " << op->name << " " << func_name << " " << ivar_name;
debug(dbg_prefetch1) << " Found prefetch directive(s)\n";
}
for (const Prefetch &p : prefetches) {
debug(dbg_prefetch1) << "InjectPrefetch: check ivar:" << p.var << "\n";
if (p.var == ivar_name) {
debug(dbg_prefetch0) << " " << func_name
<< " prefetch(" << ivar_name << ", " << p.offset << ")\n";
// Interval prein(op->name, op->name);
// Add in prefetch offset
Expr var = Variable::make(Int(32), op->name);
Interval prein(var + p.offset, var + p.offset);
scope.push(op->name, prein);
map<string, Box> boxes;
boxes = boxes_required(body, scope);
int cnt = 0; // Number of prefetch ops generated
Stmt pstmts; // Generated prefetch statements
debug(dbg_prefetch1) << " boxes required:\n";
for (auto &b : boxes) {
bool do_prefetch = true;
const string &varname = b.first;
Box &box = b.second;
int dims = box.size();
bool has_static_type = true;
Type t = get_type(varname, has_static_type);
debug(dbg_prefetch0) << " prefetch" << ptmp << ": "
<< varname << " (" << t
<< (has_static_type ? "" : "dynamic_type")
<< ", dims:" << dims << ")\n";
for (int i = 0; i < dims; i++) {
debug(dbg_prefetch1) << " ---\n";
debug(dbg_prefetch1) << " box[" << i << "].min: " << box[i].min << "\n";
debug(dbg_prefetch1) << " box[" << i << "].max: " << box[i].max << "\n";
}
debug(dbg_prefetch1) << " ---------\n";
// TODO: Opt: check box if it should be prefetched?
// TODO - Only prefetch if varying by ivar_name?
// TODO - Don't prefetch if "small" all constant dimensions?
// TODO e.g. see: camera_pipe.cpp corrected matrix(4,3)
string pstr = std::to_string(ptmp++);
string varname_prefetch_buf = varname + ".prefetch_" + pstr + "_buf";
Expr var_prefetch_buf = Variable::make(Int(32), varname_prefetch_buf);
// Make the names for accessing the buffer strides
vector<Expr> stride_var(dims);
for (int i = 0; i < dims; i++) {
string istr = std::to_string(i);
string stride_name = varname + ".stride." + istr;
#if 0 // TODO: Determine if the stride varname is defined - check not yet working
// if (!scope.contains(stride_name)) [
if (env.find(stride_name) == env.end()) {
do_prefetch = false;
debug(dbg_prefetch0) << " " << stride_name << " undefined\n";
break;
}
#endif
stride_var[i] = Variable::make(Int(32), stride_name);
}
// This box should not be prefetched
if (!do_prefetch) {
debug(dbg_prefetch0) << " not prefetching " << varname << "\n";
continue;
}
// Make the names for the prefetch box mins & maxes
vector<string> min_name(dims), max_name(dims);
for (int i = 0; i < dims; i++) {
string istr = std::to_string(i);
min_name[i] = varname + ".prefetch_" + pstr + "_min_" + istr;
max_name[i] = varname + ".prefetch_" + pstr + "_max_" + istr;
}
vector<Expr> min_var(dims), max_var(dims);
for (int i = 0; i < dims; i++) {
min_var[i] = Variable::make(Int(32), min_name[i]);
max_var[i] = Variable::make(Int(32), max_name[i]);
}
// Create a buffer_t object for this prefetch.
vector<Expr> args(dims*3 + 2);
Expr first_elem = Load::make(t, varname, 0, Buffer(), Parameter());
args[0] = Call::make(Handle(), Call::address_of, {first_elem}, Call::PureIntrinsic);
args[1] = make_zero(t);
for (int i = 0; i < dims; i++) {
args[3*i+2] = min_var[i];
args[3*i+3] = max_var[i] - min_var[i] + 1;
args[3*i+4] = stride_var[i];
}
// Inject the prefetch call
vector<Expr> args_prefetch(3);
args_prefetch[0] = dims;
if (has_static_type) {
args_prefetch[1] = t.bytes();
} else {
// Element size for inputs that don't have static types
string elem_size_name = varname + ".elem_size";
Expr elem_size_var = Variable::make(Int(32), elem_size_name);
args_prefetch[1] = elem_size_var;
}
args_prefetch[2] = var_prefetch_buf;
// TODO: Opt: Keep running sum of bytes prefetched on this sequence
// TODO: Opt: Keep running sum of number of prefetch instructions issued
// TODO on this sequence? (to not exceed MAX_PREFETCH)
// TODO: Opt: Generate control code for prefetch_buffer_t in Prefetch.cpp
// TODO Passing box info through a buffer_t results in ~30 additional stores/loads
Stmt stmt_prefetch = Evaluate::make(Call::make(Int(32), Call::prefetch_buffer_t,
args_prefetch, Call::Intrinsic));
if (cnt == 0) {
pstmts = stmt_prefetch;
} else {
pstmts = Block::make({stmt_prefetch, pstmts});
}
cnt++;
// Inject the create_buffer_t call
Expr prefetch_buf = Call::make(type_of<struct buffer_t *>(), Call::create_buffer_t,
args, Call::Intrinsic);
pstmts = LetStmt::make(varname_prefetch_buf, prefetch_buf, pstmts);
// Inject bounds variable assignments
for (int i = dims-1; i >= 0; i--) {
pstmts = LetStmt::make(max_name[i], box[i].max, pstmts);
pstmts = LetStmt::make(min_name[i], box[i].min, pstmts);
// stride already defined by input buffer
}
}
if (cnt) {
#if 1
// Guard to not prefetch past the end of the iteration space
// TODO: Opt: Use original extent of loop for guard (avoid conservative guard when stripmined)
Expr pcond = likely((Variable::make(Int(32), op->name) + p.offset)
< (op->min + op->extent - 1));
Stmt pguard = IfThenElse::make(pcond, pstmts);
body = Block::make({pguard, body});
debug(dbg_prefetch3) << " prefetch: (cnt:" << cnt << ")\n";
debug(dbg_prefetch3) << pguard << "\n";
#else
body = Block::make({pstmts, body});
#endif
}
scope.pop(op->name);
}
}
body = mutate(body);
stmt = For::make(op->name, op->min, op->extent, op->for_type, op->device_api, body);
}
};
Stmt inject_prefetch(Stmt s, const std::map<std::string, Function> &env)
{
size_t read;
std::string lvl = get_env_variable("HL_DEBUG_PREFETCH", read);
if (read) {
int dbg_level = atoi(lvl.c_str());
dbg_prefetch0 = MAX(dbg_prefetch0 - dbg_level, 0);
dbg_prefetch1 = MAX(dbg_prefetch1 - dbg_level, 0);
dbg_prefetch2 = MAX(dbg_prefetch2 - dbg_level, 0);
dbg_prefetch3 = MAX(dbg_prefetch3 - dbg_level, 0);
}
return InjectPrefetch(env).mutate(s);
}
}
}
<commit_msg>Cleanup debug dynamic_type indicator<commit_after>#include <algorithm>
#include <map>
#include <string>
#include <limits>
#include "Prefetch.h"
#include "CodeGen_Internal.h"
#include "IRMutator.h"
#include "IROperator.h"
#include "Bounds.h"
#include "Scope.h"
#include "Simplify.h"
#include "Substitute.h"
#include "Util.h"
namespace Halide {
namespace Internal {
using std::map;
using std::string;
using std::vector;
using std::stack;
// Prefetch debug levels
int dbg_prefetch0 = 1;
int dbg_prefetch1 = 2;
int dbg_prefetch2 = 3;
int dbg_prefetch3 = 10;
#define MIN(x,y) (((x)<(y)) ? (x) : (y))
#define MAX(x,y) (((x)>(y)) ? (x) : (y))
class InjectPrefetch : public IRMutator {
public:
InjectPrefetch(const map<string, Function> &e)
: env(e) { }
private:
const map<string, Function> &env;
Scope<Interval> scope;
unsigned long ptmp = 0; // ID for all tmp vars in a prefetch op
private:
using IRMutator::visit;
// Strip down the tuple name, e.g. f.*.var into f
string tuple_func(const string &name) {
vector<string> v = split_string(name, ".");
internal_assert(v.size() > 0);
return v[0];
}
// Strip down the tuple name, e.g. f.*.var into var
string tuple_var(const string &name) {
vector<string> v = split_string(name, ".");
internal_assert(v.size() > 0);
return v[v.size()-1];
}
// Lookup a function in the environment
Function get_func(const string &name) {
map<string, Function>::const_iterator iter = env.find(name);
internal_assert(iter != env.end()) << "function not in environment.\n";
return iter->second;
}
// Determine the static type of a named buffer (if available)
// Note: the type of input is only known at runtime (use input.elem_size)
Type get_type(string varname, bool &has_static_type) {
debug(dbg_prefetch2) << " getType(" << varname << ")\n";
Type t = UInt(8);
map<string, Function>::const_iterator varit = env.find(varname);
if (varit != env.end()) {
Function varf = varit->second;
debug(dbg_prefetch2) << " found: " << varit->first << "\n";
if (varf.outputs()) {
vector<Type> varts = varf.output_types();
t = varts[0];
debug(dbg_prefetch2) << " type: " << t << "\n";
}
has_static_type = true;
} else {
debug(dbg_prefetch2) << " could not statically determine type of " << varname
<< ", temporarily using: " << t << "\n";
has_static_type = false;
}
return t;
}
void visit(const Let *op) {
Interval in = bounds_of_expr_in_scope(op->value, scope);
scope.push(op->name, in);
IRMutator::visit(op);
scope.pop(op->name);
}
void visit(const LetStmt *op) {
Interval in = bounds_of_expr_in_scope(op->value, scope);
scope.push(op->name, in);
IRMutator::visit(op);
scope.pop(op->name);
}
void visit(const For *op) {
Stmt body = op->body;
string func_name = tuple_func(op->name);
string ivar_name = tuple_var(op->name);
vector<Prefetch> &prefetches = get_func(func_name).schedule().prefetches();
if (prefetches.empty()) {
debug(dbg_prefetch2) << "InjectPrefetch: " << op->name << " " << func_name << " " << ivar_name;
debug(dbg_prefetch2) << " No prefetch\n";
} else {
debug(dbg_prefetch1) << "InjectPrefetch: " << op->name << " " << func_name << " " << ivar_name;
debug(dbg_prefetch1) << " Found prefetch directive(s)\n";
}
for (const Prefetch &p : prefetches) {
debug(dbg_prefetch1) << "InjectPrefetch: check ivar:" << p.var << "\n";
if (p.var == ivar_name) {
debug(dbg_prefetch0) << " " << func_name
<< " prefetch(" << ivar_name << ", " << p.offset << ")\n";
// Interval prein(op->name, op->name);
// Add in prefetch offset
Expr var = Variable::make(Int(32), op->name);
Interval prein(var + p.offset, var + p.offset);
scope.push(op->name, prein);
map<string, Box> boxes;
boxes = boxes_required(body, scope);
int cnt = 0; // Number of prefetch ops generated
Stmt pstmts; // Generated prefetch statements
debug(dbg_prefetch1) << " boxes required:\n";
for (auto &b : boxes) {
bool do_prefetch = true;
const string &varname = b.first;
Box &box = b.second;
int dims = box.size();
bool has_static_type = true;
Type t = get_type(varname, has_static_type);
debug(dbg_prefetch0) << " prefetch" << ptmp << ": "
<< varname << " (" << t
<< (has_static_type ? "" : ":dynamic_type")
<< ", dims:" << dims << ")\n";
for (int i = 0; i < dims; i++) {
debug(dbg_prefetch1) << " ---\n";
debug(dbg_prefetch1) << " box[" << i << "].min: " << box[i].min << "\n";
debug(dbg_prefetch1) << " box[" << i << "].max: " << box[i].max << "\n";
}
debug(dbg_prefetch1) << " ---------\n";
// TODO: Opt: check box if it should be prefetched?
// TODO - Only prefetch if varying by ivar_name?
// TODO - Don't prefetch if "small" all constant dimensions?
// TODO e.g. see: camera_pipe.cpp corrected matrix(4,3)
string pstr = std::to_string(ptmp++);
string varname_prefetch_buf = varname + ".prefetch_" + pstr + "_buf";
Expr var_prefetch_buf = Variable::make(Int(32), varname_prefetch_buf);
// Make the names for accessing the buffer strides
vector<Expr> stride_var(dims);
for (int i = 0; i < dims; i++) {
string istr = std::to_string(i);
string stride_name = varname + ".stride." + istr;
#if 0 // TODO: Determine if the stride varname is defined - check not yet working
// if (!scope.contains(stride_name)) [
if (env.find(stride_name) == env.end()) {
do_prefetch = false;
debug(dbg_prefetch0) << " " << stride_name << " undefined\n";
break;
}
#endif
stride_var[i] = Variable::make(Int(32), stride_name);
}
// This box should not be prefetched
if (!do_prefetch) {
debug(dbg_prefetch0) << " not prefetching " << varname << "\n";
continue;
}
// Make the names for the prefetch box mins & maxes
vector<string> min_name(dims), max_name(dims);
for (int i = 0; i < dims; i++) {
string istr = std::to_string(i);
min_name[i] = varname + ".prefetch_" + pstr + "_min_" + istr;
max_name[i] = varname + ".prefetch_" + pstr + "_max_" + istr;
}
vector<Expr> min_var(dims), max_var(dims);
for (int i = 0; i < dims; i++) {
min_var[i] = Variable::make(Int(32), min_name[i]);
max_var[i] = Variable::make(Int(32), max_name[i]);
}
// Create a buffer_t object for this prefetch.
vector<Expr> args(dims*3 + 2);
Expr first_elem = Load::make(t, varname, 0, Buffer(), Parameter());
args[0] = Call::make(Handle(), Call::address_of, {first_elem}, Call::PureIntrinsic);
args[1] = make_zero(t);
for (int i = 0; i < dims; i++) {
args[3*i+2] = min_var[i];
args[3*i+3] = max_var[i] - min_var[i] + 1;
args[3*i+4] = stride_var[i];
}
// Inject the prefetch call
vector<Expr> args_prefetch(3);
args_prefetch[0] = dims;
if (has_static_type) {
args_prefetch[1] = t.bytes();
} else {
// Element size for inputs that don't have static types
string elem_size_name = varname + ".elem_size";
Expr elem_size_var = Variable::make(Int(32), elem_size_name);
args_prefetch[1] = elem_size_var;
}
args_prefetch[2] = var_prefetch_buf;
// TODO: Opt: Keep running sum of bytes prefetched on this sequence
// TODO: Opt: Keep running sum of number of prefetch instructions issued
// TODO on this sequence? (to not exceed MAX_PREFETCH)
// TODO: Opt: Generate control code for prefetch_buffer_t in Prefetch.cpp
// TODO Passing box info through a buffer_t results in ~30 additional stores/loads
Stmt stmt_prefetch = Evaluate::make(Call::make(Int(32), Call::prefetch_buffer_t,
args_prefetch, Call::Intrinsic));
if (cnt == 0) { // First prefetch in sequence
pstmts = stmt_prefetch;
} else { // Add to existing sequence
pstmts = Block::make({stmt_prefetch, pstmts});
}
cnt++;
// Inject the create_buffer_t call
Expr prefetch_buf = Call::make(type_of<struct buffer_t *>(), Call::create_buffer_t,
args, Call::Intrinsic);
pstmts = LetStmt::make(varname_prefetch_buf, prefetch_buf, pstmts);
// Inject bounds variable assignments
for (int i = dims-1; i >= 0; i--) {
pstmts = LetStmt::make(max_name[i], box[i].max, pstmts);
pstmts = LetStmt::make(min_name[i], box[i].min, pstmts);
// stride already defined by input buffer
}
}
if (cnt) {
#if 1
// Guard to not prefetch past the end of the iteration space
// TODO: Opt: Use original extent of loop for guard (avoid conservative guard when stripmined)
Expr pcond = likely((Variable::make(Int(32), op->name) + p.offset)
< (op->min + op->extent - 1));
Stmt pguard = IfThenElse::make(pcond, pstmts);
body = Block::make({pguard, body});
debug(dbg_prefetch3) << " prefetch: (cnt:" << cnt << ")\n";
debug(dbg_prefetch3) << pguard << "\n";
#else
body = Block::make({pstmts, body});
#endif
}
scope.pop(op->name);
}
}
body = mutate(body);
stmt = For::make(op->name, op->min, op->extent, op->for_type, op->device_api, body);
}
};
Stmt inject_prefetch(Stmt s, const std::map<std::string, Function> &env)
{
size_t read;
std::string lvl = get_env_variable("HL_DEBUG_PREFETCH", read);
if (read) {
int dbg_level = atoi(lvl.c_str());
dbg_prefetch0 = MAX(dbg_prefetch0 - dbg_level, 0);
dbg_prefetch1 = MAX(dbg_prefetch1 - dbg_level, 0);
dbg_prefetch2 = MAX(dbg_prefetch2 - dbg_level, 0);
dbg_prefetch3 = MAX(dbg_prefetch3 - dbg_level, 0);
}
return InjectPrefetch(env).mutate(s);
}
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 - 2015, GS Group, https://github.com/GSGroup
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
// provided that the above copyright notice and this permission notice appear in all copies.
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#include <stingraykit/Version.h>
#include <stdio.h>
namespace stingray
{
Version Version::FromString(const std::string& version)
{
unsigned major, minor, build;
const int parsed = sscanf(version.c_str(), "%u.%u.%u", &major, &minor, &build);
STINGRAYKIT_CHECK(parsed == 3 || parsed == 2, FormatException(version));
return Version(major, minor, parsed == 3 ? build : optional<unsigned>());
}
}
<commit_msg>Revert "Version: fix parsing"<commit_after>// Copyright (c) 2011 - 2015, GS Group, https://github.com/GSGroup
// Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
// provided that the above copyright notice and this permission notice appear in all copies.
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
// IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#include <stingraykit/Version.h>
#include <stingraykit/string/StringParse.h>
namespace stingray
{
Version Version::FromString(const std::string& version)
{
unsigned major, minor;
optional<unsigned> build;
STINGRAYKIT_CHECK(StringParse(version, "%1%.%2%.%3%", major, minor, build) || StringParse(version, "%1%.%2%", major, minor), FormatException(version));
return Version(major, minor, build);
}
}
<|endoftext|>
|
<commit_before>#ifndef MJOLNIR_CORE_ENERGY_OBSERVER_HPP
#define MJOLNIR_CORE_ENERGY_OBSERVER_HPP
#include <mjolnir/core/ObserverBase.hpp>
#include <mjolnir/core/Unit.hpp>
#include <iostream>
#include <fstream>
#include <iomanip>
namespace mjolnir
{
template<typename traitsT>
class EnergyObserver final : public ObserverBase<traitsT>
{
public:
using base_type = ObserverBase<traitsT>;
using traits_type = typename base_type::traits_type;
using real_type = typename base_type::real_type;
using coordinate_type = typename base_type::coordinate_type;
using system_type = typename base_type::system_type;
using forcefield_type = typename base_type::forcefield_type;
public:
explicit EnergyObserver(const std::string& filename_prefix)
: prefix_(filename_prefix), file_name_(filename_prefix + ".ene")
{
// clear files and throw an error if the files cannot be opened.
this->clear_file(this->file_name_);
}
~EnergyObserver() override {}
void initialize(const std::size_t, const real_type,
const system_type&, const forcefield_type& ff) override
{
using phys_constants = physics::constants<real_type>;
std::ofstream ofs(this->file_name_, std::ios::app);
ofs << "# unit of length : " << phys_constants::length_unit()
<< ", unit of energy : " << phys_constants::energy_unit() << '\n';
ofs << "# timestep ";
const auto names = ff.list_energy_name();
this->widths_.reserve(names.size());
for(std::size_t i=0; i<names.size(); ++i)
{
ofs << names.at(i) << ' ';
this->widths_.push_back(names.at(i).size());
}
ofs << " kinetic_energy\n";
return;
}
// update column names and widths if forcefield changed.
void update(const std::size_t, const real_type,
const system_type&, const forcefield_type& ff) override
{
std::ofstream ofs(this->file_name_, std::ios::app);
ofs << "# timestep ";
const auto names = ff.list_energy_name();
this->widths_.reserve(names.size());
for(std::size_t i=0; i<names.size(); ++i)
{
ofs << names.at(i) << ' ';
this->widths_.push_back(names.at(i).size());
}
ofs << " kinetic_energy\n";
return;
}
void output(const std::size_t step, const real_type,
const system_type& sys, const forcefield_type& ff) override
{
std::ofstream ofs(this->file_name_, std::ios::app);
// if the width exceeds, operator<<(std::ostream, std::string) ignores
// ostream::width and outputs whole string.
ofs << std::setw(11) << std::left << std::to_string(step) << ' ';
const auto energies = ff.dump_energy(sys);
for(std::size_t i=0; i<energies.size(); ++i)
{
ofs << std::setw(this->widths_.at(i)) << std::fixed
<< std::right << energies.at(i) << ' ';
}
ofs << std::setw(14) << std::right << this->calc_kinetic_energy(sys)
<< '\n';
return;
}
void finalize(const std::size_t, const real_type,
const system_type&, const forcefield_type&) override
{/* do nothing. */}
std::string const& prefix() const noexcept override {return this->prefix_;}
private:
void clear_file(const std::string& fname) const
{
std::ofstream ofs(fname);
if(not ofs.good())
{
throw_exception<std::runtime_error>(
"[error] mjolnir::EnergyObserver: file open error: ", fname);
}
return;
}
real_type calc_kinetic_energy(const system_type& sys) const
{
real_type k = 0.0;
for(std::size_t i=0; i<sys.size(); ++i)
{
k += math::length_sq(sys.velocity(i)) * sys.mass(i);
}
return k * 0.5;
}
private:
std::string prefix_;
std::string file_name_;
std::vector<std::size_t> widths_; // column width to format energy values
};
#ifdef MJOLNIR_SEPARATE_BUILD
extern template class EnergyObserver<SimulatorTraits<double, UnlimitedBoundary> >;
extern template class EnergyObserver<SimulatorTraits<float, UnlimitedBoundary> >;
extern template class EnergyObserver<SimulatorTraits<double, CuboidalPeriodicBoundary>>;
extern template class EnergyObserver<SimulatorTraits<float, CuboidalPeriodicBoundary>>;
#endif
} // mjolnir
#endif//MJOLNIR_CORE_ENERGY_OBSERVER_HPP
<commit_msg>feat: output system attributes to .ene file<commit_after>#ifndef MJOLNIR_CORE_ENERGY_OBSERVER_HPP
#define MJOLNIR_CORE_ENERGY_OBSERVER_HPP
#include <mjolnir/core/ObserverBase.hpp>
#include <mjolnir/core/Unit.hpp>
#include <iostream>
#include <fstream>
#include <iomanip>
namespace mjolnir
{
template<typename traitsT>
class EnergyObserver final : public ObserverBase<traitsT>
{
public:
using base_type = ObserverBase<traitsT>;
using traits_type = typename base_type::traits_type;
using real_type = typename base_type::real_type;
using coordinate_type = typename base_type::coordinate_type;
using system_type = typename base_type::system_type;
using forcefield_type = typename base_type::forcefield_type;
public:
explicit EnergyObserver(const std::string& filename_prefix)
: prefix_(filename_prefix), file_name_(filename_prefix + ".ene")
{
// clear files and throw an error if the files cannot be opened.
this->clear_file(this->file_name_);
}
~EnergyObserver() override {}
void initialize(const std::size_t, const real_type,
const system_type& sys, const forcefield_type& ff) override
{
using phys_constants = physics::constants<real_type>;
std::ofstream ofs(this->file_name_, std::ios::app);
ofs << "# unit of length : " << phys_constants::length_unit()
<< ", unit of energy : " << phys_constants::energy_unit() << '\n';
ofs << "# timestep ";
const auto names = ff.list_energy_name();
this->widths_.reserve(names.size());
for(std::size_t i=0; i<names.size(); ++i)
{
ofs << names.at(i) << ' ';
this->widths_.push_back(names.at(i).size());
}
ofs << " kinetic_energy";
for(const auto& attr : sys.attributes())
{
ofs << " attribute:" << attr.first;
}
ofs << '\n';
return;
}
// update column names and widths if forcefield changed.
void update(const std::size_t, const real_type,
const system_type& sys, const forcefield_type& ff) override
{
std::ofstream ofs(this->file_name_, std::ios::app);
ofs << "# timestep ";
const auto names = ff.list_energy_name();
this->widths_.reserve(names.size());
for(std::size_t i=0; i<names.size(); ++i)
{
ofs << names.at(i) << ' ';
this->widths_.push_back(names.at(i).size());
}
ofs << " kinetic_energy";
for(const auto& attr : sys.attributes())
{
ofs << " attribute:" << attr.first;
}
ofs << '\n';
return;
}
void output(const std::size_t step, const real_type,
const system_type& sys, const forcefield_type& ff) override
{
std::ofstream ofs(this->file_name_, std::ios::app);
// if the width exceeds, operator<<(std::ostream, std::string) ignores
// ostream::width and outputs whole string.
ofs << std::setw(11) << std::left << std::to_string(step) << ' ';
const auto energies = ff.dump_energy(sys);
for(std::size_t i=0; i<energies.size(); ++i)
{
ofs << std::setw(this->widths_.at(i)) << std::fixed
<< std::right << energies.at(i) << ' ';
}
ofs << std::setw(14) << std::right << this->calc_kinetic_energy(sys);
for(const auto& attr : sys.attributes())
{
ofs << ' ' << std::setw(10 + attr.first.size()) << std::right
<< attr.second;
}
ofs << '\n';
return;
}
void finalize(const std::size_t, const real_type,
const system_type&, const forcefield_type&) override
{/* do nothing. */}
std::string const& prefix() const noexcept override {return this->prefix_;}
private:
void clear_file(const std::string& fname) const
{
std::ofstream ofs(fname);
if(not ofs.good())
{
throw_exception<std::runtime_error>(
"[error] mjolnir::EnergyObserver: file open error: ", fname);
}
return;
}
real_type calc_kinetic_energy(const system_type& sys) const
{
real_type k = 0.0;
for(std::size_t i=0; i<sys.size(); ++i)
{
k += math::length_sq(sys.velocity(i)) * sys.mass(i);
}
return k * 0.5;
}
private:
std::string prefix_;
std::string file_name_;
std::vector<std::size_t> widths_; // column width to format energy values
};
#ifdef MJOLNIR_SEPARATE_BUILD
extern template class EnergyObserver<SimulatorTraits<double, UnlimitedBoundary> >;
extern template class EnergyObserver<SimulatorTraits<float, UnlimitedBoundary> >;
extern template class EnergyObserver<SimulatorTraits<double, CuboidalPeriodicBoundary>>;
extern template class EnergyObserver<SimulatorTraits<float, CuboidalPeriodicBoundary>>;
#endif
} // mjolnir
#endif//MJOLNIR_CORE_ENERGY_OBSERVER_HPP
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.