text
stringlengths 54
60.6k
|
|---|
<commit_before>#define BOOST_TEST_MODULE trace_data_extraction
#include <boost/test/included/unit_test.hpp>
#include <eosio/chain/trace.hpp>
#include <eosio/chain/transaction.hpp>
#include <eosio/chain/block.hpp>
#include <eosio/chain/block_state.hpp>
#include <eosio/trace_api_plugin/test_common.hpp>
#include <eosio/trace_api_plugin/chain_extraction.hpp>
using namespace eosio;
using namespace eosio::trace_api_plugin;
using namespace eosio::trace_api_plugin::test_common;
using eosio::chain::name;
using eosio::chain::digest_type;
namespace {
chain::transaction_trace_ptr make_transaction_trace( chain::transaction_id_type&& id, uint32_t block_number, uint32_t slot, chain::transaction_receipt_header::status_enum status, std::vector<chain::action_trace> && actions ) {
return std::make_shared<chain::transaction_trace>(chain::transaction_trace{
std::move(id),
block_number,
chain::block_timestamp_type(slot),
{},
chain::transaction_receipt_header{status},
fc::microseconds(0),
0,
false,
std::move(actions),
{},
{},
{},
{},
{}
});
}
chain::action_trace make_action_trace(uint64_t global_sequence, chain::name receiver, chain::name account, chain::name action, std::vector<chain::permission_level>&& authorizations, chain::bytes&& data ) {
chain::action_trace result;
// don't think we need any information other than receiver and global sequence
result.receipt.emplace(chain::action_receipt{
receiver,
"0000000000000000000000000000000000000000000000000000000000000000"_h,
global_sequence,
0,
{},
0,
0
});
result.receiver = receiver;
result.act = chain::action( std::move(authorizations), account, action, std::move(data) );
return result;
}
chain::bytes make_transfer_data( chain::name from, chain::name to, chain::asset quantity, std::string&& memo) {
fc::datastream<size_t> ps;
fc::raw::pack(ps, from, to, quantity, memo);
chain::bytes result(ps.tellp());
if( result.size() ) {
fc::datastream<char*> ds( result.data(), size_t(result.size()) );
fc::raw::pack(ds, from, to, quantity, memo);
}
return result;
}
auto get_private_key( name keyname, std::string role = "owner" ) {
auto secret = fc::sha256::hash( keyname.to_string() + role );
return chain::private_key_type::regenerate<fc::ecc::private_key_shim>( secret );
}
auto get_public_key( name keyname, std::string role = "owner" ) {
return get_private_key( keyname, role ).get_public_key();
}
auto create_test_block_state( std::vector<chain::transaction_metadata_ptr> trx_metas ) {
chain::signed_block_ptr block = std::make_shared<chain::signed_block>();
for( auto& trx_meta : trx_metas ) {
block->transactions.emplace_back( *trx_meta->packed_trx());
}
block->producer = eosio::chain::config::system_account_name;
auto priv_key = get_private_key( block->producer, "active" );
auto pub_key = get_public_key( block->producer, "active" );
auto prev = std::make_shared<chain::block_state>();
auto header_bmroot = digest_type::hash( std::make_pair( block->digest(), prev->blockroot_merkle.get_root()));
auto sig_digest = digest_type::hash( std::make_pair( header_bmroot, prev->pending_schedule.schedule_hash ));
block->producer_signature = priv_key.sign( sig_digest );
std::vector<chain::private_key_type> signing_keys;
signing_keys.emplace_back( std::move( priv_key ));
auto signer = [&]( digest_type d ) {
std::vector<chain::signature_type> result;
result.reserve( signing_keys.size());
for( const auto& k: signing_keys )
result.emplace_back( k.sign( d ));
return result;
};
chain::pending_block_header_state pbhs;
pbhs.producer = block->producer;
chain::producer_authority_schedule schedule = {0, {chain::producer_authority{block->producer,
chain::block_signing_authority_v0{1, {{pub_key, 1}}}}}};
pbhs.active_schedule = schedule;
pbhs.valid_block_signing_authority = chain::block_signing_authority_v0{1, {{pub_key, 1}}};
auto bsp = std::make_shared<chain::block_state>(
std::move( pbhs ),
std::move( block ),
std::move( trx_metas ),
chain::protocol_feature_set(),
[]( chain::block_timestamp_type timestamp,
const fc::flat_set<digest_type>& cur_features,
const std::vector<digest_type>& new_features ) {},
signer
);
return bsp;
}
chain::block_state_ptr make_block_state( chain::block_id_type id, chain::block_id_type previous, uint32_t height,
uint32_t slot, chain::name producer,
std::vector<std::tuple<chain::transaction_id_type, chain::transaction_receipt_header::status_enum>> transactions ) {
// TODO: it was going to be very complicated to produce a proper block_state_ptr, this can probably be changed
// to some sort of intermediate form that a shim interface can extract from a block_state_ptr to make testing
// and refactoring easier.
return {};
}
}
struct extraction_test_fixture {
/**
* MOCK implementation of the logfile input API
*/
struct mock_logfile_provider_type {
mock_logfile_provider_type(extraction_test_fixture& fixture)
:fixture(fixture)
{}
/**
* append an entry to the end of the data log
*
* @param entry : the entry to append
* @return the offset in the log where that entry is written
*/
uint64_t append_data_log( const data_log_entry& entry ) {
fixture.data_log.emplace_back(entry);
return fixture.data_log.size() - 1;
}
/**
* Append an entry to the metadata log
*
* @param entry
* @return
*/
uint64_t append_metadata_log( const metadata_log_entry& entry ) {
if (entry.contains<block_entry_v0>()) {
const auto& b = entry.get<block_entry_v0>();
fixture.block_entry_for_height[b.number] = b;
} else if (entry.contains<lib_entry_v0>()) {
const auto& lib = entry.get<lib_entry_v0>();
fixture.max_lib = std::max(fixture.max_lib, lib.lib);
} else {
BOOST_FAIL("Unknown metadata log entry emitted");
}
return fixture.metadata_offset++;
}
extraction_test_fixture& fixture;
};
/**
* TODO: initialize extraction implementation here with `mock_logfile_provider` as template param
*/
extraction_test_fixture()
: extraction_impl(mock_logfile_provider_type(*this), [](std::exception_ptr eptr) {})
{
}
void signal_applied_transaction( const chain::transaction_trace_ptr& trace, const chain::signed_transaction& strx ) {
extraction_impl.signal_applied_transaction(trace, strx);
}
void signal_accepted_block( const chain::block_state_ptr& bsp ) {
extraction_impl.signal_accepted_block(bsp);
}
// fixture data and methods
std::map<uint64_t, block_entry_v0> block_entry_for_height = {};
uint64_t metadata_offset = 0;
uint64_t max_lib = 0;
std::vector<data_log_entry> data_log = {};
chain_extraction_impl_type<mock_logfile_provider_type> extraction_impl;
};
BOOST_AUTO_TEST_SUITE(block_extraction)
BOOST_FIXTURE_TEST_CASE(basic_single_transaction_block, extraction_test_fixture)
{
// apply a basic transfer
//
signal_applied_transaction(
make_transaction_trace(
"0000000000000000000000000000000000000000000000000000000000000001"_h,
1,
1,
chain::transaction_receipt_header::executed,
{
make_action_trace(0, "eosio.token"_n, "eosio.token"_n, "transfer"_n, {{ "alice"_n, "active"_n }}, make_transfer_data( "alice"_n, "bob"_n, "0.0001 SYS"_t, "Memo!" ) ),
make_action_trace(1, "alice"_n, "eosio.token"_n, "transfer"_n, {{ "alice"_n, "active"_n }}, make_transfer_data( "alice"_n, "bob"_n, "0.0001 SYS"_t, "Memo!" ) ),
make_action_trace(2, "bob"_n, "eosio.token"_n, "transfer"_n, {{ "alice"_n, "active"_n }}, make_transfer_data( "alice"_n, "bob"_n, "0.0001 SYS"_t, "Memo!" ) )
}
),
{
// I don't think we will need any data from here?
}
);
// accept the block with one transaction
//
signal_accepted_block(
make_block_state(
"b000000000000000000000000000000000000000000000000000000000000001"_h,
"0000000000000000000000000000000000000000000000000000000000000000"_h,
1,
1,
"bp.one"_n,
{
{ "0000000000000000000000000000000000000000000000000000000000000001"_h, chain::transaction_receipt_header::executed }
}
)
);
// Verify that the blockheight and LIB are correct
//
const uint64_t expected_lib = 0;
const block_entry_v0 expected_entry {
"b000000000000000000000000000000000000000000000000000000000000001"_h,
1,
0
};
const block_trace_v0 expected_trace {
"b000000000000000000000000000000000000000000000000000000000000001"_h,
1,
"0000000000000000000000000000000000000000000000000000000000000000"_h,
chain::block_timestamp_type(1),
"bp.one"_n,
{
{
"0000000000000000000000000000000000000000000000000000000000000001"_h,
chain::transaction_receipt_header::executed,
{
{
0,
"eosio.token"_n, "eosio.token"_n, "transfer"_n,
{{ "alice"_n, "active"_n }},
make_transfer_data( "alice"_n, "bob"_n, "0.0001 SYS"_t, "Memo!" )
},
{
1,
"alice"_n, "eosio.token"_n, "transfer"_n,
{{ "alice"_n, "active"_n }},
make_transfer_data( "alice"_n, "bob"_n, "0.0001 SYS"_t, "Memo!" )
},
{
2,
"bob"_n, "eosio.token"_n, "transfer"_n,
{{ "alice"_n, "active"_n }},
make_transfer_data( "alice"_n, "bob"_n, "0.0001 SYS"_t, "Memo!" )
}
}
}
}
};
BOOST_REQUIRE_EQUAL(max_lib, 0);
BOOST_REQUIRE(block_entry_for_height.count(1) > 0);
BOOST_REQUIRE_EQUAL(block_entry_for_height.at(1), expected_entry);
BOOST_REQUIRE(data_log.size() >= expected_entry.offset);
BOOST_REQUIRE(data_log.at(expected_entry.offset).contains<block_trace_v0>());
BOOST_REQUIRE_EQUAL(data_log.at(expected_entry.offset).get<block_trace_v0>(), expected_trace);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>First test passing<commit_after>#define BOOST_TEST_MODULE trace_data_extraction
#include <boost/test/included/unit_test.hpp>
#include <eosio/chain/trace.hpp>
#include <eosio/chain/transaction.hpp>
#include <eosio/chain/block.hpp>
#include <eosio/chain/block_state.hpp>
#include <eosio/trace_api_plugin/test_common.hpp>
#include <eosio/trace_api_plugin/chain_extraction.hpp>
#include <fc/bitutil.hpp>
using namespace eosio;
using namespace eosio::trace_api_plugin;
using namespace eosio::trace_api_plugin::test_common;
using eosio::chain::name;
using eosio::chain::digest_type;
namespace {
chain::transaction_trace_ptr make_transaction_trace( const chain::transaction_id_type& id, uint32_t block_number,
uint32_t slot, chain::transaction_receipt_header::status_enum status, std::vector<chain::action_trace>&& actions ) {
return std::make_shared<chain::transaction_trace>(chain::transaction_trace{
id,
block_number,
chain::block_timestamp_type(slot),
{},
chain::transaction_receipt_header{status},
fc::microseconds(0),
0,
false,
std::move(actions),
{},
{},
{},
{},
{}
});
}
chain::bytes make_transfer_data( chain::name from, chain::name to, chain::asset quantity, std::string&& memo ) {
fc::datastream<size_t> ps;
fc::raw::pack(ps, from, to, quantity, memo);
chain::bytes result(ps.tellp());
if( result.size() ) {
fc::datastream<char*> ds( result.data(), size_t(result.size()) );
fc::raw::pack(ds, from, to, quantity, memo);
}
return result;
}
auto get_private_key( name keyname, std::string role = "owner" ) {
auto secret = fc::sha256::hash( keyname.to_string() + role );
return chain::private_key_type::regenerate<fc::ecc::private_key_shim>( secret );
}
auto get_public_key( name keyname, std::string role = "owner" ) {
return get_private_key( keyname, role ).get_public_key();
}
auto make_transfer_action( chain::name from, chain::name to, chain::asset quantity, std::string memo ) {
return chain::action( std::vector<chain::permission_level> {{from, chain::config::active_name}},
"eosio.token"_n, "transfer"_n, make_transfer_data( from, to, quantity, std::move(memo) ) );
}
auto make_packed_trx( std::vector<chain::action> actions ) {
chain::signed_transaction trx;
trx.actions = std::move( actions );
return packed_transaction( trx );
}
chain::action_trace make_action_trace( uint64_t global_sequence, chain::action act, chain::name receiver ) {
chain::action_trace result;
// don't think we need any information other than receiver and global sequence
result.receipt.emplace(chain::action_receipt{
receiver,
digest_type::hash(act),
global_sequence,
0,
{},
0,
0
});
result.receiver = receiver;
result.act = std::move(act);
return result;
}
auto make_block_state( chain::block_id_type previous, uint32_t height, uint32_t slot, chain::name producer,
std::vector<chain::packed_transaction> trxs ) {
chain::signed_block_ptr block = std::make_shared<chain::signed_block>();
for( auto& trx : trxs ) {
block->transactions.emplace_back( trx );
}
block->producer = producer;
block->timestamp = chain::block_timestamp_type(slot);
// make sure previous contains correct block # so block_header::block_num() returns correct value
if( previous == chain::block_id_type() ) {
previous._hash[0] &= 0xffffffff00000000;
previous._hash[0] += fc::endian_reverse_u32(height - 1);
}
block->previous = previous;
auto priv_key = get_private_key( block->producer, "active" );
auto pub_key = get_public_key( block->producer, "active" );
auto prev = std::make_shared<chain::block_state>();
auto header_bmroot = digest_type::hash( std::make_pair( block->digest(), prev->blockroot_merkle.get_root()));
auto sig_digest = digest_type::hash( std::make_pair( header_bmroot, prev->pending_schedule.schedule_hash ));
block->producer_signature = priv_key.sign( sig_digest );
std::vector<chain::private_key_type> signing_keys;
signing_keys.emplace_back( std::move( priv_key ));
auto signer = [&]( digest_type d ) {
std::vector<chain::signature_type> result;
result.reserve( signing_keys.size());
for( const auto& k: signing_keys )
result.emplace_back( k.sign( d ));
return result;
};
chain::pending_block_header_state pbhs;
pbhs.producer = block->producer;
pbhs.timestamp = block->timestamp;
chain::producer_authority_schedule schedule = {0, {chain::producer_authority{block->producer,
chain::block_signing_authority_v0{1, {{pub_key, 1}}}}}};
pbhs.active_schedule = schedule;
pbhs.valid_block_signing_authority = chain::block_signing_authority_v0{1, {{pub_key, 1}}};
auto bsp = std::make_shared<chain::block_state>(
std::move( pbhs ),
std::move( block ),
std::vector<chain::transaction_metadata_ptr>(),
chain::protocol_feature_set(),
[]( chain::block_timestamp_type timestamp,
const fc::flat_set<digest_type>& cur_features,
const std::vector<digest_type>& new_features ) {},
signer
);
bsp->block_num = height;
return bsp;
}
}
struct extraction_test_fixture {
/**
* MOCK implementation of the logfile input API
*/
struct mock_logfile_provider_type {
mock_logfile_provider_type(extraction_test_fixture& fixture)
:fixture(fixture)
{}
/**
* append an entry to the end of the data log
*
* @param entry : the entry to append
* @return the offset in the log where that entry is written
*/
uint64_t append_data_log( const data_log_entry& entry ) {
fixture.data_log.emplace_back(entry);
return fixture.data_log.size() - 1;
}
/**
* Append an entry to the metadata log
*
* @param entry
* @return
*/
uint64_t append_metadata_log( const metadata_log_entry& entry ) {
if (entry.contains<block_entry_v0>()) {
const auto& b = entry.get<block_entry_v0>();
fixture.block_entry_for_height[b.number] = b;
} else if (entry.contains<lib_entry_v0>()) {
const auto& lib = entry.get<lib_entry_v0>();
fixture.max_lib = std::max(fixture.max_lib, lib.lib);
} else {
BOOST_FAIL("Unknown metadata log entry emitted");
}
return fixture.metadata_offset++;
}
extraction_test_fixture& fixture;
};
extraction_test_fixture()
: extraction_impl(mock_logfile_provider_type(*this), [](std::exception_ptr eptr) {})
{
}
void signal_applied_transaction( const chain::transaction_trace_ptr& trace, const chain::signed_transaction& strx ) {
extraction_impl.signal_applied_transaction(trace, strx);
}
void signal_accepted_block( const chain::block_state_ptr& bsp ) {
extraction_impl.signal_accepted_block(bsp);
}
// fixture data and methods
std::map<uint64_t, block_entry_v0> block_entry_for_height = {};
uint64_t metadata_offset = 0;
uint64_t max_lib = 0;
std::vector<data_log_entry> data_log = {};
chain_extraction_impl_type<mock_logfile_provider_type> extraction_impl;
};
BOOST_AUTO_TEST_SUITE(block_extraction)
BOOST_FIXTURE_TEST_CASE(basic_single_transaction_block, extraction_test_fixture)
{
auto act1 = make_transfer_action( "alice"_n, "bob"_n, "0.0001 SYS"_t, "Memo!" );
auto act2 = make_transfer_action( "alice"_n, "bob"_n, "0.0001 SYS"_t, "Memo!" );
auto act3 = make_transfer_action( "alice"_n, "bob"_n, "0.0001 SYS"_t, "Memo!" );
auto actt1 = make_action_trace( 0, act1, "eosio.token"_n );
auto actt2 = make_action_trace( 1, act1, "alice"_n );
auto actt3 = make_action_trace( 2, act1, "bob"_n );
auto ptrx1 = make_packed_trx( { act1, act2, act3 } );
// apply a basic transfer
//
signal_applied_transaction(
make_transaction_trace(
ptrx1.id(),
1,
1,
chain::transaction_receipt_header::executed,
{ actt1, actt2, actt3 }
),
{
// I don't think we will need any data from here?
}
);
// accept the block with one transaction
auto bsp1 = make_block_state(
chain::block_id_type(),
1,
1,
"bp.one"_n,
{ chain::packed_transaction(ptrx1) } );
signal_accepted_block( bsp1 );
// Verify that the blockheight and LIB are correct
//
const uint64_t expected_lib = 0;
const block_entry_v0 expected_entry {
bsp1->id,
1,
0
};
const block_trace_v0 expected_trace {
bsp1->id,
1,
bsp1->prev(),
chain::block_timestamp_type(1),
"bp.one"_n,
{
{
ptrx1.id(),
chain::transaction_receipt_header::executed,
{
{
0,
"eosio.token"_n, "eosio.token"_n, "transfer"_n,
{{ "alice"_n, "active"_n }},
make_transfer_data( "alice"_n, "bob"_n, "0.0001 SYS"_t, "Memo!" )
},
{
1,
"alice"_n, "eosio.token"_n, "transfer"_n,
{{ "alice"_n, "active"_n }},
make_transfer_data( "alice"_n, "bob"_n, "0.0001 SYS"_t, "Memo!" )
},
{
2,
"bob"_n, "eosio.token"_n, "transfer"_n,
{{ "alice"_n, "active"_n }},
make_transfer_data( "alice"_n, "bob"_n, "0.0001 SYS"_t, "Memo!" )
}
}
}
}
};
BOOST_REQUIRE_EQUAL(max_lib, 0);
BOOST_REQUIRE(block_entry_for_height.count(1) > 0);
BOOST_REQUIRE_EQUAL(block_entry_for_height.at(1), expected_entry);
BOOST_REQUIRE(data_log.size() >= expected_entry.offset);
BOOST_REQUIRE(data_log.at(expected_entry.offset).contains<block_trace_v0>());
BOOST_REQUIRE_EQUAL(data_log.at(expected_entry.offset).get<block_trace_v0>(), expected_trace);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>
|
<commit_before>// Copyright 2008, Google Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. Neither the name of Google Inc. nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// The file contains the implementation of the File methods specific to
// the win32 platform.
// TODO: likely there are better ways to accomplish Delete and
// CreateNewTempFile.
#include "kml/base/file.h"
#include <windows.h>
#include <tchar.h>
#include <xstring>
#include <algorithm>
namespace kmlbase {
// Internal to the win32 file class. We need a conversion from string to
// LPCWSTR.
static std::wstring Str2Wstr(const string& str) {
std::wstring wstr(str.length(), L'');
std::copy(str.begin(), str.end(), wstr.begin());
return wstr;
}
// Internal to the win32 file class. We need a conversion from std::wstring to
// string.
string Wstr2Str(const std::wstring& wstr) {
size_t s = wstr.size();
string str(static_cast<int>(s+1), 0);
WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), static_cast<int>(s), &str[0],
static_cast<int>(s), NULL, NULL);
return str;
}
bool File::Exists(const string& full_path) {
if (full_path.empty()) {
return false;
}
std::wstring wstr = Str2Wstr(full_path);
DWORD attrs = ::GetFileAttributes(wstr.c_str());
return (attrs != INVALID_FILE_ATTRIBUTES) &&
((attrs & FILE_ATTRIBUTE_DIRECTORY) == 0);
}
bool File::Delete(const string& filepath) {
if (filepath.empty()) {
return false;
}
std::wstring wstr = Str2Wstr(filepath);
return ::DeleteFile(wstr.c_str()) ? true : false;
}
static const unsigned int BUFSIZE = 1024;
DWORD dwBufSize = BUFSIZE;
DWORD dwRetVal;
TCHAR lpPathBuffer[BUFSIZE];
UINT uRetVal;
TCHAR szTempName[BUFSIZE];
// http://msdn.microsoft.com/en-us/library/aa363875(VS.85).aspx
bool File::CreateNewTempFile(string* path) {
if (!path) {
return false;
}
// Get the temp path.
dwRetVal = ::GetTempPath(dwBufSize, lpPathBuffer);
if (dwRetVal > dwBufSize || (dwRetVal == 0)) {
return false;
}
// Create a temporary file.
uRetVal = ::GetTempFileName(lpPathBuffer, TEXT("libkml"), 0, szTempName);
if (uRetVal == 0) {
return false;
}
string str = Wstr2Str(szTempName);
path->assign(str.c_str(), strlen(str.c_str()));
return true;
}
} // end namespace kmlbase
<commit_msg>_WIN32 guard for including windows headers<commit_after>// Copyright 2008, Google Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. Neither the name of Google Inc. nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// The file contains the implementation of the File methods specific to
// the win32 platform.
// TODO: likely there are better ways to accomplish Delete and
// CreateNewTempFile.
#ifdef _WIN32
#include "kml/base/file.h"
#include <windows.h>
#include <tchar.h>
#include <xstring>
#include <algorithm>
namespace kmlbase {
// Internal to the win32 file class. We need a conversion from string to
// LPCWSTR.
static std::wstring Str2Wstr(const string& str) {
std::wstring wstr(str.length(), L'');
std::copy(str.begin(), str.end(), wstr.begin());
return wstr;
}
// Internal to the win32 file class. We need a conversion from std::wstring to
// string.
string Wstr2Str(const std::wstring& wstr) {
size_t s = wstr.size();
string str(static_cast<int>(s+1), 0);
WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), static_cast<int>(s), &str[0],
static_cast<int>(s), NULL, NULL);
return str;
}
bool File::Exists(const string& full_path) {
if (full_path.empty()) {
return false;
}
std::wstring wstr = Str2Wstr(full_path);
DWORD attrs = ::GetFileAttributes(wstr.c_str());
return (attrs != INVALID_FILE_ATTRIBUTES) &&
((attrs & FILE_ATTRIBUTE_DIRECTORY) == 0);
}
bool File::Delete(const string& filepath) {
if (filepath.empty()) {
return false;
}
std::wstring wstr = Str2Wstr(filepath);
return ::DeleteFile(wstr.c_str()) ? true : false;
}
static const unsigned int BUFSIZE = 1024;
DWORD dwBufSize = BUFSIZE;
DWORD dwRetVal;
TCHAR lpPathBuffer[BUFSIZE];
UINT uRetVal;
TCHAR szTempName[BUFSIZE];
// http://msdn.microsoft.com/en-us/library/aa363875(VS.85).aspx
bool File::CreateNewTempFile(string* path) {
if (!path) {
return false;
}
// Get the temp path.
dwRetVal = ::GetTempPath(dwBufSize, lpPathBuffer);
if (dwRetVal > dwBufSize || (dwRetVal == 0)) {
return false;
}
// Create a temporary file.
uRetVal = ::GetTempFileName(lpPathBuffer, TEXT("libkml"), 0, szTempName);
if (uRetVal == 0) {
return false;
}
string str = Wstr2Str(szTempName);
path->assign(str.c_str(), strlen(str.c_str()));
return true;
}
} // end namespace kmlbase
#endif
<|endoftext|>
|
<commit_before>#include "ofdpa_bridge.hpp"
#include "roflibs/netlink/clogging.hpp"
#include <cassert>
#include <map>
#include <rofl/common/openflow/cofport.h>
namespace basebox {
ofdpa_bridge::ofdpa_bridge(rofl::rofl_ofdpa_fm_driver &fm_driver)
: fm_driver(fm_driver) {}
ofdpa_bridge::~ofdpa_bridge() {}
void ofdpa_bridge::set_bridge_interface(const rofcore::crtlink &rtl) {
if (AF_BRIDGE != rtl.get_family() || 0 != rtl.get_master()) {
rofcore::logging::error << __PRETTY_FUNCTION__
<< " not a bridge master: " << rtl << std::endl;
return;
}
this->bridge = rtl;
fm_driver.enable_policy_arp(1,1);
}
static int find_next_bit(int i, uint32_t x) {
int j;
if (i >= 32)
return -1;
/* find first bit */
if (i < 0)
return __builtin_ffs(x);
/* mask off prior finds to get next */
j = __builtin_ffs(x >> i);
return j ? j + i : 0;
}
void ofdpa_bridge::add_interface(const rofcore::crtlink &rtl) {
using rofcore::logging;
// sanity checks
if (0 == bridge.get_ifindex()) {
logging::error << __PRETTY_FUNCTION__
<< " cannot attach interface without bridge: " << rtl
<< std::endl;
return;
}
if (AF_BRIDGE != rtl.get_family()) {
logging::error << __PRETTY_FUNCTION__ << rtl
<< " is not a bridge interface " << std::endl;
return;
}
if (bridge.get_ifindex() != rtl.get_master()) {
logging::error << __PRETTY_FUNCTION__ << rtl
<< " is not a slave of this bridge interface " << std::endl;
return;
}
const struct rtnl_link_bridge_vlan *br_vlan = rtl.get_br_vlan();
for (int k = 0; k < RTNL_LINK_BRIDGE_VLAN_BITMAP_LEN; k++) {
int base_bit;
uint32_t a = br_vlan->vlan_bitmap[k];
base_bit = k * 32;
int i = -1;
int done = 0;
while (!done) {
int j = find_next_bit(i, a);
if (j > 0) {
int vid = j - 1 + base_bit;
bool egress_untagged = false;
// check if egress is untagged
if (br_vlan->untagged_bitmap[k] & 1 << (j - 1)) {
egress_untagged = true;
}
uint32_t group = fm_driver.enable_port_vid_egress(rtl.get_devname(),
vid, egress_untagged);
assert(group && "invalid group identifier");
if (rofl::openflow::OFPG_MAX == group) {
logging::error << __PRETTY_FUNCTION__
<< " failed to set vid on egress " << std::endl;
i = j;
continue;
}
l2_domain[vid].push_back(group);
if (br_vlan->pvid == vid) {
fm_driver.enable_port_pvid_ingress(rtl.get_devname(), vid);
} else {
fm_driver.enable_port_vid_ingress(rtl.get_devname(), vid);
}
// // todo check if vid is okay as an id as well
// group = fm_driver.enable_group_l2_multicast(vid, vid, l2_domain[vid],
// 1 != l2_domain[vid].size());
//
// if (1 == l2_domain[vid].size()) { // todo maybe unnecessary
// fm_driver.enable_policy_arp(vid, group);
// }
i = j;
} else {
done = 1;
}
}
}
}
void ofdpa_bridge::update_vlans(const std::string &devname,
const rtnl_link_bridge_vlan *old_br_vlan,
const rtnl_link_bridge_vlan *new_br_vlan) {
using rofcore::logging;
for (int k = 0; k < RTNL_LINK_BRIDGE_VLAN_BITMAP_LEN; k++) {
int base_bit;
uint32_t a = old_br_vlan->vlan_bitmap[k];
uint32_t b = new_br_vlan->vlan_bitmap[k];
uint32_t c = old_br_vlan->untagged_bitmap[k];
uint32_t d = new_br_vlan->untagged_bitmap[k];
uint32_t vlan_diff = a ^ b;
uint32_t untagged_diff = c ^ d;
base_bit = k * 32;
int i = -1;
int done = 0;
while (!done) {
int j = find_next_bit(i, vlan_diff);
if (j > 0) {
// vlan added or removed
int vid = j - 1 + base_bit;
bool egress_untagged = false;
// check if egress is untagged
if (new_br_vlan->untagged_bitmap[k] & 1 << (j - 1)) {
egress_untagged = true;
// clear untagged_diff bit
untagged_diff &= ~((uint32_t)1 << (j - 1));
}
if (new_br_vlan->vlan_bitmap[k] & 1 << (j - 1)) {
// vlan added
uint32_t group =
fm_driver.enable_port_vid_egress(devname, vid, egress_untagged);
assert(group && "invalid group identifier");
if (rofl::openflow::OFPG_MAX == group) {
logging::error << __PRETTY_FUNCTION__
<< " failed to set vid on egress " << std::endl;
i = j;
continue;
}
l2_domain[vid].push_back(group);
if (new_br_vlan->pvid == vid) {
// todo check for existing pvid?
fm_driver.enable_port_pvid_ingress(devname, vid);
} else {
fm_driver.enable_port_vid_ingress(devname, vid);
}
// todo check if vid is okay as an id as well
// group = fm_driver.enable_group_l2_multicast(
// vid, vid, l2_domain[vid], 1 != l2_domain[vid].size());
//// enable arp flooding as well
//#if DISABLED_TO_TEST
// if (1 == l2_domain[vid].size()) { // todo maybe unnecessary
// fm_driver.enable_policy_arp(vid, group);
// }
//#endif
} else {
// vlan removed
}
i = j;
} else {
done = 1;
}
}
#if 0 // not yet implemented the update
done = 0;
i = -1;
while (!done) {
// vlan is existing, but swapping egress tagged/untagged
int j = find_next_bit(i, untagged_diff);
if (j > 0) {
// egress untagged changed
int vid = j - 1 + base_bit;
bool egress_untagged = false;
// check if egress is untagged
if (new_br_vlan->untagged_bitmap[k] & 1 << (j-1)) {
egress_untagged = true;
}
// XXX implement update
fm_driver.update_port_vid_egress(devname, vid, egress_untagged);
i = j;
} else {
done = 1;
}
}
#endif
}
}
void ofdpa_bridge::update_interface(const rofcore::crtlink &oldlink,
const rofcore::crtlink &newlink) {
using rofcore::crtlink;
using rofcore::logging;
// sanity checks
if (0 == bridge.get_ifindex()) {
logging::error << __PRETTY_FUNCTION__
<< " cannot update interface without bridge" << std::endl;
return;
}
if (AF_BRIDGE != newlink.get_family()) {
logging::error << __PRETTY_FUNCTION__ << newlink
<< " is not a bridge interface" << std::endl;
return;
}
// if (AF_BRIDGE != oldlink.get_family()) {
// logging::error << __PRETTY_FUNCTION__ << oldlink << " is
// not a bridge interface" << std::endl;
// return;
// }
if (bridge.get_ifindex() != newlink.get_master()) {
logging::error << __PRETTY_FUNCTION__ << newlink
<< " is not a slave of this bridge interface" << std::endl;
return;
}
if (bridge.get_ifindex() != oldlink.get_master()) {
logging::error << __PRETTY_FUNCTION__ << newlink
<< " is not a slave of this bridge interface" << std::endl;
return;
}
if (newlink.get_devname().compare(oldlink.get_devname())) {
logging::info << __PRETTY_FUNCTION__
<< " interface rename currently ignored " << std::endl;
// FIXME this has to be handled differently
return;
}
if (not crtlink::are_br_vlan_equal(newlink.get_br_vlan(),
oldlink.get_br_vlan())) {
// vlan updated
update_vlans(oldlink.get_devname(), oldlink.get_br_vlan(),
newlink.get_br_vlan());
}
}
void ofdpa_bridge::delete_interface(const rofcore::crtlink &rtl) {
// XXX update L2 Multicast Group
// get group id
// remove id from l2_domain
// update enable_group_l2_multicast
}
void ofdpa_bridge::add_mac_to_fdb(const uint32_t of_port_no,
const uint16_t vlan,
const rofl::cmacaddr &mac, bool permanent) {
fm_driver.add_bridging_unicast_vlan(mac, vlan, of_port_no, permanent);
}
void ofdpa_bridge::remove_mac_from_fdb(const uint32_t of_port_no, uint16_t vid,
const rofl::cmacaddr &mac) {
fm_driver.remove_bridging_unicast_vlan(mac, vid, of_port_no);
}
} /* namespace basebox */
<commit_msg>catch errors in case of congestion<commit_after>#include "ofdpa_bridge.hpp"
#include "roflibs/netlink/clogging.hpp"
#include <cassert>
#include <map>
#include <rofl/common/openflow/cofport.h>
namespace basebox {
ofdpa_bridge::ofdpa_bridge(rofl::rofl_ofdpa_fm_driver &fm_driver)
: fm_driver(fm_driver) {}
ofdpa_bridge::~ofdpa_bridge() {}
void ofdpa_bridge::set_bridge_interface(const rofcore::crtlink &rtl) {
if (AF_BRIDGE != rtl.get_family() || 0 != rtl.get_master()) {
rofcore::logging::error << __PRETTY_FUNCTION__
<< " not a bridge master: " << rtl << std::endl;
return;
}
this->bridge = rtl;
fm_driver.enable_policy_arp(1,1);
}
static int find_next_bit(int i, uint32_t x) {
int j;
if (i >= 32)
return -1;
/* find first bit */
if (i < 0)
return __builtin_ffs(x);
/* mask off prior finds to get next */
j = __builtin_ffs(x >> i);
return j ? j + i : 0;
}
void ofdpa_bridge::add_interface(const rofcore::crtlink &rtl) {
using rofcore::logging;
// sanity checks
if (0 == bridge.get_ifindex()) {
logging::error << __PRETTY_FUNCTION__
<< " cannot attach interface without bridge: " << rtl
<< std::endl;
return;
}
if (AF_BRIDGE != rtl.get_family()) {
logging::error << __PRETTY_FUNCTION__ << rtl
<< " is not a bridge interface " << std::endl;
return;
}
if (bridge.get_ifindex() != rtl.get_master()) {
logging::error << __PRETTY_FUNCTION__ << rtl
<< " is not a slave of this bridge interface " << std::endl;
return;
}
const struct rtnl_link_bridge_vlan *br_vlan = rtl.get_br_vlan();
for (int k = 0; k < RTNL_LINK_BRIDGE_VLAN_BITMAP_LEN; k++) {
int base_bit;
uint32_t a = br_vlan->vlan_bitmap[k];
base_bit = k * 32;
int i = -1;
int done = 0;
while (!done) {
int j = find_next_bit(i, a);
if (j > 0) {
int vid = j - 1 + base_bit;
bool egress_untagged = false;
// check if egress is untagged
if (br_vlan->untagged_bitmap[k] & 1 << (j - 1)) {
egress_untagged = true;
}
uint32_t group = fm_driver.enable_port_vid_egress(rtl.get_devname(),
vid, egress_untagged);
assert(group && "invalid group identifier");
if (rofl::openflow::OFPG_MAX == group) {
logging::error << __PRETTY_FUNCTION__
<< " failed to set vid on egress " << std::endl;
i = j;
continue;
}
l2_domain[vid].push_back(group);
if (br_vlan->pvid == vid) {
fm_driver.enable_port_pvid_ingress(rtl.get_devname(), vid);
} else {
fm_driver.enable_port_vid_ingress(rtl.get_devname(), vid);
}
// // todo check if vid is okay as an id as well
// group = fm_driver.enable_group_l2_multicast(vid, vid, l2_domain[vid],
// 1 != l2_domain[vid].size());
//
// if (1 == l2_domain[vid].size()) { // todo maybe unnecessary
// fm_driver.enable_policy_arp(vid, group);
// }
i = j;
} else {
done = 1;
}
}
}
}
void ofdpa_bridge::update_vlans(const std::string &devname,
const rtnl_link_bridge_vlan *old_br_vlan,
const rtnl_link_bridge_vlan *new_br_vlan) {
using rofcore::logging;
for (int k = 0; k < RTNL_LINK_BRIDGE_VLAN_BITMAP_LEN; k++) {
int base_bit;
uint32_t a = old_br_vlan->vlan_bitmap[k];
uint32_t b = new_br_vlan->vlan_bitmap[k];
uint32_t c = old_br_vlan->untagged_bitmap[k];
uint32_t d = new_br_vlan->untagged_bitmap[k];
uint32_t vlan_diff = a ^ b;
uint32_t untagged_diff = c ^ d;
base_bit = k * 32;
int i = -1;
int done = 0;
while (!done) {
int j = find_next_bit(i, vlan_diff);
if (j > 0) {
// vlan added or removed
int vid = j - 1 + base_bit;
bool egress_untagged = false;
// check if egress is untagged
if (new_br_vlan->untagged_bitmap[k] & 1 << (j - 1)) {
egress_untagged = true;
// clear untagged_diff bit
untagged_diff &= ~((uint32_t)1 << (j - 1));
}
if (new_br_vlan->vlan_bitmap[k] & 1 << (j - 1)) {
// vlan added
try {
uint32_t group =
fm_driver.enable_port_vid_egress(devname, vid, egress_untagged);
assert(group && "invalid group identifier");
if (rofl::openflow::OFPG_MAX == group) {
logging::error << __PRETTY_FUNCTION__
<< " failed to set vid on egress " << std::endl;
i = j;
continue;
}
l2_domain[vid].push_back(group);
} catch (std::exception &e) {
logging::error << __PRETTY_FUNCTION__ << " caught error1:"
<< e.what() << std::endl;
}
try {
if (new_br_vlan->pvid == vid) {
// todo check for existing pvid?
fm_driver.enable_port_pvid_ingress(devname, vid);
} else {
fm_driver.enable_port_vid_ingress(devname, vid);
}
} catch (std::exception &e) {
logging::error << __PRETTY_FUNCTION__ << " caught error2:"
<< e.what() << std::endl;
}
// todo check if vid is okay as an id as well
// group = fm_driver.enable_group_l2_multicast(
// vid, vid, l2_domain[vid], 1 != l2_domain[vid].size());
//// enable arp flooding as well
//#if DISABLED_TO_TEST
// if (1 == l2_domain[vid].size()) { // todo maybe unnecessary
// fm_driver.enable_policy_arp(vid, group);
// }
//#endif
} else {
// vlan removed
}
i = j;
} else {
done = 1;
}
}
#if 0 // not yet implemented the update
done = 0;
i = -1;
while (!done) {
// vlan is existing, but swapping egress tagged/untagged
int j = find_next_bit(i, untagged_diff);
if (j > 0) {
// egress untagged changed
int vid = j - 1 + base_bit;
bool egress_untagged = false;
// check if egress is untagged
if (new_br_vlan->untagged_bitmap[k] & 1 << (j-1)) {
egress_untagged = true;
}
// XXX implement update
fm_driver.update_port_vid_egress(devname, vid, egress_untagged);
i = j;
} else {
done = 1;
}
}
#endif
}
}
void ofdpa_bridge::update_interface(const rofcore::crtlink &oldlink,
const rofcore::crtlink &newlink) {
using rofcore::crtlink;
using rofcore::logging;
// sanity checks
if (0 == bridge.get_ifindex()) {
logging::error << __PRETTY_FUNCTION__
<< " cannot update interface without bridge" << std::endl;
return;
}
if (AF_BRIDGE != newlink.get_family()) {
logging::error << __PRETTY_FUNCTION__ << newlink
<< " is not a bridge interface" << std::endl;
return;
}
// if (AF_BRIDGE != oldlink.get_family()) {
// logging::error << __PRETTY_FUNCTION__ << oldlink << " is
// not a bridge interface" << std::endl;
// return;
// }
if (bridge.get_ifindex() != newlink.get_master()) {
logging::error << __PRETTY_FUNCTION__ << newlink
<< " is not a slave of this bridge interface" << std::endl;
return;
}
if (bridge.get_ifindex() != oldlink.get_master()) {
logging::error << __PRETTY_FUNCTION__ << newlink
<< " is not a slave of this bridge interface" << std::endl;
return;
}
if (newlink.get_devname().compare(oldlink.get_devname())) {
logging::info << __PRETTY_FUNCTION__
<< " interface rename currently ignored " << std::endl;
// FIXME this has to be handled differently
return;
}
if (not crtlink::are_br_vlan_equal(newlink.get_br_vlan(),
oldlink.get_br_vlan())) {
// vlan updated
update_vlans(oldlink.get_devname(), oldlink.get_br_vlan(),
newlink.get_br_vlan());
}
}
void ofdpa_bridge::delete_interface(const rofcore::crtlink &rtl) {
// XXX update L2 Multicast Group
// get group id
// remove id from l2_domain
// update enable_group_l2_multicast
}
void ofdpa_bridge::add_mac_to_fdb(const uint32_t of_port_no,
const uint16_t vlan,
const rofl::cmacaddr &mac, bool permanent) {
fm_driver.add_bridging_unicast_vlan(mac, vlan, of_port_no, permanent);
}
void ofdpa_bridge::remove_mac_from_fdb(const uint32_t of_port_no, uint16_t vid,
const rofl::cmacaddr &mac) {
fm_driver.remove_bridging_unicast_vlan(mac, vid, of_port_no);
}
} /* namespace basebox */
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* This file is part of the libvisio project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <vector>
#include <string>
#include <algorithm> // std::count
#include <cstdarg>
#include <cstdio>
#include "VSDInternalStream.h"
#include "libvisio_utils.h"
uint8_t libvisio::readU8(librevenge::RVNGInputStream *input)
{
if (!input || input->isEnd())
{
VSD_DEBUG_MSG(("Throwing EndOfStreamException\n"));
throw EndOfStreamException();
}
unsigned long numBytesRead;
uint8_t const *p = input->read(sizeof(uint8_t), numBytesRead);
if (p && numBytesRead == sizeof(uint8_t))
return *(uint8_t const *)(p);
VSD_DEBUG_MSG(("Throwing EndOfStreamException\n"));
throw EndOfStreamException();
}
uint16_t libvisio::readU16(librevenge::RVNGInputStream *input)
{
if (!input || input->isEnd())
{
VSD_DEBUG_MSG(("Throwing EndOfStreamException\n"));
throw EndOfStreamException();
}
unsigned long numBytesRead;
uint8_t const *p = input->read(sizeof(uint16_t), numBytesRead);
if (p && numBytesRead == sizeof(uint16_t))
return (uint16_t)p[0]|((uint16_t)p[1]<<8);
VSD_DEBUG_MSG(("Throwing EndOfStreamException\n"));
throw EndOfStreamException();
}
int16_t libvisio::readS16(librevenge::RVNGInputStream *input)
{
return (int16_t)readU16(input);
}
uint32_t libvisio::readU32(librevenge::RVNGInputStream *input)
{
if (!input || input->isEnd())
{
VSD_DEBUG_MSG(("Throwing EndOfStreamException\n"));
throw EndOfStreamException();
}
unsigned long numBytesRead;
uint8_t const *p = input->read(sizeof(uint32_t), numBytesRead);
if (p && numBytesRead == sizeof(uint32_t))
return (uint32_t)p[0]|((uint32_t)p[1]<<8)|((uint32_t)p[2]<<16)|((uint32_t)p[3]<<24);
VSD_DEBUG_MSG(("Throwing EndOfStreamException\n"));
throw EndOfStreamException();
}
int32_t libvisio::readS32(librevenge::RVNGInputStream *input)
{
return (int32_t)readU32(input);
}
uint64_t libvisio::readU64(librevenge::RVNGInputStream *input)
{
if (!input || input->isEnd())
{
VSD_DEBUG_MSG(("Throwing EndOfStreamException\n"));
throw EndOfStreamException();
}
unsigned long numBytesRead;
uint8_t const *p = input->read(sizeof(uint64_t), numBytesRead);
if (p && numBytesRead == sizeof(uint64_t))
return (uint64_t)p[0]|((uint64_t)p[1]<<8)|((uint64_t)p[2]<<16)|((uint64_t)p[3]<<24)|((uint64_t)p[4]<<32)|((uint64_t)p[5]<<40)|((uint64_t)p[6]<<48)|((uint64_t)p[7]<<56);
VSD_DEBUG_MSG(("Throwing EndOfStreamException\n"));
throw EndOfStreamException();
}
double libvisio::readDouble(librevenge::RVNGInputStream *input)
{
union
{
uint64_t u;
double d;
} tmpUnion;
tmpUnion.u = readU64(input);
return tmpUnion.d;
}
const librevenge::RVNGString libvisio::getColourString(const Colour &c)
{
librevenge::RVNGString sColour;
sColour.sprintf("#%.2x%.2x%.2x", c.r, c.g, c.b);
return sColour;
}
unsigned long libvisio::getRemainingLength(librevenge::RVNGInputStream *const input)
{
if (!input)
throw EndOfStreamException();
const unsigned long begin = (unsigned long) input->tell();
unsigned long end = begin;
if (0 == input->seek(0, librevenge::RVNG_SEEK_END))
{
end = (unsigned long) input->tell();
}
else
{
// librevenge::RVNG_SEEK_END does not work. Use the harder way.
while (!input->isEnd())
{
readU8(input);
++end;
}
}
input->seek(begin, librevenge::RVNG_SEEK_SET);
return end - begin;
}
void libvisio::appendUCS4(librevenge::RVNGString &text, UChar32 ucs4Character)
{
// Convert carriage returns to new line characters
if (ucs4Character == (UChar32) 0x0d || ucs4Character == (UChar32) 0x0e)
ucs4Character = (UChar32) '\n';
unsigned char outbuf[U8_MAX_LENGTH+1];
int i = 0;
U8_APPEND_UNSAFE(&outbuf[0], i, ucs4Character);
outbuf[i] = 0;
text.append((char *)outbuf);
}
void libvisio::debugPrint(const char *format, ...)
{
va_list args;
va_start(args, format);
std::vfprintf(stderr, format, args);
va_end(args);
}
/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<commit_msg>cid#1419957 rewrite to avoid coverity warning<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/*
* This file is part of the libvisio project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <vector>
#include <string>
#include <algorithm> // std::count
#include <cstdarg>
#include <cstdio>
#include "VSDInternalStream.h"
#include "libvisio_utils.h"
uint8_t libvisio::readU8(librevenge::RVNGInputStream *input)
{
if (!input || input->isEnd())
{
VSD_DEBUG_MSG(("Throwing EndOfStreamException\n"));
throw EndOfStreamException();
}
unsigned long numBytesRead;
uint8_t const *p = input->read(sizeof(uint8_t), numBytesRead);
if (p && numBytesRead == sizeof(uint8_t))
return *(uint8_t const *)(p);
VSD_DEBUG_MSG(("Throwing EndOfStreamException\n"));
throw EndOfStreamException();
}
uint16_t libvisio::readU16(librevenge::RVNGInputStream *input)
{
if (!input || input->isEnd())
{
VSD_DEBUG_MSG(("Throwing EndOfStreamException\n"));
throw EndOfStreamException();
}
unsigned long numBytesRead;
uint8_t const *p = input->read(sizeof(uint16_t), numBytesRead);
if (p && numBytesRead == sizeof(uint16_t))
return (uint16_t)p[0]|((uint16_t)p[1]<<8);
VSD_DEBUG_MSG(("Throwing EndOfStreamException\n"));
throw EndOfStreamException();
}
int16_t libvisio::readS16(librevenge::RVNGInputStream *input)
{
return (int16_t)readU16(input);
}
uint32_t libvisio::readU32(librevenge::RVNGInputStream *input)
{
if (!input || input->isEnd())
{
VSD_DEBUG_MSG(("Throwing EndOfStreamException\n"));
throw EndOfStreamException();
}
unsigned long numBytesRead;
uint8_t const *p = input->read(sizeof(uint32_t), numBytesRead);
if (p && numBytesRead == sizeof(uint32_t))
return (uint32_t)p[0]|((uint32_t)p[1]<<8)|((uint32_t)p[2]<<16)|((uint32_t)p[3]<<24);
VSD_DEBUG_MSG(("Throwing EndOfStreamException\n"));
throw EndOfStreamException();
}
int32_t libvisio::readS32(librevenge::RVNGInputStream *input)
{
return (int32_t)readU32(input);
}
uint64_t libvisio::readU64(librevenge::RVNGInputStream *input)
{
if (!input || input->isEnd())
{
VSD_DEBUG_MSG(("Throwing EndOfStreamException\n"));
throw EndOfStreamException();
}
unsigned long numBytesRead;
uint8_t const *p = input->read(sizeof(uint64_t), numBytesRead);
if (p && numBytesRead == sizeof(uint64_t))
return (uint64_t)p[0]|((uint64_t)p[1]<<8)|((uint64_t)p[2]<<16)|((uint64_t)p[3]<<24)|((uint64_t)p[4]<<32)|((uint64_t)p[5]<<40)|((uint64_t)p[6]<<48)|((uint64_t)p[7]<<56);
VSD_DEBUG_MSG(("Throwing EndOfStreamException\n"));
throw EndOfStreamException();
}
double libvisio::readDouble(librevenge::RVNGInputStream *input)
{
union
{
uint64_t u;
double d;
} tmpUnion;
tmpUnion.u = readU64(input);
return tmpUnion.d;
}
const librevenge::RVNGString libvisio::getColourString(const Colour &c)
{
librevenge::RVNGString sColour;
sColour.sprintf("#%.2x%.2x%.2x", c.r, c.g, c.b);
return sColour;
}
unsigned long libvisio::getRemainingLength(librevenge::RVNGInputStream *const input)
{
if (!input)
throw EndOfStreamException();
const long begin = input->tell();
if (input->seek(0, librevenge::RVNG_SEEK_END) != 0)
{
// librevenge::RVNG_SEEK_END does not work. Use the harder way.
while (!input->isEnd())
readU8(input);
}
const long end = input->tell();
input->seek(begin, librevenge::RVNG_SEEK_SET);
if (end < begin)
throw EndOfStreamException();
return static_cast<unsigned long>(end - begin);
}
void libvisio::appendUCS4(librevenge::RVNGString &text, UChar32 ucs4Character)
{
// Convert carriage returns to new line characters
if (ucs4Character == (UChar32) 0x0d || ucs4Character == (UChar32) 0x0e)
ucs4Character = (UChar32) '\n';
unsigned char outbuf[U8_MAX_LENGTH+1];
int i = 0;
U8_APPEND_UNSAFE(&outbuf[0], i, ucs4Character);
outbuf[i] = 0;
text.append((char *)outbuf);
}
void libvisio::debugPrint(const char *format, ...)
{
va_list args;
va_start(args, format);
std::vfprintf(stderr, format, args);
va_end(args);
}
/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<|endoftext|>
|
<commit_before>
#include <cctype>
#include <cstring>
#include "Word.h"
Word& Word::operator=(const String& other)
{
(String&)*this = other;
return *this;
}
bool Word::operator==(const Word& other) const
{
return *(String*)this == other;
}
bool Word::operator!=(const Word& other) const
{
return *(String*)this != other;
}
void Word::split(const String& text, List<Word>& words)
{
const char* str = text.getData();
for(;;)
{
while(isspace(*str))
++str;
if(!*str)
break;
if(*str == '"')
{
++str;
const char* end = str;
for(; *end; ++end)
if(*end == '\\' && end[1] == '"')
++end;
else if(*end == '"')
break;
if(end > str) // TODO: read escaped spaces as ordinary spaces?
words.append(Word(text.substr(str - text.getData(), end - str), true));
str = end;
if(*str)
++str; // skip closing '"'
}
else
{
const char* end = str;
for(; *end; ++end)
if(isspace(*end))
break;
// TODO: read escaped spaces as ordinary spaces
words.append(Word(text.substr(str - text.getData(), end - str), false));
str = end;
}
}
}
void Word::append(const List<Word>& words, String& text)
{
if(words.isEmpty())
return;
int totalLen = words.getSize() * 3;
for(const List<Word>::Node* i = words.getFirst(); i; i = i->getNext())
totalLen += i->data.getLength();
text.setCapacity(totalLen + 16);
const List<Word>::Node* i = words.getFirst();
const List<Word>::Node* previousWord = i;
i->data.appendTo(text);
for(i = i->getNext(); i; i = i->getNext())
{
text.append(/*previousWord->data.terminated ? '\n' : */' ');
i->data.appendTo(text);
previousWord = i;
}
}
void Word::appendTo(String& text) const
{
if(quoted)
{
text.append('"');
text.append(*this);
text.append('"');
}
else // TODO: escape spaces using blackslashes
text.append(*this);
}
void Word::splitLines(const String& text, List<Word>& words)
{
const char* str = text.getData();
for(;;)
{
const char* end = str;
for(; *end; ++end)
if(*end == '\n' || *end == '\r')
break;
// TODO: read escaped spaces as ordinary spaces
Word& word = words.append(Word(text.substr(str - text.getData(), end - str), false));
str = end;
if(*str)
{
if(*str == '\r' && str[1] == '\n')
str += 2;
else
++str;
}
else
break;
}
}
<commit_msg>Remove warning<commit_after>
#include <cctype>
#include <cstring>
#include "Word.h"
Word& Word::operator=(const String& other)
{
(String&)*this = other;
return *this;
}
bool Word::operator==(const Word& other) const
{
return *(String*)this == other;
}
bool Word::operator!=(const Word& other) const
{
return *(String*)this != other;
}
void Word::split(const String& text, List<Word>& words)
{
const char* str = text.getData();
for(;;)
{
while(isspace(*str))
++str;
if(!*str)
break;
if(*str == '"')
{
++str;
const char* end = str;
for(; *end; ++end)
if(*end == '\\' && end[1] == '"')
++end;
else if(*end == '"')
break;
if(end > str) // TODO: read escaped spaces as ordinary spaces?
words.append(Word(text.substr(str - text.getData(), end - str), true));
str = end;
if(*str)
++str; // skip closing '"'
}
else
{
const char* end = str;
for(; *end; ++end)
if(isspace(*end))
break;
// TODO: read escaped spaces as ordinary spaces
words.append(Word(text.substr(str - text.getData(), end - str), false));
str = end;
}
}
}
void Word::append(const List<Word>& words, String& text)
{
if(words.isEmpty())
return;
int totalLen = words.getSize() * 3;
for(const List<Word>::Node* i = words.getFirst(); i; i = i->getNext())
totalLen += i->data.getLength();
text.setCapacity(totalLen + 16);
const List<Word>::Node* i = words.getFirst();
const List<Word>::Node* previousWord = i;
i->data.appendTo(text);
for(i = i->getNext(); i; i = i->getNext())
{
text.append(/*previousWord->data.terminated ? '\n' : */' ');
i->data.appendTo(text);
previousWord = i;
}
}
void Word::appendTo(String& text) const
{
if(quoted)
{
text.append('"');
text.append(*this);
text.append('"');
}
else // TODO: escape spaces using blackslashes
text.append(*this);
}
void Word::splitLines(const String& text, List<Word>& words)
{
const char* str = text.getData();
for(;;)
{
const char* end = str;
for(; *end; ++end)
if(*end == '\n' || *end == '\r')
break;
// TODO: read escaped spaces as ordinary spaces
words.append(Word(text.substr(str - text.getData(), end - str), false));
str = end;
if(*str)
{
if(*str == '\r' && str[1] == '\n')
str += 2;
else
++str;
}
else
break;
}
}
<|endoftext|>
|
<commit_before>#include "qmdatabase.h"
QMDatabase::onCreate()
{
// table for frames
Exec("CREATE TABLE frames ("
"_id INTEGER PRIMARY KEY AUTOINCREMENT,"
"time REAL NOT NULL,"
"step INT NOT NULL,"
"box11 REAL NOT NULL,"
"box12 REAL NOT NULL,"
"box13 REAL NOT NULL,"
"box21 REAL NOT NULL,"
"box22 REAL NOT NULL,"
"box23 REAL NOT NULL,"
"box31 REAL NOT NULL,"
"box32 REAL NOT NULL,"
"box33 REAL NOT NULL)");
// table for molecules
Exec("CREATE TABLE molecules ("
"_id INTEGER PRIMARY KEY AUTOINCREMENT,"
"id INT NOT NULL,"
"name TEXT NOT NULL,"
"frame INT NOT NULL)");
// delete molecules if frame is deleted
Exec("CREATE TRIGGER trig_delete_frame BEFOR DELETE ON frames "
"FOR EACH ROW BEGIN "
"DELETE FROM molecules WHERE molecules.frame = OLD._id;"
" END");
// table for conjugated segments
Exec("CREATE TABLE segments ("
"_id INTEGER PRIMARY KEY AUTOINCREMENT,"
"id INT NOT NULL,"
"name TEXT NOT NULL,"
"occ REAL NOT NULL)");
// additional properties of conjugated segments
Exec("CREATE TABLE segment_properties ("
"_id INTEGER PRIMARY KEY AUTOINCREMENT,"
"segmentid INTEGER NOT NULL,"
"key TEXT NOT NULL,"
"value REAL NOT NULL)");
// delete molecules if frame is deleted
Exec("CREATE TRIGGER trig_delete_frame BEFOR DELETE ON frames "
"FOR EACH ROW BEGIN "
"DELETE FROM molecules WHERE molecules.frame = OLD._id;"
" END");
// table for rigid fragments
Exec("CREATE TABLE fragments ("
"_id INTEGER PRIMARY KEY AUTOINCREMENT,"
"id INT NOT NULL,"
"name TEXT NOT NULL,"
"symmetry INT NOT NULL,"
"type TEXT NOT NULL,"
"resnr INT NOT NULL,"
"mass REAL NOT NULL,"
"charge REAL NOT NULL,"
"molid INT NOT NULL,"
"segment_id INT NOT NULL,"
"segment_index INT NOT NULL,"
"pos_x REAL NOT NULL,"
"pos_y REAL NOT NULL,"
"pos_z REAL NOT NULL,"
"u_x REAL NOT NULL,"
"u_y REAL NOT NULL,"
"u_z REAL NOT NULL,"
"v_x REAL NOT NULL,"
"v_y REAL NOT NULL,"
"v_z REAL NOT NULL)");
// additional properties of rigid fragments
Exec("CREATE TABLE fragment_properties ("
"_id INTEGER PRIMARY KEY AUTOINCREMENT,"
"fragmenttid INTEGER NOT NULL,"
"key TEXT NOT NULL,"
"value REAL NOT NULL)");
// table for pairs
Exec("CREATE TABLE pairs ("
"_id INTEGER PRIMARY KEY AUTOINCREMENT,"
"segment1 INT NOT NULL,"
"segment2 INT NOT NULL,"
"rate12 REAL NOT NULL,"
"rate21 REAL NOT NULL,"
"r_x REAL NOT NULL,"
"r_y REAL NOT NULL,"
"r_z REAL NOT NULL)");
// additional properties of pairs
Exec("CREATE TABLE pair_properties ("
"_id INTEGER PRIMARY KEY AUTOINCREMENT,"
"pairid INTEGER NOT NULL,"
"key TEXT NOT NULL,"
"value REAL NOT NULL)");
}
<commit_msg>some more triggers<commit_after>#include "qmdatabase.h"
void QMDatabase::onCreate()
{
// table for frames
Exec("CREATE TABLE frames ("
"_id INTEGER PRIMARY KEY AUTOINCREMENT,"
"time REAL NOT NULL,"
"step INT NOT NULL,"
"box11 REAL NOT NULL,"
"box12 REAL NOT NULL,"
"box13 REAL NOT NULL,"
"box21 REAL NOT NULL,"
"box22 REAL NOT NULL,"
"box23 REAL NOT NULL,"
"box31 REAL NOT NULL,"
"box32 REAL NOT NULL,"
"box33 REAL NOT NULL)");
// table for molecules
Exec("CREATE TABLE molecules ("
"_id INTEGER PRIMARY KEY AUTOINCREMENT,"
"id INT NOT NULL,"
"name TEXT NOT NULL,"
"frame INT NOT NULL)");
// table for conjugated segments
Exec("CREATE TABLE segments ("
"_id INTEGER PRIMARY KEY AUTOINCREMENT,"
"id INT NOT NULL,"
"name TEXT NOT NULL,"
"occ REAL NOT NULL)");
// additional properties of conjugated segments
Exec("CREATE TABLE segment_properties ("
"_id INTEGER PRIMARY KEY AUTOINCREMENT,"
"segment INTEGER NOT NULL,"
"key TEXT NOT NULL,"
"value REAL NOT NULL)");
// table for rigid fragments
Exec("CREATE TABLE fragments ("
"_id INTEGER PRIMARY KEY AUTOINCREMENT,"
"id INT NOT NULL,"
"name TEXT NOT NULL,"
"symmetry INT NOT NULL,"
"type TEXT NOT NULL,"
"resnr INT NOT NULL,"
"mass REAL NOT NULL,"
"charge REAL NOT NULL,"
"molid INT NOT NULL,"
"segment_id INT NOT NULL,"
"segment_index INT NOT NULL,"
"pos_x REAL NOT NULL,"
"pos_y REAL NOT NULL,"
"pos_z REAL NOT NULL,"
"u_x REAL NOT NULL,"
"u_y REAL NOT NULL,"
"u_z REAL NOT NULL,"
"v_x REAL NOT NULL,"
"v_y REAL NOT NULL,"
"v_z REAL NOT NULL)");
// additional properties of rigid fragments
Exec("CREATE TABLE fragment_properties ("
"_id INTEGER PRIMARY KEY AUTOINCREMENT,"
"fragmenttid INTEGER NOT NULL,"
"key TEXT NOT NULL,"
"value REAL NOT NULL)");
// table for pairs
Exec("CREATE TABLE pairs ("
"_id INTEGER PRIMARY KEY AUTOINCREMENT,"
"segment1 INT NOT NULL,"
"segment2 INT NOT NULL,"
"rate12 REAL NOT NULL,"
"rate21 REAL NOT NULL,"
"r_x REAL NOT NULL,"
"r_y REAL NOT NULL,"
"r_z REAL NOT NULL)");
// additional properties of pairs
Exec("CREATE TABLE pair_properties ("
"_id INTEGER PRIMARY KEY AUTOINCREMENT,"
"pair INTEGER NOT NULL,"
"key TEXT NOT NULL,"
"value REAL NOT NULL)");
// delete molecules if frame is deleted
Exec("CREATE TRIGGER trig_delete_frame BEFOR DELETE ON frames "
"FOR EACH ROW BEGIN "
"DELETE FROM molecules WHERE molecules.frame = OLD._id;"
" END");
// delete segment properties + fragments + pairs if segment is deleted
Exec("CREATE TRIGGER trig_delete_segment BEFOR DELETE ON segments "
"FOR EACH ROW BEGIN "
"DELETE FROM segment_properties WHERE segment_properties=segmentid.segment = OLD._id;"
"DELETE FROM fragments WHERE segment_id=segmentid.frame = OLD._id;"
"DELETE FROM pairs WHERE pairs.segment1 = OLD._id OR pairs.segment2 = OLD._id;"
" END");
// delete fragment properties if fragment is deleted
Exec("CREATE TRIGGER trig_delete_fragment BEFOR DELETE ON fragments "
"FOR EACH ROW BEGIN "
"DELETE FROM fragment_properties WHERE fragment_properties.fragment = OLD._id;"
"DELETE FROM fragments WHERE segment_id=segmentid.frame = OLD._id;"
" END");
// delete pair property if property is deleted
Exec("CREATE TRIGGER trig_delete_pair BEFOR DELETE ON pairs "
"FOR EACH ROW BEGIN "
"DELETE FROM pair_properties WHERE pair_properties.pair = OLD._id;"
" END");
}
<|endoftext|>
|
<commit_before>#include "standard_entity_validators.h"
#include "halley/entity/entity.h"
#include "halley/entity/world.h"
#define DONT_INCLUDE_HALLEY_HPP
#include "component_editor_context.h"
#include "halley/entity/components/transform_2d_component.h"
using namespace Halley;
std::vector<IEntityValidator::Result> TransformEntityValidator::validateEntity(EntityValidator& validator, EntityData& entityData)
{
std::vector<Result> result;
const auto entity = validator.getWorld().findEntity(entityData.getInstanceUUID());
if (entity->isValid()) {
const bool hasTransform = entity->hasComponent<Transform2DComponent>();
if (!hasTransform) {
for (auto c: entity->getChildren()) {
if (c.hasComponent<Transform2DComponent>()) {
result.emplace_back("Entity has no Transform2D component, but some of its children do.", Action("Add Component", AddComponentValidatorActionHandler::makeAction("Transform2D")));
}
}
}
}
return result;
}
bool AddComponentValidatorActionHandler::canHandle(const ConfigNode& actionData)
{
return actionData["action"].asString() == "addComponent" && actionData.hasKey("component");
}
void AddComponentValidatorActionHandler::applyAction(EntityValidator& validator, IEntityEditor& entityEditor, EntityData& entityData, const ConfigNode& actionData)
{
const auto compType = actionData["component"].asString();
entityEditor.addComponent(compType, ConfigNode::MapType());
}
ConfigNode AddComponentValidatorActionHandler::makeAction(String componentName)
{
ConfigNode::MapType action;
action["action"] = "addComponent";
action["component"] = std::move(componentName);
return action;
}
bool ModifyFieldsValidatorActionHandler::canHandle(const ConfigNode& actionData)
{
return actionData["action"].asString() == "modifyField" || actionData["action"].asString() == "modifyFields";
}
void ModifyFieldsValidatorActionHandler::applyAction(EntityValidator& validator, IEntityEditor& entityEditor, EntityData& entityData, const ConfigNode& actionData)
{
if (actionData["action"].asString() == "modifyField") {
applyEntry(entityEditor, entityData, actionData);
} else if (actionData["action"].asString() == "modifyFields") {
for (const auto& entry: actionData["entries"].asSequence()) {
applyEntry(entityEditor, entityData, entry);
}
}
}
ConfigNode ModifyFieldsValidatorActionHandler::makeAction(String componentName, String fieldName, ConfigNode fieldData)
{
ConfigNode::MapType result;
result["action"] = "modifyField";
result["component"] = componentName;
result["field"] = fieldName;
result["data"] = fieldData;
return result;
}
void ModifyFieldsValidatorActionHandler::applyEntry(IEntityEditor& entityEditor, EntityData& entityData, const ConfigNode& entry)
{
const auto component = entry["component"].asString();
const auto field = entry["field"].asString();
bool found = false;
for (auto& comp: entityData.getComponents()) {
if (comp.first == component) {
auto& compData = comp.second.asMap();
compData[field] = ConfigNode(entry["data"]);
found = true;
break;
}
}
if (found) {
entityEditor.onFieldChangedByGizmo(component, field);
}
}
<commit_msg>Some missing moves<commit_after>#include "standard_entity_validators.h"
#include "halley/entity/entity.h"
#include "halley/entity/world.h"
#define DONT_INCLUDE_HALLEY_HPP
#include "component_editor_context.h"
#include "halley/entity/components/transform_2d_component.h"
using namespace Halley;
std::vector<IEntityValidator::Result> TransformEntityValidator::validateEntity(EntityValidator& validator, EntityData& entityData)
{
std::vector<Result> result;
const auto entity = validator.getWorld().findEntity(entityData.getInstanceUUID());
if (entity->isValid()) {
const bool hasTransform = entity->hasComponent<Transform2DComponent>();
if (!hasTransform) {
for (auto c: entity->getChildren()) {
if (c.hasComponent<Transform2DComponent>()) {
result.emplace_back("Entity has no Transform2D component, but some of its children do.", Action("Add Component", AddComponentValidatorActionHandler::makeAction("Transform2D")));
}
}
}
}
return result;
}
bool AddComponentValidatorActionHandler::canHandle(const ConfigNode& actionData)
{
return actionData["action"].asString() == "addComponent" && actionData.hasKey("component");
}
void AddComponentValidatorActionHandler::applyAction(EntityValidator& validator, IEntityEditor& entityEditor, EntityData& entityData, const ConfigNode& actionData)
{
const auto compType = actionData["component"].asString();
entityEditor.addComponent(compType, ConfigNode::MapType());
}
ConfigNode AddComponentValidatorActionHandler::makeAction(String componentName)
{
ConfigNode::MapType action;
action["action"] = "addComponent";
action["component"] = std::move(componentName);
return action;
}
bool ModifyFieldsValidatorActionHandler::canHandle(const ConfigNode& actionData)
{
return actionData["action"].asString() == "modifyField" || actionData["action"].asString() == "modifyFields";
}
void ModifyFieldsValidatorActionHandler::applyAction(EntityValidator& validator, IEntityEditor& entityEditor, EntityData& entityData, const ConfigNode& actionData)
{
if (actionData["action"].asString() == "modifyField") {
applyEntry(entityEditor, entityData, actionData);
} else if (actionData["action"].asString() == "modifyFields") {
for (const auto& entry: actionData["entries"].asSequence()) {
applyEntry(entityEditor, entityData, entry);
}
}
}
ConfigNode ModifyFieldsValidatorActionHandler::makeAction(String componentName, String fieldName, ConfigNode fieldData)
{
ConfigNode::MapType result;
result["action"] = "modifyField";
result["component"] = std::move(componentName);
result["field"] = std::move(fieldName);
result["data"] = std::move(fieldData);
return result;
}
void ModifyFieldsValidatorActionHandler::applyEntry(IEntityEditor& entityEditor, EntityData& entityData, const ConfigNode& entry)
{
const auto component = entry["component"].asString();
const auto field = entry["field"].asString();
bool found = false;
for (auto& comp: entityData.getComponents()) {
if (comp.first == component) {
auto& compData = comp.second.asMap();
compData[field] = ConfigNode(entry["data"]);
found = true;
break;
}
}
if (found) {
entityEditor.onFieldChangedByGizmo(component, field);
}
}
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "NetworkClient.hpp"
//fToServerStc NetworkClient::toServerData;
NetworkClient::NetworkClient() : NetworkWorker()
{
tryToConnect = true;
clientConnected = false;
myType = CLIENT;
}
int NetworkClient::initialize(int port)
{
last = now = AnnEngine::Instance()->getTimeFromStartUp();
return 0;
}
void NetworkClient::update(){
AnnDebug() << "client update";
now = AnnEngine::Instance()->getTimeFromStartUp();
float frameTime = now - last;
last = now;
communicate(frameTime);
}
// --- Do network communications ---
void NetworkClient::communicate(float frameTime)
{
AnnDebug() << "Com";
if(clientConnected)
getInfoFromServer(); // Get game state from server
// Calculate elapsed time for network communications
/*netTime += frameTime;
if(netTime < netNS::NET_TIMER) // if not time to communicate*/
//return;
if(tryToConnect)
connectToServer(); // Attempt to connect to game server
else if(clientConnected)
{
AnnDebug() << "Should transmit data here";
checkNetworkTimeout(); // check for disconnect from server
sendInfoToServer(); //
}
netTime -= netNS::NET_TIMER;
}
void NetworkClient::connectToServer()
{
AnnDebug() << "Call connect to server..." ;
static int step = 0;
static float waitTime; // seconds we have waited for a response from server
int size;
int newPort;
std::string str;
std::stringstream ss;
if(clientConnected) // if connected
{
tryToConnect = false;
AnnDebug() << "Currently connected";
return;
}
AnnDebug() << "----- Vr AirHockey Client -----";
switch (step)
{
case 0:
newPort = config.port;
if(newPort == 0)
newPort = netNS::DEFAULT_PORT;
if(newPort > netNS::MIN_PORT && newPort < 65536)
{
port = newPort;
}
else
AnnDebug() << "Invalid port number";
strcpy(remoteIP, config.serverAddress.c_str());
error = net.createClient(remoteIP, port, netNS::UDP);
if(error != netNS::NET_OK) // if error
{
AnnDebug() << net.getError(error); // display error message
tryToConnect = false;
return;
}
// send request to join the server
AnnDebug() << "Attempting to connect with server."; // display message
toServerData.playerN = 255; // playerN=255 is request to join
size = sizeof(toServerData);
AnnDebug() << "'Request to join' sent to server.";
error = net.sendData((char*) &toServerData, size, remoteIP, port);
AnnDebug() << net.getError(error);
waitTime = 0;
step = 4;
break;
case 4:
waitTime+=netTime; // add time since last call to connect
// if we timed out with no reponse to our request to join
if (waitTime > CONNECT_TIMEOUT)
{
AnnDebug() << "'Request to join' timed out.";
//tryToConnect = false;
return;
}
// read ConnectResponse from server
size = sizeof(connectResponse);
error = net.readData((char*)&connectResponse, size, remoteIP, remotePort);
if (error == netNS::NET_OK) // if read was OK
{
if(size == 0) // if no data received
return;
// if the server sent back the proper ID then we are connected
if (strcmp(connectResponse.response, netNS::SERVER_ID) == 0)
{
if (connectResponse.number < MAX_CLIENT) // if valid player number
{
playerN = connectResponse.number; // set my player number
ss << "Connected as player number: " << playerN;
AnnDebug() << ss.str();
clientConnected = true;
commErrors = 0;
commWarnings = 0;
}
else
AnnDebug() << "Invalid player number received from server.";
}
else if (strcmp(connectResponse.response, netNS::SERVER_FULL) == 0)
AnnDebug() << "Server Full";
else
{
AnnDebug() << "Invalid ID from server. Server sent:";
AnnDebug() << connectResponse.response;
}
}
else // read error
{
AnnDebug() << net.getError(error);
}
tryToConnect = false;
step = 0;
}
}
//=============================================================================
// Check for network timeout
//=============================================================================
void NetworkClient::checkNetworkTimeout()
{
if (!clientConnected)
return;
commErrors++; // increment timeout count
if (commErrors > netNS::MAX_ERRORS) // if communication timeout
{
clientConnected = false;
AnnDebug() << "***** Disconnected from server. *****";
}
}
//=============================================================================
// Send the keypress codes to the server
//=============================================================================
void NetworkClient::sendInfoToServer()
{
int size;
// prepare structure to be sent
//toServerData.buttons = buttonState;
toServerData.playerN = playerN;
//toServerData.ClientPaddlePos = AnnVect3(10,20,30);
// send data from client to server
toServerData.ClientPaddlePos = localPosiion;
size = sizeof(toServerData);
error = net.sendData((char*) &toServerData, size, remoteIP, remotePort);
}
//=============================================================================
// Get toClientData from server.
// called by client to get game state from server
//=============================================================================
void NetworkClient::getInfoFromServer()
{
int size;
size = sizeof(toClientData);
int readStatus = net.readData((char *)&toClientData, size, remoteIP, remotePort);
if( readStatus == netNS::NET_OK && size > 0)
{
distantPosition = toClientData.postition;
referencePuckPosiion = toClientData.PuckPos;
for(int i=0; i<MAX_CLIENT; i++) // for all player positions
{
// load new data into each player
// player[i].setNetData(toClientData.player[i].playerData);
}
// Game state
// Bit 0 = roundStart
// Bits 1-7 reserved for future use
if((toClientData.gameState & ROUND_START_BIT) &&
countDownOn == false)
roundStart();
gameState = toClientData.gameState; // save new game state
commErrors = 0;
commWarnings = 0;
}
}
//=============================================================================
// Start a new round of play
//=============================================================================
void NetworkClient::roundStart()
{
// Start ships on opposite sides of planet in stable clockwise orbit
//player[0].setX();
//player[1].setX();
//player[0].setY();
//player[1].setY();
countDownTimer = COUNT_DOWN;
countDownOn = true;
}
AnnVect3 NetworkClient::getRefPuckPosition()
{
return referencePuckPosiion;
}
<commit_msg>remove useless stuff in the client code<commit_after>#include "stdafx.h"
#include "NetworkClient.hpp"
//fToServerStc NetworkClient::toServerData;
NetworkClient::NetworkClient() : NetworkWorker()
{
tryToConnect = true;
clientConnected = false;
myType = CLIENT;
}
int NetworkClient::initialize(int port)
{
last = now = AnnEngine::Instance()->getTimeFromStartUp();
return 0;
}
void NetworkClient::update(){
//AnnDebug() << "client update";
now = AnnEngine::Instance()->getTimeFromStartUp();
float frameTime = now - last;
last = now;
communicate(frameTime);
}
// --- Do network communications ---
void NetworkClient::communicate(float frameTime)
{
//AnnDebug() << "Com";
if(clientConnected)
getInfoFromServer(); // Get game state from server
// Calculate elapsed time for network communications
/*netTime += frameTime;
if(netTime < netNS::NET_TIMER) // if not time to communicate*/
//return;
if(tryToConnect)
connectToServer(); // Attempt to connect to game server
else if(clientConnected)
{
/*AnnDebug() << "Should transmit data here";*/
//checkNetworkTimeout(); // check for disconnect from server
sendInfoToServer(); //
}
netTime -= netNS::NET_TIMER;
}
void NetworkClient::connectToServer()
{
AnnDebug() << "Call connect to server..." ;
static int step = 0;
static float waitTime; // seconds we have waited for a response from server
int size;
int newPort;
std::string str;
std::stringstream ss;
if(clientConnected) // if connected
{
tryToConnect = false;
AnnDebug() << "Currently connected";
return;
}
AnnDebug() << "----- Vr AirHockey Client -----";
switch (step)
{
case 0:
newPort = config.port;
if(newPort == 0)
newPort = netNS::DEFAULT_PORT;
if(newPort > netNS::MIN_PORT && newPort < 65536)
{
port = newPort;
}
else
AnnDebug() << "Invalid port number";
strcpy(remoteIP, config.serverAddress.c_str());
error = net.createClient(remoteIP, port, netNS::UDP);
if(error != netNS::NET_OK) // if error
{
AnnDebug() << net.getError(error); // display error message
tryToConnect = false;
return;
}
// send request to join the server
AnnDebug() << "Attempting to connect with server."; // display message
toServerData.playerN = 255; // playerN=255 is request to join
size = sizeof(toServerData);
AnnDebug() << "'Request to join' sent to server.";
error = net.sendData((char*) &toServerData, size, remoteIP, port);
AnnDebug() << net.getError(error);
waitTime = 0;
step = 4;
break;
case 4:
waitTime+=netTime; // add time since last call to connect
// if we timed out with no reponse to our request to join
if (waitTime > CONNECT_TIMEOUT)
{
AnnDebug() << "'Request to join' timed out.";
//tryToConnect = false;
return;
}
// read ConnectResponse from server
size = sizeof(connectResponse);
error = net.readData((char*)&connectResponse, size, remoteIP, remotePort);
if (error == netNS::NET_OK) // if read was OK
{
if(size == 0) // if no data received
return;
// if the server sent back the proper ID then we are connected
if (strcmp(connectResponse.response, netNS::SERVER_ID) == 0)
{
if (connectResponse.number < MAX_CLIENT) // if valid player number
{
playerN = connectResponse.number; // set my player number
ss << "Connected as player number: " << playerN;
AnnDebug() << ss.str();
clientConnected = true;
commErrors = 0;
commWarnings = 0;
}
else
AnnDebug() << "Invalid player number received from server.";
}
else if (strcmp(connectResponse.response, netNS::SERVER_FULL) == 0)
AnnDebug() << "Server Full";
else
{
AnnDebug() << "Invalid ID from server. Server sent:";
AnnDebug() << connectResponse.response;
}
}
else // read error
{
AnnDebug() << net.getError(error);
}
tryToConnect = false;
step = 0;
}
}
//=============================================================================
// Check for network timeout
//=============================================================================
void NetworkClient::checkNetworkTimeout()
{
if (!clientConnected)
return;
commErrors++; // increment timeout count
if (commErrors > netNS::MAX_ERRORS) // if communication timeout
{
clientConnected = false;
AnnDebug() << "***** Disconnected from server. *****";
}
}
//=============================================================================
// Send the keypress codes to the server
//=============================================================================
void NetworkClient::sendInfoToServer()
{
int size;
// prepare structure to be sent
//toServerData.buttons = buttonState;
toServerData.playerN = playerN;
//toServerData.ClientPaddlePos = AnnVect3(10,20,30);
// send data from client to server
toServerData.ClientPaddlePos = localPosiion;
size = sizeof(toServerData);
error = net.sendData((char*) &toServerData, size, remoteIP, remotePort);
}
//=============================================================================
// Get toClientData from server.
// called by client to get game state from server
//=============================================================================
void NetworkClient::getInfoFromServer()
{
int size;
size = sizeof(toClientData);
int readStatus = net.readData((char *)&toClientData, size, remoteIP, remotePort);
if( readStatus == netNS::NET_OK && size > 0)
{
distantPosition = toClientData.postition;
referencePuckPosiion = toClientData.PuckPos;
for(int i=0; i<MAX_CLIENT; i++) // for all player positions
{
// load new data into each player
// player[i].setNetData(toClientData.player[i].playerData);
}
// Game state
// Bit 0 = roundStart
// Bits 1-7 reserved for future use
if((toClientData.gameState & ROUND_START_BIT) &&
countDownOn == false)
roundStart();
gameState = toClientData.gameState; // save new game state
commErrors = 0;
commWarnings = 0;
}
}
//=============================================================================
// Start a new round of play
//=============================================================================
void NetworkClient::roundStart()
{
// Start ships on opposite sides of planet in stable clockwise orbit
//player[0].setX();
//player[1].setX();
//player[0].setY();
//player[1].setY();
countDownTimer = COUNT_DOWN;
countDownOn = true;
}
AnnVect3 NetworkClient::getRefPuckPosition()
{
return referencePuckPosiion;
}
<|endoftext|>
|
<commit_before>#include "accelometerwidget.h"
AccelometerWidget::AccelometerWidget(QQuickItem *parent) :
QQuickPaintedItem(parent)
{
}
void AccelometerWidget::paint(QPainter *painter)
{
const int boundX = boundingRect().x();
const int boundY = boundingRect().y();
const int boundHeight = boundingRect().height();
const int boundWidth = boundingRect().width();
const QPointF center = boundingRect().center();
//draw outer circle
painter->setPen(QPen(p_edgeColor));
painter->setBrush(QBrush(p_edgeColor));
painter->setRenderHint(QPainter::Antialiasing);
painter->drawEllipse(boundingRect());
//draw inner circle
painter->setPen(QPen(p_color));
painter->setBrush(QBrush(p_color));
painter->setRenderHint(QPainter::Antialiasing);
painter->drawEllipse(boundX + p_edgeWidth, boundY + p_edgeWidth, boundWidth - 2 * p_edgeWidth, boundHeight - 2 * p_edgeWidth);
//draw arrow
//set triangle path
QPainterPath path;
path.moveTo(p_arrowWidth / 2, 0);
path.lineTo(0, boundHeight /2 - p_edgeWidth * 0.75);
path.lineTo(- p_arrowWidth / 2, 0);
path.lineTo( - p_arrowWidth / 2, 0);
//set painter
painter->setPen(QPen(p_arrowColor));
painter->setBrush(QBrush(p_arrowColor));
painter->translate(center.x(), center.y());
painter->rotate(p_angle + 180);
painter->setRenderHint(QPainter::Antialiasing);
painter->drawPath(path);
//draw text
painter->resetTransform();
QFont font = painter->font();
font.setPixelSize(boundHeight / 3);
//font.setFamily("Roboto");
font.setBold(true);
painter->setFont(QFont("Arial Narrow", boundHeight / 3.5, QFont::Black));
painter->setPen(QPen(QColor("white")));
painter->setBrush(QBrush(QColor("white")));
painter->drawText(boundingRect(), Qt::AlignCenter, QString::number(p_angle).append("°"));
}
/*-------------------------------------*/
/*---------------SETTERS---------------*/
/*-------------------------------------*/
void AccelometerWidget::setAngle(qreal &value)
{
if(p_angle != value)
{
p_angle = value;
emit angleChanged();
}
}
void AccelometerWidget::setColor(QColor &value)
{
if(p_color != value)
{
p_color = value;
emit colorChanged();
}
}
void AccelometerWidget::setEdgeColor(QColor &value)
{
if(p_edgeColor != value)
{
p_edgeColor = value;
emit edgeColorChanged();
}
}
void AccelometerWidget::setArrowColor(QColor &value)
{
if(p_arrowColor != value)
{
p_arrowColor = value;
emit arrowColorChanged();
}
}
void AccelometerWidget::setEdgeWidth(int &value)
{
if(p_edgeWidth != value)
{
p_edgeWidth = value;
emit edgeWidthChanged();
}
}
void AccelometerWidget::setArrowWidth(int &value)
{
if(p_arrowWidth != value)
{
p_arrowWidth = value;
emit arrowWidthChanged();
}
}
/*-------------------------------------*/
/*---------------GETTERS---------------*/
/*-------------------------------------*/
qreal AccelometerWidget::angle() const
{
return p_angle;
}
QColor AccelometerWidget::color() const
{
return p_color;
}
QColor AccelometerWidget::edgeColor() const
{
return p_edgeColor;
}
QColor AccelometerWidget::arrowColor() const
{
return p_arrowColor;
}
int AccelometerWidget::edgeWidth() const
{
return p_edgeWidth;
}
int AccelometerWidget::arrowWidth() const
{
return p_arrowWidth;
}
<commit_msg>Typos C++: AccelometerWidget<commit_after>#include "accelometerwidget.h"
AccelometerWidget::AccelometerWidget(QQuickItem *parent) :
QQuickPaintedItem(parent)
{
}
void AccelometerWidget::paint(QPainter *painter)
{
const int boundX = boundingRect().x();
const int boundY = boundingRect().y();
const int boundHeight = boundingRect().height();
const int boundWidth = boundingRect().width();
const QPointF center = boundingRect().center();
//draw outer circle
painter->setPen(QPen(p_edgeColor));
painter->setBrush(QBrush(p_edgeColor));
painter->setRenderHint(QPainter::Antialiasing);
painter->drawEllipse(boundingRect());
//draw inner circle
painter->setPen(QPen(p_color));
painter->setBrush(QBrush(p_color));
painter->setRenderHint(QPainter::Antialiasing);
painter->drawEllipse(boundX + p_edgeWidth, boundY + p_edgeWidth, boundWidth - 2 * p_edgeWidth, boundHeight - 2 * p_edgeWidth);
//draw arrow
//set triangle path
QPainterPath path;
path.moveTo(p_arrowWidth / 2, 0);
path.lineTo(0, boundHeight /2 - p_edgeWidth * 0.75);
path.lineTo(- p_arrowWidth / 2, 0);
path.lineTo( - p_arrowWidth / 2, 0);
//set painter
painter->setPen(QPen(p_arrowColor));
painter->setBrush(QBrush(p_arrowColor));
painter->translate(center.x(), center.y());
painter->rotate(p_angle + 180);
painter->setRenderHint(QPainter::Antialiasing);
painter->drawPath(path);
//draw text
painter->resetTransform();
painter->setFont(QFont("Arial Narrow", boundHeight / 3.5, QFont::Black));
painter->setPen(QPen(QColor("white")));
painter->setBrush(QBrush(QColor("white")));
painter->drawText(boundingRect(), Qt::AlignCenter, QString::number(p_angle).append("°"));
}
/*-------------------------------------*/
/*---------------SETTERS---------------*/
/*-------------------------------------*/
void AccelometerWidget::setAngle(qreal &value)
{
if(p_angle != value)
{
p_angle = value;
emit angleChanged();
}
}
void AccelometerWidget::setColor(QColor &value)
{
if(p_color != value)
{
p_color = value;
emit colorChanged();
}
}
void AccelometerWidget::setEdgeColor(QColor &value)
{
if(p_edgeColor != value)
{
p_edgeColor = value;
emit edgeColorChanged();
}
}
void AccelometerWidget::setArrowColor(QColor &value)
{
if(p_arrowColor != value)
{
p_arrowColor = value;
emit arrowColorChanged();
}
}
void AccelometerWidget::setEdgeWidth(int &value)
{
if(p_edgeWidth != value)
{
p_edgeWidth = value;
emit edgeWidthChanged();
}
}
void AccelometerWidget::setArrowWidth(int &value)
{
if(p_arrowWidth != value)
{
p_arrowWidth = value;
emit arrowWidthChanged();
}
}
/*-------------------------------------*/
/*---------------GETTERS---------------*/
/*-------------------------------------*/
qreal AccelometerWidget::angle() const
{
return p_angle;
}
QColor AccelometerWidget::color() const
{
return p_color;
}
QColor AccelometerWidget::edgeColor() const
{
return p_edgeColor;
}
QColor AccelometerWidget::arrowColor() const
{
return p_arrowColor;
}
int AccelometerWidget::edgeWidth() const
{
return p_edgeWidth;
}
int AccelometerWidget::arrowWidth() const
{
return p_arrowWidth;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: convuno.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: kz $ $Date: 2006-07-21 14:30:28 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#include <tools/debug.hxx>
#include <i18npool/mslangid.hxx>
#include "convuno.hxx"
#include "global.hxx"
using namespace com::sun::star;
//------------------------------------------------------------------------
// everything is static...
LanguageType ScUnoConversion::GetLanguage( const lang::Locale& rLocale )
{
// empty language -> LANGUAGE_SYSTEM
if ( rLocale.Language.getLength() == 0 )
return LANGUAGE_SYSTEM;
LanguageType eRet = MsLangId::convertLocaleToLanguage( rLocale );
if ( eRet == LANGUAGE_NONE )
eRet = LANGUAGE_SYSTEM; //! or throw an exception?
return eRet;
}
void ScUnoConversion::FillLocale( lang::Locale& rLocale, LanguageType eLang )
{
MsLangId::convertLanguageToLocale( eLang, rLocale );
}
<commit_msg>INTEGRATION: CWS changefileheader (1.6.492); FILE MERGED 2008/03/31 17:19:33 rt 1.6.492.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: convuno.cxx,v $
* $Revision: 1.7 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#include <tools/debug.hxx>
#include <i18npool/mslangid.hxx>
#include "convuno.hxx"
#include "global.hxx"
using namespace com::sun::star;
//------------------------------------------------------------------------
// everything is static...
LanguageType ScUnoConversion::GetLanguage( const lang::Locale& rLocale )
{
// empty language -> LANGUAGE_SYSTEM
if ( rLocale.Language.getLength() == 0 )
return LANGUAGE_SYSTEM;
LanguageType eRet = MsLangId::convertLocaleToLanguage( rLocale );
if ( eRet == LANGUAGE_NONE )
eRet = LANGUAGE_SYSTEM; //! or throw an exception?
return eRet;
}
void ScUnoConversion::FillLocale( lang::Locale& rLocale, LanguageType eLang )
{
MsLangId::convertLanguageToLocale( eLang, rLocale );
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: test_activedatasink.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2006-09-17 13:53: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_ucb.hxx"
/**************************************************************************
TODO
**************************************************************************
*************************************************************************/
#ifndef _TEST_ACTIVEDATASINK_HXX_
#include "test_activedatasink.hxx"
#endif
using namespace test_ftp;
using namespace com::sun::star::uno;
using namespace com::sun::star::io;
Any SAL_CALL Test_ActiveDataSink::queryInterface( const Type& rType ) throw( RuntimeException ) {
Any aRet = ::cppu::queryInterface(rType,
SAL_STATIC_CAST( XActiveDataSink*,this ));
return aRet.hasValue() ? aRet : OWeakObject::queryInterface( rType );
}
void SAL_CALL Test_ActiveDataSink::acquire( void ) throw() {
OWeakObject::acquire();
}
void SAL_CALL Test_ActiveDataSink::release( void ) throw() {
OWeakObject::release();
}
<commit_msg>INTEGRATION: CWS changefileheader (1.4.118); FILE MERGED 2008/03/31 15:30:21 rt 1.4.118.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: test_activedatasink.cxx,v $
* $Revision: 1.5 $
*
* 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_ucb.hxx"
/**************************************************************************
TODO
**************************************************************************
*************************************************************************/
#ifndef _TEST_ACTIVEDATASINK_HXX_
#include "test_activedatasink.hxx"
#endif
using namespace test_ftp;
using namespace com::sun::star::uno;
using namespace com::sun::star::io;
Any SAL_CALL Test_ActiveDataSink::queryInterface( const Type& rType ) throw( RuntimeException ) {
Any aRet = ::cppu::queryInterface(rType,
SAL_STATIC_CAST( XActiveDataSink*,this ));
return aRet.hasValue() ? aRet : OWeakObject::queryInterface( rType );
}
void SAL_CALL Test_ActiveDataSink::acquire( void ) throw() {
OWeakObject::acquire();
}
void SAL_CALL Test_ActiveDataSink::release( void ) throw() {
OWeakObject::release();
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: pkgdatasupplier.cxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: ihi $ $Date: 2007-06-05 18:13:27 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_ucb.hxx"
/**************************************************************************
TODO
**************************************************************************
*************************************************************************/
#include <vector>
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XENUMERATION_HPP_
#include <com/sun/star/container/XEnumeration.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_
#include <com/sun/star/container/XNamed.hpp>
#endif
#ifndef _UCBHELPER_CONTENTIDENTIFIER_HXX
#include <ucbhelper/contentidentifier.hxx>
#endif
#ifndef _UCBHELPER_PROVIDERHELPER_HXX
#include <ucbhelper/providerhelper.hxx>
#endif
#ifndef _PKGDATASUPPLIER_HXX
#include "pkgdatasupplier.hxx"
#endif
#ifndef _PKGCONTENT_HXX
#include "pkgcontent.hxx"
#endif
#ifndef _PKGPROVIDER_HXX
#include "pkgprovider.hxx"
#endif
#include "../inc/urihelper.hxx"
using namespace com::sun::star;
using namespace package_ucp;
namespace package_ucp
{
//=========================================================================
//
// struct ResultListEntry.
//
//=========================================================================
struct ResultListEntry
{
rtl::OUString aURL;
uno::Reference< ucb::XContentIdentifier > xId;
uno::Reference< ucb::XContent > xContent;
uno::Reference< sdbc::XRow > xRow;
ResultListEntry( const rtl::OUString& rURL ) : aURL( rURL ) {}
};
//=========================================================================
//
// ResultList.
//
//=========================================================================
typedef std::vector< ResultListEntry* > ResultList;
//=========================================================================
//
// struct DataSupplier_Impl.
//
//=========================================================================
struct DataSupplier_Impl
{
osl::Mutex m_aMutex;
ResultList m_aResults;
rtl::Reference< Content > m_xContent;
uno::Reference< lang::XMultiServiceFactory > m_xSMgr;
uno::Reference< container::XEnumeration > m_xFolderEnum;
sal_Int32 m_nOpenMode;
sal_Bool m_bCountFinal;
sal_Bool m_bThrowException;
DataSupplier_Impl(
const uno::Reference< lang::XMultiServiceFactory >& rxSMgr,
const rtl::Reference< Content >& rContent,
sal_Int32 nOpenMode )
: m_xContent( rContent ), m_xSMgr( rxSMgr ),
m_xFolderEnum( rContent->getIterator() ), m_nOpenMode( nOpenMode ),
m_bCountFinal( !m_xFolderEnum.is() ), m_bThrowException( m_bCountFinal )
{}
~DataSupplier_Impl();
};
//=========================================================================
DataSupplier_Impl::~DataSupplier_Impl()
{
ResultList::const_iterator it = m_aResults.begin();
ResultList::const_iterator end = m_aResults.end();
while ( it != end )
{
delete (*it);
it++;
}
}
}
//=========================================================================
//=========================================================================
//
// DataSupplier Implementation.
//
//=========================================================================
//=========================================================================
DataSupplier::DataSupplier(
const uno::Reference< lang::XMultiServiceFactory >& rxSMgr,
const rtl::Reference< Content >& rContent,
sal_Int32 nOpenMode )
: m_pImpl( new DataSupplier_Impl( rxSMgr, rContent, nOpenMode ) )
{
}
//=========================================================================
// virtual
DataSupplier::~DataSupplier()
{
delete m_pImpl;
}
//=========================================================================
// virtual
rtl::OUString DataSupplier::queryContentIdentifierString( sal_uInt32 nIndex )
{
osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );
if ( nIndex < m_pImpl->m_aResults.size() )
{
rtl::OUString aId = m_pImpl->m_aResults[ nIndex ]->aURL;
if ( aId.getLength() )
{
// Already cached.
return aId;
}
}
if ( getResult( nIndex ) )
{
// Note: getResult fills m_pImpl->m_aResults[ nIndex ]->aURL.
return m_pImpl->m_aResults[ nIndex ]->aURL;
}
return rtl::OUString();
}
//=========================================================================
// virtual
uno::Reference< ucb::XContentIdentifier >
DataSupplier::queryContentIdentifier( sal_uInt32 nIndex )
{
osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );
if ( nIndex < m_pImpl->m_aResults.size() )
{
uno::Reference< ucb::XContentIdentifier > xId
= m_pImpl->m_aResults[ nIndex ]->xId;
if ( xId.is() )
{
// Already cached.
return xId;
}
}
rtl::OUString aId = queryContentIdentifierString( nIndex );
if ( aId.getLength() )
{
uno::Reference< ucb::XContentIdentifier > xId
= new ::ucbhelper::ContentIdentifier( aId );
m_pImpl->m_aResults[ nIndex ]->xId = xId;
return xId;
}
return uno::Reference< ucb::XContentIdentifier >();
}
//=========================================================================
// virtual
uno::Reference< ucb::XContent > DataSupplier::queryContent(
sal_uInt32 nIndex )
{
osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );
if ( nIndex < m_pImpl->m_aResults.size() )
{
uno::Reference< ucb::XContent > xContent
= m_pImpl->m_aResults[ nIndex ]->xContent;
if ( xContent.is() )
{
// Already cached.
return xContent;
}
}
uno::Reference< ucb::XContentIdentifier > xId
= queryContentIdentifier( nIndex );
if ( xId.is() )
{
try
{
uno::Reference< ucb::XContent > xContent
= m_pImpl->m_xContent->getProvider()->queryContent( xId );
m_pImpl->m_aResults[ nIndex ]->xContent = xContent;
return xContent;
}
catch ( ucb::IllegalIdentifierException const & )
{
}
}
return uno::Reference< ucb::XContent >();
}
//=========================================================================
// virtual
sal_Bool DataSupplier::getResult( sal_uInt32 nIndex )
{
osl::ClearableGuard< osl::Mutex > aGuard( m_pImpl->m_aMutex );
if ( m_pImpl->m_aResults.size() > nIndex )
{
// Result already present.
return sal_True;
}
// Result not (yet) present.
if ( m_pImpl->m_bCountFinal )
return sal_False;
// Try to obtain result...
sal_uInt32 nOldCount = m_pImpl->m_aResults.size();
sal_Bool bFound = sal_False;
sal_uInt32 nPos = nOldCount;
while ( m_pImpl->m_xFolderEnum->hasMoreElements() )
{
try
{
uno::Reference< container::XNamed > xNamed;
m_pImpl->m_xFolderEnum->nextElement() >>= xNamed;
if ( !xNamed.is() )
{
OSL_ENSURE( sal_False,
"DataSupplier::getResult - Got no XNamed!" );
break;
}
rtl::OUString aName = xNamed->getName();
if ( !aName.getLength() )
{
OSL_ENSURE( sal_False,
"DataSupplier::getResult - Empty name!" );
break;
}
// Assemble URL for child.
rtl::OUString aURL = assembleChildURL( aName );
m_pImpl->m_aResults.push_back( new ResultListEntry( aURL ) );
if ( nPos == nIndex )
{
// Result obtained.
bFound = sal_True;
break;
}
nPos++;
}
catch ( container::NoSuchElementException const & )
{
m_pImpl->m_bThrowException = sal_True;
break;
}
catch ( lang::WrappedTargetException const & )
{
m_pImpl->m_bThrowException = sal_True;
break;
}
}
if ( !bFound )
m_pImpl->m_bCountFinal = sal_True;
rtl::Reference< ::ucbhelper::ResultSet > xResultSet = getResultSet().get();
if ( xResultSet.is() )
{
// Callbacks follow!
aGuard.clear();
if ( nOldCount < m_pImpl->m_aResults.size() )
xResultSet->rowCountChanged(
nOldCount, m_pImpl->m_aResults.size() );
if ( m_pImpl->m_bCountFinal )
xResultSet->rowCountFinal();
}
return bFound;
}
//=========================================================================
// virtual
sal_uInt32 DataSupplier::totalCount()
{
osl::ClearableGuard< osl::Mutex > aGuard( m_pImpl->m_aMutex );
if ( m_pImpl->m_bCountFinal )
return m_pImpl->m_aResults.size();
sal_uInt32 nOldCount = m_pImpl->m_aResults.size();
while ( m_pImpl->m_xFolderEnum->hasMoreElements() )
{
try
{
uno::Reference< container::XNamed > xNamed;
m_pImpl->m_xFolderEnum->nextElement() >>= xNamed;
if ( !xNamed.is() )
{
OSL_ENSURE( sal_False,
"DataSupplier::getResult - Got no XNamed!" );
break;
}
rtl::OUString aName = xNamed->getName();
if ( !aName.getLength() )
{
OSL_ENSURE( sal_False,
"DataSupplier::getResult - Empty name!" );
break;
}
// Assemble URL for child.
rtl::OUString aURL = assembleChildURL( aName );
m_pImpl->m_aResults.push_back( new ResultListEntry( aURL ) );
}
catch ( container::NoSuchElementException const & )
{
m_pImpl->m_bThrowException = sal_True;
break;
}
catch ( lang::WrappedTargetException const & )
{
m_pImpl->m_bThrowException = sal_True;
break;
}
}
m_pImpl->m_bCountFinal = sal_True;
rtl::Reference< ::ucbhelper::ResultSet > xResultSet = getResultSet().get();
if ( xResultSet.is() )
{
// Callbacks follow!
aGuard.clear();
if ( nOldCount < m_pImpl->m_aResults.size() )
xResultSet->rowCountChanged(
nOldCount, m_pImpl->m_aResults.size() );
xResultSet->rowCountFinal();
}
return m_pImpl->m_aResults.size();
}
//=========================================================================
// virtual
sal_uInt32 DataSupplier::currentCount()
{
return m_pImpl->m_aResults.size();
}
//=========================================================================
// virtual
sal_Bool DataSupplier::isCountFinal()
{
return m_pImpl->m_bCountFinal;
}
//=========================================================================
// virtual
uno::Reference< sdbc::XRow > DataSupplier::queryPropertyValues(
sal_uInt32 nIndex )
{
osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );
if ( nIndex < m_pImpl->m_aResults.size() )
{
uno::Reference< sdbc::XRow > xRow = m_pImpl->m_aResults[ nIndex ]->xRow;
if ( xRow.is() )
{
// Already cached.
return xRow;
}
}
if ( getResult( nIndex ) )
{
uno::Reference< sdbc::XRow > xRow = Content::getPropertyValues(
m_pImpl->m_xSMgr,
getResultSet()->getProperties(),
static_cast< ContentProvider * >(
m_pImpl->m_xContent->getProvider().get() ),
queryContentIdentifierString( nIndex ) );
m_pImpl->m_aResults[ nIndex ]->xRow = xRow;
return xRow;
}
return uno::Reference< sdbc::XRow >();
}
//=========================================================================
// virtual
void DataSupplier::releasePropertyValues( sal_uInt32 nIndex )
{
osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );
if ( nIndex < m_pImpl->m_aResults.size() )
m_pImpl->m_aResults[ nIndex ]->xRow = uno::Reference< sdbc::XRow >();
}
//=========================================================================
// virtual
void DataSupplier::close()
{
}
//=========================================================================
// virtual
void DataSupplier::validate()
throw( ucb::ResultSetException )
{
if ( m_pImpl->m_bThrowException )
throw ucb::ResultSetException();
}
//=========================================================================
::rtl::OUString DataSupplier::assembleChildURL( const ::rtl::OUString& aName )
{
rtl::OUString aURL;
rtl::OUString aContURL
= m_pImpl->m_xContent->getIdentifier()->getContentIdentifier();
sal_Int32 nParam = aContURL.indexOf( '?' );
if ( nParam >= 0 )
{
aURL = aContURL.copy( 0, nParam );
sal_Int32 nPackageUrlEnd = aURL.lastIndexOf( '/' );
if ( nPackageUrlEnd != aURL.getLength() - 1 )
aURL += rtl::OUString::createFromAscii( "/" );
aURL += ::ucb_impl::urihelper::encodeSegment( aName );
aURL += aContURL.copy( nParam );
}
else
{
aURL = aContURL;
sal_Int32 nPackageUrlEnd = aURL.lastIndexOf( '/' );
if ( nPackageUrlEnd != aURL.getLength() - 1 )
aURL += rtl::OUString::createFromAscii( "/" );
aURL += ::ucb_impl::urihelper::encodeSegment( aName );
}
return aURL;
}
<commit_msg>INTEGRATION: CWS changefileheader (1.15.72); FILE MERGED 2008/04/01 16:02:23 thb 1.15.72.3: #i85898# Stripping all external header guards 2008/04/01 12:58:22 thb 1.15.72.2: #i85898# Stripping all external header guards 2008/03/31 15:30:27 rt 1.15.72.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: pkgdatasupplier.cxx,v $
* $Revision: 1.16 $
*
* 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_ucb.hxx"
/**************************************************************************
TODO
**************************************************************************
*************************************************************************/
#include <vector>
#include <osl/diagnose.h>
#include <com/sun/star/container/XEnumeration.hpp>
#include <com/sun/star/container/XNamed.hpp>
#include <ucbhelper/contentidentifier.hxx>
#include <ucbhelper/providerhelper.hxx>
#include "pkgdatasupplier.hxx"
#include "pkgcontent.hxx"
#include "pkgprovider.hxx"
#include "../inc/urihelper.hxx"
using namespace com::sun::star;
using namespace package_ucp;
namespace package_ucp
{
//=========================================================================
//
// struct ResultListEntry.
//
//=========================================================================
struct ResultListEntry
{
rtl::OUString aURL;
uno::Reference< ucb::XContentIdentifier > xId;
uno::Reference< ucb::XContent > xContent;
uno::Reference< sdbc::XRow > xRow;
ResultListEntry( const rtl::OUString& rURL ) : aURL( rURL ) {}
};
//=========================================================================
//
// ResultList.
//
//=========================================================================
typedef std::vector< ResultListEntry* > ResultList;
//=========================================================================
//
// struct DataSupplier_Impl.
//
//=========================================================================
struct DataSupplier_Impl
{
osl::Mutex m_aMutex;
ResultList m_aResults;
rtl::Reference< Content > m_xContent;
uno::Reference< lang::XMultiServiceFactory > m_xSMgr;
uno::Reference< container::XEnumeration > m_xFolderEnum;
sal_Int32 m_nOpenMode;
sal_Bool m_bCountFinal;
sal_Bool m_bThrowException;
DataSupplier_Impl(
const uno::Reference< lang::XMultiServiceFactory >& rxSMgr,
const rtl::Reference< Content >& rContent,
sal_Int32 nOpenMode )
: m_xContent( rContent ), m_xSMgr( rxSMgr ),
m_xFolderEnum( rContent->getIterator() ), m_nOpenMode( nOpenMode ),
m_bCountFinal( !m_xFolderEnum.is() ), m_bThrowException( m_bCountFinal )
{}
~DataSupplier_Impl();
};
//=========================================================================
DataSupplier_Impl::~DataSupplier_Impl()
{
ResultList::const_iterator it = m_aResults.begin();
ResultList::const_iterator end = m_aResults.end();
while ( it != end )
{
delete (*it);
it++;
}
}
}
//=========================================================================
//=========================================================================
//
// DataSupplier Implementation.
//
//=========================================================================
//=========================================================================
DataSupplier::DataSupplier(
const uno::Reference< lang::XMultiServiceFactory >& rxSMgr,
const rtl::Reference< Content >& rContent,
sal_Int32 nOpenMode )
: m_pImpl( new DataSupplier_Impl( rxSMgr, rContent, nOpenMode ) )
{
}
//=========================================================================
// virtual
DataSupplier::~DataSupplier()
{
delete m_pImpl;
}
//=========================================================================
// virtual
rtl::OUString DataSupplier::queryContentIdentifierString( sal_uInt32 nIndex )
{
osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );
if ( nIndex < m_pImpl->m_aResults.size() )
{
rtl::OUString aId = m_pImpl->m_aResults[ nIndex ]->aURL;
if ( aId.getLength() )
{
// Already cached.
return aId;
}
}
if ( getResult( nIndex ) )
{
// Note: getResult fills m_pImpl->m_aResults[ nIndex ]->aURL.
return m_pImpl->m_aResults[ nIndex ]->aURL;
}
return rtl::OUString();
}
//=========================================================================
// virtual
uno::Reference< ucb::XContentIdentifier >
DataSupplier::queryContentIdentifier( sal_uInt32 nIndex )
{
osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );
if ( nIndex < m_pImpl->m_aResults.size() )
{
uno::Reference< ucb::XContentIdentifier > xId
= m_pImpl->m_aResults[ nIndex ]->xId;
if ( xId.is() )
{
// Already cached.
return xId;
}
}
rtl::OUString aId = queryContentIdentifierString( nIndex );
if ( aId.getLength() )
{
uno::Reference< ucb::XContentIdentifier > xId
= new ::ucbhelper::ContentIdentifier( aId );
m_pImpl->m_aResults[ nIndex ]->xId = xId;
return xId;
}
return uno::Reference< ucb::XContentIdentifier >();
}
//=========================================================================
// virtual
uno::Reference< ucb::XContent > DataSupplier::queryContent(
sal_uInt32 nIndex )
{
osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );
if ( nIndex < m_pImpl->m_aResults.size() )
{
uno::Reference< ucb::XContent > xContent
= m_pImpl->m_aResults[ nIndex ]->xContent;
if ( xContent.is() )
{
// Already cached.
return xContent;
}
}
uno::Reference< ucb::XContentIdentifier > xId
= queryContentIdentifier( nIndex );
if ( xId.is() )
{
try
{
uno::Reference< ucb::XContent > xContent
= m_pImpl->m_xContent->getProvider()->queryContent( xId );
m_pImpl->m_aResults[ nIndex ]->xContent = xContent;
return xContent;
}
catch ( ucb::IllegalIdentifierException const & )
{
}
}
return uno::Reference< ucb::XContent >();
}
//=========================================================================
// virtual
sal_Bool DataSupplier::getResult( sal_uInt32 nIndex )
{
osl::ClearableGuard< osl::Mutex > aGuard( m_pImpl->m_aMutex );
if ( m_pImpl->m_aResults.size() > nIndex )
{
// Result already present.
return sal_True;
}
// Result not (yet) present.
if ( m_pImpl->m_bCountFinal )
return sal_False;
// Try to obtain result...
sal_uInt32 nOldCount = m_pImpl->m_aResults.size();
sal_Bool bFound = sal_False;
sal_uInt32 nPos = nOldCount;
while ( m_pImpl->m_xFolderEnum->hasMoreElements() )
{
try
{
uno::Reference< container::XNamed > xNamed;
m_pImpl->m_xFolderEnum->nextElement() >>= xNamed;
if ( !xNamed.is() )
{
OSL_ENSURE( sal_False,
"DataSupplier::getResult - Got no XNamed!" );
break;
}
rtl::OUString aName = xNamed->getName();
if ( !aName.getLength() )
{
OSL_ENSURE( sal_False,
"DataSupplier::getResult - Empty name!" );
break;
}
// Assemble URL for child.
rtl::OUString aURL = assembleChildURL( aName );
m_pImpl->m_aResults.push_back( new ResultListEntry( aURL ) );
if ( nPos == nIndex )
{
// Result obtained.
bFound = sal_True;
break;
}
nPos++;
}
catch ( container::NoSuchElementException const & )
{
m_pImpl->m_bThrowException = sal_True;
break;
}
catch ( lang::WrappedTargetException const & )
{
m_pImpl->m_bThrowException = sal_True;
break;
}
}
if ( !bFound )
m_pImpl->m_bCountFinal = sal_True;
rtl::Reference< ::ucbhelper::ResultSet > xResultSet = getResultSet().get();
if ( xResultSet.is() )
{
// Callbacks follow!
aGuard.clear();
if ( nOldCount < m_pImpl->m_aResults.size() )
xResultSet->rowCountChanged(
nOldCount, m_pImpl->m_aResults.size() );
if ( m_pImpl->m_bCountFinal )
xResultSet->rowCountFinal();
}
return bFound;
}
//=========================================================================
// virtual
sal_uInt32 DataSupplier::totalCount()
{
osl::ClearableGuard< osl::Mutex > aGuard( m_pImpl->m_aMutex );
if ( m_pImpl->m_bCountFinal )
return m_pImpl->m_aResults.size();
sal_uInt32 nOldCount = m_pImpl->m_aResults.size();
while ( m_pImpl->m_xFolderEnum->hasMoreElements() )
{
try
{
uno::Reference< container::XNamed > xNamed;
m_pImpl->m_xFolderEnum->nextElement() >>= xNamed;
if ( !xNamed.is() )
{
OSL_ENSURE( sal_False,
"DataSupplier::getResult - Got no XNamed!" );
break;
}
rtl::OUString aName = xNamed->getName();
if ( !aName.getLength() )
{
OSL_ENSURE( sal_False,
"DataSupplier::getResult - Empty name!" );
break;
}
// Assemble URL for child.
rtl::OUString aURL = assembleChildURL( aName );
m_pImpl->m_aResults.push_back( new ResultListEntry( aURL ) );
}
catch ( container::NoSuchElementException const & )
{
m_pImpl->m_bThrowException = sal_True;
break;
}
catch ( lang::WrappedTargetException const & )
{
m_pImpl->m_bThrowException = sal_True;
break;
}
}
m_pImpl->m_bCountFinal = sal_True;
rtl::Reference< ::ucbhelper::ResultSet > xResultSet = getResultSet().get();
if ( xResultSet.is() )
{
// Callbacks follow!
aGuard.clear();
if ( nOldCount < m_pImpl->m_aResults.size() )
xResultSet->rowCountChanged(
nOldCount, m_pImpl->m_aResults.size() );
xResultSet->rowCountFinal();
}
return m_pImpl->m_aResults.size();
}
//=========================================================================
// virtual
sal_uInt32 DataSupplier::currentCount()
{
return m_pImpl->m_aResults.size();
}
//=========================================================================
// virtual
sal_Bool DataSupplier::isCountFinal()
{
return m_pImpl->m_bCountFinal;
}
//=========================================================================
// virtual
uno::Reference< sdbc::XRow > DataSupplier::queryPropertyValues(
sal_uInt32 nIndex )
{
osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );
if ( nIndex < m_pImpl->m_aResults.size() )
{
uno::Reference< sdbc::XRow > xRow = m_pImpl->m_aResults[ nIndex ]->xRow;
if ( xRow.is() )
{
// Already cached.
return xRow;
}
}
if ( getResult( nIndex ) )
{
uno::Reference< sdbc::XRow > xRow = Content::getPropertyValues(
m_pImpl->m_xSMgr,
getResultSet()->getProperties(),
static_cast< ContentProvider * >(
m_pImpl->m_xContent->getProvider().get() ),
queryContentIdentifierString( nIndex ) );
m_pImpl->m_aResults[ nIndex ]->xRow = xRow;
return xRow;
}
return uno::Reference< sdbc::XRow >();
}
//=========================================================================
// virtual
void DataSupplier::releasePropertyValues( sal_uInt32 nIndex )
{
osl::Guard< osl::Mutex > aGuard( m_pImpl->m_aMutex );
if ( nIndex < m_pImpl->m_aResults.size() )
m_pImpl->m_aResults[ nIndex ]->xRow = uno::Reference< sdbc::XRow >();
}
//=========================================================================
// virtual
void DataSupplier::close()
{
}
//=========================================================================
// virtual
void DataSupplier::validate()
throw( ucb::ResultSetException )
{
if ( m_pImpl->m_bThrowException )
throw ucb::ResultSetException();
}
//=========================================================================
::rtl::OUString DataSupplier::assembleChildURL( const ::rtl::OUString& aName )
{
rtl::OUString aURL;
rtl::OUString aContURL
= m_pImpl->m_xContent->getIdentifier()->getContentIdentifier();
sal_Int32 nParam = aContURL.indexOf( '?' );
if ( nParam >= 0 )
{
aURL = aContURL.copy( 0, nParam );
sal_Int32 nPackageUrlEnd = aURL.lastIndexOf( '/' );
if ( nPackageUrlEnd != aURL.getLength() - 1 )
aURL += rtl::OUString::createFromAscii( "/" );
aURL += ::ucb_impl::urihelper::encodeSegment( aName );
aURL += aContURL.copy( nParam );
}
else
{
aURL = aContURL;
sal_Int32 nPackageUrlEnd = aURL.lastIndexOf( '/' );
if ( nPackageUrlEnd != aURL.getLength() - 1 )
aURL += rtl::OUString::createFromAscii( "/" );
aURL += ::ucb_impl::urihelper::encodeSegment( aName );
}
return aURL;
}
<|endoftext|>
|
<commit_before>// Author: Enrico Guiraud, 2021
/*************************************************************************
* Copyright (C) 1995-2021, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT_RDF_RSAMPLEINFO
#define ROOT_RDF_RSAMPLEINFO
#include <ROOT/RStringView.hxx>
#include <Rtypes.h>
#include <functional>
#include <stdexcept>
#include <string>
namespace ROOT {
namespace RDF {
/// This type represents a sample identifier, to be used in conjunction with RDataFrame features such as
/// DefinePerSample() and per-sample callbacks.
///
/// When the input data comes from a TTree, the string representation of RSampleInfo (which is returned by AsString()
/// and that can be queried e.g. with Contains()) is of the form "<filename>/<treename>".
///
/// In multi-thread runs different tasks might process different entry ranges of the same sample,
/// so RSampleInfo also provides methods to inspect which part of a sample is being taken into consideration.
class RSampleInfo {
// Currently backed by a simple string, might change in the future as we get usage experience.
std::string fID;
std::pair<ULong64_t, ULong64_t> fEntryRange;
public:
explicit RSampleInfo(std::string_view id, std::pair<ULong64_t, ULong64_t> entryRange)
: fID(id), fEntryRange(entryRange)
{
}
RSampleInfo() = default;
RSampleInfo(const RSampleInfo &) = default;
RSampleInfo &operator=(const RSampleInfo &) = default;
RSampleInfo(RSampleInfo &&) = default;
RSampleInfo &operator=(RSampleInfo &&) = default;
~RSampleInfo() = default;
/// Check whether the sample name contains the given substring.
bool Contains(std::string_view substr) const
{
// C++14 needs the conversion from std::string_view to std::string
return fID.find(std::string(substr)) != std::string::npos;
}
/// Check whether the sample name is empty.
///
/// This is the case e.g. when using a RDataFrame with no input data, constructed as `RDataFrame(nEntries)`.
bool Empty() const {
return fID.empty();
}
/// Return a string representation of the sample name.
///
/// The representation is of the form "<filename>/<treename>" if the input data comes from a TTree or a TChain.
const std::string &AsString() const
{
return fID;
}
/// Return the entry range in this sample that is being taken into consideration.
///
/// Multiple multi-threading tasks might process different entry ranges of the same sample.
std::pair<ULong64_t, ULong64_t> EntryRange() const { return fEntryRange; }
/// Return the number of entries of this sample that is being taken into consideration.
ULong64_t NEntries() const { return fEntryRange.second - fEntryRange.first; }
bool operator==(const RSampleInfo &other) const { return fID == other.fID; }
bool operator!=(const RSampleInfo &other) const { return !(*this == other); }
};
/// The type of a data-block callback, registered with a RDataFrame computation graph via e.g.
/// DefinePerSample() or by certain actions (e.g. Snapshot()).
using SampleCallback_t = std::function<void(unsigned int, const ROOT::RDF::RSampleInfo &)>;
} // namespace RDF
} // namespace ROOT
#endif
<commit_msg>[DF][NFC] Add a comma<commit_after>// Author: Enrico Guiraud, 2021
/*************************************************************************
* Copyright (C) 1995-2021, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOT_RDF_RSAMPLEINFO
#define ROOT_RDF_RSAMPLEINFO
#include <ROOT/RStringView.hxx>
#include <Rtypes.h>
#include <functional>
#include <stdexcept>
#include <string>
namespace ROOT {
namespace RDF {
/// This type represents a sample identifier, to be used in conjunction with RDataFrame features such as
/// DefinePerSample() and per-sample callbacks.
///
/// When the input data comes from a TTree, the string representation of RSampleInfo (which is returned by AsString()
/// and that can be queried e.g. with Contains()) is of the form "<filename>/<treename>".
///
/// In multi-thread runs, different tasks might process different entry ranges of the same sample,
/// so RSampleInfo also provides methods to inspect which part of a sample is being taken into consideration.
class RSampleInfo {
// Currently backed by a simple string, might change in the future as we get usage experience.
std::string fID;
std::pair<ULong64_t, ULong64_t> fEntryRange;
public:
explicit RSampleInfo(std::string_view id, std::pair<ULong64_t, ULong64_t> entryRange)
: fID(id), fEntryRange(entryRange)
{
}
RSampleInfo() = default;
RSampleInfo(const RSampleInfo &) = default;
RSampleInfo &operator=(const RSampleInfo &) = default;
RSampleInfo(RSampleInfo &&) = default;
RSampleInfo &operator=(RSampleInfo &&) = default;
~RSampleInfo() = default;
/// Check whether the sample name contains the given substring.
bool Contains(std::string_view substr) const
{
// C++14 needs the conversion from std::string_view to std::string
return fID.find(std::string(substr)) != std::string::npos;
}
/// Check whether the sample name is empty.
///
/// This is the case e.g. when using a RDataFrame with no input data, constructed as `RDataFrame(nEntries)`.
bool Empty() const {
return fID.empty();
}
/// Return a string representation of the sample name.
///
/// The representation is of the form "<filename>/<treename>" if the input data comes from a TTree or a TChain.
const std::string &AsString() const
{
return fID;
}
/// Return the entry range in this sample that is being taken into consideration.
///
/// Multiple multi-threading tasks might process different entry ranges of the same sample.
std::pair<ULong64_t, ULong64_t> EntryRange() const { return fEntryRange; }
/// Return the number of entries of this sample that is being taken into consideration.
ULong64_t NEntries() const { return fEntryRange.second - fEntryRange.first; }
bool operator==(const RSampleInfo &other) const { return fID == other.fID; }
bool operator!=(const RSampleInfo &other) const { return !(*this == other); }
};
/// The type of a data-block callback, registered with a RDataFrame computation graph via e.g.
/// DefinePerSample() or by certain actions (e.g. Snapshot()).
using SampleCallback_t = std::function<void(unsigned int, const ROOT::RDF::RSampleInfo &)>;
} // namespace RDF
} // namespace ROOT
#endif
<|endoftext|>
|
<commit_before>#include <stdio.h>
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
/*void doExec(char* cmd){
int pid = fork();
if (pid == -1){
perror("There was an error with fork()");
exit(1);
}
else if (pid == 0){
if (-1 == execvp(cmd, argv)){
perror("There was an error with execvp()");
exit(1);
}
}
else {
if (-1 == wait(0)){
perror("There was an error with wait()");
exit(1);
}
}
}*/
char* convert(const string& str){
char* p = new char[str.size()+1];
strcpy(p,str.c_str());
return p;
}
vector<char*> str_parse(string str){
string arg;
vector<string> argList;
vector<char*> argListC;
istringstream inSS(arg);
while(!inSS.eof()){
inSS >> str;
argList.push_back(arg);
}
transform(argList.begin(), argList.end(), back_inserter(argListC), convert);
return argListC;
}
int main () {
string cmd;
while (true){
cout << "$ ";
getline(cin, cmd);
//check for exit command
if (cmd == "exit") exit(0);
str_parse(cmd);
}
return 0;
}
<commit_msg>shell now functions properly on single command w/ args<commit_after>#include <stdio.h>
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;
void doExec(vector<char*> instr){
int pid = fork();
if (pid == -1){
perror("There was an error with fork()");
exit(1);
}
else if (pid == 0){
if (-1 == execvp(instr[0],&instr[0] )){
perror("There was an error with execvp()");
exit(1);
}
}
else {
if (-1 == wait(0)){
perror("There was an error with wait()");
exit(1);
}
}
}
char* convert(const string& str){
char* p = new char[str.size()+1];
strcpy(p,str.c_str());
return p;
}
vector<char*> str_parse(string str){
string arg;
vector<string> argList;
vector<char*> argListC;
istringstream inSS(str);
//parse from command string
while(!inSS.eof()){
inSS >> arg;
argList.push_back(arg);
}
//convert c++ string vector into cstring array
transform(argList.begin(), argList.end(), back_inserter(argListC), convert);
argListC.push_back(NULL);
return argListC;
}
int main () {
string cmd;
while (true){
cout << "$ ";
getline(cin, cmd);
//check for exit command
if (cmd == "exit") exit(0);
vector<char*> v = str_parse(cmd);
doExec(str_parse(cmd));
}
return 0;
}
<|endoftext|>
|
<commit_before>#include <boost/tokenizer.hpp>
#include <iostream>
#include <unistd.h>
#include <string.h>
#include <cstdlib>
#include <errno.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string>
#include <sstream>
#include <vector>
//using namespace boost;
using namespace std;
int main()
{
using namespace boost;
string args;
while(1 != 2)
{
cout << "$ ";
getline(cin, args);
char *argv[9];
int i = 0;
vector<string> arg_s;
typedef tokenizer< char_separator<char> > tokenizer;
char_separator<char> sep(" ", "-;||&&", drop_empty_tokens);
tokenizer tokens(args, sep);
for(tokenizer::iterator tok_iter=tokens.begin(); tok_iter != tokens.end();++tok_iter) {
if(*tok_iter == "&&" || *tok_iter == "||" || *tok_iter == ";") {
// argv[i] = NULL;
// int pidb = fork();
// if(pidb == -1) {
// perror("fork");
// }
// if(pidb == 0) {
// int t = execvp(argv[0], argv);
// if(t == -1) {
// perror("execvp");
// }
// }
// else {
// if(-1 == waitpid(pidb, &pidb, 0)) {
// perror("waitpid");
// }
// }
}
else {
cout << *tok_iter << endl;
arg_s.push_back(*tok_iter);
argv[i] = new char[12];
strcpy(argv[i], const_cast<char*>(arg_s[i].c_str()));
if(*tok_iter == "exit")
exit(1);
++i;
}
}
argv[i] = NULL;
int pid = fork();
if(pid == -1) {
perror("fork");
exit(1);
}
if(pid == 0) {
int r = execvp(argv[0], argv);
if(r == -1) {
perror("execvp");
exit(1);
}
}
else {
if(-1 == waitpid(pid, &pid, 0)) {
perror("waitpid");
}
}
// int pid = fork();
// if(pid == -1) {
// perror("fork");
// exit(1);
// }
// if(pid == 0)
// {
//char *argv2[4];
//argv2[0] = new char[6];
//strcpy(argv[0], "ls");
//argv2[1] = new char[6];
//strcpy(argv[1], "-a");
//argv2[2] = new char [6];
//strcpy(argv[2], "-l");
// int pid2 = fork();
// if(pid2 == -1) {
// perror("fork");
// exit(1);
// }
// if(pid2 == 0) {
/// if(execvp(argv[0], argv) == -1) {
// perror("execvp");
// exit(1);
// }
// }
// else {
// if(-1 == waitpid(pid2,&pid2,0 ))
// perror("waitpid");
// }
//
// if(execvp(argv[1], argv) == -1) {
// perror("execvp");
// exit(1);
// }
//
// cout << "after" << endl;
// }
// else {
// if(-1 == waitpid(pid, &pid, 0))
// perror("waitpid");
// }
}
return 0;
}
<commit_msg>rshell.cpp updated<commit_after>#include <boost/tokenizer.hpp>
#include <iostream>
#include <unistd.h>
#include <string.h>
#include <cstdlib>
#include <errno.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string>
#include <sstream>
#include <vector>
//using namespace boost;
using namespace std;
int main()
{
using namespace boost;
string args;
while(1 != 2)
{
cout << "$ ";
getline(cin, args);
char *argv[9];
int i = 0;
vector<string> arg_s;
typedef tokenizer< char_separator<char> > tokenizer;
char_separator<char> sep(" ", "-;||&&", drop_empty_tokens);
tokenizer tokens(args, sep);
for(tokenizer::iterator tok_iter=tokens.begin(); tok_iter != tokens.end();++tok_iter) {
if(*tok_iter == "&&" || *tok_iter == "||" || *tok_iter == ";") {
// argv[i] = NULL;
// int pidb = fork();
// if(pidb == -1) {
// perror("fork");
// }
// if(pidb == 0) {
// int t = execvp(argv[0], argv);
// if(t == -1) {
// perror("execvp");
// }
// }
// else {
// if(-1 == waitpid(pidb, &pidb, 0)) {
// perror("waitpid");
// }
// }
}
else {
arg_s.push_back(*tok_iter);
argv[i] = new char[12];
strcpy(argv[i], const_cast<char*>(arg_s[i].c_str()));
if(*tok_iter == "exit")
exit(1);
++i;
}
}
argv[i] = NULL;
int pid = fork();
if(pid == -1) {
perror("fork");
exit(1);
}
if(pid == 0) {
int r = execvp(argv[0], argv);
if(r == -1) {
perror("execvp");
exit(1);
}
}
else {
if(-1 == waitpid(pid, &pid, 0)) {
perror("waitpid");
}
}
// int pid = fork();
// if(pid == -1) {
// perror("fork");
// exit(1);
// }
// if(pid == 0)
// {
//char *argv2[4];
//argv2[0] = new char[6];
//strcpy(argv[0], "ls");
//argv2[1] = new char[6];
//strcpy(argv[1], "-a");
//argv2[2] = new char [6];
//strcpy(argv[2], "-l");
// int pid2 = fork();
// if(pid2 == -1) {
// perror("fork");
// exit(1);
// }
// if(pid2 == 0) {
/// if(execvp(argv[0], argv) == -1) {
// perror("execvp");
// exit(1);
// }
// }
// else {
// if(-1 == waitpid(pid2,&pid2,0 ))
// perror("waitpid");
// }
//
// if(execvp(argv[1], argv) == -1) {
// perror("execvp");
// exit(1);
// }
//
// cout << "after" << endl;
// }
// else {
// if(-1 == waitpid(pid, &pid, 0))
// perror("waitpid");
// }
}
return 0;
}
<|endoftext|>
|
<commit_before><commit_msg>Adding many of the features. Considering this a v0.1<commit_after>#include <iostream>
#include <string>
#include <queue>
#include <vector>
#include <algorithm>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
const string cmd_delimiter = ";|&#";
void splice_input(queue<string> &cmds, queue<char> &conns, const string &input);
string get_input(const string &input, int &start, int &end);
int find_delimiter(const string &input, int &start);
bool run_command(string &input, char &conn);
void tokenize(vector<char*> &comms, string &input);
int main()
{
string input;
char logic;
queue<string> commands;
queue<char> connectors;
bool running = true;
while(1)
{
cout << "$ ";
getline(cin, input);
splice_input(commands, connectors, input);
while(!commands.empty() && running)
{
input = commands.front();
commands.pop();
if(!connectors.empty())
{
logic = connectors.front();
connectors.pop();
}
if(input.find("exit") == string::npos)
running = run_command(input, logic);
else
exit(1);
if(!running)
{
connectors = queue<char>();
commands = queue<string>();
}
}
running = true;
}
return 0;
}
void splice_input(queue<string> &cmds, queue<char> &conns, const string &input)
{
int pos = 0;
char logic;
string new_cmd;
string parse = input;
while(pos != -1)
{
pos = parse.find_first_of(cmd_delimiter);
new_cmd = parse.substr(0, pos);
logic = parse[pos];
while(new_cmd[0] == ' ')
new_cmd = new_cmd.substr(1, new_cmd.length());
if(logic == '&' || logic == '|')
{
cmds.push(new_cmd);
parse.erase(0, pos + 2);
}
else if(logic == ';')
{
cmds.push(new_cmd);
parse.erase(0, pos + 1);
}
else
cmds.push(new_cmd);
if(logic == '#')
return;
conns.push(logic);
}
}
bool run_command(string &input, char &conn)
{
pid_t pid = fork();
vector<char*> tokens;
int status = 0;
if(pid == -1)
{
perror("Error with fork()");
exit(1);
}
else if(pid == 0)
{
tokenize(tokens, input);
char **cmds = &tokens[0];
execvp(cmds[0], cmds);
perror("Execvp failed!");
exit(1);
}
else
{
wait(&status);
if(conn == '&')
{
if(status > 0)
return false;
}
}
return true;
}
void tokenize(vector<char*> &comms, string &input)
{
string convert;
string tokenizer = input;
size_t pos = 0;
while(pos != string::npos)
{
pos = tokenizer.find(' ');
convert = pos == string::npos ? tokenizer \
: tokenizer.substr(0, pos);
convert.erase(std::remove_if(convert.begin(), convert.end(), ::isspace), convert.end());
if(!convert.empty())
{
char *tmp = new char[convert.length() + 1];
strcpy(tmp, convert.c_str());
comms.push_back(tmp);
tokenizer.erase(0, pos + 1);
}
}
comms.push_back(NULL);
return;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/automation/testing_automation_provider.h"
#include <windows.h>
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/automation/automation_browser_tracker.h"
#include "chrome/browser/automation/automation_window_tracker.h"
#include "chrome/browser/ui/browser_window.h"
void TestingAutomationProvider::ActivateWindow(int handle) {
if (window_tracker_->ContainsHandle(handle)) {
::SetActiveWindow(window_tracker_->GetResource(handle));
}
}
void TestingAutomationProvider::IsWindowMaximized(int handle,
bool* is_maximized,
bool* success) {
*success = false;
HWND hwnd = window_tracker_->GetResource(handle);
if (hwnd) {
*success = true;
WINDOWPLACEMENT window_placement;
GetWindowPlacement(hwnd, &window_placement);
*is_maximized = (window_placement.showCmd == SW_MAXIMIZE);
}
}
void TestingAutomationProvider::TerminateSession(int handle, bool* success) {
*success = false;
if (browser_tracker_->ContainsHandle(handle)) {
Browser* browser = browser_tracker_->GetResource(handle);
HWND window = browser->window()->GetNativeHandle();
*success = (::PostMessageW(window, WM_ENDSESSION, 0, 0) == TRUE);
}
}
void TestingAutomationProvider::GetWindowBounds(int handle,
gfx::Rect* bounds,
bool* success) {
*success = false;
HWND hwnd = window_tracker_->GetResource(handle);
if (hwnd) {
*success = true;
WINDOWPLACEMENT window_placement;
GetWindowPlacement(hwnd, &window_placement);
*bounds = window_placement.rcNormalPosition;
}
}
void TestingAutomationProvider::SetWindowBounds(int handle,
const gfx::Rect& bounds,
bool* success) {
*success = false;
if (window_tracker_->ContainsHandle(handle)) {
HWND hwnd = window_tracker_->GetResource(handle);
if (::MoveWindow(hwnd, bounds.x(), bounds.y(), bounds.width(),
bounds.height(), true)) {
*success = true;
}
}
}
void TestingAutomationProvider::SetWindowVisible(int handle,
bool visible,
bool* result) {
if (window_tracker_->ContainsHandle(handle)) {
HWND hwnd = window_tracker_->GetResource(handle);
::ShowWindow(hwnd, visible ? SW_SHOW : SW_HIDE);
*result = true;
} else {
*result = false;
}
}
void TestingAutomationProvider::GetWindowTitle(int handle, string16* text) {
gfx::NativeWindow window = window_tracker_->GetResource(handle);
std::wstring result;
int length = ::GetWindowTextLength(window) + 1;
::GetWindowText(window, WriteInto(&result, length), length);
text->assign(WideToUTF16(result));
}
<commit_msg>Set WINDOWPLACEMENT.length before calling GetWindowPlacement() Also check return value of GetWindowPlacement()<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/automation/testing_automation_provider.h"
#include <windows.h>
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/automation/automation_browser_tracker.h"
#include "chrome/browser/automation/automation_window_tracker.h"
#include "chrome/browser/ui/browser_window.h"
void TestingAutomationProvider::ActivateWindow(int handle) {
if (window_tracker_->ContainsHandle(handle)) {
::SetActiveWindow(window_tracker_->GetResource(handle));
}
}
void TestingAutomationProvider::IsWindowMaximized(int handle,
bool* is_maximized,
bool* success) {
*success = false;
HWND hwnd = window_tracker_->GetResource(handle);
if (hwnd) {
WINDOWPLACEMENT window_placement;
window_placement.length = sizeof(window_placement);
if (GetWindowPlacement(hwnd, &window_placement)) {
*success = true;
*is_maximized = (window_placement.showCmd == SW_MAXIMIZE);
}
}
}
void TestingAutomationProvider::TerminateSession(int handle, bool* success) {
*success = false;
if (browser_tracker_->ContainsHandle(handle)) {
Browser* browser = browser_tracker_->GetResource(handle);
HWND window = browser->window()->GetNativeHandle();
*success = (::PostMessageW(window, WM_ENDSESSION, 0, 0) == TRUE);
}
}
void TestingAutomationProvider::GetWindowBounds(int handle,
gfx::Rect* bounds,
bool* success) {
*success = false;
HWND hwnd = window_tracker_->GetResource(handle);
if (hwnd) {
WINDOWPLACEMENT window_placement;
window_placement.length = sizeof(window_placement);
if (GetWindowPlacement(hwnd, &window_placement)) {
*success = true;
*bounds = window_placement.rcNormalPosition;
}
}
}
void TestingAutomationProvider::SetWindowBounds(int handle,
const gfx::Rect& bounds,
bool* success) {
*success = false;
if (window_tracker_->ContainsHandle(handle)) {
HWND hwnd = window_tracker_->GetResource(handle);
if (::MoveWindow(hwnd, bounds.x(), bounds.y(), bounds.width(),
bounds.height(), true)) {
*success = true;
}
}
}
void TestingAutomationProvider::SetWindowVisible(int handle,
bool visible,
bool* result) {
if (window_tracker_->ContainsHandle(handle)) {
HWND hwnd = window_tracker_->GetResource(handle);
::ShowWindow(hwnd, visible ? SW_SHOW : SW_HIDE);
*result = true;
} else {
*result = false;
}
}
void TestingAutomationProvider::GetWindowTitle(int handle, string16* text) {
gfx::NativeWindow window = window_tracker_->GetResource(handle);
std::wstring result;
int length = ::GetWindowTextLength(window) + 1;
::GetWindowText(window, WriteInto(&result, length), length);
text->assign(WideToUTF16(result));
}
<|endoftext|>
|
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/drive/change_list_loader.h"
#include "base/files/scoped_temp_dir.h"
#include "base/memory/scoped_ptr.h"
#include "base/prefs/testing_pref_service.h"
#include "base/run_loop.h"
#include "chrome/browser/chromeos/drive/change_list_loader_observer.h"
#include "chrome/browser/chromeos/drive/file_cache.h"
#include "chrome/browser/chromeos/drive/file_system_util.h"
#include "chrome/browser/chromeos/drive/job_scheduler.h"
#include "chrome/browser/chromeos/drive/resource_metadata.h"
#include "chrome/browser/chromeos/drive/test_util.h"
#include "chrome/browser/drive/fake_drive_service.h"
#include "chrome/browser/google_apis/test_util.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace drive {
namespace internal {
class TestChangeListLoaderObserver : public ChangeListLoaderObserver {
public:
explicit TestChangeListLoaderObserver(ChangeListLoader* loader)
: loader_(loader),
load_from_server_complete_count_(0),
initial_load_complete_count_(0) {
loader_->AddObserver(this);
}
virtual ~TestChangeListLoaderObserver() {
loader_->RemoveObserver(this);
}
const std::set<base::FilePath>& changed_directories() const {
return changed_directories_;
}
int load_from_server_complete_count() const {
return load_from_server_complete_count_;
}
int initial_load_complete_count() const {
return initial_load_complete_count_;
}
// ChageListObserver overrides:
virtual void OnDirectoryChanged(
const base::FilePath& directory_path) OVERRIDE {
changed_directories_.insert(directory_path);
}
virtual void OnLoadFromServerComplete() OVERRIDE {
++load_from_server_complete_count_;
}
virtual void OnInitialLoadComplete() OVERRIDE {
++initial_load_complete_count_;
}
private:
ChangeListLoader* loader_;
std::set<base::FilePath> changed_directories_;
int load_from_server_complete_count_;
int initial_load_complete_count_;
DISALLOW_COPY_AND_ASSIGN(TestChangeListLoaderObserver);
};
class ChangeListLoaderTest : public testing::Test {
protected:
virtual void SetUp() OVERRIDE {
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
pref_service_.reset(new TestingPrefServiceSimple);
test_util::RegisterDrivePrefs(pref_service_->registry());
drive_service_.reset(new FakeDriveService);
ASSERT_TRUE(drive_service_->LoadResourceListForWapi(
"gdata/root_feed.json"));
ASSERT_TRUE(drive_service_->LoadAccountMetadataForWapi(
"gdata/account_metadata.json"));
scheduler_.reset(new JobScheduler(pref_service_.get(),
drive_service_.get(),
base::MessageLoopProxy::current().get()));
metadata_storage_.reset(new ResourceMetadataStorage(
temp_dir_.path(), base::MessageLoopProxy::current().get()));
ASSERT_TRUE(metadata_storage_->Initialize());
metadata_.reset(new ResourceMetadata(
metadata_storage_.get(), base::MessageLoopProxy::current().get()));
ASSERT_EQ(FILE_ERROR_OK, metadata_->Initialize());
cache_.reset(new FileCache(metadata_storage_.get(),
temp_dir_.path(),
base::MessageLoopProxy::current().get(),
NULL /* free_disk_space_getter */));
ASSERT_TRUE(cache_->Initialize());
change_list_loader_.reset(
new ChangeListLoader(base::MessageLoopProxy::current().get(),
metadata_.get(),
scheduler_.get()));
}
// Adds a new file to the root directory of the service.
scoped_ptr<google_apis::ResourceEntry> AddNewFile(const std::string& title) {
google_apis::GDataErrorCode error = google_apis::GDATA_FILE_ERROR;
scoped_ptr<google_apis::ResourceEntry> entry;
drive_service_->AddNewFile(
"text/plain",
"content text",
drive_service_->GetRootResourceId(),
title,
false, // shared_with_me
google_apis::test_util::CreateCopyResultCallback(&error, &entry));
base::RunLoop().RunUntilIdle();
EXPECT_EQ(google_apis::HTTP_CREATED, error);
return entry.Pass();
}
content::TestBrowserThreadBundle thread_bundle_;
base::ScopedTempDir temp_dir_;
scoped_ptr<TestingPrefServiceSimple> pref_service_;
scoped_ptr<FakeDriveService> drive_service_;
scoped_ptr<JobScheduler> scheduler_;
scoped_ptr<ResourceMetadataStorage,
test_util::DestroyHelperForTests> metadata_storage_;
scoped_ptr<ResourceMetadata, test_util::DestroyHelperForTests> metadata_;
scoped_ptr<FileCache, test_util::DestroyHelperForTests> cache_;
scoped_ptr<ChangeListLoader> change_list_loader_;
};
TEST_F(ChangeListLoaderTest, LoadIfNeeded) {
EXPECT_FALSE(change_list_loader_->IsRefreshing());
// Start initial load.
TestChangeListLoaderObserver observer(change_list_loader_.get());
FileError error = FILE_ERROR_FAILED;
change_list_loader_->LoadIfNeeded(
DirectoryFetchInfo(),
google_apis::test_util::CreateCopyResultCallback(&error));
EXPECT_TRUE(change_list_loader_->IsRefreshing());
base::RunLoop().RunUntilIdle();
EXPECT_EQ(FILE_ERROR_OK, error);
EXPECT_FALSE(change_list_loader_->IsRefreshing());
EXPECT_LT(0, metadata_->GetLargestChangestamp());
EXPECT_EQ(1, drive_service_->resource_list_load_count());
EXPECT_EQ(1, observer.initial_load_complete_count());
EXPECT_EQ(1, observer.load_from_server_complete_count());
EXPECT_TRUE(observer.changed_directories().empty());
base::FilePath file_path =
util::GetDriveMyDriveRootPath().AppendASCII("File 1.txt");
ResourceEntry entry;
EXPECT_EQ(FILE_ERROR_OK,
metadata_->GetResourceEntryByPath(file_path, &entry));
// Reload. This should result in no-op.
int64 previous_changestamp = metadata_->GetLargestChangestamp();
int previous_resource_list_load_count =
drive_service_->resource_list_load_count();
change_list_loader_->LoadIfNeeded(
DirectoryFetchInfo(),
google_apis::test_util::CreateCopyResultCallback(&error));
EXPECT_FALSE(change_list_loader_->IsRefreshing());
base::RunLoop().RunUntilIdle();
EXPECT_EQ(FILE_ERROR_OK, error);
EXPECT_FALSE(change_list_loader_->IsRefreshing());
EXPECT_EQ(previous_changestamp, metadata_->GetLargestChangestamp());
EXPECT_EQ(previous_resource_list_load_count,
drive_service_->resource_list_load_count());
}
TEST_F(ChangeListLoaderTest, LoadIfNeeded_LocalMetadataAvailable) {
// Prepare metadata.
FileError error = FILE_ERROR_FAILED;
change_list_loader_->LoadIfNeeded(
DirectoryFetchInfo(),
google_apis::test_util::CreateCopyResultCallback(&error));
base::RunLoop().RunUntilIdle();
EXPECT_EQ(FILE_ERROR_OK, error);
// Reset loader.
change_list_loader_.reset(
new ChangeListLoader(base::MessageLoopProxy::current().get(),
metadata_.get(),
scheduler_.get()));
// Add a file to the service.
scoped_ptr<google_apis::ResourceEntry> gdata_entry = AddNewFile("New File");
ASSERT_TRUE(gdata_entry);
// Start loading. Because local metadata is available, the load results in
// returning FILE_ERROR_OK without fetching full list of resources.
const int previous_resource_list_load_count =
drive_service_->resource_list_load_count();
TestChangeListLoaderObserver observer(change_list_loader_.get());
change_list_loader_->LoadIfNeeded(
DirectoryFetchInfo(),
google_apis::test_util::CreateCopyResultCallback(&error));
EXPECT_TRUE(change_list_loader_->IsRefreshing());
base::RunLoop().RunUntilIdle();
EXPECT_EQ(FILE_ERROR_OK, error);
EXPECT_EQ(previous_resource_list_load_count,
drive_service_->resource_list_load_count());
EXPECT_EQ(1, observer.initial_load_complete_count());
// Update should be checked by LoadIfNeeded().
EXPECT_EQ(drive_service_->largest_changestamp(),
metadata_->GetLargestChangestamp());
EXPECT_EQ(1, drive_service_->change_list_load_count());
EXPECT_EQ(1, observer.load_from_server_complete_count());
EXPECT_EQ(1U, observer.changed_directories().count(
util::GetDriveMyDriveRootPath()));
base::FilePath file_path =
util::GetDriveMyDriveRootPath().AppendASCII(gdata_entry->title());
ResourceEntry entry;
EXPECT_EQ(FILE_ERROR_OK,
metadata_->GetResourceEntryByPath(file_path, &entry));
}
TEST_F(ChangeListLoaderTest, CheckForUpdates) {
// CheckForUpdates() results in no-op before load.
FileError check_for_updates_error = FILE_ERROR_FAILED;
change_list_loader_->CheckForUpdates(
google_apis::test_util::CreateCopyResultCallback(
&check_for_updates_error));
EXPECT_FALSE(change_list_loader_->IsRefreshing());
base::RunLoop().RunUntilIdle();
EXPECT_EQ(FILE_ERROR_FAILED,
check_for_updates_error); // Callback was not run.
EXPECT_EQ(0, metadata_->GetLargestChangestamp());
EXPECT_EQ(0, drive_service_->resource_list_load_count());
// Start initial load.
FileError load_error = FILE_ERROR_FAILED;
change_list_loader_->LoadIfNeeded(
DirectoryFetchInfo(),
google_apis::test_util::CreateCopyResultCallback(&load_error));
EXPECT_TRUE(change_list_loader_->IsRefreshing());
// CheckForUpdates() while loading.
change_list_loader_->CheckForUpdates(
google_apis::test_util::CreateCopyResultCallback(
&check_for_updates_error));
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(change_list_loader_->IsRefreshing());
EXPECT_EQ(FILE_ERROR_OK, load_error);
EXPECT_EQ(FILE_ERROR_OK, check_for_updates_error);
EXPECT_LT(0, metadata_->GetLargestChangestamp());
EXPECT_EQ(1, drive_service_->resource_list_load_count());
int64 previous_changestamp = metadata_->GetLargestChangestamp();
// CheckForUpdates() results in no update.
change_list_loader_->CheckForUpdates(
google_apis::test_util::CreateCopyResultCallback(
&check_for_updates_error));
EXPECT_TRUE(change_list_loader_->IsRefreshing());
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(change_list_loader_->IsRefreshing());
EXPECT_EQ(previous_changestamp, metadata_->GetLargestChangestamp());
// Add a file to the service.
scoped_ptr<google_apis::ResourceEntry> gdata_entry = AddNewFile("New File");
ASSERT_TRUE(gdata_entry);
// CheckForUpdates() results in update.
TestChangeListLoaderObserver observer(change_list_loader_.get());
change_list_loader_->CheckForUpdates(
google_apis::test_util::CreateCopyResultCallback(
&check_for_updates_error));
EXPECT_TRUE(change_list_loader_->IsRefreshing());
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(change_list_loader_->IsRefreshing());
EXPECT_LT(previous_changestamp, metadata_->GetLargestChangestamp());
EXPECT_EQ(1, observer.load_from_server_complete_count());
EXPECT_EQ(1U, observer.changed_directories().count(
util::GetDriveMyDriveRootPath()));
// The new file is found in the local metadata.
base::FilePath new_file_path =
util::GetDriveMyDriveRootPath().AppendASCII(gdata_entry->title());
ResourceEntry entry;
EXPECT_EQ(FILE_ERROR_OK,
metadata_->GetResourceEntryByPath(new_file_path, &entry));
}
} // namespace internal
} // namespace drive
<commit_msg>drive: Add test for ChangeListLoader::LoadIfNeeded with non empty DirectoryFetchInfo<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/drive/change_list_loader.h"
#include "base/files/scoped_temp_dir.h"
#include "base/memory/scoped_ptr.h"
#include "base/prefs/testing_pref_service.h"
#include "base/run_loop.h"
#include "chrome/browser/chromeos/drive/change_list_loader_observer.h"
#include "chrome/browser/chromeos/drive/file_cache.h"
#include "chrome/browser/chromeos/drive/file_system_util.h"
#include "chrome/browser/chromeos/drive/job_scheduler.h"
#include "chrome/browser/chromeos/drive/resource_metadata.h"
#include "chrome/browser/chromeos/drive/test_util.h"
#include "chrome/browser/drive/fake_drive_service.h"
#include "chrome/browser/google_apis/test_util.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace drive {
namespace internal {
class TestChangeListLoaderObserver : public ChangeListLoaderObserver {
public:
explicit TestChangeListLoaderObserver(ChangeListLoader* loader)
: loader_(loader),
load_from_server_complete_count_(0),
initial_load_complete_count_(0) {
loader_->AddObserver(this);
}
virtual ~TestChangeListLoaderObserver() {
loader_->RemoveObserver(this);
}
const std::set<base::FilePath>& changed_directories() const {
return changed_directories_;
}
int load_from_server_complete_count() const {
return load_from_server_complete_count_;
}
int initial_load_complete_count() const {
return initial_load_complete_count_;
}
// ChageListObserver overrides:
virtual void OnDirectoryChanged(
const base::FilePath& directory_path) OVERRIDE {
changed_directories_.insert(directory_path);
}
virtual void OnLoadFromServerComplete() OVERRIDE {
++load_from_server_complete_count_;
}
virtual void OnInitialLoadComplete() OVERRIDE {
++initial_load_complete_count_;
}
private:
ChangeListLoader* loader_;
std::set<base::FilePath> changed_directories_;
int load_from_server_complete_count_;
int initial_load_complete_count_;
DISALLOW_COPY_AND_ASSIGN(TestChangeListLoaderObserver);
};
class TestDriveService : public FakeDriveService {
public:
TestDriveService() : never_return_all_resource_list_(false),
blocked_call_count_(0) {}
void set_never_return_all_resource_list(bool value) {
never_return_all_resource_list_ = value;
}
int blocked_call_count() const { return blocked_call_count_; }
// FakeDriveService override.
virtual google_apis::CancelCallback GetAllResourceList(
const google_apis::GetResourceListCallback& callback) OVERRIDE {
if (never_return_all_resource_list_) {
++blocked_call_count_;
return google_apis::CancelCallback();
}
return FakeDriveService::GetAllResourceList(callback);
}
private:
// GetAllResourceList never returns result when this is set to true.
// Used to emulate the real server's slowness.
bool never_return_all_resource_list_;
int blocked_call_count_; // Number of blocked method calls.
};
class ChangeListLoaderTest : public testing::Test {
protected:
virtual void SetUp() OVERRIDE {
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
pref_service_.reset(new TestingPrefServiceSimple);
test_util::RegisterDrivePrefs(pref_service_->registry());
drive_service_.reset(new TestDriveService);
ASSERT_TRUE(drive_service_->LoadResourceListForWapi(
"gdata/root_feed.json"));
ASSERT_TRUE(drive_service_->LoadAccountMetadataForWapi(
"gdata/account_metadata.json"));
scheduler_.reset(new JobScheduler(pref_service_.get(),
drive_service_.get(),
base::MessageLoopProxy::current().get()));
metadata_storage_.reset(new ResourceMetadataStorage(
temp_dir_.path(), base::MessageLoopProxy::current().get()));
ASSERT_TRUE(metadata_storage_->Initialize());
metadata_.reset(new ResourceMetadata(
metadata_storage_.get(), base::MessageLoopProxy::current().get()));
ASSERT_EQ(FILE_ERROR_OK, metadata_->Initialize());
cache_.reset(new FileCache(metadata_storage_.get(),
temp_dir_.path(),
base::MessageLoopProxy::current().get(),
NULL /* free_disk_space_getter */));
ASSERT_TRUE(cache_->Initialize());
change_list_loader_.reset(
new ChangeListLoader(base::MessageLoopProxy::current().get(),
metadata_.get(),
scheduler_.get()));
}
// Adds a new file to the root directory of the service.
scoped_ptr<google_apis::ResourceEntry> AddNewFile(const std::string& title) {
google_apis::GDataErrorCode error = google_apis::GDATA_FILE_ERROR;
scoped_ptr<google_apis::ResourceEntry> entry;
drive_service_->AddNewFile(
"text/plain",
"content text",
drive_service_->GetRootResourceId(),
title,
false, // shared_with_me
google_apis::test_util::CreateCopyResultCallback(&error, &entry));
base::RunLoop().RunUntilIdle();
EXPECT_EQ(google_apis::HTTP_CREATED, error);
return entry.Pass();
}
content::TestBrowserThreadBundle thread_bundle_;
base::ScopedTempDir temp_dir_;
scoped_ptr<TestingPrefServiceSimple> pref_service_;
scoped_ptr<TestDriveService> drive_service_;
scoped_ptr<JobScheduler> scheduler_;
scoped_ptr<ResourceMetadataStorage,
test_util::DestroyHelperForTests> metadata_storage_;
scoped_ptr<ResourceMetadata, test_util::DestroyHelperForTests> metadata_;
scoped_ptr<FileCache, test_util::DestroyHelperForTests> cache_;
scoped_ptr<ChangeListLoader> change_list_loader_;
};
TEST_F(ChangeListLoaderTest, LoadIfNeeded) {
EXPECT_FALSE(change_list_loader_->IsRefreshing());
// Start initial load.
TestChangeListLoaderObserver observer(change_list_loader_.get());
FileError error = FILE_ERROR_FAILED;
change_list_loader_->LoadIfNeeded(
DirectoryFetchInfo(),
google_apis::test_util::CreateCopyResultCallback(&error));
EXPECT_TRUE(change_list_loader_->IsRefreshing());
base::RunLoop().RunUntilIdle();
EXPECT_EQ(FILE_ERROR_OK, error);
EXPECT_FALSE(change_list_loader_->IsRefreshing());
EXPECT_LT(0, metadata_->GetLargestChangestamp());
EXPECT_EQ(1, drive_service_->resource_list_load_count());
EXPECT_EQ(1, observer.initial_load_complete_count());
EXPECT_EQ(1, observer.load_from_server_complete_count());
EXPECT_TRUE(observer.changed_directories().empty());
base::FilePath file_path =
util::GetDriveMyDriveRootPath().AppendASCII("File 1.txt");
ResourceEntry entry;
EXPECT_EQ(FILE_ERROR_OK,
metadata_->GetResourceEntryByPath(file_path, &entry));
// Reload. This should result in no-op.
int64 previous_changestamp = metadata_->GetLargestChangestamp();
int previous_resource_list_load_count =
drive_service_->resource_list_load_count();
change_list_loader_->LoadIfNeeded(
DirectoryFetchInfo(),
google_apis::test_util::CreateCopyResultCallback(&error));
EXPECT_FALSE(change_list_loader_->IsRefreshing());
base::RunLoop().RunUntilIdle();
EXPECT_EQ(FILE_ERROR_OK, error);
EXPECT_FALSE(change_list_loader_->IsRefreshing());
EXPECT_EQ(previous_changestamp, metadata_->GetLargestChangestamp());
EXPECT_EQ(previous_resource_list_load_count,
drive_service_->resource_list_load_count());
}
TEST_F(ChangeListLoaderTest, LoadIfNeeded_LocalMetadataAvailable) {
// Prepare metadata.
FileError error = FILE_ERROR_FAILED;
change_list_loader_->LoadIfNeeded(
DirectoryFetchInfo(),
google_apis::test_util::CreateCopyResultCallback(&error));
base::RunLoop().RunUntilIdle();
EXPECT_EQ(FILE_ERROR_OK, error);
// Reset loader.
change_list_loader_.reset(
new ChangeListLoader(base::MessageLoopProxy::current().get(),
metadata_.get(),
scheduler_.get()));
// Add a file to the service.
scoped_ptr<google_apis::ResourceEntry> gdata_entry = AddNewFile("New File");
ASSERT_TRUE(gdata_entry);
// Start loading. Because local metadata is available, the load results in
// returning FILE_ERROR_OK without fetching full list of resources.
const int previous_resource_list_load_count =
drive_service_->resource_list_load_count();
TestChangeListLoaderObserver observer(change_list_loader_.get());
change_list_loader_->LoadIfNeeded(
DirectoryFetchInfo(),
google_apis::test_util::CreateCopyResultCallback(&error));
EXPECT_TRUE(change_list_loader_->IsRefreshing());
base::RunLoop().RunUntilIdle();
EXPECT_EQ(FILE_ERROR_OK, error);
EXPECT_EQ(previous_resource_list_load_count,
drive_service_->resource_list_load_count());
EXPECT_EQ(1, observer.initial_load_complete_count());
// Update should be checked by LoadIfNeeded().
EXPECT_EQ(drive_service_->largest_changestamp(),
metadata_->GetLargestChangestamp());
EXPECT_EQ(1, drive_service_->change_list_load_count());
EXPECT_EQ(1, observer.load_from_server_complete_count());
EXPECT_EQ(1U, observer.changed_directories().count(
util::GetDriveMyDriveRootPath()));
base::FilePath file_path =
util::GetDriveMyDriveRootPath().AppendASCII(gdata_entry->title());
ResourceEntry entry;
EXPECT_EQ(FILE_ERROR_OK,
metadata_->GetResourceEntryByPath(file_path, &entry));
}
TEST_F(ChangeListLoaderTest, LoadIfNeeded_MyDrive) {
// Emulate the slowness of GetAllResourceList().
drive_service_->set_never_return_all_resource_list(true);
// Load grand root.
FileError error = FILE_ERROR_FAILED;
change_list_loader_->LoadIfNeeded(
DirectoryFetchInfo(util::kDriveGrandRootSpecialResourceId, 0),
google_apis::test_util::CreateCopyResultCallback(&error));
base::RunLoop().RunUntilIdle();
EXPECT_EQ(FILE_ERROR_OK, error);
// GetAllResourceList() was called.
EXPECT_EQ(1, drive_service_->blocked_call_count());
// My Drive is present in the local metadata, but its child is not.
ResourceEntry entry;
EXPECT_EQ(FILE_ERROR_OK,
metadata_->GetResourceEntryByPath(util::GetDriveMyDriveRootPath(),
&entry));
const int64 mydrive_changestamp =
entry.directory_specific_info().changestamp();
base::FilePath file_path =
util::GetDriveMyDriveRootPath().AppendASCII("File 1.txt");
EXPECT_EQ(FILE_ERROR_NOT_FOUND,
metadata_->GetResourceEntryByPath(file_path, &entry));
// Load My Drive.
change_list_loader_->LoadIfNeeded(
DirectoryFetchInfo(drive_service_->GetRootResourceId(),
mydrive_changestamp),
google_apis::test_util::CreateCopyResultCallback(&error));
base::RunLoop().RunUntilIdle();
EXPECT_EQ(FILE_ERROR_OK, error);
// Now the file is present.
EXPECT_EQ(FILE_ERROR_OK,
metadata_->GetResourceEntryByPath(file_path, &entry));
}
TEST_F(ChangeListLoaderTest, LoadIfNeeded_NewDirectories) {
// Make local metadata up to date.
FileError error = FILE_ERROR_FAILED;
change_list_loader_->LoadIfNeeded(
DirectoryFetchInfo(),
google_apis::test_util::CreateCopyResultCallback(&error));
base::RunLoop().RunUntilIdle();
EXPECT_EQ(FILE_ERROR_OK, error);
// Add a new file.
scoped_ptr<google_apis::ResourceEntry> file = AddNewFile("New File");
ASSERT_TRUE(file);
// Emulate the slowness of GetAllResourceList().
drive_service_->set_never_return_all_resource_list(true);
// Enter refreshing state.
FileError check_for_updates_error = FILE_ERROR_FAILED;
change_list_loader_->CheckForUpdates(
google_apis::test_util::CreateCopyResultCallback(
&check_for_updates_error));
EXPECT_TRUE(change_list_loader_->IsRefreshing());
// Load My Drive.
change_list_loader_->LoadIfNeeded(
DirectoryFetchInfo(drive_service_->GetRootResourceId(),
metadata_->GetLargestChangestamp()),
google_apis::test_util::CreateCopyResultCallback(&error));
base::RunLoop().RunUntilIdle();
EXPECT_EQ(FILE_ERROR_OK, error);
// The new file is present in the local metadata.
base::FilePath file_path =
util::GetDriveMyDriveRootPath().AppendASCII(file->title());
ResourceEntry entry;
EXPECT_EQ(FILE_ERROR_OK,
metadata_->GetResourceEntryByPath(file_path, &entry));
}
TEST_F(ChangeListLoaderTest, CheckForUpdates) {
// CheckForUpdates() results in no-op before load.
FileError check_for_updates_error = FILE_ERROR_FAILED;
change_list_loader_->CheckForUpdates(
google_apis::test_util::CreateCopyResultCallback(
&check_for_updates_error));
EXPECT_FALSE(change_list_loader_->IsRefreshing());
base::RunLoop().RunUntilIdle();
EXPECT_EQ(FILE_ERROR_FAILED,
check_for_updates_error); // Callback was not run.
EXPECT_EQ(0, metadata_->GetLargestChangestamp());
EXPECT_EQ(0, drive_service_->resource_list_load_count());
// Start initial load.
FileError load_error = FILE_ERROR_FAILED;
change_list_loader_->LoadIfNeeded(
DirectoryFetchInfo(),
google_apis::test_util::CreateCopyResultCallback(&load_error));
EXPECT_TRUE(change_list_loader_->IsRefreshing());
// CheckForUpdates() while loading.
change_list_loader_->CheckForUpdates(
google_apis::test_util::CreateCopyResultCallback(
&check_for_updates_error));
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(change_list_loader_->IsRefreshing());
EXPECT_EQ(FILE_ERROR_OK, load_error);
EXPECT_EQ(FILE_ERROR_OK, check_for_updates_error);
EXPECT_LT(0, metadata_->GetLargestChangestamp());
EXPECT_EQ(1, drive_service_->resource_list_load_count());
int64 previous_changestamp = metadata_->GetLargestChangestamp();
// CheckForUpdates() results in no update.
change_list_loader_->CheckForUpdates(
google_apis::test_util::CreateCopyResultCallback(
&check_for_updates_error));
EXPECT_TRUE(change_list_loader_->IsRefreshing());
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(change_list_loader_->IsRefreshing());
EXPECT_EQ(previous_changestamp, metadata_->GetLargestChangestamp());
// Add a file to the service.
scoped_ptr<google_apis::ResourceEntry> gdata_entry = AddNewFile("New File");
ASSERT_TRUE(gdata_entry);
// CheckForUpdates() results in update.
TestChangeListLoaderObserver observer(change_list_loader_.get());
change_list_loader_->CheckForUpdates(
google_apis::test_util::CreateCopyResultCallback(
&check_for_updates_error));
EXPECT_TRUE(change_list_loader_->IsRefreshing());
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(change_list_loader_->IsRefreshing());
EXPECT_LT(previous_changestamp, metadata_->GetLargestChangestamp());
EXPECT_EQ(1, observer.load_from_server_complete_count());
EXPECT_EQ(1U, observer.changed_directories().count(
util::GetDriveMyDriveRootPath()));
// The new file is found in the local metadata.
base::FilePath new_file_path =
util::GetDriveMyDriveRootPath().AppendASCII(gdata_entry->title());
ResourceEntry entry;
EXPECT_EQ(FILE_ERROR_OK,
metadata_->GetResourceEntryByPath(new_file_path, &entry));
}
} // namespace internal
} // namespace drive
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_webnavigation_api.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/render_view_context_menu.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/context_menu_params.h"
#include "net/base/mock_host_resolver.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebContextMenuData.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebInputEvent.h"
using content::WebContents;
namespace {
class TestRenderViewContextMenu : public RenderViewContextMenu {
public:
TestRenderViewContextMenu(WebContents* web_contents,
const content::ContextMenuParams& params)
: RenderViewContextMenu(web_contents, params) {
}
virtual ~TestRenderViewContextMenu() {}
private:
virtual void PlatformInit() {}
virtual bool GetAcceleratorForCommandId(int, ui::Accelerator*) {
return false;
}
DISALLOW_COPY_AND_ASSIGN(TestRenderViewContextMenu);
};
} // namespace
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigation) {
FrameNavigationState::set_allow_extension_scheme(true);
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAllowLegacyExtensionManifests);
ASSERT_TRUE(
RunExtensionSubtest("webnavigation", "test_api.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationGetFrame) {
FrameNavigationState::set_allow_extension_scheme(true);
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAllowLegacyExtensionManifests);
ASSERT_TRUE(
RunExtensionSubtest("webnavigation", "test_getFrame.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationClientRedirect) {
FrameNavigationState::set_allow_extension_scheme(true);
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAllowLegacyExtensionManifests);
ASSERT_TRUE(
RunExtensionSubtest("webnavigation", "test_clientRedirect.html"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationServerRedirect) {
FrameNavigationState::set_allow_extension_scheme(true);
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(StartTestServer());
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAllowLegacyExtensionManifests);
ASSERT_TRUE(
RunExtensionSubtest("webnavigation", "test_serverRedirect.html"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationForwardBack) {
FrameNavigationState::set_allow_extension_scheme(true);
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAllowLegacyExtensionManifests);
ASSERT_TRUE(
RunExtensionSubtest("webnavigation", "test_forwardBack.html"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationIFrame) {
FrameNavigationState::set_allow_extension_scheme(true);
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAllowLegacyExtensionManifests);
ASSERT_TRUE(
RunExtensionSubtest("webnavigation", "test_iframe.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationOpenTab) {
FrameNavigationState::set_allow_extension_scheme(true);
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAllowLegacyExtensionManifests);
ASSERT_TRUE(
RunExtensionSubtest("webnavigation", "test_openTab.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationReferenceFragment) {
FrameNavigationState::set_allow_extension_scheme(true);
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAllowLegacyExtensionManifests);
ASSERT_TRUE(
RunExtensionSubtest("webnavigation", "test_referenceFragment.html"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationSimpleLoad) {
FrameNavigationState::set_allow_extension_scheme(true);
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAllowLegacyExtensionManifests);
ASSERT_TRUE(
RunExtensionSubtest("webnavigation", "test_simpleLoad.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationFailures) {
FrameNavigationState::set_allow_extension_scheme(true);
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAllowLegacyExtensionManifests);
ASSERT_TRUE(
RunExtensionSubtest("webnavigation", "test_failures.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationUserAction) {
FrameNavigationState::set_allow_extension_scheme(true);
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAllowLegacyExtensionManifests);
// Wait for the extension to set itself up and return control to us.
ASSERT_TRUE(
RunExtensionSubtest("webnavigation", "test_userAction.html")) << message_;
WebContents* tab = browser()->GetSelectedWebContents();
ui_test_utils::WaitForLoadStop(tab);
ResultCatcher catcher;
ExtensionService* service = browser()->profile()->GetExtensionService();
const Extension* extension =
service->GetExtensionById(last_loaded_extension_id_, false);
GURL url = extension->GetResourceURL("userAction/a.html");
ui_test_utils::NavigateToURL(browser(), url);
// This corresponds to "Open link in new tab".
content::ContextMenuParams params;
params.is_editable = false;
params.media_type = WebKit::WebContextMenuData::MediaTypeNone;
params.page_url = url;
params.frame_id =
ExtensionWebNavigationTabObserver::Get(tab)->
frame_navigation_state().GetMainFrameID();
params.link_url = extension->GetResourceURL("userAction/b.html");
TestRenderViewContextMenu menu(tab, params);
menu.Init();
menu.ExecuteCommand(IDC_CONTENT_CONTEXT_OPENLINKNEWTAB);
ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationRequestOpenTab) {
FrameNavigationState::set_allow_extension_scheme(true);
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAllowLegacyExtensionManifests);
// Wait for the extension to set itself up and return control to us.
ASSERT_TRUE(RunExtensionSubtest("webnavigation", "test_requestOpenTab.html"))
<< message_;
WebContents* tab = browser()->GetSelectedWebContents();
ui_test_utils::WaitForLoadStop(tab);
ResultCatcher catcher;
ExtensionService* service = browser()->profile()->GetExtensionService();
const Extension* extension =
service->GetExtensionById(last_loaded_extension_id_, false);
GURL url = extension->GetResourceURL("requestOpenTab/a.html");
ui_test_utils::NavigateToURL(browser(), url);
// There's a link on a.html. Middle-click on it to open it in a new tab.
WebKit::WebMouseEvent mouse_event;
mouse_event.type = WebKit::WebInputEvent::MouseDown;
mouse_event.button = WebKit::WebMouseEvent::ButtonMiddle;
mouse_event.x = 7;
mouse_event.y = 7;
mouse_event.clickCount = 1;
tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);
mouse_event.type = WebKit::WebInputEvent::MouseUp;
tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);
ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationTargetBlank) {
FrameNavigationState::set_allow_extension_scheme(true);
ASSERT_TRUE(StartTestServer());
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAllowLegacyExtensionManifests);
// Wait for the extension to set itself up and return control to us.
ASSERT_TRUE(RunExtensionSubtest("webnavigation", "test_targetBlank.html"))
<< message_;
WebContents* tab = browser()->GetSelectedWebContents();
ui_test_utils::WaitForLoadStop(tab);
ResultCatcher catcher;
GURL url = test_server()->GetURL(
"files/extensions/api_test/webnavigation/targetBlank/a.html");
browser::NavigateParams params(browser(), url, content::PAGE_TRANSITION_LINK);
ui_test_utils::NavigateToURL(¶ms);
// There's a link with target=_blank on a.html. Click on it to open it in a
// new tab.
WebKit::WebMouseEvent mouse_event;
mouse_event.type = WebKit::WebInputEvent::MouseDown;
mouse_event.button = WebKit::WebMouseEvent::ButtonLeft;
mouse_event.x = 7;
mouse_event.y = 7;
mouse_event.clickCount = 1;
tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);
mouse_event.type = WebKit::WebInputEvent::MouseUp;
tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);
ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationTargetBlankIncognito) {
FrameNavigationState::set_allow_extension_scheme(true);
ASSERT_TRUE(StartTestServer());
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAllowLegacyExtensionManifests);
// Wait for the extension to set itself up and return control to us.
ASSERT_TRUE(RunExtensionSubtestIncognito(
"webnavigation", "test_targetBlank.html")) << message_;
ResultCatcher catcher;
GURL url = test_server()->GetURL(
"files/extensions/api_test/webnavigation/targetBlank/a.html");
ui_test_utils::OpenURLOffTheRecord(browser()->profile(), url);
WebContents* tab = BrowserList::FindTabbedBrowser(
browser()->profile()->GetOffTheRecordProfile(), false)->
GetSelectedWebContents();
// There's a link with target=_blank on a.html. Click on it to open it in a
// new tab.
WebKit::WebMouseEvent mouse_event;
mouse_event.type = WebKit::WebInputEvent::MouseDown;
mouse_event.button = WebKit::WebMouseEvent::ButtonLeft;
mouse_event.x = 7;
mouse_event.y = 7;
mouse_event.clickCount = 1;
tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);
mouse_event.type = WebKit::WebInputEvent::MouseUp;
tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);
ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();
}
<commit_msg>Marks a test as flaky.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_webnavigation_api.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/render_view_context_menu.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/context_menu_params.h"
#include "net/base/mock_host_resolver.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebContextMenuData.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebInputEvent.h"
using content::WebContents;
namespace {
class TestRenderViewContextMenu : public RenderViewContextMenu {
public:
TestRenderViewContextMenu(WebContents* web_contents,
const content::ContextMenuParams& params)
: RenderViewContextMenu(web_contents, params) {
}
virtual ~TestRenderViewContextMenu() {}
private:
virtual void PlatformInit() {}
virtual bool GetAcceleratorForCommandId(int, ui::Accelerator*) {
return false;
}
DISALLOW_COPY_AND_ASSIGN(TestRenderViewContextMenu);
};
} // namespace
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigation) {
FrameNavigationState::set_allow_extension_scheme(true);
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAllowLegacyExtensionManifests);
ASSERT_TRUE(
RunExtensionSubtest("webnavigation", "test_api.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationGetFrame) {
FrameNavigationState::set_allow_extension_scheme(true);
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAllowLegacyExtensionManifests);
ASSERT_TRUE(
RunExtensionSubtest("webnavigation", "test_getFrame.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationClientRedirect) {
FrameNavigationState::set_allow_extension_scheme(true);
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAllowLegacyExtensionManifests);
ASSERT_TRUE(
RunExtensionSubtest("webnavigation", "test_clientRedirect.html"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationServerRedirect) {
FrameNavigationState::set_allow_extension_scheme(true);
host_resolver()->AddRule("*", "127.0.0.1");
ASSERT_TRUE(StartTestServer());
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAllowLegacyExtensionManifests);
ASSERT_TRUE(
RunExtensionSubtest("webnavigation", "test_serverRedirect.html"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationForwardBack) {
FrameNavigationState::set_allow_extension_scheme(true);
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAllowLegacyExtensionManifests);
ASSERT_TRUE(
RunExtensionSubtest("webnavigation", "test_forwardBack.html"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationIFrame) {
FrameNavigationState::set_allow_extension_scheme(true);
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAllowLegacyExtensionManifests);
ASSERT_TRUE(
RunExtensionSubtest("webnavigation", "test_iframe.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationOpenTab) {
FrameNavigationState::set_allow_extension_scheme(true);
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAllowLegacyExtensionManifests);
ASSERT_TRUE(
RunExtensionSubtest("webnavigation", "test_openTab.html")) << message_;
}
// This test has been timing out: 114208.
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FLAKY_WebNavigationReferenceFragment) {
FrameNavigationState::set_allow_extension_scheme(true);
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAllowLegacyExtensionManifests);
ASSERT_TRUE(
RunExtensionSubtest("webnavigation", "test_referenceFragment.html"))
<< message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationSimpleLoad) {
FrameNavigationState::set_allow_extension_scheme(true);
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAllowLegacyExtensionManifests);
ASSERT_TRUE(
RunExtensionSubtest("webnavigation", "test_simpleLoad.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationFailures) {
FrameNavigationState::set_allow_extension_scheme(true);
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAllowLegacyExtensionManifests);
ASSERT_TRUE(
RunExtensionSubtest("webnavigation", "test_failures.html")) << message_;
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationUserAction) {
FrameNavigationState::set_allow_extension_scheme(true);
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAllowLegacyExtensionManifests);
// Wait for the extension to set itself up and return control to us.
ASSERT_TRUE(
RunExtensionSubtest("webnavigation", "test_userAction.html")) << message_;
WebContents* tab = browser()->GetSelectedWebContents();
ui_test_utils::WaitForLoadStop(tab);
ResultCatcher catcher;
ExtensionService* service = browser()->profile()->GetExtensionService();
const Extension* extension =
service->GetExtensionById(last_loaded_extension_id_, false);
GURL url = extension->GetResourceURL("userAction/a.html");
ui_test_utils::NavigateToURL(browser(), url);
// This corresponds to "Open link in new tab".
content::ContextMenuParams params;
params.is_editable = false;
params.media_type = WebKit::WebContextMenuData::MediaTypeNone;
params.page_url = url;
params.frame_id =
ExtensionWebNavigationTabObserver::Get(tab)->
frame_navigation_state().GetMainFrameID();
params.link_url = extension->GetResourceURL("userAction/b.html");
TestRenderViewContextMenu menu(tab, params);
menu.Init();
menu.ExecuteCommand(IDC_CONTENT_CONTEXT_OPENLINKNEWTAB);
ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationRequestOpenTab) {
FrameNavigationState::set_allow_extension_scheme(true);
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAllowLegacyExtensionManifests);
// Wait for the extension to set itself up and return control to us.
ASSERT_TRUE(RunExtensionSubtest("webnavigation", "test_requestOpenTab.html"))
<< message_;
WebContents* tab = browser()->GetSelectedWebContents();
ui_test_utils::WaitForLoadStop(tab);
ResultCatcher catcher;
ExtensionService* service = browser()->profile()->GetExtensionService();
const Extension* extension =
service->GetExtensionById(last_loaded_extension_id_, false);
GURL url = extension->GetResourceURL("requestOpenTab/a.html");
ui_test_utils::NavigateToURL(browser(), url);
// There's a link on a.html. Middle-click on it to open it in a new tab.
WebKit::WebMouseEvent mouse_event;
mouse_event.type = WebKit::WebInputEvent::MouseDown;
mouse_event.button = WebKit::WebMouseEvent::ButtonMiddle;
mouse_event.x = 7;
mouse_event.y = 7;
mouse_event.clickCount = 1;
tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);
mouse_event.type = WebKit::WebInputEvent::MouseUp;
tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);
ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationTargetBlank) {
FrameNavigationState::set_allow_extension_scheme(true);
ASSERT_TRUE(StartTestServer());
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAllowLegacyExtensionManifests);
// Wait for the extension to set itself up and return control to us.
ASSERT_TRUE(RunExtensionSubtest("webnavigation", "test_targetBlank.html"))
<< message_;
WebContents* tab = browser()->GetSelectedWebContents();
ui_test_utils::WaitForLoadStop(tab);
ResultCatcher catcher;
GURL url = test_server()->GetURL(
"files/extensions/api_test/webnavigation/targetBlank/a.html");
browser::NavigateParams params(browser(), url, content::PAGE_TRANSITION_LINK);
ui_test_utils::NavigateToURL(¶ms);
// There's a link with target=_blank on a.html. Click on it to open it in a
// new tab.
WebKit::WebMouseEvent mouse_event;
mouse_event.type = WebKit::WebInputEvent::MouseDown;
mouse_event.button = WebKit::WebMouseEvent::ButtonLeft;
mouse_event.x = 7;
mouse_event.y = 7;
mouse_event.clickCount = 1;
tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);
mouse_event.type = WebKit::WebInputEvent::MouseUp;
tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);
ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();
}
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, WebNavigationTargetBlankIncognito) {
FrameNavigationState::set_allow_extension_scheme(true);
ASSERT_TRUE(StartTestServer());
CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kAllowLegacyExtensionManifests);
// Wait for the extension to set itself up and return control to us.
ASSERT_TRUE(RunExtensionSubtestIncognito(
"webnavigation", "test_targetBlank.html")) << message_;
ResultCatcher catcher;
GURL url = test_server()->GetURL(
"files/extensions/api_test/webnavigation/targetBlank/a.html");
ui_test_utils::OpenURLOffTheRecord(browser()->profile(), url);
WebContents* tab = BrowserList::FindTabbedBrowser(
browser()->profile()->GetOffTheRecordProfile(), false)->
GetSelectedWebContents();
// There's a link with target=_blank on a.html. Click on it to open it in a
// new tab.
WebKit::WebMouseEvent mouse_event;
mouse_event.type = WebKit::WebInputEvent::MouseDown;
mouse_event.button = WebKit::WebMouseEvent::ButtonLeft;
mouse_event.x = 7;
mouse_event.y = 7;
mouse_event.clickCount = 1;
tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);
mouse_event.type = WebKit::WebInputEvent::MouseUp;
tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);
ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();
}
<|endoftext|>
|
<commit_before>
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#include "BeaconEntity.h"
#include "../BlockArea.h"
#include "../Entities/Player.h"
#include "../UI/BeaconWindow.h"
#include "../ClientHandle.h"
cBeaconEntity::cBeaconEntity(BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World):
Super(a_BlockType, a_BlockMeta, a_BlockX, a_BlockY, a_BlockZ, 1, 1, a_World),
m_IsActive(false),
m_BeaconLevel(0),
m_PrimaryEffect(cEntityEffect::effNoEffect),
m_SecondaryEffect(cEntityEffect::effNoEffect)
{
ASSERT(a_BlockType == E_BLOCK_BEACON);
if (m_World != nullptr)
{
UpdateBeacon();
}
}
char cBeaconEntity::CalculatePyramidLevel(void)
{
cBlockArea Area;
int MinY = std::max(GetPosY() - 4, 0);
int MaxY = std::max(GetPosY() - 1, 0);
Area.Read(
*m_World,
GetPosX() - 4, GetPosX() + 4,
MinY, MaxY,
GetPosZ() - 4, GetPosZ() + 4,
cBlockArea::baTypes
);
int Layer = 1;
int MiddleXZ = 4;
for (int Y = (Area.GetSizeY() - 1); Y >= 0; Y--)
{
for (int X = MiddleXZ - Layer; X <= (MiddleXZ + Layer); X++)
{
for (int Z = MiddleXZ - Layer; Z <= (MiddleXZ + Layer); Z++)
{
if (!IsMineralBlock(Area.GetRelBlockType(X, Y, Z)))
{
return static_cast<char>(Layer - 1);
}
}
}
Layer++;
}
return static_cast<char>(Layer - 1);
}
bool cBeaconEntity::IsValidEffect(cEntityEffect::eType a_Effect, char a_BeaconLevel)
{
switch (a_Effect)
{
case cEntityEffect::effRegeneration: return (a_BeaconLevel >= 4);
case cEntityEffect::effStrength: return (a_BeaconLevel >= 3);
case cEntityEffect::effResistance: return (a_BeaconLevel >= 2);
case cEntityEffect::effJumpBoost: return (a_BeaconLevel >= 2);
case cEntityEffect::effSpeed: return (a_BeaconLevel >= 1);
case cEntityEffect::effHaste: return (a_BeaconLevel >= 1);
case cEntityEffect::effNoEffect: return true;
default:
{
LOGD("%s: Invalid beacon effect: %d", __FUNCTION__, static_cast<int>(a_Effect));
return false;
}
}
}
bool cBeaconEntity::SetPrimaryEffect(cEntityEffect::eType a_Effect)
{
if (!IsValidEffect(a_Effect, m_BeaconLevel))
{
m_PrimaryEffect = cEntityEffect::effNoEffect;
return false;
}
m_PrimaryEffect = a_Effect;
// Send window update:
if (GetWindow() != nullptr)
{
GetWindow()->SetProperty(1, m_PrimaryEffect);
}
return true;
}
bool cBeaconEntity::SetSecondaryEffect(cEntityEffect::eType a_Effect)
{
if (!IsValidEffect(a_Effect, m_BeaconLevel))
{
m_SecondaryEffect = cEntityEffect::effNoEffect;
return false;
}
m_SecondaryEffect = a_Effect;
// Send window update:
if (GetWindow() != nullptr)
{
GetWindow()->SetProperty(2, m_SecondaryEffect);
}
return true;
}
bool cBeaconEntity::IsBeaconBlocked(void)
{
for (int Y = m_PosY; Y < cChunkDef::Height; ++Y)
{
BLOCKTYPE Block = m_World->GetBlock(m_PosX, Y, m_PosZ);
if (!cBlockInfo::IsTransparent(Block))
{
return true;
}
}
return false;
}
bool cBeaconEntity::IsMineralBlock(BLOCKTYPE a_BlockType)
{
switch (a_BlockType)
{
case E_BLOCK_DIAMOND_BLOCK:
case E_BLOCK_GOLD_BLOCK:
case E_BLOCK_IRON_BLOCK:
case E_BLOCK_EMERALD_BLOCK:
{
return true;
}
}
return false;
}
void cBeaconEntity::UpdateBeacon(void)
{
int OldBeaconLevel = m_BeaconLevel;
if (IsBeaconBlocked())
{
m_IsActive = false;
m_BeaconLevel = 0;
}
else
{
m_BeaconLevel = CalculatePyramidLevel();
m_IsActive = (m_BeaconLevel > 0);
}
if (m_BeaconLevel != OldBeaconLevel)
{
// Send window update:
if (GetWindow() != nullptr)
{
GetWindow()->SetProperty(0, m_BeaconLevel);
}
}
// TODO: Add achievement
}
void cBeaconEntity::GiveEffects(void)
{
if (!m_IsActive || (m_BeaconLevel < 0))
{
return;
}
int Radius = m_BeaconLevel * 10 + 10;
short EffectLevel = 0;
if ((m_BeaconLevel >= 4) && (m_PrimaryEffect == m_SecondaryEffect))
{
EffectLevel = 1;
}
cEntityEffect::eType SecondaryEffect = cEntityEffect::effNoEffect;
if ((m_BeaconLevel >= 4) && (m_PrimaryEffect != m_SecondaryEffect) && (m_SecondaryEffect > 0))
{
SecondaryEffect = m_SecondaryEffect;
}
class cPlayerCallback : public cPlayerListCallback
{
int m_Radius;
int m_PosX, m_PosY, m_PosZ;
cEntityEffect::eType m_PrimaryEffect, m_SecondaryEffect;
short m_EffectLevel;
virtual bool Item(cPlayer * a_Player)
{
Vector3d PlayerPosition = Vector3d(a_Player->GetPosition());
if (PlayerPosition.y > static_cast<double>(m_PosY))
{
PlayerPosition.y = static_cast<double>(m_PosY);
}
// TODO: Vanilla minecraft uses an AABB check instead of a radius one
Vector3d BeaconPosition = Vector3d(m_PosX, m_PosY, m_PosZ);
if ((PlayerPosition - BeaconPosition).Length() <= m_Radius)
{
a_Player->AddEntityEffect(m_PrimaryEffect, 180, m_EffectLevel);
if (m_SecondaryEffect != cEntityEffect::effNoEffect)
{
a_Player->AddEntityEffect(m_SecondaryEffect, 180, 0);
}
}
return false;
}
public:
cPlayerCallback(int a_Radius, int a_PosX, int a_PosY, int a_PosZ, cEntityEffect::eType a_PrimaryEffect, cEntityEffect::eType a_SecondaryEffect, short a_EffectLevel):
m_Radius(a_Radius),
m_PosX(a_PosX),
m_PosY(a_PosY),
m_PosZ(a_PosZ),
m_PrimaryEffect(a_PrimaryEffect),
m_SecondaryEffect(a_SecondaryEffect),
m_EffectLevel(a_EffectLevel)
{
}
} PlayerCallback(Radius, m_PosX, m_PosY, m_PosZ, m_PrimaryEffect, SecondaryEffect, EffectLevel);
GetWorld()->ForEachPlayer(PlayerCallback);
}
void cBeaconEntity::CopyFrom(const cBlockEntity & a_Src)
{
Super::CopyFrom(a_Src);
auto & src = reinterpret_cast<const cBeaconEntity &>(a_Src);
m_BeaconLevel = src.m_BeaconLevel;
m_Contents.CopyFrom(src.m_Contents);
m_IsActive = src.m_IsActive;
m_PrimaryEffect = src.m_PrimaryEffect;
m_SecondaryEffect = src.m_SecondaryEffect;
}
void cBeaconEntity::SendTo(cClientHandle & a_Client)
{
a_Client.SendUpdateBlockEntity(*this);
}
bool cBeaconEntity::Tick(std::chrono::milliseconds a_Dt, cChunk & a_Chunk)
{
// Update the beacon every 4 seconds
if ((GetWorld()->GetWorldAge() % 80) == 0)
{
UpdateBeacon();
GiveEffects();
}
return false;
}
bool cBeaconEntity::UsedBy(cPlayer * a_Player)
{
cWindow * Window = GetWindow();
if (Window == nullptr)
{
OpenWindow(new cBeaconWindow(m_PosX, m_PosY, m_PosZ, this));
Window = GetWindow();
}
if (Window != nullptr)
{
// if (a_Player->GetWindow() != Window)
// -> Because mojang doesn't send a 'close window' packet when you click the cancel button in the beacon inventory ...
{
a_Player->OpenWindow(*Window);
}
}
return true;
}
<commit_msg>Award player an achievement when creating a beacon (#3930)<commit_after>
#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#include "BeaconEntity.h"
#include "../BlockArea.h"
#include "../Entities/Player.h"
#include "../UI/BeaconWindow.h"
#include "../ClientHandle.h"
cBeaconEntity::cBeaconEntity(BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World):
Super(a_BlockType, a_BlockMeta, a_BlockX, a_BlockY, a_BlockZ, 1, 1, a_World),
m_IsActive(false),
m_BeaconLevel(0),
m_PrimaryEffect(cEntityEffect::effNoEffect),
m_SecondaryEffect(cEntityEffect::effNoEffect)
{
ASSERT(a_BlockType == E_BLOCK_BEACON);
if (m_World != nullptr)
{
UpdateBeacon();
}
}
char cBeaconEntity::CalculatePyramidLevel(void)
{
cBlockArea Area;
int MinY = std::max(GetPosY() - 4, 0);
int MaxY = std::max(GetPosY() - 1, 0);
Area.Read(
*m_World,
GetPosX() - 4, GetPosX() + 4,
MinY, MaxY,
GetPosZ() - 4, GetPosZ() + 4,
cBlockArea::baTypes
);
int Layer = 1;
int MiddleXZ = 4;
for (int Y = (Area.GetSizeY() - 1); Y >= 0; Y--)
{
for (int X = MiddleXZ - Layer; X <= (MiddleXZ + Layer); X++)
{
for (int Z = MiddleXZ - Layer; Z <= (MiddleXZ + Layer); Z++)
{
if (!IsMineralBlock(Area.GetRelBlockType(X, Y, Z)))
{
return static_cast<char>(Layer - 1);
}
}
}
Layer++;
}
return static_cast<char>(Layer - 1);
}
bool cBeaconEntity::IsValidEffect(cEntityEffect::eType a_Effect, char a_BeaconLevel)
{
switch (a_Effect)
{
case cEntityEffect::effRegeneration: return (a_BeaconLevel >= 4);
case cEntityEffect::effStrength: return (a_BeaconLevel >= 3);
case cEntityEffect::effResistance: return (a_BeaconLevel >= 2);
case cEntityEffect::effJumpBoost: return (a_BeaconLevel >= 2);
case cEntityEffect::effSpeed: return (a_BeaconLevel >= 1);
case cEntityEffect::effHaste: return (a_BeaconLevel >= 1);
case cEntityEffect::effNoEffect: return true;
default:
{
LOGD("%s: Invalid beacon effect: %d", __FUNCTION__, static_cast<int>(a_Effect));
return false;
}
}
}
bool cBeaconEntity::SetPrimaryEffect(cEntityEffect::eType a_Effect)
{
if (!IsValidEffect(a_Effect, m_BeaconLevel))
{
m_PrimaryEffect = cEntityEffect::effNoEffect;
return false;
}
m_PrimaryEffect = a_Effect;
// Send window update:
if (GetWindow() != nullptr)
{
GetWindow()->SetProperty(1, m_PrimaryEffect);
}
return true;
}
bool cBeaconEntity::SetSecondaryEffect(cEntityEffect::eType a_Effect)
{
if (!IsValidEffect(a_Effect, m_BeaconLevel))
{
m_SecondaryEffect = cEntityEffect::effNoEffect;
return false;
}
m_SecondaryEffect = a_Effect;
// Send window update:
if (GetWindow() != nullptr)
{
GetWindow()->SetProperty(2, m_SecondaryEffect);
}
return true;
}
bool cBeaconEntity::IsBeaconBlocked(void)
{
for (int Y = m_PosY; Y < cChunkDef::Height; ++Y)
{
BLOCKTYPE Block = m_World->GetBlock(m_PosX, Y, m_PosZ);
if (!cBlockInfo::IsTransparent(Block))
{
return true;
}
}
return false;
}
bool cBeaconEntity::IsMineralBlock(BLOCKTYPE a_BlockType)
{
switch (a_BlockType)
{
case E_BLOCK_DIAMOND_BLOCK:
case E_BLOCK_GOLD_BLOCK:
case E_BLOCK_IRON_BLOCK:
case E_BLOCK_EMERALD_BLOCK:
{
return true;
}
}
return false;
}
void cBeaconEntity::UpdateBeacon(void)
{
int OldBeaconLevel = m_BeaconLevel;
if (IsBeaconBlocked())
{
m_IsActive = false;
m_BeaconLevel = 0;
}
else
{
m_BeaconLevel = CalculatePyramidLevel();
m_IsActive = (m_BeaconLevel > 0);
}
if ((m_BeaconLevel != OldBeaconLevel) && (m_BeaconLevel == 4))
{
// Send window update:
if (GetWindow() != nullptr)
{
GetWindow()->SetProperty(0, m_BeaconLevel);
}
class cPlayerCallback :
public cPlayerListCallback
{
public:
cPlayerCallback(Vector3d a_Position):
m_Position(a_Position)
{
}
virtual bool Item(cPlayer * a_Player)
{
Vector3d Distance = m_Position - a_Player->GetPosition();
if (
(std::abs(Distance.y) <= 14) &&
(std::abs(Distance.x) <= 20) &&
(std::abs(Distance.z) <= 20)
)
{
a_Player->AwardAchievement(eStatistic::achFullBeacon);
}
return false;
}
private:
Vector3d m_Position;
} PlayerCallback(Vector3d(m_PosX, m_PosY, m_PosZ));
GetWorld()->ForEachPlayer(PlayerCallback);
}
}
void cBeaconEntity::GiveEffects(void)
{
if (!m_IsActive || (m_BeaconLevel < 0))
{
return;
}
int Radius = m_BeaconLevel * 10 + 10;
short EffectLevel = 0;
if ((m_BeaconLevel >= 4) && (m_PrimaryEffect == m_SecondaryEffect))
{
EffectLevel = 1;
}
cEntityEffect::eType SecondaryEffect = cEntityEffect::effNoEffect;
if ((m_BeaconLevel >= 4) && (m_PrimaryEffect != m_SecondaryEffect) && (m_SecondaryEffect > 0))
{
SecondaryEffect = m_SecondaryEffect;
}
class cPlayerCallback : public cPlayerListCallback
{
int m_Radius;
Vector3d m_Position;
cEntityEffect::eType m_PrimaryEffect, m_SecondaryEffect;
short m_EffectLevel;
virtual bool Item(cPlayer * a_Player)
{
Vector3d PlayerPosition = Vector3d(a_Player->GetPosition());
if (PlayerPosition.y > m_Position.y)
{
PlayerPosition.y = m_Position.y;
}
// TODO: Vanilla minecraft uses an AABB check instead of a radius one
if ((PlayerPosition - m_Position).Length() <= m_Radius)
{
a_Player->AddEntityEffect(m_PrimaryEffect, 180, m_EffectLevel);
if (m_SecondaryEffect != cEntityEffect::effNoEffect)
{
a_Player->AddEntityEffect(m_SecondaryEffect, 180, 0);
}
}
return false;
}
public:
cPlayerCallback(int a_Radius, Vector3d a_Position, cEntityEffect::eType a_PrimaryEffect, cEntityEffect::eType a_SecondaryEffect, short a_EffectLevel):
m_Radius(a_Radius),
m_Position(a_Position),
m_PrimaryEffect(a_PrimaryEffect),
m_SecondaryEffect(a_SecondaryEffect),
m_EffectLevel(a_EffectLevel)
{
}
} PlayerCallback(Radius, Vector3d(m_PosX, m_PosY, m_PosZ), m_PrimaryEffect, SecondaryEffect, EffectLevel);
GetWorld()->ForEachPlayer(PlayerCallback);
}
void cBeaconEntity::CopyFrom(const cBlockEntity & a_Src)
{
Super::CopyFrom(a_Src);
auto & src = reinterpret_cast<const cBeaconEntity &>(a_Src);
m_BeaconLevel = src.m_BeaconLevel;
m_Contents.CopyFrom(src.m_Contents);
m_IsActive = src.m_IsActive;
m_PrimaryEffect = src.m_PrimaryEffect;
m_SecondaryEffect = src.m_SecondaryEffect;
}
void cBeaconEntity::SendTo(cClientHandle & a_Client)
{
a_Client.SendUpdateBlockEntity(*this);
}
bool cBeaconEntity::Tick(std::chrono::milliseconds a_Dt, cChunk & a_Chunk)
{
// Update the beacon every 4 seconds
if ((GetWorld()->GetWorldAge() % 80) == 0)
{
UpdateBeacon();
GiveEffects();
}
return false;
}
bool cBeaconEntity::UsedBy(cPlayer * a_Player)
{
cWindow * Window = GetWindow();
if (Window == nullptr)
{
OpenWindow(new cBeaconWindow(m_PosX, m_PosY, m_PosZ, this));
Window = GetWindow();
}
if (Window != nullptr)
{
// if (a_Player->GetWindow() != Window)
// -> Because mojang doesn't send a 'close window' packet when you click the cancel button in the beacon inventory ...
{
a_Player->OpenWindow(*Window);
}
}
return true;
}
<|endoftext|>
|
<commit_before>/**
* The Seeks proxy and plugin framework are part of the SEEKS project.
* Copyright (C) 2009 Emmanuel Benazera, juban@free.fr
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "plugin_manager.h"
#include "seeks_proxy.h"
#include "proxy_configuration.h"
#include "errlog.h"
#include "plugin.h"
#include "interceptor_plugin.h"
#include "action_plugin.h"
#include "filter_plugin.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dlfcn.h> // linux, TODO: windows.
#include <list>
#include <iostream>
#include <assert.h>
using sp::proxy_configuration;
namespace sp
{
// variables.
std::vector<plugin*> plugin_manager::_plugins = std::vector<plugin*>();
std::vector<interceptor_plugin*> plugin_manager::_ref_interceptor_plugins
= std::vector<interceptor_plugin*>();
std::vector<action_plugin*> plugin_manager::_ref_action_plugins
= std::vector<action_plugin*>();
std::vector<filter_plugin*> plugin_manager::_ref_filter_plugins
= std::vector<filter_plugin*>();
hash_map<const char*,cgi_dispatcher*,hash<const char*>,eqstr> plugin_manager::_cgi_dispatchers
= hash_map<const char*,cgi_dispatcher*,hash<const char*>,eqstr>();
std::string plugin_manager::_plugin_repository = "";
std::map<std::string,maker_ptr*,std::less<std::string> > plugin_manager::_factory
= std::map<std::string,maker_ptr*,std::less<std::string> >();
std::list<void*> plugin_manager::_dl_list = std::list<void*>();
std::map<std::string,configuration_spec*,std::less<std::string> > plugin_manager::_configurations
= std::map<std::string,configuration_spec*,std::less<std::string> >();
std::string plugin_manager::_config_html_template = "templates/pm_config.html";
int plugin_manager::load_all_plugins()
{
/**
* Defaults the plugin repository to the base directory, only if the repository has not been set
* through the command line, or in the configuration file, in that order.
*/
if (plugin_manager::_plugin_repository.empty() && seeks_proxy::_config->_plugindir)
{
plugin_manager::_plugin_repository = std::string(seeks_proxy::_config->_plugindir);
}
else if (plugin_manager::_plugin_repository.empty())
{
// basedir.
assert(seeks_proxy::_basedir);
plugin_manager::_plugin_repository = std::string(seeks_proxy::_basedir)
#ifdef unix
+ "/plugins/"
#endif
;
#if defined(_WIN32)
+ "\plugins\\";
#endif
}
unsigned int BUF_SIZE = 1024;
// TODO: win32...
std::string command_str = "find " + plugin_manager::_plugin_repository
#if defined(ON_OPENBSD)
+ " -name *.so*";
#elsif defined (ON_OSX)
+ " -name *plugin.dylib";
#else
+ " -name *.so";
#endif
FILE *dl = popen(command_str.c_str(), "r"); // reading directory.
if (!dl)
{
perror("popen");
exit(-1);
}
void *dlib;
char name[1024];
char in_buf[BUF_SIZE]; // input buffer for lib names.
while(fgets(in_buf, BUF_SIZE, dl))
{
char *ws = strpbrk(in_buf, " \t\n"); // remove spaces.
if (ws) *ws = '\0';
sprintf(name, "%s", in_buf); // append './' to lib name.
dlib = dlopen(name, RTLD_NOW); // NOW imposes resolving all symbols
// required for auto-registration.
if (dlib == NULL)
{
errlog::log_error(LOG_LEVEL_FATAL, "%s", dlerror());
exit(-1);
}
plugin_manager::_dl_list.insert(plugin_manager::_dl_list.end(),dlib); // add lib handle to the list.
#if defined(ON_OPENBSD) || defined(ON_OSX)
maker_ptr *pl_fct = (maker_ptr*)dlsym(dlib,"maker");
if (!pl_fct)
continue;
plugin *pl = (*pl_fct)();
if (pl)
plugin_manager::_factory[pl->get_name()] = pl_fct;
#endif
}
pclose(dl);
//debug
std::map<std::string,maker_ptr*,std::less<std::string> >::const_iterator mit
= plugin_manager::_factory.begin();
while(mit!=plugin_manager::_factory.end())
{
errlog::log_error(LOG_LEVEL_INFO,"loaded plugin \t%s", (*mit).first.c_str());
mit++;
}
//debug
return 1;
}
int plugin_manager::close_all_plugins()
{
// destroy all plugins that have been created.
std::vector<plugin*>::iterator vit = plugin_manager::_plugins.begin();
while(vit!=plugin_manager::_plugins.end())
{
delete *vit;
++vit;
}
plugin_manager::_plugins.clear();
// close all the opened dynamic libs.
std::list<void*>::iterator lit = plugin_manager::_dl_list.begin();
while(lit!=plugin_manager::_dl_list.end())
{
dlclose((*lit));
++lit;
}
return 1;
}
int plugin_manager::instanciate_plugins()
{
std::map<std::string,maker_ptr*,std::less<std::string> >::const_iterator mit
= plugin_manager::_factory.begin();
while(mit!=plugin_manager::_factory.end())
{
plugin *p = (*mit).second(); // call to a maker function.
// register the plugin object and its functions, if activated.
if (seeks_proxy::_config->is_plugin_activated(p->get_name_cstr()))
{
plugin_manager::register_plugin(p);
// register the plugin elements.
if (p->_interceptor_plugin)
plugin_manager::_ref_interceptor_plugins.push_back(p->_interceptor_plugin);
if (p->_action_plugin)
plugin_manager::_ref_action_plugins.push_back(p->_action_plugin);
if (p->_filter_plugin)
plugin_manager::_ref_filter_plugins.push_back(p->_filter_plugin);
// run start() on plugin.
p->start();
}
++mit;
}
return 0;
}
//TODO: deinstanciate plugin = deregister + stop().
void plugin_manager::register_plugin(plugin *p)
{
plugin_manager::_plugins.push_back(p);
errlog::log_error(LOG_LEVEL_INFO,"Registering plugin %s, and %d CGI dispatchers",
p->get_name_cstr(), p->_cgi_dispatchers.size());
std::vector<cgi_dispatcher*>::const_iterator vit = p->_cgi_dispatchers.begin();
while(vit != p->_cgi_dispatchers.end())
{
cgi_dispatcher *cgid = (*vit);
hash_map<const char*,cgi_dispatcher*,hash<const char*>,eqstr>::iterator hit;
if ((hit = plugin_manager::_cgi_dispatchers.find(cgid->_name)) != plugin_manager::_cgi_dispatchers.end())
{
errlog::log_error(LOG_LEVEL_CGI, "CGI function %s of plugin %s, has already been registered by another plugin.",
cgid->_name, p->get_name_cstr());
}
else
{
errlog::log_error(LOG_LEVEL_INFO, "registering CGI dispatcher %s", cgid->_name);
plugin_manager::_cgi_dispatchers.insert(std::pair<const char*,cgi_dispatcher*>(cgid->_name,
cgid));
}
++vit;
}
}
cgi_dispatcher* plugin_manager::find_plugin_cgi_dispatcher(const char *path)
{
hash_map<const char*,cgi_dispatcher*,hash<const char*>,eqstr>::const_iterator hit;
if((hit = plugin_manager::_cgi_dispatchers.find(path)) != plugin_manager::_cgi_dispatchers.end())
return (*hit).second;
else
{
errlog::log_error(LOG_LEVEL_ERROR, "Can't find any plugin dispatcher in %s", path);
return NULL;
}
}
void plugin_manager::get_url_plugins(client_state *csp, http_request *http)
{
std::vector<interceptor_plugin*>::const_iterator lit1
= plugin_manager::_ref_interceptor_plugins.begin();
while(lit1!=plugin_manager::_ref_interceptor_plugins.end())
{
interceptor_plugin *ip = (*lit1);
#ifdef PLUGIN_DEBUG
ip->reload();
#endif
if (ip->match_url(http))
csp->add_interceptor_plugin(ip);
++lit1;
}
std::vector<action_plugin*>::const_iterator lit2
= plugin_manager::_ref_action_plugins.begin();
while(lit2!=plugin_manager::_ref_action_plugins.end())
{
action_plugin *ip = (*lit2);
#ifdef PLUGIN_DEBUG
ip->reload();
#endif
if (ip->match_url(http))
csp->add_action_plugin(ip);
++lit2;
}
std::vector<filter_plugin*>::const_iterator lit3
= plugin_manager::_ref_filter_plugins.begin();
while(lit3!=plugin_manager::_ref_filter_plugins.end())
{
filter_plugin *ip = (*lit3);
#ifdef PLUGIN_DEBUG
ip->reload();
#endif
if (ip->match_url(http))
csp->add_filter_plugin(ip);
++lit3;
}
// debug
/* std::cout << "[Debug]:plugin_manager::get_url_plugin: interceptor plugins: "
<< csp->_interceptor_plugins.size() << std::endl; */
//debug
}
plugin* plugin_manager::get_plugin(const std::string &name)
{
std::vector<plugin*>::const_iterator vit = plugin_manager::_plugins.begin();
while(vit!=plugin_manager::_plugins.end())
{
if ((*vit)->get_name() == name)
return (*vit);
++vit;
}
return NULL;
}
} /* end of namespace. */
<commit_msg>plugin loading failure is no more a fatal error<commit_after>/**
* The Seeks proxy and plugin framework are part of the SEEKS project.
* Copyright (C) 2009 Emmanuel Benazera, juban@free.fr
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "plugin_manager.h"
#include "seeks_proxy.h"
#include "proxy_configuration.h"
#include "errlog.h"
#include "plugin.h"
#include "interceptor_plugin.h"
#include "action_plugin.h"
#include "filter_plugin.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dlfcn.h> // linux, TODO: windows.
#include <list>
#include <iostream>
#include <assert.h>
using sp::proxy_configuration;
namespace sp
{
// variables.
std::vector<plugin*> plugin_manager::_plugins = std::vector<plugin*>();
std::vector<interceptor_plugin*> plugin_manager::_ref_interceptor_plugins
= std::vector<interceptor_plugin*>();
std::vector<action_plugin*> plugin_manager::_ref_action_plugins
= std::vector<action_plugin*>();
std::vector<filter_plugin*> plugin_manager::_ref_filter_plugins
= std::vector<filter_plugin*>();
hash_map<const char*,cgi_dispatcher*,hash<const char*>,eqstr> plugin_manager::_cgi_dispatchers
= hash_map<const char*,cgi_dispatcher*,hash<const char*>,eqstr>();
std::string plugin_manager::_plugin_repository = "";
std::map<std::string,maker_ptr*,std::less<std::string> > plugin_manager::_factory
= std::map<std::string,maker_ptr*,std::less<std::string> >();
std::list<void*> plugin_manager::_dl_list = std::list<void*>();
std::map<std::string,configuration_spec*,std::less<std::string> > plugin_manager::_configurations
= std::map<std::string,configuration_spec*,std::less<std::string> >();
std::string plugin_manager::_config_html_template = "templates/pm_config.html";
int plugin_manager::load_all_plugins()
{
/**
* Defaults the plugin repository to the base directory, only if the repository has not been set
* through the command line, or in the configuration file, in that order.
*/
if (plugin_manager::_plugin_repository.empty() && seeks_proxy::_config->_plugindir)
{
plugin_manager::_plugin_repository = std::string(seeks_proxy::_config->_plugindir);
}
else if (plugin_manager::_plugin_repository.empty())
{
// basedir.
assert(seeks_proxy::_basedir);
plugin_manager::_plugin_repository = std::string(seeks_proxy::_basedir)
#ifdef unix
+ "/plugins/"
#endif
;
#if defined(_WIN32)
+ "\plugins\\";
#endif
}
unsigned int BUF_SIZE = 1024;
// TODO: win32...
std::string command_str = "find " + plugin_manager::_plugin_repository
#if defined(ON_OPENBSD)
+ " -name *.so*";
#elsif defined (ON_OSX)
+ " -name *plugin.dylib";
#else
+ " -name *.so";
#endif
FILE *dl = popen(command_str.c_str(), "r"); // reading directory.
if (!dl)
{
perror("popen");
exit(-1);
}
void *dlib;
char name[1024];
char in_buf[BUF_SIZE]; // input buffer for lib names.
while(fgets(in_buf, BUF_SIZE, dl))
{
char *ws = strpbrk(in_buf, " \t\n"); // remove spaces.
if (ws) *ws = '\0';
sprintf(name, "%s", in_buf); // append './' to lib name.
dlib = dlopen(name, RTLD_NOW); // NOW imposes resolving all symbols
// required for auto-registration.
if (dlib == NULL)
{
errlog::log_error(LOG_LEVEL_ERROR, "%s", dlerror());
//exit(-1);
}
plugin_manager::_dl_list.insert(plugin_manager::_dl_list.end(),dlib); // add lib handle to the list.
#if defined(ON_OPENBSD) || defined(ON_OSX)
maker_ptr *pl_fct = (maker_ptr*)dlsym(dlib,"maker");
if (!pl_fct)
continue;
plugin *pl = (*pl_fct)();
if (pl)
plugin_manager::_factory[pl->get_name()] = pl_fct;
#endif
}
pclose(dl);
//debug
std::map<std::string,maker_ptr*,std::less<std::string> >::const_iterator mit
= plugin_manager::_factory.begin();
while(mit!=plugin_manager::_factory.end())
{
errlog::log_error(LOG_LEVEL_INFO,"loaded plugin \t%s", (*mit).first.c_str());
mit++;
}
//debug
return 1;
}
int plugin_manager::close_all_plugins()
{
// destroy all plugins that have been created.
std::vector<plugin*>::iterator vit = plugin_manager::_plugins.begin();
while(vit!=plugin_manager::_plugins.end())
{
delete *vit;
++vit;
}
plugin_manager::_plugins.clear();
// close all the opened dynamic libs.
std::list<void*>::iterator lit = plugin_manager::_dl_list.begin();
while(lit!=plugin_manager::_dl_list.end())
{
dlclose((*lit));
++lit;
}
return 1;
}
int plugin_manager::instanciate_plugins()
{
std::map<std::string,maker_ptr*,std::less<std::string> >::const_iterator mit
= plugin_manager::_factory.begin();
while(mit!=plugin_manager::_factory.end())
{
plugin *p = (*mit).second(); // call to a maker function.
// register the plugin object and its functions, if activated.
if (seeks_proxy::_config->is_plugin_activated(p->get_name_cstr()))
{
plugin_manager::register_plugin(p);
// register the plugin elements.
if (p->_interceptor_plugin)
plugin_manager::_ref_interceptor_plugins.push_back(p->_interceptor_plugin);
if (p->_action_plugin)
plugin_manager::_ref_action_plugins.push_back(p->_action_plugin);
if (p->_filter_plugin)
plugin_manager::_ref_filter_plugins.push_back(p->_filter_plugin);
// run start() on plugin.
p->start();
}
++mit;
}
return 0;
}
//TODO: deinstanciate plugin = deregister + stop().
void plugin_manager::register_plugin(plugin *p)
{
plugin_manager::_plugins.push_back(p);
errlog::log_error(LOG_LEVEL_INFO,"Registering plugin %s, and %d CGI dispatchers",
p->get_name_cstr(), p->_cgi_dispatchers.size());
std::vector<cgi_dispatcher*>::const_iterator vit = p->_cgi_dispatchers.begin();
while(vit != p->_cgi_dispatchers.end())
{
cgi_dispatcher *cgid = (*vit);
hash_map<const char*,cgi_dispatcher*,hash<const char*>,eqstr>::iterator hit;
if ((hit = plugin_manager::_cgi_dispatchers.find(cgid->_name)) != plugin_manager::_cgi_dispatchers.end())
{
errlog::log_error(LOG_LEVEL_CGI, "CGI function %s of plugin %s, has already been registered by another plugin.",
cgid->_name, p->get_name_cstr());
}
else
{
errlog::log_error(LOG_LEVEL_INFO, "registering CGI dispatcher %s", cgid->_name);
plugin_manager::_cgi_dispatchers.insert(std::pair<const char*,cgi_dispatcher*>(cgid->_name,
cgid));
}
++vit;
}
}
cgi_dispatcher* plugin_manager::find_plugin_cgi_dispatcher(const char *path)
{
hash_map<const char*,cgi_dispatcher*,hash<const char*>,eqstr>::const_iterator hit;
if((hit = plugin_manager::_cgi_dispatchers.find(path)) != plugin_manager::_cgi_dispatchers.end())
return (*hit).second;
else
{
errlog::log_error(LOG_LEVEL_ERROR, "Can't find any plugin dispatcher in %s", path);
return NULL;
}
}
void plugin_manager::get_url_plugins(client_state *csp, http_request *http)
{
std::vector<interceptor_plugin*>::const_iterator lit1
= plugin_manager::_ref_interceptor_plugins.begin();
while(lit1!=plugin_manager::_ref_interceptor_plugins.end())
{
interceptor_plugin *ip = (*lit1);
#ifdef PLUGIN_DEBUG
ip->reload();
#endif
if (ip->match_url(http))
csp->add_interceptor_plugin(ip);
++lit1;
}
std::vector<action_plugin*>::const_iterator lit2
= plugin_manager::_ref_action_plugins.begin();
while(lit2!=plugin_manager::_ref_action_plugins.end())
{
action_plugin *ip = (*lit2);
#ifdef PLUGIN_DEBUG
ip->reload();
#endif
if (ip->match_url(http))
csp->add_action_plugin(ip);
++lit2;
}
std::vector<filter_plugin*>::const_iterator lit3
= plugin_manager::_ref_filter_plugins.begin();
while(lit3!=plugin_manager::_ref_filter_plugins.end())
{
filter_plugin *ip = (*lit3);
#ifdef PLUGIN_DEBUG
ip->reload();
#endif
if (ip->match_url(http))
csp->add_filter_plugin(ip);
++lit3;
}
// debug
/* std::cout << "[Debug]:plugin_manager::get_url_plugin: interceptor plugins: "
<< csp->_interceptor_plugins.size() << std::endl; */
//debug
}
plugin* plugin_manager::get_plugin(const std::string &name)
{
std::vector<plugin*>::const_iterator vit = plugin_manager::_plugins.begin();
while(vit!=plugin_manager::_plugins.end())
{
if ((*vit)->get_name() == name)
return (*vit);
++vit;
}
return NULL;
}
} /* end of namespace. */
<|endoftext|>
|
<commit_before>#ifndef UTENSOR_FULLY_CONNECTED_OPS
#define UTENSOR_FULLY_CONNECTED_OPS
#include "uTensor/core/tensor.hpp"
#include "uTensor/core/uTensorBase.hpp"
#include "arm_math.h"
#include "arm_nnfunctions.h"
/***
* Here we have two types of kernel functions. The basic function implements the function using regular GEMV approach. The opt functions operates with weights in interleaved formats.
*
* http://www.keil.com/pack/doc/CMSIS/NN/html/group__FC.html#gae3857bb6375692e81dde8cbd70adec08
*/
/**
* @param [in] iV input vector
* @param [in] mW matrix weights
* @param [in] b bias
* @param [in] scratch scrath computation space
* @param [out] pOut output
*/
template<typename T1, typename T2, typename TOut>
void FullyConnectedLayerCmsis(S_TENSOR iV, S_TENSOR mW, S_TENSOR b,
S_TENSOR bShift, S_TENSOR oShift,
S_TENSOR pOut, S_TENSOR scratch,
T1 byteme1, T2 byteme2, TOut byteme3)
{
//Throw error if this gets called
}
template<>
void FullyConnectedLayerCmsis<q7_t, q7_t, q7_t>(S_TENSOR iV, S_TENSOR mW, S_TENSOR b,
S_TENSOR bShift, S_TENSOR oShift,
S_TENSOR pOut, S_TENSOR scratch,
q7_t byteme1, q7_t byteme2, q7_t byteme3)
{
const q7_t* iV_data = iV->read<q7_t>(0, sizeof(q7_t)); //Read one byte
const q7_t* mW_data = mW->read<q7_t>(0, sizeof(q7_t)); //Read one byte
const q7_t* bias_data = b->read<q7_t>(0, sizeof(q7_t)); //Read one byte
const uint16_t dim_vec = iV->getShape()[0];
const uint16_t num_of_rows = mW->getShape()[0];
const uint16_t bias_shift = *(bShift->read<uint16_t>(0,0));
const uint16_t out_shift = *(oShift->read<uint16_t>(0,0));
pOut->resize(b->getShape());
q7_t* pOut_data = pOut->write<q7_t>(0, sizeof(q7_t));
q15_t* scratch_data = scratch->write<q15_t>(0, sizeof(q15_t));
arm_fully_connected_q7(iV_data, mW_data, dim_vec, num_of_rows,
bias_shift, out_shift, bias_data, pOut_data, scratch_data);
//Error checking
}
template<>
void FullyConnectedLayerCmsis<q15_t, q15_t, q15_t>(S_TENSOR iV, S_TENSOR mW, S_TENSOR b,
S_TENSOR bShift, S_TENSOR oShift,
S_TENSOR pOut, S_TENSOR scratch,
q15_t byteme1, q15_t byteme2, q15_t byteme3)
{
const q15_t* iV_data = iV->read<q15_t>(0, sizeof(q15_t)); //Read one byte
const q15_t* mW_data = mW->read<q15_t>(0, sizeof(q15_t)); //Read one byte
const q15_t* bias_data = b->read<q15_t>(0, sizeof(q15_t)); //Read one byte
const uint16_t dim_vec = iV->getShape()[0];
const uint16_t num_of_rows = mW->getShape()[0];
const uint16_t bias_shift = *(bShift->read<uint16_t>(0,0));
const uint16_t out_shift = *(oShift->read<uint16_t>(0,0));
pOut->resize(b->getShape());
q15_t* pOut_data = pOut->write<q15_t>(0, sizeof(q15_t));
q15_t* scratch_data = scratch->write<q15_t>(0, sizeof(q15_t));
arm_fully_connected_q15(iV_data, mW_data, dim_vec, num_of_rows,
bias_shift, out_shift, bias_data, pOut_data, scratch_data);
//Error checking
}
template<>
void FullyConnectedLayerCmsis<q15_t, q7_t, q7_t>(S_TENSOR iV, S_TENSOR mW, S_TENSOR b,
S_TENSOR bShift, S_TENSOR oShift,
S_TENSOR pOut, S_TENSOR scratch,
q15_t byteme1, q7_t byteme2, q7_t byteme3)
{
const q15_t* iV_data = iV->read<q15_t>(0, sizeof(q15_t)); //Read one byte
const q7_t* mW_data = mW->read<q7_t>(0, sizeof(q7_t)); //Read one byte
const q7_t* bias_data = b->read<q7_t>(0, sizeof(q7_t)); //Read one byte
const uint16_t dim_vec = iV->getShape()[0];
const uint16_t num_of_rows = mW->getShape()[0];
const uint16_t bias_shift = *(bShift->read<uint16_t>(0,0));
const uint16_t out_shift = *(oShift->read<uint16_t>(0,0));
pOut->resize(b->getShape());
q15_t* pOut_data = pOut->write<q15_t>(0, sizeof(q15_t));
q15_t* scratch_data = scratch->write<q15_t>(0, sizeof(q15_t));
arm_fully_connected_mat_q7_vec_q15(iV_data, mW_data, dim_vec, num_of_rows,
bias_shift, out_shift, bias_data, pOut_data, scratch_data);
//Error checking
}
/***
* Here we have two types of kernel functions. The basic function implements the function using regular GEMV approach. The opt functions operates with weights in interleaved formats.
*
* http://www.keil.com/pack/doc/CMSIS/NN/html/group__FC.html#gae3857bb6375692e81dde8cbd70adec08
*/
/**
* @param [in] iV input vector
* @param [in] mW matrix weights
* @param [in] b bias
* @param [in] scratch scrath computation space
* @param [out] pOut output
*/
template<typename T1, typename T2, typename TOut>
void FullyConnectedLayerOptCmsis(S_TENSOR iV, S_TENSOR mW, S_TENSOR b,
S_TENSOR bShift, S_TENSOR oShift,
S_TENSOR pOut, S_TENSOR scratch,
T1 byteme1, T2 byteme2, TOut byteme3)
{
//Throw error if this gets called
}
template<>
void FullyConnectedLayerOptCmsis<q7_t, q7_t, q7_t>(S_TENSOR iV, S_TENSOR mW, S_TENSOR b,
S_TENSOR bShift, S_TENSOR oShift,
S_TENSOR pOut, S_TENSOR scratch,
q7_t byteme1, q7_t byteme2, q7_t byteme3)
{
const q7_t* iV_data = iV->read<q7_t>(0, sizeof(q7_t)); //Read one byte
const q7_t* mW_data = mW->read<q7_t>(0, sizeof(q7_t)); //Read one byte
const q7_t* bias_data = b->read<q7_t>(0, sizeof(q7_t)); //Read one byte
const uint16_t dim_vec = iV->getShape()[0];
const uint16_t num_of_rows = mW->getShape()[0];
const uint16_t bias_shift = *(bShift->read<uint16_t>(0,0));
const uint16_t out_shift = *(oShift->read<uint16_t>(0,0));
pOut->resize(b->getShape());
q7_t* pOut_data = pOut->write<q7_t>(0, sizeof(q7_t));
q15_t* scratch_data = scratch->write<q15_t>(0, sizeof(q15_t));
arm_fully_connected_q7_opt(iV_data, mW_data, dim_vec, num_of_rows,
bias_shift, out_shift, bias_data, pOut_data, scratch_data);
//Error checking
}
template<>
void FullyConnectedLayerOptCmsis<q15_t, q15_t, q15_t>(S_TENSOR iV, S_TENSOR mW, S_TENSOR b,
S_TENSOR bShift, S_TENSOR oShift,
S_TENSOR pOut, S_TENSOR scratch,
q15_t byteme1, q15_t byteme2, q15_t byteme3)
{
const q15_t* iV_data = iV->read<q15_t>(0, sizeof(q15_t)); //Read one byte
const q15_t* mW_data = mW->read<q15_t>(0, sizeof(q15_t)); //Read one byte
const q15_t* bias_data = b->read<q15_t>(0, sizeof(q15_t)); //Read one byte
const uint16_t dim_vec = iV->getShape()[0];
const uint16_t num_of_rows = mW->getShape()[0];
const uint16_t bias_shift = *(bShift->read<uint16_t>(0,0));
const uint16_t out_shift = *(oShift->read<uint16_t>(0,0));
pOut->resize(b->getShape());
q15_t* pOut_data = pOut->write<q15_t>(0, sizeof(q15_t));
q15_t* scratch_data = scratch->write<q15_t>(0, sizeof(q15_t));
arm_fully_connected_q15_opt(iV_data, mW_data, dim_vec, num_of_rows,
bias_shift, out_shift, bias_data, pOut_data, scratch_data);
//Error checking
}
template<>
void FullyConnectedLayerOptCmsis<q15_t, q7_t, q7_t>(S_TENSOR iV, S_TENSOR mW, S_TENSOR b,
S_TENSOR bShift, S_TENSOR oShift,
S_TENSOR pOut, S_TENSOR scratch,
q15_t byteme1, q7_t byteme2, q7_t byteme3)
{
const q15_t* iV_data = iV->read<q15_t>(0, sizeof(q15_t)); //Read one byte
const q7_t* mW_data = mW->read<q7_t>(0, sizeof(q7_t)); //Read one byte
const q7_t* bias_data = b->read<q7_t>(0, sizeof(q7_t)); //Read one byte
const uint16_t dim_vec = iV->getShape()[0];
const uint16_t num_of_rows = mW->getShape()[0];
const uint16_t bias_shift = *(bShift->read<uint16_t>(0,0));
const uint16_t out_shift = *(oShift->read<uint16_t>(0,0));
pOut->resize(b->getShape());
q15_t* pOut_data = pOut->write<q15_t>(0, sizeof(q15_t));
q15_t* scratch_data = scratch->write<q15_t>(0, sizeof(q15_t));
arm_fully_connected_mat_q7_vec_q15_opt(iV_data, mW_data, dim_vec, num_of_rows,
bias_shift, out_shift, bias_data, pOut_data, scratch_data);
//Error checking
}
template <class T1, class T2, class TOut>
class FullyConnectedLayerCmsisOp : public Operator {
public:
FullyConnectedLayerCmsisOp() {
n_inputs = 6;
n_outputs = 1;
}
virtual void compute() override {
T1 x;
T2 y;
TOut byteme;
FullyConnectedLayerCmsis(inputs[0], inputs[1], inputs[2], inputs[3],
inputs[4], outputs[0], inputs[5], x, y, byteme);
}
};
template <class T1, class T2, class TOut>
class FullyConnectedLayerOptCmsisOp : public Operator {
public:
FullyConnectedLayerOptCmsisOp() {
n_inputs = 6;
n_outputs = 1;
}
virtual void compute() override {
T1 x;
T2 y;
TOut byteme;
FullyConnectedLayerOptCmsis<T1, T2, TOut>(inputs[0], inputs[1], inputs[2], inputs[3],
inputs[4], outputs[0], inputs[5], x, y, byteme);
}
};
#endif /*UTENSOR_FULLY_CONNECTED_OPS*/
<commit_msg>Greatly simplify cmsis interface<commit_after>#ifndef UTENSOR_FULLY_CONNECTED_OPS
#define UTENSOR_FULLY_CONNECTED_OPS
#include "uTensor/core/tensor.hpp"
#include "uTensor/core/uTensorBase.hpp"
#include "arm_math.h"
#include "arm_nnfunctions.h"
/***
* Here we have two types of kernel functions. The basic function implements the function using regular GEMV approach. The opt functions operates with weights in interleaved formats.
*
* http://www.keil.com/pack/doc/CMSIS/NN/html/group__FC.html#gae3857bb6375692e81dde8cbd70adec08
*/
template<typename T1, typename T2, typename T3>
void cmsis_fc_selector(const T1* iV, const T2* mW, const uint16_t dim_vec, const uint16_t num_of_rows,
const uint16_t bias_shift, const uint16_t out_shift, const T3* bias,
T1* pOut, q15_t* scratch_data);
template<>
void cmsis_fc_selector<q7_t, q7_t, q7_t>(const q7_t* iV, const q7_t* mW, const uint16_t dim_vec, const uint16_t num_of_rows,
const uint16_t bias_shift, const uint16_t out_shift, const q7_t* bias,
q7_t* pOut, q15_t* scratch_data){
arm_fully_connected_q7(iV, mW, dim_vec, num_of_rows,
bias_shift, out_shift, bias, pOut, scratch_data);
}
template<>
void cmsis_fc_selector<q15_t, q15_t, q15_t>(const q15_t* iV, const q15_t* mW, const uint16_t dim_vec, const uint16_t num_of_rows,
const uint16_t bias_shift, const uint16_t out_shift, const q15_t* bias,
q15_t* pOut, q15_t* scratch_data){
arm_fully_connected_q15(iV, mW, dim_vec, num_of_rows,
bias_shift, out_shift, bias, pOut, scratch_data);
}
template<>
void cmsis_fc_selector<q15_t, q7_t, q7_t>(const q15_t* iV, const q7_t* mW, const uint16_t dim_vec, const uint16_t num_of_rows,
const uint16_t bias_shift, const uint16_t out_shift, const q7_t* bias,
q15_t* pOut, q15_t* scratch_data){
arm_fully_connected_mat_q7_vec_q15(iV, mW, dim_vec, num_of_rows,
bias_shift, out_shift, bias, pOut, scratch_data);
}
template<typename T1, typename T2, typename T3>
void cmsis_fc_selector_opt(const T1* iV, const T2* mW, const uint16_t dim_vec, const uint16_t num_of_rows,
const uint16_t bias_shift, const uint16_t out_shift, const T3* bias,
T1* pOut, q15_t* scratch_data);
template<>
void cmsis_fc_selector_opt<q7_t, q7_t, q7_t>(const q7_t* iV, const q7_t* mW, const uint16_t dim_vec, const uint16_t num_of_rows,
const uint16_t bias_shift, const uint16_t out_shift, const q7_t* bias,
q7_t* pOut, q15_t* scratch_data){
arm_fully_connected_q7_opt(iV, mW, dim_vec, num_of_rows,
bias_shift, out_shift, bias, pOut, scratch_data);
}
template<>
void cmsis_fc_selector_opt<q15_t, q15_t, q15_t>(const q15_t* iV, const q15_t* mW, const uint16_t dim_vec, const uint16_t num_of_rows,
const uint16_t bias_shift, const uint16_t out_shift, const q15_t* bias,
q15_t* pOut, q15_t* scratch_data){
arm_fully_connected_q15_opt(iV, mW, dim_vec, num_of_rows,
bias_shift, out_shift, bias, pOut, scratch_data);
}
template<>
void cmsis_fc_selector_opt<q15_t, q7_t, q7_t>(const q15_t* iV, const q7_t* mW, const uint16_t dim_vec, const uint16_t num_of_rows,
const uint16_t bias_shift, const uint16_t out_shift, const q7_t* bias,
q15_t* pOut, q15_t* scratch_data){
arm_fully_connected_mat_q7_vec_q15_opt(iV, mW, dim_vec, num_of_rows,
bias_shift, out_shift, bias, pOut, scratch_data);
}
/**
* @param [in] iV input vector
* @param [in] mW matrix weights
* @param [in] b bias
* @param [in] scratch scrath computation space
* @param [out] pOut output
*/
template<typename T1, typename T2, typename T3>
void FullyConnectedLayerCmsis(S_TENSOR iV, S_TENSOR mW, S_TENSOR b,
S_TENSOR bShift, S_TENSOR oShift,
S_TENSOR pOut, S_TENSOR scratch,
T1 byteme1, T2 byteme2, T3 byteme3)
{
const T1* iV_data = iV->read<T1>(0, sizeof(T1)); //Read one byte
const T2* mW_data = mW->read<T2>(0, sizeof(T2)); //Read one byte
const T3* bias_data = b->read<T3>(0, sizeof(T3)); //Read one byte
const uint16_t dim_vec = iV->getShape()[0];
const uint16_t num_of_rows = mW->getShape()[0];
const uint16_t bias_shift = *(bShift->read<uint16_t>(0,0));
const uint16_t out_shift = *(oShift->read<uint16_t>(0,0));
pOut->resize(b->getShape());
T1* pOut_data = pOut->write<T1>(0, sizeof(T1));
q15_t* scratch_data = scratch->write<q15_t>(0, sizeof(q15_t));
cmsis_fc_selector(iV_data, mW_data, dim_vec, num_of_rows,
bias_shift, out_shift, bias_data, pOut_data, scratch_data);
//Error checking
}
/***
* Here we have two types of kernel functions. The basic function implements the function using regular GEMV approach. The opt functions operates with weights in interleaved formats.
*
* http://www.keil.com/pack/doc/CMSIS/NN/html/group__FC.html#gae3857bb6375692e81dde8cbd70adec08
*/
/**
* @param [in] iV input vector
* @param [in] mW matrix weights
* @param [in] b bias
* @param [in] scratch scrath computation space
* @param [out] pOut output
*/
template<typename T1, typename T2, typename T3>
void FullyConnectedLayerOptCmsis(S_TENSOR iV, S_TENSOR mW, S_TENSOR b,
S_TENSOR bShift, S_TENSOR oShift,
S_TENSOR pOut, S_TENSOR scratch,
T1 byteme1, T2 byteme2, T3 byteme3)
{
const T1* iV_data = iV->read<T1>(0, sizeof(T1)); //Read one byte
const T2* mW_data = mW->read<T2>(0, sizeof(T2)); //Read one byte
const T3* bias_data = b->read<T3>(0, sizeof(T3)); //Read one byte
const uint16_t dim_vec = iV->getShape()[0];
const uint16_t num_of_rows = mW->getShape()[0];
const uint16_t bias_shift = *(bShift->read<uint16_t>(0,0));
const uint16_t out_shift = *(oShift->read<uint16_t>(0,0));
pOut->resize(b->getShape());
T1* pOut_data = pOut->write<T1>(0, sizeof(T1));
q15_t* scratch_data = scratch->write<q15_t>(0, sizeof(q15_t));
cmsis_fc_selector_opt(iV_data, mW_data, dim_vec, num_of_rows,
bias_shift, out_shift, bias_data, pOut_data, scratch_data);
//Error checking
}
template <class T1, class T2, class T3>
class FullyConnectedLayerCmsisOp : public Operator {
public:
FullyConnectedLayerCmsisOp() {
n_inputs = 6;
n_outputs = 1;
}
virtual void compute() override {
T1 x;
T2 y;
T3 byteme;
FullyConnectedLayerCmsis(inputs[0], inputs[1], inputs[2], inputs[3],
inputs[4], outputs[0], inputs[5], x, y, byteme);
}
};
template <class T1, class T2, class T3>
class FullyConnectedLayerOptCmsisOp : public Operator {
public:
FullyConnectedLayerOptCmsisOp() {
n_inputs = 6;
n_outputs = 1;
}
virtual void compute() override {
T1 x;
T2 y;
T3 byteme;
FullyConnectedLayerOptCmsis(inputs[0], inputs[1], inputs[2], inputs[3],
inputs[4], outputs[0], inputs[5], x, y, byteme);
}
};
#endif /*UTENSOR_FULLY_CONNECTED_OPS*/
<|endoftext|>
|
<commit_before>#include "merlin_image.h":
namespace merlin {
Persistent<FunctionTemplate> MerlinImage::constructor_template;
Handle<Value>
MerlinImage::New(const Arguments& args) {
HandleScope scope;
node::Buffer *buf = ObjectWrap::Unwrap<node::Buffer>(args[0]->ToObject());
MerlinImage* img = new MerlinImage(buf);
img->Wrap(args.This());
return scope.Close(args.This());
}
Handle<Value>
MerlinImage::GetBuffer(const Arguments& args) {
HandleScope scope;
MerlinImage *img = ObjectWrap::Unwrap<MerlinImage>(args.This());
Handle<Value> buf = img->buffer->handle_;
return scope.Close(buf);
}
Handle<Value>
MerlinImage::CropImage(const Arguments& args) {
HandleScope scope;
MerlinImage *img = ObjectWrap::Unwrap<MerlinImage>(args.This());
fprintf(stderr, "1\n");
fprintf(stderr, "%i", img->buffer->length());
fprintf(stderr, "1.5\n");
node::Buffer* new_buffer = node::Buffer::New(img->buffer->length());
fprintf(stderr, "2\n");
new_buffer->Utf8Write(img->buffer->data(), 0, img->buffer->length());
fprintf(stderr, "3\n");
MerlinImage *new_image = new MerlinImage(new_buffer);
fprintf(stderr, "before return\n");
return scope.Close(new_image->handle_);
}
void
MerlinImage::Initialize(Handle<Object> target) {
HandleScope scope;
Handle<FunctionTemplate> f = FunctionTemplate::New(MerlinImage::New);
constructor_template = Persistent<FunctionTemplate>::New(f);
constructor_template->InstanceTemplate()->SetInternalFieldCount(1);
constructor_template->SetClassName(String::NewSymbol("MerlinImage"));
NODE_SET_PROTOTYPE_METHOD(constructor_template, "cropImage", MerlinImage::CropImage);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "getBuffer", MerlinImage::GetBuffer);
target->Set(String::NewSymbol("MerlinImage"), constructor_template->GetFunction());
}
MerlinImage::MerlinImage(node::Buffer *buffer) :
buffer(buffer)
{
wand = NewMagickWand();
}
MerlinImage::~MerlinImage() {
delete buffer;
wand = DestroyMagickWand(wand);
}
}
<commit_msg>another shot at transferring buffers<commit_after>#include "merlin_image.h":
namespace merlin {
Persistent<FunctionTemplate> MerlinImage::constructor_template;
Handle<Value>
MerlinImage::New(const Arguments& args) {
HandleScope scope;
node::Buffer *buf = ObjectWrap::Unwrap<node::Buffer>(args[0]->ToObject());
MerlinImage* img = new MerlinImage(buf);
img->Wrap(args.This());
return scope.Close(args.This());
}
Handle<Value>
MerlinImage::GetBuffer(const Arguments& args) {
HandleScope scope;
MerlinImage *img = ObjectWrap::Unwrap<MerlinImage>(args.This());
Handle<Value> buf = img->buffer->handle_;
return scope.Close(buf);
}
Handle<Value>
MerlinImage::CropImage(const Arguments& args) {
HandleScope scope;
MerlinImage *img = ObjectWrap::Unwrap<MerlinImage>(args.This());
fprintf(stderr, "1\n");
// return scope.Close(new_image->handle_);
Handle<String> str = String::New(img->buffer->data(), img->buffer->length());
return scope.Close(str);
}
void
MerlinImage::Initialize(Handle<Object> target) {
HandleScope scope;
Handle<FunctionTemplate> f = FunctionTemplate::New(MerlinImage::New);
constructor_template = Persistent<FunctionTemplate>::New(f);
constructor_template->InstanceTemplate()->SetInternalFieldCount(1);
constructor_template->SetClassName(String::NewSymbol("MerlinImage"));
NODE_SET_PROTOTYPE_METHOD(constructor_template, "cropImage", MerlinImage::CropImage);
NODE_SET_PROTOTYPE_METHOD(constructor_template, "getBuffer", MerlinImage::GetBuffer);
target->Set(String::NewSymbol("MerlinImage"), constructor_template->GetFunction());
}
MerlinImage::MerlinImage(node::Buffer *buffer) :
buffer(buffer)
{
wand = NewMagickWand();
}
MerlinImage::~MerlinImage() {
delete buffer;
wand = DestroyMagickWand(wand);
}
}
<|endoftext|>
|
<commit_before>#include "editaddressdialog.h"
#include "ui_editaddressdialog.h"
#include "addresstablemodel.h"
#include "dialogwindowflags.h"
#include "guiconstants.h"
#include "guiutil.h"
#include <QDataWidgetMapper>
#include <QMessageBox>
EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) :
QDialog(parent, DIALOGWINDOWHINTS),
ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0)
{
ui->setupUi(this);
GUIUtil::setupAddressWidget(ui->addressEdit, this);
switch(mode)
{
case NewReceivingAddress:
setWindowTitle(tr("New receiving address"));
ui->addressEdit->setEnabled(false);
break;
case NewSendingAddress:
setWindowTitle(tr("New sending address"));
break;
case EditReceivingAddress:
setWindowTitle(tr("Edit receiving address"));
ui->addressEdit->setEnabled(false);
break;
case EditSendingAddress:
setWindowTitle(tr("Edit sending address"));
break;
}
mapper = new QDataWidgetMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
}
EditAddressDialog::~EditAddressDialog()
{
delete ui;
}
void EditAddressDialog::setModel(AddressTableModel *model)
{
this->model = model;
if(!model)
return;
mapper->setModel(model);
mapper->addMapping(ui->labelEdit, AddressTableModel::Label);
mapper->addMapping(ui->addressEdit, AddressTableModel::Address);
}
void EditAddressDialog::loadRow(int row)
{
mapper->setCurrentIndex(row);
}
bool EditAddressDialog::saveCurrentRow()
{
if(!model)
return false;
switch(mode)
{
case NewReceivingAddress:
case NewSendingAddress:
address = model->addRow(
mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive,
ui->labelEdit->text(),
ui->addressEdit->text());
break;
case EditReceivingAddress:
case EditSendingAddress:
if(mapper->submit())
{
address = ui->addressEdit->text();
}
break;
}
return !address.isEmpty();
}
void EditAddressDialog::accept()
{
if(!model)
return;
if(!saveCurrentRow())
{
switch(model->getEditStatus())
{
case AddressTableModel::OK:
// Failed with unknown reason. Just reject.
break;
case AddressTableModel::NO_CHANGES:
// No changes were made during edit operation. Just reject.
break;
case AddressTableModel::INVALID_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is not a valid NovaCoin address.").arg(ui->addressEdit->text()),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::DUPLICATE_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::WALLET_UNLOCK_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("Could not unlock wallet."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::KEY_GENERATION_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("New key generation failed."),
QMessageBox::Ok, QMessageBox::Ok);
break;
}
return;
}
QDialog::accept();
}
QString EditAddressDialog::getAddress() const
{
return address;
}
void EditAddressDialog::setAddress(const QString &address)
{
this->address = address;
ui->addressEdit->setText(address);
}
<commit_msg>лишний #include<commit_after>#include "editaddressdialog.h"
#include "ui_editaddressdialog.h"
#include "addresstablemodel.h"
#include "dialogwindowflags.h"
#include "guiutil.h"
#include <QDataWidgetMapper>
#include <QMessageBox>
EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) :
QDialog(parent, DIALOGWINDOWHINTS),
ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0)
{
ui->setupUi(this);
GUIUtil::setupAddressWidget(ui->addressEdit, this);
switch(mode)
{
case NewReceivingAddress:
setWindowTitle(tr("New receiving address"));
ui->addressEdit->setEnabled(false);
break;
case NewSendingAddress:
setWindowTitle(tr("New sending address"));
break;
case EditReceivingAddress:
setWindowTitle(tr("Edit receiving address"));
ui->addressEdit->setEnabled(false);
break;
case EditSendingAddress:
setWindowTitle(tr("Edit sending address"));
break;
}
mapper = new QDataWidgetMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
}
EditAddressDialog::~EditAddressDialog()
{
delete ui;
}
void EditAddressDialog::setModel(AddressTableModel *model)
{
this->model = model;
if(!model)
return;
mapper->setModel(model);
mapper->addMapping(ui->labelEdit, AddressTableModel::Label);
mapper->addMapping(ui->addressEdit, AddressTableModel::Address);
}
void EditAddressDialog::loadRow(int row)
{
mapper->setCurrentIndex(row);
}
bool EditAddressDialog::saveCurrentRow()
{
if(!model)
return false;
switch(mode)
{
case NewReceivingAddress:
case NewSendingAddress:
address = model->addRow(
mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive,
ui->labelEdit->text(),
ui->addressEdit->text());
break;
case EditReceivingAddress:
case EditSendingAddress:
if(mapper->submit())
{
address = ui->addressEdit->text();
}
break;
}
return !address.isEmpty();
}
void EditAddressDialog::accept()
{
if(!model)
return;
if(!saveCurrentRow())
{
switch(model->getEditStatus())
{
case AddressTableModel::OK:
// Failed with unknown reason. Just reject.
break;
case AddressTableModel::NO_CHANGES:
// No changes were made during edit operation. Just reject.
break;
case AddressTableModel::INVALID_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is not a valid NovaCoin address.").arg(ui->addressEdit->text()),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::DUPLICATE_ADDRESS:
QMessageBox::warning(this, windowTitle(),
tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::WALLET_UNLOCK_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("Could not unlock wallet."),
QMessageBox::Ok, QMessageBox::Ok);
break;
case AddressTableModel::KEY_GENERATION_FAILURE:
QMessageBox::critical(this, windowTitle(),
tr("New key generation failed."),
QMessageBox::Ok, QMessageBox::Ok);
break;
}
return;
}
QDialog::accept();
}
QString EditAddressDialog::getAddress() const
{
return address;
}
void EditAddressDialog::setAddress(const QString &address)
{
this->address = address;
ui->addressEdit->setText(address);
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* REALM CONFIDENTIAL
* __________________
*
* [2011] - [2012] Realm Inc
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Realm Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Realm Incorporated
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Realm Incorporated.
*
**************************************************************************/
#ifndef REALM_UTIL_TERMINATE_HPP
#define REALM_UTIL_TERMINATE_HPP
#include <sstream>
#include <cstdlib>
#include <string>
#include <realm/util/features.h>
#define REALM_TERMINATE(msg) realm::util::terminate((msg), __FILE__, __LINE__)
namespace realm {
namespace util {
REALM_NORETURN void terminate_internal(std::stringstream&) noexcept;
REALM_NORETURN inline void terminate(const char* message, const char* file, long line) noexcept {
std::stringstream ss;
ss << file << ":" << line << ": " << message << "\n";
terminate_internal(ss);
}
template <typename T1, typename T2>
REALM_NORETURN void terminate(const char* message, const char* file, long line, T1 info1, T2 info2) noexcept {
std::stringstream ss;
ss << file << ":" << line << ": " << message << " [" << info1 << ", " << info2 << "]\n";
terminate_internal(ss);
}
template <typename T1, typename T2, typename T3, typename T4>
REALM_NORETURN void terminate(const char* message, const char* file, long line, T1 info1, T2 info2, T3 info3, T4 info4) noexcept {
std::stringstream ss;
ss << file << ":" << line << ": " << message << " [" << info1 << ", " << info2 << ", " << info3 << ", " << info4 << "]\n";
terminate_internal(ss);
}
template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
REALM_NORETURN void terminate(const char* message, const char* file, long line, T1 info1, T2 info2, T3 info3, T4 info4, T5 info5, T6 info6) noexcept {
std::stringstream ss;
ss << file << ":" << line << ": " << message << " [" << info1 << ", " << info2 << ", " << info3 << ", " << info4 << ", " << info5 << ", " << info6 << "]\n";
terminate_internal(ss);
}
} // namespace util
} // namespace realm
#endif // REALM_UTIL_TERMINATE_HPP
<commit_msg>Reorganised headers in terminate.hpp<commit_after>/*************************************************************************
*
* REALM CONFIDENTIAL
* __________________
*
* [2011] - [2012] Realm Inc
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Realm Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Realm Incorporated
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Realm Incorporated.
*
**************************************************************************/
#ifndef REALM_UTIL_TERMINATE_HPP
#define REALM_UTIL_TERMINATE_HPP
#include <cstdlib>
#include <sstream>
#include <string>
#include <realm/util/features.h>
#define REALM_TERMINATE(msg) realm::util::terminate((msg), __FILE__, __LINE__)
namespace realm {
namespace util {
REALM_NORETURN void terminate_internal(std::stringstream&) noexcept;
REALM_NORETURN inline void terminate(const char* message, const char* file, long line) noexcept {
std::stringstream ss;
ss << file << ":" << line << ": " << message << "\n";
terminate_internal(ss);
}
template <typename T1, typename T2>
REALM_NORETURN void terminate(const char* message, const char* file, long line, T1 info1, T2 info2) noexcept {
std::stringstream ss;
ss << file << ":" << line << ": " << message << " [" << info1 << ", " << info2 << "]\n";
terminate_internal(ss);
}
template <typename T1, typename T2, typename T3, typename T4>
REALM_NORETURN void terminate(const char* message, const char* file, long line, T1 info1, T2 info2, T3 info3, T4 info4) noexcept {
std::stringstream ss;
ss << file << ":" << line << ": " << message << " [" << info1 << ", " << info2 << ", " << info3 << ", " << info4 << "]\n";
terminate_internal(ss);
}
template <typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
REALM_NORETURN void terminate(const char* message, const char* file, long line, T1 info1, T2 info2, T3 info3, T4 info4, T5 info5, T6 info6) noexcept {
std::stringstream ss;
ss << file << ":" << line << ": " << message << " [" << info1 << ", " << info2 << ", " << info3 << ", " << info4 << ", " << info5 << ", " << info6 << "]\n";
terminate_internal(ss);
}
} // namespace util
} // namespace realm
#endif // REALM_UTIL_TERMINATE_HPP
<|endoftext|>
|
<commit_before>#include "AssetConverter.hpp"
#include <Utility/Log.hpp>
#include <Engine/Hymn.hpp>
#include <Engine/Util/FileSystem.hpp>
AssetConverter::AssetConverter() {
}
AssetConverter::~AssetConverter() {
}
void AssetConverter::Convert(const char* filepath, const char* destination, glm::vec3 scale, bool triangulate, bool importNormals, bool importTangents, bool flipUVs, bool importMaterial, Materials& materials) {
success = true;
errorString.clear();
Geometry::AssetFileHandler file;
// Return if file is not open.
file.Open(destination, Geometry::AssetFileHandler::WRITE);
unsigned int flags = triangulate ? aiProcess_Triangulate : 0;
flags = importNormals ? flags : flags | aiProcess_CalcTangentSpace;
flags = importTangents ? flags : flags | aiProcess_GenSmoothNormals;
const aiScene* aScene = aImporter.ReadFile(filepath, flags);
if (aScene == nullptr) {
Log() << "Error importing mesh: " << filepath << "\n";
Log() << aImporter.GetErrorString() << "\n";
aImporter.FreeScene();
aScene = aImporter.ReadFile("ErrorSign.fbx", flags);
}
if (importMaterial) {
if (aScene->mMeshes[0]->mMaterialIndex >= 0) {
aiMaterial* material = aScene->mMaterials[aScene->mMeshes[0]->mMaterialIndex];
LoadMaterial(material, aiTextureType_DIFFUSE, materials.albedo);
LoadMaterial(material, aiTextureType_NORMALS, materials.normal);
LoadMaterial(material, aiTextureType_SPECULAR, materials.roughness);
LoadMaterial(material, aiTextureType_REFLECTION, materials.metallic);
}
}
ConvertMeshes(aScene, &file, scale, flipUVs);
aImporter.FreeScene();
file.Close();
}
bool AssetConverter::Success() const {
return success;
}
std::string& AssetConverter::GetErrorString() {
return errorString;
}
void AssetConverter::ConvertMeshes(const aiScene * aScene, Geometry::AssetFileHandler * file, glm::vec3 scale, bool flipUVs) {
for (unsigned int i = 0; i < aScene->mNumMeshes; ++i)
ConvertMesh(aScene->mMeshes[i], file, scale, flipUVs);
}
void AssetConverter::ConvertMesh(aiMesh * aMesh, Geometry::AssetFileHandler * file, glm::vec3 scale, bool flipUVs) {
Geometry::AssetFileHandler::MeshData * meshData = new Geometry::AssetFileHandler::MeshData;
meshData->parent = 0;
// Convert vertices.
unsigned int numVertices = aMesh->mNumVertices;
meshData->numVertices = numVertices;
// If mesh has no bones the mesh is static.
if (aMesh->mNumBones == 0) {
meshData->staticVertices = ConvertStaticVertices(aMesh, file, numVertices, scale, flipUVs);
meshData->isSkinned = false;
}
else {
meshData->skinnedVertices = ConvertSkinnedVertices(aMesh, file, numVertices, scale, flipUVs);
meshData->isSkinned = true;
}
// Convert indicies. 3 indicies for a face/triangle.
unsigned int numIndicies = aMesh->mNumFaces * 3;
uint32_t * indices = new uint32_t[numIndicies];
unsigned int indexCounter = 0;
for (unsigned int i = 0; i < aMesh->mNumFaces; ++i) {
const aiFace& aFace = aMesh->mFaces[i];
if (aFace.mNumIndices != 3) {
errorString.append("ERROR: Mesh not triangulated.\n");
success = false;
delete[] indices;
delete meshData;
return;
}
indices[indexCounter++] = aFace.mIndices[0];
indices[indexCounter++] = aFace.mIndices[1];
indices[indexCounter++] = aFace.mIndices[2];
}
meshData->numIndices = indexCounter;
meshData->indices = indices;
CalculateAABB(meshData, meshData->numVertices);
file->SaveStaticMesh(meshData);
delete meshData;
meshData = nullptr;
}
Video::Geometry::VertexType::StaticVertex * AssetConverter::ConvertStaticVertices(aiMesh* aMesh, Geometry::AssetFileHandler* file, unsigned int numVertices, glm::vec3 scale, bool flipUVs) {
Video::Geometry::VertexType::StaticVertex * vertices = new Video::Geometry::VertexType::StaticVertex[numVertices];
// Positions.
if (aMesh->HasNormals()) {
for (unsigned int i = 0; i < numVertices; ++i) {
Geometry::CpyVec(vertices[i].position, aMesh->mVertices[i]);
vertices[i].position *= scale;
}
} else {
success = false;
errorString.append("WARNING: The model has no positions yet the user is trying to import them.\n");
for (unsigned int i = 0; i < numVertices; ++i)
vertices[i].position = glm::vec3(1.0f, 0.0f, 0.0f);
}
// Texture coordinates.
if (aMesh->HasTextureCoords(0)) {
for (unsigned int i = 0; i < numVertices; ++i) {
Geometry::CpyVec(vertices[i].textureCoordinate, aMesh->mTextureCoords[0][i]);
if (flipUVs)
vertices[i].textureCoordinate.y = 1.0f - vertices[i].textureCoordinate.y;
}
} else {
success = false;
errorString.append("WARNING: The model has no texture coordinates yet the user is trying to import them.\n");
for (unsigned int i = 0; i < numVertices; ++i)
vertices[i].textureCoordinate = glm::vec2(0.0f, 0.0f);
}
// Normals.
if (aMesh->HasNormals()) {
for (unsigned int i = 0; i < numVertices; ++i) {
Geometry::CpyVec(vertices[i].normal, aMesh->mNormals[i]);
}
} else {
success = false;
errorString.append("WARNING: The model has no normals yet the user is trying to import them.\n");
for (unsigned int i = 0; i < numVertices; ++i)
vertices[i].normal = glm::vec3(1.0f, 0.0f, 0.0f);
}
// Tangents.
if (aMesh->HasTangentsAndBitangents()) {
for (unsigned int i = 0; i < numVertices; ++i)
Geometry::CpyVec(vertices[i].tangent, aMesh->mTangents[i]);
} else {
success = false;
errorString.append("WARNING: The model has no tangents yet the user is trying to import them.\n");
for (unsigned int i = 0; i < numVertices; ++i)
vertices[i].tangent = glm::vec3(1.0f, 0.0f, 0.0f);
}
return vertices;
}
Video::Geometry::VertexType::SkinVertex * AssetConverter::ConvertSkinnedVertices(aiMesh * aMesh, Geometry::AssetFileHandler * file, unsigned int numVertices, glm::vec3 scale, bool flipUVs) {
Video::Geometry::VertexType::SkinVertex * vertices = new Video::Geometry::VertexType::SkinVertex[numVertices];
// Positions.
if (aMesh->HasNormals()) {
for (unsigned int i = 0; i < numVertices; ++i) {
Geometry::CpyVec(vertices[i].position, aMesh->mVertices[i]);
vertices[i].position *= scale;
}
} else {
success = false;
errorString.append("WARNING: The model has no positions yet the user is trying to import them.\n");
for (unsigned int i = 0; i < numVertices; ++i)
vertices[i].position = glm::vec3(1.0f, 0.0f, 0.0f);
}
// Texture coordinates.
if (aMesh->HasTextureCoords(0)) {
for (unsigned int i = 0; i < numVertices; ++i) {
Geometry::CpyVec(vertices[i].textureCoordinate, aMesh->mTextureCoords[0][i]);
if (flipUVs)
vertices[i].textureCoordinate.y = 1.0f - vertices[i].textureCoordinate.y;
}
} else {
success = false;
errorString.append("WARNING: The model has no texture coordinates yet the user is trying to import them.\n");
for (unsigned int i = 0; i < numVertices; ++i)
vertices[i].textureCoordinate = glm::vec2(0.0f, 0.0f);
}
// Normals.
if (aMesh->HasNormals()) {
for (unsigned int i = 0; i < numVertices; ++i)
Geometry::CpyVec(vertices[i].normal, aMesh->mNormals[i]);
} else {
success = false;
errorString.append("WARNING: The model has no normals yet the user is trying to import them.\n");
for (unsigned int i = 0; i < numVertices; ++i)
vertices[i].normal = glm::vec3(1.0f, 0.0f, 0.0f);
}
// Tangents.
if (aMesh->HasTangentsAndBitangents()) {
for (unsigned int i = 0; i < numVertices; ++i)
Geometry::CpyVec(vertices[i].tangent, aMesh->mTangents[i]);
} else {
success = false;
errorString.append("WARNING: The model has no tangents yet the user is trying to import them.\n");
for (unsigned int i = 0; i < numVertices; ++i)
vertices[i].tangent = glm::vec3(1.0f, 0.0f, 0.0f);
}
std::vector<unsigned int> weightCounter(numVertices, 0);
for (unsigned int b = 0; b < aMesh->mNumBones; ++b) {
const aiBone * aBone = aMesh->mBones[b];
for (unsigned int i = 0; i < aBone->mNumWeights; ++i) {
unsigned int vertexID = aBone->mWeights[i].mVertexId;
unsigned int& count = weightCounter[vertexID];
vertices[vertexID].weights[count] = aBone->mWeights[i].mWeight;
vertices[vertexID].boneIDs[count] = i;
++count;
}
}
weightCounter.clear();
return vertices;
}
void AssetConverter::CalculateAABB(Geometry::AssetFileHandler::MeshData * meshData, unsigned int numVertices) {
glm::vec3 minValues, maxValues, origin, dim;
minValues = maxValues = origin = glm::vec3(0.f, 0.f, 0.f);
// Find minimum/maximum bounding points.
for (std::size_t i = 0; i < numVertices; ++i) {
const glm::vec3& pos = meshData->isSkinned ? meshData->skinnedVertices[i].position : meshData->staticVertices[i].position;
if (pos.x > maxValues.x)
maxValues.x = pos.x;
else if (pos.x < minValues.x)
minValues.x = pos.x;
if (pos.y > maxValues.y)
maxValues.y = pos.y;
else if (pos.y < minValues.y)
minValues.y = pos.y;
if (pos.z > maxValues.z)
maxValues.z = pos.z;
else if (pos.z < minValues.z)
minValues.z = pos.z;
}
// Set origin.
origin.x = (minValues.x + maxValues.x) / 2.f;
origin.y = (minValues.y + maxValues.y) / 2.f;
origin.z = (minValues.z + maxValues.z) / 2.f;
// Dimensions.
dim.x = maxValues.x - minValues.x;
dim.y = maxValues.y - minValues.y;
dim.z = maxValues.z - minValues.z;
meshData->aabbDim = dim;
meshData->aabbOrigin = origin;
meshData->aabbMaxpos = maxValues;
meshData->aabbMinpos = minValues;
}
void AssetConverter::LoadMaterial(aiMaterial* material, aiTextureType type, std::string& path) {
if (material->GetTextureCount(type) > 0) {
aiString p;
material->GetTexture(type, 0, &p);
path = p.C_Str();
}
}
<commit_msg>Update AssetConverter.cpp<commit_after>#include "AssetConverter.hpp"
#include <Utility/Log.hpp>
#include <Engine/Hymn.hpp>
#include <Engine/Util/FileSystem.hpp>
AssetConverter::AssetConverter() {
}
AssetConverter::~AssetConverter() {
}
void AssetConverter::Convert(const char* filepath, const char* destination, glm::vec3 scale, bool triangulate, bool importNormals, bool importTangents, bool flipUVs, bool importMaterial, Materials& materials) {
success = true;
errorString.clear();
Geometry::AssetFileHandler file;
// Return if file is not open.
file.Open(destination, Geometry::AssetFileHandler::WRITE);
unsigned int flags = triangulate ? aiProcess_Triangulate : 0;
flags = importNormals ? flags : flags | aiProcess_CalcTangentSpace;
flags = importTangents ? flags : flags | aiProcess_GenSmoothNormals;
const aiScene* aScene = aImporter.ReadFile(filepath, flags);
if (aScene == nullptr) {
Log() << "Error importing mesh: " << filepath << "\n";
Log() << aImporter.GetErrorString() << "\n";
aImporter.FreeScene();
aScene = aImporter.ReadFile("ErrorSign.fbx", flags);
}
if (importMaterial) {
if (aScene->mMeshes[0]->mMaterialIndex >= 0) {
aiMaterial* material = aScene->mMaterials[aScene->mMeshes[0]->mMaterialIndex];
LoadMaterial(material, aiTextureType_DIFFUSE, materials.albedo);
LoadMaterial(material, aiTextureType_NORMALS, materials.normal);
LoadMaterial(material, aiTextureType_SPECULAR, materials.roughness);
LoadMaterial(material, aiTextureType_REFLECTION, materials.metallic);
}
}
ConvertMeshes(aScene, &file, scale, flipUVs);
aImporter.FreeScene();
file.Close();
}
bool AssetConverter::Success() const {
return success;
}
std::string& AssetConverter::GetErrorString() {
return errorString;
}
void AssetConverter::ConvertMeshes(const aiScene * aScene, Geometry::AssetFileHandler * file, glm::vec3 scale, bool flipUVs) {
for (unsigned int i = 0; i < aScene->mNumMeshes; ++i)
ConvertMesh(aScene->mMeshes[i], file, scale, flipUVs);
}
void AssetConverter::ConvertMesh(aiMesh * aMesh, Geometry::AssetFileHandler * file, glm::vec3 scale, bool flipUVs) {
Geometry::AssetFileHandler::MeshData * meshData = new Geometry::AssetFileHandler::MeshData;
meshData->parent = 0;
// Convert vertices.
unsigned int numVertices = aMesh->mNumVertices;
meshData->numVertices = numVertices;
// If mesh has no bones the mesh is static.
if (aMesh->mNumBones == 0) {
meshData->staticVertices = ConvertStaticVertices(aMesh, file, numVertices, scale, flipUVs);
meshData->isSkinned = false;
}
else {
meshData->skinnedVertices = ConvertSkinnedVertices(aMesh, file, numVertices, scale, flipUVs);
meshData->isSkinned = true;
}
// Convert indicies. 3 indicies for a face/triangle.
unsigned int numIndicies = aMesh->mNumFaces * 3;
uint32_t * indices = new uint32_t[numIndicies];
unsigned int indexCounter = 0;
for (unsigned int i = 0; i < aMesh->mNumFaces; ++i) {
const aiFace& aFace = aMesh->mFaces[i];
if (aFace.mNumIndices != 3) {
errorString.append("ERROR: Mesh not triangulated.\n");
success = false;
delete[] indices;
delete meshData;
return;
}
indices[indexCounter++] = aFace.mIndices[0];
indices[indexCounter++] = aFace.mIndices[1];
indices[indexCounter++] = aFace.mIndices[2];
}
meshData->numIndices = indexCounter;
meshData->indices = indices;
CalculateAABB(meshData, meshData->numVertices);
file->SaveStaticMesh(meshData);
delete meshData;
meshData = nullptr;
}
Video::Geometry::VertexType::StaticVertex * AssetConverter::ConvertStaticVertices(aiMesh* aMesh, Geometry::AssetFileHandler* file, unsigned int numVertices, glm::vec3 scale, bool flipUVs) {
Video::Geometry::VertexType::StaticVertex * vertices = new Video::Geometry::VertexType::StaticVertex[numVertices];
// Positions.
if (aMesh->HasNormals()) {
for (unsigned int i = 0; i < numVertices; ++i) {
Geometry::CpyVec(vertices[i].position, aMesh->mVertices[i]);
vertices[i].position *= scale;
}
} else {
success = false;
errorString.append("WARNING: The model has no positions yet the user is trying to import them.\n");
for (unsigned int i = 0; i < numVertices; ++i)
vertices[i].position = glm::vec3(1.0f, 0.0f, 0.0f);
}
// Texture coordinates.
if (aMesh->HasTextureCoords(0)) {
for (unsigned int i = 0; i < numVertices; ++i) {
Geometry::CpyVec(vertices[i].textureCoordinate, aMesh->mTextureCoords[0][i]);
if (flipUVs)
vertices[i].textureCoordinate.y = 1.0f - vertices[i].textureCoordinate.y;
}
} else {
success = false;
errorString.append("WARNING: The model has no texture coordinates yet the user is trying to import them.\n");
for (unsigned int i = 0; i < numVertices; ++i)
vertices[i].textureCoordinate = glm::vec2(0.0f, 0.0f);
}
// Normals.
if (aMesh->HasNormals()) {
for (unsigned int i = 0; i < numVertices; ++i) {
Geometry::CpyVec(vertices[i].normal, aMesh->mNormals[i]);
}
} else {
success = false;
errorString.append("WARNING: The model has no normals yet the user is trying to import them.\n");
for (unsigned int i = 0; i < numVertices; ++i)
vertices[i].normal = glm::vec3(1.0f, 0.0f, 0.0f);
}
// Tangents.
if (aMesh->HasTangentsAndBitangents()) {
for (unsigned int i = 0; i < numVertices; ++i)
Geometry::CpyVec(vertices[i].tangent, aMesh->mTangents[i]);
} else {
success = false;
errorString.append("WARNING: The model has no tangents yet the user is trying to import them.\n");
for (unsigned int i = 0; i < numVertices; ++i)
vertices[i].tangent = glm::vec3(1.0f, 0.0f, 0.0f);
}
return vertices;
}
Video::Geometry::VertexType::SkinVertex * AssetConverter::ConvertSkinnedVertices(aiMesh * aMesh, Geometry::AssetFileHandler * file, unsigned int numVertices, glm::vec3 scale, bool flipUVs) {
Video::Geometry::VertexType::SkinVertex * vertices = new Video::Geometry::VertexType::SkinVertex[numVertices];
// Positions.
if (aMesh->HasNormals()) {
for (unsigned int i = 0; i < numVertices; ++i) {
Geometry::CpyVec(vertices[i].position, aMesh->mVertices[i]);
vertices[i].position *= scale;
}
} else {
success = false;
errorString.append("WARNING: The model has no positions yet the user is trying to import them.\n");
for (unsigned int i = 0; i < numVertices; ++i)
vertices[i].position = glm::vec3(1.0f, 0.0f, 0.0f);
}
// Texture coordinates.
if (aMesh->HasTextureCoords(0)) {
for (unsigned int i = 0; i < numVertices; ++i) {
Geometry::CpyVec(vertices[i].textureCoordinate, aMesh->mTextureCoords[0][i]);
if (flipUVs)
vertices[i].textureCoordinate.y = 1.0f - vertices[i].textureCoordinate.y;
}
} else {
success = false;
errorString.append("WARNING: The model has no texture coordinates yet the user is trying to import them.\n");
for (unsigned int i = 0; i < numVertices; ++i)
vertices[i].textureCoordinate = glm::vec2(0.0f, 0.0f);
}
// Normals.
if (aMesh->HasNormals()) {
for (unsigned int i = 0; i < numVertices; ++i)
Geometry::CpyVec(vertices[i].normal, aMesh->mNormals[i]);
} else {
success = false;
errorString.append("WARNING: The model has no normals yet the user is trying to import them.\n");
for (unsigned int i = 0; i < numVertices; ++i)
vertices[i].normal = glm::vec3(1.0f, 0.0f, 0.0f);
}
// Tangents.
if (aMesh->HasTangentsAndBitangents()) {
for (unsigned int i = 0; i < numVertices; ++i)
Geometry::CpyVec(vertices[i].tangent, aMesh->mTangents[i]);
} else {
success = false;
errorString.append("WARNING: The model has no tangents yet the user is trying to import them.\n");
for (unsigned int i = 0; i < numVertices; ++i)
vertices[i].tangent = glm::vec3(1.0f, 0.0f, 0.0f);
}
std::vector<unsigned int> weightCounter(numVertices, 0);
for (unsigned int b = 0; b < aMesh->mNumBones; ++b) {
const aiBone * aBone = aMesh->mBones[b];
for (unsigned int i = 0; i < aBone->mNumWeights; ++i) {
unsigned int vertexID = aBone->mWeights[i].mVertexId;
unsigned int& count = weightCounter[vertexID];
vertices[vertexID].weights[count] = aBone->mWeights[i].mWeight;
vertices[vertexID].boneIDs[count] = i;
++count;
}
}
weightCounter.clear();
return vertices;
}
void AssetConverter::CalculateAABB(Geometry::AssetFileHandler::MeshData * meshData, unsigned int numVertices) {
glm::vec3 minValues, maxValues, origin, dim;
minValues = maxValues = origin = glm::vec3(0.f, 0.f, 0.f);
// Find minimum/maximum bounding points.
for (std::size_t i = 0; i < numVertices; ++i) {
const glm::vec3& pos = meshData->isSkinned ? meshData->skinnedVertices[i].position : meshData->staticVertices[i].position;
if (pos.x > maxValues.x)
maxValues.x = pos.x;
else if (pos.x < minValues.x)
minValues.x = pos.x;
if (pos.y > maxValues.y)
maxValues.y = pos.y;
else if (pos.y < minValues.y)
minValues.y = pos.y;
if (pos.z > maxValues.z)
maxValues.z = pos.z;
else if (pos.z < minValues.z)
minValues.z = pos.z;
}
// Set origin.
origin.x = (minValues.x + maxValues.x) / 2.f;
origin.y = (minValues.y + maxValues.y) / 2.f;
origin.z = (minValues.z + maxValues.z) / 2.f;
// Dimensions.
dim.x = maxValues.x - minValues.x;
dim.y = maxValues.y - minValues.y;
dim.z = maxValues.z - minValues.z;
meshData->aabbDim = dim;
meshData->aabbOrigin = origin;
meshData->aabbMaxpos = maxValues;
meshData->aabbMinpos = minValues;
}
void AssetConverter::LoadMaterial(aiMaterial* material, aiTextureType type, std::string& path) {
if (material->GetTextureCount(type) > 0) {
aiString p;
material->GetTexture(type, 0, &p);
path = p.C_Str();
}
}
<|endoftext|>
|
<commit_before>/** \file circularize_main.cpp
*
* Defines the "vg circularize" subcommand
*/
#include <omp.h>
#include <unistd.h>
#include <getopt.h>
#include <iostream>
#include "subcommand.hpp"
#include "../utility.hpp"
#include "../handle.hpp"
#include "../vg.hpp"
#include <vg/io/stream.hpp>
#include <vg/io/vpkg.hpp>
using namespace std;
using namespace vg;
using namespace vg::subcommand;
void help_circularize(char** argv){
cerr << "usage: " << argv[0] << " circularize [options] <graph.vg> > [circularized.vg]" << endl
<< "Makes specific paths or nodes in a graph circular." << endl
<< endl
<< "options:" << endl
<< " -p --path <PATHNAME> circularize the path by connecting its head/tail node." << endl
<< " -P, --pathfile <PATHSFILE> circularize all paths in the provided file." << endl
<< " -a, --head <node_id> circularize a head and tail node (must provide a tail)." << endl
<< " -z, --tail <tail_id> circularize a head and tail node (must provide a head)." << endl
<< " -d --describe list all the paths in the graph." << endl
<< endl;
exit(1);
}
int main_circularize(int argc, char** argv){
if (argc == 2){
help_circularize(argv);
exit(1);
}
string path = "";
string pathfile = "";
bool describe = false;
vg::id_t head = -1;
vg::id_t tail = -1;
int c;
optind = 2;
while (true){
static struct option long_options[] =
{
{"path", required_argument, 0, 'p'},
{"pathfile", required_argument, 0, 'P'},
{"head", required_argument, 0, 'a'},
{"tail", required_argument, 0, 'z'},
{"describe", required_argument, 0, 'd'},
{0,0,0,0}
};
int option_index = 0;
c = getopt_long (argc, argv, "hdp:P:a:z:",
long_options, &option_index);
if (c == -1){
break;
}
switch(c){
case 'a':
head = parse<int>(optarg);
break;
case 'z':
tail = parse<int>(optarg);
break;
case 'p':
path = optarg;
break;
case 'P':
pathfile = optarg;
break;
case 'd':
describe = true;
break;
case 'h':
case '?':
help_circularize(argv);
exit(1);
break;
default:
abort();
}
}
vector<string> paths_to_circularize;
if (!((head * tail) > 0)){
cerr << "Both a head and tail node must be provided" << endl;
help_circularize(argv);
exit(1);
}
if (pathfile != ""){
string line;
ifstream pfi;
pfi.open(pathfile);
if (!pfi.good()){
cerr << "There is an error with the input file." << endl;
help_circularize(argv);
}
while (getline(pfi, line)){
paths_to_circularize.push_back(line);
}
pfi.close();
}
else if (path != ""){
paths_to_circularize.push_back(path);
}
// TODO: if we settle on a uniform serialzation method that covers the VG class, the code is ready to be switched
VG* graph;
get_input_file(optind, argc, argv, [&](istream& in) {
graph = new VG(in);
});
// Check if paths are in graph:
for (const string& p : paths_to_circularize){
if (!graph->has_path(p)){
cerr << "ERROR: PATH NOT IN GRAPH - " << p << endl;
exit(1);
}
}
if (describe){
graph->for_each_path_handle([&](const path_handle_t& path_handle) {
cout << graph->get_path_name(path_handle) << endl;
});
exit(0);
}
if (head > 0 && tail > head){
graph->create_edge(graph->get_handle(tail), graph->get_handle(head));
}
else{
for (const auto& path_name : paths_to_circularize) {
graph->set_circularity(graph->get_path_handle(path_name), true);
}
}
graph->serialize_to_ostream(cout);
// SerializableHandleGraph* to_serialize = dynamic_cast<SerializableHandleGraph*>(&(*graph));
// if (!to_serialize) {
// cerr << "error: graph format is not serializable!" << endl;
// return 1;
// }
// to_serialize->serialize(std::cout);
return 0;
}
// Register subcommand
static Subcommand vg_circularize("circularize", "circularize a path within a graph", main_circularize);
<commit_msg>restore previous circularize behavior<commit_after>/** \file circularize_main.cpp
*
* Defines the "vg circularize" subcommand
*/
#include <omp.h>
#include <unistd.h>
#include <getopt.h>
#include <iostream>
#include "subcommand.hpp"
#include "../utility.hpp"
#include "../handle.hpp"
#include "../vg.hpp"
#include <vg/io/stream.hpp>
#include <vg/io/vpkg.hpp>
using namespace std;
using namespace vg;
using namespace vg::subcommand;
void help_circularize(char** argv){
cerr << "usage: " << argv[0] << " circularize [options] <graph.vg> > [circularized.vg]" << endl
<< "Makes specific paths or nodes in a graph circular." << endl
<< endl
<< "options:" << endl
<< " -p --path <PATHNAME> circularize the path by connecting its head/tail node." << endl
<< " -P, --pathfile <PATHSFILE> circularize all paths in the provided file." << endl
<< " -a, --head <node_id> circularize a head and tail node (must provide a tail)." << endl
<< " -z, --tail <tail_id> circularize a head and tail node (must provide a head)." << endl
<< " -d --describe list all the paths in the graph." << endl
<< endl;
exit(1);
}
int main_circularize(int argc, char** argv){
if (argc == 2){
help_circularize(argv);
exit(1);
}
string path = "";
string pathfile = "";
bool describe = false;
vg::id_t head = -1;
vg::id_t tail = -1;
int c;
optind = 2;
while (true){
static struct option long_options[] =
{
{"path", required_argument, 0, 'p'},
{"pathfile", required_argument, 0, 'P'},
{"head", required_argument, 0, 'a'},
{"tail", required_argument, 0, 'z'},
{"describe", required_argument, 0, 'd'},
{0,0,0,0}
};
int option_index = 0;
c = getopt_long (argc, argv, "hdp:P:a:z:",
long_options, &option_index);
if (c == -1){
break;
}
switch(c){
case 'a':
head = parse<int>(optarg);
break;
case 'z':
tail = parse<int>(optarg);
break;
case 'p':
path = optarg;
break;
case 'P':
pathfile = optarg;
break;
case 'd':
describe = true;
break;
case 'h':
case '?':
help_circularize(argv);
exit(1);
break;
default:
abort();
}
}
vector<string> paths_to_circularize;
if (!((head * tail) > 0)){
cerr << "Both a head and tail node must be provided" << endl;
help_circularize(argv);
exit(1);
}
if (pathfile != ""){
string line;
ifstream pfi;
pfi.open(pathfile);
if (!pfi.good()){
cerr << "There is an error with the input file." << endl;
help_circularize(argv);
}
while (getline(pfi, line)){
paths_to_circularize.push_back(line);
}
pfi.close();
}
else if (path != ""){
paths_to_circularize.push_back(path);
}
// TODO: if we settle on a uniform serialzation method that covers the VG class, the code is ready to be switched
VG* graph;
get_input_file(optind, argc, argv, [&](istream& in) {
graph = new VG(in);
});
// Check if paths are in graph:
for (const string& p : paths_to_circularize){
if (!graph->has_path(p)){
cerr << "ERROR: PATH NOT IN GRAPH - " << p << endl;
exit(1);
}
}
if (describe){
graph->for_each_path_handle([&](const path_handle_t& path_handle) {
cout << graph->get_path_name(path_handle) << endl;
});
exit(0);
}
if (head > 0 && tail > head){
graph->create_edge(graph->get_handle(tail), graph->get_handle(head));
}
else{
for (const auto& path_name : paths_to_circularize) {
path_handle_t path = graph->get_path_handle(path_name);
if (graph->get_step_count(path) > 0) {
graph->create_edge(graph->get_handle_of_step(graph->path_back(path)),
graph->get_handle_of_step(graph->path_begin(path)));
}
graph->set_circularity(path, true);
}
}
graph->serialize_to_ostream(cout);
// SerializableHandleGraph* to_serialize = dynamic_cast<SerializableHandleGraph*>(&(*graph));
// if (!to_serialize) {
// cerr << "error: graph format is not serializable!" << endl;
// return 1;
// }
// to_serialize->serialize(std::cout);
return 0;
}
// Register subcommand
static Subcommand vg_circularize("circularize", "circularize a path within a graph", main_circularize);
<|endoftext|>
|
<commit_before>#include "MainDialog.h"
#include "../common/bouncing.h"
#include "../common/paths.h"
#include "../common/timing.h"
#include <agge/blenders_simd.h>
#include <agge/clipper.h>
#include <agge/dash.h>
#include <agge/math.h>
#include <agge/rasterizer.h>
#include <agge/renderer_parallel.h>
#include <agge/stroke.h>
#include <agge/stroke_features.h>
#include <aggx/blenders.h>
#include <aggx/aggx_ellipse.h>
#include <agg_conv_stroke.h>
#include <agg_rasterizer_sl_clip.h>
#include <agg_ellipse.h>
#include <agg_pixfmt_rgba.h>
#include <agg_renderer_base.h>
#include <agg_scanline_u.h>
#include <agg_rasterizer_scanline_aa.h>
#include <agg_renderer_scanline.h>
using namespace std;
using namespace demo;
const int c_thread_count = 1;
const bool c_use_original_agg = false;
const int c_balls_number = 0;
typedef agge::simd::blender_solid_color blender_used;
namespace
{
class unlimited_miter : public agge::stroke::join
{
public:
virtual void calc(agge::points &output, agge::real_t w, const agge::point_r &v0, agge::real_t d01,
const agge::point_r &v1, agge::real_t d12, const agge::point_r &v2) const
{
using namespace agge;
d01 = w / d01;
d12 = w / d12;
const real_t dx1 = d01 * (v1.y - v0.y);
const real_t dy1 = d01 * (v1.x - v0.x);
const real_t dx2 = d12 * (v2.y - v1.y);
const real_t dy2 = d12 * (v2.x - v1.x);
real_t xi, yi;
if (calc_intersection(v0.x + dx1, v0.y - dy1, v1.x + dx1, v1.y - dy1,
v1.x + dx2, v1.y - dy2, v2.x + dx2, v2.y - dy2, &xi, &yi))
{
output.push_back(create_point(xi, yi));
}
}
private:
AGGE_INLINE static bool calc_intersection(agge::real_t ax, agge::real_t ay, agge::real_t bx, agge::real_t by,
agge::real_t cx, agge::real_t cy, agge::real_t dx, agge::real_t dy, agge::real_t *x, agge::real_t *y)
{
using namespace agge;
real_t num = (ay-cy) * (dx-cx) - (ax-cx) * (dy-cy);
real_t den = (bx-ax) * (dy-cy) - (by-ay) * (dx-cx);
if (fabs(den) < distance_epsilon)
return false;
real_t r = num / den;
*x = ax + r * (bx-ax);
*y = ay + r * (by-ay);
return true;
}
};
agge::simd::blender_solid_color::pixel make_pixel(aggx::rgba8 color)
{
agge::simd::blender_solid_color::pixel p = { color.b, color.g, color.r, 0 };
return p;
}
template <typename BlenderT>
class blender : public BlenderT
{
public:
blender(aggx::rgba8 color)
: BlenderT(make_pixel(color), color.a)
{ }
};
template <int precision>
struct calculate_alpha
{
unsigned int operator ()(int area) const
{
area >>= precision + 1;
if (area < 0)
area = -area;
if (area > 255)
area = 255;
return area;
}
};
template <typename LinesSinkT, typename PathT>
void add_path(LinesSinkT &sink, PathT &path)
{
using namespace agge;
real_t x, y;
path.rewind(0);
for (int command; command = path.vertex(&x, &y), path_command_stop != command; )
{
if (path_command_line_to == (command & path_command_mask))
sink.line_to(x, y);
else if (path_command_move_to == (command & path_command_mask))
sink.move_to(x, y);
if (command & path_flag_close)
sink.close_polygon();
}
}
class bitmap_rendering_buffer
{
public:
typedef unsigned int pixel_type;
typedef agg::const_row_info<pixel_type> row_data;
public:
bitmap_rendering_buffer(::bitmap &target)
: _target(target)
{ }
pixel_type *row_ptr(int, int y, int)
{ return reinterpret_cast<pixel_type *>(_target.row_ptr(y)); }
unsigned int width() const
{ return _target.width(); }
unsigned int height() const
{ return _target.height(); }
private:
::bitmap &_target;
};
class agg_drawer : public Drawer
{
public:
typedef blender<blender_used> solid_color_brush;
typedef agg::pixfmt_alpha_blend_rgba<agg::blender_bgra32, bitmap_rendering_buffer> pixfmt;
typedef agg::rgba8 color_type;
typedef agg::order_bgra component_order;
typedef agg::renderer_base<pixfmt> renderer_base;
typedef agg::renderer_scanline_aa_solid<renderer_base> renderer_aa;
public:
agg_drawer()
: _balls(c_balls)
{ _balls.resize(c_balls_number); }
private:
virtual void draw(::bitmap &surface, Timings &timings)
{
LARGE_INTEGER counter;
const float dt = 0.3f * (float)stopwatch(_balls_timer);
stopwatch(counter);
agge::fill(surface, solid_color_brush(aggx::rgba8(255, 255, 255)));
timings.clearing += stopwatch(counter);
stopwatch(counter);
agg_path_adaptor p(_spiral);
if (!_stroke.get())
_stroke.reset(new agg::conv_stroke<agg_path_adaptor>(p));
else
_stroke->attach(p);
_stroke->width(3);
_stroke->line_join(agg::bevel_join);
_spiral_flattened.clear();
flatten<double>(_spiral_flattened, *_stroke);
timings.stroking += stopwatch(counter);
bitmap_rendering_buffer rbuf(surface);
pixfmt pixf(rbuf);
renderer_base rb(pixf);
renderer_aa ren_aa(rb);
if (_balls.empty())
{
stopwatch(counter);
_rasterizer.add_path(agg_path_adaptor(_spiral_flattened));
_rasterizer.sort();
timings.rasterization += stopwatch(counter);
ren_aa.color(agg::rgba8(0, 154, 255, 255));
agg::render_scanlines(_rasterizer, _scanline, ren_aa);
timings.rendition += stopwatch(counter);
}
for_each(_balls.begin(), _balls.end(), [&] (ball &b) {
demo::move_and_bounce(b, dt, surface.width(), surface.height());
});
for_each(_balls.begin(), _balls.end(), [&] (ball &b) {
agg::ellipse e(b.x, b.y, b.radius, b.radius);
_rasterizer.reset();
stopwatch(counter);
_rasterizer.add_path(e);
_rasterizer.sort();
timings.rasterization += stopwatch(counter);
ren_aa.color(agg::rgba8(b.color.r, b.color.g, b.color.b, b.color.a));
agg::render_scanlines(_rasterizer, _scanline, ren_aa);
timings.rendition += stopwatch(counter);
});
}
virtual void resize(int width, int height)
{
_spiral.clear();
spiral(_spiral, width / 2, height / 2, 5, (std::min)(width, height) / 2 - 10, 1, 0);
}
private:
agg::rasterizer_scanline_aa<agg::rasterizer_sl_no_clip> _rasterizer;
agg::scanline_u8 _scanline;
AggPath _spiral, _spiral_flattened;
LARGE_INTEGER _balls_timer;
vector<demo::ball> _balls;
auto_ptr< agg::conv_stroke<agg_path_adaptor> > _stroke;
};
class agge_drawer : public Drawer
{
public:
typedef blender<blender_used> solid_color_brush;
public:
agge_drawer()
: _renderer(c_thread_count), _balls(c_balls)
{
_balls.resize(c_balls_number);
_dash.add_dash(15.0f, 4.0f);
}
private:
virtual void draw(::bitmap &surface, Timings &timings)
{
LARGE_INTEGER counter;
const float dt = 0.3f * (float)stopwatch(_balls_timer);
_rasterizer.reset();
stopwatch(counter);
agge::fill(surface, solid_color_brush(aggx::rgba8(255, 255, 255)));
timings.clearing += stopwatch(counter);
if (_balls.empty())
{
stopwatch(counter);
agg_path_adaptor p(_spiral);
agge::path_generator_adapter<agg_path_adaptor, agge::stroke> path_stroke1(p, _stroke1);
agge::path_generator_adapter<agge::path_generator_adapter<agg_path_adaptor, agge::stroke>, agge::stroke> path_stroke2(path_stroke1, _stroke2);
agge::path_generator_adapter<agg_path_adaptor, agge::dash> path_stroke3(p, _dash);
agge::path_generator_adapter<agge::path_generator_adapter<agg_path_adaptor, agge::dash>, agge::stroke> path_stroke4(path_stroke3, _stroke1);
agge::path_generator_adapter<agge::path_generator_adapter<agge::path_generator_adapter<agg_path_adaptor, agge::dash>, agge::stroke>, agge::stroke> path_stroke5(path_stroke4, _stroke2);
_stroke1.width(3.0f);
_stroke1.set_cap(agge::caps::butt());
_stroke1.set_join(unlimited_miter());
_stroke2.width(1.2f);
_stroke2.set_cap(agge::caps::butt());
_stroke2.set_join(unlimited_miter());
_spiral_flattened.clear();
flatten<agge::real_t>(_spiral_flattened, path_stroke5);
timings.stroking += stopwatch(counter);
solid_color_brush brush(aggx::rgba8(0, 154, 255, 230));
stopwatch(counter);
add_path(_rasterizer, agg_path_adaptor(_spiral_flattened));
_rasterizer.sort();
timings.rasterization += stopwatch(counter);
_renderer(surface, 0, _rasterizer, brush, calculate_alpha<agge::vector_rasterizer::_1_shift>());
timings.rendition += stopwatch(counter);
}
for_each(_balls.begin(), _balls.end(), [&] (ball &b) {
demo::move_and_bounce(b, dt, surface.width(), surface.height());
});
for_each(_balls.begin(), _balls.end(), [&] (ball &b) {
aggx::ellipse e(b.x, b.y, b.radius, b.radius);
_rasterizer.reset();
stopwatch(counter);
add_path(_rasterizer, e);
_rasterizer.sort();
timings.rasterization += stopwatch(counter);
_renderer(surface, 0, _rasterizer, agge_drawer::solid_color_brush(b.color), calculate_alpha<agge::vector_rasterizer::_1_shift>());
timings.rendition += stopwatch(counter);
});
}
virtual void resize(int width, int height)
{
_spiral.clear();
spiral(_spiral, width / 2, height / 2, 5, (std::min)(width, height) / 2 - 10, 1, 0);
}
private:
agge::rasterizer< agge::clipper<int> > _rasterizer;
__declspec(align(16)) agge::renderer_parallel _renderer;
AggPath _spiral, _spiral_flattened;
LARGE_INTEGER _balls_timer;
vector<demo::ball> _balls;
agge::stroke _stroke1, _stroke2;
agge::dash _dash;
};
}
int main()
{
delete new int;
agg_drawer d1;
agge_drawer d2;
MainDialog dlg(c_use_original_agg ? (Drawer &)d1 : (Drawer &)d2);
MainDialog::PumpMessages();
}
<commit_msg>Sandbox app is now DPI-aware<commit_after>#include "MainDialog.h"
#include "../common/bouncing.h"
#include "../common/paths.h"
#include "../common/timing.h"
#include <agge/blenders_simd.h>
#include <agge/clipper.h>
#include <agge/dash.h>
#include <agge/math.h>
#include <agge/rasterizer.h>
#include <agge/renderer_parallel.h>
#include <agge/stroke.h>
#include <agge/stroke_features.h>
#include <aggx/blenders.h>
#include <aggx/aggx_ellipse.h>
#include <agg_conv_stroke.h>
#include <agg_rasterizer_sl_clip.h>
#include <agg_ellipse.h>
#include <agg_pixfmt_rgba.h>
#include <agg_renderer_base.h>
#include <agg_scanline_u.h>
#include <agg_rasterizer_scanline_aa.h>
#include <agg_renderer_scanline.h>
using namespace std;
using namespace demo;
const int c_thread_count = 1;
const bool c_use_original_agg = false;
const int c_balls_number = 0;
typedef agge::simd::blender_solid_color blender_used;
namespace
{
class unlimited_miter : public agge::stroke::join
{
public:
virtual void calc(agge::points &output, agge::real_t w, const agge::point_r &v0, agge::real_t d01,
const agge::point_r &v1, agge::real_t d12, const agge::point_r &v2) const
{
using namespace agge;
d01 = w / d01;
d12 = w / d12;
const real_t dx1 = d01 * (v1.y - v0.y);
const real_t dy1 = d01 * (v1.x - v0.x);
const real_t dx2 = d12 * (v2.y - v1.y);
const real_t dy2 = d12 * (v2.x - v1.x);
real_t xi, yi;
if (calc_intersection(v0.x + dx1, v0.y - dy1, v1.x + dx1, v1.y - dy1,
v1.x + dx2, v1.y - dy2, v2.x + dx2, v2.y - dy2, &xi, &yi))
{
output.push_back(create_point(xi, yi));
}
}
private:
AGGE_INLINE static bool calc_intersection(agge::real_t ax, agge::real_t ay, agge::real_t bx, agge::real_t by,
agge::real_t cx, agge::real_t cy, agge::real_t dx, agge::real_t dy, agge::real_t *x, agge::real_t *y)
{
using namespace agge;
real_t num = (ay-cy) * (dx-cx) - (ax-cx) * (dy-cy);
real_t den = (bx-ax) * (dy-cy) - (by-ay) * (dx-cx);
if (fabs(den) < distance_epsilon)
return false;
real_t r = num / den;
*x = ax + r * (bx-ax);
*y = ay + r * (by-ay);
return true;
}
};
agge::simd::blender_solid_color::pixel make_pixel(aggx::rgba8 color)
{
agge::simd::blender_solid_color::pixel p = { color.b, color.g, color.r, 0 };
return p;
}
template <typename BlenderT>
class blender : public BlenderT
{
public:
blender(aggx::rgba8 color)
: BlenderT(make_pixel(color), color.a)
{ }
};
template <int precision>
struct calculate_alpha
{
unsigned int operator ()(int area) const
{
area >>= precision + 1;
if (area < 0)
area = -area;
if (area > 255)
area = 255;
return area;
}
};
template <typename LinesSinkT, typename PathT>
void add_path(LinesSinkT &sink, PathT &path)
{
using namespace agge;
real_t x, y;
path.rewind(0);
for (int command; command = path.vertex(&x, &y), path_command_stop != command; )
{
if (path_command_line_to == (command & path_command_mask))
sink.line_to(x, y);
else if (path_command_move_to == (command & path_command_mask))
sink.move_to(x, y);
if (command & path_flag_close)
sink.close_polygon();
}
}
class bitmap_rendering_buffer
{
public:
typedef unsigned int pixel_type;
typedef agg::const_row_info<pixel_type> row_data;
public:
bitmap_rendering_buffer(::bitmap &target)
: _target(target)
{ }
pixel_type *row_ptr(int, int y, int)
{ return reinterpret_cast<pixel_type *>(_target.row_ptr(y)); }
unsigned int width() const
{ return _target.width(); }
unsigned int height() const
{ return _target.height(); }
private:
::bitmap &_target;
};
class agg_drawer : public Drawer
{
public:
typedef blender<blender_used> solid_color_brush;
typedef agg::pixfmt_alpha_blend_rgba<agg::blender_bgra32, bitmap_rendering_buffer> pixfmt;
typedef agg::rgba8 color_type;
typedef agg::order_bgra component_order;
typedef agg::renderer_base<pixfmt> renderer_base;
typedef agg::renderer_scanline_aa_solid<renderer_base> renderer_aa;
public:
agg_drawer()
: _balls(c_balls)
{ _balls.resize(c_balls_number); }
private:
virtual void draw(::bitmap &surface, Timings &timings)
{
LARGE_INTEGER counter;
const float dt = 0.3f * (float)stopwatch(_balls_timer);
stopwatch(counter);
agge::fill(surface, solid_color_brush(aggx::rgba8(255, 255, 255)));
timings.clearing += stopwatch(counter);
stopwatch(counter);
agg_path_adaptor p(_spiral);
if (!_stroke.get())
_stroke.reset(new agg::conv_stroke<agg_path_adaptor>(p));
else
_stroke->attach(p);
_stroke->width(3);
_stroke->line_join(agg::bevel_join);
_spiral_flattened.clear();
flatten<double>(_spiral_flattened, *_stroke);
timings.stroking += stopwatch(counter);
bitmap_rendering_buffer rbuf(surface);
pixfmt pixf(rbuf);
renderer_base rb(pixf);
renderer_aa ren_aa(rb);
if (_balls.empty())
{
stopwatch(counter);
_rasterizer.add_path(agg_path_adaptor(_spiral_flattened));
_rasterizer.sort();
timings.rasterization += stopwatch(counter);
ren_aa.color(agg::rgba8(0, 154, 255, 255));
agg::render_scanlines(_rasterizer, _scanline, ren_aa);
timings.rendition += stopwatch(counter);
}
for_each(_balls.begin(), _balls.end(), [&] (ball &b) {
demo::move_and_bounce(b, dt, surface.width(), surface.height());
});
for_each(_balls.begin(), _balls.end(), [&] (ball &b) {
agg::ellipse e(b.x, b.y, b.radius, b.radius);
_rasterizer.reset();
stopwatch(counter);
_rasterizer.add_path(e);
_rasterizer.sort();
timings.rasterization += stopwatch(counter);
ren_aa.color(agg::rgba8(b.color.r, b.color.g, b.color.b, b.color.a));
agg::render_scanlines(_rasterizer, _scanline, ren_aa);
timings.rendition += stopwatch(counter);
});
}
virtual void resize(int width, int height)
{
_spiral.clear();
spiral(_spiral, width / 2, height / 2, 5, (std::min)(width, height) / 2 - 10, 1, 0);
}
private:
agg::rasterizer_scanline_aa<agg::rasterizer_sl_no_clip> _rasterizer;
agg::scanline_u8 _scanline;
AggPath _spiral, _spiral_flattened;
LARGE_INTEGER _balls_timer;
vector<demo::ball> _balls;
auto_ptr< agg::conv_stroke<agg_path_adaptor> > _stroke;
};
class agge_drawer : public Drawer
{
public:
typedef blender<blender_used> solid_color_brush;
public:
agge_drawer()
: _renderer(c_thread_count), _balls(c_balls)
{
_balls.resize(c_balls_number);
_dash.add_dash(15.0f, 4.0f);
}
private:
virtual void draw(::bitmap &surface, Timings &timings)
{
LARGE_INTEGER counter;
const float dt = 0.3f * (float)stopwatch(_balls_timer);
_rasterizer.reset();
stopwatch(counter);
agge::fill(surface, solid_color_brush(aggx::rgba8(255, 255, 255)));
timings.clearing += stopwatch(counter);
if (_balls.empty())
{
stopwatch(counter);
agg_path_adaptor p(_spiral);
agge::path_generator_adapter<agg_path_adaptor, agge::stroke> path_stroke1(p, _stroke1);
agge::path_generator_adapter<agge::path_generator_adapter<agg_path_adaptor, agge::stroke>, agge::stroke> path_stroke2(path_stroke1, _stroke2);
agge::path_generator_adapter<agg_path_adaptor, agge::dash> path_stroke3(p, _dash);
agge::path_generator_adapter<agge::path_generator_adapter<agg_path_adaptor, agge::dash>, agge::stroke> path_stroke4(path_stroke3, _stroke1);
agge::path_generator_adapter<agge::path_generator_adapter<agge::path_generator_adapter<agg_path_adaptor, agge::dash>, agge::stroke>, agge::stroke> path_stroke5(path_stroke4, _stroke2);
_stroke1.width(3.0f);
_stroke1.set_cap(agge::caps::butt());
_stroke1.set_join(unlimited_miter());
_stroke2.width(1.2f);
_stroke2.set_cap(agge::caps::butt());
_stroke2.set_join(unlimited_miter());
_spiral_flattened.clear();
flatten<agge::real_t>(_spiral_flattened, path_stroke5);
timings.stroking += stopwatch(counter);
solid_color_brush brush(aggx::rgba8(0, 154, 255, 230));
stopwatch(counter);
add_path(_rasterizer, agg_path_adaptor(_spiral_flattened));
_rasterizer.sort();
timings.rasterization += stopwatch(counter);
_renderer(surface, 0, _rasterizer, brush, calculate_alpha<agge::vector_rasterizer::_1_shift>());
timings.rendition += stopwatch(counter);
}
for_each(_balls.begin(), _balls.end(), [&] (ball &b) {
demo::move_and_bounce(b, dt, surface.width(), surface.height());
});
for_each(_balls.begin(), _balls.end(), [&] (ball &b) {
aggx::ellipse e(b.x, b.y, b.radius, b.radius);
_rasterizer.reset();
stopwatch(counter);
add_path(_rasterizer, e);
_rasterizer.sort();
timings.rasterization += stopwatch(counter);
_renderer(surface, 0, _rasterizer, agge_drawer::solid_color_brush(b.color), calculate_alpha<agge::vector_rasterizer::_1_shift>());
timings.rendition += stopwatch(counter);
});
}
virtual void resize(int width, int height)
{
_spiral.clear();
spiral(_spiral, width / 2, height / 2, 5, (std::min)(width, height) / 2 - 10, 1, 0);
}
private:
agge::rasterizer< agge::clipper<int> > _rasterizer;
__declspec(align(16)) agge::renderer_parallel _renderer;
AggPath _spiral, _spiral_flattened;
LARGE_INTEGER _balls_timer;
vector<demo::ball> _balls;
agge::stroke _stroke1, _stroke2;
agge::dash _dash;
};
}
int main()
{
::SetProcessDPIAware();
agg_drawer d1;
agge_drawer d2;
MainDialog dlg(c_use_original_agg ? (Drawer &)d1 : (Drawer &)d2);
MainDialog::PumpMessages();
}
<|endoftext|>
|
<commit_before>#ifndef MJOLNIR_CORE_GLOBAL_FORCE_FIELD_HPP
#define MJOLNIR_CORE_GLOBAL_FORCE_FIELD_HPP
#include <mjolnir/core/GlobalInteractionBase.hpp>
#include <mjolnir/util/logger.hpp>
#include <vector>
#include <array>
#include <memory>
namespace mjolnir
{
template<typename traitsT>
class GlobalForceField
{
public:
using traits_type = traitsT;
using real_type = typename traits_type::real_type;
using coordinate_type = typename traits_type::coordinate_type;
using boundary_type = typename traits_type::boundary_type;
using system_type = System<traits_type>;
using topology_type = Topology;
using interaction_base = GlobalInteractionBase<traitsT>;
using interaction_ptr = std::unique_ptr<interaction_base>;
using container_type = std::vector<interaction_ptr>;
using iterator = typename container_type::iterator;
using const_iterator = typename container_type::const_iterator;
public:
GlobalForceField() = default;
~GlobalForceField() = default;
GlobalForceField(GlobalForceField&&) = default;
GlobalForceField& operator=(GlobalForceField&&) = default;
GlobalForceField(const GlobalForceField& other)
: interactions_(other.size())
{
std::transform(other.begin(), other.end(), this->interactions_.begin(),
[](const interaction_ptr& interaction) -> interaction_ptr {
return interaction_ptr(interaction->clone());
});
}
GlobalForceField& operator=(const GlobalForceField& other)
{
this->interactions_.clear();
this->interactions_.reserve(other.size());
for(const auto& interaction : other)
{
this->emplace(interaction_ptr(interaction->clone()));
}
return *this;
}
void emplace(interaction_ptr&& inter)
{
interactions_.emplace_back(std::move(inter));
return;
}
void initialize(const system_type& sys, const topology_type& topol)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
for(auto& item : this->interactions_)
{
MJOLNIR_LOG_INFO("initializing ", item->name());
item->initialize(sys, topol);
}
return;
}
// to re-calculate parameters like temperature, ionic concentration, etc...
void update(const system_type& sys, const topology_type& topol)
{
for(auto& item : this->interactions_)
{
item->update(sys, topol);
}
return;
}
// to reduce margin of neighbor list, and re-construct the list if needed
void reduce_margin(const real_type dmargin, const system_type& sys)
{
for(auto& item : this->interactions_)
{
item->reduce_margin(dmargin, sys);
}
return;
}
void scale_margin(const real_type scale, const system_type& sys)
{
for(auto& item : this->interactions_)
{
item->scale_margin(scale, sys);
}
return;
}
void calc_force(system_type& sys) const noexcept
{
MJOLNIR_GET_DEFAULT_LOGGER_DEBUG();
MJOLNIR_LOG_FUNCTION_DEBUG();
for(const auto& item : this->interactions_)
{
MJOLNIR_LOG_DEBUG("interaction name is ", item->name());
item->calc_force(sys);
}
return;
}
real_type calc_energy(const system_type& sys) const noexcept
{
real_type energy = 0.;
for(const auto& item : this->interactions_)
{
energy += item->calc_energy(sys);
}
return energy;
}
real_type calc_force_and_energy(system_type& sys) const noexcept
{
// TODO speedup
real_type energy = 0.;
for(const auto& item : this->interactions_)
{
item->calc_force(sys);
energy += item->calc_energy(sys);
}
return energy;
}
// basically, it is called only once at the begenning of a simulation.
// this function do a lot of stuff, such as memory allocation, but it does
// not affect runtime efficiency so much.
std::vector<std::string> list_energy() const
{
std::vector<std::string> retval;
for(const auto& i : interactions_)
{
retval.push_back(i->name());
}
return retval;
}
std::vector<real_type> dump_energy(const system_type& sys) const
{
std::vector<real_type> retval;
for(const auto& i : interactions_)
{
retval.push_back(i->calc_energy(sys));
}
return retval;
}
bool empty() const noexcept {return interactions_.empty();}
std::size_t size() const noexcept {return interactions_.size();}
iterator begin() noexcept {return interactions_.begin();}
iterator end() noexcept {return interactions_.end();}
const_iterator begin() const noexcept {return interactions_.begin();}
const_iterator end() const noexcept {return interactions_.end();}
const_iterator cbegin() const noexcept {return interactions_.begin();}
const_iterator cend() const noexcept {return interactions_.end();}
private:
container_type interactions_;
};
#ifdef MJOLNIR_SEPARATE_BUILD
extern template class GlobalForceField<SimulatorTraits<double, UnlimitedBoundary>>;
extern template class GlobalForceField<SimulatorTraits<float, UnlimitedBoundary>>;
extern template class GlobalForceField<SimulatorTraits<double, CuboidalPeriodicBoundary>>;
extern template class GlobalForceField<SimulatorTraits<float, CuboidalPeriodicBoundary>>;
#endif
} // mjolnir
#endif /* MJOLNIR_GLOBAL_FORCE_FIELD */
<commit_msg>feat: use global calc_force_and_energy<commit_after>#ifndef MJOLNIR_CORE_GLOBAL_FORCE_FIELD_HPP
#define MJOLNIR_CORE_GLOBAL_FORCE_FIELD_HPP
#include <mjolnir/core/GlobalInteractionBase.hpp>
#include <mjolnir/util/logger.hpp>
#include <vector>
#include <array>
#include <memory>
namespace mjolnir
{
template<typename traitsT>
class GlobalForceField
{
public:
using traits_type = traitsT;
using real_type = typename traits_type::real_type;
using coordinate_type = typename traits_type::coordinate_type;
using boundary_type = typename traits_type::boundary_type;
using system_type = System<traits_type>;
using topology_type = Topology;
using interaction_base = GlobalInteractionBase<traitsT>;
using interaction_ptr = std::unique_ptr<interaction_base>;
using container_type = std::vector<interaction_ptr>;
using iterator = typename container_type::iterator;
using const_iterator = typename container_type::const_iterator;
public:
GlobalForceField() = default;
~GlobalForceField() = default;
GlobalForceField(GlobalForceField&&) = default;
GlobalForceField& operator=(GlobalForceField&&) = default;
GlobalForceField(const GlobalForceField& other)
: interactions_(other.size())
{
std::transform(other.begin(), other.end(), this->interactions_.begin(),
[](const interaction_ptr& interaction) -> interaction_ptr {
return interaction_ptr(interaction->clone());
});
}
GlobalForceField& operator=(const GlobalForceField& other)
{
this->interactions_.clear();
this->interactions_.reserve(other.size());
for(const auto& interaction : other)
{
this->emplace(interaction_ptr(interaction->clone()));
}
return *this;
}
void emplace(interaction_ptr&& inter)
{
interactions_.emplace_back(std::move(inter));
return;
}
void initialize(const system_type& sys, const topology_type& topol)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
for(auto& item : this->interactions_)
{
MJOLNIR_LOG_INFO("initializing ", item->name());
item->initialize(sys, topol);
}
return;
}
// to re-calculate parameters like temperature, ionic concentration, etc...
void update(const system_type& sys, const topology_type& topol)
{
for(auto& item : this->interactions_)
{
item->update(sys, topol);
}
return;
}
// to reduce margin of neighbor list, and re-construct the list if needed
void reduce_margin(const real_type dmargin, const system_type& sys)
{
for(auto& item : this->interactions_)
{
item->reduce_margin(dmargin, sys);
}
return;
}
void scale_margin(const real_type scale, const system_type& sys)
{
for(auto& item : this->interactions_)
{
item->scale_margin(scale, sys);
}
return;
}
void calc_force(system_type& sys) const noexcept
{
MJOLNIR_GET_DEFAULT_LOGGER_DEBUG();
MJOLNIR_LOG_FUNCTION_DEBUG();
for(const auto& item : this->interactions_)
{
MJOLNIR_LOG_DEBUG("interaction name is ", item->name());
item->calc_force(sys);
}
return;
}
real_type calc_energy(const system_type& sys) const noexcept
{
real_type energy = 0.;
for(const auto& item : this->interactions_)
{
energy += item->calc_energy(sys);
}
return energy;
}
real_type calc_force_and_energy(system_type& sys) const noexcept
{
real_type energy = 0.;
for(const auto& item : this->interactions_)
{
energy += item->calc_force_and_energy(sys);
}
return energy;
}
// basically, it is called only once at the begenning of a simulation.
// this function do a lot of stuff, such as memory allocation, but it does
// not affect runtime efficiency so much.
std::vector<std::string> list_energy() const
{
std::vector<std::string> retval;
for(const auto& i : interactions_)
{
retval.push_back(i->name());
}
return retval;
}
std::vector<real_type> dump_energy(const system_type& sys) const
{
std::vector<real_type> retval;
for(const auto& i : interactions_)
{
retval.push_back(i->calc_energy(sys));
}
return retval;
}
bool empty() const noexcept {return interactions_.empty();}
std::size_t size() const noexcept {return interactions_.size();}
iterator begin() noexcept {return interactions_.begin();}
iterator end() noexcept {return interactions_.end();}
const_iterator begin() const noexcept {return interactions_.begin();}
const_iterator end() const noexcept {return interactions_.end();}
const_iterator cbegin() const noexcept {return interactions_.begin();}
const_iterator cend() const noexcept {return interactions_.end();}
private:
container_type interactions_;
};
#ifdef MJOLNIR_SEPARATE_BUILD
extern template class GlobalForceField<SimulatorTraits<double, UnlimitedBoundary>>;
extern template class GlobalForceField<SimulatorTraits<float, UnlimitedBoundary>>;
extern template class GlobalForceField<SimulatorTraits<double, CuboidalPeriodicBoundary>>;
extern template class GlobalForceField<SimulatorTraits<float, CuboidalPeriodicBoundary>>;
#endif
} // mjolnir
#endif /* MJOLNIR_GLOBAL_FORCE_FIELD */
<|endoftext|>
|
<commit_before>#ifndef MJOLNIR_INPUT_READ_INPUT_FILE_HPP
#define MJOLNIR_INPUT_READ_INPUT_FILE_HPP
#include <extlib/toml/toml.hpp>
#include <mjolnir/core/BoundaryCondition.hpp>
#include <mjolnir/core/SimulatorBase.hpp>
#include <mjolnir/core/SimulatorTraits.hpp>
#include <mjolnir/core/Unit.hpp>
#include <mjolnir/util/logger.hpp>
#include <mjolnir/input/utility.hpp>
#include <mjolnir/input/read_units.hpp>
#include <mjolnir/input/read_path.hpp>
#ifdef MJOLNIR_WITH_OPENMP
#include <mjolnir/omp/omp.hpp>
#endif
#include <memory>
namespace mjolnir
{
template<typename realT, template<typename, typename> class boundaryT>
std::unique_ptr<SimulatorBase>
read_parallelism(const toml::value& root, const toml::value& simulator)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
if(simulator.as_table().count("parallelism") == 0)
{
MJOLNIR_LOG_NOTICE("execute on single core");
return read_units<SimulatorTraits<realT, boundaryT>>(root, simulator);
}
const auto parallelism = toml::find(simulator, "parallelism");
if(parallelism.is_string() && parallelism.as_string() == "sequencial")
{
MJOLNIR_LOG_NOTICE("execute on single core");
return read_units<SimulatorTraits<realT, boundaryT>>(root, simulator);
}
else if(parallelism.is_string() &&
(parallelism.as_string() == "openmp" ||
parallelism.as_string() == "OpenMP"))
{
#ifdef MJOLNIR_WITH_OPENMP
MJOLNIR_LOG_NOTICE("execute on ", omp_get_max_threads() ," cores with openmp");
return read_units<OpenMPSimulatorTraits<realT, boundaryT>>(root, simulator);
#else
MJOLNIR_LOG_WARN("OpenMP flag is set, but OpenMP is not enabled when building.");
MJOLNIR_LOG_WARN("Cannot use OpenMP, running with single core.");
return read_units<SimulatorTraits<realT, boundaryT>>(root, simulator);
#endif
}
else
{
throw_exception<std::runtime_error>(toml::format_error("[error] "
"mjolnir::read_parallelism: invalid variable ",
toml::find(simulator, "parallelism"), "here", {
"- \"sequencial\": run with only 1 core (default)",
"- \"openmp\" : use openmp to parallelize."
}));
}
}
template<typename realT>
std::unique_ptr<SimulatorBase>
read_boundary(const toml::value& root, const toml::value& simulator)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
const auto boundary = toml::find<std::string>(simulator, "boundary_type");
if(boundary == "Unlimited")
{
MJOLNIR_LOG_NOTICE("Boundary Condition is Unlimited");
return read_parallelism<realT, UnlimitedBoundary>(root, simulator);
}
else if(boundary == "Periodic")
{
MJOLNIR_LOG_NOTICE("Boundary Condition is Periodic. "
"The shape is cuboid.");
return read_parallelism<realT, CuboidalPeriodicBoundary>(root, simulator);
}
else if(boundary == "PeriodicCuboid")
{
MJOLNIR_LOG_NOTICE("Boundary Condition is PeriodicCuboid");
return read_parallelism<realT, CuboidalPeriodicBoundary>(root, simulator);
}
else
{
throw_exception<std::runtime_error>(toml::format_error("[error] "
"mjolnir::read_boundary: invalid boundary",
toml::find(simulator, "boundary_type"), "here", {
"- \"Unlimited\" : no boundary condition. infinite space",
"- \"Periodic\" : periodic boundary. Assuming cuboidal shape.",
"- \"PeriodicCuboid\": periodic boundary with cuboidal shape"
}));
}
}
inline std::unique_ptr<SimulatorBase>
read_precision(const toml::value& root, const toml::value& simulator)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
const auto prec = toml::find<std::string>(simulator, "precision");
if(prec == "double")
{
MJOLNIR_LOG_NOTICE("precision is double");
return read_boundary<double>(root, simulator);
}
else if(prec == "float")
{
MJOLNIR_LOG_NOTICE("precision is float");
return read_boundary<float>(root, simulator);
}
else
{
throw_exception<std::runtime_error>(toml::format_error("[error] "
"mjolnir::read_precision: invalid precision",
toml::find(simulator, "precition"), "here", {
"expected value is one of the following.",
"- \"double\": 64 bit floating-point",
"- \"float\" : 32 bit floating-point"
}));
}
}
inline std::unique_ptr<SimulatorBase>
read_input_file(const std::string& filename)
{
// here, logger name is not given yet. output status directory on console.
std::cerr << "-- reading and parsing toml file `" << filename << "` ... ";
auto root = toml::parse(filename);
std::cerr << " successfully parsed." << std::endl;
// initializing logger by using output_path and output_prefix ...
const auto& output = toml::find(root, "files", "output");
const auto out_path = read_output_path(root);
// XXX: Here, this code assumes POSIX. it does not support windows.
// TODO: Consider using Boost.filesystem to manage path and files
// in more elegant and powerful way? After switching C++17,
// we can re-write that with <filesystem>.
const auto logger_name = out_path +
toml::find<std::string>(output, "prefix") + ".log";
MJOLNIR_SET_DEFAULT_LOGGER(logger_name);
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
MJOLNIR_LOG_NOTICE("the log file is `", logger_name, '`');
// Check top-level toml-values. Since it uses logger to warn,
// we need to call it after `MJOLNIR_SET_DEFAULT_LOGGER(logger_name)`.
check_keys_available(root, {"files"_s, "units"_s, "simulator"_s,
"systems"_s, "forcefields"_s});
// load the input path in the [files] table and set it globally
read_input_path(root);
MJOLNIR_LOG_NOTICE("expanding include files ...");
expand_include(root);
MJOLNIR_LOG_NOTICE("done.");
// the most of important flags are defined in [simulator], like
// `precision = "float"`, `boundary_type = "Unlimited"`.
// Those values should be read before others.
const auto simulator = read_table_from_file(
toml::find(root, "simulator"), "simulator");
return read_precision(root, simulator);
}
#ifdef MJOLNIR_SEPARATE_BUILD
extern template std::unique_ptr<SimulatorBase> read_parallelism<double, UnlimitedBoundary >(const toml::value& root, const toml::value& simulator);
extern template std::unique_ptr<SimulatorBase> read_parallelism<float , UnlimitedBoundary >(const toml::value& root, const toml::value& simulator);
extern template std::unique_ptr<SimulatorBase> read_parallelism<double, CuboidalPeriodicBoundary>(const toml::value& root, const toml::value& simulator);
extern template std::unique_ptr<SimulatorBase> read_parallelism<float , CuboidalPeriodicBoundary>(const toml::value& root, const toml::value& simulator);
extern template std::unique_ptr<SimulatorBase> read_boundary<double>(const toml::value& root, const toml::value& simulator);
extern template std::unique_ptr<SimulatorBase> read_boundary<float >(const toml::value& root, const toml::value& simulator);
#endif
}// mjolnir
#endif// MJOLNIR_READ_INPUT_FILE
<commit_msg>feat: output version and compiler to log<commit_after>#ifndef MJOLNIR_INPUT_READ_INPUT_FILE_HPP
#define MJOLNIR_INPUT_READ_INPUT_FILE_HPP
#include <extlib/toml/toml.hpp>
#include <mjolnir/core/BoundaryCondition.hpp>
#include <mjolnir/core/SimulatorBase.hpp>
#include <mjolnir/core/SimulatorTraits.hpp>
#include <mjolnir/core/Unit.hpp>
#include <mjolnir/util/logger.hpp>
#include <mjolnir/input/utility.hpp>
#include <mjolnir/input/read_units.hpp>
#include <mjolnir/input/read_path.hpp>
#ifdef MJOLNIR_WITH_OPENMP
#include <mjolnir/omp/omp.hpp>
#endif
#include <memory>
namespace mjolnir
{
template<typename realT, template<typename, typename> class boundaryT>
std::unique_ptr<SimulatorBase>
read_parallelism(const toml::value& root, const toml::value& simulator)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
if(simulator.as_table().count("parallelism") == 0)
{
MJOLNIR_LOG_NOTICE("execute on single core");
return read_units<SimulatorTraits<realT, boundaryT>>(root, simulator);
}
const auto parallelism = toml::find(simulator, "parallelism");
if(parallelism.is_string() && parallelism.as_string() == "sequencial")
{
MJOLNIR_LOG_NOTICE("execute on single core");
return read_units<SimulatorTraits<realT, boundaryT>>(root, simulator);
}
else if(parallelism.is_string() &&
(parallelism.as_string() == "openmp" ||
parallelism.as_string() == "OpenMP"))
{
#ifdef MJOLNIR_WITH_OPENMP
MJOLNIR_LOG_NOTICE("execute on ", omp_get_max_threads() ," cores with openmp");
return read_units<OpenMPSimulatorTraits<realT, boundaryT>>(root, simulator);
#else
MJOLNIR_LOG_WARN("OpenMP flag is set, but OpenMP is not enabled when building.");
MJOLNIR_LOG_WARN("Cannot use OpenMP, running with single core.");
return read_units<SimulatorTraits<realT, boundaryT>>(root, simulator);
#endif
}
else
{
throw_exception<std::runtime_error>(toml::format_error("[error] "
"mjolnir::read_parallelism: invalid variable ",
toml::find(simulator, "parallelism"), "here", {
"- \"sequencial\": run with only 1 core (default)",
"- \"openmp\" : use openmp to parallelize."
}));
}
}
template<typename realT>
std::unique_ptr<SimulatorBase>
read_boundary(const toml::value& root, const toml::value& simulator)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
const auto boundary = toml::find<std::string>(simulator, "boundary_type");
if(boundary == "Unlimited")
{
MJOLNIR_LOG_NOTICE("Boundary Condition is Unlimited");
return read_parallelism<realT, UnlimitedBoundary>(root, simulator);
}
else if(boundary == "Periodic")
{
MJOLNIR_LOG_NOTICE("Boundary Condition is Periodic. "
"The shape is cuboid.");
return read_parallelism<realT, CuboidalPeriodicBoundary>(root, simulator);
}
else if(boundary == "PeriodicCuboid")
{
MJOLNIR_LOG_NOTICE("Boundary Condition is PeriodicCuboid");
return read_parallelism<realT, CuboidalPeriodicBoundary>(root, simulator);
}
else
{
throw_exception<std::runtime_error>(toml::format_error("[error] "
"mjolnir::read_boundary: invalid boundary",
toml::find(simulator, "boundary_type"), "here", {
"- \"Unlimited\" : no boundary condition. infinite space",
"- \"Periodic\" : periodic boundary. Assuming cuboidal shape.",
"- \"PeriodicCuboid\": periodic boundary with cuboidal shape"
}));
}
}
inline std::unique_ptr<SimulatorBase>
read_precision(const toml::value& root, const toml::value& simulator)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
const auto prec = toml::find<std::string>(simulator, "precision");
if(prec == "double")
{
MJOLNIR_LOG_NOTICE("precision is double");
return read_boundary<double>(root, simulator);
}
else if(prec == "float")
{
MJOLNIR_LOG_NOTICE("precision is float");
return read_boundary<float>(root, simulator);
}
else
{
throw_exception<std::runtime_error>(toml::format_error("[error] "
"mjolnir::read_precision: invalid precision",
toml::find(simulator, "precition"), "here", {
"expected value is one of the following.",
"- \"double\": 64 bit floating-point",
"- \"float\" : 32 bit floating-point"
}));
}
}
inline std::unique_ptr<SimulatorBase>
read_input_file(const std::string& filename)
{
// here, logger name is not given yet. output status directory on console.
std::cerr << "-- reading and parsing toml file `" << filename << "` ... ";
auto root = toml::parse(filename);
std::cerr << " successfully parsed." << std::endl;
// initializing logger by using output_path and output_prefix ...
const auto& output = toml::find(root, "files", "output");
const auto out_path = read_output_path(root);
// XXX: Here, this code assumes POSIX. it does not support windows.
// TODO: Consider using Boost.filesystem to manage path and files
// in more elegant and powerful way? After switching C++17,
// we can re-write that with <filesystem>.
const auto logger_name = out_path +
toml::find<std::string>(output, "prefix") + ".log";
MJOLNIR_SET_DEFAULT_LOGGER(logger_name);
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
MJOLNIR_LOG_NOTICE("the log file is `", logger_name, '`');
MJOLNIR_LOG_NOTICE("mjolnir version ", MJOLNIR_VERSION);
MJOLNIR_LOG_NOTICE("compiled using ", MJOLNIR_COMPILER_VERSION);
// Check top-level toml-values. Since it uses logger to warn,
// we need to call it after `MJOLNIR_SET_DEFAULT_LOGGER(logger_name)`.
check_keys_available(root, {"files"_s, "units"_s, "simulator"_s,
"systems"_s, "forcefields"_s});
// load the input path in the [files] table and set it globally
read_input_path(root);
MJOLNIR_LOG_NOTICE("expanding include files ...");
expand_include(root);
MJOLNIR_LOG_NOTICE("done.");
// the most of important flags are defined in [simulator], like
// `precision = "float"`, `boundary_type = "Unlimited"`.
// Those values should be read before others.
const auto simulator = read_table_from_file(
toml::find(root, "simulator"), "simulator");
return read_precision(root, simulator);
}
#ifdef MJOLNIR_SEPARATE_BUILD
extern template std::unique_ptr<SimulatorBase> read_parallelism<double, UnlimitedBoundary >(const toml::value& root, const toml::value& simulator);
extern template std::unique_ptr<SimulatorBase> read_parallelism<float , UnlimitedBoundary >(const toml::value& root, const toml::value& simulator);
extern template std::unique_ptr<SimulatorBase> read_parallelism<double, CuboidalPeriodicBoundary>(const toml::value& root, const toml::value& simulator);
extern template std::unique_ptr<SimulatorBase> read_parallelism<float , CuboidalPeriodicBoundary>(const toml::value& root, const toml::value& simulator);
extern template std::unique_ptr<SimulatorBase> read_boundary<double>(const toml::value& root, const toml::value& simulator);
extern template std::unique_ptr<SimulatorBase> read_boundary<float >(const toml::value& root, const toml::value& simulator);
#endif
}// mjolnir
#endif// MJOLNIR_READ_INPUT_FILE
<|endoftext|>
|
<commit_before>/*!
* Copyright (c) 2018 by Contributors
* \file type_functor.cc
* \brief Implementations of type functors.
*/
#include "type_functor.h"
namespace tvm {
namespace relay {
void TypeVisitor::VisitType_(const TypeVarNode* op) {
}
void TypeVisitor::VisitType_(const TensorTypeNode* op) {
}
void TypeVisitor::VisitType_(const IncompleteTypeNode* op) {
}
void TypeVisitor::VisitType_(const FuncTypeNode* op) {
for (auto type_param : op->type_params) {
this->VisitType(type_param);
}
for (auto type_cs : op->type_constraints) {
this->VisitType(type_cs);
}
for (auto arg_type : op->arg_types) {
this->VisitType(arg_type);
}
this->VisitType(op->ret_type);
}
void TypeVisitor::VisitType_(const TupleTypeNode* op) {
for (const Type& t : op->fields) {
this->VisitType(t);
}
}
void TypeVisitor::VisitType_(const TypeRelationNode* op) {
for (const Type& t : op->args) {
this->VisitType(t);
}
}
// Type Mutator.
Array<Type> TypeMutator::MutateArray(Array<Type> arr) {
// The array will do copy on write
// If no changes are made, the original array will be returned.
for (size_t i = 0; i < arr.size(); ++i) {
Type ty = arr[i];
Type new_ty = VisitType(ty);
if (!ty.same_as(new_ty)) {
arr.Set(i, new_ty);
}
}
return arr;
}
Type TypeMutator::VisitType_(const TypeVarNode* op) {
return GetRef<TypeVar>(op);
}
Type TypeMutator::VisitType_(const TensorTypeNode* op) {
// TODO(tvm-team) recursively visit to replace Var
return GetRef<Type>(op);
}
Type TypeMutator::VisitType_(const IncompleteTypeNode* op) {
return GetRef<Type>(op);
}
Type TypeMutator::VisitType_(const FuncTypeNode* op) {
bool changed = false;
Array<TypeVar> type_params;
for (auto type_param : op->type_params) {
auto new_type_param = VisitType(type_param);
changed = changed || !new_type_param.same_as(type_param);
if (const TypeVarNode* tin = new_type_param.as<TypeVarNode>()) {
type_params.push_back(GetRef<TypeVar>(tin));
} else {
LOG(FATAL) << new_type_param << std::endl;
}
}
Array<TypeConstraint> type_constraints;
for (auto type_cs : op->type_constraints) {
auto new_type_cs = VisitType(type_cs);
changed = changed || !new_type_cs.same_as(type_cs);
if (const TypeConstraintNode* tin =
new_type_cs.as_derived<TypeConstraintNode>()) {
type_constraints.push_back(GetRef<TypeConstraint>(tin));
} else {
LOG(FATAL) << new_type_cs << std::endl;
}
}
Array<Type> new_args = MutateArray(op->arg_types);
changed = changed || new_args.same_as(op->arg_types);
Type new_ret_type = VisitType(op->ret_type);
changed = changed || new_ret_type.same_as(op->ret_type);
if (!changed) return GetRef<Type>(op);
return FuncTypeNode::make(new_args,
new_ret_type,
type_params,
type_constraints);
}
Type TypeMutator::VisitType_(const TupleTypeNode* op) {
Array<Type> new_fields = MutateArray(op->fields);
if (new_fields.same_as(op->fields)) {
return GetRef<Type>(op);
} else {
return TupleTypeNode::make(new_fields);
}
}
Type TypeMutator::VisitType_(const TypeRelationNode* type_rel) {
Array<Type> new_args = MutateArray(type_rel->args);
if (new_args.same_as(type_rel->args)) {
return GetRef<Type>(type_rel);
} else {
return TypeRelationNode::make(type_rel->func,
new_args,
type_rel->num_inputs,
type_rel->attrs);
}
}
// Implements bind.
class TypeBinder : public TypeMutator {
public:
explicit TypeBinder(const tvm::Map<TypeVar, Type>& args_map)
: args_map_(args_map) {}
Type VisitType_(const TypeVarNode* op) override {
auto id = GetRef<TypeVar>(op);
auto it = args_map_.find(id);
if (it != args_map_.end()) {
return (*it).second;
} else {
return id;
}
}
private:
const tvm::Map<TypeVar, Type>& args_map_;
};
Type Bind(const Type& type, const tvm::Map<TypeVar, Type>& args_map) {
return TypeBinder(args_map).VisitType(type);
}
} // namespace relay
} // namespace tvm
<commit_msg>[RELAY] bugfix type functor caching (#2113)<commit_after>/*!
* Copyright (c) 2018 by Contributors
* \file type_functor.cc
* \brief Implementations of type functors.
*/
#include "type_functor.h"
namespace tvm {
namespace relay {
void TypeVisitor::VisitType_(const TypeVarNode* op) {
}
void TypeVisitor::VisitType_(const TensorTypeNode* op) {
}
void TypeVisitor::VisitType_(const IncompleteTypeNode* op) {
}
void TypeVisitor::VisitType_(const FuncTypeNode* op) {
for (auto type_param : op->type_params) {
this->VisitType(type_param);
}
for (auto type_cs : op->type_constraints) {
this->VisitType(type_cs);
}
for (auto arg_type : op->arg_types) {
this->VisitType(arg_type);
}
this->VisitType(op->ret_type);
}
void TypeVisitor::VisitType_(const TupleTypeNode* op) {
for (const Type& t : op->fields) {
this->VisitType(t);
}
}
void TypeVisitor::VisitType_(const TypeRelationNode* op) {
for (const Type& t : op->args) {
this->VisitType(t);
}
}
// Type Mutator.
Array<Type> TypeMutator::MutateArray(Array<Type> arr) {
// The array will do copy on write
// If no changes are made, the original array will be returned.
for (size_t i = 0; i < arr.size(); ++i) {
Type ty = arr[i];
Type new_ty = VisitType(ty);
if (!ty.same_as(new_ty)) {
arr.Set(i, new_ty);
}
}
return arr;
}
Type TypeMutator::VisitType_(const TypeVarNode* op) {
return GetRef<TypeVar>(op);
}
Type TypeMutator::VisitType_(const TensorTypeNode* op) {
// TODO(tvm-team) recursively visit to replace Var
return GetRef<Type>(op);
}
Type TypeMutator::VisitType_(const IncompleteTypeNode* op) {
return GetRef<Type>(op);
}
Type TypeMutator::VisitType_(const FuncTypeNode* op) {
bool changed = false;
Array<TypeVar> type_params;
for (auto type_param : op->type_params) {
auto new_type_param = VisitType(type_param);
changed = changed || !new_type_param.same_as(type_param);
if (const TypeVarNode* tin = new_type_param.as<TypeVarNode>()) {
type_params.push_back(GetRef<TypeVar>(tin));
} else {
LOG(FATAL) << new_type_param << std::endl;
}
}
Array<TypeConstraint> type_constraints;
for (auto type_cs : op->type_constraints) {
auto new_type_cs = VisitType(type_cs);
changed = changed || !new_type_cs.same_as(type_cs);
if (const TypeConstraintNode* tin =
new_type_cs.as_derived<TypeConstraintNode>()) {
type_constraints.push_back(GetRef<TypeConstraint>(tin));
} else {
LOG(FATAL) << new_type_cs << std::endl;
}
}
Array<Type> new_args = MutateArray(op->arg_types);
changed = changed || !new_args.same_as(op->arg_types);
Type new_ret_type = VisitType(op->ret_type);
changed = changed || !new_ret_type.same_as(op->ret_type);
if (!changed) return GetRef<Type>(op);
return FuncTypeNode::make(new_args,
new_ret_type,
type_params,
type_constraints);
}
Type TypeMutator::VisitType_(const TupleTypeNode* op) {
Array<Type> new_fields = MutateArray(op->fields);
if (new_fields.same_as(op->fields)) {
return GetRef<Type>(op);
} else {
return TupleTypeNode::make(new_fields);
}
}
Type TypeMutator::VisitType_(const TypeRelationNode* type_rel) {
Array<Type> new_args = MutateArray(type_rel->args);
if (new_args.same_as(type_rel->args)) {
return GetRef<Type>(type_rel);
} else {
return TypeRelationNode::make(type_rel->func,
new_args,
type_rel->num_inputs,
type_rel->attrs);
}
}
// Implements bind.
class TypeBinder : public TypeMutator {
public:
explicit TypeBinder(const tvm::Map<TypeVar, Type>& args_map)
: args_map_(args_map) {}
Type VisitType_(const TypeVarNode* op) override {
auto id = GetRef<TypeVar>(op);
auto it = args_map_.find(id);
if (it != args_map_.end()) {
return (*it).second;
} else {
return id;
}
}
private:
const tvm::Map<TypeVar, Type>& args_map_;
};
Type Bind(const Type& type, const tvm::Map<TypeVar, Type>& args_map) {
return TypeBinder(args_map).VisitType(type);
}
} // namespace relay
} // namespace tvm
<|endoftext|>
|
<commit_before>#include "vec2.h"
namespace fd {
namespace core {
namespace math {
vec2i::vec2i() : x(0), y(0) {}
vec2i::vec2i(int32 x, int32 y) : x(x), y(y) {}
//int32
vec2i& vec2i::Add(const vec2i& v) {
__m128i vxmm = _mm_set_epi32(0, 0, v.y, v.x);
__m128i xmm = _mm_set_epi32(0, 0, y, x);
xmm = _mm_add_epi32(xmm, vxmm);
x = xmm.m128i_i32[0];
y = xmm.m128i_i32[1];
return *this;
}
//int32
vec2i& vec2i::Sub(const vec2i& v) {
__m128i vxmm = _mm_set_epi32(0, 0, v.y, v.x);
__m128i xmm = _mm_set_epi32(0, 0, y, x);
xmm = _mm_sub_epi32(xmm, vxmm);
x = xmm.m128i_i32[0];
y = xmm.m128i_i32[1];
return *this;
}
//int32
vec2i& vec2i::Mul(const vec2i& v) {
__m128i vxmm = _mm_set_epi32(0, v.y, 0, v.x);
__m128i xmm = _mm_set_epi32(0, y, 0, x);
xmm = _mm_mul_epi32(xmm, vxmm);
x = xmm.m128i_i32[0];
y = xmm.m128i_i32[2];
return *this;
}
//int32
vec2i& vec2i::Div(const vec2i& v) {
x /= v.x;
y /= v.y;
return *this;
}
//int32
vec2i& vec2i::Add(int32 v) {
__m128i vxmm = _mm_set_epi32(0, 0, v, v);
__m128i xmm = _mm_set_epi32(0, 0, y, x);
xmm = _mm_add_epi32(xmm, vxmm);
x = xmm.m128i_i32[0];
y = xmm.m128i_i32[1];
return *this;
}
//int32
vec2i& vec2i::Sub(int32 v) {
__m128i vxmm = _mm_set_epi32(0, 0, v, v);
__m128i xmm = _mm_set_epi32(0, 0, y, x);
xmm = _mm_sub_epi32(xmm, vxmm);
x = xmm.m128i_i32[0];
y = xmm.m128i_i32[1];
return *this;
}
//int32
vec2i& vec2i::Mul(int32 v) {
__m128i vxmm = _mm_set_epi32(0, v, 0, v);
__m128i xmm = _mm_set_epi32(0, y, 0, x);
xmm = _mm_mul_epi32(xmm, vxmm);
x = xmm.m128i_i32[0];
y = xmm.m128i_i32[2];
return *this;
}
//int32
vec2i& vec2i::Div(int32 v) {
x /= v;
y /= v;
return *this;
}
}
}
}<commit_msg>LNX: vec2i<commit_after>#include "vec2.h"
namespace fd {
namespace core {
namespace math {
vec2i::vec2i() : x(0), y(0) {}
vec2i::vec2i(int32 x, int32 y) : x(x), y(y) {}
//int32
vec2i& vec2i::Add(const vec2i& v) {
__m128i vxmm = _mm_set_epi32(0, 0, v.y, v.x);
__m128i xmm = _mm_set_epi32(0, 0, y, x);
xmm = _mm_add_epi32(xmm, vxmm);
x = M128I(xmm, 0);
y = M128I(xmm, 1);
return *this;
}
//int32
vec2i& vec2i::Sub(const vec2i& v) {
__m128i vxmm = _mm_set_epi32(0, 0, v.y, v.x);
__m128i xmm = _mm_set_epi32(0, 0, y, x);
xmm = _mm_sub_epi32(xmm, vxmm);
x = M128I(xmm, 0);
y = M128I(xmm, 1);
return *this;
}
//int32
vec2i& vec2i::Mul(const vec2i& v) {
__m128i vxmm = _mm_set_epi32(0, v.y, 0, v.x);
__m128i xmm = _mm_set_epi32(0, y, 0, x);
xmm = _mm_mul_epi32(xmm, vxmm);
x = M128I(xmm, 0);
y = M128I(xmm, 1);
return *this;
}
//int32
vec2i& vec2i::Div(const vec2i& v) {
x /= v.x;
y /= v.y;
return *this;
}
//int32
vec2i& vec2i::Add(int32 v) {
__m128i vxmm = _mm_set_epi32(0, 0, v, v);
__m128i xmm = _mm_set_epi32(0, 0, y, x);
xmm = _mm_add_epi32(xmm, vxmm);
x = M128I(xmm, 0);
y = M128I(xmm, 1);
return *this;
}
//int32
vec2i& vec2i::Sub(int32 v) {
__m128i vxmm = _mm_set_epi32(0, 0, v, v);
__m128i xmm = _mm_set_epi32(0, 0, y, x);
xmm = _mm_sub_epi32(xmm, vxmm);
x = M128I(xmm, 0);
y = M128I(xmm, 1);
return *this;
}
//int32
vec2i& vec2i::Mul(int32 v) {
__m128i vxmm = _mm_set_epi32(0, v, 0, v);
__m128i xmm = _mm_set_epi32(0, y, 0, x);
xmm = _mm_mul_epi32(xmm, vxmm);
x = M128I(xmm, 0);
y = M128I(xmm, 1);
return *this;
}
//int32
vec2i& vec2i::Div(int32 v) {
x /= v;
y /= v;
return *this;
}
}
}
}<|endoftext|>
|
<commit_before>#include "Genes/Freedom_To_Move_Gene.h"
#include <memory>
#include <string>
#include <array>
#include <bitset>
#include "Genes/Gene.h"
#include "Game/Board.h"
#include "Game/Color.h"
#include "Game/Piece.h"
double Freedom_To_Move_Gene::score_board(const Board& board, Color perspective, size_t) const
{
static auto initial_score = double(attack_count(Board(), WHITE));
return attack_count(board, perspective)/initial_score;
}
std::unique_ptr<Gene> Freedom_To_Move_Gene::duplicate() const
{
return std::make_unique<Freedom_To_Move_Gene>(*this);
}
std::string Freedom_To_Move_Gene::name() const
{
return "Freedom to Move Gene";
}
size_t Freedom_To_Move_Gene::attack_count(const Board& board, Color perspective) const
{
size_t count = 0;
for(char file = 'a'; file <= 'h'; ++file)
{
for(int rank = 1; rank <= 8; ++rank)
{
auto piece = board.piece_on_square(file, rank);
if( ! piece || piece->color() != perspective)
{
count += board.moves_attacking_square(file, rank, perspective).count();
}
}
}
return count;
}
<commit_msg>Speedup to Freedom to Move Gene<commit_after>#include "Genes/Freedom_To_Move_Gene.h"
#include <memory>
#include <string>
#include <array>
#include <bitset>
#include "Genes/Gene.h"
#include "Game/Board.h"
#include "Game/Color.h"
#include "Game/Piece.h"
double Freedom_To_Move_Gene::score_board(const Board& board, Color perspective, size_t) const
{
static auto initial_score = double(attack_count(Board(), WHITE));
return attack_count(board, perspective)/initial_score;
}
std::unique_ptr<Gene> Freedom_To_Move_Gene::duplicate() const
{
return std::make_unique<Freedom_To_Move_Gene>(*this);
}
std::string Freedom_To_Move_Gene::name() const
{
return "Freedom to Move Gene";
}
size_t Freedom_To_Move_Gene::attack_count(const Board& board, Color perspective) const
{
size_t count = 0;
for(char file = 'a'; file <= 'h'; ++file)
{
for(int rank = 1; rank <= 8; ++rank)
{
if(board.moves_attacking_square(file, rank, perspective).any())
{
auto piece = board.piece_on_square(file, rank);
if( ! piece || piece->color() != perspective)
{
count += board.moves_attacking_square(file, rank, perspective).count();
}
}
}
}
return count;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2016 Stefan Krüger
// released under MIT (see LICENSE for details)
// based on example from
// http://docs.openlighting.org/ola/doc/latest/dmx_cpp_client_tutorial.html
// build for local:
// g++ -std=c++11 olamapper.cpp -o olamapper.out $(pkg-config --cflags --libs libola)
#include <ola/DmxBuffer.h>
#include <ola/Logging.h>
#include <ola/client/ClientWrapper.h>
#include <ola/io/SelectServer.h>
#include <unistd.h>
#include <string>
#include <iostream>
#include <fstream>
uint16_t universe_in = 1;
uint16_t universe_in_start_address = 1;
uint16_t universe_out = 2;
uint16_t universe_channel_count = 240;
uint16_t universe_rescale_max = 60000;
static const uint16_t channel_count_MAX = 512;
ola::client::OlaClientWrapper wrapper(false);
ola::client::OlaClient *client;
ola::DmxBuffer channels_out;
int my_map[channel_count_MAX];
enum ola_state_t {
state_undefined,
state_standby,
state_waiting,
state_connected,
state_running,
};
ola_state_t system_state = state_undefined;
bool flag_run = true;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// configuration things
void parse_config_channels(std::string raw_channels) {
// get part between []
size_t start = raw_channels.find('[');
size_t end = raw_channels.find(']');
raw_channels = raw_channels.substr(start+1, (end-1)-start);
// std::cout << "raw_channels: '" << raw_channels << "'" << std::endl;
// split at every ', '
start = 0;
end = 0;
size_t map_index = 0;
while ( (end = raw_channels.find(", ", start)) != std::string::npos ) {
std::string element = raw_channels.substr(start, end - start);
start = end + 1;
// std::cout << element << std::endl;
// now we can convert the element string to a int
int value;
value = std::stoi(element);
my_map[map_index] = value;
map_index += 1;
// std::cout << value << std::endl;
}
// handle last element
std::string element = raw_channels.substr(start);
int value;
value = std::stoi(element);
my_map[map_index] = value;
map_index += 1;
// std::cout << value << std::endl;
// std::cout << map_index << std::endl;
// std::cout << my_map << std::endl;
}
void parse_config_map(std::string raw_input) {
// find "map": { "channels": [....]}
size_t start = std::string::npos;
start = raw_input.find("\"map\"");
// std::cout << "map start: '" << start << "'" << std::endl;
if (start != std::string::npos) {
// std::cout << "map found." << std::endl;
size_t start_channels = raw_input.find("\"channels\"", start);
// std::cout << "channels start: '" << start_channels << "'" << std::endl;
if (start_channels != std::string::npos) {
// std::cout << "channels found." << std::endl;
size_t end = raw_input.find('}', start_channels);
if (end != std::string::npos) {
// std::cout << "channels end found." << std::endl;
std::string channels_list = raw_input.substr(start+1, (end-1)-start);
// std::cout << "channels_list: '" << channels_list << "'" << std::endl;
parse_config_channels(channels_list);
} else {
std::cout
<< "Error in Config Format: 'channels' section end not found."
<< std::endl;
}
} else {
std::cout
<< "Error in Config Format: 'channels' section not found."
<< std::endl;
}
} else {
std::cout
<< "Error in Config Format: 'map' section not found."
<< std::endl;
}
}
int parse_value(std::string raw_input, std::string key_name) {
size_t start = std::string::npos;
size_t end = std::string::npos;
std::string value_raw;
int value = -1;
start = raw_input.find("\"" + key_name + "\"");
// std::cout << "start: '" << start << "'" << std::endl;
if (start != std::string::npos) {
end = raw_input.find_first_of(",}", start);
if (end != std::string::npos) {
// start + " + key_name + " + :
size_t value_content_start = start + 1 + key_name.length() + 1 + 1;
value_raw = raw_input.substr(
value_content_start,
(end)-value_content_start);
// std::cout << "value_raw: '" << value_raw << "'" << std::endl;
// now we can convert the element string to a int
value = std::stoi(value_raw);
} else {
std::cout
<< "Error in Config Format: '"
<< key_name
<< "' value end not found."
<< std::endl;
}
} else {
std::cout
<< "Error in Config Format: '"
<< key_name
<< "' value not found."
<< std::endl;
}
return value;
}
void parse_config_universe(std::string raw_input) {
// find "universe": { }
// std::cout << "raw_input: '" << raw_input << "'" << std::endl;
std::string key_name = "universe";
size_t start_section = raw_input.find("\""+key_name+"\"");
// std::cout << "start_section: '" << start_section << "'" << std::endl;
if (start_section != std::string::npos) {
size_t section_content_start = start_section + 1 + key_name.length();
std::string section_content = raw_input.substr(
section_content_start);
// find 'start_address'
uint16_t u_start_address = parse_value(section_content, "start_address");
// find 'channel_count'
uint16_t u_channel_count = parse_value(section_content, "channel_count");
// find 'input'
uint16_t u_input = parse_value(section_content, "input");
// find 'output'
uint16_t u_output = parse_value(section_content, "output");
// find 'rescale_max'
uint16_t u_rescale_max = parse_value(section_content, "rescale_max");
// done
std::cout << "start_address: " << u_start_address << std::endl;
std::cout << "input: " << u_input << std::endl;
std::cout << "output: " << u_output << std::endl;
std::cout << "channel_count: " << u_channel_count << std::endl;
std::cout << "rescale_max: " << u_rescale_max << std::endl;
universe_in_start_address = u_start_address;
universe_in = u_input;
universe_out = u_output;
universe_channel_count = u_channel_count;
universe_rescale_max = u_rescale_max;
std::cout << "universe_in_start_address: " << universe_in_start_address << std::endl;
std::cout << "universe_in: " << universe_in << std::endl;
std::cout << "universe_out: " << universe_out << std::endl;
std::cout << "universe_channel_count: " << universe_channel_count << std::endl;
std::cout << "universe_rescale_max: " << universe_rescale_max << std::endl;
} else {
std::cout
<< "Error in Config Format: 'universe' section not found."
<< std::endl;
}
}
// void read_config_from_file(std::string filename) {
void read_config_from_file() {
// std::string filename = "my_map.config";
std::ifstream myfile("./map.json");
if (myfile.is_open()) {
std::string line;
std::string raw_input;
// read in all lines and combine theme.
while ( std::getline(myfile, line) ) {
std::cout << line << std::endl;
raw_input += line;
}
myfile.close();
std::cout << std::endl;
std::cout << std::endl;
// ------------------------------------------
// now we can parse the input
// std::cout << "raw_input: '" << raw_input << "'" << std::endl;
// search and extract map
std::cout << "parse_config_map.."<< std::endl;
parse_config_map(raw_input);
// search and extract universe information
std::cout << "parse_config_universe.."<< std::endl;
parse_config_universe(raw_input);
std::cout << "parsing done."<< std::endl;
} else {
std::cout << "Unable to open file."<< std::endl;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// helper
void rescale_channels() {
for (
size_t channel_output_index = 0;
channel_output_index < universe_channel_count;
channel_output_index = channel_output_index +2
) {
uint8_t value_h = 0;
uint8_t value_l = 0;
uint16_t value = 0;
// get channel values
value_h = channels_out.Get(channel_output_index);
value_l = channels_out.Get(channel_output_index+1);
// combine to 16bit value
value = (value_h << 8) | value_l;
// rescale:
uint32_t value_calc = value * universe_rescale_max;
value = value_calc / 65535;
// splitt to 8itt values
value_h = value >> 8;
value_l = value;
// set channel values
channels_out.SetChannel(
channel_output_index,
value_h
);
channels_out.SetChannel(
channel_output_index+1,
value_l
);
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// mapping
// map data to new channels and send frame
void map_channels(const ola::DmxBuffer &data) {
for (
size_t channel_output_index = 0;
channel_output_index < universe_channel_count;
channel_output_index++
) {
int map_value = my_map[channel_output_index];
// check if map_value is
if (map_value > -1) {
// check if map_value is in range of input channels
if (map_value < (int)data.Size()) {
channels_out.SetChannel(
channel_output_index,
data.Get(map_value));
}
}
}
rescale_channels();
// std::cout << "Send frame: " << std::endl << channels_out << std::endl;
wrapper.GetClient()->SendDMX(
universe_out,
channels_out,
ola::client::SendDMXArgs());
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// ola things
// Called when universe registration completes.
void RegisterComplete(const ola::client::Result& result) {
if (!result.Success()) {
OLA_WARN << "Failed to register universe: " << result.Error();
}
}
// Called when new DMX data arrives.
void dmx_receive_frame(const ola::client::DMXMetadata &metadata,
const ola::DmxBuffer &data) {
// std::cout << "Received " << data.Size()
// << " channels for universe " << metadata.universe
// << ", priority " << static_cast<int>(metadata.priority)
// << std::endl;
map_channels(data);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// ola state helper
void ola_connection_closed(ola::io::SelectServer *ss) {
std::cerr << "Connection to olad was closed" << std::endl;
ss->Terminate();
system_state = state_waiting;
}
void ola_waiting_for_connection() {
bool flag_connected = false;
try {
std::cout << "try wrapper.Setup() " << std::endl;
bool available = wrapper.Setup();
std::cout << "available: " << available << std::endl;
if (available) {
flag_connected = true;
}
}
// catch (const std::exception &exc) {
// // catch anything thrown that derives from std::exception
// std::cerr << exc.what();
// std::cout << "error!!: " << exc.what() << std::endl;
// }
catch (...) {
// catch all
// sleep microseconds
// usleep(500000);
std::cout << "error!!: " << std::endl;
}
// }
if (flag_connected) {
client = wrapper.GetClient();
system_state = state_connected;
}
}
void ola_setup() {
client->SetCloseHandler(
ola::NewSingleCallback(
ola_connection_closed,
wrapper.GetSelectServer() ));
// clean channels_out buffer
channels_out.Blackout();
// Set the callback and register our interest in this universe
client->SetDMXCallback(ola::NewCallback(&dmx_receive_frame));
client->RegisterUniverse(
universe_in,
ola::client::REGISTER,
ola::NewSingleCallback(&RegisterComplete));
std::cout << "map incoming channels." << std::endl;
system_state = state_running;
}
void ola_run() {
// this call blocks:
wrapper.GetSelectServer()->Run();
// if this exits we switch back to waiting state:
std::cout << "map incoming channels." << std::endl;
system_state = state_waiting;
}
void ola_statemaschine() {
switch (system_state) {
case state_undefined : {
system_state = state_waiting;
} break;
case state_standby : {
system_state = state_waiting;
} break;
case state_waiting : {
ola_waiting_for_connection();
} break;
case state_connected : {
ola_setup();
} break;
case state_running : {
// attention! blocks untill error..
ola_run();
} break;
} // end switch
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// main
int main() {
ola::InitLogging(ola::OLA_LOG_INFO, ola::OLA_LOG_STDERR);
// read map from file:
// read_config_from_file("my_map.config");
read_config_from_file();
// while (flag_run) {
// ola_statemaschine()
// }
// manual cycle
std::cout << "ola_waiting_for_connection()" << std::endl;
ola_waiting_for_connection();
std::cout << "ola_setup()" << std::endl;
ola_setup();
std::cout << "ola_run()" << std::endl;
ola_run();
}
<commit_msg>initial wait works. now get the rewaiting to work...<commit_after>// Copyright (c) 2016 Stefan Krüger
// released under MIT (see LICENSE for details)
// based on example from
// http://docs.openlighting.org/ola/doc/latest/dmx_cpp_client_tutorial.html
// build for local:
// g++ -std=c++11 olamapper.cpp -o olamapper.out $(pkg-config --cflags --libs libola)
#include <ola/DmxBuffer.h>
#include <ola/Logging.h>
#include <ola/client/ClientWrapper.h>
#include <ola/io/SelectServer.h>
#include <unistd.h>
#include <string>
#include <iostream>
#include <fstream>
uint16_t universe_in = 1;
uint16_t universe_in_start_address = 1;
uint16_t universe_out = 2;
uint16_t universe_channel_count = 240;
uint16_t universe_rescale_max = 60000;
static const uint16_t channel_count_MAX = 512;
ola::client::OlaClientWrapper wrapper(false);
ola::client::OlaClient *client;
ola::DmxBuffer channels_out;
int my_map[channel_count_MAX];
enum ola_state_t {
state_undefined,
state_standby,
state_waiting,
state_connected,
state_running,
};
ola_state_t system_state = state_undefined;
bool flag_run = true;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// configuration things
void parse_config_channels(std::string raw_channels) {
// get part between []
size_t start = raw_channels.find('[');
size_t end = raw_channels.find(']');
raw_channels = raw_channels.substr(start+1, (end-1)-start);
// std::cout << "raw_channels: '" << raw_channels << "'" << std::endl;
// split at every ', '
start = 0;
end = 0;
size_t map_index = 0;
while ( (end = raw_channels.find(", ", start)) != std::string::npos ) {
std::string element = raw_channels.substr(start, end - start);
start = end + 1;
// std::cout << element << std::endl;
// now we can convert the element string to a int
int value;
value = std::stoi(element);
my_map[map_index] = value;
map_index += 1;
// std::cout << value << std::endl;
}
// handle last element
std::string element = raw_channels.substr(start);
int value;
value = std::stoi(element);
my_map[map_index] = value;
map_index += 1;
// std::cout << value << std::endl;
// std::cout << map_index << std::endl;
// std::cout << my_map << std::endl;
}
void parse_config_map(std::string raw_input) {
// find "map": { "channels": [....]}
size_t start = std::string::npos;
start = raw_input.find("\"map\"");
// std::cout << "map start: '" << start << "'" << std::endl;
if (start != std::string::npos) {
// std::cout << "map found." << std::endl;
size_t start_channels = raw_input.find("\"channels\"", start);
// std::cout << "channels start: '" << start_channels << "'" << std::endl;
if (start_channels != std::string::npos) {
// std::cout << "channels found." << std::endl;
size_t end = raw_input.find('}', start_channels);
if (end != std::string::npos) {
// std::cout << "channels end found." << std::endl;
std::string channels_list = raw_input.substr(start+1, (end-1)-start);
// std::cout << "channels_list: '" << channels_list << "'" << std::endl;
parse_config_channels(channels_list);
} else {
std::cout
<< "Error in Config Format: 'channels' section end not found."
<< std::endl;
}
} else {
std::cout
<< "Error in Config Format: 'channels' section not found."
<< std::endl;
}
} else {
std::cout
<< "Error in Config Format: 'map' section not found."
<< std::endl;
}
}
int parse_value(std::string raw_input, std::string key_name) {
size_t start = std::string::npos;
size_t end = std::string::npos;
std::string value_raw;
int value = -1;
start = raw_input.find("\"" + key_name + "\"");
// std::cout << "start: '" << start << "'" << std::endl;
if (start != std::string::npos) {
end = raw_input.find_first_of(",}", start);
if (end != std::string::npos) {
// start + " + key_name + " + :
size_t value_content_start = start + 1 + key_name.length() + 1 + 1;
value_raw = raw_input.substr(
value_content_start,
(end)-value_content_start);
// std::cout << "value_raw: '" << value_raw << "'" << std::endl;
// now we can convert the element string to a int
value = std::stoi(value_raw);
} else {
std::cout
<< "Error in Config Format: '"
<< key_name
<< "' value end not found."
<< std::endl;
}
} else {
std::cout
<< "Error in Config Format: '"
<< key_name
<< "' value not found."
<< std::endl;
}
return value;
}
void parse_config_universe(std::string raw_input) {
// find "universe": { }
// std::cout << "raw_input: '" << raw_input << "'" << std::endl;
std::string key_name = "universe";
size_t start_section = raw_input.find("\""+key_name+"\"");
// std::cout << "start_section: '" << start_section << "'" << std::endl;
if (start_section != std::string::npos) {
size_t section_content_start = start_section + 1 + key_name.length();
std::string section_content = raw_input.substr(
section_content_start);
// find 'start_address'
uint16_t u_start_address = parse_value(section_content, "start_address");
// find 'channel_count'
uint16_t u_channel_count = parse_value(section_content, "channel_count");
// find 'input'
uint16_t u_input = parse_value(section_content, "input");
// find 'output'
uint16_t u_output = parse_value(section_content, "output");
// find 'rescale_max'
uint16_t u_rescale_max = parse_value(section_content, "rescale_max");
// done
std::cout << "start_address: " << u_start_address << std::endl;
std::cout << "input: " << u_input << std::endl;
std::cout << "output: " << u_output << std::endl;
std::cout << "channel_count: " << u_channel_count << std::endl;
std::cout << "rescale_max: " << u_rescale_max << std::endl;
universe_in_start_address = u_start_address;
universe_in = u_input;
universe_out = u_output;
universe_channel_count = u_channel_count;
universe_rescale_max = u_rescale_max;
std::cout << "universe_in_start_address: " << universe_in_start_address << std::endl;
std::cout << "universe_in: " << universe_in << std::endl;
std::cout << "universe_out: " << universe_out << std::endl;
std::cout << "universe_channel_count: " << universe_channel_count << std::endl;
std::cout << "universe_rescale_max: " << universe_rescale_max << std::endl;
} else {
std::cout
<< "Error in Config Format: 'universe' section not found."
<< std::endl;
}
}
// void read_config_from_file(std::string filename) {
void read_config_from_file() {
// std::string filename = "my_map.config";
std::ifstream myfile("./map.json");
if (myfile.is_open()) {
std::string line;
std::string raw_input;
// read in all lines and combine theme.
while ( std::getline(myfile, line) ) {
std::cout << line << std::endl;
raw_input += line;
}
myfile.close();
std::cout << std::endl;
std::cout << std::endl;
// ------------------------------------------
// now we can parse the input
// std::cout << "raw_input: '" << raw_input << "'" << std::endl;
// search and extract map
std::cout << "parse_config_map.."<< std::endl;
parse_config_map(raw_input);
// search and extract universe information
std::cout << "parse_config_universe.."<< std::endl;
parse_config_universe(raw_input);
std::cout << "parsing done."<< std::endl;
} else {
std::cout << "Unable to open file."<< std::endl;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// helper
void rescale_channels() {
for (
size_t channel_output_index = 0;
channel_output_index < universe_channel_count;
channel_output_index = channel_output_index +2
) {
uint8_t value_h = 0;
uint8_t value_l = 0;
uint16_t value = 0;
// get channel values
value_h = channels_out.Get(channel_output_index);
value_l = channels_out.Get(channel_output_index+1);
// combine to 16bit value
value = (value_h << 8) | value_l;
// rescale:
uint32_t value_calc = value * universe_rescale_max;
value = value_calc / 65535;
// splitt to 8itt values
value_h = value >> 8;
value_l = value;
// set channel values
channels_out.SetChannel(
channel_output_index,
value_h
);
channels_out.SetChannel(
channel_output_index+1,
value_l
);
}
}
// helper for delay:
// http://www.cplusplus.com/forum/unices/10491/#msg49054
#if defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__WINDOWS__) || defined(__TOS_WIN__)
#include <windows.h>
inline void delay( unsigned long ms )
{
Sleep( ms );
}
#else /* presume POSIX */
#include <unistd.h>
inline void delay( unsigned long ms )
{
usleep( ms * 1000 );
}
#endif
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// mapping
// map data to new channels and send frame
void map_channels(const ola::DmxBuffer &data) {
for (
size_t channel_output_index = 0;
channel_output_index < universe_channel_count;
channel_output_index++
) {
int map_value = my_map[channel_output_index];
// check if map_value is
if (map_value > -1) {
// check if map_value is in range of input channels
if (map_value < (int)data.Size()) {
channels_out.SetChannel(
channel_output_index,
data.Get(map_value));
}
}
}
rescale_channels();
// std::cout << "Send frame: " << std::endl << channels_out << std::endl;
wrapper.GetClient()->SendDMX(
universe_out,
channels_out,
ola::client::SendDMXArgs());
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// ola things
// Called when universe registration completes.
void RegisterComplete(const ola::client::Result& result) {
if (!result.Success()) {
OLA_WARN << "Failed to register universe: " << result.Error();
}
}
// Called when new DMX data arrives.
void dmx_receive_frame(const ola::client::DMXMetadata &metadata,
const ola::DmxBuffer &data) {
// std::cout << "Received " << data.Size()
// << " channels for universe " << metadata.universe
// << ", priority " << static_cast<int>(metadata.priority)
// << std::endl;
map_channels(data);
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// ola state helper
void ola_connection_closed(ola::io::SelectServer *ss) {
std::cerr << "Connection to olad was closed" << std::endl;
// system_state = state_waiting;
// stop SelectServer
ss->Terminate();
}
void ola_waiting_for_connection() {
bool flag_connected = false;
// try {
// std::cout << "try wrapper.Setup() " << std::endl;
bool available = wrapper.Setup();
// std::cout << "available: " << available << std::endl;
if (available) {
flag_connected = true;
} else {
// wait 500ms till next request
delay(500);
}
// }
// catch (const std::exception &exc) {
// // catch anything thrown that derives from std::exception
// std::cerr << exc.what();
// std::cout << "error!!: " << exc.what() << std::endl;
// }
// catch (...) {
// // catch all
// // sleep microseconds
// // usleep(500000);
// std::cout << "error!!: " << std::endl;
// }
// }
std::cout << "flag_connected: " << flag_connected << std::endl;
if (flag_connected) {
// std::cout << "GetClient: " << std::endl;
client = wrapper.GetClient();
// std::cout << "switch to state_connected." << std::endl;
system_state = state_connected;
}
}
void ola_setup() {
client->SetCloseHandler(
ola::NewSingleCallback(
ola_connection_closed,
wrapper.GetSelectServer() ));
// clean channels_out buffer
channels_out.Blackout();
// Set the callback and register our interest in this universe
client->SetDMXCallback(ola::NewCallback(&dmx_receive_frame));
client->RegisterUniverse(
universe_in,
ola::client::REGISTER,
ola::NewSingleCallback(&RegisterComplete));
std::cout << "map incoming channels." << std::endl;
system_state = state_running;
}
void ola_run() {
// this call blocks:
wrapper.GetSelectServer()->Run();
// if this exits we switch back to waiting state:
std::cout << "SelectServer exited." << std::endl;
std::cout << "wrapper.Cleanup()" << std::endl;
wrapper.Cleanup();
// std::cout << "wrapper" << std::endl;
std::cout << "switching to state_waiting" << std::endl;
system_state = state_waiting;
}
void ola_statemaschine() {
switch (system_state) {
case state_undefined : {
system_state = state_waiting;
} break;
case state_standby : {
system_state = state_waiting;
} break;
case state_waiting : {
ola_waiting_for_connection();
} break;
case state_connected : {
ola_setup();
} break;
case state_running : {
// attention! blocks untill error..
ola_run();
} break;
} // end switch
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// main
int main() {
ola::InitLogging(ola::OLA_LOG_INFO, ola::OLA_LOG_STDERR);
// read map from file:
// read_config_from_file("my_map.config");
read_config_from_file();
bool flag_run = true;
while (flag_run) {
ola_statemaschine();
}
// manual cycle
// std::cout << "ola_waiting_for_connection()" << std::endl;
// ola_waiting_for_connection();
// std::cout << "ola_setup()" << std::endl;
// ola_setup();
// std::cout << "ola_run()" << std::endl;
// ola_run();
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/autocomplete/autocomplete_popup_model.h"
#include "unicode/ubidi.h"
#include "base/string_util.h"
#include "chrome/browser/autocomplete/autocomplete_edit.h"
#include "chrome/browser/autocomplete/autocomplete_match.h"
#include "chrome/browser/autocomplete/autocomplete_popup_view.h"
#include "chrome/browser/autocomplete/search_provider.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/search_engines/template_url.h"
#include "chrome/browser/search_engines/template_url_model.h"
#include "chrome/common/notification_service.h"
#include "gfx/rect.h"
///////////////////////////////////////////////////////////////////////////////
// AutocompletePopupModel
AutocompletePopupModel::AutocompletePopupModel(
AutocompletePopupView* popup_view,
AutocompleteEditModel* edit_model,
Profile* profile)
: view_(popup_view),
edit_model_(edit_model),
controller_(new AutocompleteController(profile)),
profile_(profile),
hovered_line_(kNoMatch),
selected_line_(kNoMatch) {
registrar_.Add(this, NotificationType::AUTOCOMPLETE_CONTROLLER_RESULT_UPDATED,
Source<AutocompleteController>(controller_.get()));
}
AutocompletePopupModel::~AutocompletePopupModel() {
}
void AutocompletePopupModel::SetProfile(Profile* profile) {
DCHECK(profile);
profile_ = profile;
controller_->SetProfile(profile);
}
void AutocompletePopupModel::StartAutocomplete(
const std::wstring& text,
const std::wstring& desired_tld,
bool prevent_inline_autocomplete,
bool prefer_keyword) {
// The user is interacting with the edit, so stop tracking hover.
SetHoveredLine(kNoMatch);
manually_selected_match_.Clear();
controller_->Start(text, desired_tld, prevent_inline_autocomplete,
prefer_keyword, true, false);
}
void AutocompletePopupModel::StopAutocomplete() {
controller_->Stop(true);
}
bool AutocompletePopupModel::IsOpen() const {
return view_->IsOpen();
}
void AutocompletePopupModel::SetHoveredLine(size_t line) {
const bool is_disabling = (line == kNoMatch);
DCHECK(is_disabling || (line < controller_->result().size()));
if (line == hovered_line_)
return; // Nothing to do
// Make sure the old hovered line is redrawn. No need to redraw the selected
// line since selection overrides hover so the appearance won't change.
if ((hovered_line_ != kNoMatch) && (hovered_line_ != selected_line_))
view_->InvalidateLine(hovered_line_);
// Change the hover to the new line.
hovered_line_ = line;
if (!is_disabling && (hovered_line_ != selected_line_))
view_->InvalidateLine(hovered_line_);
}
void AutocompletePopupModel::SetSelectedLine(size_t line,
bool reset_to_default) {
// We should at least be dealing with the results of the current query. Note
// that even if |line| was valid on entry, this may make it invalid. We clamp
// it below.
controller_->CommitIfQueryHasNeverBeenCommitted();
const AutocompleteResult& result = controller_->result();
if (result.empty())
return;
// Cancel the query so the matches don't change on the user.
controller_->Stop(false);
line = std::min(line, result.size() - 1);
const AutocompleteMatch& match = result.match_at(line);
if (reset_to_default) {
manually_selected_match_.Clear();
} else {
// Track the user's selection until they cancel it.
manually_selected_match_.destination_url = match.destination_url;
manually_selected_match_.provider_affinity = match.provider;
manually_selected_match_.is_history_what_you_typed_match =
match.is_history_what_you_typed_match;
}
if (line == selected_line_)
return; // Nothing else to do.
// We need to update |selected_line_| before calling OnPopupDataChanged(), so
// that when the edit notifies its controller that something has changed, the
// controller can get the correct updated data.
//
// NOTE: We should never reach here with no selected line; the same code that
// opened the popup and made it possible to get here should have also set a
// selected line.
CHECK(selected_line_ != kNoMatch);
GURL current_destination(result.match_at(selected_line_).destination_url);
view_->InvalidateLine(selected_line_);
selected_line_ = line;
view_->InvalidateLine(selected_line_);
// Update the edit with the new data for this match.
// TODO(pkasting): If |selected_line_| moves to the controller, this can be
// eliminated and just become a call to the observer on the edit.
std::wstring keyword;
const bool is_keyword_hint = GetKeywordForMatch(match, &keyword);
if (reset_to_default) {
std::wstring inline_autocomplete_text;
if ((match.inline_autocomplete_offset != std::wstring::npos) &&
(match.inline_autocomplete_offset < match.fill_into_edit.length())) {
inline_autocomplete_text =
match.fill_into_edit.substr(match.inline_autocomplete_offset);
}
edit_model_->OnPopupDataChanged(inline_autocomplete_text, NULL,
keyword, is_keyword_hint);
} else {
edit_model_->OnPopupDataChanged(match.fill_into_edit, ¤t_destination,
keyword, is_keyword_hint);
}
// Repaint old and new selected lines immediately, so that the edit doesn't
// appear to update [much] faster than the popup.
view_->PaintUpdatesNow();
}
void AutocompletePopupModel::ResetToDefaultMatch() {
const AutocompleteResult& result = controller_->result();
CHECK(!result.empty());
SetSelectedLine(result.default_match() - result.begin(), true);
view_->OnDragCanceled();
}
void AutocompletePopupModel::InfoForCurrentSelection(
AutocompleteMatch* match,
GURL* alternate_nav_url) const {
DCHECK(match != NULL);
const AutocompleteResult* result;
if (!controller_->done()) {
// NOTE: Using latest_result() is important here since not only could it
// contain newer results than result() for the current query, it could even
// refer to an entirely different query (e.g. if the user is typing rapidly
// and the controller is purposefully delaying updates to avoid flicker).
result = &controller_->latest_result();
// It's technically possible for |result| to be empty if no provider returns
// a synchronous result but the query has not completed synchronously;
// pratically, however, that should never actually happen.
if (result->empty())
return;
// The user cannot have manually selected a match, or the query would have
// stopped. So the default match must be the desired selection.
*match = *result->default_match();
} else {
CHECK(IsOpen());
// The query isn't running, so the standard result set can't possibly be out
// of date.
//
// NOTE: In practice, it should actually be safe to use
// controller_->latest_result() here too, since the controller keeps that
// up-to-date. However we generally try to avoid referring to that.
result = &controller_->result();
// If there are no results, the popup should be closed (so we should have
// failed the CHECK above), and URLsForDefaultMatch() should have been
// called instead.
CHECK(!result->empty());
CHECK(selected_line_ < result->size());
*match = result->match_at(selected_line_);
}
if (alternate_nav_url && manually_selected_match_.empty())
*alternate_nav_url = result->alternate_nav_url();
}
bool AutocompletePopupModel::GetKeywordForMatch(const AutocompleteMatch& match,
std::wstring* keyword) const {
// Assume we have no keyword until we find otherwise.
keyword->clear();
// If the current match is a keyword, return that as the selected keyword.
if (TemplateURL::SupportsReplacement(match.template_url)) {
keyword->assign(match.template_url->keyword());
return false;
}
// See if the current match's fill_into_edit corresponds to a keyword.
if (!profile_->GetTemplateURLModel())
return false;
profile_->GetTemplateURLModel()->Load();
const std::wstring keyword_hint(
TemplateURLModel::CleanUserInputKeyword(match.fill_into_edit));
if (keyword_hint.empty())
return false;
// Don't provide a hint if this keyword doesn't support replacement.
const TemplateURL* const template_url =
profile_->GetTemplateURLModel()->GetTemplateURLForKeyword(keyword_hint);
if (!TemplateURL::SupportsReplacement(template_url))
return false;
// Don't provide a hint if this is an extension keyword not enabled for
// incognito mode (and if this is an incognito profile).
if (template_url->IsExtensionKeyword() && profile_->IsOffTheRecord()) {
const Extension* extension = profile_->GetExtensionsService()->
GetExtensionById(template_url->GetExtensionId(), false);
if (!profile_->GetExtensionsService()->IsIncognitoEnabled(extension))
return false;
}
keyword->assign(keyword_hint);
return true;
}
void AutocompletePopupModel::FinalizeInstantQuery(const std::wstring& text) {
if (IsOpen()) {
SearchProvider* search_provider = controller_->search_provider();
search_provider->FinalizeInstantQuery(text);
}
}
AutocompleteLog* AutocompletePopupModel::GetAutocompleteLog() {
return new AutocompleteLog(controller_->input().text(),
controller_->input().type(), selected_line_, 0, controller_->result());
}
void AutocompletePopupModel::Move(int count) {
const AutocompleteResult& result = controller_->result();
if (result.empty())
return;
// The user is using the keyboard to change the selection, so stop tracking
// hover.
SetHoveredLine(kNoMatch);
// Clamp the new line to [0, result_.count() - 1].
const size_t new_line = selected_line_ + count;
SetSelectedLine(((count < 0) && (new_line >= selected_line_)) ? 0 : new_line,
false);
}
void AutocompletePopupModel::TryDeletingCurrentItem() {
// We could use InfoForCurrentSelection() here, but it seems better to try
// and shift-delete the actual selection, rather than any "in progress, not
// yet visible" one.
if (selected_line_ == kNoMatch)
return;
// Cancel the query so the matches don't change on the user.
controller_->Stop(false);
const AutocompleteMatch& match =
controller_->result().match_at(selected_line_);
if (match.deletable) {
const size_t selected_line = selected_line_;
controller_->DeleteMatch(match); // This may synchronously notify us that
// the results have changed.
const AutocompleteResult& result = controller_->result();
if (!result.empty()) {
// Move the selection to the next choice after the deleted one.
// SetSelectedLine() will clamp to take care of the case where we deleted
// the last item.
// TODO(pkasting): Eventually the controller should take care of this
// before notifying us, reducing flicker. At that point the check for
// deletability can move there too.
SetSelectedLine(selected_line, false);
}
}
}
void AutocompletePopupModel::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK_EQ(NotificationType::AUTOCOMPLETE_CONTROLLER_RESULT_UPDATED,
type.value);
const AutocompleteResult* result =
Details<const AutocompleteResult>(details).ptr();
selected_line_ = result->default_match() == result->end() ?
kNoMatch : static_cast<size_t>(result->default_match() - result->begin());
// There had better not be a nonempty result set with no default match.
CHECK((selected_line_ != kNoMatch) || result->empty());
// If we're going to trim the window size to no longer include the hovered
// line, turn hover off. Practically, this shouldn't happen, but it
// doesn't hurt to be defensive.
if ((hovered_line_ != kNoMatch) && (result->size() <= hovered_line_))
SetHoveredLine(kNoMatch);
view_->UpdatePopupAppearance();
edit_model_->ResultsUpdated();
edit_model_->PopupBoundsChangedTo(view_->GetTargetBounds());
}
const SkBitmap* AutocompletePopupModel::GetSpecialIconForMatch(
const AutocompleteMatch& match) const {
if (!match.template_url || !match.template_url->IsExtensionKeyword())
return NULL;
return &profile_->GetExtensionsService()->GetOmniboxPopupIcon(
match.template_url->GetExtensionId());
}
<commit_msg>Fix a browser crash when typing a disabled extension keyword in an incognito window's URL bar.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/autocomplete/autocomplete_popup_model.h"
#include "unicode/ubidi.h"
#include "base/string_util.h"
#include "chrome/browser/autocomplete/autocomplete_edit.h"
#include "chrome/browser/autocomplete/autocomplete_match.h"
#include "chrome/browser/autocomplete/autocomplete_popup_view.h"
#include "chrome/browser/autocomplete/search_provider.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/search_engines/template_url.h"
#include "chrome/browser/search_engines/template_url_model.h"
#include "chrome/common/notification_service.h"
#include "gfx/rect.h"
///////////////////////////////////////////////////////////////////////////////
// AutocompletePopupModel
AutocompletePopupModel::AutocompletePopupModel(
AutocompletePopupView* popup_view,
AutocompleteEditModel* edit_model,
Profile* profile)
: view_(popup_view),
edit_model_(edit_model),
controller_(new AutocompleteController(profile)),
profile_(profile),
hovered_line_(kNoMatch),
selected_line_(kNoMatch) {
registrar_.Add(this, NotificationType::AUTOCOMPLETE_CONTROLLER_RESULT_UPDATED,
Source<AutocompleteController>(controller_.get()));
}
AutocompletePopupModel::~AutocompletePopupModel() {
}
void AutocompletePopupModel::SetProfile(Profile* profile) {
DCHECK(profile);
profile_ = profile;
controller_->SetProfile(profile);
}
void AutocompletePopupModel::StartAutocomplete(
const std::wstring& text,
const std::wstring& desired_tld,
bool prevent_inline_autocomplete,
bool prefer_keyword) {
// The user is interacting with the edit, so stop tracking hover.
SetHoveredLine(kNoMatch);
manually_selected_match_.Clear();
controller_->Start(text, desired_tld, prevent_inline_autocomplete,
prefer_keyword, true, false);
}
void AutocompletePopupModel::StopAutocomplete() {
controller_->Stop(true);
}
bool AutocompletePopupModel::IsOpen() const {
return view_->IsOpen();
}
void AutocompletePopupModel::SetHoveredLine(size_t line) {
const bool is_disabling = (line == kNoMatch);
DCHECK(is_disabling || (line < controller_->result().size()));
if (line == hovered_line_)
return; // Nothing to do
// Make sure the old hovered line is redrawn. No need to redraw the selected
// line since selection overrides hover so the appearance won't change.
if ((hovered_line_ != kNoMatch) && (hovered_line_ != selected_line_))
view_->InvalidateLine(hovered_line_);
// Change the hover to the new line.
hovered_line_ = line;
if (!is_disabling && (hovered_line_ != selected_line_))
view_->InvalidateLine(hovered_line_);
}
void AutocompletePopupModel::SetSelectedLine(size_t line,
bool reset_to_default) {
// We should at least be dealing with the results of the current query. Note
// that even if |line| was valid on entry, this may make it invalid. We clamp
// it below.
controller_->CommitIfQueryHasNeverBeenCommitted();
const AutocompleteResult& result = controller_->result();
if (result.empty())
return;
// Cancel the query so the matches don't change on the user.
controller_->Stop(false);
line = std::min(line, result.size() - 1);
const AutocompleteMatch& match = result.match_at(line);
if (reset_to_default) {
manually_selected_match_.Clear();
} else {
// Track the user's selection until they cancel it.
manually_selected_match_.destination_url = match.destination_url;
manually_selected_match_.provider_affinity = match.provider;
manually_selected_match_.is_history_what_you_typed_match =
match.is_history_what_you_typed_match;
}
if (line == selected_line_)
return; // Nothing else to do.
// We need to update |selected_line_| before calling OnPopupDataChanged(), so
// that when the edit notifies its controller that something has changed, the
// controller can get the correct updated data.
//
// NOTE: We should never reach here with no selected line; the same code that
// opened the popup and made it possible to get here should have also set a
// selected line.
CHECK(selected_line_ != kNoMatch);
GURL current_destination(result.match_at(selected_line_).destination_url);
view_->InvalidateLine(selected_line_);
selected_line_ = line;
view_->InvalidateLine(selected_line_);
// Update the edit with the new data for this match.
// TODO(pkasting): If |selected_line_| moves to the controller, this can be
// eliminated and just become a call to the observer on the edit.
std::wstring keyword;
const bool is_keyword_hint = GetKeywordForMatch(match, &keyword);
if (reset_to_default) {
std::wstring inline_autocomplete_text;
if ((match.inline_autocomplete_offset != std::wstring::npos) &&
(match.inline_autocomplete_offset < match.fill_into_edit.length())) {
inline_autocomplete_text =
match.fill_into_edit.substr(match.inline_autocomplete_offset);
}
edit_model_->OnPopupDataChanged(inline_autocomplete_text, NULL,
keyword, is_keyword_hint);
} else {
edit_model_->OnPopupDataChanged(match.fill_into_edit, ¤t_destination,
keyword, is_keyword_hint);
}
// Repaint old and new selected lines immediately, so that the edit doesn't
// appear to update [much] faster than the popup.
view_->PaintUpdatesNow();
}
void AutocompletePopupModel::ResetToDefaultMatch() {
const AutocompleteResult& result = controller_->result();
CHECK(!result.empty());
SetSelectedLine(result.default_match() - result.begin(), true);
view_->OnDragCanceled();
}
void AutocompletePopupModel::InfoForCurrentSelection(
AutocompleteMatch* match,
GURL* alternate_nav_url) const {
DCHECK(match != NULL);
const AutocompleteResult* result;
if (!controller_->done()) {
// NOTE: Using latest_result() is important here since not only could it
// contain newer results than result() for the current query, it could even
// refer to an entirely different query (e.g. if the user is typing rapidly
// and the controller is purposefully delaying updates to avoid flicker).
result = &controller_->latest_result();
// It's technically possible for |result| to be empty if no provider returns
// a synchronous result but the query has not completed synchronously;
// pratically, however, that should never actually happen.
if (result->empty())
return;
// The user cannot have manually selected a match, or the query would have
// stopped. So the default match must be the desired selection.
*match = *result->default_match();
} else {
CHECK(IsOpen());
// The query isn't running, so the standard result set can't possibly be out
// of date.
//
// NOTE: In practice, it should actually be safe to use
// controller_->latest_result() here too, since the controller keeps that
// up-to-date. However we generally try to avoid referring to that.
result = &controller_->result();
// If there are no results, the popup should be closed (so we should have
// failed the CHECK above), and URLsForDefaultMatch() should have been
// called instead.
CHECK(!result->empty());
CHECK(selected_line_ < result->size());
*match = result->match_at(selected_line_);
}
if (alternate_nav_url && manually_selected_match_.empty())
*alternate_nav_url = result->alternate_nav_url();
}
bool AutocompletePopupModel::GetKeywordForMatch(const AutocompleteMatch& match,
std::wstring* keyword) const {
// Assume we have no keyword until we find otherwise.
keyword->clear();
// If the current match is a keyword, return that as the selected keyword.
if (TemplateURL::SupportsReplacement(match.template_url)) {
keyword->assign(match.template_url->keyword());
return false;
}
// See if the current match's fill_into_edit corresponds to a keyword.
if (!profile_->GetTemplateURLModel())
return false;
profile_->GetTemplateURLModel()->Load();
const std::wstring keyword_hint(
TemplateURLModel::CleanUserInputKeyword(match.fill_into_edit));
if (keyword_hint.empty())
return false;
// Don't provide a hint if this keyword doesn't support replacement.
const TemplateURL* const template_url =
profile_->GetTemplateURLModel()->GetTemplateURLForKeyword(keyword_hint);
if (!TemplateURL::SupportsReplacement(template_url))
return false;
// Don't provide a hint for inactive/disabled extension keywords.
if (template_url->IsExtensionKeyword()) {
const Extension* extension = profile_->GetExtensionsService()->
GetExtensionById(template_url->GetExtensionId(), false);
if (!extension ||
(profile_->IsOffTheRecord() &&
!profile_->GetExtensionsService()->IsIncognitoEnabled(extension)))
return false;
}
keyword->assign(keyword_hint);
return true;
}
void AutocompletePopupModel::FinalizeInstantQuery(const std::wstring& text) {
if (IsOpen()) {
SearchProvider* search_provider = controller_->search_provider();
search_provider->FinalizeInstantQuery(text);
}
}
AutocompleteLog* AutocompletePopupModel::GetAutocompleteLog() {
return new AutocompleteLog(controller_->input().text(),
controller_->input().type(), selected_line_, 0, controller_->result());
}
void AutocompletePopupModel::Move(int count) {
const AutocompleteResult& result = controller_->result();
if (result.empty())
return;
// The user is using the keyboard to change the selection, so stop tracking
// hover.
SetHoveredLine(kNoMatch);
// Clamp the new line to [0, result_.count() - 1].
const size_t new_line = selected_line_ + count;
SetSelectedLine(((count < 0) && (new_line >= selected_line_)) ? 0 : new_line,
false);
}
void AutocompletePopupModel::TryDeletingCurrentItem() {
// We could use InfoForCurrentSelection() here, but it seems better to try
// and shift-delete the actual selection, rather than any "in progress, not
// yet visible" one.
if (selected_line_ == kNoMatch)
return;
// Cancel the query so the matches don't change on the user.
controller_->Stop(false);
const AutocompleteMatch& match =
controller_->result().match_at(selected_line_);
if (match.deletable) {
const size_t selected_line = selected_line_;
controller_->DeleteMatch(match); // This may synchronously notify us that
// the results have changed.
const AutocompleteResult& result = controller_->result();
if (!result.empty()) {
// Move the selection to the next choice after the deleted one.
// SetSelectedLine() will clamp to take care of the case where we deleted
// the last item.
// TODO(pkasting): Eventually the controller should take care of this
// before notifying us, reducing flicker. At that point the check for
// deletability can move there too.
SetSelectedLine(selected_line, false);
}
}
}
void AutocompletePopupModel::Observe(NotificationType type,
const NotificationSource& source,
const NotificationDetails& details) {
DCHECK_EQ(NotificationType::AUTOCOMPLETE_CONTROLLER_RESULT_UPDATED,
type.value);
const AutocompleteResult* result =
Details<const AutocompleteResult>(details).ptr();
selected_line_ = result->default_match() == result->end() ?
kNoMatch : static_cast<size_t>(result->default_match() - result->begin());
// There had better not be a nonempty result set with no default match.
CHECK((selected_line_ != kNoMatch) || result->empty());
// If we're going to trim the window size to no longer include the hovered
// line, turn hover off. Practically, this shouldn't happen, but it
// doesn't hurt to be defensive.
if ((hovered_line_ != kNoMatch) && (result->size() <= hovered_line_))
SetHoveredLine(kNoMatch);
view_->UpdatePopupAppearance();
edit_model_->ResultsUpdated();
edit_model_->PopupBoundsChangedTo(view_->GetTargetBounds());
}
const SkBitmap* AutocompletePopupModel::GetSpecialIconForMatch(
const AutocompleteMatch& match) const {
if (!match.template_url || !match.template_url->IsExtensionKeyword())
return NULL;
return &profile_->GetExtensionsService()->GetOmniboxPopupIcon(
match.template_url->GetExtensionId());
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/automation/url_request_automation_job.h"
#include "base/message_loop.h"
#include "base/time.h"
#include "chrome/browser/automation/automation_resource_message_filter.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
#include "chrome/browser/renderer_host/resource_dispatcher_host_request_info.h"
#include "chrome/test/automation/automation_messages.h"
#include "net/base/cookie_monster.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/http/http_request_headers.h"
#include "net/http/http_util.h"
#include "net/url_request/url_request_context.h"
using base::Time;
using base::TimeDelta;
// The list of filtered headers that are removed from requests sent via
// StartAsync(). These must be lower case.
static const char* const kFilteredHeaderStrings[] = {
"accept",
"cache-control",
"connection",
"cookie",
"expect",
"max-forwards",
"proxy-authorization",
"te",
"upgrade",
"via"
};
int URLRequestAutomationJob::instance_count_ = 0;
bool URLRequestAutomationJob::is_protocol_factory_registered_ = false;
URLRequest::ProtocolFactory* URLRequestAutomationJob::old_http_factory_
= NULL;
URLRequest::ProtocolFactory* URLRequestAutomationJob::old_https_factory_
= NULL;
URLRequestAutomationJob::URLRequestAutomationJob(URLRequest* request, int tab,
int request_id, AutomationResourceMessageFilter* filter, bool is_pending)
: URLRequestJob(request),
tab_(tab),
message_filter_(filter),
pending_buf_size_(0),
redirect_status_(0),
request_id_(request_id),
is_pending_(is_pending) {
DLOG(INFO) << "URLRequestAutomationJob create. Count: " << ++instance_count_;
DCHECK(message_filter_ != NULL);
if (message_filter_) {
id_ = message_filter_->NewAutomationRequestId();
DCHECK_NE(id_, 0);
}
}
URLRequestAutomationJob::~URLRequestAutomationJob() {
DLOG(INFO) << "URLRequestAutomationJob delete. Count: " << --instance_count_;
Cleanup();
}
bool URLRequestAutomationJob::EnsureProtocolFactoryRegistered() {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));
if (!is_protocol_factory_registered_) {
old_http_factory_ =
URLRequest::RegisterProtocolFactory("http",
&URLRequestAutomationJob::Factory);
old_https_factory_ =
URLRequest::RegisterProtocolFactory("https",
&URLRequestAutomationJob::Factory);
is_protocol_factory_registered_ = true;
}
return true;
}
URLRequestJob* URLRequestAutomationJob::Factory(URLRequest* request,
const std::string& scheme) {
bool scheme_is_http = request->url().SchemeIs("http");
bool scheme_is_https = request->url().SchemeIs("https");
// Returning null here just means that the built-in handler will be used.
if (scheme_is_http || scheme_is_https) {
ResourceDispatcherHostRequestInfo* request_info =
ResourceDispatcherHost::InfoForRequest(request);
if (request_info) {
int child_id = request_info->child_id();
int route_id = request_info->route_id();
if (request_info->process_type() == ChildProcessInfo::PLUGIN_PROCESS) {
child_id = request_info->host_renderer_id();
route_id = request_info->host_render_view_id();
}
AutomationResourceMessageFilter::AutomationDetails details;
if (AutomationResourceMessageFilter::LookupRegisteredRenderView(
child_id, route_id, &details)) {
URLRequestAutomationJob* job = new URLRequestAutomationJob(request,
details.tab_handle, request_info->request_id(), details.filter,
details.is_pending_render_view);
return job;
}
}
if (scheme_is_http && old_http_factory_)
return old_http_factory_(request, scheme);
else if (scheme_is_https && old_https_factory_)
return old_https_factory_(request, scheme);
}
return NULL;
}
// URLRequestJob Implementation.
void URLRequestAutomationJob::Start() {
if (!is_pending()) {
// Start reading asynchronously so that all error reporting and data
// callbacks happen as they would for network requests.
MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(
this, &URLRequestAutomationJob::StartAsync));
} else {
// If this is a pending job, then register it immediately with the message
// filter so it can be serviced later when we receive a request from the
// external host to connect to the corresponding external tab.
message_filter_->RegisterRequest(this);
}
}
void URLRequestAutomationJob::Kill() {
if (message_filter_.get()) {
if (!is_pending()) {
message_filter_->Send(new AutomationMsg_RequestEnd(0, tab_, id_,
URLRequestStatus(URLRequestStatus::CANCELED, net::ERR_ABORTED)));
}
}
DisconnectFromMessageFilter();
URLRequestJob::Kill();
}
bool URLRequestAutomationJob::ReadRawData(
net::IOBuffer* buf, int buf_size, int* bytes_read) {
DLOG(INFO) << "URLRequestAutomationJob: " <<
request_->url().spec() << " - read pending: " << buf_size;
// We should not receive a read request for a pending job.
DCHECK(!is_pending());
pending_buf_ = buf;
pending_buf_size_ = buf_size;
if (message_filter_) {
message_filter_->Send(new AutomationMsg_RequestRead(0, tab_, id_,
buf_size));
SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));
} else {
ChromeThread::PostTask(ChromeThread::IO, FROM_HERE,
NewRunnableMethod(this,
&URLRequestAutomationJob::NotifyJobCompletionTask));
}
return false;
}
bool URLRequestAutomationJob::GetMimeType(std::string* mime_type) const {
if (!mime_type_.empty()) {
*mime_type = mime_type_;
} else if (headers_) {
headers_->GetMimeType(mime_type);
}
return (!mime_type->empty());
}
bool URLRequestAutomationJob::GetCharset(std::string* charset) {
if (headers_)
return headers_->GetCharset(charset);
return false;
}
void URLRequestAutomationJob::GetResponseInfo(net::HttpResponseInfo* info) {
if (headers_)
info->headers = headers_;
if (request_->url().SchemeIsSecure()) {
// Make up a fake certificate for this response since we don't have
// access to the real SSL info.
const char* kCertIssuer = "Chrome Internal";
const int kLifetimeDays = 100;
info->ssl_info.cert =
new net::X509Certificate(request_->url().GetWithEmptyPath().spec(),
kCertIssuer,
Time::Now(),
Time::Now() +
TimeDelta::FromDays(kLifetimeDays));
info->ssl_info.cert_status = 0;
info->ssl_info.security_bits = 0;
}
}
int URLRequestAutomationJob::GetResponseCode() const {
if (headers_)
return headers_->response_code();
static const int kDefaultResponseCode = 200;
return kDefaultResponseCode;
}
bool URLRequestAutomationJob::IsRedirectResponse(
GURL* location, int* http_status_code) {
if (!net::HttpResponseHeaders::IsRedirectResponseCode(redirect_status_))
return false;
*http_status_code = redirect_status_;
*location = GURL(redirect_url_);
return true;
}
bool URLRequestAutomationJob::MayFilterMessage(const IPC::Message& message,
int* request_id) {
switch (message.type()) {
case AutomationMsg_RequestStarted::ID:
case AutomationMsg_RequestData::ID:
case AutomationMsg_RequestEnd::ID: {
void* iter = NULL;
int tab = 0;
if (message.ReadInt(&iter, &tab) &&
message.ReadInt(&iter, request_id)) {
return true;
}
break;
}
}
return false;
}
void URLRequestAutomationJob::OnMessage(const IPC::Message& message) {
if (!request_) {
NOTREACHED() << __FUNCTION__
<< ": Unexpected request received for job:"
<< id();
return;
}
IPC_BEGIN_MESSAGE_MAP(URLRequestAutomationJob, message)
IPC_MESSAGE_HANDLER(AutomationMsg_RequestStarted, OnRequestStarted)
IPC_MESSAGE_HANDLER(AutomationMsg_RequestData, OnDataAvailable)
IPC_MESSAGE_HANDLER(AutomationMsg_RequestEnd, OnRequestEnd)
IPC_END_MESSAGE_MAP()
}
void URLRequestAutomationJob::OnRequestStarted(int tab, int id,
const IPC::AutomationURLResponse& response) {
DLOG(INFO) << "URLRequestAutomationJob: " <<
request_->url().spec() << " - response started.";
set_expected_content_size(response.content_length);
mime_type_ = response.mime_type;
redirect_url_ = response.redirect_url;
redirect_status_ = response.redirect_status;
DCHECK(redirect_status_ == 0 || redirect_status_ == 200 ||
(redirect_status_ >= 300 && redirect_status_ < 400));
if (!response.headers.empty()) {
headers_ = new net::HttpResponseHeaders(
net::HttpUtil::AssembleRawHeaders(response.headers.data(),
response.headers.size()));
}
NotifyHeadersComplete();
}
void URLRequestAutomationJob::OnDataAvailable(
int tab, int id, const std::string& bytes) {
DLOG(INFO) << "URLRequestAutomationJob: " <<
request_->url().spec() << " - data available, Size: " << bytes.size();
DCHECK(!bytes.empty());
// The request completed, and we have all the data.
// Clear any IO pending status.
SetStatus(URLRequestStatus());
if (pending_buf_ && pending_buf_->data()) {
DCHECK_GE(pending_buf_size_, bytes.size());
const int bytes_to_copy = std::min(bytes.size(), pending_buf_size_);
memcpy(pending_buf_->data(), &bytes[0], bytes_to_copy);
pending_buf_ = NULL;
pending_buf_size_ = 0;
NotifyReadComplete(bytes_to_copy);
} else {
NOTREACHED() << "Received unexpected data of length:" << bytes.size();
}
}
void URLRequestAutomationJob::OnRequestEnd(
int tab, int id, const URLRequestStatus& status) {
#ifndef NDEBUG
std::string url;
if (request_)
url = request_->url().spec();
DLOG(INFO) << "URLRequestAutomationJob: "
<< url << " - request end. Status: " << status.status();
#endif
// TODO(tommi): When we hit certificate errors, notify the delegate via
// OnSSLCertificateError(). Right now we don't have the certificate
// so we don't. We could possibly call OnSSLCertificateError with a NULL
// certificate, but I'm not sure if all implementations expect it.
// if (status.status() == URLRequestStatus::FAILED &&
// net::IsCertificateError(status.os_error()) && request_->delegate()) {
// request_->delegate()->OnSSLCertificateError(request_, status.os_error());
// }
DisconnectFromMessageFilter();
// NotifyDone may have been called on the job if the original request was
// redirected.
if (!is_done()) {
// We can complete the job if we have a valid response or a pending read.
// An end request can be received in the following cases
// 1. We failed to connect to the server, in which case we did not receive
// a valid response.
// 2. In response to a read request.
if (!has_response_started() || pending_buf_) {
NotifyDone(status);
} else {
// Wait for the http stack to issue a Read request where we will notify
// that the job has completed.
request_status_ = status;
return;
}
}
// Reset any pending reads.
if (pending_buf_) {
pending_buf_ = NULL;
pending_buf_size_ = 0;
NotifyReadComplete(0);
}
}
void URLRequestAutomationJob::Cleanup() {
headers_ = NULL;
mime_type_.erase();
id_ = 0;
tab_ = 0;
DCHECK(message_filter_ == NULL);
DisconnectFromMessageFilter();
pending_buf_ = NULL;
pending_buf_size_ = 0;
}
void URLRequestAutomationJob::StartAsync() {
DLOG(INFO) << "URLRequestAutomationJob: start request: " <<
(request_ ? request_->url().spec() : "NULL request");
// If the job is cancelled before we got a chance to start it
// we have nothing much to do here.
if (is_done())
return;
// We should not receive a Start request for a pending job.
DCHECK(!is_pending());
if (!request_) {
NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED,
net::ERR_FAILED));
return;
}
// Register this request with automation message filter.
message_filter_->RegisterRequest(this);
// Strip unwanted headers.
net::HttpRequestHeaders new_request_headers;
new_request_headers.MergeFrom(request_->extra_request_headers());
for (size_t i = 0; i < arraysize(kFilteredHeaderStrings); ++i)
new_request_headers.RemoveHeader(kFilteredHeaderStrings[i]);
if (request_->context()) {
// Only add default Accept-Language and Accept-Charset if the request
// didn't have them specified.
if (!new_request_headers.HasHeader(
net::HttpRequestHeaders::kAcceptLanguage) &&
!request_->context()->accept_language().empty()) {
new_request_headers.SetHeader(net::HttpRequestHeaders::kAcceptLanguage,
request_->context()->accept_language());
}
if (!new_request_headers.HasHeader(
net::HttpRequestHeaders::kAcceptCharset) &&
!request_->context()->accept_charset().empty()) {
new_request_headers.SetHeader(net::HttpRequestHeaders::kAcceptCharset,
request_->context()->accept_charset());
}
}
// Ensure that we do not send username and password fields in the referrer.
GURL referrer(request_->GetSanitizedReferrer());
// The referrer header must be suppressed if the preceding URL was
// a secure one and the new one is not.
if (referrer.SchemeIsSecure() && !request_->url().SchemeIsSecure()) {
DLOG(INFO) <<
"Suppressing referrer header since going from secure to non-secure";
referrer = GURL();
}
// Ask automation to start this request.
IPC::AutomationURLRequest automation_request = {
request_->url().spec(),
request_->method(),
referrer.spec(),
new_request_headers.ToString(),
request_->get_upload()
};
DCHECK(message_filter_);
message_filter_->Send(new AutomationMsg_RequestStart(0, tab_, id_,
automation_request));
}
void URLRequestAutomationJob::DisconnectFromMessageFilter() {
if (message_filter_) {
message_filter_->UnRegisterRequest(this);
message_filter_ = NULL;
}
}
void URLRequestAutomationJob::StartPendingJob(
int new_tab_handle,
AutomationResourceMessageFilter* new_filter) {
DCHECK(new_filter != NULL);
tab_ = new_tab_handle;
message_filter_ = new_filter;
is_pending_ = false;
Start();
}
void URLRequestAutomationJob::NotifyJobCompletionTask() {
if (!is_done()) {
NotifyDone(request_status_);
}
// Reset any pending reads.
if (pending_buf_) {
pending_buf_ = NULL;
pending_buf_size_ = 0;
NotifyReadComplete(0);
}
}
<commit_msg>Coverity issue 8297: Uninitialized member in url_request_automation_job.cc<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/automation/url_request_automation_job.h"
#include "base/message_loop.h"
#include "base/time.h"
#include "chrome/browser/automation/automation_resource_message_filter.h"
#include "chrome/browser/chrome_thread.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
#include "chrome/browser/renderer_host/resource_dispatcher_host_request_info.h"
#include "chrome/test/automation/automation_messages.h"
#include "net/base/cookie_monster.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/http/http_request_headers.h"
#include "net/http/http_util.h"
#include "net/url_request/url_request_context.h"
using base::Time;
using base::TimeDelta;
// The list of filtered headers that are removed from requests sent via
// StartAsync(). These must be lower case.
static const char* const kFilteredHeaderStrings[] = {
"accept",
"cache-control",
"connection",
"cookie",
"expect",
"max-forwards",
"proxy-authorization",
"te",
"upgrade",
"via"
};
int URLRequestAutomationJob::instance_count_ = 0;
bool URLRequestAutomationJob::is_protocol_factory_registered_ = false;
URLRequest::ProtocolFactory* URLRequestAutomationJob::old_http_factory_
= NULL;
URLRequest::ProtocolFactory* URLRequestAutomationJob::old_https_factory_
= NULL;
URLRequestAutomationJob::URLRequestAutomationJob(URLRequest* request, int tab,
int request_id, AutomationResourceMessageFilter* filter, bool is_pending)
: URLRequestJob(request),
id_(0),
tab_(tab),
message_filter_(filter),
pending_buf_size_(0),
redirect_status_(0),
request_id_(request_id),
is_pending_(is_pending) {
DLOG(INFO) << "URLRequestAutomationJob create. Count: " << ++instance_count_;
DCHECK(message_filter_ != NULL);
if (message_filter_) {
id_ = message_filter_->NewAutomationRequestId();
DCHECK_NE(id_, 0);
}
}
URLRequestAutomationJob::~URLRequestAutomationJob() {
DLOG(INFO) << "URLRequestAutomationJob delete. Count: " << --instance_count_;
Cleanup();
}
bool URLRequestAutomationJob::EnsureProtocolFactoryRegistered() {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::IO));
if (!is_protocol_factory_registered_) {
old_http_factory_ =
URLRequest::RegisterProtocolFactory("http",
&URLRequestAutomationJob::Factory);
old_https_factory_ =
URLRequest::RegisterProtocolFactory("https",
&URLRequestAutomationJob::Factory);
is_protocol_factory_registered_ = true;
}
return true;
}
URLRequestJob* URLRequestAutomationJob::Factory(URLRequest* request,
const std::string& scheme) {
bool scheme_is_http = request->url().SchemeIs("http");
bool scheme_is_https = request->url().SchemeIs("https");
// Returning null here just means that the built-in handler will be used.
if (scheme_is_http || scheme_is_https) {
ResourceDispatcherHostRequestInfo* request_info =
ResourceDispatcherHost::InfoForRequest(request);
if (request_info) {
int child_id = request_info->child_id();
int route_id = request_info->route_id();
if (request_info->process_type() == ChildProcessInfo::PLUGIN_PROCESS) {
child_id = request_info->host_renderer_id();
route_id = request_info->host_render_view_id();
}
AutomationResourceMessageFilter::AutomationDetails details;
if (AutomationResourceMessageFilter::LookupRegisteredRenderView(
child_id, route_id, &details)) {
URLRequestAutomationJob* job = new URLRequestAutomationJob(request,
details.tab_handle, request_info->request_id(), details.filter,
details.is_pending_render_view);
return job;
}
}
if (scheme_is_http && old_http_factory_)
return old_http_factory_(request, scheme);
else if (scheme_is_https && old_https_factory_)
return old_https_factory_(request, scheme);
}
return NULL;
}
// URLRequestJob Implementation.
void URLRequestAutomationJob::Start() {
if (!is_pending()) {
// Start reading asynchronously so that all error reporting and data
// callbacks happen as they would for network requests.
MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod(
this, &URLRequestAutomationJob::StartAsync));
} else {
// If this is a pending job, then register it immediately with the message
// filter so it can be serviced later when we receive a request from the
// external host to connect to the corresponding external tab.
message_filter_->RegisterRequest(this);
}
}
void URLRequestAutomationJob::Kill() {
if (message_filter_.get()) {
if (!is_pending()) {
message_filter_->Send(new AutomationMsg_RequestEnd(0, tab_, id_,
URLRequestStatus(URLRequestStatus::CANCELED, net::ERR_ABORTED)));
}
}
DisconnectFromMessageFilter();
URLRequestJob::Kill();
}
bool URLRequestAutomationJob::ReadRawData(
net::IOBuffer* buf, int buf_size, int* bytes_read) {
DLOG(INFO) << "URLRequestAutomationJob: " <<
request_->url().spec() << " - read pending: " << buf_size;
// We should not receive a read request for a pending job.
DCHECK(!is_pending());
pending_buf_ = buf;
pending_buf_size_ = buf_size;
if (message_filter_) {
message_filter_->Send(new AutomationMsg_RequestRead(0, tab_, id_,
buf_size));
SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));
} else {
ChromeThread::PostTask(ChromeThread::IO, FROM_HERE,
NewRunnableMethod(this,
&URLRequestAutomationJob::NotifyJobCompletionTask));
}
return false;
}
bool URLRequestAutomationJob::GetMimeType(std::string* mime_type) const {
if (!mime_type_.empty()) {
*mime_type = mime_type_;
} else if (headers_) {
headers_->GetMimeType(mime_type);
}
return (!mime_type->empty());
}
bool URLRequestAutomationJob::GetCharset(std::string* charset) {
if (headers_)
return headers_->GetCharset(charset);
return false;
}
void URLRequestAutomationJob::GetResponseInfo(net::HttpResponseInfo* info) {
if (headers_)
info->headers = headers_;
if (request_->url().SchemeIsSecure()) {
// Make up a fake certificate for this response since we don't have
// access to the real SSL info.
const char* kCertIssuer = "Chrome Internal";
const int kLifetimeDays = 100;
info->ssl_info.cert =
new net::X509Certificate(request_->url().GetWithEmptyPath().spec(),
kCertIssuer,
Time::Now(),
Time::Now() +
TimeDelta::FromDays(kLifetimeDays));
info->ssl_info.cert_status = 0;
info->ssl_info.security_bits = 0;
}
}
int URLRequestAutomationJob::GetResponseCode() const {
if (headers_)
return headers_->response_code();
static const int kDefaultResponseCode = 200;
return kDefaultResponseCode;
}
bool URLRequestAutomationJob::IsRedirectResponse(
GURL* location, int* http_status_code) {
if (!net::HttpResponseHeaders::IsRedirectResponseCode(redirect_status_))
return false;
*http_status_code = redirect_status_;
*location = GURL(redirect_url_);
return true;
}
bool URLRequestAutomationJob::MayFilterMessage(const IPC::Message& message,
int* request_id) {
switch (message.type()) {
case AutomationMsg_RequestStarted::ID:
case AutomationMsg_RequestData::ID:
case AutomationMsg_RequestEnd::ID: {
void* iter = NULL;
int tab = 0;
if (message.ReadInt(&iter, &tab) &&
message.ReadInt(&iter, request_id)) {
return true;
}
break;
}
}
return false;
}
void URLRequestAutomationJob::OnMessage(const IPC::Message& message) {
if (!request_) {
NOTREACHED() << __FUNCTION__
<< ": Unexpected request received for job:"
<< id();
return;
}
IPC_BEGIN_MESSAGE_MAP(URLRequestAutomationJob, message)
IPC_MESSAGE_HANDLER(AutomationMsg_RequestStarted, OnRequestStarted)
IPC_MESSAGE_HANDLER(AutomationMsg_RequestData, OnDataAvailable)
IPC_MESSAGE_HANDLER(AutomationMsg_RequestEnd, OnRequestEnd)
IPC_END_MESSAGE_MAP()
}
void URLRequestAutomationJob::OnRequestStarted(int tab, int id,
const IPC::AutomationURLResponse& response) {
DLOG(INFO) << "URLRequestAutomationJob: " <<
request_->url().spec() << " - response started.";
set_expected_content_size(response.content_length);
mime_type_ = response.mime_type;
redirect_url_ = response.redirect_url;
redirect_status_ = response.redirect_status;
DCHECK(redirect_status_ == 0 || redirect_status_ == 200 ||
(redirect_status_ >= 300 && redirect_status_ < 400));
if (!response.headers.empty()) {
headers_ = new net::HttpResponseHeaders(
net::HttpUtil::AssembleRawHeaders(response.headers.data(),
response.headers.size()));
}
NotifyHeadersComplete();
}
void URLRequestAutomationJob::OnDataAvailable(
int tab, int id, const std::string& bytes) {
DLOG(INFO) << "URLRequestAutomationJob: " <<
request_->url().spec() << " - data available, Size: " << bytes.size();
DCHECK(!bytes.empty());
// The request completed, and we have all the data.
// Clear any IO pending status.
SetStatus(URLRequestStatus());
if (pending_buf_ && pending_buf_->data()) {
DCHECK_GE(pending_buf_size_, bytes.size());
const int bytes_to_copy = std::min(bytes.size(), pending_buf_size_);
memcpy(pending_buf_->data(), &bytes[0], bytes_to_copy);
pending_buf_ = NULL;
pending_buf_size_ = 0;
NotifyReadComplete(bytes_to_copy);
} else {
NOTREACHED() << "Received unexpected data of length:" << bytes.size();
}
}
void URLRequestAutomationJob::OnRequestEnd(
int tab, int id, const URLRequestStatus& status) {
#ifndef NDEBUG
std::string url;
if (request_)
url = request_->url().spec();
DLOG(INFO) << "URLRequestAutomationJob: "
<< url << " - request end. Status: " << status.status();
#endif
// TODO(tommi): When we hit certificate errors, notify the delegate via
// OnSSLCertificateError(). Right now we don't have the certificate
// so we don't. We could possibly call OnSSLCertificateError with a NULL
// certificate, but I'm not sure if all implementations expect it.
// if (status.status() == URLRequestStatus::FAILED &&
// net::IsCertificateError(status.os_error()) && request_->delegate()) {
// request_->delegate()->OnSSLCertificateError(request_, status.os_error());
// }
DisconnectFromMessageFilter();
// NotifyDone may have been called on the job if the original request was
// redirected.
if (!is_done()) {
// We can complete the job if we have a valid response or a pending read.
// An end request can be received in the following cases
// 1. We failed to connect to the server, in which case we did not receive
// a valid response.
// 2. In response to a read request.
if (!has_response_started() || pending_buf_) {
NotifyDone(status);
} else {
// Wait for the http stack to issue a Read request where we will notify
// that the job has completed.
request_status_ = status;
return;
}
}
// Reset any pending reads.
if (pending_buf_) {
pending_buf_ = NULL;
pending_buf_size_ = 0;
NotifyReadComplete(0);
}
}
void URLRequestAutomationJob::Cleanup() {
headers_ = NULL;
mime_type_.erase();
id_ = 0;
tab_ = 0;
DCHECK(message_filter_ == NULL);
DisconnectFromMessageFilter();
pending_buf_ = NULL;
pending_buf_size_ = 0;
}
void URLRequestAutomationJob::StartAsync() {
DLOG(INFO) << "URLRequestAutomationJob: start request: " <<
(request_ ? request_->url().spec() : "NULL request");
// If the job is cancelled before we got a chance to start it
// we have nothing much to do here.
if (is_done())
return;
// We should not receive a Start request for a pending job.
DCHECK(!is_pending());
if (!request_) {
NotifyStartError(URLRequestStatus(URLRequestStatus::FAILED,
net::ERR_FAILED));
return;
}
// Register this request with automation message filter.
message_filter_->RegisterRequest(this);
// Strip unwanted headers.
net::HttpRequestHeaders new_request_headers;
new_request_headers.MergeFrom(request_->extra_request_headers());
for (size_t i = 0; i < arraysize(kFilteredHeaderStrings); ++i)
new_request_headers.RemoveHeader(kFilteredHeaderStrings[i]);
if (request_->context()) {
// Only add default Accept-Language and Accept-Charset if the request
// didn't have them specified.
if (!new_request_headers.HasHeader(
net::HttpRequestHeaders::kAcceptLanguage) &&
!request_->context()->accept_language().empty()) {
new_request_headers.SetHeader(net::HttpRequestHeaders::kAcceptLanguage,
request_->context()->accept_language());
}
if (!new_request_headers.HasHeader(
net::HttpRequestHeaders::kAcceptCharset) &&
!request_->context()->accept_charset().empty()) {
new_request_headers.SetHeader(net::HttpRequestHeaders::kAcceptCharset,
request_->context()->accept_charset());
}
}
// Ensure that we do not send username and password fields in the referrer.
GURL referrer(request_->GetSanitizedReferrer());
// The referrer header must be suppressed if the preceding URL was
// a secure one and the new one is not.
if (referrer.SchemeIsSecure() && !request_->url().SchemeIsSecure()) {
DLOG(INFO) <<
"Suppressing referrer header since going from secure to non-secure";
referrer = GURL();
}
// Ask automation to start this request.
IPC::AutomationURLRequest automation_request = {
request_->url().spec(),
request_->method(),
referrer.spec(),
new_request_headers.ToString(),
request_->get_upload()
};
DCHECK(message_filter_);
message_filter_->Send(new AutomationMsg_RequestStart(0, tab_, id_,
automation_request));
}
void URLRequestAutomationJob::DisconnectFromMessageFilter() {
if (message_filter_) {
message_filter_->UnRegisterRequest(this);
message_filter_ = NULL;
}
}
void URLRequestAutomationJob::StartPendingJob(
int new_tab_handle,
AutomationResourceMessageFilter* new_filter) {
DCHECK(new_filter != NULL);
tab_ = new_tab_handle;
message_filter_ = new_filter;
is_pending_ = false;
Start();
}
void URLRequestAutomationJob::NotifyJobCompletionTask() {
if (!is_done()) {
NotifyDone(request_status_);
}
// Reset any pending reads.
if (pending_buf_) {
pending_buf_ = NULL;
pending_buf_size_ = 0;
NotifyReadComplete(0);
}
}
<|endoftext|>
|
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/chrome_restart_request.h"
#include <vector>
#include "ash/ash_switches.h"
#include "base/chromeos/chromeos_version.h"
#include "base/command_line.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/prefs/json_pref_store.h"
#include "base/prefs/pref_service.h"
#include "base/process_util.h"
#include "base/stringprintf.h"
#include "base/strings/string_split.h"
#include "base/timer.h"
#include "base/values.h"
#include "cc/base/switches.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/lifetime/application_lifetime.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chromeos/chromeos_switches.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/session_manager_client.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_switches.h"
#include "googleurl/src/gurl.h"
#include "gpu/command_buffer/service/gpu_switches.h"
#include "media/base/media_switches.h"
#include "ui/base/ui_base_switches.h"
#include "ui/compositor/compositor_switches.h"
#include "ui/gfx/switches.h"
#include "ui/gl/gl_switches.h"
#include "ui/views/corewm/corewm_switches.h"
#include "webkit/plugins/plugin_switches.h"
using content::BrowserThread;
namespace chromeos {
namespace {
// Increase logging level for Guest mode to avoid LOG(INFO) messages in logs.
const char kGuestModeLoggingLevel[] = "1";
// Format of command line switch.
const char kSwitchFormatString[] = " --%s=\"%s\"";
// User name which is used in the Guest session.
const char kGuestUserName[] = "";
// Derives the new command line from |base_command_line| by doing the following:
// - Forward a given switches list to new command;
// - Set start url if given;
// - Append/override switches using |new_switches|;
std::string DeriveCommandLine(const GURL& start_url,
const CommandLine& base_command_line,
const base::DictionaryValue& new_switches,
CommandLine* command_line) {
DCHECK_NE(&base_command_line, command_line);
static const char* kForwardSwitches[] = {
::switches::kAllowWebUICompositing,
::switches::kDeviceManagementUrl,
::switches::kDisableAccelerated2dCanvas,
::switches::kDisableAcceleratedOverflowScroll,
::switches::kDisableAcceleratedPlugins,
::switches::kDisableAcceleratedVideoDecode,
::switches::kDisableBrowserPluginCompositing,
::switches::kDisableEncryptedMedia,
::switches::kDisableForceCompositingMode,
::switches::kDisableGpuShaderDiskCache,
::switches::kDisableGpuWatchdog,
::switches::kDisableLoginAnimations,
::switches::kDisableOobeAnimation,
::switches::kDisablePanelFitting,
::switches::kDisableSeccompFilterSandbox,
::switches::kDisableSeccompSandbox,
::switches::kDisableThreadedCompositing,
::switches::kEnableAcceleratedOverflowScroll,
::switches::kEnableCompositingForFixedPosition,
::switches::kEnableGestureTapHighlight,
::switches::kDisableGestureTapHighlight,
::switches::kEnableLogging,
::switches::kEnablePinch,
::switches::kEnableThreadedCompositing,
::switches::kEnableViewport,
::switches::kEnableVsyncNotification,
::switches::kForceDeviceScaleFactor,
::switches::kGpuStartupDialog,
::switches::kHasChromeOSDiamondKey,
::switches::kHasChromeOSKeyboard,
::switches::kNaturalScrollDefault,
::switches::kNoSandbox,
::switches::kPpapiFlashArgs,
::switches::kPpapiFlashInProcess,
::switches::kPpapiFlashPath,
::switches::kPpapiFlashVersion,
::switches::kPpapiInProcess,
::switches::kRendererStartupDialog,
#if defined(USE_XI2_MT)
::switches::kTouchCalibration,
#endif
::switches::kTouchDevices,
::switches::kTouchEvents,
::switches::kTouchOptimizedUI,
::switches::kUIDisableThreadedCompositing,
::switches::kUIMaxFramesPending,
::switches::kUIPrioritizeInGpuProcess,
#if defined(USE_CRAS)
::switches::kUseCras,
#endif
::switches::kUseGL,
::switches::kUserDataDir,
::switches::kUseExynosVda,
::switches::kV,
ash::switches::kAshTouchHud,
ash::switches::kAuraLegacyPowerButton,
ash::switches::kAshDisableNewNetworkStatusArea,
ash::switches::kAshEnableNewAudioHandler,
// Please keep these in alphabetical order. Non-UI Compositor switches
// here should also be added to
// content/browser/renderer_host/render_process_host_impl.cc.
cc::switches::kBackgroundColorInsteadOfCheckerboard,
cc::switches::kCompositeToMailbox,
cc::switches::kDisableCheapnessEstimator,
cc::switches::kDisableColorEstimator,
cc::switches::kDisableImplSidePainting,
cc::switches::kDisablePinchZoomScrollbars,
cc::switches::kDisableThreadedAnimation,
cc::switches::kEnableCompositorFrameMessage,
cc::switches::kEnableImplSidePainting,
cc::switches::kEnablePartialSwap,
cc::switches::kEnablePerTilePainting,
cc::switches::kEnablePinchZoomScrollbars,
cc::switches::kEnablePredictionBenchmarking,
cc::switches::kEnableRightAlignedScheduling,
cc::switches::kEnableTopControlsPositionCalculation,
cc::switches::kLowResolutionContentsScaleFactor,
cc::switches::kMaxTilesForInterestArea,
cc::switches::kMaxUnusedResourceMemoryUsagePercentage,
cc::switches::kNumRasterThreads,
cc::switches::kShowCompositedLayerBorders,
cc::switches::kShowCompositedLayerTree,
cc::switches::kShowFPSCounter,
cc::switches::kShowNonOccludingRects,
cc::switches::kShowOccludingRects,
cc::switches::kShowPropertyChangedRects,
cc::switches::kShowReplicaScreenSpaceRects,
cc::switches::kShowScreenSpaceRects,
cc::switches::kShowSurfaceDamageRects,
cc::switches::kSlowDownRasterScaleFactor,
cc::switches::kTraceAllRenderedFrames,
cc::switches::kTraceOverdraw,
cc::switches::kUIDisablePartialSwap,
cc::switches::kUIEnablePerTilePainting,
chromeos::switches::kDbusStub,
chromeos::switches::kLoginProfile,
gfx::switches::kEnableBrowserTextSubpixelPositioning,
gfx::switches::kEnableWebkitTextSubpixelPositioning,
views::corewm::switches::kNoDropShadows,
views::corewm::switches::kWindowAnimationsDisabled,
};
command_line->CopySwitchesFrom(base_command_line,
kForwardSwitches,
arraysize(kForwardSwitches));
if (start_url.is_valid())
command_line->AppendArg(start_url.spec());
for (base::DictionaryValue::Iterator it(new_switches);
!it.IsAtEnd();
it.Advance()) {
std::string value;
CHECK(it.value().GetAsString(&value));
command_line->AppendSwitchASCII(it.key(), value);
}
std::string cmd_line_str = command_line->GetCommandLineString();
// Special workaround for the arguments that should be quoted.
// Copying switches won't be needed when Guest mode won't need restart
// http://crosbug.com/6924
if (base_command_line.HasSwitch(::switches::kRegisterPepperPlugins)) {
cmd_line_str += base::StringPrintf(
kSwitchFormatString,
::switches::kRegisterPepperPlugins,
base_command_line.GetSwitchValueNative(
::switches::kRegisterPepperPlugins).c_str());
}
// TODO(zelidrag): Remove this hack that get us around compositing bug from
// http://crbug.com/179256 once that bug is resolved.
if (command_line->HasSwitch(::switches::kForceAppMode)) {
std::string switch_to_remove("--");
switch_to_remove.append(cc::switches::kEnablePartialSwap);
cmd_line_str = cmd_line_str.replace(cmd_line_str.find(switch_to_remove),
switch_to_remove.length(), "");
}
return cmd_line_str;
}
// Simulates a session manager restart by launching give command line
// and exit current process.
void ReLaunch(const std::string& command_line) {
std::vector<std::string> argv;
// This is not a proper way to get |argv| but it's good enough for debugging.
base::SplitString(command_line, ' ', &argv);
base::LaunchProcess(argv, base::LaunchOptions(), NULL);
chrome::AttemptUserExit();
}
// Empty function that run by the local state task runner to ensure last
// commit goes through.
void EnsureLocalStateIsWritten() {}
// Wraps the work of sending chrome restart request to session manager.
// If local state is present, try to commit it first. The request is fired when
// the commit goes through or some time (3 seconds) has elapsed.
class ChromeRestartRequest
: public base::SupportsWeakPtr<ChromeRestartRequest> {
public:
explicit ChromeRestartRequest(const std::string& command_line);
~ChromeRestartRequest();
// Starts the request.
void Start();
private:
// Fires job restart request to session manager.
void RestartJob();
const int pid_;
const std::string command_line_;
base::OneShotTimer<ChromeRestartRequest> timer_;
DISALLOW_COPY_AND_ASSIGN(ChromeRestartRequest);
};
ChromeRestartRequest::ChromeRestartRequest(const std::string& command_line)
: pid_(getpid()),
command_line_(command_line) {}
ChromeRestartRequest::~ChromeRestartRequest() {}
void ChromeRestartRequest::Start() {
VLOG(1) << "Requesting a restart with PID " << pid_
<< " and command line: " << command_line_;
// Session Manager may kill the chrome anytime after this point.
// Write exit_cleanly and other stuff to the disk here.
g_browser_process->EndSession();
PrefService* local_state = g_browser_process->local_state();
if (!local_state) {
RestartJob();
return;
}
// XXX: normally this call must not be needed, however RestartJob
// just kills us so settings may be lost. See http://crosbug.com/13102
local_state->CommitPendingWrite();
timer_.Start(
FROM_HERE, base::TimeDelta::FromSeconds(3), this,
&ChromeRestartRequest::RestartJob);
// Post a task to local state task runner thus it occurs last on the task
// queue, so it would be executed after committing pending write on that
// thread.
scoped_refptr<base::SequencedTaskRunner> local_state_task_runner =
JsonPrefStore::GetTaskRunnerForFile(
base::FilePath(chrome::kLocalStorePoolName),
BrowserThread::GetBlockingPool());
local_state_task_runner->PostTaskAndReply(
FROM_HERE,
base::Bind(&EnsureLocalStateIsWritten),
base::Bind(&ChromeRestartRequest::RestartJob, AsWeakPtr()));
}
void ChromeRestartRequest::RestartJob() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DBusThreadManager::Get()->GetSessionManagerClient()->RestartJob(
pid_, command_line_);
delete this;
}
} // namespace
std::string GetOffTheRecordCommandLine(
const GURL& start_url,
const CommandLine& base_command_line,
CommandLine* command_line) {
base::DictionaryValue otr_switches;
otr_switches.SetString(switches::kGuestSession, std::string());
otr_switches.SetString(::switches::kIncognito, std::string());
otr_switches.SetString(::switches::kLoggingLevel, kGuestModeLoggingLevel);
otr_switches.SetString(switches::kLoginUser, kGuestUserName);
// Override the home page.
otr_switches.SetString(::switches::kHomePage,
GURL(chrome::kChromeUINewTabURL).spec());
return DeriveCommandLine(start_url,
base_command_line,
otr_switches,
command_line);
}
void RestartChrome(const std::string& command_line) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
static bool restart_requested = false;
if (restart_requested) {
NOTREACHED() << "Request chrome restart for more than once.";
}
restart_requested = true;
if (!base::chromeos::IsRunningOnChromeOS()) {
// Relaunch chrome without session manager on dev box.
ReLaunch(command_line);
return;
}
// ChromeRestartRequest deletes itself after request sent to session manager.
(new ChromeRestartRequest(command_line))->Start();
}
} // namespace chromeos
<commit_msg>Pass '--{disable,enable}-gpu-sandbox' to Guest mode.<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/login/chrome_restart_request.h"
#include <vector>
#include "ash/ash_switches.h"
#include "base/chromeos/chromeos_version.h"
#include "base/command_line.h"
#include "base/memory/weak_ptr.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/prefs/json_pref_store.h"
#include "base/prefs/pref_service.h"
#include "base/process_util.h"
#include "base/stringprintf.h"
#include "base/strings/string_split.h"
#include "base/timer.h"
#include "base/values.h"
#include "cc/base/switches.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/lifetime/application_lifetime.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chromeos/chromeos_switches.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/session_manager_client.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_switches.h"
#include "googleurl/src/gurl.h"
#include "gpu/command_buffer/service/gpu_switches.h"
#include "media/base/media_switches.h"
#include "ui/base/ui_base_switches.h"
#include "ui/compositor/compositor_switches.h"
#include "ui/gfx/switches.h"
#include "ui/gl/gl_switches.h"
#include "ui/views/corewm/corewm_switches.h"
#include "webkit/plugins/plugin_switches.h"
using content::BrowserThread;
namespace chromeos {
namespace {
// Increase logging level for Guest mode to avoid LOG(INFO) messages in logs.
const char kGuestModeLoggingLevel[] = "1";
// Format of command line switch.
const char kSwitchFormatString[] = " --%s=\"%s\"";
// User name which is used in the Guest session.
const char kGuestUserName[] = "";
// Derives the new command line from |base_command_line| by doing the following:
// - Forward a given switches list to new command;
// - Set start url if given;
// - Append/override switches using |new_switches|;
std::string DeriveCommandLine(const GURL& start_url,
const CommandLine& base_command_line,
const base::DictionaryValue& new_switches,
CommandLine* command_line) {
DCHECK_NE(&base_command_line, command_line);
static const char* kForwardSwitches[] = {
::switches::kAllowWebUICompositing,
::switches::kDeviceManagementUrl,
::switches::kDisableAccelerated2dCanvas,
::switches::kDisableAcceleratedOverflowScroll,
::switches::kDisableAcceleratedPlugins,
::switches::kDisableAcceleratedVideoDecode,
::switches::kDisableBrowserPluginCompositing,
::switches::kDisableEncryptedMedia,
::switches::kDisableForceCompositingMode,
::switches::kDisableGpuShaderDiskCache,
::switches::kDisableGpuWatchdog,
::switches::kDisableLoginAnimations,
::switches::kDisableOobeAnimation,
::switches::kDisablePanelFitting,
::switches::kDisableSeccompFilterSandbox,
::switches::kDisableSeccompSandbox,
::switches::kDisableThreadedCompositing,
::switches::kEnableAcceleratedOverflowScroll,
::switches::kEnableCompositingForFixedPosition,
::switches::kEnableGestureTapHighlight,
::switches::kDisableGestureTapHighlight,
::switches::kDisableGpuSandbox,
::switches::kEnableGpuSandbox,
::switches::kEnableLogging,
::switches::kEnablePinch,
::switches::kEnableThreadedCompositing,
::switches::kEnableViewport,
::switches::kEnableVsyncNotification,
::switches::kForceDeviceScaleFactor,
::switches::kGpuStartupDialog,
::switches::kHasChromeOSDiamondKey,
::switches::kHasChromeOSKeyboard,
::switches::kNaturalScrollDefault,
::switches::kNoSandbox,
::switches::kPpapiFlashArgs,
::switches::kPpapiFlashInProcess,
::switches::kPpapiFlashPath,
::switches::kPpapiFlashVersion,
::switches::kPpapiInProcess,
::switches::kRendererStartupDialog,
#if defined(USE_XI2_MT)
::switches::kTouchCalibration,
#endif
::switches::kTouchDevices,
::switches::kTouchEvents,
::switches::kTouchOptimizedUI,
::switches::kUIDisableThreadedCompositing,
::switches::kUIMaxFramesPending,
::switches::kUIPrioritizeInGpuProcess,
#if defined(USE_CRAS)
::switches::kUseCras,
#endif
::switches::kUseGL,
::switches::kUserDataDir,
::switches::kUseExynosVda,
::switches::kV,
ash::switches::kAshTouchHud,
ash::switches::kAuraLegacyPowerButton,
ash::switches::kAshDisableNewNetworkStatusArea,
ash::switches::kAshEnableNewAudioHandler,
// Please keep these in alphabetical order. Non-UI Compositor switches
// here should also be added to
// content/browser/renderer_host/render_process_host_impl.cc.
cc::switches::kBackgroundColorInsteadOfCheckerboard,
cc::switches::kCompositeToMailbox,
cc::switches::kDisableCheapnessEstimator,
cc::switches::kDisableColorEstimator,
cc::switches::kDisableImplSidePainting,
cc::switches::kDisablePinchZoomScrollbars,
cc::switches::kDisableThreadedAnimation,
cc::switches::kEnableCompositorFrameMessage,
cc::switches::kEnableImplSidePainting,
cc::switches::kEnablePartialSwap,
cc::switches::kEnablePerTilePainting,
cc::switches::kEnablePinchZoomScrollbars,
cc::switches::kEnablePredictionBenchmarking,
cc::switches::kEnableRightAlignedScheduling,
cc::switches::kEnableTopControlsPositionCalculation,
cc::switches::kLowResolutionContentsScaleFactor,
cc::switches::kMaxTilesForInterestArea,
cc::switches::kMaxUnusedResourceMemoryUsagePercentage,
cc::switches::kNumRasterThreads,
cc::switches::kShowCompositedLayerBorders,
cc::switches::kShowCompositedLayerTree,
cc::switches::kShowFPSCounter,
cc::switches::kShowNonOccludingRects,
cc::switches::kShowOccludingRects,
cc::switches::kShowPropertyChangedRects,
cc::switches::kShowReplicaScreenSpaceRects,
cc::switches::kShowScreenSpaceRects,
cc::switches::kShowSurfaceDamageRects,
cc::switches::kSlowDownRasterScaleFactor,
cc::switches::kTraceAllRenderedFrames,
cc::switches::kTraceOverdraw,
cc::switches::kUIDisablePartialSwap,
cc::switches::kUIEnablePerTilePainting,
chromeos::switches::kDbusStub,
chromeos::switches::kLoginProfile,
gfx::switches::kEnableBrowserTextSubpixelPositioning,
gfx::switches::kEnableWebkitTextSubpixelPositioning,
views::corewm::switches::kNoDropShadows,
views::corewm::switches::kWindowAnimationsDisabled,
};
command_line->CopySwitchesFrom(base_command_line,
kForwardSwitches,
arraysize(kForwardSwitches));
if (start_url.is_valid())
command_line->AppendArg(start_url.spec());
for (base::DictionaryValue::Iterator it(new_switches);
!it.IsAtEnd();
it.Advance()) {
std::string value;
CHECK(it.value().GetAsString(&value));
command_line->AppendSwitchASCII(it.key(), value);
}
std::string cmd_line_str = command_line->GetCommandLineString();
// Special workaround for the arguments that should be quoted.
// Copying switches won't be needed when Guest mode won't need restart
// http://crosbug.com/6924
if (base_command_line.HasSwitch(::switches::kRegisterPepperPlugins)) {
cmd_line_str += base::StringPrintf(
kSwitchFormatString,
::switches::kRegisterPepperPlugins,
base_command_line.GetSwitchValueNative(
::switches::kRegisterPepperPlugins).c_str());
}
// TODO(zelidrag): Remove this hack that get us around compositing bug from
// http://crbug.com/179256 once that bug is resolved.
if (command_line->HasSwitch(::switches::kForceAppMode)) {
std::string switch_to_remove("--");
switch_to_remove.append(cc::switches::kEnablePartialSwap);
cmd_line_str = cmd_line_str.replace(cmd_line_str.find(switch_to_remove),
switch_to_remove.length(), "");
}
return cmd_line_str;
}
// Simulates a session manager restart by launching give command line
// and exit current process.
void ReLaunch(const std::string& command_line) {
std::vector<std::string> argv;
// This is not a proper way to get |argv| but it's good enough for debugging.
base::SplitString(command_line, ' ', &argv);
base::LaunchProcess(argv, base::LaunchOptions(), NULL);
chrome::AttemptUserExit();
}
// Empty function that run by the local state task runner to ensure last
// commit goes through.
void EnsureLocalStateIsWritten() {}
// Wraps the work of sending chrome restart request to session manager.
// If local state is present, try to commit it first. The request is fired when
// the commit goes through or some time (3 seconds) has elapsed.
class ChromeRestartRequest
: public base::SupportsWeakPtr<ChromeRestartRequest> {
public:
explicit ChromeRestartRequest(const std::string& command_line);
~ChromeRestartRequest();
// Starts the request.
void Start();
private:
// Fires job restart request to session manager.
void RestartJob();
const int pid_;
const std::string command_line_;
base::OneShotTimer<ChromeRestartRequest> timer_;
DISALLOW_COPY_AND_ASSIGN(ChromeRestartRequest);
};
ChromeRestartRequest::ChromeRestartRequest(const std::string& command_line)
: pid_(getpid()),
command_line_(command_line) {}
ChromeRestartRequest::~ChromeRestartRequest() {}
void ChromeRestartRequest::Start() {
VLOG(1) << "Requesting a restart with PID " << pid_
<< " and command line: " << command_line_;
// Session Manager may kill the chrome anytime after this point.
// Write exit_cleanly and other stuff to the disk here.
g_browser_process->EndSession();
PrefService* local_state = g_browser_process->local_state();
if (!local_state) {
RestartJob();
return;
}
// XXX: normally this call must not be needed, however RestartJob
// just kills us so settings may be lost. See http://crosbug.com/13102
local_state->CommitPendingWrite();
timer_.Start(
FROM_HERE, base::TimeDelta::FromSeconds(3), this,
&ChromeRestartRequest::RestartJob);
// Post a task to local state task runner thus it occurs last on the task
// queue, so it would be executed after committing pending write on that
// thread.
scoped_refptr<base::SequencedTaskRunner> local_state_task_runner =
JsonPrefStore::GetTaskRunnerForFile(
base::FilePath(chrome::kLocalStorePoolName),
BrowserThread::GetBlockingPool());
local_state_task_runner->PostTaskAndReply(
FROM_HERE,
base::Bind(&EnsureLocalStateIsWritten),
base::Bind(&ChromeRestartRequest::RestartJob, AsWeakPtr()));
}
void ChromeRestartRequest::RestartJob() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DBusThreadManager::Get()->GetSessionManagerClient()->RestartJob(
pid_, command_line_);
delete this;
}
} // namespace
std::string GetOffTheRecordCommandLine(
const GURL& start_url,
const CommandLine& base_command_line,
CommandLine* command_line) {
base::DictionaryValue otr_switches;
otr_switches.SetString(switches::kGuestSession, std::string());
otr_switches.SetString(::switches::kIncognito, std::string());
otr_switches.SetString(::switches::kLoggingLevel, kGuestModeLoggingLevel);
otr_switches.SetString(switches::kLoginUser, kGuestUserName);
// Override the home page.
otr_switches.SetString(::switches::kHomePage,
GURL(chrome::kChromeUINewTabURL).spec());
return DeriveCommandLine(start_url,
base_command_line,
otr_switches,
command_line);
}
void RestartChrome(const std::string& command_line) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
static bool restart_requested = false;
if (restart_requested) {
NOTREACHED() << "Request chrome restart for more than once.";
}
restart_requested = true;
if (!base::chromeos::IsRunningOnChromeOS()) {
// Relaunch chrome without session manager on dev box.
ReLaunch(command_line);
return;
}
// ChromeRestartRequest deletes itself after request sent to session manager.
(new ChromeRestartRequest(command_line))->Start();
}
} // namespace chromeos
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/task_manager/task_manager.h"
#include "app/l10n_util.h"
#include "base/file_path.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/crashed_extension_infobar.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/tab_contents/infobar_delegate.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/page_transition_types.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "grit/generated_resources.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
const FilePath::CharType* kTitle1File = FILE_PATH_LITERAL("title1.html");
class ResourceChangeObserver : public TaskManagerModelObserver {
public:
ResourceChangeObserver(const TaskManagerModel* model,
int target_resource_count)
: model_(model),
target_resource_count_(target_resource_count) {
}
virtual void OnModelChanged() {
OnResourceChange();
}
virtual void OnItemsChanged(int start, int length) {
OnResourceChange();
}
virtual void OnItemsAdded(int start, int length) {
OnResourceChange();
}
virtual void OnItemsRemoved(int start, int length) {
OnResourceChange();
}
private:
void OnResourceChange() {
if (model_->ResourceCount() == target_resource_count_)
MessageLoopForUI::current()->Quit();
}
const TaskManagerModel* model_;
const int target_resource_count_;
};
} // namespace
class TaskManagerBrowserTest : public ExtensionBrowserTest {
public:
TaskManagerModel* model() const {
return TaskManager::GetInstance()->model();
}
void WaitForResourceChange(int target_count) {
if (model()->ResourceCount() == target_count)
return;
ResourceChangeObserver observer(model(), target_count);
model()->AddObserver(&observer);
ui_test_utils::RunMessageLoop();
model()->RemoveObserver(&observer);
}
};
// Crashes on Vista (dbg): http://crbug.com/44991
#if defined(OS_WIN)
#define ShutdownWhileOpen DISABLED_ShutdownWhileOpen
#endif
// Regression test for http://crbug.com/13361
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, ShutdownWhileOpen) {
browser()->window()->ShowTaskManager();
}
// Times out on Vista; disabled to keep tests fast. http://crbug.com/44991
#if defined(OS_WIN)
#define NoticeTabContentsChanges DISABLED_NoticeTabContentsChanges
#endif
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, NoticeTabContentsChanges) {
EXPECT_EQ(0, model()->ResourceCount());
// Show the task manager. This populates the model, and helps with debugging
// (you see the task manager).
browser()->window()->ShowTaskManager();
// Browser and the New Tab Page.
EXPECT_EQ(2, model()->ResourceCount());
// Open a new tab and make sure we notice that.
GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),
FilePath(kTitle1File)));
Browser::AddTabWithURLParams params(url, PageTransition::TYPED);
params.index = 0;
browser()->AddTabWithURL(¶ms);
EXPECT_EQ(browser(), params.target);
WaitForResourceChange(3);
// Close the tab and verify that we notice.
TabContents* first_tab = browser()->GetTabContentsAt(0);
ASSERT_TRUE(first_tab);
browser()->CloseTabContents(first_tab);
WaitForResourceChange(2);
}
#if defined(OS_WIN)
// http://crbug.com/31663
#define NoticeExtensionChanges DISABLED_NoticeExtensionChanges
#endif
// Flaky test bug filed in http://crbug.com/51701
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, FLAKY_NoticeExtensionChanges) {
EXPECT_EQ(0, model()->ResourceCount());
// Show the task manager. This populates the model, and helps with debugging
// (you see the task manager).
browser()->window()->ShowTaskManager();
// Browser and the New Tab Page.
EXPECT_EQ(2, model()->ResourceCount());
// Loading an extension with a background page should result in a new
// resource being created for it.
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("common").AppendASCII("background_page")));
WaitForResourceChange(3);
}
// Times out on Vista; disabled to keep tests fast. http://crbug.com/44991
#if defined(OS_WIN)
#define KillExtension DISABLED_KillExtension
#endif
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, KillExtension) {
// Show the task manager. This populates the model, and helps with debugging
// (you see the task manager).
browser()->window()->ShowTaskManager();
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("common").AppendASCII("background_page")));
// Wait until we see the loaded extension in the task manager (the three
// resources are: the browser process, New Tab Page, and the extension).
WaitForResourceChange(3);
EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);
EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);
ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);
// Kill the extension process and make sure we notice it.
TaskManager::GetInstance()->KillProcess(2);
WaitForResourceChange(2);
}
// Times out on Vista; disabled to keep tests fast. http://crbug.com/44991
#if defined(OS_WIN)
#define KillExtensionAndReload DISABLED_KillExtensionAndReload
#endif
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, KillExtensionAndReload) {
// Show the task manager. This populates the model, and helps with debugging
// (you see the task manager).
browser()->window()->ShowTaskManager();
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("common").AppendASCII("background_page")));
// Wait until we see the loaded extension in the task manager (the three
// resources are: the browser process, New Tab Page, and the extension).
WaitForResourceChange(3);
EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);
EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);
ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);
// Kill the extension process and make sure we notice it.
TaskManager::GetInstance()->KillProcess(2);
WaitForResourceChange(2);
// Reload the extension using the "crashed extension" infobar while the task
// manager is still visible. Make sure we don't crash and the extension
// gets reloaded and noticed in the task manager.
TabContents* current_tab = browser()->GetSelectedTabContents();
ASSERT_EQ(1, current_tab->infobar_delegate_count());
InfoBarDelegate* delegate = current_tab->GetInfoBarDelegateAt(0);
CrashedExtensionInfoBarDelegate* crashed_delegate =
delegate->AsCrashedExtensionInfoBarDelegate();
ASSERT_TRUE(crashed_delegate);
crashed_delegate->Accept();
WaitForResourceChange(3);
}
// Regression test for http://crbug.com/18693.
// Crashy, http://crbug.com/42315.
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, DISABLED_ReloadExtension) {
// Show the task manager. This populates the model, and helps with debugging
// (you see the task manager).
browser()->window()->ShowTaskManager();
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("common").AppendASCII("background_page")));
// Wait until we see the loaded extension in the task manager (the three
// resources are: the browser process, New Tab Page, and the extension).
WaitForResourceChange(3);
EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);
EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);
ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);
const Extension* extension = model()->GetResourceExtension(2);
// Reload the extension a few times and make sure our resource count
// doesn't increase.
ReloadExtension(extension->id());
WaitForResourceChange(3);
extension = model()->GetResourceExtension(2);
ReloadExtension(extension->id());
WaitForResourceChange(3);
extension = model()->GetResourceExtension(2);
ReloadExtension(extension->id());
WaitForResourceChange(3);
}
// Crashy, http://crbug.com/42301.
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest,
DISABLED_PopulateWebCacheFields) {
EXPECT_EQ(0, model()->ResourceCount());
// Show the task manager. This populates the model, and helps with debugging
// (you see the task manager).
browser()->window()->ShowTaskManager();
// Browser and the New Tab Page.
EXPECT_EQ(2, model()->ResourceCount());
// Open a new tab and make sure we notice that.
GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),
FilePath(kTitle1File)));
Browser::AddTabWithURLParams params(url, PageTransition::TYPED);
params.index = 0;
browser()->AddTabWithURL(¶ms);
WaitForResourceChange(3);
// Check that we get some value for the cache columns.
DCHECK_NE(model()->GetResourceWebCoreImageCacheSize(2),
l10n_util::GetStringUTF16(IDS_TASK_MANAGER_NA_CELL_TEXT));
DCHECK_NE(model()->GetResourceWebCoreScriptsCacheSize(2),
l10n_util::GetStringUTF16(IDS_TASK_MANAGER_NA_CELL_TEXT));
DCHECK_NE(model()->GetResourceWebCoreCSSCacheSize(2),
l10n_util::GetStringUTF16(IDS_TASK_MANAGER_NA_CELL_TEXT));
}
<commit_msg>When FLAKY_ was added, it removed the DISABLED_ flag that was there for 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.
#include "chrome/browser/task_manager/task_manager.h"
#include "app/l10n_util.h"
#include "base/file_path.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/extensions/crashed_extension_infobar.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/tab_contents/infobar_delegate.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/page_transition_types.h"
#include "chrome/test/in_process_browser_test.h"
#include "chrome/test/ui_test_utils.h"
#include "grit/generated_resources.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
const FilePath::CharType* kTitle1File = FILE_PATH_LITERAL("title1.html");
class ResourceChangeObserver : public TaskManagerModelObserver {
public:
ResourceChangeObserver(const TaskManagerModel* model,
int target_resource_count)
: model_(model),
target_resource_count_(target_resource_count) {
}
virtual void OnModelChanged() {
OnResourceChange();
}
virtual void OnItemsChanged(int start, int length) {
OnResourceChange();
}
virtual void OnItemsAdded(int start, int length) {
OnResourceChange();
}
virtual void OnItemsRemoved(int start, int length) {
OnResourceChange();
}
private:
void OnResourceChange() {
if (model_->ResourceCount() == target_resource_count_)
MessageLoopForUI::current()->Quit();
}
const TaskManagerModel* model_;
const int target_resource_count_;
};
} // namespace
class TaskManagerBrowserTest : public ExtensionBrowserTest {
public:
TaskManagerModel* model() const {
return TaskManager::GetInstance()->model();
}
void WaitForResourceChange(int target_count) {
if (model()->ResourceCount() == target_count)
return;
ResourceChangeObserver observer(model(), target_count);
model()->AddObserver(&observer);
ui_test_utils::RunMessageLoop();
model()->RemoveObserver(&observer);
}
};
// Crashes on Vista (dbg): http://crbug.com/44991
#if defined(OS_WIN)
#define ShutdownWhileOpen DISABLED_ShutdownWhileOpen
#endif
// Regression test for http://crbug.com/13361
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, ShutdownWhileOpen) {
browser()->window()->ShowTaskManager();
}
// Times out on Vista; disabled to keep tests fast. http://crbug.com/44991
#if defined(OS_WIN)
#define NoticeTabContentsChanges DISABLED_NoticeTabContentsChanges
#endif
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, NoticeTabContentsChanges) {
EXPECT_EQ(0, model()->ResourceCount());
// Show the task manager. This populates the model, and helps with debugging
// (you see the task manager).
browser()->window()->ShowTaskManager();
// Browser and the New Tab Page.
EXPECT_EQ(2, model()->ResourceCount());
// Open a new tab and make sure we notice that.
GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),
FilePath(kTitle1File)));
Browser::AddTabWithURLParams params(url, PageTransition::TYPED);
params.index = 0;
browser()->AddTabWithURL(¶ms);
EXPECT_EQ(browser(), params.target);
WaitForResourceChange(3);
// Close the tab and verify that we notice.
TabContents* first_tab = browser()->GetTabContentsAt(0);
ASSERT_TRUE(first_tab);
browser()->CloseTabContents(first_tab);
WaitForResourceChange(2);
}
#if defined(OS_WIN)
// http://crbug.com/31663
#define MAYBE_NoticeExtensionChanges DISABLED_NoticeExtensionChanges
#else
// Flaky test bug filed in http://crbug.com/51701
#define MAYBE_NoticeExtensionChanges FLAKY_NoticeExtensionChanges
#endif
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, MAYBE_NoticeExtensionChanges) {
EXPECT_EQ(0, model()->ResourceCount());
// Show the task manager. This populates the model, and helps with debugging
// (you see the task manager).
browser()->window()->ShowTaskManager();
// Browser and the New Tab Page.
EXPECT_EQ(2, model()->ResourceCount());
// Loading an extension with a background page should result in a new
// resource being created for it.
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("common").AppendASCII("background_page")));
WaitForResourceChange(3);
}
// Times out on Vista; disabled to keep tests fast. http://crbug.com/44991
#if defined(OS_WIN)
#define KillExtension DISABLED_KillExtension
#endif
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, KillExtension) {
// Show the task manager. This populates the model, and helps with debugging
// (you see the task manager).
browser()->window()->ShowTaskManager();
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("common").AppendASCII("background_page")));
// Wait until we see the loaded extension in the task manager (the three
// resources are: the browser process, New Tab Page, and the extension).
WaitForResourceChange(3);
EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);
EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);
ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);
// Kill the extension process and make sure we notice it.
TaskManager::GetInstance()->KillProcess(2);
WaitForResourceChange(2);
}
// Times out on Vista; disabled to keep tests fast. http://crbug.com/44991
#if defined(OS_WIN)
#define KillExtensionAndReload DISABLED_KillExtensionAndReload
#endif
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, KillExtensionAndReload) {
// Show the task manager. This populates the model, and helps with debugging
// (you see the task manager).
browser()->window()->ShowTaskManager();
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("common").AppendASCII("background_page")));
// Wait until we see the loaded extension in the task manager (the three
// resources are: the browser process, New Tab Page, and the extension).
WaitForResourceChange(3);
EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);
EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);
ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);
// Kill the extension process and make sure we notice it.
TaskManager::GetInstance()->KillProcess(2);
WaitForResourceChange(2);
// Reload the extension using the "crashed extension" infobar while the task
// manager is still visible. Make sure we don't crash and the extension
// gets reloaded and noticed in the task manager.
TabContents* current_tab = browser()->GetSelectedTabContents();
ASSERT_EQ(1, current_tab->infobar_delegate_count());
InfoBarDelegate* delegate = current_tab->GetInfoBarDelegateAt(0);
CrashedExtensionInfoBarDelegate* crashed_delegate =
delegate->AsCrashedExtensionInfoBarDelegate();
ASSERT_TRUE(crashed_delegate);
crashed_delegate->Accept();
WaitForResourceChange(3);
}
// Regression test for http://crbug.com/18693.
// Crashy, http://crbug.com/42315.
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, DISABLED_ReloadExtension) {
// Show the task manager. This populates the model, and helps with debugging
// (you see the task manager).
browser()->window()->ShowTaskManager();
ASSERT_TRUE(LoadExtension(
test_data_dir_.AppendASCII("common").AppendASCII("background_page")));
// Wait until we see the loaded extension in the task manager (the three
// resources are: the browser process, New Tab Page, and the extension).
WaitForResourceChange(3);
EXPECT_TRUE(model()->GetResourceExtension(0) == NULL);
EXPECT_TRUE(model()->GetResourceExtension(1) == NULL);
ASSERT_TRUE(model()->GetResourceExtension(2) != NULL);
const Extension* extension = model()->GetResourceExtension(2);
// Reload the extension a few times and make sure our resource count
// doesn't increase.
ReloadExtension(extension->id());
WaitForResourceChange(3);
extension = model()->GetResourceExtension(2);
ReloadExtension(extension->id());
WaitForResourceChange(3);
extension = model()->GetResourceExtension(2);
ReloadExtension(extension->id());
WaitForResourceChange(3);
}
// Crashy, http://crbug.com/42301.
IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest,
DISABLED_PopulateWebCacheFields) {
EXPECT_EQ(0, model()->ResourceCount());
// Show the task manager. This populates the model, and helps with debugging
// (you see the task manager).
browser()->window()->ShowTaskManager();
// Browser and the New Tab Page.
EXPECT_EQ(2, model()->ResourceCount());
// Open a new tab and make sure we notice that.
GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),
FilePath(kTitle1File)));
Browser::AddTabWithURLParams params(url, PageTransition::TYPED);
params.index = 0;
browser()->AddTabWithURL(¶ms);
WaitForResourceChange(3);
// Check that we get some value for the cache columns.
DCHECK_NE(model()->GetResourceWebCoreImageCacheSize(2),
l10n_util::GetStringUTF16(IDS_TASK_MANAGER_NA_CELL_TEXT));
DCHECK_NE(model()->GetResourceWebCoreScriptsCacheSize(2),
l10n_util::GetStringUTF16(IDS_TASK_MANAGER_NA_CELL_TEXT));
DCHECK_NE(model()->GetResourceWebCoreCSSCacheSize(2),
l10n_util::GetStringUTF16(IDS_TASK_MANAGER_NA_CELL_TEXT));
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome_frame/ready_mode/internal/ready_prompt_window.h"
#include <atlctrls.h>
#include <Shellapi.h> // Must appear before atlctrlx.h
// These seem to be required by atlctrlx?
template<class A>
A min(A const& a, A const& b) { return a < b ? a : b; }
template<class A>
A max(A const& a, A const& b) { return a > b ? a : b; }
#include <atlctrlx.h>
#include "base/compiler_specific.h"
#include "base/win/scoped_bstr.h"
#include "base/win/scoped_comptr.h"
#include "chrome_frame/ready_mode/internal/ready_mode_state.h"
#include "chrome_frame/ready_mode/internal/url_launcher.h"
#include "chrome_frame/simple_resource_loader.h"
#include "grit/chromium_strings.h"
ReadyPromptWindow::ReadyPromptWindow(
InfobarContent::Frame* frame, ReadyModeState* ready_mode_state,
UrlLauncher* url_launcher)
: frame_(frame),
ready_mode_state_(ready_mode_state),
url_launcher_(url_launcher),
weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {
}
ReadyPromptWindow::~ReadyPromptWindow() {
}
base::WeakPtr<ReadyPromptWindow> ReadyPromptWindow::CreateInstance(
InfobarContent::Frame* frame, ReadyModeState* ready_mode_state,
UrlLauncher* url_launcher) {
DCHECK(frame != NULL);
DCHECK(ready_mode_state != NULL);
DCHECK(url_launcher != NULL);
base::WeakPtr<ReadyPromptWindow> instance((new ReadyPromptWindow(
frame, ready_mode_state, url_launcher))->weak_ptr_factory_.GetWeakPtr());
DCHECK(!instance->IsWindow());
if (instance->Create(frame->GetFrameWindow()) == NULL) {
DPLOG(ERROR) << "Failed to create HWND for ReadyPromptWindow.";
return base::WeakPtr<ReadyPromptWindow>();
}
// Subclass the "Learn more." text to make it behave like a link. Clicks are
// routed to OnLearnMore().
CWindow rte = instance->GetDlgItem(IDC_PROMPT_LINK);
instance->link_.reset(new CHyperLink());
instance->link_->SubclassWindow(rte);
instance->link_->SetHyperLinkExtendedStyle(HLINK_NOTIFYBUTTON,
HLINK_NOTIFYBUTTON);
return instance;
}
void ReadyPromptWindow::OnDestroy() {
frame_ = NULL;
}
BOOL ReadyPromptWindow::OnInitDialog(CWindow wndFocus, LPARAM lInitParam) {
DlgResize_Init(false); // false => 'no gripper'
return TRUE;
}
LRESULT ReadyPromptWindow::OnYes(WORD /*wNotifyCode*/,
WORD /*wID*/,
HWND /*hWndCtl*/,
BOOL& /*bHandled*/) {
frame_->CloseInfobar();
ready_mode_state_->AcceptChromeFrame();
return 0;
}
LRESULT ReadyPromptWindow::OnRemindMeLater(WORD /*wNotifyCode*/,
WORD /*wID*/,
HWND /*hWndCtl*/,
BOOL& /*bHandled*/) {
frame_->CloseInfobar();
ready_mode_state_->TemporarilyDeclineChromeFrame();
return 0;
}
LRESULT ReadyPromptWindow::OnNo(WORD /*wNotifyCode*/,
WORD /*wID*/,
HWND /*hWndCtl*/,
BOOL& /*bHandled*/) {
frame_->CloseInfobar();
ready_mode_state_->PermanentlyDeclineChromeFrame();
return 0;
}
LRESULT ReadyPromptWindow::OnLearnMore(WORD /*wParam*/,
LPNMHDR /*lParam*/,
BOOL& /*bHandled*/) {
url_launcher_->LaunchUrl(SimpleResourceLoader::Get(
IDS_CHROME_FRAME_READY_MODE_LEARN_MORE_URL));
return 0;
}
void ReadyPromptWindow::OnFinalMessage(HWND) {
delete this;
}
<commit_msg>Replace one unfortunate hack with a somewhat better one. The included atlctrlx.h relies on min and max macros, which are generally bad and especially so in combination with STL.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome_frame/ready_mode/internal/ready_prompt_window.h"
#include <atlctrls.h>
#include <Shellapi.h>
#include "base/compiler_specific.h"
#include "base/win/scoped_bstr.h"
#include "base/win/scoped_comptr.h"
#include "chrome_frame/ready_mode/internal/ready_mode_state.h"
#include "chrome_frame/ready_mode/internal/url_launcher.h"
#include "chrome_frame/simple_resource_loader.h"
#include "grit/chromium_strings.h"
// atlctrlx.h requires 'min' and 'max' macros, the definition of which conflicts
// with STL headers. Hence we include them out of the order defined by style
// guidelines. As a result you may not refer to std::min or std::max in this
// file.
#include <minmax.h> // NOLINT
#include <atlctrlx.h> // NOLINT
ReadyPromptWindow::ReadyPromptWindow(
InfobarContent::Frame* frame, ReadyModeState* ready_mode_state,
UrlLauncher* url_launcher)
: frame_(frame),
ready_mode_state_(ready_mode_state),
url_launcher_(url_launcher),
weak_ptr_factory_(ALLOW_THIS_IN_INITIALIZER_LIST(this)) {
}
ReadyPromptWindow::~ReadyPromptWindow() {
}
base::WeakPtr<ReadyPromptWindow> ReadyPromptWindow::CreateInstance(
InfobarContent::Frame* frame, ReadyModeState* ready_mode_state,
UrlLauncher* url_launcher) {
DCHECK(frame != NULL);
DCHECK(ready_mode_state != NULL);
DCHECK(url_launcher != NULL);
base::WeakPtr<ReadyPromptWindow> instance((new ReadyPromptWindow(
frame, ready_mode_state, url_launcher))->weak_ptr_factory_.GetWeakPtr());
DCHECK(!instance->IsWindow());
if (instance->Create(frame->GetFrameWindow()) == NULL) {
DPLOG(ERROR) << "Failed to create HWND for ReadyPromptWindow.";
return base::WeakPtr<ReadyPromptWindow>();
}
// Subclass the "Learn more." text to make it behave like a link. Clicks are
// routed to OnLearnMore().
CWindow rte = instance->GetDlgItem(IDC_PROMPT_LINK);
instance->link_.reset(new CHyperLink());
instance->link_->SubclassWindow(rte);
instance->link_->SetHyperLinkExtendedStyle(HLINK_NOTIFYBUTTON,
HLINK_NOTIFYBUTTON);
return instance;
}
void ReadyPromptWindow::OnDestroy() {
frame_ = NULL;
}
BOOL ReadyPromptWindow::OnInitDialog(CWindow wndFocus, LPARAM lInitParam) {
DlgResize_Init(false); // false => 'no gripper'
return TRUE;
}
LRESULT ReadyPromptWindow::OnYes(WORD /*wNotifyCode*/,
WORD /*wID*/,
HWND /*hWndCtl*/,
BOOL& /*bHandled*/) {
frame_->CloseInfobar();
ready_mode_state_->AcceptChromeFrame();
return 0;
}
LRESULT ReadyPromptWindow::OnRemindMeLater(WORD /*wNotifyCode*/,
WORD /*wID*/,
HWND /*hWndCtl*/,
BOOL& /*bHandled*/) {
frame_->CloseInfobar();
ready_mode_state_->TemporarilyDeclineChromeFrame();
return 0;
}
LRESULT ReadyPromptWindow::OnNo(WORD /*wNotifyCode*/,
WORD /*wID*/,
HWND /*hWndCtl*/,
BOOL& /*bHandled*/) {
frame_->CloseInfobar();
ready_mode_state_->PermanentlyDeclineChromeFrame();
return 0;
}
LRESULT ReadyPromptWindow::OnLearnMore(WORD /*wParam*/,
LPNMHDR /*lParam*/,
BOOL& /*bHandled*/) {
url_launcher_->LaunchUrl(SimpleResourceLoader::Get(
IDS_CHROME_FRAME_READY_MODE_LEARN_MORE_URL));
return 0;
}
void ReadyPromptWindow::OnFinalMessage(HWND) {
delete this;
}
<|endoftext|>
|
<commit_before>// @(#)root/treeplayer:$Id$
// Author: Axel Naumann, 2011-09-21
/*************************************************************************
* Copyright (C) 1995-2013, Rene Brun and Fons Rademakers and al. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "TTreeReader.h"
#include "TChain.h"
#include "TDirectory.h"
#include "TTreeReaderValue.h"
////////////////////////////////////////////////////////////////////////////////
/*BEGIN_HTML
TTreeReader is a simple, robust and fast interface to read values from a TTree,
TChain or TNtuple. It uses TTreeReaderValue<T> and
TTreeReaderArray<T> to access the data. Example code can be found in
tutorial/tree/hsimpleReader.C and tutorial/tree/h1analysisTreeReader.h.
Roottest contains an
<a href="http://root.cern.ch/gitweb?p=roottest.git;a=tree;f=root/tree/reader;hb=HEAD">example</a>
showing the full power.
Usually it is as simple as this:
END_HTML
BEGIN_MACRO(source)
../../../tutorials/tree/hsimpleReader.C
END_MACRO */
////////////////////////////////////////////////////////////////////////////////
ClassImp(TTreeReader)
//______________________________________________________________________________
TTreeReader::TTreeReader(TTree* tree):
fTree(tree),
fDirectory(0),
fEntryStatus(kEntryNotLoaded),
fDirector(0)
{
// Access data from tree.
Initialize();
}
//______________________________________________________________________________
TTreeReader::TTreeReader(const char* keyname, TDirectory* dir /*= NULL*/):
fTree(0),
fDirectory(dir),
fEntryStatus(kEntryNotLoaded),
fDirector(0)
{
// Access data from the tree called keyname in the directory (e.g. TFile)
// dir, or the current directory if dir is NULL. If keyname cannot be
// found, or if it is not a TTree, IsZombie() will return true.
if (!fDirectory) fDirectory = gDirectory;
fDirectory->GetObject(keyname, fTree);
Initialize();
}
//______________________________________________________________________________
TTreeReader::~TTreeReader()
{
// Tell all value readers that the tree reader does not exist anymore.
for (std::deque<ROOT::TTreeReaderValueBase*>::const_iterator
i = fValues.begin(), e = fValues.end(); i != e; ++i) {
(*i)->MarkTreeReaderUnavailable();
}
delete fDirector;
fProxies.SetOwner();
}
//______________________________________________________________________________
void TTreeReader::Initialize()
{
// Initialization of the director.
if (!fTree) {
MakeZombie();
fEntryStatus = kEntryNoTree;
} else {
fDirector = new ROOT::TBranchProxyDirector(fTree, -1);
}
}
//______________________________________________________________________________
Long64_t TTreeReader::GetCurrentEntry() const {
//Returns the index of the current entry being read
if (!fDirector) return 0;
Long64_t currentTreeEntry = fDirector->GetReadEntry();
if (fTree->IsA() == TChain::Class() && currentTreeEntry >= 0) {
return ((TChain*)fTree)->GetChainEntryNumber(currentTreeEntry);
}
return currentTreeEntry;
}
//______________________________________________________________________________
TTreeReader::EEntryStatus TTreeReader::SetEntryBase(Long64_t entry, Bool_t local)
{
// Load an entry into the tree, return the status of the read.
// For chains, entry is the global (i.e. not tree-local) entry number.
if (!fTree) {
fEntryStatus = kEntryNoTree;
return fEntryStatus;
}
TTree* prevTree = fDirector->GetTree();
int loadResult;
if (!local){
Int_t treeNumInChain = fTree->GetTreeNumber();
loadResult = fTree->LoadTree(entry);
if (loadResult == -2) {
fEntryStatus = kEntryNotFound;
return fEntryStatus;
}
Int_t currentTreeNumInChain = fTree->GetTreeNumber();
if (treeNumInChain != currentTreeNumInChain) {
fDirector->SetTree(fTree->GetTree());
}
}
else {
loadResult = entry;
}
if (!prevTree || fDirector->GetReadEntry() == -1) {
// Tell readers we now have a tree
for (std::deque<ROOT::TTreeReaderValueBase*>::const_iterator
i = fValues.begin(); i != fValues.end(); ++i) { // Iterator end changes when parameterized arrays are read
(*i)->CreateProxy();
if (!(*i)->GetProxy()){
fEntryStatus = kEntryDictionaryError;
return fEntryStatus;
}
}
}
fDirector->SetReadEntry(loadResult);
fEntryStatus = kEntryValid;
return fEntryStatus;
}
//______________________________________________________________________________
void TTreeReader::SetTree(TTree* tree)
{
// Set (or update) the which tree to reader from. tree can be
// a TTree or a TChain.
fTree = tree;
if (fTree) {
ResetBit(kZombie);
if (fTree->InheritsFrom(TChain::Class())) {
SetBit(kBitIsChain);
}
}
if (!fDirector) {
Initialize();
}
else {
fDirector->SetTree(fTree);
fDirector->SetReadEntry(-1);
}
}
//______________________________________________________________________________
void TTreeReader::RegisterValueReader(ROOT::TTreeReaderValueBase* reader)
{
// Add a value reader for this tree.
fValues.push_back(reader);
}
//______________________________________________________________________________
void TTreeReader::DeregisterValueReader(ROOT::TTreeReaderValueBase* reader)
{
// Remove a value reader for this tree.
std::deque<ROOT::TTreeReaderValueBase*>::iterator iReader
= std::find(fValues.begin(), fValues.end(), reader);
if (iReader == fValues.end()) {
Error("DeregisterValueReader", "Cannot find reader of type %s for branch %s", reader->GetDerivedTypeName(), reader->fBranchName.Data());
return;
}
fValues.erase(iReader);
}
<commit_msg>Improve documentation of TTreeReader.<commit_after>// @(#)root/treeplayer:$Id$
// Author: Axel Naumann, 2011-09-21
/*************************************************************************
* Copyright (C) 1995-2013, Rene Brun and Fons Rademakers and al. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "TTreeReader.h"
#include "TChain.h"
#include "TDirectory.h"
#include "TTreeReaderValue.h"
////////////////////////////////////////////////////////////////////////////////
/*BEGIN_HTML
TTreeReader is a simple, robust and fast interface to read values from a TTree,
TChain or TNtuple. It uses TTreeReaderValue<T> and
TTreeReaderArray<T> to access the data. Example code can be found in
tutorials/tree/hsimpleReader.C and tutorials/trees/h1analysisTreeReader.h and
tutorials/trees/h1analysisTreeReader.C for a TSelector.
Roottest contains an
<a href="http://root.cern.ch/gitweb?p=roottest.git;a=tree;f=root/tree/reader;hb=HEAD">example</a>
showing the full power.
Usually it is as simple as this:
<div class="code">
<table><tr><td>
<pre class="_listing">
<span class="cpp">#include <<a href="TFile.h">TFile.h</a>></span>
<span class="cpp">#include <<a href="TTreeReader.h">TTreeReader.h</a>></span>
<span class="cpp">#include <<a href="TTreeReaderValue.h">TTreeReaderValue.h</a>></span>
<span class="cpp">#include <<a href="TTreeReaderArray.h">TTreeReaderArray.h</a>></span>
<span class="cpp">#include "TriggerInfo.h"</span>
<span class="cpp">#include "Muon.h"</span>
<span class="cpp">#include "Tau.h"</span>
<span class="cpp">#include <vector></span>
<span class="cpp">#include <iostream></span>
<span class="keyword">bool</span> CheckValue(<a href="ROOT__TTreeReaderValueBase.html">ROOT::TTreeReaderValueBase</a>* value) {
<span class="keyword">if</span> (value->GetSetupStatus() < 0) {
std::cerr << <span class="string">"Error "</span> << value->GetSetupStatus()
<< <span class="string">"setting up reader for "</span> << value->GetBranchName() << '\n';
<span class="keyword">return</span> <span class="keyword">false</span>;
}
<span class="keyword">return</span> <span class="keyword">true</span>;
}
<span class="comment">// Analyze the tree <span class="string">"MyTree"</span> in the file passed into the function.</span>
<span class="comment">// Returns false in case of errors.</span>
<span class="keyword">bool</span> analyze(<a href="TFile.html">TFile</a>* file) {
<span class="comment">// Create a <a href="TTreeReader.html">TTreeReader</a> named <span class="string">"MyTree"</span> from the given <a href="TDirectory.html">TDirectory</a>.</span>
<span class="comment">// The <a href="TTreeReader.html">TTreeReader</a> gives access to the <a href="TTree.html">TTree</a> to the TTreeReaderValue and</span>
<span class="comment">// TTreeReaderArray objects. It knows the current entry number and knows</span>
<span class="comment">// how to iterate through the <a href="TTree.html">TTree</a>.</span>
<a href="TTreeReader.html">TTreeReader</a> reader(<span class="string">"MyTree"</span>, file);
<span class="comment">// <a href="TObject.html#TObject:Read" title="Int_t TObject::Read(const char* name)">Read</a> a single <a href="ListOfTypes.html#float">float</a> value in each tree entries:</span>
TTreeReaderValue<<span class="keyword">float</span>> weight(reader, <span class="string">"event.weight"</span>);
<span class="keyword">if</span> (!CheckValue(weight)) <span class="keyword">return</span> <span class="keyword">false</span>;
<span class="comment">// <a href="TObject.html#TObject:Read" title="Int_t TObject::Read(const char* name)">Read</a> a TriggerInfo object from the tree entries:</span>
TTreeReaderValue<TriggerInfo> triggerInfo(reader, <span class="string">"triggerInfo"</span>);
<span class="keyword">if</span> (!CheckValue(triggerInfo)) <span class="keyword">return</span> <span class="keyword">false</span>;
<span class="comment">// <a href="TObject.html#TObject:Read" title="Int_t TObject::Read(const char* name)">Read</a> a vector of Muon objects from the tree entries:</span>
TTreeReaderValue<std::vector<Muon>> muons(reader, <span class="string">"muons"</span>);
<span class="keyword">if</span> (!CheckValue(muons)) <span class="keyword">return</span> <span class="keyword">false</span>;
<span class="comment">// <a href="TObject.html#TObject:Read" title="Int_t TObject::Read(const char* name)">Read</a> the pT for all jets in the tree entry:</span>
TTreeReaderArray<<span class="keyword">double</span>> jetPt(reader, <span class="string">"jets.pT"</span>);
<span class="keyword">if</span> (!CheckValue(jetPt)) <span class="keyword">return</span> <span class="keyword">false</span>;
<span class="comment">// <a href="TObject.html#TObject:Read" title="Int_t TObject::Read(const char* name)">Read</a> the taus in the tree entry:</span>
TTreeReaderArray<Tau> taus(reader, <span class="string">"taus"</span>);
<span class="keyword">if</span> (!CheckValue(taus)) <span class="keyword">return</span> <span class="keyword">false</span>;
<span class="comment">// Now iterate through the <a href="TTree.html">TTree</a> entries and fill a histogram.</span>
<a href="TH1.html">TH1</a>* hist = <span class="keyword">new</span> <a href="TH1F.html">TH1F</a>(<span class="string">"hist"</span>, <span class="string">"TTreeReader example histogram"</span>, 10, 0., 100.);
<span class="keyword">while</span> (reader.Next()) {
<span class="keyword">if</span> (reader.GetEntryStatus() == <a href="TTreeReader.html#TTreeReader:kEntryValid" title="TTreeReader::EEntryStatus TTreeReader::kEntryValid">kEntryValid</a>) {
std::cout << <span class="string">"Loaded entry "</span> << reader.GetCurrentEntry() << '\n';
} <span class="keyword">else</span> {
<span class="keyword">switch</span> (reader.GetEntryStatus()) {
<a href="TTreeReader.html#TTreeReader:kEntryValid" title="TTreeReader::EEntryStatus TTreeReader::kEntryValid">kEntryValid</a>:
<span class="comment">// Handled above.</span>
<span class="keyword">break</span>;
<a href="TTreeReader.html#TTreeReader:kEntryNotLoaded" title="TTreeReader::EEntryStatus TTreeReader::kEntryNotLoaded">kEntryNotLoaded</a>:
std::cerr << <span class="string">"Error: TTreeReader has not loaded any data yet!\n"</span>;
<span class="keyword">break</span>;
<a href="TTreeReader.html#TTreeReader:kEntryNoTree" title="TTreeReader::EEntryStatus TTreeReader::kEntryNoTree">kEntryNoTree</a>:
std::cerr << <span class="string">"Error: TTreeReader cannot find a tree names \"MyTree\"!\n"</span>;
<span class="keyword">break</span>;
<a href="TTreeReader.html#TTreeReader:kEntryNotFound" title="TTreeReader::EEntryStatus TTreeReader::kEntryNotFound">kEntryNotFound</a>:
<span class="comment">// Can't really happen as <a href="TTreeReader.html">TTreeReader</a>::<a href="TTreeReader.html#TTreeReader:Next" title="Bool_t TTreeReader::Next()">Next</a>() knows when to stop.</span>
std::cerr << <span class="string">"Error: The entry number doe not exist\n"</span>;
<span class="keyword">break</span>;
<a href="TTreeReader.html#TTreeReader:kEntryChainSetupError" title="TTreeReader::EEntryStatus TTreeReader::kEntryChainSetupError">kEntryChainSetupError</a>:
std::cerr << <span class="string">"Error: TTreeReader cannot access a chain element, e.g. file without the tree\n"</span>;
<span class="keyword">break</span>;
<a href="TTreeReader.html#TTreeReader:kEntryChainFileError" title="TTreeReader::EEntryStatus TTreeReader::kEntryChainFileError">kEntryChainFileError</a>:
std::cerr << <span class="string">"Error: TTreeReader cannot open a chain element, e.g. missing file\n"</span>;
<span class="keyword">break</span>;
<a href="TTreeReader.html#TTreeReader:kEntryDictionaryError" title="TTreeReader::EEntryStatus TTreeReader::kEntryDictionaryError">kEntryDictionaryError</a>:
std::cerr << <span class="string">"Error: TTreeReader cannot find the dictionary for some data\n"</span>;
<span class="keyword">break</span>;
}
<span class="keyword">return</span> <span class="keyword">false</span>;
}
<span class="comment">// Access the TriggerInfo object as if it's a pointer.</span>
<span class="keyword">if</span> (!triggerInfo->hasMuonL1())
<span class="keyword">continue</span>;
<span class="comment">// Ditto for the vector<Muon>.</span>
<span class="keyword">if</span> (!muons->size())
<span class="keyword">continue</span>;
<span class="comment">// Access the jetPt as an array, whether the <a href="TTree.html">TTree</a> stores this as</span>
<span class="comment">// a std::vector, std::list, <a href="TClonesArray.html">TClonesArray</a> or Jet* C-style array, with</span>
<span class="comment">// fixed or variable array size.</span>
<span class="keyword">if</span> (jetPt.<a href="TCollection.html#TCollection:GetSize" title="Int_t TCollection::GetSize() const">GetSize</a>() < 2 || jetPt[0] < 100)
<span class="keyword">continue</span>;
<span class="comment">// Access the array of taus.</span>
<span class="keyword">if</span> (!taus.<a href="TObjArray.html#TObjArray:IsEmpty" title="Bool_t TObjArray::IsEmpty() const">IsEmpty</a>()) {
<span class="keyword">float</span> currentWeight = *weight;
<span class="keyword">for</span> (<span class="keyword">int</span> iTau = 0, nTau = taus.<a href="TCollection.html#TCollection:GetSize" title="Int_t TCollection::GetSize() const">GetSize</a>(); iTau < nTau; ++iTau) {
<span class="comment">// Access a <a href="ListOfTypes.html#float">float</a> value - need to dereference as TTreeReaderValue</span>
<span class="comment">// behaves like an iterator</span>
hist->Fill(taus[iTau].eta(), currentWeight);
}
}
}
}
</pre></td></tr></table></div>
<div class="clear">
</div>
<p>A simpler analysis example - the one from the tutorials - can be found below, in
the Source tab: it histograms a function of the px and py branches:</p>
END_HTML
BEGIN_MACRO(source)
../../../tutorials/tree/hsimpleReader.C
END_MACRO */
////////////////////////////////////////////////////////////////////////////////
ClassImp(TTreeReader)
//______________________________________________________________________________
TTreeReader::TTreeReader(TTree* tree):
fTree(tree),
fDirectory(0),
fEntryStatus(kEntryNotLoaded),
fDirector(0)
{
// Access data from tree.
Initialize();
}
//______________________________________________________________________________
TTreeReader::TTreeReader(const char* keyname, TDirectory* dir /*= NULL*/):
fTree(0),
fDirectory(dir),
fEntryStatus(kEntryNotLoaded),
fDirector(0)
{
// Access data from the tree called keyname in the directory (e.g. TFile)
// dir, or the current directory if dir is NULL. If keyname cannot be
// found, or if it is not a TTree, IsZombie() will return true.
if (!fDirectory) fDirectory = gDirectory;
fDirectory->GetObject(keyname, fTree);
Initialize();
}
//______________________________________________________________________________
TTreeReader::~TTreeReader()
{
// Tell all value readers that the tree reader does not exist anymore.
for (std::deque<ROOT::TTreeReaderValueBase*>::const_iterator
i = fValues.begin(), e = fValues.end(); i != e; ++i) {
(*i)->MarkTreeReaderUnavailable();
}
delete fDirector;
fProxies.SetOwner();
}
//______________________________________________________________________________
void TTreeReader::Initialize()
{
// Initialization of the director.
if (!fTree) {
MakeZombie();
fEntryStatus = kEntryNoTree;
} else {
fDirector = new ROOT::TBranchProxyDirector(fTree, -1);
}
}
//______________________________________________________________________________
Long64_t TTreeReader::GetCurrentEntry() const {
//Returns the index of the current entry being read
if (!fDirector) return 0;
Long64_t currentTreeEntry = fDirector->GetReadEntry();
if (fTree->IsA() == TChain::Class() && currentTreeEntry >= 0) {
return ((TChain*)fTree)->GetChainEntryNumber(currentTreeEntry);
}
return currentTreeEntry;
}
//______________________________________________________________________________
TTreeReader::EEntryStatus TTreeReader::SetEntryBase(Long64_t entry, Bool_t local)
{
// Load an entry into the tree, return the status of the read.
// For chains, entry is the global (i.e. not tree-local) entry number.
if (!fTree) {
fEntryStatus = kEntryNoTree;
return fEntryStatus;
}
TTree* prevTree = fDirector->GetTree();
int loadResult;
if (!local){
Int_t treeNumInChain = fTree->GetTreeNumber();
loadResult = fTree->LoadTree(entry);
if (loadResult == -2) {
fEntryStatus = kEntryNotFound;
return fEntryStatus;
}
Int_t currentTreeNumInChain = fTree->GetTreeNumber();
if (treeNumInChain != currentTreeNumInChain) {
fDirector->SetTree(fTree->GetTree());
}
}
else {
loadResult = entry;
}
if (!prevTree || fDirector->GetReadEntry() == -1) {
// Tell readers we now have a tree
for (std::deque<ROOT::TTreeReaderValueBase*>::const_iterator
i = fValues.begin(); i != fValues.end(); ++i) { // Iterator end changes when parameterized arrays are read
(*i)->CreateProxy();
if (!(*i)->GetProxy()){
fEntryStatus = kEntryDictionaryError;
return fEntryStatus;
}
}
}
fDirector->SetReadEntry(loadResult);
fEntryStatus = kEntryValid;
return fEntryStatus;
}
//______________________________________________________________________________
void TTreeReader::SetTree(TTree* tree)
{
// Set (or update) the which tree to reader from. tree can be
// a TTree or a TChain.
fTree = tree;
if (fTree) {
ResetBit(kZombie);
if (fTree->InheritsFrom(TChain::Class())) {
SetBit(kBitIsChain);
}
}
if (!fDirector) {
Initialize();
}
else {
fDirector->SetTree(fTree);
fDirector->SetReadEntry(-1);
}
}
//______________________________________________________________________________
void TTreeReader::RegisterValueReader(ROOT::TTreeReaderValueBase* reader)
{
// Add a value reader for this tree.
fValues.push_back(reader);
}
//______________________________________________________________________________
void TTreeReader::DeregisterValueReader(ROOT::TTreeReaderValueBase* reader)
{
// Remove a value reader for this tree.
std::deque<ROOT::TTreeReaderValueBase*>::iterator iReader
= std::find(fValues.begin(), fValues.end(), reader);
if (iReader == fValues.end()) {
Error("DeregisterValueReader", "Cannot find reader of type %s for branch %s", reader->GetDerivedTypeName(), reader->fBranchName.Data());
return;
}
fValues.erase(iReader);
}
<|endoftext|>
|
<commit_before>/*
The MIT License (MIT)
Copyright (c) 2013-2014 winlin
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef SRS_KERNEL_LOG_HPP
#define SRS_KERNEL_LOG_HPP
/*
#include <srs_kernel_log.hpp>
*/
#include <srs_core.hpp>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <srs_kernel_consts.hpp>
/**
* the log level, for example:
* if specified Debug level, all level messages will be logged.
* if specified Warn level, only Warn/Error/Fatal level messages will be logged.
*/
class SrsLogLevel
{
public:
// only used for very verbose debug, generally,
// we compile without this level for high performance.
static const int Verbose = 0x01;
static const int Info = 0x02;
static const int Trace = 0x03;
static const int Warn = 0x04;
static const int Error = 0x05;
};
/**
* the log interface provides method to write log.
* but we provides some macro, which enable us to disable the log when compile.
* @see also SmtDebug/SmtTrace/SmtWarn/SmtError which is corresponding to Debug/Trace/Warn/Fatal.
*/
class ISrsLog
{
public:
ISrsLog();
virtual ~ISrsLog();
public:
/**
* initialize log utilities.
*/
virtual int initialize();
public:
/**
* log for verbose, very verbose information.
*/
virtual void verbose(const char* tag, int context_id, const char* fmt, ...);
/**
* log for debug, detail information.
*/
virtual void info(const char* tag, int context_id, const char* fmt, ...);
/**
* log for trace, important information.
*/
virtual void trace(const char* tag, int context_id, const char* fmt, ...);
/**
* log for warn, warn is something should take attention, but not a error.
*/
virtual void warn(const char* tag, int context_id, const char* fmt, ...);
/**
* log for error, something error occur, do something about the error, ie. close the connection,
* but we will donot abort the program.
*/
virtual void error(const char* tag, int context_id, const char* fmt, ...);
};
// the context for multiple clients.
class ISrsThreadContext
{
public:
ISrsThreadContext();
virtual ~ISrsThreadContext();
public:
virtual void generate_id();
virtual int get_id();
};
// user must provides a log object
extern ISrsLog* _srs_log;
// user must implements the LogContext and define a global instance.
extern ISrsThreadContext* _srs_context;
// donot print method
#if 1
#define srs_verbose(msg, ...) _srs_log->verbose(NULL, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_info(msg, ...) _srs_log->info(NULL, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_trace(msg, ...) _srs_log->trace(NULL, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_warn(msg, ...) _srs_log->warn(NULL, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_error(msg, ...) _srs_log->error(NULL, _srs_context->get_id(), msg, ##__VA_ARGS__)
// use __FUNCTION__ to print c method
#elif 0
#define srs_verbose(msg, ...) _srs_log->verbose(__FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_info(msg, ...) _srs_log->info(__FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_trace(msg, ...) _srs_log->trace(__FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_warn(msg, ...) _srs_log->warn(__FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_error(msg, ...) _srs_log->error(__FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
// use __PRETTY_FUNCTION__ to print c++ class:method
#else
#define srs_verbose(msg, ...) _srs_log->verbose(__PRETTY_FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_info(msg, ...) _srs_log->info(__PRETTY_FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_trace(msg, ...) _srs_log->trace(__PRETTY_FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_warn(msg, ...) _srs_log->warn(__PRETTY_FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_error(msg, ...) _srs_log->error(__PRETTY_FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#endif
#if 0
#undef srs_verbose
#define srs_verbose(msg, ...) (void)0
#endif
#if 0
#undef srs_info
#define srs_info(msg, ...) (void)0
#endif
#if 0
#undef srs_trace
#define srs_trace(msg, ...) (void)0
#endif
#endif
<commit_msg>add todo fixme for log verbose and info<commit_after>/*
The MIT License (MIT)
Copyright (c) 2013-2014 winlin
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef SRS_KERNEL_LOG_HPP
#define SRS_KERNEL_LOG_HPP
/*
#include <srs_kernel_log.hpp>
*/
#include <srs_core.hpp>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <srs_kernel_consts.hpp>
/**
* the log level, for example:
* if specified Debug level, all level messages will be logged.
* if specified Warn level, only Warn/Error/Fatal level messages will be logged.
*/
class SrsLogLevel
{
public:
// only used for very verbose debug, generally,
// we compile without this level for high performance.
static const int Verbose = 0x01;
static const int Info = 0x02;
static const int Trace = 0x03;
static const int Warn = 0x04;
static const int Error = 0x05;
};
/**
* the log interface provides method to write log.
* but we provides some macro, which enable us to disable the log when compile.
* @see also SmtDebug/SmtTrace/SmtWarn/SmtError which is corresponding to Debug/Trace/Warn/Fatal.
*/
class ISrsLog
{
public:
ISrsLog();
virtual ~ISrsLog();
public:
/**
* initialize log utilities.
*/
virtual int initialize();
public:
/**
* log for verbose, very verbose information.
*/
virtual void verbose(const char* tag, int context_id, const char* fmt, ...);
/**
* log for debug, detail information.
*/
virtual void info(const char* tag, int context_id, const char* fmt, ...);
/**
* log for trace, important information.
*/
virtual void trace(const char* tag, int context_id, const char* fmt, ...);
/**
* log for warn, warn is something should take attention, but not a error.
*/
virtual void warn(const char* tag, int context_id, const char* fmt, ...);
/**
* log for error, something error occur, do something about the error, ie. close the connection,
* but we will donot abort the program.
*/
virtual void error(const char* tag, int context_id, const char* fmt, ...);
};
// the context for multiple clients.
class ISrsThreadContext
{
public:
ISrsThreadContext();
virtual ~ISrsThreadContext();
public:
virtual void generate_id();
virtual int get_id();
};
// user must provides a log object
extern ISrsLog* _srs_log;
// user must implements the LogContext and define a global instance.
extern ISrsThreadContext* _srs_context;
// donot print method
#if 1
#define srs_verbose(msg, ...) _srs_log->verbose(NULL, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_info(msg, ...) _srs_log->info(NULL, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_trace(msg, ...) _srs_log->trace(NULL, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_warn(msg, ...) _srs_log->warn(NULL, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_error(msg, ...) _srs_log->error(NULL, _srs_context->get_id(), msg, ##__VA_ARGS__)
// use __FUNCTION__ to print c method
#elif 0
#define srs_verbose(msg, ...) _srs_log->verbose(__FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_info(msg, ...) _srs_log->info(__FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_trace(msg, ...) _srs_log->trace(__FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_warn(msg, ...) _srs_log->warn(__FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_error(msg, ...) _srs_log->error(__FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
// use __PRETTY_FUNCTION__ to print c++ class:method
#else
#define srs_verbose(msg, ...) _srs_log->verbose(__PRETTY_FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_info(msg, ...) _srs_log->info(__PRETTY_FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_trace(msg, ...) _srs_log->trace(__PRETTY_FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_warn(msg, ...) _srs_log->warn(__PRETTY_FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_error(msg, ...) _srs_log->error(__PRETTY_FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#endif
// TODO: FIXME: add more verbose and info logs.
#if 1
#undef srs_verbose
#define srs_verbose(msg, ...) (void)0
#endif
#if 1
#undef srs_info
#define srs_info(msg, ...) (void)0
#endif
#if 0
#undef srs_trace
#define srs_trace(msg, ...) (void)0
#endif
#endif
<|endoftext|>
|
<commit_before>/*
The MIT License (MIT)
Copyright (c) 2013-2015 SRS(simple-rtmp-server)
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 <srs_app_statistic.hpp>
#include <unistd.h>
#include <sstream>
using namespace std;
#include <srs_rtmp_stack.hpp>
#include <srs_app_json.hpp>
#include <srs_protocol_kbps.hpp>
#include <srs_app_conn.hpp>
#include <srs_app_config.hpp>
#include <srs_kernel_utility.hpp>
int64_t srs_gvid = getpid();
int64_t srs_generate_id()
{
return srs_gvid++;
}
SrsStatisticVhost::SrsStatisticVhost()
{
id = srs_generate_id();
kbps = new SrsKbps();
kbps->set_io(NULL, NULL);
}
SrsStatisticVhost::~SrsStatisticVhost()
{
srs_freep(kbps);
}
SrsStatisticStream::SrsStatisticStream()
{
id = srs_generate_id();
vhost = NULL;
status = STATISTIC_STREAM_STATUS_IDLING;
has_video = false;
vcodec = SrsCodecVideoReserved;
avc_profile = SrsAvcProfileReserved;
avc_level = SrsAvcLevelReserved;
has_audio = false;
acodec = SrsCodecAudioReserved1;
asample_rate = SrsCodecAudioSampleRateReserved;
asound_type = SrsCodecAudioSoundTypeReserved;
aac_object = SrsAacObjectTypeReserved;
kbps = new SrsKbps();
kbps->set_io(NULL, NULL);
}
SrsStatisticStream::~SrsStatisticStream()
{
srs_freep(kbps);
}
void SrsStatisticStream::publish()
{
status = STATISTIC_STREAM_STATUS_PUBLISHING;
}
void SrsStatisticStream::close()
{
has_video = false;
has_audio = false;
status = STATISTIC_STREAM_STATUS_IDLING;
}
SrsStatistic* SrsStatistic::_instance = new SrsStatistic();
SrsStatistic::SrsStatistic()
{
_server_id = srs_generate_id();
kbps = new SrsKbps();
kbps->set_io(NULL, NULL);
}
SrsStatistic::~SrsStatistic()
{
srs_freep(kbps);
if (true) {
std::map<std::string, SrsStatisticVhost*>::iterator it;
for (it = vhosts.begin(); it != vhosts.end(); it++) {
SrsStatisticVhost* vhost = it->second;
srs_freep(vhost);
}
}
if (true) {
std::map<std::string, SrsStatisticStream*>::iterator it;
for (it = streams.begin(); it != streams.end(); it++) {
SrsStatisticStream* stream = it->second;
srs_freep(stream);
}
}
if (true) {
std::map<int, SrsStatisticClient*>::iterator it;
for (it = clients.begin(); it != clients.end(); it++) {
SrsStatisticClient* client = it->second;
srs_freep(client);
}
}
}
SrsStatistic* SrsStatistic::instance()
{
return _instance;
}
SrsStatisticStream* SrsStatistic::find_stream(int stream_id)
{
std::map<int, SrsStatisticClient*>::iterator it;
for (it = clients.begin(); it != clients.end(); it++) {
SrsStatisticClient* client = it->second;
SrsStatisticStream* stream = client->stream;
if (stream_id == stream->id) {
return stream;
}
}
return NULL;
}
int SrsStatistic::on_video_info(SrsRequest* req,
SrsCodecVideo vcodec, SrsAvcProfile avc_profile, SrsAvcLevel avc_level
) {
int ret = ERROR_SUCCESS;
SrsStatisticVhost* vhost = create_vhost(req);
SrsStatisticStream* stream = create_stream(vhost, req);
stream->has_video = true;
stream->vcodec = vcodec;
stream->avc_profile = avc_profile;
stream->avc_level = avc_level;
return ret;
}
int SrsStatistic::on_audio_info(SrsRequest* req,
SrsCodecAudio acodec, SrsCodecAudioSampleRate asample_rate, SrsCodecAudioSoundType asound_type,
SrsAacObjectType aac_object
) {
int ret = ERROR_SUCCESS;
SrsStatisticVhost* vhost = create_vhost(req);
SrsStatisticStream* stream = create_stream(vhost, req);
stream->has_audio = true;
stream->acodec = acodec;
stream->asample_rate = asample_rate;
stream->asound_type = asound_type;
stream->aac_object = aac_object;
return ret;
}
void SrsStatistic::on_stream_publish(SrsRequest* req)
{
SrsStatisticVhost* vhost = create_vhost(req);
SrsStatisticStream* stream = create_stream(vhost, req);
stream->publish();
}
void SrsStatistic::on_stream_close(SrsRequest* req)
{
SrsStatisticVhost* vhost = create_vhost(req);
SrsStatisticStream* stream = create_stream(vhost, req);
stream->close();
}
int SrsStatistic::on_client(int id, SrsRequest* req)
{
int ret = ERROR_SUCCESS;
SrsStatisticVhost* vhost = create_vhost(req);
SrsStatisticStream* stream = create_stream(vhost, req);
// create client if not exists
SrsStatisticClient* client = NULL;
if (clients.find(id) == clients.end()) {
client = new SrsStatisticClient();
client->id = id;
client->stream = stream;
clients[id] = client;
} else {
client = clients[id];
}
return ret;
}
void SrsStatistic::on_disconnect(int id)
{
std::map<int, SrsStatisticClient*>::iterator it;
it = clients.find(id);
if (it != clients.end()) {
SrsStatisticClient* client = it->second;
srs_freep(client);
clients.erase(it);
}
}
void SrsStatistic::kbps_add_delta(SrsConnection* conn)
{
int id = conn->srs_id();
if (clients.find(id) == clients.end()) {
return;
}
SrsStatisticClient* client = clients[id];
// resample the kbps to collect the delta.
conn->resample();
// add delta of connection to kbps.
// for next sample() of server kbps can get the stat.
kbps->add_delta(conn);
client->stream->kbps->add_delta(conn);
client->stream->vhost->kbps->add_delta(conn);
// cleanup the delta.
conn->cleanup();
}
SrsKbps* SrsStatistic::kbps_sample()
{
kbps->sample();
if (true) {
std::map<std::string, SrsStatisticVhost*>::iterator it;
for (it = vhosts.begin(); it != vhosts.end(); it++) {
SrsStatisticVhost* vhost = it->second;
vhost->kbps->sample();
}
}
if (true) {
std::map<std::string, SrsStatisticStream*>::iterator it;
for (it = streams.begin(); it != streams.end(); it++) {
SrsStatisticStream* stream = it->second;
stream->kbps->sample();
}
}
return kbps;
}
int64_t SrsStatistic::server_id()
{
return _server_id;
}
int SrsStatistic::dumps_vhosts(stringstream& ss)
{
int ret = ERROR_SUCCESS;
ss << SRS_JARRAY_START;
std::map<std::string, SrsStatisticVhost*>::iterator it;
for (it = vhosts.begin(); it != vhosts.end(); it++) {
SrsStatisticVhost* vhost = it->second;
if (it != vhosts.begin()) {
ss << SRS_JFIELD_CONT;
}
// dumps the config of vhost.
bool hls_enabled = _srs_config->get_hls_enabled(vhost->vhost);
ss << SRS_JOBJECT_START
<< SRS_JFIELD_ORG("id", vhost->id) << SRS_JFIELD_CONT
<< SRS_JFIELD_STR("name", vhost->vhost) << SRS_JFIELD_CONT
<< SRS_JFIELD_ORG("send_bytes", vhost->kbps->get_send_bytes()) << SRS_JFIELD_CONT
<< SRS_JFIELD_ORG("recv_bytes", vhost->kbps->get_recv_bytes()) << SRS_JFIELD_CONT
<< SRS_JFIELD_NAME("hls") << SRS_JOBJECT_START
<< SRS_JFIELD_BOOL("enabled", hls_enabled) << SRS_JFIELD_CONT
<< SRS_JFIELD_ORG("fragment", _srs_config->get_hls_fragment(vhost->vhost))
<< SRS_JOBJECT_END
<< SRS_JOBJECT_END;
}
ss << SRS_JARRAY_END;
return ret;
}
int SrsStatistic::dumps_streams(stringstream& ss)
{
int ret = ERROR_SUCCESS;
ss << SRS_JARRAY_START;
std::map<std::string, SrsStatisticStream*>::iterator it;
for (it = streams.begin(); it != streams.end(); it++) {
SrsStatisticStream* stream = it->second;
if (it != streams.begin()) {
ss << SRS_JFIELD_CONT;
}
int client_num = 0;
std::map<int, SrsStatisticClient*>::iterator it_client;
for (it_client = clients.begin(); it_client != clients.end(); it_client++) {
SrsStatisticClient* client = it_client->second;
if (client->stream == stream) {
client_num++;
}
}
ss << SRS_JOBJECT_START
<< SRS_JFIELD_ORG("id", stream->id) << SRS_JFIELD_CONT
<< SRS_JFIELD_STR("name", stream->stream) << SRS_JFIELD_CONT
<< SRS_JFIELD_ORG("vhost", stream->vhost->id) << SRS_JFIELD_CONT
<< SRS_JFIELD_STR("app", stream->app) << SRS_JFIELD_CONT
<< SRS_JFIELD_ORG("clients", client_num) << SRS_JFIELD_CONT
<< SRS_JFIELD_ORG("send_bytes", stream->kbps->get_send_bytes()) << SRS_JFIELD_CONT
<< SRS_JFIELD_ORG("recv_bytes", stream->kbps->get_recv_bytes()) << SRS_JFIELD_CONT
<< SRS_JFIELD_ORG("live_ms", srs_get_system_time_ms()) << SRS_JFIELD_CONT
<< SRS_JFIELD_STR("status", stream->status) << SRS_JFIELD_CONT;
if (!stream->has_video) {
ss << SRS_JFIELD_NULL("video") << SRS_JFIELD_CONT;
} else {
ss << SRS_JFIELD_NAME("video")
<< SRS_JOBJECT_START
<< SRS_JFIELD_STR("codec", srs_codec_video2str(stream->vcodec)) << SRS_JFIELD_CONT
<< SRS_JFIELD_STR("profile", srs_codec_avc_profile2str(stream->avc_profile)) << SRS_JFIELD_CONT
<< SRS_JFIELD_ORG("level", srs_codec_avc_level2str(stream->avc_level))
<< SRS_JOBJECT_END
<< SRS_JFIELD_CONT;
}
if (!stream->has_audio) {
ss << SRS_JFIELD_NULL("audio");
} else {
ss << SRS_JFIELD_NAME("audio")
<< SRS_JOBJECT_START
<< SRS_JFIELD_STR("codec", srs_codec_audio2str(stream->acodec)) << SRS_JFIELD_CONT
<< SRS_JFIELD_ORG("sample_rate", (int)flv_sample_rates[stream->asample_rate]) << SRS_JFIELD_CONT
<< SRS_JFIELD_ORG("channel", (int)stream->asound_type + 1) << SRS_JFIELD_CONT
<< SRS_JFIELD_STR("profile", srs_codec_aac_object2str(stream->aac_object))
<< SRS_JOBJECT_END;
}
ss << SRS_JOBJECT_END;
}
ss << SRS_JARRAY_END;
return ret;
}
SrsStatisticVhost* SrsStatistic::create_vhost(SrsRequest* req)
{
SrsStatisticVhost* vhost = NULL;
// create vhost if not exists.
if (vhosts.find(req->vhost) == vhosts.end()) {
vhost = new SrsStatisticVhost();
vhost->vhost = req->vhost;
vhosts[req->vhost] = vhost;
return vhost;
}
vhost = vhosts[req->vhost];
return vhost;
}
SrsStatisticStream* SrsStatistic::create_stream(SrsStatisticVhost* vhost, SrsRequest* req)
{
std::string url = req->get_stream_url();
SrsStatisticStream* stream = NULL;
// create stream if not exists.
if (streams.find(url) == streams.end()) {
stream = new SrsStatisticStream();
stream->vhost = vhost;
stream->stream = req->stream;
stream->app = req->app;
stream->url = url;
streams[url] = stream;
return stream;
}
stream = streams[url];
return stream;
}
<commit_msg>refine code, donot remove the detail when hls disabled.<commit_after>/*
The MIT License (MIT)
Copyright (c) 2013-2015 SRS(simple-rtmp-server)
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 <srs_app_statistic.hpp>
#include <unistd.h>
#include <sstream>
using namespace std;
#include <srs_rtmp_stack.hpp>
#include <srs_app_json.hpp>
#include <srs_protocol_kbps.hpp>
#include <srs_app_conn.hpp>
#include <srs_app_config.hpp>
#include <srs_kernel_utility.hpp>
int64_t srs_gvid = getpid();
int64_t srs_generate_id()
{
return srs_gvid++;
}
SrsStatisticVhost::SrsStatisticVhost()
{
id = srs_generate_id();
kbps = new SrsKbps();
kbps->set_io(NULL, NULL);
}
SrsStatisticVhost::~SrsStatisticVhost()
{
srs_freep(kbps);
}
SrsStatisticStream::SrsStatisticStream()
{
id = srs_generate_id();
vhost = NULL;
status = STATISTIC_STREAM_STATUS_IDLING;
has_video = false;
vcodec = SrsCodecVideoReserved;
avc_profile = SrsAvcProfileReserved;
avc_level = SrsAvcLevelReserved;
has_audio = false;
acodec = SrsCodecAudioReserved1;
asample_rate = SrsCodecAudioSampleRateReserved;
asound_type = SrsCodecAudioSoundTypeReserved;
aac_object = SrsAacObjectTypeReserved;
kbps = new SrsKbps();
kbps->set_io(NULL, NULL);
}
SrsStatisticStream::~SrsStatisticStream()
{
srs_freep(kbps);
}
void SrsStatisticStream::publish()
{
status = STATISTIC_STREAM_STATUS_PUBLISHING;
}
void SrsStatisticStream::close()
{
has_video = false;
has_audio = false;
status = STATISTIC_STREAM_STATUS_IDLING;
}
SrsStatistic* SrsStatistic::_instance = new SrsStatistic();
SrsStatistic::SrsStatistic()
{
_server_id = srs_generate_id();
kbps = new SrsKbps();
kbps->set_io(NULL, NULL);
}
SrsStatistic::~SrsStatistic()
{
srs_freep(kbps);
if (true) {
std::map<std::string, SrsStatisticVhost*>::iterator it;
for (it = vhosts.begin(); it != vhosts.end(); it++) {
SrsStatisticVhost* vhost = it->second;
srs_freep(vhost);
}
}
if (true) {
std::map<std::string, SrsStatisticStream*>::iterator it;
for (it = streams.begin(); it != streams.end(); it++) {
SrsStatisticStream* stream = it->second;
srs_freep(stream);
}
}
if (true) {
std::map<int, SrsStatisticClient*>::iterator it;
for (it = clients.begin(); it != clients.end(); it++) {
SrsStatisticClient* client = it->second;
srs_freep(client);
}
}
}
SrsStatistic* SrsStatistic::instance()
{
return _instance;
}
SrsStatisticStream* SrsStatistic::find_stream(int stream_id)
{
std::map<int, SrsStatisticClient*>::iterator it;
for (it = clients.begin(); it != clients.end(); it++) {
SrsStatisticClient* client = it->second;
SrsStatisticStream* stream = client->stream;
if (stream_id == stream->id) {
return stream;
}
}
return NULL;
}
int SrsStatistic::on_video_info(SrsRequest* req,
SrsCodecVideo vcodec, SrsAvcProfile avc_profile, SrsAvcLevel avc_level
) {
int ret = ERROR_SUCCESS;
SrsStatisticVhost* vhost = create_vhost(req);
SrsStatisticStream* stream = create_stream(vhost, req);
stream->has_video = true;
stream->vcodec = vcodec;
stream->avc_profile = avc_profile;
stream->avc_level = avc_level;
return ret;
}
int SrsStatistic::on_audio_info(SrsRequest* req,
SrsCodecAudio acodec, SrsCodecAudioSampleRate asample_rate, SrsCodecAudioSoundType asound_type,
SrsAacObjectType aac_object
) {
int ret = ERROR_SUCCESS;
SrsStatisticVhost* vhost = create_vhost(req);
SrsStatisticStream* stream = create_stream(vhost, req);
stream->has_audio = true;
stream->acodec = acodec;
stream->asample_rate = asample_rate;
stream->asound_type = asound_type;
stream->aac_object = aac_object;
return ret;
}
void SrsStatistic::on_stream_publish(SrsRequest* req)
{
SrsStatisticVhost* vhost = create_vhost(req);
SrsStatisticStream* stream = create_stream(vhost, req);
stream->publish();
}
void SrsStatistic::on_stream_close(SrsRequest* req)
{
SrsStatisticVhost* vhost = create_vhost(req);
SrsStatisticStream* stream = create_stream(vhost, req);
stream->close();
}
int SrsStatistic::on_client(int id, SrsRequest* req)
{
int ret = ERROR_SUCCESS;
SrsStatisticVhost* vhost = create_vhost(req);
SrsStatisticStream* stream = create_stream(vhost, req);
// create client if not exists
SrsStatisticClient* client = NULL;
if (clients.find(id) == clients.end()) {
client = new SrsStatisticClient();
client->id = id;
client->stream = stream;
clients[id] = client;
} else {
client = clients[id];
}
return ret;
}
void SrsStatistic::on_disconnect(int id)
{
std::map<int, SrsStatisticClient*>::iterator it;
it = clients.find(id);
if (it != clients.end()) {
SrsStatisticClient* client = it->second;
srs_freep(client);
clients.erase(it);
}
}
void SrsStatistic::kbps_add_delta(SrsConnection* conn)
{
int id = conn->srs_id();
if (clients.find(id) == clients.end()) {
return;
}
SrsStatisticClient* client = clients[id];
// resample the kbps to collect the delta.
conn->resample();
// add delta of connection to kbps.
// for next sample() of server kbps can get the stat.
kbps->add_delta(conn);
client->stream->kbps->add_delta(conn);
client->stream->vhost->kbps->add_delta(conn);
// cleanup the delta.
conn->cleanup();
}
SrsKbps* SrsStatistic::kbps_sample()
{
kbps->sample();
if (true) {
std::map<std::string, SrsStatisticVhost*>::iterator it;
for (it = vhosts.begin(); it != vhosts.end(); it++) {
SrsStatisticVhost* vhost = it->second;
vhost->kbps->sample();
}
}
if (true) {
std::map<std::string, SrsStatisticStream*>::iterator it;
for (it = streams.begin(); it != streams.end(); it++) {
SrsStatisticStream* stream = it->second;
stream->kbps->sample();
}
}
return kbps;
}
int64_t SrsStatistic::server_id()
{
return _server_id;
}
int SrsStatistic::dumps_vhosts(stringstream& ss)
{
int ret = ERROR_SUCCESS;
ss << SRS_JARRAY_START;
std::map<std::string, SrsStatisticVhost*>::iterator it;
for (it = vhosts.begin(); it != vhosts.end(); it++) {
SrsStatisticVhost* vhost = it->second;
if (it != vhosts.begin()) {
ss << SRS_JFIELD_CONT;
}
// dumps the config of vhost.
bool hls_enabled = _srs_config->get_hls_enabled(vhost->vhost);
ss << SRS_JOBJECT_START
<< SRS_JFIELD_ORG("id", vhost->id) << SRS_JFIELD_CONT
<< SRS_JFIELD_STR("name", vhost->vhost) << SRS_JFIELD_CONT
<< SRS_JFIELD_ORG("send_bytes", vhost->kbps->get_send_bytes()) << SRS_JFIELD_CONT
<< SRS_JFIELD_ORG("recv_bytes", vhost->kbps->get_recv_bytes()) << SRS_JFIELD_CONT
<< SRS_JFIELD_NAME("hls") << SRS_JOBJECT_START
<< SRS_JFIELD_BOOL("enabled", hls_enabled);
if (hls_enabled) {
ss << SRS_JFIELD_CONT;
ss << SRS_JFIELD_ORG("fragment", _srs_config->get_hls_fragment(vhost->vhost));
}
ss << SRS_JOBJECT_END
<< SRS_JOBJECT_END;
}
ss << SRS_JARRAY_END;
return ret;
}
int SrsStatistic::dumps_streams(stringstream& ss)
{
int ret = ERROR_SUCCESS;
ss << SRS_JARRAY_START;
std::map<std::string, SrsStatisticStream*>::iterator it;
for (it = streams.begin(); it != streams.end(); it++) {
SrsStatisticStream* stream = it->second;
if (it != streams.begin()) {
ss << SRS_JFIELD_CONT;
}
int client_num = 0;
std::map<int, SrsStatisticClient*>::iterator it_client;
for (it_client = clients.begin(); it_client != clients.end(); it_client++) {
SrsStatisticClient* client = it_client->second;
if (client->stream == stream) {
client_num++;
}
}
ss << SRS_JOBJECT_START
<< SRS_JFIELD_ORG("id", stream->id) << SRS_JFIELD_CONT
<< SRS_JFIELD_STR("name", stream->stream) << SRS_JFIELD_CONT
<< SRS_JFIELD_ORG("vhost", stream->vhost->id) << SRS_JFIELD_CONT
<< SRS_JFIELD_STR("app", stream->app) << SRS_JFIELD_CONT
<< SRS_JFIELD_ORG("clients", client_num) << SRS_JFIELD_CONT
<< SRS_JFIELD_ORG("send_bytes", stream->kbps->get_send_bytes()) << SRS_JFIELD_CONT
<< SRS_JFIELD_ORG("recv_bytes", stream->kbps->get_recv_bytes()) << SRS_JFIELD_CONT
<< SRS_JFIELD_ORG("live_ms", srs_get_system_time_ms()) << SRS_JFIELD_CONT
<< SRS_JFIELD_STR("status", stream->status) << SRS_JFIELD_CONT;
if (!stream->has_video) {
ss << SRS_JFIELD_NULL("video") << SRS_JFIELD_CONT;
} else {
ss << SRS_JFIELD_NAME("video")
<< SRS_JOBJECT_START
<< SRS_JFIELD_STR("codec", srs_codec_video2str(stream->vcodec)) << SRS_JFIELD_CONT
<< SRS_JFIELD_STR("profile", srs_codec_avc_profile2str(stream->avc_profile)) << SRS_JFIELD_CONT
<< SRS_JFIELD_ORG("level", srs_codec_avc_level2str(stream->avc_level))
<< SRS_JOBJECT_END
<< SRS_JFIELD_CONT;
}
if (!stream->has_audio) {
ss << SRS_JFIELD_NULL("audio");
} else {
ss << SRS_JFIELD_NAME("audio")
<< SRS_JOBJECT_START
<< SRS_JFIELD_STR("codec", srs_codec_audio2str(stream->acodec)) << SRS_JFIELD_CONT
<< SRS_JFIELD_ORG("sample_rate", (int)flv_sample_rates[stream->asample_rate]) << SRS_JFIELD_CONT
<< SRS_JFIELD_ORG("channel", (int)stream->asound_type + 1) << SRS_JFIELD_CONT
<< SRS_JFIELD_STR("profile", srs_codec_aac_object2str(stream->aac_object))
<< SRS_JOBJECT_END;
}
ss << SRS_JOBJECT_END;
}
ss << SRS_JARRAY_END;
return ret;
}
SrsStatisticVhost* SrsStatistic::create_vhost(SrsRequest* req)
{
SrsStatisticVhost* vhost = NULL;
// create vhost if not exists.
if (vhosts.find(req->vhost) == vhosts.end()) {
vhost = new SrsStatisticVhost();
vhost->vhost = req->vhost;
vhosts[req->vhost] = vhost;
return vhost;
}
vhost = vhosts[req->vhost];
return vhost;
}
SrsStatisticStream* SrsStatistic::create_stream(SrsStatisticVhost* vhost, SrsRequest* req)
{
std::string url = req->get_stream_url();
SrsStatisticStream* stream = NULL;
// create stream if not exists.
if (streams.find(url) == streams.end()) {
stream = new SrsStatisticStream();
stream->vhost = vhost;
stream->stream = req->stream;
stream->app = req->app;
stream->url = url;
streams[url] = stream;
return stream;
}
stream = streams[url];
return stream;
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <unotest/bootstrapfixturebase.hxx>
#include <rtl/strbuf.hxx>
#include <rtl/bootstrap.hxx>
#include <cppuhelper/bootstrap.hxx>
#include <comphelper/processfactory.hxx>
#include <com/sun/star/lang/Locale.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
using namespace ::com::sun::star;
// NB. this constructor is called before any tests are run, once for each
// test function in a rather non-intuitive way. This is why all the 'real'
// heavy lifting is deferred until setUp. setUp and tearDown are interleaved
// between the tests as you might expect.
test::BootstrapFixtureBase::BootstrapFixtureBase()
: m_aSrcRootURL("file://"), m_aSolverRootURL( m_aSrcRootURL ),
m_aWorkdirRootURL(m_aSrcRootURL)
{
#ifndef ANDROID
const char* pSrcRoot = getenv( "SRC_ROOT" );
CPPUNIT_ASSERT_MESSAGE("SRC_ROOT env variable not set", pSrcRoot != NULL && pSrcRoot[0] != 0);
const char* pSolverRoot = getenv( "OUTDIR_FOR_BUILD" );
CPPUNIT_ASSERT_MESSAGE("$OUTDIR_FOR_BUILD env variable not set", pSolverRoot != NULL && pSolverRoot[0] != 0);
const char* pWorkdirRoot = getenv( "WORKDIR_FOR_BUILD" );
CPPUNIT_ASSERT_MESSAGE("$WORKDIR_FOR_BUILD env variable not set", pWorkdirRoot != NULL && pWorkdirRoot[0] != 0);
#ifdef WNT
if (pSrcRoot[1] == ':')
{
m_aSrcRootURL += "/";
}
if (pSolverRoot[1] == ':')
{
m_aSolverRootURL += "/";
}
if (pWorkdirRoot[1] == ':')
{
m_aWorkdirRootURL += "/";
}
#endif
#else
const char* pSrcRoot = "/assets";
const char* pSolverRoot = "/assets";
const char* pWorkdirRoot = "/assets";
#endif
m_aSrcRootPath = OUString::createFromAscii( pSrcRoot );
m_aSrcRootURL += m_aSrcRootPath;
m_aSolverRootPath = OUString::createFromAscii( pSolverRoot );
m_aSolverRootURL += m_aSolverRootPath;
m_aWorkdirRootPath = OUString::createFromAscii( pWorkdirRoot );
m_aWorkdirRootURL += m_aWorkdirRootPath;
}
test::BootstrapFixtureBase::~BootstrapFixtureBase()
{
}
OUString test::BootstrapFixtureBase::getURLFromSrc( const char *pPath )
{
return m_aSrcRootURL + OUString::createFromAscii( pPath );
}
OUString test::BootstrapFixtureBase::getPathFromSrc( const char *pPath )
{
return m_aSrcRootPath + OUString::createFromAscii( pPath );
}
OUString test::BootstrapFixtureBase::getURLFromWorkdir( const char *pPath )
{
return m_aWorkdirRootURL + OUString::createFromAscii( pPath );
}
OUString test::BootstrapFixtureBase::getPathFromWorkdir( const char *pPath )
{
return m_aWorkdirRootPath + OUString::createFromAscii( pPath );
}
void test::BootstrapFixtureBase::setUp()
{
// set UserInstallation to user profile dir in test/user-template
rtl::Bootstrap aDefaultVars;
OUString sUserInstallURL = m_aSolverRootURL + OUString("/unittest");
aDefaultVars.set(OUString("UserInstallation"), sUserInstallURL);
m_xContext = comphelper::getProcessComponentContext();
m_xFactory = m_xContext->getServiceManager();
m_xSFactory = uno::Reference<lang::XMultiServiceFactory>(m_xFactory, uno::UNO_QUERY_THROW);
}
void test::BootstrapFixtureBase::tearDown()
{
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Fix URL creation<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "sal/config.h"
#include <cassert>
#include <unotest/bootstrapfixturebase.hxx>
#include <osl/file.hxx>
#include <rtl/strbuf.hxx>
#include <rtl/bootstrap.hxx>
#include <cppuhelper/bootstrap.hxx>
#include <comphelper/processfactory.hxx>
#include <com/sun/star/lang/Locale.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
using namespace ::com::sun::star;
namespace {
OUString getFileURLFromSystemPath(OUString const & path) {
OUString url;
osl::FileBase::RC e = osl::FileBase::getFileURLFromSystemPath(path, url);
assert(e == osl::FileBase::E_None);
if (!url.endsWith("/")) {
url += "/";
}
return url;
}
}
// NB. this constructor is called before any tests are run, once for each
// test function in a rather non-intuitive way. This is why all the 'real'
// heavy lifting is deferred until setUp. setUp and tearDown are interleaved
// between the tests as you might expect.
test::BootstrapFixtureBase::BootstrapFixtureBase()
{
#ifndef ANDROID
const char* pSrcRoot = getenv( "SRC_ROOT" );
CPPUNIT_ASSERT_MESSAGE("SRC_ROOT env variable not set", pSrcRoot != NULL && pSrcRoot[0] != 0);
const char* pSolverRoot = getenv( "OUTDIR_FOR_BUILD" );
CPPUNIT_ASSERT_MESSAGE("$OUTDIR_FOR_BUILD env variable not set", pSolverRoot != NULL && pSolverRoot[0] != 0);
const char* pWorkdirRoot = getenv( "WORKDIR_FOR_BUILD" );
CPPUNIT_ASSERT_MESSAGE("$WORKDIR_FOR_BUILD env variable not set", pWorkdirRoot != NULL && pWorkdirRoot[0] != 0);
#else
const char* pSrcRoot = "/assets";
const char* pSolverRoot = "/assets";
const char* pWorkdirRoot = "/assets";
#endif
m_aSrcRootPath = OUString::createFromAscii( pSrcRoot );
m_aSrcRootURL = getFileURLFromSystemPath(m_aSrcRootPath);
m_aSolverRootPath = OUString::createFromAscii( pSolverRoot );
m_aSolverRootURL = getFileURLFromSystemPath(m_aSolverRootPath);
m_aWorkdirRootPath = OUString::createFromAscii( pWorkdirRoot );
m_aWorkdirRootURL = getFileURLFromSystemPath(m_aWorkdirRootPath);
}
test::BootstrapFixtureBase::~BootstrapFixtureBase()
{
}
OUString test::BootstrapFixtureBase::getURLFromSrc( const char *pPath )
{
return m_aSrcRootURL + OUString::createFromAscii( pPath );
}
OUString test::BootstrapFixtureBase::getPathFromSrc( const char *pPath )
{
return m_aSrcRootPath + OUString::createFromAscii( pPath );
}
OUString test::BootstrapFixtureBase::getURLFromWorkdir( const char *pPath )
{
return m_aWorkdirRootURL + OUString::createFromAscii( pPath );
}
OUString test::BootstrapFixtureBase::getPathFromWorkdir( const char *pPath )
{
return m_aWorkdirRootPath + OUString::createFromAscii( pPath );
}
void test::BootstrapFixtureBase::setUp()
{
// set UserInstallation to user profile dir in test/user-template
rtl::Bootstrap aDefaultVars;
OUString sUserInstallURL = m_aSolverRootURL + OUString("/unittest");
aDefaultVars.set(OUString("UserInstallation"), sUserInstallURL);
m_xContext = comphelper::getProcessComponentContext();
m_xFactory = m_xContext->getServiceManager();
m_xSFactory = uno::Reference<lang::XMultiServiceFactory>(m_xFactory, uno::UNO_QUERY_THROW);
}
void test::BootstrapFixtureBase::tearDown()
{
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "Token.h"
#include <cassert>
#include <memory>
using namespace std;
using Checkpoint = GraphLang::Parser::Checkpoint;
namespace GraphLang
{
namespace Tokenizer
{
const TokenVisitor::RootTag TokenVisitor::Root = {};
void TokenVisitor::operator()(Token& tok)
{
auto directive = visit(tok);
switch(directive)
{
case Status::Stop:
throw Impl::FullStopException{};
return;
case Status::StopBranch:
return;
case Status::Continue:
tok.expose_children(*this);
}
}
void TokenVisitor::operator()(Token& tok, RootTag)
{
try
{
operator()(tok);
}
catch(Impl::FullStopException)
{
// that's fine :)
}
return; // end of input
}
Token::Token()
{
}
TokenParseResult Token::Parse(Parser& p)
{
assert(false);
return TokenParseResult{ false, "CANT TRY TO PARSE A RAW (TOKEN)!!!!!" };
}
Token::~Token()
{
}
Token::PrintablePosition Token::pos() const
{
return PrintablePosition(startpos, endpos);
}
TokenParseResult Identifier::Parse(Parser& input)
{
auto& in = input.i();
Parser::Checkpoint ch(input, this);
bool digitsOk = false;
char c = in.peek();
while(
c == '_'
|| ('a' <= c && c <= 'z')
|| ('A' <= c && c <= 'Z')
|| (digitsOk && '0' <= c && c <= '9')
)
{
digitsOk = true;
id += in.get();
c = in.peek();
}
if (id.size() > 0)
{
ch.commit();
return TokenParseResult{true, ""};
}
return TokenParseResult{false, "Couldn't match an ID."};
}
TokenParseResult Number::Parse(Parser& p)
{
Checkpoint ch(p, this);
bool makeNegative = false;
if (p.i().peek() == '-')
{
p.i().get();
makeNegative = true;
p.readws();
}
char firstChar = p.i().peek();
if ('0' <= firstChar && firstChar <= '9')
{
p.i() >> num;
if (makeNegative)
{
num *= -1;
}
ch.commit();
return make_tuple(true, "");
}
return make_tuple(false, "Can't interpret as begining of number: "+firstChar);
}
TokenParseResult String::Parse(Parser& p)
{
Checkpoint ch(p, this);
val = "";
auto& i = p.i();
char buf;
i >> buf;
if (buf != '"')
{
return TokenParseResult{false, "Expected '\"' to open string."};
}
while (i.peek() != '"')
{
i >> buf;
if (buf == '\\')
{
i >> buf;
switch (buf)
{
case '\\': val += '\\'; break;
case 'n': val += '\n'; break;
case 't': val += '\t'; break;
case 'r': val += '\r'; break;
case '"' : val += '"'; break;
default:
// This is such a dumb idea!
throw string("Woah! Unknown escape sequence in string: \\"+buf);
}
continue;
}
val += buf;
}
i >> buf;
if (buf != '"')
{
return TokenParseResult{ false, "Expected '\"' to close! string." };
}
ch.commit();
return TokenParseResult{true, ""};
}
TokenParseResult Attribute::Parse(Parser& p)
{
Checkpoint ch(p, this);
if (!get<0>(p.require(id)))
{
return make_tuple(false, "Couldn't match ID in AttributeKV-Pair");
}
if (!p.matchLiteral(":"))
{
return make_tuple(false, "Couldn't match colon in AttributeKV-Pair");
}
auto r = p.require(val);
if (!get<0>(r))
{
return make_tuple(false, "Couldn't match val: (" + get<1>(r) + ") in AttributeKV-Pair");
}
ch.commit();
return make_tuple(true, "");
}
void Attribute::expose_children(TokenVisitor& vis)
{
vis(id);
vis(val);
}
TokenParseResult LiteralValue::Parse(Parser& p)
{
Checkpoint ch(p, this);
// std::move({ make_unique<Number>(), make_unique<String>() })
//vector<unique_ptr<Token>> tokens;
//auto r = p.requireOneOf(std::move(tokens));
auto r = p.oneOf<Number, String>();
auto nodeptr = std::move(get<0>(r));
if (nodeptr == nullptr)
{
return TokenParseResult{false, "Could not match a literal-value token!"};
}
ch.commit();
val = std::move(nodeptr);
return std::get<1>(r);
}
LiteralValue::LiteralValue(const LiteralValue& other)
{
val = nullptr;
if (other.val != nullptr)
{
val = unique_ptr<Token>(other.val->clone());
}
}
void LiteralValue::expose_children(TokenVisitor& v)
{
v(*val.get());
}
NodeValue LiteralValue::toNodeValue() const
{
if (String* strptr = dynamic_cast<String*>(val.get()))
{
return NodeValue(make_unique<std::string>(strptr->val));
}
if (Number* numptr = dynamic_cast<Number*>(val.get()))
{
return NodeValue(numptr->num);
}
return NodeValue{};
}
TokenParseResult Node::Parse(Parser& p)
{
// (hunter name:"Hunter" age:20)
Checkpoint ch(p, this);
TokenParseResult r;
if (!p.matchLiteral("("))
{
return TokenParseResult{ false, "Nodes need to open with a left-paren." };
}
if (p.matchLiteral("?"))
{
// anonymous node!!
identifier = Identifier();
identifier.id = "";
}
else
{
// named node
r = p.require(identifier);
if (!get<0>(r))
{
return TokenParseResult{ false, "Couldn't locate an identifier for the node"};
}
}
while (true)
{
Attribute attr;
r = p.require(attr);
if (! get<0>(r))
{
break;
}
attributes.push_back(make_unique<Attribute>(attr));
}
if (!p.matchLiteral(")"))
{
return TokenParseResult{ false, "Expected node to close with right-paren." };
}
ch.commit();
return TokenParseResult{ true, ""};
}
Node::Node()
{
}
Node::Node(const Node& other)
{
attributes.reserve(other.attributes.size());
for (auto& p: other.attributes)
{
attributes.push_back(unique_ptr<Attribute>(static_cast<Attribute*>(p->clone())));
}
}
void Node::expose_children(TokenVisitor& vis)
{
vis(identifier);
for (auto& attr: attributes)
{
vis(*attr.get());
}
}
::std::ostream& operator<<(::std::ostream& os, const Token::PrintablePosition& pos)
{
os << "(" << pos.b << ", " << pos.e << ")";
return os;
}
TokenParseResult NodeArray::Parse(Parser& p)
{
Checkpoint ch(p, this);
if (!p.matchLiteral("["))
{
// Single node
Node node;
auto r = p.require(node);
if (!get<0>(r))
{
return TokenParseResult{ false,
"Node-Array expected a single node in lieu of bracketed-array, but got (" + get<1>(r) + ")."
};
}
nodes.push_back(node);
ch.commit();
return TokenParseResult{ true, "" };
}
if (p.matchLiteral("]"))
{
// empty vec of nodes
ch.commit();
return TokenParseResult{ true, "Empty NodeArray" };
}
Node primaryNode;
auto r = p.require(primaryNode);
if (!get<0>(r))
{
return TokenParseResult{false, "NodeArray expects non-empty NodeArray internals to start with a Node."};
}
nodes.push_back(primaryNode);
while(p.matchLiteral(","))
{
Node extraNode;
auto xnr = p.require(extraNode);
if (!get<0>(xnr))
{
return TokenParseResult{ false, "NodeArray expects node to follow comma, but got: " + get<1>(xnr) };
}
nodes.push_back(extraNode);
}
// before consume ]
if (!p.matchLiteral("]"))
{
return{false, "Couldn't match closing ] to NodeArray"};
}
ch.commit();
return{ true, "" };
}
void NodeArray::expose_children(TokenVisitor& vis)
{
for (auto& node : nodes)
{
vis(node);
}
}
TokenParseResult Relation::Parse(Parser& p)
{
// <-id- left relation
// -id-> right relation
// <-id-> both relation
// -id- wtf is this???
Checkpoint ch(p, this);
if (p.matchLiteral("<-"))
{
direction.set(Direction::Left);
}
else
{
// at least need a - on the left
if (!p.matchLiteral("-"))
{
return TokenParseResult{false, "Relation expected left to have either a <- or a -"};
}
}
auto r = p.require(relationName);
if (!get<0>(r))
{
return TokenParseResult{
false,
"Relation expects there to be an identifier, but: " + get<1>(r)
};
}
if (p.matchLiteral("->"))
{
direction.set(Direction::Right);
}
else
{
// at least need a - on the right
if (!p.matchLiteral("-"))
{
return TokenParseResult{ false, "Relation expected right to have either a -> or a -" };
}
}
if (!direction.is(Direction::Left) && !direction.is(Direction::Right))
{
return TokenParseResult{ false, "Relation must be either left, right, or both!" };
}
ch.commit();
return TokenParseResult{true, ""};
}
void Relation::expose_children(TokenVisitor& vis)
{
vis(relationName);
}
std::string Relation::Direction::pretty() const
{
switch (field)
{
case 0x0: return "NONE?";
case Dir::Left: return "LEFT";
case Dir::Right: return "RIGHT";
case Dir::Left | Dir::Right: return "LEFT-RIGHT";
default:
assert(0);
return "UNKNOWN!!!";
}
}
TokenParseResult RelationStatement::Parse(Parser& p)
{
Checkpoint ch(p, this);
NodeArray firstNode;
auto r = p.require(firstNode);
if (!get<0>(r))
{
return{false, "RelationStatement expects a nodearray but failed b/c: " + get<1>(r)};
}
nodeSets.push_back(std::move(firstNode));
bool atLeast1 = false;
while(true)
{
Relation rel;
auto rrel = p.require(rel);
if (!get<0>(rrel))
{
// no next relation
break;
}
NodeArray arr;
auto rarr = p.require(arr);
if (!get<0>(rarr))
{
// should be a fatal error really
return {false, "RelationStatement: expected NodeArray to follow relation, but got: " + get<1>(rarr)};
}
relations.emplace_back(std::move(rel));
nodeSets.emplace_back(std::move(arr));
atLeast1 = true;
}
if (!atLeast1)
{
return{false, "RelationStatement: Expected at least a single relation between nodes."};
}
if (!p.matchLiteral(";"))
{
return{ false, "RelationStatement expects to end with ';' and didn't." };
}
ch.commit();
return {true, ""};
}
void RelationStatement::expose_children(TokenVisitor& vis)
{
for (auto& node : nodeSets) vis(node);
for (auto& relation : relations) vis(relation);
}
TokenParseResult SingleNodeStatement::Parse(Parser& p)
{
Checkpoint ch(p, this);
if (!get<0>(p.require(node)))
{
return{ false, "SingleNodeStatement requires a single node!" };
}
if (!p.matchLiteral(";"))
{
return{ false, "SingleNodeStatement expects a node to be followed by ';'" };
}
ch.commit();
return{ true, "" };
}
void SingleNodeStatement::expose_children(TokenVisitor& vis)
{
vis(node);
}
TokenParseResult NodeArrayDeclarationStatement::Parse(Parser& p)
{
Checkpoint ch(p, this);
if (!get<0>(p.require(nodearr)))
{
return{ false, "NodeArrayDeclarationStatement requires a node array!" };
}
if (!p.matchLiteral(";"))
{
return{ false, "NodeArrayDeclarationStatement expects a nodearray to be followed by ';'" };
}
ch.commit();
return{ true, "" };
}
void NodeArrayDeclarationStatement::expose_children(TokenVisitor& vis)
{
vis(nodearr);
}
}; // /namespace Tokenizer
}; // /namespace GraphLang
<commit_msg>Disable anon nodes<commit_after>#include "stdafx.h"
#include "Token.h"
#include <cassert>
#include <memory>
using namespace std;
using Checkpoint = GraphLang::Parser::Checkpoint;
namespace GraphLang
{
namespace Tokenizer
{
const TokenVisitor::RootTag TokenVisitor::Root = {};
void TokenVisitor::operator()(Token& tok)
{
auto directive = visit(tok);
switch(directive)
{
case Status::Stop:
throw Impl::FullStopException{};
return;
case Status::StopBranch:
return;
case Status::Continue:
tok.expose_children(*this);
}
}
void TokenVisitor::operator()(Token& tok, RootTag)
{
try
{
operator()(tok);
}
catch(Impl::FullStopException)
{
// that's fine :)
}
return; // end of input
}
Token::Token()
{
}
TokenParseResult Token::Parse(Parser& p)
{
assert(false);
return TokenParseResult{ false, "CANT TRY TO PARSE A RAW (TOKEN)!!!!!" };
}
Token::~Token()
{
}
Token::PrintablePosition Token::pos() const
{
return PrintablePosition(startpos, endpos);
}
TokenParseResult Identifier::Parse(Parser& input)
{
auto& in = input.i();
Parser::Checkpoint ch(input, this);
bool digitsOk = false;
char c = in.peek();
while(
c == '_'
|| ('a' <= c && c <= 'z')
|| ('A' <= c && c <= 'Z')
|| (digitsOk && '0' <= c && c <= '9')
)
{
digitsOk = true;
id += in.get();
c = in.peek();
}
if (id.size() > 0)
{
ch.commit();
return TokenParseResult{true, ""};
}
return TokenParseResult{false, "Couldn't match an ID."};
}
TokenParseResult Number::Parse(Parser& p)
{
Checkpoint ch(p, this);
bool makeNegative = false;
if (p.i().peek() == '-')
{
p.i().get();
makeNegative = true;
p.readws();
}
char firstChar = p.i().peek();
if ('0' <= firstChar && firstChar <= '9')
{
p.i() >> num;
if (makeNegative)
{
num *= -1;
}
ch.commit();
return make_tuple(true, "");
}
return make_tuple(false, "Can't interpret as begining of number: "+firstChar);
}
TokenParseResult String::Parse(Parser& p)
{
Checkpoint ch(p, this);
val = "";
auto& i = p.i();
char buf;
i >> buf;
if (buf != '"')
{
return TokenParseResult{false, "Expected '\"' to open string."};
}
while (i.peek() != '"')
{
i >> buf;
if (buf == '\\')
{
i >> buf;
switch (buf)
{
case '\\': val += '\\'; break;
case 'n': val += '\n'; break;
case 't': val += '\t'; break;
case 'r': val += '\r'; break;
case '"' : val += '"'; break;
default:
// This is such a dumb idea!
throw string("Woah! Unknown escape sequence in string: \\"+buf);
}
continue;
}
val += buf;
}
i >> buf;
if (buf != '"')
{
return TokenParseResult{ false, "Expected '\"' to close! string." };
}
ch.commit();
return TokenParseResult{true, ""};
}
TokenParseResult Attribute::Parse(Parser& p)
{
Checkpoint ch(p, this);
if (!get<0>(p.require(id)))
{
return make_tuple(false, "Couldn't match ID in AttributeKV-Pair");
}
if (!p.matchLiteral(":"))
{
return make_tuple(false, "Couldn't match colon in AttributeKV-Pair");
}
auto r = p.require(val);
if (!get<0>(r))
{
return make_tuple(false, "Couldn't match val: (" + get<1>(r) + ") in AttributeKV-Pair");
}
ch.commit();
return make_tuple(true, "");
}
void Attribute::expose_children(TokenVisitor& vis)
{
vis(id);
vis(val);
}
TokenParseResult LiteralValue::Parse(Parser& p)
{
Checkpoint ch(p, this);
// std::move({ make_unique<Number>(), make_unique<String>() })
//vector<unique_ptr<Token>> tokens;
//auto r = p.requireOneOf(std::move(tokens));
auto r = p.oneOf<Number, String>();
auto nodeptr = std::move(get<0>(r));
if (nodeptr == nullptr)
{
return TokenParseResult{false, "Could not match a literal-value token!"};
}
ch.commit();
val = std::move(nodeptr);
return std::get<1>(r);
}
LiteralValue::LiteralValue(const LiteralValue& other)
{
val = nullptr;
if (other.val != nullptr)
{
val = unique_ptr<Token>(other.val->clone());
}
}
void LiteralValue::expose_children(TokenVisitor& v)
{
v(*val.get());
}
NodeValue LiteralValue::toNodeValue() const
{
if (String* strptr = dynamic_cast<String*>(val.get()))
{
return NodeValue(make_unique<std::string>(strptr->val));
}
if (Number* numptr = dynamic_cast<Number*>(val.get()))
{
return NodeValue(numptr->num);
}
return NodeValue{};
}
TokenParseResult Node::Parse(Parser& p)
{
// (hunter name:"Hunter" age:20)
Checkpoint ch(p, this);
TokenParseResult r;
if (!p.matchLiteral("("))
{
return TokenParseResult{ false, "Nodes need to open with a left-paren." };
}
// TODO(Hunter): enable anonymous node support
if (false && p.matchLiteral("?"))
{
// anonymous node!!
identifier = Identifier();
identifier.id = "";
}
else
{
// named node
r = p.require(identifier);
if (!get<0>(r))
{
return TokenParseResult{ false, "Couldn't locate an identifier for the node"};
}
}
while (true)
{
Attribute attr;
r = p.require(attr);
if (! get<0>(r))
{
break;
}
attributes.push_back(make_unique<Attribute>(attr));
}
if (!p.matchLiteral(")"))
{
return TokenParseResult{ false, "Expected node to close with right-paren." };
}
ch.commit();
return TokenParseResult{ true, ""};
}
Node::Node()
{
}
Node::Node(const Node& other)
{
attributes.reserve(other.attributes.size());
for (auto& p: other.attributes)
{
attributes.push_back(unique_ptr<Attribute>(static_cast<Attribute*>(p->clone())));
}
}
void Node::expose_children(TokenVisitor& vis)
{
vis(identifier);
for (auto& attr: attributes)
{
vis(*attr.get());
}
}
::std::ostream& operator<<(::std::ostream& os, const Token::PrintablePosition& pos)
{
os << "(" << pos.b << ", " << pos.e << ")";
return os;
}
TokenParseResult NodeArray::Parse(Parser& p)
{
Checkpoint ch(p, this);
if (!p.matchLiteral("["))
{
// Single node
Node node;
auto r = p.require(node);
if (!get<0>(r))
{
return TokenParseResult{ false,
"Node-Array expected a single node in lieu of bracketed-array, but got (" + get<1>(r) + ")."
};
}
nodes.push_back(node);
ch.commit();
return TokenParseResult{ true, "" };
}
if (p.matchLiteral("]"))
{
// empty vec of nodes
ch.commit();
return TokenParseResult{ true, "Empty NodeArray" };
}
Node primaryNode;
auto r = p.require(primaryNode);
if (!get<0>(r))
{
return TokenParseResult{false, "NodeArray expects non-empty NodeArray internals to start with a Node."};
}
nodes.push_back(primaryNode);
while(p.matchLiteral(","))
{
Node extraNode;
auto xnr = p.require(extraNode);
if (!get<0>(xnr))
{
return TokenParseResult{ false, "NodeArray expects node to follow comma, but got: " + get<1>(xnr) };
}
nodes.push_back(extraNode);
}
// before consume ]
if (!p.matchLiteral("]"))
{
return{false, "Couldn't match closing ] to NodeArray"};
}
ch.commit();
return{ true, "" };
}
void NodeArray::expose_children(TokenVisitor& vis)
{
for (auto& node : nodes)
{
vis(node);
}
}
TokenParseResult Relation::Parse(Parser& p)
{
// <-id- left relation
// -id-> right relation
// <-id-> both relation
// -id- wtf is this???
Checkpoint ch(p, this);
if (p.matchLiteral("<-"))
{
direction.set(Direction::Left);
}
else
{
// at least need a - on the left
if (!p.matchLiteral("-"))
{
return TokenParseResult{false, "Relation expected left to have either a <- or a -"};
}
}
auto r = p.require(relationName);
if (!get<0>(r))
{
return TokenParseResult{
false,
"Relation expects there to be an identifier, but: " + get<1>(r)
};
}
if (p.matchLiteral("->"))
{
direction.set(Direction::Right);
}
else
{
// at least need a - on the right
if (!p.matchLiteral("-"))
{
return TokenParseResult{ false, "Relation expected right to have either a -> or a -" };
}
}
if (!direction.is(Direction::Left) && !direction.is(Direction::Right))
{
return TokenParseResult{ false, "Relation must be either left, right, or both!" };
}
ch.commit();
return TokenParseResult{true, ""};
}
void Relation::expose_children(TokenVisitor& vis)
{
vis(relationName);
}
std::string Relation::Direction::pretty() const
{
switch (field)
{
case 0x0: return "NONE?";
case Dir::Left: return "LEFT";
case Dir::Right: return "RIGHT";
case Dir::Left | Dir::Right: return "LEFT-RIGHT";
default:
assert(0);
return "UNKNOWN!!!";
}
}
TokenParseResult RelationStatement::Parse(Parser& p)
{
Checkpoint ch(p, this);
NodeArray firstNode;
auto r = p.require(firstNode);
if (!get<0>(r))
{
return{false, "RelationStatement expects a nodearray but failed b/c: " + get<1>(r)};
}
nodeSets.push_back(std::move(firstNode));
bool atLeast1 = false;
while(true)
{
Relation rel;
auto rrel = p.require(rel);
if (!get<0>(rrel))
{
// no next relation
break;
}
NodeArray arr;
auto rarr = p.require(arr);
if (!get<0>(rarr))
{
// should be a fatal error really
return {false, "RelationStatement: expected NodeArray to follow relation, but got: " + get<1>(rarr)};
}
relations.emplace_back(std::move(rel));
nodeSets.emplace_back(std::move(arr));
atLeast1 = true;
}
if (!atLeast1)
{
return{false, "RelationStatement: Expected at least a single relation between nodes."};
}
if (!p.matchLiteral(";"))
{
return{ false, "RelationStatement expects to end with ';' and didn't." };
}
ch.commit();
return {true, ""};
}
void RelationStatement::expose_children(TokenVisitor& vis)
{
for (auto& node : nodeSets) vis(node);
for (auto& relation : relations) vis(relation);
}
TokenParseResult SingleNodeStatement::Parse(Parser& p)
{
Checkpoint ch(p, this);
if (!get<0>(p.require(node)))
{
return{ false, "SingleNodeStatement requires a single node!" };
}
if (!p.matchLiteral(";"))
{
return{ false, "SingleNodeStatement expects a node to be followed by ';'" };
}
ch.commit();
return{ true, "" };
}
void SingleNodeStatement::expose_children(TokenVisitor& vis)
{
vis(node);
}
TokenParseResult NodeArrayDeclarationStatement::Parse(Parser& p)
{
Checkpoint ch(p, this);
if (!get<0>(p.require(nodearr)))
{
return{ false, "NodeArrayDeclarationStatement requires a node array!" };
}
if (!p.matchLiteral(";"))
{
return{ false, "NodeArrayDeclarationStatement expects a nodearray to be followed by ';'" };
}
ch.commit();
return{ true, "" };
}
void NodeArrayDeclarationStatement::expose_children(TokenVisitor& vis)
{
vis(nodearr);
}
}; // /namespace Tokenizer
}; // /namespace GraphLang
<|endoftext|>
|
<commit_before>#include "application.h"
// POSIX
#include <fcntl.h>
// POSIX++
#include <cstring> // for strerror()
#include <cstdlib> // for exit
// STL
#include <atomic>
#include <list>
// PDTK
#include <cxxutils/error_helpers.h>
#ifndef VTERM_H
namespace terminal
{ const char* const critical = "\x1b[0;41;37;1mCRITICAL ERROR:\x1b[0m "; }
#endif
// atomic vars are to avoid race conditions
static std::atomic_int s_return_value (0);
static std::atomic_bool s_run (true); // quit signal
static posix::fd_t s_pipeio[2] = { posix::invalid_descriptor }; // execution stepper pipe
lockable<std::queue<vfunc>> Application::ms_signal_queue;
lockable<std::unordered_multimap<posix::fd_t, std::pair<EventFlags_t, vfdfunc>>> Application::ms_fd_signals;
enum {
Read = 0,
Write = 1,
};
Application::Application(void) noexcept
{
if(s_pipeio[Read] == posix::invalid_descriptor) // if execution stepper pipe hasn't been initialized yet
{
flaw(::pipe(s_pipeio) == posix::error_response, terminal::critical, std::exit(errno),,
"Unable to create pipe for execution stepper: %s", std::strerror(errno))
::fcntl(s_pipeio[Read], F_SETFD, FD_CLOEXEC);
::fcntl(s_pipeio[Read], F_SETFL, O_NONBLOCK);
EventBackend::init(); // initialize event backend
EventBackend::watch(s_pipeio[Read], EventFlags::Readable); // watch for when execution stepper pipe has been triggered
}
}
Application::~Application(void) noexcept
{
if(s_pipeio[Read] != posix::invalid_descriptor)
{
EventBackend::destroy(); // shutdown event backend
posix::close(s_pipeio[Read ]);
posix::close(s_pipeio[Write]);
s_pipeio[Read ] = posix::invalid_descriptor;
s_pipeio[Write] = posix::invalid_descriptor;
}
}
void Application::step(void) noexcept
{
static const uint8_t dummydata = 0; // dummy content
flaw(posix::write(s_pipeio[Write], &dummydata, 1) != 1, terminal::critical, /*std::exit(errno)*/,, // triggers execution stepper FD
"Unable to trigger Object signal queue processor: %s", std::strerror(errno))
}
int Application::exec(void) noexcept // non-static function to ensure an instance of Application exists
{
while(s_run) // while not quitting
{
EventBackend::getevents(); // get event queue
for(const std::pair<posix::fd_t, EventData_t> pos : EventBackend::results) // process queued events
{
if(pos.first == s_pipeio[Read]) // if this is the execution stepper pipe (via Object::enqueue())
{
uint64_t discard;
while(posix::read(pos.first, &discard, sizeof(discard)) != posix::error_response);
// execute queue of object signal calls
static std::queue<vfunc> exec_queue;
if(exec_queue.empty()) // if not currently executing (recursive or multithread exec() calls?)
{
ms_signal_queue.lock(); // get exclusive access (make thread-safe)
exec_queue.swap(ms_signal_queue); // swap the queues
ms_signal_queue.unlock(); // access is no longer needed
while(!exec_queue.empty()) // while still have object signals to execute
{
exec_queue.front()(); // execute current object signal/callback
exec_queue.pop(); // discard current object signal
}
}
}
else // if this was a watched FD
{
ms_fd_signals.lock(); // get exclusive access (make thread-safe)
auto entries = ms_fd_signals.equal_range(pos.first); // get all the callback entries for that FD
std::list<std::pair<posix::fd_t, std::pair<EventFlags_t, vfdfunc>>> exec_fds(entries.first, entries.second); // copy entries
ms_fd_signals.unlock(); // access is no longer needed
for(auto& entry : exec_fds) // for each FD
{
if(entry.second.first.isSet(pos.second.flags)) // if the flags match
entry.second.second(pos.first, pos.second); // call the fuction with the FD and triggering EventFlag
}
}
}
}
return s_return_value; // quit() has been called, return value specified
}
void Application::quit(int return_value) noexcept // soft application exit (allows event queues to complete)
{
if(s_run) // if not already quitting
{
s_return_value = return_value; // set application return value
s_run = false; // indicate program must quit
}
}
<commit_msg>readd vterm dependency<commit_after>#include "application.h"
// POSIX
#include <fcntl.h>
// POSIX++
#include <cstring> // for strerror()
#include <cstdlib> // for exit
// STL
#include <atomic>
#include <list>
// PDTK
#include <cxxutils/vterm.h>
#include <cxxutils/error_helpers.h>
// atomic vars are to avoid race conditions
static std::atomic_int s_return_value (0);
static std::atomic_bool s_run (true); // quit signal
static posix::fd_t s_pipeio[2] = { posix::invalid_descriptor }; // execution stepper pipe
lockable<std::queue<vfunc>> Application::ms_signal_queue;
lockable<std::unordered_multimap<posix::fd_t, std::pair<EventFlags_t, vfdfunc>>> Application::ms_fd_signals;
enum {
Read = 0,
Write = 1,
};
Application::Application(void) noexcept
{
if(s_pipeio[Read] == posix::invalid_descriptor) // if execution stepper pipe hasn't been initialized yet
{
flaw(::pipe(s_pipeio) == posix::error_response, terminal::critical, std::exit(errno),,
"Unable to create pipe for execution stepper: %s", std::strerror(errno))
::fcntl(s_pipeio[Read], F_SETFD, FD_CLOEXEC);
::fcntl(s_pipeio[Read], F_SETFL, O_NONBLOCK);
EventBackend::init(); // initialize event backend
EventBackend::watch(s_pipeio[Read], EventFlags::Readable); // watch for when execution stepper pipe has been triggered
}
}
Application::~Application(void) noexcept
{
if(s_pipeio[Read] != posix::invalid_descriptor)
{
EventBackend::destroy(); // shutdown event backend
posix::close(s_pipeio[Read ]);
posix::close(s_pipeio[Write]);
s_pipeio[Read ] = posix::invalid_descriptor;
s_pipeio[Write] = posix::invalid_descriptor;
}
}
void Application::step(void) noexcept
{
static const uint8_t dummydata = 0; // dummy content
flaw(posix::write(s_pipeio[Write], &dummydata, 1) != 1, terminal::critical, /*std::exit(errno)*/,, // triggers execution stepper FD
"Unable to trigger Object signal queue processor: %s", std::strerror(errno))
}
int Application::exec(void) noexcept // non-static function to ensure an instance of Application exists
{
while(s_run) // while not quitting
{
EventBackend::getevents(); // get event queue
for(const std::pair<posix::fd_t, EventData_t> pos : EventBackend::results) // process queued events
{
if(pos.first == s_pipeio[Read]) // if this is the execution stepper pipe (via Object::enqueue())
{
uint64_t discard;
while(posix::read(pos.first, &discard, sizeof(discard)) != posix::error_response);
// execute queue of object signal calls
static std::queue<vfunc> exec_queue;
if(exec_queue.empty()) // if not currently executing (recursive or multithread exec() calls?)
{
ms_signal_queue.lock(); // get exclusive access (make thread-safe)
exec_queue.swap(ms_signal_queue); // swap the queues
ms_signal_queue.unlock(); // access is no longer needed
while(!exec_queue.empty()) // while still have object signals to execute
{
exec_queue.front()(); // execute current object signal/callback
exec_queue.pop(); // discard current object signal
}
}
}
else // if this was a watched FD
{
ms_fd_signals.lock(); // get exclusive access (make thread-safe)
auto entries = ms_fd_signals.equal_range(pos.first); // get all the callback entries for that FD
std::list<std::pair<posix::fd_t, std::pair<EventFlags_t, vfdfunc>>> exec_fds(entries.first, entries.second); // copy entries
ms_fd_signals.unlock(); // access is no longer needed
for(auto& entry : exec_fds) // for each FD
{
if(entry.second.first.isSet(pos.second.flags)) // if the flags match
entry.second.second(pos.first, pos.second); // call the fuction with the FD and triggering EventFlag
}
}
}
}
return s_return_value; // quit() has been called, return value specified
}
void Application::quit(int return_value) noexcept // soft application exit (allows event queues to complete)
{
if(s_run) // if not already quitting
{
s_return_value = return_value; // set application return value
s_run = false; // indicate program must quit
}
}
<|endoftext|>
|
<commit_before>
/*************************************************************************
* 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. *
*************************************************************************/
#include "TBenchmark.h"
#include "TROOT.h"
#include "TStopwatch.h"
TBenchmark *gBenchmark = 0;
ClassImp(TBenchmark)
//______________________________________________________________________________
//////////////////////////////////////////////////////////////////////////
//
// This class is a ROOT utility to help benchmarking applications
//
// Examples of use of this class are given in the tutorials macros.
//////////////////////////////////////////////////////////////////////////
//______________________________________________________________________________
TBenchmark::TBenchmark(): TNamed()
{
//*-*-*-*-*-*-*-*-*-*-*Benchmark default constructor*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-* =============================
fNbench = 0;
fNmax = 20;
fNames = 0;
fRealTime = 0;
fCpuTime = 0;
fTimer = 0;
}
//______________________________________________________________________________
TBenchmark::TBenchmark(const TBenchmark& bm) :
TNamed(bm),
fNbench(bm.fNbench),
fNmax(bm.fNmax),
fNames(0),
fRealTime(0),
fCpuTime(0),
fTimer(0)
{
//copy constructor
fNames = new TString[fNmax];
fRealTime = new Float_t[fNmax];
fCpuTime = new Float_t[fNmax];
fTimer = new TStopwatch[fNmax];
for(Int_t i = 0; i<fNmax; ++i) {
fNames[i] = bm.fNames[i];
fRealTime[i] = bm.fRealTime[i];
fCpuTime[i] = bm.fCpuTime[i];
fTimer[i] = bm.fTimer[i];
}
}
//______________________________________________________________________________
TBenchmark& TBenchmark::operator=(const TBenchmark& bm)
{
//assignment operator
if(this!=&bm) {
TNamed::operator=(bm);
fNbench=bm.fNbench;
fNmax=bm.fNmax;
delete [] fNames;
delete [] fRealTime;
delete [] fCpuTime;
delete [] fTimer;
fNames = new TString[fNmax];
fRealTime = new Float_t[fNmax];
fCpuTime = new Float_t[fNmax];
fTimer = new TStopwatch[fNmax];
for(Int_t i = 0; i<fNmax; ++i) {
fNames[i] = bm.fNames[i];
fRealTime[i] = bm.fRealTime[i];
fCpuTime[i] = bm.fCpuTime[i];
fTimer[i] = bm.fTimer[i];
}
}
return *this;
}
//______________________________________________________________________________
TBenchmark::~TBenchmark()
{
//*-*-*-*-*-*-*-*-*-*-*Benchmark default destructor*-*-*-*-*-*-*-*-*-*-*-*-*-*
//*-* ============================
fNbench = 0;
if (fNames) { delete [] fNames; fNames = 0;}
if (fRealTime) { delete [] fRealTime; fRealTime = 0;}
if (fCpuTime) { delete [] fCpuTime; fCpuTime = 0;}
if (fTimer ) { delete [] fTimer; fTimer = 0;}
}
//______________________________________________________________________________
Int_t TBenchmark::GetBench(const char *name) const
{
//*-*-*-*-*-*-*-*-*-*-*Returns index of Benchmark name*-*-*-*-*-*-*-*
//*-* ===============================
for (Int_t i=0;i<fNbench;i++) {
if (!strcmp(name,(const char*)fNames[i])) return i;
}
return -1;
}
//______________________________________________________________________________
Float_t TBenchmark::GetCpuTime(const char *name)
{
//*-*-*-*-*-*-*-*-*-*-*Returns Cpu time used by Benchmark name*-*-*-*-*-*-*-*
//*-* =======================================
Int_t bench = GetBench(name);
if (bench >= 0) return fCpuTime[bench];
else return 0;
}
//______________________________________________________________________________
Float_t TBenchmark::GetRealTime(const char *name)
{
//*-*-*-*-*-*-*-*-*-*-*Returns Realtime used by Benchmark name*-*-*-*-*-*-*-*
//*-* =======================================
Int_t bench = GetBench(name);
if (bench >= 0) return fRealTime[bench];
else return 0;
}
//______________________________________________________________________________
void TBenchmark::Print(const char *name) const
{
//*-*-*-*-*-*-*-*-*-*-*Prints parameters of Benchmark name*-*-*-*-*-*-*-*-*-*
//*-* ===================================
Int_t bench = GetBench(name);
if (bench < 0) return;
Printf("%-10s: Real Time = %6.2f seconds Cpu Time = %6.2f seconds",name,fRealTime[bench],fCpuTime[bench]);
}
//______________________________________________________________________________
void TBenchmark::Reset()
{
//*-*-*-*-*-*-*-*-*-*-*-*-*-*Reset all Benchmarks*-*-*-*-*-*-*-*-*-*-*-*-*
//*-* ====================
fNbench = 0;
}
//______________________________________________________________________________
void TBenchmark::Show(const char *name)
{
//*-*-*-*-*-*-*-*-*Stops Benchmark name and Prints results*-*-*-*-*-*-*-*-*-*
//*-* =======================================
Stop(name);
Print((char*)name);
}
//______________________________________________________________________________
void TBenchmark::Start(const char *name)
{
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*Starts Benchmark name*-*-*-*-*-*-*-*-*-*
//*-* =====================
//*-*
//*-* An independent timer (see class TStopwatch) is started.
//*-* the name of the benchmark is entered into the list of benchmarks.
//*-* Benchmark can be stopped via TBenchmark::Stop
//*-* Results can be printed via TBenchmark::Print
//*-* TBenchmark::Show can be used to stop benchmark and print results.
//*-* If name is an already existing benchmark, existing parameters are reset.
//*-* A summary of all benchmarks can be seen via TBenchmark::Summary.
//*-*
//*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-**-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
if (!fNames) {
fNames = new TString[fNmax];
fRealTime = new Float_t[fNmax];
fCpuTime = new Float_t[fNmax];
fTimer = new TStopwatch[fNmax];
}
Int_t bench = GetBench(name);
if (bench < 0 && fNbench < fNmax ) {
// define a new benchmark to Start
fNames[fNbench] = name;
bench = fNbench;
fNbench++;
fTimer[bench].Reset();
fTimer[bench].Start();
fRealTime[bench] = 0;
fCpuTime[bench] = 0;
} else if (bench >=0) {
// Resume the existen benchmark
fTimer[bench].Continue();
}
else
Warning("Start","too many benches");
}
//______________________________________________________________________________
void TBenchmark::Stop(const char *name)
{
//*-*-*-*-*-*-*-*-*-*-*Terminates Benchmark name*-*-*-*-*-*-*-*-*-*-*-*
//*-* =========================
Int_t bench = GetBench(name);
if (bench < 0) return;
fTimer[bench].Stop();
fRealTime[bench] = fTimer[bench].RealTime();
fCpuTime[bench] = fTimer[bench].CpuTime();
}
//______________________________________________________________________________
void TBenchmark::Summary(Float_t &rt, Float_t &cp)
{
//*-*-*-*-*-*-*-*-*-*-*-*-*-*Prints a summary of all benchmarks*-*-*-*-*-*-*-*
//*-* ==================================
rt = 0;
cp = 0;
for (Int_t i=0;i<fNbench;i++) {
Printf("%-10s: Real Time = %6.2f seconds Cpu Time = %6.2f seconds",(const char*)fNames[i],fRealTime[i],fCpuTime[i]);
rt += fRealTime[i];
cp += fCpuTime[i];
}
Printf("%-10s: Real Time = %6.2f seconds Cpu Time = %6.2f seconds","TOTAL",rt,cp);
}
<commit_msg>Fix comment in Start(), starting of an existing benchmark will resume the benchmark, not reset it.<commit_after>
/*************************************************************************
* 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. *
*************************************************************************/
#include "TBenchmark.h"
#include "TROOT.h"
#include "TStopwatch.h"
TBenchmark *gBenchmark = 0;
ClassImp(TBenchmark)
//////////////////////////////////////////////////////////////////////////
// //
// TBenchmark //
// //
// This class is a ROOT utility to help benchmarking applications //
// //
//////////////////////////////////////////////////////////////////////////
//______________________________________________________________________________
TBenchmark::TBenchmark(): TNamed()
{
// Benchmark default constructor
fNbench = 0;
fNmax = 20;
fNames = 0;
fRealTime = 0;
fCpuTime = 0;
fTimer = 0;
}
//______________________________________________________________________________
TBenchmark::TBenchmark(const TBenchmark& bm) :
TNamed(bm),
fNbench(bm.fNbench),
fNmax(bm.fNmax),
fNames(0),
fRealTime(0),
fCpuTime(0),
fTimer(0)
{
// Copy constructor.
fNames = new TString[fNmax];
fRealTime = new Float_t[fNmax];
fCpuTime = new Float_t[fNmax];
fTimer = new TStopwatch[fNmax];
for(Int_t i = 0; i<fNmax; ++i) {
fNames[i] = bm.fNames[i];
fRealTime[i] = bm.fRealTime[i];
fCpuTime[i] = bm.fCpuTime[i];
fTimer[i] = bm.fTimer[i];
}
}
//______________________________________________________________________________
TBenchmark& TBenchmark::operator=(const TBenchmark& bm)
{
// Assignment operator.
if (this!=&bm) {
TNamed::operator=(bm);
fNbench=bm.fNbench;
fNmax=bm.fNmax;
delete [] fNames;
delete [] fRealTime;
delete [] fCpuTime;
delete [] fTimer;
fNames = new TString[fNmax];
fRealTime = new Float_t[fNmax];
fCpuTime = new Float_t[fNmax];
fTimer = new TStopwatch[fNmax];
for(Int_t i = 0; i<fNmax; ++i) {
fNames[i] = bm.fNames[i];
fRealTime[i] = bm.fRealTime[i];
fCpuTime[i] = bm.fCpuTime[i];
fTimer[i] = bm.fTimer[i];
}
}
return *this;
}
//______________________________________________________________________________
TBenchmark::~TBenchmark()
{
// Benchmark destructor.
fNbench = 0;
if (fNames) { delete [] fNames; fNames = 0;}
if (fRealTime) { delete [] fRealTime; fRealTime = 0;}
if (fCpuTime) { delete [] fCpuTime; fCpuTime = 0;}
if (fTimer ) { delete [] fTimer; fTimer = 0;}
}
//______________________________________________________________________________
Int_t TBenchmark::GetBench(const char *name) const
{
// Returns index of Benchmark name.
for (Int_t i=0;i<fNbench;i++) {
if (!strcmp(name,(const char*)fNames[i])) return i;
}
return -1;
}
//______________________________________________________________________________
Float_t TBenchmark::GetCpuTime(const char *name)
{
// Returns Cpu time used by Benchmark name.
Int_t bench = GetBench(name);
if (bench >= 0) return fCpuTime[bench];
else return 0;
}
//______________________________________________________________________________
Float_t TBenchmark::GetRealTime(const char *name)
{
// Returns Realtime used by Benchmark name.
Int_t bench = GetBench(name);
if (bench >= 0) return fRealTime[bench];
else return 0;
}
//______________________________________________________________________________
void TBenchmark::Print(const char *name) const
{
// Prints parameters of Benchmark name.
Int_t bench = GetBench(name);
if (bench < 0) return;
Printf("%-10s: Real Time = %6.2f seconds Cpu Time = %6.2f seconds",name,fRealTime[bench],fCpuTime[bench]);
}
//______________________________________________________________________________
void TBenchmark::Reset()
{
// Reset all Benchmarks
fNbench = 0;
}
//______________________________________________________________________________
void TBenchmark::Show(const char *name)
{
// Stops Benchmark name and Prints results
Stop(name);
Print((char*)name);
}
//______________________________________________________________________________
void TBenchmark::Start(const char *name)
{
// Starts Benchmark with the specified name.
//
// An independent timer (see class TStopwatch) is started.
// The name of the benchmark is entered into the list of benchmarks.
// Benchmark can be stopped via TBenchmark::Stop().
// Results can be printed via TBenchmark::Print().
// TBenchmark::Show() can be used to stop benchmark and print results.
// If name is an already existing benchmark, timing will resume.
// A summary of all benchmarks can be seen via TBenchmark::Summary().
if (!fNames) {
fNames = new TString[fNmax];
fRealTime = new Float_t[fNmax];
fCpuTime = new Float_t[fNmax];
fTimer = new TStopwatch[fNmax];
}
Int_t bench = GetBench(name);
if (bench < 0 && fNbench < fNmax ) {
// define a new benchmark to Start
fNames[fNbench] = name;
bench = fNbench;
fNbench++;
fTimer[bench].Reset();
fTimer[bench].Start();
fRealTime[bench] = 0;
fCpuTime[bench] = 0;
} else if (bench >= 0) {
// Resume the existing benchmark
fTimer[bench].Continue();
}
else
Warning("Start","too many benchemarks");
}
//______________________________________________________________________________
void TBenchmark::Stop(const char *name)
{
// Terminates Benchmark with specified name.
Int_t bench = GetBench(name);
if (bench < 0) return;
fTimer[bench].Stop();
fRealTime[bench] = fTimer[bench].RealTime();
fCpuTime[bench] = fTimer[bench].CpuTime();
}
//______________________________________________________________________________
void TBenchmark::Summary(Float_t &rt, Float_t &cp)
{
// Prints a summary of all benchmarks.
rt = 0;
cp = 0;
for (Int_t i=0;i<fNbench;i++) {
Printf("%-10s: Real Time = %6.2f seconds Cpu Time = %6.2f seconds",(const char*)fNames[i],fRealTime[i],fCpuTime[i]);
rt += fRealTime[i];
cp += fCpuTime[i];
}
Printf("%-10s: Real Time = %6.2f seconds Cpu Time = %6.2f seconds","TOTAL",rt,cp);
}
<|endoftext|>
|
<commit_before>#include "trajopt/configuration_space.hpp"
#include <boost/foreach.hpp>
#include "trajopt/rave_utils.hpp"
#include "utils/math.hpp"
using namespace OpenRAVE;
using namespace util;
// TODO: configuration should know something about what dofs are part of SO(1), SO(2) etc for functions like RandomDOFValues
namespace trajopt {
void RobotAndDOF::SetDOFValues(const DblVec& dofs) {
if (affinedofs != 0) {
OR::Transform T;
OR::RaveGetTransformFromAffineDOFValues(T, dofs.begin()+joint_inds.size(), affinedofs, rotationaxis, true);
robot->SetTransform(T);
if (joint_inds.size() > 0)
robot->SetDOFValues(dofs, false, joint_inds);
}
else {
robot->SetDOFValues(dofs, false, joint_inds);
}
}
DblVec RobotAndDOF::GetDOFValues() {
DblVec out;
if (joint_inds.size() > 0):
robot->GetDOFValues(out, joint_inds);
if (affinedofs != 0) {
out.resize(GetDOF());
OR::Transform T = robot->GetTransform();
OR::RaveGetAffineDOFValuesFromTransform(out.begin() + joint_inds.size(), T, affinedofs, rotationaxis);
}
return out;
}
void RobotAndDOF::SetRobotActiveDOFs() {
RobotBasePtr robot1 = boost::dynamic_pointer_cast<RobotBase>(robot); // since robot is just a kinbody
vector<int> current_active = robot1->GetActiveDOFIndices();
if (robot1->GetActiveDOF() != GetDOF() || !std::equal(current_active.begin(), current_active.end(), joint_inds.begin()))
robot1->SetActiveDOFs(joint_inds, affinedofs);
}
void RobotAndDOF::GetDOFLimits(DblVec& lower, DblVec& upper) const {
if (joint_inds.size() > 0)
robot->GetDOFLimits(lower, upper, joint_inds);
const int translation_dofs[3] = {DOF_X, DOF_Y, DOF_Z};
for (int i=0; i < 3; ++i) {
if (affinedofs & translation_dofs[i]) {
lower.push_back(-INFINITY);
upper.push_back(INFINITY);
}
}
if (affinedofs & DOF_RotationMask) {
if (affinedofs & DOF_RotationAxis) {
lower.push_back(-INFINITY);
upper.push_back(INFINITY);
}
else if (affinedofs & DOF_Rotation3D) {
for (int i=0; i < 3; ++i) {
lower.push_back(-INFINITY);
upper.push_back(INFINITY);
}
}
else if (affinedofs & DOF_Rotation3D) {
for (int i=0; i < 3; ++i) {
lower.push_back(-INFINITY);
upper.push_back(INFINITY);
}
}
else if (affinedofs & DOF_RotationQuat) {
for (int i=0; i < 4; ++i) {
lower.push_back(-1);
upper.push_back(1);
}
}
else throw OR::openrave_exception("invalid rotation dofs", ORE_InvalidArguments);
}
}
int RobotAndDOF::GetDOF() const {
return joint_inds.size() + RaveGetAffineDOF(affinedofs);
}
DblMatrix RobotAndDOF::PositionJacobian(int link_ind, const OR::Vector& pt) const {
Configuration::SaverPtr saver = const_cast<RobotAndDOF*>(this)->Save();
const_cast<RobotAndDOF*>(this)->SetRobotActiveDOFs();
vector<double> jacdata;
boost::dynamic_pointer_cast<RobotBase>(robot)->CalculateActiveJacobian(link_ind, pt, jacdata);
return Eigen::Map<DblMatrix>(jacdata.data(), 3, GetDOF());
}
DblMatrix RobotAndDOF::RotationJacobian(int link_ind) const {
Configuration::SaverPtr saver = const_cast<RobotAndDOF*>(this)->Save();
const_cast<RobotAndDOF*>(this)->SetRobotActiveDOFs();
vector<double> jacdata;
boost::dynamic_pointer_cast<RobotBase>(robot)->ComputeJacobianAxisAngle(link_ind, jacdata);
return Eigen::Map<DblMatrix>(jacdata.data(), 3, GetDOF());
}
bool RobotAndDOF::DoesAffect(const KinBody::Link& link) {
if (affinedofs > 0) return true;
else if (link.GetParent() == GetRobot()) return trajopt::DoesAffect(*GetRobot(), joint_inds, GetRobotLinkIndex(*GetRobot(), link));
else return false;
}
std::vector<KinBody::LinkPtr> RobotAndDOF::GetAffectedLinks() {
vector<int> inds;
std::vector<KinBody::LinkPtr> out;
GetAffectedLinks(out,false,inds);
return out;
}
void RobotAndDOF::GetAffectedLinks(std::vector<KinBody::LinkPtr>& links, bool only_with_geom, vector<int>& link_inds) {
links.clear();
link_inds.clear();
BOOST_FOREACH(const KinBody::LinkPtr& link, GetRobot()->GetLinks()) {
if (this->DoesAffect(*link) && !(only_with_geom && link->GetGeometries().empty())) {
links.push_back(link);
link_inds.push_back(link->GetIndex());
}
}
vector<KinBodyPtr> grabbed;
boost::dynamic_pointer_cast<RobotBase>(robot)->GetGrabbed(grabbed);
BOOST_FOREACH(const KinBodyPtr& body, grabbed) {
KinBody::LinkPtr grabberLink = boost::dynamic_pointer_cast<RobotBase>(robot)->IsGrabbing(body);
assert(grabberLink);
BOOST_FOREACH(const KinBody::LinkPtr& link, body->GetLinks()) {
if (link->GetGeometries().size() > 0) {
links.push_back(link);
link_inds.push_back(grabberLink->GetIndex());
}
}
}
}
vector<KinBodyPtr> RobotAndDOF::GetBodies() {
std::set<KinBodyPtr> bodies;
robot->GetAttached(bodies);
return vector<KinBodyPtr> (bodies.begin(), bodies.end());
}
DblVec RobotAndDOF::RandomDOFValues() {
int ndof = GetDOF();
DblVec lower, upper;
GetDOFLimits(lower, upper);
DblVec out(ndof);
for (int i=0; i < ndof; ++i) {
// TODO this is only right for a circular joint!!
lower[i] = fmax(lower[i], -2*M_PI);
upper[i] = fmin(upper[i], 2*M_PI);
out[i] = lower[i] + randf() * (upper[i] - lower[i]);
}
return out;
}
}
<commit_msg>Fixed typo<commit_after>#include "trajopt/configuration_space.hpp"
#include <boost/foreach.hpp>
#include "trajopt/rave_utils.hpp"
#include "utils/math.hpp"
using namespace OpenRAVE;
using namespace util;
// TODO: configuration should know something about what dofs are part of SO(1), SO(2) etc for functions like RandomDOFValues
namespace trajopt {
void RobotAndDOF::SetDOFValues(const DblVec& dofs) {
if (affinedofs != 0) {
OR::Transform T;
OR::RaveGetTransformFromAffineDOFValues(T, dofs.begin()+joint_inds.size(), affinedofs, rotationaxis, true);
robot->SetTransform(T);
if (joint_inds.size() > 0)
robot->SetDOFValues(dofs, false, joint_inds);
}
else {
robot->SetDOFValues(dofs, false, joint_inds);
}
}
DblVec RobotAndDOF::GetDOFValues() {
DblVec out;
if (joint_inds.size() > 0)
robot->GetDOFValues(out, joint_inds);
if (affinedofs != 0) {
out.resize(GetDOF());
OR::Transform T = robot->GetTransform();
OR::RaveGetAffineDOFValuesFromTransform(out.begin() + joint_inds.size(), T, affinedofs, rotationaxis);
}
return out;
}
void RobotAndDOF::SetRobotActiveDOFs() {
RobotBasePtr robot1 = boost::dynamic_pointer_cast<RobotBase>(robot); // since robot is just a kinbody
vector<int> current_active = robot1->GetActiveDOFIndices();
if (robot1->GetActiveDOF() != GetDOF() || !std::equal(current_active.begin(), current_active.end(), joint_inds.begin()))
robot1->SetActiveDOFs(joint_inds, affinedofs);
}
void RobotAndDOF::GetDOFLimits(DblVec& lower, DblVec& upper) const {
if (joint_inds.size() > 0)
robot->GetDOFLimits(lower, upper, joint_inds);
const int translation_dofs[3] = {DOF_X, DOF_Y, DOF_Z};
for (int i=0; i < 3; ++i) {
if (affinedofs & translation_dofs[i]) {
lower.push_back(-INFINITY);
upper.push_back(INFINITY);
}
}
if (affinedofs & DOF_RotationMask) {
if (affinedofs & DOF_RotationAxis) {
lower.push_back(-INFINITY);
upper.push_back(INFINITY);
}
else if (affinedofs & DOF_Rotation3D) {
for (int i=0; i < 3; ++i) {
lower.push_back(-INFINITY);
upper.push_back(INFINITY);
}
}
else if (affinedofs & DOF_Rotation3D) {
for (int i=0; i < 3; ++i) {
lower.push_back(-INFINITY);
upper.push_back(INFINITY);
}
}
else if (affinedofs & DOF_RotationQuat) {
for (int i=0; i < 4; ++i) {
lower.push_back(-1);
upper.push_back(1);
}
}
else throw OR::openrave_exception("invalid rotation dofs", ORE_InvalidArguments);
}
}
int RobotAndDOF::GetDOF() const {
return joint_inds.size() + RaveGetAffineDOF(affinedofs);
}
DblMatrix RobotAndDOF::PositionJacobian(int link_ind, const OR::Vector& pt) const {
Configuration::SaverPtr saver = const_cast<RobotAndDOF*>(this)->Save();
const_cast<RobotAndDOF*>(this)->SetRobotActiveDOFs();
vector<double> jacdata;
boost::dynamic_pointer_cast<RobotBase>(robot)->CalculateActiveJacobian(link_ind, pt, jacdata);
return Eigen::Map<DblMatrix>(jacdata.data(), 3, GetDOF());
}
DblMatrix RobotAndDOF::RotationJacobian(int link_ind) const {
Configuration::SaverPtr saver = const_cast<RobotAndDOF*>(this)->Save();
const_cast<RobotAndDOF*>(this)->SetRobotActiveDOFs();
vector<double> jacdata;
boost::dynamic_pointer_cast<RobotBase>(robot)->ComputeJacobianAxisAngle(link_ind, jacdata);
return Eigen::Map<DblMatrix>(jacdata.data(), 3, GetDOF());
}
bool RobotAndDOF::DoesAffect(const KinBody::Link& link) {
if (affinedofs > 0) return true;
else if (link.GetParent() == GetRobot()) return trajopt::DoesAffect(*GetRobot(), joint_inds, GetRobotLinkIndex(*GetRobot(), link));
else return false;
}
std::vector<KinBody::LinkPtr> RobotAndDOF::GetAffectedLinks() {
vector<int> inds;
std::vector<KinBody::LinkPtr> out;
GetAffectedLinks(out,false,inds);
return out;
}
void RobotAndDOF::GetAffectedLinks(std::vector<KinBody::LinkPtr>& links, bool only_with_geom, vector<int>& link_inds) {
links.clear();
link_inds.clear();
BOOST_FOREACH(const KinBody::LinkPtr& link, GetRobot()->GetLinks()) {
if (this->DoesAffect(*link) && !(only_with_geom && link->GetGeometries().empty())) {
links.push_back(link);
link_inds.push_back(link->GetIndex());
}
}
vector<KinBodyPtr> grabbed;
boost::dynamic_pointer_cast<RobotBase>(robot)->GetGrabbed(grabbed);
BOOST_FOREACH(const KinBodyPtr& body, grabbed) {
KinBody::LinkPtr grabberLink = boost::dynamic_pointer_cast<RobotBase>(robot)->IsGrabbing(body);
assert(grabberLink);
BOOST_FOREACH(const KinBody::LinkPtr& link, body->GetLinks()) {
if (link->GetGeometries().size() > 0) {
links.push_back(link);
link_inds.push_back(grabberLink->GetIndex());
}
}
}
}
vector<KinBodyPtr> RobotAndDOF::GetBodies() {
std::set<KinBodyPtr> bodies;
robot->GetAttached(bodies);
return vector<KinBodyPtr> (bodies.begin(), bodies.end());
}
DblVec RobotAndDOF::RandomDOFValues() {
int ndof = GetDOF();
DblVec lower, upper;
GetDOFLimits(lower, upper);
DblVec out(ndof);
for (int i=0; i < ndof; ++i) {
// TODO this is only right for a circular joint!!
lower[i] = fmax(lower[i], -2*M_PI);
upper[i] = fmin(upper[i], 2*M_PI);
out[i] = lower[i] + randf() * (upper[i] - lower[i]);
}
return out;
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <unistd.h> // For getpid, getppid.
#include <gmock/gmock.h>
#include <set>
#include <stout/abort.hpp>
#include <stout/gtest.hpp>
#include <stout/numify.hpp>
#include <stout/os.hpp>
#include <stout/proc.hpp>
#include <stout/try.hpp>
using proc::CPU;
using proc::SystemStatus;
using proc::ProcessStatus;
using std::set;
using std::string;
TEST(ProcTest, pids)
{
Try<set<pid_t> > pids = proc::pids();
ASSERT_SOME(pids);
EXPECT_NE(0u, pids.get().size());
EXPECT_EQ(1u, pids.get().count(getpid()));
EXPECT_EQ(1u, pids.get().count(1));
}
TEST(ProcTest, cpus)
{
Try<std::list<CPU> > cpus = proc::cpus();
ASSERT_SOME(cpus);
EXPECT_LE(1u, cpus.get().size());
}
TEST(ProcTest, SystemStatus)
{
Try<SystemStatus> status = proc::status();
ASSERT_SOME(status);
EXPECT_NE(0u, status.get().btime);
}
TEST(ProcTest, ProcessStatus)
{
Result<ProcessStatus> status = proc::status(getpid());
ASSERT_SOME(status);
EXPECT_EQ(getpid(), status.get().pid);
EXPECT_EQ(getppid(), status.get().ppid);
}
TEST(ProcTest, SingleThread)
{
pid_t pid = ::fork();
ASSERT_NE(-1, pid);
if (pid == 0) {
// In child process, wait until killed.
while (true) { sleep(1); }
// Should not reach here.
ABORT("Error, child should be killed before reaching here");
}
// In parent process.
// Check we have the expected number of threads.
Try<set<pid_t> > threads = proc::threads(pid);
ASSERT_SOME(threads);
EXPECT_EQ(1u, threads.get().size());
EXPECT_EQ(1u, threads.get().count(pid));
// Kill the child process.
ASSERT_NE(-1, ::kill(pid, SIGKILL));
// Wait for the child process.
int status;
EXPECT_NE(-1, ::waitpid((pid_t) -1, &status, 0));
ASSERT_TRUE(WIFSIGNALED(status));
EXPECT_EQ(SIGKILL, WTERMSIG(status));
}
int threadFunction(void*)
{
while (true) { sleep(1); }
return -1;
}
TEST(ProcTest, MultipleThreads)
{
int ready;
int pipes[2];
ASSERT_NE(-1, ::pipe(pipes));
pid_t pid = ::fork();
ASSERT_NE(-1, pid);
if (pid == 0) {
// In child process
::close(pipes[0]);
int numThreads = 5;
// 32 KiB stack (2x the common value for PTHREAD_STACK_MIN) for each thread
// is sufficient since they are essentially no-ops.
size_t stackSize = 32*1024 / sizeof(unsigned long long);
unsigned long long stack[numThreads][stackSize];
set<pid_t> threads;
for (int i = 0; i < numThreads; i++) {
pid_t thread;
// We use clone here to create threads because pthread_create is not
// async-signal-safe.
thread = clone(
threadFunction,
&(stack[i][stackSize - 1]),
CLONE_THREAD | CLONE_SIGHAND | CLONE_VM | CLONE_FILES | SIGCHLD,
NULL);
EXPECT_NE(-1, thread);
threads.insert(thread);
}
// Also add our own pid to the set.
threads.insert(getpid());
// Notify parent of the thread ids.
ASSERT_SOME(os::write(pipes[1], strings::join(",", threads)));
// NOTE: CLONE_FILES ensures the pipe file descriptor will be closed in the
// threads as well, ensuring the parent gets the EOF.
::close(pipes[1]);
// Sleep until killed.
while (true) { sleep(1); }
// Should not reach here.
ABORT("Error, child should be killed before reaching here");
}
// In parent process.
::close(pipes[1]);
// Get thread ids from the child. Read up to the first 1024 characters which
// is sufficient for the expected number of stringified pids.
Result<string> read = os::read(pipes[0], 1024);
ASSERT_SOME(read);
set<pid_t> childThreads;
foreach (const string& token, strings::tokenize(read.get(), ",")) {
Try<pid_t> thread = numify<pid_t>(token);
ASSERT_SOME(thread);
childThreads.insert(thread.get());
}
// Read thread ids from /proc for the child.
Try<set<pid_t> > procThreads = proc::threads(pid);
// Check we have the expected threads.
ASSERT_SOME_EQ(childThreads, procThreads);
// Kill the child process.
ASSERT_NE(-1, ::kill(pid, SIGKILL));
// Wait for the child process.
int status;
EXPECT_NE(-1, ::waitpid((pid_t) -1, &status, 0));
EXPECT_TRUE(WIFSIGNALED(status));
EXPECT_EQ(SIGKILL, WTERMSIG(status));
}
<commit_msg>Correct and simplify the ProcTests for threads.<commit_after>#include <iostream>
#include <pthread.h>
#include <unistd.h> // For getpid, getppid.
#include <gmock/gmock.h>
#include <set>
#include <stout/abort.hpp>
#include <stout/gtest.hpp>
#include <stout/numify.hpp>
#include <stout/os.hpp>
#include <stout/proc.hpp>
#include <stout/try.hpp>
using proc::CPU;
using proc::SystemStatus;
using proc::ProcessStatus;
using std::set;
using std::string;
TEST(ProcTest, pids)
{
Try<set<pid_t> > pids = proc::pids();
ASSERT_SOME(pids);
EXPECT_NE(0u, pids.get().size());
EXPECT_EQ(1u, pids.get().count(getpid()));
EXPECT_EQ(1u, pids.get().count(1));
}
TEST(ProcTest, cpus)
{
Try<std::list<CPU> > cpus = proc::cpus();
ASSERT_SOME(cpus);
EXPECT_LE(1u, cpus.get().size());
}
TEST(ProcTest, SystemStatus)
{
Try<SystemStatus> status = proc::status();
ASSERT_SOME(status);
EXPECT_NE(0u, status.get().btime);
}
TEST(ProcTest, ProcessStatus)
{
Result<ProcessStatus> status = proc::status(getpid());
ASSERT_SOME(status);
EXPECT_EQ(getpid(), status.get().pid);
EXPECT_EQ(getppid(), status.get().ppid);
}
// NOTE: This test assumes there is a single thread running for the test.
TEST(ProcTest, SingleThread)
{
// Check we have the expected number of threads.
Try<set<pid_t> > threads = proc::threads(::getpid());
ASSERT_SOME(threads);
EXPECT_EQ(1u, threads.get().size());
EXPECT_EQ(1u, threads.get().count(::getpid()));
}
void* threadFunction(void*)
{
// Newly created threads have PTHREAD_CANCEL_ENABLE and
// PTHREAD_CANCEL_DEFERRED so they can be cancelled from the main thread.
while (true) { sleep(1); }
}
// NOTE: This test assumes there is only a single thread running for the test.
TEST(ProcTest, MultipleThreads)
{
size_t numThreads = 5;
pthread_t pthreads[numThreads];
// Create additional threads.
for (size_t i = 0; i < numThreads; i++)
{
EXPECT_EQ(0, pthread_create(&pthreads[i], NULL, threadFunction, NULL));
}
// Check we have the expected number of threads.
Try<set<pid_t> > threads = proc::threads(::getpid());
ASSERT_SOME(threads);
EXPECT_EQ(1u + numThreads, threads.get().size());
EXPECT_EQ(1u, threads.get().count(::getpid()));
// Terminate the threads.
for (int i = 0; i < numThreads; i++)
{
EXPECT_EQ(0, pthread_cancel(pthreads[i]));
EXPECT_EQ(0, pthread_join(pthreads[i], NULL));
}
}
<|endoftext|>
|
<commit_before>//*****************************************************************************
// Copyright 2017-2020 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#pragma once
#include <pybind11/pybind11.h>
#include "pyngraph/ops/allreduce.hpp"
#include "pyngraph/ops/argmax.hpp"
#include "pyngraph/ops/argmin.hpp"
#include "pyngraph/ops/avg_pool.hpp"
#include "pyngraph/ops/batch_norm.hpp"
#include "pyngraph/ops/broadcast.hpp"
#include "pyngraph/ops/broadcast_distributed.hpp"
#include "pyngraph/ops/constant.hpp"
#include "pyngraph/ops/convert.hpp"
#include "pyngraph/ops/convolution.hpp"
#include "pyngraph/ops/dequantize.hpp"
#include "pyngraph/ops/dot.hpp"
#include "pyngraph/ops/fused/depth_to_space.hpp"
#include "pyngraph/ops/fused/gelu.hpp"
#include "pyngraph/ops/fused/gemm.hpp"
#include "pyngraph/ops/fused/grn.hpp"
#include "pyngraph/ops/fused/group_conv.hpp"
#include "pyngraph/ops/fused/hard_sigmoid.hpp"
#include "pyngraph/ops/fused/mvn.hpp"
#include "pyngraph/ops/fused/rnn_cell.hpp"
#include "pyngraph/ops/fused/scale_shift.hpp"
#include "pyngraph/ops/fused/shuffle_channels.hpp"
#include "pyngraph/ops/fused/space_to_depth.hpp"
#include "pyngraph/ops/fused/unsqueeze.hpp"
#include "pyngraph/ops/get_output_element.hpp"
#include "pyngraph/ops/max.hpp"
#include "pyngraph/ops/max_pool.hpp"
#include "pyngraph/ops/maximum.hpp"
#include "pyngraph/ops/min.hpp"
#include "pyngraph/ops/parameter.hpp"
#include "pyngraph/ops/passthrough.hpp"
#include "pyngraph/ops/product.hpp"
#include "pyngraph/ops/quantize.hpp"
#include "pyngraph/ops/quantized_convolution.hpp"
#include "pyngraph/ops/quantized_dot.hpp"
#include "pyngraph/ops/replace_slice.hpp"
#include "pyngraph/ops/result.hpp"
#include "pyngraph/ops/slice.hpp"
#include "pyngraph/ops/softmax.hpp"
namespace py = pybind11;
void regmodule_pyngraph_op(py::module m);
<commit_msg>Style apply<commit_after>//*****************************************************************************
// Copyright 2017-2020 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#pragma once
#include <pybind11/pybind11.h>
#include "pyngraph/ops/allreduce.hpp"
#include "pyngraph/ops/argmax.hpp"
#include "pyngraph/ops/argmin.hpp"
#include "pyngraph/ops/avg_pool.hpp"
#include "pyngraph/ops/batch_norm.hpp"
#include "pyngraph/ops/broadcast.hpp"
#include "pyngraph/ops/broadcast_distributed.hpp"
#include "pyngraph/ops/constant.hpp"
#include "pyngraph/ops/convert.hpp"
#include "pyngraph/ops/convolution.hpp"
#include "pyngraph/ops/dequantize.hpp"
#include "pyngraph/ops/dot.hpp"
#include "pyngraph/ops/fused/depth_to_space.hpp"
#include "pyngraph/ops/fused/gelu.hpp"
#include "pyngraph/ops/fused/gemm.hpp"
#include "pyngraph/ops/fused/grn.hpp"
#include "pyngraph/ops/fused/group_conv.hpp"
#include "pyngraph/ops/fused/hard_sigmoid.hpp"
#include "pyngraph/ops/fused/mvn.hpp"
#include "pyngraph/ops/fused/rnn_cell.hpp"
#include "pyngraph/ops/fused/scale_shift.hpp"
#include "pyngraph/ops/fused/shuffle_channels.hpp"
#include "pyngraph/ops/fused/space_to_depth.hpp"
#include "pyngraph/ops/fused/unsqueeze.hpp"
#include "pyngraph/ops/get_output_element.hpp"
#include "pyngraph/ops/max.hpp"
#include "pyngraph/ops/max_pool.hpp"
#include "pyngraph/ops/maximum.hpp"
#include "pyngraph/ops/min.hpp"
#include "pyngraph/ops/parameter.hpp"
#include "pyngraph/ops/passthrough.hpp"
#include "pyngraph/ops/product.hpp"
#include "pyngraph/ops/quantize.hpp"
#include "pyngraph/ops/quantized_convolution.hpp"
#include "pyngraph/ops/quantized_dot.hpp"
#include "pyngraph/ops/replace_slice.hpp"
#include "pyngraph/ops/result.hpp"
#include "pyngraph/ops/slice.hpp"
#include "pyngraph/ops/softmax.hpp"
namespace py = pybind11;
void regmodule_pyngraph_op(py::module m);
<|endoftext|>
|
<commit_before>/*
This file is part of the ORK library.
Full copyright and license terms can be found in the LICENSE.txt file.
*/
#pragma once
#include"boost/spirit/home/support/common_terminals.hpp"
#include"boost/spirit/home/qi.hpp"
#include"ork/ork.hpp"
/*
Placeholders for parser components
*/
namespace ork {
namespace orq {//ork-qi :)
BOOST_SPIRIT_TERMINAL(id);
BOOST_SPIRIT_TERMINAL(quote);
BOOST_SPIRIT_TERMINAL(lb_com);//'pound comment'
}//namespace orq
}//namespace ork
/*
Enablers for parser components
*/
namespace boost {
namespace spirit {
//Make custom parser usable as a terminal only, and only for parser expressions (qi::domain).
template<> struct use_terminal<qi::domain, ork::orq::tag::id> : mpl::true_ {};
template<> struct use_terminal<qi::domain, ork::orq::tag::quote> : mpl::true_ {};
template<> struct use_terminal<qi::domain, ork::orq::tag::lb_com> : mpl::true_ {};
}//namespace spirit
}//namespace boost
namespace ork {
namespace spirit = boost::spirit;
namespace qi = spirit::qi;
namespace ascii = spirit::ascii;
namespace proto = boost::proto;
#if ORK_UNICODE
typedef spirit::char_encoding::standard_wide charset;
#else
typedef spirit::char_encoding::standard charset;
#endif
namespace orq {//ork-qi :)
struct ORK_ORK_API id_parser : qi::primitive_parser<id_parser> {
public://Parser component stuff
template<typename context, typename iter>
struct attribute {//Define the attribute type exposed by this parser component
typedef string type;
};
//This function is called during the actual parsing process
template<typename iter, typename context, typename skipper, typename attribute>
bool parse(iter& first, const iter& last, context&ctxt, const skipper& skip, attribute& attr) const {
boost::spirit::qi::skip_over(first, last, skip);//All primitive parsers pre-skip
if(first == last) {
return false;
}
iter it(first);
if(!std::isalpha(*it) && *it != ORK('_')) {
return false;//First character must be letter or underscore
}
while(it != last && (std::isalnum(*it) || *it == ORK('_'))) {
++it;//Subsequent characters can be numbers also
}
attribute result(first, it);
if(result.empty()) {
return false;
}
first = it;
spirit::traits::assign_to(result, attr);
return true;
}
//This function is called during error handling to create a human readable string for the error context.
template<typename context>
boost::spirit::info what(context&) const {
return boost::spirit::info("id");
}
};
struct ORK_ORK_API quote_parser : qi::primitive_parser<quote_parser> {
public://Parser component stuff
template<typename context, typename iter>
struct attribute {//Define the attribute type exposed by this parser component
typedef string type;
};
//This function is called during the actual parsing process
template<typename iter, typename context, typename skipper, typename attribute>
bool parse(iter& first, const iter& last, context&ctxt, const skipper& skip, attribute& attr) const {
boost::spirit::qi::skip_over(first, last, skip);//All primitive parsers pre-skip
if(first == last) {
return false;
}
iter it(first);
if(*it++ != ORK('"')) {//Consume the quote
return false;
}
while(it != last && *it != ORK('"')) {//Up to but do not consume the quote
++it;
}
if(it == last) {
return false;
}
if(*it++ != ORK('"')) {//Consume the quote
return false;
}
attribute result(first, it);
//Allow empty attribute
first = it;
spirit::traits::assign_to(result, attr);
return true;
}
//This function is called during error handling to create a human readable string for the error context.
template<typename context>
boost::spirit::info what(context&) const {
return boost::spirit::info("quote");
}
};
struct ORK_ORK_API lb_com_parser : qi::primitive_parser<lb_com_parser> {
public://Parser component stuff
template<typename context, typename iter>
struct attribute {//Define the attribute type exposed by this parser component
typedef qi::unused_type type;
};
//This function is called during the actual parsing process
template<typename iter, typename context, typename skipper, typename attribute>
bool parse(iter& first, const iter& last, context&ctxt, const skipper& skip, attribute& attr) const {
boost::spirit::qi::skip_over(first, last, skip);//All primitive parsers pre-skip
if(first == last) {
return false;
}
iter it(first);
if(*it++ != ORK('#')) {//Consume the marker
return false;
}
while(it != last && *it != ORK('\n')) {//Up to but do not consume the eol
++it;
}
first = it;
return true;
}
//This function is called during error handling to create a human readable string for the error context.
template<typename context>
boost::spirit::info what(context&) const {
return boost::spirit::info("lb_com");
}
};
}//namespace orq
}//namespace ork
/*
Instantiators for parser components
*/
namespace boost {
namespace spirit {
namespace qi {
//This is the factory function object invoked in order to create an instance of our parser.
template<typename modifiers>
struct make_primitive<ork::orq::tag::id, modifiers> {
typedef typename ork::orq::id_parser result_type;
result_type operator()(unused_type, unused_type) const {
return result_type();
}
};
template<typename modifiers>
struct make_primitive<ork::orq::tag::quote, modifiers> {
typedef typename ork::orq::quote_parser result_type;
result_type operator()(unused_type, unused_type) const {
return result_type();
}
};
template<typename modifiers>
struct make_primitive<ork::orq::tag::lb_com, modifiers> {
typedef typename ork::orq::lb_com_parser result_type;
result_type operator()(unused_type, unused_type) const {
return result_type();
}
};
}//namespace qi
}//namespace spirit
}//namespace boost<commit_msg>Fixed a bug including quotes in quoted string<commit_after>/*
This file is part of the ORK library.
Full copyright and license terms can be found in the LICENSE.txt file.
*/
#pragma once
#include"boost/spirit/home/support/common_terminals.hpp"
#include"boost/spirit/home/qi.hpp"
#include"ork/ork.hpp"
/*
Placeholders for parser components
*/
namespace ork {
namespace orq {//ork-qi :)
BOOST_SPIRIT_TERMINAL(id);
BOOST_SPIRIT_TERMINAL(quote);
BOOST_SPIRIT_TERMINAL(lb_com);//'pound comment'
}//namespace orq
}//namespace ork
/*
Enablers for parser components
*/
namespace boost {
namespace spirit {
//Make custom parser usable as a terminal only, and only for parser expressions (qi::domain).
template<> struct use_terminal<qi::domain, ork::orq::tag::id> : mpl::true_ {};
template<> struct use_terminal<qi::domain, ork::orq::tag::quote> : mpl::true_ {};
template<> struct use_terminal<qi::domain, ork::orq::tag::lb_com> : mpl::true_ {};
}//namespace spirit
}//namespace boost
namespace ork {
namespace spirit = boost::spirit;
namespace qi = spirit::qi;
namespace ascii = spirit::ascii;
namespace proto = boost::proto;
#if ORK_UNICODE
typedef spirit::char_encoding::standard_wide charset;
#else
typedef spirit::char_encoding::standard charset;
#endif
namespace orq {//ork-qi :)
struct ORK_ORK_API id_parser : qi::primitive_parser<id_parser> {
public://Parser component stuff
template<typename context, typename iter>
struct attribute {//Define the attribute type exposed by this parser component
typedef string type;
};
//This function is called during the actual parsing process
template<typename iter, typename context, typename skipper, typename attribute>
bool parse(iter& first, const iter& last, context&ctxt, const skipper& skip, attribute& attr) const {
boost::spirit::qi::skip_over(first, last, skip);//All primitive parsers pre-skip
if(first == last) {
return false;
}
iter it(first);
if(!std::isalpha(*it) && *it != ORK('_')) {
return false;//First character must be letter or underscore
}
while(it != last && (std::isalnum(*it) || *it == ORK('_'))) {
++it;//Subsequent characters can be numbers also
}
attribute result(first, it);
if(result.empty()) {
return false;
}
first = it;
spirit::traits::assign_to(result, attr);
return true;
}
//This function is called during error handling to create a human readable string for the error context.
template<typename context>
boost::spirit::info what(context&) const {
return boost::spirit::info("id");
}
};
struct ORK_ORK_API quote_parser : qi::primitive_parser<quote_parser> {
public://Parser component stuff
template<typename context, typename iter>
struct attribute {//Define the attribute type exposed by this parser component
typedef string type;
};
//This function is called during the actual parsing process
template<typename iter, typename context, typename skipper, typename attribute>
bool parse(iter& first, const iter& last, context&ctxt, const skipper& skip, attribute& attr) const {
boost::spirit::qi::skip_over(first, last, skip);//All primitive parsers pre-skip
if(first == last) {
return false;
}
iter it(first);
if(*it++ != ORK('"')) {//Consume the quote
return false;
}
while(it != last && *it != ORK('"')) {//Up to but do not consume the quote
++it;
}
if(it == last) {
return false;
}
if(*it++ != ORK('"')) {//Consume the quote
return false;
}
attribute result(++first, it - 1);//Do not include quotes
//Allow empty attribute
first = it;
spirit::traits::assign_to(result, attr);
return true;
}
//This function is called during error handling to create a human readable string for the error context.
template<typename context>
boost::spirit::info what(context&) const {
return boost::spirit::info("quote");
}
};
struct ORK_ORK_API lb_com_parser : qi::primitive_parser<lb_com_parser> {
public://Parser component stuff
template<typename context, typename iter>
struct attribute {//Define the attribute type exposed by this parser component
typedef qi::unused_type type;
};
//This function is called during the actual parsing process
template<typename iter, typename context, typename skipper, typename attribute>
bool parse(iter& first, const iter& last, context&ctxt, const skipper& skip, attribute& attr) const {
boost::spirit::qi::skip_over(first, last, skip);//All primitive parsers pre-skip
if(first == last) {
return false;
}
iter it(first);
if(*it++ != ORK('#')) {//Consume the marker
return false;
}
while(it != last && *it != ORK('\n')) {//Up to but do not consume the eol
++it;
}
first = it;
return true;
}
//This function is called during error handling to create a human readable string for the error context.
template<typename context>
boost::spirit::info what(context&) const {
return boost::spirit::info("lb_com");
}
};
}//namespace orq
}//namespace ork
/*
Instantiators for parser components
*/
namespace boost {
namespace spirit {
namespace qi {
//This is the factory function object invoked in order to create an instance of our parser.
template<typename modifiers>
struct make_primitive<ork::orq::tag::id, modifiers> {
typedef typename ork::orq::id_parser result_type;
result_type operator()(unused_type, unused_type) const {
return result_type();
}
};
template<typename modifiers>
struct make_primitive<ork::orq::tag::quote, modifiers> {
typedef typename ork::orq::quote_parser result_type;
result_type operator()(unused_type, unused_type) const {
return result_type();
}
};
template<typename modifiers>
struct make_primitive<ork::orq::tag::lb_com, modifiers> {
typedef typename ork::orq::lb_com_parser result_type;
result_type operator()(unused_type, unused_type) const {
return result_type();
}
};
}//namespace qi
}//namespace spirit
}//namespace boost<|endoftext|>
|
<commit_before>/******************************************************************
*
* Round for C++
*
* Copyright (C) Satoshi Konno 2014
*
* This is licensed under BSD-style license, see file COPYING.
*
******************************************************************/
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <round/Round.h>
#include <round/core/LocalNode.h>
#include <round/core/SystemMethod.h>
////////////////////////////////////////////////
// Constructor
////////////////////////////////////////////////
Round::LocalNode::LocalNode() {
init();
}
Round::LocalNode::~LocalNode() {
}
void Round::LocalNode::init() {
setState(NodeStatus::STOP);
}
////////////////////////////////////////////////
// Configuration
////////////////////////////////////////////////
bool Round::LocalNode::loadConfigFromString(const std::string &string, Error *error) {
if (this->nodeConfig.loadFromString(string, error) == false)
return false;
return true;
}
bool Round::LocalNode::loadConfigFromFile(const std::string &filename, Error *error) {
if (this->nodeConfig.loadFromFile(filename, error) == false)
return false;
return true;
}
bool Round::LocalNode::isConfigValid(Error *error) {
return this->nodeConfig.isValid(error);
}
bool Round::LocalNode::getClusterName(std::string *name, Error *error) {
return this->nodeConfig.getCluster(name, error);
}
////////////////////////////////////////////////
// Thread
////////////////////////////////////////////////
bool Round::LocalNode::start(Error *error) {
stop(error);
bool areAllOperationSucess = true;
setState(NodeStatus::ACTIVATING);
nodeWorker.setObject(this);
if (nodeWorker.start()) {
if (!this->nodeGraph.addNode(this)) {
areAllOperationSucess = false;
}
}
else {
areAllOperationSucess = false;
}
if (!areAllOperationSucess) {
stop(error);
return false;
}
setState(NodeStatus::ACTIVE);
return true;
}
bool Round::LocalNode::stop(Error *error) {
bool areAllOperationSucess = true;
if (!nodeWorker.stop()) {
areAllOperationSucess = false;
return false;
}
NodeGraph *nodeGraph = getNodeGraph();
if (!nodeGraph->clear()) {
areAllOperationSucess = false;
}
if (areAllOperationSucess == true) {
setState(NodeStatus::STOP);
}
return areAllOperationSucess;
}
bool Round::LocalNode::restart(Error *error) {
if (stop(error) == false)
return false;
return start(error);
}
////////////////////////////////////////////////
// Notification
////////////////////////////////////////////////
bool Round::LocalNode::nodeAdded(Round::Node *notifyNode) {
Error error;
std::string notifyNodeCluster;
if (!notifyNode->getClusterName(¬ifyNodeCluster, &error))
return false;
std::string thisNodeCluster;
if (!getClusterName(&thisNodeCluster, &error))
return false;
if (thisNodeCluster.compare(notifyNodeCluster) != 0)
return false;
if (this->nodeGraph.hasNode(notifyNode))
return true;
if (!this->nodeGraph.addNode(notifyNode))
return true;
if (equals(notifyNode))
return true;
return true;
}
bool Round::LocalNode::nodeRemoved(Round::Node *notifyNode) {
if (!this->nodeGraph.hasNode(notifyNode))
return true;
if (equals(notifyNode)) {
this->nodeGraph.removeNode(notifyNode);
return true;
}
ssize_t notifyNodeIndex = this->nodeGraph.getNodeIndex(notifyNode);
if (notifyNodeIndex < 0)
return false;
Node *failedNode = this->nodeGraph.getNode(notifyNodeIndex);
if (!failedNode)
return false;
return true;
}
////////////////////////////////////////////////
// Message
////////////////////////////////////////////////
bool Round::LocalNode::postMessage(NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) {
// Set id and ts parameter
clock_t localTs = getLocalClock();
nodeReq->setId(localTs);
nodeReq->setTimestamp(localTs);
// Post RPC message
return execMessage(nodeReq, nodeRes, error);
}
bool Round::LocalNode::pushMessage(const NodeRequest *nodeReq) {
return this->nodeMsgMgr.pushMessage(nodeReq);
}
bool Round::LocalNode::waitMessage(const NodeRequest **nodeReq) {
*nodeReq = NULL;
const Message *nodeMsg = NULL;
if (!this->nodeMsgMgr.waitMessage(&nodeMsg))
return false;
*nodeReq = dynamic_cast<const NodeRequest *>(nodeMsg);
return (*nodeReq) ? true : false;
}
////////////////////////////////////////////////
// Execution
////////////////////////////////////////////////
bool Round::LocalNode::hasUserMethod(const std::string &method) {
return this->scriptMgr.hasScript(method);
}
bool Round::LocalNode::setError(int rpcErrorCode, Error *err) {
if (!err)
return false;
RPC::JSON::ErrorCodeToError(rpcErrorCode, err);
return true;
}
bool Round::LocalNode::execMessage(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *err) {
if (!nodeReq || !nodeRes || !err)
return false;
// Check hash code
if (nodeReq->hasHash()) {
std::string hashCode;
if (getHashCode(&hashCode)) {
if (hashCode.length() != HashObject::GetHashCodeLength()) {
setError(RPC::JSON::ErrorCodeBadHashCode, err);
return false;
}
NodeGraph *nodeGraph = getNodeGraph();
if (!nodeGraph->isHandleNode(this, hashCode)) {
setError(RPC::JSON::ErrorCodeMovedPermanently, err);
return false;
}
}
}
// Update local clock
clock_t remoteTs;
if (nodeRes->getTimestamp(&remoteTs)) {
setRemoteClock(remoteTs);
}
else {
incrementLocalClock();
}
// Set id and ts parameter
size_t msgId;
if (nodeReq->getId(&msgId)) {
nodeRes->setId(msgId);
}
nodeRes->setTimestamp(getLocalClock());
// Exec Message
std::string name;
nodeReq->getMethod(&name);
if (isSetMethod(name)) {
if (!setMethod(nodeReq, nodeRes, err)) {
setError(RPC::JSON::ErrorCodeInvalidParams, err);
return false;
}
return true;
}
if (hasUserMethod(name)) {
std::string params;
nodeReq->getParams(¶ms);
std::string result;
return this->scriptMgr.run(name, params, &result, err);
}
if (isSystemMethod(name)) {
return execSystemMethod(nodeReq, nodeRes, err);
}
setError(RPC::JSON::ErrorCodeMethodNotFound, err);
return false;
}
////////////////////////////////////////////////
// System Static Method
////////////////////////////////////////////////
bool Round::LocalNode::isSetMethod(const std::string &method) {
return (SystemMethodRequest::SET_METHOD.compare(method) == 0) ? true : false;
}
bool Round::LocalNode::setMethod(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *err) {
std::string params;
nodeReq->getParams(¶ms);
JSONParser jsonParser;
if (!jsonParser.parse(params, err)) {
RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err);
return false;
}
JSONObject *jsonObj = jsonParser.getRootObject();
if (!jsonObj->isDictionary()) {
RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err);
return false;
}
JSONDictionary *jsonDict = dynamic_cast<JSONDictionary *>(jsonObj);
if (!jsonDict) {
RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err);
return false;
}
std::string scriptMethod;
if (!jsonDict->get(SystemMethodRequest::NAME, &scriptMethod) || (scriptMethod.length() <= 0)) {
RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err);
return false;
}
// Couldn't override '_set_method'
if (isSetMethod(scriptMethod)) {
RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err);
return false;
}
std::string scriptLang;
if (!jsonDict->get(SystemMethodRequest::LANGUAGE, &scriptLang) || (scriptLang.length() <= 0)) {
RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err);
return false;
}
// This method is removed if the code parameter is null.
std::string scriptCode;
jsonDict->get(SystemMethodRequest::CODE, &scriptCode);
// Encode
int encodeType = Script::ENCODING_NONE;
std::string encodeTypeStr;
if (jsonDict->get(SystemMethodRequest::ENCODE, &encodeTypeStr)) {
if (encodeTypeStr.compare(SystemMethodRequest::ENCODE_BASE64)) {
encodeType = Script::ENCODING_BASE64;
}
}
return this->scriptMgr.setScript(scriptMethod, scriptLang, scriptCode, encodeType, err);
}
////////////////////////////////////////////////
// System Dynamic Method
////////////////////////////////////////////////
bool Round::LocalNode::isSystemMethod(const std::string &method) {
return (method.find(SystemMethodRequest::PREFIX) == 0) ? true : false;
}
bool Round::LocalNode::execSystemMethod(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) {
static std::map<std::string, int> systemMethods;
enum {
SystemGetNodeInfo,
SystemGetClusterInfo,
SystemGetNetworkInfo,
};
if (systemMethods.size() <= 0) {
systemMethods[SystemMethodRequest::GET_NODE_INFO] = SystemGetNodeInfo;
systemMethods[SystemMethodRequest::GET_CLUSTER_INFO] = SystemGetClusterInfo;
systemMethods[SystemMethodRequest::GET_NETWORK_INFO] = SystemGetNetworkInfo;
}
std::string reqMethod;
nodeReq->getMethod(&reqMethod);
if (systemMethods.find(reqMethod) == systemMethods.end()) {
RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeMethodNotFound, error);
return false;
}
int systemMethodType = systemMethods[reqMethod];
switch (systemMethodType) {
case SystemGetNodeInfo:
return _get_node_info(nodeReq, nodeRes, error);
case SystemGetClusterInfo:
return _get_cluster_info(nodeReq, nodeRes, error);
case SystemGetNetworkInfo:
return _get_network_info(nodeReq, nodeRes, error);
}
RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeMethodNotFound, error);
return false;
}
bool Round::LocalNode::_get_node_info(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) {
SystemGetNodeInfoResponse sysRes(nodeRes);
return sysRes.setNode(this);
}
bool Round::LocalNode::_get_cluster_info(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) {
SystemGetClusterInfoResponse sysRes(nodeRes);
return sysRes.setCluster(this);
}
bool Round::LocalNode::_get_network_info(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) {
SystemGetNetworkInfoResponse sysRes(nodeRes);
return sysRes.setClusters(this);
}
<commit_msg>* Fixed LocalNode::execMessage() to return the result of user script execution. * Updated LocalNode::execMessage() to check if the method is null.<commit_after>/******************************************************************
*
* Round for C++
*
* Copyright (C) Satoshi Konno 2014
*
* This is licensed under BSD-style license, see file COPYING.
*
******************************************************************/
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <round/Round.h>
#include <round/core/LocalNode.h>
#include <round/core/SystemMethod.h>
////////////////////////////////////////////////
// Constructor
////////////////////////////////////////////////
Round::LocalNode::LocalNode() {
init();
}
Round::LocalNode::~LocalNode() {
}
void Round::LocalNode::init() {
setState(NodeStatus::STOP);
}
////////////////////////////////////////////////
// Configuration
////////////////////////////////////////////////
bool Round::LocalNode::loadConfigFromString(const std::string &string, Error *error) {
if (this->nodeConfig.loadFromString(string, error) == false)
return false;
return true;
}
bool Round::LocalNode::loadConfigFromFile(const std::string &filename, Error *error) {
if (this->nodeConfig.loadFromFile(filename, error) == false)
return false;
return true;
}
bool Round::LocalNode::isConfigValid(Error *error) {
return this->nodeConfig.isValid(error);
}
bool Round::LocalNode::getClusterName(std::string *name, Error *error) {
return this->nodeConfig.getCluster(name, error);
}
////////////////////////////////////////////////
// Thread
////////////////////////////////////////////////
bool Round::LocalNode::start(Error *error) {
stop(error);
bool areAllOperationSucess = true;
setState(NodeStatus::ACTIVATING);
nodeWorker.setObject(this);
if (nodeWorker.start()) {
if (!this->nodeGraph.addNode(this)) {
areAllOperationSucess = false;
}
}
else {
areAllOperationSucess = false;
}
if (!areAllOperationSucess) {
stop(error);
return false;
}
setState(NodeStatus::ACTIVE);
return true;
}
bool Round::LocalNode::stop(Error *error) {
bool areAllOperationSucess = true;
if (!nodeWorker.stop()) {
areAllOperationSucess = false;
return false;
}
NodeGraph *nodeGraph = getNodeGraph();
if (!nodeGraph->clear()) {
areAllOperationSucess = false;
}
if (areAllOperationSucess == true) {
setState(NodeStatus::STOP);
}
return areAllOperationSucess;
}
bool Round::LocalNode::restart(Error *error) {
if (stop(error) == false)
return false;
return start(error);
}
////////////////////////////////////////////////
// Notification
////////////////////////////////////////////////
bool Round::LocalNode::nodeAdded(Round::Node *notifyNode) {
Error error;
std::string notifyNodeCluster;
if (!notifyNode->getClusterName(¬ifyNodeCluster, &error))
return false;
std::string thisNodeCluster;
if (!getClusterName(&thisNodeCluster, &error))
return false;
if (thisNodeCluster.compare(notifyNodeCluster) != 0)
return false;
if (this->nodeGraph.hasNode(notifyNode))
return true;
if (!this->nodeGraph.addNode(notifyNode))
return true;
if (equals(notifyNode))
return true;
return true;
}
bool Round::LocalNode::nodeRemoved(Round::Node *notifyNode) {
if (!this->nodeGraph.hasNode(notifyNode))
return true;
if (equals(notifyNode)) {
this->nodeGraph.removeNode(notifyNode);
return true;
}
ssize_t notifyNodeIndex = this->nodeGraph.getNodeIndex(notifyNode);
if (notifyNodeIndex < 0)
return false;
Node *failedNode = this->nodeGraph.getNode(notifyNodeIndex);
if (!failedNode)
return false;
return true;
}
////////////////////////////////////////////////
// Message
////////////////////////////////////////////////
bool Round::LocalNode::postMessage(NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) {
// Set id and ts parameter
clock_t localTs = getLocalClock();
nodeReq->setId(localTs);
nodeReq->setTimestamp(localTs);
// Post RPC message
return execMessage(nodeReq, nodeRes, error);
}
bool Round::LocalNode::pushMessage(const NodeRequest *nodeReq) {
return this->nodeMsgMgr.pushMessage(nodeReq);
}
bool Round::LocalNode::waitMessage(const NodeRequest **nodeReq) {
*nodeReq = NULL;
const Message *nodeMsg = NULL;
if (!this->nodeMsgMgr.waitMessage(&nodeMsg))
return false;
*nodeReq = dynamic_cast<const NodeRequest *>(nodeMsg);
return (*nodeReq) ? true : false;
}
////////////////////////////////////////////////
// Execution
////////////////////////////////////////////////
bool Round::LocalNode::hasUserMethod(const std::string &method) {
return this->scriptMgr.hasScript(method);
}
bool Round::LocalNode::setError(int rpcErrorCode, Error *err) {
if (!err)
return false;
RPC::JSON::ErrorCodeToError(rpcErrorCode, err);
return true;
}
bool Round::LocalNode::execMessage(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *err) {
if (!nodeReq || !nodeRes || !err)
return false;
// Check hash code
if (nodeReq->hasHash()) {
std::string hashCode;
if (getHashCode(&hashCode)) {
if (hashCode.length() != HashObject::GetHashCodeLength()) {
setError(RPC::JSON::ErrorCodeBadHashCode, err);
return false;
}
NodeGraph *nodeGraph = getNodeGraph();
if (!nodeGraph->isHandleNode(this, hashCode)) {
setError(RPC::JSON::ErrorCodeMovedPermanently, err);
return false;
}
}
}
// Update local clock
clock_t remoteTs;
if (nodeRes->getTimestamp(&remoteTs)) {
setRemoteClock(remoteTs);
}
else {
incrementLocalClock();
}
// Set id and ts parameter
size_t msgId;
if (nodeReq->getId(&msgId)) {
nodeRes->setId(msgId);
}
nodeRes->setTimestamp(getLocalClock());
// Exec Message
std::string name;
if (!nodeReq->getMethod(&name) || (name.length() <= 0)) {
setError(RPC::JSON::ErrorCodeMethodNotFound, err);
return false;
}
if (isSetMethod(name)) {
if (!setMethod(nodeReq, nodeRes, err)) {
setError(RPC::JSON::ErrorCodeInvalidParams, err);
return false;
}
return true;
}
if (hasUserMethod(name)) {
std::string params;
nodeReq->getParams(¶ms);
std::string result;
bool isSuccess = this->scriptMgr.run(name, params, &result, err);
if (isSuccess) {
nodeRes->setResult(result);
}
else {
nodeRes->setError(err);
}
return isSuccess;
}
if (isSystemMethod(name)) {
return execSystemMethod(nodeReq, nodeRes, err);
}
setError(RPC::JSON::ErrorCodeMethodNotFound, err);
return false;
}
////////////////////////////////////////////////
// System Static Method
////////////////////////////////////////////////
bool Round::LocalNode::isSetMethod(const std::string &method) {
return (SystemMethodRequest::SET_METHOD.compare(method) == 0) ? true : false;
}
bool Round::LocalNode::setMethod(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *err) {
std::string params;
nodeReq->getParams(¶ms);
JSONParser jsonParser;
if (!jsonParser.parse(params, err)) {
RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err);
return false;
}
JSONObject *jsonObj = jsonParser.getRootObject();
if (!jsonObj->isDictionary()) {
RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err);
return false;
}
JSONDictionary *jsonDict = dynamic_cast<JSONDictionary *>(jsonObj);
if (!jsonDict) {
RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err);
return false;
}
std::string scriptMethod;
if (!jsonDict->get(SystemMethodRequest::NAME, &scriptMethod) || (scriptMethod.length() <= 0)) {
RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err);
return false;
}
// Couldn't override '_set_method'
if (isSetMethod(scriptMethod)) {
RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err);
return false;
}
std::string scriptLang;
if (!jsonDict->get(SystemMethodRequest::LANGUAGE, &scriptLang) || (scriptLang.length() <= 0)) {
RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeInvalidParams, err);
return false;
}
// This method is removed if the code parameter is null.
std::string scriptCode;
jsonDict->get(SystemMethodRequest::CODE, &scriptCode);
// Encode
int encodeType = Script::ENCODING_NONE;
std::string encodeTypeStr;
if (jsonDict->get(SystemMethodRequest::ENCODE, &encodeTypeStr)) {
if (encodeTypeStr.compare(SystemMethodRequest::ENCODE_BASE64)) {
encodeType = Script::ENCODING_BASE64;
}
}
return this->scriptMgr.setScript(scriptMethod, scriptLang, scriptCode, encodeType, err);
}
////////////////////////////////////////////////
// System Dynamic Method
////////////////////////////////////////////////
bool Round::LocalNode::isSystemMethod(const std::string &method) {
return (method.find(SystemMethodRequest::PREFIX) == 0) ? true : false;
}
bool Round::LocalNode::execSystemMethod(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) {
static std::map<std::string, int> systemMethods;
enum {
SystemGetNodeInfo,
SystemGetClusterInfo,
SystemGetNetworkInfo,
};
if (systemMethods.size() <= 0) {
systemMethods[SystemMethodRequest::GET_NODE_INFO] = SystemGetNodeInfo;
systemMethods[SystemMethodRequest::GET_CLUSTER_INFO] = SystemGetClusterInfo;
systemMethods[SystemMethodRequest::GET_NETWORK_INFO] = SystemGetNetworkInfo;
}
std::string reqMethod;
nodeReq->getMethod(&reqMethod);
if (systemMethods.find(reqMethod) == systemMethods.end()) {
RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeMethodNotFound, error);
return false;
}
int systemMethodType = systemMethods[reqMethod];
switch (systemMethodType) {
case SystemGetNodeInfo:
return _get_node_info(nodeReq, nodeRes, error);
case SystemGetClusterInfo:
return _get_cluster_info(nodeReq, nodeRes, error);
case SystemGetNetworkInfo:
return _get_network_info(nodeReq, nodeRes, error);
}
RPC::JSON::ErrorCodeToError(RPC::JSON::ErrorCodeMethodNotFound, error);
return false;
}
bool Round::LocalNode::_get_node_info(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) {
SystemGetNodeInfoResponse sysRes(nodeRes);
return sysRes.setNode(this);
}
bool Round::LocalNode::_get_cluster_info(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) {
SystemGetClusterInfoResponse sysRes(nodeRes);
return sysRes.setCluster(this);
}
bool Round::LocalNode::_get_network_info(const NodeRequest *nodeReq, NodeResponse *nodeRes, Error *error) {
SystemGetNetworkInfoResponse sysRes(nodeRes);
return sysRes.setClusters(this);
}
<|endoftext|>
|
<commit_before>/*!
\copyright (c) RDO-Team, 2003-2012
\file output.cpp
\author (rdo@rk9.bmstu.ru)
\date 20.02.2003
\brief
\indent 4T
*/
// ---------------------------------------------------------------------------- PCH
#include "app/rdo_studio_mfc/pch/stdpch.h"
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/report/build_edit_line_info.h"
#include "app/rdo_studio_mfc/src/output.h"
#include "app/rdo_studio_mfc/src/application.h"
#include "app/rdo_studio_mfc/src/main_windows_base.h"
#include "app/rdo_studio_mfc/src/model/model.h"
#include "app/rdo_studio_mfc/edit_ctrls/rdobuildedit.h"
#include "app/rdo_studio_mfc/edit_ctrls/rdodebugedit.h"
#include "app/rdo_studio_mfc/edit_ctrls/rdofindedit.h"
#include "app/rdo_studio_mfc/rdo_edit/rdoeditorresults.h"
#include "app/rdo_studio_mfc/rdo_edit/rdoeditortabctrl.h"
#include "app/rdo_studio_mfc/rdo_tracer/rdotracer.h"
#include "app/rdo_studio_mfc/rdo_tracer/tracer_ctrls/rdotracerlogctrl.h"
// --------------------------------------------------------------------------------
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
using namespace rdoEditor;
using namespace rdoEditCtrl;
using namespace rdo::simulation::report;
// --------------------------------------------------------------------------------
// -------------------- RDOStudioOutput
// --------------------------------------------------------------------------------
BEGIN_MESSAGE_MAP(RDOStudioOutput, RDOStudioDockWnd)
ON_WM_CREATE()
END_MESSAGE_MAP()
RDOStudioOutput::RDOStudioOutput()
: build (NULL)
, debug (NULL)
, trace (NULL)
, results(NULL)
, find (NULL)
{}
RDOStudioOutput::~RDOStudioOutput()
{
eraseMenu( &popupMenu );
}
int RDOStudioOutput::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (RDOStudioDockWnd::OnCreate(lpCreateStruct) == -1)
return -1;
tab.Create( NULL, NULL, 0, CRect(0, 0, 100, 100), this, 0 );
tab.modifyTabStyle( 0, TCS_MULTILINE );
// tab.modifyTabStyle( 0, TCS_BOTTOM | TCS_MULTILINE );
popupMenu.CreatePopupMenu();
if (AfxGetMainWnd())
{
CMenu* mainMenu = AfxGetMainWnd()->GetMenu();
if (mainMenu)
{
rbool maximized = studioApp.getIMainWnd()->isMDIMaximazed();
int delta = maximized ? 1 : 0;
appendMenu( mainMenu->GetSubMenu( 1 + delta ), 4, &popupMenu );
appendMenu( mainMenu->GetSubMenu( 1 + delta ), 8, &popupMenu );
appendMenu( mainMenu->GetSubMenu( 1 + delta ), 10, &popupMenu );
popupMenu.AppendMenu( MF_SEPARATOR );
appendMenu( mainMenu->GetSubMenu( 2 + delta ), 0, &popupMenu );
appendMenu( mainMenu->GetSubMenu( 2 + delta ), 1, &popupMenu );
appendMenu( mainMenu->GetSubMenu( 2 + delta ), 2, &popupMenu );
popupMenu.AppendMenu( MF_SEPARATOR );
appendMenu( mainMenu->GetSubMenu( 2 + delta ), 7, &popupMenu );
appendMenu( mainMenu->GetSubMenu( 2 + delta ), 8, &popupMenu );
appendMenu( mainMenu->GetSubMenu( 2 + delta ), 9, &popupMenu );
appendMenu( mainMenu->GetSubMenu( 2 + delta ), 10, &popupMenu );
}
}
build = new RDOBuildEdit;
debug = new RDODebugEdit;
trace = tracer->createLog();
results = new RDOEditorResults;
find = new RDOFindEdit;
build->Create( NULL, NULL, 0, CRect(0, 0, 0, 0), tab.getTabAsParent(), 0 );
debug->Create( NULL, NULL, 0, CRect(0, 0, 0, 0), tab.getTabAsParent(), 0 );
trace->Create( NULL, NULL, 0, CRect(0, 0, 0, 0), tab.getTabAsParent(), 0 );
results->Create( NULL, NULL, 0, CRect(0, 0, 0, 0), tab.getTabAsParent(), 0 );
find->Create( NULL, NULL, 0, CRect(0, 0, 0, 0), tab.getTabAsParent(), 0 );
build->setEditorStyle( &studioApp.getStyle()->style_build );
build->setPopupMenu( &popupMenu );
debug->setEditorStyle( &studioApp.getStyle()->style_debug );
debug->setPopupMenu( &popupMenu );
trace->setStyle( &studioApp.getStyle()->style_trace );
results->setEditorStyle( &studioApp.getStyle()->style_results );
results->setPopupMenu( &popupMenu );
find->setEditorStyle( &studioApp.getStyle()->style_find );
find->setPopupMenu( &popupMenu );
tab.insertItem( build, rdo::format( IDS_TAB_BUILD ).c_str() );
tab.insertItem( debug, rdo::format( IDS_TAB_DEBUG ).c_str() );
tab.insertItem( trace, rdo::format( IDS_TAB_TRACE ).c_str() );
tab.insertItem( results, rdo::format( IDS_TAB_RESULT ).c_str() );
tab.insertItem( find, rdo::format( IDS_TAB_FIND ).c_str() );
//studioApp.m_pMainFrame->registerCmdWnd( build, build->getSCIHWND() );
//studioApp.m_pMainFrame->registerCmdWnd( debug, debug->getSCIHWND() );
//studioApp.m_pMainFrame->registerCmdWnd( trace );
//studioApp.m_pMainFrame->registerCmdWnd( results, results->getSCIHWND() );
//studioApp.m_pMainFrame->registerCmdWnd( find, find->getSCIHWND() );
return 0;
}
void RDOStudioOutput::showBuild()
{
studioApp.getIMainWnd()->showOutput();
tab.setCurrentItem( 0 );
if ( plugins->studioIsShow() ) {
build->SetFocus();
UpdateWindow();
}
}
void RDOStudioOutput::showDebug()
{
studioApp.getIMainWnd()->showOutput();
tab.setCurrentItem( 1 );
if ( plugins->studioIsShow() ) {
debug->SetFocus();
UpdateWindow();
}
}
void RDOStudioOutput::showTrace()
{
studioApp.getIMainWnd()->showOutput();
tab.setCurrentItem( 2 );
if ( plugins->studioIsShow() ) {
trace->SetFocus();
UpdateWindow();
}
}
void RDOStudioOutput::showResults()
{
studioApp.getIMainWnd()->showOutput();
tab.setCurrentItem( 3 );
if ( plugins->studioIsShow() ) {
results->SetFocus();
UpdateWindow();
}
}
void RDOStudioOutput::showFind()
{
studioApp.getIMainWnd()->showOutput();
tab.setCurrentItem( 4 );
if ( plugins->studioIsShow() ) {
find->SetFocus();
UpdateWindow();
}
}
void RDOStudioOutput::clearBuild()
{
if ( build ) build->clearAll();
}
void RDOStudioOutput::clearDebug()
{
if ( debug ) debug->clearAll();
}
void RDOStudioOutput::clearResults()
{
if ( results ) results->clearAll();
}
void RDOStudioOutput::clearFind()
{
if ( find ) find->clearAll();
}
void RDOStudioOutput::appendStringToBuild( CREF(tstring) str ) const
{
PTR(BuildEditLineInfo) pLine = new BuildEditLineInfo( str );
build->appendLine( pLine );
}
void RDOStudioOutput::appendStringToBuild( CREF(rdo::simulation::report::FileMessage) message ) const
{
if ( message.getType() == rdo::simulation::report::FileMessage::MT_ERROR || (message.getType() == FileMessage::MT_WARNING && static_cast<PTR(RDOBuildEditTheme)>(studioApp.m_pMainFrame->style_build.theme)->warning) )
{
PTR(BuildEditLineInfo) pLine = new BuildEditLineInfo(message);
build->appendLine(pLine);
}
}
void RDOStudioOutput::appendStringToDebug( CREF(tstring) str ) const
{
debug->appendLine( str );
}
void RDOStudioOutput::appendStringToResults( CREF(tstring) str ) const
{
int pos = results->getCurrentPos();
results->setCurrentPos(results->getLength());
results->setReadOnly (false);
results->appendText (str );
results->setReadOnly (true );
results->setCurrentPos(pos );
}
void RDOStudioOutput::appendStringToFind( CREF(tstring) str, rdoModelObjects::RDOFileType fileType, int lineNumber, int posInLine ) const
{
LogEditLineInfo* line = new LogEditLineInfo( rdo::simulation::report::FileMessage(str, fileType, lineNumber, posInLine ) );
find->appendLine( line );
}
void RDOStudioOutput::Tab::changeCurrentItem()
{
studioApp.getIMainWnd()->output.updateLogConnection();
}
void RDOStudioOutput::updateLogConnection() const
{
int item = tab.getCurrentIndex();
RDOLogEdit* log = NULL;
if ( item == 0 ) {
log = build;
} else if ( item == 4 ) {
log = find;
}
if ( log ) {
rdoEditor::RDOEditorTabCtrl* editor_tab = model->getTab();
if ( editor_tab ) {
for ( int i = 0; i < editor_tab->getItemCount(); i++ ) {
editor_tab->getItemEdit( i )->setLog( *log );
}
}
}
}
void RDOStudioOutput::updateStyles() const
{
build->setEditorStyle( &studioApp.getStyle()->style_build );
debug->setEditorStyle( &studioApp.getStyle()->style_debug );
trace->setStyle( &studioApp.getStyle()->style_trace );
results->setEditorStyle( &studioApp.getStyle()->style_results );
find->setEditorStyle( &studioApp.getStyle()->style_find );
}
<commit_msg> - конфликт после мержа<commit_after>/*!
\copyright (c) RDO-Team, 2003-2012
\file output.cpp
\author (rdo@rk9.bmstu.ru)
\date 20.02.2003
\brief
\indent 4T
*/
// ---------------------------------------------------------------------------- PCH
#include "app/rdo_studio_mfc/pch/stdpch.h"
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/report/build_edit_line_info.h"
#include "app/rdo_studio_mfc/src/output.h"
#include "app/rdo_studio_mfc/src/application.h"
#include "app/rdo_studio_mfc/src/main_windows_base.h"
#include "app/rdo_studio_mfc/src/model/model.h"
#include "app/rdo_studio_mfc/edit_ctrls/rdobuildedit.h"
#include "app/rdo_studio_mfc/edit_ctrls/rdodebugedit.h"
#include "app/rdo_studio_mfc/edit_ctrls/rdofindedit.h"
#include "app/rdo_studio_mfc/rdo_edit/rdoeditorresults.h"
#include "app/rdo_studio_mfc/rdo_edit/rdoeditortabctrl.h"
#include "app/rdo_studio_mfc/rdo_tracer/rdotracer.h"
#include "app/rdo_studio_mfc/rdo_tracer/tracer_ctrls/rdotracerlogctrl.h"
// --------------------------------------------------------------------------------
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
using namespace rdoEditor;
using namespace rdoEditCtrl;
using namespace rdo::simulation::report;
// --------------------------------------------------------------------------------
// -------------------- RDOStudioOutput
// --------------------------------------------------------------------------------
BEGIN_MESSAGE_MAP(RDOStudioOutput, RDOStudioDockWnd)
ON_WM_CREATE()
END_MESSAGE_MAP()
RDOStudioOutput::RDOStudioOutput()
: build (NULL)
, debug (NULL)
, trace (NULL)
, results(NULL)
, find (NULL)
{}
RDOStudioOutput::~RDOStudioOutput()
{
eraseMenu( &popupMenu );
}
int RDOStudioOutput::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (RDOStudioDockWnd::OnCreate(lpCreateStruct) == -1)
return -1;
tab.Create( NULL, NULL, 0, CRect(0, 0, 100, 100), this, 0 );
tab.modifyTabStyle( 0, TCS_MULTILINE );
// tab.modifyTabStyle( 0, TCS_BOTTOM | TCS_MULTILINE );
popupMenu.CreatePopupMenu();
if (AfxGetMainWnd())
{
CMenu* mainMenu = AfxGetMainWnd()->GetMenu();
if (mainMenu)
{
rbool maximized = studioApp.getIMainWnd()->isMDIMaximazed();
int delta = maximized ? 1 : 0;
appendMenu( mainMenu->GetSubMenu( 1 + delta ), 4, &popupMenu );
appendMenu( mainMenu->GetSubMenu( 1 + delta ), 8, &popupMenu );
appendMenu( mainMenu->GetSubMenu( 1 + delta ), 10, &popupMenu );
popupMenu.AppendMenu( MF_SEPARATOR );
appendMenu( mainMenu->GetSubMenu( 2 + delta ), 0, &popupMenu );
appendMenu( mainMenu->GetSubMenu( 2 + delta ), 1, &popupMenu );
appendMenu( mainMenu->GetSubMenu( 2 + delta ), 2, &popupMenu );
popupMenu.AppendMenu( MF_SEPARATOR );
appendMenu( mainMenu->GetSubMenu( 2 + delta ), 7, &popupMenu );
appendMenu( mainMenu->GetSubMenu( 2 + delta ), 8, &popupMenu );
appendMenu( mainMenu->GetSubMenu( 2 + delta ), 9, &popupMenu );
appendMenu( mainMenu->GetSubMenu( 2 + delta ), 10, &popupMenu );
}
}
build = new RDOBuildEdit;
debug = new RDODebugEdit;
trace = tracer->createLog();
results = new RDOEditorResults;
find = new RDOFindEdit;
build->Create( NULL, NULL, 0, CRect(0, 0, 0, 0), tab.getTabAsParent(), 0 );
debug->Create( NULL, NULL, 0, CRect(0, 0, 0, 0), tab.getTabAsParent(), 0 );
trace->Create( NULL, NULL, 0, CRect(0, 0, 0, 0), tab.getTabAsParent(), 0 );
results->Create( NULL, NULL, 0, CRect(0, 0, 0, 0), tab.getTabAsParent(), 0 );
find->Create( NULL, NULL, 0, CRect(0, 0, 0, 0), tab.getTabAsParent(), 0 );
build->setEditorStyle( &studioApp.getStyle()->style_build );
build->setPopupMenu( &popupMenu );
debug->setEditorStyle( &studioApp.getStyle()->style_debug );
debug->setPopupMenu( &popupMenu );
trace->setStyle( &studioApp.getStyle()->style_trace );
results->setEditorStyle( &studioApp.getStyle()->style_results );
results->setPopupMenu( &popupMenu );
find->setEditorStyle( &studioApp.getStyle()->style_find );
find->setPopupMenu( &popupMenu );
tab.insertItem( build, rdo::format( IDS_TAB_BUILD ).c_str() );
tab.insertItem( debug, rdo::format( IDS_TAB_DEBUG ).c_str() );
tab.insertItem( trace, rdo::format( IDS_TAB_TRACE ).c_str() );
tab.insertItem( results, rdo::format( IDS_TAB_RESULT ).c_str() );
tab.insertItem( find, rdo::format( IDS_TAB_FIND ).c_str() );
//studioApp.m_pMainFrame->registerCmdWnd( build, build->getSCIHWND() );
//studioApp.m_pMainFrame->registerCmdWnd( debug, debug->getSCIHWND() );
//studioApp.m_pMainFrame->registerCmdWnd( trace );
//studioApp.m_pMainFrame->registerCmdWnd( results, results->getSCIHWND() );
//studioApp.m_pMainFrame->registerCmdWnd( find, find->getSCIHWND() );
return 0;
}
void RDOStudioOutput::showBuild()
{
studioApp.getIMainWnd()->showOutput();
tab.setCurrentItem( 0 );
if ( plugins->studioIsShow() ) {
build->SetFocus();
UpdateWindow();
}
}
void RDOStudioOutput::showDebug()
{
studioApp.getIMainWnd()->showOutput();
tab.setCurrentItem( 1 );
if ( plugins->studioIsShow() ) {
debug->SetFocus();
UpdateWindow();
}
}
void RDOStudioOutput::showTrace()
{
studioApp.getIMainWnd()->showOutput();
tab.setCurrentItem( 2 );
if ( plugins->studioIsShow() ) {
trace->SetFocus();
UpdateWindow();
}
}
void RDOStudioOutput::showResults()
{
studioApp.getIMainWnd()->showOutput();
tab.setCurrentItem( 3 );
if ( plugins->studioIsShow() ) {
results->SetFocus();
UpdateWindow();
}
}
void RDOStudioOutput::showFind()
{
studioApp.getIMainWnd()->showOutput();
tab.setCurrentItem( 4 );
if ( plugins->studioIsShow() ) {
find->SetFocus();
UpdateWindow();
}
}
void RDOStudioOutput::clearBuild()
{
if ( build ) build->clearAll();
}
void RDOStudioOutput::clearDebug()
{
if ( debug ) debug->clearAll();
}
void RDOStudioOutput::clearResults()
{
if ( results ) results->clearAll();
}
void RDOStudioOutput::clearFind()
{
if ( find ) find->clearAll();
}
void RDOStudioOutput::appendStringToBuild( CREF(tstring) str ) const
{
PTR(BuildEditLineInfo) pLine = new BuildEditLineInfo( str );
build->appendLine( pLine );
}
void RDOStudioOutput::appendStringToBuild( CREF(rdo::simulation::report::FileMessage) message ) const
{
if ( message.getType() == rdo::simulation::report::FileMessage::MT_ERROR || (message.getType() == FileMessage::MT_WARNING && static_cast<PTR(RDOBuildEditTheme)>(studioApp.getStyle()->style_build.theme)->warning) )
{
PTR(BuildEditLineInfo) pLine = new BuildEditLineInfo(message);
build->appendLine(pLine);
}
}
void RDOStudioOutput::appendStringToDebug( CREF(tstring) str ) const
{
debug->appendLine( str );
}
void RDOStudioOutput::appendStringToResults( CREF(tstring) str ) const
{
int pos = results->getCurrentPos();
results->setCurrentPos(results->getLength());
results->setReadOnly (false);
results->appendText (str );
results->setReadOnly (true );
results->setCurrentPos(pos );
}
void RDOStudioOutput::appendStringToFind( CREF(tstring) str, rdoModelObjects::RDOFileType fileType, int lineNumber, int posInLine ) const
{
LogEditLineInfo* line = new LogEditLineInfo( rdo::simulation::report::FileMessage(str, fileType, lineNumber, posInLine ) );
find->appendLine( line );
}
void RDOStudioOutput::Tab::changeCurrentItem()
{
studioApp.getIMainWnd()->output.updateLogConnection();
}
void RDOStudioOutput::updateLogConnection() const
{
int item = tab.getCurrentIndex();
RDOLogEdit* log = NULL;
if ( item == 0 ) {
log = build;
} else if ( item == 4 ) {
log = find;
}
if ( log ) {
rdoEditor::RDOEditorTabCtrl* editor_tab = model->getTab();
if ( editor_tab ) {
for ( int i = 0; i < editor_tab->getItemCount(); i++ ) {
editor_tab->getItemEdit( i )->setLog( *log );
}
}
}
}
void RDOStudioOutput::updateStyles() const
{
build->setEditorStyle( &studioApp.getStyle()->style_build );
debug->setEditorStyle( &studioApp.getStyle()->style_debug );
trace->setStyle( &studioApp.getStyle()->style_trace );
results->setEditorStyle( &studioApp.getStyle()->style_results );
find->setEditorStyle( &studioApp.getStyle()->style_find );
}
<|endoftext|>
|
<commit_before>/* * This file is part of Maliit framework *
*
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
*
* Contact: maliit-discuss@lists.maliit.org
*
* 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
* and appearing in the file LICENSE.LGPL included in the packaging
* of this file.
*/
#include "mdirectinputcontextplugin.h"
#include "mimserver.h"
#include "mimapphostedserverlogic.h"
#include "connectionfactory.h"
#include "mimdirectserverconnection.h"
#include "miminputcontextdirectconnection.h"
#include <maliit/inputmethod.h>
using namespace std::tr1;
#include <minputcontext.h>
#include <QString>
#include <QStringList>
namespace {
const QString MaliitDirectInputContextName(MALIIT_INPUTCONTEXT_NAME"Direct");
}
MDirectInputContextPlugin::MDirectInputContextPlugin(QObject *parent)
: QInputContextPlugin(parent)
{
// nothing
}
MDirectInputContextPlugin::~MDirectInputContextPlugin()
{
// nothing
}
QInputContext *MDirectInputContextPlugin::create(const QString &key)
{
QInputContext *ctx = NULL;
if (key == MaliitDirectInputContextName) {
QSharedPointer<MImDirectServerConnection> serverConnection =
qSharedPointerObjectCast<MImDirectServerConnection>(Maliit::createServerConnection(MaliitDirectInputContextName));
MImInputContextDirectConnection *icConnection = new MImInputContextDirectConnection;
serverConnection->connectTo(icConnection);
shared_ptr<MInputContextConnection> icConn(icConnection);
QSharedPointer<MImAppHostedServerLogic> serverLogic(new MImAppHostedServerLogic);
MImServer::configureSettings(MImServer::TemporarySettings);
MImServer *imServer = new MImServer(serverLogic, icConn);
Maliit::InputMethod::instance()->setWidget(serverLogic->pluginsProxyWidget());
ctx = new MInputContext(serverConnection, MaliitDirectInputContextName, this);
imServer->setParent(ctx);
} else {
qCritical() << "Unknown plugin name";
}
return ctx;
}
QString MDirectInputContextPlugin::description(const QString &s)
{
Q_UNUSED(s);
return "Maliit input context plugin";
}
QString MDirectInputContextPlugin::displayName(const QString &s)
{
Q_UNUSED(s);
// TODO: want this translated?
return "Input context for Maliit input methods";
}
QStringList MDirectInputContextPlugin::keys() const
{
return QStringList(MaliitDirectInputContextName);
}
QStringList MDirectInputContextPlugin::languages(const QString &)
{
return QStringList("EN"); // FIXME
}
Q_EXPORT_PLUGIN2(mdirectinputcontext, MDirectInputContextPlugin)
<commit_msg>Differentiate direct input context plugin description strings<commit_after>/* * This file is part of Maliit framework *
*
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
*
* Contact: maliit-discuss@lists.maliit.org
*
* 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
* and appearing in the file LICENSE.LGPL included in the packaging
* of this file.
*/
#include "mdirectinputcontextplugin.h"
#include "mimserver.h"
#include "mimapphostedserverlogic.h"
#include "connectionfactory.h"
#include "mimdirectserverconnection.h"
#include "miminputcontextdirectconnection.h"
#include <maliit/inputmethod.h>
using namespace std::tr1;
#include <minputcontext.h>
#include <QString>
#include <QStringList>
namespace {
const QString MaliitDirectInputContextName(MALIIT_INPUTCONTEXT_NAME"Direct");
}
MDirectInputContextPlugin::MDirectInputContextPlugin(QObject *parent)
: QInputContextPlugin(parent)
{
// nothing
}
MDirectInputContextPlugin::~MDirectInputContextPlugin()
{
// nothing
}
QInputContext *MDirectInputContextPlugin::create(const QString &key)
{
QInputContext *ctx = NULL;
if (key == MaliitDirectInputContextName) {
QSharedPointer<MImDirectServerConnection> serverConnection =
qSharedPointerObjectCast<MImDirectServerConnection>(Maliit::createServerConnection(MaliitDirectInputContextName));
MImInputContextDirectConnection *icConnection = new MImInputContextDirectConnection;
serverConnection->connectTo(icConnection);
shared_ptr<MInputContextConnection> icConn(icConnection);
QSharedPointer<MImAppHostedServerLogic> serverLogic(new MImAppHostedServerLogic);
MImServer::configureSettings(MImServer::TemporarySettings);
MImServer *imServer = new MImServer(serverLogic, icConn);
Maliit::InputMethod::instance()->setWidget(serverLogic->pluginsProxyWidget());
ctx = new MInputContext(serverConnection, MaliitDirectInputContextName, this);
imServer->setParent(ctx);
} else {
qCritical() << "Unknown plugin name";
}
return ctx;
}
QString MDirectInputContextPlugin::description(const QString &s)
{
Q_UNUSED(s);
return "Maliit input context plugin (direct)";
}
QString MDirectInputContextPlugin::displayName(const QString &s)
{
Q_UNUSED(s);
// TODO: want this translated?
return "Input context for Maliit input methods (direct)";
}
QStringList MDirectInputContextPlugin::keys() const
{
return QStringList(MaliitDirectInputContextName);
}
QStringList MDirectInputContextPlugin::languages(const QString &)
{
return QStringList("EN"); // FIXME
}
Q_EXPORT_PLUGIN2(mdirectinputcontext, MDirectInputContextPlugin)
<|endoftext|>
|
<commit_before>//==============================================================================
#include <game.hpp>
#include <engine.hpp>
#include <entity.hpp>
#include <entity_manager.hpp>
#include <viewport.hpp>
#include <score.hpp>
#include <hgeresource.h>
#include <algorithm>
#include <set>
//==============================================================================
Game::Game()
:
Context(),
m_arena()
{
}
//------------------------------------------------------------------------------
Game::~Game()
{
}
//------------------------------------------------------------------------------
// public:
//------------------------------------------------------------------------------
void
Game::init()
{
HGE * hge( Engine::hge() );
b2World * b2d( Engine::b2d() );
hgeResourceManager * rm( Engine::rm() );
ViewPort * vp( Engine::vp() );
Engine::em()->init();
vp->offset().x = 0.0f;
vp->offset().y = 0.0f;
vp->centre().x = 0.0f;
vp->centre().y = 0.0f;
vp->bounds().x = 1280.0f;
vp->bounds().y = 720.0f;
vp->setAngle( 0.0f );
vp->setScale( 10.0f );
for ( int x = 0; x < 10; ++x )
{
for ( int y = 0; y < 20; ++y )
{
m_arena[x][y] = false;
}
}
}
//------------------------------------------------------------------------------
void
Game::fini()
{
Engine::em()->fini();
}
//------------------------------------------------------------------------------
bool
Game::update( float dt )
{
const Controller & pad( Engine::instance()->getController() );
HGE * hge( Engine::hge() );
ViewPort * vp( Engine::vp() );
bool paused( Engine::instance()->isPaused() );
return false;
}
//------------------------------------------------------------------------------
void
Game::render()
{
hgeResourceManager * rm( Engine::rm() );
hgeFont* font = Engine::rm()->GetFont("menu");
ViewPort * vp( Engine::vp() );
vp->setTransform();
float scale( 1.0f );
std::vector< Entity * > entities;
for ( b2Body * body( Engine::b2d()->GetBodyList() ); body != NULL;
body = body->GetNext() )
{
Entity * entity( static_cast< Entity * >( body->GetUserData() ) );
if ( entity )
{
entity->render( scale );
}
}
Engine::vp()->reset();
vp->setTransform();
hgeSprite * black( rm->GetSprite( "empty" ) );
hgeSprite * white( rm->GetSprite( "tile" ) );
for ( int x = 0; x < 10; ++x )
{
for ( int y = 0; y < 20; ++y )
{
hgeSprite * sprite( m_arena[x][y] ? white : black );
sprite->RenderEx( ( x - 4.5 ) * 3.2f, ( y - 9.5 ) * 3.2f,
0.0f, 0.1f );
}
}
}
//==============================================================================
<commit_msg>Fix warning<commit_after>//==============================================================================
#include <game.hpp>
#include <engine.hpp>
#include <entity.hpp>
#include <entity_manager.hpp>
#include <viewport.hpp>
#include <score.hpp>
#include <hgeresource.h>
#include <algorithm>
#include <set>
//==============================================================================
Game::Game()
:
Context(),
m_arena()
{
}
//------------------------------------------------------------------------------
Game::~Game()
{
}
//------------------------------------------------------------------------------
// public:
//------------------------------------------------------------------------------
void
Game::init()
{
HGE * hge( Engine::hge() );
b2World * b2d( Engine::b2d() );
hgeResourceManager * rm( Engine::rm() );
ViewPort * vp( Engine::vp() );
Engine::em()->init();
vp->offset().x = 0.0f;
vp->offset().y = 0.0f;
vp->centre().x = 0.0f;
vp->centre().y = 0.0f;
vp->bounds().x = 1280.0f;
vp->bounds().y = 720.0f;
vp->setAngle( 0.0f );
vp->setScale( 10.0f );
for ( int x = 0; x < 10; ++x )
{
for ( int y = 0; y < 20; ++y )
{
m_arena[x][y] = false;
}
}
}
//------------------------------------------------------------------------------
void
Game::fini()
{
Engine::em()->fini();
}
//------------------------------------------------------------------------------
bool
Game::update( float dt )
{
const Controller & pad( Engine::instance()->getController() );
HGE * hge( Engine::hge() );
ViewPort * vp( Engine::vp() );
bool paused( Engine::instance()->isPaused() );
return false;
}
//------------------------------------------------------------------------------
void
Game::render()
{
hgeResourceManager * rm( Engine::rm() );
hgeFont* font = Engine::rm()->GetFont("menu");
ViewPort * vp( Engine::vp() );
vp->setTransform();
float scale( 1.0f );
std::vector< Entity * > entities;
for ( b2Body * body( Engine::b2d()->GetBodyList() ); body != NULL;
body = body->GetNext() )
{
Entity * entity( static_cast< Entity * >( body->GetUserData() ) );
if ( entity )
{
entity->render( scale );
}
}
Engine::vp()->reset();
vp->setTransform();
hgeSprite * black( rm->GetSprite( "empty" ) );
hgeSprite * white( rm->GetSprite( "tile" ) );
for ( int x = 0; x < 10; ++x )
{
for ( int y = 0; y < 20; ++y )
{
hgeSprite * sprite( m_arena[x][y] ? white : black );
sprite->RenderEx( ( x - 4.5f ) * 3.2f, ( y - 9.5f ) * 3.2f,
0.0f, 0.1f );
}
}
}
//==============================================================================
<|endoftext|>
|
<commit_before>#include "game.h"
#include "rook.h"
#include "pawn.h"
#include "queen.h"
#include "bishop.h"
#include "knight.h"
#include "king.h"
game::game()
{
turn = true;
board.addPiece(new rook(0,0,true));
board.addPiece(new knight(1,0,true));
board.addPiece(new bishop(2,0,true));
board.addPiece(new queen(3,0,true));
board.addPiece(new king(4,0,true));
board.addPiece(new bishop(5,0,true));
board.addPiece(new knight(6,0,true));
board.addPiece(new rook(7,0,true));
for(int i = 0;i<8;i++)
{
board.addPiece(new pawn(i,1,true));
}
board.addPiece(new rook(0,7,true));
board.addPiece(new knight(1,7,true));
board.addPiece(new bishop(2,7,true));
board.addPiece(new queen(3,7,true));
board.addPiece(new king(4,7,true));
board.addPiece(new bishop(5,7,true));
board.addPiece(new knight(6,7,true));
board.addPiece(new rook(7,7,true));
for(int i = 0;i<8;i++)
{
board.addPiece(new pawn(i,6,true));
}
}
game::~game(){}
void game::print()
{
board.printBoard();
}<commit_msg>Fixed naming issue<commit_after>#include "game.h"
#include "rook.h"
#include "pawn.h"
#include "queen.h"
#include "bishop.h"
#include "knight.h"
#include "king.h"
game::game()
{
turn = true;
boardGame.addPiece(new rook(0,0,true));
boardGame.addPiece(new knight(1,0,true));
boardGame.addPiece(new bishop(2,0,true));
boardGame.addPiece(new queen(3,0,true));
boardGame.addPiece(new king(4,0,true));
boardGame.addPiece(new bishop(5,0,true));
boardGame.addPiece(new knight(6,0,true));
boardGame.addPiece(new rook(7,0,true));
for(int i = 0;i<8;i++)
{
boardGame.addPiece(new pawn(i,1,true));
}
boardGame.addPiece(new rook(0,7,true));
boardGame.addPiece(new knight(1,7,true));
boardGame.addPiece(new bishop(2,7,true));
boardGame.addPiece(new queen(3,7,true));
boardGame.addPiece(new king(4,7,true));
boardGame.addPiece(new bishop(5,7,true));
boardGame.addPiece(new knight(6,7,true));
boardGame.addPiece(new rook(7,7,true));
for(int i = 0;i<8;i++)
{
boardGame.addPiece(new pawn(i,6,true));
}
}
game::~game(){}
void game::print()
{
boardGame.printBoard();
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2015, Project OSRM, Dennis Luxen, others
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef RECTANGLE_HPP
#define RECTANGLE_HPP
#include "coordinate_calculation.hpp"
#include <boost/assert.hpp>
#include <algorithm>
#include <cstdint>
#include <limits>
// TODO: Make template type, add tests
struct RectangleInt2D
{
RectangleInt2D()
: min_lon(std::numeric_limits<int32_t>::max()),
max_lon(std::numeric_limits<int32_t>::min()),
min_lat(std::numeric_limits<int32_t>::max()), max_lat(std::numeric_limits<int32_t>::min())
{
}
int32_t min_lon, max_lon;
int32_t min_lat, max_lat;
void MergeBoundingBoxes(const RectangleInt2D &other)
{
min_lon = std::min(min_lon, other.min_lon);
max_lon = std::max(max_lon, other.max_lon);
min_lat = std::min(min_lat, other.min_lat);
max_lat = std::max(max_lat, other.max_lat);
BOOST_ASSERT(min_lat != std::numeric_limits<int32_t>::min());
BOOST_ASSERT(min_lon != std::numeric_limits<int32_t>::min());
BOOST_ASSERT(max_lat != std::numeric_limits<int32_t>::min());
BOOST_ASSERT(max_lon != std::numeric_limits<int32_t>::min());
}
FixedPointCoordinate Centroid() const
{
FixedPointCoordinate centroid;
// The coordinates of the midpoints are given by:
// x = (x1 + x2) /2 and y = (y1 + y2) /2.
centroid.lon = (min_lon + max_lon) / 2;
centroid.lat = (min_lat + max_lat) / 2;
return centroid;
}
bool Intersects(const RectangleInt2D &other) const
{
FixedPointCoordinate upper_left(other.max_lat, other.min_lon);
FixedPointCoordinate upper_right(other.max_lat, other.max_lon);
FixedPointCoordinate lower_right(other.min_lat, other.max_lon);
FixedPointCoordinate lower_left(other.min_lat, other.min_lon);
return (Contains(upper_left) || Contains(upper_right) || Contains(lower_right) ||
Contains(lower_left));
}
float GetMinDist(const FixedPointCoordinate &location) const
{
const bool is_contained = Contains(location);
if (is_contained)
{
return 0.0f;
}
enum Direction
{
INVALID = 0,
NORTH = 1,
SOUTH = 2,
EAST = 4,
NORTH_EAST = 5,
SOUTH_EAST = 6,
WEST = 8,
NORTH_WEST = 9,
SOUTH_WEST = 10
};
Direction d = INVALID;
if (location.lat > max_lat)
d = (Direction)(d | NORTH);
else if (location.lat < min_lat)
d = (Direction)(d | SOUTH);
if (location.lon > max_lon)
d = (Direction)(d | EAST);
else if (location.lon < min_lon)
d = (Direction)(d | WEST);
BOOST_ASSERT(d != INVALID);
float min_dist = std::numeric_limits<float>::max();
switch (d)
{
case NORTH:
min_dist = coordinate_calculation::euclidean_distance(
location, FixedPointCoordinate(max_lat, location.lon));
break;
case SOUTH:
min_dist = coordinate_calculation::euclidean_distance(
location, FixedPointCoordinate(min_lat, location.lon));
break;
case WEST:
min_dist = coordinate_calculation::euclidean_distance(
location, FixedPointCoordinate(location.lat, min_lon));
break;
case EAST:
min_dist = coordinate_calculation::euclidean_distance(
location, FixedPointCoordinate(location.lat, max_lon));
break;
case NORTH_EAST:
min_dist = coordinate_calculation::euclidean_distance(
location, FixedPointCoordinate(max_lat, max_lon));
break;
case NORTH_WEST:
min_dist = coordinate_calculation::euclidean_distance(
location, FixedPointCoordinate(max_lat, min_lon));
break;
case SOUTH_EAST:
min_dist = coordinate_calculation::euclidean_distance(
location, FixedPointCoordinate(min_lat, max_lon));
break;
case SOUTH_WEST:
min_dist = coordinate_calculation::euclidean_distance(
location, FixedPointCoordinate(min_lat, min_lon));
break;
default:
break;
}
BOOST_ASSERT(min_dist < std::numeric_limits<float>::max());
return min_dist;
}
float GetMinMaxDist(const FixedPointCoordinate &location) const
{
float min_max_dist = std::numeric_limits<float>::max();
// Get minmax distance to each of the four sides
const FixedPointCoordinate upper_left(max_lat, min_lon);
const FixedPointCoordinate upper_right(max_lat, max_lon);
const FixedPointCoordinate lower_right(min_lat, max_lon);
const FixedPointCoordinate lower_left(min_lat, min_lon);
min_max_dist =
std::min(min_max_dist,
std::max(coordinate_calculation::euclidean_distance(location, upper_left),
coordinate_calculation::euclidean_distance(location, upper_right)));
min_max_dist =
std::min(min_max_dist,
std::max(coordinate_calculation::euclidean_distance(location, upper_right),
coordinate_calculation::euclidean_distance(location, lower_right)));
min_max_dist =
std::min(min_max_dist,
std::max(coordinate_calculation::euclidean_distance(location, lower_right),
coordinate_calculation::euclidean_distance(location, lower_left)));
min_max_dist =
std::min(min_max_dist,
std::max(coordinate_calculation::euclidean_distance(location, lower_left),
coordinate_calculation::euclidean_distance(location, upper_left)));
return min_max_dist;
}
bool Contains(const FixedPointCoordinate &location) const
{
const bool lats_contained = (location.lat >= min_lat) && (location.lat <= max_lat);
const bool lons_contained = (location.lon >= min_lon) && (location.lon <= max_lon);
return lats_contained && lons_contained;
}
friend std::ostream &operator<<(std::ostream &out, const RectangleInt2D &rect)
{
out << rect.min_lat / COORDINATE_PRECISION << "," << rect.min_lon / COORDINATE_PRECISION
<< " " << rect.max_lat / COORDINATE_PRECISION << ","
<< rect.max_lon / COORDINATE_PRECISION;
return out;
}
};
#endif
<commit_msg>add include to be self-sufficient<commit_after>/*
Copyright (c) 2015, Project OSRM, Dennis Luxen, others
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef RECTANGLE_HPP
#define RECTANGLE_HPP
#include "coordinate_calculation.hpp"
#include <boost/assert.hpp>
#include <osrm/coordinate.hpp>
#include <algorithm>
#include <cstdint>
#include <limits>
// TODO: Make template type, add tests
struct RectangleInt2D
{
RectangleInt2D()
: min_lon(std::numeric_limits<int32_t>::max()),
max_lon(std::numeric_limits<int32_t>::min()),
min_lat(std::numeric_limits<int32_t>::max()), max_lat(std::numeric_limits<int32_t>::min())
{
}
int32_t min_lon, max_lon;
int32_t min_lat, max_lat;
void MergeBoundingBoxes(const RectangleInt2D &other)
{
min_lon = std::min(min_lon, other.min_lon);
max_lon = std::max(max_lon, other.max_lon);
min_lat = std::min(min_lat, other.min_lat);
max_lat = std::max(max_lat, other.max_lat);
BOOST_ASSERT(min_lat != std::numeric_limits<int32_t>::min());
BOOST_ASSERT(min_lon != std::numeric_limits<int32_t>::min());
BOOST_ASSERT(max_lat != std::numeric_limits<int32_t>::min());
BOOST_ASSERT(max_lon != std::numeric_limits<int32_t>::min());
}
FixedPointCoordinate Centroid() const
{
FixedPointCoordinate centroid;
// The coordinates of the midpoints are given by:
// x = (x1 + x2) /2 and y = (y1 + y2) /2.
centroid.lon = (min_lon + max_lon) / 2;
centroid.lat = (min_lat + max_lat) / 2;
return centroid;
}
bool Intersects(const RectangleInt2D &other) const
{
FixedPointCoordinate upper_left(other.max_lat, other.min_lon);
FixedPointCoordinate upper_right(other.max_lat, other.max_lon);
FixedPointCoordinate lower_right(other.min_lat, other.max_lon);
FixedPointCoordinate lower_left(other.min_lat, other.min_lon);
return (Contains(upper_left) || Contains(upper_right) || Contains(lower_right) ||
Contains(lower_left));
}
float GetMinDist(const FixedPointCoordinate &location) const
{
const bool is_contained = Contains(location);
if (is_contained)
{
return 0.0f;
}
enum Direction
{
INVALID = 0,
NORTH = 1,
SOUTH = 2,
EAST = 4,
NORTH_EAST = 5,
SOUTH_EAST = 6,
WEST = 8,
NORTH_WEST = 9,
SOUTH_WEST = 10
};
Direction d = INVALID;
if (location.lat > max_lat)
d = (Direction)(d | NORTH);
else if (location.lat < min_lat)
d = (Direction)(d | SOUTH);
if (location.lon > max_lon)
d = (Direction)(d | EAST);
else if (location.lon < min_lon)
d = (Direction)(d | WEST);
BOOST_ASSERT(d != INVALID);
float min_dist = std::numeric_limits<float>::max();
switch (d)
{
case NORTH:
min_dist = coordinate_calculation::euclidean_distance(
location, FixedPointCoordinate(max_lat, location.lon));
break;
case SOUTH:
min_dist = coordinate_calculation::euclidean_distance(
location, FixedPointCoordinate(min_lat, location.lon));
break;
case WEST:
min_dist = coordinate_calculation::euclidean_distance(
location, FixedPointCoordinate(location.lat, min_lon));
break;
case EAST:
min_dist = coordinate_calculation::euclidean_distance(
location, FixedPointCoordinate(location.lat, max_lon));
break;
case NORTH_EAST:
min_dist = coordinate_calculation::euclidean_distance(
location, FixedPointCoordinate(max_lat, max_lon));
break;
case NORTH_WEST:
min_dist = coordinate_calculation::euclidean_distance(
location, FixedPointCoordinate(max_lat, min_lon));
break;
case SOUTH_EAST:
min_dist = coordinate_calculation::euclidean_distance(
location, FixedPointCoordinate(min_lat, max_lon));
break;
case SOUTH_WEST:
min_dist = coordinate_calculation::euclidean_distance(
location, FixedPointCoordinate(min_lat, min_lon));
break;
default:
break;
}
BOOST_ASSERT(min_dist < std::numeric_limits<float>::max());
return min_dist;
}
float GetMinMaxDist(const FixedPointCoordinate &location) const
{
float min_max_dist = std::numeric_limits<float>::max();
// Get minmax distance to each of the four sides
const FixedPointCoordinate upper_left(max_lat, min_lon);
const FixedPointCoordinate upper_right(max_lat, max_lon);
const FixedPointCoordinate lower_right(min_lat, max_lon);
const FixedPointCoordinate lower_left(min_lat, min_lon);
min_max_dist =
std::min(min_max_dist,
std::max(coordinate_calculation::euclidean_distance(location, upper_left),
coordinate_calculation::euclidean_distance(location, upper_right)));
min_max_dist =
std::min(min_max_dist,
std::max(coordinate_calculation::euclidean_distance(location, upper_right),
coordinate_calculation::euclidean_distance(location, lower_right)));
min_max_dist =
std::min(min_max_dist,
std::max(coordinate_calculation::euclidean_distance(location, lower_right),
coordinate_calculation::euclidean_distance(location, lower_left)));
min_max_dist =
std::min(min_max_dist,
std::max(coordinate_calculation::euclidean_distance(location, lower_left),
coordinate_calculation::euclidean_distance(location, upper_left)));
return min_max_dist;
}
bool Contains(const FixedPointCoordinate &location) const
{
const bool lats_contained = (location.lat >= min_lat) && (location.lat <= max_lat);
const bool lons_contained = (location.lon >= min_lon) && (location.lon <= max_lon);
return lats_contained && lons_contained;
}
friend std::ostream &operator<<(std::ostream &out, const RectangleInt2D &rect)
{
out << rect.min_lat / COORDINATE_PRECISION << "," << rect.min_lon / COORDINATE_PRECISION
<< " " << rect.max_lat / COORDINATE_PRECISION << ","
<< rect.max_lon / COORDINATE_PRECISION;
return out;
}
};
#endif
<|endoftext|>
|
<commit_before>#include <lib/Numeric.hpp>
#include <iostream>
#include <thread>
#include <mutex>
#include <vector>
#include <atomic>
struct Fraction
{
Fraction(uint64_t n, uint64_t d)
: numerator(n),
denominator(d),
value((double)n / d)
{
}
Fraction(uint64_t n, uint64_t d, double f)
: numerator(n),
denominator(d),
value(f)
{
}
size_t numerator;
size_t denominator;
double value;
auto operator<(const Fraction& other) const -> bool
{
return value < other.value;
}
};
/**
* Counting fractions in a range
* Problem 71
*
* Consider the fraction, n/d, where n and d are positive integers.
* If n < d and HCF(n, d) = 1, it is called a reduced proper fraction.
*
* If we list the set of reduced proper fractions for d <= 8 in ascending order of size, we get:
* 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8
*
* It can be seen that there are 3 fractions between 1/3 and 1/2.
*
* How many fractions lie between 1/3 and 1/2 in the sorted set of reduced proper fractions for d <= 12,000?
*/
int main()
{
Fraction lower_bound{1, 3};
Fraction upper_bound{1, 2};
std::atomic<size_t> worker_position{0};
std::atomic<size_t> g_count{0};
std::vector<std::thread> workers;
constexpr size_t WORKER_COUNT = 8;
constexpr size_t STOP = 1'000'000;
constexpr size_t WORK_AMOUNT = 1000;
for(size_t w = 0; w < WORKER_COUNT; ++w)
{
workers.emplace_back(
[&lower_bound, &upper_bound, &worker_position, &g_count]()
{
while(worker_position < STOP)
{
size_t start_idx = worker_position.fetch_add(WORK_AMOUNT);
size_t stop_idx = start_idx + WORK_AMOUNT;
size_t local_count{0};
if(__glibc_unlikely(start_idx == 0))
{
start_idx = 2;
}
if(__glibc_unlikely(stop_idx >= STOP))
{
stop_idx = STOP + 1;
}
for(size_t d = start_idx; d < stop_idx; ++d)
{
for(size_t n = 1; n < d; ++n)
{
// skip anything less than current left fraction
double value = ((double)n) / d;
if(value <= lower_bound.value)
{
continue;
}
// stop entirely if the fraction is now 3/7 or greater.
else if(value >= upper_bound.value)
{
break;
}
// If the gcd equals 1, reduce the fraction
// and save to merge into the global to_the_left var
// across threads. These are our candidates to be the
// next version
auto hcf = lib::gcd(n, d);
if(hcf == 1)
{
++local_count;
}
}
}
g_count += local_count;
}
}
);
}
while(worker_position < STOP)
{
using namespace std::chrono_literals;
std::this_thread::sleep_for(1000ms);
std::cout << worker_position << "\n";
}
for(auto& t : workers)
{
t.join();
}
std::cout << g_count;
return 0;
}
<commit_msg>add p073 c++ solution<commit_after>#include <lib/Numeric.hpp>
#include <iostream>
#include <thread>
#include <mutex>
#include <vector>
#include <atomic>
struct Fraction
{
Fraction(uint64_t n, uint64_t d)
: numerator(n),
denominator(d),
value((double)n / d)
{
}
Fraction(uint64_t n, uint64_t d, double f)
: numerator(n),
denominator(d),
value(f)
{
}
size_t numerator;
size_t denominator;
double value;
auto operator<(const Fraction& other) const -> bool
{
return value < other.value;
}
};
/**
* Counting fractions in a range
* Problem 71
*
* Consider the fraction, n/d, where n and d are positive integers.
* If n < d and HCF(n, d) = 1, it is called a reduced proper fraction.
*
* If we list the set of reduced proper fractions for d <= 8 in ascending order of size, we get:
* 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8
*
* It can be seen that there are 3 fractions between 1/3 and 1/2.
*
* How many fractions lie between 1/3 and 1/2 in the sorted set of reduced proper fractions for d <= 12,000?
*/
int main()
{
Fraction lower_bound{1, 3};
Fraction upper_bound{1, 2};
std::atomic<size_t> worker_position{0};
std::atomic<size_t> g_count{0};
std::vector<std::thread> workers;
constexpr size_t WORKER_COUNT = 8;
constexpr size_t STOP = 12'000;
constexpr size_t WORK_AMOUNT = 1000;
for(size_t w = 0; w < WORKER_COUNT; ++w)
{
workers.emplace_back(
[&lower_bound, &upper_bound, &worker_position, &g_count]()
{
while(worker_position < STOP)
{
size_t start_idx = worker_position.fetch_add(WORK_AMOUNT);
size_t stop_idx = start_idx + WORK_AMOUNT;
size_t local_count{0};
if(__glibc_unlikely(start_idx == 0))
{
start_idx = 2;
}
if(__glibc_unlikely(stop_idx >= STOP))
{
stop_idx = STOP + 1;
}
for(size_t d = start_idx; d < stop_idx; ++d)
{
for(size_t n = 1; n < d; ++n)
{
// skip anything less than current left fraction
double value = ((double)n) / d;
if(value <= lower_bound.value)
{
continue;
}
// stop entirely if the fraction is now 3/7 or greater.
else if(value >= upper_bound.value)
{
break;
}
// If the gcd equals 1, reduce the fraction
// and save to merge into the global to_the_left var
// across threads. These are our candidates to be the
// next version
auto hcf = lib::gcd(n, d);
if(hcf == 1)
{
++local_count;
}
}
}
g_count += local_count;
}
}
);
}
while(worker_position < STOP)
{
using namespace std::chrono_literals;
std::this_thread::sleep_for(1000ms);
std::cout << worker_position << "\n";
}
for(auto& t : workers)
{
t.join();
}
std::cout << g_count;
return 0;
}
<|endoftext|>
|
<commit_before>/*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "RConnectSocket.hxx"
#include "net/Resolver.hxx"
#include "net/AddressInfo.hxx"
#include "net/UniqueSocketDescriptor.hxx"
#include "system/Error.hxx"
#include "io/FileDescriptor.hxx"
UniqueSocketDescriptor
ResolveConnectSocket(const char *host_and_port, int default_port,
const struct addrinfo &hints)
{
const auto ail = Resolve(host_and_port, default_port, &hints);
const auto &ai = ail.front();
UniqueSocketDescriptor s;
if (!s.CreateNonBlock(ai.GetFamily(), ai.GetType(), ai.GetProtocol()))
throw MakeErrno("Failed to create socket");
if (!s.Connect(ai)) {
if (errno != EINPROGRESS)
throw MakeErrno("Failed to connect");
int w = FileDescriptor(s.Get()).WaitWritable(60000);
if (w < 0)
throw MakeErrno("Connect wait error");
else if (w == 0)
throw std::runtime_error("Connect timeout");
int err = s.GetError();
if (err != 0)
throw MakeErrno(err, "Failed to connect");
}
return s;
}
<commit_msg>net/RConnectSocket: eliminate obsolete FileDescriptor cast<commit_after>/*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "RConnectSocket.hxx"
#include "net/Resolver.hxx"
#include "net/AddressInfo.hxx"
#include "net/UniqueSocketDescriptor.hxx"
#include "system/Error.hxx"
UniqueSocketDescriptor
ResolveConnectSocket(const char *host_and_port, int default_port,
const struct addrinfo &hints)
{
const auto ail = Resolve(host_and_port, default_port, &hints);
const auto &ai = ail.front();
UniqueSocketDescriptor s;
if (!s.CreateNonBlock(ai.GetFamily(), ai.GetType(), ai.GetProtocol()))
throw MakeErrno("Failed to create socket");
if (!s.Connect(ai)) {
if (errno != EINPROGRESS)
throw MakeErrno("Failed to connect");
int w = s.WaitWritable(60000);
if (w < 0)
throw MakeErrno("Connect wait error");
else if (w == 0)
throw std::runtime_error("Connect timeout");
int err = s.GetError();
if (err != 0)
throw MakeErrno(err, "Failed to connect");
}
return s;
}
<|endoftext|>
|
<commit_before>#include "genome.h"
#include <vector>
#include <algorithm>
Genome::Genome(const TrainingParameters& parameters) :
parameters(parameters),
genes(parameters.numberOfInputs * parameters.numberOfOutputs)
{
auto *currentGene = &genes.front();
for (auto in = 0U; in < parameters.numberOfInputs; ++in) {
for (auto out = 0U; out < parameters.numberOfOutputs; ++out) {
currentGene->from = in;
currentGene->to = out + parameters.numberOfInputs;
++currentGene;
}
}
}
std::size_t Genome::ExtrapolateNeuronCount() const {
auto CompareToNeuron = [](const Gene& lhs, const Gene& rhs) {
return lhs.to < rhs.to;
};
auto maxNeuronGene = std::max_element(genes.begin(), genes.end(), CompareToNeuron);
// TODO jnf Maybe add lookup table
return maxNeuronGene->to + 1U;
}
std::size_t Genome::GetGeneCount() const {
return genes.size();
}
Genome& Genome::operator=(const Genome& other)
{
this->genes = other.genes;
const_cast<TrainingParameters&>(this->parameters) = other.parameters;
return *this;
}
void Genome::MutateGenes() {
if (ShouldAddConnection()) {
AddRandomConnection();
}
else
if (ShouldAddNeuron()) {
AddRandomNeuron();
}
else {
ShuffleWeights();
}
}
bool Genome::DidChanceOccure(float chance)
{
auto num = rand() % 100;
return num < int(100.0f * chance);
}
void Genome::AddRandomNeuron()
{
Gene* randGene = nullptr;
do {
int num = rand() % genes.size();
randGene = &genes[num];
} while (!randGene->isEnabled);
auto indexOfNewNeuron = ExtrapolateNeuronCount();
Gene g1;
g1.from = randGene->from;
g1.to = indexOfNewNeuron;
Gene g2;
g2.from = indexOfNewNeuron;
g2.to = randGene->to;
randGene->isEnabled = false;
genes.push_back(std::move(g1));
genes.push_back(std::move(g2));
}
void Genome::AddRandomConnection()
{
auto GetRandomNumberBetween = [](size_t min, size_t max) {
return rand() % (max - min) + min;
};
Gene newConnection;
auto highestNeuronIndex = ExtrapolateNeuronCount() - 1U;
newConnection.from = GetRandomNumberBetween(0U, highestNeuronIndex - 1U);
newConnection.to = GetRandomNumberBetween(newConnection.from + 1, highestNeuronIndex);
genes.push_back(newConnection);
}
void Genome::ShuffleWeights()
{
for (size_t i = 0; i < genes.size(); i++) {
if (ShouldMutateWeight()) {
MutateWeightOfGeneAt(i);
}
}
}
void Genome::MutateWeightOfGeneAt(size_t index)
{
constexpr float chanceOfTotalWeightReset = 0.1f;
if (DidChanceOccure(chanceOfTotalWeightReset)) {
genes[index].SetRandomWeight();
} else {
PerturbWeightAt(index);
}
}
void Genome::PerturbWeightAt(size_t index)
{
constexpr float perturbanceBoundaries = 0.2f;
auto perturbance = (float)(rand() % 10'000) / 10'000.0f * perturbanceBoundaries;
if (rand() % 2) {
perturbance = -perturbance;
}
genes[index].weight *= perturbance;
}
double Genome::GetGeneticalDistanceFrom(const Genome& other) const
{
double totalWeightDifference = 0.0;
size_t numberOfOverlapingGenes = 0;
size_t sizeOfSmallerGenome = std::min(this->GetGeneCount(), other.GetGeneCount());
auto IsHistoricalMarkingSameAt = [&](size_t i) {
return this->GetGeneAt(i).historicalMarking == other[i].historicalMarking;
};
for (size_t i = 0; i < sizeOfSmallerGenome && IsHistoricalMarkingSameAt(i); ++i) {
totalWeightDifference += (double)std::abs(this->GetGeneAt(i).weight - other[i].weight);
++numberOfOverlapingGenes;
}
auto numberOfDisjointGenes = this->GetGeneCount() + other.GetGeneCount() - (size_t)2 * numberOfOverlapingGenes;
auto sizeOfBiggerGenome = std::max(this->GetGeneCount(), other.GetGeneCount());
auto disjointGenesInfluence = (double)numberOfDisjointGenes / (double)sizeOfBiggerGenome;
auto averageWeightDifference = totalWeightDifference / (double)numberOfOverlapingGenes;
disjointGenesInfluence *= (double)parameters.advanced.speciation.importanceOfDisjointGenes;
averageWeightDifference *= (double)parameters.advanced.speciation.importanceOfAverageWeightDifference;
return disjointGenesInfluence + averageWeightDifference;
}<commit_msg>Continued work on #2<commit_after>#include "genome.h"
#include <vector>
#include <algorithm>
Genome::Genome(const TrainingParameters& parameters) :
parameters(parameters),
genes(parameters.numberOfInputs * parameters.numberOfOutputs)
{
auto *currentGene = &genes.front();
for (auto in = 0U; in < parameters.numberOfInputs; ++in) {
for (auto out = 0U; out < parameters.numberOfOutputs; ++out) {
currentGene->from = in;
currentGene->to = out + parameters.numberOfInputs;
++currentGene;
}
}
}
std::size_t Genome::ExtrapolateNeuronCount() const {
auto CompareToNeuron = [](const Gene& lhs, const Gene& rhs) {
return lhs.to < rhs.to;
};
auto maxNeuronGene = std::max_element(genes.begin(), genes.end(), CompareToNeuron);
// TODO jnf Maybe add lookup table
return maxNeuronGene->to + 1U;
}
std::size_t Genome::GetGeneCount() const {
return genes.size();
}
Genome& Genome::operator=(const Genome& other)
{
this->genes = other.genes;
const_cast<TrainingParameters&>(this->parameters) = other.parameters;
return *this;
}
void Genome::MutateGenes() {
if (ShouldAddConnection()) {
AddRandomConnection();
}
else
if (ShouldAddNeuron()) {
AddRandomNeuron();
}
else {
ShuffleWeights();
}
}
bool Genome::DidChanceOccure(float chance)
{
auto num = rand() % 100;
return num < int(100.0f * chance);
}
void Genome::AddRandomNeuron()
{
Gene* randGene = nullptr;
do {
int num = rand() % genes.size();
randGene = &genes[num];
} while (!randGene->isEnabled);
auto indexOfNewNeuron = ExtrapolateNeuronCount();
Gene g1;
g1.from = randGene->from;
g1.to = indexOfNewNeuron;
g1.weight = randGene->weight;
Gene g2;
g2.from = indexOfNewNeuron;
g2.to = randGene->to;
g2.weight = randGene->weight;
randGene->isEnabled = false;
genes.push_back(std::move(g1));
genes.push_back(std::move(g2));
}
void Genome::AddRandomConnection()
{
auto GetRandomNumberBetween = [](size_t min, size_t max) {
return rand() % (max - min) + min;
};
Gene newConnection;
auto highestNeuronIndex = ExtrapolateNeuronCount() - 1U;
newConnection.from = GetRandomNumberBetween(0U, highestNeuronIndex - 1U);
newConnection.to = GetRandomNumberBetween(newConnection.from + 1, highestNeuronIndex);
//genes.push_back(newConnection);
}
void Genome::ShuffleWeights()
{
for (size_t i = 0; i < genes.size(); i++) {
if (ShouldMutateWeight()) {
MutateWeightOfGeneAt(i);
}
}
}
void Genome::MutateWeightOfGeneAt(size_t index)
{
constexpr float chanceOfTotalWeightReset = 0.1f;
if (DidChanceOccure(chanceOfTotalWeightReset)) {
genes[index].SetRandomWeight();
} else {
PerturbWeightAt(index);
}
}
void Genome::PerturbWeightAt(size_t index)
{
constexpr float perturbanceBoundaries = 0.2f;
auto perturbance = (float)(rand() % 10'000) / 10'000.0f * perturbanceBoundaries;
if (rand() % 2) {
perturbance = -perturbance;
}
genes[index].weight *= perturbance;
}
double Genome::GetGeneticalDistanceFrom(const Genome& other) const
{
double totalWeightDifference = 0.0;
size_t numberOfOverlapingGenes = 0;
size_t sizeOfSmallerGenome = std::min(this->GetGeneCount(), other.GetGeneCount());
auto IsHistoricalMarkingSameAt = [&](size_t i) {
return this->GetGeneAt(i).historicalMarking == other[i].historicalMarking;
};
for (size_t i = 0; i < sizeOfSmallerGenome && IsHistoricalMarkingSameAt(i); ++i) {
totalWeightDifference += (double)std::abs(this->GetGeneAt(i).weight - other[i].weight);
++numberOfOverlapingGenes;
}
auto numberOfDisjointGenes = this->GetGeneCount() + other.GetGeneCount() - (size_t)2 * numberOfOverlapingGenes;
auto sizeOfBiggerGenome = std::max(this->GetGeneCount(), other.GetGeneCount());
auto disjointGenesInfluence = (double)numberOfDisjointGenes / (double)sizeOfBiggerGenome;
auto averageWeightDifference = totalWeightDifference / (double)numberOfOverlapingGenes;
disjointGenesInfluence *= (double)parameters.advanced.speciation.importanceOfDisjointGenes;
averageWeightDifference *= (double)parameters.advanced.speciation.importanceOfAverageWeightDifference;
return disjointGenesInfluence + averageWeightDifference;
}<|endoftext|>
|
<commit_before>//-----------------------------------------------------------------------------
// Jikken - 3D Abstract High Performance Graphics API
// Copyright(c) 2017 Jeff Hutchinson
// Copyright(c) 2017 Tim Barnes
//
// 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 <cassert>
#include <cstdlib>
#include "vulkan/VulkanGraphicsDevice.hpp"
#include "vulkan/VulkanUtil.hpp"
//just temp
#include <GLFW/glfw3.h>
namespace Jikken
{
VulkanGraphicsDevice::VulkanGraphicsDevice() :
mInstance(VK_NULL_HANDLE),
mSurface(VK_NULL_HANDLE),
mPhysicalDevice(VK_NULL_HANDLE),
mDevice(VK_NULL_HANDLE),
mGraphicsQueue(VK_NULL_HANDLE),
mGraphicsQueueIndex(UINT32_MAX),
mDebugCallback(VK_NULL_HANDLE),
mAllocCallback(nullptr)
{
}
VulkanGraphicsDevice::~VulkanGraphicsDevice()
{
//wait for device to be idle
if (mDevice)
vkDeviceWaitIdle(mDevice);
// cleanup other stuff
// destroy logical device
if (mDevice)
vkDestroyDevice(mDevice, mAllocCallback);
if (mSurface)
vkDestroySurfaceKHR(mInstance, mSurface, mAllocCallback);
if (mDebugCallback)
{
auto debugReportDestroyFunc = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(mInstance, "vkDestroyDebugReportCallbackEXT");
if (debugReportDestroyFunc != nullptr)
{
debugReportDestroyFunc(mInstance, mDebugCallback, mAllocCallback);
}
}
if (mInstance)
vkDestroyInstance(mInstance, mAllocCallback);
}
bool VulkanGraphicsDevice::init(void *glfwWinHandle)
{
if (!glfwVulkanSupported())
{
std::printf("Vulkan is not supported\n");
return false;
}
//validation layers
#ifdef _DEBUG
bool validationLayersEnabled = true;
#else
bool validationLayersEnabled = false
#endif
//grab vulkan instance extension list
uint32_t extensionsCount = 0;
VkResult result = vkEnumerateInstanceExtensionProperties(nullptr, &extensionsCount, nullptr);
if (result != VK_SUCCESS || extensionsCount == 0)
{
std::printf("vkEnumerateInstanceExtensionProperties failed\n");
return false;
}
std::vector<VkExtensionProperties> instanceExtensionList(extensionsCount);
result = vkEnumerateInstanceExtensionProperties(nullptr, &extensionsCount, instanceExtensionList.data());
if (result != VK_SUCCESS)
{
std::printf("vkEnumerateInstanceExtensionProperties failed\n");
return false;
}
//get required extensions from glfw
uint32_t glfwExtCount = 0;
const char** glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtCount);
if (glfwExtCount == 0)
{
std::printf("Failed to find any required extensions\n");
return false;
}
std::vector<const char*> requiredExtensions(glfwExtensions, glfwExtensions + glfwExtCount);
if (validationLayersEnabled)
requiredExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
// check required extension list against all availble extensions
for (const auto &ext : requiredExtensions)
{
if (!vkutils::checkExtension(ext, instanceExtensionList))
{
std::printf("Required extension: %s not found\n", ext);
return false;
}
}
//setup validation layers - just VK_LAYER_LUNARG_standard_validation for now. There are plenty more though ;)
const std::vector<const char*> validationLayers = { "VK_LAYER_LUNARG_standard_validation" };
uint32_t layerCount = 0;
if (validationLayersEnabled)
{
vkEnumerateInstanceLayerProperties(&layerCount, nullptr);
std::vector<VkLayerProperties> availableLayers(layerCount);
vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data());
for (const auto &layer : validationLayers)
{
//this is not fatal so just disable validation layers if it is not found
if (!vkutils::checkLayer(layer, availableLayers))
{
std::printf("Could not find validation layer: %s Disabling validation layers\n", layer);
validationLayersEnabled = false;
}
}
}
//setup application and instance info
VkApplicationInfo appInfo = {};
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
appInfo.pApplicationName = "Jikken";
appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.pEngineName = "Jikken";
appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.apiVersion = VK_API_VERSION_1_0;
VkInstanceCreateInfo createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
createInfo.flags = 0;
createInfo.pApplicationInfo = &appInfo;
createInfo.enabledExtensionCount = static_cast<uint32_t>(requiredExtensions.size());
createInfo.ppEnabledExtensionNames = requiredExtensions.data();
if (validationLayersEnabled)
{
createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
createInfo.ppEnabledLayerNames = validationLayers.data();
}
else
createInfo.enabledLayerCount = 0;
//finally create vulkan instance
result = vkCreateInstance(&createInfo, mAllocCallback, &mInstance);
if (result != VK_SUCCESS)
{
std::printf("vkCreateInstance failed\n");
return false;
}
//setup debug callback if validation layers enabled
if (validationLayersEnabled)
{
VkDebugReportCallbackCreateInfoEXT debugCreateInfo = {};
debugCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT;
debugCreateInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT;
debugCreateInfo.pfnCallback = vkutils::debugCallback;
auto debugReportFunc = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(mInstance, "vkCreateDebugReportCallbackEXT");
if (debugReportFunc != nullptr)
{
result = debugReportFunc(mInstance, &debugCreateInfo, mAllocCallback, &mDebugCallback);
if (result != VK_SUCCESS)
{
std::printf("vkCreateDebugReportCallbackEXT failed\n");
return false;
}
}
else
{
std::printf("Failed to retrieve vkCreateDebugReportCallbackEXT address. Debug callbacks will be disabled\n");
validationLayersEnabled = false;
}
}
//create window surface
result = glfwCreateWindowSurface(mInstance, static_cast<GLFWwindow*>(glfwWinHandle), mAllocCallback, &mSurface);
if (result != VK_SUCCESS)
{
std::printf("Failed to create vulkan window surface\n");
return false;
}
//find physical devices
uint32_t numDevices = 0;
result = vkEnumeratePhysicalDevices(mInstance, &numDevices, nullptr);
if (result != VK_SUCCESS || numDevices == 0)
{
std::printf("vkEnumeratePhysicalDevices failed\n");
return false;
}
std::vector<VkPhysicalDevice> physicalDevices(numDevices);
result = vkEnumeratePhysicalDevices(mInstance, &numDevices, physicalDevices.data());
if (result != VK_SUCCESS)
{
std::printf("vkEnumeratePhysicalDevices failed\n");
return false;
}
//get our queue index and hopefully find an acceptable device
for (const auto &device : physicalDevices)
{
//break on first acceptable device
if (vkutils::checkPhysicalDevice(device, mSurface, mGraphicsQueueIndex))
{
mPhysicalDevice = device;
break;
}
}
if (mGraphicsQueueIndex == UINT32_MAX)
{
std::printf("Failed to find suitable graphics queue\n");
return false;
}
if (mPhysicalDevice == VK_NULL_HANDLE)
{
std::printf("Failed to select a physical device\n");
return false;
}
//print some information about our physical device
vkutils::printDeviceInfo(mPhysicalDevice);
//create logical device
std::vector<VkDeviceQueueCreateInfo> queueCreateInfos;
float queuePriority = 1.0f;
VkDeviceQueueCreateInfo queueCreateInfo = {};
queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queueCreateInfo.flags = 0;
queueCreateInfo.queueFamilyIndex = mGraphicsQueueIndex;
queueCreateInfo.queueCount = 1;
queueCreateInfo.pQueuePriorities = &queuePriority;
queueCreateInfos.push_back(queueCreateInfo);
//need swap chain extension - this extension is already checked above with checkPhysicalDevice, no need to check again
std::vector<const char*> requiredDeviceExtensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME };
VkDeviceCreateInfo deviceCreateInfo = {};
deviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
deviceCreateInfo.flags = 0;
deviceCreateInfo.enabledExtensionCount = static_cast<uint32_t>(requiredDeviceExtensions.size());
deviceCreateInfo.ppEnabledExtensionNames = requiredDeviceExtensions.data();
deviceCreateInfo.queueCreateInfoCount = 1;
deviceCreateInfo.pQueueCreateInfos = queueCreateInfos.data();
deviceCreateInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size());
deviceCreateInfo.enabledLayerCount = 0;
if (validationLayersEnabled)
{
deviceCreateInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
deviceCreateInfo.ppEnabledLayerNames = validationLayers.data();
}
//create vulkan device
//todo: for some reason NVidia drivers spew out vkCreateSampler errors here, find out why because we are not calling that function!
result = vkCreateDevice(mPhysicalDevice, &deviceCreateInfo, mAllocCallback, &mDevice);
if (result != VK_SUCCESS)
{
std::printf("vkCreateDevice failed\n");
return false;
}
//grab graphics queue handle
vkGetDeviceQueue(mDevice, mGraphicsQueueIndex, 0, &mGraphicsQueue);
if (!mGraphicsQueue)
{
std::printf("Failed to retrieve graphics queue\n");
return false;
}
return true;
}
ShaderHandle VulkanGraphicsDevice::createShader(const std::vector<ShaderDetails> &shaders)
{
return InvalidHandle;
}
BufferHandle VulkanGraphicsDevice::createBuffer(BufferType type, BufferUsageHint hint, size_t dataSize, float *data)
{
return InvalidHandle;
}
LayoutHandle VulkanGraphicsDevice::createVertexInputLayout(const std::vector<VertexInputLayout> &attributes)
{
return InvalidHandle;
}
VertexArrayHandle VulkanGraphicsDevice::createVAO(LayoutHandle layout, BufferHandle vertexBuffer, BufferHandle indexBuffer)
{
return InvalidHandle;
}
void VulkanGraphicsDevice::bindConstantBuffer(ShaderHandle shader, BufferHandle cBuffer, int32_t index)
{
}
void VulkanGraphicsDevice::deleteVertexInputLayout(LayoutHandle handle)
{
}
void VulkanGraphicsDevice::deleteVAO(VertexArrayHandle handle)
{
}
void VulkanGraphicsDevice::deleteBuffer(BufferHandle handle)
{
}
void VulkanGraphicsDevice::deleteShader(ShaderHandle handle)
{
}
void VulkanGraphicsDevice::submitCommandQueue(CommandQueue *cmdQueue)
{
}
void VulkanGraphicsDevice::present()
{
}
}<commit_msg>todo comment update<commit_after>//-----------------------------------------------------------------------------
// Jikken - 3D Abstract High Performance Graphics API
// Copyright(c) 2017 Jeff Hutchinson
// Copyright(c) 2017 Tim Barnes
//
// 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 <cassert>
#include <cstdlib>
#include "vulkan/VulkanGraphicsDevice.hpp"
#include "vulkan/VulkanUtil.hpp"
//just temp
#include <GLFW/glfw3.h>
namespace Jikken
{
VulkanGraphicsDevice::VulkanGraphicsDevice() :
mInstance(VK_NULL_HANDLE),
mSurface(VK_NULL_HANDLE),
mPhysicalDevice(VK_NULL_HANDLE),
mDevice(VK_NULL_HANDLE),
mGraphicsQueue(VK_NULL_HANDLE),
mGraphicsQueueIndex(UINT32_MAX),
mDebugCallback(VK_NULL_HANDLE),
mAllocCallback(nullptr)
{
}
VulkanGraphicsDevice::~VulkanGraphicsDevice()
{
//wait for device to be idle
if (mDevice)
vkDeviceWaitIdle(mDevice);
// cleanup other stuff
// destroy logical device
if (mDevice)
vkDestroyDevice(mDevice, mAllocCallback);
if (mSurface)
vkDestroySurfaceKHR(mInstance, mSurface, mAllocCallback);
if (mDebugCallback)
{
auto debugReportDestroyFunc = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(mInstance, "vkDestroyDebugReportCallbackEXT");
if (debugReportDestroyFunc != nullptr)
{
debugReportDestroyFunc(mInstance, mDebugCallback, mAllocCallback);
}
}
if (mInstance)
vkDestroyInstance(mInstance, mAllocCallback);
}
bool VulkanGraphicsDevice::init(void *glfwWinHandle)
{
if (!glfwVulkanSupported())
{
std::printf("Vulkan is not supported\n");
// return false;
}
//validation layers
#ifdef _DEBUG
bool validationLayersEnabled = true;
#else
bool validationLayersEnabled = false
#endif
//grab vulkan instance extension list
uint32_t extensionsCount = 0;
VkResult result = vkEnumerateInstanceExtensionProperties(nullptr, &extensionsCount, nullptr);
if (result != VK_SUCCESS || extensionsCount == 0)
{
std::printf("vkEnumerateInstanceExtensionProperties failed\n");
return false;
}
std::vector<VkExtensionProperties> instanceExtensionList(extensionsCount);
result = vkEnumerateInstanceExtensionProperties(nullptr, &extensionsCount, instanceExtensionList.data());
if (result != VK_SUCCESS)
{
std::printf("vkEnumerateInstanceExtensionProperties failed\n");
return false;
}
//get required extensions from glfw
uint32_t glfwExtCount = 0;
const char** glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtCount);
if (glfwExtCount == 0)
{
std::printf("Failed to find any required extensions\n");
return false;
}
std::vector<const char*> requiredExtensions(glfwExtensions, glfwExtensions + glfwExtCount);
if (validationLayersEnabled)
requiredExtensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
// check required extension list against all availble extensions
for (const auto &ext : requiredExtensions)
{
if (!vkutils::checkExtension(ext, instanceExtensionList))
{
std::printf("Required extension: %s not found\n", ext);
return false;
}
}
//setup validation layers - just VK_LAYER_LUNARG_standard_validation for now. There are plenty more though ;)
const std::vector<const char*> validationLayers = { "VK_LAYER_LUNARG_standard_validation" };
uint32_t layerCount = 0;
if (validationLayersEnabled)
{
vkEnumerateInstanceLayerProperties(&layerCount, nullptr);
std::vector<VkLayerProperties> availableLayers(layerCount);
vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data());
for (const auto &layer : validationLayers)
{
//this is not fatal so just disable validation layers if it is not found
if (!vkutils::checkLayer(layer, availableLayers))
{
std::printf("Could not find validation layer: %s Disabling validation layers\n", layer);
validationLayersEnabled = false;
}
}
}
//setup application and instance info
VkApplicationInfo appInfo = {};
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
appInfo.pApplicationName = "Jikken";
appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.pEngineName = "Jikken";
appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.apiVersion = VK_API_VERSION_1_0;
VkInstanceCreateInfo createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
createInfo.flags = 0;
createInfo.pApplicationInfo = &appInfo;
createInfo.enabledExtensionCount = static_cast<uint32_t>(requiredExtensions.size());
createInfo.ppEnabledExtensionNames = requiredExtensions.data();
if (validationLayersEnabled)
{
createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
createInfo.ppEnabledLayerNames = validationLayers.data();
}
else
createInfo.enabledLayerCount = 0;
//finally create vulkan instance
result = vkCreateInstance(&createInfo, mAllocCallback, &mInstance);
if (result != VK_SUCCESS)
{
std::printf("vkCreateInstance failed\n");
return false;
}
//setup debug callback if validation layers enabled
if (validationLayersEnabled)
{
VkDebugReportCallbackCreateInfoEXT debugCreateInfo = {};
debugCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT;
debugCreateInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT | VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT;
debugCreateInfo.pfnCallback = vkutils::debugCallback;
auto debugReportFunc = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(mInstance, "vkCreateDebugReportCallbackEXT");
if (debugReportFunc != nullptr)
{
result = debugReportFunc(mInstance, &debugCreateInfo, mAllocCallback, &mDebugCallback);
if (result != VK_SUCCESS)
{
std::printf("vkCreateDebugReportCallbackEXT failed\n");
return false;
}
}
else
{
std::printf("Failed to retrieve vkCreateDebugReportCallbackEXT address. Debug callbacks will be disabled\n");
validationLayersEnabled = false;
}
}
//create window surface
result = glfwCreateWindowSurface(mInstance, static_cast<GLFWwindow*>(glfwWinHandle), mAllocCallback, &mSurface);
if (result != VK_SUCCESS)
{
std::printf("Failed to create vulkan window surface\n");
return false;
}
//find physical devices
uint32_t numDevices = 0;
result = vkEnumeratePhysicalDevices(mInstance, &numDevices, nullptr);
if (result != VK_SUCCESS || numDevices == 0)
{
std::printf("vkEnumeratePhysicalDevices failed\n");
return false;
}
std::vector<VkPhysicalDevice> physicalDevices(numDevices);
result = vkEnumeratePhysicalDevices(mInstance, &numDevices, physicalDevices.data());
if (result != VK_SUCCESS)
{
std::printf("vkEnumeratePhysicalDevices failed\n");
return false;
}
//get our queue index and hopefully find an acceptable device
for (const auto &device : physicalDevices)
{
//break on first acceptable device
if (vkutils::checkPhysicalDevice(device, mSurface, mGraphicsQueueIndex))
{
mPhysicalDevice = device;
break;
}
}
if (mGraphicsQueueIndex == UINT32_MAX)
{
std::printf("Failed to find suitable graphics queue\n");
return false;
}
if (mPhysicalDevice == VK_NULL_HANDLE)
{
std::printf("Failed to select a physical device\n");
return false;
}
//print some information about our physical device
vkutils::printDeviceInfo(mPhysicalDevice);
//create logical device
std::vector<VkDeviceQueueCreateInfo> queueCreateInfos;
float queuePriority = 1.0f;
VkDeviceQueueCreateInfo queueCreateInfo = {};
queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queueCreateInfo.flags = 0;
queueCreateInfo.queueFamilyIndex = mGraphicsQueueIndex;
queueCreateInfo.queueCount = 1;
queueCreateInfo.pQueuePriorities = &queuePriority;
queueCreateInfos.push_back(queueCreateInfo);
//need swap chain extension - this extension is already checked above with checkPhysicalDevice, no need to check again
std::vector<const char*> requiredDeviceExtensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME };
VkDeviceCreateInfo deviceCreateInfo = {};
deviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
deviceCreateInfo.flags = 0;
deviceCreateInfo.enabledExtensionCount = static_cast<uint32_t>(requiredDeviceExtensions.size());
deviceCreateInfo.ppEnabledExtensionNames = requiredDeviceExtensions.data();
deviceCreateInfo.queueCreateInfoCount = 1;
deviceCreateInfo.pQueueCreateInfos = queueCreateInfos.data();
deviceCreateInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size());
deviceCreateInfo.enabledLayerCount = 0;
if (validationLayersEnabled)
{
deviceCreateInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
deviceCreateInfo.ppEnabledLayerNames = validationLayers.data();
}
//create vulkan device
//todo: for some reason this is creating vkCreateSampler errors here, find out why because we are not calling that function.
//happens on both intel/nv drivers and also happens with lunarg demo, possible lunarg debug layer bug??
result = vkCreateDevice(mPhysicalDevice, &deviceCreateInfo, mAllocCallback, &mDevice);
if (result != VK_SUCCESS)
{
std::printf("vkCreateDevice failed\n");
return false;
}
//grab graphics queue handle
vkGetDeviceQueue(mDevice, mGraphicsQueueIndex, 0, &mGraphicsQueue);
if (!mGraphicsQueue)
{
std::printf("Failed to retrieve graphics queue\n");
return false;
}
return true;
}
ShaderHandle VulkanGraphicsDevice::createShader(const std::vector<ShaderDetails> &shaders)
{
return InvalidHandle;
}
BufferHandle VulkanGraphicsDevice::createBuffer(BufferType type, BufferUsageHint hint, size_t dataSize, float *data)
{
return InvalidHandle;
}
LayoutHandle VulkanGraphicsDevice::createVertexInputLayout(const std::vector<VertexInputLayout> &attributes)
{
return InvalidHandle;
}
VertexArrayHandle VulkanGraphicsDevice::createVAO(LayoutHandle layout, BufferHandle vertexBuffer, BufferHandle indexBuffer)
{
return InvalidHandle;
}
void VulkanGraphicsDevice::bindConstantBuffer(ShaderHandle shader, BufferHandle cBuffer, int32_t index)
{
}
void VulkanGraphicsDevice::deleteVertexInputLayout(LayoutHandle handle)
{
}
void VulkanGraphicsDevice::deleteVAO(VertexArrayHandle handle)
{
}
void VulkanGraphicsDevice::deleteBuffer(BufferHandle handle)
{
}
void VulkanGraphicsDevice::deleteShader(ShaderHandle handle)
{
}
void VulkanGraphicsDevice::submitCommandQueue(CommandQueue *cmdQueue)
{
}
void VulkanGraphicsDevice::present()
{
}
}<|endoftext|>
|
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "otbImage.h"
#include "otbMeanDifferenceImageFilter.h"
#include "otbCommandProgressUpdate.h"
int otbMeanDiffChangeDetectionTest(int argc, char* argv[] )
{
if ( argc < 5 )
{
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0] << " inputImageFile1 inputImageFile2 radius outputImageFile " << std::endl;
return -1;
}
// Define the dimension of the images
const unsigned int Dimension = 2;
// Declare the types of the images
typedef double InternalPixelType;
typedef double OutputPixelType;
typedef otb::Image<InternalPixelType, Dimension> InputImageType1;
typedef otb::Image<InternalPixelType, Dimension> InputImageType2;
typedef otb::Image<InternalPixelType, Dimension> ChangeImageType;
typedef otb::Image<OutputPixelType, Dimension> OutputImageType;
typedef otb::ImageFileReader< InputImageType1 > ReaderType1;
typedef otb::ImageFileReader< InputImageType2 > ReaderType2;
typedef otb::ImageFileWriter< OutputImageType > WriterType;
typedef itk::RescaleIntensityImageFilter< ChangeImageType,
OutputImageType > RescalerType;
// Declare the type for the filter
typedef otb::MeanDifferenceImageFilter<
InputImageType1,
InputImageType2,
ChangeImageType > FilterType;
ReaderType1::Pointer reader1 = ReaderType1::New();
ReaderType2::Pointer reader2 = ReaderType2::New();
WriterType::Pointer writer = WriterType::New();
FilterType::Pointer filter = FilterType::New();
RescalerType::Pointer rescaler = RescalerType::New();
const char * inputFilename1 = argv[1];
const char * inputFilename2 = argv[2];
const char * outputFilename = argv[4];
reader1->SetFileName( inputFilename1 );
reader2->SetFileName( inputFilename2 );
writer->SetFileName( outputFilename );
rescaler->SetOutputMinimum( 0 );
rescaler->SetOutputMaximum( 255 );
filter->SetInput1( reader1->GetOutput() );
filter->SetInput2( reader2->GetOutput() );
filter->SetRadius( atoi(argv[3]) );
rescaler->SetInput( filter->GetOutput() );
writer->SetInput( rescaler->GetOutput() );
typedef otb::CommandProgressUpdate<FilterType> CommandType;
CommandType::Pointer observer = CommandType::New();
filter->AddObserver(itk::ProgressEvent(), observer);
writer->Update();
return EXIT_SUCCESS;
}
<commit_msg>ENH : revert changes on meandiff test<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "otbImage.h"
#include "otbMeanDifferenceImageFilter.h"
#include "otbCommandProgressUpdate.h"
int otbMeanDiffChangeDetectionTest(int argc, char* argv[] )
{
if ( argc < 5 )
{
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0] << " inputImageFile1 inputImageFile2 radius outputImageFile " << std::endl;
return -1;
}
// Define the dimension of the images
const unsigned int Dimension = 2;
// Declare the types of the images
typedef double InternalPixelType;
typedef double OutputPixelType;
typedef otb::Image<InternalPixelType, Dimension> InputImageType1;
typedef otb::Image<InternalPixelType, Dimension> InputImageType2;
typedef otb::Image<InternalPixelType, Dimension> ChangeImageType;
typedef otb::Image<OutputPixelType, Dimension> OutputImageType;
typedef otb::ImageFileReader< InputImageType1 > ReaderType1;
typedef otb::ImageFileReader< InputImageType2 > ReaderType2;
typedef otb::ImageFileWriter< OutputImageType > WriterType;
typedef itk::RescaleIntensityImageFilter< ChangeImageType,
OutputImageType > RescalerType;
// Declare the type for the filter
typedef otb::MeanDifferenceImageFilter<
InputImageType1,
InputImageType2,
ChangeImageType > FilterType;
ReaderType1::Pointer reader1 = ReaderType1::New();
ReaderType2::Pointer reader2 = ReaderType2::New();
WriterType::Pointer writer = WriterType::New();
FilterType::Pointer filter = FilterType::New();
RescalerType::Pointer rescaler = RescalerType::New();
const char * inputFilename1 = argv[1];
const char * inputFilename2 = argv[2];
const char * outputFilename = argv[4];
reader1->SetFileName( inputFilename1 );
reader2->SetFileName( inputFilename2 );
writer->SetFileName( outputFilename );
rescaler->SetOutputMinimum( -1 );
rescaler->SetOutputMaximum( 1 );
filter->SetInput1( reader1->GetOutput() );
filter->SetInput2( reader2->GetOutput() );
filter->SetRadius( atoi(argv[3]) );
rescaler->SetInput( filter->GetOutput() );
writer->SetInput( rescaler->GetOutput() );
typedef otb::CommandProgressUpdate<FilterType> CommandType;
CommandType::Pointer observer = CommandType::New();
filter->AddObserver(itk::ProgressEvent(), observer);
writer->Update();
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>// SafeArryGUID.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <objbase.h>
#include <string>
#include<atlsafe.h>
#include<iostream>
using namespace std;
string GuidToString(const GUID &guid)
{
char buf[64] = { 0 };
sprintf_s(buf, sizeof(buf), "{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}",
guid.Data1, guid.Data2, guid.Data3,
guid.Data4[0], guid.Data4[1],
guid.Data4[2], guid.Data4[3],
guid.Data4[4], guid.Data4[5],
guid.Data4[6], guid.Data4[7]);
return string(buf);
}
void Put1GuidInSafeArry()
{
GUID guid;
CoCreateGuid(&guid);
auto guidStri = GuidToString(guid);
cout << guidStri << endl;
//TODO... put the guid into safearry..
SAFEARRAY* p_safe_arry;
SAFEARRAYBOUND safe_arry_bound[2] = { 0 };
auto guidsize = sizeof(GUID);
safe_arry_bound[0].cElements = guidsize;
safe_arry_bound[0].lLbound = 0;
safe_arry_bound[1].cElements = guidsize;
safe_arry_bound[1].lLbound = 0;
p_safe_arry = SafeArrayCreate(VT_ARRAY, 1, safe_arry_bound);
auto pnData = reinterpret_cast<char*>(p_safe_arry->pvData);
memcpy_s(pnData, guidsize, guidStri.c_str(), guidsize);
//TODO...
//do something..
SafeArrayDestroy(p_safe_arry);
}
void Put2GuidInSafeArry()
{
GUID guid, guid2;
CoCreateGuid(&guid);
CoCreateGuid(&guid2);
//TODO... put the guid into safearry..
SAFEARRAY* p_safe_arry;
SAFEARRAYBOUND safe_arry_bound[2] = { 0 };
safe_arry_bound[0].cElements = 2;
safe_arry_bound[0].lLbound = 0;
safe_arry_bound[1].cElements = 16;
safe_arry_bound[1].lLbound = 0;
p_safe_arry = SafeArrayCreate(VT_CLSID, 2, safe_arry_bound);
auto pnData = reinterpret_cast<GUID*>(p_safe_arry->pvData);
pnData[0] = guid;
pnData[1] = guid2;
//TODO...
//do something..
//TODO...
SafeArrayDestroy(p_safe_arry);
}
void Put1GuidInSafeArryByStack()
{
GUID guid;
//TODO... put the guid into safearry..
SAFEARRAY* pArray = nullptr;
auto hr = SafeArrayAllocDescriptorEx(VT_CLSID, 1, &pArray);
pArray->cbElements = sizeof(GUID);
pArray->rgsabound[0].cElements = 1;
pArray->rgsabound[0].lLbound = 16;
pArray->pvData = &guid;
pArray->fFeatures = FADF_AUTO;
//_bstr_t bstr;
}
void CComSafeArrayGUID()
{
//CComSafeArray<GUID> comsafeguid(10);
}
void LearnSafeArray()
{
SAFEARRAY *pArray = nullptr;
HRESULT hr = SafeArrayAllocDescriptor(1, &pArray);//SAFEARRAYṹĶ
pArray->cbElements = sizeof(GUID);
pArray->rgsabound[0].cElements = 10;
pArray->rgsabound[0].lLbound = 0;
GUID guid, guid2;
CoCreateGuid(&guid);
CoCreateGuid(&guid2);
GUID _guidarr[] = { guid,guid2 };
pArray->pvData = _guidarr;
pArray->fFeatures = FADF_AUTO | FADF_FIXEDSIZE;
//CComSafeArray<VARIANT> saguid;
// saguid.Attach(pArray);
//auto count = saguid.GetCount();
//auto t = saguid.GetType();
GUID* p_GUIDArry = nullptr;
SafeArrayAccessData(pArray, (PVOID*)&p_GUIDArry);
auto retv = p_GUIDArry[0];
auto retv1 = p_GUIDArry[1];
long Low(0), High(0);
hr = SafeArrayGetLBound(pArray, 1, &Low);//ά1ʼ
hr = SafeArrayGetUBound(pArray, 1, &High);//ά1ʼ
SafeArrayUnaccessData(pArray);
SafeArrayDestroy(pArray);
cin.get();
}
void TestSafeArry()
{
LearnSafeArray();
//CComSafeArrayBound bound(2);
//CComSafeArray<GUID> guid_Array;
//GUID guid, guid2;
//CoCreateGuid(&guid);
//CoCreateGuid(&guid2);
//guid_Array.Add(guid);
//guid_Array.Add(guid2);
//auto count = guid_Array.GetCount();
//auto demention = guid_Array.GetDimensions();
//auto upperbound = guid_Array.GetUpperBound();
//auto p_safeArry = &guid_Array;
//GUID guid3;
//CoCreateGuid(&guid3);
//p_safeArry->SetAt(1, guid3);
}
int _tmain(int argc, _TCHAR* argv[])
{
TestSafeArry();
Put1GuidInSafeArry();
Put2GuidInSafeArry();
Put1GuidInSafeArryByStack();
return 0;
}<commit_msg>update GUID using...<commit_after>// SafeArryGUID.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <objbase.h>
#include <string>
#include<atlsafe.h>
#include<iostream>
using namespace std;
string GuidToString(const GUID &guid)
{
char buf[64] = { 0 };
sprintf_s(buf, sizeof(buf), "{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}",
guid.Data1, guid.Data2, guid.Data3,
guid.Data4[0], guid.Data4[1],
guid.Data4[2], guid.Data4[3],
guid.Data4[4], guid.Data4[5],
guid.Data4[6], guid.Data4[7]);
return string(buf);
}
void Put1GuidInSafeArry()
{
GUID guid;
CoCreateGuid(&guid);
auto guidStri = GuidToString(guid);
cout << guidStri << endl;
//TODO... put the guid into safearry..
SAFEARRAY* p_safe_arry;
SAFEARRAYBOUND safe_arry_bound[2] = { 0 };
auto guidsize = sizeof(GUID);
safe_arry_bound[0].cElements = guidsize;
safe_arry_bound[0].lLbound = 0;
safe_arry_bound[1].cElements = guidsize;
safe_arry_bound[1].lLbound = 0;
p_safe_arry = SafeArrayCreate(VT_ARRAY, 1, safe_arry_bound);
auto pnData = reinterpret_cast<char*>(p_safe_arry->pvData);
memcpy_s(pnData, guidsize, guidStri.c_str(), guidsize);
//TODO...
//do something..
SafeArrayDestroy(p_safe_arry);
}
void Put2GuidInSafeArry()
{
GUID guid, guid2;
CoCreateGuid(&guid);
CoCreateGuid(&guid2);
//TODO... put the guid into safearry..
SAFEARRAY* p_safe_arry;
SAFEARRAYBOUND safe_arry_bound[1] = { 0 };
safe_arry_bound[0].cElements = 5;
safe_arry_bound[0].lLbound = 0;
p_safe_arry = SafeArrayCreate(VT_VARIANT, 1, safe_arry_bound);
long Low(0), High(0);
SafeArrayGetLBound(p_safe_arry, 1, &Low);
SafeArrayGetUBound(p_safe_arry, 1, &High);
////p_safe_arry->cbElements = sizeof(GUID);
//long lDimension;
//lDimension = 0;
//SafeArrayPutElement(p_safe_arry, &lDimension, &guid);
//lDimension = 1;
//SafeArrayPutElement(p_safe_arry, &lDimension, &guid2);
////TODO...
//GUID guidout = { 0 };
//SafeArrayGetElement(p_safe_arry, &lDimension, &guidout);
GUID* pData = NULL;
HRESULT hr = SafeArrayAccessData(p_safe_arry, (void**)&pData);
pData[0] = guid;
pData[1] = guid2;
//TODO...
SafeArrayUnaccessData(p_safe_arry);
SafeArrayDestroy(p_safe_arry);
}
void Put1GuidInSafeArryByStack()
{
GUID guid;
//TODO... put the guid into safearry..
SAFEARRAY* pArray = nullptr;
auto hr = SafeArrayAllocDescriptorEx(VT_CLSID, 1, &pArray);
pArray->cbElements = sizeof(GUID);
pArray->rgsabound[0].cElements = 1;
pArray->rgsabound[0].lLbound = 16;
pArray->pvData = &guid;
pArray->fFeatures = FADF_AUTO;
//_bstr_t bstr;
}
void CComSafeArrayGUID()
{
//CComSafeArray<GUID> comsafeguid(10);
}
void LearnSafeArray()
{
SAFEARRAY *pArray = nullptr;
HRESULT hr = SafeArrayAllocDescriptor(1, &pArray);//SAFEARRAYṹĶ
pArray->cbElements = sizeof(GUID);
pArray->rgsabound[0].cElements = 10;
pArray->rgsabound[0].lLbound = 0;
GUID guid, guid2;
CoCreateGuid(&guid);
CoCreateGuid(&guid2);
GUID _guidarr[] = { guid,guid2 };
pArray->pvData = _guidarr;
pArray->fFeatures = FADF_AUTO | FADF_FIXEDSIZE;
//CComSafeArray<VARIANT> saguid;
// saguid.Attach(pArray);
//auto count = saguid.GetCount();
//auto t = saguid.GetType();
GUID* p_GUIDArry = nullptr;
SafeArrayAccessData(pArray, (PVOID*)&p_GUIDArry);
auto retv = p_GUIDArry[0];
auto retv1 = p_GUIDArry[1];
long Low(0), High(0);
hr = SafeArrayGetLBound(pArray, 1, &Low);//ά1ʼ
hr = SafeArrayGetUBound(pArray, 1, &High);//ά1ʼ
SafeArrayUnaccessData(pArray);
SafeArrayDestroy(pArray);
// cin.get();
}
void TestSafeArry()
{
LearnSafeArray();
//CComSafeArrayBound bound(2);
//CComSafeArray<GUID> guid_Array;
//GUID guid, guid2;
//CoCreateGuid(&guid);
//CoCreateGuid(&guid2);
//guid_Array.Add(guid);
//guid_Array.Add(guid2);
//auto count = guid_Array.GetCount();
//auto demention = guid_Array.GetDimensions();
//auto upperbound = guid_Array.GetUpperBound();
//auto p_safeArry = &guid_Array;
//GUID guid3;
//CoCreateGuid(&guid3);
//p_safeArry->SetAt(1, guid3);
}
int _tmain(int argc, _TCHAR* argv[])
{
TestSafeArry();
//Put1GuidInSafeArry();
Put2GuidInSafeArry();
Put1GuidInSafeArryByStack();
return 0;
}<|endoftext|>
|
<commit_before>// SafeArryGUID.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <objbase.h>
#include <string>
#include<atlsafe.h>
#include<iostream>
using namespace std;
string GuidToString(const GUID &guid)
{
char buf[64] = { 0 };
sprintf_s(buf, sizeof(buf), "{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}",
guid.Data1, guid.Data2, guid.Data3,
guid.Data4[0], guid.Data4[1],
guid.Data4[2], guid.Data4[3],
guid.Data4[4], guid.Data4[5],
guid.Data4[6], guid.Data4[7]);
return string(buf);
}
void Put1GuidInSafeArry()
{
GUID guid;
CoCreateGuid(&guid);
auto guidStri = GuidToString(guid);
cout << guidStri << endl;
//TODO... put the guid into safearry..
SAFEARRAY* p_safe_arry;
SAFEARRAYBOUND safe_arry_bound[2] = { 0 };
auto guidsize = sizeof(GUID);
safe_arry_bound[0].cElements = guidsize;
safe_arry_bound[0].lLbound = 0;
safe_arry_bound[1].cElements = guidsize;
safe_arry_bound[1].lLbound = 0;
p_safe_arry = SafeArrayCreate(VT_ARRAY, 1, safe_arry_bound);
auto pnData = reinterpret_cast<char*>(p_safe_arry->pvData);
memcpy_s(pnData, guidsize, guidStri.c_str(), guidsize);
//TODO...
//do something..
SafeArrayDestroy(p_safe_arry);
}
void Put2GuidInSafeArry()
{
GUID guid, guid2;
CoCreateGuid(&guid);
CoCreateGuid(&guid2);
//TODO... put the guid into safearry..
SAFEARRAY* p_safe_arry;
SAFEARRAYBOUND safe_arry_bound[2] = { 0 };
safe_arry_bound[0].cElements = 2;
safe_arry_bound[0].lLbound = 0;
safe_arry_bound[1].cElements = 16;
safe_arry_bound[1].lLbound = 0;
p_safe_arry = SafeArrayCreate(VT_CLSID, 2, safe_arry_bound);
auto pnData = reinterpret_cast<GUID*>(p_safe_arry->pvData);
pnData[0] = guid;
pnData[1] = guid2;
//TODO...
//do something..
//TODO...
SafeArrayDestroy(p_safe_arry);
}
void Put1GuidInSafeArryByStack()
{
GUID guid;
//TODO... put the guid into safearry..
SAFEARRAY* pArray = nullptr;
auto hr = SafeArrayAllocDescriptorEx(VT_CLSID, 1, &pArray);
pArray->cbElements = sizeof(GUID);
pArray->rgsabound[0].cElements = 1;
pArray->rgsabound[0].lLbound = 16;
pArray->pvData = &guid;
pArray->fFeatures = FADF_AUTO;
//_bstr_t bstr;
}
void CComSafeArrayGUID()
{
//CComSafeArray<GUID> comsafeguid(10);
}
void LearnSafeArray()
{
VARIANT var_Chunk;
SAFEARRAY *psa;
SAFEARRAYBOUND rgsabund[1];
rgsabund[0].cElements = sizeof(GUID);
rgsabund[0].lLbound = 0;
//psa = SafeArrayCreate(VT_UI1,1,rgsabund);
var_Chunk.vt = VT_RECORD | VT_ARRAY;
//var_Chunk.parray =
}
int _tmain(int argc, _TCHAR* argv[])
{
Put1GuidInSafeArry();
Put1GuidInSafeArry();
Put1GuidInSafeArryByStack();
return 0;
}<commit_msg>update<commit_after>// SafeArryGUID.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <objbase.h>
#include <string>
#include<atlsafe.h>
#include<iostream>
using namespace std;
string GuidToString(const GUID &guid)
{
char buf[64] = { 0 };
sprintf_s(buf, sizeof(buf), "{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}",
guid.Data1, guid.Data2, guid.Data3,
guid.Data4[0], guid.Data4[1],
guid.Data4[2], guid.Data4[3],
guid.Data4[4], guid.Data4[5],
guid.Data4[6], guid.Data4[7]);
return string(buf);
}
void Put1GuidInSafeArry()
{
GUID guid;
CoCreateGuid(&guid);
auto guidStri = GuidToString(guid);
cout << guidStri << endl;
//TODO... put the guid into safearry..
SAFEARRAY* p_safe_arry;
SAFEARRAYBOUND safe_arry_bound[2] = { 0 };
auto guidsize = sizeof(GUID);
safe_arry_bound[0].cElements = guidsize;
safe_arry_bound[0].lLbound = 0;
safe_arry_bound[1].cElements = guidsize;
safe_arry_bound[1].lLbound = 0;
p_safe_arry = SafeArrayCreate(VT_ARRAY, 1, safe_arry_bound);
auto pnData = reinterpret_cast<char*>(p_safe_arry->pvData);
memcpy_s(pnData, guidsize, guidStri.c_str(), guidsize);
//TODO...
//do something..
SafeArrayDestroy(p_safe_arry);
}
void Put2GuidInSafeArry()
{
GUID guid, guid2;
CoCreateGuid(&guid);
CoCreateGuid(&guid2);
//TODO... put the guid into safearry..
SAFEARRAY* p_safe_arry;
SAFEARRAYBOUND safe_arry_bound[2] = { 0 };
safe_arry_bound[0].cElements = 2;
safe_arry_bound[0].lLbound = 0;
safe_arry_bound[1].cElements = 16;
safe_arry_bound[1].lLbound = 0;
p_safe_arry = SafeArrayCreate(VT_CLSID, 2, safe_arry_bound);
auto pnData = reinterpret_cast<GUID*>(p_safe_arry->pvData);
pnData[0] = guid;
pnData[1] = guid2;
//TODO...
//do something..
//TODO...
SafeArrayDestroy(p_safe_arry);
}
void Put1GuidInSafeArryByStack()
{
GUID guid;
//TODO... put the guid into safearry..
SAFEARRAY* pArray = nullptr;
auto hr = SafeArrayAllocDescriptorEx(VT_CLSID, 1, &pArray);
pArray->cbElements = sizeof(GUID);
pArray->rgsabound[0].cElements = 1;
pArray->rgsabound[0].lLbound = 16;
pArray->pvData = &guid;
pArray->fFeatures = FADF_AUTO;
//_bstr_t bstr;
}
void CComSafeArrayGUID()
{
//CComSafeArray<GUID> comsafeguid(10);
}
void LearnSafeArray()
{
VARIANT var_Chunk;
SAFEARRAY *psa;
SAFEARRAYBOUND rgsabund[1];
rgsabund[0].cElements = sizeof(GUID);
rgsabund[0].lLbound = 0;
//psa = SafeArrayCreate(VT_UI1,1,rgsabund);
var_Chunk.vt = VT_RECORD | VT_ARRAY;
//var_Chunk.parray =
}
int _tmain(int argc, _TCHAR* argv[])
{
Put1GuidInSafeArry();
Put2GuidInSafeArry();
Put1GuidInSafeArryByStack();
return 0;
}<|endoftext|>
|
<commit_before>/*****************************************************************************
* Controller.hpp : Controller for the main interface
****************************************************************************
* Copyright (C) 2006-2008 the VideoLAN team
* $Id$
*
* Authors: Jean-Baptiste Kempf <jb@videolan.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifndef QVLC_CONTROLLER_H_
#define QVLC_CONTROLLER_H_
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "qt4.hpp"
#include <QFrame>
#include <QString>
#include <QSizeGrip>
#define MAIN_TB1_DEFAULT "64;39;64;38;65"
#define MAIN_TB2_DEFAULT "0-2;64;3;1;4;64;7;9;64;10;20;19;64-4;37;65;35-4"
#define ADV_TB_DEFAULT "12;11;13;14"
#define INPT_TB_DEFAULT "5-1;15-1;33;6-1"
#define FSC_TB_DEFAULT "0-2;64;3;1;4;64;37;64;38;64;8;65;35-4;34"
#define I_PLAY_TOOLTIP N_("Play\nIf the playlist is empty, open a medium")
class QPixmap;
class QLabel;
class QGridLayout;
class QHBoxLayout;
class QBoxLayout;
class QAbstractSlider;
class QAbstractButton;
class SeekSlider;
class QToolButton;
class VolumeClickHandler;
class WidgetListing;
class QSignalMapper;
class QTimer;
typedef enum buttonType_e
{
PLAY_BUTTON,
STOP_BUTTON,
OPEN_BUTTON,
PREV_SLOW_BUTTON,
NEXT_FAST_BUTTON,
SLOWER_BUTTON,
FASTER_BUTTON,
FULLSCREEN_BUTTON,
DEFULLSCREEN_BUTTON,
EXTENDED_BUTTON,
PLAYLIST_BUTTON,
SNAPSHOT_BUTTON,
RECORD_BUTTON,
ATOB_BUTTON,
FRAME_BUTTON,
REVERSE_BUTTON,
SKIP_BACK_BUTTON,
SKIP_FW_BUTTON,
QUIT_BUTTON,
RANDOM_BUTTON,
LOOP_BUTTON,
INFO_BUTTON,
PREVIOUS_BUTTON,
NEXT_BUTTON,
OPEN_SUB_BUTTON,
BUTTON_MAX,
SPLITTER = 0x20,
INPUT_SLIDER,
TIME_LABEL,
VOLUME,
VOLUME_SPECIAL,
MENU_BUTTONS,
TELETEXT_BUTTONS,
ADVANCED_CONTROLLER,
PLAYBACK_BUTTONS,
SPECIAL_MAX,
WIDGET_SPACER = 0x40,
WIDGET_SPACER_EXTEND,
WIDGET_MAX,
} buttonType_e;
static const char* const nameL[BUTTON_MAX] = { N_("Play"), N_("Stop"), N_("Open"),
N_("Previous/Backward"), N_("Next/Forward"), N_("Slower"), N_("Faster"), N_("Fullscreen"),
N_("De-Fullscreen"), N_("Extended panel"), N_("Playlist"), N_("Snapshot"),
N_("Record"), N_("A->B Loop"), N_("Frame By Frame"), N_("Trickplay Reverse"),
N_("Step backward" ), N_("Step forward"), N_("Quit"), N_("Random"),
N_("Loop/Repeat mode"), N_("Information"), N_("Previous"), N_("Next"),
N_("Open subtitles file")};
static const char* const tooltipL[BUTTON_MAX] = { I_PLAY_TOOLTIP,
N_("Stop playback"), N_("Open a medium"),
N_("Previous media in the playlist, skip backward when keep-pressed"),
N_("Next media in the playlist, skip forward when keep-pressed"), N_("Slower"), N_("Faster"),
N_("Toggle the video in fullscreen"), N_("Toggle the video out fullscreen"),
N_("Show extended settings" ), N_( "Show playlist" ),
N_( "Take a snapshot" ), N_( "Record" ),
N_( "Loop from point A to point B continuously." ), N_("Frame by frame"),
N_("Reverse"), N_("Step backward"), N_("Step forward"), N_("Quit"),
N_("Random"), N_("Change the loop and repeat modes"), N_("Information"),
N_("Previous media in the playlist"), N_("Next media in the playlist"),
N_("Open subtitles file")};
static const QString iconL[BUTTON_MAX] ={ ":/toolbar/play_b", ":/toolbar/stop_b",
":/toolbar/eject", ":/toolbar/previous_b", ":/toolbar/next_b",
":/toolbar/slower", ":/toolbar/faster", ":/toolbar/fullscreen",
":/toolbar/defullscreen", ":/toolbar/extended", ":/toolbar/playlist",
":/toolbar/snapshot", ":/toolbar/record", ":/toolbar/atob_nob",
":/toolbar/frame", ":/toolbar/reverse", ":/toolbar/skip_back",
":/toolbar/skip_fw", ":/toolbar/clear", ":/buttons/playlist/shuffle_on",
":/buttons/playlist/repeat_all", ":/menu/info",
":/toolbar/previous_b", ":/toolbar/next_b", "" };
enum
{
WIDGET_NORMAL = 0x0,
WIDGET_FLAT = 0x1,
WIDGET_BIG = 0x2,
WIDGET_SHINY = 0x4,
};
class AdvControlsWidget;
class AbstractController : public QFrame
{
friend class WidgetListing; /* For ToolBar Edition HACKS */
Q_OBJECT
public:
AbstractController( intf_thread_t *_p_i, QWidget *_parent = 0 );
protected:
intf_thread_t *p_intf;
QSignalMapper *toolbarActionsMapper;
QHBoxLayout *controlLayout;
/* Change to BoxLayout if both dir are needed */
AdvControlsWidget *advControls;
void parseAndCreate( const QString& config, QBoxLayout *controlLayout );
virtual void createAndAddWidget( QBoxLayout *controlLayout, int i_index,
buttonType_e i_type, int i_option );
QWidget *createWidget( buttonType_e, int options = WIDGET_NORMAL );
private:
static void setupButton( QAbstractButton * );
QFrame *discFrame();
QFrame *telexFrame();
void applyAttributes( QToolButton *, bool b_flat, bool b_big );
QHBoxLayout *buttonGroupLayout;
protected slots:
virtual void setStatus( int );
signals:
void inputExists( bool ); /// This might be useful in the IM ?
void inputPlaying( bool ); /// This might be useful in the IM ?
void inputIsRecordable( bool ); /// same ?
void inputIsTrickPlayable( bool ); /// same ?
};
/* Advanced Button Bar */
class AdvControlsWidget : public AbstractController
{
Q_OBJECT
public:
AdvControlsWidget( intf_thread_t *, QWidget *_parent = 0 );
};
/* Slider Bar */
class InputControlsWidget : public AbstractController
{
Q_OBJECT
public:
InputControlsWidget( intf_thread_t * , QWidget *_parent = 0 );
};
/* Button Bar */
class ControlsWidget : public AbstractController
{
Q_OBJECT
public:
/* p_intf, advanced control visible or not, blingbling or not */
ControlsWidget( intf_thread_t *_p_i, bool b_advControls,
QWidget *_parent = 0 );
void setGripVisible( bool b_visible )
{ grip->setVisible( b_visible ); }
protected:
friend class MainInterface;
bool b_advancedVisible;
private:
QSizeGrip *grip;
protected slots:
void toggleAdvanced();
signals:
void advancedControlsToggled( bool );
};
/* to trying transparency with fullscreen controller on windows enable that */
/* it can be enabled on-non windows systems,
but it will be transparent only with composite manager */
#define HAVE_TRANSPARENCY 1
/* Default value of opacity for FS controller */
#define DEFAULT_OPACITY 0.70
/***********************************
* Fullscreen controller
***********************************/
class FullscreenControllerWidget : public AbstractController
{
Q_OBJECT
public:
FullscreenControllerWidget( intf_thread_t *, QWidget *_parent = 0 );
virtual ~FullscreenControllerWidget();
/* Vout */
void fullscreenChanged( vout_thread_t *, bool b_fs, int i_timeout );
void mouseChanged( vout_thread_t *, int i_mousex, int i_mousey );
signals:
void keyPressed( QKeyEvent * );
public slots:
void setVoutList( vout_thread_t **, int );
protected:
friend class MainInterface;
virtual void mouseMoveEvent( QMouseEvent *event );
virtual void mousePressEvent( QMouseEvent *event );
virtual void mouseReleaseEvent( QMouseEvent *event );
virtual void enterEvent( QEvent *event );
virtual void leaveEvent( QEvent *event );
virtual void keyPressEvent( QKeyEvent *event );
private slots:
void showFSC();
void planHideFSC();
void hideFSC() { hide(); }
void slowHideFSC();
void centerFSC( int );
private:
virtual void customEvent( QEvent *event );
QTimer *p_hideTimer;
#if HAVE_TRANSPARENCY
QTimer *p_slowHideTimer;
bool b_slow_hide_begin;
int i_slow_hide_timeout;
float f_opacity;
#endif
int i_mouse_last_x, i_mouse_last_y;
bool b_mouse_over;
int i_screennumber;
QRect screenRes;
/* List of vouts currently tracked */
QList<vout_thread_t *> vout;
/* Shared variable between FSC and VLC (protected by a lock) */
vlc_mutex_t lock;
bool b_fullscreen;
int i_hide_timeout; /* FSC hiding timeout, same as mouse hiding timeout */
int i_mouse_last_move_x;
int i_mouse_last_move_y;
};
#endif
<commit_msg>Qt: Fix protectedness of customEvent<commit_after>/*****************************************************************************
* Controller.hpp : Controller for the main interface
****************************************************************************
* Copyright (C) 2006-2008 the VideoLAN team
* $Id$
*
* Authors: Jean-Baptiste Kempf <jb@videolan.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifndef QVLC_CONTROLLER_H_
#define QVLC_CONTROLLER_H_
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "qt4.hpp"
#include <QFrame>
#include <QString>
#include <QSizeGrip>
#define MAIN_TB1_DEFAULT "64;39;64;38;65"
#define MAIN_TB2_DEFAULT "0-2;64;3;1;4;64;7;9;64;10;20;19;64-4;37;65;35-4"
#define ADV_TB_DEFAULT "12;11;13;14"
#define INPT_TB_DEFAULT "5-1;15-1;33;6-1"
#define FSC_TB_DEFAULT "0-2;64;3;1;4;64;37;64;38;64;8;65;35-4;34"
#define I_PLAY_TOOLTIP N_("Play\nIf the playlist is empty, open a medium")
class QPixmap;
class QLabel;
class QGridLayout;
class QHBoxLayout;
class QBoxLayout;
class QAbstractSlider;
class QAbstractButton;
class SeekSlider;
class QToolButton;
class VolumeClickHandler;
class WidgetListing;
class QSignalMapper;
class QTimer;
typedef enum buttonType_e
{
PLAY_BUTTON,
STOP_BUTTON,
OPEN_BUTTON,
PREV_SLOW_BUTTON,
NEXT_FAST_BUTTON,
SLOWER_BUTTON,
FASTER_BUTTON,
FULLSCREEN_BUTTON,
DEFULLSCREEN_BUTTON,
EXTENDED_BUTTON,
PLAYLIST_BUTTON,
SNAPSHOT_BUTTON,
RECORD_BUTTON,
ATOB_BUTTON,
FRAME_BUTTON,
REVERSE_BUTTON,
SKIP_BACK_BUTTON,
SKIP_FW_BUTTON,
QUIT_BUTTON,
RANDOM_BUTTON,
LOOP_BUTTON,
INFO_BUTTON,
PREVIOUS_BUTTON,
NEXT_BUTTON,
OPEN_SUB_BUTTON,
BUTTON_MAX,
SPLITTER = 0x20,
INPUT_SLIDER,
TIME_LABEL,
VOLUME,
VOLUME_SPECIAL,
MENU_BUTTONS,
TELETEXT_BUTTONS,
ADVANCED_CONTROLLER,
PLAYBACK_BUTTONS,
SPECIAL_MAX,
WIDGET_SPACER = 0x40,
WIDGET_SPACER_EXTEND,
WIDGET_MAX,
} buttonType_e;
static const char* const nameL[BUTTON_MAX] = { N_("Play"), N_("Stop"), N_("Open"),
N_("Previous/Backward"), N_("Next/Forward"), N_("Slower"), N_("Faster"), N_("Fullscreen"),
N_("De-Fullscreen"), N_("Extended panel"), N_("Playlist"), N_("Snapshot"),
N_("Record"), N_("A->B Loop"), N_("Frame By Frame"), N_("Trickplay Reverse"),
N_("Step backward" ), N_("Step forward"), N_("Quit"), N_("Random"),
N_("Loop/Repeat mode"), N_("Information"), N_("Previous"), N_("Next"),
N_("Open subtitles file")};
static const char* const tooltipL[BUTTON_MAX] = { I_PLAY_TOOLTIP,
N_("Stop playback"), N_("Open a medium"),
N_("Previous media in the playlist, skip backward when keep-pressed"),
N_("Next media in the playlist, skip forward when keep-pressed"), N_("Slower"), N_("Faster"),
N_("Toggle the video in fullscreen"), N_("Toggle the video out fullscreen"),
N_("Show extended settings" ), N_( "Show playlist" ),
N_( "Take a snapshot" ), N_( "Record" ),
N_( "Loop from point A to point B continuously." ), N_("Frame by frame"),
N_("Reverse"), N_("Step backward"), N_("Step forward"), N_("Quit"),
N_("Random"), N_("Change the loop and repeat modes"), N_("Information"),
N_("Previous media in the playlist"), N_("Next media in the playlist"),
N_("Open subtitles file")};
static const QString iconL[BUTTON_MAX] ={ ":/toolbar/play_b", ":/toolbar/stop_b",
":/toolbar/eject", ":/toolbar/previous_b", ":/toolbar/next_b",
":/toolbar/slower", ":/toolbar/faster", ":/toolbar/fullscreen",
":/toolbar/defullscreen", ":/toolbar/extended", ":/toolbar/playlist",
":/toolbar/snapshot", ":/toolbar/record", ":/toolbar/atob_nob",
":/toolbar/frame", ":/toolbar/reverse", ":/toolbar/skip_back",
":/toolbar/skip_fw", ":/toolbar/clear", ":/buttons/playlist/shuffle_on",
":/buttons/playlist/repeat_all", ":/menu/info",
":/toolbar/previous_b", ":/toolbar/next_b", "" };
enum
{
WIDGET_NORMAL = 0x0,
WIDGET_FLAT = 0x1,
WIDGET_BIG = 0x2,
WIDGET_SHINY = 0x4,
};
class AdvControlsWidget;
class AbstractController : public QFrame
{
friend class WidgetListing; /* For ToolBar Edition HACKS */
Q_OBJECT
public:
AbstractController( intf_thread_t *_p_i, QWidget *_parent = 0 );
protected:
intf_thread_t *p_intf;
QSignalMapper *toolbarActionsMapper;
QHBoxLayout *controlLayout;
/* Change to BoxLayout if both dir are needed */
AdvControlsWidget *advControls;
void parseAndCreate( const QString& config, QBoxLayout *controlLayout );
virtual void createAndAddWidget( QBoxLayout *controlLayout, int i_index,
buttonType_e i_type, int i_option );
QWidget *createWidget( buttonType_e, int options = WIDGET_NORMAL );
private:
static void setupButton( QAbstractButton * );
QFrame *discFrame();
QFrame *telexFrame();
void applyAttributes( QToolButton *, bool b_flat, bool b_big );
QHBoxLayout *buttonGroupLayout;
protected slots:
virtual void setStatus( int );
signals:
void inputExists( bool ); /// This might be useful in the IM ?
void inputPlaying( bool ); /// This might be useful in the IM ?
void inputIsRecordable( bool ); /// same ?
void inputIsTrickPlayable( bool ); /// same ?
};
/* Advanced Button Bar */
class AdvControlsWidget : public AbstractController
{
Q_OBJECT
public:
AdvControlsWidget( intf_thread_t *, QWidget *_parent = 0 );
};
/* Slider Bar */
class InputControlsWidget : public AbstractController
{
Q_OBJECT
public:
InputControlsWidget( intf_thread_t * , QWidget *_parent = 0 );
};
/* Button Bar */
class ControlsWidget : public AbstractController
{
Q_OBJECT
public:
/* p_intf, advanced control visible or not, blingbling or not */
ControlsWidget( intf_thread_t *_p_i, bool b_advControls,
QWidget *_parent = 0 );
void setGripVisible( bool b_visible )
{ grip->setVisible( b_visible ); }
protected:
friend class MainInterface;
bool b_advancedVisible;
private:
QSizeGrip *grip;
protected slots:
void toggleAdvanced();
signals:
void advancedControlsToggled( bool );
};
/* to trying transparency with fullscreen controller on windows enable that */
/* it can be enabled on-non windows systems,
but it will be transparent only with composite manager */
#define HAVE_TRANSPARENCY 1
/* Default value of opacity for FS controller */
#define DEFAULT_OPACITY 0.70
/***********************************
* Fullscreen controller
***********************************/
class FullscreenControllerWidget : public AbstractController
{
Q_OBJECT
public:
FullscreenControllerWidget( intf_thread_t *, QWidget *_parent = 0 );
virtual ~FullscreenControllerWidget();
/* Vout */
void fullscreenChanged( vout_thread_t *, bool b_fs, int i_timeout );
void mouseChanged( vout_thread_t *, int i_mousex, int i_mousey );
signals:
void keyPressed( QKeyEvent * );
public slots:
void setVoutList( vout_thread_t **, int );
protected:
friend class MainInterface;
virtual void mouseMoveEvent( QMouseEvent *event );
virtual void mousePressEvent( QMouseEvent *event );
virtual void mouseReleaseEvent( QMouseEvent *event );
virtual void enterEvent( QEvent *event );
virtual void leaveEvent( QEvent *event );
virtual void keyPressEvent( QKeyEvent *event );
virtual void customEvent( QEvent *event );
private slots:
void showFSC();
void planHideFSC();
void hideFSC() { hide(); }
void slowHideFSC();
void centerFSC( int );
private:
QTimer *p_hideTimer;
#if HAVE_TRANSPARENCY
QTimer *p_slowHideTimer;
bool b_slow_hide_begin;
int i_slow_hide_timeout;
float f_opacity;
#endif
int i_mouse_last_x, i_mouse_last_y;
bool b_mouse_over;
int i_screennumber;
QRect screenRes;
/* List of vouts currently tracked */
QList<vout_thread_t *> vout;
/* Shared variable between FSC and VLC (protected by a lock) */
vlc_mutex_t lock;
bool b_fullscreen;
int i_hide_timeout; /* FSC hiding timeout, same as mouse hiding timeout */
int i_mouse_last_move_x;
int i_mouse_last_move_y;
};
#endif
<|endoftext|>
|
<commit_before>/*****************************************************************************
* ctrl_text.cpp
*****************************************************************************
* Copyright (C) 2003 VideoLAN
* $Id$
*
* Authors: Cyril Deguet <asmax@via.ecp.fr>
* Olivier Teulire <ipkiss@via.ecp.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA.
*****************************************************************************/
#include "ctrl_text.hpp"
#include "../events/evt_generic.hpp"
#include "../events/evt_mouse.hpp"
#include "../src/generic_bitmap.hpp"
#include "../src/generic_font.hpp"
#include "../src/os_factory.hpp"
#include "../src/os_graphics.hpp"
#include "../src/os_timer.hpp"
#include "../utils/position.hpp"
#include "../utils/ustring.hpp"
#include "../utils/var_text.hpp"
#define MOVING_TEXT_STEP 3
#define MOVING_TEXT_DELAY 200
#define SEPARATOR_STRING " "
CtrlText::CtrlText( intf_thread_t *pIntf, VarText &rVariable,
const GenericFont &rFont, const UString &rHelp,
uint32_t color, VarBool *pVisible ):
CtrlGeneric( pIntf, rHelp, pVisible ), m_fsm( pIntf ),
m_rVariable( rVariable ), m_cmdToManual( this, &transToManual ),
m_cmdManualMoving( this, &transManualMoving ),
m_cmdManualStill( this, &transManualStill ),
m_cmdMove( this, &transMove ),
m_pEvt( NULL ), m_rFont( rFont ), m_color( color ),
m_pImg( NULL ), m_pImgDouble( NULL ), m_pCurrImg( NULL ),
m_xPos( 0 ), m_xOffset( 0 )
{
m_pTimer = OSFactory::instance( getIntf() )->createOSTimer(
Callback( this, &updateText ) );
// States
m_fsm.addState( "still" );
m_fsm.addState( "moving" );
m_fsm.addState( "manual1" );
m_fsm.addState( "manual2" );
m_fsm.addState( "outStill" );
m_fsm.addState( "outMoving" );
// Transitions
m_fsm.addTransition( "still", "mouse:left:down", "manual1",
&m_cmdToManual );
m_fsm.addTransition( "manual1", "mouse:left:up", "moving",
&m_cmdManualMoving );
m_fsm.addTransition( "moving", "mouse:left:down", "manual2",
&m_cmdToManual );
m_fsm.addTransition( "manual2", "mouse:left:up", "still",
&m_cmdManualStill );
m_fsm.addTransition( "manual1", "motion", "manual1", &m_cmdMove );
m_fsm.addTransition( "manual2", "motion", "manual2", &m_cmdMove );
m_fsm.addTransition( "still", "leave", "outStill" );
m_fsm.addTransition( "outStill", "enter", "still" );
m_fsm.addTransition( "moving", "leave", "outMoving" );
m_fsm.addTransition( "outMoving", "enter", "moving" );
// Initial state
m_fsm.setState( "outStill" );
// Observe the variable
m_rVariable.addObserver( this );
// Set the text
displayText( m_rVariable.get() );
}
CtrlText::~CtrlText()
{
m_rVariable.delObserver( this );
if( m_pTimer )
{
delete m_pTimer;
}
if( m_pImg )
{
delete m_pImg;
}
if( m_pImgDouble )
{
delete m_pImgDouble;
}
}
void CtrlText::handleEvent( EvtGeneric &rEvent )
{
// Save the event to use it in callbacks
m_pEvt = &rEvent;
m_fsm.handleTransition( rEvent.getAsString() );
}
bool CtrlText::mouseOver( int x, int y ) const
{
if( m_pCurrImg )
{
// We have 3 different ways of deciding when to return true here:
// 1) the mouse is exactly over the text (so if you click between two
// letters, the text control doesn't catch the event)
// 2) the mouse is over the rectangle of the control
// 3) the mouse is over the rectangle of the visible text
// I don't know which one is the best...
#if 0
return( x >= 0 && x < getPosition()->getWidth()
&& m_pCurrImg->hit( x - m_xPos, y ) );
#endif
#if 1
return( x >= 0 && x < getPosition()->getWidth()
&& y >= 0 && y < getPosition()->getHeight() );
#endif
#if 0
return( x >= 0 && x < getPosition()->getWidth()
&& y >= 0 && y < getPosition()->getHeight()
&& x < m_pCurrImg->getWidth() && x < m_pCurrImg->getHeight() );
#endif
}
else
{
return false;
}
}
void CtrlText::draw( OSGraphics &rImage, int xDest, int yDest )
{
if( m_pCurrImg )
{
// Compute the dimensions to draw
int width = min( m_pCurrImg->getWidth() + m_xPos,
getPosition()->getWidth() );
int height = min( m_pCurrImg->getHeight(), getPosition()->getHeight() );
// Draw the current image
rImage.drawBitmap( *m_pCurrImg, -m_xPos, 0, xDest, yDest,
width, height );
}
}
void CtrlText::setText( const UString &rText, uint32_t color )
{
// Change the color
if( color != 0xFFFFFFFF )
{
m_color = color;
}
// Change the text
m_rVariable.set( rText );
}
void CtrlText::onUpdate( Subject<VarText> &rVariable )
{
displayText( m_rVariable.get() );
}
void CtrlText::displayText( const UString &rText )
{
// Create the images ('normal' and 'double') from the text
// 'Normal' image
if( m_pImg )
{
delete m_pImg;
}
m_pImg = m_rFont.drawString( rText, m_color );
if( !m_pImg )
{
return;
}
// 'Double' image
const UString doubleStringWithSep = rText + SEPARATOR_STRING + rText;
if( m_pImgDouble )
{
delete m_pImgDouble;
}
m_pImgDouble = m_rFont.drawString( doubleStringWithSep, m_color );
// Update the current image used, as if the control size had changed
onChangePosition();
notifyLayout();
}
void CtrlText::onChangePosition()
{
if( m_pImg && getPosition() )
{
if( m_pImg->getWidth() < getPosition()->getWidth() )
{
m_pCurrImg = m_pImg;
}
else
{
m_pCurrImg = m_pImgDouble;
}
}
else
{
// m_pImg is a better default value than m_pImgDouble, but anyway we
// don't care because the control is never drawn without position :)
m_pCurrImg = m_pImg;
}
}
void CtrlText::transToManual( SkinObject *pCtrl )
{
CtrlText *pThis = (CtrlText*)pCtrl;
EvtMouse *pEvtMouse = (EvtMouse*)pThis->m_pEvt;
// Compute the offset
pThis->m_xOffset = pEvtMouse->getXPos() - pThis->m_xPos;
pThis->m_pTimer->stop();
pThis->captureMouse();
}
void CtrlText::transManualMoving( SkinObject *pCtrl )
{
CtrlText *pThis = (CtrlText*)pCtrl;
pThis->releaseMouse();
// Start the automatic movement, but only if the text is wider than the
// control
if( pThis->m_pImg &&
pThis->m_pImg->getWidth() >= pThis->getPosition()->getWidth() )
{
// The current image may have been set incorrectly in displayText(), so
// set the correct value
pThis->m_pCurrImg = pThis->m_pImgDouble;
pThis->m_pTimer->start( MOVING_TEXT_DELAY, false );
}
}
void CtrlText::transManualStill( SkinObject *pCtrl )
{
CtrlText *pThis = (CtrlText*)pCtrl;
pThis->releaseMouse();
}
void CtrlText::transMove( SkinObject *pCtrl )
{
CtrlText *pThis = (CtrlText*)pCtrl;
EvtMouse *pEvtMouse = (EvtMouse*)pThis->m_pEvt;
// Do nothing if the text fits in the control
if( pThis->m_pImg &&
pThis->m_pImg->getWidth() >= pThis->getPosition()->getWidth() )
{
// The current image may have been set incorrectly in displayText(), so
// we set the correct value
pThis->m_pCurrImg = pThis->m_pImgDouble;
// Compute the new position of the left side, and make sure it is
// in the correct range
pThis->m_xPos = (pEvtMouse->getXPos() - pThis->m_xOffset);
pThis->adjust( pThis->m_xPos );
pThis->notifyLayout();
}
}
void CtrlText::updateText( SkinObject *pCtrl )
{
CtrlText *pThis = (CtrlText*)pCtrl;
pThis->m_xPos -= MOVING_TEXT_STEP;
pThis->adjust( pThis->m_xPos );
pThis->notifyLayout();
}
void CtrlText::adjust( int &position )
{
// {m_pImgDouble->getWidth() - m_pImg->getWidth()} is the period of the
// bitmap; remember that the string used to generate m_pImgDouble is of the
// form: "foo foo", the number of spaces being a parameter
if( !m_pImg )
{
return;
}
position %= m_pImgDouble->getWidth() - m_pImg->getWidth();
if( position > 0 )
{
position -= m_pImgDouble->getWidth() - m_pImg->getWidth();
}
}
<commit_msg> * ctrl_text.cpp: check if the scrolling is still necessary when the text is updated (avoid many crashes)<commit_after>/*****************************************************************************
* ctrl_text.cpp
*****************************************************************************
* Copyright (C) 2003 VideoLAN
* $Id$
*
* Authors: Cyril Deguet <asmax@via.ecp.fr>
* Olivier Teulire <ipkiss@via.ecp.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA.
*****************************************************************************/
#include "ctrl_text.hpp"
#include "../events/evt_generic.hpp"
#include "../events/evt_mouse.hpp"
#include "../src/generic_bitmap.hpp"
#include "../src/generic_font.hpp"
#include "../src/os_factory.hpp"
#include "../src/os_graphics.hpp"
#include "../src/os_timer.hpp"
#include "../utils/position.hpp"
#include "../utils/ustring.hpp"
#include "../utils/var_text.hpp"
#define MOVING_TEXT_STEP 3
#define MOVING_TEXT_DELAY 200
#define SEPARATOR_STRING " "
CtrlText::CtrlText( intf_thread_t *pIntf, VarText &rVariable,
const GenericFont &rFont, const UString &rHelp,
uint32_t color, VarBool *pVisible ):
CtrlGeneric( pIntf, rHelp, pVisible ), m_fsm( pIntf ),
m_rVariable( rVariable ), m_cmdToManual( this, &transToManual ),
m_cmdManualMoving( this, &transManualMoving ),
m_cmdManualStill( this, &transManualStill ),
m_cmdMove( this, &transMove ),
m_pEvt( NULL ), m_rFont( rFont ), m_color( color ),
m_pImg( NULL ), m_pImgDouble( NULL ), m_pCurrImg( NULL ),
m_xPos( 0 ), m_xOffset( 0 )
{
m_pTimer = OSFactory::instance( getIntf() )->createOSTimer(
Callback( this, &updateText ) );
// States
m_fsm.addState( "still" );
m_fsm.addState( "moving" );
m_fsm.addState( "manual1" );
m_fsm.addState( "manual2" );
m_fsm.addState( "outStill" );
m_fsm.addState( "outMoving" );
// Transitions
m_fsm.addTransition( "still", "mouse:left:down", "manual1",
&m_cmdToManual );
m_fsm.addTransition( "manual1", "mouse:left:up", "moving",
&m_cmdManualMoving );
m_fsm.addTransition( "moving", "mouse:left:down", "manual2",
&m_cmdToManual );
m_fsm.addTransition( "manual2", "mouse:left:up", "still",
&m_cmdManualStill );
m_fsm.addTransition( "manual1", "motion", "manual1", &m_cmdMove );
m_fsm.addTransition( "manual2", "motion", "manual2", &m_cmdMove );
m_fsm.addTransition( "still", "leave", "outStill" );
m_fsm.addTransition( "outStill", "enter", "still" );
m_fsm.addTransition( "moving", "leave", "outMoving" );
m_fsm.addTransition( "outMoving", "enter", "moving" );
// Initial state
m_fsm.setState( "outStill" );
// Observe the variable
m_rVariable.addObserver( this );
// Set the text
displayText( m_rVariable.get() );
}
CtrlText::~CtrlText()
{
m_rVariable.delObserver( this );
if( m_pTimer )
{
delete m_pTimer;
}
if( m_pImg )
{
delete m_pImg;
}
if( m_pImgDouble )
{
delete m_pImgDouble;
}
}
void CtrlText::handleEvent( EvtGeneric &rEvent )
{
// Save the event to use it in callbacks
m_pEvt = &rEvent;
m_fsm.handleTransition( rEvent.getAsString() );
}
bool CtrlText::mouseOver( int x, int y ) const
{
if( m_pCurrImg )
{
// We have 3 different ways of deciding when to return true here:
// 1) the mouse is exactly over the text (so if you click between two
// letters, the text control doesn't catch the event)
// 2) the mouse is over the rectangle of the control
// 3) the mouse is over the rectangle of the visible text
// I don't know which one is the best...
#if 0
return( x >= 0 && x < getPosition()->getWidth()
&& m_pCurrImg->hit( x - m_xPos, y ) );
#endif
#if 1
return( x >= 0 && x < getPosition()->getWidth()
&& y >= 0 && y < getPosition()->getHeight() );
#endif
#if 0
return( x >= 0 && x < getPosition()->getWidth()
&& y >= 0 && y < getPosition()->getHeight()
&& x < m_pCurrImg->getWidth() && x < m_pCurrImg->getHeight() );
#endif
}
else
{
return false;
}
}
void CtrlText::draw( OSGraphics &rImage, int xDest, int yDest )
{
if( m_pCurrImg )
{
// Compute the dimensions to draw
int width = min( m_pCurrImg->getWidth() + m_xPos,
getPosition()->getWidth() );
int height = min( m_pCurrImg->getHeight(), getPosition()->getHeight() );
// Draw the current image
rImage.drawBitmap( *m_pCurrImg, -m_xPos, 0, xDest, yDest,
width, height );
}
}
void CtrlText::setText( const UString &rText, uint32_t color )
{
// Change the color
if( color != 0xFFFFFFFF )
{
m_color = color;
}
// Change the text
m_rVariable.set( rText );
}
void CtrlText::onUpdate( Subject<VarText> &rVariable )
{
displayText( m_rVariable.get() );
}
void CtrlText::displayText( const UString &rText )
{
// Create the images ('normal' and 'double') from the text
// 'Normal' image
if( m_pImg )
{
delete m_pImg;
}
m_pImg = m_rFont.drawString( rText, m_color );
if( !m_pImg )
{
return;
}
// 'Double' image
const UString doubleStringWithSep = rText + SEPARATOR_STRING + rText;
if( m_pImgDouble )
{
delete m_pImgDouble;
}
m_pImgDouble = m_rFont.drawString( doubleStringWithSep, m_color );
// Update the current image used, as if the control size had changed
onChangePosition();
m_xPos = 0;
// If the control was in the moving state, check if the scrolling is
// still necessary
const string &rState = m_fsm.getState();
if( rState == "moving" || rState == "outMoving" )
{
if( m_pImg && m_pImg->getWidth() >= getPosition()->getWidth() )
{
m_pCurrImg = m_pImgDouble;
m_pTimer->start( MOVING_TEXT_DELAY, false );
}
else
{
m_pTimer->stop();
}
}
notifyLayout();
}
void CtrlText::onChangePosition()
{
if( m_pImg && getPosition() )
{
if( m_pImg->getWidth() < getPosition()->getWidth() )
{
m_pCurrImg = m_pImg;
}
else
{
m_pCurrImg = m_pImgDouble;
}
}
else
{
// m_pImg is a better default value than m_pImgDouble, but anyway we
// don't care because the control is never drawn without position :)
m_pCurrImg = m_pImg;
}
}
void CtrlText::transToManual( SkinObject *pCtrl )
{
CtrlText *pThis = (CtrlText*)pCtrl;
EvtMouse *pEvtMouse = (EvtMouse*)pThis->m_pEvt;
// Compute the offset
pThis->m_xOffset = pEvtMouse->getXPos() - pThis->m_xPos;
pThis->m_pTimer->stop();
pThis->captureMouse();
}
void CtrlText::transManualMoving( SkinObject *pCtrl )
{
CtrlText *pThis = (CtrlText*)pCtrl;
pThis->releaseMouse();
// Start the automatic movement, but only if the text is wider than the
// control
if( pThis->m_pImg &&
pThis->m_pImg->getWidth() >= pThis->getPosition()->getWidth() )
{
// The current image may have been set incorrectly in displayText(), so
// set the correct value
pThis->m_pCurrImg = pThis->m_pImgDouble;
pThis->m_pTimer->start( MOVING_TEXT_DELAY, false );
}
}
void CtrlText::transManualStill( SkinObject *pCtrl )
{
CtrlText *pThis = (CtrlText*)pCtrl;
pThis->releaseMouse();
}
void CtrlText::transMove( SkinObject *pCtrl )
{
CtrlText *pThis = (CtrlText*)pCtrl;
EvtMouse *pEvtMouse = (EvtMouse*)pThis->m_pEvt;
// Do nothing if the text fits in the control
if( pThis->m_pImg &&
pThis->m_pImg->getWidth() >= pThis->getPosition()->getWidth() )
{
// The current image may have been set incorrectly in displayText(), so
// we set the correct value
pThis->m_pCurrImg = pThis->m_pImgDouble;
// Compute the new position of the left side, and make sure it is
// in the correct range
pThis->m_xPos = (pEvtMouse->getXPos() - pThis->m_xOffset);
pThis->adjust( pThis->m_xPos );
pThis->notifyLayout();
}
}
void CtrlText::updateText( SkinObject *pCtrl )
{
CtrlText *pThis = (CtrlText*)pCtrl;
pThis->m_xPos -= MOVING_TEXT_STEP;
pThis->adjust( pThis->m_xPos );
pThis->notifyLayout();
}
void CtrlText::adjust( int &position )
{
// {m_pImgDouble->getWidth() - m_pImg->getWidth()} is the period of the
// bitmap; remember that the string used to generate m_pImgDouble is of the
// form: "foo foo", the number of spaces being a parameter
if( !m_pImg )
{
return;
}
position %= m_pImgDouble->getWidth() - m_pImg->getWidth();
if( position > 0 )
{
position -= m_pImgDouble->getWidth() - m_pImg->getWidth();
}
}
<|endoftext|>
|
<commit_before>#include "sass_context_wrapper.h"
extern "C" {
using namespace std;
void compile_it(uv_work_t* req) {
sass_context_wrapper* ctx_w = static_cast<sass_context_wrapper*>(req->data);
if (ctx_w->dctx) {
compile_data(ctx_w->dctx);
}
else if (ctx_w->fctx) {
compile_file(ctx_w->fctx);
}
}
void compile_data(struct Sass_Data_Context* dctx) {
sass_compile_data_context(dctx);
}
void compile_file(struct Sass_File_Context* fctx) {
sass_compile_file_context(fctx);
}
sass_context_wrapper* sass_make_context_wrapper() {
auto ctx_w = (sass_context_wrapper*)calloc(1, sizeof(sass_context_wrapper));
uv_mutex_init(&ctx_w->importer_mutex);
uv_cond_init(&ctx_w->importer_condition_variable);
return ctx_w;
}
void sass_free_context_wrapper(sass_context_wrapper* ctx_w) {
if (ctx_w->dctx) {
sass_delete_data_context(ctx_w->dctx);
}
else if (ctx_w->fctx) {
sass_delete_file_context(ctx_w->fctx);
}
NanDisposePersistent(ctx_w->stats);
delete ctx_w->success_callback;
delete ctx_w->error_callback;
delete ctx_w->importer_callback;
free(ctx_w);
}
}
<commit_msg>Importer: Destroys vars before leaving the scope.<commit_after>#include "sass_context_wrapper.h"
extern "C" {
using namespace std;
void compile_it(uv_work_t* req) {
sass_context_wrapper* ctx_w = static_cast<sass_context_wrapper*>(req->data);
if (ctx_w->dctx) {
compile_data(ctx_w->dctx);
}
else if (ctx_w->fctx) {
compile_file(ctx_w->fctx);
}
}
void compile_data(struct Sass_Data_Context* dctx) {
sass_compile_data_context(dctx);
}
void compile_file(struct Sass_File_Context* fctx) {
sass_compile_file_context(fctx);
}
sass_context_wrapper* sass_make_context_wrapper() {
auto ctx_w = (sass_context_wrapper*)calloc(1, sizeof(sass_context_wrapper));
uv_mutex_init(&ctx_w->importer_mutex);
uv_cond_init(&ctx_w->importer_condition_variable);
return ctx_w;
}
void sass_free_context_wrapper(sass_context_wrapper* ctx_w) {
if (ctx_w->dctx) {
sass_delete_data_context(ctx_w->dctx);
}
else if (ctx_w->fctx) {
sass_delete_file_context(ctx_w->fctx);
}
NanDisposePersistent(ctx_w->stats);
delete ctx_w->success_callback;
delete ctx_w->error_callback;
delete ctx_w->importer_callback;
delete ctx_w->file;
delete ctx_w->cookie;
uv_mutex_destroy(&ctx_w->importer_mutex);
uv_cond_destroy(&ctx_w->importer_condition_variable);
free(ctx_w);
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: tlog.hxx,v $
*
* $Revision: 1.1 $
*
* last change: $Author: sz $ $Date: 2001-04-12 10:55:26 $
*
* 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 _SOLTOOLS_TESTSHL_TLOG_HXX__
#define _SOLTOOLS_TESTSHL_TLOG_HXX__
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _RTL_TRES_HXX_
#include <rtl/tres.hxx>
#endif
#ifndef _SOLTOOLS_TESTSHL_TUTIL_HXX_
#include "tutil.hxx"
#endif
#include <iostream>
using namespace std;
// <namespace_tstutl>
namespace tstutl {
// <class_tLog>
class tLog {
// <private_members>
::osl::File* m_logfile; // fileobject
::rtl::OUString m_logname; // name of log
// </private_members>
// <private_methods>
void initialize( const ::rtl::OString& name );
// </private_methods>
public:
// <public_ctors>
tLog() : m_logfile( 0 ) {
}
tLog( const sal_Char* name ) {
if( name ) {
initialize( name );
}
else {
m_logfile = 0;
}
}
// </public_ctors>
// <dtor>
virtual ~tLog() {
if ( m_logfile ) {
m_logfile->close();
delete( m_logfile );
}
} // </dtor>
// <public_methods>
inline ::rtl::OUString& getName() { return m_logname; }
inline ::osl::File* getFile() { return m_logfile; }
// open logfile for overwrite (default) or append
::osl::FileBase::RC open( sal_Bool append = sal_False );
::osl::FileBase::RC close();
::osl::FileBase::RC writeRes( ::rtl::tRes& oRes, sal_Bool v = sal_False ,
sal_Bool xml = sal_False );
// write methods without (default) or with echo on display
::osl::FileBase::RC write( const sal_Char* buf, sal_Bool v = sal_False );
// </public_methods>
}; // </class_tLog>
} // </namespace_tstutl>
#endif
<commit_msg>*** empty log message ***<commit_after>/*************************************************************************
*
* $RCSfile: tlog.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: ganaya $ $Date: 2001-05-04 04:29:27 $
*
* 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 _SOLTOOLS_TESTSHL_TLOG_HXX__
#define _SOLTOOLS_TESTSHL_TLOG_HXX__
#ifndef _OSL_FILE_HXX_
#include <osl/file.hxx>
#endif
#ifndef _RTL_TRES_HXX_
#include <rtl/tres.hxx>
#endif
#ifndef _SOLTOOLS_TESTSHL_TUTIL_HXX_
#include "tutil.hxx"
#endif
#include <iostream>
using namespace std;
// <namespace_tstutl>
namespace tstutl {
// <class_tLog>
class tLog {
// <private_members>
::osl::File* m_logfile; // fileobject
::rtl::OUString m_logname; // name of log
// </private_members>
// <private_methods>
void initialize( const ::rtl::OString& name );
// </private_methods>
public:
// <public_ctors>
tLog() : m_logfile( 0 ) {
}
tLog( const sal_Char* name ) {
if( name ) {
initialize( name );
}
else {
m_logfile = 0;
}
}
// </public_ctors>
// <dtor>
virtual ~tLog() {
if ( m_logfile ) {
m_logfile->close();
delete( m_logfile );
}
} // </dtor>
// <public_methods>
inline ::rtl::OUString& getName() { return m_logname; }
inline ::osl::File* getFile() { return m_logfile; }
// open logfile for overwrite (default) or append
::osl::FileBase::RC open( sal_Bool append = sal_False );
::osl::FileBase::RC close();
::osl::FileBase::RC writeRes( ::rtl::TestResult& oRes, sal_Bool v = sal_False ,
sal_Bool xml = sal_False );
// write methods without (default) or with echo on display
::osl::FileBase::RC write( const sal_Char* buf, sal_Bool v = sal_False );
// </public_methods>
}; // </class_tLog>
} // </namespace_tstutl>
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* 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: InsertFunctions.cxx,v $
* $Revision: 1.3 $
*
* 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_reportdesign.hxx"
#include <com/sun/star/embed/NoVisualAreaSizeException.hpp>
#include <com/sun/star/embed/Aspects.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
//------------------------------------------------------------------------
#include <toolkit/helper/vclunohelper.hxx>
#include <sot/exchange.hxx>
#include <svtools/globalnameitem.hxx>
#include <sfx2/viewfrm.hxx>
#include <sfx2/docfile.hxx>
#include <svtools/stritem.hxx>
#include <svx/svdoole2.hxx>
#include <svx/svdview.hxx>
#include <svx/pfiledlg.hxx>
#include <tools/urlobj.hxx>
#include <vcl/msgbox.hxx>
#include <svtools/urihelper.hxx>
#include <svtools/moduleoptions.hxx>
#include <svtools/insdlg.hxx>
#include <svtools/soerr.hxx>
#include <svx/svxdlg.hxx>
#include <sot/clsids.hxx>
#include <svx/svdpagv.hxx>
#include <svx/svdpage.hxx>
#include <svx/svdundo.hxx>
#include <svx/svdmodel.hxx>
#include <cppuhelper/component_context.hxx>
#include <comphelper/processfactory.hxx>
#include <comphelper/storagehelper.hxx>
#include <comphelper/property.hxx>
#include <comphelper/types.hxx>
#include <comphelper/embeddedobjectcontainer.hxx>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/frame/XSynchronousFrameLoader.hpp>
#include <com/sun/star/frame/XComponentLoader.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/chart2/data/DatabaseDataProvider.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/frame/XModel.hpp>
#include <com/sun/star/chart/ChartDataRowSource.hpp>
#include <com/sun/star/chart2/data/XDataReceiver.hpp>
using namespace ::com::sun::star;
#include "InsertFunctions.hxx"
#include "RptObject.hxx"
namespace rptui
{
//------------------------------------------------------------------------
void InitializeChart( const uno::Reference< frame::XModel>& _xModel,
const uno::Reference < embed::XEmbeddedObject >& xObj)
{
//ScDocShell* pDocShell = pViewData->GetDocShell();
//ScDocument* pScDoc = pDocShell->GetDocument();
//rtl::OUString aRangeString( rRangeParam );
//if ( !aRangeString.getLength() )
//{
// SCCOL nCol1 = 0;
// SCROW nRow1 = 0;
// SCTAB nTab1 = 0;
// SCCOL nCol2 = 0;
// SCROW nRow2 = 0;
// SCTAB nTab2 = 0;
// ScMarkData& rMark = pViewData->GetMarkData();
// if ( !rMark.IsMarked() )
// pViewData->GetView()->MarkDataArea( TRUE );
// if ( pViewData->GetSimpleArea( nCol1,nRow1,nTab1, nCol2,nRow2,nTab2 ) )
// {
// PutInOrder( nCol1, nCol2 );
// PutInOrder( nRow1, nRow2 );
// if ( nCol2>nCol1 || nRow2>nRow1 )
// {
// ScDocument* pDoc = pViewData->GetDocument();
// pDoc->LimitChartArea( nTab1, nCol1,nRow1, nCol2,nRow2 );
// String aStr;
// ScRange aRange( nCol1, nRow1, nTab1, nCol2, nRow2, nTab2 );
// aRange.Format( aStr, SCR_ABS_3D, pScDoc );
// aRangeString = aStr;
// }
// }
//}
//if ( rRangeParam.getLength() )
{
// connect to Calc data (if no range string, leave chart alone, with its own data)
uno::Reference< chart2::data::XDataReceiver > xReceiver;
uno::Reference< embed::XComponentSupplier > xCompSupp( xObj, uno::UNO_QUERY );
if( xCompSupp.is())
xReceiver.set( xCompSupp->getComponent(), uno::UNO_QUERY );
OSL_ASSERT( xReceiver.is());
if( xReceiver.is() )
{
// lock the model to suppress any internal updates
uno::Reference< frame::XModel > xChartModel( xReceiver, uno::UNO_QUERY );
if( xChartModel.is() )
xChartModel->lockControllers();
uno::Reference< lang::XMultiServiceFactory> xFac(_xModel,uno::UNO_QUERY_THROW);
uno::Reference< chart2::data::XDatabaseDataProvider > xDataProvider( xFac->createInstance(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.chart2.data.DataProvider"))),uno::UNO_QUERY);
xReceiver->attachDataProvider( xDataProvider.get() );
uno::Reference< util::XNumberFormatsSupplier > xNumberFormatsSupplier( _xModel, uno::UNO_QUERY );
xReceiver->attachNumberFormatsSupplier( xNumberFormatsSupplier );
uno::Sequence< beans::PropertyValue > aArgs( 4 );
aArgs[0] = beans::PropertyValue(
::rtl::OUString::createFromAscii("CellRangeRepresentation"), -1,
uno::makeAny( ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("all")) ), beans::PropertyState_DIRECT_VALUE );
aArgs[1] = beans::PropertyValue(
::rtl::OUString::createFromAscii("HasCategories"), -1,
uno::makeAny( sal_True ), beans::PropertyState_DIRECT_VALUE );
aArgs[2] = beans::PropertyValue(
::rtl::OUString::createFromAscii("FirstCellAsLabel"), -1,
uno::makeAny( sal_False ), beans::PropertyState_DIRECT_VALUE );
aArgs[3] = beans::PropertyValue(
::rtl::OUString::createFromAscii("DataRowSource"), -1,
uno::makeAny( chart::ChartDataRowSource_COLUMNS ), beans::PropertyState_DIRECT_VALUE );
xReceiver->setArguments( aArgs );
if( xChartModel.is() )
xChartModel->unlockControllers();
}
}
}
// -----------------------------------------------------------------------------
} // namespace rptui
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS rptchart02 (1.2.4); FILE MERGED 2008/04/30 13:03:35 oj 1.2.4.3: #i88843# impl clone method 2008/04/16 06:30:23 oj 1.2.4.2: RESYNC: (1.2-1.3); FILE MERGED 2008/03/12 09:45:18 oj 1.2.4.1: impl chart handling<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: InsertFunctions.cxx,v $
* $Revision: 1.4 $
*
* 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_reportdesign.hxx"
#include <com/sun/star/embed/NoVisualAreaSizeException.hpp>
#include <com/sun/star/embed/Aspects.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/embed/XEmbedPersist.hpp>
//------------------------------------------------------------------------
#include <toolkit/helper/vclunohelper.hxx>
#include <sot/exchange.hxx>
#include <svtools/globalnameitem.hxx>
#include <sfx2/viewfrm.hxx>
#include <sfx2/docfile.hxx>
#include <svtools/stritem.hxx>
#include <svx/svdoole2.hxx>
#include <svx/svdview.hxx>
#include <svx/pfiledlg.hxx>
#include <tools/urlobj.hxx>
#include <vcl/msgbox.hxx>
#include <svtools/urihelper.hxx>
#include <svtools/moduleoptions.hxx>
#include <svtools/insdlg.hxx>
#include <svtools/soerr.hxx>
#include <svx/svxdlg.hxx>
#include <sot/clsids.hxx>
#include <svx/svdpagv.hxx>
#include <svx/svdpage.hxx>
#include <svx/svdundo.hxx>
#include <svx/svdmodel.hxx>
#include <cppuhelper/component_context.hxx>
#include <comphelper/processfactory.hxx>
#include <comphelper/storagehelper.hxx>
#include <comphelper/property.hxx>
#include <comphelper/types.hxx>
#include <comphelper/embeddedobjectcontainer.hxx>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/frame/XSynchronousFrameLoader.hpp>
#include <com/sun/star/frame/XComponentLoader.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/chart2/data/DatabaseDataProvider.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/frame/XModel.hpp>
#include <com/sun/star/chart/ChartDataRowSource.hpp>
#include <com/sun/star/chart2/data/XDataReceiver.hpp>
using namespace ::com::sun::star;
#include "InsertFunctions.hxx"
#include "RptObject.hxx"
namespace rptui
{
//------------------------------------------------------------------------
// -----------------------------------------------------------------------------
} // namespace rptui
// -----------------------------------------------------------------------------
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: stgelem.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: mba $ $Date: 2001-02-05 18:11:55 $
*
* 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): _______________________________________
*
*
************************************************************************/
// This file reflects the structure of MS file elements.
// It is very sensitive to alignment!
#ifndef _STGELEM_HXX
#define _STGELEM_HXX
#ifndef _TOOLS_SOLAR_H
#include <tools/solar.h>
#endif
class StgIo;
class SvStream;
class String;
SvStream& operator>>( SvStream&, ClsId& );
SvStream& operator<<( SvStream&, const ClsId& );
class StgHeader
{
BYTE cSignature[ 8 ]; // 00 signature (see below)
ClsId aClsId; // 08 Class ID
INT32 nVersion; // 18 version number
UINT16 nByteOrder; // 1C Unicode byte order indicator
INT16 nPageSize; // 1E 1 << nPageSize = block size
INT16 nDataPageSize; // 20 1 << this size == data block size
BYTE bDirty; // 22 internal dirty flag
BYTE cReserved[ 9 ]; // 23
INT32 nFATSize; // 2C total number of FAT pages
INT32 nTOCstrm; // 30 starting page for the TOC stream
INT32 nReserved; // 34
INT32 nThreshold; // 38 minimum file size for big data
INT32 nDataFAT; // 3C page # of 1st data FAT block
INT32 nDataFATSize; // 40 # of data fat blocks
INT32 nMasterChain; // 44 chain to the next master block
INT32 nMaster; // 48 # of additional master blocks
INT32 nMasterFAT[ 109 ]; // 4C first 109 master FAT pages
public:
StgHeader();
void Init(); // initialize the header
BOOL Load( StgIo& );
BOOL Load( SvStream& );
BOOL Store( StgIo& );
BOOL Check(); // check the signature and version
short GetByteOrder() const { return nByteOrder; }
INT32 GetTOCStart() const { return nTOCstrm; }
void SetTOCStart( INT32 n );
INT32 GetDataFATStart() const { return nDataFAT; }
void SetDataFATStart( INT32 n );
INT32 GetDataFATSize() const { return nDataFATSize; }
void SetDataFATSize( INT32 n );
INT32 GetThreshold() const { return nThreshold; }
short GetPageSize() const { return nPageSize; }
short GetDataPageSize() const { return nDataPageSize; }
INT32 GetFATSize() const { return nFATSize; }
void SetFATSize( INT32 n );
INT32 GetFATChain() const { return nMasterChain; }
void SetFATChain( INT32 n );
INT32 GetMasters() const { return nMaster; }
void SetMasters( INT32 n );
short GetFAT1Size() const { return 109; }
const ClsId& GetClassId() const { return aClsId; }
void SetClassId( const ClsId& );
INT32 GetFATPage( short ) const;
void SetFATPage( short, INT32 );
};
enum StgEntryType { // dir entry types:
STG_EMPTY = 0,
STG_STORAGE = 1,
STG_STREAM = 2,
STG_LOCKBYTES = 3,
STG_PROPERTY = 4,
STG_ROOT = 5
};
enum StgEntryRef { // reference blocks:
STG_LEFT = 0, // left
STG_RIGHT = 1, // right
STG_CHILD = 2, // child
STG_DATA = 3 // data start
};
enum StgEntryTime { // time codes:
STG_MODIFIED = 0, // last modification
STG_ACCESSED = 1 // last access
};
class StgStream;
#define STGENTRY_SIZE 128
class StgEntry { // directory enty
UINT16 nName[ 32 ]; // 00 name as WCHAR
INT16 nNameLen; // 40 size of name in bytes including 00H
BYTE cType; // 42 entry type
BYTE cFlags; // 43 0 or 1 (tree balance?)
INT32 nLeft; // 44 left node entry
INT32 nRight; // 48 right node entry
INT32 nChild; // 4C 1st child entry if storage
ClsId aClsId; // 50 class ID (optional)
INT32 nFlags; // 60 state flags(?)
INT32 nMtime[ 2 ]; // 64 modification time
INT32 nAtime[ 2 ]; // 6C creation and access time
INT32 nPage1; // 74 starting block (either direct or translated)
INT32 nSize; // 78 file size
INT32 nUnknown; // 7C unknown
String aName; // Name as Compare String (ascii, upper)
public:
BOOL Init(); // initialize the data
BOOL SetName( const String& ); // store a name (ASCII, up to 32 chars)
void GetName( String& rName ) const;
// fill in the name
short Compare( const StgEntry& ) const; // compare two entries
BOOL Load( const void* );
void Store( void* );
StgEntryType GetType() const { return (StgEntryType) cType; }
INT32 GetStartPage() const { return nPage1; }
void SetType( StgEntryType t ) { cType = (BYTE) t; }
BYTE GetFlags() const { return cFlags; }
void SetFlags( BYTE c ) { cFlags = c; }
INT32 GetSize() const { return nSize; }
void SetSize( INT32 n ) { nSize = n; }
const ClsId& GetClassId() const { return aClsId; }
void SetClassId( const ClsId& );
INT32 GetLeaf( StgEntryRef ) const;
void SetLeaf( StgEntryRef, INT32 );
const INT32* GetTime( StgEntryTime ) const;
void SetTime( StgEntryTime, INT32* );
};
#define STG_FREE -1L // page is free
#define STG_EOF -2L // page is last page in chain
#define STG_FAT -3L // page is FAT page
#define STG_MASTER -4L // page is master FAT page
#endif
<commit_msg>#65293# moved clsid<commit_after>/*************************************************************************
*
* $RCSfile: stgelem.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2001-02-13 13:45: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): _______________________________________
*
*
************************************************************************/
// This file reflects the structure of MS file elements.
// It is very sensitive to alignment!
#ifndef _STGELEM_HXX
#define _STGELEM_HXX
#ifndef _TOOLS_SOLAR_H
#include <tools/solar.h>
#endif
#include <stg.hxx>
class StgIo;
class SvStream;
class String;
SvStream& operator>>( SvStream&, ClsId& );
SvStream& operator<<( SvStream&, const ClsId& );
class StgHeader
{
BYTE cSignature[ 8 ]; // 00 signature (see below)
ClsId aClsId; // 08 Class ID
INT32 nVersion; // 18 version number
UINT16 nByteOrder; // 1C Unicode byte order indicator
INT16 nPageSize; // 1E 1 << nPageSize = block size
INT16 nDataPageSize; // 20 1 << this size == data block size
BYTE bDirty; // 22 internal dirty flag
BYTE cReserved[ 9 ]; // 23
INT32 nFATSize; // 2C total number of FAT pages
INT32 nTOCstrm; // 30 starting page for the TOC stream
INT32 nReserved; // 34
INT32 nThreshold; // 38 minimum file size for big data
INT32 nDataFAT; // 3C page # of 1st data FAT block
INT32 nDataFATSize; // 40 # of data fat blocks
INT32 nMasterChain; // 44 chain to the next master block
INT32 nMaster; // 48 # of additional master blocks
INT32 nMasterFAT[ 109 ]; // 4C first 109 master FAT pages
public:
StgHeader();
void Init(); // initialize the header
BOOL Load( StgIo& );
BOOL Load( SvStream& );
BOOL Store( StgIo& );
BOOL Check(); // check the signature and version
short GetByteOrder() const { return nByteOrder; }
INT32 GetTOCStart() const { return nTOCstrm; }
void SetTOCStart( INT32 n );
INT32 GetDataFATStart() const { return nDataFAT; }
void SetDataFATStart( INT32 n );
INT32 GetDataFATSize() const { return nDataFATSize; }
void SetDataFATSize( INT32 n );
INT32 GetThreshold() const { return nThreshold; }
short GetPageSize() const { return nPageSize; }
short GetDataPageSize() const { return nDataPageSize; }
INT32 GetFATSize() const { return nFATSize; }
void SetFATSize( INT32 n );
INT32 GetFATChain() const { return nMasterChain; }
void SetFATChain( INT32 n );
INT32 GetMasters() const { return nMaster; }
void SetMasters( INT32 n );
short GetFAT1Size() const { return 109; }
const ClsId& GetClassId() const { return aClsId; }
void SetClassId( const ClsId& );
INT32 GetFATPage( short ) const;
void SetFATPage( short, INT32 );
};
enum StgEntryType { // dir entry types:
STG_EMPTY = 0,
STG_STORAGE = 1,
STG_STREAM = 2,
STG_LOCKBYTES = 3,
STG_PROPERTY = 4,
STG_ROOT = 5
};
enum StgEntryRef { // reference blocks:
STG_LEFT = 0, // left
STG_RIGHT = 1, // right
STG_CHILD = 2, // child
STG_DATA = 3 // data start
};
enum StgEntryTime { // time codes:
STG_MODIFIED = 0, // last modification
STG_ACCESSED = 1 // last access
};
class StgStream;
#define STGENTRY_SIZE 128
class StgEntry { // directory enty
UINT16 nName[ 32 ]; // 00 name as WCHAR
INT16 nNameLen; // 40 size of name in bytes including 00H
BYTE cType; // 42 entry type
BYTE cFlags; // 43 0 or 1 (tree balance?)
INT32 nLeft; // 44 left node entry
INT32 nRight; // 48 right node entry
INT32 nChild; // 4C 1st child entry if storage
ClsId aClsId; // 50 class ID (optional)
INT32 nFlags; // 60 state flags(?)
INT32 nMtime[ 2 ]; // 64 modification time
INT32 nAtime[ 2 ]; // 6C creation and access time
INT32 nPage1; // 74 starting block (either direct or translated)
INT32 nSize; // 78 file size
INT32 nUnknown; // 7C unknown
String aName; // Name as Compare String (ascii, upper)
public:
BOOL Init(); // initialize the data
BOOL SetName( const String& ); // store a name (ASCII, up to 32 chars)
void GetName( String& rName ) const;
// fill in the name
short Compare( const StgEntry& ) const; // compare two entries
BOOL Load( const void* );
void Store( void* );
StgEntryType GetType() const { return (StgEntryType) cType; }
INT32 GetStartPage() const { return nPage1; }
void SetType( StgEntryType t ) { cType = (BYTE) t; }
BYTE GetFlags() const { return cFlags; }
void SetFlags( BYTE c ) { cFlags = c; }
INT32 GetSize() const { return nSize; }
void SetSize( INT32 n ) { nSize = n; }
const ClsId& GetClassId() const { return aClsId; }
void SetClassId( const ClsId& );
INT32 GetLeaf( StgEntryRef ) const;
void SetLeaf( StgEntryRef, INT32 );
const INT32* GetTime( StgEntryTime ) const;
void SetTime( StgEntryTime, INT32* );
};
#define STG_FREE -1L // page is free
#define STG_EOF -2L // page is last page in chain
#define STG_FAT -3L // page is FAT page
#define STG_MASTER -4L // page is master FAT page
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: NeonTypes.hxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: obo $ $Date: 2005-01-27 12:13:58 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _NEONTYPES_HXX_
#define _NEONTYPES_HXX_
#ifndef NE_SESSION_H
#include <neon/ne_session.h> // for ne_session
#endif
#ifndef NE_UTILS_H
#include <neon/ne_utils.h> // for ne_status
#endif
#ifndef NE_BASIC_H
#include <neon/ne_basic.h> // for ne_server_capabilities
#endif
#ifndef NE_PROPS_H
#include <neon/ne_props.h> // for ne_propname, ne_prop_result_set
#endif
typedef ne_session HttpSession;
typedef ne_status HttpStatus;
typedef ne_server_capabilities HttpServerCapabilities;
typedef ne_propname NeonPropName;
typedef ne_prop_result_set NeonPropFindResultSet;
#endif // _NEONTYPES_HXX_
<commit_msg>INTEGRATION: CWS ooo19126 (1.9.34); FILE MERGED 2005/09/05 18:45:37 rt 1.9.34.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: NeonTypes.hxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: rt $ $Date: 2005-09-09 16:13:33 $
*
* 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 _NEONTYPES_HXX_
#define _NEONTYPES_HXX_
#ifndef NE_SESSION_H
#include <neon/ne_session.h> // for ne_session
#endif
#ifndef NE_UTILS_H
#include <neon/ne_utils.h> // for ne_status
#endif
#ifndef NE_BASIC_H
#include <neon/ne_basic.h> // for ne_server_capabilities
#endif
#ifndef NE_PROPS_H
#include <neon/ne_props.h> // for ne_propname, ne_prop_result_set
#endif
typedef ne_session HttpSession;
typedef ne_status HttpStatus;
typedef ne_server_capabilities HttpServerCapabilities;
typedef ne_propname NeonPropName;
typedef ne_prop_result_set NeonPropFindResultSet;
#endif // _NEONTYPES_HXX_
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/base/cursor/cursor_loader_x11.h"
#include <X11/Xlib.h>
#include <X11/cursorfont.h>
#include "base/logging.h"
#include "grit/ui_resources.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/x/x11_util.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/image/image_skia.h"
namespace {
// Returns X font cursor shape from an Aura cursor.
int CursorShapeFromNative(gfx::NativeCursor native_cursor) {
switch (native_cursor.native_type()) {
case ui::kCursorMiddlePanning:
return XC_fleur;
case ui::kCursorEastPanning:
return XC_sb_right_arrow;
case ui::kCursorNorthPanning:
return XC_sb_up_arrow;
case ui::kCursorNorthEastPanning:
return XC_top_right_corner;
case ui::kCursorNorthWestPanning:
return XC_top_left_corner;
case ui::kCursorSouthPanning:
return XC_sb_down_arrow;
case ui::kCursorSouthEastPanning:
return XC_bottom_right_corner;
case ui::kCursorSouthWestPanning:
return XC_bottom_left_corner;
case ui::kCursorWestPanning:
return XC_sb_left_arrow;
case ui::kCursorNone:
case ui::kCursorGrab:
case ui::kCursorGrabbing:
// TODO(jamescook): Need cursors for these. crbug.com/111650
return XC_left_ptr;
#if defined(OS_CHROMEOS)
case ui::kCursorNull:
case ui::kCursorPointer:
case ui::kCursorNoDrop:
case ui::kCursorNotAllowed:
case ui::kCursorCopy:
case ui::kCursorMove:
case ui::kCursorEastResize:
case ui::kCursorNorthResize:
case ui::kCursorSouthResize:
case ui::kCursorWestResize:
case ui::kCursorNorthEastResize:
case ui::kCursorNorthWestResize:
case ui::kCursorSouthWestResize:
case ui::kCursorSouthEastResize:
case ui::kCursorIBeam:
case ui::kCursorAlias:
case ui::kCursorCell:
case ui::kCursorContextMenu:
case ui::kCursorCross:
case ui::kCursorHelp:
case ui::kCursorWait:
case ui::kCursorNorthSouthResize:
case ui::kCursorEastWestResize:
case ui::kCursorNorthEastSouthWestResize:
case ui::kCursorNorthWestSouthEastResize:
case ui::kCursorProgress:
case ui::kCursorColumnResize:
case ui::kCursorRowResize:
case ui::kCursorVerticalText:
case ui::kCursorZoomIn:
case ui::kCursorZoomOut:
// In some environments, the image assets are not set (e.g. in
// content-browsertests, content-shell etc.).
return XC_left_ptr;
#else // defined(OS_CHROMEOS)
case ui::kCursorNull:
return XC_left_ptr;
case ui::kCursorPointer:
return XC_left_ptr;
case ui::kCursorMove:
return XC_fleur;
case ui::kCursorCross:
return XC_crosshair;
case ui::kCursorHand:
return XC_hand2;
case ui::kCursorIBeam:
return XC_xterm;
case ui::kCursorWait:
return XC_watch;
case ui::kCursorHelp:
return XC_question_arrow;
case ui::kCursorEastResize:
return XC_right_side;
case ui::kCursorNorthResize:
return XC_top_side;
case ui::kCursorNorthEastResize:
return XC_top_right_corner;
case ui::kCursorNorthWestResize:
return XC_top_left_corner;
case ui::kCursorSouthResize:
return XC_bottom_side;
case ui::kCursorSouthEastResize:
return XC_bottom_right_corner;
case ui::kCursorSouthWestResize:
return XC_bottom_left_corner;
case ui::kCursorWestResize:
return XC_left_side;
case ui::kCursorNorthSouthResize:
return XC_sb_v_double_arrow;
case ui::kCursorEastWestResize:
return XC_sb_h_double_arrow;
case ui::kCursorNorthEastSouthWestResize:
case ui::kCursorNorthWestSouthEastResize:
// There isn't really a useful cursor available for these.
return XC_left_ptr;
case ui::kCursorColumnResize:
return XC_sb_h_double_arrow;
case ui::kCursorRowResize:
return XC_sb_v_double_arrow;
#endif // defined(OS_CHROMEOS)
case ui::kCursorCustom:
NOTREACHED();
return XC_left_ptr;
}
NOTREACHED() << "Case not handled for " << native_cursor.native_type();
return XC_left_ptr;
}
} // namespace
namespace ui {
CursorLoader* CursorLoader::Create() {
return new CursorLoaderX11;
}
CursorLoaderX11::CursorLoaderX11()
: invisible_cursor_(CreateInvisibleCursor(), GetXDisplay()) {
}
CursorLoaderX11::~CursorLoaderX11() {
UnloadAll();
// Clears XCursorCache.
GetXCursor(kCursorClearXCursorCache);
}
void CursorLoaderX11::LoadImageCursor(int id,
int resource_id,
const gfx::Point& hot) {
const gfx::ImageSkia* image =
ResourceBundle::GetSharedInstance().GetImageSkiaNamed(resource_id);
const gfx::ImageSkiaRep& image_rep = image->GetRepresentation(
GetScaleFactorFromScale(device_scale_factor()));
XcursorImage* x_image =
SkBitmapToXcursorImage(&image_rep.sk_bitmap(), hot);
cursors_[id] = CreateReffedCustomXCursor(x_image);
// |image_rep| is owned by the resource bundle. So we do not need to free it.
}
void CursorLoaderX11::LoadAnimatedCursor(int id,
int resource_id,
const gfx::Point& hot,
int frame_delay_ms) {
const gfx::ImageSkia* image =
ResourceBundle::GetSharedInstance().GetImageSkiaNamed(resource_id);
const gfx::ImageSkiaRep& image_rep = image->GetRepresentation(
GetScaleFactorFromScale(device_scale_factor()));
const SkBitmap bitmap = image_rep.sk_bitmap();
DCHECK_EQ(bitmap.config(), SkBitmap::kARGB_8888_Config);
int frame_width = bitmap.height();
int frame_height = frame_width;
int total_width = bitmap.width();
DCHECK_EQ(total_width % frame_width, 0);
int frame_count = total_width / frame_width;
DCHECK_GT(frame_count, 0);
XcursorImages* x_images = XcursorImagesCreate(frame_count);
x_images->nimage = frame_count;
bitmap.lockPixels();
unsigned int* pixels = bitmap.getAddr32(0, 0);
// Create each frame.
for (int frame = 0; frame < frame_count; ++frame) {
XcursorImage* x_image = XcursorImageCreate(frame_width, frame_height);
for (int row = 0; row < frame_height; ++row) {
// Copy |row|'th row of |frame|'th frame.
memcpy(x_image->pixels + row * frame_width,
pixels + frame * frame_width + row * total_width,
frame_width * 4);
}
x_image->xhot = hot.x();
x_image->yhot = hot.y();
x_image->delay = frame_delay_ms;
x_images->images[frame] = x_image;
}
bitmap.unlockPixels();
animated_cursors_[id] = std::make_pair(
XcursorImagesLoadCursor(GetXDisplay(), x_images), x_images);
// |bitmap| is owned by the resource bundle. So we do not need to free it.
}
void CursorLoaderX11::UnloadAll() {
for (ImageCursorMap::const_iterator it = cursors_.begin();
it != cursors_.end(); ++it)
UnrefCustomXCursor(it->second);
// Free animated cursors and images.
for (AnimatedCursorMap::iterator it = animated_cursors_.begin();
it != animated_cursors_.end(); ++it) {
XcursorImagesDestroy(it->second.second); // also frees individual frames.
XFreeCursor(GetXDisplay(), it->second.first);
}
}
void CursorLoaderX11::SetPlatformCursor(gfx::NativeCursor* cursor) {
DCHECK(cursor);
::Cursor xcursor;
if (IsImageCursor(*cursor))
xcursor = ImageCursorFromNative(*cursor);
else if (*cursor == kCursorNone)
xcursor = invisible_cursor_.get();
else if (*cursor == kCursorCustom)
xcursor = cursor->platform();
else if (device_scale_factor() == 1.0f)
xcursor = GetXCursor(CursorShapeFromNative(*cursor));
else
xcursor = ImageCursorFromNative(kCursorPointer);
cursor->SetPlatformCursor(xcursor);
}
bool CursorLoaderX11::IsImageCursor(gfx::NativeCursor native_cursor) {
int type = native_cursor.native_type();
return cursors_.count(type) || animated_cursors_.count(type);
}
::Cursor CursorLoaderX11::ImageCursorFromNative(
gfx::NativeCursor native_cursor) {
int type = native_cursor.native_type();
if (animated_cursors_.count(type))
return animated_cursors_[type].first;
ImageCursorMap::iterator find = cursors_.find(type);
if (find != cursors_.end())
return cursors_[type];
return GetXCursor(CursorShapeFromNative(native_cursor));
}
} // namespace ui
<commit_msg>Fixing crash with Chrome upon cursor access<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/base/cursor/cursor_loader_x11.h"
#include <X11/Xlib.h>
#include <X11/cursorfont.h>
#include "base/logging.h"
#include "grit/ui_resources.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/x/x11_util.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/image/image_skia.h"
namespace {
// Returns X font cursor shape from an Aura cursor.
int CursorShapeFromNative(gfx::NativeCursor native_cursor) {
switch (native_cursor.native_type()) {
case ui::kCursorMiddlePanning:
return XC_fleur;
case ui::kCursorEastPanning:
return XC_sb_right_arrow;
case ui::kCursorNorthPanning:
return XC_sb_up_arrow;
case ui::kCursorNorthEastPanning:
return XC_top_right_corner;
case ui::kCursorNorthWestPanning:
return XC_top_left_corner;
case ui::kCursorSouthPanning:
return XC_sb_down_arrow;
case ui::kCursorSouthEastPanning:
return XC_bottom_right_corner;
case ui::kCursorSouthWestPanning:
return XC_bottom_left_corner;
case ui::kCursorWestPanning:
return XC_sb_left_arrow;
case ui::kCursorNone:
case ui::kCursorGrab:
case ui::kCursorGrabbing:
// TODO(jamescook): Need cursors for these. crbug.com/111650
return XC_left_ptr;
#if defined(OS_CHROMEOS)
case ui::kCursorNull:
case ui::kCursorPointer:
case ui::kCursorNoDrop:
case ui::kCursorNotAllowed:
case ui::kCursorCopy:
case ui::kCursorMove:
case ui::kCursorEastResize:
case ui::kCursorNorthResize:
case ui::kCursorSouthResize:
case ui::kCursorWestResize:
case ui::kCursorNorthEastResize:
case ui::kCursorNorthWestResize:
case ui::kCursorSouthWestResize:
case ui::kCursorSouthEastResize:
case ui::kCursorIBeam:
case ui::kCursorAlias:
case ui::kCursorCell:
case ui::kCursorContextMenu:
case ui::kCursorCross:
case ui::kCursorHelp:
case ui::kCursorWait:
case ui::kCursorNorthSouthResize:
case ui::kCursorEastWestResize:
case ui::kCursorNorthEastSouthWestResize:
case ui::kCursorNorthWestSouthEastResize:
case ui::kCursorProgress:
case ui::kCursorColumnResize:
case ui::kCursorRowResize:
case ui::kCursorVerticalText:
case ui::kCursorZoomIn:
case ui::kCursorZoomOut:
case ui::kCursorHand:
// In some environments, the image assets are not set (e.g. in
// content-browsertests, content-shell etc.).
return XC_left_ptr;
#else // defined(OS_CHROMEOS)
case ui::kCursorNull:
return XC_left_ptr;
case ui::kCursorPointer:
return XC_left_ptr;
case ui::kCursorMove:
return XC_fleur;
case ui::kCursorCross:
return XC_crosshair;
case ui::kCursorHand:
return XC_hand2;
case ui::kCursorIBeam:
return XC_xterm;
case ui::kCursorWait:
return XC_watch;
case ui::kCursorHelp:
return XC_question_arrow;
case ui::kCursorEastResize:
return XC_right_side;
case ui::kCursorNorthResize:
return XC_top_side;
case ui::kCursorNorthEastResize:
return XC_top_right_corner;
case ui::kCursorNorthWestResize:
return XC_top_left_corner;
case ui::kCursorSouthResize:
return XC_bottom_side;
case ui::kCursorSouthEastResize:
return XC_bottom_right_corner;
case ui::kCursorSouthWestResize:
return XC_bottom_left_corner;
case ui::kCursorWestResize:
return XC_left_side;
case ui::kCursorNorthSouthResize:
return XC_sb_v_double_arrow;
case ui::kCursorEastWestResize:
return XC_sb_h_double_arrow;
case ui::kCursorNorthEastSouthWestResize:
case ui::kCursorNorthWestSouthEastResize:
// There isn't really a useful cursor available for these.
return XC_left_ptr;
case ui::kCursorColumnResize:
return XC_sb_h_double_arrow;
case ui::kCursorRowResize:
return XC_sb_v_double_arrow;
#endif // defined(OS_CHROMEOS)
case ui::kCursorCustom:
NOTREACHED();
return XC_left_ptr;
}
NOTREACHED() << "Case not handled for " << native_cursor.native_type();
return XC_left_ptr;
}
} // namespace
namespace ui {
CursorLoader* CursorLoader::Create() {
return new CursorLoaderX11;
}
CursorLoaderX11::CursorLoaderX11()
: invisible_cursor_(CreateInvisibleCursor(), GetXDisplay()) {
}
CursorLoaderX11::~CursorLoaderX11() {
UnloadAll();
// Clears XCursorCache.
GetXCursor(kCursorClearXCursorCache);
}
void CursorLoaderX11::LoadImageCursor(int id,
int resource_id,
const gfx::Point& hot) {
const gfx::ImageSkia* image =
ResourceBundle::GetSharedInstance().GetImageSkiaNamed(resource_id);
const gfx::ImageSkiaRep& image_rep = image->GetRepresentation(
GetScaleFactorFromScale(device_scale_factor()));
XcursorImage* x_image =
SkBitmapToXcursorImage(&image_rep.sk_bitmap(), hot);
cursors_[id] = CreateReffedCustomXCursor(x_image);
// |image_rep| is owned by the resource bundle. So we do not need to free it.
}
void CursorLoaderX11::LoadAnimatedCursor(int id,
int resource_id,
const gfx::Point& hot,
int frame_delay_ms) {
const gfx::ImageSkia* image =
ResourceBundle::GetSharedInstance().GetImageSkiaNamed(resource_id);
const gfx::ImageSkiaRep& image_rep = image->GetRepresentation(
GetScaleFactorFromScale(device_scale_factor()));
const SkBitmap bitmap = image_rep.sk_bitmap();
DCHECK_EQ(bitmap.config(), SkBitmap::kARGB_8888_Config);
int frame_width = bitmap.height();
int frame_height = frame_width;
int total_width = bitmap.width();
DCHECK_EQ(total_width % frame_width, 0);
int frame_count = total_width / frame_width;
DCHECK_GT(frame_count, 0);
XcursorImages* x_images = XcursorImagesCreate(frame_count);
x_images->nimage = frame_count;
bitmap.lockPixels();
unsigned int* pixels = bitmap.getAddr32(0, 0);
// Create each frame.
for (int frame = 0; frame < frame_count; ++frame) {
XcursorImage* x_image = XcursorImageCreate(frame_width, frame_height);
for (int row = 0; row < frame_height; ++row) {
// Copy |row|'th row of |frame|'th frame.
memcpy(x_image->pixels + row * frame_width,
pixels + frame * frame_width + row * total_width,
frame_width * 4);
}
x_image->xhot = hot.x();
x_image->yhot = hot.y();
x_image->delay = frame_delay_ms;
x_images->images[frame] = x_image;
}
bitmap.unlockPixels();
animated_cursors_[id] = std::make_pair(
XcursorImagesLoadCursor(GetXDisplay(), x_images), x_images);
// |bitmap| is owned by the resource bundle. So we do not need to free it.
}
void CursorLoaderX11::UnloadAll() {
for (ImageCursorMap::const_iterator it = cursors_.begin();
it != cursors_.end(); ++it)
UnrefCustomXCursor(it->second);
// Free animated cursors and images.
for (AnimatedCursorMap::iterator it = animated_cursors_.begin();
it != animated_cursors_.end(); ++it) {
XcursorImagesDestroy(it->second.second); // also frees individual frames.
XFreeCursor(GetXDisplay(), it->second.first);
}
}
void CursorLoaderX11::SetPlatformCursor(gfx::NativeCursor* cursor) {
DCHECK(cursor);
::Cursor xcursor;
if (IsImageCursor(*cursor))
xcursor = ImageCursorFromNative(*cursor);
else if (*cursor == kCursorNone)
xcursor = invisible_cursor_.get();
else if (*cursor == kCursorCustom)
xcursor = cursor->platform();
else if (device_scale_factor() == 1.0f)
xcursor = GetXCursor(CursorShapeFromNative(*cursor));
else
xcursor = ImageCursorFromNative(kCursorPointer);
cursor->SetPlatformCursor(xcursor);
}
bool CursorLoaderX11::IsImageCursor(gfx::NativeCursor native_cursor) {
int type = native_cursor.native_type();
return cursors_.count(type) || animated_cursors_.count(type);
}
::Cursor CursorLoaderX11::ImageCursorFromNative(
gfx::NativeCursor native_cursor) {
int type = native_cursor.native_type();
if (animated_cursors_.count(type))
return animated_cursors_[type].first;
ImageCursorMap::iterator find = cursors_.find(type);
if (find != cursors_.end())
return cursors_[type];
return GetXCursor(CursorShapeFromNative(native_cursor));
}
} // namespace ui
<|endoftext|>
|
<commit_before>/*************************************************************************/
/* file_access_memory.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* http://www.godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */
/* */
/* 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 "file_access_memory.h"
#include "os/dir_access.h"
#include "os/copymem.h"
#include "globals.h"
#include "map.h"
static Map<String, Vector<uint8_t> >* files = NULL;
void FileAccessMemory::register_file(String p_name, Vector<uint8_t> p_data) {
if (!files) {
files = memnew((Map<String, Vector<uint8_t> >));
};
String name;
if (Globals::get_singleton())
name = Globals::get_singleton()->globalize_path(p_name);
else
name = p_name;
name = DirAccess::normalize_path(name);
(*files)[name] = p_data;
};
void FileAccessMemory::cleanup() {
if (!files)
return;
memdelete(files);
};
FileAccess* FileAccessMemory::create() {
return memnew(FileAccessMemory);
};
bool FileAccessMemory::file_exists(const String& p_name) {
String name = fix_path(p_name);
name = DirAccess::normalize_path(name);
return files && (files->find(name) != NULL);
};
Error FileAccessMemory::_open(const String& p_path, int p_mode_flags) {
ERR_FAIL_COND_V(!files, ERR_FILE_NOT_FOUND);
String name = fix_path(p_path);
name = DirAccess::normalize_path(name);
Map<String, Vector<uint8_t> >::Element* E = files->find(name);
ERR_FAIL_COND_V(!E, ERR_FILE_NOT_FOUND);
data = &(E->get()[0]);
length = E->get().size();
pos = 0;
return OK;
};
void FileAccessMemory::close() {
data = NULL;
};
bool FileAccessMemory::is_open() const {
return data != NULL;
};
void FileAccessMemory::seek(size_t p_position) {
ERR_FAIL_COND(!data);
pos = p_position;
};
void FileAccessMemory::seek_end(int64_t p_position) {
ERR_FAIL_COND(!data);
pos = length + p_position;
};
size_t FileAccessMemory::get_pos() const {
ERR_FAIL_COND_V(!data, 0);
return pos;
};
size_t FileAccessMemory::get_len() const {
ERR_FAIL_COND_V(!data, 0);
return length;
};
bool FileAccessMemory::eof_reached() const {
return pos >= length;
};
uint8_t FileAccessMemory::get_8() const {
uint8_t ret = 0;
if (pos < length) {
ret = data[pos];
};
++pos;
return ret;
};
int FileAccessMemory::get_buffer(uint8_t *p_dst,int p_length) const {
ERR_FAIL_COND_V(!data, -1);
int left = length - pos;
int read = MIN(p_length, left);
if (read < p_length) {
WARN_PRINT("Reading less data than requested");
};
copymem(p_dst, &data[pos], read);
pos += p_length;
return read;
};
Error FileAccessMemory::get_error() const {
return pos >= length ? ERR_FILE_EOF : OK;
};
void FileAccessMemory::store_8(uint8_t p_byte) {
ERR_FAIL_COND(!data);
ERR_FAIL_COND(pos >= length);
data[pos++] = p_byte;
};
void FileAccessMemory::store_buffer(const uint8_t *p_src,int p_length) {
int left = length - pos;
int write = MIN(p_length, left);
if (write < p_length) {
WARN_PRINT("Writing less data than requested");
};
copymem(&data[pos], p_src, write);
pos += p_length;
};
FileAccessMemory::FileAccessMemory() {
data = NULL;
}
<commit_msg>removed unnecessary semicolons<commit_after>/*************************************************************************/
/* file_access_memory.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* http://www.godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur. */
/* */
/* 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 "file_access_memory.h"
#include "os/dir_access.h"
#include "os/copymem.h"
#include "globals.h"
#include "map.h"
static Map<String, Vector<uint8_t> >* files = NULL;
void FileAccessMemory::register_file(String p_name, Vector<uint8_t> p_data) {
if (!files) {
files = memnew((Map<String, Vector<uint8_t> >));
}
String name;
if (Globals::get_singleton())
name = Globals::get_singleton()->globalize_path(p_name);
else
name = p_name;
name = DirAccess::normalize_path(name);
(*files)[name] = p_data;
}
void FileAccessMemory::cleanup() {
if (!files)
return;
memdelete(files);
}
FileAccess* FileAccessMemory::create() {
return memnew(FileAccessMemory);
}
bool FileAccessMemory::file_exists(const String& p_name) {
String name = fix_path(p_name);
name = DirAccess::normalize_path(name);
return files && (files->find(name) != NULL);
}
Error FileAccessMemory::_open(const String& p_path, int p_mode_flags) {
ERR_FAIL_COND_V(!files, ERR_FILE_NOT_FOUND);
String name = fix_path(p_path);
name = DirAccess::normalize_path(name);
Map<String, Vector<uint8_t> >::Element* E = files->find(name);
ERR_FAIL_COND_V(!E, ERR_FILE_NOT_FOUND);
data = &(E->get()[0]);
length = E->get().size();
pos = 0;
return OK;
}
void FileAccessMemory::close() {
data = NULL;
}
bool FileAccessMemory::is_open() const {
return data != NULL;
}
void FileAccessMemory::seek(size_t p_position) {
ERR_FAIL_COND(!data);
pos = p_position;
}
void FileAccessMemory::seek_end(int64_t p_position) {
ERR_FAIL_COND(!data);
pos = length + p_position;
}
size_t FileAccessMemory::get_pos() const {
ERR_FAIL_COND_V(!data, 0);
return pos;
}
size_t FileAccessMemory::get_len() const {
ERR_FAIL_COND_V(!data, 0);
return length;
}
bool FileAccessMemory::eof_reached() const {
return pos >= length;
}
uint8_t FileAccessMemory::get_8() const {
uint8_t ret = 0;
if (pos < length) {
ret = data[pos];
}
++pos;
return ret;
}
int FileAccessMemory::get_buffer(uint8_t *p_dst,int p_length) const {
ERR_FAIL_COND_V(!data, -1);
int left = length - pos;
int read = MIN(p_length, left);
if (read < p_length) {
WARN_PRINT("Reading less data than requested");
};
copymem(p_dst, &data[pos], read);
pos += p_length;
return read;
}
Error FileAccessMemory::get_error() const {
return pos >= length ? ERR_FILE_EOF : OK;
}
void FileAccessMemory::store_8(uint8_t p_byte) {
ERR_FAIL_COND(!data);
ERR_FAIL_COND(pos >= length);
data[pos++] = p_byte;
}
void FileAccessMemory::store_buffer(const uint8_t *p_src,int p_length) {
int left = length - pos;
int write = MIN(p_length, left);
if (write < p_length) {
WARN_PRINT("Writing less data than requested");
}
copymem(&data[pos], p_src, write);
pos += p_length;
}
FileAccessMemory::FileAccessMemory() {
data = NULL;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "rtp_format_vp8.h"
#include <cassert> // assert
#include <string.h> // memcpy
namespace webrtc {
// Define how the VP8PacketizerModes are implemented.
// Modes are: kStrict, kAggregate, kSloppy.
const RtpFormatVp8::AggregationMode RtpFormatVp8::aggr_modes_[kNumModes] =
{ kAggrNone, kAggrPartitions, kAggrFragments };
const bool RtpFormatVp8::balance_modes_[kNumModes] =
{ true, true, false };
const bool RtpFormatVp8::separate_first_modes_[kNumModes] =
{ true, false, false };
RtpFormatVp8::RtpFormatVp8(const WebRtc_UWord8* payload_data,
WebRtc_UWord32 payload_size,
const RTPVideoHeaderVP8& hdr_info,
const RTPFragmentationHeader& fragmentation,
VP8PacketizerMode mode)
: payload_data_(payload_data),
payload_size_(static_cast<int>(payload_size)),
payload_bytes_sent_(0),
part_ix_(0),
beginning_(true),
first_fragment_(true),
vp8_header_bytes_(1),
aggr_mode_(aggr_modes_[mode]),
balance_(balance_modes_[mode]),
separate_first_(separate_first_modes_[mode]),
hdr_info_(hdr_info)
{
part_info_ = fragmentation;
}
RtpFormatVp8::RtpFormatVp8(const WebRtc_UWord8* payload_data,
WebRtc_UWord32 payload_size,
const RTPVideoHeaderVP8& hdr_info)
: payload_data_(payload_data),
payload_size_(static_cast<int>(payload_size)),
part_info_(),
payload_bytes_sent_(0),
part_ix_(0),
beginning_(true),
first_fragment_(true),
vp8_header_bytes_(1),
aggr_mode_(aggr_modes_[kSloppy]),
balance_(balance_modes_[kSloppy]),
separate_first_(separate_first_modes_[kSloppy]),
hdr_info_(hdr_info)
{
part_info_.VerifyAndAllocateFragmentationHeader(1);
part_info_.fragmentationLength[0] = payload_size;
part_info_.fragmentationOffset[0] = 0;
}
int RtpFormatVp8::CalcNextSize(int max_payload_len, int remaining_bytes,
bool split_payload) const
{
if (max_payload_len == 0 || remaining_bytes == 0)
{
return 0;
}
if (!split_payload)
{
return max_payload_len >= remaining_bytes ? remaining_bytes : 0;
}
if (balance_)
{
// Balance payload sizes to produce (almost) equal size
// fragments.
// Number of fragments for remaining_bytes:
int num_frags = remaining_bytes / max_payload_len + 1;
// Number of bytes in this fragment:
return static_cast<int>(static_cast<double>(remaining_bytes)
/ num_frags + 0.5);
}
else
{
return max_payload_len >= remaining_bytes ? remaining_bytes
: max_payload_len;
}
}
int RtpFormatVp8::NextPacket(int max_payload_len, WebRtc_UWord8* buffer,
int* bytes_to_send, bool* last_packet)
{
const int num_partitions = part_info_.fragmentationVectorSize;
int send_bytes = 0; // How much data to send in this packet.
bool split_payload = true; // Splitting of partitions is initially allowed.
int remaining_in_partition = part_info_.fragmentationOffset[part_ix_] -
payload_bytes_sent_ + part_info_.fragmentationLength[part_ix_] +
FirstHeaderExtraLength(); // Add header extra length to payload length.
int rem_payload_len = max_payload_len - vp8_header_bytes_;
const int first_partition_in_packet = part_ix_;
while (int next_size = CalcNextSize(rem_payload_len, remaining_in_partition,
split_payload))
{
send_bytes += next_size;
rem_payload_len -= next_size;
remaining_in_partition -= next_size;
if (remaining_in_partition == 0 && !(beginning_ && separate_first_))
{
// Advance to next partition?
// Check that there are more partitions; verify that we are either
// allowed to aggregate fragments, or that we are allowed to
// aggregate intact partitions and that we started this packet
// with an intact partition (indicated by first_fragment_ == true).
if (part_ix_ + 1 < num_partitions &&
((aggr_mode_ == kAggrFragments) ||
(aggr_mode_ == kAggrPartitions && first_fragment_)))
{
remaining_in_partition
= part_info_.fragmentationLength[++part_ix_];
// Disallow splitting unless kAggrFragments. In kAggrPartitions,
// we can only aggregate intact partitions.
split_payload = (aggr_mode_ == kAggrFragments);
}
}
else if (balance_ && remaining_in_partition > 0)
{
break;
}
}
if (remaining_in_partition == 0)
{
++part_ix_; // Advance to next partition.
}
send_bytes -= FirstHeaderExtraLength(); // Remove the extra length again.
assert(send_bytes > 0);
const bool end_of_fragment = (remaining_in_partition == 0);
// Write the payload header and the payload to buffer.
*bytes_to_send = WriteHeaderAndPayload(send_bytes, end_of_fragment, buffer,
max_payload_len);
if (*bytes_to_send < 0)
{
return -1;
}
*last_packet = (payload_bytes_sent_ >= payload_size_);
assert(!*last_packet || (payload_bytes_sent_ == payload_size_));
return first_partition_in_packet;
}
int RtpFormatVp8::WriteHeaderAndPayload(int payload_bytes,
bool end_of_fragment,
WebRtc_UWord8* buffer,
int buffer_length)
{
// Write the VP8 payload header.
// 0 1 2
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | RSV |I|N|FI |B| PictureID (1 or 2 octets) |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
if (payload_bytes < 0)
{
return -1;
}
if (payload_bytes_sent_ + payload_bytes > payload_size_)
{
return -1;
}
buffer[0] = 0;
if (hdr_info_.nonReference) buffer[0] |= (0x01 << 3); // N
buffer[0] |= (GetFIFlag(end_of_fragment) << 1); // FI
if (beginning_) buffer[0] |= 0x01; // B
int pic_id_len = WritePictureID(&buffer[vp8_header_bytes_],
buffer_length - vp8_header_bytes_);
if (pic_id_len < 0) return pic_id_len; // error
if (pic_id_len > 0) buffer[0] |= (0x01 << 4); // I
if (vp8_header_bytes_ + pic_id_len + payload_bytes > buffer_length)
{
return -1;
}
memcpy(&buffer[vp8_header_bytes_ + pic_id_len],
&payload_data_[payload_bytes_sent_], payload_bytes);
beginning_ = false; // next packet cannot be first packet in frame
// next packet starts new fragment if this ended one
first_fragment_ = end_of_fragment;
payload_bytes_sent_ += payload_bytes;
// Return total length of written data.
return payload_bytes + vp8_header_bytes_ + pic_id_len;
}
int RtpFormatVp8::WritePictureID(WebRtc_UWord8* buffer, int buffer_length) const
{
const WebRtc_UWord16 pic_id =
static_cast<WebRtc_UWord16> (hdr_info_.pictureId);
int picture_id_len = PictureIdLength();
if (picture_id_len > buffer_length) return -1; // error
if (picture_id_len == 2)
{
buffer[0] = 0x80 | ((pic_id >> 8) & 0x7F);
buffer[1] = pic_id & 0xFF;
}
else if (picture_id_len == 1)
{
buffer[0] = pic_id & 0x7F;
}
return picture_id_len;
}
int RtpFormatVp8::FirstHeaderExtraLength() const
{
if (!beginning_)
{
return 0;
}
int length = 0;
length += PictureIdLength();
return length;
}
int RtpFormatVp8::PictureIdLength() const
{
if (!beginning_ || hdr_info_.pictureId == kNoPictureId)
{
return 0;
}
if (hdr_info_.pictureId <= 0x7F)
{
return 1;
}
else
{
return 2;
}
}
int RtpFormatVp8::GetFIFlag(bool end_of_fragment) const
{
if (first_fragment_ && end_of_fragment) {
return 0x0;
}
else if (first_fragment_ && !end_of_fragment) {
return 0x1;
}
else if (!first_fragment_ && !end_of_fragment) {
return 0x2;
}
else if (!first_fragment_ && end_of_fragment) {
return 0x3;
}
}
} // namespace webrtc
<commit_msg>Add return value Review URL: http://webrtc-codereview.appspot.com/98004<commit_after>/*
* Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "rtp_format_vp8.h"
#include <cassert> // assert
#include <string.h> // memcpy
namespace webrtc {
// Define how the VP8PacketizerModes are implemented.
// Modes are: kStrict, kAggregate, kSloppy.
const RtpFormatVp8::AggregationMode RtpFormatVp8::aggr_modes_[kNumModes] =
{ kAggrNone, kAggrPartitions, kAggrFragments };
const bool RtpFormatVp8::balance_modes_[kNumModes] =
{ true, true, false };
const bool RtpFormatVp8::separate_first_modes_[kNumModes] =
{ true, false, false };
RtpFormatVp8::RtpFormatVp8(const WebRtc_UWord8* payload_data,
WebRtc_UWord32 payload_size,
const RTPVideoHeaderVP8& hdr_info,
const RTPFragmentationHeader& fragmentation,
VP8PacketizerMode mode)
: payload_data_(payload_data),
payload_size_(static_cast<int>(payload_size)),
payload_bytes_sent_(0),
part_ix_(0),
beginning_(true),
first_fragment_(true),
vp8_header_bytes_(1),
aggr_mode_(aggr_modes_[mode]),
balance_(balance_modes_[mode]),
separate_first_(separate_first_modes_[mode]),
hdr_info_(hdr_info)
{
part_info_ = fragmentation;
}
RtpFormatVp8::RtpFormatVp8(const WebRtc_UWord8* payload_data,
WebRtc_UWord32 payload_size,
const RTPVideoHeaderVP8& hdr_info)
: payload_data_(payload_data),
payload_size_(static_cast<int>(payload_size)),
part_info_(),
payload_bytes_sent_(0),
part_ix_(0),
beginning_(true),
first_fragment_(true),
vp8_header_bytes_(1),
aggr_mode_(aggr_modes_[kSloppy]),
balance_(balance_modes_[kSloppy]),
separate_first_(separate_first_modes_[kSloppy]),
hdr_info_(hdr_info)
{
part_info_.VerifyAndAllocateFragmentationHeader(1);
part_info_.fragmentationLength[0] = payload_size;
part_info_.fragmentationOffset[0] = 0;
}
int RtpFormatVp8::CalcNextSize(int max_payload_len, int remaining_bytes,
bool split_payload) const
{
if (max_payload_len == 0 || remaining_bytes == 0)
{
return 0;
}
if (!split_payload)
{
return max_payload_len >= remaining_bytes ? remaining_bytes : 0;
}
if (balance_)
{
// Balance payload sizes to produce (almost) equal size
// fragments.
// Number of fragments for remaining_bytes:
int num_frags = remaining_bytes / max_payload_len + 1;
// Number of bytes in this fragment:
return static_cast<int>(static_cast<double>(remaining_bytes)
/ num_frags + 0.5);
}
else
{
return max_payload_len >= remaining_bytes ? remaining_bytes
: max_payload_len;
}
}
int RtpFormatVp8::NextPacket(int max_payload_len, WebRtc_UWord8* buffer,
int* bytes_to_send, bool* last_packet)
{
const int num_partitions = part_info_.fragmentationVectorSize;
int send_bytes = 0; // How much data to send in this packet.
bool split_payload = true; // Splitting of partitions is initially allowed.
int remaining_in_partition = part_info_.fragmentationOffset[part_ix_] -
payload_bytes_sent_ + part_info_.fragmentationLength[part_ix_] +
FirstHeaderExtraLength(); // Add header extra length to payload length.
int rem_payload_len = max_payload_len - vp8_header_bytes_;
const int first_partition_in_packet = part_ix_;
while (int next_size = CalcNextSize(rem_payload_len, remaining_in_partition,
split_payload))
{
send_bytes += next_size;
rem_payload_len -= next_size;
remaining_in_partition -= next_size;
if (remaining_in_partition == 0 && !(beginning_ && separate_first_))
{
// Advance to next partition?
// Check that there are more partitions; verify that we are either
// allowed to aggregate fragments, or that we are allowed to
// aggregate intact partitions and that we started this packet
// with an intact partition (indicated by first_fragment_ == true).
if (part_ix_ + 1 < num_partitions &&
((aggr_mode_ == kAggrFragments) ||
(aggr_mode_ == kAggrPartitions && first_fragment_)))
{
remaining_in_partition
= part_info_.fragmentationLength[++part_ix_];
// Disallow splitting unless kAggrFragments. In kAggrPartitions,
// we can only aggregate intact partitions.
split_payload = (aggr_mode_ == kAggrFragments);
}
}
else if (balance_ && remaining_in_partition > 0)
{
break;
}
}
if (remaining_in_partition == 0)
{
++part_ix_; // Advance to next partition.
}
send_bytes -= FirstHeaderExtraLength(); // Remove the extra length again.
assert(send_bytes > 0);
const bool end_of_fragment = (remaining_in_partition == 0);
// Write the payload header and the payload to buffer.
*bytes_to_send = WriteHeaderAndPayload(send_bytes, end_of_fragment, buffer,
max_payload_len);
if (*bytes_to_send < 0)
{
return -1;
}
*last_packet = (payload_bytes_sent_ >= payload_size_);
assert(!*last_packet || (payload_bytes_sent_ == payload_size_));
return first_partition_in_packet;
}
int RtpFormatVp8::WriteHeaderAndPayload(int payload_bytes,
bool end_of_fragment,
WebRtc_UWord8* buffer,
int buffer_length)
{
// Write the VP8 payload header.
// 0 1 2
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | RSV |I|N|FI |B| PictureID (1 or 2 octets) |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
if (payload_bytes < 0)
{
return -1;
}
if (payload_bytes_sent_ + payload_bytes > payload_size_)
{
return -1;
}
buffer[0] = 0;
if (hdr_info_.nonReference) buffer[0] |= (0x01 << 3); // N
buffer[0] |= (GetFIFlag(end_of_fragment) << 1); // FI
if (beginning_) buffer[0] |= 0x01; // B
int pic_id_len = WritePictureID(&buffer[vp8_header_bytes_],
buffer_length - vp8_header_bytes_);
if (pic_id_len < 0) return pic_id_len; // error
if (pic_id_len > 0) buffer[0] |= (0x01 << 4); // I
if (vp8_header_bytes_ + pic_id_len + payload_bytes > buffer_length)
{
return -1;
}
memcpy(&buffer[vp8_header_bytes_ + pic_id_len],
&payload_data_[payload_bytes_sent_], payload_bytes);
beginning_ = false; // next packet cannot be first packet in frame
// next packet starts new fragment if this ended one
first_fragment_ = end_of_fragment;
payload_bytes_sent_ += payload_bytes;
// Return total length of written data.
return payload_bytes + vp8_header_bytes_ + pic_id_len;
}
int RtpFormatVp8::WritePictureID(WebRtc_UWord8* buffer, int buffer_length) const
{
const WebRtc_UWord16 pic_id =
static_cast<WebRtc_UWord16> (hdr_info_.pictureId);
int picture_id_len = PictureIdLength();
if (picture_id_len > buffer_length) return -1; // error
if (picture_id_len == 2)
{
buffer[0] = 0x80 | ((pic_id >> 8) & 0x7F);
buffer[1] = pic_id & 0xFF;
}
else if (picture_id_len == 1)
{
buffer[0] = pic_id & 0x7F;
}
return picture_id_len;
}
int RtpFormatVp8::FirstHeaderExtraLength() const
{
if (!beginning_)
{
return 0;
}
int length = 0;
length += PictureIdLength();
return length;
}
int RtpFormatVp8::PictureIdLength() const
{
if (!beginning_ || hdr_info_.pictureId == kNoPictureId)
{
return 0;
}
if (hdr_info_.pictureId <= 0x7F)
{
return 1;
}
else
{
return 2;
}
}
int RtpFormatVp8::GetFIFlag(bool end_of_fragment) const
{
if (first_fragment_ && end_of_fragment) {
return 0x0;
}
if (first_fragment_ && !end_of_fragment) {
return 0x1;
}
if (!first_fragment_ && !end_of_fragment) {
return 0x2;
}
// if (!first_fragment_ && end_of_fragment)
return 0x3;
}
} // namespace webrtc
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/gfx/color_utils.h"
#include "ui/gfx/sys_color_change_listener.h"
#if defined(OS_WIN)
#include <windows.h>
#endif
#include "base/basictypes.h"
#include "base/memory/singleton.h"
#include "base/observer_list.h"
#if defined(OS_WIN)
#include "ui/base/win/singleton_hwnd.h"
#endif
namespace gfx {
namespace {
bool g_is_inverted_color_scheme = false;
bool g_is_inverted_color_scheme_initialized = false;
void UpdateInvertedColorScheme() {
#if defined(OS_WIN)
int foreground = color_utils::GetLuminanceForColor(
color_utils::GetSysSkColor(COLOR_WINDOWTEXT));
int background = color_utils::GetLuminanceForColor(
color_utils::GetSysSkColor(COLOR_WINDOW));
HIGHCONTRAST high_contrast = {0};
high_contrast.cbSize = sizeof(HIGHCONTRAST);
g_is_inverted_color_scheme =
SystemParametersInfo(SPI_GETHIGHCONTRAST, 0, &high_contrast, 0) &&
((high_contrast.dwFlags & HCF_HIGHCONTRASTON) != 0);
g_is_inverted_color_scheme_initialized = true;
#endif
}
} // namespace
bool IsInvertedColorScheme() {
if (!g_is_inverted_color_scheme_initialized)
UpdateInvertedColorScheme();
return g_is_inverted_color_scheme;
}
#if defined(OS_WIN)
class SysColorChangeObserver : public ui::SingletonHwnd::Observer {
public:
static SysColorChangeObserver* GetInstance();
void AddListener(SysColorChangeListener* listener);
void RemoveListener(SysColorChangeListener* listener);
private:
friend struct DefaultSingletonTraits<SysColorChangeObserver>;
SysColorChangeObserver();
virtual ~SysColorChangeObserver();
virtual void OnWndProc(HWND hwnd,
UINT message,
WPARAM wparam,
LPARAM lparam) OVERRIDE;
ObserverList<SysColorChangeListener> listeners_;
};
// static
SysColorChangeObserver* SysColorChangeObserver::GetInstance() {
return Singleton<SysColorChangeObserver>::get();
}
SysColorChangeObserver::SysColorChangeObserver() {
ui::SingletonHwnd::GetInstance()->AddObserver(this);
}
SysColorChangeObserver::~SysColorChangeObserver() {
ui::SingletonHwnd::GetInstance()->RemoveObserver(this);
}
void SysColorChangeObserver::AddListener(SysColorChangeListener* listener) {
listeners_.AddObserver(listener);
}
void SysColorChangeObserver::RemoveListener(SysColorChangeListener* listener) {
listeners_.RemoveObserver(listener);
}
void SysColorChangeObserver::OnWndProc(HWND hwnd,
UINT message,
WPARAM wparam,
LPARAM lparam) {
if (message == WM_SYSCOLORCHANGE ||
(message == WM_SETTINGCHANGE && wparam == SPI_SETHIGHCONTRAST)) {
UpdateInvertedColorScheme();
FOR_EACH_OBSERVER(SysColorChangeListener, listeners_, OnSysColorChange());
}
}
#endif
ScopedSysColorChangeListener::ScopedSysColorChangeListener(
SysColorChangeListener* listener)
: listener_(listener) {
#if defined(OS_WIN)
SysColorChangeObserver::GetInstance()->AddListener(listener_);
#endif
}
ScopedSysColorChangeListener::~ScopedSysColorChangeListener() {
#if defined(OS_WIN)
SysColorChangeObserver::GetInstance()->RemoveListener(listener_);
#endif
}
} // namespace gfx
<commit_msg>Disable inverting web content when high-contrast mode is on.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/gfx/color_utils.h"
#include "ui/gfx/sys_color_change_listener.h"
#if defined(OS_WIN)
#include <windows.h>
#endif
#include "base/basictypes.h"
#include "base/memory/singleton.h"
#include "base/observer_list.h"
#if defined(OS_WIN)
#include "ui/base/win/singleton_hwnd.h"
#endif
namespace gfx {
namespace {
bool g_is_inverted_color_scheme = false;
bool g_is_inverted_color_scheme_initialized = false;
void UpdateInvertedColorScheme() {
#if defined(OS_WIN)
int foreground = color_utils::GetLuminanceForColor(
color_utils::GetSysSkColor(COLOR_WINDOWTEXT));
int background = color_utils::GetLuminanceForColor(
color_utils::GetSysSkColor(COLOR_WINDOW));
HIGHCONTRAST high_contrast = {0};
high_contrast.cbSize = sizeof(HIGHCONTRAST);
// TODO(dmazzoni): this is temporarily disabled until the color inverting
// can be made optional or the need is addressed some other way.
// http://crbug.com/112944
//g_is_inverted_color_scheme =
// SystemParametersInfo(SPI_GETHIGHCONTRAST, 0, &high_contrast, 0) &&
// ((high_contrast.dwFlags & HCF_HIGHCONTRASTON) != 0);
g_is_inverted_color_scheme_initialized = true;
#endif
}
} // namespace
bool IsInvertedColorScheme() {
if (!g_is_inverted_color_scheme_initialized)
UpdateInvertedColorScheme();
return g_is_inverted_color_scheme;
}
#if defined(OS_WIN)
class SysColorChangeObserver : public ui::SingletonHwnd::Observer {
public:
static SysColorChangeObserver* GetInstance();
void AddListener(SysColorChangeListener* listener);
void RemoveListener(SysColorChangeListener* listener);
private:
friend struct DefaultSingletonTraits<SysColorChangeObserver>;
SysColorChangeObserver();
virtual ~SysColorChangeObserver();
virtual void OnWndProc(HWND hwnd,
UINT message,
WPARAM wparam,
LPARAM lparam) OVERRIDE;
ObserverList<SysColorChangeListener> listeners_;
};
// static
SysColorChangeObserver* SysColorChangeObserver::GetInstance() {
return Singleton<SysColorChangeObserver>::get();
}
SysColorChangeObserver::SysColorChangeObserver() {
ui::SingletonHwnd::GetInstance()->AddObserver(this);
}
SysColorChangeObserver::~SysColorChangeObserver() {
ui::SingletonHwnd::GetInstance()->RemoveObserver(this);
}
void SysColorChangeObserver::AddListener(SysColorChangeListener* listener) {
listeners_.AddObserver(listener);
}
void SysColorChangeObserver::RemoveListener(SysColorChangeListener* listener) {
listeners_.RemoveObserver(listener);
}
void SysColorChangeObserver::OnWndProc(HWND hwnd,
UINT message,
WPARAM wparam,
LPARAM lparam) {
if (message == WM_SYSCOLORCHANGE ||
(message == WM_SETTINGCHANGE && wparam == SPI_SETHIGHCONTRAST)) {
UpdateInvertedColorScheme();
FOR_EACH_OBSERVER(SysColorChangeListener, listeners_, OnSysColorChange());
}
}
#endif
ScopedSysColorChangeListener::ScopedSysColorChangeListener(
SysColorChangeListener* listener)
: listener_(listener) {
#if defined(OS_WIN)
SysColorChangeObserver::GetInstance()->AddListener(listener_);
#endif
}
ScopedSysColorChangeListener::~ScopedSysColorChangeListener() {
#if defined(OS_WIN)
SysColorChangeObserver::GetInstance()->RemoveListener(listener_);
#endif
}
} // namespace gfx
<|endoftext|>
|
<commit_before>
// NetworkSingleton.cpp
// Implements the cNetworkSingleton class representing the storage for global data pertaining to network API
// such as a list of all connections, all listening sockets and the LibEvent dispatch thread.
#include "Globals.h"
#include "NetworkSingleton.h"
#include <event2/event.h>
#include <event2/thread.h>
#include <event2/bufferevent.h>
#include <event2/dns.h>
#include <event2/listener.h>
#include "IPLookup.h"
#include "HostnameLookup.h"
cNetworkSingleton::cNetworkSingleton(void):
m_HasTerminated(false)
{
// Windows: initialize networking:
#ifdef _WIN32
WSADATA wsaData;
memset(&wsaData, 0, sizeof(wsaData));
int res = WSAStartup (MAKEWORD(2, 2), &wsaData);
if (res != 0)
{
int err = WSAGetLastError();
LOGWARNING("WSAStartup failed: %d, WSAGLE = %d (%s)", res, err, evutil_socket_error_to_string(err));
exit(1);
}
#endif // _WIN32
// Initialize LibEvent logging:
event_set_log_callback(LogCallback);
// Initialize threading:
#if defined(EVTHREAD_USE_WINDOWS_THREADS_IMPLEMENTED)
evthread_use_windows_threads();
#elif defined(EVTHREAD_USE_PTHREADS_IMPLEMENTED)
evthread_use_pthreads();
#else
#error No threading implemented for EVTHREAD
#endif
// Create the main event_base:
m_EventBase = event_base_new();
if (m_EventBase == nullptr)
{
LOGERROR("Failed to initialize LibEvent. The server will now terminate.");
abort();
}
// Create the DNS lookup helper:
m_DNSBase = evdns_base_new(m_EventBase, 1);
if (m_DNSBase == nullptr)
{
LOGERROR("Failed to initialize LibEvent's DNS subsystem. The server will now terminate.");
abort();
}
// Create the event loop thread:
m_EventLoopThread = std::thread(RunEventLoop, this);
}
cNetworkSingleton::~cNetworkSingleton()
{
// Check that Terminate has been called already:
ASSERT(m_HasTerminated);
}
cNetworkSingleton & cNetworkSingleton::Get(void)
{
static cNetworkSingleton Instance;
return Instance;
}
void cNetworkSingleton::Terminate(void)
{
ASSERT(!m_HasTerminated);
m_HasTerminated = true;
// Wait for the LibEvent event loop to terminate:
event_base_loopbreak(m_EventBase);
m_EventLoopThread.join();
// Remove all objects:
{
cCSLock Lock(m_CS);
m_Connections.clear();
m_Servers.clear();
m_HostnameLookups.clear();
m_IPLookups.clear();
}
// Free the underlying LibEvent objects:
evdns_base_free(m_DNSBase, true);
event_base_free(m_EventBase);
libevent_global_shutdown();
}
void cNetworkSingleton::LogCallback(int a_Severity, const char * a_Msg)
{
switch (a_Severity)
{
case _EVENT_LOG_DEBUG: LOGD ("LibEvent: %s", a_Msg); break;
case _EVENT_LOG_MSG: LOG ("LibEvent: %s", a_Msg); break;
case _EVENT_LOG_WARN: LOGWARNING("LibEvent: %s", a_Msg); break;
case _EVENT_LOG_ERR: LOGERROR ("LibEvent: %s", a_Msg); break;
default:
{
LOGWARNING("LibEvent: Unknown log severity (%d): %s", a_Severity, a_Msg);
break;
}
}
}
void cNetworkSingleton::RunEventLoop(cNetworkSingleton * a_Self)
{
event_base_loop(a_Self->m_EventBase, EVLOOP_NO_EXIT_ON_EMPTY);
}
void cNetworkSingleton::AddHostnameLookup(cHostnameLookupPtr a_HostnameLookup)
{
ASSERT(!m_HasTerminated);
cCSLock Lock(m_CS);
m_HostnameLookups.push_back(a_HostnameLookup);
}
void cNetworkSingleton::RemoveHostnameLookup(const cHostnameLookup * a_HostnameLookup)
{
ASSERT(!m_HasTerminated);
cCSLock Lock(m_CS);
for (auto itr = m_HostnameLookups.begin(), end = m_HostnameLookups.end(); itr != end; ++itr)
{
if (itr->get() == a_HostnameLookup)
{
m_HostnameLookups.erase(itr);
return;
}
} // for itr - m_HostnameLookups[]
}
void cNetworkSingleton::AddIPLookup(cIPLookupPtr a_IPLookup)
{
ASSERT(!m_HasTerminated);
cCSLock Lock(m_CS);
m_IPLookups.push_back(a_IPLookup);
}
void cNetworkSingleton::RemoveIPLookup(const cIPLookup * a_IPLookup)
{
ASSERT(!m_HasTerminated);
cCSLock Lock(m_CS);
for (auto itr = m_IPLookups.begin(), end = m_IPLookups.end(); itr != end; ++itr)
{
if (itr->get() == a_IPLookup)
{
m_IPLookups.erase(itr);
return;
}
} // for itr - m_IPLookups[]
}
void cNetworkSingleton::AddLink(cTCPLinkImplPtr a_Link)
{
ASSERT(!m_HasTerminated);
cCSLock Lock(m_CS);
m_Connections.push_back(a_Link);
}
void cNetworkSingleton::RemoveLink(const cTCPLinkImpl * a_Link)
{
ASSERT(!m_HasTerminated);
cCSLock Lock(m_CS);
for (auto itr = m_Connections.begin(), end = m_Connections.end(); itr != end; ++itr)
{
if (itr->get() == a_Link)
{
m_Connections.erase(itr);
return;
}
} // for itr - m_Connections[]
}
void cNetworkSingleton::AddServer(cServerHandleImplPtr a_Server)
{
ASSERT(!m_HasTerminated);
cCSLock Lock(m_CS);
m_Servers.push_back(a_Server);
}
void cNetworkSingleton::RemoveServer(const cServerHandleImpl * a_Server)
{
ASSERT(!m_HasTerminated);
cCSLock Lock(m_CS);
for (auto itr = m_Servers.begin(), end = m_Servers.end(); itr != end; ++itr)
{
if (itr->get() == a_Server)
{
m_Servers.erase(itr);
return;
}
} // for itr - m_Servers[]
}
<commit_msg>Fixed cNetworkSingleton's HasTerminated flag.<commit_after>
// NetworkSingleton.cpp
// Implements the cNetworkSingleton class representing the storage for global data pertaining to network API
// such as a list of all connections, all listening sockets and the LibEvent dispatch thread.
#include "Globals.h"
#include "NetworkSingleton.h"
#include <event2/event.h>
#include <event2/thread.h>
#include <event2/bufferevent.h>
#include <event2/dns.h>
#include <event2/listener.h>
#include "IPLookup.h"
#include "HostnameLookup.h"
cNetworkSingleton::cNetworkSingleton(void):
m_HasTerminated(false)
{
// Windows: initialize networking:
#ifdef _WIN32
WSADATA wsaData;
memset(&wsaData, 0, sizeof(wsaData));
int res = WSAStartup (MAKEWORD(2, 2), &wsaData);
if (res != 0)
{
int err = WSAGetLastError();
LOGWARNING("WSAStartup failed: %d, WSAGLE = %d (%s)", res, err, evutil_socket_error_to_string(err));
exit(1);
}
#endif // _WIN32
// Initialize LibEvent logging:
event_set_log_callback(LogCallback);
// Initialize threading:
#if defined(EVTHREAD_USE_WINDOWS_THREADS_IMPLEMENTED)
evthread_use_windows_threads();
#elif defined(EVTHREAD_USE_PTHREADS_IMPLEMENTED)
evthread_use_pthreads();
#else
#error No threading implemented for EVTHREAD
#endif
// Create the main event_base:
m_EventBase = event_base_new();
if (m_EventBase == nullptr)
{
LOGERROR("Failed to initialize LibEvent. The server will now terminate.");
abort();
}
// Create the DNS lookup helper:
m_DNSBase = evdns_base_new(m_EventBase, 1);
if (m_DNSBase == nullptr)
{
LOGERROR("Failed to initialize LibEvent's DNS subsystem. The server will now terminate.");
abort();
}
// Create the event loop thread:
m_EventLoopThread = std::thread(RunEventLoop, this);
}
cNetworkSingleton::~cNetworkSingleton()
{
// Check that Terminate has been called already:
ASSERT(m_HasTerminated);
}
cNetworkSingleton & cNetworkSingleton::Get(void)
{
static cNetworkSingleton Instance;
return Instance;
}
void cNetworkSingleton::Terminate(void)
{
ASSERT(!m_HasTerminated);
// Wait for the LibEvent event loop to terminate:
event_base_loopbreak(m_EventBase);
m_EventLoopThread.join();
// Remove all objects:
{
cCSLock Lock(m_CS);
m_Connections.clear();
m_Servers.clear();
m_HostnameLookups.clear();
m_IPLookups.clear();
}
// Free the underlying LibEvent objects:
evdns_base_free(m_DNSBase, true);
event_base_free(m_EventBase);
libevent_global_shutdown();
// Set the HasTerminated flag:
// (Only set the flag after everything has been removed, to avoid the random failures in the Google-test, caused by links terminating after this flag was set)
m_HasTerminated = true;
}
void cNetworkSingleton::LogCallback(int a_Severity, const char * a_Msg)
{
switch (a_Severity)
{
case _EVENT_LOG_DEBUG: LOGD ("LibEvent: %s", a_Msg); break;
case _EVENT_LOG_MSG: LOG ("LibEvent: %s", a_Msg); break;
case _EVENT_LOG_WARN: LOGWARNING("LibEvent: %s", a_Msg); break;
case _EVENT_LOG_ERR: LOGERROR ("LibEvent: %s", a_Msg); break;
default:
{
LOGWARNING("LibEvent: Unknown log severity (%d): %s", a_Severity, a_Msg);
break;
}
}
}
void cNetworkSingleton::RunEventLoop(cNetworkSingleton * a_Self)
{
event_base_loop(a_Self->m_EventBase, EVLOOP_NO_EXIT_ON_EMPTY);
}
void cNetworkSingleton::AddHostnameLookup(cHostnameLookupPtr a_HostnameLookup)
{
ASSERT(!m_HasTerminated);
cCSLock Lock(m_CS);
m_HostnameLookups.push_back(a_HostnameLookup);
}
void cNetworkSingleton::RemoveHostnameLookup(const cHostnameLookup * a_HostnameLookup)
{
ASSERT(!m_HasTerminated);
cCSLock Lock(m_CS);
for (auto itr = m_HostnameLookups.begin(), end = m_HostnameLookups.end(); itr != end; ++itr)
{
if (itr->get() == a_HostnameLookup)
{
m_HostnameLookups.erase(itr);
return;
}
} // for itr - m_HostnameLookups[]
}
void cNetworkSingleton::AddIPLookup(cIPLookupPtr a_IPLookup)
{
ASSERT(!m_HasTerminated);
cCSLock Lock(m_CS);
m_IPLookups.push_back(a_IPLookup);
}
void cNetworkSingleton::RemoveIPLookup(const cIPLookup * a_IPLookup)
{
ASSERT(!m_HasTerminated);
cCSLock Lock(m_CS);
for (auto itr = m_IPLookups.begin(), end = m_IPLookups.end(); itr != end; ++itr)
{
if (itr->get() == a_IPLookup)
{
m_IPLookups.erase(itr);
return;
}
} // for itr - m_IPLookups[]
}
void cNetworkSingleton::AddLink(cTCPLinkImplPtr a_Link)
{
ASSERT(!m_HasTerminated);
cCSLock Lock(m_CS);
m_Connections.push_back(a_Link);
}
void cNetworkSingleton::RemoveLink(const cTCPLinkImpl * a_Link)
{
ASSERT(!m_HasTerminated);
cCSLock Lock(m_CS);
for (auto itr = m_Connections.begin(), end = m_Connections.end(); itr != end; ++itr)
{
if (itr->get() == a_Link)
{
m_Connections.erase(itr);
return;
}
} // for itr - m_Connections[]
}
void cNetworkSingleton::AddServer(cServerHandleImplPtr a_Server)
{
ASSERT(!m_HasTerminated);
cCSLock Lock(m_CS);
m_Servers.push_back(a_Server);
}
void cNetworkSingleton::RemoveServer(const cServerHandleImpl * a_Server)
{
ASSERT(!m_HasTerminated);
cCSLock Lock(m_CS);
for (auto itr = m_Servers.begin(), end = m_Servers.end(); itr != end; ++itr)
{
if (itr->get() == a_Server)
{
m_Servers.erase(itr);
return;
}
} // for itr - m_Servers[]
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2021 The Orbit 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 "GpuSubmissionTrack.h"
#include <absl/time/time.h>
#include <memory>
#include "App.h"
#include "Batcher.h"
#include "ClientData/TimerChain.h"
#include "DisplayFormats/DisplayFormats.h"
#include "GlUtils.h"
#include "OrbitBase/Logging.h"
#include "OrbitBase/ThreadConstants.h"
#include "TimeGraph.h"
#include "TimeGraphLayout.h"
#include "TriangleToggle.h"
#include "absl/strings/str_format.h"
#include "capture_data.pb.h"
using orbit_client_data::TimerChain;
using orbit_client_protos::TimerInfo;
constexpr const char* kSwQueueString = "sw queue";
constexpr const char* kHwQueueString = "hw queue";
constexpr const char* kHwExecutionString = "hw execution";
constexpr const char* kCmdBufferString = "command buffer";
GpuSubmissionTrack::GpuSubmissionTrack(Track* parent, TimeGraph* time_graph,
orbit_gl::Viewport* viewport, TimeGraphLayout* layout,
uint64_t timeline_hash, OrbitApp* app,
const orbit_client_data::CaptureData* capture_data)
: TimerTrack(parent, time_graph, viewport, layout, app, capture_data) {
draw_background_ = false;
text_renderer_ = time_graph->GetTextRenderer();
timeline_hash_ = timeline_hash;
string_manager_ = app->GetStringManager();
parent_ = parent;
}
std::string GpuSubmissionTrack::GetName() const {
return absl::StrFormat(
"%s_submissions",
string_manager_->Get(timeline_hash_).value_or(std::to_string(timeline_hash_)));
}
std::string GpuSubmissionTrack::GetTooltip() const {
return "Shows scheduling and execution times for selected GPU job "
"submissions";
}
void GpuSubmissionTrack::OnTimer(const orbit_client_protos::TimerInfo& timer_info) {
// In case of having command buffer timers, we need to double the depth of the GPU timers (as we
// are drawing the corresponding command buffer timers below them). Therefore, we watch out for
// those timers.
if (timer_info.type() == TimerInfo::kGpuCommandBuffer) {
has_vulkan_layer_command_buffer_timers_ = true;
}
TimerTrack::OnTimer(timer_info);
}
bool GpuSubmissionTrack::IsTimerActive(const TimerInfo& timer_info) const {
bool is_same_tid_as_selected = timer_info.thread_id() == app_->selected_thread_id();
// We do not properly track the PID for GPU jobs and we still want to show
// all jobs as active when no thread is selected, so this logic is a bit
// different than SchedulerTrack::IsTimerActive.
bool no_thread_selected = app_->selected_thread_id() == orbit_base::kAllProcessThreadsTid;
return is_same_tid_as_selected || no_thread_selected;
}
Color GpuSubmissionTrack::GetTimerColor(const TimerInfo& timer_info, bool is_selected,
bool is_highlighted) const {
const Color kInactiveColor(100, 100, 100, 255);
const Color kSelectionColor(0, 128, 255, 255);
if (is_highlighted) {
return TimerTrack::kHighlightColor;
}
if (is_selected) {
return kSelectionColor;
}
if (!IsTimerActive(timer_info)) {
return kInactiveColor;
}
if (timer_info.has_color()) {
CHECK(timer_info.color().red() < 256);
CHECK(timer_info.color().green() < 256);
CHECK(timer_info.color().blue() < 256);
CHECK(timer_info.color().alpha() < 256);
return Color(static_cast<uint8_t>(timer_info.color().red()),
static_cast<uint8_t>(timer_info.color().green()),
static_cast<uint8_t>(timer_info.color().blue()),
static_cast<uint8_t>(timer_info.color().alpha()));
}
// We color code the timeslices for GPU activity using the color
// of the CPU thread track that submitted the job.
Color color = TimeGraph::GetThreadColor(timer_info.thread_id());
// We disambiguate the different types of GPU activity based on the
// string that is displayed on their timeslice.
float coeff = 1.0f;
std::string gpu_stage = string_manager_->Get(timer_info.user_data_key()).value_or("");
if (gpu_stage == kSwQueueString) {
coeff = 0.5f;
} else if (gpu_stage == kHwQueueString) {
coeff = 0.75f;
} else if (gpu_stage == kHwExecutionString) {
coeff = 1.0f;
}
color[0] = static_cast<uint8_t>(coeff * color[0]);
color[1] = static_cast<uint8_t>(coeff * color[1]);
color[2] = static_cast<uint8_t>(coeff * color[2]);
constexpr uint8_t kOddAlpha = 210;
if ((timer_info.depth() & 0x1) == 0u) {
color[3] = kOddAlpha;
}
return color;
}
float GpuSubmissionTrack::GetYFromTimer(const TimerInfo& timer_info) const {
auto adjusted_depth = static_cast<float>(timer_info.depth());
if (IsCollapsed()) {
adjusted_depth = 0.f;
}
CHECK(timer_info.type() == TimerInfo::kGpuActivity ||
timer_info.type() == TimerInfo::kGpuCommandBuffer);
// We are drawing a small gap between each depth, for visualization purposes.
// There won't be a gap between "hw execution"timers and command buffer timers, which
// is why the gap space needs to be calculated before adjusting the depth further (see below).
float gap_space = adjusted_depth * layout_->GetSpaceBetweenGpuDepths();
// Command buffer timers are drawn underneath the matching "hw execution" timer, which has the
// same depth value as the command buffer timer. Therefore, we need to double the depth in the
// case that we have command buffer timers.
if (has_vulkan_layer_command_buffer_timers_) {
adjusted_depth *= 2.f;
}
// Command buffer timers have the same depth value as their matching "hw execution" timer.
// As we want to draw command buffers underneath the hw execution timers, we need to increase
// the depth by one.
if (timer_info.type() == TimerInfo::kGpuCommandBuffer) {
adjusted_depth += 1.f;
}
return pos_[1] - layout_->GetTrackTabHeight() -
layout_->GetTextBoxHeight() * (adjusted_depth + 1.f) - gap_space;
}
// When track or its parent is collapsed, only draw "hardware execution" timers.
bool GpuSubmissionTrack::TimerFilter(const TimerInfo& timer_info) const {
if (IsCollapsed()) {
std::string gpu_stage = string_manager_->Get(timer_info.user_data_key()).value_or("");
return gpu_stage == kHwExecutionString;
}
return true;
}
std::string GpuSubmissionTrack::GetTimesliceText(const TimerInfo& timer_info) const {
CHECK(timer_info.type() == TimerInfo::kGpuActivity ||
timer_info.type() == TimerInfo::kGpuCommandBuffer);
std::string time = GetDisplayTime(timer_info);
return absl::StrFormat("%s %s", string_manager_->Get(timer_info.user_data_key()).value_or(""),
time);
}
float GpuSubmissionTrack::GetHeight() const {
bool collapsed = IsCollapsed();
uint32_t depth = collapsed ? 1 : GetDepth();
uint32_t num_gaps = depth > 0 ? depth - 1 : 0;
if (has_vulkan_layer_command_buffer_timers_ && !collapsed) {
depth *= 2;
}
return layout_->GetTrackTabHeight() + layout_->GetTextBoxHeight() * depth +
(num_gaps * layout_->GetSpaceBetweenGpuDepths()) + layout_->GetTrackBottomMargin();
}
const TimerInfo* GpuSubmissionTrack::GetLeft(const TimerInfo& timer_info) const {
uint64_t timeline_hash = timer_info.user_data_key();
if (timeline_hash == timeline_hash_) {
const TimerChain* chain = track_data_->GetChain(timer_info.depth());
if (chain != nullptr) return chain->GetElementBefore(timer_info);
}
return nullptr;
}
const TimerInfo* GpuSubmissionTrack::GetRight(const TimerInfo& timer_info) const {
uint64_t timeline_hash = timer_info.user_data_key();
if (timeline_hash == timeline_hash_) {
const TimerChain* chain = track_data_->GetChain(timer_info.depth());
if (chain != nullptr) return chain->GetElementAfter(timer_info);
}
return nullptr;
}
std::string GpuSubmissionTrack::GetBoxTooltip(const Batcher& batcher, PickingId id) const {
const TimerInfo* timer_info = batcher.GetTimerInfo(id);
if ((timer_info == nullptr) || timer_info->type() == TimerInfo::kCoreActivity) {
return "";
}
std::string gpu_stage = string_manager_->Get(timer_info->user_data_key()).value_or("");
if (gpu_stage == kSwQueueString) {
return GetSwQueueTooltip(*timer_info);
}
if (gpu_stage == kHwQueueString) {
return GetHwQueueTooltip(*timer_info);
}
if (gpu_stage == kHwExecutionString) {
return GetHwExecutionTooltip(*timer_info);
}
if (gpu_stage == kCmdBufferString) {
return GetCommandBufferTooltip(*timer_info);
}
return "";
}
std::string GpuSubmissionTrack::GetSwQueueTooltip(const TimerInfo& timer_info) const {
CHECK(capture_data_ != nullptr);
return absl::StrFormat(
"<b>Software Queue</b><br/>"
"<i>Time between amdgpu_cs_ioctl (job submitted) and "
"amdgpu_sched_run_job (job scheduled)</i>"
"<br/>"
"<br/>"
"<b>Submitted from process:</b> %s [%d]<br/>"
"<b>Submitted from thread:</b> %s [%d]<br/>"
"<b>Time:</b> %s",
capture_data_->GetThreadName(timer_info.process_id()), timer_info.process_id(),
capture_data_->GetThreadName(timer_info.thread_id()), timer_info.thread_id(),
orbit_display_formats::GetDisplayTime(TicksToDuration(timer_info.start(), timer_info.end()))
.c_str());
}
std::string GpuSubmissionTrack::GetHwQueueTooltip(const TimerInfo& timer_info) const {
CHECK(capture_data_ != nullptr);
return absl::StrFormat(
"<b>Hardware Queue</b><br/><i>Time between amdgpu_sched_run_job "
"(job scheduled) and start of GPU execution</i>"
"<br/>"
"<br/>"
"<b>Submitted from process:</b> %s [%d]<br/>"
"<b>Submitted from thread:</b> %s [%d]<br/>"
"<b>Time:</b> %s",
capture_data_->GetThreadName(timer_info.process_id()), timer_info.process_id(),
capture_data_->GetThreadName(timer_info.thread_id()), timer_info.thread_id(),
orbit_display_formats::GetDisplayTime(TicksToDuration(timer_info.start(), timer_info.end()))
.c_str());
}
std::string GpuSubmissionTrack::GetHwExecutionTooltip(const TimerInfo& timer_info) const {
CHECK(capture_data_ != nullptr);
return absl::StrFormat(
"<b>Harware Execution</b><br/>"
"<i>End is marked by \"dma_fence_signaled\" event for this command "
"buffer submission</i>"
"<br/>"
"<br/>"
"<b>Submitted from process:</b> %s [%d]<br/>"
"<b>Submitted from thread:</b> %s [%d]<br/>"
"<b>Time:</b> %s",
capture_data_->GetThreadName(timer_info.process_id()), timer_info.process_id(),
capture_data_->GetThreadName(timer_info.thread_id()), timer_info.thread_id(),
orbit_display_formats::GetDisplayTime(TicksToDuration(timer_info.start(), timer_info.end()))
.c_str());
}
std::string GpuSubmissionTrack::GetCommandBufferTooltip(
const orbit_client_protos::TimerInfo& timer_info) const {
return absl::StrFormat(
"<b>Command Buffer Execution</b><br/>"
"<i>At `vkBeginCommandBuffer` and `vkEndCommandBuffer` `vkCmdWriteTimestamp`s have been "
"inserted. The GPU timestamps get aligned with the corresponding hardware execution of the "
"submission.</i>"
"<br/>"
"<br/>"
"<b>Submitted from process:</b> %s [%d]<br/>"
"<b>Submitted from thread:</b> %s [%d]<br/>"
"<b>Time:</b> %s",
capture_data_->GetThreadName(timer_info.process_id()), timer_info.process_id(),
capture_data_->GetThreadName(timer_info.thread_id()), timer_info.thread_id(),
orbit_display_formats::GetDisplayTime(TicksToDuration(timer_info.start(), timer_info.end()))
.c_str());
}
<commit_msg>Fix GetLeft/Right in GPUSubmissionTrack<commit_after>// Copyright (c) 2021 The Orbit 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 "GpuSubmissionTrack.h"
#include <absl/time/time.h>
#include <memory>
#include "App.h"
#include "Batcher.h"
#include "ClientData/TimerChain.h"
#include "DisplayFormats/DisplayFormats.h"
#include "GlUtils.h"
#include "OrbitBase/Logging.h"
#include "OrbitBase/ThreadConstants.h"
#include "TimeGraph.h"
#include "TimeGraphLayout.h"
#include "TriangleToggle.h"
#include "absl/strings/str_format.h"
#include "capture_data.pb.h"
using orbit_client_data::TimerChain;
using orbit_client_protos::TimerInfo;
constexpr const char* kSwQueueString = "sw queue";
constexpr const char* kHwQueueString = "hw queue";
constexpr const char* kHwExecutionString = "hw execution";
constexpr const char* kCmdBufferString = "command buffer";
GpuSubmissionTrack::GpuSubmissionTrack(Track* parent, TimeGraph* time_graph,
orbit_gl::Viewport* viewport, TimeGraphLayout* layout,
uint64_t timeline_hash, OrbitApp* app,
const orbit_client_data::CaptureData* capture_data)
: TimerTrack(parent, time_graph, viewport, layout, app, capture_data) {
draw_background_ = false;
text_renderer_ = time_graph->GetTextRenderer();
timeline_hash_ = timeline_hash;
string_manager_ = app->GetStringManager();
parent_ = parent;
}
std::string GpuSubmissionTrack::GetName() const {
return absl::StrFormat(
"%s_submissions",
string_manager_->Get(timeline_hash_).value_or(std::to_string(timeline_hash_)));
}
std::string GpuSubmissionTrack::GetTooltip() const {
return "Shows scheduling and execution times for selected GPU job "
"submissions";
}
void GpuSubmissionTrack::OnTimer(const orbit_client_protos::TimerInfo& timer_info) {
// In case of having command buffer timers, we need to double the depth of the GPU timers (as we
// are drawing the corresponding command buffer timers below them). Therefore, we watch out for
// those timers.
if (timer_info.type() == TimerInfo::kGpuCommandBuffer) {
has_vulkan_layer_command_buffer_timers_ = true;
}
TimerTrack::OnTimer(timer_info);
}
bool GpuSubmissionTrack::IsTimerActive(const TimerInfo& timer_info) const {
bool is_same_tid_as_selected = timer_info.thread_id() == app_->selected_thread_id();
// We do not properly track the PID for GPU jobs and we still want to show
// all jobs as active when no thread is selected, so this logic is a bit
// different than SchedulerTrack::IsTimerActive.
bool no_thread_selected = app_->selected_thread_id() == orbit_base::kAllProcessThreadsTid;
return is_same_tid_as_selected || no_thread_selected;
}
Color GpuSubmissionTrack::GetTimerColor(const TimerInfo& timer_info, bool is_selected,
bool is_highlighted) const {
const Color kInactiveColor(100, 100, 100, 255);
const Color kSelectionColor(0, 128, 255, 255);
if (is_highlighted) {
return TimerTrack::kHighlightColor;
}
if (is_selected) {
return kSelectionColor;
}
if (!IsTimerActive(timer_info)) {
return kInactiveColor;
}
if (timer_info.has_color()) {
CHECK(timer_info.color().red() < 256);
CHECK(timer_info.color().green() < 256);
CHECK(timer_info.color().blue() < 256);
CHECK(timer_info.color().alpha() < 256);
return Color(static_cast<uint8_t>(timer_info.color().red()),
static_cast<uint8_t>(timer_info.color().green()),
static_cast<uint8_t>(timer_info.color().blue()),
static_cast<uint8_t>(timer_info.color().alpha()));
}
// We color code the timeslices for GPU activity using the color
// of the CPU thread track that submitted the job.
Color color = TimeGraph::GetThreadColor(timer_info.thread_id());
// We disambiguate the different types of GPU activity based on the
// string that is displayed on their timeslice.
float coeff = 1.0f;
std::string gpu_stage = string_manager_->Get(timer_info.user_data_key()).value_or("");
if (gpu_stage == kSwQueueString) {
coeff = 0.5f;
} else if (gpu_stage == kHwQueueString) {
coeff = 0.75f;
} else if (gpu_stage == kHwExecutionString) {
coeff = 1.0f;
}
color[0] = static_cast<uint8_t>(coeff * color[0]);
color[1] = static_cast<uint8_t>(coeff * color[1]);
color[2] = static_cast<uint8_t>(coeff * color[2]);
constexpr uint8_t kOddAlpha = 210;
if ((timer_info.depth() & 0x1) == 0u) {
color[3] = kOddAlpha;
}
return color;
}
float GpuSubmissionTrack::GetYFromTimer(const TimerInfo& timer_info) const {
auto adjusted_depth = static_cast<float>(timer_info.depth());
if (IsCollapsed()) {
adjusted_depth = 0.f;
}
CHECK(timer_info.type() == TimerInfo::kGpuActivity ||
timer_info.type() == TimerInfo::kGpuCommandBuffer);
// We are drawing a small gap between each depth, for visualization purposes.
// There won't be a gap between "hw execution"timers and command buffer timers, which
// is why the gap space needs to be calculated before adjusting the depth further (see below).
float gap_space = adjusted_depth * layout_->GetSpaceBetweenGpuDepths();
// Command buffer timers are drawn underneath the matching "hw execution" timer, which has the
// same depth value as the command buffer timer. Therefore, we need to double the depth in the
// case that we have command buffer timers.
if (has_vulkan_layer_command_buffer_timers_) {
adjusted_depth *= 2.f;
}
// Command buffer timers have the same depth value as their matching "hw execution" timer.
// As we want to draw command buffers underneath the hw execution timers, we need to increase
// the depth by one.
if (timer_info.type() == TimerInfo::kGpuCommandBuffer) {
adjusted_depth += 1.f;
}
return pos_[1] - layout_->GetTrackTabHeight() -
layout_->GetTextBoxHeight() * (adjusted_depth + 1.f) - gap_space;
}
// When track or its parent is collapsed, only draw "hardware execution" timers.
bool GpuSubmissionTrack::TimerFilter(const TimerInfo& timer_info) const {
if (IsCollapsed()) {
std::string gpu_stage = string_manager_->Get(timer_info.user_data_key()).value_or("");
return gpu_stage == kHwExecutionString;
}
return true;
}
std::string GpuSubmissionTrack::GetTimesliceText(const TimerInfo& timer_info) const {
CHECK(timer_info.type() == TimerInfo::kGpuActivity ||
timer_info.type() == TimerInfo::kGpuCommandBuffer);
std::string time = GetDisplayTime(timer_info);
return absl::StrFormat("%s %s", string_manager_->Get(timer_info.user_data_key()).value_or(""),
time);
}
float GpuSubmissionTrack::GetHeight() const {
bool collapsed = IsCollapsed();
uint32_t depth = collapsed ? 1 : GetDepth();
uint32_t num_gaps = depth > 0 ? depth - 1 : 0;
if (has_vulkan_layer_command_buffer_timers_ && !collapsed) {
depth *= 2;
}
return layout_->GetTrackTabHeight() + layout_->GetTextBoxHeight() * depth +
(num_gaps * layout_->GetSpaceBetweenGpuDepths()) + layout_->GetTrackBottomMargin();
}
const TimerInfo* GpuSubmissionTrack::GetLeft(const TimerInfo& timer_info) const {
if (timer_info.timeline_hash() == timeline_hash_) {
const TimerChain* chain = track_data_->GetChain(timer_info.depth());
if (chain != nullptr) return chain->GetElementBefore(timer_info);
}
return nullptr;
}
const TimerInfo* GpuSubmissionTrack::GetRight(const TimerInfo& timer_info) const {
if (timer_info.timeline_hash() == timeline_hash_) {
const TimerChain* chain = track_data_->GetChain(timer_info.depth());
if (chain != nullptr) return chain->GetElementAfter(timer_info);
}
return nullptr;
}
std::string GpuSubmissionTrack::GetBoxTooltip(const Batcher& batcher, PickingId id) const {
const TimerInfo* timer_info = batcher.GetTimerInfo(id);
if ((timer_info == nullptr) || timer_info->type() == TimerInfo::kCoreActivity) {
return "";
}
std::string gpu_stage = string_manager_->Get(timer_info->user_data_key()).value_or("");
if (gpu_stage == kSwQueueString) {
return GetSwQueueTooltip(*timer_info);
}
if (gpu_stage == kHwQueueString) {
return GetHwQueueTooltip(*timer_info);
}
if (gpu_stage == kHwExecutionString) {
return GetHwExecutionTooltip(*timer_info);
}
if (gpu_stage == kCmdBufferString) {
return GetCommandBufferTooltip(*timer_info);
}
return "";
}
std::string GpuSubmissionTrack::GetSwQueueTooltip(const TimerInfo& timer_info) const {
CHECK(capture_data_ != nullptr);
return absl::StrFormat(
"<b>Software Queue</b><br/>"
"<i>Time between amdgpu_cs_ioctl (job submitted) and "
"amdgpu_sched_run_job (job scheduled)</i>"
"<br/>"
"<br/>"
"<b>Submitted from process:</b> %s [%d]<br/>"
"<b>Submitted from thread:</b> %s [%d]<br/>"
"<b>Time:</b> %s",
capture_data_->GetThreadName(timer_info.process_id()), timer_info.process_id(),
capture_data_->GetThreadName(timer_info.thread_id()), timer_info.thread_id(),
orbit_display_formats::GetDisplayTime(TicksToDuration(timer_info.start(), timer_info.end()))
.c_str());
}
std::string GpuSubmissionTrack::GetHwQueueTooltip(const TimerInfo& timer_info) const {
CHECK(capture_data_ != nullptr);
return absl::StrFormat(
"<b>Hardware Queue</b><br/><i>Time between amdgpu_sched_run_job "
"(job scheduled) and start of GPU execution</i>"
"<br/>"
"<br/>"
"<b>Submitted from process:</b> %s [%d]<br/>"
"<b>Submitted from thread:</b> %s [%d]<br/>"
"<b>Time:</b> %s",
capture_data_->GetThreadName(timer_info.process_id()), timer_info.process_id(),
capture_data_->GetThreadName(timer_info.thread_id()), timer_info.thread_id(),
orbit_display_formats::GetDisplayTime(TicksToDuration(timer_info.start(), timer_info.end()))
.c_str());
}
std::string GpuSubmissionTrack::GetHwExecutionTooltip(const TimerInfo& timer_info) const {
CHECK(capture_data_ != nullptr);
return absl::StrFormat(
"<b>Harware Execution</b><br/>"
"<i>End is marked by \"dma_fence_signaled\" event for this command "
"buffer submission</i>"
"<br/>"
"<br/>"
"<b>Submitted from process:</b> %s [%d]<br/>"
"<b>Submitted from thread:</b> %s [%d]<br/>"
"<b>Time:</b> %s",
capture_data_->GetThreadName(timer_info.process_id()), timer_info.process_id(),
capture_data_->GetThreadName(timer_info.thread_id()), timer_info.thread_id(),
orbit_display_formats::GetDisplayTime(TicksToDuration(timer_info.start(), timer_info.end()))
.c_str());
}
std::string GpuSubmissionTrack::GetCommandBufferTooltip(
const orbit_client_protos::TimerInfo& timer_info) const {
return absl::StrFormat(
"<b>Command Buffer Execution</b><br/>"
"<i>At `vkBeginCommandBuffer` and `vkEndCommandBuffer` `vkCmdWriteTimestamp`s have been "
"inserted. The GPU timestamps get aligned with the corresponding hardware execution of the "
"submission.</i>"
"<br/>"
"<br/>"
"<b>Submitted from process:</b> %s [%d]<br/>"
"<b>Submitted from thread:</b> %s [%d]<br/>"
"<b>Time:</b> %s",
capture_data_->GetThreadName(timer_info.process_id()), timer_info.process_id(),
capture_data_->GetThreadName(timer_info.thread_id()), timer_info.thread_id(),
orbit_display_formats::GetDisplayTime(TicksToDuration(timer_info.start(), timer_info.end()))
.c_str());
}
<|endoftext|>
|
<commit_before>// https://oj.leetcode.com/problems/word-break/
namespace WordBreak {
class Solution {
public:
bool wordBreak(string s, unordered_set<string> &dict) {
if (s.length() == 0) {
return true;
}
if (dict.size() == 0) {
return false;
}
// 1. find the words in dict with min and max length
unordered_set<string>::const_iterator it = dict.begin();
int minLen = INT_MAX;
int maxLen = INT_MIN;
for (; it != dict.end(); it++) {
int len = (*it).length();
if (len < minLen) {
minLen = len;
}
if (len > maxLen) {
maxLen = len;
}
}
// 2. run dp
bool * dp = new bool[s.length() + 1];
memset(dp, 0, sizeof(bool) * (s.length() + 1));
dp[0] = true;
for (int i = 1; i <= s.length() - minLen + 1; i++) {
if (dp[i - 1]) {
for (int len = minLen; len <= maxLen; len++) {
int endPos = i + len - 1;
if (endPos > s.length()) {
break;
}
if (dp[endPos] == true) {
continue;
}
string str = s.substr(i - 1, len);
if (dict.find(str) != dict.end()) {
dp[endPos] = true;
continue;
}
}
}
}
return dp[s.length()];
}
};
}
<commit_msg>Update WordBreak.cc<commit_after>// https://oj.leetcode.com/problems/word-break/
namespace WordBreak {
class Solution {
public:
pair<int, int> findMinLenAndMaxLen(unordered_set<string> &dict) {
int minLen = INT_MAX;
int maxLen = INT_MIN;
for (unordered_set<string>::iterator it = dict.begin(); it != dict.end(); it++) {
const string & cur = *it;
minLen = min((int)cur.size(), minLen);
maxLen = max((int)cur.size(), maxLen);
}
return make_pair(minLen, maxLen);
}
bool wordBreak(string s, unordered_set<string> &dict) {
if (s.empty()) return false;
if (dict.empty()) return false;
pair<int, int> m = findMinLenAndMaxLen(dict);
int minLen = m.first;
int maxLen = m.second;
vector<bool> dp = vector<bool>(s.size() + 1, false);
dp[0] = true;
for (int i = 1; i <= s.size(); i++) {
if (!dp[i - 1]) continue;
for (int len = minLen; len <= maxLen; len++) {
if (i + len - 1 > s.size()) break;
string cur = s.substr(i - 1, len);
if (dict.find(cur) != dict.end()) {
dp[i + len - 1] = true;
}
}
}
return dp[s.size()];
}
};
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/common/math/mpc_solver.h"
#include <algorithm>
#include <memory>
#include "modules/common/log.h"
#include "modules/common/math/qp_solver/active_set_qp_solver.h"
#include "modules/common/math/qp_solver/qp_solver.h"
namespace apollo {
namespace common {
namespace math {
using Matrix = Eigen::MatrixXd;
// discrete linear predictive control solver, with control format
// x(i + 1) = A * x(i) + B * u (i) + C
bool SolveLinearMPC(const Matrix &matrix_a, const Matrix &matrix_b,
const Matrix &matrix_c, const Matrix &matrix_q,
const Matrix &matrix_r, const Matrix &matrix_lower,
const Matrix &matrix_upper,
const Matrix &matrix_initial_state,
const std::vector<Matrix> &reference, const double eps,
const int max_iter, std::vector<Matrix> *control) {
if (matrix_a.rows() != matrix_a.cols() ||
matrix_b.rows() != matrix_a.rows() ||
matrix_lower.rows() != matrix_upper.rows()) {
AERROR << "One or more matrices have incompatible dimensions. Aborting.";
return false;
}
unsigned int horizon = reference.size();
// Update augment reference matrix_t
Matrix matrix_t = Matrix::Zero(matrix_b.rows() * horizon, 1);
for (unsigned int j = 0; j < horizon; ++j) {
matrix_t.block(j * reference[0].size(), 0, reference[0].size(), 1) =
reference[j];
}
// Update augment control matrix_v
Matrix matrix_v = Matrix::Zero((*control)[0].rows() * horizon, 1);
for (unsigned int j = 0; j < horizon; ++j) {
matrix_v.block(j * (*control)[0].rows(), 0, (*control)[0].rows(), 1) =
(*control)[j];
}
std::vector<Matrix> matrix_a_power(horizon);
matrix_a_power[0] = matrix_a;
for (unsigned int i = 1; i < matrix_a_power.size(); ++i) {
matrix_a_power[i] = matrix_a * matrix_a_power[i - 1];
}
Matrix matrix_k =
Matrix::Zero(matrix_b.rows() * horizon, matrix_b.cols() * horizon);
for (unsigned int r = 0; r < horizon; ++r) {
for (unsigned int c = 0; c <= r; ++c) {
matrix_k.block(r * matrix_b.rows(), c * matrix_b.cols(), matrix_b.rows(),
matrix_b.cols()) = matrix_a_power[r - c] * matrix_b;
}
}
// Initialize matrix_k, matrix_m, matrix_t and matrix_v, matrix_qq, matrix_rr,
// vector of matrix A power
Matrix matrix_m = Matrix::Zero(matrix_b.rows() * horizon, 1);
Matrix matrix_qq = Matrix::Zero(matrix_k.rows(), matrix_k.rows());
Matrix matrix_rr = Matrix::Zero(matrix_k.cols(), matrix_k.cols());
Matrix matrix_ll = Matrix::Zero(horizon * matrix_lower.rows(), 1);
Matrix matrix_uu = Matrix::Zero(horizon * matrix_upper.rows(), 1);
// Compute matrix_m
matrix_m.block(0, 0, matrix_a.rows(), 1) =
matrix_a * matrix_initial_state + matrix_c;
for (unsigned int i = 1; i < horizon; ++i) {
matrix_m.block(i * matrix_a.rows(), 0, matrix_a.rows(), 1) =
matrix_a *
matrix_m.block((i - 1) * matrix_a.rows(), 0, matrix_a.rows(), 1) +
matrix_c;
}
// Compute matrix_ll, matrix_uu, matrix_qq, matrix_rr
for (unsigned int i = 0; i < horizon; ++i) {
matrix_ll.block(i * (*control)[0].rows(), 0, (*control)[0].rows(), 1) =
matrix_lower;
matrix_uu.block(i * (*control)[0].rows(), 0, (*control)[0].rows(), 1) =
matrix_upper;
matrix_qq.block(i * matrix_q.rows(), i * matrix_q.rows(), matrix_q.rows(),
matrix_q.rows()) = matrix_q;
matrix_rr.block(i * matrix_r.rows(), i * matrix_r.rows(), matrix_r.cols(),
matrix_r.cols()) = matrix_r;
}
// Update matrix_m1, matrix_m2, convert MPC problem to QP problem done
Matrix matrix_m1 = matrix_k.transpose() * matrix_qq * matrix_k + matrix_rr;
Matrix matrix_m2 = matrix_k.transpose() * matrix_qq * (matrix_m - matrix_t);
// Format in qp_solver
/**
* * min_x : q(x) = 0.5 * x^T * Q * x + x^T c
* * with respect to: A * x = b (equality constraint)
* * C * x >= d (inequality constraint)
* **/
// TODO(QiL) : change qp solver to box constraint or substitue QPOAESE
// Method 1: QPOASES
Matrix matrix_inequality_constrain_ll =
Matrix::Identity(matrix_ll.rows(), matrix_ll.rows());
Matrix matrix_inequality_constrain_uu =
Matrix::Identity(matrix_uu.rows(), matrix_uu.rows());
Matrix matrix_inequality_constrain =
Matrix::Zero(matrix_ll.rows() + matrix_uu.rows(), matrix_ll.rows());
matrix_inequality_constrain << matrix_inequality_constrain_ll,
-matrix_inequality_constrain_uu;
Matrix matrix_inequality_boundary =
Matrix::Zero(matrix_ll.rows() + matrix_uu.rows(), matrix_ll.cols());
matrix_inequality_boundary << matrix_ll, -matrix_uu;
Matrix matrix_equality_constrain =
Matrix::Zero(matrix_ll.rows() + matrix_uu.rows(), matrix_ll.rows());
Matrix matrix_equality_boundary =
Matrix::Zero(matrix_ll.rows() + matrix_uu.rows(), matrix_ll.cols());
std::unique_ptr<QpSolver> qp_solver(new ActiveSetQpSolver(
matrix_m1, matrix_m2, matrix_inequality_constrain,
matrix_inequality_boundary, matrix_equality_constrain,
matrix_equality_boundary));
auto result = qp_solver->Solve();
if (!result) {
AERROR << "Linear MPC solver failed";
return false;
}
matrix_v = qp_solver->params();
for (unsigned int i = 0; i < horizon; ++i) {
(*control)[i] =
matrix_v.block(i * (*control)[0].rows(), 0, (*control)[0].rows(), 1);
}
return true;
}
} // namespace math
} // namespace common
} // namespace apollo
<commit_msg>Common : Fix typo<commit_after>/******************************************************************************
* Copyright 2017 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/common/math/mpc_solver.h"
#include <algorithm>
#include <memory>
#include "modules/common/log.h"
#include "modules/common/math/qp_solver/active_set_qp_solver.h"
#include "modules/common/math/qp_solver/qp_solver.h"
namespace apollo {
namespace common {
namespace math {
using Matrix = Eigen::MatrixXd;
// discrete linear predictive control solver, with control format
// x(i + 1) = A * x(i) + B * u (i) + C
bool SolveLinearMPC(const Matrix &matrix_a, const Matrix &matrix_b,
const Matrix &matrix_c, const Matrix &matrix_q,
const Matrix &matrix_r, const Matrix &matrix_lower,
const Matrix &matrix_upper,
const Matrix &matrix_initial_state,
const std::vector<Matrix> &reference, const double eps,
const int max_iter, std::vector<Matrix> *control) {
if (matrix_a.rows() != matrix_a.cols() ||
matrix_b.rows() != matrix_a.rows() ||
matrix_lower.rows() != matrix_upper.rows()) {
AERROR << "One or more matrices have incompatible dimensions. Aborting.";
return false;
}
unsigned int horizon = reference.size();
// Update augment reference matrix_t
Matrix matrix_t = Matrix::Zero(matrix_b.rows() * horizon, 1);
for (unsigned int j = 0; j < horizon; ++j) {
matrix_t.block(j * reference[0].size(), 0, reference[0].size(), 1) =
reference[j];
}
// Update augment control matrix_v
Matrix matrix_v = Matrix::Zero((*control)[0].rows() * horizon, 1);
for (unsigned int j = 0; j < horizon; ++j) {
matrix_v.block(j * (*control)[0].rows(), 0, (*control)[0].rows(), 1) =
(*control)[j];
}
std::vector<Matrix> matrix_a_power(horizon);
matrix_a_power[0] = matrix_a;
for (unsigned int i = 1; i < matrix_a_power.size(); ++i) {
matrix_a_power[i] = matrix_a * matrix_a_power[i - 1];
}
Matrix matrix_k =
Matrix::Zero(matrix_b.rows() * horizon, matrix_b.cols() * horizon);
for (unsigned int r = 0; r < horizon; ++r) {
for (unsigned int c = 0; c <= r; ++c) {
matrix_k.block(r * matrix_b.rows(), c * matrix_b.cols(), matrix_b.rows(),
matrix_b.cols()) = matrix_a_power[r - c] * matrix_b;
}
}
// Initialize matrix_k, matrix_m, matrix_t and matrix_v, matrix_qq, matrix_rr,
// vector of matrix A power
Matrix matrix_m = Matrix::Zero(matrix_b.rows() * horizon, 1);
Matrix matrix_qq = Matrix::Zero(matrix_k.rows(), matrix_k.rows());
Matrix matrix_rr = Matrix::Zero(matrix_k.cols(), matrix_k.cols());
Matrix matrix_ll = Matrix::Zero(horizon * matrix_lower.rows(), 1);
Matrix matrix_uu = Matrix::Zero(horizon * matrix_upper.rows(), 1);
// Compute matrix_m
matrix_m.block(0, 0, matrix_a.rows(), 1) =
matrix_a * matrix_initial_state + matrix_c;
for (unsigned int i = 1; i < horizon; ++i) {
matrix_m.block(i * matrix_a.rows(), 0, matrix_a.rows(), 1) =
matrix_a *
matrix_m.block((i - 1) * matrix_a.rows(), 0, matrix_a.rows(), 1) +
matrix_c;
}
// Compute matrix_ll, matrix_uu, matrix_qq, matrix_rr
for (unsigned int i = 0; i < horizon; ++i) {
matrix_ll.block(i * (*control)[0].rows(), 0, (*control)[0].rows(), 1) =
matrix_lower;
matrix_uu.block(i * (*control)[0].rows(), 0, (*control)[0].rows(), 1) =
matrix_upper;
matrix_qq.block(i * matrix_q.rows(), i * matrix_q.rows(), matrix_q.rows(),
matrix_q.rows()) = matrix_q;
matrix_rr.block(i * matrix_r.rows(), i * matrix_r.rows(), matrix_r.cols(),
matrix_r.cols()) = matrix_r;
}
// Update matrix_m1, matrix_m2, convert MPC problem to QP problem done
Matrix matrix_m1 = matrix_k.transpose() * matrix_qq * matrix_k + matrix_rr;
Matrix matrix_m2 = matrix_k.transpose() * matrix_qq * (matrix_m - matrix_t);
// Format in qp_solver
/**
* * min_x : q(x) = 0.5 * x^T * Q * x + x^T c
* * with respect to: A * x = b (equality constraint)
* * C * x >= d (inequality constraint)
* **/
// TODO(QiL) : change qp solver to box constraint or substitute QPOASES
// Method 1: QPOASES
Matrix matrix_inequality_constrain_ll =
Matrix::Identity(matrix_ll.rows(), matrix_ll.rows());
Matrix matrix_inequality_constrain_uu =
Matrix::Identity(matrix_uu.rows(), matrix_uu.rows());
Matrix matrix_inequality_constrain =
Matrix::Zero(matrix_ll.rows() + matrix_uu.rows(), matrix_ll.rows());
matrix_inequality_constrain << matrix_inequality_constrain_ll,
-matrix_inequality_constrain_uu;
Matrix matrix_inequality_boundary =
Matrix::Zero(matrix_ll.rows() + matrix_uu.rows(), matrix_ll.cols());
matrix_inequality_boundary << matrix_ll, -matrix_uu;
Matrix matrix_equality_constrain =
Matrix::Zero(matrix_ll.rows() + matrix_uu.rows(), matrix_ll.rows());
Matrix matrix_equality_boundary =
Matrix::Zero(matrix_ll.rows() + matrix_uu.rows(), matrix_ll.cols());
std::unique_ptr<QpSolver> qp_solver(new ActiveSetQpSolver(
matrix_m1, matrix_m2, matrix_inequality_constrain,
matrix_inequality_boundary, matrix_equality_constrain,
matrix_equality_boundary));
auto result = qp_solver->Solve();
if (!result) {
AERROR << "Linear MPC solver failed";
return false;
}
matrix_v = qp_solver->params();
for (unsigned int i = 0; i < horizon; ++i) {
(*control)[i] =
matrix_v.block(i * (*control)[0].rows(), 0, (*control)[0].rows(), 1);
}
return true;
}
} // namespace math
} // namespace common
} // namespace apollo
<|endoftext|>
|
<commit_before>///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2011 - 2012 by //
// Simon Pratt //
// (All rights reserved) //
///////////////////////////////////////////////////////////////////////////////
// //
// FILE: test_pst.cpp //
// //
// MODULE: Priority Search Tree //
// //
// NOTES: None. //
// //
///////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <string>
#include <time.h>
#include <assert.h>
#include "PSTPoint.h"
#include "InPlacePST.h"
#include "array_utilities.h"
#include "control_utilities.h"
using namespace std;
using namespace PrioritySearchTree;
// Dirty hack, but hey: it's c++!
PSTPoint* vectorPointerToArray(vector<PSTPoint>* v) {
return &(*v)[0];
}
int main(int argv, char** argc) {
const int MAX_POINTS_DISPLAY = 16;
bool QUIET_MODE = false;
time_t before, after;
int n, qi;
/////////////////////////////////////////////////////////////////////////////
// Seed the PRNG //
/////////////////////////////////////////////////////////////////////////////
srand( time(0) );
/////////////////////////////////////////////////////////////////////////////
// Ensure the user has entered required parameters, otherwise print //
// a helpful message. //
/////////////////////////////////////////////////////////////////////////////
if(argv < 3) {
cout << "Usage: test_pst [number of points] [query iterations] [quiet]"
<< endl;
return 1;
}
// parse number of points
n = atoi(argc[1]);
// parse query iterations
qi = atoi(argc[2]);
// check for quiet mode
if(argv > 3)
QUIET_MODE = true;
/////////////////////////////////////////////////////////////////////////////
// Create Points //
/////////////////////////////////////////////////////////////////////////////
cout << "Creating " << n << " points..." << flush;
before = time(0);
PSTPoint *points = new PSTPoint[n]; // allocate on the heap
for(int i = 1; i < n; i++) {
PSTPoint p(i,i); // allocate on the stack
points[i] = p;
}
after = time(0);
cout << "took: " << (after - before) << endl;
if(n <= MAX_POINTS_DISPLAY) {
cout << "Points: ";
PSTArray::print(points,n);
}
/////////////////////////////////////////////////////////////////////////////
// Build tree //
/////////////////////////////////////////////////////////////////////////////
cout << "Building tree..." << flush;
before = time(0);
InPlacePST ippst(points,n);
after = time(0);
cout << "took: " << (after - before) << endl;
delete points;
/////////////////////////////////////////////////////////////////////////////
// Check memory - quietly or manually //
/////////////////////////////////////////////////////////////////////////////
if(QUIET_MODE) {
cout << "Memory usage(%): " << flush;
// this next line is system-specific, but should work on any
// reasonable unix compatible system. Procedure:
// 1. Ask for detailed information on processes
// 2. filter out all lines which don't have the name of the program
// 3. filter out all lines which have the word grep
// 4. filter out all lines which have the word "ps "
// 5. print the 4th column (memory usage)
assert(system("ps auxww | grep test_pst | grep -v grep | grep -v ps\\ | awk '{print $4}'") == 0);
} else {
control_utilities::waitForAnyKey();
}
/////////////////////////////////////////////////////////////////////////////
// Print the structure if the number of points is small //
/////////////////////////////////////////////////////////////////////////////
if(n <= MAX_POINTS_DISPLAY) {
cout << "Tree: " << endl;
ippst.printTree();
}
/////////////////////////////////////////////////////////////////////////////
// leftMostNE //
/////////////////////////////////////////////////////////////////////////////
PSTPoint result;
cout << qi << " iterations of ";
cout << "leftMostNE..." << flush;
before = time(0);
for(int i = 0; i < qi; i++)
result = ippst.leftMostNE(rand() % n, rand() % n);
after = time(0);
cout << "took: " << (after - before) << endl;
/////////////////////////////////////////////////////////////////////////////
// highestNE //
/////////////////////////////////////////////////////////////////////////////
cout << qi << " iterations of ";
cout << "highestNE..." << flush;
before = time(0);
for(int i = 0; i < qi; i++)
result = ippst.highestNE(rand() % n, rand() % n);
after = time(0);
cout << "took: " << (after - before) << endl;
/////////////////////////////////////////////////////////////////////////////
// highest3Sided //
/////////////////////////////////////////////////////////////////////////////
cout << qi << " iterations of ";
cout << "highest3Sided..." << flush;
int xmin = 0, xmax = 0, ymin = 0;
before = time(0);
for(int i = 0; i < qi; i++) {
xmin = rand() % n;
xmax = xmin + (rand() % (n - xmin));
ymin = rand() % n;
result = ippst.highest3Sided(xmin,xmax,ymin);
}
after = time(0);
cout << "took: " << (after - before) << endl;
/////////////////////////////////////////////////////////////////////////////
// enumerate3Sided //
/////////////////////////////////////////////////////////////////////////////
vector<PSTPoint>* results;
cout << qi << " iterations of ";
cout << "enumerate3Sided..." << flush;
before = time(0);
for(int i = 0; i < qi; i++) {
xmin = rand() % n;
xmax = xmin + (rand() % (n - xmin));
results = ippst.enumerate3Sided(xmin,xmax,rand() % n);
delete results;
}
after = time(0);
cout << "took: " << (after - before) << endl;
return 0;
}
<commit_msg>Now able to specify how many enumeration iterations<commit_after>///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2011 - 2012 by //
// Simon Pratt //
// (All rights reserved) //
///////////////////////////////////////////////////////////////////////////////
// //
// FILE: test_pst.cpp //
// //
// MODULE: Priority Search Tree //
// //
// NOTES: None. //
// //
///////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <string>
#include <time.h>
#include <assert.h>
#include "PSTPoint.h"
#include "InPlacePST.h"
#include "array_utilities.h"
#include "control_utilities.h"
using namespace std;
using namespace PrioritySearchTree;
// Dirty hack, but hey: it's c++!
PSTPoint* vectorPointerToArray(vector<PSTPoint>* v) {
return &(*v)[0];
}
int main(int argv, char** argc) {
const int MAX_POINTS_DISPLAY = 16;
bool QUIET_MODE = false;
time_t before, after;
int n, qi, ei;
/////////////////////////////////////////////////////////////////////////////
// Seed the PRNG //
/////////////////////////////////////////////////////////////////////////////
srand( time(0) );
/////////////////////////////////////////////////////////////////////////////
// Ensure the user has entered required parameters, otherwise print //
// a helpful message. //
/////////////////////////////////////////////////////////////////////////////
if(argv < 3) {
cout << "Usage: test_pst [number of points] [query iterations] "
<< "[enumerate iterations] [quiet]" << endl;
return 1;
}
// parse number of points
n = atoi(argc[1]);
// parse query iterations
qi = atoi(argc[2]);
// parse enumerate iterations
ei = atoi(argc[3]);
// check for quiet mode
if(argv > 4)
QUIET_MODE = true;
/////////////////////////////////////////////////////////////////////////////
// Create Points //
/////////////////////////////////////////////////////////////////////////////
cout << "Creating " << n << " points..." << flush;
before = time(0);
PSTPoint *points = new PSTPoint[n]; // allocate on the heap
for(int i = 1; i < n; i++) {
PSTPoint p(i,i); // allocate on the stack
points[i] = p;
}
after = time(0);
cout << "took: " << (after - before) << endl;
if(n <= MAX_POINTS_DISPLAY) {
cout << "Points: ";
PSTArray::print(points,n);
}
/////////////////////////////////////////////////////////////////////////////
// Build tree //
/////////////////////////////////////////////////////////////////////////////
cout << "Building tree..." << flush;
before = time(0);
InPlacePST ippst(points,n);
after = time(0);
cout << "took: " << (after - before) << endl;
delete points;
/////////////////////////////////////////////////////////////////////////////
// Check memory - quietly or manually //
/////////////////////////////////////////////////////////////////////////////
if(QUIET_MODE) {
cout << "Memory usage(%): " << flush;
// this next line is system-specific, but should work on any
// reasonable unix compatible system. Procedure:
// 1. Ask for detailed information on processes
// 2. filter out all lines which don't have the name of the program
// 3. filter out all lines which have the word grep
// 4. filter out all lines which have the word "ps "
// 5. print the 4th column (memory usage)
assert(system("ps auxww | grep test_pst | grep -v grep | grep -v ps\\ | awk '{print $4}'") == 0);
} else {
control_utilities::waitForAnyKey();
}
/////////////////////////////////////////////////////////////////////////////
// Print the structure if the number of points is small //
/////////////////////////////////////////////////////////////////////////////
if(n <= MAX_POINTS_DISPLAY) {
cout << "Tree: " << endl;
ippst.printTree();
}
/////////////////////////////////////////////////////////////////////////////
// leftMostNE //
/////////////////////////////////////////////////////////////////////////////
PSTPoint result;
cout << qi << " iterations of ";
cout << "leftMostNE..." << flush;
before = time(0);
for(int i = 0; i < qi; i++)
result = ippst.leftMostNE(rand() % n, rand() % n);
after = time(0);
cout << "took: " << (after - before) << endl;
/////////////////////////////////////////////////////////////////////////////
// highestNE //
/////////////////////////////////////////////////////////////////////////////
cout << qi << " iterations of ";
cout << "highestNE..." << flush;
before = time(0);
for(int i = 0; i < qi; i++)
result = ippst.highestNE(rand() % n, rand() % n);
after = time(0);
cout << "took: " << (after - before) << endl;
/////////////////////////////////////////////////////////////////////////////
// highest3Sided //
/////////////////////////////////////////////////////////////////////////////
cout << qi << " iterations of ";
cout << "highest3Sided..." << flush;
int xmin = 0, xmax = 0, ymin = 0;
before = time(0);
for(int i = 0; i < qi; i++) {
xmin = rand() % n;
xmax = xmin + (rand() % (n - xmin));
ymin = rand() % n;
result = ippst.highest3Sided(xmin,xmax,ymin);
}
after = time(0);
cout << "took: " << (after - before) << endl;
/////////////////////////////////////////////////////////////////////////////
// enumerate3Sided //
/////////////////////////////////////////////////////////////////////////////
vector<PSTPoint>* results;
cout << ei << " iterations of ";
cout << "enumerate3Sided..." << flush;
before = time(0);
for(int i = 0; i < ei; i++) {
xmin = rand() % n;
xmax = xmin + (rand() % (n - xmin));
results = ippst.enumerate3Sided(xmin,xmax,rand() % n);
delete results;
}
after = time(0);
cout << "took: " << (after - before) << endl;
return 0;
}
<|endoftext|>
|
<commit_before>{
cout << "rootlogon.C for UCNSIM" << endl;
cout << "-------------------------------------" << endl;
if ( gSystem->Load("libPhysics") == 0 ) {
cout << "Successfully loaded libPhysics.so" << endl;
}
if ( gSystem->Load("libGeom.so") == 0 ) {
cout << "Successfully loaded libGeom.so" << endl;
}
if ( gSystem->Load("libGeomPainter.so") == 0 ) {
cout << "Successfully loaded libGeomPainter.so" << endl;
}
if ( gSystem->Load("libTree.so") == 0 ) {
cout << "Successfully loaded libTree.so" << endl;
}
if ( gSystem->Load("libEG.so") == 0 ) {
cout << "Successfully loaded libEG.so" << endl;
}
if ( gSystem->Load("libMathCore.so") == 0 ) {
cout << "Successfully loaded libMathCore.so" << endl;
}
if ( gSystem->Load("libMathMore.so") == 0 ) {
cout << "Successfully loaded libMathCore.so" << endl;
}
TString ucnsim = gSystem->Getenv("UCN_DIR");
if ( ucnsim.Length() == 0 ) {
cerr << "-------------------------------------" << endl;
cerr << "Warning: Failed to find env. variable UCNSIM" << endl;
cerr << "-------------------------------------" << endl;
}
else {
TString ucnlib = ucnsim + "/lib/libUCN.so";
cerr << ucnlib.Data() << endl;
if ( gSystem->Load(ucnlib.Data()) == 0 ) {
cout << "Successfully loaded libUCN.so" << endl;
}
}
TString magdir = gSystem->Getenv("MAGDIR");
if ( magdir.Length() == 0 ) {
cerr << "-------------------------------------" << endl;
cerr << "Warning: Failed to find env. variable MAGDIR" << endl;
cerr << "-------------------------------------" << endl;
}
else {
TString maglib = magdir + "/lib/libEDM.so";
cerr << maglib.Data() << endl;
if ( gSystem->Load(maglib.Data()) == 0 ) {
cout << "Successfully loaded libEDM.so" << endl;
}
}
cout << "-------------------------------------" << endl;
set_my_style();
}
<commit_msg>Cleaned up some garbage in rootlogon<commit_after>{
cout << "rootlogon.C for UCNSIM" << endl;
cout << "-------------------------------------" << endl;
if ( gSystem->Load("libPhysics") == 0 ) {
cout << "Successfully loaded libPhysics.so" << endl;
}
if ( gSystem->Load("libGeom.so") == 0 ) {
cout << "Successfully loaded libGeom.so" << endl;
}
if ( gSystem->Load("libGeomPainter.so") == 0 ) {
cout << "Successfully loaded libGeomPainter.so" << endl;
}
if ( gSystem->Load("libTree.so") == 0 ) {
cout << "Successfully loaded libTree.so" << endl;
}
if ( gSystem->Load("libEG.so") == 0 ) {
cout << "Successfully loaded libEG.so" << endl;
}
if ( gSystem->Load("libMathCore.so") == 0 ) {
cout << "Successfully loaded libMathCore.so" << endl;
}
if ( gSystem->Load("libMathMore.so") == 0 ) {
cout << "Successfully loaded libMathCore.so" << endl;
}
TString ucnsim = gSystem->Getenv("UCN_DIR");
if ( ucnsim.Length() == 0 ) {
cerr << "-------------------------------------" << endl;
cerr << "Warning: Failed to find env. variable UCNSIM" << endl;
cerr << "-------------------------------------" << endl;
}
else {
TString ucnlib = ucnsim + "/lib/libUCN.so";
cerr << ucnlib.Data() << endl;
if ( gSystem->Load(ucnlib.Data()) == 0 ) {
cout << "Successfully loaded libUCN.so" << endl;
}
}
cout << "-------------------------------------" << endl;
set_my_style();
}
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2000 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/>.
*/
#if !defined(ARENABLOCK_INCLUDE_GUARD_1357924680)
#define ARENABLOCK_INCLUDE_GUARD_1357924680
#include <algorithm>
#include <cassert>
#include <set>
#include <memory>
#if defined(XALAN_NO_STD_ALLOCATORS) && !defined(XALAN_NO_SELECTIVE_TEMPLATE_INSTANTIATION)
#include <PlatformSupport/XalanAllocator.hpp>
#endif
#if defined(XALAN_NO_SELECTIVE_TEMPLATE_INSTANTIATION)
template <class Type>
class ArenaBlockAllocator
{
public:
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef Type* pointer;
typedef const Type* const_pointer;
typedef Type& reference;
typedef const Type& const_reference;
typedef Type value_type;
ArenaBlockAllocator()
{
}
ArenaBlockAllocator(const ArenaBlockAllocator<Type>&)
{
};
~ArenaBlockAllocator()
{
}
pointer
allocate(
size_type size,
const void* /* hint */ = 0)
{
return (pointer)operator new(size * sizeof(Type));
}
void
deallocate(
pointer p,
size_type /* n */)
{
operator delete(p);
}
};
#endif
template<class ObjectType>
class ArenaBlockDestroy
{
public:
void
operator()(ObjectType& theObject) const
{
theObject.ObjectType::~ObjectType();
}
};
template<class ObjectType>
class ArenaBlock
{
public:
#if defined(XALAN_NO_SELECTIVE_TEMPLATE_INSTANTIATION)
typedef ArenaBlockAllocator<ObjectType> AllocatorType;
#elif defined(XALAN_NO_STD_ALLOCATORS)
typedef XalanAllocator<ObjectType> AllocatorType;
#else
typedef std::allocator<ObjectType> AllocatorType;
#endif
typedef ArenaBlockDestroy<ObjectType> DestroyFunctionType;
typedef typename AllocatorType::size_type size_type;
/*
* Construct an ArenaBlock of the specified size
* of objects.
*
* @param theBlockSize The size of the block (the number of objects it can contain).
*/
ArenaBlock(size_type theBlockSize) :
m_destroyFunction(DestroyFunctionType()),
m_objectCount(0),
m_blockSize(theBlockSize),
m_objectBlock(0),
m_allocator()
{
assert(theBlockSize > 0);
}
virtual
~ArenaBlock()
{
destroyAll();
// Release the memory...
m_allocator.deallocate(m_objectBlock, 0);
}
/*
* Allocate a block. Once the object is constructed, you must call
* commitAllocation().
*
* @return a pointer to the new block.
*/
virtual ObjectType*
allocateBlock()
{
// Any space left?
if (m_objectCount == m_blockSize)
{
return 0;
}
else
{
// If no memory has yet been allocated, then allocate it...
if (m_objectBlock == 0)
{
#if defined(XALAN_NEW_STD_ALLOCATOR)
m_objectBlock = m_allocator.allocate(m_blockSize);
#else
m_objectBlock = m_allocator.allocate(m_blockSize, 0);
#endif
}
assert(m_objectBlock != 0);
return m_objectBlock + m_objectCount;
}
}
/*
* Commit the previous allocation.
*
* @param theBlock the address that was returned by allocateBlock()
*/
virtual void
#if defined (NDEBUG)
commitAllocation(ObjectType* /* theBlock */)
#else
commitAllocation(ObjectType* theBlock)
#endif
{
assert(theBlock == m_objectBlock + m_objectCount);
assert(m_objectCount < m_blockSize);
m_objectCount++;
}
/*
* Find out if there is a block available.
*
* @return true if one is available, false if not.
*/
virtual bool
blockAvailable() const
{
return m_objectCount < m_blockSize ? true : false;
}
/*
* Get the number of objects currently allocated in the
* block.
*
* @return The number of objects allocated.
*/
virtual size_type
getCountAllocated() const
{
return m_objectCount;
}
/*
* Get the block size, that is, the number
* of objects in each block.
*
* @return The size of the block
*/
size_type
getBlockSize() const
{
return m_blockSize;
}
/*
* Determine if this block owns the specified object. Note
* that even if the object address is within our block, this
* call will return false if no object currently occupies the
* block. See also ownsBlock().
*
* @param theObject the address of the object.
* @return true if we own the object, false if not.
*/
virtual bool
ownsObject(const ObjectType* theObject) const
{
#if !defined(XALAN_NO_NAMESPACES)
using std::less;
#endif
// Use less<>, since it's guaranteed to do pointer
// comparisons correctly...
less<const ObjectType*> functor;
if (functor(theObject, m_objectBlock) == false &&
functor(theObject, m_objectBlock + m_objectCount) == true)
{
return true;
}
else
{
return false;
}
}
/*
* Determine if this block owns the specified object block.
* Note that, unlike ownsObject(), there does not need to
* be an object at the address.
*
* @param theObject the address of the object
* @return true if we own the object block, false if not.
*/
bool
ownsBlock(const ObjectType* theObject) const
{
#if !defined(XALAN_NO_NAMESPACES)
using std::less;
#endif
// Use less<>, since it's guaranteed to do pointer
// comparisons correctly...
less<const ObjectType*> functor;
if (functor(theObject, m_objectBlock) == false &&
functor(theObject, m_objectBlock + m_blockSize) == true)
{
return true;
}
else
{
return false;
}
}
/*
* Destroy all objects in the block. You can then reuse the
* block.
*/
void
destroyAll()
{
#if !defined(XALAN_NO_NAMESPACES)
using std::for_each;
#endif
// Destroy all existing objects...
for_each(m_objectBlock,
m_objectBlock + m_objectCount,
DeleteFunctor(*this, m_destroyFunction));
m_objectCount = 0;
}
protected:
/*
* Determine if the block should be destroyed. Called by
* an instance of DeleteFunctor, this function is for
* deriving classes that might want to control the destruction
* of things.
*
* @param theObject the address of the object
* @return true if block should be destroyed, false if not.
*/
virtual bool
shouldDestroyBlock(const ObjectType* /* theObject */) const
{
return true;
}
/*
* Determine the offset into the block for the given address.
* Behavior is undefined if the address is not within our
* block
*
* @param theObject the address of the object
* @return the offset
*/
size_type
getBlockOffset(const ObjectType* theObject) const
{
assert(size_type(theObject - m_objectBlock) < m_blockSize);
return theObject - m_objectBlock;
}
/*
* Determine the address within our block of the object
* at the specified offset.
* Behavior is undefined if the offset is greater than the
* block size.
*
* @param theObject the address of the object
* @return the offset
*/
ObjectType*
getBlockAddress(size_type theOffset) const
{
assert(theOffset < m_blockSize);
return m_objectBlock + theOffset;
}
struct DeleteFunctor
{
DeleteFunctor(
const ArenaBlock<ObjectType>& theArenaBlock,
const DestroyFunctionType& theDestroyFunction) :
m_arenaBlock(theArenaBlock),
m_destroyFunction(theDestroyFunction)
{
}
void
operator()(ObjectType& theObject) const
{
if (m_arenaBlock.shouldDestroyBlock(&theObject) == true)
{
m_destroyFunction(theObject);
}
}
private:
const ArenaBlock<ObjectType>& m_arenaBlock;
const DestroyFunctionType& m_destroyFunction;
};
friend struct DeleteFunctor;
const DestroyFunctionType m_destroyFunction;
private:
// Not implemented...
ArenaBlock(const ArenaBlock<ObjectType>&);
ArenaBlock<ObjectType>&
operator=(const ArenaBlock<ObjectType>&);
bool
operator==(const ArenaBlock<ObjectType>&) const;
// data members...
size_type m_objectCount;
const size_type m_blockSize;
ObjectType* m_objectBlock;
AllocatorType m_allocator;
};
#endif // !defined(ARENABLOCK_INCLUDE_GUARD_1357924680)
<commit_msg>Added workaround for broken IBM compiler.<commit_after>/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2000 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/>.
*/
#if !defined(ARENABLOCK_INCLUDE_GUARD_1357924680)
#define ARENABLOCK_INCLUDE_GUARD_1357924680
#include <algorithm>
#include <cassert>
#include <set>
#include <memory>
#if defined(XALAN_NO_STD_ALLOCATORS) && !defined(XALAN_NO_SELECTIVE_TEMPLATE_INSTANTIATION)
#include <PlatformSupport/XalanAllocator.hpp>
#endif
#if defined(XALAN_NO_SELECTIVE_TEMPLATE_INSTANTIATION)
template <class Type>
class ArenaBlockAllocator
{
public:
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef Type* pointer;
typedef const Type* const_pointer;
typedef Type& reference;
typedef const Type& const_reference;
typedef Type value_type;
ArenaBlockAllocator()
{
}
ArenaBlockAllocator(const ArenaBlockAllocator<Type>&)
{
};
~ArenaBlockAllocator()
{
}
pointer
allocate(
size_type size,
const void* /* hint */ = 0)
{
return (pointer)operator new(size * sizeof(Type));
}
void
deallocate(
pointer p,
size_type /* n */)
{
operator delete(p);
}
};
#endif
template<class ObjectType>
class ArenaBlockDestroy
{
public:
void
operator()(ObjectType& theObject) const
{
#if defined(XALAN_EXPLICIT_SCOPE_IN_TEMPLATE_BUG)
theObject.~ObjectType();
#else
theObject.ObjectType::~ObjectType();
#endif
}
};
template<class ObjectType>
class ArenaBlock
{
public:
#if defined(XALAN_NO_SELECTIVE_TEMPLATE_INSTANTIATION)
typedef ArenaBlockAllocator<ObjectType> AllocatorType;
#elif defined(XALAN_NO_STD_ALLOCATORS)
typedef XalanAllocator<ObjectType> AllocatorType;
#else
typedef std::allocator<ObjectType> AllocatorType;
#endif
typedef ArenaBlockDestroy<ObjectType> DestroyFunctionType;
typedef typename AllocatorType::size_type size_type;
/*
* Construct an ArenaBlock of the specified size
* of objects.
*
* @param theBlockSize The size of the block (the number of objects it can contain).
*/
ArenaBlock(size_type theBlockSize) :
m_destroyFunction(DestroyFunctionType()),
m_objectCount(0),
m_blockSize(theBlockSize),
m_objectBlock(0),
m_allocator()
{
assert(theBlockSize > 0);
}
virtual
~ArenaBlock()
{
destroyAll();
// Release the memory...
m_allocator.deallocate(m_objectBlock, 0);
}
/*
* Allocate a block. Once the object is constructed, you must call
* commitAllocation().
*
* @return a pointer to the new block.
*/
virtual ObjectType*
allocateBlock()
{
// Any space left?
if (m_objectCount == m_blockSize)
{
return 0;
}
else
{
// If no memory has yet been allocated, then allocate it...
if (m_objectBlock == 0)
{
#if defined(XALAN_NEW_STD_ALLOCATOR)
m_objectBlock = m_allocator.allocate(m_blockSize);
#else
m_objectBlock = m_allocator.allocate(m_blockSize, 0);
#endif
}
assert(m_objectBlock != 0);
return m_objectBlock + m_objectCount;
}
}
/*
* Commit the previous allocation.
*
* @param theBlock the address that was returned by allocateBlock()
*/
virtual void
#if defined (NDEBUG)
commitAllocation(ObjectType* /* theBlock */)
#else
commitAllocation(ObjectType* theBlock)
#endif
{
assert(theBlock == m_objectBlock + m_objectCount);
assert(m_objectCount < m_blockSize);
m_objectCount++;
}
/*
* Find out if there is a block available.
*
* @return true if one is available, false if not.
*/
virtual bool
blockAvailable() const
{
return m_objectCount < m_blockSize ? true : false;
}
/*
* Get the number of objects currently allocated in the
* block.
*
* @return The number of objects allocated.
*/
virtual size_type
getCountAllocated() const
{
return m_objectCount;
}
/*
* Get the block size, that is, the number
* of objects in each block.
*
* @return The size of the block
*/
size_type
getBlockSize() const
{
return m_blockSize;
}
/*
* Determine if this block owns the specified object. Note
* that even if the object address is within our block, this
* call will return false if no object currently occupies the
* block. See also ownsBlock().
*
* @param theObject the address of the object.
* @return true if we own the object, false if not.
*/
virtual bool
ownsObject(const ObjectType* theObject) const
{
#if !defined(XALAN_NO_NAMESPACES)
using std::less;
#endif
// Use less<>, since it's guaranteed to do pointer
// comparisons correctly...
less<const ObjectType*> functor;
if (functor(theObject, m_objectBlock) == false &&
functor(theObject, m_objectBlock + m_objectCount) == true)
{
return true;
}
else
{
return false;
}
}
/*
* Determine if this block owns the specified object block.
* Note that, unlike ownsObject(), there does not need to
* be an object at the address.
*
* @param theObject the address of the object
* @return true if we own the object block, false if not.
*/
bool
ownsBlock(const ObjectType* theObject) const
{
#if !defined(XALAN_NO_NAMESPACES)
using std::less;
#endif
// Use less<>, since it's guaranteed to do pointer
// comparisons correctly...
less<const ObjectType*> functor;
if (functor(theObject, m_objectBlock) == false &&
functor(theObject, m_objectBlock + m_blockSize) == true)
{
return true;
}
else
{
return false;
}
}
/*
* Destroy all objects in the block. You can then reuse the
* block.
*/
void
destroyAll()
{
#if !defined(XALAN_NO_NAMESPACES)
using std::for_each;
#endif
// Destroy all existing objects...
for_each(m_objectBlock,
m_objectBlock + m_objectCount,
DeleteFunctor(*this, m_destroyFunction));
m_objectCount = 0;
}
protected:
/*
* Determine if the block should be destroyed. Called by
* an instance of DeleteFunctor, this function is for
* deriving classes that might want to control the destruction
* of things.
*
* @param theObject the address of the object
* @return true if block should be destroyed, false if not.
*/
virtual bool
shouldDestroyBlock(const ObjectType* /* theObject */) const
{
return true;
}
/*
* Determine the offset into the block for the given address.
* Behavior is undefined if the address is not within our
* block
*
* @param theObject the address of the object
* @return the offset
*/
size_type
getBlockOffset(const ObjectType* theObject) const
{
assert(size_type(theObject - m_objectBlock) < m_blockSize);
return theObject - m_objectBlock;
}
/*
* Determine the address within our block of the object
* at the specified offset.
* Behavior is undefined if the offset is greater than the
* block size.
*
* @param theObject the address of the object
* @return the offset
*/
ObjectType*
getBlockAddress(size_type theOffset) const
{
assert(theOffset < m_blockSize);
return m_objectBlock + theOffset;
}
struct DeleteFunctor
{
DeleteFunctor(
const ArenaBlock<ObjectType>& theArenaBlock,
const DestroyFunctionType& theDestroyFunction) :
m_arenaBlock(theArenaBlock),
m_destroyFunction(theDestroyFunction)
{
}
void
operator()(ObjectType& theObject) const
{
if (m_arenaBlock.shouldDestroyBlock(&theObject) == true)
{
m_destroyFunction(theObject);
}
}
private:
const ArenaBlock<ObjectType>& m_arenaBlock;
const DestroyFunctionType& m_destroyFunction;
};
friend struct DeleteFunctor;
const DestroyFunctionType m_destroyFunction;
private:
// Not implemented...
ArenaBlock(const ArenaBlock<ObjectType>&);
ArenaBlock<ObjectType>&
operator=(const ArenaBlock<ObjectType>&);
bool
operator==(const ArenaBlock<ObjectType>&) const;
// data members...
size_type m_objectCount;
const size_type m_blockSize;
ObjectType* m_objectBlock;
AllocatorType m_allocator;
};
#endif // !defined(ARENABLOCK_INCLUDE_GUARD_1357924680)
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: AccessibleDocument.cxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: sab $ $Date: 2002-03-12 09:44:28 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SC_ACCESSIBLEDOCUMENT_HXX
#include "AccessibleDocument.hxx"
#endif
#ifndef _SC_ACCESSIBLESPREADSHEET_HXX
#include "AccessibleSpreadsheet.hxx"
#endif
#ifndef SC_TABVWSH_HXX
#include "tabvwsh.hxx"
#endif
#ifndef SC_ACCESSIBILITYHINTS_HXX
#include "AccessibilityHints.hxx"
#endif
#ifndef SC_DOCUMENT_HXX
#include "document.hxx"
#endif
#ifndef SC_DRWLAYER_HXX
#include "drwlayer.hxx"
#endif
#ifndef SC_UNOGUARD_HXX
#include "unoguard.hxx"
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEEVENTID_HPP_
#include <drafts/com/sun/star/accessibility/AccessibleEventId.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLESTATETYPE_HPP_
#include <drafts/com/sun/star/accessibility/AccessibleStateType.hpp>
#endif
#ifndef _UTL_ACCESSIBLESTATESETHELPER_HXX
#include <unotools/accessiblestatesethelper.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _SV_GEN_HXX
#include <tools/gen.hxx>
#endif
#ifndef _SVDPAGE_HXX
#include <svx/svdpage.hxx>
#endif
#ifndef _SVDOBJ_HXX
#include <svx/svdobj.hxx>
#endif
using namespace ::com::sun::star;
using namespace ::drafts::com::sun::star::accessibility;
//===== internal ========================================================
ScAccessibleDocument::ScAccessibleDocument(
const uno::Reference<XAccessible>& rxParent,
ScTabViewShell* pViewShell,
ScSplitPos eSplitPos)
: ScAccessibleDocumentBase(rxParent),
mpViewShell(pViewShell),
meSplitPos(eSplitPos),
mpAccessibleSpreadsheet(NULL)
{
if (pViewShell)
pViewShell->AddAccessibilityObject(*this);
}
ScAccessibleDocument::~ScAccessibleDocument(void)
{
FreeAccessibleSpreadsheet();
if (mpViewShell)
{
mpViewShell->RemoveAccessibilityObject(*this);
}
}
void ScAccessibleDocument::SetDefunc()
{
FreeAccessibleSpreadsheet();
if (mpViewShell)
{
mpViewShell->RemoveAccessibilityObject(*this);
mpViewShell = NULL;
}
ScAccessibleDocumentBase::SetDefunc();
}
//===== SfxListener =====================================================
void ScAccessibleDocument::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )
{
if (rHint.ISA( ScAccGridViewChangeHint ) )
{
const ScAccGridViewChangeHint& rRef = (const ScAccGridViewChangeHint&)rHint;
if ((rRef.GetOldGridWin() == meSplitPos) ||
(rRef.GetNewGridWin() == meSplitPos))
{
awt::FocusEvent aFocusEvent;
aFocusEvent.Temporary = sal_False;
if (rRef.GetOldGridWin() == meSplitPos)
{
aFocusEvent.NextFocus = rRef.GetNewAccessible();
CommitFocusLost(aFocusEvent);
}
else
{
aFocusEvent.NextFocus = rRef.GetOldAccessible();
CommitFocusGained(aFocusEvent);
}
}
}
else if (rHint.ISA( SfxSimpleHint ))
{
const SfxSimpleHint& rRef = (const SfxSimpleHint&)rHint;
// only notify if child exist, otherwise it is not necessary
if ((rRef.GetId() == SC_HINT_ACC_TABLECHANGED) &&
mpAccessibleSpreadsheet)
{
AccessibleEventObject aEvent;
aEvent.EventId = AccessibleEventId::ACCESSIBLE_CHILD_EVENT;
aEvent.OldValue <<= GetAccessibleSpreadsheet();
CommitChange(aEvent); // child is gone - event
aEvent.OldValue = uno::Any();
FreeAccessibleSpreadsheet(); // free the spreadsheet after free the reference on this object
aEvent.NewValue <<= GetAccessibleSpreadsheet();
CommitChange(aEvent); // there is a new child - event
}
else if (rRef.GetId() == SFX_HINT_DYING)
{
// it seems the Broadcaster is dying, since the view is dying
SetDefunc();
}
}
}
//===== XAccessibleComponent ============================================
uno::Reference< XAccessible > SAL_CALL ScAccessibleDocument::getAccessibleAt(
const awt::Point& rPoint )
throw (uno::RuntimeException)
{
ScUnoGuard aGuard;
uno::Reference<XAccessible> xAccessible = NULL;
SdrPage* pDrawPage = GetDrawPage();
if (pDrawPage)
{
DBG_ERROR("not implemented");
}
else
xAccessible = GetAccessibleSpreadsheet();
return xAccessible;
}
void SAL_CALL ScAccessibleDocument::grabFocus( )
throw (uno::RuntimeException)
{
ScUnoGuard aGuard;
if (getAccessibleParent().is())
{
uno::Reference<XAccessibleComponent> xAccessibleComponent(getAccessibleParent()->getAccessibleContext(), uno::UNO_QUERY);
if (xAccessibleComponent.is())
{
xAccessibleComponent->grabFocus();
// grab only focus if it does not have the focus and it is not hidden
if (mpViewShell && mpViewShell->GetViewData() &&
(mpViewShell->GetViewData()->GetActivePart() != meSplitPos) &&
mpViewShell->GetWindowByPos(meSplitPos)->IsVisible())
{
mpViewShell->ActivatePart(meSplitPos);
}
}
}
}
//===== XAccessibleContext ==============================================
/// Return the number of currently visible children.
long SAL_CALL
ScAccessibleDocument::getAccessibleChildCount(void)
throw (uno::RuntimeException)
{
ScUnoGuard aGuard;
sal_Int32 nShapes (0);
SdrPage* pDrawPage = GetDrawPage();
if (pDrawPage)
{
sal_uInt32 nObjCount(pDrawPage->GetObjCount());
for (sal_uInt32 i = 0; i < nObjCount; i++)
{
SdrObject* pObj = pDrawPage->GetObj(i);
if (pObj && (pObj->GetLayer() != SC_LAYER_INTERN))
nShapes++;
}
}
return nShapes + 1;
}
/// Return the specified child or NULL if index is invalid.
uno::Reference<XAccessible> SAL_CALL
ScAccessibleDocument::getAccessibleChild(long nIndex)
throw (uno::RuntimeException,
lang::IndexOutOfBoundsException)
{
ScUnoGuard aGuard;
uno::Reference<XAccessible> xAccessible;// = GetChild(nIndex);
if (!xAccessible.is())
{
if (nIndex == 0)
xAccessible = GetAccessibleSpreadsheet();
else
{
DBG_ERROR("should return other childs here");
// there is no child with this index at the moment
throw lang::IndexOutOfBoundsException();
}
//SetChild(nIndex, xAccessible);
}
return xAccessible;
}
/// Return the set of current states.
uno::Reference<XAccessibleStateSet> SAL_CALL
ScAccessibleDocument::getAccessibleStateSet(void)
throw (uno::RuntimeException)
{
ScUnoGuard aGuard;
uno::Reference<XAccessibleStateSet> xParentStates;
if (getAccessibleParent().is())
{
uno::Reference<XAccessibleContext> xParentContext = getAccessibleParent()->getAccessibleContext();
xParentStates = xParentContext->getAccessibleStateSet();
}
utl::AccessibleStateSetHelper* pStateSet = new utl::AccessibleStateSetHelper();
if (IsDefunc(xParentStates))
pStateSet->AddState(AccessibleStateType::DEFUNC);
if (IsEditable(xParentStates))
pStateSet->AddState(AccessibleStateType::EDITABLE);
pStateSet->AddState(AccessibleStateType::ENABLED);
pStateSet->AddState(AccessibleStateType::OPAQUE);
if (isShowing())
pStateSet->AddState(AccessibleStateType::SHOWING);
if (isVisible())
pStateSet->AddState(AccessibleStateType::VISIBLE);
return pStateSet;
}
//===== XServiceInfo ====================================================
::rtl::OUString SAL_CALL
ScAccessibleDocument::getImplementationName(void)
throw (uno::RuntimeException)
{
return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM ("ScAccessibleDocument"));
}
uno::Sequence< ::rtl::OUString> SAL_CALL
ScAccessibleDocument::getSupportedServiceNames(void)
throw (uno::RuntimeException)
{
uno::Sequence< ::rtl::OUString > aSequence = ScAccessibleContextBase::getSupportedServiceNames();
sal_Int32 nOldSize(aSequence.getLength());
aSequence.realloc(nOldSize + 1);
::rtl::OUString* pNames = aSequence.getArray();
pNames[nOldSize] = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("drafts.com.sun.star.AccessibleSpreadsheetDocumentView"));
return aSequence;
}
//===== XTypeProvider =======================================================
uno::Sequence<sal_Int8> SAL_CALL
ScAccessibleDocument::getImplementationId(void)
throw (uno::RuntimeException)
{
ScUnoGuard aGuard;
static uno::Sequence<sal_Int8> aId;
if (aId.getLength() == 0)
{
aId.realloc (16);
rtl_createUuid ((sal_uInt8 *)aId.getArray(), 0, sal_True);
}
return aId;
}
//===== internal ========================================================
::rtl::OUString SAL_CALL
ScAccessibleDocument::createAccessibleDescription(void)
throw (uno::RuntimeException)
{
return rtl::OUString(RTL_CONSTASCII_USTRINGPARAM ("This is a view of a Spreadsheet Document."));
}
::rtl::OUString SAL_CALL
ScAccessibleDocument::createAccessibleName(void)
throw (uno::RuntimeException)
{
ScUnoGuard aGuard;
rtl::OUString sName(RTL_CONSTASCII_USTRINGPARAM ("Spreadsheet Document View "));
sal_Int32 nNumber(sal_Int32(meSplitPos) + 1);
sName += rtl::OUString::valueOf(nNumber);
return sName;
}
Rectangle ScAccessibleDocument::GetBoundingBoxOnScreen()
throw (uno::RuntimeException)
{
Rectangle aRect;
if (mpViewShell)
{
Window* pWindow = mpViewShell->GetWindowByPos(meSplitPos);
if (pWindow)
aRect = pWindow->GetWindowExtentsRelative(NULL);
}
return aRect;
}
Rectangle ScAccessibleDocument::GetBoundingBox()
throw (uno::RuntimeException)
{
Rectangle aRect;
if (mpViewShell)
{
Window* pWindow = mpViewShell->GetWindowByPos(meSplitPos);
if (pWindow)
aRect = pWindow->GetWindowExtentsRelative(pWindow->GetAccessibleParentWindow());
}
return aRect;
}
sal_uInt16 ScAccessibleDocument::getVisibleTable()
{
sal_uInt16 nVisibleTable(0);
if (mpViewShell && mpViewShell->GetViewData())
nVisibleTable = mpViewShell->GetViewData()->GetTabNo();
return nVisibleTable;
}
uno::Reference < XAccessible >
ScAccessibleDocument::GetAccessibleSpreadsheet()
{
if (!mpAccessibleSpreadsheet && mpViewShell)
{
mpAccessibleSpreadsheet = new ScAccessibleSpreadsheet(this, mpViewShell, getVisibleTable(), meSplitPos);
mpAccessibleSpreadsheet->acquire();
mpAccessibleSpreadsheet->Init();
}
return mpAccessibleSpreadsheet;
}
void ScAccessibleDocument::FreeAccessibleSpreadsheet()
{
if (mpAccessibleSpreadsheet)
{
mpAccessibleSpreadsheet->SetDefunc();
mpAccessibleSpreadsheet->release();
mpAccessibleSpreadsheet = NULL;
}
}
SdrPage* ScAccessibleDocument::GetDrawPage()
{
sal_uInt16 nTab(getVisibleTable());
SdrPage* pDrawPage = NULL;
if (mpViewShell && mpViewShell->GetViewData())
{
ScDocument* pDoc = mpViewShell->GetViewData()->GetDocument();
if (pDoc && pDoc->GetDrawLayer())
{
ScDrawLayer* pDrawLayer = pDoc->GetDrawLayer();
if (pDrawLayer->HasObjects() && (pDrawLayer->GetPageCount() > nTab))
pDrawPage = pDrawLayer->GetPage(nTab);
}
}
return pDrawPage;
}
sal_Bool ScAccessibleDocument::IsDefunc(
const uno::Reference<XAccessibleStateSet>& rxParentStates)
{
return (mpViewShell == NULL) || !getAccessibleParent().is() ||
(rxParentStates.is() && rxParentStates->contains(AccessibleStateType::DEFUNC));
}
sal_Bool ScAccessibleDocument::IsEditable(
const uno::Reference<XAccessibleStateSet>& rxParentStates)
{
// what is with document protection?
return sal_True;
}
<commit_msg>#95584#; Eventsource is a XAccessible<commit_after>/*************************************************************************
*
* $RCSfile: AccessibleDocument.cxx,v $
*
* $Revision: 1.16 $
*
* last change: $Author: sab $ $Date: 2002-03-14 15:29:58 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SC_ACCESSIBLEDOCUMENT_HXX
#include "AccessibleDocument.hxx"
#endif
#ifndef _SC_ACCESSIBLESPREADSHEET_HXX
#include "AccessibleSpreadsheet.hxx"
#endif
#ifndef SC_TABVWSH_HXX
#include "tabvwsh.hxx"
#endif
#ifndef SC_ACCESSIBILITYHINTS_HXX
#include "AccessibilityHints.hxx"
#endif
#ifndef SC_DOCUMENT_HXX
#include "document.hxx"
#endif
#ifndef SC_DRWLAYER_HXX
#include "drwlayer.hxx"
#endif
#ifndef SC_UNOGUARD_HXX
#include "unoguard.hxx"
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEEVENTID_HPP_
#include <drafts/com/sun/star/accessibility/AccessibleEventId.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLESTATETYPE_HPP_
#include <drafts/com/sun/star/accessibility/AccessibleStateType.hpp>
#endif
#ifndef _UTL_ACCESSIBLESTATESETHELPER_HXX
#include <unotools/accessiblestatesethelper.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _SV_GEN_HXX
#include <tools/gen.hxx>
#endif
#ifndef _SVDPAGE_HXX
#include <svx/svdpage.hxx>
#endif
#ifndef _SVDOBJ_HXX
#include <svx/svdobj.hxx>
#endif
using namespace ::com::sun::star;
using namespace ::drafts::com::sun::star::accessibility;
//===== internal ========================================================
ScAccessibleDocument::ScAccessibleDocument(
const uno::Reference<XAccessible>& rxParent,
ScTabViewShell* pViewShell,
ScSplitPos eSplitPos)
: ScAccessibleDocumentBase(rxParent),
mpViewShell(pViewShell),
meSplitPos(eSplitPos),
mpAccessibleSpreadsheet(NULL)
{
if (pViewShell)
pViewShell->AddAccessibilityObject(*this);
}
ScAccessibleDocument::~ScAccessibleDocument(void)
{
FreeAccessibleSpreadsheet();
if (mpViewShell)
{
mpViewShell->RemoveAccessibilityObject(*this);
}
}
void ScAccessibleDocument::SetDefunc()
{
FreeAccessibleSpreadsheet();
if (mpViewShell)
{
mpViewShell->RemoveAccessibilityObject(*this);
mpViewShell = NULL;
}
ScAccessibleDocumentBase::SetDefunc();
}
//===== SfxListener =====================================================
void ScAccessibleDocument::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )
{
if (rHint.ISA( ScAccGridViewChangeHint ) )
{
const ScAccGridViewChangeHint& rRef = (const ScAccGridViewChangeHint&)rHint;
if ((rRef.GetOldGridWin() == meSplitPos) ||
(rRef.GetNewGridWin() == meSplitPos))
{
awt::FocusEvent aFocusEvent;
aFocusEvent.Temporary = sal_False;
if (rRef.GetOldGridWin() == meSplitPos)
{
aFocusEvent.NextFocus = rRef.GetNewAccessible();
CommitFocusLost(aFocusEvent);
}
else
{
aFocusEvent.NextFocus = rRef.GetOldAccessible();
CommitFocusGained(aFocusEvent);
}
}
}
else if (rHint.ISA( SfxSimpleHint ))
{
const SfxSimpleHint& rRef = (const SfxSimpleHint&)rHint;
// only notify if child exist, otherwise it is not necessary
if ((rRef.GetId() == SC_HINT_ACC_TABLECHANGED) &&
mpAccessibleSpreadsheet)
{
AccessibleEventObject aEvent;
aEvent.EventId = AccessibleEventId::ACCESSIBLE_CHILD_EVENT;
aEvent.Source = uno::Reference< XAccessible >(this);
aEvent.OldValue <<= GetAccessibleSpreadsheet();
CommitChange(aEvent); // child is gone - event
aEvent.OldValue = uno::Any();
FreeAccessibleSpreadsheet(); // free the spreadsheet after free the reference on this object
aEvent.NewValue <<= GetAccessibleSpreadsheet();
CommitChange(aEvent); // there is a new child - event
}
else if (rRef.GetId() == SFX_HINT_DYING)
{
// it seems the Broadcaster is dying, since the view is dying
SetDefunc();
}
}
}
//===== XAccessibleComponent ============================================
uno::Reference< XAccessible > SAL_CALL ScAccessibleDocument::getAccessibleAt(
const awt::Point& rPoint )
throw (uno::RuntimeException)
{
ScUnoGuard aGuard;
uno::Reference<XAccessible> xAccessible = NULL;
SdrPage* pDrawPage = GetDrawPage();
if (pDrawPage)
{
DBG_ERROR("not implemented");
}
else
xAccessible = GetAccessibleSpreadsheet();
return xAccessible;
}
void SAL_CALL ScAccessibleDocument::grabFocus( )
throw (uno::RuntimeException)
{
ScUnoGuard aGuard;
if (getAccessibleParent().is())
{
uno::Reference<XAccessibleComponent> xAccessibleComponent(getAccessibleParent()->getAccessibleContext(), uno::UNO_QUERY);
if (xAccessibleComponent.is())
{
xAccessibleComponent->grabFocus();
// grab only focus if it does not have the focus and it is not hidden
if (mpViewShell && mpViewShell->GetViewData() &&
(mpViewShell->GetViewData()->GetActivePart() != meSplitPos) &&
mpViewShell->GetWindowByPos(meSplitPos)->IsVisible())
{
mpViewShell->ActivatePart(meSplitPos);
}
}
}
}
//===== XAccessibleContext ==============================================
/// Return the number of currently visible children.
long SAL_CALL
ScAccessibleDocument::getAccessibleChildCount(void)
throw (uno::RuntimeException)
{
ScUnoGuard aGuard;
sal_Int32 nShapes (0);
SdrPage* pDrawPage = GetDrawPage();
if (pDrawPage)
{
sal_uInt32 nObjCount(pDrawPage->GetObjCount());
for (sal_uInt32 i = 0; i < nObjCount; i++)
{
SdrObject* pObj = pDrawPage->GetObj(i);
if (pObj && (pObj->GetLayer() != SC_LAYER_INTERN))
nShapes++;
}
}
return nShapes + 1;
}
/// Return the specified child or NULL if index is invalid.
uno::Reference<XAccessible> SAL_CALL
ScAccessibleDocument::getAccessibleChild(long nIndex)
throw (uno::RuntimeException,
lang::IndexOutOfBoundsException)
{
ScUnoGuard aGuard;
uno::Reference<XAccessible> xAccessible;// = GetChild(nIndex);
if (!xAccessible.is())
{
if (nIndex == 0)
xAccessible = GetAccessibleSpreadsheet();
else
{
DBG_ERROR("should return other childs here");
// there is no child with this index at the moment
throw lang::IndexOutOfBoundsException();
}
//SetChild(nIndex, xAccessible);
}
return xAccessible;
}
/// Return the set of current states.
uno::Reference<XAccessibleStateSet> SAL_CALL
ScAccessibleDocument::getAccessibleStateSet(void)
throw (uno::RuntimeException)
{
ScUnoGuard aGuard;
uno::Reference<XAccessibleStateSet> xParentStates;
if (getAccessibleParent().is())
{
uno::Reference<XAccessibleContext> xParentContext = getAccessibleParent()->getAccessibleContext();
xParentStates = xParentContext->getAccessibleStateSet();
}
utl::AccessibleStateSetHelper* pStateSet = new utl::AccessibleStateSetHelper();
if (IsDefunc(xParentStates))
pStateSet->AddState(AccessibleStateType::DEFUNC);
if (IsEditable(xParentStates))
pStateSet->AddState(AccessibleStateType::EDITABLE);
pStateSet->AddState(AccessibleStateType::ENABLED);
pStateSet->AddState(AccessibleStateType::OPAQUE);
if (isShowing())
pStateSet->AddState(AccessibleStateType::SHOWING);
if (isVisible())
pStateSet->AddState(AccessibleStateType::VISIBLE);
return pStateSet;
}
//===== XServiceInfo ====================================================
::rtl::OUString SAL_CALL
ScAccessibleDocument::getImplementationName(void)
throw (uno::RuntimeException)
{
return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM ("ScAccessibleDocument"));
}
uno::Sequence< ::rtl::OUString> SAL_CALL
ScAccessibleDocument::getSupportedServiceNames(void)
throw (uno::RuntimeException)
{
uno::Sequence< ::rtl::OUString > aSequence = ScAccessibleContextBase::getSupportedServiceNames();
sal_Int32 nOldSize(aSequence.getLength());
aSequence.realloc(nOldSize + 1);
::rtl::OUString* pNames = aSequence.getArray();
pNames[nOldSize] = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("drafts.com.sun.star.AccessibleSpreadsheetDocumentView"));
return aSequence;
}
//===== XTypeProvider =======================================================
uno::Sequence<sal_Int8> SAL_CALL
ScAccessibleDocument::getImplementationId(void)
throw (uno::RuntimeException)
{
ScUnoGuard aGuard;
static uno::Sequence<sal_Int8> aId;
if (aId.getLength() == 0)
{
aId.realloc (16);
rtl_createUuid ((sal_uInt8 *)aId.getArray(), 0, sal_True);
}
return aId;
}
//===== internal ========================================================
::rtl::OUString SAL_CALL
ScAccessibleDocument::createAccessibleDescription(void)
throw (uno::RuntimeException)
{
return rtl::OUString(RTL_CONSTASCII_USTRINGPARAM ("This is a view of a Spreadsheet Document."));
}
::rtl::OUString SAL_CALL
ScAccessibleDocument::createAccessibleName(void)
throw (uno::RuntimeException)
{
ScUnoGuard aGuard;
rtl::OUString sName(RTL_CONSTASCII_USTRINGPARAM ("Spreadsheet Document View "));
sal_Int32 nNumber(sal_Int32(meSplitPos) + 1);
sName += rtl::OUString::valueOf(nNumber);
return sName;
}
Rectangle ScAccessibleDocument::GetBoundingBoxOnScreen()
throw (uno::RuntimeException)
{
Rectangle aRect;
if (mpViewShell)
{
Window* pWindow = mpViewShell->GetWindowByPos(meSplitPos);
if (pWindow)
aRect = pWindow->GetWindowExtentsRelative(NULL);
}
return aRect;
}
Rectangle ScAccessibleDocument::GetBoundingBox()
throw (uno::RuntimeException)
{
Rectangle aRect;
if (mpViewShell)
{
Window* pWindow = mpViewShell->GetWindowByPos(meSplitPos);
if (pWindow)
aRect = pWindow->GetWindowExtentsRelative(pWindow->GetAccessibleParentWindow());
}
return aRect;
}
sal_uInt16 ScAccessibleDocument::getVisibleTable()
{
sal_uInt16 nVisibleTable(0);
if (mpViewShell && mpViewShell->GetViewData())
nVisibleTable = mpViewShell->GetViewData()->GetTabNo();
return nVisibleTable;
}
uno::Reference < XAccessible >
ScAccessibleDocument::GetAccessibleSpreadsheet()
{
if (!mpAccessibleSpreadsheet && mpViewShell)
{
mpAccessibleSpreadsheet = new ScAccessibleSpreadsheet(this, mpViewShell, getVisibleTable(), meSplitPos);
mpAccessibleSpreadsheet->acquire();
mpAccessibleSpreadsheet->Init();
}
return mpAccessibleSpreadsheet;
}
void ScAccessibleDocument::FreeAccessibleSpreadsheet()
{
if (mpAccessibleSpreadsheet)
{
mpAccessibleSpreadsheet->SetDefunc();
mpAccessibleSpreadsheet->release();
mpAccessibleSpreadsheet = NULL;
}
}
SdrPage* ScAccessibleDocument::GetDrawPage()
{
sal_uInt16 nTab(getVisibleTable());
SdrPage* pDrawPage = NULL;
if (mpViewShell && mpViewShell->GetViewData())
{
ScDocument* pDoc = mpViewShell->GetViewData()->GetDocument();
if (pDoc && pDoc->GetDrawLayer())
{
ScDrawLayer* pDrawLayer = pDoc->GetDrawLayer();
if (pDrawLayer->HasObjects() && (pDrawLayer->GetPageCount() > nTab))
pDrawPage = pDrawLayer->GetPage(nTab);
}
}
return pDrawPage;
}
sal_Bool ScAccessibleDocument::IsDefunc(
const uno::Reference<XAccessibleStateSet>& rxParentStates)
{
return (mpViewShell == NULL) || !getAccessibleParent().is() ||
(rxParentStates.is() && rxParentStates->contains(AccessibleStateType::DEFUNC));
}
sal_Bool ScAccessibleDocument::IsEditable(
const uno::Reference<XAccessibleStateSet>& rxParentStates)
{
// what is with document protection?
return sal_True;
}
<|endoftext|>
|
<commit_before>/*---------------------------------------------------------------------\
| |
| _ _ _ _ __ _ |
| | | | | | \_/ | / \ | | |
| | | | | | |_| | / /\ \ | | |
| | |__ | | | | | | / ____ \ | |__ |
| |____||_| |_| |_|/ / \ \|____| |
| |
| ca-mgm library |
| |
| (C) SUSE Linux Products GmbH |
\----------------------------------------------------------------------/
File: DNObject.cpp
Author: <Michael Calmer> <mc@suse.de>
Maintainer: <Michael Calmer> <mc@suse.de>
Purpose:
/-*/
#include <limal/ca-mgm/DNObject.hpp>
#include <limal/ValueRegExCheck.hpp>
#include <limal/Exception.hpp>
#include <blocxx/Format.hpp>
#include "Utils.hpp"
using namespace limal;
using namespace limal::ca_mgm;
using namespace blocxx;
RDNObject::RDNObject()
: type(String()), value(String())
{
}
RDNObject::RDNObject(const String& type, const String& value)
: type(type), value(value)
{}
RDNObject::RDNObject(const RDNObject& rdn)
: type(rdn.type), value(rdn.value)
{}
RDNObject::~RDNObject()
{}
RDNObject&
RDNObject::operator=(const RDNObject& rdn)
{
if(this == &rdn) return *this;
type = rdn.type;
value = rdn.value;
return *this;
}
void
RDNObject::setRDN(const String& type, const String& value)
{
this->type = type;
this->value = value;
}
blocxx::String
RDNObject::getType() const
{
return type;
}
blocxx::String
RDNObject::getValue() const
{
return value;
}
bool
RDNObject::valid() const
{
if(type.empty()) {
LOGIT_DEBUG("type is empty");
return false;
}
if(value.empty()) {
LOGIT_DEBUG("value is empty");
return false;
}
// FIXME: define and check pre defined types ?
return true;
}
blocxx::StringArray
RDNObject::verify() const
{
StringArray result;
if(type.empty()) {
result.append("type is empty");
}
if(value.empty()) {
result.append("value is empty");
}
// FIXME: define and check pre defined types ?
LOGIT_DEBUG_STRINGARRAY("RDNObject::verify()", result);
return result;
}
blocxx::StringArray
RDNObject::dump() const
{
StringArray result;
result.append("RDNObject::dump()");
result.append(type + "=" + value);
return result;
}
// ######################################################################
DNObject::DNObject()
: dn(blocxx::List<RDNObject>())
{
}
DNObject::DNObject(const blocxx::List<RDNObject> &dn)
: dn(dn)
{
StringArray r = this->verify();
if(!r.empty()) {
BLOCXX_THROW(limal::ValueException, r[0].c_str());
}
}
DNObject::DNObject(const DNObject& dn)
: dn(dn.dn)
{}
DNObject::~DNObject()
{}
DNObject&
DNObject::operator=(const DNObject& dn)
{
if(this == &dn) return *this;
this->dn = dn.dn;
return *this;
}
void
DNObject::setDN(const blocxx::List<RDNObject> &dn)
{
StringArray r = checkRDNList(dn);
if(!r.empty()) {
LOGIT_ERROR(r[0]);
BLOCXX_THROW(limal::ValueException, r[0].c_str());
}
this->dn = dn;
}
blocxx::List<RDNObject>
DNObject::getDN() const
{
return dn;
}
bool
DNObject::valid() const
{
if(dn.empty()) {
LOGIT_DEBUG("empty DN");
return false;
}
StringArray r = checkRDNList(dn);
if(!r.empty()) {
LOGIT_DEBUG(r[0]);
return false;
}
return true;
}
blocxx::StringArray
DNObject::verify() const
{
StringArray result;
if(dn.empty()) {
result.append("empty DN");
}
result.appendArray(checkRDNList(dn));
LOGIT_DEBUG_STRINGARRAY("DNObject::verify()", result);
return result;
}
blocxx::StringArray
DNObject::checkRDNList(const blocxx::List<RDNObject>& list) const
{
StringArray result;
blocxx::List<RDNObject>::const_iterator it = list.begin();
for(; it != list.end(); ++it) {
result.appendArray((*it).verify());
}
return result;
}
blocxx::StringArray
DNObject::dump() const
{
StringArray result;
result.append("DNObject::dump()");
blocxx::List< RDNObject >::const_iterator it = dn.begin();
for(; it != dn.end(); ++it) {
result.appendArray((*it).dump());
}
return result;
}
<commit_msg>return default DN list<commit_after>/*---------------------------------------------------------------------\
| |
| _ _ _ _ __ _ |
| | | | | | \_/ | / \ | | |
| | | | | | |_| | / /\ \ | | |
| | |__ | | | | | | / ____ \ | |__ |
| |____||_| |_| |_|/ / \ \|____| |
| |
| ca-mgm library |
| |
| (C) SUSE Linux Products GmbH |
\----------------------------------------------------------------------/
File: DNObject.cpp
Author: <Michael Calmer> <mc@suse.de>
Maintainer: <Michael Calmer> <mc@suse.de>
Purpose:
/-*/
#include <limal/ca-mgm/DNObject.hpp>
#include <limal/ValueRegExCheck.hpp>
#include <limal/Exception.hpp>
#include <blocxx/Format.hpp>
#include "Utils.hpp"
using namespace limal;
using namespace limal::ca_mgm;
using namespace blocxx;
RDNObject::RDNObject()
: type(String()), value(String())
{
}
RDNObject::RDNObject(const String& type, const String& value)
: type(type), value(value)
{}
RDNObject::RDNObject(const RDNObject& rdn)
: type(rdn.type), value(rdn.value)
{}
RDNObject::~RDNObject()
{}
RDNObject&
RDNObject::operator=(const RDNObject& rdn)
{
if(this == &rdn) return *this;
type = rdn.type;
value = rdn.value;
return *this;
}
void
RDNObject::setRDN(const String& type, const String& value)
{
this->type = type;
this->value = value;
}
blocxx::String
RDNObject::getType() const
{
return type;
}
blocxx::String
RDNObject::getValue() const
{
return value;
}
bool
RDNObject::valid() const
{
if(type.empty()) {
LOGIT_DEBUG("type is empty");
return false;
}
/*
if(value.empty()) {
LOGIT_DEBUG("value is empty");
return false;
}
*/
// FIXME: define and check pre defined types ?
return true;
}
blocxx::StringArray
RDNObject::verify() const
{
StringArray result;
if(type.empty()) {
result.append("type is empty");
}
/*
if(value.empty()) {
result.append("value is empty");
}
*/
// FIXME: define and check pre defined types ?
LOGIT_DEBUG_STRINGARRAY("RDNObject::verify()", result);
return result;
}
blocxx::StringArray
RDNObject::dump() const
{
StringArray result;
result.append("RDNObject::dump()");
result.append(type + "=" + value);
return result;
}
// ######################################################################
DNObject::DNObject()
: dn(blocxx::List<RDNObject>())
{
dn.push_back(RDNObject("countryName", ""));
dn.push_back(RDNObject("stateOrProvinceName", ""));
dn.push_back(RDNObject("localityName", ""));
dn.push_back(RDNObject("organizationName", ""));
dn.push_back(RDNObject("organizationalUnitName", ""));
dn.push_back(RDNObject("commonName", ""));
dn.push_back(RDNObject("emailAddress", ""));
}
DNObject::DNObject(const blocxx::List<RDNObject> &dn)
: dn(dn)
{
StringArray r = this->verify();
if(!r.empty()) {
BLOCXX_THROW(limal::ValueException, r[0].c_str());
}
}
DNObject::DNObject(const DNObject& dn)
: dn(dn.dn)
{}
DNObject::~DNObject()
{}
DNObject&
DNObject::operator=(const DNObject& dn)
{
if(this == &dn) return *this;
this->dn = dn.dn;
return *this;
}
void
DNObject::setDN(const blocxx::List<RDNObject> &dn)
{
StringArray r = checkRDNList(dn);
if(!r.empty()) {
LOGIT_ERROR(r[0]);
BLOCXX_THROW(limal::ValueException, r[0].c_str());
}
this->dn = dn;
}
blocxx::List<RDNObject>
DNObject::getDN() const
{
return dn;
}
bool
DNObject::valid() const
{
if(dn.empty()) {
LOGIT_DEBUG("empty DN");
return false;
}
StringArray r = checkRDNList(dn);
if(!r.empty()) {
LOGIT_DEBUG(r[0]);
return false;
}
return true;
}
blocxx::StringArray
DNObject::verify() const
{
StringArray result;
if(dn.empty()) {
result.append("empty DN");
}
result.appendArray(checkRDNList(dn));
LOGIT_DEBUG_STRINGARRAY("DNObject::verify()", result);
return result;
}
blocxx::StringArray
DNObject::checkRDNList(const blocxx::List<RDNObject>& list) const
{
StringArray result;
blocxx::List<RDNObject>::const_iterator it = list.begin();
for(; it != list.end(); ++it) {
result.appendArray((*it).verify());
}
return result;
}
blocxx::StringArray
DNObject::dump() const
{
StringArray result;
result.append("DNObject::dump()");
blocxx::List< RDNObject >::const_iterator it = dn.begin();
for(; it != dn.end(); ++it) {
result.appendArray((*it).dump());
}
return result;
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include "TObjArray.h"
#include "TTimer.h"
#include "TThread.h"
#include "AliEveEventBuffer.h"
//Not needed, only for debug
#include "AliESDEvent.h"
using namespace std;
ClassImp(AliEveEventBuffer)
///_______________________________________________________________________
AliEveEventBuffer::AliEveEventBuffer() :
fBufferSize(10),
fPreBuffer(4),
fBusy(kFALSE),
fEventBuffer(NULL),
fCurrentEvent(NULL),
fBIndex(),
fTimer(NULL),
fEventId(),
fBufferMonStarted(kFALSE)
{
// see header file for class documentation
fEventBuffer = new TObjArray(fBufferSize, 0);
fEventBuffer->SetOwner(kFALSE);
for(int id = 0; id < kSize; id++) {
fBIndex[id] = -1;
}
fTimer = new TTimer();
fTimer->Connect("Timeout()", "AliEveEventBuffer", this, "CreateBufferThread()");
fEventId = new ULong64_t[fBufferSize];
for(Int_t id = 0; id < fBufferSize; id++ ) {
fEventId[id] = -2;
}
}
///_______________________________________________________________________
AliEveEventBuffer::~AliEveEventBuffer() {
// see header file for class documentation
if ( fEventBuffer ) {
fEventBuffer->Clear();
delete fEventBuffer;
}
fEventBuffer = NULL;
if(fCurrentEvent)
delete fCurrentEvent;
fCurrentEvent = NULL;
}
///___________________________________________________________________________
void AliEveEventBuffer::CreateBufferThread() {
if(GetBusy()) {
cout << "Buffer is busy, no thread created"<< endl;
} else {
SetBusy(kTRUE);
if ( (CalculateDifference(fBIndex[kTop],fBIndex[kLast]) < fPreBuffer) ) {
cout << "CreateBufferThread()"<<endl;
TThread * fThread = new TThread(AliEveEventBuffer::BufferThread, (void*) this);
fThread->Run();
cout << "Started BufferThread"<<endl;
} else {
cout << "Buffer is full already"<<endl;
}
}
}
///___________________________________________________________________________
void * AliEveEventBuffer::BufferThread(void * buffer) {
cout <<"BufferThread : " <<endl;
if(buffer) {
reinterpret_cast<AliEveEventBuffer*>(buffer)->MonitorBuffer();
} else {
cout << "no buffer"<<endl;
}
return (void*)0;
}
///_____________________________________________________________________________
void AliEveEventBuffer::MonitorBuffer() {
cout << "Monitorbuffer() ";
SetBusy(kTRUE);
FetchEvent();
SetBusy(kFALSE);
cout << "done " << endl;
}
///_______________________________________________________________________________
TObject * AliEveEventBuffer::NextEvent() {
//See header file for documentation
cout << "NextEvent()"<<endl;
TObject * nextEvent = GetNextUnSeen();
return nextEvent;
}
///______________________________________________________________________________
TObject * AliEveEventBuffer::Back() {
cout << "go back"<<endl;
PrintIndeces();
Int_t prevId = CalculatePrevious(fBIndex[kCurrent]);
if(prevId == fBIndex[kTop]) {
cout << "returning NULL" << endl;
return NULL;
} else {
fBIndex[kCurrent] = prevId;
PrintIndeces();
cout <<"returning: "<< fBIndex[kCurrent] << " " << fEventBuffer->At(fBIndex[kCurrent]);
return fEventBuffer->At(fBIndex[kCurrent]);
}
}
///______________________________________________________________________________
TObject * AliEveEventBuffer::Fwd() {
PrintIndeces();
if (fBIndex[kCurrent] == fBIndex[kLast]) {
cout<< "returning NULL"<<endl;
return NULL;
}
fBIndex[kCurrent] = CalculateNext(fBIndex[kCurrent]);
TObject * event = fEventBuffer->At(fBIndex[kCurrent]);
return event;
}
///________________________________________________________________________________
TObject * AliEveEventBuffer::GetNextUnSeen() {
//See header file for documentation
cout << "GetNextUnSeen"<<endl;
PrintIndeces();
if(CalculateDifference(fBIndex[kTop], fBIndex[kLast])) {
fBIndex[kLast] = CalculateNext(fBIndex[kLast]);
fBIndex[kCurrent] = fBIndex[kLast];
PrintIndeces();
return fEventBuffer->At(fBIndex[kCurrent]);
} else {
cout << "No new event available, only events in buffer available!"<<endl;
return NULL;
}
}
///_________________________________________________________________________________
void AliEveEventBuffer::PrintIndeces() {
for(Int_t i = 0; i < kSize; i++) {
cout << i << ": " << fBIndex[i] << endl;
}
}
///_________________________________________________________________________________
void AliEveEventBuffer::PrintBuffer() {
for(Int_t i = 0; i < 10; i++) {
AliESDEvent * event = dynamic_cast<AliESDEvent*>(fEventBuffer->At(i));
if(event) {
cout << i << ": " <<event << " " << event->GetEventNumberInFile() << endl;;
}
}
}
///____________________________________________________________________________________
void AliEveEventBuffer::FetchEvent() {
cout << "FetchEvent " << endl;
TObject * event = GetEventFromSource();
ULong64_t eventId = GetEventIdFromSource();
if(event) {
AddToBuffer(event);
fEventId[fBIndex[kTop]] = eventId;
}
PrintIndeces();
cout << "FetchedEvent " << endl;
}
///_________________________________________________________________________________
void AliEveEventBuffer::AddToBuffer(TObject * event) {
cout << "Add to buffer"<<endl;
if(!event) return;
fBIndex[kTop] = CalculateNext(fBIndex[kTop]);
//Delete the event already there (ok to delete as object, not aliesdevent, TList?)
//TObject * object = fEventBuffer->At(fBIndex[kTop]);
fEventBuffer->RemoveAt(fBIndex[kTop]);
//if (object) delete object;
fEventBuffer->AddAt(event, fBIndex[kTop]);
}
///_____________________________________________________________________________________
Int_t AliEveEventBuffer::CalculateNext(Int_t current) {
//See header file for documentation
current++;
if(current == fBufferSize) current = 0;
return current;
}
///_____________________________________________________________________________________
Int_t AliEveEventBuffer::CalculatePrevious(Int_t current) {
//See header file for documentation
cout << "CalculatePrev: " << current;
current--;
if(current == -1) current += fBufferSize;
cout << "... " << current << endl;
return current;
}
///__________________________________________________________________________________
Int_t AliEveEventBuffer::CalculateDifference(Int_t top, Int_t low) {
//See header file for documentation
if (top > low) {
// cout << "top > low"<<endl;
return (top - low);
} else if (top < low) {
// cout << "low < top"<<endl;
return (fBufferSize - low + top);
} else {
//cout << "calculated to 0"<<endl;
return 0;
}
}
///___________________________________________________________________________________
void AliEveEventBuffer::StartBufferMonitor() {
//cout << "NOT !!! starting buffer mon"<<endl;
cout << "starting buffer mon"<<endl;
if(!GetBufferMonStarted()) {
CreateBufferThread();
SetBufferMonStarted(kTRUE);
fTimer->Start(3000);
} else {
cout << "Stopping buffer monitor"<<endl;
fTimer->Stop();
SetBufferMonStarted(kFALSE);
}
}
///___________________________________________________________________________________
void AliEveEventBuffer::StopBufferMonitor() {
cout << "Stopping buffer mon"<<endl;
SetBufferMonStarted(kFALSE);
fTimer->Stop();
}
// //_________________________________________________________________________________
// Int_t AliEveEventBuffer::NavigateEventBufferBack() {
// // see header file for class documentation
// // -- reached the end of the buffer
// if ( fNavigateBufferIdx == fBufferLowIdx )
// return -1;
// Int_t newIdx = fNavigateBufferIdx - 1;
// if ( newIdx == -1 )
// newIdx = BUFFERSIZE-1;
// fCurrentBufferIdx = fNavigateBufferIdx = newIdx;
// return newIdx;
// }
// //_______________________________________________________________
// Int_t AliEveEventBuffer::NavigateEventBufferFwd() {
// // see header file for class documentation
// // -- reached the top of the buffer
// if ( fNavigateBufferIdx == fBufferTopIdx )
// return -1;
// Int_t newIdx = fNavigateBufferIdx + 1;
// if ( newIdx == BUFFERSIZE )
// newIdx = 0;
// fCurrentBufferIdx = fNavigateBufferIdx = newIdx;
// return newIdx;
// }
// void AliEveEventBuffer::MonitorBuffer() {
// //See header file for documentation
// if( GetNAvailableEvents() < 10) {
// StopBufferChecker();
// StartLoop();
// }
// }
// void AliEveEventBuffer::StartLoop() {
// //See header file for documentation
// fTimer->Start(2000);
// }
// void AliEveEventBuffer::StopLoop() {
// //See header file for documentation
// fTimer->Stop();
// }
// void AliEveEventBuffer::StartBufferChecker() {
// //See header file for documentation
// fBufferTimer->Start(2000);
// }
// void AliEveEventBuffer::StopBufferChecker() {
// //See header file for documentation
// fBufferTimer->Stop();
// }
// AliESDEvent * GetNextEvent() {
// tree->GetEntry(fEvent++);
// AliESDEvent * event = new AliESDEvent();
// event->ReadFromTree(fTree);
// if (event) {
// return event;
// } else {
// cout << "error getting event" << endl;
// return NULL;
// }
// }
<commit_msg>Fixed busy error<commit_after>#include <iostream>
#include "TObjArray.h"
#include "TTimer.h"
#include "TThread.h"
#include "AliEveEventBuffer.h"
//Not needed, only for debug
#include "AliESDEvent.h"
using namespace std;
ClassImp(AliEveEventBuffer)
///_______________________________________________________________________
AliEveEventBuffer::AliEveEventBuffer() :
fBufferSize(10),
fPreBuffer(4),
fBusy(kFALSE),
fEventBuffer(NULL),
fCurrentEvent(NULL),
fBIndex(),
fTimer(NULL),
fEventId(),
fBufferMonStarted(kFALSE)
{
// see header file for class documentation
fEventBuffer = new TObjArray(fBufferSize, 0);
fEventBuffer->SetOwner(kFALSE);
for(int id = 0; id < kSize; id++) {
fBIndex[id] = -1;
}
fTimer = new TTimer();
fTimer->Connect("Timeout()", "AliEveEventBuffer", this, "CreateBufferThread()");
fEventId = new ULong64_t[fBufferSize];
for(Int_t id = 0; id < fBufferSize; id++ ) {
fEventId[id] = -2;
}
}
///_______________________________________________________________________
AliEveEventBuffer::~AliEveEventBuffer() {
// see header file for class documentation
if ( fEventBuffer ) {
fEventBuffer->Clear();
delete fEventBuffer;
}
fEventBuffer = NULL;
if(fCurrentEvent)
delete fCurrentEvent;
fCurrentEvent = NULL;
}
///___________________________________________________________________________
void AliEveEventBuffer::CreateBufferThread() {
if(GetBusy()) {
cout << "Buffer is busy, no thread created"<< endl;
} else {
if ( (CalculateDifference(fBIndex[kTop],fBIndex[kLast]) < fPreBuffer) ) {
SetBusy(kTRUE);
cout << "CreateBufferThread()"<<endl;
TThread * fThread = new TThread(AliEveEventBuffer::BufferThread, (void*) this);
fThread->Run();
cout << "Started BufferThread"<<endl;
} else {
cout << "Buffer is full already"<<endl;
}
}
}
///___________________________________________________________________________
void * AliEveEventBuffer::BufferThread(void * buffer) {
cout <<"BufferThread : " <<endl;
if(buffer) {
reinterpret_cast<AliEveEventBuffer*>(buffer)->MonitorBuffer();
} else {
cout << "no buffer"<<endl;
}
return (void*)0;
}
///_____________________________________________________________________________
void AliEveEventBuffer::MonitorBuffer() {
cout << "Monitorbuffer() ";
SetBusy(kTRUE);
FetchEvent();
SetBusy(kFALSE);
cout << "done " << endl;
}
///_______________________________________________________________________________
TObject * AliEveEventBuffer::NextEvent() {
//See header file for documentation
cout << "NextEvent()"<<endl;
TObject * nextEvent = GetNextUnSeen();
return nextEvent;
}
///______________________________________________________________________________
TObject * AliEveEventBuffer::Back() {
cout << "go back"<<endl;
PrintIndeces();
Int_t prevId = CalculatePrevious(fBIndex[kCurrent]);
if(prevId == fBIndex[kTop]) {
cout << "returning NULL" << endl;
return NULL;
} else {
fBIndex[kCurrent] = prevId;
PrintIndeces();
cout <<"returning: "<< fBIndex[kCurrent] << " " << fEventBuffer->At(fBIndex[kCurrent]);
return fEventBuffer->At(fBIndex[kCurrent]);
}
}
///______________________________________________________________________________
TObject * AliEveEventBuffer::Fwd() {
PrintIndeces();
if (fBIndex[kCurrent] == fBIndex[kLast]) {
cout<< "returning NULL"<<endl;
return NULL;
}
fBIndex[kCurrent] = CalculateNext(fBIndex[kCurrent]);
TObject * event = fEventBuffer->At(fBIndex[kCurrent]);
return event;
}
///________________________________________________________________________________
TObject * AliEveEventBuffer::GetNextUnSeen() {
//See header file for documentation
cout << "GetNextUnSeen"<<endl;
PrintIndeces();
if(CalculateDifference(fBIndex[kTop], fBIndex[kLast])) {
fBIndex[kLast] = CalculateNext(fBIndex[kLast]);
fBIndex[kCurrent] = fBIndex[kLast];
PrintIndeces();
return fEventBuffer->At(fBIndex[kCurrent]);
} else {
cout << "No new event available, only events in buffer available!"<<endl;
return NULL;
}
}
///_________________________________________________________________________________
void AliEveEventBuffer::PrintIndeces() {
for(Int_t i = 0; i < kSize; i++) {
cout << i << ": " << fBIndex[i] << endl;
}
}
///_________________________________________________________________________________
void AliEveEventBuffer::PrintBuffer() {
for(Int_t i = 0; i < 10; i++) {
AliESDEvent * event = dynamic_cast<AliESDEvent*>(fEventBuffer->At(i));
if(event) {
cout << i << ": " <<event << " " << event->GetEventNumberInFile() << endl;;
}
}
}
///____________________________________________________________________________________
void AliEveEventBuffer::FetchEvent() {
cout << "FetchEvent " << endl;
TObject * event = GetEventFromSource();
ULong64_t eventId = GetEventIdFromSource();
if(event) {
AddToBuffer(event);
fEventId[fBIndex[kTop]] = eventId;
}
PrintIndeces();
cout << "FetchedEvent " << endl;
}
///_________________________________________________________________________________
void AliEveEventBuffer::AddToBuffer(TObject * event) {
cout << "Add to buffer"<<endl;
if(!event) return;
fBIndex[kTop] = CalculateNext(fBIndex[kTop]);
//Delete the event already there (ok to delete as object, not aliesdevent, TList?)
//TObject * object = fEventBuffer->At(fBIndex[kTop]);
fEventBuffer->RemoveAt(fBIndex[kTop]);
//if (object) delete object;
fEventBuffer->AddAt(event, fBIndex[kTop]);
}
///_____________________________________________________________________________________
Int_t AliEveEventBuffer::CalculateNext(Int_t current) {
//See header file for documentation
current++;
if(current == fBufferSize) current = 0;
return current;
}
///_____________________________________________________________________________________
Int_t AliEveEventBuffer::CalculatePrevious(Int_t current) {
//See header file for documentation
cout << "CalculatePrev: " << current;
current--;
if(current == -1) current += fBufferSize;
cout << "... " << current << endl;
return current;
}
///__________________________________________________________________________________
Int_t AliEveEventBuffer::CalculateDifference(Int_t top, Int_t low) {
//See header file for documentation
if (top > low) {
// cout << "top > low"<<endl;
return (top - low);
} else if (top < low) {
// cout << "low < top"<<endl;
return (fBufferSize - low + top);
} else {
//cout << "calculated to 0"<<endl;
return 0;
}
}
///___________________________________________________________________________________
void AliEveEventBuffer::StartBufferMonitor() {
//cout << "NOT !!! starting buffer mon"<<endl;
cout << "starting buffer mon"<<endl;
if(!GetBufferMonStarted()) {
CreateBufferThread();
SetBufferMonStarted(kTRUE);
fTimer->Start(3000);
} else {
cout << "Stopping buffer monitor"<<endl;
fTimer->Stop();
SetBufferMonStarted(kFALSE);
}
}
///___________________________________________________________________________________
void AliEveEventBuffer::StopBufferMonitor() {
cout << "Stopping buffer mon"<<endl;
SetBufferMonStarted(kFALSE);
fTimer->Stop();
}
// //_________________________________________________________________________________
// Int_t AliEveEventBuffer::NavigateEventBufferBack() {
// // see header file for class documentation
// // -- reached the end of the buffer
// if ( fNavigateBufferIdx == fBufferLowIdx )
// return -1;
// Int_t newIdx = fNavigateBufferIdx - 1;
// if ( newIdx == -1 )
// newIdx = BUFFERSIZE-1;
// fCurrentBufferIdx = fNavigateBufferIdx = newIdx;
// return newIdx;
// }
// //_______________________________________________________________
// Int_t AliEveEventBuffer::NavigateEventBufferFwd() {
// // see header file for class documentation
// // -- reached the top of the buffer
// if ( fNavigateBufferIdx == fBufferTopIdx )
// return -1;
// Int_t newIdx = fNavigateBufferIdx + 1;
// if ( newIdx == BUFFERSIZE )
// newIdx = 0;
// fCurrentBufferIdx = fNavigateBufferIdx = newIdx;
// return newIdx;
// }
// void AliEveEventBuffer::MonitorBuffer() {
// //See header file for documentation
// if( GetNAvailableEvents() < 10) {
// StopBufferChecker();
// StartLoop();
// }
// }
// void AliEveEventBuffer::StartLoop() {
// //See header file for documentation
// fTimer->Start(2000);
// }
// void AliEveEventBuffer::StopLoop() {
// //See header file for documentation
// fTimer->Stop();
// }
// void AliEveEventBuffer::StartBufferChecker() {
// //See header file for documentation
// fBufferTimer->Start(2000);
// }
// void AliEveEventBuffer::StopBufferChecker() {
// //See header file for documentation
// fBufferTimer->Stop();
// }
// AliESDEvent * GetNextEvent() {
// tree->GetEntry(fEvent++);
// AliESDEvent * event = new AliESDEvent();
// event->ReadFromTree(fTree);
// if (event) {
// return event;
// } else {
// cout << "error getting event" << endl;
// return NULL;
// }
// }
<|endoftext|>
|
<commit_before><commit_msg>Fixing SPXRatio::Parse: data_stat and data_tot<commit_after><|endoftext|>
|
<commit_before>#ifndef CV_ADAPTERS_ROWRANGE_HPP
#define CV_ADAPTERS_ROWRANGE_HPP
#include <iterator>
#include <opencv2/core/core.hpp>
template <typename T>
class RowRangeConstIterator : public std::iterator<std::forward_iterator_tag, T>
{
public:
RowRangeConstIterator()
: data()
, row()
, position()
{}
RowRangeConstIterator(const cv::Mat_<T>& m, int index)
: data(m)
, position(index)
{
CV_DbgAssert(position >= 0 && position <= data.rows + 1);
if (index != data.rows + 1) {
row = m.row(index);
}
}
// Dereference
const cv::Mat_<T>& operator*() const
{
return row;
}
const cv::Mat_<T>* operator->() const
{
return &row;
}
// Logical comparison
bool operator==(const RowRangeConstIterator& that) const
{
return this->position == that.position;
}
bool operator!=(const RowRangeConstIterator& that) const
{
return !(*this == that);
}
bool operator<(const RowRangeConstIterator& that) const
{
return this->position < that.position;
}
bool operator>(const RowRangeConstIterator& that) const
{
return this->position > that.position;
}
bool operator<=(const RowRangeConstIterator& that) const
{
return !(*this > that);
}
bool operator>=(const RowRangeConstIterator& that) const
{
return !(*this < that);
}
// Increment
RowRangeConstIterator& operator++()
{
++position;
return *this;
}
RowRangeConstIterator operator++(int) const
{
RowRangeConstIterator tmp(*this);
++(*this);
return tmp;
}
protected:
cv::Mat_<T> data;
mutable cv::Mat_<T> row;
int position;
};
template <typename T>
class RowRangeIterator : public RowRangeConstIterator<T>
{
public:
RowRangeIterator()
: RowRangeConstIterator<T>()
{}
RowRangeIterator(const cv::Mat_<T>& m, int index)
: RowRangeConstIterator<T>(m, index)
{}
// Dereference
cv::Mat_<T>& operator*() const
{
return RowRangeConstIterator<T>::row;
}
cv::Mat_<T>* operator->() const
{
return &RowRangeConstIterator<T>::row;
}
};
template <typename T>
class RowRange
{
public:
typedef RowRangeConstIterator<T> const_iterator;
typedef RowRangeIterator<T> iterator;
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
RowRange(cv::Mat m)
: data(m)
{
CV_Assert(m.type() == cv::DataType<T>::type);
}
RowRange(cv::Mat_<T> m)
: data(m) {}
const_iterator begin() const
{
return const_iterator(data, 0);
}
iterator begin()
{
return iterator(data, 0);
}
const_iterator end() const
{
return const_iterator(data, data.rows + 1);
}
iterator end()
{
return iterator(data, data.rows + 1);
}
const_iterator cbegin() const
{
return begin();
}
const_iterator cend() const
{
return end();
}
private:
cv::Mat_<T> data;
};
template <typename T>
RowRange<T> make_RowRange(cv::Mat_<T> m)
{
return RowRange<T>(m);
}
#endif /* CV_ADAPTERS_ROWRANGE_HPP */
<commit_msg>Fixing off-by-one error in iterator bounds.<commit_after>#ifndef CV_ADAPTERS_ROWRANGE_HPP
#define CV_ADAPTERS_ROWRANGE_HPP
#include <iterator>
#include <opencv2/core/core.hpp>
namespace cv
{
template <typename T>
class RowRangeConstIterator : public std::iterator<std::forward_iterator_tag, T>
{
public:
RowRangeConstIterator()
: data()
, row()
, position()
{}
RowRangeConstIterator(const cv::Mat_<T>& m, int index)
: data(m)
, row()
, position(index)
{
CV_DbgAssert(position >= 0 && position <= data.rows);
}
// Dereference
const cv::Mat_<T>& operator*() const
{
setRow();
return row;
}
const cv::Mat_<T>* operator->() const
{
setRow();
return &row;
}
// Logical comparison
bool operator==(const RowRangeConstIterator& that) const
{
return this->position == that.position;
}
bool operator!=(const RowRangeConstIterator& that) const
{
return !(*this == that);
}
bool operator<(const RowRangeConstIterator& that) const
{
return this->position < that.position;
}
bool operator>(const RowRangeConstIterator& that) const
{
return this->position > that.position;
}
bool operator<=(const RowRangeConstIterator& that) const
{
return !(*this > that);
}
bool operator>=(const RowRangeConstIterator& that) const
{
return !(*this < that);
}
// Increment
RowRangeConstIterator& operator++()
{
++position;
return *this;
}
RowRangeConstIterator operator++(int) const
{
RowRangeConstIterator tmp(*this);
++(*this);
return tmp;
}
protected:
void setRow() const
{
row = data.row(position);
}
cv::Mat_<T> data;
mutable cv::Mat_<T> row;
int position;
};
template <typename T>
class RowRangeIterator : public RowRangeConstIterator<T>
{
public:
RowRangeIterator()
: RowRangeConstIterator<T>()
{}
RowRangeIterator(const cv::Mat_<T>& m, int index)
: RowRangeConstIterator<T>(m, index)
{}
// Dereference
cv::Mat_<T>& operator*() const
{
this->setRow();
return this->row;
}
cv::Mat_<T>* operator->() const
{
this->setRow();
return &this->row;
}
};
template <typename T>
class RowRange
{
public:
typedef RowRangeConstIterator<T> const_iterator;
typedef RowRangeIterator<T> iterator;
RowRange(cv::Mat m)
: data(m)
{
CV_Assert(m.type() == cv::DataType<T>::type);
}
RowRange(cv::Mat_<T> m)
: data(m) {}
const_iterator begin() const
{
return const_iterator(data, 0);
}
iterator begin()
{
return iterator(data, 0);
}
const_iterator end() const
{
return const_iterator(data, data.rows);
}
iterator end()
{
return iterator(data, data.rows);
}
const_iterator cbegin() const
{
return begin();
}
const_iterator cend() const
{
return end();
}
private:
cv::Mat_<T> data;
};
template <typename T>
RowRange<T> make_RowRange(cv::Mat_<T> m)
{
return RowRange<T>(m);
}
} // namespace cv
#endif /* CV_ADAPTERS_ROWRANGE_HPP */
<|endoftext|>
|
<commit_before>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* 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 <curl/curl.h>
#include <map>
#include <zorba/zorba.h>
#include <zorba/serializer.h>
#include <zorba/external_module.h>
#include <zorba/function.h>
#include <zorba/empty_sequence.h>
#include <zorba/user_exception.h>
#include "http_request_handler.h"
#include "request_parser.h"
#include "http_response_handler.h"
#include "http_response_parser.h"
#ifdef WIN32
# include <Windows.h>
# define MAX_BUF_SIZE 2048
#endif
namespace zorba {
namespace http_client {
#ifdef WIN32
static void set_cacert(CURL* lCurl, std::string aPath) {
TCHAR path[MAX_BUF_SIZE];
int r = GetModuleFileName(NULL, path, 2048);
if (r == -1)
return;
# ifdef UNICODE
char buf[MAX_BUF_SIZE];
memset(buf, 0, MAX_BUF_SIZE);
for (int i = 0; i <= r; ++i) {
buf[i] = (char) path[i];
}
std::string lPath(buf);
# else
std::string lPath(path);
# endif
aPath = lPath.substr(0, lPath.rfind('\\'));
aPath += "\\cacert.pem";
if(GetFileAttributesA(aPath.c_str()) != INVALID_FILE_ATTRIBUTES)
curl_easy_setopt(lCurl, CURLOPT_CAINFO, aPath.c_str());
else
curl_easy_setopt(lCurl, CURLOPT_SSL_VERIFYPEER, 0L);
}
#endif //WIN32
class HttpSendFunction : public ContextualExternalFunction {
protected:
const ExternalModule* theModule;
ItemFactory* theFactory;
public:
HttpSendFunction(const ExternalModule* aModule)
: theModule(aModule),
theFactory(Zorba::getInstance(0)->getItemFactory()) {}
virtual ~HttpSendFunction() {}
public:
virtual String
getURI() const { return theModule->getURI(); }
virtual String
getLocalName() const { return "http-sequential-impl"; }
virtual ItemSequence_t
evaluate(const ExternalFunction::Arguments_t& args,
const StaticContext* aStaticContext, const DynamicContext* aDynamicContext)
const;
};
class HttpReadFunction : public HttpSendFunction {
public:
HttpReadFunction(const ExternalModule* aModule)
: HttpSendFunction(aModule) {}
virtual ~HttpReadFunction() {}
public:
virtual String
getLocalName() const { return "http-nondeterministic-impl"; }
};
class HttpClientModule : public ExternalModule {
protected:
class ltstr
{
public:
bool operator()(const String& s1, const String& s2) const
{
return s1.compare(s2) < 0;
}
};
typedef std::map<String, ExternalFunction*, ltstr> FuncMap_t;
FuncMap_t theFunctions;
public:
virtual ~HttpClientModule();
HttpClientModule() : theModuleUri("http://www.zorba-xquery.com/modules/http-client")
{
for (FuncMap_t::const_iterator lIter = theFunctions.begin();
lIter != theFunctions.end(); ++lIter) {
delete lIter->second;
}
theFunctions.clear();
}
virtual String
getURI() const { return theModuleUri; }
virtual ExternalFunction*
getExternalFunction(const String& aLocalname)
{
ExternalFunction*& lFunc = theFunctions[aLocalname];
if (!lFunc) {
if (aLocalname == "http-sequential-impl") {
lFunc = new HttpSendFunction(this);
} else if (aLocalname == "http-nondeterministic-impl") {
lFunc = new HttpReadFunction(this);
}
}
return lFunc;
}
virtual void
destroy()
{
if (!dynamic_cast<HttpClientModule*>(this)) {
return;
}
delete this;
}
private:
String theModuleUri;
};
ItemSequence_t
general_evaluate(
const ExternalFunction::Arguments_t& args,
const StaticContext* aStaticContext,
const DynamicContext* aDynamicContext,
ItemFactory* aFactory)
{
CURL* lCURL = curl_easy_init();
Item lRequest;
Item lHref;
Item lContent;
Iterator_t arg0_iter = args[0]->getIterator();
arg0_iter->open();
bool lReqSet = arg0_iter->next(lRequest);
arg0_iter->close();
Iterator_t arg1_iter = args[1]->getIterator();
arg1_iter->open();
bool lHrefSet = arg1_iter->next(lHref);
arg1_iter->close();
std::string lData;
std::auto_ptr<HttpRequestHandler> lHandler;
std::auto_ptr<RequestParser> lParser;
struct curl_slist* lHeaderList = 0;
ErrorThrower thrower(aFactory, &lHeaderList);
if (lReqSet) {
lHandler.reset(new HttpRequestHandler(lCURL, args[2]));
lParser.reset(new RequestParser(lHandler.get()));
lParser->parse(lRequest);
}
if (lHrefSet) {
curl_easy_setopt(lCURL, CURLOPT_URL, lHref.getStringValue().c_str());
}
curl_easy_setopt(lCURL, CURLOPT_USERAGENT, "libcurl-agent/1.0");
//curl_easy_setopt(lCURL, CURLOPT_PROXY, "localhost:8888");
#ifdef WIN32
std::string caCertPath;
set_cacert(lCURL, caCertPath);
#endif
HttpResponseHandler lRespHandler(aFactory, lHeaderList);
String lOverrideContentType;
if (lHandler.get())
lHandler->getOverrideContentType(lOverrideContentType);
bool lStatusOnly =
lHandler.get() == NULL ? false : (lHandler->isStatusOnly() || lHandler->isHeadRequest());
// This gives the ownership of lCurl to the HttpResponseParser
std::auto_ptr<HttpResponseParser> lRespParser(new HttpResponseParser(lRespHandler, lCURL, thrower,
lOverrideContentType.c_str(), lStatusOnly));
int lRetCode = lRespParser->parse();
if (lRetCode) {
thrower.raiseException("http://expath.org/ns/error", "HC001", "An HTTP error occurred");
}
// If the Parser is "self contained", that means it didn't create any
// objects with a lifecycle longer than itself; therefore we should free
// it (by letting auto_ptr delete it). If the Parser is not self contained,
// then it will have arranged for some other memory manager to free it
// later when appropriate; therefore we should NOT let auto_ptr delete it
// now.
if ( ! lRespParser->selfContained()) {
lRespParser.release();
}
return ItemSequence_t(lRespHandler.releaseResult());
}
ItemSequence_t
HttpSendFunction::evaluate(const ExternalFunction::Arguments_t& args,
const StaticContext* aStaticContext, const DynamicContext* aDynamicContext) const
{
return general_evaluate(args, aStaticContext, aDynamicContext, theFactory);
}
HttpClientModule::~HttpClientModule()
{
for (FuncMap_t::const_iterator lIter = theFunctions.begin();
lIter != theFunctions.end(); ++lIter) {
delete lIter->second;
}
theFunctions.clear();
}
} // namespace http_request
} // namespace zorba
#ifdef WIN32
# define DLL_EXPORT __declspec(dllexport)
#else
# define DLL_EXPORT __attribute__ ((visibility("default")))
#endif
extern "C" DLL_EXPORT zorba::ExternalModule* createModule() {
return new zorba::http_client::HttpClientModule();
}
<commit_msg>Reverted change to http_client<commit_after>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* 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 <curl/curl.h>
#include <map>
#include <zorba/zorba.h>
#include <zorba/serializer.h>
#include <zorba/external_module.h>
#include <zorba/function.h>
#include <zorba/empty_sequence.h>
#include <zorba/user_exception.h>
#include "http_request_handler.h"
#include "request_parser.h"
#include "http_response_handler.h"
#include "http_response_parser.h"
#ifdef WIN32
# include <Windows.h>
# define MAX_BUF_SIZE 2048
#endif
namespace zorba {
namespace http_client {
#ifdef WIN32
static void set_cacert(CURL* lCurl, std::string aPath) {
TCHAR path[MAX_BUF_SIZE];
int r = GetModuleFileName(NULL, path, 2048);
if (r == -1)
return;
# ifdef UNICODE
char buf[MAX_BUF_SIZE];
memset(buf, 0, MAX_BUF_SIZE);
for (int i = 0; i <= r; ++i) {
buf[i] = (char) path[i];
}
std::string lPath(buf);
# else
std::string lPath(path);
# endif
aPath = lPath.substr(0, lPath.rfind('\\'));
aPath += "\\cacert.pem";
curl_easy_setopt(lCurl, CURLOPT_CAINFO, aPath.c_str());
}
#endif //WIN32
class HttpSendFunction : public ContextualExternalFunction {
protected:
const ExternalModule* theModule;
ItemFactory* theFactory;
public:
HttpSendFunction(const ExternalModule* aModule)
: theModule(aModule),
theFactory(Zorba::getInstance(0)->getItemFactory()) {}
virtual ~HttpSendFunction() {}
public:
virtual String
getURI() const { return theModule->getURI(); }
virtual String
getLocalName() const { return "http-sequential-impl"; }
virtual ItemSequence_t
evaluate(const ExternalFunction::Arguments_t& args,
const StaticContext* aStaticContext, const DynamicContext* aDynamicContext)
const;
};
class HttpReadFunction : public HttpSendFunction {
public:
HttpReadFunction(const ExternalModule* aModule)
: HttpSendFunction(aModule) {}
virtual ~HttpReadFunction() {}
public:
virtual String
getLocalName() const { return "http-nondeterministic-impl"; }
};
class HttpClientModule : public ExternalModule {
protected:
class ltstr
{
public:
bool operator()(const String& s1, const String& s2) const
{
return s1.compare(s2) < 0;
}
};
typedef std::map<String, ExternalFunction*, ltstr> FuncMap_t;
FuncMap_t theFunctions;
public:
virtual ~HttpClientModule();
HttpClientModule() : theModuleUri("http://www.zorba-xquery.com/modules/http-client")
{
for (FuncMap_t::const_iterator lIter = theFunctions.begin();
lIter != theFunctions.end(); ++lIter) {
delete lIter->second;
}
theFunctions.clear();
}
virtual String
getURI() const { return theModuleUri; }
virtual ExternalFunction*
getExternalFunction(const String& aLocalname)
{
ExternalFunction*& lFunc = theFunctions[aLocalname];
if (!lFunc) {
if (aLocalname == "http-sequential-impl") {
lFunc = new HttpSendFunction(this);
} else if (aLocalname == "http-nondeterministic-impl") {
lFunc = new HttpReadFunction(this);
}
}
return lFunc;
}
virtual void
destroy()
{
if (!dynamic_cast<HttpClientModule*>(this)) {
return;
}
delete this;
}
private:
String theModuleUri;
};
ItemSequence_t
general_evaluate(
const ExternalFunction::Arguments_t& args,
const StaticContext* aStaticContext,
const DynamicContext* aDynamicContext,
ItemFactory* aFactory)
{
CURL* lCURL = curl_easy_init();
Item lRequest;
Item lHref;
Item lContent;
Iterator_t arg0_iter = args[0]->getIterator();
arg0_iter->open();
bool lReqSet = arg0_iter->next(lRequest);
arg0_iter->close();
Iterator_t arg1_iter = args[1]->getIterator();
arg1_iter->open();
bool lHrefSet = arg1_iter->next(lHref);
arg1_iter->close();
std::string lData;
std::auto_ptr<HttpRequestHandler> lHandler;
std::auto_ptr<RequestParser> lParser;
struct curl_slist* lHeaderList = 0;
ErrorThrower thrower(aFactory, &lHeaderList);
if (lReqSet) {
lHandler.reset(new HttpRequestHandler(lCURL, args[2]));
lParser.reset(new RequestParser(lHandler.get()));
lParser->parse(lRequest);
}
if (lHrefSet) {
curl_easy_setopt(lCURL, CURLOPT_URL, lHref.getStringValue().c_str());
}
curl_easy_setopt(lCURL, CURLOPT_USERAGENT, "libcurl-agent/1.0");
//curl_easy_setopt(lCURL, CURLOPT_PROXY, "localhost:8888");
#ifdef WIN32
std::string caCertPath;
set_cacert(lCURL, caCertPath);
#endif
HttpResponseHandler lRespHandler(aFactory, lHeaderList);
String lOverrideContentType;
if (lHandler.get())
lHandler->getOverrideContentType(lOverrideContentType);
bool lStatusOnly =
lHandler.get() == NULL ? false : (lHandler->isStatusOnly() || lHandler->isHeadRequest());
// This gives the ownership of lCurl to the HttpResponseParser
std::auto_ptr<HttpResponseParser> lRespParser(new HttpResponseParser(lRespHandler, lCURL, thrower,
lOverrideContentType.c_str(), lStatusOnly));
int lRetCode = lRespParser->parse();
if (lRetCode) {
thrower.raiseException("http://expath.org/ns/error", "HC001", "An HTTP error occurred");
}
// If the Parser is "self contained", that means it didn't create any
// objects with a lifecycle longer than itself; therefore we should free
// it (by letting auto_ptr delete it). If the Parser is not self contained,
// then it will have arranged for some other memory manager to free it
// later when appropriate; therefore we should NOT let auto_ptr delete it
// now.
if ( ! lRespParser->selfContained()) {
lRespParser.release();
}
return ItemSequence_t(lRespHandler.releaseResult());
}
ItemSequence_t
HttpSendFunction::evaluate(const ExternalFunction::Arguments_t& args,
const StaticContext* aStaticContext, const DynamicContext* aDynamicContext) const
{
return general_evaluate(args, aStaticContext, aDynamicContext, theFactory);
}
HttpClientModule::~HttpClientModule()
{
for (FuncMap_t::const_iterator lIter = theFunctions.begin();
lIter != theFunctions.end(); ++lIter) {
delete lIter->second;
}
theFunctions.clear();
}
} // namespace http_request
} // namespace zorba
#ifdef WIN32
# define DLL_EXPORT __declspec(dllexport)
#else
# define DLL_EXPORT __attribute__ ((visibility("default")))
#endif
extern "C" DLL_EXPORT zorba::ExternalModule* createModule() {
return new zorba::http_client::HttpClientModule();
}
<|endoftext|>
|
<commit_before>
// -*- mode: c++; c-basic-offset:4 -*-
// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.
// Copyright (c) 2013 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
#include <cppunit/TextTestRunner.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/extensions/HelperMacros.h>
//#define DODS_DEBUG
#include <fcntl.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
#include "GetOpt.h"
#include "chunked_ostream.h"
#include "chunked_istream.h"
#include "InternalErr.h"
#include "test_config.h"
#include "debug.h"
static bool debug = false;
#undef DBG
#define DBG(x) do { if (debug) (x); } while(false);
using namespace std;
using namespace CppUnit;
using namespace libdap;
/**
* The intent is to test writing to and reading from a chunked iostream,
* using various combinations of chunk/buffer sizes and character red/write
* sizes. There are three write functions and three read functions and
* all combinations are tested.
*/
class chunked_iostream_test: public TestFixture {
private:
// This should be big enough to do meaningful timing tests
string big_file;
// This should be smaller than a single buffer
string small_file;
// A modest sized text file - makes looking at the results easier
string text_file;
public:
chunked_iostream_test()
{
}
~chunked_iostream_test()
{
}
void setUp()
{
big_file = "test_big_binary_file.bin";
small_file = "test_small_text_file.txt";
text_file = "test_text_file.txt";
}
void tearDown()
{
}
void
single_char_write(const string &file, int buf_size)
{
fstream infile(file.c_str(), ios::in|ios::binary);
if (!infile.good())
CPPUNIT_FAIL("File not open or eof");
string out = file + ".chunked";
fstream outfile(out.c_str(), ios::out|ios::binary);
chunked_ostream chunked_outfile(outfile, buf_size);
char c;
infile.read(&c, 1);
int num = infile.gcount();
while (num > 0 && !infile.eof()) {
chunked_outfile.write(&c, num);
infile.read(&c, 1);
num = infile.gcount();
}
if (num > 0 && !infile.bad()) {
chunked_outfile.write(&c, num);
}
chunked_outfile.flush();
}
void
write_128char_data(const string &file, int buf_size)
{
fstream infile(file.c_str(), ios::in|ios::binary);
if (!infile.good())
CPPUNIT_FAIL("File not open or eof");
string out = file + ".chunked";
fstream outfile(out.c_str(), ios::out|ios::binary);
chunked_ostream chunked_outfile(outfile, buf_size);
char str[128];
infile.read(str, 128);
int num = infile.gcount();
while (num > 0 && !infile.eof()) {
chunked_outfile.write(str, num);
infile.read(str, 128);
num = infile.gcount();
}
if (num > 0 && !infile.bad()) {
chunked_outfile.write(str, num);
}
chunked_outfile.flush();
}
void
write_24char_data_with_error_option(const string &file, int buf_size, bool error = false)
{
fstream infile(file.c_str(), ios::in|ios::binary);
if (!infile.good())
CPPUNIT_FAIL("File not open or eof");
string out = file + ".chunked";
fstream outfile(out.c_str(), ios::out|ios::binary);
chunked_ostream chunked_outfile(outfile, buf_size);
try {
char str[24];
infile.read(str, 24);
int num = infile.gcount();
if (num > 0 && !infile.eof()) {
chunked_outfile.write(str, num);
chunked_outfile.flush();
}
infile.read(str, 24);
num = infile.gcount();
if (num > 0 && !infile.eof()) chunked_outfile.write(str, num);
// Send an error chunk; the 24 bytes read here are lost...
if (error)
throw InternalErr(__FILE__, __LINE__, "Testing error transmission");
infile.read(str, 24);
num = infile.gcount();
while (num > 0 && !infile.eof()) {
chunked_outfile.write(str, num);
infile.read(str, 24);
num = infile.gcount();
}
if (num > 0 && !infile.bad()) {
chunked_outfile.write(str, num);
}
chunked_outfile.flush();
}
catch (Error &e) {
chunked_outfile.write_err_chunk(e.get_error_message());
}
}
void
single_char_read(const string &file, int buf_size)
{
string in = file + ".chunked";
fstream infile(in.c_str(), ios::in|ios::binary);
if (!infile.good())
CPPUNIT_FAIL("File not open or eof");
chunked_istream chunked_infile(infile, buf_size, 0x00);
string out = file + ".plain";
fstream outfile(out.c_str(), ios::out|ios::binary);
char c;
int count = 1;
chunked_infile.read(&c, 1);
int num = chunked_infile.gcount();
DBG(cerr << "num: " << count++ << endl);
while (num > 0 && !chunked_infile.eof()) {
outfile.write(&c, num);
chunked_infile.read(&c, 1);
num = chunked_infile.gcount();
DBG(cerr << "num: " << count++ << endl);
}
if (num > 0 && !chunked_infile.bad())
outfile.write(&c, num);
outfile.flush();
}
void
read_128char_data(const string &file, int buf_size)
{
string in = file + ".chunked";
fstream infile(in.c_str(), ios::in|ios::binary);
if (!infile.good())
cerr << "File not open or eof" << endl;
chunked_istream chunked_infile(infile, buf_size);
string out = file + ".plain";
fstream outfile(out.c_str(), ios::out|ios::binary);
char str[128];
int count = 1;
chunked_infile.read(str, 128);
int num = chunked_infile.gcount();
DBG(cerr << "num: " << num << ", " << count++ << endl);
while (num > 0 && !chunked_infile.eof()) {
outfile.write(str, num);
chunked_infile.read(str, 128);
num = chunked_infile.gcount();
DBG(cerr << "num: " << num << ", " << count++ << endl);
}
if (num > 0 && !chunked_infile.bad()) {
outfile.write(str, num);
}
outfile.flush();
}
void
read_24char_data_with_error_option(const string &file, int buf_size)
{
string in = file + ".chunked";
fstream infile(in.c_str(), ios::in|ios::binary);
if (!infile.good())
cerr << "File not open or eof" << endl;
chunked_istream chunked_infile(infile, buf_size);
string out = file + ".plain";
fstream outfile(out.c_str(), ios::out|ios::binary);
try {
char str[24];
chunked_infile.read(str, 24);
int num = chunked_infile.gcount();
if (num > 0 && !chunked_infile.eof()) {
outfile.write(str, num);
outfile.flush();
}
chunked_infile.read(str, 24);
num = chunked_infile.gcount();
while (num > 0 && !chunked_infile.eof()) {
outfile.write(str, num);
chunked_infile.read(str, 24);
num = chunked_infile.gcount();
}
if (num > 0 && !chunked_infile.bad()) {
outfile.write(str, num);
}
outfile.flush();
}
catch (Error &e) {
cerr << "Error chunk found: " << e.get_error_message() << endl;
}
}
// these are the tests
void test_write_1_read_1_small_file() {
single_char_write(small_file, 32);
single_char_read(small_file, 32);
string cmp = "cmp " + small_file + " " + small_file + ".plain";
CPPUNIT_ASSERT(system(cmp.c_str()) == 0);
}
void test_write_1_read_1_text_file() {
single_char_write(text_file, 32);
single_char_read(text_file, 32);
string cmp = "cmp " + text_file + " " + text_file + ".plain";
CPPUNIT_ASSERT(system(cmp.c_str()) == 0);
}
void test_write_1_read_1_big_file() {
single_char_write(big_file, 28);
single_char_read(big_file, 28);
string cmp = "cmp " + big_file + " " + big_file + ".plain";
CPPUNIT_ASSERT(system(cmp.c_str()) == 0);
}
// these are the tests
void test_write_1_read_128_small_file() {
single_char_write(small_file, 32);
read_128char_data(small_file, 32);
string cmp = "cmp " + small_file + " " + small_file + ".plain";
CPPUNIT_ASSERT(system(cmp.c_str()) == 0);
}
void test_write_1_read_128_text_file() {
single_char_write(text_file, 32);
read_128char_data(text_file, 32);
string cmp = "cmp " + text_file + " " + text_file + ".plain";
CPPUNIT_ASSERT(system(cmp.c_str()) == 0);
}
void test_write_1_read_128_big_file() {
single_char_write(big_file, 28);
read_128char_data(big_file, 28);
string cmp = "cmp " + big_file + " " + big_file + ".plain";
CPPUNIT_ASSERT(system(cmp.c_str()) == 0);
}
CPPUNIT_TEST_SUITE(chunked_iostream_test);
CPPUNIT_TEST(test_write_1_read_1_small_file);
CPPUNIT_TEST(test_write_1_read_1_text_file);
CPPUNIT_TEST(test_write_1_read_1_big_file);
CPPUNIT_TEST(test_write_1_read_128_small_file);
CPPUNIT_TEST(test_write_1_read_128_text_file);
CPPUNIT_TEST(test_write_1_read_128_big_file);
CPPUNIT_TEST_SUITE_END();
};
CPPUNIT_TEST_SUITE_REGISTRATION(chunked_iostream_test);
int
main(int argc, char *argv[])
{
GetOpt getopt(argc, argv, "d");
char option_char;
while ((option_char = getopt()) != EOF)
switch (option_char) {
case 'd':
debug = 1; // debug is a static global
break;
default:
break;
}
CppUnit::TextTestRunner runner;
runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest());
bool wasSuccessful = true;
string test = "";
int i = getopt.optind;
if (i == argc) {
// run them all
wasSuccessful = runner.run("");
}
else {
while (i < argc) {
test = string("chunked_iostream_test::") + argv[i++];
if (debug)
cerr << "Running " << test << endl;
wasSuccessful = wasSuccessful && runner.run(test);
}
}
return wasSuccessful ? 0 : 1;
}
<commit_msg>added big_file_2 tests<commit_after>
// -*- mode: c++; c-basic-offset:4 -*-
// This file is part of libdap, A C++ implementation of the OPeNDAP Data
// Access Protocol.
// Copyright (c) 2013 OPeNDAP, Inc.
// Author: James Gallagher <jgallagher@opendap.org>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.
#include <cppunit/TextTestRunner.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/extensions/HelperMacros.h>
//#define DODS_DEBUG
#include <fcntl.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
#include "GetOpt.h"
#include "chunked_ostream.h"
#include "chunked_istream.h"
#include "InternalErr.h"
#include "test_config.h"
#include "debug.h"
static bool debug = false;
#undef DBG
#define DBG(x) do { if (debug) (x); } while(false);
using namespace std;
using namespace CppUnit;
using namespace libdap;
/**
* The intent is to test writing to and reading from a chunked iostream,
* using various combinations of chunk/buffer sizes and character red/write
* sizes. There are three write functions and three read functions and
* all combinations are tested.
*/
class chunked_iostream_test: public TestFixture {
private:
// This should be big enough to do meaningful timing tests
string big_file, big_file_2;
// This should be smaller than a single buffer
string small_file;
// A modest sized text file - makes looking at the results easier
string text_file;
public:
chunked_iostream_test()
{
}
~chunked_iostream_test()
{
}
void setUp()
{
big_file = "test_big_binary_file.bin";
big_file_2 = "test_big_binary_file_2.bin";
small_file = "test_small_text_file.txt";
text_file = "test_text_file.txt";
}
void tearDown()
{
}
void
single_char_write(const string &file, int buf_size)
{
fstream infile(file.c_str(), ios::in|ios::binary);
if (!infile.good())
CPPUNIT_FAIL("File not open or eof");
string out = file + ".chunked";
fstream outfile(out.c_str(), ios::out|ios::binary);
chunked_ostream chunked_outfile(outfile, buf_size);
char c;
infile.read(&c, 1);
int num = infile.gcount();
while (num > 0 && !infile.eof()) {
chunked_outfile.write(&c, num);
infile.read(&c, 1);
num = infile.gcount();
}
if (num > 0 && !infile.bad()) {
chunked_outfile.write(&c, num);
}
chunked_outfile.flush();
}
void
write_128char_data(const string &file, int buf_size)
{
fstream infile(file.c_str(), ios::in|ios::binary);
if (!infile.good())
CPPUNIT_FAIL("File not open or eof");
string out = file + ".chunked";
fstream outfile(out.c_str(), ios::out|ios::binary);
chunked_ostream chunked_outfile(outfile, buf_size);
char str[128];
infile.read(str, 128);
int num = infile.gcount();
while (num > 0 && !infile.eof()) {
chunked_outfile.write(str, num);
infile.read(str, 128);
num = infile.gcount();
}
if (num > 0 && !infile.bad()) {
chunked_outfile.write(str, num);
}
chunked_outfile.flush();
}
void
write_24char_data_with_error_option(const string &file, int buf_size, bool error = false)
{
fstream infile(file.c_str(), ios::in|ios::binary);
if (!infile.good())
CPPUNIT_FAIL("File not open or eof");
string out = file + ".chunked";
fstream outfile(out.c_str(), ios::out|ios::binary);
chunked_ostream chunked_outfile(outfile, buf_size);
try {
char str[24];
infile.read(str, 24);
int num = infile.gcount();
if (num > 0 && !infile.eof()) {
chunked_outfile.write(str, num);
chunked_outfile.flush();
}
infile.read(str, 24);
num = infile.gcount();
if (num > 0 && !infile.eof()) chunked_outfile.write(str, num);
// Send an error chunk; the 24 bytes read here are lost...
if (error)
throw InternalErr(__FILE__, __LINE__, "Testing error transmission");
infile.read(str, 24);
num = infile.gcount();
while (num > 0 && !infile.eof()) {
chunked_outfile.write(str, num);
infile.read(str, 24);
num = infile.gcount();
}
if (num > 0 && !infile.bad()) {
chunked_outfile.write(str, num);
}
chunked_outfile.flush();
}
catch (Error &e) {
chunked_outfile.write_err_chunk(e.get_error_message());
}
}
void
single_char_read(const string &file, int buf_size)
{
string in = file + ".chunked";
fstream infile(in.c_str(), ios::in|ios::binary);
if (!infile.good())
CPPUNIT_FAIL("File not open or eof");
chunked_istream chunked_infile(infile, buf_size, 0x00);
string out = file + ".plain";
fstream outfile(out.c_str(), ios::out|ios::binary);
char c;
int count = 1;
chunked_infile.read(&c, 1);
int num = chunked_infile.gcount();
DBG(cerr << "num: " << num << ", " << count++ << endl);
while (num > 0 && !chunked_infile.eof()) {
outfile.write(&c, num);
chunked_infile.read(&c, 1);
num = chunked_infile.gcount();
DBG(cerr << "num: " << num << ", " << count++ << endl);
}
DBG(cerr << "eof is :" << chunked_infile.eof() << ", num: " << num << endl);
if (num > 0 && !chunked_infile.bad())
outfile.write(&c, num);
outfile.flush();
}
void
read_128char_data(const string &file, int buf_size)
{
string in = file + ".chunked";
fstream infile(in.c_str(), ios::in|ios::binary);
if (!infile.good())
cerr << "File not open or eof" << endl;
chunked_istream chunked_infile(infile, buf_size);
string out = file + ".plain";
fstream outfile(out.c_str(), ios::out|ios::binary);
char str[128];
int count = 1;
chunked_infile.read(str, 128);
int num = chunked_infile.gcount();
DBG(cerr << "num: " << num << ", " << count++ << endl);
while (num > 0 && !chunked_infile.eof()) {
outfile.write(str, num);
chunked_infile.read(str, 128);
num = chunked_infile.gcount();
DBG(cerr << "num: " << num << ", " << count++ << endl);
}
if (num > 0 && !chunked_infile.bad()) {
outfile.write(str, num);
}
outfile.flush();
}
void
read_24char_data_with_error_option(const string &file, int buf_size)
{
string in = file + ".chunked";
fstream infile(in.c_str(), ios::in|ios::binary);
if (!infile.good())
cerr << "File not open or eof" << endl;
chunked_istream chunked_infile(infile, buf_size);
string out = file + ".plain";
fstream outfile(out.c_str(), ios::out|ios::binary);
try {
char str[24];
chunked_infile.read(str, 24);
int num = chunked_infile.gcount();
if (num > 0 && !chunked_infile.eof()) {
outfile.write(str, num);
outfile.flush();
}
chunked_infile.read(str, 24);
num = chunked_infile.gcount();
while (num > 0 && !chunked_infile.eof()) {
outfile.write(str, num);
chunked_infile.read(str, 24);
num = chunked_infile.gcount();
}
if (num > 0 && !chunked_infile.bad()) {
outfile.write(str, num);
}
outfile.flush();
}
catch (Error &e) {
cerr << "Error chunk found: " << e.get_error_message() << endl;
}
}
// these are the tests
void test_write_1_read_1_small_file() {
single_char_write(small_file, 32);
single_char_read(small_file, 32);
string cmp = "cmp " + small_file + " " + small_file + ".plain";
CPPUNIT_ASSERT(system(cmp.c_str()) == 0);
}
void test_write_1_read_1_text_file() {
single_char_write(text_file, 32);
single_char_read(text_file, 32);
string cmp = "cmp " + text_file + " " + text_file + ".plain";
CPPUNIT_ASSERT(system(cmp.c_str()) == 0);
}
void test_write_1_read_1_big_file() {
single_char_write(big_file, 28);
single_char_read(big_file, 28);
string cmp = "cmp " + big_file + " " + big_file + ".plain";
CPPUNIT_ASSERT(system(cmp.c_str()) == 0);
}
void test_write_1_read_1_big_file_2() {
single_char_write(big_file_2, 28);
single_char_read(big_file_2, 28);
string cmp = "cmp " + big_file_2 + " " + big_file_2 + ".plain";
CPPUNIT_ASSERT(system(cmp.c_str()) == 0);
}
// these are the tests
void test_write_1_read_128_small_file() {
single_char_write(small_file, 32);
read_128char_data(small_file, 32);
string cmp = "cmp " + small_file + " " + small_file + ".plain";
CPPUNIT_ASSERT(system(cmp.c_str()) == 0);
}
void test_write_1_read_128_text_file() {
single_char_write(text_file, 32);
read_128char_data(text_file, 32);
string cmp = "cmp " + text_file + " " + text_file + ".plain";
CPPUNIT_ASSERT(system(cmp.c_str()) == 0);
}
void test_write_1_read_128_big_file() {
single_char_write(big_file, 28);
read_128char_data(big_file, 28);
string cmp = "cmp " + big_file + " " + big_file + ".plain";
CPPUNIT_ASSERT(system(cmp.c_str()) == 0);
}
void test_write_1_read_128_big_file_2() {
single_char_write(big_file_2, 28);
read_128char_data(big_file_2, 28);
string cmp = "cmp " + big_file_2 + " " + big_file_2 + ".plain";
CPPUNIT_ASSERT(system(cmp.c_str()) == 0);
}
CPPUNIT_TEST_SUITE(chunked_iostream_test);
CPPUNIT_TEST(test_write_1_read_1_small_file);
CPPUNIT_TEST(test_write_1_read_1_text_file);
CPPUNIT_TEST(test_write_1_read_1_big_file);
CPPUNIT_TEST(test_write_1_read_1_big_file_2);
CPPUNIT_TEST(test_write_1_read_128_small_file);
CPPUNIT_TEST(test_write_1_read_128_text_file);
CPPUNIT_TEST(test_write_1_read_128_big_file);
CPPUNIT_TEST(test_write_1_read_128_big_file_2);
CPPUNIT_TEST_SUITE_END();
};
CPPUNIT_TEST_SUITE_REGISTRATION(chunked_iostream_test);
int
main(int argc, char *argv[])
{
GetOpt getopt(argc, argv, "d");
char option_char;
while ((option_char = getopt()) != EOF)
switch (option_char) {
case 'd':
debug = 1; // debug is a static global
break;
default:
break;
}
CppUnit::TextTestRunner runner;
runner.addTest(CppUnit::TestFactoryRegistry::getRegistry().makeTest());
bool wasSuccessful = true;
string test = "";
int i = getopt.optind;
if (i == argc) {
// run them all
wasSuccessful = runner.run("");
}
else {
while (i < argc) {
test = string("chunked_iostream_test::") + argv[i++];
if (debug)
cerr << "Running " << test << endl;
wasSuccessful = wasSuccessful && runner.run(test);
}
}
return wasSuccessful ? 0 : 1;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2006-2009 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WebInputEventFactory.h"
#include "WebInputEvent.h"
#include <wtf/Assertions.h>
namespace WebKit {
static const unsigned long defaultScrollLinesPerWheelDelta = 3;
static const unsigned long defaultScrollCharsPerWheelDelta = 1;
// WebKeyboardEvent -----------------------------------------------------------
static bool isKeyPad(WPARAM wparam, LPARAM lparam)
{
bool keypad = false;
switch (wparam) {
case VK_RETURN:
keypad = (lparam >> 16) & KF_EXTENDED;
break;
case VK_INSERT:
case VK_DELETE:
case VK_HOME:
case VK_END:
case VK_PRIOR:
case VK_NEXT:
case VK_UP:
case VK_DOWN:
case VK_LEFT:
case VK_RIGHT:
keypad = !((lparam >> 16) & KF_EXTENDED);
break;
case VK_NUMLOCK:
case VK_NUMPAD0:
case VK_NUMPAD1:
case VK_NUMPAD2:
case VK_NUMPAD3:
case VK_NUMPAD4:
case VK_NUMPAD5:
case VK_NUMPAD6:
case VK_NUMPAD7:
case VK_NUMPAD8:
case VK_NUMPAD9:
case VK_DIVIDE:
case VK_MULTIPLY:
case VK_SUBTRACT:
case VK_ADD:
case VK_DECIMAL:
case VK_CLEAR:
keypad = true;
break;
default:
keypad = false;
}
return keypad;
}
WebKeyboardEvent WebInputEventFactory::keyboardEvent(HWND hwnd, UINT message,
WPARAM wparam, LPARAM lparam)
{
WebKeyboardEvent result;
result.windowsKeyCode = result.nativeKeyCode = static_cast<int>(wparam);
switch (message) {
case WM_SYSKEYDOWN:
result.isSystemKey = true;
case WM_KEYDOWN:
result.type = WebInputEvent::RawKeyDown;
break;
case WM_SYSKEYUP:
result.isSystemKey = true;
case WM_KEYUP:
result.type = WebInputEvent::KeyUp;
break;
case WM_IME_CHAR:
result.type = WebInputEvent::Char;
break;
case WM_SYSCHAR:
result.isSystemKey = true;
result.type = WebInputEvent::Char;
case WM_CHAR:
result.type = WebInputEvent::Char;
break;
default:
ASSERT_NOT_REACHED();
}
if (result.type == WebInputEvent::Char || result.type == WebInputEvent::RawKeyDown) {
result.text[0] = result.windowsKeyCode;
result.unmodifiedText[0] = result.windowsKeyCode;
}
if (result.type != WebInputEvent::Char)
result.setKeyIdentifierFromWindowsKeyCode();
if (GetKeyState(VK_SHIFT) & 0x8000)
result.modifiers |= WebInputEvent::ShiftKey;
if (GetKeyState(VK_CONTROL) & 0x8000)
result.modifiers |= WebInputEvent::ControlKey;
if (GetKeyState(VK_MENU) & 0x8000)
result.modifiers |= (WebInputEvent::AltKey | WebInputEvent::MetaKey);
if (LOWORD(lparam) > 1)
result.modifiers |= WebInputEvent::IsAutoRepeat;
if (isKeyPad(wparam, lparam))
result.modifiers |= WebInputEvent::IsKeyPad;
return result;
}
// WebMouseEvent --------------------------------------------------------------
static int gLastClickCount;
static double gLastClickTime;
static LPARAM GetRelativeCursorPos(HWND hwnd)
{
POINT pos = {-1, -1};
GetCursorPos(&pos);
ScreenToClient(hwnd, &pos);
return MAKELPARAM(pos.x, pos.y);
}
void WebInputEventFactory::resetLastClickState()
{
gLastClickTime = gLastClickCount = 0;
}
WebMouseEvent WebInputEventFactory::mouseEvent(HWND hwnd, UINT message,
WPARAM wparam, LPARAM lparam)
{
WebMouseEvent result; //(WebInputEvent::Uninitialized());
switch (message) {
case WM_MOUSEMOVE:
result.type = WebInputEvent::MouseMove;
if (wparam & MK_LBUTTON)
result.button = WebMouseEvent::ButtonLeft;
else if (wparam & MK_MBUTTON)
result.button = WebMouseEvent::ButtonMiddle;
else if (wparam & MK_RBUTTON)
result.button = WebMouseEvent::ButtonMiddle;
else
result.button = WebMouseEvent::ButtonNone;
break;
case WM_MOUSELEAVE:
result.type = WebInputEvent::MouseLeave;
result.button = WebMouseEvent::ButtonNone;
// set the current mouse position (relative to the client area of the
// current window) since none is specified for this event
lparam = GetRelativeCursorPos(hwnd);
break;
case WM_LBUTTONDOWN:
case WM_LBUTTONDBLCLK:
result.type = WebInputEvent::MouseDown;
result.button = WebMouseEvent::ButtonLeft;
break;
case WM_MBUTTONDOWN:
case WM_MBUTTONDBLCLK:
result.type = WebInputEvent::MouseDown;
result.button = WebMouseEvent::ButtonMiddle;
break;
case WM_RBUTTONDOWN:
case WM_RBUTTONDBLCLK:
result.type = WebInputEvent::MouseDown;
result.button = WebMouseEvent::ButtonRight;
break;
case WM_LBUTTONUP:
result.type = WebInputEvent::MouseUp;
result.button = WebMouseEvent::ButtonLeft;
break;
case WM_MBUTTONUP:
result.type = WebInputEvent::MouseUp;
result.button = WebMouseEvent::ButtonMiddle;
break;
case WM_RBUTTONUP:
result.type = WebInputEvent::MouseUp;
result.button = WebMouseEvent::ButtonRight;
break;
default:
ASSERT_NOT_REACHED();
}
// TODO(pkasting): http://b/1117926 Are we guaranteed that the message that
// GetMessageTime() refers to is the same one that we're passed in? Perhaps
// one of the construction parameters should be the time passed by the
// caller, who would know for sure.
result.timeStampSeconds = GetMessageTime() / 1000.0;
// set position fields:
result.x = static_cast<short>(LOWORD(lparam));
result.y = static_cast<short>(HIWORD(lparam));
POINT globalPoint = { result.x, result.y };
ClientToScreen(hwnd, &globalPoint);
result.globalX = globalPoint.x;
result.globalY = globalPoint.y;
// calculate number of clicks:
// This differs slightly from the WebKit code in WebKit/win/WebView.cpp
// where their original code looks buggy.
static int lastClickPositionX;
static int lastClickPositionY;
static WebMouseEvent::Button lastClickButton = WebMouseEvent::ButtonLeft;
double currentTime = result.timeStampSeconds;
bool cancelPreviousClick =
(abs(lastClickPositionX - result.x) > (GetSystemMetrics(SM_CXDOUBLECLK) / 2))
|| (abs(lastClickPositionY - result.y) > (GetSystemMetrics(SM_CYDOUBLECLK) / 2))
|| ((currentTime - gLastClickTime) * 1000.0 > GetDoubleClickTime());
if (result.type == WebInputEvent::MouseDown) {
if (!cancelPreviousClick && (result.button == lastClickButton))
++gLastClickCount;
else {
gLastClickCount = 1;
lastClickPositionX = result.x;
lastClickPositionY = result.y;
}
gLastClickTime = currentTime;
lastClickButton = result.button;
} else if (result.type == WebInputEvent::MouseMove
|| result.type == WebInputEvent::MouseLeave) {
if (cancelPreviousClick) {
gLastClickCount = 0;
lastClickPositionX = 0;
lastClickPositionY = 0;
gLastClickTime = 0;
}
}
result.clickCount = gLastClickCount;
// set modifiers:
if (wparam & MK_CONTROL)
result.modifiers |= WebInputEvent::ControlKey;
if (wparam & MK_SHIFT)
result.modifiers |= WebInputEvent::ShiftKey;
if (GetKeyState(VK_MENU) & 0x8000)
result.modifiers |= (WebInputEvent::AltKey | WebInputEvent::MetaKey); // FIXME: set META properly
return result;
}
// WebMouseWheelEvent ---------------------------------------------------------
WebMouseWheelEvent WebInputEventFactory::mouseWheelEvent(HWND hwnd, UINT message,
WPARAM wparam, LPARAM lparam)
{
WebMouseWheelEvent result; //(WebInputEvent::Uninitialized());
result.type = WebInputEvent::MouseWheel;
result.button = WebMouseEvent::ButtonNone;
// Get key state, coordinates, and wheel delta from event.
typedef SHORT (WINAPI *GetKeyStateFunction)(int key);
GetKeyStateFunction getKeyState;
UINT keyState;
float wheelDelta;
bool horizontalScroll = false;
if ((message == WM_VSCROLL) || (message == WM_HSCROLL)) {
// Synthesize mousewheel event from a scroll event. This is needed to
// simulate middle mouse scrolling in some laptops. Use GetAsyncKeyState
// for key state since we are synthesizing the input event.
getKeyState = GetAsyncKeyState;
keyState = 0;
if (getKeyState(VK_SHIFT))
keyState |= MK_SHIFT;
if (getKeyState(VK_CONTROL))
keyState |= MK_CONTROL;
POINT cursorPosition = {0};
GetCursorPos(&cursorPosition);
result.globalX = cursorPosition.x;
result.globalY = cursorPosition.y;
switch (LOWORD(wparam)) {
case SB_LINEUP: // == SB_LINELEFT
wheelDelta = WHEEL_DELTA;
break;
case SB_LINEDOWN: // == SB_LINERIGHT
wheelDelta = -WHEEL_DELTA;
break;
case SB_PAGEUP:
wheelDelta = 1;
result.scrollByPage = true;
break;
case SB_PAGEDOWN:
wheelDelta = -1;
result.scrollByPage = true;
break;
default: // We don't supoprt SB_THUMBPOSITION or SB_THUMBTRACK here.
wheelDelta = 0;
break;
}
if (message == WM_HSCROLL)
horizontalScroll = true;
} else {
// Non-synthesized event; we can just read data off the event.
getKeyState = GetKeyState;
keyState = GET_KEYSTATE_WPARAM(wparam);
result.globalX = static_cast<short>(LOWORD(lparam));
result.globalY = static_cast<short>(HIWORD(lparam));
wheelDelta = static_cast<float>(GET_WHEEL_DELTA_WPARAM(wparam));
if (message == WM_MOUSEHWHEEL) {
horizontalScroll = true;
wheelDelta = -wheelDelta; // Windows is <- -/+ ->, WebKit <- +/- ->.
}
}
if (keyState & MK_SHIFT)
horizontalScroll = true;
// Set modifiers based on key state.
if (keyState & MK_SHIFT)
result.modifiers |= WebInputEvent::ShiftKey;
if (keyState & MK_CONTROL)
result.modifiers |= WebInputEvent::ControlKey;
if (getKeyState(VK_MENU) & 0x8000)
result.modifiers |= (WebInputEvent::AltKey | WebInputEvent::MetaKey);
// Set coordinates by translating event coordinates from screen to client.
POINT clientPoint = { result.globalX, result.globalY };
MapWindowPoints(NULL, hwnd, &clientPoint, 1);
result.x = clientPoint.x;
result.y = clientPoint.y;
// Convert wheel delta amount to a number of pixels to scroll.
//
// How many pixels should we scroll per line? Gecko uses the height of the
// current line, which means scroll distance changes as you go through the
// page or go to different pages. IE 7 is ~50 px/line, although the value
// seems to vary slightly by page and zoom level. Since IE 7 has a smoothing
// algorithm on scrolling, it can get away with slightly larger scroll values
// without feeling jerky. Here we use 100 px per three lines (the default
// scroll amount is three lines per wheel tick).
static const float scrollbarPixelsPerLine = 100.0f / 3.0f;
wheelDelta /= WHEEL_DELTA;
float scrollDelta = wheelDelta;
if (horizontalScroll) {
unsigned long scrollChars = defaultScrollCharsPerWheelDelta;
SystemParametersInfo(SPI_GETWHEELSCROLLCHARS, 0, &scrollChars, 0);
// TODO(pkasting): Should probably have a different multiplier
// scrollbarPixelsPerChar here.
scrollDelta *= static_cast<float>(scrollChars) * scrollbarPixelsPerLine;
} else {
unsigned long scrollLines = defaultScrollLinesPerWheelDelta;
SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &scrollLines, 0);
if (scrollLines == WHEEL_PAGESCROLL)
result.scrollByPage = true;
if (!result.scrollByPage)
scrollDelta *= static_cast<float>(scrollLines) * scrollbarPixelsPerLine;
}
// Set scroll amount based on above calculations. WebKit expects positive
// deltaY to mean "scroll up" and positive deltaX to mean "scroll left".
if (horizontalScroll) {
result.deltaX = scrollDelta;
result.wheelTicksX = wheelDelta;
} else {
result.deltaY = scrollDelta;
result.wheelTicksY = wheelDelta;
}
return result;
}
} // namespace WebKit
<commit_msg>Fix typo. The right button is pressed when MK_RBUTTON is set.<commit_after>/*
* Copyright (C) 2006-2009 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "WebInputEventFactory.h"
#include "WebInputEvent.h"
#include <wtf/Assertions.h>
namespace WebKit {
static const unsigned long defaultScrollLinesPerWheelDelta = 3;
static const unsigned long defaultScrollCharsPerWheelDelta = 1;
// WebKeyboardEvent -----------------------------------------------------------
static bool isKeyPad(WPARAM wparam, LPARAM lparam)
{
bool keypad = false;
switch (wparam) {
case VK_RETURN:
keypad = (lparam >> 16) & KF_EXTENDED;
break;
case VK_INSERT:
case VK_DELETE:
case VK_HOME:
case VK_END:
case VK_PRIOR:
case VK_NEXT:
case VK_UP:
case VK_DOWN:
case VK_LEFT:
case VK_RIGHT:
keypad = !((lparam >> 16) & KF_EXTENDED);
break;
case VK_NUMLOCK:
case VK_NUMPAD0:
case VK_NUMPAD1:
case VK_NUMPAD2:
case VK_NUMPAD3:
case VK_NUMPAD4:
case VK_NUMPAD5:
case VK_NUMPAD6:
case VK_NUMPAD7:
case VK_NUMPAD8:
case VK_NUMPAD9:
case VK_DIVIDE:
case VK_MULTIPLY:
case VK_SUBTRACT:
case VK_ADD:
case VK_DECIMAL:
case VK_CLEAR:
keypad = true;
break;
default:
keypad = false;
}
return keypad;
}
WebKeyboardEvent WebInputEventFactory::keyboardEvent(HWND hwnd, UINT message,
WPARAM wparam, LPARAM lparam)
{
WebKeyboardEvent result;
result.windowsKeyCode = result.nativeKeyCode = static_cast<int>(wparam);
switch (message) {
case WM_SYSKEYDOWN:
result.isSystemKey = true;
case WM_KEYDOWN:
result.type = WebInputEvent::RawKeyDown;
break;
case WM_SYSKEYUP:
result.isSystemKey = true;
case WM_KEYUP:
result.type = WebInputEvent::KeyUp;
break;
case WM_IME_CHAR:
result.type = WebInputEvent::Char;
break;
case WM_SYSCHAR:
result.isSystemKey = true;
result.type = WebInputEvent::Char;
case WM_CHAR:
result.type = WebInputEvent::Char;
break;
default:
ASSERT_NOT_REACHED();
}
if (result.type == WebInputEvent::Char || result.type == WebInputEvent::RawKeyDown) {
result.text[0] = result.windowsKeyCode;
result.unmodifiedText[0] = result.windowsKeyCode;
}
if (result.type != WebInputEvent::Char)
result.setKeyIdentifierFromWindowsKeyCode();
if (GetKeyState(VK_SHIFT) & 0x8000)
result.modifiers |= WebInputEvent::ShiftKey;
if (GetKeyState(VK_CONTROL) & 0x8000)
result.modifiers |= WebInputEvent::ControlKey;
if (GetKeyState(VK_MENU) & 0x8000)
result.modifiers |= (WebInputEvent::AltKey | WebInputEvent::MetaKey);
if (LOWORD(lparam) > 1)
result.modifiers |= WebInputEvent::IsAutoRepeat;
if (isKeyPad(wparam, lparam))
result.modifiers |= WebInputEvent::IsKeyPad;
return result;
}
// WebMouseEvent --------------------------------------------------------------
static int gLastClickCount;
static double gLastClickTime;
static LPARAM GetRelativeCursorPos(HWND hwnd)
{
POINT pos = {-1, -1};
GetCursorPos(&pos);
ScreenToClient(hwnd, &pos);
return MAKELPARAM(pos.x, pos.y);
}
void WebInputEventFactory::resetLastClickState()
{
gLastClickTime = gLastClickCount = 0;
}
WebMouseEvent WebInputEventFactory::mouseEvent(HWND hwnd, UINT message,
WPARAM wparam, LPARAM lparam)
{
WebMouseEvent result; //(WebInputEvent::Uninitialized());
switch (message) {
case WM_MOUSEMOVE:
result.type = WebInputEvent::MouseMove;
if (wparam & MK_LBUTTON)
result.button = WebMouseEvent::ButtonLeft;
else if (wparam & MK_MBUTTON)
result.button = WebMouseEvent::ButtonMiddle;
else if (wparam & MK_RBUTTON)
result.button = WebMouseEvent::ButtonRight;
else
result.button = WebMouseEvent::ButtonNone;
break;
case WM_MOUSELEAVE:
result.type = WebInputEvent::MouseLeave;
result.button = WebMouseEvent::ButtonNone;
// set the current mouse position (relative to the client area of the
// current window) since none is specified for this event
lparam = GetRelativeCursorPos(hwnd);
break;
case WM_LBUTTONDOWN:
case WM_LBUTTONDBLCLK:
result.type = WebInputEvent::MouseDown;
result.button = WebMouseEvent::ButtonLeft;
break;
case WM_MBUTTONDOWN:
case WM_MBUTTONDBLCLK:
result.type = WebInputEvent::MouseDown;
result.button = WebMouseEvent::ButtonMiddle;
break;
case WM_RBUTTONDOWN:
case WM_RBUTTONDBLCLK:
result.type = WebInputEvent::MouseDown;
result.button = WebMouseEvent::ButtonRight;
break;
case WM_LBUTTONUP:
result.type = WebInputEvent::MouseUp;
result.button = WebMouseEvent::ButtonLeft;
break;
case WM_MBUTTONUP:
result.type = WebInputEvent::MouseUp;
result.button = WebMouseEvent::ButtonMiddle;
break;
case WM_RBUTTONUP:
result.type = WebInputEvent::MouseUp;
result.button = WebMouseEvent::ButtonRight;
break;
default:
ASSERT_NOT_REACHED();
}
// TODO(pkasting): http://b/1117926 Are we guaranteed that the message that
// GetMessageTime() refers to is the same one that we're passed in? Perhaps
// one of the construction parameters should be the time passed by the
// caller, who would know for sure.
result.timeStampSeconds = GetMessageTime() / 1000.0;
// set position fields:
result.x = static_cast<short>(LOWORD(lparam));
result.y = static_cast<short>(HIWORD(lparam));
POINT globalPoint = { result.x, result.y };
ClientToScreen(hwnd, &globalPoint);
result.globalX = globalPoint.x;
result.globalY = globalPoint.y;
// calculate number of clicks:
// This differs slightly from the WebKit code in WebKit/win/WebView.cpp
// where their original code looks buggy.
static int lastClickPositionX;
static int lastClickPositionY;
static WebMouseEvent::Button lastClickButton = WebMouseEvent::ButtonLeft;
double currentTime = result.timeStampSeconds;
bool cancelPreviousClick =
(abs(lastClickPositionX - result.x) > (GetSystemMetrics(SM_CXDOUBLECLK) / 2))
|| (abs(lastClickPositionY - result.y) > (GetSystemMetrics(SM_CYDOUBLECLK) / 2))
|| ((currentTime - gLastClickTime) * 1000.0 > GetDoubleClickTime());
if (result.type == WebInputEvent::MouseDown) {
if (!cancelPreviousClick && (result.button == lastClickButton))
++gLastClickCount;
else {
gLastClickCount = 1;
lastClickPositionX = result.x;
lastClickPositionY = result.y;
}
gLastClickTime = currentTime;
lastClickButton = result.button;
} else if (result.type == WebInputEvent::MouseMove
|| result.type == WebInputEvent::MouseLeave) {
if (cancelPreviousClick) {
gLastClickCount = 0;
lastClickPositionX = 0;
lastClickPositionY = 0;
gLastClickTime = 0;
}
}
result.clickCount = gLastClickCount;
// set modifiers:
if (wparam & MK_CONTROL)
result.modifiers |= WebInputEvent::ControlKey;
if (wparam & MK_SHIFT)
result.modifiers |= WebInputEvent::ShiftKey;
if (GetKeyState(VK_MENU) & 0x8000)
result.modifiers |= (WebInputEvent::AltKey | WebInputEvent::MetaKey); // FIXME: set META properly
return result;
}
// WebMouseWheelEvent ---------------------------------------------------------
WebMouseWheelEvent WebInputEventFactory::mouseWheelEvent(HWND hwnd, UINT message,
WPARAM wparam, LPARAM lparam)
{
WebMouseWheelEvent result; //(WebInputEvent::Uninitialized());
result.type = WebInputEvent::MouseWheel;
result.button = WebMouseEvent::ButtonNone;
// Get key state, coordinates, and wheel delta from event.
typedef SHORT (WINAPI *GetKeyStateFunction)(int key);
GetKeyStateFunction getKeyState;
UINT keyState;
float wheelDelta;
bool horizontalScroll = false;
if ((message == WM_VSCROLL) || (message == WM_HSCROLL)) {
// Synthesize mousewheel event from a scroll event. This is needed to
// simulate middle mouse scrolling in some laptops. Use GetAsyncKeyState
// for key state since we are synthesizing the input event.
getKeyState = GetAsyncKeyState;
keyState = 0;
if (getKeyState(VK_SHIFT))
keyState |= MK_SHIFT;
if (getKeyState(VK_CONTROL))
keyState |= MK_CONTROL;
POINT cursorPosition = {0};
GetCursorPos(&cursorPosition);
result.globalX = cursorPosition.x;
result.globalY = cursorPosition.y;
switch (LOWORD(wparam)) {
case SB_LINEUP: // == SB_LINELEFT
wheelDelta = WHEEL_DELTA;
break;
case SB_LINEDOWN: // == SB_LINERIGHT
wheelDelta = -WHEEL_DELTA;
break;
case SB_PAGEUP:
wheelDelta = 1;
result.scrollByPage = true;
break;
case SB_PAGEDOWN:
wheelDelta = -1;
result.scrollByPage = true;
break;
default: // We don't supoprt SB_THUMBPOSITION or SB_THUMBTRACK here.
wheelDelta = 0;
break;
}
if (message == WM_HSCROLL)
horizontalScroll = true;
} else {
// Non-synthesized event; we can just read data off the event.
getKeyState = GetKeyState;
keyState = GET_KEYSTATE_WPARAM(wparam);
result.globalX = static_cast<short>(LOWORD(lparam));
result.globalY = static_cast<short>(HIWORD(lparam));
wheelDelta = static_cast<float>(GET_WHEEL_DELTA_WPARAM(wparam));
if (message == WM_MOUSEHWHEEL) {
horizontalScroll = true;
wheelDelta = -wheelDelta; // Windows is <- -/+ ->, WebKit <- +/- ->.
}
}
if (keyState & MK_SHIFT)
horizontalScroll = true;
// Set modifiers based on key state.
if (keyState & MK_SHIFT)
result.modifiers |= WebInputEvent::ShiftKey;
if (keyState & MK_CONTROL)
result.modifiers |= WebInputEvent::ControlKey;
if (getKeyState(VK_MENU) & 0x8000)
result.modifiers |= (WebInputEvent::AltKey | WebInputEvent::MetaKey);
// Set coordinates by translating event coordinates from screen to client.
POINT clientPoint = { result.globalX, result.globalY };
MapWindowPoints(NULL, hwnd, &clientPoint, 1);
result.x = clientPoint.x;
result.y = clientPoint.y;
// Convert wheel delta amount to a number of pixels to scroll.
//
// How many pixels should we scroll per line? Gecko uses the height of the
// current line, which means scroll distance changes as you go through the
// page or go to different pages. IE 7 is ~50 px/line, although the value
// seems to vary slightly by page and zoom level. Since IE 7 has a smoothing
// algorithm on scrolling, it can get away with slightly larger scroll values
// without feeling jerky. Here we use 100 px per three lines (the default
// scroll amount is three lines per wheel tick).
static const float scrollbarPixelsPerLine = 100.0f / 3.0f;
wheelDelta /= WHEEL_DELTA;
float scrollDelta = wheelDelta;
if (horizontalScroll) {
unsigned long scrollChars = defaultScrollCharsPerWheelDelta;
SystemParametersInfo(SPI_GETWHEELSCROLLCHARS, 0, &scrollChars, 0);
// TODO(pkasting): Should probably have a different multiplier
// scrollbarPixelsPerChar here.
scrollDelta *= static_cast<float>(scrollChars) * scrollbarPixelsPerLine;
} else {
unsigned long scrollLines = defaultScrollLinesPerWheelDelta;
SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &scrollLines, 0);
if (scrollLines == WHEEL_PAGESCROLL)
result.scrollByPage = true;
if (!result.scrollByPage)
scrollDelta *= static_cast<float>(scrollLines) * scrollbarPixelsPerLine;
}
// Set scroll amount based on above calculations. WebKit expects positive
// deltaY to mean "scroll up" and positive deltaX to mean "scroll left".
if (horizontalScroll) {
result.deltaX = scrollDelta;
result.wheelTicksX = wheelDelta;
} else {
result.deltaY = scrollDelta;
result.wheelTicksY = wheelDelta;
}
return result;
}
} // namespace WebKit
<|endoftext|>
|
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "config.h"
#include <wtf/HashSet.h>
#include <wtf/RefPtr.h>
#include <wtf/Vector.h>
#include "Document.h"
#include "Page.h"
#include "V8Binding.h"
#include "V8DOMWindow.h"
#include "V8Index.h"
#include "V8Proxy.h"
#undef LOG
#include "base/string_piece.h"
#include "grit/webkit_resources.h"
#include "webkit/glue/devtools/debugger_agent_impl.h"
#include "webkit/glue/devtools/debugger_agent_manager.h"
#include "webkit/glue/glue_util.h"
#include "webkit/glue/webdevtoolsagent_impl.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/glue/webview_impl.h"
using WebCore::DOMWindow;
using WebCore::Document;
using WebCore::Frame;
using WebCore::Page;
using WebCore::String;
using WebCore::V8ClassIndex;
using WebCore::V8Custom;
using WebCore::V8DOMWindow;
using WebCore::V8Proxy;
DebuggerAgentImpl::DebuggerAgentImpl(
WebViewImpl* web_view_impl,
DebuggerAgentDelegate* delegate,
WebDevToolsAgentImpl* webdevtools_agent)
: web_view_impl_(web_view_impl),
delegate_(delegate),
webdevtools_agent_(webdevtools_agent),
profiler_log_position_(0) {
DebuggerAgentManager::DebugAttach(this);
}
DebuggerAgentImpl::~DebuggerAgentImpl() {
DebuggerAgentManager::DebugDetach(this);
}
void DebuggerAgentImpl::DebugBreak() {
DebuggerAgentManager::DebugBreak(this);
}
void DebuggerAgentImpl::GetContextId() {
delegate_->SetContextId(webdevtools_agent_->host_id());
}
void DebuggerAgentImpl::StartProfiling() {
v8::HandleScope scope;
WebCore::V8Proxy* proxy = V8Proxy::retrieve(GetPage()->mainFrame());
DCHECK(proxy && proxy->isContextInitialized());
v8::Context::Scope context_scope(proxy->context());
v8::V8::ResumeProfiler();
}
void DebuggerAgentImpl::StopProfiling() {
v8::V8::PauseProfiler();
}
void DebuggerAgentImpl::IsProfilingStarted() {
delegate_->DidIsProfilingStarted(!v8::V8::IsProfilerPaused());
}
void DebuggerAgentImpl::GetNextLogLines() {
static char buffer[65536];
int read_size = v8::V8::GetLogLines(
profiler_log_position_, buffer, sizeof(buffer) - 1);
profiler_log_position_ += read_size;
buffer[read_size] = '\0';
delegate_->DidGetNextLogLines(buffer);
}
void DebuggerAgentImpl::DebuggerOutput(const std::string& command) {
delegate_->DebuggerOutput(command);
webdevtools_agent_->ForceRepaint();
}
// static
void DebuggerAgentImpl::ResetUtilityContext(
Document* document,
v8::Persistent<v8::Context>* context) {
if (!context->IsEmpty()) {
context->Dispose();
context->Clear();
}
v8::HandleScope scope;
// TODO(pfeldman): Validate against Soeren.
// Set up the DOM window as the prototype of the new global object.
v8::Handle<v8::Context> window_context =
V8Proxy::context(document->frame());
v8::Handle<v8::Object> window_global = window_context->Global();
v8::Handle<v8::Value> window_wrapper =
V8Proxy::lookupDOMWrapper(V8ClassIndex::DOMWINDOW, window_global);
ASSERT(V8Proxy::convertDOMWrapperToNative<DOMWindow>(window_wrapper) ==
document->frame()->domWindow());
// Create a new environment using an empty template for the shadow
// object. Reuse the global object if one has been created earlier.
v8::Handle<v8::ObjectTemplate> global_template =
V8DOMWindow::GetShadowObjectTemplate();
// Install a security handler with V8.
global_template->SetAccessCheckCallbacks(
V8Custom::v8DOMWindowNamedSecurityCheck,
V8Custom::v8DOMWindowIndexedSecurityCheck,
v8::Integer::New(V8ClassIndex::DOMWINDOW));
*context = v8::Context::New(
NULL /* no extensions */,
global_template,
v8::Handle<v8::Object>());
v8::Context::Scope context_scope(*context);
v8::Handle<v8::Object> global = (*context)->Global();
v8::Handle<v8::String> implicit_proto_string = v8::String::New("__proto__");
global->Set(implicit_proto_string, window_wrapper);
// Give the code running in the new context a way to get access to the
// original context.
global->Set(v8::String::New("contentWindow"), window_global);
// Inject javascript into the context.
StringPiece basejs = webkit_glue::GetDataResource(IDR_DEVTOOLS_BASE_JS);
v8::Script::Compile(v8::String::New(basejs.as_string().c_str()))->Run();
StringPiece injectjs = webkit_glue::GetDataResource(IDR_DEVTOOLS_INJECT_JS);
v8::Script::Compile(v8::String::New(injectjs.as_string().c_str()))->Run();
StringPiece inject_dispatchjs = webkit_glue::GetDataResource(
IDR_DEVTOOLS_INJECT_DISPATCH_JS);
v8::Script::Compile(v8::String::New(
inject_dispatchjs.as_string().c_str()))->Run();
}
String DebuggerAgentImpl::ExecuteUtilityFunction(
v8::Handle<v8::Context> context,
const String &function_name,
const String& json_args,
String* exception) {
v8::HandleScope scope;
ASSERT(!context.IsEmpty());
if (context.IsEmpty()) {
*exception = "No window context.";
return "";
}
v8::Context::Scope context_scope(context);
v8::Handle<v8::Function> function = v8::Local<v8::Function>::Cast(
context->Global()->Get(v8::String::New("devtools$$dispatch")));
v8::Handle<v8::String> function_name_wrapper = v8::Handle<v8::String>(
v8::String::New(function_name.utf8().data()));
v8::Handle<v8::String> json_args_wrapper = v8::Handle<v8::String>(
v8::String::New(json_args.utf8().data()));
v8::Handle<v8::Value> args[] = {
function_name_wrapper,
json_args_wrapper
};
v8::TryCatch try_catch;
v8::Handle<v8::Value> res_obj = function->Call(context->Global(), 2, args);
if (try_catch.HasCaught()) {
*exception = WebCore::toWebCoreString(try_catch.Message()->Get());
return "";
} else {
v8::Handle<v8::String> res_json = v8::Handle<v8::String>::Cast(res_obj);
return WebCore::toWebCoreString(res_json);
}
}
WebCore::Page* DebuggerAgentImpl::GetPage() {
return web_view_impl_->page();
}
<commit_msg>Land Anton's patch to avoid throwing away type information on the window wrapper in the debugger agent.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "config.h"
#include <wtf/HashSet.h>
#include <wtf/RefPtr.h>
#include <wtf/Vector.h>
#include "Document.h"
#include "Page.h"
#include "V8Binding.h"
#include "V8DOMWindow.h"
#include "V8Index.h"
#include "V8Proxy.h"
#undef LOG
#include "base/string_piece.h"
#include "grit/webkit_resources.h"
#include "webkit/glue/devtools/debugger_agent_impl.h"
#include "webkit/glue/devtools/debugger_agent_manager.h"
#include "webkit/glue/glue_util.h"
#include "webkit/glue/webdevtoolsagent_impl.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/glue/webview_impl.h"
using WebCore::DOMWindow;
using WebCore::Document;
using WebCore::Frame;
using WebCore::Page;
using WebCore::String;
using WebCore::V8ClassIndex;
using WebCore::V8Custom;
using WebCore::V8DOMWindow;
using WebCore::V8Proxy;
DebuggerAgentImpl::DebuggerAgentImpl(
WebViewImpl* web_view_impl,
DebuggerAgentDelegate* delegate,
WebDevToolsAgentImpl* webdevtools_agent)
: web_view_impl_(web_view_impl),
delegate_(delegate),
webdevtools_agent_(webdevtools_agent),
profiler_log_position_(0) {
DebuggerAgentManager::DebugAttach(this);
}
DebuggerAgentImpl::~DebuggerAgentImpl() {
DebuggerAgentManager::DebugDetach(this);
}
void DebuggerAgentImpl::DebugBreak() {
DebuggerAgentManager::DebugBreak(this);
}
void DebuggerAgentImpl::GetContextId() {
delegate_->SetContextId(webdevtools_agent_->host_id());
}
void DebuggerAgentImpl::StartProfiling() {
v8::HandleScope scope;
WebCore::V8Proxy* proxy = V8Proxy::retrieve(GetPage()->mainFrame());
DCHECK(proxy && proxy->isContextInitialized());
v8::Context::Scope context_scope(proxy->context());
v8::V8::ResumeProfiler();
}
void DebuggerAgentImpl::StopProfiling() {
v8::V8::PauseProfiler();
}
void DebuggerAgentImpl::IsProfilingStarted() {
delegate_->DidIsProfilingStarted(!v8::V8::IsProfilerPaused());
}
void DebuggerAgentImpl::GetNextLogLines() {
static char buffer[65536];
int read_size = v8::V8::GetLogLines(
profiler_log_position_, buffer, sizeof(buffer) - 1);
profiler_log_position_ += read_size;
buffer[read_size] = '\0';
delegate_->DidGetNextLogLines(buffer);
}
void DebuggerAgentImpl::DebuggerOutput(const std::string& command) {
delegate_->DebuggerOutput(command);
webdevtools_agent_->ForceRepaint();
}
// static
void DebuggerAgentImpl::ResetUtilityContext(
Document* document,
v8::Persistent<v8::Context>* context) {
if (!context->IsEmpty()) {
context->Dispose();
context->Clear();
}
v8::HandleScope scope;
// TODO(pfeldman): Validate against Soeren.
// Set up the DOM window as the prototype of the new global object.
v8::Handle<v8::Context> window_context =
V8Proxy::context(document->frame());
v8::Handle<v8::Object> window_global = window_context->Global();
v8::Handle<v8::Object> window_wrapper =
V8Proxy::lookupDOMWrapper(V8ClassIndex::DOMWINDOW, window_global);
ASSERT(V8Proxy::convertDOMWrapperToNative<DOMWindow>(window_wrapper) ==
document->frame()->domWindow());
// Create a new environment using an empty template for the shadow
// object. Reuse the global object if one has been created earlier.
v8::Handle<v8::ObjectTemplate> global_template =
V8DOMWindow::GetShadowObjectTemplate();
// Install a security handler with V8.
global_template->SetAccessCheckCallbacks(
V8Custom::v8DOMWindowNamedSecurityCheck,
V8Custom::v8DOMWindowIndexedSecurityCheck,
v8::Integer::New(V8ClassIndex::DOMWINDOW));
*context = v8::Context::New(
NULL /* no extensions */,
global_template,
v8::Handle<v8::Object>());
v8::Context::Scope context_scope(*context);
v8::Handle<v8::Object> global = (*context)->Global();
v8::Handle<v8::String> implicit_proto_string = v8::String::New("__proto__");
global->Set(implicit_proto_string, window_wrapper);
// Give the code running in the new context a way to get access to the
// original context.
global->Set(v8::String::New("contentWindow"), window_global);
// Inject javascript into the context.
StringPiece basejs = webkit_glue::GetDataResource(IDR_DEVTOOLS_BASE_JS);
v8::Script::Compile(v8::String::New(basejs.as_string().c_str()))->Run();
StringPiece injectjs = webkit_glue::GetDataResource(IDR_DEVTOOLS_INJECT_JS);
v8::Script::Compile(v8::String::New(injectjs.as_string().c_str()))->Run();
StringPiece inject_dispatchjs = webkit_glue::GetDataResource(
IDR_DEVTOOLS_INJECT_DISPATCH_JS);
v8::Script::Compile(v8::String::New(
inject_dispatchjs.as_string().c_str()))->Run();
}
String DebuggerAgentImpl::ExecuteUtilityFunction(
v8::Handle<v8::Context> context,
const String &function_name,
const String& json_args,
String* exception) {
v8::HandleScope scope;
ASSERT(!context.IsEmpty());
if (context.IsEmpty()) {
*exception = "No window context.";
return "";
}
v8::Context::Scope context_scope(context);
v8::Handle<v8::Function> function = v8::Local<v8::Function>::Cast(
context->Global()->Get(v8::String::New("devtools$$dispatch")));
v8::Handle<v8::String> function_name_wrapper = v8::Handle<v8::String>(
v8::String::New(function_name.utf8().data()));
v8::Handle<v8::String> json_args_wrapper = v8::Handle<v8::String>(
v8::String::New(json_args.utf8().data()));
v8::Handle<v8::Value> args[] = {
function_name_wrapper,
json_args_wrapper
};
v8::TryCatch try_catch;
v8::Handle<v8::Value> res_obj = function->Call(context->Global(), 2, args);
if (try_catch.HasCaught()) {
*exception = WebCore::toWebCoreString(try_catch.Message()->Get());
return "";
} else {
v8::Handle<v8::String> res_json = v8::Handle<v8::String>::Cast(res_obj);
return WebCore::toWebCoreString(res_json);
}
}
WebCore::Page* DebuggerAgentImpl::GetPage() {
return web_view_impl_->page();
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2008 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h"
#include "Color.h"
#include "SkColor.h"
#include <wtf/Assertions.h>
namespace WebCore {
COMPILE_ASSERT(SK_ColorBLACK == Color::black, SkColorAndColorAreLaidOutTheSame);
Color WebCore::focusRingColor()
{
static Color focusRingColor(229, 151, 0, 255);
return focusRingColor;
}
} // namespace WebCore
<commit_msg>Fix at least the Linux build. Boo MSVC for not complaining about this.<commit_after>/*
* Copyright (C) 2008 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h"
#include "Color.h"
#include "SkColor.h"
#include <wtf/Assertions.h>
namespace WebCore {
COMPILE_ASSERT(SK_ColorBLACK == Color::black, SkColorAndColorAreLaidOutTheSame);
Color focusRingColor()
{
static Color focusRingColor(229, 151, 0, 255);
return focusRingColor;
}
} // namespace WebCore
<|endoftext|>
|
<commit_before>//===- unittests/Basic/FileMangerTest.cpp ------------ FileManger tests ---===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "clang/Basic/FileManager.h"
#include "clang/Basic/FileSystemOptions.h"
#include "clang/Basic/FileSystemStatCache.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/VirtualFileSystem.h"
#include "gtest/gtest.h"
using namespace llvm;
using namespace clang;
namespace {
// Used to create a fake file system for running the tests with such
// that the tests are not affected by the structure/contents of the
// file system on the machine running the tests.
class FakeStatCache : public FileSystemStatCache {
private:
// Maps a file/directory path to its desired stat result. Anything
// not in this map is considered to not exist in the file system.
llvm::StringMap<llvm::vfs::Status, llvm::BumpPtrAllocator> StatCalls;
void InjectFileOrDirectory(const char *Path, ino_t INode, bool IsFile) {
#ifndef _WIN32
SmallString<128> NormalizedPath(Path);
llvm::sys::path::native(NormalizedPath);
Path = NormalizedPath.c_str();
#endif
auto fileType = IsFile ?
llvm::sys::fs::file_type::regular_file :
llvm::sys::fs::file_type::directory_file;
llvm::vfs::Status Status(Path, llvm::sys::fs::UniqueID(1, INode),
/*MTime*/{}, /*User*/0, /*Group*/0,
/*Size*/0, fileType,
llvm::sys::fs::perms::all_all);
StatCalls[Path] = Status;
}
public:
// Inject a file with the given inode value to the fake file system.
void InjectFile(const char *Path, ino_t INode) {
InjectFileOrDirectory(Path, INode, /*IsFile=*/true);
}
// Inject a directory with the given inode value to the fake file system.
void InjectDirectory(const char *Path, ino_t INode) {
InjectFileOrDirectory(Path, INode, /*IsFile=*/false);
}
// Implement FileSystemStatCache::getStat().
std::error_code getStat(StringRef Path, llvm::vfs::Status &Status,
bool isFile,
std::unique_ptr<llvm::vfs::File> *F,
llvm::vfs::FileSystem &FS) override {
#ifndef _WIN32
SmallString<128> NormalizedPath(Path);
llvm::sys::path::native(NormalizedPath);
Path = NormalizedPath.c_str();
#endif
if (StatCalls.count(Path) != 0) {
Status = StatCalls[Path];
return std::error_code();
}
return std::make_error_code(std::errc::no_such_file_or_directory);
}
};
// The test fixture.
class FileManagerTest : public ::testing::Test {
protected:
FileManagerTest() : manager(options) {
}
FileSystemOptions options;
FileManager manager;
};
// When a virtual file is added, its getDir() field is set correctly
// (not NULL, correct name).
TEST_F(FileManagerTest, getVirtualFileSetsTheDirFieldCorrectly) {
const FileEntry *file = manager.getVirtualFile("foo.cpp", 42, 0);
ASSERT_TRUE(file != nullptr);
const DirectoryEntry *dir = file->getDir();
ASSERT_TRUE(dir != nullptr);
EXPECT_EQ(".", dir->getName());
file = manager.getVirtualFile("x/y/z.cpp", 42, 0);
ASSERT_TRUE(file != nullptr);
dir = file->getDir();
ASSERT_TRUE(dir != nullptr);
EXPECT_EQ("x/y", dir->getName());
}
// Before any virtual file is added, no virtual directory exists.
TEST_F(FileManagerTest, NoVirtualDirectoryExistsBeforeAVirtualFileIsAdded) {
// An empty FakeStatCache causes all stat calls made by the
// FileManager to report "file/directory doesn't exist". This
// avoids the possibility of the result of this test being affected
// by what's in the real file system.
manager.setStatCache(llvm::make_unique<FakeStatCache>());
ASSERT_FALSE(manager.getDirectory("virtual/dir/foo"));
ASSERT_FALSE(manager.getDirectory("virtual/dir"));
ASSERT_FALSE(manager.getDirectory("virtual"));
}
// When a virtual file is added, all of its ancestors should be created.
TEST_F(FileManagerTest, getVirtualFileCreatesDirectoryEntriesForAncestors) {
// Fake an empty real file system.
manager.setStatCache(llvm::make_unique<FakeStatCache>());
manager.getVirtualFile("virtual/dir/bar.h", 100, 0);
ASSERT_FALSE(manager.getDirectory("virtual/dir/foo"));
auto dir = manager.getDirectory("virtual/dir");
ASSERT_TRUE(dir);
EXPECT_EQ("virtual/dir", (*dir)->getName());
dir = manager.getDirectory("virtual");
ASSERT_TRUE(dir);
EXPECT_EQ("virtual", (*dir)->getName());
}
// getFile() returns non-NULL if a real file exists at the given path.
TEST_F(FileManagerTest, getFileReturnsValidFileEntryForExistingRealFile) {
// Inject fake files into the file system.
auto statCache = llvm::make_unique<FakeStatCache>();
statCache->InjectDirectory("/tmp", 42);
statCache->InjectFile("/tmp/test", 43);
#ifdef _WIN32
const char *DirName = "C:.";
const char *FileName = "C:test";
statCache->InjectDirectory(DirName, 44);
statCache->InjectFile(FileName, 45);
#endif
manager.setStatCache(std::move(statCache));
auto file = manager.getFile("/tmp/test");
ASSERT_TRUE(file);
ASSERT_TRUE((*file)->isValid());
EXPECT_EQ("/tmp/test", (*file)->getName());
const DirectoryEntry *dir = (*file)->getDir();
ASSERT_TRUE(dir != nullptr);
EXPECT_EQ("/tmp", dir->getName());
#ifdef _WIN32
file = manager.getFile(FileName);
ASSERT_TRUE(file);
dir = file->getDir();
ASSERT_TRUE(dir != NULL);
EXPECT_EQ(DirName, dir->getName());
#endif
}
// getFile() returns non-NULL if a virtual file exists at the given path.
TEST_F(FileManagerTest, getFileReturnsValidFileEntryForExistingVirtualFile) {
// Fake an empty real file system.
manager.setStatCache(llvm::make_unique<FakeStatCache>());
manager.getVirtualFile("virtual/dir/bar.h", 100, 0);
auto file = manager.getFile("virtual/dir/bar.h");
ASSERT_TRUE(file);
ASSERT_TRUE((*file)->isValid());
EXPECT_EQ("virtual/dir/bar.h", (*file)->getName());
const DirectoryEntry *dir = (*file)->getDir();
ASSERT_TRUE(dir != nullptr);
EXPECT_EQ("virtual/dir", dir->getName());
}
// getFile() returns different FileEntries for different paths when
// there's no aliasing.
TEST_F(FileManagerTest, getFileReturnsDifferentFileEntriesForDifferentFiles) {
// Inject two fake files into the file system. Different inodes
// mean the files are not symlinked together.
auto statCache = llvm::make_unique<FakeStatCache>();
statCache->InjectDirectory(".", 41);
statCache->InjectFile("foo.cpp", 42);
statCache->InjectFile("bar.cpp", 43);
manager.setStatCache(std::move(statCache));
auto fileFoo = manager.getFile("foo.cpp");
auto fileBar = manager.getFile("bar.cpp");
ASSERT_TRUE(fileFoo);
ASSERT_TRUE((*fileFoo)->isValid());
ASSERT_TRUE(fileBar);
ASSERT_TRUE((*fileBar)->isValid());
EXPECT_NE(*fileFoo, *fileBar);
}
// getFile() returns an error if neither a real file nor a virtual file
// exists at the given path.
TEST_F(FileManagerTest, getFileReturnsErrorForNonexistentFile) {
// Inject a fake foo.cpp into the file system.
auto statCache = llvm::make_unique<FakeStatCache>();
statCache->InjectDirectory(".", 41);
statCache->InjectFile("foo.cpp", 42);
statCache->InjectDirectory("MyDirectory", 49);
manager.setStatCache(std::move(statCache));
// Create a virtual bar.cpp file.
manager.getVirtualFile("bar.cpp", 200, 0);
auto file = manager.getFile("xyz.txt");
ASSERT_FALSE(file);
ASSERT_EQ(file.getError(), std::errc::no_such_file_or_directory);
auto readingDirAsFile = manager.getFile("MyDirectory");
ASSERT_FALSE(readingDirAsFile);
ASSERT_EQ(readingDirAsFile.getError(), std::errc::is_a_directory);
auto readingFileAsDir = manager.getDirectory("foo.cpp");
ASSERT_FALSE(readingFileAsDir);
ASSERT_EQ(readingFileAsDir.getError(), std::errc::not_a_directory);
}
// The following tests apply to Unix-like system only.
#ifndef _WIN32
// getFile() returns the same FileEntry for real files that are aliases.
TEST_F(FileManagerTest, getFileReturnsSameFileEntryForAliasedRealFiles) {
// Inject two real files with the same inode.
auto statCache = llvm::make_unique<FakeStatCache>();
statCache->InjectDirectory("abc", 41);
statCache->InjectFile("abc/foo.cpp", 42);
statCache->InjectFile("abc/bar.cpp", 42);
manager.setStatCache(std::move(statCache));
auto f1 = manager.getFile("abc/foo.cpp");
auto f2 = manager.getFile("abc/bar.cpp");
EXPECT_EQ(f1 ? *f1 : nullptr,
f2 ? *f2 : nullptr);
}
// getFile() returns the same FileEntry for virtual files that have
// corresponding real files that are aliases.
TEST_F(FileManagerTest, getFileReturnsSameFileEntryForAliasedVirtualFiles) {
// Inject two real files with the same inode.
auto statCache = llvm::make_unique<FakeStatCache>();
statCache->InjectDirectory("abc", 41);
statCache->InjectFile("abc/foo.cpp", 42);
statCache->InjectFile("abc/bar.cpp", 42);
manager.setStatCache(std::move(statCache));
ASSERT_TRUE(manager.getVirtualFile("abc/foo.cpp", 100, 0)->isValid());
ASSERT_TRUE(manager.getVirtualFile("abc/bar.cpp", 200, 0)->isValid());
auto f1 = manager.getFile("abc/foo.cpp");
auto f2 = manager.getFile("abc/bar.cpp");
EXPECT_EQ(f1 ? *f1 : nullptr,
f2 ? *f2 : nullptr);
}
// getFile() Should return the same entry as getVirtualFile if the file actually
// is a virtual file, even if the name is not exactly the same (but is after
// normalisation done by the file system, like on Windows). This can be checked
// here by checking the size.
TEST_F(FileManagerTest, getVirtualFileWithDifferentName) {
// Inject fake files into the file system.
auto statCache = llvm::make_unique<FakeStatCache>();
statCache->InjectDirectory("c:\\tmp", 42);
statCache->InjectFile("c:\\tmp\\test", 43);
manager.setStatCache(std::move(statCache));
// Inject the virtual file:
const FileEntry *file1 = manager.getVirtualFile("c:\\tmp\\test", 123, 1);
ASSERT_TRUE(file1 != nullptr);
ASSERT_TRUE(file1->isValid());
EXPECT_EQ(43U, file1->getUniqueID().getFile());
EXPECT_EQ(123, file1->getSize());
// Lookup the virtual file with a different name:
auto file2 = manager.getFile("c:/tmp/test", 100, 1);
ASSERT_TRUE(file2);
ASSERT_TRUE((*file2)->isValid());
// Check that it's the same UFE:
EXPECT_EQ(file1, *file2);
EXPECT_EQ(43U, (*file2)->getUniqueID().getFile());
// Check that the contents of the UFE are not overwritten by the entry in the
// filesystem:
EXPECT_EQ(123, (*file2)->getSize());
}
#endif // !_WIN32
TEST_F(FileManagerTest, makeAbsoluteUsesVFS) {
SmallString<64> CustomWorkingDir;
#ifdef _WIN32
CustomWorkingDir = "C:";
#else
CustomWorkingDir = "/";
#endif
llvm::sys::path::append(CustomWorkingDir, "some", "weird", "path");
auto FS = IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem>(
new llvm::vfs::InMemoryFileSystem);
// setCurrentworkingdirectory must finish without error.
ASSERT_TRUE(!FS->setCurrentWorkingDirectory(CustomWorkingDir));
FileSystemOptions Opts;
FileManager Manager(Opts, FS);
SmallString<64> Path("a/foo.cpp");
SmallString<64> ExpectedResult(CustomWorkingDir);
llvm::sys::path::append(ExpectedResult, Path);
ASSERT_TRUE(Manager.makeAbsolutePath(Path));
EXPECT_EQ(Path, ExpectedResult);
}
// getVirtualFile should always fill the real path.
TEST_F(FileManagerTest, getVirtualFileFillsRealPathName) {
SmallString<64> CustomWorkingDir;
#ifdef _WIN32
CustomWorkingDir = "C:/";
#else
CustomWorkingDir = "/";
#endif
auto FS = IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem>(
new llvm::vfs::InMemoryFileSystem);
// setCurrentworkingdirectory must finish without error.
ASSERT_TRUE(!FS->setCurrentWorkingDirectory(CustomWorkingDir));
FileSystemOptions Opts;
FileManager Manager(Opts, FS);
// Inject fake files into the file system.
auto statCache = llvm::make_unique<FakeStatCache>();
statCache->InjectDirectory("/tmp", 42);
statCache->InjectFile("/tmp/test", 43);
Manager.setStatCache(std::move(statCache));
// Check for real path.
const FileEntry *file = Manager.getVirtualFile("/tmp/test", 123, 1);
ASSERT_TRUE(file != nullptr);
ASSERT_TRUE(file->isValid());
SmallString<64> ExpectedResult = CustomWorkingDir;
llvm::sys::path::append(ExpectedResult, "tmp", "test");
EXPECT_EQ(file->tryGetRealPathName(), ExpectedResult);
}
TEST_F(FileManagerTest, getFileDontOpenRealPath) {
SmallString<64> CustomWorkingDir;
#ifdef _WIN32
CustomWorkingDir = "C:/";
#else
CustomWorkingDir = "/";
#endif
auto FS = IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem>(
new llvm::vfs::InMemoryFileSystem);
// setCurrentworkingdirectory must finish without error.
ASSERT_TRUE(!FS->setCurrentWorkingDirectory(CustomWorkingDir));
FileSystemOptions Opts;
FileManager Manager(Opts, FS);
// Inject fake files into the file system.
auto statCache = llvm::make_unique<FakeStatCache>();
statCache->InjectDirectory("/tmp", 42);
statCache->InjectFile("/tmp/test", 43);
Manager.setStatCache(std::move(statCache));
// Check for real path.
auto file = Manager.getFile("/tmp/test", /*OpenFile=*/false);
ASSERT_TRUE(file);
ASSERT_TRUE((*file)->isValid());
SmallString<64> ExpectedResult = CustomWorkingDir;
llvm::sys::path::append(ExpectedResult, "tmp", "test");
EXPECT_EQ((*file)->tryGetRealPathName(), ExpectedResult);
}
} // anonymous namespace
<commit_msg>Fix Windows branch of FileManagerTest changes<commit_after>//===- unittests/Basic/FileMangerTest.cpp ------------ FileManger tests ---===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "clang/Basic/FileManager.h"
#include "clang/Basic/FileSystemOptions.h"
#include "clang/Basic/FileSystemStatCache.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/VirtualFileSystem.h"
#include "gtest/gtest.h"
using namespace llvm;
using namespace clang;
namespace {
// Used to create a fake file system for running the tests with such
// that the tests are not affected by the structure/contents of the
// file system on the machine running the tests.
class FakeStatCache : public FileSystemStatCache {
private:
// Maps a file/directory path to its desired stat result. Anything
// not in this map is considered to not exist in the file system.
llvm::StringMap<llvm::vfs::Status, llvm::BumpPtrAllocator> StatCalls;
void InjectFileOrDirectory(const char *Path, ino_t INode, bool IsFile) {
#ifndef _WIN32
SmallString<128> NormalizedPath(Path);
llvm::sys::path::native(NormalizedPath);
Path = NormalizedPath.c_str();
#endif
auto fileType = IsFile ?
llvm::sys::fs::file_type::regular_file :
llvm::sys::fs::file_type::directory_file;
llvm::vfs::Status Status(Path, llvm::sys::fs::UniqueID(1, INode),
/*MTime*/{}, /*User*/0, /*Group*/0,
/*Size*/0, fileType,
llvm::sys::fs::perms::all_all);
StatCalls[Path] = Status;
}
public:
// Inject a file with the given inode value to the fake file system.
void InjectFile(const char *Path, ino_t INode) {
InjectFileOrDirectory(Path, INode, /*IsFile=*/true);
}
// Inject a directory with the given inode value to the fake file system.
void InjectDirectory(const char *Path, ino_t INode) {
InjectFileOrDirectory(Path, INode, /*IsFile=*/false);
}
// Implement FileSystemStatCache::getStat().
std::error_code getStat(StringRef Path, llvm::vfs::Status &Status,
bool isFile,
std::unique_ptr<llvm::vfs::File> *F,
llvm::vfs::FileSystem &FS) override {
#ifndef _WIN32
SmallString<128> NormalizedPath(Path);
llvm::sys::path::native(NormalizedPath);
Path = NormalizedPath.c_str();
#endif
if (StatCalls.count(Path) != 0) {
Status = StatCalls[Path];
return std::error_code();
}
return std::make_error_code(std::errc::no_such_file_or_directory);
}
};
// The test fixture.
class FileManagerTest : public ::testing::Test {
protected:
FileManagerTest() : manager(options) {
}
FileSystemOptions options;
FileManager manager;
};
// When a virtual file is added, its getDir() field is set correctly
// (not NULL, correct name).
TEST_F(FileManagerTest, getVirtualFileSetsTheDirFieldCorrectly) {
const FileEntry *file = manager.getVirtualFile("foo.cpp", 42, 0);
ASSERT_TRUE(file != nullptr);
const DirectoryEntry *dir = file->getDir();
ASSERT_TRUE(dir != nullptr);
EXPECT_EQ(".", dir->getName());
file = manager.getVirtualFile("x/y/z.cpp", 42, 0);
ASSERT_TRUE(file != nullptr);
dir = file->getDir();
ASSERT_TRUE(dir != nullptr);
EXPECT_EQ("x/y", dir->getName());
}
// Before any virtual file is added, no virtual directory exists.
TEST_F(FileManagerTest, NoVirtualDirectoryExistsBeforeAVirtualFileIsAdded) {
// An empty FakeStatCache causes all stat calls made by the
// FileManager to report "file/directory doesn't exist". This
// avoids the possibility of the result of this test being affected
// by what's in the real file system.
manager.setStatCache(llvm::make_unique<FakeStatCache>());
ASSERT_FALSE(manager.getDirectory("virtual/dir/foo"));
ASSERT_FALSE(manager.getDirectory("virtual/dir"));
ASSERT_FALSE(manager.getDirectory("virtual"));
}
// When a virtual file is added, all of its ancestors should be created.
TEST_F(FileManagerTest, getVirtualFileCreatesDirectoryEntriesForAncestors) {
// Fake an empty real file system.
manager.setStatCache(llvm::make_unique<FakeStatCache>());
manager.getVirtualFile("virtual/dir/bar.h", 100, 0);
ASSERT_FALSE(manager.getDirectory("virtual/dir/foo"));
auto dir = manager.getDirectory("virtual/dir");
ASSERT_TRUE(dir);
EXPECT_EQ("virtual/dir", (*dir)->getName());
dir = manager.getDirectory("virtual");
ASSERT_TRUE(dir);
EXPECT_EQ("virtual", (*dir)->getName());
}
// getFile() returns non-NULL if a real file exists at the given path.
TEST_F(FileManagerTest, getFileReturnsValidFileEntryForExistingRealFile) {
// Inject fake files into the file system.
auto statCache = llvm::make_unique<FakeStatCache>();
statCache->InjectDirectory("/tmp", 42);
statCache->InjectFile("/tmp/test", 43);
#ifdef _WIN32
const char *DirName = "C:.";
const char *FileName = "C:test";
statCache->InjectDirectory(DirName, 44);
statCache->InjectFile(FileName, 45);
#endif
manager.setStatCache(std::move(statCache));
auto file = manager.getFile("/tmp/test");
ASSERT_TRUE(file);
ASSERT_TRUE((*file)->isValid());
EXPECT_EQ("/tmp/test", (*file)->getName());
const DirectoryEntry *dir = (*file)->getDir();
ASSERT_TRUE(dir != nullptr);
EXPECT_EQ("/tmp", dir->getName());
#ifdef _WIN32
file = manager.getFile(FileName);
ASSERT_TRUE(file);
dir = (*file)->getDir();
ASSERT_TRUE(dir != NULL);
EXPECT_EQ(DirName, dir->getName());
#endif
}
// getFile() returns non-NULL if a virtual file exists at the given path.
TEST_F(FileManagerTest, getFileReturnsValidFileEntryForExistingVirtualFile) {
// Fake an empty real file system.
manager.setStatCache(llvm::make_unique<FakeStatCache>());
manager.getVirtualFile("virtual/dir/bar.h", 100, 0);
auto file = manager.getFile("virtual/dir/bar.h");
ASSERT_TRUE(file);
ASSERT_TRUE((*file)->isValid());
EXPECT_EQ("virtual/dir/bar.h", (*file)->getName());
const DirectoryEntry *dir = (*file)->getDir();
ASSERT_TRUE(dir != nullptr);
EXPECT_EQ("virtual/dir", dir->getName());
}
// getFile() returns different FileEntries for different paths when
// there's no aliasing.
TEST_F(FileManagerTest, getFileReturnsDifferentFileEntriesForDifferentFiles) {
// Inject two fake files into the file system. Different inodes
// mean the files are not symlinked together.
auto statCache = llvm::make_unique<FakeStatCache>();
statCache->InjectDirectory(".", 41);
statCache->InjectFile("foo.cpp", 42);
statCache->InjectFile("bar.cpp", 43);
manager.setStatCache(std::move(statCache));
auto fileFoo = manager.getFile("foo.cpp");
auto fileBar = manager.getFile("bar.cpp");
ASSERT_TRUE(fileFoo);
ASSERT_TRUE((*fileFoo)->isValid());
ASSERT_TRUE(fileBar);
ASSERT_TRUE((*fileBar)->isValid());
EXPECT_NE(*fileFoo, *fileBar);
}
// getFile() returns an error if neither a real file nor a virtual file
// exists at the given path.
TEST_F(FileManagerTest, getFileReturnsErrorForNonexistentFile) {
// Inject a fake foo.cpp into the file system.
auto statCache = llvm::make_unique<FakeStatCache>();
statCache->InjectDirectory(".", 41);
statCache->InjectFile("foo.cpp", 42);
statCache->InjectDirectory("MyDirectory", 49);
manager.setStatCache(std::move(statCache));
// Create a virtual bar.cpp file.
manager.getVirtualFile("bar.cpp", 200, 0);
auto file = manager.getFile("xyz.txt");
ASSERT_FALSE(file);
ASSERT_EQ(file.getError(), std::errc::no_such_file_or_directory);
auto readingDirAsFile = manager.getFile("MyDirectory");
ASSERT_FALSE(readingDirAsFile);
ASSERT_EQ(readingDirAsFile.getError(), std::errc::is_a_directory);
auto readingFileAsDir = manager.getDirectory("foo.cpp");
ASSERT_FALSE(readingFileAsDir);
ASSERT_EQ(readingFileAsDir.getError(), std::errc::not_a_directory);
}
// The following tests apply to Unix-like system only.
#ifndef _WIN32
// getFile() returns the same FileEntry for real files that are aliases.
TEST_F(FileManagerTest, getFileReturnsSameFileEntryForAliasedRealFiles) {
// Inject two real files with the same inode.
auto statCache = llvm::make_unique<FakeStatCache>();
statCache->InjectDirectory("abc", 41);
statCache->InjectFile("abc/foo.cpp", 42);
statCache->InjectFile("abc/bar.cpp", 42);
manager.setStatCache(std::move(statCache));
auto f1 = manager.getFile("abc/foo.cpp");
auto f2 = manager.getFile("abc/bar.cpp");
EXPECT_EQ(f1 ? *f1 : nullptr,
f2 ? *f2 : nullptr);
}
// getFile() returns the same FileEntry for virtual files that have
// corresponding real files that are aliases.
TEST_F(FileManagerTest, getFileReturnsSameFileEntryForAliasedVirtualFiles) {
// Inject two real files with the same inode.
auto statCache = llvm::make_unique<FakeStatCache>();
statCache->InjectDirectory("abc", 41);
statCache->InjectFile("abc/foo.cpp", 42);
statCache->InjectFile("abc/bar.cpp", 42);
manager.setStatCache(std::move(statCache));
ASSERT_TRUE(manager.getVirtualFile("abc/foo.cpp", 100, 0)->isValid());
ASSERT_TRUE(manager.getVirtualFile("abc/bar.cpp", 200, 0)->isValid());
auto f1 = manager.getFile("abc/foo.cpp");
auto f2 = manager.getFile("abc/bar.cpp");
EXPECT_EQ(f1 ? *f1 : nullptr,
f2 ? *f2 : nullptr);
}
// getFile() Should return the same entry as getVirtualFile if the file actually
// is a virtual file, even if the name is not exactly the same (but is after
// normalisation done by the file system, like on Windows). This can be checked
// here by checking the size.
TEST_F(FileManagerTest, getVirtualFileWithDifferentName) {
// Inject fake files into the file system.
auto statCache = llvm::make_unique<FakeStatCache>();
statCache->InjectDirectory("c:\\tmp", 42);
statCache->InjectFile("c:\\tmp\\test", 43);
manager.setStatCache(std::move(statCache));
// Inject the virtual file:
const FileEntry *file1 = manager.getVirtualFile("c:\\tmp\\test", 123, 1);
ASSERT_TRUE(file1 != nullptr);
ASSERT_TRUE(file1->isValid());
EXPECT_EQ(43U, file1->getUniqueID().getFile());
EXPECT_EQ(123, file1->getSize());
// Lookup the virtual file with a different name:
auto file2 = manager.getFile("c:/tmp/test", 100, 1);
ASSERT_TRUE(file2);
ASSERT_TRUE((*file2)->isValid());
// Check that it's the same UFE:
EXPECT_EQ(file1, *file2);
EXPECT_EQ(43U, (*file2)->getUniqueID().getFile());
// Check that the contents of the UFE are not overwritten by the entry in the
// filesystem:
EXPECT_EQ(123, (*file2)->getSize());
}
#endif // !_WIN32
TEST_F(FileManagerTest, makeAbsoluteUsesVFS) {
SmallString<64> CustomWorkingDir;
#ifdef _WIN32
CustomWorkingDir = "C:";
#else
CustomWorkingDir = "/";
#endif
llvm::sys::path::append(CustomWorkingDir, "some", "weird", "path");
auto FS = IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem>(
new llvm::vfs::InMemoryFileSystem);
// setCurrentworkingdirectory must finish without error.
ASSERT_TRUE(!FS->setCurrentWorkingDirectory(CustomWorkingDir));
FileSystemOptions Opts;
FileManager Manager(Opts, FS);
SmallString<64> Path("a/foo.cpp");
SmallString<64> ExpectedResult(CustomWorkingDir);
llvm::sys::path::append(ExpectedResult, Path);
ASSERT_TRUE(Manager.makeAbsolutePath(Path));
EXPECT_EQ(Path, ExpectedResult);
}
// getVirtualFile should always fill the real path.
TEST_F(FileManagerTest, getVirtualFileFillsRealPathName) {
SmallString<64> CustomWorkingDir;
#ifdef _WIN32
CustomWorkingDir = "C:/";
#else
CustomWorkingDir = "/";
#endif
auto FS = IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem>(
new llvm::vfs::InMemoryFileSystem);
// setCurrentworkingdirectory must finish without error.
ASSERT_TRUE(!FS->setCurrentWorkingDirectory(CustomWorkingDir));
FileSystemOptions Opts;
FileManager Manager(Opts, FS);
// Inject fake files into the file system.
auto statCache = llvm::make_unique<FakeStatCache>();
statCache->InjectDirectory("/tmp", 42);
statCache->InjectFile("/tmp/test", 43);
Manager.setStatCache(std::move(statCache));
// Check for real path.
const FileEntry *file = Manager.getVirtualFile("/tmp/test", 123, 1);
ASSERT_TRUE(file != nullptr);
ASSERT_TRUE(file->isValid());
SmallString<64> ExpectedResult = CustomWorkingDir;
llvm::sys::path::append(ExpectedResult, "tmp", "test");
EXPECT_EQ(file->tryGetRealPathName(), ExpectedResult);
}
TEST_F(FileManagerTest, getFileDontOpenRealPath) {
SmallString<64> CustomWorkingDir;
#ifdef _WIN32
CustomWorkingDir = "C:/";
#else
CustomWorkingDir = "/";
#endif
auto FS = IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem>(
new llvm::vfs::InMemoryFileSystem);
// setCurrentworkingdirectory must finish without error.
ASSERT_TRUE(!FS->setCurrentWorkingDirectory(CustomWorkingDir));
FileSystemOptions Opts;
FileManager Manager(Opts, FS);
// Inject fake files into the file system.
auto statCache = llvm::make_unique<FakeStatCache>();
statCache->InjectDirectory("/tmp", 42);
statCache->InjectFile("/tmp/test", 43);
Manager.setStatCache(std::move(statCache));
// Check for real path.
auto file = Manager.getFile("/tmp/test", /*OpenFile=*/false);
ASSERT_TRUE(file);
ASSERT_TRUE((*file)->isValid());
SmallString<64> ExpectedResult = CustomWorkingDir;
llvm::sys::path::append(ExpectedResult, "tmp", "test");
EXPECT_EQ((*file)->tryGetRealPathName(), ExpectedResult);
}
} // anonymous namespace
<|endoftext|>
|
<commit_before>#include "index/MeshStream.hpp"
#include <cstdint>
using namespace utymap::index;
using namespace utymap::math;
namespace {
const float Precision = 1E7;
template<typename T>
T read(std::istream &stream) {
T data;
stream.read(reinterpret_cast<char *>(&data), sizeof(data));
return data;
}
/// Restores double stored as signed 4-bytes integer.
template<>
double read<double>(std::istream &stream) {
std::int32_t data;
stream.read(reinterpret_cast<char *>(&data), sizeof(data));
return data / Precision;
}
template<typename T>
void write(std::ostream &stream, const T &data) {
stream.write(reinterpret_cast<const char *>(&data), sizeof(data));
}
/// Stores double as signed 4-bytes integer.
///
template<>
void write<double>(std::ostream &stream, const double &data) {
auto simplified = static_cast<std::int32_t>(data * Precision);
stream.write(reinterpret_cast<const char *>(&simplified), sizeof(simplified));
}
template<typename T>
std::ostream &operator<<(std::ostream &stream, const std::vector<T> &data) {
auto size = static_cast<std::uint32_t>(data.size());
stream.write(reinterpret_cast<const char *>(&size), sizeof(size));
for (const auto &item : data)
write<T>(stream, item);
return stream;
}
template<typename T>
std::istream &operator>>(std::istream &stream, std::vector<T> &data) {
std::uint32_t size = 0;
stream.read(reinterpret_cast<char *>(&size), sizeof(size));
data.resize(size);
for (size_t i = 0; i < size; ++i)
data[i] = read<T>(stream);
return stream;
}
std::ostream &operator<<(std::ostream &stream, const Mesh &mesh) {
return stream << mesh.name.c_str() << '\0' << mesh.vertices << mesh.triangles
<< mesh.colors << mesh.uvs << mesh.uvMap;
}
std::istream &operator>>(std::istream &stream, Mesh &mesh) {
std::getline(stream, mesh.name, '\0');
return stream >> mesh.vertices >> mesh.triangles
>> mesh.colors >> mesh.uvs >> mesh.uvMap;
}
}
Mesh MeshStream::read(std::istream &stream) {
Mesh mesh("");
stream >> mesh;
return std::move(mesh);
}
void MeshStream::write(std::ostream &stream, const Mesh &mesh) {
stream << mesh;
}
<commit_msg>core: fix elevation overflow problem in mesh caching<commit_after>#include "index/MeshStream.hpp"
#include <cstdint>
using namespace utymap::index;
using namespace utymap::math;
namespace {
const double Precision = 1E7;
template<typename T>
void initData(std::istream &stream, std::vector<T> &data) {
std::uint32_t size = 0;
stream.read(reinterpret_cast<char *>(&size), sizeof(size));
data.resize(size);
}
template<typename T>
void initData(std::ostream &stream, const std::vector<T> &data) {
auto size = static_cast<std::uint32_t>(data.size());
stream.write(reinterpret_cast<const char *>(&size), sizeof(size));
}
template<typename T>
T read(std::istream &stream) {
T data;
stream.read(reinterpret_cast<char *>(&data), sizeof(data));
return data;
}
/// Restores double stored as signed 4-bytes integer.
template<>
double read<double>(std::istream &stream) {
std::int32_t data;
stream.read(reinterpret_cast<char *>(&data), sizeof(data));
return data / Precision;
}
template<typename T>
void write(std::ostream &stream, const T &data) {
stream.write(reinterpret_cast<const char *>(&data), sizeof(data));
}
/// Stores double as signed 4-bytes integer.
///
template<>
void write<double>(std::ostream &stream, const double &data) {
auto simplified = static_cast<std::int32_t>(data * Precision);
stream.write(reinterpret_cast<const char *>(&simplified), sizeof(simplified));
}
template<typename T>
std::ostream &operator<<(std::ostream &stream, const std::vector<T> &data) {
initData(stream, data);
for (const auto &item : data)
write<T>(stream, item);
return stream;
}
template<typename T>
std::istream &operator>>(std::istream &stream, std::vector<T> &data) {
initData(stream, data);
for (size_t i = 0; i < data.size(); ++i)
data[i] = read<T>(stream);
return stream;
}
void readVertices(std::istream &stream, std::vector<double> &data) {
initData(stream, data);
for (size_t i = 0; i < data.size(); ++i)
// NOTE store elevation as float, not as packed double
data[i] = (i + 1) % 3 == 0 ? read<float>(stream) : read<double>(stream);
}
void writeVertices(std::ostream &stream, const std::vector<double> &data) {
initData(stream, data);
for (size_t i = 0; i < data.size(); ++i) {
if ((i + 1) % 3 == 0)
write<float>(stream, static_cast<float>(data[i]));
else
write<double>(stream, data[i]);
}
}
std::ostream &operator<<(std::ostream &stream, const Mesh &mesh) {
stream << mesh.name.c_str() << '\0';
writeVertices(stream, mesh.vertices);
return stream << mesh.triangles << mesh.colors << mesh.uvs << mesh.uvMap;
}
std::istream &operator>>(std::istream &stream, Mesh &mesh) {
std::getline(stream, mesh.name, '\0');
readVertices(stream, mesh.vertices);
return stream >> mesh.triangles >> mesh.colors >> mesh.uvs >> mesh.uvMap;
}
}
Mesh MeshStream::read(std::istream &stream) {
Mesh mesh("");
stream >> mesh;
return std::move(mesh);
}
void MeshStream::write(std::ostream &stream, const Mesh &mesh) {
stream << mesh;
}
<|endoftext|>
|
<commit_before>/*************** <auto-copyright.pl BEGIN do not edit this line> **************
*
* VR Juggler is (C) Copyright 1998-2003 by Iowa State University
*
* Original Authors:
* Allen Bierbaum, Christopher Just,
* Patrick Hartling, Kevin Meinert,
* Carolina Cruz-Neira, Albert Baker
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
* -----------------------------------------------------------------
* File: $RCSfile$
* Date modified: $Date$
* Version: $Revision$
* -----------------------------------------------------------------
*
*************** <auto-copyright.pl END do not edit this line> ***************/
#include <gadget/Devices/DriverConfig.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vpr/Util/Debug.h>
#include <jccl/Config/ConfigElement.h>
#include <gadget/Type/DeviceConstructor.h>
#include <gadget/Util/Debug.h>
#include <drivers/Microsoft/DirectXJoystick/DirectXJoystick.h>
extern "C"
{
GADGET_DRIVER_EXPORT(void) initDevice(gadget::InputManager* inputMgr)
{
new gadget::DeviceConstructor<gadget::DirectXJoystick>(inputMgr);
}
}
namespace gadget
{
/** Constructor. */
DirectXJoystick::DirectXJoystick()
: mActive(false)
{
}
/**
* Destructor.
*
* @pre None.
* @post Shared memory is released.
*/
DirectXJoystick::~DirectXJoystick()
{
}
std::string DirectXJoystick::getElementType()
{
return "directx_joystick";
}
/**
* config
*/
bool DirectXJoystick::config(jccl::ConfigElementPtr e)
{
if(! (Input::config(e) && Digital::config(e) && Analog::config(e)))
{
return false;
}
mJsLabel = e->getName();
unsigned num_axis_buttons = e->getNum("axis_buttons");
for ( unsigned i = 0; i < num_axis_buttons; ++i )
{
unsigned idx = e->getProperty<int>("axis_buttons", i);
mAxisButtonIndices.push_back(idx);
}
// XXX: This doesn't make any sense. PH 8/19/2004
if( getMin() == 0 && getMax() == 0 || getMin() >= getMax() )
{
setMin(-100.0f);
setMax(100.0f);
}
return true;
}
bool DirectXJoystick::startSampling()
{
vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_STATUS_LVL)
<< "Opening Win Joystick driver " << std::endl << vprDEBUG_FLUSH;
mActive = (mInputDrv.init() == 0);
if ( ! mActive )
{
vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CRITICAL_LVL)
<< "ERROR: Failed to open Win Joystick." << std::endl
<< vprDEBUG_FLUSH;
return false;
}
// FIXME: hardcoded number of axes and buttons
int version = 0;
mNumAxes = 9; // Analog = 8 from DIJOYSTATE
mNumButtons = 10; // Digital = 32 from DIJOYSTATE
// Output joystick description
vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_LVL)
<< " joystick label: " << mJsLabel << std::endl
<< " joystick name: " << mInputDrv.getProductName() << std::endl
<< " axes: " << mNumAxes << std::endl
<< " buttons: " << mNumButtons << std::endl
<< " driver ver: " << version << std::endl
<< " axis buttons: ";
for(unsigned i=0;i<mAxisButtonIndices.size(); ++i)
{
vprDEBUG_CONTnl(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_LVL)
<< mAxisButtonIndices[i] << " ";
}
vprDEBUG_CONTnl(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_LVL)
<< std::endl << vprDEBUG_FLUSH;
// Allocate initial device data
// - By default this will clear them out
mCurAxes.resize(mNumAxes);
mCurAxesRanges.resize(mNumAxes, axis_range_t(-100.0f, 100.0f)); // Initialize ranges to 0,255
mCurButtons.resize(mNumButtons + mAxisButtonIndices.size());
// Setup axis as button stuff
mAxisToButtonIndexLookup.clear();
mAxisToButtonIndexLookup.resize(mNumAxes, -1); // Default to -1, meaning no axis button
for(unsigned i=0;i<mAxisButtonIndices.size(); ++i) // For each configured axis index
{
unsigned virtual_btn_index = (mNumButtons+i); // Index of the virtual button from the axis
vprASSERT(virtual_btn_index < mCurButtons.size() && "Virtual button index out of range");
unsigned axis_index = mAxisButtonIndices[i]; // Index of the axis we are mapping
mAxisToButtonIndexLookup[axis_index] = int(virtual_btn_index); // Setup the mapping
}
return true;
}
/**
* Stops sampling.
* Drop connection to joystick and clear everything.
*/
bool DirectXJoystick::stopSampling()
{
if ( mActive )
{
mInputDrv.close(); // Close the joystick device
mActive = false;
}
return true;
}
/**
* Updates to the sampled data.
*
* @pre None.
* @post Most recent value is copied over to temp area.
*/
void DirectXJoystick::updateData()
{
mInputDrv.poll();
DIJOYSTATE mJsData = mInputDrv.getData();
//FIXME: if & only if there is events happen, do setTime
// for buttons, do update
for ( unsigned int i = 0; i < mCurButtons.size(); ++i )
{
mCurButtons[i].setDigital(mJsData.rgbButtons[i]);
if( mCurButtons[i].getDigital() != 0)
{
mCurButtons[i].setTime();
}
}
// for axes, do update
float norm_value;
normalizeMinToMax(mJsData.lX, norm_value);
mCurAxes[0] = norm_value;
normalizeMinToMax(mJsData.lY, norm_value);
mCurAxes[1] = norm_value;
normalizeMinToMax(mJsData.lZ, norm_value);
mCurAxes[2] = norm_value;
normalizeMinToMax(mJsData.lRx, norm_value); // x rotation
mCurAxes[3] = norm_value;
normalizeMinToMax(mJsData.lRy, norm_value); // y rotation
mCurAxes[4] = norm_value;
normalizeMinToMax(mJsData.lRz, norm_value); // z rotation
mCurAxes[5] = norm_value;
normalizeMinToMax(mJsData.rglSlider[0], norm_value); // u-axis
mCurAxes[6] = norm_value;
normalizeMinToMax(mJsData.rglSlider[1], norm_value); // v-axis
mCurAxes[7] = norm_value;
mCurAxes[8] = (float(mJsData.rgdwPOV[0])); //hat: -1, 0, 9,000, 18,000, or 27,000.
// use axes as button, only first 3 are tested.
for ( int axis_number = 0; axis_number < mNumAxes; ++axis_number )
{
// FIXME: don't know when it is changed
mCurAxes[axis_number].setTime();
// Check for axis buttons
// - If we have a mapping
// - If axis is gt 0.5, then btn is down
if ( axis_number < 3 )
{
float norm_value(0.0f); // mCurAxes[axis_number].getAnalog();
if ( mAxisToButtonIndexLookup[axis_number] != -1 ) // If we map to a virtual button
{
unsigned vir_btn_index = mAxisToButtonIndexLookup[axis_number];
vprASSERT(vir_btn_index < mCurButtons.size() && "Virtual button index out of range");
mCurButtons[vir_btn_index] = ((norm_value > 0.5f) ? 1 : 0);
mCurButtons[vir_btn_index].setTime();
}
}
}
addDigitalSample(mCurButtons);
swapDigitalBuffers();
addAnalogSample(mCurAxes);
swapAnalogBuffers();
} // end of Update
} // End of gadget namespace
<commit_msg>Silenced a compiler warning.<commit_after>/*************** <auto-copyright.pl BEGIN do not edit this line> **************
*
* VR Juggler is (C) Copyright 1998-2003 by Iowa State University
*
* Original Authors:
* Allen Bierbaum, Christopher Just,
* Patrick Hartling, Kevin Meinert,
* Carolina Cruz-Neira, Albert Baker
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
* -----------------------------------------------------------------
* File: $RCSfile$
* Date modified: $Date$
* Version: $Revision$
* -----------------------------------------------------------------
*
*************** <auto-copyright.pl END do not edit this line> ***************/
#include <gadget/Devices/DriverConfig.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vpr/Util/Debug.h>
#include <jccl/Config/ConfigElement.h>
#include <gadget/Type/DeviceConstructor.h>
#include <gadget/Util/Debug.h>
#include <drivers/Microsoft/DirectXJoystick/DirectXJoystick.h>
extern "C"
{
GADGET_DRIVER_EXPORT(void) initDevice(gadget::InputManager* inputMgr)
{
new gadget::DeviceConstructor<gadget::DirectXJoystick>(inputMgr);
}
}
namespace gadget
{
/** Constructor. */
DirectXJoystick::DirectXJoystick()
: mActive(false)
{
}
/**
* Destructor.
*
* @pre None.
* @post Shared memory is released.
*/
DirectXJoystick::~DirectXJoystick()
{
}
std::string DirectXJoystick::getElementType()
{
return "directx_joystick";
}
/**
* config
*/
bool DirectXJoystick::config(jccl::ConfigElementPtr e)
{
if(! (Input::config(e) && Digital::config(e) && Analog::config(e)))
{
return false;
}
mJsLabel = e->getName();
unsigned num_axis_buttons = e->getNum("axis_buttons");
for ( unsigned i = 0; i < num_axis_buttons; ++i )
{
unsigned idx = e->getProperty<int>("axis_buttons", i);
mAxisButtonIndices.push_back(idx);
}
// XXX: This doesn't make any sense. PH 8/19/2004
if( getMin() == 0 && getMax() == 0 || getMin() >= getMax() )
{
setMin(-100.0f);
setMax(100.0f);
}
return true;
}
bool DirectXJoystick::startSampling()
{
vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_STATUS_LVL)
<< "Opening Win Joystick driver " << std::endl << vprDEBUG_FLUSH;
mActive = (mInputDrv.init() == 0);
if ( ! mActive )
{
vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CRITICAL_LVL)
<< "ERROR: Failed to open Win Joystick." << std::endl
<< vprDEBUG_FLUSH;
return false;
}
// FIXME: hardcoded number of axes and buttons
int version = 0;
mNumAxes = 9; // Analog = 8 from DIJOYSTATE
mNumButtons = 10; // Digital = 32 from DIJOYSTATE
// Output joystick description
vprDEBUG(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_LVL)
<< " joystick label: " << mJsLabel << std::endl
<< " joystick name: " << mInputDrv.getProductName() << std::endl
<< " axes: " << mNumAxes << std::endl
<< " buttons: " << mNumButtons << std::endl
<< " driver ver: " << version << std::endl
<< " axis buttons: ";
for(unsigned i=0;i<mAxisButtonIndices.size(); ++i)
{
vprDEBUG_CONTnl(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_LVL)
<< mAxisButtonIndices[i] << " ";
}
vprDEBUG_CONTnl(gadgetDBG_INPUT_MGR, vprDBG_CONFIG_LVL)
<< std::endl << vprDEBUG_FLUSH;
// Allocate initial device data
// - By default this will clear them out
mCurAxes.resize(mNumAxes);
mCurAxesRanges.resize(mNumAxes, axis_range_t(-100.0f, 100.0f)); // Initialize ranges to 0,255
mCurButtons.resize(mNumButtons + mAxisButtonIndices.size());
// Setup axis as button stuff
mAxisToButtonIndexLookup.clear();
mAxisToButtonIndexLookup.resize(mNumAxes, -1); // Default to -1, meaning no axis button
for(unsigned i=0;i<mAxisButtonIndices.size(); ++i) // For each configured axis index
{
unsigned virtual_btn_index = (mNumButtons+i); // Index of the virtual button from the axis
vprASSERT(virtual_btn_index < mCurButtons.size() && "Virtual button index out of range");
unsigned axis_index = mAxisButtonIndices[i]; // Index of the axis we are mapping
mAxisToButtonIndexLookup[axis_index] = int(virtual_btn_index); // Setup the mapping
}
return true;
}
/**
* Stops sampling.
* Drop connection to joystick and clear everything.
*/
bool DirectXJoystick::stopSampling()
{
if ( mActive )
{
mInputDrv.close(); // Close the joystick device
mActive = false;
}
return true;
}
/**
* Updates to the sampled data.
*
* @pre None.
* @post Most recent value is copied over to temp area.
*/
void DirectXJoystick::updateData()
{
mInputDrv.poll();
DIJOYSTATE mJsData = mInputDrv.getData();
//FIXME: if & only if there is events happen, do setTime
// for buttons, do update
for ( unsigned int i = 0; i < mCurButtons.size(); ++i )
{
mCurButtons[i].setDigital(mJsData.rgbButtons[i]);
if( mCurButtons[i].getDigital() != 0)
{
mCurButtons[i].setTime();
}
}
// for axes, do update
float norm_value;
normalizeMinToMax(mJsData.lX, norm_value);
mCurAxes[0] = norm_value;
normalizeMinToMax(mJsData.lY, norm_value);
mCurAxes[1] = norm_value;
normalizeMinToMax(mJsData.lZ, norm_value);
mCurAxes[2] = norm_value;
normalizeMinToMax(mJsData.lRx, norm_value); // x rotation
mCurAxes[3] = norm_value;
normalizeMinToMax(mJsData.lRy, norm_value); // y rotation
mCurAxes[4] = norm_value;
normalizeMinToMax(mJsData.lRz, norm_value); // z rotation
mCurAxes[5] = norm_value;
normalizeMinToMax(mJsData.rglSlider[0], norm_value); // u-axis
mCurAxes[6] = norm_value;
normalizeMinToMax(mJsData.rglSlider[1], norm_value); // v-axis
mCurAxes[7] = norm_value;
mCurAxes[8] = (float(mJsData.rgdwPOV[0])); //hat: -1, 0, 9,000, 18,000, or 27,000.
// use axes as button, only first 3 are tested.
for ( unsigned int axis_number = 0; axis_number < mNumAxes; ++axis_number )
{
// FIXME: don't know when it is changed
mCurAxes[axis_number].setTime();
// Check for axis buttons
// - If we have a mapping
// - If axis is gt 0.5, then btn is down
if ( axis_number < 3 )
{
float norm_value(0.0f); // mCurAxes[axis_number].getAnalog();
if ( mAxisToButtonIndexLookup[axis_number] != -1 ) // If we map to a virtual button
{
unsigned vir_btn_index = mAxisToButtonIndexLookup[axis_number];
vprASSERT(vir_btn_index < mCurButtons.size() && "Virtual button index out of range");
mCurButtons[vir_btn_index] = ((norm_value > 0.5f) ? 1 : 0);
mCurButtons[vir_btn_index].setTime();
}
}
}
addDigitalSample(mCurButtons);
swapDigitalBuffers();
addAnalogSample(mCurAxes);
swapAnalogBuffers();
} // end of Update
} // End of gadget namespace
<|endoftext|>
|
<commit_before>/** \brief Utility for deleting partial or entire MARC records based on an input list.
* \author Mario Trojan (mario.trojan@uni-tuebingen.de)
*
* \copyright 2018 Universitätsbibliothek Tübingen. 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/>.
*/
#include <iostream>
#include <map>
#include <memory>
#include <cstdlib>
#include "Downloader.h"
#include "File.h"
#include "FileUtil.h"
#include "MARC.h"
#include "StringUtil.h"
#include "util.h"
namespace {
[[noreturn]] void Usage() {
std::cerr << "Usage: " << ::progname
<< " [--input-format=(marc-21|marc-xml)] [--output-format=(marc-21|marc-xml)] input_marc21 output_marc21\n";
std::exit(EXIT_FAILURE);
}
// TODO: add archivportal-d (BEACON url not found)
// BEACON file can only be used if entry elemtents are plain GND numbers.
const std::map<std::string, std::string> beacon_id_to_url_map({ { "kalliope", "http://kalliope.staatsbibliothek-berlin.de/beacon/beacon.txt" } });
std::map<std::string, std::set<std::string>> PopulateGNDToBeaconIdsMap() {
std::map<std::string, std::set<std::string>> gnd_to_beacon_ids_map;
FileUtil::AutoTempDirectory temp_dir;
for (const auto &beacon_id_and_url : beacon_id_to_url_map) {
const std::string beacon_id(beacon_id_and_url.first);
const std::string beacon_url(beacon_id_and_url.second);
const std::string beacon_temp_path(temp_dir.getDirectoryPath() + "/" + beacon_id);
LOG_INFO("Downloading/Processing " + beacon_id + " BEACON file from " + beacon_url);
if (not Download(beacon_url, beacon_temp_path, Downloader::DEFAULT_TIME_LIMIT))
LOG_ERROR("BEACON file could not be downloaded: " + beacon_url);
File beacon_file(beacon_temp_path, "r");
unsigned beacon_gnd_count(0);
while (not beacon_file.eof()) {
const std::string line(beacon_file.getline());
if (not StringUtil::StartsWith(line, "#")) {
const std::string gnd(line);
++beacon_gnd_count;
auto gnd_to_beacon_ids_iter(gnd_to_beacon_ids_map.find(gnd));
if (gnd_to_beacon_ids_iter == gnd_to_beacon_ids_map.end())
gnd_to_beacon_ids_map.emplace(gnd, std::initializer_list<std::string>{ beacon_id });
else
gnd_to_beacon_ids_iter->second.emplace(beacon_id);
}
}
LOG_INFO("Found " + std::to_string(beacon_gnd_count) + " GND numbers in " + beacon_id + " BEACON file.");
}
return gnd_to_beacon_ids_map;
}
void ProcessRecords(const std::map<std::string, std::set<std::string>> &gnd_to_beacon_ids_map,
MARC::Reader * const marc_reader, MARC::Writer * const marc_writer)
{
unsigned beacon_reference_count(0);
while (MARC::Record record = marc_reader->read()) {
std::string gnd;
if (MARC::GetGNDCode(record, &gnd)) {
const auto gnd_to_beacon_ids(gnd_to_beacon_ids_map.find(gnd));
if (gnd_to_beacon_ids != gnd_to_beacon_ids_map.end()) {
MARC::Record::Field beacon_field("BEA");
beacon_field.appendSubfield('a', "1");
for (const std::string &beacon_id : gnd_to_beacon_ids->second) {
beacon_field.appendSubfield('b', beacon_id);
++beacon_reference_count;
}
record.insertField(beacon_field);
}
}
marc_writer->write(record);
}
LOG_INFO("Added " + std::to_string(beacon_reference_count) + " BEACON references to MARC records!");
}
} // unnamed namespace
int Main(int argc, char *argv[]) {
::progname = argv[0];
if (argc < 3)
Usage();
const auto reader_type(MARC::GetOptionalReaderType(&argc, &argv, 1));
const auto writer_type(MARC::GetOptionalWriterType(&argc, &argv, 1));
if (argc != 3)
Usage();
const auto marc_reader(MARC::Reader::Factory(argv[1], reader_type));
const auto marc_writer(MARC::Writer::Factory(argv[2], writer_type));
std::map<std::string, std::set<std::string>> gnd_to_beacon_ids_map(PopulateGNDToBeaconIdsMap());
ProcessRecords(gnd_to_beacon_ids_map, marc_reader.get(), marc_writer.get());
return EXIT_SUCCESS;
}
<commit_msg>removed add_beacon_references input & output format override flags<commit_after>/** \brief Utility for adding external BEACON references to MARC data.
* \author Mario Trojan (mario.trojan@uni-tuebingen.de)
*
* \copyright 2018 Universitätsbibliothek Tübingen. 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/>.
*/
#include <iostream>
#include <map>
#include <memory>
#include <cstdlib>
#include "Downloader.h"
#include "File.h"
#include "FileUtil.h"
#include "MARC.h"
#include "StringUtil.h"
#include "util.h"
namespace {
[[noreturn]] void Usage() {
std::cerr << "Usage: " << ::progname
<< " input_marc output_marc\n";
std::exit(EXIT_FAILURE);
}
// TODO: add archivportal-d (BEACON url not found)
// BEACON file can only be used if entry elemtents are plain GND numbers.
const std::map<std::string, std::string> beacon_id_to_url_map({ { "kalliope", "http://kalliope.staatsbibliothek-berlin.de/beacon/beacon.txt" } });
std::map<std::string, std::set<std::string>> PopulateGNDToBeaconIdsMap() {
std::map<std::string, std::set<std::string>> gnd_to_beacon_ids_map;
FileUtil::AutoTempDirectory temp_dir;
for (const auto &beacon_id_and_url : beacon_id_to_url_map) {
const std::string beacon_id(beacon_id_and_url.first);
const std::string beacon_url(beacon_id_and_url.second);
const std::string beacon_temp_path(temp_dir.getDirectoryPath() + "/" + beacon_id);
LOG_INFO("Downloading/Processing " + beacon_id + " BEACON file from " + beacon_url);
if (not Download(beacon_url, beacon_temp_path, Downloader::DEFAULT_TIME_LIMIT))
LOG_ERROR("BEACON file could not be downloaded: " + beacon_url);
File beacon_file(beacon_temp_path, "r");
unsigned beacon_gnd_count(0);
while (not beacon_file.eof()) {
const std::string line(beacon_file.getline());
if (not StringUtil::StartsWith(line, "#")) {
const std::string gnd(line);
++beacon_gnd_count;
auto gnd_to_beacon_ids_iter(gnd_to_beacon_ids_map.find(gnd));
if (gnd_to_beacon_ids_iter == gnd_to_beacon_ids_map.end())
gnd_to_beacon_ids_map.emplace(gnd, std::initializer_list<std::string>{ beacon_id });
else
gnd_to_beacon_ids_iter->second.emplace(beacon_id);
}
}
LOG_INFO("Found " + std::to_string(beacon_gnd_count) + " GND numbers in " + beacon_id + " BEACON file.");
}
return gnd_to_beacon_ids_map;
}
void ProcessRecords(const std::map<std::string, std::set<std::string>> &gnd_to_beacon_ids_map,
MARC::Reader * const marc_reader, MARC::Writer * const marc_writer)
{
unsigned beacon_reference_count(0);
while (MARC::Record record = marc_reader->read()) {
std::string gnd;
if (MARC::GetGNDCode(record, &gnd)) {
const auto gnd_to_beacon_ids(gnd_to_beacon_ids_map.find(gnd));
if (gnd_to_beacon_ids != gnd_to_beacon_ids_map.end()) {
MARC::Record::Field beacon_field("BEA");
beacon_field.appendSubfield('a', "1");
for (const std::string &beacon_id : gnd_to_beacon_ids->second) {
beacon_field.appendSubfield('b', beacon_id);
++beacon_reference_count;
}
record.insertField(beacon_field);
}
}
marc_writer->write(record);
}
LOG_INFO("Added " + std::to_string(beacon_reference_count) + " BEACON references to MARC records!");
}
} // unnamed namespace
int Main(int argc, char *argv[]) {
::progname = argv[0];
if (argc != 3)
Usage();
const auto marc_reader(MARC::Reader::Factory(argv[1]));
const auto marc_writer(MARC::Writer::Factory(argv[2]));
std::map<std::string, std::set<std::string>> gnd_to_beacon_ids_map(PopulateGNDToBeaconIdsMap());
ProcessRecords(gnd_to_beacon_ids_map, marc_reader.get(), marc_writer.get());
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <vector>
// template <class... Args> reference emplace_back(Args&&... args);
//#include <vector>
//#include <cassert>
//#include "../../../stack_allocator.h"
//#include "min_allocator.h"
//#include "asan_testing.h"
#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
class A
{
int i_;
double d_;
A(const A&);
A& operator=(const A&);
public:
A(int i, double d)
: i_(i), d_(d) {}
A(A&& a)
: i_(a.i_),
d_(a.d_)
{
a.i_ = 0;
a.d_ = 0;
}
A& operator=(A&& a)
{
i_ = a.i_;
d_ = a.d_;
a.i_ = 0;
a.d_ = 0;
return *this;
}
int geti() const {return i_;}
double getd() const {return d_;}
};
#endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES
void main()
{
#ifndef _LIBCPP_HAS_NO_VARIADICS
#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
{
vector<A> c;
A& r1 = c.emplace_back(2, 3.5);
assert(c.size() == 1);
assert(&r1 == &c.back());
assert(c.front().geti() == 2);
assert(c.front().getd() == 3.5);
//assert(is_contiguous_container_asan_correct(c));
A& r2 = c.emplace_back(3, 4.5);
assert(c.size() == 2);
assert(&r2 == &c.back());
assert(c.front().geti() == 2);
assert(c.front().getd() == 3.5);
assert(c.back().geti() == 3);
assert(c.back().getd() == 4.5);
//assert(is_contiguous_container_asan_correct(c));
}
#ifdef LIBCPP_TEST_STACK_ALLOCATOR
{
vector<A, stack_allocator<A, 4> > c;
A& r1 = c.emplace_back(2, 3.5);
assert(c.size() == 1);
assert(&r1 == &c.back());
assert(c.front().geti() == 2);
assert(c.front().getd() == 3.5);
//assert(is_contiguous_container_asan_correct(c));
A& r2 = c.emplace_back(3, 4.5);
assert(c.size() == 2);
assert(&r2 == &c.back());
assert(c.front().geti() == 2);
assert(c.front().getd() == 3.5);
assert(c.back().geti() == 3);
assert(c.back().getd() == 4.5);
//assert(is_contiguous_container_asan_correct(c));
}
#endif
//#if __cplusplus >= 201103L
#ifdef LIBCPP_TEST_MIN_ALLOCATOR
{
vector<A, min_allocator<A>> c;
A& r1 = c.emplace_back(2, 3.5);
assert(c.size() == 1);
assert(&r1 == &c.back());
assert(c.front().geti() == 2);
assert(c.front().getd() == 3.5);
//assert(is_contiguous_container_asan_correct(c));
A& r2 = c.emplace_back(3, 4.5);
assert(c.size() == 2);
assert(&r2 == &c.back());
assert(c.front().geti() == 2);
assert(c.front().getd() == 3.5);
assert(c.back().geti() == 3);
assert(c.back().getd() == 4.5);
//assert(is_contiguous_container_asan_correct(c));
}
#endif
#endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES
#endif // _LIBCPP_HAS_NO_VARIADICS
}
<commit_msg>Vector tests<commit_after>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <vector>
// template <class... Args> reference emplace_back(Args&&... args);
//#include <vector>
//#include <cassert>
//#include "../../../stack_allocator.h"
//#include "min_allocator.h"
//#include "asan_testing.h"
#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
class A
{
int i_;
double d_;
A(const A&);
A& operator=(const A&);
public:
A(int i, double d)
: i_(i), d_(d) {}
A(A&& a) = default;
// : i_(a.i_),
// d_(a.d_)
//{
// a.i_ = 0;
// a.d_ = 0;
//}
A& operator=(A&& a) = default;
//{
// i_ = a.i_;
// d_ = a.d_;
// a.i_ = 0;
// a.d_ = 0;
// return *this;
//}
int geti() const {return i_;}
double getd() const {return d_;}
};
#endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES
void main()
{
#ifndef _LIBCPP_HAS_NO_VARIADICS
#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
{
vector<A> c;
A& r1 = c.emplace_back(2, 3.5);
assert(c.size() == 1);
assert(&r1 == &c.back());
assert(c.front().geti() == 2);
assert(c.front().getd() == 3.5);
//assert(is_contiguous_container_asan_correct(c));
A& r2 = c.emplace_back(3, 4.5);
assert(c.size() == 2);
assert(&r2 == &c.back());
assert(c.front().geti() == 2);
assert(c.front().getd() == 3.5);
assert(c.back().geti() == 3);
assert(c.back().getd() == 4.5);
//assert(is_contiguous_container_asan_correct(c));
}
#ifdef LIBCPP_TEST_STACK_ALLOCATOR
{
vector<A, stack_allocator<A, 4> > c;
A& r1 = c.emplace_back(2, 3.5);
assert(c.size() == 1);
assert(&r1 == &c.back());
assert(c.front().geti() == 2);
assert(c.front().getd() == 3.5);
//assert(is_contiguous_container_asan_correct(c));
A& r2 = c.emplace_back(3, 4.5);
assert(c.size() == 2);
assert(&r2 == &c.back());
assert(c.front().geti() == 2);
assert(c.front().getd() == 3.5);
assert(c.back().geti() == 3);
assert(c.back().getd() == 4.5);
//assert(is_contiguous_container_asan_correct(c));
}
#endif
//#if __cplusplus >= 201103L
#ifdef LIBCPP_TEST_MIN_ALLOCATOR
{
vector<A, min_allocator<A>> c;
A& r1 = c.emplace_back(2, 3.5);
assert(c.size() == 1);
assert(&r1 == &c.back());
assert(c.front().geti() == 2);
assert(c.front().getd() == 3.5);
//assert(is_contiguous_container_asan_correct(c));
A& r2 = c.emplace_back(3, 4.5);
assert(c.size() == 2);
assert(&r2 == &c.back());
assert(c.front().geti() == 2);
assert(c.front().getd() == 3.5);
assert(c.back().geti() == 3);
assert(c.back().getd() == 4.5);
//assert(is_contiguous_container_asan_correct(c));
}
#endif
#endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES
#endif // _LIBCPP_HAS_NO_VARIADICS
}
<|endoftext|>
|
<commit_before><commit_msg>Reduce limit to 2^64-1<commit_after><|endoftext|>
|
<commit_before>/*
* Copyright 2016 Nu-book Inc.
* Copyright 2016 ZXing authors
*
* 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 "MultiFormatReader.h"
#include "BarcodeFormat.h"
#include "DecodeHints.h"
#include "aztec/AZReader.h"
#include "datamatrix/DMReader.h"
#include "maxicode/MCReader.h"
#include "oned/ODReader.h"
#include "pdf417/PDFReader.h"
#include "qrcode/QRReader.h"
#include <memory>
namespace ZXing {
MultiFormatReader::MultiFormatReader(const DecodeHints& hints)
{
bool tryHarder = hints.tryHarder();
auto formats = hints.formats().empty() ? BarcodeFormat::Any : hints.formats();
// Put 1D readers upfront in "normal" mode
if (formats.testFlags(BarcodeFormat::OneDCodes) && !tryHarder)
_readers.emplace_back(new OneD::Reader(hints));
if (formats.testFlag(BarcodeFormat::QRCode))
_readers.emplace_back(new QRCode::Reader(hints));
if (formats.testFlag(BarcodeFormat::DataMatrix))
_readers.emplace_back(new DataMatrix::Reader(hints));
if (formats.testFlag(BarcodeFormat::Aztec))
_readers.emplace_back(new Aztec::Reader(hints));
if (formats.testFlag(BarcodeFormat::PDF417))
_readers.emplace_back(new Pdf417::Reader(hints));
if (formats.testFlag(BarcodeFormat::MaxiCode))
_readers.emplace_back(new MaxiCode::Reader(hints));
// At end in "try harder" mode
if (formats.testFlags(BarcodeFormat::OneDCodes) && tryHarder) {
_readers.emplace_back(new OneD::Reader(hints));
}
}
MultiFormatReader::~MultiFormatReader() = default;
Result
MultiFormatReader::read(const BinaryBitmap& image) const
{
// If we have only one reader in our list, just return whatever that decoded.
// This preserves information (e.g. ChecksumError) instead of just returning 'NotFound'.
if (_readers.size() == 1)
return _readers.front()->decode(image);
for (const auto& reader : _readers) {
Result r = reader->decode(image);
if (r.isValid())
return r;
}
return Result(DecodeStatus::NotFound);
}
Results MultiFormatReader::readMultiple(const BinaryBitmap& image, int maxSymbols) const
{
std::vector<Result> res;
for (const auto& reader : _readers) {
auto r = reader->decode(image, maxSymbols);
maxSymbols -= r.size();
res.insert(res.end(), std::move_iterator(r.begin()), std::move_iterator(r.end()));
if (maxSymbols <= 0)
break;
}
// sort results based on their position on the image
std::sort(res.begin(), res.end(), [](const Result& l, const Result& r) {
auto lp = l.position().topLeft();
auto rp = r.position().topLeft();
return lp.y < rp.y || (lp.y == rp.y && lp.x <= rp.x);
});
return res;
}
} // ZXing
<commit_msg>Fixed comparison bug in MultiFormatReader.cpp<commit_after>/*
* Copyright 2016 Nu-book Inc.
* Copyright 2016 ZXing authors
*
* 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 "MultiFormatReader.h"
#include "BarcodeFormat.h"
#include "DecodeHints.h"
#include "aztec/AZReader.h"
#include "datamatrix/DMReader.h"
#include "maxicode/MCReader.h"
#include "oned/ODReader.h"
#include "pdf417/PDFReader.h"
#include "qrcode/QRReader.h"
#include <memory>
namespace ZXing {
MultiFormatReader::MultiFormatReader(const DecodeHints& hints)
{
bool tryHarder = hints.tryHarder();
auto formats = hints.formats().empty() ? BarcodeFormat::Any : hints.formats();
// Put 1D readers upfront in "normal" mode
if (formats.testFlags(BarcodeFormat::OneDCodes) && !tryHarder)
_readers.emplace_back(new OneD::Reader(hints));
if (formats.testFlag(BarcodeFormat::QRCode))
_readers.emplace_back(new QRCode::Reader(hints));
if (formats.testFlag(BarcodeFormat::DataMatrix))
_readers.emplace_back(new DataMatrix::Reader(hints));
if (formats.testFlag(BarcodeFormat::Aztec))
_readers.emplace_back(new Aztec::Reader(hints));
if (formats.testFlag(BarcodeFormat::PDF417))
_readers.emplace_back(new Pdf417::Reader(hints));
if (formats.testFlag(BarcodeFormat::MaxiCode))
_readers.emplace_back(new MaxiCode::Reader(hints));
// At end in "try harder" mode
if (formats.testFlags(BarcodeFormat::OneDCodes) && tryHarder) {
_readers.emplace_back(new OneD::Reader(hints));
}
}
MultiFormatReader::~MultiFormatReader() = default;
Result
MultiFormatReader::read(const BinaryBitmap& image) const
{
// If we have only one reader in our list, just return whatever that decoded.
// This preserves information (e.g. ChecksumError) instead of just returning 'NotFound'.
if (_readers.size() == 1)
return _readers.front()->decode(image);
for (const auto& reader : _readers) {
Result r = reader->decode(image);
if (r.isValid())
return r;
}
return Result(DecodeStatus::NotFound);
}
Results MultiFormatReader::readMultiple(const BinaryBitmap& image, int maxSymbols) const
{
std::vector<Result> res;
for (const auto& reader : _readers) {
auto r = reader->decode(image, maxSymbols);
maxSymbols -= r.size();
res.insert(res.end(), std::move_iterator(r.begin()), std::move_iterator(r.end()));
if (maxSymbols <= 0)
break;
}
// sort results based on their position on the image
std::sort(res.begin(), res.end(), [](const Result& l, const Result& r) {
auto lp = l.position().topLeft();
auto rp = r.position().topLeft();
return lp.y < rp.y || (lp.y == rp.y && lp.x < rp.x);
});
return res;
}
} // ZXing
<|endoftext|>
|
<commit_before>/** \file restart_zts
* \brief Restart the docker container with the Zotero Translation Server
* \author Johannes Riedl
*/
/*
Copyright (C) 2020,2021, Library of the University of Tübingen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <functional>
#include <iostream>
#include <sstream>
#include "ExecUtil.h"
#include "IniFile.h"
#include "StringUtil.h"
#include "WebUtil.h"
#include "util.h"
namespace {
const std::string ZTS_RESTART_CONFIG("/usr/local/var/lib/tuelib/restart_zts.conf");
// Make sure to match this directory in /etc/sudoers.d/99-zts-restart otherwise symbolic linking will fail
const std::string ZTS_TRANSLATORS_DIR("/usr/local/zotero-translators");
void SendHeaders() {
std::cout << "Content-Type: text/html; charset=utf-8\r\n\r\n"
<< "<html>\n";
}
void SendTrailer() {
std::cout << "</html>\n";
}
struct TranslatorsLocationConfig {
std::string name_;
std::string url_;
std::string local_path_;
std::string branch_;
TranslatorsLocationConfig(std::string name = "", std::string url = "",
std::string local_path = "", std::string branch = "") :
name_(name), url_(url), local_path_(local_path), branch_(branch)
{}
};
void GetTranslatorLocationConfigs(const IniFile &ini_file,
std::vector<TranslatorsLocationConfig> * translators_location_configs) {
translators_location_configs->clear();
const std::string location_prefix("Repo_");
for (const auto §ion : ini_file) {
if (StringUtil::StartsWith(section.getSectionName(), location_prefix)) {
TranslatorsLocationConfig translators_location_config;
translators_location_config.name_ = section.getSectionName().substr(location_prefix.length());
translators_location_config.url_ = section.getString("url", "");
translators_location_config.local_path_ = section.getString("local_path");
translators_location_config.branch_ = section.getString("branch");
translators_location_configs->emplace_back(translators_location_config);
}
}
}
bool IsRestartActionPresent(const std::multimap<std::string, std::string> &cgi_args) {
const auto key_and_value(cgi_args.find("action"));
return key_and_value != cgi_args.cend() and key_and_value->second == "Restart";
}
void ExecuteAndDumpMessages(const std::string &command, const std::vector<std::string> &args) {
auto auto_temp_file((FileUtil::AutoTempFile()));
const std::string tmp_output(auto_temp_file.getFilePath());
ExecUtil::ExecOrDie(command, args, "" /*stdin*/, tmp_output, "/dev/stdout");
std::ifstream output_file(tmp_output);
if (not output_file)
LOG_ERROR("Could not open " + tmp_output + " for reading\n");
std::stringstream output_istream;
output_istream << output_file.rdbuf();
std::cout << StringUtil::ReplaceString("\n", "<br/>", output_istream.str());
}
template<typename Function>
void ExecuteAndDisplayStatus(const std::string &header_msg, Function function, std::string footer_msg = "") {
std::cout << header_msg << std::endl;
bool log_no_decorations_old(logger->getLogNoDecorations());
bool log_strip_call_site_old(logger->getLogStripCallSite());
logger->setLogNoDecorations(true);
logger->setLogStripCallSite(true);
logger->redirectOutput(STDOUT_FILENO);
try {
function();
} catch (const std::runtime_error &error) {
std::cerr << error.what();
}
std::cout << footer_msg << std::endl;
logger->redirectOutput(STDERR_FILENO);
logger->setLogNoDecorations(log_no_decorations_old);
logger->setLogStripCallSite(log_strip_call_site_old);
}
template<typename Function>
void ExecuteAndSendStatus(const std::string &message, Function function) {
SendHeaders();
ExecuteAndDisplayStatus(message, function);
SendTrailer();
}
void GetCurrentRepoAndBranch() {
const std::string chdir_to_translators_dir("cd " + ZTS_TRANSLATORS_DIR + "/translators");
auto closure = [&]{
ExecuteAndDumpMessages("/usr/bin/sudo",
{ "/bin/bash", "-c", "/usr/local/bin/restart_zts_show_current_gitrepo.sh" });
};
ExecuteAndDisplayStatus("<h4>Current repo and branch </h4>", closure, "<p>");
}
void DisplayRestartAndSelectButtons(const std::vector<TranslatorsLocationConfig> &translators_location_configs) {
SendHeaders();
std::cout << "<h2>Restart Zotero Translation Server Service</h2>\n";
GetCurrentRepoAndBranch();
std::cout << "<form action=\"\" method=\"post\">\n";
for (const auto &translators_location_config : translators_location_configs)
std::cout << "\t<input type=\"submit\" name=\"action\" value=\"" + translators_location_config.name_ +"\">\n";
std::cout << "<p/><hr/><p/>" << std::endl;
std::cout << "\t<input type=\"submit\" name=\"action\" value=\"Restart\">\n"
<< "</form>\n";
SendTrailer();
}
void RestartZTS() {
auto closure = []{
ExecUtil::ExecOrDie("/usr/bin/sudo", { "systemctl", "restart", "zts" });
ExecuteAndDumpMessages("/usr/bin/sudo", { "systemctl", "status", "zts" });
};
ExecuteAndSendStatus("<h2>Trying to restart ZTS Server</h2>", closure);
}
void RelinkTranslatorDirectory(const TranslatorsLocationConfig &translators_location_config) {
auto closure = [&]{
ExecuteAndDumpMessages("/usr/bin/sudo",
{ "ln" , "--symbolic", "--force", "--no-dereference",
translators_location_config.local_path_, ZTS_TRANSLATORS_DIR});
std::cout << "Linking " + ZTS_TRANSLATORS_DIR + " to " + translators_location_config.local_path_ << '\n';
RestartZTS();
};
ExecuteAndSendStatus("<h2>Switching to branch " + translators_location_config.name_ + "</h2>",
closure);
}
bool GetSwitchBranch(const std::multimap<std::string, std::string> &cgi_args,
std::vector<TranslatorsLocationConfig> translators_location_configs,
TranslatorsLocationConfig * const translator_location_config) {
const auto key_and_value(cgi_args.find("action"));
if (key_and_value == cgi_args.end())
return false;
const std::string target(key_and_value->second);
auto match(std::find_if(translators_location_configs.begin(),
translators_location_configs.end(),
[&target](const TranslatorsLocationConfig &target_obj)
{return target_obj.name_ == target;}));
if (match == translators_location_configs.end()) {
std::cout << "NO MATCH";
return false;
}
*translator_location_config = *match;
return true;
}
} // end unnamed namespace
int Main(int /*argc*/, char */*argv*/[]) {
std::multimap<std::string, std::string> cgi_args;
WebUtil::GetAllCgiArgs(&cgi_args);
IniFile ini_file(ZTS_RESTART_CONFIG);
std::vector<TranslatorsLocationConfig> translators_location_configs;
GetTranslatorLocationConfigs(ini_file, &translators_location_configs);
if (IsRestartActionPresent(cgi_args)) {
RestartZTS();
return EXIT_SUCCESS;
}
TranslatorsLocationConfig translators_location_config;
if (GetSwitchBranch(cgi_args, translators_location_configs, &translators_location_config)) {
RelinkTranslatorDirectory(translators_location_config);
return EXIT_SUCCESS;
}
DisplayRestartAndSelectButtons(translators_location_configs);
return EXIT_SUCCESS;
}
<commit_msg>ZEM switch functionality<commit_after>/** \file restart_zts
* \brief Restart the docker container with the Zotero Translation Server
* \author Johannes Riedl
*/
/*
Copyright (C) 2020,2021, Library of the University of Tübingen
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <functional>
#include <iostream>
#include <sstream>
#include "ExecUtil.h"
#include "IniFile.h"
#include "StringUtil.h"
#include "WebUtil.h"
#include "util.h"
namespace {
const std::string ZTS_RESTART_CONFIG("/usr/local/var/lib/tuelib/restart_zts.conf");
// Make sure to match this directory in /etc/sudoers.d/99-zts-restart otherwise symbolic linking will fail
const std::string ZTS_TRANSLATORS_DIR("/usr/local/zotero-translators");
const std::string ZOTERO_ENHANCEMENT_MAPS_DIR("/usr/local/var/lib/tuelib/zotero-enhancement-maps");
void SendHeaders() {
std::cout << "Content-Type: text/html; charset=utf-8\r\n\r\n"
<< "<html>\n";
}
void SendTrailer() {
std::cout << "</html>\n";
}
struct TranslatorsLocationConfig {
std::string name_;
std::string url_;
std::string local_path_;
std::string branch_;
std::string zotero_enhancement_maps_local_path_;
std::string zotero_enhancement_maps_branch_;
TranslatorsLocationConfig(std::string name = "", std::string url = "",
std::string local_path = "", std::string branch = "",
std::string zotero_enhancement_maps_local_path = "",
std::string zotero_enhancement_maps_branch = "") :
name_(name), url_(url), local_path_(local_path), branch_(branch),
zotero_enhancement_maps_local_path_(zotero_enhancement_maps_local_path),
zotero_enhancement_maps_branch_(zotero_enhancement_maps_branch)
{}
};
void GetTranslatorLocationConfigs(const IniFile &ini_file,
std::vector<TranslatorsLocationConfig> * translators_location_configs) {
translators_location_configs->clear();
const std::string location_prefix("Repo_");
for (const auto §ion : ini_file) {
if (StringUtil::StartsWith(section.getSectionName(), location_prefix)) {
TranslatorsLocationConfig translators_location_config;
translators_location_config.name_ = section.getSectionName().substr(location_prefix.length());
translators_location_config.url_ = section.getString("url", "");
translators_location_config.local_path_ = section.getString("local_path");
translators_location_config.branch_ = section.getString("branch");
translators_location_config.zotero_enhancement_maps_local_path_ =
section.getString("zotero_enhancement_maps_local_path");
translators_location_config.zotero_enhancement_maps_branch_ =
section.getString("zotero_enhancement_maps_branch");
translators_location_configs->emplace_back(translators_location_config);
}
}
}
bool IsRestartActionPresent(const std::multimap<std::string, std::string> &cgi_args) {
const auto key_and_value(cgi_args.find("action"));
return key_and_value != cgi_args.cend() and key_and_value->second == "Restart";
}
void ExecuteAndDumpMessages(const std::string &command, const std::vector<std::string> &args) {
auto auto_temp_file((FileUtil::AutoTempFile()));
const std::string tmp_output(auto_temp_file.getFilePath());
ExecUtil::ExecOrDie(command, args, "" /*stdin*/, tmp_output, "/dev/stdout");
std::ifstream output_file(tmp_output);
if (not output_file)
LOG_ERROR("Could not open " + tmp_output + " for reading\n");
std::stringstream output_istream;
output_istream << output_file.rdbuf();
std::cout << StringUtil::ReplaceString("\n", "<br/>", output_istream.str());
}
template<typename Function>
void ExecuteAndDisplayStatus(const std::string &header_msg, Function function, std::string footer_msg = "") {
std::cout << header_msg << std::endl;
bool log_no_decorations_old(logger->getLogNoDecorations());
bool log_strip_call_site_old(logger->getLogStripCallSite());
logger->setLogNoDecorations(true);
logger->setLogStripCallSite(true);
logger->redirectOutput(STDOUT_FILENO);
try {
function();
} catch (const std::runtime_error &error) {
std::cerr << error.what();
}
std::cout << footer_msg << std::endl;
logger->redirectOutput(STDERR_FILENO);
logger->setLogNoDecorations(log_no_decorations_old);
logger->setLogStripCallSite(log_strip_call_site_old);
}
template<typename Function>
void ExecuteAndSendStatus(const std::string &message, Function function) {
SendHeaders();
ExecuteAndDisplayStatus(message, function);
SendTrailer();
}
void GetCurrentRepoAndBranch() {
const std::string chdir_to_translators_dir("cd " + ZTS_TRANSLATORS_DIR + "/translators");
auto closure = [&]{
ExecuteAndDumpMessages("/usr/bin/sudo",
{ "/bin/bash", "-c", "/usr/local/bin/restart_zts_show_current_gitrepo.sh" });
};
ExecuteAndDisplayStatus("<h4>Current repo and branch </h4>", closure, "<p>");
}
void DisplayRestartAndSelectButtons(const std::vector<TranslatorsLocationConfig> &translators_location_configs) {
SendHeaders();
std::cout << "<h2>Restart Zotero Translation Server Service</h2>\n";
GetCurrentRepoAndBranch();
std::cout << "<form action=\"\" method=\"post\">\n";
for (const auto &translators_location_config : translators_location_configs)
std::cout << "\t<input type=\"submit\" name=\"action\" value=\"" + translators_location_config.name_ +"\">\n";
std::cout << "<p/><hr/><p/>" << std::endl;
std::cout << "\t<input type=\"submit\" name=\"action\" value=\"Restart\">\n"
<< "</form>\n";
SendTrailer();
}
void RestartZTS() {
auto closure = []{
ExecUtil::ExecOrDie("/usr/bin/sudo", { "systemctl", "restart", "zts" });
ExecuteAndDumpMessages("/usr/bin/sudo", { "systemctl", "status", "zts" });
};
ExecuteAndSendStatus("<h2>Trying to restart ZTS Server</h2>", closure);
}
void RelinkTranslatorAndEnhancemenMapsDirectory(const TranslatorsLocationConfig &translators_location_config) {
auto closure = [&]{
ExecuteAndDumpMessages("/usr/bin/sudo",
{ "ln" , "--symbolic", "--force", "--no-dereference",
translators_location_config.local_path_, ZTS_TRANSLATORS_DIR});
std::cout << "Linking " << ZTS_TRANSLATORS_DIR << " to " << translators_location_config.local_path_ << "<br/>";
ExecuteAndDumpMessages("/usr/bin/sudo",
{ "ln" , "--symbolic", "--force", "--no-dereference",
translators_location_config.zotero_enhancement_maps_local_path_, ZOTERO_ENHANCEMENT_MAPS_DIR});
std::cout << "Linking " << ZOTERO_ENHANCEMENT_MAPS_DIR << " to " <<
translators_location_config.zotero_enhancement_maps_local_path_ << "<br/>";
RestartZTS();
};
ExecuteAndSendStatus("<h2>Switching to branch " + translators_location_config.name_ + "</h2>",
closure);
}
bool GetSwitchBranch(const std::multimap<std::string, std::string> &cgi_args,
std::vector<TranslatorsLocationConfig> translators_location_configs,
TranslatorsLocationConfig * const translator_location_config) {
const auto key_and_value(cgi_args.find("action"));
if (key_and_value == cgi_args.end())
return false;
const std::string target(key_and_value->second);
auto match(std::find_if(translators_location_configs.begin(),
translators_location_configs.end(),
[&target](const TranslatorsLocationConfig &target_obj)
{return target_obj.name_ == target;}));
if (match == translators_location_configs.end()) {
std::cout << "NO MATCH";
return false;
}
*translator_location_config = *match;
return true;
}
} // end unnamed namespace
int Main(int /*argc*/, char */*argv*/[]) {
std::multimap<std::string, std::string> cgi_args;
WebUtil::GetAllCgiArgs(&cgi_args);
IniFile ini_file(ZTS_RESTART_CONFIG);
std::vector<TranslatorsLocationConfig> translators_location_configs;
GetTranslatorLocationConfigs(ini_file, &translators_location_configs);
if (IsRestartActionPresent(cgi_args)) {
RestartZTS();
return EXIT_SUCCESS;
}
TranslatorsLocationConfig translators_location_config;
if (GetSwitchBranch(cgi_args, translators_location_configs, &translators_location_config)) {
RelinkTranslatorAndEnhancemenMapsDirectory(translators_location_config);
return EXIT_SUCCESS;
}
DisplayRestartAndSelectButtons(translators_location_configs);
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/** \file Elasticsearch.cc
* \brief Implementation of utility functions relating to Elasticsearch.
* \author Mario Trojan
*
* \copyright 2018 Universitätsbibliothek Tübingen. 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/>.
*/
#include "Elasticsearch.h"
#include <memory>
#include "FileUtil.h"
#include "IniFile.h"
std::shared_ptr<Elasticsearch::Configuration> Elasticsearch::Configuration::FactoryByConfigFile() {
const std::string ini_path("/usr/local/var/lib/tuelib/Elasticsearch.conf");
if (not FileUtil::Exists(ini_path))
ERROR("config file missing: " + ini_path);
const IniFile ini_file(ini_path);
std::shared_ptr<Elasticsearch::Configuration> config(new Elasticsearch::Configuration);
config->host_ = Url(ini_file.getString("Elasticsearch", "host"));
config->index_ = ini_file.getString("Elasticsearch", "index");
config->document_type_ = ini_file.getString("Elasticsearch", "document_type");
return config;
}
std::shared_ptr<JSON::ObjectNode> FieldsToJSON(const Elasticsearch::Fields &fields) {
std::shared_ptr<JSON::ObjectNode> tree_root(new JSON::ObjectNode);
for (const auto &field : fields) {
std::shared_ptr<JSON::StringNode> value_node(new JSON::StringNode(field.second));
tree_root->insert(field.first, value_node);
}
return tree_root;
}
Elasticsearch::Fields JSONToFields(const std::shared_ptr<const JSON::ObjectNode> &json_object) {
Elasticsearch::Fields fields;
for (const auto &key_and_value : *json_object) {
std::shared_ptr<JSON::StringNode> string_node(JSON::JSONNode::CastToStringNodeOrDie(key_and_value.first, key_and_value.second));
fields[key_and_value.first] = string_node->getValue();
}
return fields;
}
/** \brief Sends REST queries to Elasticsearch server
* \throws std::runtime_error on REST error or if the JSON response contained an error flag.
*/
std::shared_ptr<JSON::ObjectNode> Elasticsearch::Api::Query(const Url &host, const std::string &action, const REST::QueryType query_type, const std::shared_ptr<const JSON::JSONNode> &data) {
Url url(host.toString() + "/" + action);
Downloader::Params params;
if (data != nullptr)
params.additional_headers_.push_back("Content-Type: application/json");
std::shared_ptr<JSON::JSONNode> result(REST::QueryJSON(url, query_type, data, params));
std::shared_ptr<JSON::ObjectNode> result_object(JSON::JSONNode::CastToObjectNodeOrDie("Elasticsearch result", result));
if (result_object->hasNode("error"))
throw std::runtime_error("in Elasticsearch::query: " + result_object->getNode("error")->toString());
DEBUG(result_object->toString());
return result_object;
}
void Elasticsearch::Api::CreateDocument(const Url &host, const std::string &index, const Document &document) {
const std::shared_ptr<JSON::ObjectNode> tree_root(FieldsToJSON(document.fields_));
const std::string action(index + "/" + document.type_ + "/" + document.id_ + "?op_type=create");
Query(host, action, REST::QueryType::PUT, tree_root);
}
void Elasticsearch::Api::CreateIndex(const Url &host, const std::string &index) {
Query(host, index, REST::QueryType::PUT);
}
void Elasticsearch::Api::DeleteDocument(const Url &host, const std::string &index, const std::string &type, const std::string &id) {
const std::string action(index + "/" + type + "/" + id);
Query(host, action, REST::QueryType::DELETE);
}
void Elasticsearch::Api::DeleteIndex(const Url &host, const std::string &index) {
Query(host, index, REST::QueryType::DELETE);
}
Elasticsearch::Document Elasticsearch::Api::GetDocument(const Url &host, const std::string &index, const std::string &type, const std::string &id) {
const std::string action(index + "/" + type + "/" + id);
std::shared_ptr<JSON::ObjectNode> result(Query(host, action, REST::QueryType::GET));
bool found(result->getOptionalBooleanValue("found", false));
if (not found)
throw std::runtime_error("in Elasticsearch::getDocument: document not found!" + result->toString());
Document document;
document.id_ = id;
document.fields_ = JSONToFields(result->getObjectNode("_source"));
return document;
}
std::vector<std::string> Elasticsearch::Api::GetIndexList(const Url &host) {
const std::string action("_cluster/health?level=indices");
const std::shared_ptr<const JSON::ObjectNode> result_node(Query(host, action, REST::QueryType::GET));
if (not result_node->hasNode("indices"))
throw std::runtime_error("in Elasticsearch::getIndexList: indices key not found in result: " + result_node->toString());
const std::shared_ptr<const JSON::ObjectNode> index_list_node(result_node->getObjectNode("indices"));
std::vector<std::string> index_list;
for (const auto &key_and_node : *index_list_node)
index_list.push_back(key_and_node.first);
return index_list;
}
Elasticsearch::IndexStatistics Elasticsearch::Api::GetIndexStatistics(const Url &host, const std::string &index) {
const std::string action(index + "/_stats");
const std::shared_ptr<const JSON::ObjectNode> result_object(Query(host, action, REST::QueryType::GET));
const std::shared_ptr<const JSON::ObjectNode> indices_object(result_object->getObjectNode("indices"));
const std::shared_ptr<const JSON::ObjectNode> index_object(indices_object->getObjectNode(index));
const std::shared_ptr<const JSON::ObjectNode> total_object(index_object->getObjectNode("total"));
const std::shared_ptr<const JSON::ObjectNode> docs_object(total_object->getObjectNode("docs"));
IndexStatistics stats;
stats.document_count_ = static_cast<unsigned>(docs_object->getIntegerValue("count"));
return stats;
}
bool Elasticsearch::Api::HasDocument(const Url &host, const std::string &index, const std::string &type, const std::string &id) {
const std::string action(index + "/" + type + "/" + id);
const std::shared_ptr<const JSON::ObjectNode> result(Query(host, action, REST::QueryType::GET));
return result->getOptionalBooleanValue("found", false);
}
void Elasticsearch::Api::Reindex(const Url &host, const std::string &source_index, const std::string &target_index) {
std::shared_ptr<JSON::ObjectNode> tree_root(new JSON::ObjectNode);
std::shared_ptr<JSON::ObjectNode> source_node(new JSON::ObjectNode);
std::shared_ptr<JSON::StringNode> source_index_node(new JSON::StringNode(source_index));
source_node->insert("index", source_index_node);
tree_root->insert("source", source_node);
std::shared_ptr<JSON::ObjectNode> dest_node(new JSON::ObjectNode);
std::shared_ptr<JSON::StringNode> dest_index_node(new JSON::StringNode(target_index));
dest_node->insert("index", dest_index_node);
tree_root->insert("dest", dest_node);
Query(host, "_reindex", REST::QueryType::POST, tree_root);
}
Elasticsearch::IdToDocumentMap Elasticsearch::Api::SearchAllDocuments(const Url &host, const std::string &index) {
const std::string action(index + "/_search");
const std::shared_ptr<JSON::ObjectNode> tree_root(new JSON::ObjectNode);
std::shared_ptr<JSON::ObjectNode> query_node(new JSON::ObjectNode);
tree_root->insert("query", query_node);
std::shared_ptr<JSON::ObjectNode> match_all_node(new JSON::ObjectNode);
query_node->insert("match_all", match_all_node);
const std::shared_ptr<const JSON::ObjectNode> result_node(Query(host, action, REST::QueryType::GET, tree_root));
IdToDocumentMap documents;
if (result_node->hasNode("hits")) {
const std::shared_ptr<const JSON::ObjectNode> hits_object(result_node->getObjectNode("hits"));
const std::shared_ptr<const JSON::ArrayNode> hits_array(hits_object->getArrayNode("hits"));
for (const auto &hit_node : *hits_array) {
const std::shared_ptr<const JSON::ObjectNode> hit_object(JSON::JSONNode::CastToObjectNodeOrDie("hit", hit_node));
Document document;
document.id_ = hit_object->getStringValue("_id");
if (hit_object->hasNode("_source")) {
const std::shared_ptr<const JSON::ObjectNode> fields_object(hit_object->getObjectNode("_source"));
document.fields_ = JSONToFields(fields_object);
}
documents[document.id_] = document;
}
}
return documents;
}
void Elasticsearch::Api::UpdateDocument(const Url &host, const std::string &index, const Document &document) {
std::shared_ptr<JSON::ObjectNode> doc_node(FieldsToJSON(document.fields_));
std::shared_ptr<JSON::ObjectNode> tree_root(new JSON::ObjectNode);
tree_root->insert("doc", doc_node);
const std::string action(index + "/" + document.type_ + "/" + document.id_ + "/_update");
Query(host, action, REST::QueryType::POST, tree_root);
}
void Elasticsearch::Api::UpdateOrInsertDocument(const Url &host, const std::string &index, const Document &document) {
std::shared_ptr<JSON::ObjectNode> tree_root(new JSON::ObjectNode);
std::shared_ptr<JSON::ObjectNode> doc_node(FieldsToJSON(document.fields_));
tree_root->insert("doc", doc_node);
std::shared_ptr<JSON::BooleanNode> doc_as_upsert_node(new JSON::BooleanNode(true));
tree_root->insert("doc_as_upsert", doc_as_upsert_node);
const std::string action(index + "/" + document.type_ + "/" + document.id_ + "/_update");
Query(host, action, REST::QueryType::POST, tree_root);
}
<commit_msg>Elasticsearch: fixed GetDocument => type not being set<commit_after>/** \file Elasticsearch.cc
* \brief Implementation of utility functions relating to Elasticsearch.
* \author Mario Trojan
*
* \copyright 2018 Universitätsbibliothek Tübingen. 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/>.
*/
#include "Elasticsearch.h"
#include <memory>
#include "FileUtil.h"
#include "IniFile.h"
std::shared_ptr<Elasticsearch::Configuration> Elasticsearch::Configuration::FactoryByConfigFile() {
const std::string ini_path("/usr/local/var/lib/tuelib/Elasticsearch.conf");
if (not FileUtil::Exists(ini_path))
ERROR("config file missing: " + ini_path);
const IniFile ini_file(ini_path);
std::shared_ptr<Elasticsearch::Configuration> config(new Elasticsearch::Configuration);
config->host_ = Url(ini_file.getString("Elasticsearch", "host"));
config->index_ = ini_file.getString("Elasticsearch", "index");
config->document_type_ = ini_file.getString("Elasticsearch", "document_type");
return config;
}
std::shared_ptr<JSON::ObjectNode> FieldsToJSON(const Elasticsearch::Fields &fields) {
std::shared_ptr<JSON::ObjectNode> tree_root(new JSON::ObjectNode);
for (const auto &field : fields) {
std::shared_ptr<JSON::StringNode> value_node(new JSON::StringNode(field.second));
tree_root->insert(field.first, value_node);
}
return tree_root;
}
Elasticsearch::Fields JSONToFields(const std::shared_ptr<const JSON::ObjectNode> &json_object) {
Elasticsearch::Fields fields;
for (const auto &key_and_value : *json_object) {
std::shared_ptr<JSON::StringNode> string_node(JSON::JSONNode::CastToStringNodeOrDie(key_and_value.first, key_and_value.second));
fields[key_and_value.first] = string_node->getValue();
}
return fields;
}
/** \brief Sends REST queries to Elasticsearch server
* \throws std::runtime_error on REST error or if the JSON response contained an error flag.
*/
std::shared_ptr<JSON::ObjectNode> Elasticsearch::Api::Query(const Url &host, const std::string &action, const REST::QueryType query_type, const std::shared_ptr<const JSON::JSONNode> &data) {
Url url(host.toString() + "/" + action);
Downloader::Params params;
if (data != nullptr)
params.additional_headers_.push_back("Content-Type: application/json");
std::shared_ptr<JSON::JSONNode> result(REST::QueryJSON(url, query_type, data, params));
std::shared_ptr<JSON::ObjectNode> result_object(JSON::JSONNode::CastToObjectNodeOrDie("Elasticsearch result", result));
if (result_object->hasNode("error"))
throw std::runtime_error("in Elasticsearch::query: " + result_object->getNode("error")->toString());
DEBUG(result_object->toString());
return result_object;
}
void Elasticsearch::Api::CreateDocument(const Url &host, const std::string &index, const Document &document) {
const std::shared_ptr<JSON::ObjectNode> tree_root(FieldsToJSON(document.fields_));
const std::string action(index + "/" + document.type_ + "/" + document.id_ + "?op_type=create");
Query(host, action, REST::QueryType::PUT, tree_root);
}
void Elasticsearch::Api::CreateIndex(const Url &host, const std::string &index) {
Query(host, index, REST::QueryType::PUT);
}
void Elasticsearch::Api::DeleteDocument(const Url &host, const std::string &index, const std::string &type, const std::string &id) {
const std::string action(index + "/" + type + "/" + id);
Query(host, action, REST::QueryType::DELETE);
}
void Elasticsearch::Api::DeleteIndex(const Url &host, const std::string &index) {
Query(host, index, REST::QueryType::DELETE);
}
Elasticsearch::Document Elasticsearch::Api::GetDocument(const Url &host, const std::string &index, const std::string &type, const std::string &id) {
const std::string action(index + "/" + type + "/" + id);
std::shared_ptr<JSON::ObjectNode> result(Query(host, action, REST::QueryType::GET));
bool found(result->getOptionalBooleanValue("found", false));
if (not found)
throw std::runtime_error("in Elasticsearch::getDocument: document not found!" + result->toString());
Document document;
document.id_ = id;
document.type_ = type;
document.fields_ = JSONToFields(result->getObjectNode("_source"));
return document;
}
std::vector<std::string> Elasticsearch::Api::GetIndexList(const Url &host) {
const std::string action("_cluster/health?level=indices");
const std::shared_ptr<const JSON::ObjectNode> result_node(Query(host, action, REST::QueryType::GET));
if (not result_node->hasNode("indices"))
throw std::runtime_error("in Elasticsearch::getIndexList: indices key not found in result: " + result_node->toString());
const std::shared_ptr<const JSON::ObjectNode> index_list_node(result_node->getObjectNode("indices"));
std::vector<std::string> index_list;
for (const auto &key_and_node : *index_list_node)
index_list.push_back(key_and_node.first);
return index_list;
}
Elasticsearch::IndexStatistics Elasticsearch::Api::GetIndexStatistics(const Url &host, const std::string &index) {
const std::string action(index + "/_stats");
const std::shared_ptr<const JSON::ObjectNode> result_object(Query(host, action, REST::QueryType::GET));
const std::shared_ptr<const JSON::ObjectNode> indices_object(result_object->getObjectNode("indices"));
const std::shared_ptr<const JSON::ObjectNode> index_object(indices_object->getObjectNode(index));
const std::shared_ptr<const JSON::ObjectNode> total_object(index_object->getObjectNode("total"));
const std::shared_ptr<const JSON::ObjectNode> docs_object(total_object->getObjectNode("docs"));
IndexStatistics stats;
stats.document_count_ = static_cast<unsigned>(docs_object->getIntegerValue("count"));
return stats;
}
bool Elasticsearch::Api::HasDocument(const Url &host, const std::string &index, const std::string &type, const std::string &id) {
const std::string action(index + "/" + type + "/" + id);
const std::shared_ptr<const JSON::ObjectNode> result(Query(host, action, REST::QueryType::GET));
return result->getOptionalBooleanValue("found", false);
}
void Elasticsearch::Api::Reindex(const Url &host, const std::string &source_index, const std::string &target_index) {
std::shared_ptr<JSON::ObjectNode> tree_root(new JSON::ObjectNode);
std::shared_ptr<JSON::ObjectNode> source_node(new JSON::ObjectNode);
std::shared_ptr<JSON::StringNode> source_index_node(new JSON::StringNode(source_index));
source_node->insert("index", source_index_node);
tree_root->insert("source", source_node);
std::shared_ptr<JSON::ObjectNode> dest_node(new JSON::ObjectNode);
std::shared_ptr<JSON::StringNode> dest_index_node(new JSON::StringNode(target_index));
dest_node->insert("index", dest_index_node);
tree_root->insert("dest", dest_node);
Query(host, "_reindex", REST::QueryType::POST, tree_root);
}
Elasticsearch::IdToDocumentMap Elasticsearch::Api::SearchAllDocuments(const Url &host, const std::string &index) {
const std::string action(index + "/_search");
const std::shared_ptr<JSON::ObjectNode> tree_root(new JSON::ObjectNode);
std::shared_ptr<JSON::ObjectNode> query_node(new JSON::ObjectNode);
tree_root->insert("query", query_node);
std::shared_ptr<JSON::ObjectNode> match_all_node(new JSON::ObjectNode);
query_node->insert("match_all", match_all_node);
const std::shared_ptr<const JSON::ObjectNode> result_node(Query(host, action, REST::QueryType::GET, tree_root));
IdToDocumentMap documents;
if (result_node->hasNode("hits")) {
const std::shared_ptr<const JSON::ObjectNode> hits_object(result_node->getObjectNode("hits"));
const std::shared_ptr<const JSON::ArrayNode> hits_array(hits_object->getArrayNode("hits"));
for (const auto &hit_node : *hits_array) {
const std::shared_ptr<const JSON::ObjectNode> hit_object(JSON::JSONNode::CastToObjectNodeOrDie("hit", hit_node));
Document document;
document.id_ = hit_object->getStringValue("_id");
if (hit_object->hasNode("_source")) {
const std::shared_ptr<const JSON::ObjectNode> fields_object(hit_object->getObjectNode("_source"));
document.fields_ = JSONToFields(fields_object);
}
documents[document.id_] = document;
}
}
return documents;
}
void Elasticsearch::Api::UpdateDocument(const Url &host, const std::string &index, const Document &document) {
std::shared_ptr<JSON::ObjectNode> doc_node(FieldsToJSON(document.fields_));
std::shared_ptr<JSON::ObjectNode> tree_root(new JSON::ObjectNode);
tree_root->insert("doc", doc_node);
const std::string action(index + "/" + document.type_ + "/" + document.id_ + "/_update");
Query(host, action, REST::QueryType::POST, tree_root);
}
void Elasticsearch::Api::UpdateOrInsertDocument(const Url &host, const std::string &index, const Document &document) {
std::shared_ptr<JSON::ObjectNode> tree_root(new JSON::ObjectNode);
std::shared_ptr<JSON::ObjectNode> doc_node(FieldsToJSON(document.fields_));
tree_root->insert("doc", doc_node);
std::shared_ptr<JSON::BooleanNode> doc_as_upsert_node(new JSON::BooleanNode(true));
tree_root->insert("doc_as_upsert", doc_as_upsert_node);
const std::string action(index + "/" + document.type_ + "/" + document.id_ + "/_update");
Query(host, action, REST::QueryType::POST, tree_root);
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.