<commit_before>/**
 *  @file
 *  @copyright defined in eos/LICENSE.txt
 */
#include <fc/io/raw.hpp>
#include <fc/bitutil.hpp>
#include <fc/smart_ref_impl.hpp>
#include <algorithm>

#include <boost/range/adaptor/transformed.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/device/back_inserter.hpp>
#include <boost/iostreams/filter/zlib.hpp>

#include <eosio/chain/config.hpp>
#include <eosio/chain/exceptions.hpp>
#include <eosio/chain/transaction.hpp>

namespace eosio { namespace chain {

using namespace boost::multi_index;

struct cached_pub_key {
   transaction_id_type trx_id;
   public_key_type pub_key;
   signature_type sig;
   cached_pub_key(const cached_pub_key&) = delete;
   cached_pub_key() = delete;
   cached_pub_key& operator=(const cached_pub_key&) = delete;
   cached_pub_key(cached_pub_key&&) = default;
};
struct by_sig{};

typedef multi_index_container<
   cached_pub_key,
   indexed_by<
      sequenced<>,
      hashed_unique<
         tag<by_sig>,
         member<cached_pub_key,
                signature_type,
                &cached_pub_key::sig>
      >
   >
> recovery_cache_type;

void transaction_header::set_reference_block( const block_id_type& reference_block ) {
   ref_block_num    = fc::endian_reverse_u32(reference_block._hash[0]);
   ref_block_prefix = reference_block._hash[1];
}

bool transaction_header::verify_reference_block( const block_id_type& reference_block )const {
   return ref_block_num    == (decltype(ref_block_num))fc::endian_reverse_u32(reference_block._hash[0]) &&
          ref_block_prefix == (decltype(ref_block_prefix))reference_block._hash[1];
}

void transaction_header::validate()const {
   EOS_ASSERT( max_net_usage_words.value < UINT32_MAX / 8UL, transaction_exception,
               "declared max_net_usage_words overflows when expanded to max net usage" );
}

transaction_id_type transaction::id() const {
   digest_type::encoder enc;
   fc::raw::pack( enc, *this );
   return enc.result();
}

digest_type transaction::sig_digest( const chain_id_type& chain_id, const vector<bytes>& cfd )const {
   digest_type::encoder enc;
   fc::raw::pack( enc, chain_id );
   fc::raw::pack( enc, *this );
   if( cfd.size() ) {
      fc::raw::pack( enc, digest_type::hash(cfd) );
   } else {
      fc::raw::pack( enc, digest_type() );
   }
   return enc.result();
}

flat_set<public_key_type> transaction::get_signature_keys( const vector<signature_type>& signatures,
      const chain_id_type& chain_id, fc::time_point deadline, const vector<bytes>& cfd, bool allow_duplicate_keys)const
{ try {
   using boost::adaptors::transformed;

   constexpr size_t recovery_cache_size = 1000;
   static thread_local recovery_cache_type recovery_cache;
   const digest_type digest = sig_digest(chain_id, cfd);

   flat_set<public_key_type> recovered_pub_keys;
   for(const signature_type& sig : signatures) {
      EOS_ASSERT( fc::time_point::now() < deadline, tx_cpu_usage_exceeded, "transaction signature verification executed for too long",
                  ("now", fc::time_point::now())("deadline", deadline) );
      public_key_type recov;
      recovery_cache_type::index<by_sig>::type::iterator it = recovery_cache.get<by_sig>().find( sig );
      const auto& tid = id();
      if( it == recovery_cache.get<by_sig>().end() || it->trx_id != tid ) {
         recov = public_key_type( sig, digest );
         recovery_cache.emplace_back( cached_pub_key{tid, recov, sig} ); //could fail on dup signatures; not a problem
      } else {
         recov = it->pub_key;
      }
      bool successful_insertion = false;
      std::tie(std::ignore, successful_insertion) = recovered_pub_keys.insert(recov);
      EOS_ASSERT( allow_duplicate_keys || successful_insertion, tx_duplicate_sig,
                  "transaction includes more than one signature signed using the same key associated with public key: ${key}",
                  ("key", recov)
               );
   }

   while ( recovery_cache.size() > recovery_cache_size )
      recovery_cache.erase( recovery_cache.begin());

   return recovered_pub_keys;
} FC_CAPTURE_AND_RETHROW() }

const signature_type& signed_transaction::sign(const private_key_type& key, const chain_id_type& chain_id) {
   signatures.push_back(key.sign(sig_digest(chain_id, context_free_data)));
   return signatures.back();
}

signature_type signed_transaction::sign(const private_key_type& key, const chain_id_type& chain_id)const {
   return key.sign(sig_digest(chain_id, context_free_data));
}

flat_set<public_key_type> signed_transaction::get_signature_keys( const chain_id_type& chain_id, fc::time_point deadline,
                                                                  bool allow_duplicate_keys)const
{
   return transaction::get_signature_keys(signatures, chain_id, deadline, context_free_data, allow_duplicate_keys);
}

uint32_t packed_transaction::get_unprunable_size()const {
   uint64_t size = config::fixed_net_overhead_of_packed_trx;
   size += packed_trx.size();
   EOS_ASSERT( size <= std::numeric_limits<uint32_t>::max(), tx_too_big, "packed_transaction is too big" );
   return static_cast<uint32_t>(size);
}

uint32_t packed_transaction::get_prunable_size()const {
   uint64_t size = fc::raw::pack_size(signatures);
   size += packed_context_free_data.size();
   EOS_ASSERT( size <= std::numeric_limits<uint32_t>::max(), tx_too_big, "packed_transaction is too big" );
   return static_cast<uint32_t>(size);
}

digest_type packed_transaction::packed_digest()const {
   digest_type::encoder prunable;
   fc::raw::pack( prunable, signatures );
   fc::raw::pack( prunable, packed_context_free_data );

   digest_type::encoder enc;
   fc::raw::pack( enc, compression );
   fc::raw::pack( enc, packed_trx  );
   fc::raw::pack( enc, prunable.result() );

   return enc.result();
}

namespace bio = boost::iostreams;

template<size_t Limit>
struct read_limiter {
   using char_type = char;
   using category = bio::multichar_output_filter_tag;

   template<typename Sink>
   size_t write(Sink &sink, const char* s, size_t count)
   {
      EOS_ASSERT(_total + count <= Limit, tx_decompression_error, "Exceeded maximum decompressed transaction size");
      _total += count;
      return bio::write(sink, s, count);
   }

   size_t _total = 0;
};

static vector<bytes> unpack_context_free_data(const bytes& data) {
   if( data.size() == 0 )
      return vector<bytes>();

   return fc::raw::unpack< vector<bytes> >(data);
}

static transaction unpack_transaction(const bytes& data) {
   return fc::raw::unpack<transaction>(data);
}

static bytes zlib_decompress(const bytes& data) {
   try {
      bytes out;
      bio::filtering_ostream decomp;
      decomp.push(bio::zlib_decompressor());
      decomp.push(read_limiter<1*1024*1024>()); // limit to 10 megs decompressed for zip bomb protections
      decomp.push(bio::back_inserter(out));
      bio::write(decomp, data.data(), data.size());
      bio::close(decomp);
      return out;
   } catch( fc::exception& er ) {
      throw;
   } catch( ... ) {
      fc::unhandled_exception er( FC_LOG_MESSAGE( warn, "internal decompression error"), std::current_exception() );
      throw er;
   }
}

static vector<bytes> zlib_decompress_context_free_data(const bytes& data) {
   if( data.size() == 0 )
      return vector<bytes>();

   bytes out = zlib_decompress(data);
   return unpack_context_free_data(out);
}

static transaction zlib_decompress_transaction(const bytes& data) {
   bytes out = zlib_decompress(data);
   return unpack_transaction(out);
}

static bytes pack_transaction(const transaction& t) {
   return fc::raw::pack(t);
}

static bytes pack_context_free_data(const vector<bytes>& cfd ) {
   if( cfd.size() == 0 )
      return bytes();

   return fc::raw::pack(cfd);
}

static bytes zlib_compress_context_free_data(const vector<bytes>& cfd ) {
   if( cfd.size() == 0 )
      return bytes();

   bytes in = pack_context_free_data(cfd);
   bytes out;
   bio::filtering_ostream comp;
   comp.push(bio::zlib_compressor(bio::zlib::best_compression));
   comp.push(bio::back_inserter(out));
   bio::write(comp, in.data(), in.size());
   bio::close(comp);
   return out;
}

static bytes zlib_compress_transaction(const transaction& t) {
   bytes in = pack_transaction(t);
   bytes out;
   bio::filtering_ostream comp;
   comp.push(bio::zlib_compressor(bio::zlib::best_compression));
   comp.push(bio::back_inserter(out));
   bio::write(comp, in.data(), in.size());
   bio::close(comp);
   return out;
}

bytes packed_transaction::get_raw_transaction() const
{
   try {
      switch(compression) {
         case none:
            return packed_trx;
         case zlib:
            return zlib_decompress(packed_trx);
         default:
            EOS_THROW(unknown_transaction_compression, "Unknown transaction compression algorithm");
      }
   } FC_CAPTURE_AND_RETHROW((compression)(packed_trx))
}

vector<bytes> packed_transaction::get_context_free_data()const
{
   try {
      switch(compression) {
         case none:
            return unpack_context_free_data(packed_context_free_data);
         case zlib:
            return zlib_decompress_context_free_data(packed_context_free_data);
         default:
            EOS_THROW(unknown_transaction_compression, "Unknown transaction compression algorithm");
      }
   } FC_CAPTURE_AND_RETHROW((compression)(packed_context_free_data))
}

time_point_sec packed_transaction::expiration()const
{
   local_unpack();
   return unpacked_trx->expiration;
}

transaction_id_type packed_transaction::id()const
{
   local_unpack();
   return get_transaction().id();
}

transaction_id_type packed_transaction::get_uncached_id()const
{
   const auto raw = get_raw_transaction();
   return fc::raw::unpack<transaction>( raw ).id();
}

void packed_transaction::local_unpack()const
{
   if (!unpacked_trx) {
      try {
         switch(compression) {
         case none:
            unpacked_trx = unpack_transaction(packed_trx);
            break;
         case zlib:
            unpacked_trx = zlib_decompress_transaction(packed_trx);
            break;
         default:
            EOS_THROW(unknown_transaction_compression, "Unknown transaction compression algorithm");
         }
      } FC_CAPTURE_AND_RETHROW((compression)(packed_trx))
   }
}

transaction packed_transaction::get_transaction()const
{
   local_unpack();
   return transaction(*unpacked_trx);
}

signed_transaction packed_transaction::get_signed_transaction() const
{
   try {
      switch(compression) {
         case none:
            return signed_transaction(get_transaction(), signatures, unpack_context_free_data(packed_context_free_data));
         case zlib:
            return signed_transaction(get_transaction(), signatures, zlib_decompress_context_free_data(packed_context_free_data));
         default:
            EOS_THROW(unknown_transaction_compression, "Unknown transaction compression algorithm");
      }
   } FC_CAPTURE_AND_RETHROW((compression)(packed_trx)(packed_context_free_data))

}

packed_transaction::packed_transaction( bytes&& packed_txn, vector<signature_type>&& sigs,
                                        bytes&& packed_cfd, vector<bytes>&& cfd, compression_type _compression )
:signatures(std::move(sigs))
,compression(_compression)
,packed_context_free_data(std::move(packed_cfd))
,packed_trx(std::move(packed_txn))
{
   EOS_ASSERT(packed_cfd.empty() || cfd.empty(), tx_decompression_error, "Invalid packed_transaction");
   if( !cfd.empty() ) {
      set_context_free_data(cfd);
   }
}

packed_transaction::packed_transaction( signed_transaction&& t, bytes&& packed_cfd, compression_type _compression )
:signatures(std::move(t.signatures))
,compression(_compression)
,packed_context_free_data(std::move(packed_cfd))
{
   set_transaction(t);
   // allow passed in packed_cfd to overwrite signed_transaction.context_free_data if provided
   if( packed_context_free_data.empty() ) {
      set_context_free_data(t.context_free_data);
   }
}

void packed_transaction::set_transaction(const transaction& t)
{
   try {
      switch(compression) {
         case none:
            packed_trx = pack_transaction(t);
            break;
         case zlib:
            packed_trx = zlib_compress_transaction(t);
            break;
         default:
            EOS_THROW(unknown_transaction_compression, "Unknown transaction compression algorithm");
      }
   } FC_CAPTURE_AND_RETHROW((compression)(t))
}

void packed_transaction::set_context_free_data(const vector<bytes>& cfd)
{
   try {
      switch(compression) {
         case none:
            packed_context_free_data = pack_context_free_data(cfd);
            break;
         case zlib:
            packed_context_free_data = zlib_compress_context_free_data(cfd);
            break;
         default:
            EOS_THROW(unknown_transaction_compression, "Unknown transaction compression algorithm");
      }
   } FC_CAPTURE_AND_RETHROW((compression))
}

} } // eosio::chain
<commit_msg>Make recovery cache non-thread local and guard by mutex<commit_after>/**
 *  @file
 *  @copyright defined in eos/LICENSE.txt
 */
#include <fc/io/raw.hpp>
#include <fc/bitutil.hpp>
#include <fc/smart_ref_impl.hpp>
#include <algorithm>

#include <boost/range/adaptor/transformed.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/device/back_inserter.hpp>
#include <boost/iostreams/filter/zlib.hpp>

#include <eosio/chain/config.hpp>
#include <eosio/chain/exceptions.hpp>
#include <eosio/chain/transaction.hpp>

namespace eosio { namespace chain {

using namespace boost::multi_index;

struct cached_pub_key {
   transaction_id_type trx_id;
   public_key_type pub_key;
   signature_type sig;
   fc::microseconds cpu_usage;
   cached_pub_key(const cached_pub_key&) = delete;
   cached_pub_key() = delete;
   cached_pub_key& operator=(const cached_pub_key&) = delete;
   cached_pub_key(cached_pub_key&&) = default;
};
struct by_sig{};

typedef multi_index_container<
   cached_pub_key,
   indexed_by<
      sequenced<>,
      hashed_unique<
         tag<by_sig>,
         member<cached_pub_key,
                signature_type,
                &cached_pub_key::sig>
      >
   >
> recovery_cache_type;

static std::mutex cache_mtx;

void transaction_header::set_reference_block( const block_id_type& reference_block ) {
   ref_block_num    = fc::endian_reverse_u32(reference_block._hash[0]);
   ref_block_prefix = reference_block._hash[1];
}

bool transaction_header::verify_reference_block( const block_id_type& reference_block )const {
   return ref_block_num    == (decltype(ref_block_num))fc::endian_reverse_u32(reference_block._hash[0]) &&
          ref_block_prefix == (decltype(ref_block_prefix))reference_block._hash[1];
}

void transaction_header::validate()const {
   EOS_ASSERT( max_net_usage_words.value < UINT32_MAX / 8UL, transaction_exception,
               "declared max_net_usage_words overflows when expanded to max net usage" );
}

transaction_id_type transaction::id() const {
   digest_type::encoder enc;
   fc::raw::pack( enc, *this );
   return enc.result();
}

digest_type transaction::sig_digest( const chain_id_type& chain_id, const vector<bytes>& cfd )const {
   digest_type::encoder enc;
   fc::raw::pack( enc, chain_id );
   fc::raw::pack( enc, *this );
   if( cfd.size() ) {
      fc::raw::pack( enc, digest_type::hash(cfd) );
   } else {
      fc::raw::pack( enc, digest_type() );
   }
   return enc.result();
}

flat_set<public_key_type> transaction::get_signature_keys( const vector<signature_type>& signatures,
      const chain_id_type& chain_id, fc::time_point deadline, const vector<bytes>& cfd, bool allow_duplicate_keys)const
{ try {
   using boost::adaptors::transformed;

   constexpr size_t recovery_cache_size = 10000;
   static recovery_cache_type recovery_cache;
   auto start = fc::time_point::now();
   const digest_type digest = sig_digest(chain_id, cfd);

   std::unique_lock<std::mutex> lock(cache_mtx, std::defer_lock);
   flat_set<public_key_type> recovered_pub_keys;
   for(const signature_type& sig : signatures) {
      auto now = fc::time_point::now();
      EOS_ASSERT( now < deadline, tx_cpu_usage_exceeded, "transaction signature verification executed for too long",
                  ("now", now)("deadline", deadline)("start", start) );
      public_key_type recov;
      const auto& tid = id();
      lock.lock();
      recovery_cache_type::index<by_sig>::type::iterator it = recovery_cache.get<by_sig>().find( sig );
      if( it == recovery_cache.get<by_sig>().end() || it->trx_id != tid ) {
         lock.unlock();
         recov = public_key_type( sig, digest );
         fc::microseconds cpu_usage = fc::time_point::now() - start;
         lock.lock();
         recovery_cache.emplace_back( cached_pub_key{tid, recov, sig, cpu_usage} ); //could fail on dup signatures; not a problem
      } else {
         recov = it->pub_key;
      }
      lock.unlock();
      bool successful_insertion = false;
      std::tie(std::ignore, successful_insertion) = recovered_pub_keys.insert(recov);
      EOS_ASSERT( allow_duplicate_keys || successful_insertion, tx_duplicate_sig,
                  "transaction includes more than one signature signed using the same key associated with public key: ${key}",
                  ("key", recov) );
   }

   lock.lock();
   while ( recovery_cache.size() > recovery_cache_size )
      recovery_cache.erase( recovery_cache.begin());
   lock.unlock();

   return recovered_pub_keys;
} FC_CAPTURE_AND_RETHROW() }

const signature_type& signed_transaction::sign(const private_key_type& key, const chain_id_type& chain_id) {
   signatures.push_back(key.sign(sig_digest(chain_id, context_free_data)));
   return signatures.back();
}

signature_type signed_transaction::sign(const private_key_type& key, const chain_id_type& chain_id)const {
   return key.sign(sig_digest(chain_id, context_free_data));
}

flat_set<public_key_type> signed_transaction::get_signature_keys( const chain_id_type& chain_id, fc::time_point deadline,
                                                                  bool allow_duplicate_keys)const
{
   return transaction::get_signature_keys(signatures, chain_id, deadline, context_free_data, allow_duplicate_keys);
}

uint32_t packed_transaction::get_unprunable_size()const {
   uint64_t size = config::fixed_net_overhead_of_packed_trx;
   size += packed_trx.size();
   EOS_ASSERT( size <= std::numeric_limits<uint32_t>::max(), tx_too_big, "packed_transaction is too big" );
   return static_cast<uint32_t>(size);
}

uint32_t packed_transaction::get_prunable_size()const {
   uint64_t size = fc::raw::pack_size(signatures);
   size += packed_context_free_data.size();
   EOS_ASSERT( size <= std::numeric_limits<uint32_t>::max(), tx_too_big, "packed_transaction is too big" );
   return static_cast<uint32_t>(size);
}

digest_type packed_transaction::packed_digest()const {
   digest_type::encoder prunable;
   fc::raw::pack( prunable, signatures );
   fc::raw::pack( prunable, packed_context_free_data );

   digest_type::encoder enc;
   fc::raw::pack( enc, compression );
   fc::raw::pack( enc, packed_trx  );
   fc::raw::pack( enc, prunable.result() );

   return enc.result();
}

namespace bio = boost::iostreams;

template<size_t Limit>
struct read_limiter {
   using char_type = char;
   using category = bio::multichar_output_filter_tag;

   template<typename Sink>
   size_t write(Sink &sink, const char* s, size_t count)
   {
      EOS_ASSERT(_total + count <= Limit, tx_decompression_error, "Exceeded maximum decompressed transaction size");
      _total += count;
      return bio::write(sink, s, count);
   }

   size_t _total = 0;
};

static vector<bytes> unpack_context_free_data(const bytes& data) {
   if( data.size() == 0 )
      return vector<bytes>();

   return fc::raw::unpack< vector<bytes> >(data);
}

static transaction unpack_transaction(const bytes& data) {
   return fc::raw::unpack<transaction>(data);
}

static bytes zlib_decompress(const bytes& data) {
   try {
      bytes out;
      bio::filtering_ostream decomp;
      decomp.push(bio::zlib_decompressor());
      decomp.push(read_limiter<1*1024*1024>()); // limit to 10 megs decompressed for zip bomb protections
      decomp.push(bio::back_inserter(out));
      bio::write(decomp, data.data(), data.size());
      bio::close(decomp);
      return out;
   } catch( fc::exception& er ) {
      throw;
   } catch( ... ) {
      fc::unhandled_exception er( FC_LOG_MESSAGE( warn, "internal decompression error"), std::current_exception() );
      throw er;
   }
}

static vector<bytes> zlib_decompress_context_free_data(const bytes& data) {
   if( data.size() == 0 )
      return vector<bytes>();

   bytes out = zlib_decompress(data);
   return unpack_context_free_data(out);
}

static transaction zlib_decompress_transaction(const bytes& data) {
   bytes out = zlib_decompress(data);
   return unpack_transaction(out);
}

static bytes pack_transaction(const transaction& t) {
   return fc::raw::pack(t);
}

static bytes pack_context_free_data(const vector<bytes>& cfd ) {
   if( cfd.size() == 0 )
      return bytes();

   return fc::raw::pack(cfd);
}

static bytes zlib_compress_context_free_data(const vector<bytes>& cfd ) {
   if( cfd.size() == 0 )
      return bytes();

   bytes in = pack_context_free_data(cfd);
   bytes out;
   bio::filtering_ostream comp;
   comp.push(bio::zlib_compressor(bio::zlib::best_compression));
   comp.push(bio::back_inserter(out));
   bio::write(comp, in.data(), in.size());
   bio::close(comp);
   return out;
}

static bytes zlib_compress_transaction(const transaction& t) {
   bytes in = pack_transaction(t);
   bytes out;
   bio::filtering_ostream comp;
   comp.push(bio::zlib_compressor(bio::zlib::best_compression));
   comp.push(bio::back_inserter(out));
   bio::write(comp, in.data(), in.size());
   bio::close(comp);
   return out;
}

bytes packed_transaction::get_raw_transaction() const
{
   try {
      switch(compression) {
         case none:
            return packed_trx;
         case zlib:
            return zlib_decompress(packed_trx);
         default:
            EOS_THROW(unknown_transaction_compression, "Unknown transaction compression algorithm");
      }
   } FC_CAPTURE_AND_RETHROW((compression)(packed_trx))
}

vector<bytes> packed_transaction::get_context_free_data()const
{
   try {
      switch(compression) {
         case none:
            return unpack_context_free_data(packed_context_free_data);
         case zlib:
            return zlib_decompress_context_free_data(packed_context_free_data);
         default:
            EOS_THROW(unknown_transaction_compression, "Unknown transaction compression algorithm");
      }
   } FC_CAPTURE_AND_RETHROW((compression)(packed_context_free_data))
}

time_point_sec packed_transaction::expiration()const
{
   local_unpack();
   return unpacked_trx->expiration;
}

transaction_id_type packed_transaction::id()const
{
   local_unpack();
   return get_transaction().id();
}

transaction_id_type packed_transaction::get_uncached_id()const
{
   const auto raw = get_raw_transaction();
   return fc::raw::unpack<transaction>( raw ).id();
}

void packed_transaction::local_unpack()const
{
   if (!unpacked_trx) {
      try {
         switch(compression) {
         case none:
            unpacked_trx = unpack_transaction(packed_trx);
            break;
         case zlib:
            unpacked_trx = zlib_decompress_transaction(packed_trx);
            break;
         default:
            EOS_THROW(unknown_transaction_compression, "Unknown transaction compression algorithm");
         }
      } FC_CAPTURE_AND_RETHROW((compression)(packed_trx))
   }
}

transaction packed_transaction::get_transaction()const
{
   local_unpack();
   return transaction(*unpacked_trx);
}

signed_transaction packed_transaction::get_signed_transaction() const
{
   try {
      switch(compression) {
         case none:
            return signed_transaction(get_transaction(), signatures, unpack_context_free_data(packed_context_free_data));
         case zlib:
            return signed_transaction(get_transaction(), signatures, zlib_decompress_context_free_data(packed_context_free_data));
         default:
            EOS_THROW(unknown_transaction_compression, "Unknown transaction compression algorithm");
      }
   } FC_CAPTURE_AND_RETHROW((compression)(packed_trx)(packed_context_free_data))

}

packed_transaction::packed_transaction( bytes&& packed_txn, vector<signature_type>&& sigs,
                                        bytes&& packed_cfd, vector<bytes>&& cfd, compression_type _compression )
:signatures(std::move(sigs))
,compression(_compression)
,packed_context_free_data(std::move(packed_cfd))
,packed_trx(std::move(packed_txn))
{
   EOS_ASSERT(packed_cfd.empty() || cfd.empty(), tx_decompression_error, "Invalid packed_transaction");
   if( !cfd.empty() ) {
      set_context_free_data(cfd);
   }
}

packed_transaction::packed_transaction( signed_transaction&& t, bytes&& packed_cfd, compression_type _compression )
:signatures(std::move(t.signatures))
,compression(_compression)
,packed_context_free_data(std::move(packed_cfd))
{
   set_transaction(t);
   // allow passed in packed_cfd to overwrite signed_transaction.context_free_data if provided
   if( packed_context_free_data.empty() ) {
      set_context_free_data(t.context_free_data);
   }
}

void packed_transaction::set_transaction(const transaction& t)
{
   try {
      switch(compression) {
         case none:
            packed_trx = pack_transaction(t);
            break;
         case zlib:
            packed_trx = zlib_compress_transaction(t);
            break;
         default:
            EOS_THROW(unknown_transaction_compression, "Unknown transaction compression algorithm");
      }
   } FC_CAPTURE_AND_RETHROW((compression)(t))
}

void packed_transaction::set_context_free_data(const vector<bytes>& cfd)
{
   try {
      switch(compression) {
         case none:
            packed_context_free_data = pack_context_free_data(cfd);
            break;
         case zlib:
            packed_context_free_data = zlib_compress_context_free_data(cfd);
            break;
         default:
            EOS_THROW(unknown_transaction_compression, "Unknown transaction compression algorithm");
      }
   } FC_CAPTURE_AND_RETHROW((compression))
}

} } // eosio::chain
<|endoftext|>


<commit_before>
/*
  Copyright 1995 The University of Rhode Island and The Massachusetts
  Institute of Technology

  Portions of this software were developed by the Graduate School of
  Oceanography (GSO) at the University of Rhode Island (URI) in collaboration
  with The Massachusetts Institute of Technology (MIT).

  Access and use of this software shall impose the following obligations and
  understandings on the user. The user is granted the right, without any fee
  or cost, to use, copy, modify, alter, enhance and distribute this software,
  and any derivative works thereof, and its supporting documentation for any
  purpose whatsoever, provided that this entire notice appears in all copies
  of the software, derivative works and supporting documentation.  Further,
  the user agrees to credit URI/MIT in any publications that result from the
  use of this software or in any product that includes this software. The
  names URI, MIT and/or GSO, however, may not be used in any advertising or
  publicity to endorse or promote any products or commercial entity unless
  specific written permission is obtained from URI/MIT. The user also
  understands that URI/MIT is not obligated to provide the user with any
  support, consulting, training or assistance of any kind with regard to the
  use, operation and performance of this software nor to provide the user
  with any updates, revisions, new versions or "bug fixes".

  THIS SOFTWARE IS PROVIDED BY URI/MIT "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 URI/MIT BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
  DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTUOUS
  ACTION, ARISING OUT OF OR IN CONNECTION WITH THE ACCESS, USE OR PERFORMANCE
  OF THIS SOFTWARE.
*/

// Methods for class DDS
//
// jhrg 9/7/94

// $Log: DDS.cc,v $
// Revision 1.11  1995/07/09 21:28:55  jimg
// Added copyright notice.
//
// Revision 1.10  1995/05/10  13:45:13  jimg
// Changed the name of the configuration header file from `config.h' to
// `config_dap.h' so that other libraries could have header files which were
// installed in the DODS include directory without overwriting this one. Each
// config header should follow the convention config_<name>.h.
//
// Revision 1.9  1994/12/09  21:37:24  jimg
// Added <unistd.h> to the include files.
//
// Revision 1.8  1994/12/07  21:23:16  jimg
// Removed config
//
// Revision 1.7  1994/11/22  14:05:40  jimg
// Added code for data transmission to parts of the type hierarchy. Not
// complete yet.
// Fixed erros in type hierarchy headers (typos, incorrect comments, ...).
//
// Revision 1.6  1994/11/03  04:58:02  reza
// Added two overloading for function parse to make it consistent with DAS class.
//
// Revision 1.5  1994/10/18  00:20:46  jimg
// Added copy ctor, dtor, duplicate, operator=.
// Added var() for const cahr * (to avoid confusion between char * and
// Pix (which is void *)).
// Switched to errmsg library.
// Added formatting to print().
//
// Revision 1.4  1994/10/05  16:34:14  jimg
// Fixed bug in the parse function(s): the bison generated parser returns
// 1 on error, 0 on success, but parse() was not checking for this.
// Instead it returned the value of bison's parser function.
// Changed types of `status' in print and parser functions from int to bool.
//
// Revision 1.3  1994/09/23  14:42:22  jimg
// Added mfunc check_semantics().
// Replaced print mfunc stub with real code.
// Fixed some errors in comments.
//
// Revision 1.2  1994/09/15  21:08:39  jimg
// Added many classes to the BaseType hierarchy - the complete set of types
// described in the DODS API design documet is now represented.
// The parser can parse DDS files.
// Fixed many small problems with BaseType.
// Added CtorType.
//
// Revision 1.1  1994/09/08  21:09:40  jimg
// First version of the Dataset descriptor class.
//

static char rcsid[]="$Id: DDS.cc,v 1.11 1995/07/09 21:28:55 jimg Exp $";

#ifdef __GNUG__
#pragma implementation
#endif

#include <unistd.h>

#include "DDS.h"
#include "errmsg.h"
#include "util.h"

#include "config_dap.h"
#ifdef TRACE_NEW
#include "trace_new.h"
#endif

void ddsrestart(FILE *yyin);
int ddsparse(DDS &table);	// defined in dds.tab.c

// Copy the stuff in DDS to THIS. The mfunc returns void because THIS gets
// the `result' of the mfunc.
//
// NB: This can't define the formal param to be const since SLList<>first()
// (which is what DDS::first_var() calls) does not define THIS to be const.

void
DDS::duplicate(DDS &dds)
{
    name = dds.name;
    // copy the things pointed to by the list, not just the pointers
    for (Pix src = dds.first_var(); src; dds.next_var(src)) {
	BaseType *btp = dds.var(src)->ptr_duplicate();
	add_var(btp);
    }
}

DDS::DDS(const String &n) : name(n)
{
}

DDS::DDS(DDS &rhs)
{
    duplicate(rhs);
}

DDS::~DDS()
{
    for (Pix p = first_var(); p; next_var(p))
	delete var(p);
}

DDS &
DDS::operator=(DDS &rhs)
{
    if (this == &rhs)
	return *this;

    duplicate(rhs);

    return *this;
}

String
DDS::get_dataset_name()
{
    return name;
}

void
DDS::set_dataset_name(const String &n)
{
    name = n;
}

void
DDS::add_var(BaseType *bt)
{
    vars.append(bt);
}

void
DDS::del_var(const String &n)
{
    Pix pp = 0;			// previous Pix

    for (Pix p = vars.first(); p; vars.next(p))
	if (vars(p)->get_var_name() == n) {
	    vars.del_after(pp);	// pp points to the pos before p
	    return;
	}
	else
	    pp = p;
}

BaseType *
DDS::var(const String &n)
{
    for (Pix p = vars.first(); p; vars.next(p))
	if (vars(p)->get_var_name() == n)
	    return vars(p);

    return 0;
}

// This is necessary because (char *) can be cast to Pix (because PIX is
// really (void *)). This must take precedence over the creation of a
// temporary object (the String).

BaseType *
DDS::var(const char *n)
{
    return var((String)n);
}

Pix
DDS::first_var()
{
    return vars.first();
}

void
DDS::next_var(Pix &p)
{
    if (!vars.empty())
	vars.next(p);
}

BaseType *
DDS::var(Pix p)
{
    if (!vars.empty() && p)
	return vars(p);
}

bool
DDS::parse(String fname)
{
    FILE *in = fopen(fname, "r");

    if (!in) {
        cerr << "Could not open: " << fname << endl;
        return false;
      }

    bool status = parse(in);

    fclose(in);

    return status;
  }

bool
DDS::parse(int fd)
{
    FILE *in = fdopen(dup(fd), "r");

    if (!in) {
        cerr << "Could not access file" << endl;
        return false;
      }

    bool status = parse(in);

    fclose(in);

    return status;
  }

// Read structure from IN (which defaults to stdin). If ddsrestart() fails,
// return false, otherwise return the status of ddsparse().

bool
DDS::parse(FILE *in)
{
    if (!in) {
	err_print("DDS::parse: NULL file pointer");
	return false;
    }

    ddsrestart(in);

    return ddsparse(*this) == 0;
}

// Write strucutre from tables to OUT (which defaults to stdout). Return
// true.

bool
DDS::print(ostream &os)
{
    os << "Dataset {" << endl;

    for (Pix p = vars.first(); p; vars.next(p))
	vars(p)->print_decl(os);

    os << "} " << name << ";" << endl;

    return true;
}

// Check the semantics of the DDS describing a complete dataset. If ALL is
// true, check not only the semantics of THIS->TABLE, but also recurrsively
// all ctor types in the THIS->TABLE. By default, ALL is false since parsing
// a DDS input file runns semantic checks on all variables (but not the
// dataset itself.
//
// Returns: true if the conventions for the DDS are not violated, false
// otherwise.

bool
DDS::check_semantics(bool all)
{
    // The dataset must have a name
    if (name == (char *)0) {
	cerr << "A dataset must have a name" << endl;
	return false;
    }

    if (!unique(vars, (const char *)name, (const char *)"Dataset"))
	return false;

    if (all)
	for (Pix p = vars.first(); p; vars.next(p))
	    if (!vars(p)->check_semantics(true))
		return false;

    return true;
}
<commit_msg>Changed from old mfuncs to new(er) ones.<commit_after>
/*
  Copyright 1994, 1995 The University of Rhode Island and The Massachusetts
  Institute of Technology

  Portions of this software were developed by the Graduate School of
  Oceanography (GSO) at the University of Rhode Island (URI) in collaboration
  with The Massachusetts Institute of Technology (MIT).

  Access and use of this software shall impose the following obligations and
  understandings on the user. The user is granted the right, without any fee
  or cost, to use, copy, modify, alter, enhance and distribute this software,
  and any derivative works thereof, and its supporting documentation for any
  purpose whatsoever, provided that this entire notice appears in all copies
  of the software, derivative works and supporting documentation.  Further,
  the user agrees to credit URI/MIT in any publications that result from the
  use of this software or in any product that includes this software. The
  names URI, MIT and/or GSO, however, may not be used in any advertising or
  publicity to endorse or promote any products or commercial entity unless
  specific written permission is obtained from URI/MIT. The user also
  understands that URI/MIT is not obligated to provide the user with any
  support, consulting, training or assistance of any kind with regard to the
  use, operation and performance of this software nor to provide the user
  with any updates, revisions, new versions or "bug fixes".

  THIS SOFTWARE IS PROVIDED BY URI/MIT "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 URI/MIT BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
  DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTUOUS
  ACTION, ARISING OUT OF OR IN CONNECTION WITH THE ACCESS, USE OR PERFORMANCE
  OF THIS SOFTWARE.
*/

// Methods for class DDS
//
// jhrg 9/7/94

// $Log: DDS.cc,v $
// Revision 1.12  1995/08/23 00:06:30  jimg
// Changed from old mfuncs to new(er) ones.
//
// Revision 1.11  1995/07/09  21:28:55  jimg
// Added copyright notice.
//
// Revision 1.10  1995/05/10  13:45:13  jimg
// Changed the name of the configuration header file from `config.h' to
// `config_dap.h' so that other libraries could have header files which were
// installed in the DODS include directory without overwriting this one. Each
// config header should follow the convention config_<name>.h.
//
// Revision 1.9  1994/12/09  21:37:24  jimg
// Added <unistd.h> to the include files.
//
// Revision 1.8  1994/12/07  21:23:16  jimg
// Removed config
//
// Revision 1.7  1994/11/22  14:05:40  jimg
// Added code for data transmission to parts of the type hierarchy. Not
// complete yet.
// Fixed erros in type hierarchy headers (typos, incorrect comments, ...).
//
// Revision 1.6  1994/11/03  04:58:02  reza
// Added two overloading for function parse to make it consistent with DAS class.
//
// Revision 1.5  1994/10/18  00:20:46  jimg
// Added copy ctor, dtor, duplicate, operator=.
// Added var() for const cahr * (to avoid confusion between char * and
// Pix (which is void *)).
// Switched to errmsg library.
// Added formatting to print().
//
// Revision 1.4  1994/10/05  16:34:14  jimg
// Fixed bug in the parse function(s): the bison generated parser returns
// 1 on error, 0 on success, but parse() was not checking for this.
// Instead it returned the value of bison's parser function.
// Changed types of `status' in print and parser functions from int to bool.
//
// Revision 1.3  1994/09/23  14:42:22  jimg
// Added mfunc check_semantics().
// Replaced print mfunc stub with real code.
// Fixed some errors in comments.
//
// Revision 1.2  1994/09/15  21:08:39  jimg
// Added many classes to the BaseType hierarchy - the complete set of types
// described in the DODS API design documet is now represented.
// The parser can parse DDS files.
// Fixed many small problems with BaseType.
// Added CtorType.
//
// Revision 1.1  1994/09/08  21:09:40  jimg
// First version of the Dataset descriptor class.
//

static char rcsid[]="$Id: DDS.cc,v 1.12 1995/08/23 00:06:30 jimg Exp $";

#ifdef __GNUG__
#pragma implementation
#endif

#include <unistd.h>

#include "DDS.h"
#include "errmsg.h"
#include "util.h"

#include "config_dap.h"
#ifdef TRACE_NEW
#include "trace_new.h"
#endif

void ddsrestart(FILE *yyin);
int ddsparse(DDS &table);	// defined in dds.tab.c

// Copy the stuff in DDS to THIS. The mfunc returns void because THIS gets
// the `result' of the mfunc.
//
// NB: This can't define the formal param to be const since SLList<>first()
// (which is what DDS::first_var() calls) does not define THIS to be const.

void
DDS::duplicate(DDS &dds)
{
    name = dds.name;
    // copy the things pointed to by the list, not just the pointers
    for (Pix src = dds.first_var(); src; dds.next_var(src)) {
	BaseType *btp = dds.var(src)->ptr_duplicate();
	add_var(btp);
    }
}

DDS::DDS(const String &n) : name(n)
{
}

DDS::DDS(DDS &rhs)
{
    duplicate(rhs);
}

DDS::~DDS()
{
    for (Pix p = first_var(); p; next_var(p))
	delete var(p);
}

DDS &
DDS::operator=(DDS &rhs)
{
    if (this == &rhs)
	return *this;

    duplicate(rhs);

    return *this;
}

String
DDS::get_dataset_name()
{
    return name;
}

void
DDS::set_dataset_name(const String &n)
{
    name = n;
}

void
DDS::add_var(BaseType *bt)
{
    vars.append(bt);
}

void
DDS::del_var(const String &n)
{
    Pix pp = 0;			// previous Pix

    for (Pix p = vars.first(); p; vars.next(p))
	if (vars(p)->name() == n) {
	    vars.del_after(pp);	// pp points to the pos before p
	    return;
	}
	else
	    pp = p;
}

BaseType *
DDS::var(const String &n)
{
    for (Pix p = vars.first(); p; vars.next(p))
	if (vars(p)->name() == n)
	    return vars(p);

    return 0;
}

// This is necessary because (char *) can be cast to Pix (because PIX is
// really (void *)). This must take precedence over the creation of a
// temporary object (the String).

BaseType *
DDS::var(const char *n)
{
    return var((String)n);
}

Pix
DDS::first_var()
{
    return vars.first();
}

void
DDS::next_var(Pix &p)
{
    if (!vars.empty())
	vars.next(p);
}

BaseType *
DDS::var(Pix p)
{
    if (!vars.empty() && p)
	return vars(p);
}

bool
DDS::parse(String fname)
{
    FILE *in = fopen(fname, "r");

    if (!in) {
        cerr << "Could not open: " << fname << endl;
        return false;
      }

    bool status = parse(in);

    fclose(in);

    return status;
  }

bool
DDS::parse(int fd)
{
    FILE *in = fdopen(dup(fd), "r");

    if (!in) {
        cerr << "Could not access file" << endl;
        return false;
      }

    bool status = parse(in);

    fclose(in);

    return status;
  }

// Read structure from IN (which defaults to stdin). If ddsrestart() fails,
// return false, otherwise return the status of ddsparse().

bool
DDS::parse(FILE *in)
{
    if (!in) {
	err_print("DDS::parse: NULL file pointer");
	return false;
    }

    ddsrestart(in);

    return ddsparse(*this) == 0;
}

// Write strucutre from tables to OUT (which defaults to stdout). Return
// true.

bool
DDS::print(ostream &os)
{
    os << "Dataset {" << endl;

    for (Pix p = vars.first(); p; vars.next(p))
	vars(p)->print_decl(os);

    os << "} " << name << ";" << endl;

    return true;
}

// Check the semantics of the DDS describing a complete dataset. If ALL is
// true, check not only the semantics of THIS->TABLE, but also recurrsively
// all ctor types in the THIS->TABLE. By default, ALL is false since parsing
// a DDS input file runns semantic checks on all variables (but not the
// dataset itself.
//
// Returns: true if the conventions for the DDS are not violated, false
// otherwise.

bool
DDS::check_semantics(bool all)
{
    // The dataset must have a name
    if (name == (char *)0) {
	cerr << "A dataset must have a name" << endl;
	return false;
    }

    if (!unique(vars, (const char *)name, (const char *)"Dataset"))
	return false;

    if (all)
	for (Pix p = vars.first(); p; vars.next(p))
	    if (!vars(p)->check_semantics(true))
		return false;

    return true;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
 * that can be found in the LICENSE file.
 */

#include <cstdarg>
#include "Porting.h"

RUNTIME_NORETURN void RuntimeAssertFailed(const char* location, const char* format, ...) {
    char buf[1024];
    int written = -1;

    // Write the title with a source location.
    if (location != nullptr) {
        written = konan::snprintf(buf, sizeof(buf), "%s: runtime assert: ", location);
    } else {
        written = konan::snprintf(buf, sizeof(buf), "runtime assert: ");
    }

    // Write the message.
    if (written >= 0 && static_cast<size_t>(written) < sizeof(buf)) {
        std::va_list args;
        va_start(args, format);
        konan::vsnprintf(buf + written, sizeof(buf) - written, format, args);
        va_end(args);
    }

    konan::consoleErrorUtf8(buf, konan::strnlen(buf, sizeof(buf)));
    konan::consoleErrorf("\n");
    // TODO: Write the stacktrace.
    konan::abort();
}
<commit_msg>[runtime] Old impl of RuntimeAssert for backward compatibility<commit_after>/*
 * Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
 * that can be found in the LICENSE file.
 */

#include <cstdarg>
#include "Porting.h"

RUNTIME_NORETURN void RuntimeAssertFailed(const char* location, const char* format, ...) {
    char buf[1024];
    int written = -1;

    // Write the title with a source location.
    if (location != nullptr) {
        written = konan::snprintf(buf, sizeof(buf), "%s: runtime assert: ", location);
    } else {
        written = konan::snprintf(buf, sizeof(buf), "runtime assert: ");
    }

    // Write the message.
    if (written >= 0 && static_cast<size_t>(written) < sizeof(buf)) {
        std::va_list args;
        va_start(args, format);
        konan::vsnprintf(buf + written, sizeof(buf) - written, format, args);
        va_end(args);
    }

    konan::consoleErrorUtf8(buf, konan::strnlen(buf, sizeof(buf)));
    konan::consoleErrorf("\n");
    // TODO: Write the stacktrace.
    konan::abort();
}

// TODO: this function is not used by runtime, but apparently there are
// third-party libraries that use it (despite the fact it is not a public API).
// Keeping the function here for now for backward compatibility, to be removed later.
RUNTIME_NORETURN void RuntimeAssertFailed(const char* location, const char* message) {
  char buf[1024];
  if (location != nullptr)
      konan::snprintf(buf, sizeof(buf), "%s: runtime assert: %s\n", location, message);
  else
      konan::snprintf(buf, sizeof(buf), "runtime assert: %s\n", message);
  konan::consoleErrorUtf8(buf, konan::strnlen(buf, sizeof(buf)));
  konan::abort();
}
<|endoftext|>


<commit_before><commit_msg>Revert "drt: transform access point before stroing in odb"<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: excform.hxx,v $
 *
 *  $Revision: 1.19 $
 *
 *  last change: $Author: obo $ $Date: 2007-06-13 09:11:41 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _EXCFORM_HXX
#define _EXCFORM_HXX

#ifndef SC_XLFORMULA_HXX
#include "xlformula.hxx"
#endif
#ifndef SC_XIROOT_HXX
#include "xiroot.hxx"
#endif

#ifndef _FORMEL_HXX
#include "formel.hxx"
#endif

class ScRangeList;

class ExcelToSc : public ExcelConverterBase, protected XclImpRoot
{
protected:
    enum ExtensionType { EXTENSION_ARRAY, EXTENSION_NLR, EXTENSION_MEMAREA };
    typedef ::std::vector< ExtensionType >          ExtensionTypeVec;

    BOOL                bExternName;    // wenn External Name gefunden wurde
    static const UINT16 nRowMask;
    static const UINT16 nLastInd;       // letzter Index fuer Excel->SC-
                                        // Token Umsetzung
    XclFunctionProvider maFuncProv;
    const XclBiff       meBiff;

    // ---------------------------------------------------------------
    void                DoMulArgs( DefTokenId eId, sal_uInt8 nNumArgs, sal_uInt8 mnMinParamCount = 0 );

    void                ExcRelToScRel( UINT16 nRow, UINT8 nCol, SingleRefData&, const BOOL bName );

    void                PushRangeOperator();

public:
                        ExcelToSc( const XclImpRoot& rRoot );
    virtual             ~ExcelToSc();
    virtual ConvErr     Convert( const ScTokenArray*&, XclImpStream& rStrm, sal_Size nFormulaLen,
                                 bool bAllowArrays, const FORMULA_TYPE eFT = FT_CellFormula );

    virtual ConvErr     Convert( _ScRangeListTabs&, XclImpStream& rStrm, sal_Size nFormulaLen, const FORMULA_TYPE eFT = FT_CellFormula );
    virtual BOOL        GetAbsRefs( ScRangeList& rRangeList, XclImpStream& rStrm, sal_Size nLen );

    void                GetDummy( const ScTokenArray*& );
    const ScTokenArray* GetBoolErr( XclBoolError );
    BOOL                GetShrFmla( const ScTokenArray*&, XclImpStream& rStrm, sal_Size nFormulaLen );

    static BOOL         SetCurVal( ScFormulaCell& rCell, double& rCurVal );
                            // return = TRUE -> String-Record folgt!
    static void         SetError( ScFormulaCell& rCell, const ConvErr eErr );

    static inline BOOL  IsComplColRange( const UINT16 nCol1, const UINT16 nCol2 );
    static inline BOOL  IsComplRowRange( const UINT16 nRow1, const UINT16 nRow2 );

    void                SetComplCol( ComplRefData& );
    void                SetComplRow( ComplRefData& );

    void                ReadExtensions( const ExtensionTypeVec& rExtensions,
                                        XclImpStream& aIn );
    void                ReadExtensionArray( unsigned int n,
                                            XclImpStream& aIn );
    void                ReadExtensionNlr( XclImpStream& aIn );
    void                ReadExtensionMemArea( XclImpStream& aIn );
};

inline BOOL ExcelToSc::IsComplColRange( const UINT16 nCol1, const UINT16 nCol2 )
{
    return ( nCol1 == 0x00 ) && ( nCol2 == 0xFF );
}

inline BOOL ExcelToSc::IsComplRowRange( const UINT16 nRow1, const UINT16 nRow2 )
{
    return ( ( nRow1 & 0x3FFF ) == 0x0000 ) && ( ( nRow2 & 0x3FFF ) == 0x3FFF );
}

class XclImpLinkManager;

class ExcelToSc8 : public ExcelToSc
{
private:
    const XclImpLinkManager&    rLinkMan;

    void                ExcRelToScRel8( UINT16 nRow, UINT16 nCol, SingleRefData&,
                            const BOOL bName );

                        // this function must read 2 bytes from stream and adjust <nBytesLeft>
    virtual BOOL        Read3DTabReference( XclImpStream& rStrm, SCTAB& rFirstTab, SCTAB& rLastTab );

public:
                        ExcelToSc8( const XclImpRoot& rRoot );
    virtual             ~ExcelToSc8();

    virtual ConvErr     Convert( const ScTokenArray*& rpTokArray, XclImpStream& rStrm, sal_Size nFormulaLen, bool bAllowArrays, const FORMULA_TYPE eFT = FT_CellFormula );

    virtual ConvErr     Convert( _ScRangeListTabs&, XclImpStream& rStrm, sal_Size nFormulaLen, const FORMULA_TYPE eFT = FT_CellFormula );

    static inline BOOL  IsComplRowRange( const UINT16 nRow1, const UINT16 nRow2 );

    virtual BOOL        GetAbsRefs( ScRangeList& rRangeList, XclImpStream& rStrm, sal_Size nLen );
};

inline BOOL ExcelToSc8::IsComplRowRange( const UINT16 nRow1, const UINT16 nRow2 )
{
    return ( nRow1 == 0x0000 ) && ( nRow2 == 0xFFFF );
}

#endif
<commit_msg>INTEGRATION: CWS odff (1.19.90); FILE MERGED 2008/02/15 13:07:24 dr 1.19.90.2: '#i67777#' 2007/11/29 19:06:47 er 1.19.90.1: #i4904# range operator ocRange<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: excform.hxx,v $
 *
 *  $Revision: 1.20 $
 *
 *  last change: $Author: kz $ $Date: 2008-03-06 15:48:47 $
 *
 *  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 _EXCFORM_HXX
#define _EXCFORM_HXX

#ifndef SC_XLFORMULA_HXX
#include "xlformula.hxx"
#endif
#ifndef SC_XIROOT_HXX
#include "xiroot.hxx"
#endif

#ifndef _FORMEL_HXX
#include "formel.hxx"
#endif

class ScRangeList;

class ExcelToSc : public ExcelConverterBase, protected XclImpRoot
{
protected:
    enum ExtensionType { EXTENSION_ARRAY, EXTENSION_NLR, EXTENSION_MEMAREA };
    typedef ::std::vector< ExtensionType >          ExtensionTypeVec;

    BOOL                bExternName;    // wenn External Name gefunden wurde
    static const UINT16 nRowMask;
    static const UINT16 nLastInd;       // letzter Index fuer Excel->SC-
                                        // Token Umsetzung
    XclFunctionProvider maFuncProv;
    const XclBiff       meBiff;

    // ---------------------------------------------------------------
    void                DoMulArgs( DefTokenId eId, sal_uInt8 nNumArgs, sal_uInt8 mnMinParamCount = 0 );

    void                ExcRelToScRel( UINT16 nRow, UINT8 nCol, SingleRefData&, const BOOL bName );

public:
                        ExcelToSc( const XclImpRoot& rRoot );
    virtual             ~ExcelToSc();
    virtual ConvErr     Convert( const ScTokenArray*&, XclImpStream& rStrm, sal_Size nFormulaLen,
                                 bool bAllowArrays, const FORMULA_TYPE eFT = FT_CellFormula );

    virtual ConvErr     Convert( _ScRangeListTabs&, XclImpStream& rStrm, sal_Size nFormulaLen, const FORMULA_TYPE eFT = FT_CellFormula );
    virtual BOOL        GetAbsRefs( ScRangeList& rRangeList, XclImpStream& rStrm, sal_Size nLen );

    void                GetDummy( const ScTokenArray*& );
    const ScTokenArray* GetBoolErr( XclBoolError );
    BOOL                GetShrFmla( const ScTokenArray*&, XclImpStream& rStrm, sal_Size nFormulaLen );

#if 0
                            // return = TRUE -> String-Record folgt!
    static BOOL         SetCurVal( ScFormulaCell& rCell, double& rCurVal );
#endif
    static void         SetError( ScFormulaCell& rCell, const ConvErr eErr );

    static inline BOOL  IsComplColRange( const UINT16 nCol1, const UINT16 nCol2 );
    static inline BOOL  IsComplRowRange( const UINT16 nRow1, const UINT16 nRow2 );

    void                SetComplCol( ComplRefData& );
    void                SetComplRow( ComplRefData& );

    void                ReadExtensions( const ExtensionTypeVec& rExtensions,
                                        XclImpStream& aIn );
    void                ReadExtensionArray( unsigned int n,
                                            XclImpStream& aIn );
    void                ReadExtensionNlr( XclImpStream& aIn );
    void                ReadExtensionMemArea( XclImpStream& aIn );
};

inline BOOL ExcelToSc::IsComplColRange( const UINT16 nCol1, const UINT16 nCol2 )
{
    return ( nCol1 == 0x00 ) && ( nCol2 == 0xFF );
}

inline BOOL ExcelToSc::IsComplRowRange( const UINT16 nRow1, const UINT16 nRow2 )
{
    return ( ( nRow1 & 0x3FFF ) == 0x0000 ) && ( ( nRow2 & 0x3FFF ) == 0x3FFF );
}

class XclImpLinkManager;

class ExcelToSc8 : public ExcelToSc
{
private:
    const XclImpLinkManager&    rLinkMan;

    void                ExcRelToScRel8( UINT16 nRow, UINT16 nCol, SingleRefData&,
                            const BOOL bName );

                        // this function must read 2 bytes from stream and adjust <nBytesLeft>
    virtual BOOL        Read3DTabReference( XclImpStream& rStrm, SCTAB& rFirstTab, SCTAB& rLastTab );

public:
                        ExcelToSc8( const XclImpRoot& rRoot );
    virtual             ~ExcelToSc8();

    virtual ConvErr     Convert( const ScTokenArray*& rpTokArray, XclImpStream& rStrm, sal_Size nFormulaLen, bool bAllowArrays, const FORMULA_TYPE eFT = FT_CellFormula );

    virtual ConvErr     Convert( _ScRangeListTabs&, XclImpStream& rStrm, sal_Size nFormulaLen, const FORMULA_TYPE eFT = FT_CellFormula );

    static inline BOOL  IsComplRowRange( const UINT16 nRow1, const UINT16 nRow2 );

    virtual BOOL        GetAbsRefs( ScRangeList& rRangeList, XclImpStream& rStrm, sal_Size nLen );
};

inline BOOL ExcelToSc8::IsComplRowRange( const UINT16 nRow1, const UINT16 nRow2 )
{
    return ( nRow1 == 0x0000 ) && ( nRow2 == 0xFFFF );
}

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xltools.hxx,v $
 *
 *  $Revision: 1.25 $
 *
 *  last change: $Author: vg $ $Date: 2006-04-07 16:25:14 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef SC_XLTOOLS_HXX
#define SC_XLTOOLS_HXX

#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif

#ifndef SC_FTOOLS_HXX
#include "ftools.hxx"
#endif

// BIFF versions ==============================================================

#define DBG_ERROR_BIFF()        DBG_ERRORFILE( "Unknown BIFF type!" )
#define DBG_ASSERT_BIFF( c )    DBG_ASSERT( c, "Unknown BIFF type!" )

// Enumerations ===============================================================

/** An enumeration for all Excel error codes and the values true and false. */
enum XclBoolError
{
    xlErrNull,                  /// The error code #NULL!
    xlErrDiv0,                  /// The error code #DIV/0!
    xlErrValue,                 /// The error code #VALUE!
    xlErrRef,                   /// The error code #REF!
    xlErrName,                  /// The error code #NAME?
    xlErrNum,                   /// The error code #NUM!
    xlErrNA,                    /// The error code #N/A!
    xlErrTrue,                  /// The Boolean value true.
    xlErrFalse,                 /// The Boolean value false.
    xlErrUnknown                /// For unknown codes and values.
};

// GUID import/export =========================================================

class XclImpStream;
class XclExpStream;

/** This struct stores a GUID (class ID) and supports reading, writing and comparison. */
struct XclGuid
{
    sal_uInt8           mpnData[ 16 ];  /// Stores GUID always in little endian.

    explicit            XclGuid();
    explicit            XclGuid(
                            sal_uInt32 nData1,
                            sal_uInt16 nData2, sal_uInt16 nData3,
                            sal_uInt8 nData41, sal_uInt8 nData42,
                            sal_uInt8 nData43, sal_uInt8 nData44,
                            sal_uInt8 nData45, sal_uInt8 nData46,
                            sal_uInt8 nData47, sal_uInt8 nData48 );
};

bool operator==( const XclGuid& rCmp1, const XclGuid& rCmp2 );
inline bool operator!=( const XclGuid& rCmp1, const XclGuid& rCmp2 ) { return !(rCmp1 == rCmp2); }
bool operator<( const XclGuid& rCmp1, const XclGuid& rCmp2 );

XclImpStream& operator>>( XclImpStream& rStrm, XclGuid& rGuid );
XclExpStream& operator<<( XclExpStream& rStrm, const XclGuid& rGuid );

// Excel Tools ================================================================

class SvStream;
class ScDocument;

/** This class contains static helper methods for the Excel import and export filters. */
class XclTools : ScfNoInstance
{
public:
    // GUID's -----------------------------------------------------------------

    static const XclGuid maGuidStdLink;     /// GUID of StdLink (HLINK record).
    static const XclGuid maGuidUrlMoniker;  /// GUID of URL moniker (HLINK record).
    static const XclGuid maGuidFileMoniker; /// GUID of file moniker (HLINK record).

    // numeric conversion -----------------------------------------------------

    /** Calculates the double value from an RK value (encoded integer or double). */
    static double       GetDoubleFromRK( sal_Int32 nRKValue );
    /** Calculates an RK value (encoded integer or double) from a double value.
        @param rnRKValue  Returns the calculated RK value.
        @param fValue  The double value.
        @return  true = An RK value could be created. */
    static bool         GetRKFromDouble( sal_Int32& rnRKValue, double fValue );

    /** Calculates an angle (in 1/100 of degrees) from an Excel angle value.
        @param nRotForStacked  This value will be returned, if nXclRot contains 'stacked'. */
    static sal_Int32    GetScRotation( sal_uInt16 nXclRot, sal_Int32 nRotForStacked );
    /** Calculates the Excel angle value from an angle in 1/100 of degrees. */
    static sal_uInt8    GetXclRotation( sal_Int32 nScRot );

    /** Converts a Calc error code to an Excel error code. */
    static sal_uInt8    GetXclErrorCode( USHORT nScError );
    /** Converts an Excel error code to a Calc error code. */
    static USHORT       GetScErrorCode( sal_uInt8 nXclError );

    /** Gets a translated error code or Boolean value from Excel error codes.
        @param rfDblValue  Returns 0.0 for error codes or the value of a Boolean (0.0 or 1.0).
        @param bErrorOrBool  false = nError is a Boolean value; true = is an error value.
        @param nValue  The error code or Boolean value. */
    static XclBoolError ErrorToEnum( double& rfDblValue, sal_uInt8 bErrOrBool, sal_uInt8 nValue );

    /** Returns the length in twips calculated from a length in inches. */
    static sal_uInt16   GetTwipsFromInch( double fInches );
    /** Returns the length in twips calculated from a length in 1/100 mm. */
    static sal_uInt16   GetTwipsFromHmm( sal_Int32 nHmm );

    /** Returns the length in inches calculated from a length in twips. */
    static double       GetInchFromTwips( sal_Int32 nTwips );
    /** Returns the length in inches calculated from a length in 1/100 mm. */
    static double       GetInchFromHmm( sal_Int32 nHmm );

    /** Returns the length in 1/100 mm calculated from a length in inches. */
    static sal_Int32    GetHmmFromInch( double fInches );
    /** Returns the length in 1/100 mm calculated from a length in twips. */
    static sal_Int32    GetHmmFromTwips( sal_Int32 nTwips );

    /** Returns the Calc column width (twips) for the passed Excel width.
        @param nScCharWidth  Width of the '0' character in Calc (twips). */
    static USHORT       GetScColumnWidth( sal_uInt16 nXclWidth, long nScCharWidth );
    /** Returns the Excel column width for the passed Calc width (twips).
        @param nScCharWidth  Width of the '0' character in Calc (twips). */
    static sal_uInt16   GetXclColumnWidth( USHORT nScWidth, long nScCharWidth );

    /** Returns a correction value to convert column widths from/to default column widths.
        @param nXclDefFontHeight  Excel height of application default font. */
    static double       GetXclDefColWidthCorrection( long nXclDefFontHeight );

    // text encoding ----------------------------------------------------------

    /** Returns a text encoding from an Excel code page.
        @return  The corresponding text encoding or RTL_TEXTENCODING_DONTKNOW. */
    static rtl_TextEncoding GetTextEncoding( sal_uInt16 nCodePage );
    /** Returns an Excel code page from a text encoding. */
    static sal_uInt16   GetXclCodePage( rtl_TextEncoding eTextEnc );

    // font names -------------------------------------------------------------

    /** Returns the matching Excel font name for a passed Calc font name. */
    static String       GetXclFontName( const String& rFontName );

    // built-in defined names -------------------------------------------------

    /** Returns the raw English UI representation of a built-in defined name used in NAME records.
        @param cBuiltIn  Excel index of the built-in name. */
    static String       GetXclBuiltInDefName( sal_Unicode cBuiltIn );
    /** Returns the Calc UI representation of a built-in defined name used in NAME records.
        @descr  Adds a prefix to the representation returned by GetXclBuiltInDefName().
        @param cBuiltIn  Excel index of the built-in name. */
    static String       GetBuiltInDefName( sal_Unicode cBuiltIn );
    /** Returns the Excel built-in name index of the passed defined name from Calc.
        @descr  Ignores any characters following a valid representation of a built-in name.
        @param pcBuiltIn  (out-param) If not 0, the index of the built-in name will be returned here.
        @return  true = passed string is a built-in name; false = user-defined name. */
    static sal_Unicode  GetBuiltInDefNameIndex( const String& rDefName );

    // built-in style names ---------------------------------------------------

    /** Returns the specified built-in cell style name.
        @param nStyleId  The identifier of the built-in style.
        @param nLevel  The zero-based outline level for RowLevel and ColLevel styles.
        @return  The style name or an empty string, if the parameters are not valid. */
    static String       GetBuiltInStyleName( sal_uInt8 nStyleId, sal_uInt8 nLevel );
    /** Returns true, if the passed string is a name of an Excel built-in style.
        @param pnStyleId  If not 0, the found style identifier will be returned here.
        @param pnNextChar  If not 0, the index of the char after the evaluated substring will be returned here. */
    static bool         IsBuiltInStyleName( const String& rStyleName, sal_uInt8* pnStyleId = 0, xub_StrLen* pnNextChar = 0 );
    /** Returns the Excel built-in style identifier of a passed style name.
        @param rnStyleId  The style identifier is returned here.
        @param rnLevel  The zero-based outline level for RowLevel and ColLevel styles is returned here.
        @param rStyleName  The style name to examine.
        @return  true = passed string is a built-in style name, false = user style. */
    static bool         GetBuiltInStyleId(
                            sal_uInt8& rnStyleId, sal_uInt8& rnLevel,
                            const String& rStyleName );

    // conditional formatting style names -------------------------------------

    /** Returns the style name for a single condition of a conditional formatting.
        @param nScTab  The current Calc sheet index.
        @param nFormat  The zero-based index of the conditional formatting.
        @param nCondition  The zero-based index of the condition.
        @return  A style sheet name in the form "Excel_CondFormat_<sheet>_<format>_<condition>". */
    static String       GetCondFormatStyleName( SCTAB nScTab, sal_Int32 nFormat, sal_uInt16 nCondition );
    /** Returns true, if the passed string is a name of a conditional format style created by Excel import.
        @param pnNextChar  If not 0, the index of the char after the evaluated substring will be returned here. */
    static bool         IsCondFormatStyleName( const String& rStyleName, xub_StrLen* pnNextChar = 0 );

    // stream handling --------------------------------------------------------

    /** Skips a substream (BOF/EOF record block). Includes all embedded substreams. */
    static void         SkipSubStream( XclImpStream& rStrm );

    // ------------------------------------------------------------------------
private:
    static const String maDefNamePrefix;        /// Prefix for built-in defined names.
    static const String maStyleNamePrefix;      /// Prefix for built-in cell style names.
    static const String maCFStyleNamePrefix;    /// Prefix for cond. formatting style names.
};

// read/write colors ----------------------------------------------------------

/** Reads a color from the passed stream.
    @descr  The color has the format (all values 8-bit): Red, Green, Blue, 0. */
XclImpStream& operator>>( XclImpStream& rStrm, Color& rColor );

/** Reads a color to the passed stream.
    @descr  The color has the format (all values 8-bit): Red, Green, Blue, 0. */
XclExpStream& operator<<( XclExpStream& rStrm, const Color& rColor );

// ============================================================================

#endif

<commit_msg>INTEGRATION: CWS chart2mst3 (1.25.26); FILE MERGED 2006/08/31 10:00:34 dr 1.25.26.2: chart2 export: text formatting, series formatting 2006/07/11 14:13:50 dr 1.25.26.1: #export of chart line and area formats<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xltools.hxx,v $
 *
 *  $Revision: 1.26 $
 *
 *  last change: $Author: vg $ $Date: 2007-05-22 20:00:34 $
 *
 *  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 SC_XLTOOLS_HXX
#define SC_XLTOOLS_HXX

#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif

#ifndef SC_FTOOLS_HXX
#include "ftools.hxx"
#endif

// BIFF versions ==============================================================

#define DBG_ERROR_BIFF()        DBG_ERRORFILE( "Unknown BIFF type!" )
#define DBG_ASSERT_BIFF( c )    DBG_ASSERT( c, "Unknown BIFF type!" )

// Enumerations ===============================================================

/** An enumeration for all Excel error codes and the values true and false. */
enum XclBoolError
{
    xlErrNull,                  /// The error code #NULL!
    xlErrDiv0,                  /// The error code #DIV/0!
    xlErrValue,                 /// The error code #VALUE!
    xlErrRef,                   /// The error code #REF!
    xlErrName,                  /// The error code #NAME?
    xlErrNum,                   /// The error code #NUM!
    xlErrNA,                    /// The error code #N/A!
    xlErrTrue,                  /// The Boolean value true.
    xlErrFalse,                 /// The Boolean value false.
    xlErrUnknown                /// For unknown codes and values.
};

// GUID import/export =========================================================

class XclImpStream;
class XclExpStream;

/** This struct stores a GUID (class ID) and supports reading, writing and comparison. */
struct XclGuid
{
    sal_uInt8           mpnData[ 16 ];  /// Stores GUID always in little endian.

    explicit            XclGuid();
    explicit            XclGuid(
                            sal_uInt32 nData1,
                            sal_uInt16 nData2, sal_uInt16 nData3,
                            sal_uInt8 nData41, sal_uInt8 nData42,
                            sal_uInt8 nData43, sal_uInt8 nData44,
                            sal_uInt8 nData45, sal_uInt8 nData46,
                            sal_uInt8 nData47, sal_uInt8 nData48 );
};

bool operator==( const XclGuid& rCmp1, const XclGuid& rCmp2 );
inline bool operator!=( const XclGuid& rCmp1, const XclGuid& rCmp2 ) { return !(rCmp1 == rCmp2); }
bool operator<( const XclGuid& rCmp1, const XclGuid& rCmp2 );

XclImpStream& operator>>( XclImpStream& rStrm, XclGuid& rGuid );
XclExpStream& operator<<( XclExpStream& rStrm, const XclGuid& rGuid );

// Excel Tools ================================================================

class SvStream;
class ScDocument;

/** This class contains static helper methods for the Excel import and export filters. */
class XclTools : ScfNoInstance
{
public:
    // GUID's -----------------------------------------------------------------

    static const XclGuid maGuidStdLink;     /// GUID of StdLink (HLINK record).
    static const XclGuid maGuidUrlMoniker;  /// GUID of URL moniker (HLINK record).
    static const XclGuid maGuidFileMoniker; /// GUID of file moniker (HLINK record).

    // numeric conversion -----------------------------------------------------

    /** Calculates the double value from an RK value (encoded integer or double). */
    static double       GetDoubleFromRK( sal_Int32 nRKValue );
    /** Calculates an RK value (encoded integer or double) from a double value.
        @param rnRKValue  Returns the calculated RK value.
        @param fValue  The double value.
        @return  true = An RK value could be created. */
    static bool         GetRKFromDouble( sal_Int32& rnRKValue, double fValue );

    /** Calculates an angle (in 1/100 of degrees) from an Excel angle value.
        @param nRotForStacked  This value will be returned, if nXclRot contains 'stacked'. */
    static sal_Int32    GetScRotation( sal_uInt16 nXclRot, sal_Int32 nRotForStacked );
    /** Calculates the Excel angle value from an angle in 1/100 of degrees. */
    static sal_uInt8    GetXclRotation( sal_Int32 nScRot );

    /** Calculates BIFF8 rotation angle from BIFF2-BIFF5 text orientation. */
    static sal_uInt8    GetXclRotFromOrient( sal_uInt8 nXclOrient );
    /** Calculates BIFF2-BIFF5 text orientation from BIFF8 rotation angle. */
    static sal_uInt8    GetXclOrientFromRot( sal_uInt16 nXclRot );

    /** Converts a Calc error code to an Excel error code. */
    static sal_uInt8    GetXclErrorCode( USHORT nScError );
    /** Converts an Excel error code to a Calc error code. */
    static USHORT       GetScErrorCode( sal_uInt8 nXclError );

    /** Gets a translated error code or Boolean value from Excel error codes.
        @param rfDblValue  Returns 0.0 for error codes or the value of a Boolean (0.0 or 1.0).
        @param bErrorOrBool  false = nError is a Boolean value; true = is an error value.
        @param nValue  The error code or Boolean value. */
    static XclBoolError ErrorToEnum( double& rfDblValue, sal_uInt8 bErrOrBool, sal_uInt8 nValue );

    /** Returns the length in twips calculated from a length in inches. */
    static sal_uInt16   GetTwipsFromInch( double fInches );
    /** Returns the length in twips calculated from a length in 1/100 mm. */
    static sal_uInt16   GetTwipsFromHmm( sal_Int32 nHmm );

    /** Returns the length in inches calculated from a length in twips. */
    static double       GetInchFromTwips( sal_Int32 nTwips );
    /** Returns the length in inches calculated from a length in 1/100 mm. */
    static double       GetInchFromHmm( sal_Int32 nHmm );

    /** Returns the length in 1/100 mm calculated from a length in inches. */
    static sal_Int32    GetHmmFromInch( double fInches );
    /** Returns the length in 1/100 mm calculated from a length in twips. */
    static sal_Int32    GetHmmFromTwips( sal_Int32 nTwips );

    /** Returns the Calc column width (twips) for the passed Excel width.
        @param nScCharWidth  Width of the '0' character in Calc (twips). */
    static USHORT       GetScColumnWidth( sal_uInt16 nXclWidth, long nScCharWidth );
    /** Returns the Excel column width for the passed Calc width (twips).
        @param nScCharWidth  Width of the '0' character in Calc (twips). */
    static sal_uInt16   GetXclColumnWidth( USHORT nScWidth, long nScCharWidth );

    /** Returns a correction value to convert column widths from/to default column widths.
        @param nXclDefFontHeight  Excel height of application default font. */
    static double       GetXclDefColWidthCorrection( long nXclDefFontHeight );

    // formatting -------------------------------------------------------------

    /** Returns the best fitting color for an Excel pattern area format. */
    static Color        GetPatternColor( const Color& rPattColor, const Color& rBackColor, sal_uInt16 nXclPattern );

    // text encoding ----------------------------------------------------------

    /** Returns a text encoding from an Excel code page.
        @return  The corresponding text encoding or RTL_TEXTENCODING_DONTKNOW. */
    static rtl_TextEncoding GetTextEncoding( sal_uInt16 nCodePage );
    /** Returns an Excel code page from a text encoding. */
    static sal_uInt16   GetXclCodePage( rtl_TextEncoding eTextEnc );

    // font names -------------------------------------------------------------

    /** Returns the matching Excel font name for a passed Calc font name. */
    static String       GetXclFontName( const String& rFontName );

    // built-in defined names -------------------------------------------------

    /** Returns the raw English UI representation of a built-in defined name used in NAME records.
        @param cBuiltIn  Excel index of the built-in name. */
    static String       GetXclBuiltInDefName( sal_Unicode cBuiltIn );
    /** Returns the Calc UI representation of a built-in defined name used in NAME records.
        @descr  Adds a prefix to the representation returned by GetXclBuiltInDefName().
        @param cBuiltIn  Excel index of the built-in name. */
    static String       GetBuiltInDefName( sal_Unicode cBuiltIn );
    /** Returns the Excel built-in name index of the passed defined name from Calc.
        @descr  Ignores any characters following a valid representation of a built-in name.
        @param pcBuiltIn  (out-param) If not 0, the index of the built-in name will be returned here.
        @return  true = passed string is a built-in name; false = user-defined name. */
    static sal_Unicode  GetBuiltInDefNameIndex( const String& rDefName );

    // built-in style names ---------------------------------------------------

    /** Returns the specified built-in cell style name.
        @param nStyleId  The identifier of the built-in style.
        @param nLevel  The zero-based outline level for RowLevel and ColLevel styles.
        @return  The style name or an empty string, if the parameters are not valid. */
    static String       GetBuiltInStyleName( sal_uInt8 nStyleId, sal_uInt8 nLevel );
    /** Returns true, if the passed string is a name of an Excel built-in style.
        @param pnStyleId  If not 0, the found style identifier will be returned here.
        @param pnNextChar  If not 0, the index of the char after the evaluated substring will be returned here. */
    static bool         IsBuiltInStyleName( const String& rStyleName, sal_uInt8* pnStyleId = 0, xub_StrLen* pnNextChar = 0 );
    /** Returns the Excel built-in style identifier of a passed style name.
        @param rnStyleId  The style identifier is returned here.
        @param rnLevel  The zero-based outline level for RowLevel and ColLevel styles is returned here.
        @param rStyleName  The style name to examine.
        @return  true = passed string is a built-in style name, false = user style. */
    static bool         GetBuiltInStyleId(
                            sal_uInt8& rnStyleId, sal_uInt8& rnLevel,
                            const String& rStyleName );

    // conditional formatting style names -------------------------------------

    /** Returns the style name for a single condition of a conditional formatting.
        @param nScTab  The current Calc sheet index.
        @param nFormat  The zero-based index of the conditional formatting.
        @param nCondition  The zero-based index of the condition.
        @return  A style sheet name in the form "Excel_CondFormat_<sheet>_<format>_<condition>". */
    static String       GetCondFormatStyleName( SCTAB nScTab, sal_Int32 nFormat, sal_uInt16 nCondition );
    /** Returns true, if the passed string is a name of a conditional format style created by Excel import.
        @param pnNextChar  If not 0, the index of the char after the evaluated substring will be returned here. */
    static bool         IsCondFormatStyleName( const String& rStyleName, xub_StrLen* pnNextChar = 0 );

    // stream handling --------------------------------------------------------

    /** Skips a substream (BOF/EOF record block). Includes all embedded substreams. */
    static void         SkipSubStream( XclImpStream& rStrm );

    // ------------------------------------------------------------------------
private:
    static const String maDefNamePrefix;        /// Prefix for built-in defined names.
    static const String maStyleNamePrefix;      /// Prefix for built-in cell style names.
    static const String maCFStyleNamePrefix;    /// Prefix for cond. formatting style names.
};

// read/write colors ----------------------------------------------------------

/** Reads a color from the passed stream.
    @descr  The color has the format (all values 8-bit): Red, Green, Blue, 0. */
XclImpStream& operator>>( XclImpStream& rStrm, Color& rColor );

/** Reads a color to the passed stream.
    @descr  The color has the format (all values 8-bit): Red, Green, Blue, 0. */
XclExpStream& operator<<( XclExpStream& rStrm, const Color& rColor );

// ============================================================================

#endif

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: xmlcoli.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: vg $ $Date: 2005-03-23 12:56: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_XMLCOLI_HXX
#define SC_XMLCOLI_HXX

#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif

#ifndef _XMLOFF_XMLIMP_HXX
#include <xmloff/xmlimp.hxx>
#endif

class ScXMLImport;

class ScXMLTableColContext : public SvXMLImportContext
{
    sal_Int32               nColCount;
    rtl::OUString           sStyleName;
    rtl::OUString           sVisibility;
    rtl::OUString           sCellStyleName;

    const ScXMLImport& GetScImport() const { return (const ScXMLImport&)GetImport(); }
    ScXMLImport& GetScImport() { return (ScXMLImport&)GetImport(); }

public:

    ScXMLTableColContext( ScXMLImport& rImport, USHORT nPrfx,
                       const ::rtl::OUString& rLName,
                       const ::com::sun::star::uno::Reference<
                                        ::com::sun::star::xml::sax::XAttributeList>& xAttrList );

    virtual ~ScXMLTableColContext();

    virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix,
                                     const ::rtl::OUString& rLocalName,
                                     const ::com::sun::star::uno::Reference<
                                          ::com::sun::star::xml::sax::XAttributeList>& xAttrList );

    virtual void EndElement();
};

class ScXMLTableColsContext : public SvXMLImportContext
{
    sal_Int32   nHeaderStartCol;
    sal_Int32   nHeaderEndCol;
    sal_Int32   nGroupStartCol;
    sal_Int32   nGroupEndCol;
    sal_Bool    bHeader;
    sal_Bool    bGroup;
    sal_Bool    bGroupDisplay;

    const ScXMLImport& GetScImport() const { return (const ScXMLImport&)GetImport(); }
    ScXMLImport& GetScImport() { return (ScXMLImport&)GetImport(); }

public:

    ScXMLTableColsContext( ScXMLImport& rImport, USHORT nPrfx,
                       const ::rtl::OUString& rLName,
                       const ::com::sun::star::uno::Reference<
                                        ::com::sun::star::xml::sax::XAttributeList>& xAttrList,
                        const sal_Bool bHeader, const sal_Bool bGroup);

    virtual ~ScXMLTableColsContext();

    virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix,
                                     const ::rtl::OUString& rLocalName,
                                     const ::com::sun::star::uno::Reference<
                                          ::com::sun::star::xml::sax::XAttributeList>& xAttrList );

    virtual void EndElement();
};

#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.7.116); FILE MERGED 2005/09/05 15:03:33 rt 1.7.116.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xmlcoli.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 20:04:45 $
 *
 *  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 SC_XMLCOLI_HXX
#define SC_XMLCOLI_HXX

#ifndef _XMLOFF_XMLICTXT_HXX
#include <xmloff/xmlictxt.hxx>
#endif

#ifndef _XMLOFF_XMLIMP_HXX
#include <xmloff/xmlimp.hxx>
#endif

class ScXMLImport;

class ScXMLTableColContext : public SvXMLImportContext
{
    sal_Int32               nColCount;
    rtl::OUString           sStyleName;
    rtl::OUString           sVisibility;
    rtl::OUString           sCellStyleName;

    const ScXMLImport& GetScImport() const { return (const ScXMLImport&)GetImport(); }
    ScXMLImport& GetScImport() { return (ScXMLImport&)GetImport(); }

public:

    ScXMLTableColContext( ScXMLImport& rImport, USHORT nPrfx,
                       const ::rtl::OUString& rLName,
                       const ::com::sun::star::uno::Reference<
                                        ::com::sun::star::xml::sax::XAttributeList>& xAttrList );

    virtual ~ScXMLTableColContext();

    virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix,
                                     const ::rtl::OUString& rLocalName,
                                     const ::com::sun::star::uno::Reference<
                                          ::com::sun::star::xml::sax::XAttributeList>& xAttrList );

    virtual void EndElement();
};

class ScXMLTableColsContext : public SvXMLImportContext
{
    sal_Int32   nHeaderStartCol;
    sal_Int32   nHeaderEndCol;
    sal_Int32   nGroupStartCol;
    sal_Int32   nGroupEndCol;
    sal_Bool    bHeader;
    sal_Bool    bGroup;
    sal_Bool    bGroupDisplay;

    const ScXMLImport& GetScImport() const { return (const ScXMLImport&)GetImport(); }
    ScXMLImport& GetScImport() { return (ScXMLImport&)GetImport(); }

public:

    ScXMLTableColsContext( ScXMLImport& rImport, USHORT nPrfx,
                       const ::rtl::OUString& rLName,
                       const ::com::sun::star::uno::Reference<
                                        ::com::sun::star::xml::sax::XAttributeList>& xAttrList,
                        const sal_Bool bHeader, const sal_Bool bGroup);

    virtual ~ScXMLTableColsContext();

    virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix,
                                     const ::rtl::OUString& rLocalName,
                                     const ::com::sun::star::uno::Reference<
                                          ::com::sun::star::xml::sax::XAttributeList>& xAttrList );

    virtual void EndElement();
};

#endif
<|endoftext|>