<commit_before>#ifndef HMLIB_CSVITERATOR_INC
#define HMLIB_CSVITERATOR_INC 100
#
#include<iterator>
#include<iostream>
#include<sstream>
namespace hmLib{
	template<class Elem = char, class Traits = std::char_traits<Elem> >
	struct basic_csv_mode{
	public:
		Elem Sep;
		Elem End;
		Elem Esc;
	public:
		constexpr basic_csv_mode(Elem Sep_, Elem End_ = '\n', Elem Esc_ = '"')
			: Sep(Sep_)
			, End(End_)
			, Esc(Esc_){
		}
	};

	namespace csv{
		namespace mode{
			constexpr const basic_csv_mode<char> csv(',');
			constexpr const basic_csv_mode<char> tsv('\t');
			constexpr const basic_csv_mode<char> ssv(' ');
		}

		template<class Elem = char, class Traits = std::char_traits<Elem> >
		std::basic_string < Elem, Traits > cell_encode(std::basic_string < Elem, Traits > Str, basic_csv_mode<Elem, Traits> CSVMode){
			if(Str.find(CSVMode.Sep) < Str.size() || Str.find(CSVMode.Esc) < Str.size()){
				for(auto itr = Str.begin(); itr != Str.end(); ++itr){
					if(*itr == CSVMode.Esc){
						itr = Str.insert(++itr, CSVMode.Esc);
					}
				}

				Str.insert(Str.begin(), CSVMode.Esc);
				Str.push_back(CSVMode.Esc);
			}

			return std::move(Str);
		}
		template<class Elem = char, class Traits = std::char_traits<Elem> >
		std::basic_string < Elem, Traits > cell_decode(std::basic_string < Elem, Traits > Str, basic_csv_mode<Elem, Traits> CSVMode){
			if(Str.size()>1 && Str.front()== CSVMode.Esc && Str.back()== CSVMode.Esc){
				Str.erase(Str.begin());
				Str.pop_back();

				bool EscFlag=false;
				for(auto itr = Str.begin(); itr != Str.end(); ++itr){
					if(*itr == CSVMode.Esc){
						if(EscFlag){
							itr = Str.erase(itr);
							--itr;
							EscFlag = false;
						} else{
							EscFlag = true;
						}
					} else{
						EscFlag = false;
					}
				}
			}

			return std::move(Str);
		}
	}
	template<class Elem = char, class Traits = std::char_traits<Elem> >
	class basic_ocsv_iterator : public std::iterator < std::output_iterator_tag, void, void, void, void > {
	private:
		using my_type = basic_ocsv_iterator < Elem, Traits >;
		using ostream_type = std::basic_ostream < Elem, Traits > ;
		using string_type = std::basic_string < Elem, Traits > ;
		using csv_mode_type = basic_csv_mode<Elem, Traits>;
	private:
		struct output_proxy{
		private:
			my_type& My;
		private:
			void cell_head_treat(){
				if(My.IsCellHead && !My.IsLineHead){
					*(My.pstream) << My.CSVMode.Sep;
				}
				My.IsCellHead = false;
			}
		public:
			output_proxy(my_type& My_) :My(My_){}
			void operator=(const string_type& Str){
				cell_head_treat();
				*(My.pstream) << csv::cell_encode(Str,My.CSVMode);
			}
			void raw_str(const string_type& Str){
				cell_head_treat();
				*(My.pstream) << Str;
			}
			template<typename T>
			output_proxy& operator<<(T Val){
				cell_head_treat();
				*(My.pstream) << Val;
				return *this;
			}
			friend std::basic_istream<Elem, Traits>& operator>>(std::basic_istream<Elem, Traits>& in, output_proxy p){
				string_type Str;
				in >> Str;
				p = Str;
				return in;
			}
		};
	private:
		ostream_type* pstream;
		csv_mode_type CSVMode;
		bool IsCellHead;
		bool IsLineHead;
	public:
		basic_ocsv_iterator()
			: pstream(nullptr){
		}
		basic_ocsv_iterator(ostream_type& Stream_, csv_mode_type CSVMode_)
			: pstream(&Stream_)
			, CSVMode(CSVMode_)
			, IsCellHead(false)
			, IsLineHead(true){
		}
		basic_ocsv_iterator(const my_type& My_) = default;
		my_type& operator=(const my_type& My_) = default;
	public:
		operator bool()const{ return pstream; }
		output_proxy operator*(){ return output_proxy(*this); }
		my_type& operator++(){
			IsCellHead = true;
			IsLineHead = false;
			return *this;
		}
		my_type operator++(int){
			my_type ans(*this);
			operator++();
			return ans;
		}
		bool eol()const{ return IsLineHead; }
		void endl(){
			(*pstream) << CSVMode.End;
			IsLineHead = true;
			IsCellHead = false;
		}
	};
	using ocsv_iterator = basic_ocsv_iterator < char, std::char_traits<char> >;

	template<class Elem = char, class Traits = std::char_traits<Elem> >
	class basic_icsv_iterator : public std::iterator < std::input_iterator_tag, std::basic_string<Elem,Traits>> {
	private:
		using my_type = basic_icsv_iterator < Elem, Traits > ;
	public:
		using sstream_type = std::basic_stringstream < Elem, Traits >;
		using istream_type = std::basic_istream < Elem, Traits > ;
		using pos_type = typename istream_type::pos_type;
		using string_type = std::basic_string < Elem, Traits > ;
		using csv_mode_type = basic_csv_mode<Elem, Traits>;
	private:
		istream_type* pstream;
		csv_mode_type CSVMode;
		pos_type Pos;
		sstream_type sstream;
		bool HasRead;
		pos_type ReadPos;
		bool IsLineHead;
	private:
		void next(){
			if(HasRead){
				HasRead = false;
				Pos = ReadPos;
			} else{
				Elem c;
				pstream->seekg(0, std::ios::end);
				auto EndPos = pstream->tellg();
				pstream->seekg(Pos);

				bool EscFlag = false;
				while(pstream->tellg() != EndPos){
					c = pstream->get();

					if(c == CSVMode.End || c == EOF){
						IsLineHead = true;
						break;
					}

					if(c == CSVMode.Sep && !EscFlag){
						IsLineHead = false;
						break;
					}

					if(c == CSVMode.Esc){
						EscFlag = !EscFlag;
					}
				}

				Pos = pstream->tellg();
			}
		}
		sstream_type& read(){
			if(!HasRead){
				Elem c;
				sstream.str(string_type());
				sstream.clear();

				pstream->seekg(0, std::ios::end);
				auto EndPos = pstream->tellg();
				pstream->seekg(Pos);

				bool EscFlag=false;
				while(pstream->tellg() != EndPos){
					c = pstream->get();

					if(c == CSVMode.End || c == EOF){
						IsLineHead = true;
						break;
					}

					if(c == CSVMode.Sep && !EscFlag){
						IsLineHead = false;
						break;
					}

					if(c == CSVMode.Esc){
						EscFlag = !EscFlag;
					}

					sstream << c;
				}

				ReadPos = pstream->tellg();
				HasRead = true;
			}
			return sstream;
		}
	private:
		struct input_proxy{
		private:
			my_type& My;
		public:
			input_proxy(my_type& My_) :My(My_){}
			operator string_type(){ return csv::cell_decode(My.read().str(), My.CSVMode); }
			string_type raw_str(){return My.read().str();}
			template<typename T>
			input_proxy& operator>>(T& Val){
				My.read() >> Val;
				return *this;
			}
			friend std::basic_ostream<Elem, Traits>& operator<<(std::basic_ostream<Elem, Traits>& out, input_proxy p){
				return out << static_cast<string_type>(p);
			}
		};
	public:
		basic_icsv_iterator() :pstream(nullptr){}
		basic_icsv_iterator(istream_type& Stream_, pos_type Pos_, csv_mode_type CSVMode_,bool IsLineHead_)
			: pstream(&Stream_)
			, CSVMode(CSVMode_)
			, Pos(Pos_)
			, sstream()
			, HasRead(false)
			, IsLineHead(IsLineHead_){
		}
		basic_icsv_iterator(const my_type& My_)
			: pstream(My_.pstream)
			, CSVMode(My_.CSVMode)
			, Pos(My_.Pos)
			, sstream(My_.sstream.str())
			, HasRead(My_.HasRead)
			, ReadPos(My_.ReadPos)
			, IsLineHead(My_.IsLineHead){
		}
		my_type& operator=(const my_type& My_){
			if(this != &My_){
				pstream = My_.pstream;
				CSVMode = My_.CSVMode;
				Pos = My_.Pos;
				sstream = My_.sstream.str();
				HasRead = My_.HasRead;
				ReadPos = My_.ReadPos;
				IsLineHead = My_.IsLineHead;
			}
		}
		input_proxy operator*(){return input_proxy(*this);}
		my_type& operator++(){
			next();
			return *this;
		}
		my_type operator++(int){
			basic_icsv_iterator ans(*this);
			operator++();
			return ans;
		}
		bool eol()const{ return IsLineHead; }
		bool eof(){
			pstream->seekg(0, std::ios::end);
			return Pos == pstream->tellg();
		}
		pos_type pos()const{ return Pos; }
		friend bool operator==(const my_type& my1, const my_type& my2){
			if(&my1 == &my2)return true;

			if(my1.pstream != my2.pstream) return false;

			return my1.Pos == my2.Pos;
		}
		friend bool operator!=(const my_type& my1, const my_type& my2){ return !(my1 == my2); }
	};
	using icsv_iterator = basic_icsv_iterator < char, std::char_traits<char> >;

	template<class Elem = char, class Traits = std::char_traits<Elem> >
	inline basic_icsv_iterator<Elem, Traits> icsv_begin(std::basic_istream < Elem, Traits >& Stream_, basic_icsv_iterator < Elem, Traits > CSVMode_ = csv::mode::csv){
		Stream_.seekg(0, std::ios::beg);
		auto Pos = Stream_.tellg();
		return basic_icsv_iterator<Elem, Traits>(Stream_, Pos, CSVMode_, true);
	}
	template<class Elem = char, class Traits = std::char_traits<Elem> >
	inline basic_icsv_iterator<Elem, Traits> icsv_current(std::basic_istream < Elem, Traits >& Stream_, basic_icsv_iterator < Elem, Traits > CSVMode_ = csv::mode::csv){
		auto Pos = Stream_.tellg();
		return basic_icsv_iterator<Elem, Traits>(Stream_, Pos, CSVMode_, false);
	}
	template<class Elem = char, class Traits = std::char_traits<Elem> >
	inline basic_icsv_iterator<Elem, Traits> icsv_end(std::basic_istream < Elem, Traits >& Stream_, basic_icsv_iterator < Elem, Traits > CSVMode_ = csv::mode::csv){
		Stream_.seekg(0, std::ios::end);
		auto Pos = Stream_.tellg();
		return basic_icsv_iterator<Elem, Traits>(Stream_, Pos, CSVMode_, true);
	}

	template<class Elem = char, class Traits = std::char_traits<Elem> >
	inline void advance_line(basic_icsv_iterator<Elem, Traits>& itr, unsigned int num = 1){
		unsigned int no = 0;
		do{
			++itr;
			if(itr.eol())++no;
		} while(no < num);
	}
	template<class Elem = char, class Traits = std::char_traits<Elem> >
	inline basic_icsv_iterator<Elem, Traits> next_line(const basic_icsv_iterator<Elem, Traits>& itr, unsigned int num = 1){
		basic_icsv_iterator<Elem, Traits> next_itr(itr);
		advance_line(next_itr);
		return next_itr;
	}
}
#
#endif
<commit_msg>Add write/read function in csv_iterator. Fix smal bugs in icsv_begin.<commit_after>#ifndef HMLIB_CSVITERATOR_INC
#define HMLIB_CSVITERATOR_INC 100
#
#include<iterator>
#include<iostream>
#include<sstream>
namespace hmLib{
	template<class Elem = char, class Traits = std::char_traits<Elem> >
	struct basic_csv_mode{
	public:
		Elem Sep;
		Elem End;
		Elem Esc;
	public:
		constexpr basic_csv_mode(Elem Sep_, Elem End_ = '\n', Elem Esc_ = '"')
			: Sep(Sep_)
			, End(End_)
			, Esc(Esc_){
		}
	};

	namespace csv{
		namespace mode{
			constexpr const basic_csv_mode<char> csv(',');
			constexpr const basic_csv_mode<char> tsv('\t');
			constexpr const basic_csv_mode<char> ssv(' ');
		}

		template<class Elem = char, class Traits = std::char_traits<Elem> >
		std::basic_string < Elem, Traits > cell_encode(std::basic_string < Elem, Traits > Str, basic_csv_mode<Elem, Traits> CSVMode){
			if(Str.find(CSVMode.Sep) < Str.size() || Str.find(CSVMode.Esc) < Str.size()){
				for(auto itr = Str.begin(); itr != Str.end(); ++itr){
					if(*itr == CSVMode.Esc){
						itr = Str.insert(++itr, CSVMode.Esc);
					}
				}

				Str.insert(Str.begin(), CSVMode.Esc);
				Str.push_back(CSVMode.Esc);
			}

			return std::move(Str);
		}
		template<class Elem = char, class Traits = std::char_traits<Elem> >
		std::basic_string < Elem, Traits > cell_decode(std::basic_string < Elem, Traits > Str, basic_csv_mode<Elem, Traits> CSVMode){
			if(Str.size()>1 && Str.front()== CSVMode.Esc && Str.back()== CSVMode.Esc){
				Str.erase(Str.begin());
				Str.pop_back();

				bool EscFlag=false;
				for(auto itr = Str.begin(); itr != Str.end(); ++itr){
					if(*itr == CSVMode.Esc){
						if(EscFlag){
							itr = Str.erase(itr);
							--itr;
							EscFlag = false;
						} else{
							EscFlag = true;
						}
					} else{
						EscFlag = false;
					}
				}
			}

			return std::move(Str);
		}
	}
	template<class Elem = char, class Traits = std::char_traits<Elem> >
	class basic_ocsv_iterator : public std::iterator < std::output_iterator_tag, void, void, void, void > {
	private:
		using my_type = basic_ocsv_iterator < Elem, Traits >;
		using ostream_type = std::basic_ostream < Elem, Traits > ;
		using string_type = std::basic_string < Elem, Traits > ;
		using csv_mode_type = basic_csv_mode<Elem, Traits>;
	private:
		struct output_proxy{
		private:
			my_type& My;
		private:
			void cell_head_treat(){
				if(My.IsCellHead && !My.IsLineHead){
					*(My.pstream) << My.CSVMode.Sep;
				}
				My.IsCellHead = false;
			}
		public:
			output_proxy(my_type& My_) :My(My_){}
			void operator=(const string_type& Str){
				cell_head_treat();
				*(My.pstream) << csv::cell_encode(Str,My.CSVMode);
			}
			void raw_str(const string_type& Str){
				cell_head_treat();
				*(My.pstream) << Str;
			}
			template<typename T>
			output_proxy& operator<<(T Val){
				cell_head_treat();
				*(My.pstream) << Val;
				return *this;
			}
			template<typename T, typename U>
			output_proxy& write(U Val) {
				cell_head_treat();
				T TmpVal = Val;
				*(My.pstream) << TmpVal;
				return *this;
			}
			friend std::basic_istream<Elem, Traits>& operator>>(std::basic_istream<Elem, Traits>& in, output_proxy p){
				string_type Str;
				in >> Str;
				p = Str;
				return in;
			}
		};
	private:
		ostream_type* pstream;
		csv_mode_type CSVMode;
		bool IsCellHead;
		bool IsLineHead;
	public:
		basic_ocsv_iterator()
			: pstream(nullptr){
		}
		basic_ocsv_iterator(ostream_type& Stream_, csv_mode_type CSVMode_)
			: pstream(&Stream_)
			, CSVMode(CSVMode_)
			, IsCellHead(false)
			, IsLineHead(true){
		}
		basic_ocsv_iterator(const my_type& My_) = default;
		my_type& operator=(const my_type& My_) = default;
	public:
		operator bool()const{ return pstream; }
		output_proxy operator*(){ return output_proxy(*this); }
		my_type& operator++(){
			IsCellHead = true;
			IsLineHead = false;
			return *this;
		}
		my_type operator++(int){
			my_type ans(*this);
			operator++();
			return ans;
		}
		bool eol()const{ return IsLineHead; }
		void endl(){
			(*pstream) << CSVMode.End;
			IsLineHead = true;
			IsCellHead = false;
		}
	};
	using ocsv_iterator = basic_ocsv_iterator < char, std::char_traits<char> >;

	template<class Elem = char, class Traits = std::char_traits<Elem> >
	class basic_icsv_iterator : public std::iterator < std::input_iterator_tag, std::basic_string<Elem,Traits>> {
	private:
		using my_type = basic_icsv_iterator < Elem, Traits > ;
	public:
		using sstream_type = std::basic_stringstream < Elem, Traits >;
		using istream_type = std::basic_istream < Elem, Traits > ;
		using pos_type = typename istream_type::pos_type;
		using string_type = std::basic_string < Elem, Traits > ;
		using csv_mode_type = basic_csv_mode<Elem, Traits>;
	private:
		istream_type* pstream;
		csv_mode_type CSVMode;
		pos_type Pos;
		sstream_type sstream;
		bool HasRead;
		pos_type ReadPos;
		bool IsLineHead;
	private:
		void next(){
			if(HasRead){
				HasRead = false;
				Pos = ReadPos;
			} else{
				Elem c;
				pstream->seekg(0, std::ios::end);
				auto EndPos = pstream->tellg();
				pstream->seekg(Pos);

				bool EscFlag = false;
				while(pstream->tellg() != EndPos){
					c = pstream->get();

					if(c == CSVMode.End || c == EOF){
						IsLineHead = true;
						break;
					}

					if(c == CSVMode.Sep && !EscFlag){
						IsLineHead = false;
						break;
					}

					if(c == CSVMode.Esc){
						EscFlag = !EscFlag;
					}
				}

				Pos = pstream->tellg();
			}
		}
		sstream_type& read(){
			if(!HasRead){
				Elem c;
				sstream.str(string_type());
				sstream.clear();

				pstream->seekg(0, std::ios::end);
				auto EndPos = pstream->tellg();
				pstream->seekg(Pos);

				bool EscFlag=false;
				while(pstream->tellg() != EndPos){
					c = pstream->get();

					if(c == CSVMode.End || c == EOF){
						IsLineHead = true;
						break;
					}

					if(c == CSVMode.Sep && !EscFlag){
						IsLineHead = false;
						break;
					}

					if(c == CSVMode.Esc){
						EscFlag = !EscFlag;
					}

					sstream << c;
				}

				ReadPos = pstream->tellg();
				HasRead = true;
			}
			return sstream;
		}
	private:
		struct input_proxy{
		private:
			my_type& My;
		public:
			input_proxy(my_type& My_) :My(My_){}
			operator string_type(){ return csv::cell_decode(My.read().str(), My.CSVMode); }
			string_type raw_str(){return My.read().str();}
			template<typename T>
			input_proxy& operator>>(T& Val){
				My.read() >> Val;
				return *this;
			}
			template<typename T,typename U>
			input_proxy& read(U& Val) {
				T TmpVal;
				My.read() >> TmpVal;
				Val = TmpVal;
				return *this;
			}
			friend std::basic_ostream<Elem, Traits>& operator<<(std::basic_ostream<Elem, Traits>& out, input_proxy p){
				return out << static_cast<string_type>(p);
			}
		};
	public:
		basic_icsv_iterator() :pstream(nullptr){}
		basic_icsv_iterator(istream_type& Stream_, pos_type Pos_, csv_mode_type CSVMode_,bool IsLineHead_)
			: pstream(&Stream_)
			, CSVMode(CSVMode_)
			, Pos(Pos_)
			, sstream()
			, HasRead(false)
			, IsLineHead(IsLineHead_){
		}
		basic_icsv_iterator(const my_type& My_)
			: pstream(My_.pstream)
			, CSVMode(My_.CSVMode)
			, Pos(My_.Pos)
			, sstream(My_.sstream.str())
			, HasRead(My_.HasRead)
			, ReadPos(My_.ReadPos)
			, IsLineHead(My_.IsLineHead){
		}
		my_type& operator=(const my_type& My_){
			if(this != &My_){
				pstream = My_.pstream;
				CSVMode = My_.CSVMode;
				Pos = My_.Pos;
				sstream = My_.sstream.str();
				HasRead = My_.HasRead;
				ReadPos = My_.ReadPos;
				IsLineHead = My_.IsLineHead;
			}
		}
		input_proxy operator*(){return input_proxy(*this);}
		my_type& operator++(){
			next();
			return *this;
		}
		my_type operator++(int){
			basic_icsv_iterator ans(*this);
			operator++();
			return ans;
		}
		bool eol()const{ return IsLineHead; }
		bool eof(){
			pstream->seekg(0, std::ios::end);
			return Pos == pstream->tellg();
		}
		pos_type pos()const{ return Pos; }
		friend bool operator==(const my_type& my1, const my_type& my2){
			if(&my1 == &my2)return true;

			if(my1.pstream != my2.pstream) return false;

			return my1.Pos == my2.Pos;
		}
		friend bool operator!=(const my_type& my1, const my_type& my2){ return !(my1 == my2); }
	};
	using icsv_iterator = basic_icsv_iterator < char, std::char_traits<char> >;

	template<class Elem = char, class Traits = std::char_traits<Elem> >
	inline basic_icsv_iterator<Elem, Traits> icsv_begin(std::basic_istream < Elem, Traits >& Stream_, basic_csv_mode < Elem, Traits > CSVMode_ = basic_csv_mode<Elem, Traits>(',')){
		Stream_.seekg(0, std::ios::beg);
		auto Pos = Stream_.tellg();
		return basic_icsv_iterator<Elem, Traits>(Stream_, Pos, CSVMode_, true);
	}
	template<class Elem = char, class Traits = std::char_traits<Elem> >
	inline basic_icsv_iterator<Elem, Traits> icsv_current(std::basic_istream < Elem, Traits >& Stream_, basic_csv_mode < Elem, Traits > CSVMode_ = basic_csv_mode<Elem, Traits>(',')){
		auto Pos = Stream_.tellg();
		return basic_icsv_iterator<Elem, Traits>(Stream_, Pos, CSVMode_, false);
	}
	template<class Elem = char, class Traits = std::char_traits<Elem> >
	inline basic_icsv_iterator<Elem, Traits> icsv_end(std::basic_istream < Elem, Traits >& Stream_, basic_csv_mode < Elem, Traits > CSVMode_ = basic_csv_mode<Elem, Traits>(',')){
		Stream_.seekg(0, std::ios::end);
		auto Pos = Stream_.tellg();
		return basic_icsv_iterator<Elem, Traits>(Stream_, Pos, CSVMode_, true);
	}

	template<class Elem = char, class Traits = std::char_traits<Elem> >
	inline void advance_line(basic_icsv_iterator<Elem, Traits>& itr, unsigned int num = 1){
		unsigned int no = 0;
		do{
			++itr;
			if(itr.eol())++no;
		} while(no < num);
	}
	template<class Elem = char, class Traits = std::char_traits<Elem> >
	inline basic_icsv_iterator<Elem, Traits> next_line(const basic_icsv_iterator<Elem, Traits>& itr, unsigned int num = 1){
		basic_icsv_iterator<Elem, Traits> next_itr(itr);
		advance_line(next_itr);
		return next_itr;
	}
}
#
#endif
<|endoftext|>


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

#ifndef INCLUDED_SVLDLLAPI_H
#include "svtools/svldllapi.h"
#endif

#if STLPORT_VERSION<321
#include <stdarg.h>
#else
#include <cstdarg>  // std::va_list and friends
#endif

#ifndef _SFXPOOLITEM_HXX //autogen
#include <svtools/poolitem.hxx>
#endif
#ifndef _RTTI_HXX //autogen
#include <tools/rtti.hxx>
#endif
#ifndef _SOLAR_H
#include <tools/solar.h>
#endif

class SfxItemPool;
class SfxPoolItem;
class SvStream;

typedef SfxPoolItem const** SfxItemArray;

#define USHORT_ARG int

#ifdef MI_HATS_REPARIERT
#ifndef DBG
#ifdef DBG_UTILx
#define DBG(s) s
#define _pChildCount(THIS)  (  *(USHORT**)SfxPointerServer::GetServer()->GetPointer(THIS) )
#define _pChildCountCtor    ( (*(USHORT**)SfxPointerServer::GetServer()->CreatePointer(this)) = new USHORT )
#define _pChildCountDtor    ( SfxPointerServer::GetServer()->ReleasePointer(this) )
#else
#define DBG(s)
#endif
#endif
#else
#ifdef DBG
#undef DBG
#endif
#define DBG(s)
#endif

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

#define SFX_ITEMSET_GET( rSet, pItem, ItemType, nSlotId, bDeep ) \
    const ItemType *pItem = (const ItemType*) \
                            (rSet).GetItem( nSlotId, bDeep, TYPE(ItemType) )

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

class SVL_DLLPUBLIC SfxItemSet
{
    friend class SfxItemIter;

    SfxItemPool*                _pPool;         // der verwendete Pool
    const SfxItemSet*           _pParent;       // Ableitung
    SfxItemArray                _aItems;        // Item-Feld
    USHORT*                     _pWhichRanges;  // Array von Which-Bereichen
    USHORT                      _nCount;        // Anzahl Items

    //---------------------------------------------------------------------
#ifndef _SFXITEMS_HXX

friend class SfxItemPoolCache;
friend class SfxAllItemSet;
friend const char *DbgCheckItemSet( const void* );

private:
    SVL_DLLPRIVATE void                     InitRanges_Impl(const USHORT *nWhichPairTable);
    SVL_DLLPRIVATE void                     InitRanges_Impl(va_list pWhich, USHORT n1, USHORT n2, USHORT n3);
    SVL_DLLPRIVATE void                     InitRanges_Impl(USHORT nWh1, USHORT nWh2);

public:
    SfxItemArray                GetItems_Impl() const { return _aItems; }

#endif
    //---------------------------------------------------------------------

private:
    const SfxItemSet&           operator=(const SfxItemSet &);   // n.i.!!

protected:
    // Notification-Callback
    virtual void                Changed( const SfxPoolItem& rOld, const SfxPoolItem& rNew );

    // direkte Put-Methode
    int                         PutDirect(const SfxPoolItem &rItem);

public:
                                SfxItemSet( const SfxItemSet& );

                                SfxItemSet( SfxItemPool&, BOOL bTotalPoolRanges = FALSE );
                                SfxItemSet( SfxItemPool&, USHORT nWhich1, USHORT nWhich2 );
                                SfxItemSet( SfxItemPool&, USHORT_ARG nWh1, USHORT_ARG nWh2, USHORT_ARG nNull, ... );
                                SfxItemSet( SfxItemPool&, const USHORT* nWhichPairTable );
    virtual                     ~SfxItemSet();

    virtual SfxItemSet *        Clone(BOOL bItems = TRUE, SfxItemPool *pToPool = 0) const;

    // Items erfragen
    USHORT                      Count() const { return _nCount; }
    USHORT                      TotalCount() const;

    virtual const SfxPoolItem&  Get( USHORT nWhich, BOOL bSrchInParent = TRUE ) const;
    const SfxPoolItem*          GetItem( USHORT nWhich, BOOL bSrchInParent = TRUE,
                                         TypeId aItemType = 0 ) const;

    // Which-Wert des Items an der Position nPos erfragen
    USHORT                      GetWhichByPos(USHORT nPos) const;

    // Item-Status erfragen
    SfxItemState                GetItemState(   USHORT nWhich,
                                                BOOL bSrchInParent = TRUE,
                                                const SfxPoolItem **ppItem = 0 ) const;

    virtual void                DisableItem(USHORT nWhich);
    virtual void                InvalidateItem( USHORT nWhich );
    virtual USHORT              ClearItem( USHORT nWhich = 0);
    virtual void                ClearInvalidItems( BOOL bHardDefault = FALSE );
            void                InvalidateAllItems(); HACK(via nWhich = 0)

    inline void                 SetParent( const SfxItemSet* pNew );

    // Items hinzufuegen, loeschen etc.
    virtual const SfxPoolItem*  Put( const SfxPoolItem&, USHORT nWhich );
    const SfxPoolItem*          Put( const SfxPoolItem& rItem )
                                { return Put(rItem, rItem.Which()); }
    virtual int                 Put( const SfxItemSet&,
                                     BOOL bInvalidAsDefault = TRUE );
    void                        PutExtended( const SfxItemSet&,
                                             SfxItemState eDontCareAs = SFX_ITEM_UNKNOWN,
                                             SfxItemState eDefaultAs = SFX_ITEM_UNKNOWN );

    virtual int                 Set( const SfxItemSet&, BOOL bDeep = TRUE );

    virtual void                Intersect( const SfxItemSet& rSet );
    virtual void                MergeValues( const SfxItemSet& rSet, BOOL bOverwriteDefaults = FALSE );
    virtual void                Differentiate( const SfxItemSet& rSet );
    virtual void                MergeValue( const SfxPoolItem& rItem, BOOL bOverwriteDefaults = FALSE  );

    SfxItemPool*                GetPool() const { return _pPool; }
    const USHORT*               GetRanges() const { return _pWhichRanges; }
    void                        SetRanges( const USHORT *pRanges );
    void                        MergeRange( USHORT nFrom, USHORT nTo );
    const SfxItemSet*           GetParent() const { return _pParent; }

    virtual SvStream &          Load( SvStream &, FASTBOOL bDirect = FALSE,
                                      const SfxItemPool *pRefPool = 0 );
    virtual SvStream &          Store( SvStream &, FASTBOOL bDirect = FALSE ) const;

    virtual int                 operator==(const SfxItemSet &) const;
};

// --------------- Inline Implementierungen ------------------------

inline void SfxItemSet::SetParent( const SfxItemSet* pNew )
{
    DBG( if (_pParent) --*_pChildCount(_pParent) );
    _pParent = pNew;
    DBG( if (_pParent) ++*_pChildCount(_pParent) );
}

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

class SVL_DLLPUBLIC SfxAllItemSet: public SfxItemSet

/*  versteht alle Ranges; werden durch das Putten der Items
    automatisch angepasst
*/

{
    SfxVoidItem                 aDefault;
    USHORT                      nFree;

public:
                                SfxAllItemSet( SfxItemPool &rPool );
                                SfxAllItemSet( const SfxItemSet & );
                                SfxAllItemSet( const SfxAllItemSet & );

    virtual SfxItemSet *        Clone( BOOL bItems = TRUE, SfxItemPool *pToPool = 0 ) const;
    virtual const SfxPoolItem*  Put( const SfxPoolItem&, USHORT nWhich );
    const SfxPoolItem*          Put( const SfxPoolItem& rItem )
    { return Put(rItem, rItem.Which()); }
    virtual int                 Put( const SfxItemSet&,
                                     BOOL bInvalidAsDefault = TRUE );
};

#endif // #ifndef _SFXITEMSET_HXX

<commit_msg>INTEGRATION: CWS changefileheader (1.3.84); FILE MERGED 2008/04/01 15:44:31 thb 1.3.84.3: #i85898# Stripping all external header guards 2008/04/01 12:43:13 thb 1.3.84.2: #i85898# Stripping all external header guards 2008/03/31 13:01:05 rt 1.3.84.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: itemset.hxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _SFXITEMSET_HXX
#define _SFXITEMSET_HXX

#include "svtools/svldllapi.h"

#if STLPORT_VERSION<321
#include <stdarg.h>
#else
#include <cstdarg>  // std::va_list and friends
#endif
#include <svtools/poolitem.hxx>
#include <tools/rtti.hxx>
#include <tools/solar.h>

class SfxItemPool;
class SfxPoolItem;
class SvStream;

typedef SfxPoolItem const** SfxItemArray;

#define USHORT_ARG int

#ifdef MI_HATS_REPARIERT
#ifndef DBG
#ifdef DBG_UTILx
#define DBG(s) s
#define _pChildCount(THIS)  (  *(USHORT**)SfxPointerServer::GetServer()->GetPointer(THIS) )
#define _pChildCountCtor    ( (*(USHORT**)SfxPointerServer::GetServer()->CreatePointer(this)) = new USHORT )
#define _pChildCountDtor    ( SfxPointerServer::GetServer()->ReleasePointer(this) )
#else
#define DBG(s)
#endif
#endif
#else
#ifdef DBG
#undef DBG
#endif
#define DBG(s)
#endif

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

#define SFX_ITEMSET_GET( rSet, pItem, ItemType, nSlotId, bDeep ) \
    const ItemType *pItem = (const ItemType*) \
                            (rSet).GetItem( nSlotId, bDeep, TYPE(ItemType) )

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

class SVL_DLLPUBLIC SfxItemSet
{
    friend class SfxItemIter;

    SfxItemPool*                _pPool;         // der verwendete Pool
    const SfxItemSet*           _pParent;       // Ableitung
    SfxItemArray                _aItems;        // Item-Feld
    USHORT*                     _pWhichRanges;  // Array von Which-Bereichen
    USHORT                      _nCount;        // Anzahl Items

    //---------------------------------------------------------------------
#ifndef _SFXITEMS_HXX

friend class SfxItemPoolCache;
friend class SfxAllItemSet;
friend const char *DbgCheckItemSet( const void* );

private:
    SVL_DLLPRIVATE void                     InitRanges_Impl(const USHORT *nWhichPairTable);
    SVL_DLLPRIVATE void                     InitRanges_Impl(va_list pWhich, USHORT n1, USHORT n2, USHORT n3);
    SVL_DLLPRIVATE void                     InitRanges_Impl(USHORT nWh1, USHORT nWh2);

public:
    SfxItemArray                GetItems_Impl() const { return _aItems; }

#endif
    //---------------------------------------------------------------------

private:
    const SfxItemSet&           operator=(const SfxItemSet &);   // n.i.!!

protected:
    // Notification-Callback
    virtual void                Changed( const SfxPoolItem& rOld, const SfxPoolItem& rNew );

    // direkte Put-Methode
    int                         PutDirect(const SfxPoolItem &rItem);

public:
                                SfxItemSet( const SfxItemSet& );

                                SfxItemSet( SfxItemPool&, BOOL bTotalPoolRanges = FALSE );
                                SfxItemSet( SfxItemPool&, USHORT nWhich1, USHORT nWhich2 );
                                SfxItemSet( SfxItemPool&, USHORT_ARG nWh1, USHORT_ARG nWh2, USHORT_ARG nNull, ... );
                                SfxItemSet( SfxItemPool&, const USHORT* nWhichPairTable );
    virtual                     ~SfxItemSet();

    virtual SfxItemSet *        Clone(BOOL bItems = TRUE, SfxItemPool *pToPool = 0) const;

    // Items erfragen
    USHORT                      Count() const { return _nCount; }
    USHORT                      TotalCount() const;

    virtual const SfxPoolItem&  Get( USHORT nWhich, BOOL bSrchInParent = TRUE ) const;
    const SfxPoolItem*          GetItem( USHORT nWhich, BOOL bSrchInParent = TRUE,
                                         TypeId aItemType = 0 ) const;

    // Which-Wert des Items an der Position nPos erfragen
    USHORT                      GetWhichByPos(USHORT nPos) const;

    // Item-Status erfragen
    SfxItemState                GetItemState(   USHORT nWhich,
                                                BOOL bSrchInParent = TRUE,
                                                const SfxPoolItem **ppItem = 0 ) const;

    virtual void                DisableItem(USHORT nWhich);
    virtual void                InvalidateItem( USHORT nWhich );
    virtual USHORT              ClearItem( USHORT nWhich = 0);
    virtual void                ClearInvalidItems( BOOL bHardDefault = FALSE );
            void                InvalidateAllItems(); HACK(via nWhich = 0)

    inline void                 SetParent( const SfxItemSet* pNew );

    // Items hinzufuegen, loeschen etc.
    virtual const SfxPoolItem*  Put( const SfxPoolItem&, USHORT nWhich );
    const SfxPoolItem*          Put( const SfxPoolItem& rItem )
                                { return Put(rItem, rItem.Which()); }
    virtual int                 Put( const SfxItemSet&,
                                     BOOL bInvalidAsDefault = TRUE );
    void                        PutExtended( const SfxItemSet&,
                                             SfxItemState eDontCareAs = SFX_ITEM_UNKNOWN,
                                             SfxItemState eDefaultAs = SFX_ITEM_UNKNOWN );

    virtual int                 Set( const SfxItemSet&, BOOL bDeep = TRUE );

    virtual void                Intersect( const SfxItemSet& rSet );
    virtual void                MergeValues( const SfxItemSet& rSet, BOOL bOverwriteDefaults = FALSE );
    virtual void                Differentiate( const SfxItemSet& rSet );
    virtual void                MergeValue( const SfxPoolItem& rItem, BOOL bOverwriteDefaults = FALSE  );

    SfxItemPool*                GetPool() const { return _pPool; }
    const USHORT*               GetRanges() const { return _pWhichRanges; }
    void                        SetRanges( const USHORT *pRanges );
    void                        MergeRange( USHORT nFrom, USHORT nTo );
    const SfxItemSet*           GetParent() const { return _pParent; }

    virtual SvStream &          Load( SvStream &, FASTBOOL bDirect = FALSE,
                                      const SfxItemPool *pRefPool = 0 );
    virtual SvStream &          Store( SvStream &, FASTBOOL bDirect = FALSE ) const;

    virtual int                 operator==(const SfxItemSet &) const;
};

// --------------- Inline Implementierungen ------------------------

inline void SfxItemSet::SetParent( const SfxItemSet* pNew )
{
    DBG( if (_pParent) --*_pChildCount(_pParent) );
    _pParent = pNew;
    DBG( if (_pParent) ++*_pChildCount(_pParent) );
}

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

class SVL_DLLPUBLIC SfxAllItemSet: public SfxItemSet

/*  versteht alle Ranges; werden durch das Putten der Items
    automatisch angepasst
*/

{
    SfxVoidItem                 aDefault;
    USHORT                      nFree;

public:
                                SfxAllItemSet( SfxItemPool &rPool );
                                SfxAllItemSet( const SfxItemSet & );
                                SfxAllItemSet( const SfxAllItemSet & );

    virtual SfxItemSet *        Clone( BOOL bItems = TRUE, SfxItemPool *pToPool = 0 ) const;
    virtual const SfxPoolItem*  Put( const SfxPoolItem&, USHORT nWhich );
    const SfxPoolItem*          Put( const SfxPoolItem& rItem )
    { return Put(rItem, rItem.Which()); }
    virtual int                 Put( const SfxItemSet&,
                                     BOOL bInvalidAsDefault = TRUE );
};

#endif // #ifndef _SFXITEMSET_HXX

<|endoftext|>


<commit_before>#ifndef maps_MLSMapVisualization_H
#define maps_MLSMapVisualization_H

#include <vizkit3d/Vizkit3DPlugin.hpp>

#include <boost/noncopyable.hpp>

#include <osg/Geode>
#include <osg/Shape>
#include <osg/Texture2D>

#include <maps/grid/MLSMap.hpp>

namespace vizkit3d
{
    class MLSMapVisualization
        : public vizkit3d::Vizkit3DPlugin< ::maps::grid::MLSMap<::maps::grid::MLSConfig::KALMAN> >
        , public vizkit3d::VizPluginAddType< ::maps::grid::MLSMap<::maps::grid::MLSConfig::SLOPE> >
        , public vizkit3d::VizPluginAddType< ::maps::grid::MLSMap<::maps::grid::MLSConfig::PRECALCULATED> >
        , boost::noncopyable
    {
        Q_OBJECT

        Q_PROPERTY(bool show_map_extents READ areMapExtentsShown WRITE setShowMapExtents)
        Q_PROPERTY(bool show_uncertainty READ isUncertaintyShown WRITE setShowUncertainty)
        Q_PROPERTY(bool show_negative READ isNegativeShown WRITE setShowNegative)
        Q_PROPERTY(bool show_patch_extents READ arePatchExtentsShown WRITE setShowPatchExtents)
        Q_PROPERTY(bool estimate_normals READ areNormalsEstimated WRITE setEstimateNormals)
        Q_PROPERTY(bool show_normals READ areNormalsShown WRITE setShowNormals)
        Q_PROPERTY(bool cycle_height_color READ isHeightColorCycled WRITE setCycleHeightColor)
        Q_PROPERTY(double cycle_color_interval READ getCycleColorInterval WRITE setCycleColorInterval)
        Q_PROPERTY(QColor horizontal_cell_color READ getHorizontalCellColor WRITE setHorizontalCellColor)
        Q_PROPERTY(QColor vertical_cell_color READ getVerticalCellColor WRITE setVerticalCellColor)
        Q_PROPERTY(QColor negative_cell_color READ getNegativeCellColor WRITE setNegativeCellColor)
        Q_PROPERTY(QColor uncertainty_color READ getUncertaintyColor WRITE setUncertaintyColor)

        public:
            MLSMapVisualization();
            ~MLSMapVisualization();

            Q_INVOKABLE void updateData(::maps::grid::MLSMap<::maps::grid::MLSConfig::KALMAN> const &sample)
            {vizkit3d::Vizkit3DPlugin<::maps::grid::MLSMap<::maps::grid::MLSConfig::KALMAN>>::updateData(sample);}
            Q_INVOKABLE void updateData(::maps::grid::MLSMap<::maps::grid::MLSConfig::SLOPE> const &sample)
            {vizkit3d::Vizkit3DPlugin<::maps::grid::MLSMap<::maps::grid::MLSConfig::KALMAN>>::updateData(sample);}

        protected:
            virtual osg::ref_ptr<osg::Node> createMainNode();
            virtual void updateMainNode(osg::Node* node);
            virtual void updateDataIntern(::maps::grid::MLSMap<::maps::grid::MLSConfig::KALMAN> const& mls);
            virtual void updateDataIntern(::maps::grid::MLSMap<::maps::grid::MLSConfig::SLOPE> const& mls);
            virtual void updateDataIntern(::maps::grid::MLSMap<::maps::grid::MLSConfig::PRECALCULATED> const& mls);

        private:
            struct Data;
            boost::scoped_ptr<Data> p;

        public slots:

            bool isUncertaintyShown() const;
            void setShowUncertainty(bool enabled);

            bool isNegativeShown() const;
            void setShowNegative(bool enabled);

            bool areNormalsEstimated() const;
            void setEstimateNormals(bool enabled);

            bool areNormalsShown() const;
            void setShowNormals(bool enabled);

            bool isHeightColorCycled() const;
            void setCycleHeightColor(bool enabled);

            double getCycleColorInterval() const;
            void setCycleColorInterval(double interval);

            QColor getHorizontalCellColor() const;
            void setHorizontalCellColor(QColor color);

            QColor getVerticalCellColor() const;
            void setVerticalCellColor(QColor color);

            QColor getNegativeCellColor() const;
            void setNegativeCellColor(QColor color);

            QColor getUncertaintyColor() const;
            void setUncertaintyColor(QColor color);

            void setShowPatchExtents( bool value );
            bool arePatchExtentsShown() const;

            void setShowMapExtents(bool value);
            bool areMapExtentsShown() const;

        protected:
            osg::Vec4 horizontalCellColor;
            osg::Vec4 verticalCellColor;
            osg::Vec4 negativeCellColor;
            osg::Vec4 uncertaintyColor;

            bool showMapExtents;
            bool showUncertainty;
            bool showNegative;
            bool estimateNormals;
            bool showNormals;
            bool cycleHeightColor;
            double cycleColorInterval;
            bool showPatchExtents;

#if 0
            osg::Vec3 estimateNormal(
                const ::maps::MLSMap &grid,
                const ::maps::SurfacePatch &patch,
                const ::maps::Index &patch_idx) const;
#endif
    };
}
#endif
<commit_msg>Visualize precalculated MLSMap<commit_after>#ifndef maps_MLSMapVisualization_H
#define maps_MLSMapVisualization_H

#include <vizkit3d/Vizkit3DPlugin.hpp>

#include <boost/noncopyable.hpp>

#include <osg/Geode>
#include <osg/Shape>
#include <osg/Texture2D>

#include <maps/grid/MLSMap.hpp>

namespace vizkit3d
{
    class MLSMapVisualization
        : public vizkit3d::Vizkit3DPlugin< ::maps::grid::MLSMap<::maps::grid::MLSConfig::KALMAN> >
        , public vizkit3d::VizPluginAddType< ::maps::grid::MLSMap<::maps::grid::MLSConfig::SLOPE> >
        , public vizkit3d::VizPluginAddType< ::maps::grid::MLSMap<::maps::grid::MLSConfig::PRECALCULATED> >
        , boost::noncopyable
    {
        Q_OBJECT

        Q_PROPERTY(bool show_map_extents READ areMapExtentsShown WRITE setShowMapExtents)
        Q_PROPERTY(bool show_uncertainty READ isUncertaintyShown WRITE setShowUncertainty)
        Q_PROPERTY(bool show_negative READ isNegativeShown WRITE setShowNegative)
        Q_PROPERTY(bool show_patch_extents READ arePatchExtentsShown WRITE setShowPatchExtents)
        Q_PROPERTY(bool estimate_normals READ areNormalsEstimated WRITE setEstimateNormals)
        Q_PROPERTY(bool show_normals READ areNormalsShown WRITE setShowNormals)
        Q_PROPERTY(bool cycle_height_color READ isHeightColorCycled WRITE setCycleHeightColor)
        Q_PROPERTY(double cycle_color_interval READ getCycleColorInterval WRITE setCycleColorInterval)
        Q_PROPERTY(QColor horizontal_cell_color READ getHorizontalCellColor WRITE setHorizontalCellColor)
        Q_PROPERTY(QColor vertical_cell_color READ getVerticalCellColor WRITE setVerticalCellColor)
        Q_PROPERTY(QColor negative_cell_color READ getNegativeCellColor WRITE setNegativeCellColor)
        Q_PROPERTY(QColor uncertainty_color READ getUncertaintyColor WRITE setUncertaintyColor)

        public:
            MLSMapVisualization();
            ~MLSMapVisualization();

            Q_INVOKABLE void updateData(::maps::grid::MLSMap<::maps::grid::MLSConfig::PRECALCULATED> const &sample)
            {vizkit3d::Vizkit3DPlugin<::maps::grid::MLSMap<::maps::grid::MLSConfig::KALMAN>>::updateData(sample);}
            Q_INVOKABLE void updateData(::maps::grid::MLSMap<::maps::grid::MLSConfig::KALMAN> const &sample)
            {vizkit3d::Vizkit3DPlugin<::maps::grid::MLSMap<::maps::grid::MLSConfig::KALMAN>>::updateData(sample);}
            Q_INVOKABLE void updateData(::maps::grid::MLSMap<::maps::grid::MLSConfig::SLOPE> const &sample)
            {vizkit3d::Vizkit3DPlugin<::maps::grid::MLSMap<::maps::grid::MLSConfig::KALMAN>>::updateData(sample);}

        protected:
            virtual osg::ref_ptr<osg::Node> createMainNode();
            virtual void updateMainNode(osg::Node* node);
            virtual void updateDataIntern(::maps::grid::MLSMap<::maps::grid::MLSConfig::KALMAN> const& mls);
            virtual void updateDataIntern(::maps::grid::MLSMap<::maps::grid::MLSConfig::SLOPE> const& mls);
            virtual void updateDataIntern(::maps::grid::MLSMap<::maps::grid::MLSConfig::PRECALCULATED> const& mls);

        private:
            struct Data;
            boost::scoped_ptr<Data> p;

        public slots:

            bool isUncertaintyShown() const;
            void setShowUncertainty(bool enabled);

            bool isNegativeShown() const;
            void setShowNegative(bool enabled);

            bool areNormalsEstimated() const;
            void setEstimateNormals(bool enabled);

            bool areNormalsShown() const;
            void setShowNormals(bool enabled);

            bool isHeightColorCycled() const;
            void setCycleHeightColor(bool enabled);

            double getCycleColorInterval() const;
            void setCycleColorInterval(double interval);

            QColor getHorizontalCellColor() const;
            void setHorizontalCellColor(QColor color);

            QColor getVerticalCellColor() const;
            void setVerticalCellColor(QColor color);

            QColor getNegativeCellColor() const;
            void setNegativeCellColor(QColor color);

            QColor getUncertaintyColor() const;
            void setUncertaintyColor(QColor color);

            void setShowPatchExtents( bool value );
            bool arePatchExtentsShown() const;

            void setShowMapExtents(bool value);
            bool areMapExtentsShown() const;

        protected:
            osg::Vec4 horizontalCellColor;
            osg::Vec4 verticalCellColor;
            osg::Vec4 negativeCellColor;
            osg::Vec4 uncertaintyColor;

            bool showMapExtents;
            bool showUncertainty;
            bool showNegative;
            bool estimateNormals;
            bool showNormals;
            bool cycleHeightColor;
            double cycleColorInterval;
            bool showPatchExtents;

#if 0
            osg::Vec3 estimateNormal(
                const ::maps::MLSMap &grid,
                const ::maps::SurfacePatch &patch,
                const ::maps::Index &patch_idx) const;
#endif
    };
}
#endif
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of meegotouch-controlpanelapplets.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "themedialog.h"
#include "themebusinesslogic.h"
#include "themedescriptor.h"

#include <QGraphicsLinearLayout>
#include <QPixmap>

#include <MButton>
#include <MContainer>
#include <MImageWidget>
#include <MLayout>
#include <MLinearLayoutPolicy>

//#define DEBUG
#include "../debug.h"

/*
 * You might wonder why this dialog is damn complicated, why do we hide the
 * button box and create a custom one. The answer is simple: the original UI
 * spec was different, so we needed to create and handle our own buttons and
 * this is how that is done.
 *
 * if you think you can simplify the applet by modifying ths dialog, then by all
 * means, please do it!
 */
ThemeDialog::ThemeDialog (
        ThemeBusinessLogic *themeBusinessLogic,
        ThemeDescriptor    *themeDesc):
    MDialog (),
    m_ThemeBusinessLogic (themeBusinessLogic),
    m_ThemeDesc (themeDesc)
{
    MLayout               *buttonLayout;
    MLinearLayoutPolicy   *portraitButtonLayoutPolicy;
    MLinearLayoutPolicy   *landscapeButtonLayoutPolicy;

    MLayout               *mainLayout;
    MLinearLayoutPolicy   *portraitLayoutPolicy;
    MLinearLayoutPolicy   *landscapeLayoutPolicy;

    MContainer            *hbox;
    MImageWidget          *image1, *image2;
    QString                landscapePreviewFileName;
    QString                portraitPreviewFileName;
    QPixmap pixmap;

    portraitPreviewFileName = themeBusinessLogic->themePreviewFileName (
            themeDesc->codeName(), M::Portrait);

    landscapePreviewFileName = themeBusinessLogic->themePreviewFileName (
            themeDesc->codeName(), M::Landscape);

    mainLayout = new MLayout;
    portraitLayoutPolicy =
        new MLinearLayoutPolicy (mainLayout, Qt::Vertical);
    landscapeLayoutPolicy =
        new MLinearLayoutPolicy (mainLayout, Qt::Vertical);
    landscapeLayoutPolicy->setSpacing (10);
    portraitLayoutPolicy->setSpacing (10);

    buttonLayout = new MLayout;
    portraitButtonLayoutPolicy =
        new MLinearLayoutPolicy (buttonLayout, Qt::Vertical);
    landscapeButtonLayoutPolicy =
        new MLinearLayoutPolicy (buttonLayout, Qt::Horizontal);
    landscapeButtonLayoutPolicy->setSpacing (10);
    portraitButtonLayoutPolicy->setSpacing (10);

    // An image widget to show some preview screenshot.
    image1 = new MImageWidget (this);
    if (pixmap.load (portraitPreviewFileName)) {
        image1->setPixmap (pixmap);
    } else {
        SYS_WARNING ("Failed to load %s", SYS_STR(portraitPreviewFileName));
        image1->setImage (themeDesc->iconName());
    }

    portraitLayoutPolicy->addItem (image1);

    image2 = new MImageWidget (this);
    if (pixmap.load (landscapePreviewFileName)) {
        image2->setPixmap (pixmap);
    } else {
        SYS_WARNING ("Failed to load %s", SYS_STR(landscapePreviewFileName));
        image2->setImage (themeDesc->iconName());
    }

    landscapeLayoutPolicy->addItem (image2);

    //% "Select"
    m_SelectButton = new MButton (qtTrId ("qtn_teme_select"));
    connect (m_SelectButton, SIGNAL(clicked()),
            this, SLOT(acceptClicked()));

    //% "Cancel"
    m_CancelButton = new MButton (qtTrId ("qtn_comm_cancel"));
    connect (m_CancelButton, SIGNAL(clicked()),
            this, SLOT(cancelClicked()));
    connect (this, SIGNAL(rejected()),
            this, SLOT(cancelClicked()));

    portraitButtonLayoutPolicy->addItem (m_SelectButton);
    portraitButtonLayoutPolicy->addItem (m_CancelButton);

    landscapeButtonLayoutPolicy->addItem (m_SelectButton);
    landscapeButtonLayoutPolicy->addItem (m_CancelButton);

    buttonLayout->setLandscapePolicy (landscapeButtonLayoutPolicy);
    buttonLayout->setPortraitPolicy (portraitButtonLayoutPolicy);

    portraitLayoutPolicy->addItem (buttonLayout);
    landscapeLayoutPolicy->addItem (buttonLayout);

    mainLayout->setLandscapePolicy (landscapeLayoutPolicy);
    mainLayout->setPortraitPolicy (portraitLayoutPolicy);

    hbox = new MContainer (this);
    hbox->setHeaderVisible (false);
    hbox->setLayout (mainLayout);

    setCentralWidget (hbox);
    setButtonBoxVisible (false);

    setTitle (m_ThemeDesc->name());
}

void
ThemeDialog::showDialog()
{
    appear(MSceneWindow::DestroyWhenDone);
}

void
ThemeDialog::acceptClicked ()
{
    SYS_DEBUG ("");

    /*
     * We need to delay the actual theme changing until the dialog disappeared
     * since libMeegoTouch does not like the theme dialog disappearing while the
     * theme is changing.
     */
    connect (this, SIGNAL(disappeared()),
            this, SLOT(dialogDisappeared()));

    accept();
    disappear ();
}

void
ThemeDialog::cancelClicked ()
{
    SYS_DEBUG ("");
    emit themeChangeCancelled ();
    accept();
    disappear ();
}

void
ThemeDialog::dialogDisappeared ()
{
    m_ThemeBusinessLogic->changeTheme (m_ThemeDesc->codeName());
}

<commit_msg>ThemeApplet: fixes: improperly using MContainer<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of meegotouch-controlpanelapplets.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "themedialog.h"
#include "themebusinesslogic.h"
#include "themedescriptor.h"

#include <QGraphicsLinearLayout>
#include <QPixmap>

#include <MButton>
#include <MWidgetController>
#include <MImageWidget>
#include <MLayout>
#include <MLinearLayoutPolicy>

//#define DEBUG
#include "../debug.h"

/*
 * You might wonder why this dialog is damn complicated, why do we hide the
 * button box and create a custom one. The answer is simple: the original UI
 * spec was different, so we needed to create and handle our own buttons and
 * this is how that is done.
 *
 * if you think you can simplify the applet by modifying ths dialog, then by all
 * means, please do it!
 */
ThemeDialog::ThemeDialog (
        ThemeBusinessLogic *themeBusinessLogic,
        ThemeDescriptor    *themeDesc):
    MDialog (),
    m_ThemeBusinessLogic (themeBusinessLogic),
    m_ThemeDesc (themeDesc)
{
    MLayout               *buttonLayout;
    MLinearLayoutPolicy   *portraitButtonLayoutPolicy;
    MLinearLayoutPolicy   *landscapeButtonLayoutPolicy;

    MLayout               *mainLayout;
    MLinearLayoutPolicy   *portraitLayoutPolicy;
    MLinearLayoutPolicy   *landscapeLayoutPolicy;

    MWidgetController     *hbox;
    MImageWidget          *image1, *image2;
    QString                landscapePreviewFileName;
    QString                portraitPreviewFileName;
    QPixmap pixmap;

    portraitPreviewFileName = themeBusinessLogic->themePreviewFileName (
            themeDesc->codeName(), M::Portrait);

    landscapePreviewFileName = themeBusinessLogic->themePreviewFileName (
            themeDesc->codeName(), M::Landscape);

    mainLayout = new MLayout;
    portraitLayoutPolicy =
        new MLinearLayoutPolicy (mainLayout, Qt::Vertical);
    landscapeLayoutPolicy =
        new MLinearLayoutPolicy (mainLayout, Qt::Vertical);
    landscapeLayoutPolicy->setSpacing (10);
    portraitLayoutPolicy->setSpacing (10);

    buttonLayout = new MLayout;
    portraitButtonLayoutPolicy =
        new MLinearLayoutPolicy (buttonLayout, Qt::Vertical);
    landscapeButtonLayoutPolicy =
        new MLinearLayoutPolicy (buttonLayout, Qt::Horizontal);
    landscapeButtonLayoutPolicy->setSpacing (10);
    portraitButtonLayoutPolicy->setSpacing (10);

    // An image widget to show some preview screenshot.
    image1 = new MImageWidget (this);
    if (pixmap.load (portraitPreviewFileName)) {
        image1->setPixmap (pixmap);
    } else {
        SYS_WARNING ("Failed to load %s", SYS_STR(portraitPreviewFileName));
        image1->setImage (themeDesc->iconName());
    }

    portraitLayoutPolicy->addItem (image1);

    image2 = new MImageWidget (this);
    if (pixmap.load (landscapePreviewFileName)) {
        image2->setPixmap (pixmap);
    } else {
        SYS_WARNING ("Failed to load %s", SYS_STR(landscapePreviewFileName));
        image2->setImage (themeDesc->iconName());
    }

    landscapeLayoutPolicy->addItem (image2);

    //% "Select"
    m_SelectButton = new MButton (qtTrId ("qtn_teme_select"));
    connect (m_SelectButton, SIGNAL(clicked()),
            this, SLOT(acceptClicked()));

    //% "Cancel"
    m_CancelButton = new MButton (qtTrId ("qtn_comm_cancel"));
    connect (m_CancelButton, SIGNAL(clicked()),
            this, SLOT(cancelClicked()));
    connect (this, SIGNAL(rejected()),
            this, SLOT(cancelClicked()));

    portraitButtonLayoutPolicy->addItem (m_SelectButton);
    portraitButtonLayoutPolicy->addItem (m_CancelButton);

    landscapeButtonLayoutPolicy->addItem (m_SelectButton);
    landscapeButtonLayoutPolicy->addItem (m_CancelButton);

    buttonLayout->setLandscapePolicy (landscapeButtonLayoutPolicy);
    buttonLayout->setPortraitPolicy (portraitButtonLayoutPolicy);

    portraitLayoutPolicy->addItem (buttonLayout);
    landscapeLayoutPolicy->addItem (buttonLayout);

    mainLayout->setLandscapePolicy (landscapeLayoutPolicy);
    mainLayout->setPortraitPolicy (portraitLayoutPolicy);

    hbox = new MWidgetController (this);
    hbox->setLayout (mainLayout);

    setCentralWidget (hbox);
    setButtonBoxVisible (false);

    setTitle (m_ThemeDesc->name());
}

void
ThemeDialog::showDialog()
{
    appear(MSceneWindow::DestroyWhenDone);
}

void
ThemeDialog::acceptClicked ()
{
    SYS_DEBUG ("");

    /*
     * We need to delay the actual theme changing until the dialog disappeared
     * since libMeegoTouch does not like the theme dialog disappearing while the
     * theme is changing.
     */
    connect (this, SIGNAL(disappeared()),
            this, SLOT(dialogDisappeared()));

    accept();
    disappear ();
}

void
ThemeDialog::cancelClicked ()
{
    SYS_DEBUG ("");
    emit themeChangeCancelled ();
    accept();
    disappear ();
}

void
ThemeDialog::dialogDisappeared ()
{
    m_ThemeBusinessLogic->changeTheme (m_ThemeDesc->codeName());
}

<|endoftext|>


<commit_before>#include "data-student.hpp"
using namespace std;

void Student::init(string n, int s, int g, string m) {
	name = n;
	startingYear = s;
	gradutationYear = g;
	addMajors(m);
}

Student::Student() {
	init("", 2000, 2004, "");
}
Student::Student(string n, string s, string e, string m) {
	int startYear = stringToInt(s), endYear = stringToInt(e);
	init(n, startYear, endYear, m);
}

Student::Student(string fn) {
	string yearS, yearE;
	ifstream infile(fn.c_str());
	string nextLine;
	vector<string> lines;

	// load the entire file
	while (infile.peek() != -1) {
		getline(infile, nextLine);
		lines.push_back(nextLine);
	}

	string previousHeading;
	for (vector<string>::iterator i = lines.begin(); i != lines.end(); ++i) {
		string str = *i;
		if (str[0] == '#') {
			previousHeading = *i;
			continue;
		}
		else if (str != "") {
			if (str.substr(0, 2) == "//")
				// it's a comment
			else if (previousHeading == "# NAME")
				name = str;
			else if (previousHeading == "# MAJORS")
				addMajor(Major(str));
			else if (previousHeading == "# CONCENTRATIONS")
				addConcentration(Concentration(str));
			else if (previousHeading == "# COURSES")
				addCourse(Course(str));
			else if (previousHeading == "# LABS")
				addCourse(Course(str));
		}
	}
}

void Student::addMajor(const Major& m) {
	majors.push_back(m);
}

void Student::addMajors(string str) {
	vector<string> record = split(str, ',');
	for (vector<string>::iterator i = record.begin(); i != record.end(); ++i)
		addMajor(Major(*i));
}

void Student::addConcentration(const Concentration& m) {
	concentrations.push_back(m);
}

void Student::addConcentrations(string str) {
	vector<string> record = split(str, ',');
	for (vector<string>::iterator i = record.begin(); i != record.end(); ++i)
		addConcentration(Concentration(*i));
}

void Student::addCourse(const Course& c) {
	courses.push_back(c);
}

void Student::addCourses(string str) {
	vector<string> record = split(str, ',');
	for (vector<string>::iterator i = record.begin(); i != record.end(); ++i)
		addCourse(Course(*i));
}

bool Student::hasTakenCourse(string str) {
	bool userHasTaken = false;
	Course checkAgainst = getCourse(str);
	for (std::vector<Course>::iterator i = courses.begin(); i != courses.end(); ++i)
		if (*i == checkAgainst)
			userHasTaken = true;
	return userHasTaken;
}

ostream& Student::getData(ostream &os) {
	os << name << ", ";

	if (majors.size()) {
		os << "you are majoring in ";

		for (vector<Major>::iterator i = majors.begin(); i != majors.end(); ++i){
			if (majors.size() == 1) {
				os << *i << " ";
			}
			else if (majors.size() == 2) {
				os << *i;
				if (i != majors.end()-1)
					os << " and ";
				else
					os << " ";
			}
			else {
				if (i != majors.end()-1)
					os << *i << ", ";
				else
					os << "and " << *i << ", ";
			}
		}
	}

	if (concentrations.size()) {
		os << "with concentrations in ";

		for (vector<Concentration>::iterator i = concentrations.begin(); i != concentrations.end(); ++i) {
			if (concentrations.size() == 1) {
				os << *i << " ";
			}
			if (concentrations.size() == 2) {
				os << *i;
				if (i != concentrations.end()-1)
					os << " and ";
				else
					os << " ";
			}
			else {
				if (i != concentrations.end()-1)
					os << *i << ", ";
				else
					os << "and " << *i << ", ";
			}
		}
	}

	if (!majors.size())
		os << "you are taking: " << endl;
	else
		os << "while taking:" << endl;

	for (vector<Course>::iterator i = courses.begin(); i != courses.end(); ++i)
		os << *i << endl;

	return os;
}

void Student::display() {
	cout << *this << endl;
};

ostream& operator<<(ostream& os, Student& item) {
	return item.getData(os);
}
<commit_msg>Make the heading finder more robust<commit_after>#include "data-student.hpp"
using namespace std;

void Student::init(string n, int s, int g, string m) {
	name = n;
	startingYear = s;
	gradutationYear = g;
	addMajors(m);
}

Student::Student() {
	init("", 2000, 2004, "");
}
Student::Student(string n, string s, string e, string m) {
	int startYear = stringToInt(s), endYear = stringToInt(e);
	init(n, startYear, endYear, m);
}

Student::Student(string fn) {
	string yearS, yearE;
	ifstream infile(fn.c_str());
	string nextLine;
	vector<string> lines;

	// load the entire file
	while (infile.peek() != -1) {
		getline(infile, nextLine);
		lines.push_back(nextLine);
	}

	string previousHeading;
	for (vector<string>::iterator i = lines.begin(); i != lines.end(); ++i) {
		string str = *i;
		if (previousHeading.empty())
			previousHeading = "# NAME";
		if (str[0] == '#') {
			previousHeading = *i;
			continue;
		}
		else if (str != "") {
			if (str.substr(0, 2) == "//")
				// it's a comment
			else if (previousHeading == "# NAME")
				name = str;
			else if (previousHeading == "# MAJORS")
				addMajor(Major(str));
			else if (previousHeading == "# CONCENTRATIONS")
				addConcentration(Concentration(str));
			else if (previousHeading == "# COURSES")
				addCourse(Course(str));
			else if (previousHeading == "# LABS")
				addCourse(Course(str));
		}
	}
}

void Student::addMajor(const Major& m) {
	majors.push_back(m);
}

void Student::addMajors(string str) {
	vector<string> record = split(str, ',');
	for (vector<string>::iterator i = record.begin(); i != record.end(); ++i)
		addMajor(Major(*i));
}

void Student::addConcentration(const Concentration& m) {
	concentrations.push_back(m);
}

void Student::addConcentrations(string str) {
	vector<string> record = split(str, ',');
	for (vector<string>::iterator i = record.begin(); i != record.end(); ++i)
		addConcentration(Concentration(*i));
}

void Student::addCourse(const Course& c) {
	courses.push_back(c);
}

void Student::addCourses(string str) {
	vector<string> record = split(str, ',');
	for (vector<string>::iterator i = record.begin(); i != record.end(); ++i)
		addCourse(Course(*i));
}

bool Student::hasTakenCourse(string str) {
	bool userHasTaken = false;
	Course checkAgainst = getCourse(str);
	for (std::vector<Course>::iterator i = courses.begin(); i != courses.end(); ++i)
		if (*i == checkAgainst)
			userHasTaken = true;
	return userHasTaken;
}

ostream& Student::getData(ostream &os) {
	os << name << ", ";

	if (majors.size()) {
		os << "you are majoring in ";

		for (vector<Major>::iterator i = majors.begin(); i != majors.end(); ++i){
			if (majors.size() == 1) {
				os << *i << " ";
			}
			else if (majors.size() == 2) {
				os << *i;
				if (i != majors.end()-1)
					os << " and ";
				else
					os << " ";
			}
			else {
				if (i != majors.end()-1)
					os << *i << ", ";
				else
					os << "and " << *i << ", ";
			}
		}
	}

	if (concentrations.size()) {
		os << "with concentrations in ";

		for (vector<Concentration>::iterator i = concentrations.begin(); i != concentrations.end(); ++i) {
			if (concentrations.size() == 1) {
				os << *i << " ";
			}
			if (concentrations.size() == 2) {
				os << *i;
				if (i != concentrations.end()-1)
					os << " and ";
				else
					os << " ";
			}
			else {
				if (i != concentrations.end()-1)
					os << *i << ", ";
				else
					os << "and " << *i << ", ";
			}
		}
	}

	if (!majors.size())
		os << "you are taking: " << endl;
	else
		os << "while taking:" << endl;

	for (vector<Course>::iterator i = courses.begin(); i != courses.end(); ++i)
		os << *i << endl;

	return os;
}

void Student::display() {
	cout << *this << endl;
};

ostream& operator<<(ostream& os, Student& item) {
	return item.getData(os);
}
<|endoftext|>


<commit_before>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile: mitkPropertyManager.cpp,v $
Language:  C++
Date:      $Date$
Version:   $Revision: 1.12 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

/*
 This test is meant to reproduce the following error:

 - The machine or current user has a German locale.
 - This esp. means that stream IO expects the decimal separator as a comma: ","
 - DICOM files use a point "." as the decimal separator to be locale independent
 - The parser used by MITK (ITK's GDCM) seems to use the current locale instead of the "C" or "POSIX" locale
 - This leads to spacings (and probably other numbers) being trimmed/rounded,
   e.g. the correct spacing of 0.314 is read as 1.0 etc.

 MITK shold work around this behavior. This test is meant to verify any workaround
 and will be activated once such a workaround is available.

*/

#include "mitkDataTreeNodeFactory.h"
#include "mitkStandardFileLocations.h"

#include "mitkTestingMacros.h"

#include <locale>
#include <locale.h>

bool mitkDICOMLocaleTestChangeLocale(const std::string& locale)
{
  try
  {
    MITK_TEST_OUTPUT(<< " ** Changing locale to '" << locale << "'");
    setlocale(LC_ALL, locale.c_str());
    std::locale l( locale.c_str() );
    std::cin.imbue(l);
    return true;
  }
  catch(...)
  {
    MITK_TEST_OUTPUT(<< "Could not activate locale " << locale);
    return false;
  }

}

void mitkDICOMLocaleTestWithReferenceImage()
{
  mitk::StandardFileLocations::Pointer locator = mitk::StandardFileLocations::GetInstance();
  MITK_TEST_CONDITION_REQUIRED(locator.IsNotNull(),"Instantiating StandardFileLocations");
  std::string filename = locator->FindFile("spacing-ok.dcm", "Core/Code/Testing/Data/");

  mitk::Image::Pointer image;
  mitk::DataTreeNodeFactory::Pointer factory = mitk::DataTreeNodeFactory::New();
  factory->SetFileName( filename );
  factory->Update();
  MITK_TEST_CONDITION_REQUIRED(factory->GetNumberOfOutputs() > 0, "file loaded");

  mitk::DataTreeNode::Pointer node = factory->GetOutput( 0 );
  image = dynamic_cast<mitk::Image*>(node->GetData());
  if(image.IsNull())
  {
    MITK_TEST_FAILED_MSG(<< "File "<< filename << " is not an image - test will not be applied." );

    return;
  }

  MITK_TEST_OUTPUT(<< "File "<< filename << " could be loaded." );

  MITK_TEST_OUTPUT(<< "MITK image reports pixel spacing of " << image->GetGeometry()->GetSpacing()[0] << " " << image->GetGeometry()->GetSpacing()[1] );
  MITK_TEST_CONDITION_REQUIRED(image->GetGeometry()->GetSpacing()[0] - 0.3141592 < 0.0000001, "correct x spacing");
  MITK_TEST_CONDITION_REQUIRED(image->GetGeometry()->GetSpacing()[1] - 0.3141592 < 0.0000001, "correct y spacing");
}

int mitkDICOMLocaleTest(int /*argc*/, char* /*argv*/ [])
{
  MITK_TEST_BEGIN("DICOMLocaleTest");

  // load a reference DICOM file with the "C" locale being set
  mitkDICOMLocaleTestChangeLocale("C");
  mitkDICOMLocaleTestWithReferenceImage();
  // load a reference DICOM file with German locales being set
  unsigned int numberOfTestedGermanLocales(0);
  if ( mitkDICOMLocaleTestChangeLocale("de_DE") )
  {
    ++numberOfTestedGermanLocales;
    mitkDICOMLocaleTestWithReferenceImage();
  }
  if ( mitkDICOMLocaleTestChangeLocale("de_DE.utf8") )
  {
    ++numberOfTestedGermanLocales;
    mitkDICOMLocaleTestWithReferenceImage();
  }

  MITK_TEST_CONDITION_REQUIRED( numberOfTestedGermanLocales > 0, "Verify that at least one German locale has been tested.");

  MITK_TEST_END();
}

<commit_msg>COMP (#2473): add more locales and output initial locale<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile: mitkPropertyManager.cpp,v $
Language:  C++
Date:      $Date$
Version:   $Revision: 1.12 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

/*
 This test is meant to reproduce the following error:

 - The machine or current user has a German locale.
 - This esp. means that stream IO expects the decimal separator as a comma: ","
 - DICOM files use a point "." as the decimal separator to be locale independent
 - The parser used by MITK (ITK's GDCM) seems to use the current locale instead of the "C" or "POSIX" locale
 - This leads to spacings (and probably other numbers) being trimmed/rounded,
   e.g. the correct spacing of 0.314 is read as 1.0 etc.

 MITK shold work around this behavior. This test is meant to verify any workaround
 and will be activated once such a workaround is available.

*/

#include "mitkDataTreeNodeFactory.h"
#include "mitkStandardFileLocations.h"

#include "mitkTestingMacros.h"

#include <list>
#include <locale>
#include <locale.h>

bool mitkDICOMLocaleTestChangeLocale(const std::string& locale)
{
  try
  {
    MITK_TEST_OUTPUT(<< " ** Changing locale from " << setlocale(LC_ALL, NULL) << " to '" << locale << "'");
    setlocale(LC_ALL, locale.c_str());
    std::locale l( locale.c_str() );
    std::cin.imbue(l);
    return true;
  }
  catch(...)
  {
    MITK_TEST_OUTPUT(<< "Could not activate locale " << locale);
    return false;
  }

}

void mitkDICOMLocaleTestWithReferenceImage()
{
  mitk::StandardFileLocations::Pointer locator = mitk::StandardFileLocations::GetInstance();
  MITK_TEST_CONDITION_REQUIRED(locator.IsNotNull(),"Instantiating StandardFileLocations");
  std::string filename = locator->FindFile("spacing-ok.dcm", "Core/Code/Testing/Data/");

  mitk::Image::Pointer image;
  mitk::DataTreeNodeFactory::Pointer factory = mitk::DataTreeNodeFactory::New();
  factory->SetFileName( filename );
  factory->Update();
  MITK_TEST_CONDITION_REQUIRED(factory->GetNumberOfOutputs() > 0, "file loaded");

  mitk::DataTreeNode::Pointer node = factory->GetOutput( 0 );
  image = dynamic_cast<mitk::Image*>(node->GetData());
  if(image.IsNull())
  {
    MITK_TEST_FAILED_MSG(<< "File "<< filename << " is not an image - test will not be applied." );

    return;
  }

  MITK_TEST_OUTPUT(<< "File "<< filename << " could be loaded." );

  MITK_TEST_OUTPUT(<< "MITK image reports pixel spacing of " << image->GetGeometry()->GetSpacing()[0] << " " << image->GetGeometry()->GetSpacing()[1] );
  MITK_TEST_CONDITION_REQUIRED(image->GetGeometry()->GetSpacing()[0] - 0.3141592 < 0.0000001, "correct x spacing");
  MITK_TEST_CONDITION_REQUIRED(image->GetGeometry()->GetSpacing()[1] - 0.3141592 < 0.0000001, "correct y spacing");
}

int mitkDICOMLocaleTest(int /*argc*/, char* /*argv*/ [])
{
  MITK_TEST_BEGIN("DICOMLocaleTest");

  // load a reference DICOM file with the "C" locale being set
  mitkDICOMLocaleTestChangeLocale("C");
  mitkDICOMLocaleTestWithReferenceImage();
  // load a reference DICOM file with German locales being set
  typedef std::list<std::string> StringList;
  StringList alllocales;
  alllocales.push_back("de_DE");
  alllocales.push_back("de_DE.utf8");
  alllocales.push_back("de_DE@euro");

  unsigned int numberOfTestedGermanLocales(0);

  for (StringList::iterator iter = alllocales.begin();
       iter != alllocales.end();
       ++iter)
  {
    if ( mitkDICOMLocaleTestChangeLocale(*iter) )
    {
      ++numberOfTestedGermanLocales;
      mitkDICOMLocaleTestWithReferenceImage();
    }
  }

  MITK_TEST_CONDITION_REQUIRED( numberOfTestedGermanLocales > 0, "Verify that at least one German locale has been tested.");

  MITK_TEST_END();
}

<|endoftext|>


<commit_before>/*
 * Unit tests for the TTSampleMatrix Object for Jamoma DSP
 * Copyright © 2012, Tim Place & Nathan Wolek
 *
 * License: This code is licensed under the terms of the "New BSD License"
 * http://creativecommons.org/licenses/BSD/
 */

#include "TTSampleMatrix.h"

TTErr TTSampleMatrix::test(TTValue& returnedTestInfo)
{
	int					errorCount = 0;
	int					testAssertionCount = 0;

	// for tests
	TTInt16				numChannels = 2;
	TTInt32				numSamples = 50000;
	TTFloat32			duration = 1500;
	TTInt32				test9Index = 10;
	TTInt32				test10Index = 11;
	TTInt32				test1Return, test2Return, test7Return, test8Return;
	TTFloat32			test3Return, test6Return;
	TTSampleValue		test9Return, test10Return, test11Return, test12return;

	TTTestLog("Test resizing of the SampleMatrix...");

	// TEST 1: can we set the number of channels?
	this->setAttributeValue("numChannels", numChannels);

	this->getAttributeValue("numChannels", test1Return);

	TTBoolean result = { numChannels == test1Return };

	TTTestAssertion("numChannels is set properly",
					result,
					testAssertionCount,
					errorCount);

	if(!result)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", numChannels, test1Return);
	}

	// TEST 2: can we set the number of samples?
	this->setAttributeValue(TT("lengthInSamples"), numSamples);

	this->getAttributeValue(TT("lengthInSamples"), test2Return);

	TTBoolean result2 = { numSamples == test2Return };

	TTTestAssertion("lengthInSamples is set properly",
								result2,
								testAssertionCount,
								errorCount);
	if(!result2)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", numSamples, test2Return);
	}

	// TEST 3: is the length in ms computed properly after setting length in samples?
	TTFloat32 computedDuration3 = (numSamples / this->mSampleRate) * 1000.;

	this->getAttributeValue(TT("length"), test3Return);

	TTBoolean result3 = TTTestFloatEquivalence(computedDuration3, test3Return);

	TTTestAssertion("after lengthInSamples is set, length (in ms) is correct",
								result3,
								testAssertionCount,
								errorCount);

	if(!result3)
	{
		TTTestLog("Expected a value of %f, but returned value was %f", computedDuration3, test3Return);
	}

	// TEST 4: is the matrix of samples the expected size? (lifted from TTMatrix.test.cpp)
	TTUInt32 computedDataSize4 = sizeof(TTFloat64) * numChannels * numSamples;

	TTBoolean result4 = { computedDataSize4 == this->mDataSize };

	TTTestAssertion("correct amount of data storage calculated",
								result4,
								testAssertionCount,
								errorCount);

	if(!result4)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", computedDataSize4, this->mDataSize);
	}

	// TEST 5: Is the component stride right? (lifted from TTMatrix.test.cpp)
	TTBoolean result5 = { sizeof(TTFloat64) == this->mComponentStride };

	TTTestAssertion("correct byte-stride between values calculated",
								result5,
								testAssertionCount,
								errorCount);

	if(!result5)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", sizeof(TTFloat64), this->mComponentStride);
	}

	// TEST 6: can we set the length in milliseconds?
	this->setAttributeValue(TT("length"), duration);

	this->getAttributeValue(TT("length"), test6Return);

	TTBoolean result6 = TTTestFloatEquivalence(duration, test6Return);

	TTTestAssertion("length (in ms) is set properly",
								result6,
								testAssertionCount,
								errorCount);

	if(!result6)
	{
		TTTestLog("Expected a value of %f, but returned value was %f", duration, test6Return);
	}

	// TEST 7: is the length in samples computed properly after setting length in ms?
	TTUInt32 computedSamples7 = TTUInt32(duration * this->mSampleRate * 0.001);

	this->getAttributeValue(TT("lengthInSamples"), test7Return);

	TTBoolean result7 = { computedSamples7 == test7Return };

	TTTestAssertion("after length (in ms) is set, lengthInSamples is correct",
								result7,
								testAssertionCount,
								errorCount);

	if(!result7)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", computedSamples7, test7Return);
	}

	// TEST 8 (REPEAT TEST 4 WITH NEW SIZE): is the matrix of samples the expected size?
	TTUInt32 computedDataSize8 = sizeof(TTFloat64) * numChannels * test7Return;

	TTBoolean result8 = { computedDataSize8 == this->mDataSize };

	TTTestAssertion("correct amount of data storage calculated with new length",
								result8,
								testAssertionCount,
								errorCount);

	if(!result8)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", computedDataSize8, this->mDataSize);
	}

	// TEST 9 & 10: set the value of two consecutive samples
	TTSampleValue pokeValue9 = TTRandom64();
	TTSampleValue pokeValue10 = TTRandom64();

	this->poke(test9Index, 1, pokeValue9);
	this->poke(test10Index, 1, pokeValue10);

	this->peek(test9Index, 1, test9Return);
	this->peek(test10Index, 1, test10Return);

	TTBoolean result9 = { pokeValue9 == test9Return };

	TTTestAssertion("set value one of two consecutive samples",
								result9,
								testAssertionCount,
								errorCount);

	if(!result9)
	{
		TTTestLog("Expected a value of %f, but returned value was %f", pokeValue9, test9Return);
	}

	TTBoolean result10 = { pokeValue10 == test10Return };

	TTTestAssertion("set value two of two consecutive samples",
								result10,
								testAssertionCount,
								errorCount);

	if(!result10)
	{
		TTTestLog("Expected a value of %f, but returned value was %f", pokeValue10, test10Return);
	}

	// TEST 11: test for interpolation between two consecutive samples
	TTFloat64 computedInterpFraction = TTRandom64();
	TTFloat64 computedInterpIndex = test9Index + computedInterpFraction;
	TTSampleValue computedInterpValue11 = (computedInterpFraction * pokeValue9) + ((1.0 - computedInterpFraction) * pokeValue10);

	this->peeki(computedInterpIndex, 1, test11Return);

	TTBoolean result11 = TTTestFloatEquivalence(computedInterpValue11, test11Return);

	TTTestAssertion("interpolate between two consecutive samples",
								result11,
								testAssertionCount,
								errorCount);

	if(!result11)
	{
		TTTestLog("Expected a value of %f, but returned value was %f", computedInterpValue11, test11Return);
	}

	/*
	// TODO: inbounds testing on hold until sorted out at TTMatrix parent class

	// TEST 12: test the new inBounds method

	TTUInt32 computedSampleAfterTail12 = -10; //test7Return + 5;
	TTErr test12Err = this->peek(computedSampleAfterTail12, 1, test12return);

	TTTestAssertion("retrieving sample out of bounds produces an error",
								test12Err == kTTErrInvalidValue,
								testAssertionCount,
								errorCount);

	if(test12Err != kTTErrInvalidValue)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", kTTErrInvalidValue, test12Err);
	}

	TTUInt32 computedDistanceFromHead12 = test7Return * test1Return

	computedDistanceFromHead12 -= 50; // 50 before tail
	TTBoolean result12 = this->inBounds(computedDistanceFromHead12);

	if(result12)
	{
		TTTestLog("Testing in bounds 12 returned true, %i", computedDistanceFromHead12);
	}

	computedDistanceFromHead12 += 50; // at tail
	TTBoolean result13 = this->inBounds(computedDistanceFromHead12);

	if(result13)
	{
		TTTestLog("Testing in bounds 13 returned true, %i", computedDistanceFromHead12);
	}

	computedDistanceFromHead12 += 1; // 1 after tail
	TTBoolean result14 = this->inBounds(computedDistanceFromHead12);

	if(!result14)
	{
		TTTestLog("Testing in bounds 14 returned false, %i", computedDistanceFromHead12);
	}

	TTBoolean result15 = this->inBounds(-1);

	if(!result15)
	{
		TTTestLog("Negative values return false: %i", -1);
	}

	TTBoolean result16 = this->inBounds(0);

	if(!result16)
	{
		TTTestLog("Zero returns false: %i", 0);
	}
	*/

	/*

	int					badSampleCount = 0;
	TTAudioObjectPtr	samplematrixObject = NULL;
	TTAudioSignalPtr	input = NULL;
	TTAudioSignalPtr	output = NULL;

	// TODO: test filling with sine wave
	// TODO: test scaling (applying gain)
	// TODO: test normalizing (with optional arg, and also without an optional arg)

	TTObjectInstantiate(TT("samplematrix"), &samplematrixObject, kTTVal1);

	TTObjectRelease(&input);
	TTObjectRelease(&output);
	TTObjectRelease(&samplematrixObject);

	*/

	// Wrap up the test results to pass back to whoever called this test
	return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo);
}

<commit_msg>SampleMatrix:test() removed TT macro calls<commit_after>/*
 * Unit tests for the TTSampleMatrix Object for Jamoma DSP
 * Copyright © 2012, Tim Place & Nathan Wolek
 *
 * License: This code is licensed under the terms of the "New BSD License"
 * http://creativecommons.org/licenses/BSD/
 */

#include "TTSampleMatrix.h"

TTErr TTSampleMatrix::test(TTValue& returnedTestInfo)
{
	int					errorCount = 0;
	int					testAssertionCount = 0;

	// for tests
	TTInt16				numChannels = 2;
	TTInt32				numSamples = 50000;
	TTFloat32			duration = 1500;
	TTInt32				test9Index = 10;
	TTInt32				test10Index = 11;
	TTInt32				test1Return, test2Return, test7Return, test8Return;
	TTFloat32			test3Return, test6Return;
	TTSampleValue		test9Return, test10Return, test11Return, test12return;

	TTTestLog("Test resizing of the SampleMatrix...");

	// TEST 1: can we set the number of channels?
	this->setAttributeValue("numChannels", numChannels);

	this->getAttributeValue("numChannels", test1Return);

	TTBoolean result = { numChannels == test1Return };

	TTTestAssertion("numChannels is set properly",
					result,
					testAssertionCount,
					errorCount);

	if(!result)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", numChannels, test1Return);
	}

	// TEST 2: can we set the number of samples?
	this->setAttributeValue("lengthInSamples", numSamples);

	this->getAttributeValue("lengthInSamples", test2Return);

	TTBoolean result2 = { numSamples == test2Return };

	TTTestAssertion("lengthInSamples is set properly",
								result2,
								testAssertionCount,
								errorCount);
	if(!result2)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", numSamples, test2Return);
	}

	// TEST 3: is the length in ms computed properly after setting length in samples?
	TTFloat32 computedDuration3 = (numSamples / this->mSampleRate) * 1000.;

	this->getAttributeValue("length", test3Return);

	TTBoolean result3 = TTTestFloatEquivalence(computedDuration3, test3Return);

	TTTestAssertion("after lengthInSamples is set, length (in ms) is correct",
								result3,
								testAssertionCount,
								errorCount);

	if(!result3)
	{
		TTTestLog("Expected a value of %f, but returned value was %f", computedDuration3, test3Return);
	}

	// TEST 4: is the matrix of samples the expected size? (lifted from TTMatrix.test.cpp)
	TTUInt32 computedDataSize4 = sizeof(TTFloat64) * numChannels * numSamples;

	TTBoolean result4 = { computedDataSize4 == this->mDataSize };

	TTTestAssertion("correct amount of data storage calculated",
								result4,
								testAssertionCount,
								errorCount);

	if(!result4)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", computedDataSize4, this->mDataSize);
	}

	// TEST 5: Is the component stride right? (lifted from TTMatrix.test.cpp)
	TTBoolean result5 = { sizeof(TTFloat64) == this->mComponentStride };

	TTTestAssertion("correct byte-stride between values calculated",
								result5,
								testAssertionCount,
								errorCount);

	if(!result5)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", sizeof(TTFloat64), this->mComponentStride);
	}

	// TEST 6: can we set the length in milliseconds?
	this->setAttributeValue("length", duration);

	this->getAttributeValue("length", test6Return);

	TTBoolean result6 = TTTestFloatEquivalence(duration, test6Return);

	TTTestAssertion("length (in ms) is set properly",
								result6,
								testAssertionCount,
								errorCount);

	if(!result6)
	{
		TTTestLog("Expected a value of %f, but returned value was %f", duration, test6Return);
	}

	// TEST 7: is the length in samples computed properly after setting length in ms?
	TTUInt32 computedSamples7 = TTUInt32(duration * this->mSampleRate * 0.001);

	this->getAttributeValue("lengthInSamples", test7Return);

	TTBoolean result7 = { computedSamples7 == test7Return };

	TTTestAssertion("after length (in ms) is set, lengthInSamples is correct",
								result7,
								testAssertionCount,
								errorCount);

	if(!result7)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", computedSamples7, test7Return);
	}

	// TEST 8 (REPEAT TEST 4 WITH NEW SIZE): is the matrix of samples the expected size?
	TTUInt32 computedDataSize8 = sizeof(TTFloat64) * numChannels * test7Return;

	TTBoolean result8 = { computedDataSize8 == this->mDataSize };

	TTTestAssertion("correct amount of data storage calculated with new length",
								result8,
								testAssertionCount,
								errorCount);

	if(!result8)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", computedDataSize8, this->mDataSize);
	}

	// TEST 9 & 10: set the value of two consecutive samples
	TTSampleValue pokeValue9 = TTRandom64();
	TTSampleValue pokeValue10 = TTRandom64();

	this->poke(test9Index, 1, pokeValue9);
	this->poke(test10Index, 1, pokeValue10);

	this->peek(test9Index, 1, test9Return);
	this->peek(test10Index, 1, test10Return);

	TTBoolean result9 = { pokeValue9 == test9Return };

	TTTestAssertion("set value one of two consecutive samples",
								result9,
								testAssertionCount,
								errorCount);

	if(!result9)
	{
		TTTestLog("Expected a value of %f, but returned value was %f", pokeValue9, test9Return);
	}

	TTBoolean result10 = { pokeValue10 == test10Return };

	TTTestAssertion("set value two of two consecutive samples",
								result10,
								testAssertionCount,
								errorCount);

	if(!result10)
	{
		TTTestLog("Expected a value of %f, but returned value was %f", pokeValue10, test10Return);
	}

	// TEST 11: test for interpolation between two consecutive samples
	TTFloat64 computedInterpFraction = TTRandom64();
	TTFloat64 computedInterpIndex = test9Index + computedInterpFraction;
	TTSampleValue computedInterpValue11 = (computedInterpFraction * pokeValue9) + ((1.0 - computedInterpFraction) * pokeValue10);

	this->peeki(computedInterpIndex, 1, test11Return);

	TTBoolean result11 = TTTestFloatEquivalence(computedInterpValue11, test11Return);

	TTTestAssertion("interpolate between two consecutive samples",
								result11,
								testAssertionCount,
								errorCount);

	if(!result11)
	{
		TTTestLog("Expected a value of %f, but returned value was %f", computedInterpValue11, test11Return);
	}

	/*
	// TODO: inbounds testing on hold until sorted out at TTMatrix parent class

	// TEST 12: test the new inBounds method

	TTUInt32 computedSampleAfterTail12 = -10; //test7Return + 5;
	TTErr test12Err = this->peek(computedSampleAfterTail12, 1, test12return);

	TTTestAssertion("retrieving sample out of bounds produces an error",
								test12Err == kTTErrInvalidValue,
								testAssertionCount,
								errorCount);

	if(test12Err != kTTErrInvalidValue)
	{
		TTTestLog("Expected a value of %i, but returned value was %i", kTTErrInvalidValue, test12Err);
	}

	TTUInt32 computedDistanceFromHead12 = test7Return * test1Return

	computedDistanceFromHead12 -= 50; // 50 before tail
	TTBoolean result12 = this->inBounds(computedDistanceFromHead12);

	if(result12)
	{
		TTTestLog("Testing in bounds 12 returned true, %i", computedDistanceFromHead12);
	}

	computedDistanceFromHead12 += 50; // at tail
	TTBoolean result13 = this->inBounds(computedDistanceFromHead12);

	if(result13)
	{
		TTTestLog("Testing in bounds 13 returned true, %i", computedDistanceFromHead12);
	}

	computedDistanceFromHead12 += 1; // 1 after tail
	TTBoolean result14 = this->inBounds(computedDistanceFromHead12);

	if(!result14)
	{
		TTTestLog("Testing in bounds 14 returned false, %i", computedDistanceFromHead12);
	}

	TTBoolean result15 = this->inBounds(-1);

	if(!result15)
	{
		TTTestLog("Negative values return false: %i", -1);
	}

	TTBoolean result16 = this->inBounds(0);

	if(!result16)
	{
		TTTestLog("Zero returns false: %i", 0);
	}
	*/

	/*

	int					badSampleCount = 0;
	TTAudioObjectPtr	samplematrixObject = NULL;
	TTAudioSignalPtr	input = NULL;
	TTAudioSignalPtr	output = NULL;

	// TODO: test filling with sine wave
	// TODO: test scaling (applying gain)
	// TODO: test normalizing (with optional arg, and also without an optional arg)

	TTObjectInstantiate("samplematrix", &samplematrixObject, kTTVal1);

	TTObjectRelease(&input);
	TTObjectRelease(&output);
	TTObjectRelease(&samplematrixObject);

	*/

	// Wrap up the test results to pass back to whoever called this test
	return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo);
}

<|endoftext|>


<commit_before>/*
 * Copyright 2016 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkOpts.h"
#include "SkRasterPipeline.h"

SkRasterPipeline::SkRasterPipeline() {}

void SkRasterPipeline::append(StockStage stage, void* ctx) {
#ifdef SK_DEBUG
    if (fNum == (int)SK_ARRAY_COUNT(fStages)) {
        this->dump();
    }
#endif
    SkASSERT(fNum < (int)SK_ARRAY_COUNT(fStages));
    fStages[fNum++] = { stage, ctx };
}

void SkRasterPipeline::extend(const SkRasterPipeline& src) {
    for (int i = 0; i < src.fNum; i++) {
        const Stage& s = src.fStages[i];
        this->append(s.stage, s.ctx);
    }
}

std::function<void(size_t, size_t, size_t)> SkRasterPipeline::compile() const {
    return SkOpts::compile_pipeline(fStages, fNum);
}

void SkRasterPipeline::dump() const {
    SkDebugf("SkRasterPipeline, %d stages\n", fNum);
    for (int i = 0; i < fNum; i++) {
        const char* name = "";
        switch (fStages[i].stage) {
        #define M(x) case x: name = #x; break;
            SK_RASTER_PIPELINE_STAGES(M)
        #undef M
        }
        SkDebugf("\t%s\n", name);
    }
    SkDebugf("\n");
}
<commit_msg>Show constant-foldable runs in SkRasterPipeline::dump().<commit_after>/*
 * Copyright 2016 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkOpts.h"
#include "SkRasterPipeline.h"

SkRasterPipeline::SkRasterPipeline() {}

void SkRasterPipeline::append(StockStage stage, void* ctx) {
#ifdef SK_DEBUG
    if (fNum == (int)SK_ARRAY_COUNT(fStages)) {
        this->dump();
    }
#endif
    SkASSERT(fNum < (int)SK_ARRAY_COUNT(fStages));
    fStages[fNum++] = { stage, ctx };
}

void SkRasterPipeline::extend(const SkRasterPipeline& src) {
    for (int i = 0; i < src.fNum; i++) {
        const Stage& s = src.fStages[i];
        this->append(s.stage, s.ctx);
    }
}

std::function<void(size_t, size_t, size_t)> SkRasterPipeline::compile() const {
    return SkOpts::compile_pipeline(fStages, fNum);
}

static bool invariant_in_x(const SkRasterPipeline::Stage& st) {
    if (st.ctx == nullptr) {
        // If a stage doesn't have a context pointer, it can't really do anything with x.
        return true;
    }

    // This would be a lot more compact as a blacklist (the loads, the stores, the gathers),
    // but it's safer to write as a whitelist.  If we get it wrong this way, not a big deal.
    switch (st.stage) {
        default: return false;

        case SkRasterPipeline::trace:
        case SkRasterPipeline::set_rgb:
        case SkRasterPipeline::constant_color:
        case SkRasterPipeline::scale_constant_float:
        case SkRasterPipeline::lerp_constant_float:
        case SkRasterPipeline::matrix_2x3:
        case SkRasterPipeline::matrix_3x4:
        case SkRasterPipeline::matrix_4x5:
        case SkRasterPipeline::matrix_perspective:
        case SkRasterPipeline::parametric_r:
        case SkRasterPipeline::parametric_g:
        case SkRasterPipeline::parametric_b:
        case SkRasterPipeline::table_r:
        case SkRasterPipeline::table_g:
        case SkRasterPipeline::table_b:
        case SkRasterPipeline::color_lookup_table:
        case SkRasterPipeline::lab_to_xyz:
        case SkRasterPipeline::clamp_x:
        case SkRasterPipeline::mirror_x:
        case SkRasterPipeline::repeat_x:
        case SkRasterPipeline::clamp_y:
        case SkRasterPipeline::mirror_y:
        case SkRasterPipeline::repeat_y:
        case SkRasterPipeline::top_left:
        case SkRasterPipeline::top_right:
        case SkRasterPipeline::bottom_left:
        case SkRasterPipeline::bottom_right:
        case SkRasterPipeline::accumulate:
            SkASSERT(st.ctx != nullptr);
            return true;
    }
    return false;
}

void SkRasterPipeline::dump() const {
    SkDebugf("SkRasterPipeline, %d stages\n", fNum);
    bool in_constant_run = false;
    for (int i = 0; i < fNum; i++) {
        const char* name = "";
        switch (fStages[i].stage) {
        #define M(x) case x: name = #x; break;
            SK_RASTER_PIPELINE_STAGES(M)
        #undef M
        }

        char mark = ' ';
        if (fStages[i].stage == SkRasterPipeline::constant_color) {
            mark = '*';
            in_constant_run = true;
        } else if (in_constant_run && invariant_in_x(fStages[i])) {
            mark = '|';
        } else {
            mark = ' ';
            in_constant_run = false;
        }
        SkDebugf("\t%c %s\n", mark, name);
    }
    SkDebugf("\n");
}
<|endoftext|>