<commit_before>#include <sstream>

#include "Tools/Exception/exception.hpp"

#include "Codec_polar.hpp"

using namespace aff3ct;
using namespace aff3ct::module;

template <typename B, typename Q>
Codec_polar<B,Q>
::Codec_polar(const factory::Frozenbits_generator::parameters &fb_params,
              const factory::Encoder_polar       ::parameters &enc_params,
              const factory::Decoder_polar       ::parameters &dec_params,
              const factory::Puncturer_polar     ::parameters *pct_params,
              CRC<B>* crc)
: Codec          <B,Q>(enc_params.K, enc_params.N_cw, pct_params ? pct_params->N : enc_params.N_cw, enc_params.tail_length, enc_params.n_frames),
  Codec_SISO_SIHO<B,Q>(enc_params.K, enc_params.N_cw, pct_params ? pct_params->N : enc_params.N_cw, enc_params.tail_length, enc_params.n_frames),
  adaptive_fb(fb_params.sigma == -1.f),
  frozen_bits(fb_params.N_cw, true),
  generated_decoder((dec_params.implem.find("_SNR") != std::string::npos)),
  fb_generator     (nullptr),
  puncturer_wangliu(nullptr),
  fb_decoder       (nullptr),
  fb_encoder       (nullptr)
{
	const std::string name = "Codec_polar";
	this->set_name(name);

	// ----------------------------------------------------------------------------------------------------- exceptions
	if (enc_params.K != dec_params.K)
	{
		std::stringstream message;
		message << "'enc_params.K' has to be equal to 'dec_params.K' ('enc_params.K' = " << enc_params.K
		        << ", 'dec_params.K' = " << dec_params.K << ").";
		throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());
	}

	if (enc_params.N_cw != dec_params.N_cw)
	{
		std::stringstream message;
		message << "'enc_params.N_cw' has to be equal to 'dec_params.N_cw' ('enc_params.N_cw' = " << enc_params.N_cw
		        << ", 'dec_params.N_cw' = " << dec_params.N_cw << ").";
		throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());
	}

	if (enc_params.n_frames != dec_params.n_frames)
	{
		std::stringstream message;
		message << "'enc_params.n_frames' has to be equal to 'dec_params.n_frames' ('enc_params.n_frames' = "
		        << enc_params.n_frames << ", 'dec_params.n_frames' = " << dec_params.n_frames << ").";
		throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());
	}

	// ---------------------------------------------------------------------------------------------------------- tools
	if (!generated_decoder)
		// build the frozen bits generator
		fb_generator = factory::Frozenbits_generator::build(fb_params);
	else
		if (this->N_cw != this->N)
		{
			std::stringstream message;
			message << "'N_cw' has to be equal to 'N' ('N_cw' = " << this->N_cw << ", 'N' = "
			        << this->N << ").";
			throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());
		}

	// ---------------------------------------------------------------------------------------------------- allocations
	std::fill(frozen_bits.begin(), frozen_bits.begin() + this->K, false);

	if (generated_decoder || !pct_params)
	{
		factory::Puncturer::parameters pctno_params;
		pctno_params.type     = "NO";
		pctno_params.K        = enc_params.K;
		pctno_params.N        = enc_params.N_cw;
		pctno_params.N_cw     = enc_params.N_cw;
		pctno_params.n_frames = enc_params.n_frames;

		this->set_puncturer(factory::Puncturer::build<B,Q>(pctno_params));
	}
	else
	{
		try
		{
			puncturer_wangliu = factory::Puncturer_polar::build<B,Q>(*pct_params, *fb_generator);
			this->set_puncturer(puncturer_wangliu);
		}
		catch(tools::cannot_allocate const&)
		{
			this->set_puncturer(factory::Puncturer::build<B,Q>(*pct_params));
		}
	}

	try
	{
		auto *encoder_polar = factory::Encoder_polar::build<B>(enc_params, frozen_bits);
		this->fb_encoder = encoder_polar;
		this->set_encoder(encoder_polar);
	}
	catch (tools::cannot_allocate const&)
	{
		this->set_encoder(factory::Encoder::build<B>(enc_params));
	}

	try
	{
		auto decoder_siso_siho = factory::Decoder_polar::build_siso<B,Q>(dec_params, frozen_bits, this->get_encoder());
		this->set_decoder_siso(decoder_siso_siho);
		this->set_decoder_siho(decoder_siso_siho);
	}
	catch (const std::exception&)
	{
		if (generated_decoder)
			this->set_decoder_siho(factory::Decoder_polar::build_gen<B,Q>(dec_params,              crc, this->get_encoder()));
		else
			this->set_decoder_siho(factory::Decoder_polar::build    <B,Q>(dec_params, frozen_bits, crc, this->get_encoder()));
	}
	if (dec_params.type != "ML")
		this->fb_decoder = dynamic_cast<tools::Frozenbits_notifier*>(this->get_decoder_siho());

	// ------------------------------------------------------------------------------------------------- frozen bit gen
	if (!generated_decoder)
	{
		if (!adaptive_fb)
		{
			fb_generator->generate(frozen_bits);
			if (this->N_cw != this->N)
				puncturer_wangliu->gen_frozen_bits(frozen_bits);
			this->notify_frozenbits_update();
		}
	}
	else
	{
		const auto fb = factory::Decoder_polar::get_frozen_bits(dec_params.implem);
		if (fb.size() != frozen_bits.size())
		{
			std::stringstream message;
			message << "'fb.size()' has to be equal to 'frozen_bits.size()' ('fb.size()' = " << fb.size()
			        << ", 'frozen_bits.size()' = " << frozen_bits.size() << ").";
			throw tools::runtime_error(__FILE__, __LINE__, __func__, message.str());
		}
		std::copy(fb.begin(), fb.end(), frozen_bits.begin());
		this->notify_frozenbits_update();
	}
}

template <typename B, typename Q>
Codec_polar<B,Q>
::~Codec_polar()
{
	if (fb_generator != nullptr) { delete fb_generator; fb_generator = nullptr; }
}

template <typename B, typename Q>
void Codec_polar<B,Q>
::notify_frozenbits_update()
{
	if (this->N_cw != this->N)
		puncturer_wangliu->gen_frozen_bits(frozen_bits);
	if (this->fb_decoder)
		this->fb_decoder->notify_frozenbits_update();
	if (this->fb_encoder)
		this->fb_encoder->notify_frozenbits_update();
}

template <typename B, typename Q>
void Codec_polar<B,Q>
::set_sigma(const float sigma)
{
	Codec_SISO_SIHO<B,Q>::set_sigma(sigma);

	// adaptive frozen bits generation
	if (adaptive_fb && !generated_decoder)
	{
		fb_generator->set_sigma(sigma);
		fb_generator->generate(frozen_bits);

		this->notify_frozenbits_update();
	}
}

template <typename B, typename Q>
std::vector<bool>& Codec_polar<B,Q>
::get_frozen_bits()
{
	return this->frozen_bits;
}

template <typename B, typename Q>
void Codec_polar<B,Q>
::_extract_sys_par(const Q* Y_N, Q* sys, Q* par, const int frame_id)
{
	auto par_idx = 0, sys_idx = 0;
	auto N_cw = this->N_cw;

	for (auto i = 0; i < N_cw; i++)
	{
		if (!frozen_bits[i])
		{
			sys[sys_idx] = Y_N[i];
			sys_idx++;
		}
		else // parity bit
		{
			par[par_idx] = Y_N[i];
			par_idx++;
		}
	}
}

template <typename B, typename Q>
void Codec_polar<B,Q>
::_extract_sys_llr(const Q* Y_N, Q* sys, const int frame_id)
{
	auto sys_idx = 0;
	auto N_cw = this->N_cw;

	for (auto i = 0; i < N_cw; i++)
	{
		if (!frozen_bits[i])
		{
			sys[sys_idx] = Y_N[i];
			sys_idx++;
		}
	}
}

template <typename B, typename Q>
void Codec_polar<B,Q>
::_add_sys_ext(const Q* ext, Q* Y_N, const int frame_id)
{
	auto sys_idx = 0;
	for (auto i = 0; i < this->N_cw; i++)
		if (!frozen_bits[i])
		{
			Y_N[i] += ext[sys_idx];
			sys_idx++;
		}
}

// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef MULTI_PREC
template class aff3ct::module::Codec_polar<B_8,Q_8>;
template class aff3ct::module::Codec_polar<B_16,Q_16>;
template class aff3ct::module::Codec_polar<B_32,Q_32>;
template class aff3ct::module::Codec_polar<B_64,Q_64>;
#else
template class aff3ct::module::Codec_polar<B,Q>;
#endif
// ==================================================================================== explicit template instantiation
<commit_msg>Rm useless processing.<commit_after>#include <sstream>

#include "Tools/Exception/exception.hpp"

#include "Codec_polar.hpp"

using namespace aff3ct;
using namespace aff3ct::module;

template <typename B, typename Q>
Codec_polar<B,Q>
::Codec_polar(const factory::Frozenbits_generator::parameters &fb_params,
              const factory::Encoder_polar       ::parameters &enc_params,
              const factory::Decoder_polar       ::parameters &dec_params,
              const factory::Puncturer_polar     ::parameters *pct_params,
              CRC<B>* crc)
: Codec          <B,Q>(enc_params.K, enc_params.N_cw, pct_params ? pct_params->N : enc_params.N_cw, enc_params.tail_length, enc_params.n_frames),
  Codec_SISO_SIHO<B,Q>(enc_params.K, enc_params.N_cw, pct_params ? pct_params->N : enc_params.N_cw, enc_params.tail_length, enc_params.n_frames),
  adaptive_fb(fb_params.sigma == -1.f),
  frozen_bits(fb_params.N_cw, true),
  generated_decoder((dec_params.implem.find("_SNR") != std::string::npos)),
  fb_generator     (nullptr),
  puncturer_wangliu(nullptr),
  fb_decoder       (nullptr),
  fb_encoder       (nullptr)
{
	const std::string name = "Codec_polar";
	this->set_name(name);

	// ----------------------------------------------------------------------------------------------------- exceptions
	if (enc_params.K != dec_params.K)
	{
		std::stringstream message;
		message << "'enc_params.K' has to be equal to 'dec_params.K' ('enc_params.K' = " << enc_params.K
		        << ", 'dec_params.K' = " << dec_params.K << ").";
		throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());
	}

	if (enc_params.N_cw != dec_params.N_cw)
	{
		std::stringstream message;
		message << "'enc_params.N_cw' has to be equal to 'dec_params.N_cw' ('enc_params.N_cw' = " << enc_params.N_cw
		        << ", 'dec_params.N_cw' = " << dec_params.N_cw << ").";
		throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());
	}

	if (enc_params.n_frames != dec_params.n_frames)
	{
		std::stringstream message;
		message << "'enc_params.n_frames' has to be equal to 'dec_params.n_frames' ('enc_params.n_frames' = "
		        << enc_params.n_frames << ", 'dec_params.n_frames' = " << dec_params.n_frames << ").";
		throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());
	}

	// ---------------------------------------------------------------------------------------------------------- tools
	if (!generated_decoder)
		// build the frozen bits generator
		fb_generator = factory::Frozenbits_generator::build(fb_params);
	else
		if (this->N_cw != this->N)
		{
			std::stringstream message;
			message << "'N_cw' has to be equal to 'N' ('N_cw' = " << this->N_cw << ", 'N' = "
			        << this->N << ").";
			throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());
		}

	// ---------------------------------------------------------------------------------------------------- allocations
	std::fill(frozen_bits.begin(), frozen_bits.begin() + this->K, false);

	if (generated_decoder || !pct_params)
	{
		factory::Puncturer::parameters pctno_params;
		pctno_params.type     = "NO";
		pctno_params.K        = enc_params.K;
		pctno_params.N        = enc_params.N_cw;
		pctno_params.N_cw     = enc_params.N_cw;
		pctno_params.n_frames = enc_params.n_frames;

		this->set_puncturer(factory::Puncturer::build<B,Q>(pctno_params));
	}
	else
	{
		try
		{
			puncturer_wangliu = factory::Puncturer_polar::build<B,Q>(*pct_params, *fb_generator);
			this->set_puncturer(puncturer_wangliu);
		}
		catch(tools::cannot_allocate const&)
		{
			this->set_puncturer(factory::Puncturer::build<B,Q>(*pct_params));
		}
	}

	try
	{
		auto *encoder_polar = factory::Encoder_polar::build<B>(enc_params, frozen_bits);
		this->fb_encoder = encoder_polar;
		this->set_encoder(encoder_polar);
	}
	catch (tools::cannot_allocate const&)
	{
		this->set_encoder(factory::Encoder::build<B>(enc_params));
	}

	try
	{
		auto decoder_siso_siho = factory::Decoder_polar::build_siso<B,Q>(dec_params, frozen_bits, this->get_encoder());
		this->set_decoder_siso(decoder_siso_siho);
		this->set_decoder_siho(decoder_siso_siho);
	}
	catch (const std::exception&)
	{
		if (generated_decoder)
			this->set_decoder_siho(factory::Decoder_polar::build_gen<B,Q>(dec_params,              crc, this->get_encoder()));
		else
			this->set_decoder_siho(factory::Decoder_polar::build    <B,Q>(dec_params, frozen_bits, crc, this->get_encoder()));
	}
	if (dec_params.type != "ML")
		this->fb_decoder = dynamic_cast<tools::Frozenbits_notifier*>(this->get_decoder_siho());

	// ------------------------------------------------------------------------------------------------- frozen bit gen
	if (!generated_decoder)
	{
		if (!adaptive_fb)
		{
			fb_generator->generate(frozen_bits);
			this->notify_frozenbits_update();
		}
	}
	else
	{
		const auto fb = factory::Decoder_polar::get_frozen_bits(dec_params.implem);
		if (fb.size() != frozen_bits.size())
		{
			std::stringstream message;
			message << "'fb.size()' has to be equal to 'frozen_bits.size()' ('fb.size()' = " << fb.size()
			        << ", 'frozen_bits.size()' = " << frozen_bits.size() << ").";
			throw tools::runtime_error(__FILE__, __LINE__, __func__, message.str());
		}
		std::copy(fb.begin(), fb.end(), frozen_bits.begin());
		this->notify_frozenbits_update();
	}
}

template <typename B, typename Q>
Codec_polar<B,Q>
::~Codec_polar()
{
	if (fb_generator != nullptr) { delete fb_generator; fb_generator = nullptr; }
}

template <typename B, typename Q>
void Codec_polar<B,Q>
::notify_frozenbits_update()
{
	if (this->N_cw != this->N)
		puncturer_wangliu->gen_frozen_bits(frozen_bits);
	if (this->fb_decoder)
		this->fb_decoder->notify_frozenbits_update();
	if (this->fb_encoder)
		this->fb_encoder->notify_frozenbits_update();
}

template <typename B, typename Q>
void Codec_polar<B,Q>
::set_sigma(const float sigma)
{
	Codec_SISO_SIHO<B,Q>::set_sigma(sigma);

	// adaptive frozen bits generation
	if (adaptive_fb && !generated_decoder)
	{
		fb_generator->set_sigma(sigma);
		fb_generator->generate(frozen_bits);

		this->notify_frozenbits_update();
	}
}

template <typename B, typename Q>
std::vector<bool>& Codec_polar<B,Q>
::get_frozen_bits()
{
	return this->frozen_bits;
}

template <typename B, typename Q>
void Codec_polar<B,Q>
::_extract_sys_par(const Q* Y_N, Q* sys, Q* par, const int frame_id)
{
	auto par_idx = 0, sys_idx = 0;
	auto N_cw = this->N_cw;

	for (auto i = 0; i < N_cw; i++)
	{
		if (!frozen_bits[i])
		{
			sys[sys_idx] = Y_N[i];
			sys_idx++;
		}
		else // parity bit
		{
			par[par_idx] = Y_N[i];
			par_idx++;
		}
	}
}

template <typename B, typename Q>
void Codec_polar<B,Q>
::_extract_sys_llr(const Q* Y_N, Q* sys, const int frame_id)
{
	auto sys_idx = 0;
	auto N_cw = this->N_cw;

	for (auto i = 0; i < N_cw; i++)
	{
		if (!frozen_bits[i])
		{
			sys[sys_idx] = Y_N[i];
			sys_idx++;
		}
	}
}

template <typename B, typename Q>
void Codec_polar<B,Q>
::_add_sys_ext(const Q* ext, Q* Y_N, const int frame_id)
{
	auto sys_idx = 0;
	for (auto i = 0; i < this->N_cw; i++)
		if (!frozen_bits[i])
		{
			Y_N[i] += ext[sys_idx];
			sys_idx++;
		}
}

// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef MULTI_PREC
template class aff3ct::module::Codec_polar<B_8,Q_8>;
template class aff3ct::module::Codec_polar<B_16,Q_16>;
template class aff3ct::module::Codec_polar<B_32,Q_32>;
template class aff3ct::module::Codec_polar<B_64,Q_64>;
#else
template class aff3ct::module::Codec_polar<B,Q>;
#endif
// ==================================================================================== explicit template instantiation
<|endoftext|>


<commit_before>#include "stxxl/bits/common/debug.h"

__STXXL_BEGIN_NAMESPACE

debugmon * debugmon::instance = NULL;

#ifndef STXXL_DEBUGMON
void debugmon::block_allocated(char * /*ptr*/, char * /*end*/, size_t /*size*/)
{ }
void debugmon::block_deallocated(char * /*ptr*/)
{ }
void debugmon::io_started(char * /*ptr*/)
{ }
void debugmon::io_finished(char * /*ptr*/)
{ }
#else
void debugmon::block_allocated(char * ptr, char * end, size_t size)
{
 #ifdef STXXL_BOOST_THREADS
    boost::mutex::scoped_lock Lock(mutex1);
 #else
    mutex1.lock();
 #endif
// checks are here
    STXXL_VERBOSE1("debugmon: block " << long (ptr) << " allocated");
    assert(tags.find(ptr) == tags.end());             // not allocated
    tag t;
    t.ongoing = false;
    t.end = end;
    t.size = size;
    tags[ptr] = t;
 #ifndef STXXL_BOOST_THREADS
    mutex1.unlock();
 #endif
}
void debugmon::block_deallocated(char * ptr)
{
 #ifdef STXXL_BOOST_THREADS
    boost::mutex::scoped_lock Lock(mutex1);
 #else
    mutex1.lock();
 #endif

    STXXL_VERBOSE1("debugmon: block_deallocated from " << long (ptr));
    assert(tags.find(ptr) != tags.end());             // allocated
    tag t = tags[ptr];
    assert(t.ongoing == false);             // not ongoing
    tags.erase(ptr);
    size_t size = t.size;
    STXXL_VERBOSE1("debugmon: block_deallocated to " << long (t.end));
    char * endptr = (char *) t.end;
    char * ptr1 = (char *) ptr;
    ptr1 += size;
    while (ptr1 < endptr)
    {
        STXXL_VERBOSE1("debugmon: block_deallocated next " << long (ptr1));
        assert(tags.find(ptr1) != tags.end());                 // allocated
        tag t = tags[ptr1];
        assert(t.ongoing == false);                 // not ongoing
        assert(t.size == size);                 // chunk size
        assert(t.end == endptr);                 // array end address
        tags.erase(ptr1);
        ptr1 += size;
    }
 #ifndef STXXL_BOOST_THREADS
    mutex1.unlock();
 #endif
}
void debugmon::io_started(char * ptr)
{
 #ifdef STXXL_BOOST_THREADS
    boost::mutex::scoped_lock Lock(mutex1);
 #else
    mutex1.lock();
 #endif

    STXXL_VERBOSE1("debugmon: I/O on block " << long (ptr) << " started");
    assert(tags.find(ptr) != tags.end());             // allocated
    tag t = tags[ptr];
    //assert(t.ongoing == false); // not ongoing
    if (t.ongoing == true)
        STXXL_ERRMSG("debugmon: I/O on block " << long (ptr) << " started, but block is already busy");
    t.ongoing = true;

    tags[ptr] = t;

 #ifndef STXXL_BOOST_THREADS
    mutex1.unlock();
 #endif
}
void debugmon::io_finished(char * ptr)
{
 #ifdef STXXL_BOOST_THREADS
    boost::mutex::scoped_lock Lock(mutex1);
 #else
    mutex1.lock();
 #endif

    STXXL_VERBOSE1("debugmon: I/O on block " << long (ptr) << " finished");
    assert(tags.find(ptr) != tags.end());             // allocated
    tag t = tags[ptr];
    //assert(t.ongoing == true); // ongoing
    if (t.ongoing == false)
        STXXL_ERRMSG("debugmon: I/O on block " << long (ptr) << " finished, but block was not busy");
    t.ongoing = false;

    tags[ptr] = t;

 #ifndef STXXL_BOOST_THREADS
    mutex1.unlock();
 #endif
}
#endif

__STXXL_END_NAMESPACE
<commit_msg>added missing utils.h include in debug.cpp<commit_after>#include "stxxl/bits/common/debug.h"
#include "stxxl/bits/common/utils.h"

__STXXL_BEGIN_NAMESPACE

debugmon * debugmon::instance = NULL;

#ifndef STXXL_DEBUGMON
void debugmon::block_allocated(char * /*ptr*/, char * /*end*/, size_t /*size*/)
{ }
void debugmon::block_deallocated(char * /*ptr*/)
{ }
void debugmon::io_started(char * /*ptr*/)
{ }
void debugmon::io_finished(char * /*ptr*/)
{ }
#else
void debugmon::block_allocated(char * ptr, char * end, size_t size)
{
 #ifdef STXXL_BOOST_THREADS
    boost::mutex::scoped_lock Lock(mutex1);
 #else
    mutex1.lock();
 #endif
// checks are here
    STXXL_VERBOSE1("debugmon: block " << long (ptr) << " allocated");
    assert(tags.find(ptr) == tags.end());             // not allocated
    tag t;
    t.ongoing = false;
    t.end = end;
    t.size = size;
    tags[ptr] = t;
 #ifndef STXXL_BOOST_THREADS
    mutex1.unlock();
 #endif
}
void debugmon::block_deallocated(char * ptr)
{
 #ifdef STXXL_BOOST_THREADS
    boost::mutex::scoped_lock Lock(mutex1);
 #else
    mutex1.lock();
 #endif

    STXXL_VERBOSE1("debugmon: block_deallocated from " << long (ptr));
    assert(tags.find(ptr) != tags.end());             // allocated
    tag t = tags[ptr];
    assert(t.ongoing == false);             // not ongoing
    tags.erase(ptr);
    size_t size = t.size;
    STXXL_VERBOSE1("debugmon: block_deallocated to " << long (t.end));
    char * endptr = (char *) t.end;
    char * ptr1 = (char *) ptr;
    ptr1 += size;
    while (ptr1 < endptr)
    {
        STXXL_VERBOSE1("debugmon: block_deallocated next " << long (ptr1));
        assert(tags.find(ptr1) != tags.end());                 // allocated
        tag t = tags[ptr1];
        assert(t.ongoing == false);                 // not ongoing
        assert(t.size == size);                 // chunk size
        assert(t.end == endptr);                 // array end address
        tags.erase(ptr1);
        ptr1 += size;
    }
 #ifndef STXXL_BOOST_THREADS
    mutex1.unlock();
 #endif
}
void debugmon::io_started(char * ptr)
{
 #ifdef STXXL_BOOST_THREADS
    boost::mutex::scoped_lock Lock(mutex1);
 #else
    mutex1.lock();
 #endif

    STXXL_VERBOSE1("debugmon: I/O on block " << long (ptr) << " started");
    assert(tags.find(ptr) != tags.end());             // allocated
    tag t = tags[ptr];
    //assert(t.ongoing == false); // not ongoing
    if (t.ongoing == true)
        STXXL_ERRMSG("debugmon: I/O on block " << long (ptr) << " started, but block is already busy");
    t.ongoing = true;

    tags[ptr] = t;

 #ifndef STXXL_BOOST_THREADS
    mutex1.unlock();
 #endif
}
void debugmon::io_finished(char * ptr)
{
 #ifdef STXXL_BOOST_THREADS
    boost::mutex::scoped_lock Lock(mutex1);
 #else
    mutex1.lock();
 #endif

    STXXL_VERBOSE1("debugmon: I/O on block " << long (ptr) << " finished");
    assert(tags.find(ptr) != tags.end());             // allocated
    tag t = tags[ptr];
    //assert(t.ongoing == true); // ongoing
    if (t.ongoing == false)
        STXXL_ERRMSG("debugmon: I/O on block " << long (ptr) << " finished, but block was not busy");
    t.ongoing = false;

    tags[ptr] = t;

 #ifndef STXXL_BOOST_THREADS
    mutex1.unlock();
 #endif
}
#endif

__STXXL_END_NAMESPACE
<|endoftext|>


<commit_before><commit_msg>scope header file paths<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: lotimpop.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 19:41: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
 *
 ************************************************************************/
#include "lotimpop.hxx"

#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif

#include "attrib.hxx"
#include "document.hxx"
#include "rangenam.hxx"
#include "cell.hxx"
#include "patattr.hxx"
#include "docpool.hxx"
#include "compiler.hxx"
#include "global.hxx"

#include "root.hxx"
#include "lotfntbf.hxx"
#include "lotform.hxx"
#include "tool.h"
#include "namebuff.hxx"
#include "lotrange.hxx"
#include "lotattr.hxx"

static NAMESPACE_VOS( OMutex )      aLotImpSemaphore;

ImportLotus::ImportLotus( SvStream& aStream, ScDocument* pDoc, CharSet eQ ) :
    ImportTyp( pDoc, eQ ),
    pIn( &aStream ),
    aConv( *pIn, eQ, FALSE )
{
    // good point to start locking of import lotus
    aLotImpSemaphore.acquire();

    pLotusRoot = new LOTUS_ROOT;
    pLotusRoot->pDoc = pDoc;
    pLotusRoot->pRangeNames = new LotusRangeList;
    pLotusRoot->pScRangeName = pDoc->GetRangeName();
    pLotusRoot->eCharsetQ = eQ;
    pLotusRoot->eFirstType = Lotus_X;
    pLotusRoot->eActType = Lotus_X;
    pLotusRoot->pRngNmBffWK3 = new RangeNameBufferWK3;
    pFontBuff = pLotusRoot->pFontBuff = new LotusFontBuffer;
    pLotusRoot->pAttrTable = new LotAttrTable;
}

ImportLotus::~ImportLotus()
{
    delete pLotusRoot->pRangeNames;
    delete pLotusRoot->pRngNmBffWK3;
    delete pFontBuff;
    delete pLotusRoot->pAttrTable;
    delete pLotusRoot;

#ifdef DBG_UTIL
    pLotusRoot = NULL;
#endif

    // no need 4 pLotusRoot anymore
    aLotImpSemaphore.release();
}

void ImportLotus::Bof( void )
{
    UINT16  nFileCode, nFileSub, nSaveCnt;
    BYTE    nMajorId, nMinorId, nFlags;

    Read( nFileCode );
    Read( nFileSub );
    Read( pLotusRoot->aActRange );
    Read( nSaveCnt );
    Read( nMajorId );
    Read( nMinorId );
    Skip( 1 );
    Read( nFlags );

    if( nFileSub == 0x0004 )
    {
        if( nFileCode == 0x1000 )
        {// <= WK3
            pLotusRoot->eFirstType = pLotusRoot->eActType = Lotus_WK3;
        }
        else if( nFileCode == 0x1002 )
        {// WK4
            pLotusRoot->eFirstType = pLotusRoot->eActType = Lotus_WK4;
        }
    }
}

BOOL ImportLotus::BofFm3( void )
{
    UINT16  nFileCode, nFileSub;

    Read( nFileCode );
    Read( nFileSub );

    return ( nFileCode == 0x8007 && ( nFileSub == 0x0000 || nFileSub == 0x00001 ) );
}

void ImportLotus::Columnwidth( UINT16 nRecLen )
{
    DBG_ASSERT( nRecLen >= 4, "*ImportLotus::Columnwidth(): Record zu kurz!" );

    BYTE    nTab, nWindow2;
    UINT16  nCnt = ( nRecLen - 4 ) / 2;

    Read( nTab );
    Read( nWindow2 );

    if( !pD->HasTable( static_cast<SCTAB> (nTab) ) )
        pD->MakeTable( static_cast<SCTAB> (nTab) );

    if( !nWindow2 )
    {
        Skip( 2 );

        BYTE    nCol, nSpaces;

        while( nCnt )
        {
            Read( nCol );
            Read( nSpaces );
            // ACHTUNG: Korrekturfaktor nach 'Augenmass' ermittelt!
            pD->SetColWidth( static_cast<SCCOL> (nCol), static_cast<SCTAB> (nTab), ( UINT16 ) ( TWIPS_PER_CHAR * 1.28 * nSpaces ) );

            nCnt--;
        }
    }
}

void ImportLotus::Hiddencolumn( UINT16 nRecLen )
{
    DBG_ASSERT( nRecLen >= 4, "*ImportLotus::Hiddencolumn(): Record zu kurz!" );

    BYTE    nTab, nWindow2;
    UINT16  nCnt = ( nRecLen - 4 ) / 2;

    Read( nTab );
    Read( nWindow2 );

    if( !nWindow2 )
    {
        Skip( 2 );

        BYTE    nCol;

        while( nCnt )
        {
            Read( nCol );

            pD->SetColFlags( static_cast<SCCOL> (nCol), static_cast<SCTAB> (nTab), pD->GetColFlags( static_cast<SCCOL> (nCol), static_cast<SCTAB> (nTab) ) | CR_HIDDEN );

            nCnt--;
        }
    }
}

void ImportLotus::Userrange( void )
{
    UINT16      nRangeType;
    ScRange     aScRange;
    sal_Char*   pBuffer = new sal_Char[ 32 ];

    Read( nRangeType );

    pIn->Read( pBuffer, 16 );
    pBuffer[ 16 ] = ( sal_Char ) 0x00;  // zur Sicherheit...
    String      aName( pBuffer, eQuellChar );

    Read( aScRange );

    pLotusRoot->pRngNmBffWK3->Add( aName, aScRange );
    delete[] pBuffer;
}

void ImportLotus::Errcell( void )
{
    ScAddress   aA;

    Read( aA );

    pD->PutCell( aA.Col(), aA.Row(), aA.Tab(), new ScStringCell( CREATE_STRING( "#ERR!" ) ), (BOOL)TRUE );
}

void ImportLotus::Nacell( void )
{
    ScAddress   aA;

    Read( aA );

    pD->PutCell( aA.Col(), aA.Row(), aA.Tab(), new ScStringCell( CREATE_STRING( "#NA!" ) ), (BOOL)TRUE );
}

void ImportLotus::Labelcell( void )
{
    ScAddress   aA;
    String      aLabel;
    sal_Char    cAlign;

    Read( aA );
    Read( cAlign );
    Read( aLabel );

//  aLabel.Convert( pLotusRoot->eCharsetQ );

    pD->PutCell( aA.Col(), aA.Row(), aA.Tab(), new ScStringCell( aLabel ), (BOOL)TRUE );
}

void ImportLotus::Numbercell( void )
    {
    ScAddress   aAddr;
    double      fVal;

    Read( aAddr );
    Read( fVal );

    pD->PutCell( aAddr.Col(), aAddr.Row(), aAddr.Tab(),
        new ScValueCell( fVal ), (BOOL)TRUE );
    }

void ImportLotus::Smallnumcell( void )
    {
    ScAddress   aAddr;
    INT16       nVal;

    Read( aAddr );
    Read( nVal );

    pD->PutCell( aAddr.Col(), aAddr.Row(), aAddr.Tab(),
        new ScValueCell( SnumToDouble( nVal ) ), ( BOOL ) TRUE );
    }

ScFormulaCell *ImportLotus::Formulacell( UINT16 n )
    {
    DBG_ASSERT( pIn, "-ImportLotus::Formulacell(): Null-Stream -> Rums!" );

    ScAddress           aAddr;

    Read( aAddr );
    Skip( 10 );

    n -= 14;

    const ScTokenArray* pErg;
    INT32               nRest = n;

    aConv.Reset( aAddr );
    aConv.SetWK3();
    aConv.Convert( pErg, nRest );

    ScFormulaCell*      pZelle = new ScFormulaCell( pD, aAddr, pErg );

    pZelle->AddRecalcMode( RECALCMODE_ONLOAD_ONCE );

    pD->PutCell( aAddr.Col(), aAddr.Row(), aAddr.Tab(), pZelle, (BOOL)TRUE );

    return NULL;
    }

void ImportLotus::Read( String &r )
{
    ScfTools::AppendCString( *pIn, r, eQuellChar );
}

void ImportLotus::RowPresentation( UINT16 nRecLen )
{
    DBG_ASSERT( nRecLen > 4, "*ImportLotus::RowPresentation(): Record zu kurz!" );

    BYTE    nTab, nFlags;
    UINT16  nRow, nHeight;
    UINT16  nCnt = ( nRecLen - 4 ) / 8;

    Read( nTab );
    Skip( 1 );

    while( nCnt )
    {
        Read( nRow );
        Read( nHeight );
        Skip( 2 );
        Read( nFlags );
        Skip( 1 );

        if( nFlags & 0x02 )     // Fixed / Strech to fit fonts
        {   // fixed
            // Height in Lotus in 1/32 Points
            nHeight *= 20;  // -> 32 * TWIPS
            nHeight /= 32;  // -> TWIPS

            pD->SetRowFlags( static_cast<SCROW> (nRow), static_cast<SCTAB> (nTab), pD->GetRowFlags( static_cast<SCROW> (nRow), static_cast<SCTAB> (nTab) ) | CR_MANUALSIZE );

            pD->SetRowHeight( static_cast<SCROW> (nRow), static_cast<SCTAB> (nTab), nHeight );
        }

        nCnt--;
    }
}

void ImportLotus::NamedSheet( void )
{
    UINT16  nTab;
    String  aName;

    Read( nTab );
    Read( aName );

    if( pD->HasTable( static_cast<SCTAB> (nTab) ) )
        pD->RenameTab( static_cast<SCTAB> (nTab), aName );
    else
        pD->InsertTab( static_cast<SCTAB> (nTab), aName );
}

void ImportLotus::Font_Face( void )
{
    BYTE    nNum;
    String  aName;

    Read( nNum );

    // ACHTUNG: QUICK-HACK gegen unerklaerliche Loops
    if( nNum > 7 )
        return;
    // ACHTUNG

    Read( aName );

    pFontBuff->SetName( nNum, aName );
}

void ImportLotus::Font_Type( void )
{
    static const UINT16 nAnz = 8;
    UINT16              nCnt;
    UINT16              nType;

    for( nCnt = 0 ; nCnt < nAnz ; nCnt++ )
    {
        Read( nType );
        pFontBuff->SetType( nCnt, nType );
    }
}

void ImportLotus::Font_Ysize( void )
{
    static const UINT16 nAnz = 8;
    UINT16              nCnt;
    UINT16              nSize;

    for( nCnt = 0 ; nCnt < nAnz ; nCnt++ )
    {
        Read( nSize );
        pFontBuff->SetHeight( nCnt, nSize );
    }
}

void ImportLotus::_Row( const UINT16 nRecLen )
    {
    DBG_ASSERT( nExtTab >= 0, "*ImportLotus::_Row(): Kann hier nicht sein!" );

    UINT16          nRow;
    UINT16          nHeight;
    UINT16          nCntDwn = ( nRecLen - 4 ) / 5;
    SCCOL           nColCnt = 0;
    UINT8           nRepeats;
    LotAttrWK3      aAttr;

    BOOL            bCenter = FALSE;
    SCCOL           nCenterStart, nCenterEnd;

    Read( nRow );
    Read( nHeight );

    nHeight &= 0x0FFF;
    nHeight *= 22;

    if( nHeight )
        pD->SetRowHeight( static_cast<SCROW> (nRow), static_cast<SCTAB> (nExtTab), nHeight );

    while( nCntDwn )
        {
        Read( aAttr );
        Read( nRepeats );

        if( aAttr.HasStyles() )
            pLotusRoot->pAttrTable->SetAttr(
                nColCnt, static_cast<SCCOL> ( nColCnt + nRepeats ), static_cast<SCROW> (nRow), aAttr );

        // hier und NICHT in class LotAttrTable, weil nur Attributiert wird,
        // wenn die anderen Attribute gesetzt sind
        //  -> bei Center-Attribute wird generell zentriert gesetzt
        if( aAttr.IsCentered() )
            {
            if( bCenter )
                {
                if( pD->HasData( nColCnt, static_cast<SCROW> (nRow), static_cast<SCTAB> (nExtTab) ) )
                    {// neue Center nach vorheriger Center
                    pD->DoMerge( static_cast<SCTAB> (nExtTab), nCenterStart, static_cast<SCROW> (nRow), nCenterEnd, static_cast<SCROW> (nRow) );
                    nCenterStart = nColCnt;
                    }
                }
            else
                {// ganz neue Center
                bCenter = TRUE;
                nCenterStart = nColCnt;
                }
            nCenterEnd = nColCnt + static_cast<SCCOL>(nRepeats);
            }
        else
            {
            if( bCenter )
                {// evtl. alte Center bemachen
                pD->DoMerge( static_cast<SCTAB> (nExtTab), nCenterStart, static_cast<SCROW> (nRow), nCenterEnd, static_cast<SCROW> (nRow) );
                bCenter = FALSE;
                }
            }

        nColCnt += static_cast<SCCOL>(nRepeats);
        nColCnt++;

        nCntDwn--;
        }

    if( bCenter )
        // evtl. alte Center bemachen
        pD->DoMerge( static_cast<SCTAB> (nExtTab), nCenterStart, static_cast<SCROW> (nRow), nCenterEnd, static_cast<SCROW> (nRow) );
    }

<commit_msg>INTEGRATION: CWS pchfix01 (1.10.214); FILE MERGED 2006/07/12 10:02:00 kaib 1.10.214.1: #i67080# Converted cxx files in sc, added initial project level pch and stripped old PCH definitions.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: lotimpop.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: kz $ $Date: 2006-07-21 12:28:07 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#include "lotimpop.hxx"

#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif

#include "attrib.hxx"
#include "document.hxx"
#include "rangenam.hxx"
#include "cell.hxx"
#include "patattr.hxx"
#include "docpool.hxx"
#include "compiler.hxx"
#include "global.hxx"

#include "root.hxx"
#include "lotfntbf.hxx"
#include "lotform.hxx"
#include "tool.h"
#include "namebuff.hxx"
#include "lotrange.hxx"
#include "lotattr.hxx"

static NAMESPACE_VOS( OMutex )      aLotImpSemaphore;

ImportLotus::ImportLotus( SvStream& aStream, ScDocument* pDoc, CharSet eQ ) :
    ImportTyp( pDoc, eQ ),
    pIn( &aStream ),
    aConv( *pIn, eQ, FALSE )
{
    // good point to start locking of import lotus
    aLotImpSemaphore.acquire();

    pLotusRoot = new LOTUS_ROOT;
    pLotusRoot->pDoc = pDoc;
    pLotusRoot->pRangeNames = new LotusRangeList;
    pLotusRoot->pScRangeName = pDoc->GetRangeName();
    pLotusRoot->eCharsetQ = eQ;
    pLotusRoot->eFirstType = Lotus_X;
    pLotusRoot->eActType = Lotus_X;
    pLotusRoot->pRngNmBffWK3 = new RangeNameBufferWK3;
    pFontBuff = pLotusRoot->pFontBuff = new LotusFontBuffer;
    pLotusRoot->pAttrTable = new LotAttrTable;
}

ImportLotus::~ImportLotus()
{
    delete pLotusRoot->pRangeNames;
    delete pLotusRoot->pRngNmBffWK3;
    delete pFontBuff;
    delete pLotusRoot->pAttrTable;
    delete pLotusRoot;

#ifdef DBG_UTIL
    pLotusRoot = NULL;
#endif

    // no need 4 pLotusRoot anymore
    aLotImpSemaphore.release();
}

void ImportLotus::Bof( void )
{
    UINT16  nFileCode, nFileSub, nSaveCnt;
    BYTE    nMajorId, nMinorId, nFlags;

    Read( nFileCode );
    Read( nFileSub );
    Read( pLotusRoot->aActRange );
    Read( nSaveCnt );
    Read( nMajorId );
    Read( nMinorId );
    Skip( 1 );
    Read( nFlags );

    if( nFileSub == 0x0004 )
    {
        if( nFileCode == 0x1000 )
        {// <= WK3
            pLotusRoot->eFirstType = pLotusRoot->eActType = Lotus_WK3;
        }
        else if( nFileCode == 0x1002 )
        {// WK4
            pLotusRoot->eFirstType = pLotusRoot->eActType = Lotus_WK4;
        }
    }
}

BOOL ImportLotus::BofFm3( void )
{
    UINT16  nFileCode, nFileSub;

    Read( nFileCode );
    Read( nFileSub );

    return ( nFileCode == 0x8007 && ( nFileSub == 0x0000 || nFileSub == 0x00001 ) );
}

void ImportLotus::Columnwidth( UINT16 nRecLen )
{
    DBG_ASSERT( nRecLen >= 4, "*ImportLotus::Columnwidth(): Record zu kurz!" );

    BYTE    nTab, nWindow2;
    UINT16  nCnt = ( nRecLen - 4 ) / 2;

    Read( nTab );
    Read( nWindow2 );

    if( !pD->HasTable( static_cast<SCTAB> (nTab) ) )
        pD->MakeTable( static_cast<SCTAB> (nTab) );

    if( !nWindow2 )
    {
        Skip( 2 );

        BYTE    nCol, nSpaces;

        while( nCnt )
        {
            Read( nCol );
            Read( nSpaces );
            // ACHTUNG: Korrekturfaktor nach 'Augenmass' ermittelt!
            pD->SetColWidth( static_cast<SCCOL> (nCol), static_cast<SCTAB> (nTab), ( UINT16 ) ( TWIPS_PER_CHAR * 1.28 * nSpaces ) );

            nCnt--;
        }
    }
}

void ImportLotus::Hiddencolumn( UINT16 nRecLen )
{
    DBG_ASSERT( nRecLen >= 4, "*ImportLotus::Hiddencolumn(): Record zu kurz!" );

    BYTE    nTab, nWindow2;
    UINT16  nCnt = ( nRecLen - 4 ) / 2;

    Read( nTab );
    Read( nWindow2 );

    if( !nWindow2 )
    {
        Skip( 2 );

        BYTE    nCol;

        while( nCnt )
        {
            Read( nCol );

            pD->SetColFlags( static_cast<SCCOL> (nCol), static_cast<SCTAB> (nTab), pD->GetColFlags( static_cast<SCCOL> (nCol), static_cast<SCTAB> (nTab) ) | CR_HIDDEN );

            nCnt--;
        }
    }
}

void ImportLotus::Userrange( void )
{
    UINT16      nRangeType;
    ScRange     aScRange;
    sal_Char*   pBuffer = new sal_Char[ 32 ];

    Read( nRangeType );

    pIn->Read( pBuffer, 16 );
    pBuffer[ 16 ] = ( sal_Char ) 0x00;  // zur Sicherheit...
    String      aName( pBuffer, eQuellChar );

    Read( aScRange );

    pLotusRoot->pRngNmBffWK3->Add( aName, aScRange );
    delete[] pBuffer;
}

void ImportLotus::Errcell( void )
{
    ScAddress   aA;

    Read( aA );

    pD->PutCell( aA.Col(), aA.Row(), aA.Tab(), new ScStringCell( CREATE_STRING( "#ERR!" ) ), (BOOL)TRUE );
}

void ImportLotus::Nacell( void )
{
    ScAddress   aA;

    Read( aA );

    pD->PutCell( aA.Col(), aA.Row(), aA.Tab(), new ScStringCell( CREATE_STRING( "#NA!" ) ), (BOOL)TRUE );
}

void ImportLotus::Labelcell( void )
{
    ScAddress   aA;
    String      aLabel;
    sal_Char    cAlign;

    Read( aA );
    Read( cAlign );
    Read( aLabel );

//  aLabel.Convert( pLotusRoot->eCharsetQ );

    pD->PutCell( aA.Col(), aA.Row(), aA.Tab(), new ScStringCell( aLabel ), (BOOL)TRUE );
}

void ImportLotus::Numbercell( void )
    {
    ScAddress   aAddr;
    double      fVal;

    Read( aAddr );
    Read( fVal );

    pD->PutCell( aAddr.Col(), aAddr.Row(), aAddr.Tab(),
        new ScValueCell( fVal ), (BOOL)TRUE );
    }

void ImportLotus::Smallnumcell( void )
    {
    ScAddress   aAddr;
    INT16       nVal;

    Read( aAddr );
    Read( nVal );

    pD->PutCell( aAddr.Col(), aAddr.Row(), aAddr.Tab(),
        new ScValueCell( SnumToDouble( nVal ) ), ( BOOL ) TRUE );
    }

ScFormulaCell *ImportLotus::Formulacell( UINT16 n )
    {
    DBG_ASSERT( pIn, "-ImportLotus::Formulacell(): Null-Stream -> Rums!" );

    ScAddress           aAddr;

    Read( aAddr );
    Skip( 10 );

    n -= 14;

    const ScTokenArray* pErg;
    INT32               nRest = n;

    aConv.Reset( aAddr );
    aConv.SetWK3();
    aConv.Convert( pErg, nRest );

    ScFormulaCell*      pZelle = new ScFormulaCell( pD, aAddr, pErg );

    pZelle->AddRecalcMode( RECALCMODE_ONLOAD_ONCE );

    pD->PutCell( aAddr.Col(), aAddr.Row(), aAddr.Tab(), pZelle, (BOOL)TRUE );

    return NULL;
    }

void ImportLotus::Read( String &r )
{
    ScfTools::AppendCString( *pIn, r, eQuellChar );
}

void ImportLotus::RowPresentation( UINT16 nRecLen )
{
    DBG_ASSERT( nRecLen > 4, "*ImportLotus::RowPresentation(): Record zu kurz!" );

    BYTE    nTab, nFlags;
    UINT16  nRow, nHeight;
    UINT16  nCnt = ( nRecLen - 4 ) / 8;

    Read( nTab );
    Skip( 1 );

    while( nCnt )
    {
        Read( nRow );
        Read( nHeight );
        Skip( 2 );
        Read( nFlags );
        Skip( 1 );

        if( nFlags & 0x02 )     // Fixed / Strech to fit fonts
        {   // fixed
            // Height in Lotus in 1/32 Points
            nHeight *= 20;  // -> 32 * TWIPS
            nHeight /= 32;  // -> TWIPS

            pD->SetRowFlags( static_cast<SCROW> (nRow), static_cast<SCTAB> (nTab), pD->GetRowFlags( static_cast<SCROW> (nRow), static_cast<SCTAB> (nTab) ) | CR_MANUALSIZE );

            pD->SetRowHeight( static_cast<SCROW> (nRow), static_cast<SCTAB> (nTab), nHeight );
        }

        nCnt--;
    }
}

void ImportLotus::NamedSheet( void )
{
    UINT16  nTab;
    String  aName;

    Read( nTab );
    Read( aName );

    if( pD->HasTable( static_cast<SCTAB> (nTab) ) )
        pD->RenameTab( static_cast<SCTAB> (nTab), aName );
    else
        pD->InsertTab( static_cast<SCTAB> (nTab), aName );
}

void ImportLotus::Font_Face( void )
{
    BYTE    nNum;
    String  aName;

    Read( nNum );

    // ACHTUNG: QUICK-HACK gegen unerklaerliche Loops
    if( nNum > 7 )
        return;
    // ACHTUNG

    Read( aName );

    pFontBuff->SetName( nNum, aName );
}

void ImportLotus::Font_Type( void )
{
    static const UINT16 nAnz = 8;
    UINT16              nCnt;
    UINT16              nType;

    for( nCnt = 0 ; nCnt < nAnz ; nCnt++ )
    {
        Read( nType );
        pFontBuff->SetType( nCnt, nType );
    }
}

void ImportLotus::Font_Ysize( void )
{
    static const UINT16 nAnz = 8;
    UINT16              nCnt;
    UINT16              nSize;

    for( nCnt = 0 ; nCnt < nAnz ; nCnt++ )
    {
        Read( nSize );
        pFontBuff->SetHeight( nCnt, nSize );
    }
}

void ImportLotus::_Row( const UINT16 nRecLen )
    {
    DBG_ASSERT( nExtTab >= 0, "*ImportLotus::_Row(): Kann hier nicht sein!" );

    UINT16          nRow;
    UINT16          nHeight;
    UINT16          nCntDwn = ( nRecLen - 4 ) / 5;
    SCCOL           nColCnt = 0;
    UINT8           nRepeats;
    LotAttrWK3      aAttr;

    BOOL            bCenter = FALSE;
    SCCOL           nCenterStart, nCenterEnd;

    Read( nRow );
    Read( nHeight );

    nHeight &= 0x0FFF;
    nHeight *= 22;

    if( nHeight )
        pD->SetRowHeight( static_cast<SCROW> (nRow), static_cast<SCTAB> (nExtTab), nHeight );

    while( nCntDwn )
        {
        Read( aAttr );
        Read( nRepeats );

        if( aAttr.HasStyles() )
            pLotusRoot->pAttrTable->SetAttr(
                nColCnt, static_cast<SCCOL> ( nColCnt + nRepeats ), static_cast<SCROW> (nRow), aAttr );

        // hier und NICHT in class LotAttrTable, weil nur Attributiert wird,
        // wenn die anderen Attribute gesetzt sind
        //  -> bei Center-Attribute wird generell zentriert gesetzt
        if( aAttr.IsCentered() )
            {
            if( bCenter )
                {
                if( pD->HasData( nColCnt, static_cast<SCROW> (nRow), static_cast<SCTAB> (nExtTab) ) )
                    {// neue Center nach vorheriger Center
                    pD->DoMerge( static_cast<SCTAB> (nExtTab), nCenterStart, static_cast<SCROW> (nRow), nCenterEnd, static_cast<SCROW> (nRow) );
                    nCenterStart = nColCnt;
                    }
                }
            else
                {// ganz neue Center
                bCenter = TRUE;
                nCenterStart = nColCnt;
                }
            nCenterEnd = nColCnt + static_cast<SCCOL>(nRepeats);
            }
        else
            {
            if( bCenter )
                {// evtl. alte Center bemachen
                pD->DoMerge( static_cast<SCTAB> (nExtTab), nCenterStart, static_cast<SCROW> (nRow), nCenterEnd, static_cast<SCROW> (nRow) );
                bCenter = FALSE;
                }
            }

        nColCnt += static_cast<SCCOL>(nRepeats);
        nColCnt++;

        nCntDwn--;
        }

    if( bCenter )
        // evtl. alte Center bemachen
        pD->DoMerge( static_cast<SCTAB> (nExtTab), nCenterStart, static_cast<SCROW> (nRow), nCenterEnd, static_cast<SCROW> (nRow) );
    }

<|endoftext|>


<commit_before>#include <babylon/materials/node/blocks/dual/light_block.h>

#include <babylon/babylon_stl_util.h>
#include <babylon/core/json_util.h>
#include <babylon/materials/material_helper.h>
#include <babylon/materials/node/blocks/input/input_block.h>
#include <babylon/materials/node/node_material.h>
#include <babylon/materials/node/node_material_build_state.h>
#include <babylon/materials/node/node_material_build_state_shared_data.h>
#include <babylon/materials/node/node_material_connection_point.h>
#include <babylon/materials/node/node_material_defines.h>
#include <babylon/meshes/abstract_mesh.h>
#include <babylon/meshes/mesh.h>
#include <babylon/misc/string_tools.h>

namespace BABYLON {

LightBlock::LightBlock(const std::string& iName)
    : NodeMaterialBlock{iName, NodeMaterialBlockTargets::VertexAndFragment}
    , light{nullptr}
    , worldPosition{this, &LightBlock::get_worldPosition}
    , worldNormal{this, &LightBlock::get_worldNormal}
    , cameraPosition{this, &LightBlock::get_cameraPosition}
    , glossiness{this, &LightBlock::get_glossiness}
    , glossPower{this, &LightBlock::get_glossPower}
    , diffuseColor{this, &LightBlock::get_diffuseColor}
    , specularColor{this, &LightBlock::get_specularColor}
    , view{this, &LightBlock::get_view}
    , diffuseOutput{this, &LightBlock::get_diffuseOutput}
    , specularOutput{this, &LightBlock::get_specularOutput}
    , shadow{this, &LightBlock::get_shadow}
{
  _isUnique = true;

  registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes::Vector4, false,
                NodeMaterialBlockTargets::Vertex);
  registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes::Vector4, false,
                NodeMaterialBlockTargets::Fragment);
  registerInput("cameraPosition", NodeMaterialBlockConnectionPointTypes::Vector3, false,
                NodeMaterialBlockTargets::Fragment);
  registerInput("glossiness", NodeMaterialBlockConnectionPointTypes::Float, true,
                NodeMaterialBlockTargets::Fragment);
  registerInput("glossPower", NodeMaterialBlockConnectionPointTypes::Float, true,
                NodeMaterialBlockTargets::Fragment);
  registerInput("diffuseColor", NodeMaterialBlockConnectionPointTypes::Color3, true,
                NodeMaterialBlockTargets::Fragment);
  registerInput("specularColor", NodeMaterialBlockConnectionPointTypes::Color3, true,
                NodeMaterialBlockTargets::Fragment);
  registerInput("view", NodeMaterialBlockConnectionPointTypes::Matrix, true);

  registerOutput("diffuseOutput", NodeMaterialBlockConnectionPointTypes::Color3,
                 NodeMaterialBlockTargets::Fragment);
  registerOutput("specularOutput", NodeMaterialBlockConnectionPointTypes::Color3,
                 NodeMaterialBlockTargets::Fragment);
  registerOutput("shadow", NodeMaterialBlockConnectionPointTypes::Float,
                 NodeMaterialBlockTargets::Fragment);
}

LightBlock::~LightBlock() = default;

std::string LightBlock::getClassName() const
{
  return "LightBlock";
}

NodeMaterialConnectionPointPtr& LightBlock::get_worldPosition()
{
  return _inputs[0];
}

NodeMaterialConnectionPointPtr& LightBlock::get_worldNormal()
{
  return _inputs[1];
}

NodeMaterialConnectionPointPtr& LightBlock::get_cameraPosition()
{
  return _inputs[2];
}

NodeMaterialConnectionPointPtr& LightBlock::get_glossiness()
{
  return _inputs[3];
}

NodeMaterialConnectionPointPtr& LightBlock::get_glossPower()
{
  return _inputs[4];
}

NodeMaterialConnectionPointPtr& LightBlock::get_diffuseColor()
{
  return _inputs[5];
}

NodeMaterialConnectionPointPtr& LightBlock::get_specularColor()
{
  return _inputs[6];
}

NodeMaterialConnectionPointPtr& LightBlock::get_view()
{
  return _inputs[7];
}

NodeMaterialConnectionPointPtr& LightBlock::get_diffuseOutput()
{
  return _outputs[0];
}

NodeMaterialConnectionPointPtr& LightBlock::get_specularOutput()
{
  return _outputs[1];
}

NodeMaterialConnectionPointPtr& LightBlock::get_shadow()
{
  return _outputs[2];
}

void LightBlock::autoConfigure(const NodeMaterialPtr& material)
{
  if (!cameraPosition()->isConnected()) {
    auto cameraPositionInput
      = material->getInputBlockByPredicate([](const InputBlockPtr& b) -> bool {
          return b->systemValue() == NodeMaterialSystemValues::CameraPosition;
        });

    if (!cameraPositionInput) {
      cameraPositionInput = InputBlock::New("cameraPosition");
      cameraPositionInput->setAsSystemValue(NodeMaterialSystemValues::CameraPosition);
    }
    cameraPositionInput->output()->connectTo(cameraPosition());
  }
}

void LightBlock::prepareDefines(AbstractMesh* mesh, const NodeMaterialPtr& nodeMaterial,
                                NodeMaterialDefines& defines, bool /*useInstances*/,
                                SubMesh* /*subMesh*/)
{
  if (!defines._areLightsDirty) {
    return;
  }

  auto scene = mesh->getScene();

  if (!light) {
    MaterialHelper::PrepareDefinesForLights(scene, mesh, defines, true,
                                            nodeMaterial->maxSimultaneousLights);
  }
  else {
    PrepareDefinesForLightsState state{
      false, // needNormals
      false, // needRebuild
      false, // shadowEnabled
      false, // specularEnabled
      false  // lightmapMode
    };

    MaterialHelper::PrepareDefinesForLight(scene, mesh, light, _lightId, defines, true, state);

    if (state.needRebuild) {
      defines.rebuild();
    }
  }
}

void LightBlock::updateUniformsAndSamples(NodeMaterialBuildState& state,
                                          const NodeMaterialPtr& nodeMaterial,
                                          const NodeMaterialDefines& defines,
                                          std::vector<std::string>& uniformBuffers)
{
  for (auto lightIndex = 0u; lightIndex < nodeMaterial->maxSimultaneousLights; ++lightIndex) {
    const auto lightIndexStr = std::to_string(lightIndex);
    if (!defines["LIGHT" + lightIndexStr]) {
      break;
    }
    MaterialHelper::PrepareUniformsAndSamplersForLight(
      lightIndex, state.uniforms, state.samplers, uniformBuffers, true,
      defines["PROJECTEDLIGHTTEXTURE" + lightIndexStr]);
  }
}

void LightBlock::bind(Effect* effect, const NodeMaterialPtr& nodeMaterial, Mesh* mesh,
                      SubMesh* /*subMesh*/)
{
  if (!mesh) {
    return;
  }

  auto scene = mesh->getScene();

  if (!light) {
    MaterialHelper::BindLights(scene, mesh, effect, true, nodeMaterial->maxSimultaneousLights);
  }
  else {
    MaterialHelper::BindLight(light, _lightId, scene, effect, true);
  }
}

void LightBlock::_injectVertexCode(NodeMaterialBuildState& state)
{
  const auto& worldPos = worldPosition();
  auto iComments       = StringTools::printf("//%s", name().c_str());

  // Declaration
  if (!light) { // Emit for all lights
    state._emitFunctionFromInclude(
      state.supportUniformBuffers ? "lightUboDeclaration" : "lightFragmentDeclaration", iComments,
      EmitFunctionFromIncludeOptions{
        "maxSimultaneousLights" // repeatKey
      });
    _lightId = 0;

    state.sharedData->dynamicUniformBlocks.emplace_back(this);
  }
  else {

    _lightId = static_cast<uint32_t>((stl_util::contains(state.counters, "lightCounter") ?
                                        static_cast<int>(state.counters["lightCounter"]) :
                                        -1)
                                     + 1);
    state.counters["lightCounter"] = _lightId;

    EmitFunctionFromIncludeOptions options;
    options.replaceStrings = {StringsReplacement{
      "{X}",                   // search
      std::to_string(_lightId) // replace
    }};
    state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightUboDeclaration" :
                                                                 "lightFragmentDeclaration",
                                   iComments, options, std::to_string(_lightId));
  }

  // Inject code in vertex
  auto worldPosVaryingName
    = StringTools::printf("v_%s", worldPos->associatedVariableName().c_str());
  if (state._emitVaryingFromString(worldPosVaryingName, "vec4")) {
    state.compilationString += StringTools::printf("%s = %s;\r\n", worldPosVaryingName.c_str(),
                                                   worldPos->associatedVariableName().c_str());
  }

  if (light) {
    EmitCodeFromIncludeOptions options;
    options.replaceStrings = {StringsReplacement{
                                "{X}",                   // search
                                std::to_string(_lightId) // replace
                              },
                              StringsReplacement{
                                "worldPos",                        // search
                                worldPos->associatedVariableName() // replace
                              }};
    state.compilationString += state._emitCodeFromInclude("shadowsVertex", iComments, options);
  }
  else {
    state.compilationString
      += StringTools::printf("vec4 worldPos = %s;\r\n", worldPos->associatedVariableName().c_str());
    if (view()->isConnected()) {
      state.compilationString
        += StringTools::printf("mat4 view = %s;\r\n", view()->associatedVariableName().c_str());
    }
    EmitCodeFromIncludeOptions options;
    options.repeatKey = "maxSimultaneousLights";
    state.compilationString += state._emitCodeFromInclude("shadowsVertex", iComments, options);
  }
}

LightBlock& LightBlock::_buildBlock(NodeMaterialBuildState& state)
{
  NodeMaterialBlock::_buildBlock(state);

  if (state.target != NodeMaterialBlockTargets::Fragment) {
    // Vertex
    _injectVertexCode(state);

    return *this;
  }

  // Fragment
  state.sharedData->bindableBlocks.emplace_back(shared_from_this());
  state.sharedData->blocksWithDefines.emplace_back(shared_from_this());

  auto iComments       = StringTools::printf("//%s", name().c_str());
  const auto& worldPos = worldPosition();

  state._emitFunctionFromInclude("helperFunctions", iComments);

  EmitFunctionFromIncludeOptions options;
  options.replaceStrings = {StringsReplacement{
    "vPositionW",                                                               // search
    StringTools::printf("v_%s.xyz", worldPos->associatedVariableName().c_str()) // replace
  }};
  state._emitFunctionFromInclude("lightsFragmentFunctions", iComments, options);

  state._emitFunctionFromInclude("shadowsFragmentFunctions", iComments, options);

  if (!light) { // Emit for all lights
    state._emitFunctionFromInclude(
      state.supportUniformBuffers ? "lightUboDeclaration" : "lightFragmentDeclaration", iComments,
      EmitFunctionFromIncludeOptions{
        "maxSimultaneousLights" // repeatKey
      });
  }
  else {
    options.replaceStrings = {StringsReplacement{
      "{X}",                   // search
      std::to_string(_lightId) // replace
    }};

    state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightUboDeclaration" :
                                                                 "lightFragmentDeclaration",
                                   iComments, options, std::to_string(_lightId));
  }

  // Code
  if (_lightId == 0) {
    if (state._registerTempVariable("viewDirectionW")) {
      state.compilationString += StringTools::printf(
        "vec3 viewDirectionW = normalize(%s - %s);\r\n",
        cameraPosition()->associatedVariableName().c_str(),
        StringTools::printf("v_%s.xyz", worldPos->associatedVariableName().c_str()).c_str());
    }
    state.compilationString += "lightingInfo info;\r\n";
    state.compilationString += "float shadow = 1.;\r\n";
    state.compilationString += StringTools::printf(
      "float glossiness = %s * %s;\r\n",
      glossiness()->isConnected() ? glossiness()->associatedVariableName().c_str() : "1.0",
      glossPower()->isConnected ? glossPower()->associatedVariableName().c_str() : "1024.0");
    state.compilationString += "vec3 diffuseBase = vec3(0., 0., 0.);\r\n";
    state.compilationString += "vec3 specularBase = vec3(0., 0., 0.);\r\n";
    state.compilationString += StringTools::printf("vec3 normalW = %s.xyz;\r\n",
                                                   worldNormal()->associatedVariableName().c_str());
  }

  if (light) {
    options.replaceStrings = {StringsReplacement{
      "{X}",                   // search
      std::to_string(_lightId) // replace
    }};
  }
  else {
    EmitCodeFromIncludeOptions includeOptions;
    includeOptions.repeatKey = "maxSimultaneousLights";
    state.compilationString
      += state._emitCodeFromInclude("lightFragment", iComments, includeOptions);
  }

  const auto& _diffuseOutput  = diffuseOutput();
  const auto& _specularOutput = specularOutput();

  state.compilationString
    += _declareOutput(_diffuseOutput, state)
       + StringTools::printf(
         " = diffuseBase%s;\r\n",
         diffuseColor()->isConnected() ?
           StringTools::printf(" * %s", diffuseColor()->associatedVariableName().c_str()).c_str() :
           "");
  if (_specularOutput->hasEndpoints()) {
    state.compilationString
      += _declareOutput(_specularOutput, state)
         + StringTools::printf(
           " = specularBase%s;\r\n",
           specularColor()->isConnected() ?
             StringTools::printf(" * %s", specularColor()->associatedVariableName().c_str())
               .c_str() :
             "");
  }

  if (shadow()->hasEndpoints()) {
    state.compilationString += _declareOutput(shadow, state) + " = shadow;\r\n";
  }

  return *this;
}

json LightBlock::serialize() const
{
  return nullptr;
}

void LightBlock::_deserialize(const json& /*serializationObject*/, Scene* /*scene*/,
                              const std::string& /*rootUrl*/)
{
}

} // end of namespace BABYLON
<commit_msg>Using onlyUpdateBuffersList value<commit_after>#include <babylon/materials/node/blocks/dual/light_block.h>

#include <babylon/babylon_stl_util.h>
#include <babylon/core/json_util.h>
#include <babylon/materials/material_helper.h>
#include <babylon/materials/node/blocks/input/input_block.h>
#include <babylon/materials/node/node_material.h>
#include <babylon/materials/node/node_material_build_state.h>
#include <babylon/materials/node/node_material_build_state_shared_data.h>
#include <babylon/materials/node/node_material_connection_point.h>
#include <babylon/materials/node/node_material_defines.h>
#include <babylon/meshes/abstract_mesh.h>
#include <babylon/meshes/mesh.h>
#include <babylon/misc/string_tools.h>

namespace BABYLON {

LightBlock::LightBlock(const std::string& iName)
    : NodeMaterialBlock{iName, NodeMaterialBlockTargets::VertexAndFragment}
    , light{nullptr}
    , worldPosition{this, &LightBlock::get_worldPosition}
    , worldNormal{this, &LightBlock::get_worldNormal}
    , cameraPosition{this, &LightBlock::get_cameraPosition}
    , glossiness{this, &LightBlock::get_glossiness}
    , glossPower{this, &LightBlock::get_glossPower}
    , diffuseColor{this, &LightBlock::get_diffuseColor}
    , specularColor{this, &LightBlock::get_specularColor}
    , view{this, &LightBlock::get_view}
    , diffuseOutput{this, &LightBlock::get_diffuseOutput}
    , specularOutput{this, &LightBlock::get_specularOutput}
    , shadow{this, &LightBlock::get_shadow}
{
  _isUnique = true;

  registerInput("worldPosition", NodeMaterialBlockConnectionPointTypes::Vector4, false,
                NodeMaterialBlockTargets::Vertex);
  registerInput("worldNormal", NodeMaterialBlockConnectionPointTypes::Vector4, false,
                NodeMaterialBlockTargets::Fragment);
  registerInput("cameraPosition", NodeMaterialBlockConnectionPointTypes::Vector3, false,
                NodeMaterialBlockTargets::Fragment);
  registerInput("glossiness", NodeMaterialBlockConnectionPointTypes::Float, true,
                NodeMaterialBlockTargets::Fragment);
  registerInput("glossPower", NodeMaterialBlockConnectionPointTypes::Float, true,
                NodeMaterialBlockTargets::Fragment);
  registerInput("diffuseColor", NodeMaterialBlockConnectionPointTypes::Color3, true,
                NodeMaterialBlockTargets::Fragment);
  registerInput("specularColor", NodeMaterialBlockConnectionPointTypes::Color3, true,
                NodeMaterialBlockTargets::Fragment);
  registerInput("view", NodeMaterialBlockConnectionPointTypes::Matrix, true);

  registerOutput("diffuseOutput", NodeMaterialBlockConnectionPointTypes::Color3,
                 NodeMaterialBlockTargets::Fragment);
  registerOutput("specularOutput", NodeMaterialBlockConnectionPointTypes::Color3,
                 NodeMaterialBlockTargets::Fragment);
  registerOutput("shadow", NodeMaterialBlockConnectionPointTypes::Float,
                 NodeMaterialBlockTargets::Fragment);
}

LightBlock::~LightBlock() = default;

std::string LightBlock::getClassName() const
{
  return "LightBlock";
}

NodeMaterialConnectionPointPtr& LightBlock::get_worldPosition()
{
  return _inputs[0];
}

NodeMaterialConnectionPointPtr& LightBlock::get_worldNormal()
{
  return _inputs[1];
}

NodeMaterialConnectionPointPtr& LightBlock::get_cameraPosition()
{
  return _inputs[2];
}

NodeMaterialConnectionPointPtr& LightBlock::get_glossiness()
{
  return _inputs[3];
}

NodeMaterialConnectionPointPtr& LightBlock::get_glossPower()
{
  return _inputs[4];
}

NodeMaterialConnectionPointPtr& LightBlock::get_diffuseColor()
{
  return _inputs[5];
}

NodeMaterialConnectionPointPtr& LightBlock::get_specularColor()
{
  return _inputs[6];
}

NodeMaterialConnectionPointPtr& LightBlock::get_view()
{
  return _inputs[7];
}

NodeMaterialConnectionPointPtr& LightBlock::get_diffuseOutput()
{
  return _outputs[0];
}

NodeMaterialConnectionPointPtr& LightBlock::get_specularOutput()
{
  return _outputs[1];
}

NodeMaterialConnectionPointPtr& LightBlock::get_shadow()
{
  return _outputs[2];
}

void LightBlock::autoConfigure(const NodeMaterialPtr& material)
{
  if (!cameraPosition()->isConnected()) {
    auto cameraPositionInput
      = material->getInputBlockByPredicate([](const InputBlockPtr& b) -> bool {
          return b->systemValue() == NodeMaterialSystemValues::CameraPosition;
        });

    if (!cameraPositionInput) {
      cameraPositionInput = InputBlock::New("cameraPosition");
      cameraPositionInput->setAsSystemValue(NodeMaterialSystemValues::CameraPosition);
    }
    cameraPositionInput->output()->connectTo(cameraPosition());
  }
}

void LightBlock::prepareDefines(AbstractMesh* mesh, const NodeMaterialPtr& nodeMaterial,
                                NodeMaterialDefines& defines, bool /*useInstances*/,
                                SubMesh* /*subMesh*/)
{
  if (!defines._areLightsDirty) {
    return;
  }

  auto scene = mesh->getScene();

  if (!light) {
    MaterialHelper::PrepareDefinesForLights(scene, mesh, defines, true,
                                            nodeMaterial->maxSimultaneousLights);
  }
  else {
    PrepareDefinesForLightsState state{
      false, // needNormals
      false, // needRebuild
      false, // shadowEnabled
      false, // specularEnabled
      false  // lightmapMode
    };

    MaterialHelper::PrepareDefinesForLight(scene, mesh, light, _lightId, defines, true, state);

    if (state.needRebuild) {
      defines.rebuild();
    }
  }
}

void LightBlock::updateUniformsAndSamples(NodeMaterialBuildState& state,
                                          const NodeMaterialPtr& nodeMaterial,
                                          const NodeMaterialDefines& defines,
                                          std::vector<std::string>& uniformBuffers)
{
  for (auto lightIndex = 0u; lightIndex < nodeMaterial->maxSimultaneousLights; ++lightIndex) {
    const auto lightIndexStr = std::to_string(lightIndex);
    if (!defines["LIGHT" + lightIndexStr]) {
      break;
    }
    const auto onlyUpdateBuffersList
      = stl_util::index_of(state.uniforms, "vLightData" + lightIndexStr) >= 0;
    MaterialHelper::PrepareUniformsAndSamplersForLight(
      lightIndex, state.uniforms, state.samplers, uniformBuffers, true,
      defines["PROJECTEDLIGHTTEXTURE" + lightIndexStr], onlyUpdateBuffersList);
  }
}

void LightBlock::bind(Effect* effect, const NodeMaterialPtr& nodeMaterial, Mesh* mesh,
                      SubMesh* /*subMesh*/)
{
  if (!mesh) {
    return;
  }

  auto scene = mesh->getScene();

  if (!light) {
    MaterialHelper::BindLights(scene, mesh, effect, true, nodeMaterial->maxSimultaneousLights);
  }
  else {
    MaterialHelper::BindLight(light, _lightId, scene, effect, true);
  }
}

void LightBlock::_injectVertexCode(NodeMaterialBuildState& state)
{
  const auto& worldPos = worldPosition();
  auto iComments       = StringTools::printf("//%s", name().c_str());

  // Declaration
  if (!light) { // Emit for all lights
    state._emitFunctionFromInclude(
      state.supportUniformBuffers ? "lightUboDeclaration" : "lightFragmentDeclaration", iComments,
      EmitFunctionFromIncludeOptions{
        "maxSimultaneousLights" // repeatKey
      });
    _lightId = 0;

    state.sharedData->dynamicUniformBlocks.emplace_back(this);
  }
  else {

    _lightId = static_cast<uint32_t>((stl_util::contains(state.counters, "lightCounter") ?
                                        static_cast<int>(state.counters["lightCounter"]) :
                                        -1)
                                     + 1);
    state.counters["lightCounter"] = _lightId;

    EmitFunctionFromIncludeOptions options;
    options.replaceStrings = {StringsReplacement{
      "{X}",                   // search
      std::to_string(_lightId) // replace
    }};
    state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightUboDeclaration" :
                                                                 "lightFragmentDeclaration",
                                   iComments, options, std::to_string(_lightId));
  }

  // Inject code in vertex
  auto worldPosVaryingName
    = StringTools::printf("v_%s", worldPos->associatedVariableName().c_str());
  if (state._emitVaryingFromString(worldPosVaryingName, "vec4")) {
    state.compilationString += StringTools::printf("%s = %s;\r\n", worldPosVaryingName.c_str(),
                                                   worldPos->associatedVariableName().c_str());
  }

  if (light) {
    EmitCodeFromIncludeOptions options;
    options.replaceStrings = {StringsReplacement{
                                "{X}",                   // search
                                std::to_string(_lightId) // replace
                              },
                              StringsReplacement{
                                "worldPos",                        // search
                                worldPos->associatedVariableName() // replace
                              }};
    state.compilationString += state._emitCodeFromInclude("shadowsVertex", iComments, options);
  }
  else {
    state.compilationString
      += StringTools::printf("vec4 worldPos = %s;\r\n", worldPos->associatedVariableName().c_str());
    if (view()->isConnected()) {
      state.compilationString
        += StringTools::printf("mat4 view = %s;\r\n", view()->associatedVariableName().c_str());
    }
    EmitCodeFromIncludeOptions options;
    options.repeatKey = "maxSimultaneousLights";
    state.compilationString += state._emitCodeFromInclude("shadowsVertex", iComments, options);
  }
}

LightBlock& LightBlock::_buildBlock(NodeMaterialBuildState& state)
{
  NodeMaterialBlock::_buildBlock(state);

  if (state.target != NodeMaterialBlockTargets::Fragment) {
    // Vertex
    _injectVertexCode(state);

    return *this;
  }

  // Fragment
  state.sharedData->bindableBlocks.emplace_back(shared_from_this());
  state.sharedData->blocksWithDefines.emplace_back(shared_from_this());

  auto iComments       = StringTools::printf("//%s", name().c_str());
  const auto& worldPos = worldPosition();

  state._emitFunctionFromInclude("helperFunctions", iComments);

  EmitFunctionFromIncludeOptions options;
  options.replaceStrings = {StringsReplacement{
    "vPositionW",                                                               // search
    StringTools::printf("v_%s.xyz", worldPos->associatedVariableName().c_str()) // replace
  }};
  state._emitFunctionFromInclude("lightsFragmentFunctions", iComments, options);

  state._emitFunctionFromInclude("shadowsFragmentFunctions", iComments, options);

  if (!light) { // Emit for all lights
    state._emitFunctionFromInclude(
      state.supportUniformBuffers ? "lightUboDeclaration" : "lightFragmentDeclaration", iComments,
      EmitFunctionFromIncludeOptions{
        "maxSimultaneousLights" // repeatKey
      });
  }
  else {
    options.replaceStrings = {StringsReplacement{
      "{X}",                   // search
      std::to_string(_lightId) // replace
    }};

    state._emitFunctionFromInclude(state.supportUniformBuffers ? "lightUboDeclaration" :
                                                                 "lightFragmentDeclaration",
                                   iComments, options, std::to_string(_lightId));
  }

  // Code
  if (_lightId == 0) {
    if (state._registerTempVariable("viewDirectionW")) {
      state.compilationString += StringTools::printf(
        "vec3 viewDirectionW = normalize(%s - %s);\r\n",
        cameraPosition()->associatedVariableName().c_str(),
        StringTools::printf("v_%s.xyz", worldPos->associatedVariableName().c_str()).c_str());
    }
    state.compilationString += "lightingInfo info;\r\n";
    state.compilationString += "float shadow = 1.;\r\n";
    state.compilationString += StringTools::printf(
      "float glossiness = %s * %s;\r\n",
      glossiness()->isConnected() ? glossiness()->associatedVariableName().c_str() : "1.0",
      glossPower()->isConnected ? glossPower()->associatedVariableName().c_str() : "1024.0");
    state.compilationString += "vec3 diffuseBase = vec3(0., 0., 0.);\r\n";
    state.compilationString += "vec3 specularBase = vec3(0., 0., 0.);\r\n";
    state.compilationString += StringTools::printf("vec3 normalW = %s.xyz;\r\n",
                                                   worldNormal()->associatedVariableName().c_str());
  }

  if (light) {
    options.replaceStrings = {StringsReplacement{
      "{X}",                   // search
      std::to_string(_lightId) // replace
    }};
  }
  else {
    EmitCodeFromIncludeOptions includeOptions;
    includeOptions.repeatKey = "maxSimultaneousLights";
    state.compilationString
      += state._emitCodeFromInclude("lightFragment", iComments, includeOptions);
  }

  const auto& _diffuseOutput  = diffuseOutput();
  const auto& _specularOutput = specularOutput();

  state.compilationString
    += _declareOutput(_diffuseOutput, state)
       + StringTools::printf(
         " = diffuseBase%s;\r\n",
         diffuseColor()->isConnected() ?
           StringTools::printf(" * %s", diffuseColor()->associatedVariableName().c_str()).c_str() :
           "");
  if (_specularOutput->hasEndpoints()) {
    state.compilationString
      += _declareOutput(_specularOutput, state)
         + StringTools::printf(
           " = specularBase%s;\r\n",
           specularColor()->isConnected() ?
             StringTools::printf(" * %s", specularColor()->associatedVariableName().c_str())
               .c_str() :
             "");
  }

  if (shadow()->hasEndpoints()) {
    state.compilationString += _declareOutput(shadow, state) + " = shadow;\r\n";
  }

  return *this;
}

json LightBlock::serialize() const
{
  return nullptr;
}

void LightBlock::_deserialize(const json& /*serializationObject*/, Scene* /*scene*/,
                              const std::string& /*rootUrl*/)
{
}

} // end of namespace BABYLON
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: scuiimoptdlg.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2004-08-23 09:31:26 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#undef SC_DLLIMPLEMENTATION

#ifdef PCH
#include "ui_pch.hxx"
#endif

#pragma hdrstop

#include "scuiimoptdlg.hxx"
#include "scresid.hxx"
#include "imoptdlg.hrc"

#ifndef _RTL_TENCINFO_H
#include <rtl/tencinfo.h>
#endif
//========================================================================
// ScDelimiterTable
//========================================================================

class ScDelimiterTable
{
public:
        ScDelimiterTable( const String& rDelTab )
            :   theDelTab ( rDelTab ),
                cSep      ( '\t' ),
                nCount    ( rDelTab.GetTokenCount('\t') ),
                nIter     ( 0 )
            {}

    USHORT  GetCode( const String& rDelimiter ) const;
    String  GetDelimiter( sal_Unicode nCode ) const;

    String  FirstDel()  { nIter = 0; return theDelTab.GetToken( nIter, cSep ); }
    String  NextDel()   { nIter +=2; return theDelTab.GetToken( nIter, cSep ); }

private:
    const String        theDelTab;
    const sal_Unicode   cSep;
    const xub_StrLen    nCount;
    xub_StrLen          nIter;
};

//------------------------------------------------------------------------

USHORT ScDelimiterTable::GetCode( const String& rDel ) const
{
    sal_Unicode nCode = 0;
    xub_StrLen i = 0;

    if ( nCount >= 2 )
    {
        while ( i<nCount )
        {
            if ( rDel == theDelTab.GetToken( i, cSep ) )
            {
                nCode = (sal_Unicode) theDelTab.GetToken( i+1, cSep ).ToInt32();
                i     = nCount;
            }
            else
                i += 2;
        }
    }

    return nCode;
}

//------------------------------------------------------------------------

String ScDelimiterTable::GetDelimiter( sal_Unicode nCode ) const
{
    String aStrDel;
    xub_StrLen i = 0;

    if ( nCount >= 2 )
    {
        while ( i<nCount )
        {
            if ( nCode == (sal_Unicode) theDelTab.GetToken( i+1, cSep ).ToInt32() )
            {
                aStrDel = theDelTab.GetToken( i, cSep );
                i       = nCount;
            }
            else
                i += 2;
        }
    }

    return aStrDel;
}

//========================================================================
// ScImportOptionsDlg
//========================================================================

ScImportOptionsDlg::ScImportOptionsDlg(
        Window*                 pParent,
        BOOL                    bAscii,
        const ScImportOptions*  pOptions,
        const String*           pStrTitle,
        BOOL                    bMultiByte,
        BOOL                    bOnlyDbtoolsEncodings,
        BOOL                    bImport )

    :   ModalDialog ( pParent, ScResId( RID_SCDLG_IMPORTOPT ) ),
        aBtnOk      ( this, ScResId( BTN_OK ) ),
        aBtnCancel  ( this, ScResId( BTN_CANCEL ) ),
        aBtnHelp    ( this, ScResId( BTN_HELP ) ),
        aFtFieldSep ( this, ScResId( FT_FIELDSEP ) ),
        aEdFieldSep ( this, ScResId( ED_FIELDSEP ) ),
        aFtTextSep  ( this, ScResId( FT_TEXTSEP ) ),
        aEdTextSep  ( this, ScResId( ED_TEXTSEP ) ),
        aFtFont     ( this, ScResId( FT_FONT ) ),
        aLbFont     ( this, ScResId( bAscii ? DDLB_FONT : LB_FONT ) ),
        aFlFieldOpt ( this, ScResId( FL_FIELDOPT ) ),
        aCbFixed    ( this, ScResId( CB_FIXEDWIDTH ) )
{
    // im Ctor-Initializer nicht moeglich (MSC kann das nicht):
    pFieldSepTab = new ScDelimiterTable( String(ScResId(SCSTR_FIELDSEP)) );
    pTextSepTab  = new ScDelimiterTable( String(ScResId(SCSTR_TEXTSEP)) );

    String aStr = pFieldSepTab->FirstDel();
    sal_Unicode nCode;

    while ( aStr.Len() > 0 )
    {
        aEdFieldSep.InsertEntry( aStr );
        aStr = pFieldSepTab->NextDel();
    }

    aStr = pTextSepTab->FirstDel();

    while ( aStr.Len() > 0 )
    {
        aEdTextSep.InsertEntry( aStr );
        aStr = pTextSepTab->NextDel();
    }

    aEdFieldSep.SetText( aEdFieldSep.GetEntry(0) );
    aEdTextSep.SetText( aEdTextSep.GetEntry(0) );

    if ( bOnlyDbtoolsEncodings )
    {   //!TODO: Unicode and MultiByte would need work in each filter
        // Think of field lengths in dBase export
        if ( bMultiByte )
            aLbFont.FillFromDbTextEncodingMap( bImport, RTL_TEXTENCODING_INFO_UNICODE );
        else
            aLbFont.FillFromDbTextEncodingMap( bImport, RTL_TEXTENCODING_INFO_UNICODE |
                RTL_TEXTENCODING_INFO_MULTIBYTE );
    }
    else if ( !bAscii )
    {   //!TODO: Unicode would need work in each filter
        if ( bMultiByte )
            aLbFont.FillFromTextEncodingTable( bImport, RTL_TEXTENCODING_INFO_UNICODE );
        else
            aLbFont.FillFromTextEncodingTable( bImport, RTL_TEXTENCODING_INFO_UNICODE |
                RTL_TEXTENCODING_INFO_MULTIBYTE );
    }
    else
    {
        if ( pOptions )
        {
            nCode = pOptions->nFieldSepCode;
            aStr  = pFieldSepTab->GetDelimiter( nCode );

            if ( !aStr.Len() )
                aEdFieldSep.SetText( String((sal_Unicode)nCode) );
            else
                aEdFieldSep.SetText( aStr );

            nCode = pOptions->nTextSepCode;
            aStr  = pTextSepTab->GetDelimiter( nCode );

            if ( !aStr.Len() )
                aEdTextSep.SetText( String((sal_Unicode)nCode) );
            else
                aEdTextSep.SetText( aStr );
        }
        // all encodings allowed, even Unicode
        aLbFont.FillFromTextEncodingTable( bImport );
    }

    if( bAscii )
    {
        Size aWinSize( GetSizePixel() );
        aWinSize.Height() = aCbFixed.GetPosPixel().Y() + aCbFixed.GetSizePixel().Height();
        Size aDiffSize( LogicToPixel( Size( 0, 6 ), MapMode( MAP_APPFONT ) ) );
        aWinSize.Height() += aDiffSize.Height();
        SetSizePixel( aWinSize );
        aCbFixed.Show();
        aCbFixed.SetClickHdl( LINK( this, ScImportOptionsDlg, FixedWidthHdl ) );
        aCbFixed.Check( FALSE );
    }
    else
    {
        aFlFieldOpt.SetText( aFtFont.GetText() );
        aFtFieldSep.Hide();
        aFtTextSep.Hide();
        aFtFont.Hide();
        aEdFieldSep.Hide();
        aEdTextSep.Hide();
        aCbFixed.Hide();
        aLbFont.GrabFocus();
        aLbFont.SetDoubleClickHdl( LINK( this, ScImportOptionsDlg, DoubleClickHdl ) );
    }

    aLbFont.SelectTextEncoding( pOptions ? pOptions->eCharSet :
        gsl_getSystemTextEncoding() );

    // optionaler Titel:
    if ( pStrTitle )
        SetText( *pStrTitle );

    FreeResource();
}

//------------------------------------------------------------------------

__EXPORT ScImportOptionsDlg::~ScImportOptionsDlg()
{
    delete pFieldSepTab;
    delete pTextSepTab;
}

//------------------------------------------------------------------------

void ScImportOptionsDlg::GetImportOptions( ScImportOptions& rOptions ) const
{
    rOptions.SetTextEncoding( aLbFont.GetSelectTextEncoding() );

    if ( aCbFixed.IsVisible() )
    {
        rOptions.nFieldSepCode = GetCodeFromCombo( aEdFieldSep );
        rOptions.nTextSepCode  = GetCodeFromCombo( aEdTextSep );
        rOptions.bFixedWidth = aCbFixed.IsChecked();
    }
}

//------------------------------------------------------------------------

USHORT ScImportOptionsDlg::GetCodeFromCombo( const ComboBox& rEd ) const
{
    ScDelimiterTable* pTab;
    String  aStr( rEd.GetText() );
    USHORT  nCode;

    if ( &rEd == &aEdTextSep )
        pTab = pTextSepTab;
    else
        pTab = pFieldSepTab;

    if ( !aStr.Len() )
    {
        nCode = 0;          // kein Trennzeichen
    }
    else
    {
        nCode = pTab->GetCode( aStr );

        if ( nCode == 0 )
            nCode = (USHORT)aStr.GetChar(0);
    }

    return nCode;
}

//------------------------------------------------------------------------

IMPL_LINK( ScImportOptionsDlg, FixedWidthHdl, CheckBox*, pCheckBox )
{
    if( pCheckBox == &aCbFixed )
    {
        BOOL bEnable = !aCbFixed.IsChecked();
        aFtFieldSep.Enable( bEnable );
        aEdFieldSep.Enable( bEnable );
        aFtTextSep.Enable( bEnable );
        aEdTextSep.Enable( bEnable );
    }
    return 0;
}

 IMPL_LINK( ScImportOptionsDlg, DoubleClickHdl, ListBox*, pLb )
{
    if ( pLb == &aLbFont )
    {
        aBtnOk.Click();
    }
    return 0;
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.346); FILE MERGED 2005/09/05 15:04:25 rt 1.3.346.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: scuiimoptdlg.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 20:41:54 $
 *
 *  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
 *
 ************************************************************************/

#undef SC_DLLIMPLEMENTATION

#ifdef PCH
#include "ui_pch.hxx"
#endif

#pragma hdrstop

#include "scuiimoptdlg.hxx"
#include "scresid.hxx"
#include "imoptdlg.hrc"

#ifndef _RTL_TENCINFO_H
#include <rtl/tencinfo.h>
#endif
//========================================================================
// ScDelimiterTable
//========================================================================

class ScDelimiterTable
{
public:
        ScDelimiterTable( const String& rDelTab )
            :   theDelTab ( rDelTab ),
                cSep      ( '\t' ),
                nCount    ( rDelTab.GetTokenCount('\t') ),
                nIter     ( 0 )
            {}

    USHORT  GetCode( const String& rDelimiter ) const;
    String  GetDelimiter( sal_Unicode nCode ) const;

    String  FirstDel()  { nIter = 0; return theDelTab.GetToken( nIter, cSep ); }
    String  NextDel()   { nIter +=2; return theDelTab.GetToken( nIter, cSep ); }

private:
    const String        theDelTab;
    const sal_Unicode   cSep;
    const xub_StrLen    nCount;
    xub_StrLen          nIter;
};

//------------------------------------------------------------------------

USHORT ScDelimiterTable::GetCode( const String& rDel ) const
{
    sal_Unicode nCode = 0;
    xub_StrLen i = 0;

    if ( nCount >= 2 )
    {
        while ( i<nCount )
        {
            if ( rDel == theDelTab.GetToken( i, cSep ) )
            {
                nCode = (sal_Unicode) theDelTab.GetToken( i+1, cSep ).ToInt32();
                i     = nCount;
            }
            else
                i += 2;
        }
    }

    return nCode;
}

//------------------------------------------------------------------------

String ScDelimiterTable::GetDelimiter( sal_Unicode nCode ) const
{
    String aStrDel;
    xub_StrLen i = 0;

    if ( nCount >= 2 )
    {
        while ( i<nCount )
        {
            if ( nCode == (sal_Unicode) theDelTab.GetToken( i+1, cSep ).ToInt32() )
            {
                aStrDel = theDelTab.GetToken( i, cSep );
                i       = nCount;
            }
            else
                i += 2;
        }
    }

    return aStrDel;
}

//========================================================================
// ScImportOptionsDlg
//========================================================================

ScImportOptionsDlg::ScImportOptionsDlg(
        Window*                 pParent,
        BOOL                    bAscii,
        const ScImportOptions*  pOptions,
        const String*           pStrTitle,
        BOOL                    bMultiByte,
        BOOL                    bOnlyDbtoolsEncodings,
        BOOL                    bImport )

    :   ModalDialog ( pParent, ScResId( RID_SCDLG_IMPORTOPT ) ),
        aBtnOk      ( this, ScResId( BTN_OK ) ),
        aBtnCancel  ( this, ScResId( BTN_CANCEL ) ),
        aBtnHelp    ( this, ScResId( BTN_HELP ) ),
        aFtFieldSep ( this, ScResId( FT_FIELDSEP ) ),
        aEdFieldSep ( this, ScResId( ED_FIELDSEP ) ),
        aFtTextSep  ( this, ScResId( FT_TEXTSEP ) ),
        aEdTextSep  ( this, ScResId( ED_TEXTSEP ) ),
        aFtFont     ( this, ScResId( FT_FONT ) ),
        aLbFont     ( this, ScResId( bAscii ? DDLB_FONT : LB_FONT ) ),
        aFlFieldOpt ( this, ScResId( FL_FIELDOPT ) ),
        aCbFixed    ( this, ScResId( CB_FIXEDWIDTH ) )
{
    // im Ctor-Initializer nicht moeglich (MSC kann das nicht):
    pFieldSepTab = new ScDelimiterTable( String(ScResId(SCSTR_FIELDSEP)) );
    pTextSepTab  = new ScDelimiterTable( String(ScResId(SCSTR_TEXTSEP)) );

    String aStr = pFieldSepTab->FirstDel();
    sal_Unicode nCode;

    while ( aStr.Len() > 0 )
    {
        aEdFieldSep.InsertEntry( aStr );
        aStr = pFieldSepTab->NextDel();
    }

    aStr = pTextSepTab->FirstDel();

    while ( aStr.Len() > 0 )
    {
        aEdTextSep.InsertEntry( aStr );
        aStr = pTextSepTab->NextDel();
    }

    aEdFieldSep.SetText( aEdFieldSep.GetEntry(0) );
    aEdTextSep.SetText( aEdTextSep.GetEntry(0) );

    if ( bOnlyDbtoolsEncodings )
    {   //!TODO: Unicode and MultiByte would need work in each filter
        // Think of field lengths in dBase export
        if ( bMultiByte )
            aLbFont.FillFromDbTextEncodingMap( bImport, RTL_TEXTENCODING_INFO_UNICODE );
        else
            aLbFont.FillFromDbTextEncodingMap( bImport, RTL_TEXTENCODING_INFO_UNICODE |
                RTL_TEXTENCODING_INFO_MULTIBYTE );
    }
    else if ( !bAscii )
    {   //!TODO: Unicode would need work in each filter
        if ( bMultiByte )
            aLbFont.FillFromTextEncodingTable( bImport, RTL_TEXTENCODING_INFO_UNICODE );
        else
            aLbFont.FillFromTextEncodingTable( bImport, RTL_TEXTENCODING_INFO_UNICODE |
                RTL_TEXTENCODING_INFO_MULTIBYTE );
    }
    else
    {
        if ( pOptions )
        {
            nCode = pOptions->nFieldSepCode;
            aStr  = pFieldSepTab->GetDelimiter( nCode );

            if ( !aStr.Len() )
                aEdFieldSep.SetText( String((sal_Unicode)nCode) );
            else
                aEdFieldSep.SetText( aStr );

            nCode = pOptions->nTextSepCode;
            aStr  = pTextSepTab->GetDelimiter( nCode );

            if ( !aStr.Len() )
                aEdTextSep.SetText( String((sal_Unicode)nCode) );
            else
                aEdTextSep.SetText( aStr );
        }
        // all encodings allowed, even Unicode
        aLbFont.FillFromTextEncodingTable( bImport );
    }

    if( bAscii )
    {
        Size aWinSize( GetSizePixel() );
        aWinSize.Height() = aCbFixed.GetPosPixel().Y() + aCbFixed.GetSizePixel().Height();
        Size aDiffSize( LogicToPixel( Size( 0, 6 ), MapMode( MAP_APPFONT ) ) );
        aWinSize.Height() += aDiffSize.Height();
        SetSizePixel( aWinSize );
        aCbFixed.Show();
        aCbFixed.SetClickHdl( LINK( this, ScImportOptionsDlg, FixedWidthHdl ) );
        aCbFixed.Check( FALSE );
    }
    else
    {
        aFlFieldOpt.SetText( aFtFont.GetText() );
        aFtFieldSep.Hide();
        aFtTextSep.Hide();
        aFtFont.Hide();
        aEdFieldSep.Hide();
        aEdTextSep.Hide();
        aCbFixed.Hide();
        aLbFont.GrabFocus();
        aLbFont.SetDoubleClickHdl( LINK( this, ScImportOptionsDlg, DoubleClickHdl ) );
    }

    aLbFont.SelectTextEncoding( pOptions ? pOptions->eCharSet :
        gsl_getSystemTextEncoding() );

    // optionaler Titel:
    if ( pStrTitle )
        SetText( *pStrTitle );

    FreeResource();
}

//------------------------------------------------------------------------

__EXPORT ScImportOptionsDlg::~ScImportOptionsDlg()
{
    delete pFieldSepTab;
    delete pTextSepTab;
}

//------------------------------------------------------------------------

void ScImportOptionsDlg::GetImportOptions( ScImportOptions& rOptions ) const
{
    rOptions.SetTextEncoding( aLbFont.GetSelectTextEncoding() );

    if ( aCbFixed.IsVisible() )
    {
        rOptions.nFieldSepCode = GetCodeFromCombo( aEdFieldSep );
        rOptions.nTextSepCode  = GetCodeFromCombo( aEdTextSep );
        rOptions.bFixedWidth = aCbFixed.IsChecked();
    }
}

//------------------------------------------------------------------------

USHORT ScImportOptionsDlg::GetCodeFromCombo( const ComboBox& rEd ) const
{
    ScDelimiterTable* pTab;
    String  aStr( rEd.GetText() );
    USHORT  nCode;

    if ( &rEd == &aEdTextSep )
        pTab = pTextSepTab;
    else
        pTab = pFieldSepTab;

    if ( !aStr.Len() )
    {
        nCode = 0;          // kein Trennzeichen
    }
    else
    {
        nCode = pTab->GetCode( aStr );

        if ( nCode == 0 )
            nCode = (USHORT)aStr.GetChar(0);
    }

    return nCode;
}

//------------------------------------------------------------------------

IMPL_LINK( ScImportOptionsDlg, FixedWidthHdl, CheckBox*, pCheckBox )
{
    if( pCheckBox == &aCbFixed )
    {
        BOOL bEnable = !aCbFixed.IsChecked();
        aFtFieldSep.Enable( bEnable );
        aEdFieldSep.Enable( bEnable );
        aFtTextSep.Enable( bEnable );
        aEdTextSep.Enable( bEnable );
    }
    return 0;
}

 IMPL_LINK( ScImportOptionsDlg, DoubleClickHdl, ListBox*, pLb )
{
    if ( pLb == &aLbFont )
    {
        aBtnOk.Click();
    }
    return 0;
}
<|endoftext|>