<commit_before>//   Copyright 2016-2020 Jean-Francois Poilpret
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

/// @cond notdocumented

#include "../flash.h"
#include "../streams.h"
#include "vl53l0x_types.h"

namespace devices::vl53l0x
{
	static const flash::FlashStorage* convert(DeviceError error)
	{
		switch (error)
		{
			case DeviceError::NONE:
			return F("NONE");

			case DeviceError::VCSEL_CONTINUITY_TEST_FAILURE:
			return F("VCSEL_CONTINUITY_TEST_FAILURE");

			case DeviceError::VCSEL_WATCHDOG_TEST_FAILURE:
			return F("VCSEL_WATCHDOG_TEST_FAILURE");

			case DeviceError::NO_VHV_VALUE_FOUND:
			return F("NO_VHV_VALUE_FOUND");

			case DeviceError::MSRC_NO_TARGET:
			return F("MSRC_NO_TARGET");

			case DeviceError::SNR_CHECK:
			return F("SNR_CHECK");

			case DeviceError::RANGE_PHASE_CHECK:
			return F("RANGE_PHASE_CHECK");

			case DeviceError::SIGMA_THRESHOLD_CHECK:
			return F("SIGMA_THRESHOLD_CHECK");

			case DeviceError::TCC:
			return F("TCC");

			case DeviceError::PHASE_CONSISTENCY:
			return F("PHASE_CONSISTENCY");

			case DeviceError::MIN_CLIP:
			return F("MIN_CLIP");

			case DeviceError::RANGE_COMPLETE:
			return F("RANGE_COMPLETE");

			case DeviceError::ALGO_UNDERFLOW:
			return F("ALGO_UNDERFLOW");

			case DeviceError::ALGO_OVERFLOW:
			return F("ALGO_OVERFLOW");

			case DeviceError::RANGE_IGNORE_THRESHOLD:
			return F("RANGE_IGNORE_THRESHOLD");

			case DeviceError::UNKNOWN:
			return F("UNKNOWN");
		}
	}

	streams::ostream& operator<<(streams::ostream& out, DeviceError error)
	{
		return out << convert(error) << streams::flush;
	}

	streams::ostream& operator<<(streams::ostream& out, DeviceStatus status)
	{
		return out << '(' << status.error() << ',' << status.data_ready() << ')' << streams::flush;
	}

	static const flash::FlashStorage* convert(PowerMode mode)
	{
		switch (mode)
		{
			case PowerMode::IDLE:
			return F("IDLE");

			case PowerMode::STANDBY:
			return F("STANDBY");
		}
	}

	streams::ostream& operator<<(streams::ostream& out, PowerMode mode)
	{
		return out << convert(mode) << streams::flush;
	}

	static const flash::FlashStorage* convert(GPIOFunction function)
	{
		switch (function)
		{
			case GPIOFunction::DISABLED:
			return F("DISABLED");

			case GPIOFunction::LEVEL_LOW:
			return F("LEVEL_LOW");

			case GPIOFunction::LEVEL_HIGH:
			return F("LEVEL_HIGH");

			case GPIOFunction::OUT_OF_WINDOW:
			return F("OUT_OF_WINDOW");

			case GPIOFunction::SAMPLE_READY:
			return F("SAMPLE_READY");
		}
	}

	streams::ostream& operator<<(streams::ostream& out, GPIOFunction function)
	{
		return out << convert(function) << streams::flush;
	}

	streams::ostream& operator<<(streams::ostream& out, const GPIOSettings& settings)
	{
		return out	<< F("(GPIO function=")
					<< streams::dec << settings.function() << streams::flush
					<< F(", ") << (settings.high_polarity() ? F("HIGH") : F("LOW")) << F(" polarity") << streams::flush
					<< F(", low_threshold=") << streams::hex << settings.low_threshold()  << streams::flush
					<< F(", high_threshold=") << streams::hex << settings.high_threshold() << ')' << streams::flush;
	}

	static streams::ostream& with_without(streams::ostream& out, bool with, const flash::FlashStorage* label)
	{
		if (!with)
			out << F("no ");
		return out << label << streams::flush;
	}

	streams::ostream& operator<<(streams::ostream& out, SequenceSteps steps)
	{
		out << '(';
		with_without(out, steps.is_tcc(), F("TCC")) << ',';
		with_without(out, steps.is_dss(), F("DSS")) << ',';
		with_without(out, steps.is_msrc(), F("MSRC")) << ',';
		with_without(out, steps.is_pre_range(), F("PRE_RANGE")) << ',';
		return with_without(out, steps.is_final_range(), F("FINAL_RANGE")) << ')' << streams::flush;
	}

	streams::ostream& operator<<(streams::ostream& out, SPADInfo info)
	{
		return out	<< F("(aperture=") << info.is_aperture()
					<< F(", count=") << streams::dec << info.count() << ')' << streams::flush;
	}

	streams::ostream& operator<<(streams::ostream& out, const SequenceStepsTimeout& timeouts)
	{
		return out	<< F("(pre_range_vcsel_period_pclks=")
					<< streams::dec << timeouts.pre_range_vcsel_period_pclks() << streams::flush
					<< F(", final_range_vcsel_period_pclks")
					<< timeouts.final_range_vcsel_period_pclks() << streams::flush
					<< F(", msrc_dss_tcc_mclks")
					<< timeouts.msrc_dss_tcc_mclks() << streams::flush
					<< F(", pre_range_mclks")
					<< timeouts.pre_range_mclks() << streams::flush
					<< F(", final_range_mclks(with pre-range)")
					<< timeouts.final_range_mclks(true) << ')' << streams::flush
					<< F(", final_range_mclks(no pre-range)")
					<< timeouts.final_range_mclks(false) << ')' << streams::flush;
	}
}

/// @endcond
<commit_msg>Fix output of VL53L0X type.<commit_after>//   Copyright 2016-2020 Jean-Francois Poilpret
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

/// @cond notdocumented

#include "../flash.h"
#include "../streams.h"
#include "vl53l0x_types.h"

namespace devices::vl53l0x
{
	static const flash::FlashStorage* convert(DeviceError error)
	{
		switch (error)
		{
			case DeviceError::NONE:
			return F("NONE");

			case DeviceError::VCSEL_CONTINUITY_TEST_FAILURE:
			return F("VCSEL_CONTINUITY_TEST_FAILURE");

			case DeviceError::VCSEL_WATCHDOG_TEST_FAILURE:
			return F("VCSEL_WATCHDOG_TEST_FAILURE");

			case DeviceError::NO_VHV_VALUE_FOUND:
			return F("NO_VHV_VALUE_FOUND");

			case DeviceError::MSRC_NO_TARGET:
			return F("MSRC_NO_TARGET");

			case DeviceError::SNR_CHECK:
			return F("SNR_CHECK");

			case DeviceError::RANGE_PHASE_CHECK:
			return F("RANGE_PHASE_CHECK");

			case DeviceError::SIGMA_THRESHOLD_CHECK:
			return F("SIGMA_THRESHOLD_CHECK");

			case DeviceError::TCC:
			return F("TCC");

			case DeviceError::PHASE_CONSISTENCY:
			return F("PHASE_CONSISTENCY");

			case DeviceError::MIN_CLIP:
			return F("MIN_CLIP");

			case DeviceError::RANGE_COMPLETE:
			return F("RANGE_COMPLETE");

			case DeviceError::ALGO_UNDERFLOW:
			return F("ALGO_UNDERFLOW");

			case DeviceError::ALGO_OVERFLOW:
			return F("ALGO_OVERFLOW");

			case DeviceError::RANGE_IGNORE_THRESHOLD:
			return F("RANGE_IGNORE_THRESHOLD");

			case DeviceError::UNKNOWN:
			return F("UNKNOWN");
		}
	}

	streams::ostream& operator<<(streams::ostream& out, DeviceError error)
	{
		return out << convert(error) << streams::flush;
	}

	streams::ostream& operator<<(streams::ostream& out, DeviceStatus status)
	{
		return out << '(' << status.error() << ',' << status.data_ready() << ')' << streams::flush;
	}

	static const flash::FlashStorage* convert(PowerMode mode)
	{
		switch (mode)
		{
			case PowerMode::IDLE:
			return F("IDLE");

			case PowerMode::STANDBY:
			return F("STANDBY");
		}
	}

	streams::ostream& operator<<(streams::ostream& out, PowerMode mode)
	{
		return out << convert(mode) << streams::flush;
	}

	static const flash::FlashStorage* convert(GPIOFunction function)
	{
		switch (function)
		{
			case GPIOFunction::DISABLED:
			return F("DISABLED");

			case GPIOFunction::LEVEL_LOW:
			return F("LEVEL_LOW");

			case GPIOFunction::LEVEL_HIGH:
			return F("LEVEL_HIGH");

			case GPIOFunction::OUT_OF_WINDOW:
			return F("OUT_OF_WINDOW");

			case GPIOFunction::SAMPLE_READY:
			return F("SAMPLE_READY");
		}
	}

	streams::ostream& operator<<(streams::ostream& out, GPIOFunction function)
	{
		return out << convert(function) << streams::flush;
	}

	streams::ostream& operator<<(streams::ostream& out, const GPIOSettings& settings)
	{
		return out	<< F("(GPIO function=")
					<< streams::dec << settings.function() << streams::flush
					<< F(", ") << (settings.high_polarity() ? F("HIGH") : F("LOW")) << F(" polarity") << streams::flush
					<< F(", low_threshold=") << streams::hex << settings.low_threshold()  << streams::flush
					<< F(", high_threshold=") << streams::hex << settings.high_threshold() << ')' << streams::flush;
	}

	static streams::ostream& with_without(streams::ostream& out, bool with, const flash::FlashStorage* label)
	{
		if (!with)
			out << F("no ");
		return out << label << streams::flush;
	}

	streams::ostream& operator<<(streams::ostream& out, SequenceSteps steps)
	{
		out << '(';
		with_without(out, steps.is_tcc(), F("TCC")) << ',';
		with_without(out, steps.is_dss(), F("DSS")) << ',';
		with_without(out, steps.is_msrc(), F("MSRC")) << ',';
		with_without(out, steps.is_pre_range(), F("PRE_RANGE")) << ',';
		return with_without(out, steps.is_final_range(), F("FINAL_RANGE")) << ')' << streams::flush;
	}

	streams::ostream& operator<<(streams::ostream& out, SPADInfo info)
	{
		return out	<< F("(aperture=") << info.is_aperture()
					<< F(", count=") << streams::dec << info.count() << ')' << streams::flush;
	}

	streams::ostream& operator<<(streams::ostream& out, const SequenceStepsTimeout& timeouts)
	{
		return out	<< F("(pre_range_vcsel_period_pclks=")
					<< streams::dec << timeouts.pre_range_vcsel_period_pclks() << streams::flush
					<< F(", final_range_vcsel_period_pclks=")
					<< timeouts.final_range_vcsel_period_pclks() << streams::flush
					<< F(", msrc_dss_tcc_mclks=")
					<< timeouts.msrc_dss_tcc_mclks() << streams::flush
					<< F(", pre_range_mclks=")
					<< timeouts.pre_range_mclks() << streams::flush
					<< F(", final_range_mclks(with pre-range)=")
					<< timeouts.final_range_mclks(true) << ')' << streams::flush
					<< F(", final_range_mclks(no pre-range)=")
					<< timeouts.final_range_mclks(false) << ')' << streams::flush;
	}
}

/// @endcond
<|endoftext|>


<commit_before>#pragma once
//=====================================================================//
/*!	@file
	@brief	RX programmer クラス
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "rx63t_protocol.hpp"
#include "rx24t_protocol.hpp"
#include <boost/format.hpp>
#include <boost/variant.hpp>

namespace rx {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief	rx_prog クラス
	 */
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	class prog {
		bool		verbose_;

		utils::rs232c_io	rs232c_;

		using protocol_type = boost::variant<rx63t::protocol, rx24t::protocol>;
		protocol_type protocol_;

		std::string out_section_(uint32_t n, uint32_t num) const {
			return (boost::format("#%02d/%02d: ") % n % num).str();
		}

		struct bind_visitor {
			using result_type = bool;

			const std::string& path_;
			uint32_t brate_;
			const rx::protocol::rx_t& rx_;

			bind_visitor(const std::string& path, uint32_t brate, const rx::protocol::rx_t& rx) :
				path_(path), brate_(brate), rx_(rx) { }

    		template <class T>
    		bool operator()(T& x) {
				return x.bind(path_, brate_, rx_);
			}
		};

		struct read_visitor {
			using result_type = bool;

			uint32_t adr_;
			uint8_t* dst_;
			uint32_t len_;
			read_visitor(uint32_t adr, uint8_t* dst, uint32_t len) : adr_(adr), dst_(dst), len_(len) { }

    		template <class T>
    		bool operator()(T& x) {
				return x.read(adr_, dst_, len_);
			}
		};

		struct select_write_visitor {
			using result_type = bool;

			bool	data_;
			select_write_visitor(bool data) : data_(data) { }

    		template <class T>
    		bool operator()(T& x) {
				return x.select_write_area(data_);
			}
		};

		struct write_visitor {
			using result_type = bool;

			uint32_t adr_;
			const uint8_t* src_;
			write_visitor(uint32_t adr, const uint8_t* src) : adr_(adr), src_(src) { }

    		template <class T>
    		bool operator()(T& x) {
				return x.write_page(adr_, src_);
			}
		};

		struct end_visitor {
			using result_type = void;

    		template <class T>
    		void operator()(T& x) {
				x.end();
			}
		};

	public:
		//-------------------------------------------------------------//
		/*!
			@brief	コンストラクター
		*/
		//-------------------------------------------------------------//
		prog(bool verbose = false) : verbose_(verbose) { }

		//-------------------------------------------------------------//
		/*!
			@brief	接続速度を変更する
			@param[in]	path	シリアル・デバイス・パス
			@param[in]	brate	ボーレート
			@param[in]	rx		CPU 設定
			@return エラー無ければ「true」
		*/
		//-------------------------------------------------------------//
		bool start(const std::string& path, uint32_t brate, const rx::protocol::rx_t& rx)
		{
			if(rx.cpu_type_ == "RX63T") {
				protocol_ = rx63t::protocol();
			} else if(rx.cpu_type_ == "RX24T") {
				protocol_ = rx24t::protocol();
			} else {
				std::cerr << "CPU type missmatch: '" << rx.cpu_type_ << "'" << std::endl;
				return false;
			}

			{  // 開始
				bind_visitor vis(path, brate, rx);
            	if(!boost::apply_visitor(vis, protocol_)) {
					end();
					return false;
				}
			}

			return true;
		}

		//-------------------------------------------------------------//
		/*!
			@brief	リード
			@param[in]	adr	開始アドレス
			@param[out]	dst	書き込みアドレス
			@param[in]	len	読み出しサイズ
			@return 成功なら「true」
		*/
		//-------------------------------------------------------------//
		bool read(uint32_t adr, uint8_t* dst, uint32_t len) {
			read_visitor vis(adr, dst, len);
           	if(!boost::apply_visitor(vis, protocol_)) {
				end();
				std::cerr << "Read error." << std::endl;
				return false;
			}
			return true;
		}

		//-------------------------------------------------------------//
		/*!
			@brief	ベリファイ
			@param[in]	adr	開始アドレス
			@param[in]	src	書き込みアドレス
			@param[in]	len	読み出しサイズ
			@return 成功なら「true」
		*/
		//-------------------------------------------------------------//
		bool verify(uint32_t adr, const uint8_t* src, uint32_t len) {
			std::vector<uint8_t> dev;
			dev.resize(len);
			if(!read(adr, &dev[0], len)) {
				return false;
			}
			uint32_t errcnt = 0;
			for(auto d : dev) {
				auto m = *src++;
				if(d != m) {
					++errcnt;
					if(verbose_) {
						std::cerr << (boost::format("0x%08X: D(%02X) to M(%02X)") % adr %
							static_cast<uint32_t>(d) % static_cast<uint32_t>(m)) << std::endl;
					}
				}
				++adr;
			}
			if(errcnt > 0) {
				std::cerr << "Verify error: " << errcnt << std::endl;
				return false;
			}
			return true;
		}

		//-------------------------------------------------------------//
		/*!
			@brief	ライト開始
			@param[in]	data	「true」ならデータ領域
			@return 成功なら「true」
		*/
		//-------------------------------------------------------------//
		bool start_write(bool data) {
			select_write_visitor vis(data);
           	if(!boost::apply_visitor(vis, protocol_)) {
				end();
				std::cerr << "Write start error.(first)" << std::endl;
				return false;
			}
			return true;
		}

		//-------------------------------------------------------------//
		/*!
			@brief	ライト（２５６バイト）
			@param[in]	adr	開始アドレス
			@param[in]	src	書き込みアドレス
			@return 成功なら「true」
		*/
		//-------------------------------------------------------------//
		bool write(uint32_t adr, const uint8_t* src) {
			write_visitor vis(adr, src);
           	if(!boost::apply_visitor(vis, protocol_)) {
				end();
				std::cerr << "Write body error." << std::endl;
				return false;
			}
			return true;
		}

		//-------------------------------------------------------------//
		/*!
			@brief	ライト終了
			@return 成功なら「true」
		*/
		//-------------------------------------------------------------//
		bool final_write() {
			write_visitor vis(0xffffffff, nullptr);
           	if(!boost::apply_visitor(vis, protocol_)) {
				end();
				std::cerr << "Write final error. (fin)" << std::endl;
				return false;
			}
			return true;
		}

		//-------------------------------------------------------------//
		/*!
			@brief	終了
		*/
		//-------------------------------------------------------------//
		void end() {
			end_visitor vis;
           	boost::apply_visitor(vis, protocol_);
		}
	};
}
<commit_msg>add RX64M protocol<commit_after>#pragma once
//=====================================================================//
/*!	@file
	@brief	RX programmer クラス
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "rx63t_protocol.hpp"
#include "rx24t_protocol.hpp"
#include "rx64m_protocol.hpp"
#include <boost/format.hpp>
#include <boost/variant.hpp>

namespace rx {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief	rx_prog クラス
	 */
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	class prog {
		bool		verbose_;

		utils::rs232c_io	rs232c_;

		using protocol_type = boost::variant<rx63t::protocol, rx24t::protocol, rx64m::protocol>;
		protocol_type protocol_;

		std::string out_section_(uint32_t n, uint32_t num) const {
			return (boost::format("#%02d/%02d: ") % n % num).str();
		}

		struct bind_visitor {
			using result_type = bool;

			const std::string& path_;
			uint32_t brate_;
			const rx::protocol::rx_t& rx_;

			bind_visitor(const std::string& path, uint32_t brate, const rx::protocol::rx_t& rx) :
				path_(path), brate_(brate), rx_(rx) { }

    		template <class T>
    		bool operator()(T& x) {
				return x.bind(path_, brate_, rx_);
			}
		};

		struct read_visitor {
			using result_type = bool;

			uint32_t adr_;
			uint8_t* dst_;
			uint32_t len_;
			read_visitor(uint32_t adr, uint8_t* dst, uint32_t len) : adr_(adr), dst_(dst), len_(len) { }

    		template <class T>
    		bool operator()(T& x) {
				return x.read(adr_, dst_, len_);
			}
		};

		struct select_write_visitor {
			using result_type = bool;

			bool	data_;
			select_write_visitor(bool data) : data_(data) { }

    		template <class T>
    		bool operator()(T& x) {
				return x.select_write_area(data_);
			}
		};

		struct write_visitor {
			using result_type = bool;

			uint32_t adr_;
			const uint8_t* src_;
			write_visitor(uint32_t adr, const uint8_t* src) : adr_(adr), src_(src) { }

    		template <class T>
    		bool operator()(T& x) {
				return x.write_page(adr_, src_);
			}
		};

		struct end_visitor {
			using result_type = void;

    		template <class T>
    		void operator()(T& x) {
				x.end();
			}
		};

	public:
		//-------------------------------------------------------------//
		/*!
			@brief	コンストラクター
		*/
		//-------------------------------------------------------------//
		prog(bool verbose = false) : verbose_(verbose) { }

		//-------------------------------------------------------------//
		/*!
			@brief	接続速度を変更する
			@param[in]	path	シリアル・デバイス・パス
			@param[in]	brate	ボーレート
			@param[in]	rx		CPU 設定
			@return エラー無ければ「true」
		*/
		//-------------------------------------------------------------//
		bool start(const std::string& path, uint32_t brate, const rx::protocol::rx_t& rx)
		{
			if(rx.cpu_type_ == "RX63T") {
				protocol_ = rx63t::protocol();
			} else if(rx.cpu_type_ == "RX24T") {
				protocol_ = rx24t::protocol();
			} else if(rx.cpu_type_ == "RX64M") {
				protocol_ = rx64m::protocol();
			} else {
				std::cerr << "CPU type missmatch: '" << rx.cpu_type_ << "'" << std::endl;
				return false;
			}

			{  // 開始
				bind_visitor vis(path, brate, rx);
            	if(!boost::apply_visitor(vis, protocol_)) {
					end();
					return false;
				}
			}

			return true;
		}

		//-------------------------------------------------------------//
		/*!
			@brief	リード
			@param[in]	adr	開始アドレス
			@param[out]	dst	書き込みアドレス
			@param[in]	len	読み出しサイズ
			@return 成功なら「true」
		*/
		//-------------------------------------------------------------//
		bool read(uint32_t adr, uint8_t* dst, uint32_t len) {
			read_visitor vis(adr, dst, len);
           	if(!boost::apply_visitor(vis, protocol_)) {
				end();
				std::cerr << "Read error." << std::endl;
				return false;
			}
			return true;
		}

		//-------------------------------------------------------------//
		/*!
			@brief	ベリファイ
			@param[in]	adr	開始アドレス
			@param[in]	src	書き込みアドレス
			@param[in]	len	読み出しサイズ
			@return 成功なら「true」
		*/
		//-------------------------------------------------------------//
		bool verify(uint32_t adr, const uint8_t* src, uint32_t len) {
			std::vector<uint8_t> dev;
			dev.resize(len);
			if(!read(adr, &dev[0], len)) {
				return false;
			}
			uint32_t errcnt = 0;
			for(auto d : dev) {
				auto m = *src++;
				if(d != m) {
					++errcnt;
					if(verbose_) {
						std::cerr << (boost::format("0x%08X: D(%02X) to M(%02X)") % adr %
							static_cast<uint32_t>(d) % static_cast<uint32_t>(m)) << std::endl;
					}
				}
				++adr;
			}
			if(errcnt > 0) {
				std::cerr << "Verify error: " << errcnt << std::endl;
				return false;
			}
			return true;
		}

		//-------------------------------------------------------------//
		/*!
			@brief	ライト開始
			@param[in]	data	「true」ならデータ領域
			@return 成功なら「true」
		*/
		//-------------------------------------------------------------//
		bool start_write(bool data) {
			select_write_visitor vis(data);
           	if(!boost::apply_visitor(vis, protocol_)) {
				end();
				std::cerr << "Write start error.(first)" << std::endl;
				return false;
			}
			return true;
		}

		//-------------------------------------------------------------//
		/*!
			@brief	ライト（２５６バイト）
			@param[in]	adr	開始アドレス
			@param[in]	src	書き込みアドレス
			@return 成功なら「true」
		*/
		//-------------------------------------------------------------//
		bool write(uint32_t adr, const uint8_t* src) {
			write_visitor vis(adr, src);
           	if(!boost::apply_visitor(vis, protocol_)) {
				end();
				std::cerr << "Write body error." << std::endl;
				return false;
			}
			return true;
		}

		//-------------------------------------------------------------//
		/*!
			@brief	ライト終了
			@return 成功なら「true」
		*/
		//-------------------------------------------------------------//
		bool final_write() {
			write_visitor vis(0xffffffff, nullptr);
           	if(!boost::apply_visitor(vis, protocol_)) {
				end();
				std::cerr << "Write final error. (fin)" << std::endl;
				return false;
			}
			return true;
		}

		//-------------------------------------------------------------//
		/*!
			@brief	終了
		*/
		//-------------------------------------------------------------//
		void end() {
			end_visitor vis;
           	boost::apply_visitor(vis, protocol_);
		}
	};
}
<|endoftext|>


<commit_before>/*
 NUI3 - C++ cross-platform GUI framework for OpenGL based applications
 Copyright (C) 2002-2003 Sebastien Metrot

 licence: see nui3/LICENCE.TXT
 */

#include "nuiTask.h"

void TestSink(int a)
{
  printf("TestSink: %d\n", a);
}

void TestTask()
{
  nuiTaskBase* pTask = new nuiTask1<int, void>(TestSink, 42);
  pTask->Run();
}
<commit_msg>experiments for Task syntax<commit_after>/*
 NUI3 - C++ cross-platform GUI framework for OpenGL based applications
 Copyright (C) 2002-2003 Sebastien Metrot

 licence: see nui3/LICENCE.TXT
 */

#include "nuiTask.h"

template <class Param1, class RetType>
nuiTask1<Param1, RetType>* nuiMakeTask(RetType (*func)(Param1 p1), Param1 P1)
{
	return new nuiTask1<Param1, RetType>(func, P1);
}

template <class X, class Y, class Param1, class RetType>
nuiTask1<Param1, RetType>* nuiMakeTask(Y* x, RetType (X::*func)(Param1 p1), Param1 P1)
{
	return new nuiTask1<Param1, RetType>(nuiMakeDelegate(x, func), P1);
}

template <class X, class Y, class Param1, class RetType>
nuiTask1<Param1, RetType>* nuiMakeTask(Y* x, RetType (X::*func)(Param1 p1) const, Param1 P1)
{
	return new nuiTask1<Param1, RetType>(nuiMakeDelegate(x, func), P1);
}

void TestSink(int a)
{
  printf("TestSink: %d\n", a);
}

void TestTask()
{
  nuiTaskBase* pTask = nuiMakeTask(TestSink, 42);
  pTask->Run();
}
<|endoftext|>


<commit_before>//
// Created by vincent on 12/06/17.
//

#include <iostream>
#include <thread>
#include "GameState.hpp"
#include "BombsManager.hpp"
#include "Fire.hpp"
#include <IndieStudioException.hpp>

is::BombsManager::BombsManager(is::map &map, irr::video::IVideoDriver &videoDriver, irr::scene::ISceneManager &sceneManager, is::PowerUpManager &pm,
				is::GameEngine *engine) :
	_map(map),
	_videoDriver(videoDriver),
	_sceneManager(sceneManager),
	_texture(NULL),
	_mesh(this->_sceneManager.getMesh("./gfx/bomb.obj")),
	_pm(pm),
	_mesh2(this->_sceneManager.getMesh("./gfx/wallBrick.obj")),
	_engine(engine)
{
}

is::BombsManager::~BombsManager()
{

}

void is::BombsManager::putBomb(const irr::core::vector3df &pos, int power)
{
  this->_bombs.push_back(std::make_shared<Bomb>(this->_map, this->_texture, this->_mesh, pos, power, this->_videoDriver, this->_sceneManager, this->_pm));
}

bool is::BombsManager::checkBombsStatus(std::list<std::shared_ptr<is::Character>> const &Char)
{
  bool          ret = false;

  this->_bombs.remove_if([&](auto const &bomb) {
    ret = true;
    bool t;
    	if ((t = bomb->blowUp(this->_bombs)))
;//	  _engine->getSound().bombSound();
    return t;
  });
  for (auto &i : _bombs)
    {
      if (!i->getCollision() && !i->alreadyBlowUp() && checkChar(Char, i->getPos2()))
	{
	  std::cerr << "Creating Colision" << std::endl;
	  irr::scene::IMeshSceneNode *node = _sceneManager.addOctreeSceneNode(_mesh2->getMesh(0), 0, 1);
	  node->setMaterialType(irr::video::EMT_TRANSPARENT_ADD_COLOR);
	  _colNode[i->_id] = node;
	  _col[i->_id] = _sceneManager.createOctreeTriangleSelector(_mesh2, node);
//	  node->setMaterialType(irr::video::EMT_NORMAL_MAP_TRANSPARENT_ADD_COLOR);
	  node->setTriangleSelector(_col[i->_id]);
	  node->setScale(irr::core::vector3df(8, 10, 8));
	  node->setPosition({i->getPos().X + 8 / 2, 0, i->getPos().Z - 8 / 2});//{i->getPos2() * SCALE,  * SCALE, 2 * SCALE});
	  i->setCollision(true);
	}
  for (auto &i : _bombs)
    {
      if (i->getCollision() && i->alreadyBlowUp() && i->getMesh() != NULL)
	{
	  for (auto &j : Char)
	    {
	      if (j->getAnim(i->_id))
		j->getMesh()->removeAnimator(j->getAnim(i->_id));
		  std::cerr << "Deleting Animation" << std::endl;
	    }
	  _engine->getSound().bombSound();
	  _sceneManager.addToDeletionQueue(_colNode[i->_id]);
	  i->setPos(i->getMesh()->getPosition());
	  _sceneManager.addToDeletionQueue(i->getMesh());
	  i->setMesh(NULL);
	}
    }
    }
  return (ret);
}

bool is::BombsManager::checkChar(std::list<std::shared_ptr<Character>> const &Char, irr::core::vector3df const &v)
{
  int j = 1;
  for (auto const &i : Char)
    {
      irr::core::vector3df v_char  = {ceil(floor(i->getPos().Z) / (float) SCALE) - 1,
					     ceil(floor(i->getPos().X) / (float) SCALE), 0};

      std::cerr << "Character pos " << (int)(v_char.X) << " " << (int)(v_char.Y) << std::endl;
      std::cerr << "Bomb pos " << (int)(v.X)  << " " << (int)(v.Y) << std::endl;
      if (v_char.X == v.X && v_char.Y == v.Y)
	return false;
      std::cerr << j << std::endl;
      j++;
    }
  std::cerr << "I will Create the colision" << std::endl;
  return true;
}

void is::BombsManager::addCollision(std::list<std::shared_ptr<is::Character>> const &Char)
{
  for (auto const &i : _col)
    {
      std::cerr << "Adding collision" << std::endl;
      for (auto const &c : Char)
	{
	  c->pushAnim(_sceneManager.createCollisionResponseAnimator(
		  i.second, c->getMesh(), core::vector3df(4,7,4),
		  core::vector3df(0,0,0), core::vector3df(0,0,0)), i.first);
	  c.get()->getMesh()->addAnimator(c->getAnim(i.first));
	}
      std::cerr << "Collision Added" << std::endl;
    }
  _col.clear();
}<commit_msg>COLISION BOMB OK<commit_after>//
// Created by vincent on 12/06/17.
//

#include <iostream>
#include <thread>
#include "GameState.hpp"
#include "BombsManager.hpp"
#include "Fire.hpp"
#include <IndieStudioException.hpp>

is::BombsManager::BombsManager(is::map &map, irr::video::IVideoDriver &videoDriver, irr::scene::ISceneManager &sceneManager, is::PowerUpManager &pm,
				is::GameEngine *engine) :
	_map(map),
	_videoDriver(videoDriver),
	_sceneManager(sceneManager),
	_texture(NULL),
	_mesh(this->_sceneManager.getMesh("./gfx/bomb.obj")),
	_pm(pm),
	_mesh2(this->_sceneManager.getMesh("./gfx/wallBrick.obj")),
	_engine(engine)
{
}

is::BombsManager::~BombsManager()
{

}

void is::BombsManager::putBomb(const irr::core::vector3df &pos, int power)
{
  this->_bombs.push_back(std::make_shared<Bomb>(this->_map, this->_texture, this->_mesh, pos, power, this->_videoDriver, this->_sceneManager, this->_pm));
}

bool is::BombsManager::checkBombsStatus(std::list<std::shared_ptr<is::Character>> const &Char)
{
  bool          ret = false;

  this->_bombs.remove_if([&](auto const &bomb) {
    ret = true;
    bool t;
    	if ((t = bomb->blowUp(this->_bombs)))
;//	  _engine->getSound().bombSound();
    return t;
  });
  for (auto &i : _bombs)
    {
      if (!i->getCollision() && !i->alreadyBlowUp() && checkChar(Char, i->getPos2()))
	{
	  std::cerr << "Creating Colision" << std::endl;
	  irr::scene::IMeshSceneNode *node = _sceneManager.addOctreeSceneNode(_mesh2->getMesh(0), 0, 1);
	  node->setMaterialType(irr::video::EMT_TRANSPARENT_ADD_COLOR);
	  _colNode[i->_id] = node;
	  _col[i->_id] = _sceneManager.createOctreeTriangleSelector(_mesh2, node);
//	  node->setMaterialType(irr::video::EMT_NORMAL_MAP_TRANSPARENT_ADD_COLOR);
	  node->setTriangleSelector(_col[i->_id]);
	  node->setScale(irr::core::vector3df(9, 10, 9));
	  node->setPosition({i->getPos().X + 9 / 2, 0, i->getPos().Z - 9 / 2});//{i->getPos2() * SCALE,  * SCALE, 2 * SCALE});
	  i->setCollision(true);
	}
  for (auto &i : _bombs)
    {
      if (i->getCollision() && i->alreadyBlowUp() && i->getMesh() != NULL)
	{
	  for (auto &j : Char)
	    {
	      if (j->getAnim(i->_id))
		j->getMesh()->removeAnimator(j->getAnim(i->_id));
		  std::cerr << "Deleting Animation" << std::endl;
	    }
	  _engine->getSound().bombSound();
	  _sceneManager.addToDeletionQueue(_colNode[i->_id]);
	  i->setPos(i->getMesh()->getPosition());
	  _sceneManager.addToDeletionQueue(i->getMesh());
	  i->setMesh(NULL);
	}
    }
    }
  return (ret);
}

bool is::BombsManager::checkChar(std::list<std::shared_ptr<Character>> const &Char, irr::core::vector3df const &v)
{
  int j = 1;
  for (auto const &i : Char)
    {
      irr::core::vector3df v_char  = {ceil(floor(i->getPos().Z) / (float) SCALE) - 1,
					     ceil(floor(i->getPos().X) / (float) SCALE), 0};

      std::cerr << "Character pos " << (int)(v_char.X) << " " << (int)(v_char.Y) << std::endl;
      std::cerr << "Bomb pos " << (int)(v.X)  << " " << (int)(v.Y) << std::endl;
      if (v_char.X == v.X && v_char.Y == v.Y)
	return false;
      std::cerr << j << std::endl;
      j++;
    }
  std::cerr << "I will Create the colision" << std::endl;
  return true;
}

void is::BombsManager::addCollision(std::list<std::shared_ptr<is::Character>> const &Char)
{
  for (auto const &i : _col)
    {
      std::cerr << "Adding collision" << std::endl;
      for (auto const &c : Char)
	{
	  c->pushAnim(_sceneManager.createCollisionResponseAnimator(
		  i.second, c->getMesh(), core::vector3df(2,2,2),
		  core::vector3df(0,0,0), core::vector3df(0,0,0)), i.first);
	  c.get()->getMesh()->addAnimator(c->getAnim(i.first));
	}
      std::cerr << "Collision Added" << std::endl;
    }
  _col.clear();
}<|endoftext|>


<commit_before>#include "ContextCairo.h"

#include <cassert>
#include <cmath>
#include <iostream>

using namespace canvas;
using namespace std;

CairoSurface::CairoSurface(unsigned int _width, unsigned int _height, bool has_alpha)
  : Surface(_width, _height, _width, _height) {
  cairo_format_t format = has_alpha ? CAIRO_FORMAT_ARGB32 : CAIRO_FORMAT_RGB24;
  surface = cairo_image_surface_create(format, _width, _height);
  assert(surface);
  cr = cairo_create(surface);
  assert(cr);
}

CairoSurface::CairoSurface(const Image & image)
  : Surface(image.getWidth(), image.getHeight(), image.getWidth(), image.getHeight())
{
  cairo_format_t format = image.hasAlpha() ? CAIRO_FORMAT_ARGB32 : CAIRO_FORMAT_RGB24;
  unsigned int stride = cairo_format_stride_for_width(format, getActualWidth());
  assert(stride == 4 * getActualWidth());
  storage = new unsigned int[getActualWidth() * getActualHeight()];
  const unsigned char * data = image.getData();
  if (image.hasAlpha()) {
    for (unsigned int i = 0; i < getActualWidth() * getActualHeight(); i++) {
#if 0
      storage[i] = (data[4 * i + 0] << 24) + (data[4 * i + 1] << 16) + (data[4 * i + 2] << 8) + data[4 * i + 3];
#else
      storage[i] = (data[4 * i + 0]) + (data[4 * i + 1] << 8) + (data[4 * i + 2] << 16) + (data[4 * i + 3] << 24);
#endif
    }
  } else {
    for (unsigned int i = 0; i < getActualWidth() * getActualHeight(); i++) {
      storage[i] = data[3 * i + 2] + (data[3 * i + 1] << 8) + (data[3 * i + 0] << 16);
    }
  }
  surface = cairo_image_surface_create_for_data((unsigned char*)storage,
						format,
						getActualWidth(),
						getActualHeight(),
						stride);
  assert(surface);
  cr = cairo_create(surface);
  assert(cr);
}

CairoSurface::CairoSurface(const std::string & filename) : Surface(0, 0, 0, 0) {
  surface = cairo_image_surface_create_from_png(filename.c_str());
  assert(surface);
  unsigned int w = cairo_image_surface_get_width(surface), h = cairo_image_surface_get_height(surface);
  Surface::resize(w, h, w, h);
  cr = cairo_create(surface);
  assert(cr);
}

struct read_buffer_s {
  size_t offset, size;
  const unsigned char * data;
};

static cairo_status_t read_buffer(void *closure, unsigned char *data, unsigned int length)
{
  read_buffer_s * buf = (read_buffer_s*)closure;

  if (buf->offset + length > buf->size) {
    return CAIRO_STATUS_READ_ERROR;
  }
  memcpy(data, buf->data + buf->offset, length);
  buf->offset += length;
  return CAIRO_STATUS_SUCCESS;
}

CairoSurface::CairoSurface(const unsigned char * buffer, size_t size) : Surface(16, 16, 16, 16) {
  read_buffer_s buf = { 0, size, buffer };
  if (isPNG(buffer, size)) {
    surface = cairo_image_surface_create_from_png_stream(read_buffer, &buf);
    unsigned int w = cairo_image_surface_get_width(surface), h = cairo_image_surface_get_height(surface);
    Surface::resize(w, h, w, h);
  } else {
    cerr << "failed to load image from memory\n";
    surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, getActualWidth(), getActualHeight());
  }
  assert(surface);
  cr = cairo_create(surface);
  assert(cr);
}

CairoSurface::~CairoSurface() {
  if (cr) {
    cairo_destroy(cr);
  }
  if (surface) {
    cairo_surface_destroy(surface);
  }
  delete[] storage;
}

void
CairoSurface::flush() {
  cairo_surface_flush(surface);
}

void
CairoSurface::markDirty() {
  cairo_surface_mark_dirty(surface);
}

void
CairoSurface::resize(unsigned int _logical_width, unsigned int _logical_height, unsigned int _actual_width, unsigned int _actual_height) {
  Surface::resize(_logical_width, _logical_height, _actual_width, _actual_height);
  if (cr) cairo_destroy(cr);
  if (surface) cairo_surface_destroy(surface);
  cairo_format_t format = CAIRO_FORMAT_ARGB32;
  // format = CAIRO_FORMAT_RGB24;
  surface = cairo_image_surface_create(format, _actual_width, _actual_height);
  assert(surface);
  cr = cairo_create(surface);
  assert(cr);
}

void
CairoSurface::sendPath(const Path & path) {
  for (auto pc : path.getData()) {
    switch (pc.type) {
    case PathComponent::MOVE_TO: cairo_move_to(cr, pc.x0 + 0.5, pc.y0 + 0.5); break;
    case PathComponent::LINE_TO: cairo_line_to(cr, pc.x0 + 0.5, pc.y0 + 0.5); break;
    case PathComponent::CLOSE: cairo_close_path(cr); break;
    case PathComponent::ARC:
      if (!pc.anticlockwise) {
	cairo_arc(cr, pc.x0 + 0.5, pc.y0 + 0.5, pc.radius, pc.sa, pc.ea);
      } else {
	cairo_arc_negative(cr, pc.x0 + 0.5, pc.y0 + 0.5, pc.radius, pc.sa, pc.ea);
      }
      break;
    }
  }
}

void
CairoSurface::clip(const Path & path, float display_scale) {
  sendPath(path);
  cairo_clip(cr);
}

void
CairoSurface::renderPath(RenderMode mode, const Path & path, const Style & style, float lineWidth, float display_scale) {
  cairo_pattern_t * pat = 0;
  if (style.getType() == Style::LINEAR_GRADIENT) {
    pat = cairo_pattern_create_linear(style.x0 * display_scale, style.y0 * display_scale, style.x1 * display_scale, style.y1 * display_scale);
    for (map<float, Color>::const_iterator it = style.getColors().begin(); it != style.getColors().end(); it++) {
      cairo_pattern_add_color_stop_rgba(pat, it->first, it->second.red, it->second.green, it->second.blue, it->second.alpha);
    }
    cairo_set_source(cr, pat);
  } else if (style.getType() == Style::FILTER) {
    double min_x, min_y, max_x, max_y;
    path.getExtents(min_x, min_y, max_x, max_y);
  } else {
    cairo_set_source_rgba(cr, style.color.red, style.color.green, style.color.blue, style.color.alpha);
  }
  sendPath(path);
  switch (mode) {
  case STROKE:
    cairo_set_line_width(cr, lineWidth);
    // cairo_set_line_join(cr, CAIRO_LINE_JOIN_ROUND);
    cairo_stroke(cr);
    break;
  case FILL:
    cairo_fill(cr);
    break;
  }

  if (pat) {
    cairo_pattern_destroy(pat);
    cairo_set_source_rgb(cr, 0.0, 0.0, 0.0);
  }
}

void
CairoSurface::renderText(RenderMode mode, const Font & font, const Style & style, TextBaseline textBaseline, TextAlign textAlign, const std::string & text, double x, double y, float lineWidth, float display_scale) {
  cairo_set_source_rgba(cr, style.color.red, style.color.green, style.color.blue, style.color.alpha);
  cairo_select_font_face(cr, font.family.c_str(),
			 font.slant == Font::NORMAL_SLANT ? CAIRO_FONT_SLANT_NORMAL : (font.slant == Font::ITALIC ? CAIRO_FONT_SLANT_ITALIC : CAIRO_FONT_SLANT_OBLIQUE),
			 font.weight == Font::NORMAL || font.weight == Font::LIGHTER ? CAIRO_FONT_WEIGHT_NORMAL : CAIRO_FONT_WEIGHT_BOLD);
  cairo_set_font_size(cr, font.size * display_scale);

  cairo_font_extents_t font_extents;
  cairo_font_extents(cr, &font_extents);

  cairo_text_extents_t text_extents;
  cairo_text_extents(cr, text.c_str(), &text_extents);

  switch (textBaseline.getType()) {
    // case TextBaseline::MIDDLE: y -= (extents.height/2 + extents.y_bearing); break;
  case TextBaseline::MIDDLE: y += -font_extents.descent + (font_extents.ascent + font_extents.descent) / 2.0; break;
  case TextBaseline::TOP: y += font_extents.ascent; break;
  default: break;
  }

  switch (textAlign.getType()) {
  case TextAlign::LEFT: break;
  case TextAlign::CENTER: x -= text_extents.width / 2; break;
  case TextAlign::RIGHT: x -= text_extents.width; break;
  default: break;
  }

  cairo_move_to(cr, x * display_scale + 0.5, y * display_scale + 0.5);

  switch (mode) {
  case STROKE:
    cairo_set_line_width(cr, lineWidth);
    cairo_text_path(cr, text.c_str());
    cairo_stroke(cr);
    break;
  case FILL:
    cairo_show_text(cr, text.c_str());
    break;
  }
}

void
CairoSurface::drawNativeSurface(CairoSurface & img, double x, double y, double w, double h, float alpha, bool imageSmoothingEnabled) {
  double sx = w / img.getActualWidth(), sy = h / img.getActualHeight();
  cairo_save(cr);
  cairo_scale(cr, sx, sy);
  cairo_set_source_surface(cr, img.surface, (x / sx) + 0.5, (y / sy) + 0.5);
  cairo_pattern_set_filter (cairo_get_source (cr), imageSmoothingEnabled ? CAIRO_FILTER_BILINEAR : CAIRO_FILTER_NEAREST);
  if (alpha < 1.0f) {
    cairo_paint_with_alpha(cr, alpha);
  } else {
    cairo_paint(cr);
  }
  cairo_set_source_rgb(cr, 0.0f, 0.0f, 0.0f); // is this needed?
  cairo_restore(cr);
}

void
CairoSurface::drawImage(Surface & _img, double x, double y, double w, double h, float alpha, bool imageSmoothingEnabled) {
  CairoSurface * cs = dynamic_cast<CairoSurface*>(&_img);
  if (cs) {
    drawNativeSurface(*cs, x, y, w, h, alpha, imageSmoothingEnabled);
  } else {
    auto img = _img.createImage();
    CairoSurface cs(*img);
    drawNativeSurface(cs, x, y, w, h, alpha, imageSmoothingEnabled);
  }
}

void
CairoSurface::drawImage(const Image & _img, double x, double y, double w, double h, float alpha, bool imageSmoothingEnabled) {
  CairoSurface img(_img);
  drawNativeSurface(img, x, y, w, h, alpha, imageSmoothingEnabled);
}

void
CairoSurface::save() {
  cairo_save(cr);
}

void
CairoSurface::restore() {
  cairo_restore(cr);
}

ContextCairo::ContextCairo(unsigned int _width, unsigned int _height, float _display_scale)
  : Context(_display_scale),
    default_surface(_width, _height)
{
}

TextMetrics
ContextCairo::measureText(const std::string & text) {
  cairo_select_font_face(default_surface.cr, font.family.c_str(),
			 font.slant == Font::NORMAL_SLANT ? CAIRO_FONT_SLANT_NORMAL : (font.slant == Font::ITALIC ? CAIRO_FONT_SLANT_ITALIC : CAIRO_FONT_SLANT_OBLIQUE),
			 font.weight == Font::NORMAL || font.weight == Font::LIGHTER ? CAIRO_FONT_WEIGHT_NORMAL : CAIRO_FONT_WEIGHT_BOLD);
  cairo_set_font_size(default_surface.cr, font.size);
  cairo_text_extents_t te;
  cairo_text_extents(default_surface.cr, text.c_str(), &te);
  return TextMetrics((float)te.width, (float)te.height);
}

<commit_msg>fix scaling<commit_after>#include "ContextCairo.h"

#include <cassert>
#include <cmath>
#include <iostream>

using namespace canvas;
using namespace std;

CairoSurface::CairoSurface(unsigned int _width, unsigned int _height, bool has_alpha)
  : Surface(_width, _height, _width, _height) {
  cairo_format_t format = has_alpha ? CAIRO_FORMAT_ARGB32 : CAIRO_FORMAT_RGB24;
  surface = cairo_image_surface_create(format, _width, _height);
  assert(surface);
  cr = cairo_create(surface);
  assert(cr);
}

CairoSurface::CairoSurface(const Image & image)
  : Surface(image.getWidth(), image.getHeight(), image.getWidth(), image.getHeight())
{
  cairo_format_t format = image.hasAlpha() ? CAIRO_FORMAT_ARGB32 : CAIRO_FORMAT_RGB24;
  unsigned int stride = cairo_format_stride_for_width(format, getActualWidth());
  assert(stride == 4 * getActualWidth());
  storage = new unsigned int[getActualWidth() * getActualHeight()];
  const unsigned char * data = image.getData();
  if (image.hasAlpha()) {
    for (unsigned int i = 0; i < getActualWidth() * getActualHeight(); i++) {
#if 0
      storage[i] = (data[4 * i + 0] << 24) + (data[4 * i + 1] << 16) + (data[4 * i + 2] << 8) + data[4 * i + 3];
#else
      storage[i] = (data[4 * i + 0]) + (data[4 * i + 1] << 8) + (data[4 * i + 2] << 16) + (data[4 * i + 3] << 24);
#endif
    }
  } else {
    for (unsigned int i = 0; i < getActualWidth() * getActualHeight(); i++) {
      storage[i] = data[3 * i + 2] + (data[3 * i + 1] << 8) + (data[3 * i + 0] << 16);
    }
  }
  surface = cairo_image_surface_create_for_data((unsigned char*)storage,
						format,
						getActualWidth(),
						getActualHeight(),
						stride);
  assert(surface);
  cr = cairo_create(surface);
  assert(cr);
}

CairoSurface::CairoSurface(const std::string & filename) : Surface(0, 0, 0, 0) {
  surface = cairo_image_surface_create_from_png(filename.c_str());
  assert(surface);
  unsigned int w = cairo_image_surface_get_width(surface), h = cairo_image_surface_get_height(surface);
  Surface::resize(w, h, w, h);
  cr = cairo_create(surface);
  assert(cr);
}

struct read_buffer_s {
  size_t offset, size;
  const unsigned char * data;
};

static cairo_status_t read_buffer(void *closure, unsigned char *data, unsigned int length)
{
  read_buffer_s * buf = (read_buffer_s*)closure;

  if (buf->offset + length > buf->size) {
    return CAIRO_STATUS_READ_ERROR;
  }
  memcpy(data, buf->data + buf->offset, length);
  buf->offset += length;
  return CAIRO_STATUS_SUCCESS;
}

CairoSurface::CairoSurface(const unsigned char * buffer, size_t size) : Surface(16, 16, 16, 16) {
  read_buffer_s buf = { 0, size, buffer };
  if (isPNG(buffer, size)) {
    surface = cairo_image_surface_create_from_png_stream(read_buffer, &buf);
    unsigned int w = cairo_image_surface_get_width(surface), h = cairo_image_surface_get_height(surface);
    Surface::resize(w, h, w, h);
  } else {
    cerr << "failed to load image from memory\n";
    surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, getActualWidth(), getActualHeight());
  }
  assert(surface);
  cr = cairo_create(surface);
  assert(cr);
}

CairoSurface::~CairoSurface() {
  if (cr) {
    cairo_destroy(cr);
  }
  if (surface) {
    cairo_surface_destroy(surface);
  }
  delete[] storage;
}

void
CairoSurface::flush() {
  cairo_surface_flush(surface);
}

void
CairoSurface::markDirty() {
  cairo_surface_mark_dirty(surface);
}

void
CairoSurface::resize(unsigned int _logical_width, unsigned int _logical_height, unsigned int _actual_width, unsigned int _actual_height) {
  Surface::resize(_logical_width, _logical_height, _actual_width, _actual_height);
  if (cr) cairo_destroy(cr);
  if (surface) cairo_surface_destroy(surface);
  cairo_format_t format = CAIRO_FORMAT_ARGB32;
  // format = CAIRO_FORMAT_RGB24;
  surface = cairo_image_surface_create(format, _actual_width, _actual_height);
  assert(surface);
  cr = cairo_create(surface);
  assert(cr);
}

void
CairoSurface::sendPath(const Path & path) {
  for (auto pc : path.getData()) {
    switch (pc.type) {
    case PathComponent::MOVE_TO: cairo_move_to(cr, pc.x0 + 0.5, pc.y0 + 0.5); break;
    case PathComponent::LINE_TO: cairo_line_to(cr, pc.x0 + 0.5, pc.y0 + 0.5); break;
    case PathComponent::CLOSE: cairo_close_path(cr); break;
    case PathComponent::ARC:
      if (!pc.anticlockwise) {
	cairo_arc(cr, pc.x0 + 0.5, pc.y0 + 0.5, pc.radius, pc.sa, pc.ea);
      } else {
	cairo_arc_negative(cr, pc.x0 + 0.5, pc.y0 + 0.5, pc.radius, pc.sa, pc.ea);
      }
      break;
    }
  }
}

void
CairoSurface::clip(const Path & path, float display_scale) {
  sendPath(path);
  cairo_clip(cr);
}

void
CairoSurface::renderPath(RenderMode mode, const Path & path, const Style & style, float lineWidth, float display_scale) {
  cairo_pattern_t * pat = 0;
  if (style.getType() == Style::LINEAR_GRADIENT) {
    pat = cairo_pattern_create_linear(style.x0 * display_scale, style.y0 * display_scale, style.x1 * display_scale, style.y1 * display_scale);
    for (map<float, Color>::const_iterator it = style.getColors().begin(); it != style.getColors().end(); it++) {
      cairo_pattern_add_color_stop_rgba(pat, it->first, it->second.red, it->second.green, it->second.blue, it->second.alpha);
    }
    cairo_set_source(cr, pat);
  } else if (style.getType() == Style::FILTER) {
    double min_x, min_y, max_x, max_y;
    path.getExtents(min_x, min_y, max_x, max_y);
  } else {
    cairo_set_source_rgba(cr, style.color.red, style.color.green, style.color.blue, style.color.alpha);
  }
  sendPath(path);
  switch (mode) {
  case STROKE:
    cairo_set_line_width(cr, lineWidth);
    // cairo_set_line_join(cr, CAIRO_LINE_JOIN_ROUND);
    cairo_stroke(cr);
    break;
  case FILL:
    cairo_fill(cr);
    break;
  }

  if (pat) {
    cairo_pattern_destroy(pat);
    cairo_set_source_rgb(cr, 0.0, 0.0, 0.0);
  }
}

void
CairoSurface::renderText(RenderMode mode, const Font & font, const Style & style, TextBaseline textBaseline, TextAlign textAlign, const std::string & text, double x, double y, float lineWidth, float display_scale) {
  cairo_set_source_rgba(cr, style.color.red, style.color.green, style.color.blue, style.color.alpha);
  cairo_select_font_face(cr, font.family.c_str(),
			 font.slant == Font::NORMAL_SLANT ? CAIRO_FONT_SLANT_NORMAL : (font.slant == Font::ITALIC ? CAIRO_FONT_SLANT_ITALIC : CAIRO_FONT_SLANT_OBLIQUE),
			 font.weight == Font::NORMAL || font.weight == Font::LIGHTER ? CAIRO_FONT_WEIGHT_NORMAL : CAIRO_FONT_WEIGHT_BOLD);
  cairo_set_font_size(cr, font.size * display_scale);

  cairo_font_extents_t font_extents;
  cairo_font_extents(cr, &font_extents);

  cairo_text_extents_t text_extents;
  cairo_text_extents(cr, text.c_str(), &text_extents);

  x *= display_scale;
  y *= display_scale;

  switch (textBaseline.getType()) {
    // case TextBaseline::MIDDLE: y -= (extents.height/2 + extents.y_bearing); break;
  case TextBaseline::MIDDLE: y += -font_extents.descent + (font_extents.ascent + font_extents.descent) / 2.0; break;
  case TextBaseline::TOP: y += font_extents.ascent; break;
  default: break;
  }

  switch (textAlign.getType()) {
  case TextAlign::LEFT: break;
  case TextAlign::CENTER: x -= text_extents.width / 2; break;
  case TextAlign::RIGHT: x -= text_extents.width; break;
  default: break;
  }

  cairo_move_to(cr, x + 0.5, y + 0.5);

  switch (mode) {
  case STROKE:
    cairo_set_line_width(cr, lineWidth);
    cairo_text_path(cr, text.c_str());
    cairo_stroke(cr);
    break;
  case FILL:
    cairo_show_text(cr, text.c_str());
    break;
  }
}

void
CairoSurface::drawNativeSurface(CairoSurface & img, double x, double y, double w, double h, float alpha, bool imageSmoothingEnabled) {
  double sx = w / img.getActualWidth(), sy = h / img.getActualHeight();
  cairo_save(cr);
  cairo_scale(cr, sx, sy);
  cairo_set_source_surface(cr, img.surface, (x / sx) + 0.5, (y / sy) + 0.5);
  cairo_pattern_set_filter (cairo_get_source (cr), imageSmoothingEnabled ? CAIRO_FILTER_BILINEAR : CAIRO_FILTER_NEAREST);
  if (alpha < 1.0f) {
    cairo_paint_with_alpha(cr, alpha);
  } else {
    cairo_paint(cr);
  }
  cairo_set_source_rgb(cr, 0.0f, 0.0f, 0.0f); // is this needed?
  cairo_restore(cr);
}

void
CairoSurface::drawImage(Surface & _img, double x, double y, double w, double h, float alpha, bool imageSmoothingEnabled) {
  CairoSurface * cs = dynamic_cast<CairoSurface*>(&_img);
  if (cs) {
    drawNativeSurface(*cs, x, y, w, h, alpha, imageSmoothingEnabled);
  } else {
    auto img = _img.createImage();
    CairoSurface cs(*img);
    drawNativeSurface(cs, x, y, w, h, alpha, imageSmoothingEnabled);
  }
}

void
CairoSurface::drawImage(const Image & _img, double x, double y, double w, double h, float alpha, bool imageSmoothingEnabled) {
  CairoSurface img(_img);
  drawNativeSurface(img, x, y, w, h, alpha, imageSmoothingEnabled);
}

void
CairoSurface::save() {
  cairo_save(cr);
}

void
CairoSurface::restore() {
  cairo_restore(cr);
}

ContextCairo::ContextCairo(unsigned int _width, unsigned int _height, float _display_scale)
  : Context(_display_scale),
    default_surface(_width, _height)
{
}

TextMetrics
ContextCairo::measureText(const std::string & text) {
  cairo_select_font_face(default_surface.cr, font.family.c_str(),
			 font.slant == Font::NORMAL_SLANT ? CAIRO_FONT_SLANT_NORMAL : (font.slant == Font::ITALIC ? CAIRO_FONT_SLANT_ITALIC : CAIRO_FONT_SLANT_OBLIQUE),
			 font.weight == Font::NORMAL || font.weight == Font::LIGHTER ? CAIRO_FONT_WEIGHT_NORMAL : CAIRO_FONT_WEIGHT_BOLD);
  cairo_set_font_size(default_surface.cr, font.size);
  cairo_text_extents_t te;
  cairo_text_extents(default_surface.cr, text.c_str(), &te);
  return TextMetrics((float)te.width, (float)te.height);
}

<|endoftext|>


<commit_before>/*
    This file is part of KOrganizer.
    Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include <qcheckbox.h>
#include <qcombobox.h>
#include <qpushbutton.h>

#include <libkcal/calfilter.h>

#include "kofilterview.h"
#include "kofilterview.moc"

KOFilterView::KOFilterView(QPtrList<CalFilter> *filterList,QWidget* parent,
                           const char* name,WFlags fl )
  : KOFilterView_base(parent,name,fl)
{
  mFilters = filterList;

  connect(mSelectionCombo,SIGNAL(activated(int)),SIGNAL(filterChanged()));
  connect(mEnabledCheck,SIGNAL(clicked()),SIGNAL(filterChanged()));
  connect(mEditButton,SIGNAL(clicked()),SIGNAL(editFilters()));
}

KOFilterView::~KOFilterView()
{
    // no need to delete child widgets, Qt does it all for us
}

bool KOFilterView::filtersEnabled()
{
  return mEnabledCheck->isChecked();
}

void KOFilterView::setFiltersEnabled(bool set)
{
  mEnabledCheck->setChecked(set);
  emit filterChanged();
}

void KOFilterView::updateFilters()
{
  mSelectionCombo->clear();

  CalFilter *filter = mFilters->first();
  while(filter) {
    mSelectionCombo->insertItem(filter->name());
    filter = mFilters->next();
  }
}

CalFilter *KOFilterView::selectedFilter()
{
  CalFilter *f = mFilters->at(mSelectionCombo->currentItem());
  return f;
}

void KOFilterView::setSelectedFilter(QString filterName)
{
  int filter_num = mSelectionCombo->count();
  int i;
  for (i=0;i<filter_num;i++) {
    if (mSelectionCombo->text(i)==filterName)
      mSelectionCombo->setCurrentItem(i);
  }
  emit filterChanged();
}

<commit_msg>Preserve current filter when re-filling filter combo. Was especially annoying when switching filters in the edit filter dialog.<commit_after>/*
    This file is part of KOrganizer.
    Copyright (c) 2001 Cornelius Schumacher <schumacher@kde.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include <qcheckbox.h>
#include <qcombobox.h>
#include <qpushbutton.h>

#include <libkcal/calfilter.h>

#include "kofilterview.h"
#include "kofilterview.moc"

KOFilterView::KOFilterView(QPtrList<CalFilter> *filterList,QWidget* parent,
                           const char* name,WFlags fl )
  : KOFilterView_base(parent,name,fl)
{
  mFilters = filterList;

  connect(mSelectionCombo,SIGNAL(activated(int)),SIGNAL(filterChanged()));
  connect(mEnabledCheck,SIGNAL(clicked()),SIGNAL(filterChanged()));
  connect(mEditButton,SIGNAL(clicked()),SIGNAL(editFilters()));
}

KOFilterView::~KOFilterView()
{
    // no need to delete child widgets, Qt does it all for us
}

bool KOFilterView::filtersEnabled()
{
  return mEnabledCheck->isChecked();
}

void KOFilterView::setFiltersEnabled(bool set)
{
  mEnabledCheck->setChecked(set);
  emit filterChanged();
}

void KOFilterView::updateFilters()
{
  const QString currentFilter = mSelectionCombo->currentText();

  mSelectionCombo->clear();

  CalFilter *filter = mFilters->first();
  while(filter) {
    mSelectionCombo->insertItem(filter->name());
    filter = mFilters->next();
  }

  setSelectedFilter( currentFilter );
}

CalFilter *KOFilterView::selectedFilter()
{
  CalFilter *f = mFilters->at(mSelectionCombo->currentItem());
  return f;
}

void KOFilterView::setSelectedFilter(QString filterName)
{
  int filter_num = mSelectionCombo->count();
  int i;
  for (i=0;i<filter_num;i++) {
    if (mSelectionCombo->text(i)==filterName)
     {
      mSelectionCombo->setCurrentItem(i);
      emit filterChanged();
     }
  }
}

<|endoftext|>


<commit_before>/*
 *     Copyright (C) 2003 by Scott Monachello <smonach@cox.net>
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License along
 *   with this program; if not, write to the
 *      Free Software Foundation, Inc.
 *      51 Franklin Street, Fifth Floor
 *      Boston, MA  02110-1301  USA.
 *
 */

#include "mainwindow.h"

#include <numeric>

#include <QMenu>
#include <QString>

#include <KAction>
#include <KApplication>       // kapp
#include <KDebug>
#include <KGlobal>
#include <KIcon>
#include <KLocale>            // i18n
#include <KMessageBox>
#include <KPushButton>
#include <KShortcutsDialog>
#include <KStandardAction>
#include <KStatusBar>         // statusBar()
#include <KXMLGUIFactory>
#include <KActionCollection>

#include "ktimetrackerutility.h"
#include "ktimetracker.h"
#include "task.h"
#include "taskview.h"
#include "timekard.h"
#include "tray.h"

#include "timetrackerwidget.h"

MainWindow::MainWindow( const QString &icsfile )
  :  KParts::MainWindow( )
{
    kDebug(5970) << "Entering function, icsfile is " << icsfile;
    // Setup our actions
    setupActions();

    // this routine will find and load our Part.
    KLibFactory *factory = KLibLoader::self()->factory("ktimetrackerpart");
    if (factory)
    {
        // now that the Part is loaded, we cast it to a Part to get
        // our hands on it
        m_part = static_cast<ktimetrackerpart *>(factory->create(this, "ktimetrackerpart" ));

        if (m_part)
        {
            // tell the KParts::MainWindow that this is indeed
            // the main widget
            setCentralWidget(m_part->widget());
            m_part->openFile(icsfile);
            slotSetCaption( icsfile );  // set the window title to our iCal file
            connect(configureAction, SIGNAL(triggered(bool)),
            m_part->widget(), SLOT(showSettingsDialog()));
            ((TimetrackerWidget *) (m_part->widget()))->setupActions( actionCollection() );
            setupGUI();
        }
    }
    else
    {
        // if we couldn't find our Part, we exit since the Shell by
        // itself can't do anything useful
        KMessageBox::error(this, i18n( "Could not find the KTimeTracker part." ));
        qApp->quit();
        // we return here, cause qApp->quit() only means "exit the
        // next time we enter the event loop...
        return;
    }
    setWindowFlags( windowFlags() | Qt::WindowContextHelpButtonHint );

    // connections
    connect( m_part->widget(), SIGNAL( statusBarTextChangeRequested( QString ) ),
                 this, SLOT( setStatusBar( QString ) ) );
    connect( m_part->widget(), SIGNAL( setCaption( const QString& ) ),
                 this, SLOT( slotSetCaption( const QString& ) ) );
    loadGeometry();

    // Setup context menu request handling
    connect( m_part->widget(),
           SIGNAL( contextMenuRequested( const QPoint& ) ),
           this,
           SLOT( taskViewCustomContextMenuRequested( const QPoint& ) ) );

    _tray = new TrayIcon( this );

    connect( _tray, SIGNAL( quitSelected() ), m_part->widget(), SLOT( quit() ) );

    connect( m_part->widget(), SIGNAL( timersActive() ), _tray, SLOT( startClock() ) );
    connect( m_part->widget(), SIGNAL( timersInactive() ), _tray, SLOT( stopClock() ) );
    connect( m_part->widget(), SIGNAL( tasksChanged( const QList<Task*>& ) ),
                      _tray, SLOT( updateToolTip( QList<Task*> ) ));
}

void MainWindow::setupActions()
{
    configureAction = new KAction(this);
    configureAction->setText(i18n("Configure KTimeTracker..."));
    actionCollection()->addAction("configure_ktimetracker", configureAction);
}

void MainWindow::readProperties( const KConfigGroup &cfg )
{
    if( cfg.readEntry( "WindowShown", true ))
        show();
}

void MainWindow::saveProperties( KConfigGroup &cfg )
{
    cfg.writeEntry( "WindowShown", isVisible());
}

void MainWindow::slotSetCaption( const QString& qs )
{
    setCaption( qs );
}

void MainWindow::setStatusBar(const QString& qs)
{
    statusBar()->showMessage(i18n(qs.toUtf8()));
}

MainWindow::~MainWindow()
{
    kDebug(5970) << "MainWindow::~MainWindows: Quitting ktimetracker.";
    saveGeometry();
}

void MainWindow::keyBindings()
{
    KShortcutsDialog::configure( actionCollection(), KShortcutsEditor::LetterShortcutsAllowed, this );
}

void MainWindow::makeMenus()
{
    mainWidget->setupActions( actionCollection() );
    actionKeyBindings = KStandardAction::keyBindings( this, SLOT( keyBindings() ),
        actionCollection() );
    setupGUI();
    actionKeyBindings->setToolTip( i18n( "Configure key bindings" ) );
    actionKeyBindings->setWhatsThis( i18n( "This will let you configure key"
                                           "bindings which are specific to ktimetracker" ) );
}

void MainWindow::loadGeometry()
{
    if (initialGeometrySet()) setAutoSaveSettings();
    else
    {
        KConfigGroup config = KGlobal::config()->group( QString::fromLatin1("Main Window Geometry") );
        int w = config.readEntry( QString::fromLatin1("Width"), 100 );
        int h = config.readEntry( QString::fromLatin1("Height"), 100 );
        w = qMax( w, sizeHint().width() );
        h = qMax( h, sizeHint().height() );
        resize(w, h);
    }
}

void MainWindow::saveGeometry()
{
    KConfigGroup config = KGlobal::config()->group( QString::fromLatin1("Main Window Geometry") );
    config.writeEntry( QString::fromLatin1("Width"), width());
    config.writeEntry( QString::fromLatin1("Height"), height());
    config.sync();
}

bool MainWindow::queryClose()
{
    if ( !kapp->sessionSaving() )
    {
        hide();
        return false;
    }
    return KMainWindow::queryClose();
}

void MainWindow::taskViewCustomContextMenuRequested( const QPoint& point )
{
    QMenu* pop = dynamic_cast<QMenu*>(
                          factory()->container( i18n( "task_popup" ), this ) );
    if ( pop )
        pop->popup( point );
}

#include "mainwindow.moc"
<commit_msg>Code cleanup<commit_after>/*
 *     Copyright (C) 2003 by Scott Monachello <smonach@cox.net>
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License along
 *   with this program; if not, write to the
 *      Free Software Foundation, Inc.
 *      51 Franklin Street, Fifth Floor
 *      Boston, MA  02110-1301  USA.
 *
 */

#include "mainwindow.h"

#include <numeric>

#include <QMenu>
#include <QString>

#include <KAction>
#include <KApplication>       // kapp
#include <KDebug>
#include <KGlobal>
#include <KIcon>
#include <KLocale>            // i18n
#include <KMessageBox>
#include <KPushButton>
#include <KShortcutsDialog>
#include <KStandardAction>
#include <KStatusBar>         // statusBar()
#include <KXMLGUIFactory>
#include <KActionCollection>

#include "ktimetrackerutility.h"
#include "ktimetracker.h"
#include "task.h"
#include "taskview.h"
#include "timekard.h"
#include "tray.h"

#include "timetrackerwidget.h"

MainWindow::MainWindow( const QString &icsfile )
  :  KParts::MainWindow( )
{
    kDebug(5970) << "Entering function, icsfile is " << icsfile;
    // Setup our actions
    setupActions();

    // this routine will find and load our Part.
    KLibFactory *factory = KLibLoader::self()->factory("ktimetrackerpart");
    if (factory)
    {
        // now that the Part is loaded, we cast it to a Part to get
        // our hands on it
        m_part = static_cast<ktimetrackerpart *>(factory->create(this, "ktimetrackerpart" ));

        if (m_part)
        {
            // tell the KParts::MainWindow that this is indeed
            // the main widget
            setCentralWidget(m_part->widget());
            m_part->openFile(icsfile);
            slotSetCaption( icsfile );  // set the window title to our iCal file
            connect(configureAction, SIGNAL(triggered(bool)),
                m_part->widget(), SLOT(showSettingsDialog()));
            ((TimetrackerWidget *) (m_part->widget()))->setupActions( actionCollection() );
            setupGUI();
        }
    }
    else
    {
        // if we couldn't find our Part, we exit since the Shell by
        // itself can't do anything useful
        KMessageBox::error(this, i18n( "Could not find the KTimeTracker part." ));
        qApp->quit();
        // we return here, cause qApp->quit() only means "exit the
        // next time we enter the event loop...
        return;
    }
    setWindowFlags( windowFlags() | Qt::WindowContextHelpButtonHint );

    // connections
    connect( m_part->widget(), SIGNAL( statusBarTextChangeRequested( QString ) ),
                 this, SLOT( setStatusBar( QString ) ) );
    connect( m_part->widget(), SIGNAL( setCaption( const QString& ) ),
                 this, SLOT( slotSetCaption( const QString& ) ) );
    loadGeometry();

    // Setup context menu request handling
    connect( m_part->widget(),
           SIGNAL( contextMenuRequested( const QPoint& ) ),
           this,
           SLOT( taskViewCustomContextMenuRequested( const QPoint& ) ) );

    _tray = new TrayIcon( this );

    connect( _tray, SIGNAL( quitSelected() ), m_part->widget(), SLOT( quit() ) );

    connect( m_part->widget(), SIGNAL( timersActive() ), _tray, SLOT( startClock() ) );
    connect( m_part->widget(), SIGNAL( timersInactive() ), _tray, SLOT( stopClock() ) );
    connect( m_part->widget(), SIGNAL( tasksChanged( const QList<Task*>& ) ),
                      _tray, SLOT( updateToolTip( QList<Task*> ) ));
}

void MainWindow::setupActions()
{
    configureAction = new KAction(this);
    configureAction->setText(i18n("Configure KTimeTracker..."));
    actionCollection()->addAction("configure_ktimetracker", configureAction);
}

void MainWindow::readProperties( const KConfigGroup &cfg )
{
    if( cfg.readEntry( "WindowShown", true ))
        show();
}

void MainWindow::saveProperties( KConfigGroup &cfg )
{
    cfg.writeEntry( "WindowShown", isVisible());
}

void MainWindow::slotSetCaption( const QString& qs )
{
    setCaption( qs );
}

void MainWindow::setStatusBar(const QString& qs)
{
    statusBar()->showMessage(i18n(qs.toUtf8()));
}

MainWindow::~MainWindow()
{
    kDebug(5970) << "MainWindow::~MainWindows: Quitting ktimetracker.";
    saveGeometry();
}

void MainWindow::keyBindings()
{
    KShortcutsDialog::configure( actionCollection(), KShortcutsEditor::LetterShortcutsAllowed, this );
}

void MainWindow::makeMenus()
{
    mainWidget->setupActions( actionCollection() );
    actionKeyBindings = KStandardAction::keyBindings( this, SLOT( keyBindings() ),
        actionCollection() );
    setupGUI();
    actionKeyBindings->setToolTip( i18n( "Configure key bindings" ) );
    actionKeyBindings->setWhatsThis( i18n( "This will let you configure key"
                                           "bindings which are specific to ktimetracker" ) );
}

void MainWindow::loadGeometry()
{
    if (initialGeometrySet()) setAutoSaveSettings();
    else
    {
        KConfigGroup config = KGlobal::config()->group( QString::fromLatin1("Main Window Geometry") );
        int w = config.readEntry( QString::fromLatin1("Width"), 100 );
        int h = config.readEntry( QString::fromLatin1("Height"), 100 );
        w = qMax( w, sizeHint().width() );
        h = qMax( h, sizeHint().height() );
        resize(w, h);
    }
}

void MainWindow::saveGeometry()
{
    KConfigGroup config = KGlobal::config()->group( QString::fromLatin1("Main Window Geometry") );
    config.writeEntry( QString::fromLatin1("Width"), width());
    config.writeEntry( QString::fromLatin1("Height"), height());
    config.sync();
}

bool MainWindow::queryClose()
{
    if ( !kapp->sessionSaving() )
    {
        hide();
        return false;
    }
    return KMainWindow::queryClose();
}

void MainWindow::taskViewCustomContextMenuRequested( const QPoint& point )
{
    QMenu* pop = dynamic_cast<QMenu*>(
                          factory()->container( i18n( "task_popup" ), this ) );
    if ( pop )
        pop->popup( point );
}

#include "mainwindow.moc"
<|endoftext|>


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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbaccess.hxx"
#ifndef DBAUI_QUERYDLG_HXX
#include "querydlg.hxx"
#endif
#ifndef _DBU_QRY_HRC_
#include "dbu_qry.hrc"
#endif
#ifndef DBAUI_QUERYDLG_HRC
#include "querydlg.hrc"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef DBAUI_QTABLECONNECTIONDATA_HXX
#include "QTableConnectionData.hxx"
#endif
#ifndef DBAUI_QUERYCONTROLLER_HXX
#include "querycontroller.hxx"
#endif
#ifndef DBAUI_QUERYTABLEVIEW_HXX
#include "QueryTableView.hxx"
#endif
#ifndef DBAUI_QUERYDESIGNVIEW_HXX
#include "QueryDesignView.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_
#include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
#endif
#ifndef DBAUI_RELATIONCONTROL_HXX
#include "RelationControl.hxx"
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif

using namespace dbaui;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::sdbc;

DBG_NAME(DlgQryJoin)
DlgQryJoin::DlgQryJoin( Window * pParent,
                       OQueryTableConnectionData* _pData,
                       OJoinTableView::OTableWindowMap* _pTableMap,
                       const Reference< XConnection >& _xConnection,
                       BOOL _bAllowTableSelect)
    :ModalDialog( pParent, ModuleRes(DLG_QRY_JOIN) )
    ,aFL_Join( this, ModuleRes( FL_JOIN ) )
    ,aFT_Title( this, ModuleRes(FT_LISTBOXTITLE) )
    ,aLB_JoinType( this, ModuleRes(LB_JOINTYPE) )
    ,aML_HelpText( this, ModuleRes(ML_HELPTEXT) )
    ,aPB_OK( this, ModuleRes( PB_OK ) )
    ,aPB_CANCEL( this, ModuleRes( PB_CANCEL ) )
    ,aPB_HELP( this, ModuleRes( PB_HELP ) )
    ,m_pTableControl( NULL )
    ,m_pTableMap(_pTableMap)
    ,eJoinType(_pData->GetJoinType())
    ,m_pConnData(NULL)
    ,m_pOrigConnData(_pData)
    ,m_xConnection(_xConnection)
{
    DBG_CTOR(DlgQryJoin,NULL);

    aML_HelpText.SetControlBackground( GetSettings().GetStyleSettings().GetFaceColor() );
    //////////////////////////////////////////////////////////////////////
    // Connection kopieren
    m_pConnData = static_cast<OQueryTableConnectionData*>(_pData->NewInstance());
    m_pConnData->CopyFrom(*_pData);

    m_pTableControl = new OTableListBoxControl(this,ModuleRes(WND_CONTROL),m_pTableMap,this);

    if( _bAllowTableSelect )
    {
        m_pTableControl->Init( m_pConnData );
        m_pTableControl->fillListBoxes();
    }
    else
    {
        m_pTableControl->fillAndDisable(m_pConnData);
        m_pTableControl->Init( m_pConnData );
    }

    m_pTableControl->lateInit();

    sal_Bool bFull = sal_False;
    sal_Bool bOuter = sal_False;
    Reference<XDatabaseMetaData> xMeta;
    try
    {
        xMeta = m_xConnection->getMetaData();
        if ( xMeta.is() )
            bFull = xMeta->supportsFullOuterJoins();
    }
    catch(SQLException&)
    {
    }
    try
    {
        if ( xMeta.is() )
            bOuter= xMeta->supportsOuterJoins();
    }
    catch(SQLException&)
    {
    }

    setJoinType(eJoinType);

    aPB_OK.SetClickHdl( LINK(this, DlgQryJoin, OKClickHdl) );

    aLB_JoinType.SetSelectHdl(LINK(this,DlgQryJoin,LBChangeHdl));

    if ( static_cast<OQueryTableView*>(pParent)->getDesignView()->getController()->isReadOnly() )
    {
        aLB_JoinType.Disable();
        m_pTableControl->Disable();
    }
    else if ( !bFull && !bOuter )
        aLB_JoinType.Disable();
    else
    {
        if ( !bFull )
            aLB_JoinType.RemoveEntry(3);

        if ( !bOuter )
        {
            aLB_JoinType.RemoveEntry(0);
            aLB_JoinType.RemoveEntry(0);
            aLB_JoinType.RemoveEntry(0);
        }

        m_pTableControl->NotifyCellChange();
    }

    FreeResource();
}

//------------------------------------------------------------------------
DlgQryJoin::~DlgQryJoin()
{
    DBG_DTOR(DlgQryJoin,NULL);
    delete m_pTableControl;
    delete m_pConnData;
}
// -----------------------------------------------------------------------------
IMPL_LINK( DlgQryJoin, LBChangeHdl, ListBox*, /*pListBox*/ )
{
    DBG_CHKTHIS(DlgQryJoin,NULL);
    aML_HelpText.SetText(String());

    String sFirstWinName,sSecondWinName;
    USHORT nResId = 0;
    USHORT nPos = aLB_JoinType.GetSelectEntryPos();
    sal_Bool bAddHint = sal_True;
    switch ( nPos )
    {
        default:
        case 0:
            nResId = STR_QUERY_INNER_JOIN;
            bAddHint = sal_False;
            break;
        case 1:
            nResId = STR_QUERY_LEFTRIGHT_JOIN;
            sFirstWinName   = m_pConnData->GetSourceWinName();
            sSecondWinName  = m_pConnData->GetDestWinName();
            break;
        case 2:
        case 3:
            nResId = (nPos == 2) ? STR_QUERY_LEFTRIGHT_JOIN : STR_QUERY_FULL_JOIN;

            sFirstWinName   = m_pConnData->GetDestWinName();
            sSecondWinName  = m_pConnData->GetSourceWinName();
            break;
    }

    String sHelpText = String( ModuleRes( nResId ) );
    if( sFirstWinName.Len() )
    {
        sHelpText.SearchAndReplace( String( RTL_CONSTASCII_STRINGPARAM( "%1" ) ), sFirstWinName );
        sHelpText.SearchAndReplace( String( RTL_CONSTASCII_STRINGPARAM( "%2" ) ), sSecondWinName );
    }
    if ( bAddHint )
    {
        sHelpText += String( RTL_CONSTASCII_STRINGPARAM( "\n" ) );
        sHelpText += String( ModuleRes( STR_JOIN_TYPE_HINT ) );
    }

    aML_HelpText.SetText( sHelpText );
    return 1;
}
// -----------------------------------------------------------------------------

IMPL_LINK( DlgQryJoin, OKClickHdl, Button*, /*pButton*/ )
{
    DBG_CHKTHIS(DlgQryJoin,NULL);
    USHORT nPos = aLB_JoinType.GetSelectEntryPos();
    switch ( nPos )
    {
        case 0:
            eJoinType = INNER_JOIN;
            break;
        case 1:
            eJoinType = LEFT_JOIN;
            break;
        case 2:
            eJoinType = RIGHT_JOIN;
            break;
        case 3:
            eJoinType = FULL_JOIN;
            break;
    }

    m_pConnData->Update();
    m_pOrigConnData->CopyFrom( *m_pConnData );

    EndDialog(RET_OK);
    return 1;
}
// -----------------------------------------------------------------------------
OTableConnectionData* DlgQryJoin::getConnectionData() const
{
    return m_pConnData;
}
// -----------------------------------------------------------------------------
void DlgQryJoin::setValid(sal_Bool _bValid)
{
    LBChangeHdl(&aLB_JoinType);

    aPB_OK.Enable(_bValid);
}
// -----------------------------------------------------------------------------
void DlgQryJoin::notifyConnectionChange( )
{
    setJoinType( m_pConnData->GetJoinType() );
}
// -----------------------------------------------------------------------------
void DlgQryJoin::setJoinType(EJoinType _eNewJoinType)
{
    eJoinType = _eNewJoinType;
    USHORT nPos = 0;
    switch(eJoinType)
    {
        case INNER_JOIN:
            break;
        case LEFT_JOIN:
            nPos = 1;
            break;
        case RIGHT_JOIN:
            nPos = 2;
            break;
        case FULL_JOIN:
            nPos = 3;
            break;
        default:
            break;
    }
    aLB_JoinType.SelectEntryPos(nPos);
    LBChangeHdl(&aLB_JoinType);
}
// -----------------------------------------------------------------------------

<commit_msg>INTEGRATION: CWS dba24b (1.15.28); FILE MERGED 2007/08/22 11:41:59 oj 1.15.28.2: #i76374# handle cross join as natural join now in query design 2007/08/16 06:14:44 oj 1.15.28.1: #i56898# clean up of the class structure<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: querydlg.cxx,v $
 *
 *  $Revision: 1.16 $
 *
 *  last change: $Author: hr $ $Date: 2007-11-01 15:35:17 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbaccess.hxx"
#ifndef DBAUI_QUERYDLG_HXX
#include "querydlg.hxx"
#endif
#ifndef _DBU_QRY_HRC_
#include "dbu_qry.hrc"
#endif
#ifndef DBAUI_QUERYDLG_HRC
#include "querydlg.hrc"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef DBAUI_QTABLECONNECTIONDATA_HXX
#include "QTableConnectionData.hxx"
#endif
#ifndef DBAUI_QUERYCONTROLLER_HXX
#include "querycontroller.hxx"
#endif
#ifndef DBAUI_QUERYTABLEVIEW_HXX
#include "QueryTableView.hxx"
#endif
#ifndef DBAUI_QUERYDESIGNVIEW_HXX
#include "QueryDesignView.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_
#include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
#endif
#ifndef DBAUI_RELATIONCONTROL_HXX
#include "RelationControl.hxx"
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif

using namespace dbaui;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::sdbc;

namespace dbaui
{
class OJoinControl  : public Window
{
public:
    FixedLine               aFL_Join;
    FixedText               aFT_Title;
    ListBox                 aLB_JoinType;
    CheckBox                m_aCBNatural;

    OJoinControl(Window* _pParent,const ResId& _rResId);
};
OJoinControl::OJoinControl(Window* _pParent,const ResId& _rResId)
    : Window(_pParent,_rResId)
    ,aFL_Join( this, ResId( FL_JOIN,*_rResId.GetResMgr() ) )
    ,aFT_Title( this, ResId(FT_LISTBOXTITLE,*_rResId.GetResMgr()) )
    ,aLB_JoinType( this, ResId(LB_JOINTYPE,*_rResId.GetResMgr()) )
    ,m_aCBNatural( this, ResId(CB_NATURAL,*_rResId.GetResMgr()) )
{
    FreeResource();
}
// -----------------------------------------------------------------------------
} // dbaui
// -----------------------------------------------------------------------------
DBG_NAME(DlgQryJoin)
DlgQryJoin::DlgQryJoin( OQueryTableView * pParent,
                       const TTableConnectionData::value_type& _pData,
                       OJoinTableView::OTableWindowMap* _pTableMap,
                       const Reference< XConnection >& _xConnection,
                       BOOL _bAllowTableSelect)
    :ModalDialog( pParent, ModuleRes(DLG_QRY_JOIN) )
    ,aML_HelpText( this, ModuleRes(ML_HELPTEXT) )
    ,aPB_OK( this, ModuleRes( PB_OK ) )
    ,aPB_CANCEL( this, ModuleRes( PB_CANCEL ) )
    ,aPB_HELP( this, ModuleRes( PB_HELP ) )
    ,m_pJoinControl( NULL )
    ,m_pTableControl( NULL )
    ,m_pTableMap(_pTableMap)
    ,m_pTableView(pParent)
    ,eJoinType(static_cast<OQueryTableConnectionData*>(_pData.get())->GetJoinType())
    ,m_pOrigConnData(_pData)
    ,m_xConnection(_xConnection)
{
    DBG_CTOR(DlgQryJoin,NULL);

    aML_HelpText.SetControlBackground( GetSettings().GetStyleSettings().GetFaceColor() );
    //////////////////////////////////////////////////////////////////////
    // Connection kopieren
    m_pConnData.reset(_pData->NewInstance());
    m_pConnData->CopyFrom(*_pData);

    m_pTableControl = new OTableListBoxControl(this,ModuleRes(WND_CONTROL),m_pTableMap,this);

    m_pJoinControl = new OJoinControl(m_pTableControl,ModuleRes(WND_JOIN_CONTROL));

    m_pJoinControl->Show();
    m_pJoinControl->m_aCBNatural.Check(static_cast<OQueryTableConnectionData*>(m_pConnData.get())->isNatural());
    m_pTableControl->Show();

    if( _bAllowTableSelect )
    {
        m_pTableControl->Init( m_pConnData );
        m_pTableControl->fillListBoxes();
    }
    else
    {
        m_pTableControl->fillAndDisable(m_pConnData);
        m_pTableControl->Init( m_pConnData );
    }

    m_pTableControl->lateUIInit(m_pJoinControl);

    sal_Bool bSupportFullJoin = sal_False;
    Reference<XDatabaseMetaData> xMeta;
    try
    {
        xMeta = m_xConnection->getMetaData();
        if ( xMeta.is() )
            bSupportFullJoin = xMeta->supportsFullOuterJoins();
    }
    catch(SQLException&)
    {
    }
    sal_Bool bSupportOuterJoin = sal_False;
    try
    {
        if ( xMeta.is() )
            bSupportOuterJoin= xMeta->supportsOuterJoins();
    }
    catch(SQLException&)
    {
    }

    setJoinType(eJoinType);

    aPB_OK.SetClickHdl( LINK(this, DlgQryJoin, OKClickHdl) );

    m_pJoinControl->aLB_JoinType.SetSelectHdl(LINK(this,DlgQryJoin,LBChangeHdl));
    m_pJoinControl->m_aCBNatural.SetToggleHdl(LINK(this,DlgQryJoin,NaturalToggleHdl));

    if ( static_cast<OQueryTableView*>(pParent)->getDesignView()->getController()->isReadOnly() )
    {
        m_pJoinControl->aLB_JoinType.Disable();
        m_pJoinControl->m_aCBNatural.Disable();
        m_pTableControl->Disable();
    }
    else
    {
        const USHORT nCount = m_pJoinControl->aLB_JoinType.GetEntryCount();
        for (USHORT i = 0; i < nCount; ++i)
        {
            const long nJoinTyp = reinterpret_cast<long>(m_pJoinControl->aLB_JoinType.GetEntryData(i));
            if ( !bSupportFullJoin && nJoinTyp == ID_FULL_JOIN )
                m_pJoinControl->aLB_JoinType.RemoveEntry(i);
            else if ( !bSupportOuterJoin && (nJoinTyp == ID_LEFT_JOIN || nJoinTyp == ID_RIGHT_JOIN) )
                m_pJoinControl->aLB_JoinType.RemoveEntry(i);
        }

        m_pTableControl->NotifyCellChange();
        m_pTableControl->enableRelation(!static_cast<OQueryTableConnectionData*>(m_pConnData.get())->isNatural() && eJoinType != CROSS_JOIN );
    }

    FreeResource();
}

//------------------------------------------------------------------------
DlgQryJoin::~DlgQryJoin()
{
    DBG_DTOR(DlgQryJoin,NULL);
    delete m_pJoinControl;
    delete m_pTableControl;
}
// -----------------------------------------------------------------------------
IMPL_LINK( DlgQryJoin, LBChangeHdl, ListBox*, /*pListBox*/ )
{
    DBG_CHKTHIS(DlgQryJoin,NULL);
    if (m_pJoinControl->aLB_JoinType.GetSelectEntryPos() == m_pJoinControl->aLB_JoinType.GetSavedValue() )
        return 1;

    m_pJoinControl->aLB_JoinType.SaveValue();
    aML_HelpText.SetText(String());

    m_pTableControl->enableRelation(true);

    const String sFirstWinName  = m_pConnData->getReferencingTable()->GetWinName();
    const String sSecondWinName = m_pConnData->getReferencedTable()->GetWinName();
    const EJoinType eOldJoinType = eJoinType;
    USHORT nResId = 0;
    const USHORT nPos = m_pJoinControl->aLB_JoinType.GetSelectEntryPos();
    const long nJoinType = reinterpret_cast<long>(m_pJoinControl->aLB_JoinType.GetEntryData(nPos));
    sal_Bool bAddHint = sal_True;
    switch ( nJoinType )
    {
        default:
        case ID_INNER_JOIN:
            nResId = STR_QUERY_INNER_JOIN;
            bAddHint = sal_False;
            eJoinType = INNER_JOIN;
            break;
        case ID_LEFT_JOIN:
            nResId = STR_QUERY_LEFTRIGHT_JOIN;
            eJoinType = LEFT_JOIN;
            break;
        case ID_RIGHT_JOIN:
            nResId = STR_QUERY_LEFTRIGHT_JOIN;
            eJoinType = RIGHT_JOIN;
            break;
        case ID_FULL_JOIN:
            nResId = STR_QUERY_FULL_JOIN;
            eJoinType = FULL_JOIN;
            break;
        case ID_CROSS_JOIN:
            {
                nResId = STR_QUERY_CROSS_JOIN;
                eJoinType = CROSS_JOIN;

                m_pConnData->ResetConnLines();
                m_pTableControl->lateInit();
                m_pJoinControl->m_aCBNatural.Check(FALSE);
                m_pTableControl->enableRelation(false);
                ::rtl::OUString sEmpty;
                m_pConnData->AppendConnLine(sEmpty,sEmpty);
                aPB_OK.Enable(TRUE);
            }
            break;
    }

    m_pJoinControl->m_aCBNatural.Enable(eJoinType != CROSS_JOIN);

    if ( eJoinType != eOldJoinType && eOldJoinType == CROSS_JOIN )
    {
        m_pConnData->ResetConnLines();
    }
    if ( eJoinType != CROSS_JOIN )
    {
        m_pTableControl->NotifyCellChange();
        NaturalToggleHdl(&m_pJoinControl->m_aCBNatural);
    }

    m_pTableControl->Invalidate();

    String sHelpText = String( ModuleRes( nResId ) );
    if( nPos )
    {
        sHelpText.SearchAndReplace( String( RTL_CONSTASCII_STRINGPARAM( "%1" ) ), sFirstWinName );
        sHelpText.SearchAndReplace( String( RTL_CONSTASCII_STRINGPARAM( "%2" ) ), sSecondWinName );
    }
    if ( bAddHint )
    {
        sHelpText += String( RTL_CONSTASCII_STRINGPARAM( "\n" ) );
        sHelpText += String( ModuleRes( STR_JOIN_TYPE_HINT ) );
    }

    aML_HelpText.SetText( sHelpText );
    return 1;
}
// -----------------------------------------------------------------------------

IMPL_LINK( DlgQryJoin, OKClickHdl, Button*, /*pButton*/ )
{
    DBG_CHKTHIS(DlgQryJoin,NULL);

    m_pConnData->Update();
    m_pOrigConnData->CopyFrom( *m_pConnData );

    EndDialog(RET_OK);
    return 1;
}
// -----------------------------------------------------------------------------

IMPL_LINK( DlgQryJoin, NaturalToggleHdl, CheckBox*, /*pButton*/ )
{
    DBG_CHKTHIS(DlgQryJoin,NULL);
    BOOL bChecked = m_pJoinControl->m_aCBNatural.IsChecked();
    static_cast<OQueryTableConnectionData*>(m_pConnData.get())->setNatural(bChecked);
    m_pTableControl->enableRelation(!bChecked);
    if ( bChecked )
    {
        m_pConnData->ResetConnLines();
        try
        {
            Reference<XNameAccess> xReferencedTableColumns(m_pConnData->getReferencedTable()->getColumns());
            Sequence< ::rtl::OUString> aSeq = m_pConnData->getReferencingTable()->getColumns()->getElementNames();
            const ::rtl::OUString* pIter = aSeq.getConstArray();
            const ::rtl::OUString* pEnd   = pIter + aSeq.getLength();
            for(;pIter != pEnd;++pIter)
            {
                if ( xReferencedTableColumns->hasByName(*pIter) )
                    m_pConnData->AppendConnLine(*pIter,*pIter);
            }
        }
        catch(const Exception&)
        {
            OSL_ENSURE(0,"Exception caught while asking for column names in case of a natural join.");
        }
        m_pTableControl->NotifyCellChange();
        m_pTableControl->Invalidate();
    }

    return 1;
}
// -----------------------------------------------------------------------------
TTableConnectionData::value_type DlgQryJoin::getConnectionData() const
{
    return m_pConnData;
}
// -----------------------------------------------------------------------------
void DlgQryJoin::setValid(sal_Bool _bValid)
{
    //LBChangeHdl(&aLB_JoinType);

    aPB_OK.Enable(_bValid || eJoinType == CROSS_JOIN );
}
// -----------------------------------------------------------------------------
void DlgQryJoin::notifyConnectionChange( )
{
    setJoinType( static_cast<OQueryTableConnectionData*>(m_pConnData.get())->GetJoinType() );
    m_pJoinControl->m_aCBNatural.Check(static_cast<OQueryTableConnectionData*>(m_pConnData.get())->isNatural());
    NaturalToggleHdl(&m_pJoinControl->m_aCBNatural);
}
// -----------------------------------------------------------------------------
void DlgQryJoin::setJoinType(EJoinType _eNewJoinType)
{
    eJoinType = _eNewJoinType;
    m_pJoinControl->m_aCBNatural.Enable(eJoinType != CROSS_JOIN);

    long nJoinType = 0;
    switch ( eJoinType )
    {
        default:
        case INNER_JOIN:
            nJoinType = ID_INNER_JOIN;
            break;
        case LEFT_JOIN:
            nJoinType = ID_LEFT_JOIN;
            break;
        case RIGHT_JOIN:
            nJoinType = ID_RIGHT_JOIN;
            break;
        case FULL_JOIN:
            nJoinType = ID_FULL_JOIN;
            break;
        case CROSS_JOIN:
            nJoinType = ID_CROSS_JOIN;
            break;
    }

    const USHORT nCount = m_pJoinControl->aLB_JoinType.GetEntryCount();
    for (USHORT i = 0; i < nCount; ++i)
    {
        if ( nJoinType == reinterpret_cast<long>(m_pJoinControl->aLB_JoinType.GetEntryData(i)) )
        {
            m_pJoinControl->aLB_JoinType.SelectEntryPos(i);
            break;
        }
    }

    LBChangeHdl(&m_pJoinControl->aLB_JoinType);
}
// -----------------------------------------------------------------------------

<|endoftext|>