<commit_before>#include <functional>
#include <initializer_list>
#include <string>
#include <vector>
#include <unordered_map>
#include <algorithm>

#include <iostream>

#include <memory>

namespace parser{

 	class Sign_{
        std::string name_;
        bool isTerm_;
      public:
        Sign_(std::string n, bool t){
            name_ = n;
            isTerm_ = t;
        }
		Sign_(std::string n){
			name_ = n;
		    isTerm_ = true;
		}
		Sign_(){
			name_ ="";
			isTerm_ = true;
		}
        bool isTerm(){
            return isTerm_;
        }
        std::string name(){
            return name_;
        }
		operator std::string() const{
    		return name_;
		}
	};

	using Sign = std::shared_ptr<Sign_>;

	class Item{
	  public:
        Sign left;
        std::vector<Sign> rights;
        int pos;
        Item(Sign l, std::initializer_list<Sign> const & r){
            left = l;
            rights.insert(rights.end(),r.begin(), r.end());
        }
        Sign nextSign(){
        	return rights[pos];
        }
        void next(){
			if(rights.size() > pos+1)
            	pos++;
        }
		friend std::ostream& operator<<(std::ostream &out, const Item &i){
			out << std::string(*i.left) <<" => ";
			for(auto s : i.rights){
				out << std::string(*s) <<" ";
			}
			out << "\n";
			return out;
		}
	};

	Sign mS(std::string name){
		return Sign(new Sign_(name,false));
	}
	Sign mtS(std::string name){
		return Sign(new Sign_(name));
	}

    auto  E = mS("E");
    auto Eq = mS("Eq");
    auto  T = mS("T");
    auto Tq = mS("Tq");
    auto  F = mS("F");

	auto Eps = mtS("Epsilon");
	auto Fin = mtS("Fin");

	std::vector<Item> rules;

	std::vector<Item> getItems(Sign s){
		//std::cout << std::string(*s) << std::endl;
		std::vector<Item> res;
		for(auto& i : rules){
			if(i.left->name() == s->name()){
				res.push_back(i);
			}
		}
		return res;
	}

    std::vector<Sign> first(Sign sign){
        if(sign->isTerm()){
            return {sign};
        }
        std::vector<Sign> res;
		auto items = getItems( sign );
		if(items.size() == 0)
			return res;

        for(auto& i : items){
			//std::cout << std::string( *i.left ) << " " << i.rights.size()  <<std::endl;
        	auto ext = first(i.rights[0]);
            if(find(ext.begin(), ext.end(), Eps) != ext.end()){
				//std::cout <<"Eps!\n";
            	ext.erase(remove(ext.begin(), ext.end(), Eps), ext.end());
               	res.insert(res.end(), ext.begin(), ext.end());
                    if(i.rights.size() >= 2){
                        auto nxt = first(i.rights[1]);
                        res.insert(res.end(), nxt.begin(), nxt.end());
                    }else{
                        res.push_back( Eps);
                    }
            }else{
            	res.insert(res.end(), ext.begin(), ext.end());
			}
		}
        return res;
    }
/*
    std::vector<Sing> first(initializer_list<Sign>& l){
        if(l.size() == 0)
            return {Sign("Epsilon")};

        std::vector<Rule> res;

        auto it = l.begin();
        if(*it == Sign("Epsilon")) return {Sign("Epsilon")};
        if((*it)->isTerm()) return {*it};

        auto ext = first(*it);
        if(find(ext.begin(), ext.end(), Sign("Epsilon")) != ext.end()){
            ext.erase(remove(ext.begin(), ext.end(), Sign("Epsilon")), ext.end());
            res.insert(res.end(), ext.begin(), ext.end());
            if(l.size() >= 2 ){
                it++;
                auto next = first(*it);
                res.insert(res.end(), next.begin(), next.end());
            }
            return res;
        }else{
            return ext;
        }
    }
*/
    std::vector<Sign> follow(Sign& s){
		std::cout<< std::string(*s) << std::endl;
        std::vector<Sign> res;

        if(s == E){
            res.push_back(Fin);
        }

        for(auto rit = rules.cbegin(); rit != rules.cend(); ++rit){
            auto ls = rit->left;
            if(ls == s) continue;

			auto rs = rit->rights;
            for(size_t i = 1; i < rs.size(); i++){
            	if(rs[i] == s){
                	if(i + 1 < rs.size()){
                    	auto ext = first(rs[i+1]);
                        if(find(ext.begin(), ext.end(), Eps) != ext.end()){
               	        	auto left = follow(ls);
                            res.insert(res.end(), left.begin(), left.end());
                        }
                        ext.erase(remove(ext.begin(), ext.end(), Eps), ext.end());
                       	res.insert(res.end(), ext.begin(), ext.end());
                    }else{
                        auto left = follow(ls);
                        res.insert(res.end(), left.begin(), left.end());
                    }
                }
            }
        }
        return res;
    }

	void closure(std::vector<Item>& I){
		int size = I.size();
		std::vector<Sign> alreadys;
		auto Ib = I;
		do{
			size = I.size();
			//std::cout<<"LOOP\n";
			for(auto i : Ib){
				//std::cout<< i << std::endl;
				auto X = getItems( i.nextSign() );
				//std::cout<<"item \n";
				for(auto x : X){
					//std::cout<< "#######\n" << x <<"\n";
					if(find(alreadys.begin(), alreadys.end(), x.left) != alreadys.end()){
						//std::cout<<":CON\n";
							continue;
					}
					//std::cout<<"loop\n";
					x.next();
					//std::cout<<"push X\n";
					I.push_back(x);
					alreadys.push_back(x.left);
				}
			}
			//std::cout<< size <<" "<<I.size() << "\n";
		}while( size != I.size() );
	}

	std::vector<Item> Goto(std::vector<Item> I,Sign X){
		std::vector<Item> J;
		for(auto i : I){
			i.next();
            J.push_back(i);
		}
		closure(J);
		return J;
	}

	void DFA(){
		std::vector<std::vector<Item>> T;
		std::vector<Item> f({ Item( mS("S"),{ E, Fin}) });
		closure(f);
		T.push_back(f);
		for(auto t : T){
			for(auto i : t){
				auto J = Goto( t, i.nextSign());
				T.push_back(J);
			}
		}
	}
	void setup(){

        rules.push_back(Item( E,
            { T, Eq }
        ));

        rules.push_back(Item( Eq,
            {mtS("+"), T,  Eq }
        ));
        rules.push_back(Item( Eq,
            { Eps }
        ));

		rules.push_back(Item( T,
            { F, Tq}
        ));

		rules.push_back(Item( Tq,
            { mtS("*"), F, Tq }
        ));
        rules.push_back(Item( Tq,
            { Eps }
        ));

        rules.push_back(Item( F,
            { mtS("("), E, mtS(")")}
        ));
        rules.push_back(Item( F,
            { mtS("i")}
		));
    }

	using namespace std;

    void test(Sign S){
        std::cout << "==== "<<std::string(*S)<< " ===\n";
        for(auto& s: first(S)){
            std::cout << std::string(*s) << std::endl;
        }
        std::cout<<"===\n";
        for(auto& r: follow(S)){
            std::cout << std::string(*r) << std::endl;
        }

	}

    void parser(){
        setup();
        /*
		test(E);

        test(Eq);

        test(T);

        test(Tq);

        test(F);
		*/
        std::cout<<"===\n";
		std::vector<Item> items = { Item( mS("S"), { E, Fin}) };
        closure(items);
		std::cout<<"~~~~~~~~~~~~~~~\n";
        for(auto i : items)
			std::cout << i;

        //delete items;

        //create_dfa();
        //for(auto rit = rule_table.begin(); rit != rule_table.end(); ++rit){
        //    if(rit->second)
        //        rit->second.reset();
        //}
    }
}

int main(){
    parser::parser();
    return 0;
}
/*
 * ==== T ===
 * (
 * i
 * ===
 * FIN
 * )
 * +
 * ==== Tq ===
 * *
 * Epsilon
 * ===
 * FIN
 * )
 * +
 * ==== F ===
 * (
 * i
 * ===
 * FIN
 * )
 * +
 * *
 * ===
 */

<commit_msg>[Add] First(initializer_list<>).<commit_after>#include <functional>
#include <initializer_list>
#include <string>
#include <vector>
#include <unordered_map>
#include <algorithm>

#include <iostream>

#include <memory>

namespace parser{

 	class Sign_{
        std::string name_;
        bool isTerm_;
      public:
        Sign_(std::string n, bool t){
            name_ = n;
            isTerm_ = t;
        }
		Sign_(std::string n){
			name_ = n;
		    isTerm_ = true;
		}
		Sign_(){
			name_ ="";
			isTerm_ = true;
		}
        bool isTerm(){
            return isTerm_;
        }
        std::string name(){
            return name_;
        }
		operator std::string() const{
    		return name_;
		}
	};

	using Sign = std::shared_ptr<Sign_>;

	class Item{
	  public:
        Sign left;
        std::vector<Sign> rights;
        int pos;
        Item(Sign l, std::initializer_list<Sign> const & r){
			pos = 0;
            left = l;
            rights.insert(rights.end(),r.begin(), r.end());
        }
        Sign nextSign(){
        	return rights[pos];
        }
        void next(){
			if(rights.size() > pos+1)
            	pos++;
        }
		bool isLast(){
			return pos == rights.size()-1;
		}
		friend std::ostream& operator<<(std::ostream &out, const Item &i){
			out << std::string(*i.left) <<" => ";
			if(i.pos == 0){
				out<< " . ";
			}
			for(int j=0;j<i.rights.size();j++){
				out << std::string(*i.rights[j]);
				if(i.pos == j+1){
					out<< " . ";
				}else{
					out<<"   ";
				}
			}
			out << "\n";
			return out;
		}
	};

	Sign mS(std::string name){
		return Sign(new Sign_(name,false));
	}
	Sign mtS(std::string name){
		return Sign(new Sign_(name));
	}

    auto  E = mS("E");
    auto Eq = mS("Eq");
    auto  T = mS("T");
    auto Tq = mS("Tq");
    auto  F = mS("F");

	auto Eps = mtS("Epsilon");
	auto Fin = mtS("Fin");

	std::vector<Item> rules;

	std::vector<Item> getItems(Sign s){
		//std::cout << std::string(*s) << std::endl;
		std::vector<Item> res;
		for(auto& i : rules){
			if(i.left->name() == s->name()){
				res.push_back(i);
			}
		}
		return res;
	}

    std::vector<Sign> first(Sign sign){
        if(sign->isTerm()){
            return {sign};
        }
        std::vector<Sign> res;
		auto items = getItems( sign );
		if(items.size() == 0)
			return res;

        for(auto& i : items){
			//std::cout << std::string( *i.left ) << " " << i.rights.size()  <<std::endl;
        	auto ext = first(i.rights[0]);
            if(find(ext.begin(), ext.end(), Eps) != ext.end()){
				//std::cout <<"Eps!\n";
            	ext.erase(remove(ext.begin(), ext.end(), Eps), ext.end());
               	res.insert(res.end(), ext.begin(), ext.end());
                    if(i.rights.size() >= 2){
                        auto nxt = first(i.rights[1]);
                        res.insert(res.end(), nxt.begin(), nxt.end());
                    }else{
                        res.push_back( Eps);
                    }
            }else{
            	res.insert(res.end(), ext.begin(), ext.end());
			}
		}
        return res;
    }
/*
    std::vector<Sing> first(initializer_list<Sign>& l){
        if(l.size() == 0)
            return {Sign("Epsilon")};

        std::vector<Rule> res;

        auto it = l.begin();
        if(*it == Sign("Epsilon")) return {Sign("Epsilon")};
        if((*it)->isTerm()) return {*it};

        auto ext = first(*it);
        if(find(ext.begin(), ext.end(), Sign("Epsilon")) != ext.end()){
            ext.erase(remove(ext.begin(), ext.end(), Sign("Epsilon")), ext.end());
            res.insert(res.end(), ext.begin(), ext.end());
            if(l.size() >= 2 ){
                it++;
                auto next = first(*it);
                res.insert(res.end(), next.begin(), next.end());
            }
            return res;
        }else{
            return ext;
        }
    }
*/
    std::vector<Sign> follow(Sign& s){
		std::cout<< std::string(*s) << std::endl;
        std::vector<Sign> res;

        if(s == E){
            res.push_back(Fin);
        }

        for(auto rit = rules.cbegin(); rit != rules.cend(); ++rit){
            auto ls = rit->left;
            if(ls == s) continue;

			auto rs = rit->rights;
            for(size_t i = 1; i < rs.size(); i++){
            	if(rs[i] == s){
                	if(i + 1 < rs.size()){
                    	auto ext = first(rs[i+1]);
                        if(find(ext.begin(), ext.end(), Eps) != ext.end()){
               	        	auto left = follow(ls);
                            res.insert(res.end(), left.begin(), left.end());
                        }
                        ext.erase(remove(ext.begin(), ext.end(), Eps), ext.end());
                       	res.insert(res.end(), ext.begin(), ext.end());
                    }else{
                        auto left = follow(ls);
                        res.insert(res.end(), left.begin(), left.end());
                    }
                }
            }
        }
        return res;
    }

	void closure(std::vector<Item>& I){
		int size = I.size();
		std::vector<Sign> alreadys;
		do{
			size = I.size();
			std::cout<<"LOOP\n";
			for(auto i : I){
				//std::cout<< i << std::endl;
				auto X = getItems( i.nextSign() );

				std::cout<< "SIZE:"<<X.size()<<std::endl;
				//std::cout<<"item \n";
				for(auto x : X){
					std::cout<< "#######\n" << x <<"\n";
					//if(find(alreadys.begin(), alreadys.end(), x.left) != alreadys.end()){
						//std::cout<<":CON\n";
					//		continue;
					//}
					//std::cout<<"loop\n";
					//x.next();
					//std::cout<<"push X\n";
					I.push_back(x);
					//alreadys.push_back(x.left);
				}
			}
			std::cout<< size <<" "<<I.size() << "\n";
		}while( size != I.size() );
	}

	std::vector<Item> Goto(std::vector<Item> I,Sign X){
		std::vector<Item> J;
		/*
		std::cout << "Goto argv b--------\n";
		for(auto i : I) std::cout<< i;
		std::cout<< std::string(*X)<<std::endl;;
		std::cout << "Goto argv e--------\n";
		// */
		for(auto i : I){
			if(i.nextSign() == X && !i.isLast()){
				//std::cout<<"1^^^^\n";
				i.next();
				//std::cout<< i;
            	J.push_back(i);
				//std::cout<<"2^^^^\n";
			}
		}
		closure(J);
		return J;
	}

	void DFA(){
		std::cout<<"Start\n";
		std::vector<std::vector<Item>> T;
		std::vector<std::vector<Item>> Tt;
		std::vector<Item> f({ Item( mS("S"),{ E, Fin}) });
		closure(f);
		T.push_back(f);
		int size = T.size();
		int count = 0;
		std::cout<< f[0];
		std::cout<<"++++++++++++++++\n";
		Tt = T;
		std::vector<Sign> alreadys;
		while( count < 5){
			count++;
			for(auto t : T){
				for(auto i : t){
					std::cout<< "i loop start\n"<< i;
					if(find(alreadys.begin(), alreadys.end(), i.nextSign()) != alreadys.end())
						continue;
					alreadys.push_back(i.nextSign());
					auto J = Goto( t, i.nextSign());
					std::cout << "***************************\n";
					std::cout << "I:"<< std::string(*i.nextSign()) << std::endl;
					for(auto j : J)
						std::cout << j;
					std::cout << "***************************\n";
					T.push_back(J);
					std::cout<<"i loop end\n";
				}
				std::cout<<"t loop end\n";
			}
			std::cout<< size << " " << T.size() << std::endl;
			if( size != T.size()){
				size = T.size();
			}else{
				break;
			}
		}
		std::cout<<"####################\n";
		for(auto t : T){
			std::cout<<"~~~~~~~~~~~~~~~\n";
			for(auto i : t){
				std::cout<< i;
			}
		}
	}
	void setup(){

        rules.push_back(Item( E,
            { T, Eq }
        ));

        rules.push_back(Item( Eq,
            {mtS("+"), T,  Eq }
        ));
        rules.push_back(Item( Eq,
            { Eps }
        ));

		rules.push_back(Item( T,
            { F, Tq}
        ));

		rules.push_back(Item( Tq,
            { mtS("*"), F, Tq }
        ));
        rules.push_back(Item( Tq,
            { Eps }
        ));

        rules.push_back(Item( F,
            { mtS("("), E, mtS(")")}
        ));
        rules.push_back(Item( F,
            { mtS("i")}
		));
    }

	using namespace std;

    void test(Sign S){
        std::cout << "==== "<<std::string(*S)<< " ===\n";
        for(auto& s: first(S)){
            std::cout << std::string(*s) << std::endl;
        }
        std::cout<<"===\n";
        for(auto& r: follow(S)){
            std::cout << std::string(*r) << std::endl;
        }
	}

    void parser(){
        setup();
        /*
		test(E);

        test(Eq);

        test(T);

        test(Tq);

        test(F);

        std::cout<<"===\n";
		std::vector<Item> items = { Item( mS("S"), { E, Fin}) };
        closure(items);
		std::cout<<"~~~~~~~~~~~~~~~\n";
        for(auto i : items)
			std::cout << i;
		*/
		DFA();

        //delete items;

        //create_dfa();
        //for(auto rit = rule_table.begin(); rit != rule_table.end(); ++rit){
        //    if(rit->second)
        //        rit->second.reset();
        //}
    }
}

int main(){
    parser::parser();
    return 0;
}
/*
 * ==== T ===
 * (
 * i
 * ===
 * FIN
 * )
 * +
 * ==== Tq ===
 * *
 * Epsilon
 * ===
 * FIN
 * )
 * +
 * ==== F ===
 * (
 * i
 * ===
 * FIN
 * )
 * +
 * *
 * ===
 */

<|endoftext|>


<commit_before>/*
	This file is part of the E_Util library.
	Copyright (C) 2012 Benjamin Eikel <benjamin@eikel.org>

	This library is subject to the terms of the Mozilla Public License, v. 2.0.
	You should have received a copy of the MPL along with this library; see the
	file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "E_Window.h"

#include <EScript/Basics.h>
#include <EScript/StdObjects.h>
#include <Util/Graphics/Bitmap.h>
#include <Util/IO/FileName.h>
#include <Util/Serialization/Serialization.h>
#include <Util/UI/UI.h>

namespace E_Util {
namespace E_UI {

EScript::Type * E_Window::getTypeObject() {
	// E_Window ---|> E_Object
	static EScript::ERef<EScript::Type> typeObject = new EScript::Type(EScript::Object::getTypeObject());
	return typeObject.get();
}

void E_Window::init(EScript::Namespace & lib) {
	EScript::Type * typeObject = E_Window::getTypeObject();
	EScript::declareConstant(&lib, getClassName(), typeObject);

	static const EScript::StringId ATTR_borderless("borderless");
	static const EScript::StringId ATTR_debug("debug");
	static const EScript::StringId ATTR_compatibilityProfile("compatibilityProfile");
	static const EScript::StringId ATTR_fullscreen("fullscreen");
	static const EScript::StringId ATTR_multisampled("multisampled");
	static const EScript::StringId ATTR_positioned("positioned");
	static const EScript::StringId ATTR_resizable("resizable");
	static const EScript::StringId ATTR_clientAreaWidth("clientAreaWidth");
	static const EScript::StringId ATTR_clientAreaHeight("clientAreaHeight");
	static const EScript::StringId ATTR_posX("posX");
	static const EScript::StringId ATTR_posY("posY");
	static const EScript::StringId ATTR_multisamples("multisamples");
	static const EScript::StringId ATTR_title("title");
	static const EScript::StringId ATTR_shareContext("shareContext");

	//!(static) [ESM] ExtObject Window.createPropertyObject()
	ES_FUNCTION(typeObject, "createPropertyObject", 0, 0, {
		EScript::ERef<EScript::ExtObject> eProperties = EScript::ExtObject::create();
		const Util::UI::Window::Properties properties; // for default values

		eProperties->setAttribute(ATTR_borderless,EScript::Bool::create(properties.borderless));
		eProperties->setAttribute(ATTR_debug,EScript::Bool::create(properties.debug));
		eProperties->setAttribute(ATTR_compatibilityProfile,EScript::Bool::create(properties.compatibilityProfile));
		eProperties->setAttribute(ATTR_fullscreen,EScript::Bool::create(properties.fullscreen));
		eProperties->setAttribute(ATTR_multisampled,EScript::Bool::create(properties.multisampled));
		eProperties->setAttribute(ATTR_positioned,EScript::Bool::create(properties.positioned));
		eProperties->setAttribute(ATTR_resizable,EScript::Bool::create(properties.resizable));
		eProperties->setAttribute(ATTR_clientAreaWidth,EScript::Number::create(properties.clientAreaWidth));
		eProperties->setAttribute(ATTR_clientAreaHeight,EScript::Number::create(properties.clientAreaHeight));
		eProperties->setAttribute(ATTR_posX,EScript::Number::create(properties.posX));
		eProperties->setAttribute(ATTR_posY,EScript::Number::create(properties.posY));
		eProperties->setAttribute(ATTR_multisamples,EScript::Number::create(properties.multisamples));
		eProperties->setAttribute(ATTR_title,EScript::String::create(properties.title));
		eProperties->setAttribute(ATTR_shareContext,EScript::Bool::create(properties.shareContext));
		return eProperties.detachAndDecrease();
	})

	//! [ESMF] Window new Window(Properties)
	ES_CONSTRUCTOR(typeObject, 1, 1,{
		Util::UI::Window::Properties properties;
		Object * eProperties = parameter[0].get();

		Object * attr;
		if( (attr = eProperties->getAttribute(ATTR_borderless).getValue()) != nullptr)
			properties.borderless = attr->toBool();
		if( (attr = eProperties->getAttribute(ATTR_debug).getValue()) != nullptr)
			properties.debug = attr->toBool();
		if( (attr = eProperties->getAttribute(ATTR_compatibilityProfile).getValue()) != nullptr)
			properties.compatibilityProfile = attr->toBool();
		if( (attr = eProperties->getAttribute(ATTR_fullscreen).getValue()) != nullptr)
			properties.fullscreen = attr->toBool();
		if( (attr = eProperties->getAttribute(ATTR_multisampled).getValue()) != nullptr)
			properties.multisampled = attr->toBool();
		if( (attr = eProperties->getAttribute(ATTR_positioned).getValue()) != nullptr)
			properties.positioned = attr->toBool();
		if( (attr = eProperties->getAttribute(ATTR_resizable).getValue()) != nullptr)
			properties.resizable = attr->toBool();
		if( (attr = eProperties->getAttribute(ATTR_clientAreaWidth).getValue()) != nullptr)
			properties.clientAreaWidth = attr->toUInt();
		if( (attr = eProperties->getAttribute(ATTR_clientAreaHeight).getValue()) != nullptr)
			properties.clientAreaHeight = attr->toUInt();
		if( (attr = eProperties->getAttribute(ATTR_posX).getValue()) != nullptr)
			properties.posX = attr->toInt();
		if( (attr = eProperties->getAttribute(ATTR_posY).getValue()) != nullptr)
			properties.posY = attr->toInt();
		if( (attr = eProperties->getAttribute(ATTR_multisamples).getValue()) != nullptr)
			properties.multisamples = attr->toUInt();
		if( (attr = eProperties->getAttribute(ATTR_title).getValue()) != nullptr)
			properties.title = attr->toString();
		if( (attr = eProperties->getAttribute(ATTR_shareContext).getValue()) != nullptr)
			properties.shareContext = attr->toBool();
		return new E_Window(properties);
	})

	//! [ESMF] Void Window.destroy()
	ES_MFUN(typeObject, E_Window, "destroy", 0, 0, (thisObj->destroy(),thisEObj))

	//! [ESMF] thisObj Window.swapBuffers()
	ES_MFUN(typeObject, E_Window, "swapBuffers", 0, 0, ((**thisObj)->swapBuffers(), thisObj))

	//! [ESMF] Number Window.getSwapInterval()
	ES_MFUN(typeObject, E_Window, "getSwapInterval", 0, 0, (**thisObj)->getSwapInterval())

	//! [ESMF] self Window.grabInput()
	ES_MFUN(typeObject, E_Window, "grabInput", 0, 0, ((**thisObj)->grabInput(),thisEObj))

	//! [ESMF] thisObj Window.hideCursor()
	ES_MFUN(typeObject, E_Window, "hideCursor", 0, 0, ((**thisObj)->hideCursor(),thisEObj))

	//! [ESMF] thisObj Window.showCursor()
	ES_MFUN(typeObject, E_Window, "showCursor", 0, 0, ((**thisObj)->showCursor(), thisObj))

	//! [ESMF] self Window.ungrabInput()
	ES_MFUN(typeObject, E_Window, "ungrabInput", 0, 0, ((**thisObj)->ungrabInput(),thisEObj))

	//! [ESMF] thisObj Window.warpCursor(Number x, Number y)
	ES_MFUN(typeObject, E_Window, "warpCursor", 2, 2,
				 ((**thisObj)->warpCursor(parameter[0].toInt(), parameter[1].toInt()), thisObj))

	//! [ESMF] thisObj Window.setIcon(String imagePath)
	ES_MFUN(typeObject, E_Window, "setIcon", 1, 1,
				 ((**thisObj)->setIcon(*Util::Serialization::loadBitmap(Util::FileName(parameter[0].toString())).get()), thisObj))

	//! [ESMF] thisObj Window.makeCurrent()
	ES_MFUN(typeObject, E_Window, "makeCurrent", 0, 0, ((**thisObj)->makeCurrent(),thisEObj))
}

E_Window::E_Window(const Util::UI::Window::Properties & properties) :
	ReferenceObject_t(E_Window::getTypeObject(), Util::UI::createWindow(properties)) {
}

E_Window::~E_Window() = default;

void E_Window::destroy() {
	ref().reset();
}

}
}
<commit_msg>Added window parameter for GL context version<commit_after>/*
	This file is part of the E_Util library.
	Copyright (C) 2012 Benjamin Eikel <benjamin@eikel.org>

	This library is subject to the terms of the Mozilla Public License, v. 2.0.
	You should have received a copy of the MPL along with this library; see the
	file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "E_Window.h"

#include <EScript/Basics.h>
#include <EScript/StdObjects.h>
#include <Util/Graphics/Bitmap.h>
#include <Util/IO/FileName.h>
#include <Util/Serialization/Serialization.h>
#include <Util/UI/UI.h>

namespace E_Util {
namespace E_UI {

EScript::Type * E_Window::getTypeObject() {
	// E_Window ---|> E_Object
	static EScript::ERef<EScript::Type> typeObject = new EScript::Type(EScript::Object::getTypeObject());
	return typeObject.get();
}

void E_Window::init(EScript::Namespace & lib) {
	EScript::Type * typeObject = E_Window::getTypeObject();
	EScript::declareConstant(&lib, getClassName(), typeObject);

	static const EScript::StringId ATTR_borderless("borderless");
	static const EScript::StringId ATTR_debug("debug");
	static const EScript::StringId ATTR_compatibilityProfile("compatibilityProfile");
	static const EScript::StringId ATTR_fullscreen("fullscreen");
	static const EScript::StringId ATTR_multisampled("multisampled");
	static const EScript::StringId ATTR_positioned("positioned");
	static const EScript::StringId ATTR_resizable("resizable");
	static const EScript::StringId ATTR_clientAreaWidth("clientAreaWidth");
	static const EScript::StringId ATTR_clientAreaHeight("clientAreaHeight");
	static const EScript::StringId ATTR_posX("posX");
	static const EScript::StringId ATTR_posY("posY");
	static const EScript::StringId ATTR_multisamples("multisamples");
	static const EScript::StringId ATTR_title("title");
	static const EScript::StringId ATTR_shareContext("shareContext");
	static const EScript::StringId ATTR_contextVersionMajor("contextVersionMajor");
	static const EScript::StringId ATTR_contextVersionMinor("contextVersionMinor");

	//!(static) [ESM] ExtObject Window.createPropertyObject()
	ES_FUNCTION(typeObject, "createPropertyObject", 0, 0, {
		EScript::ERef<EScript::ExtObject> eProperties = EScript::ExtObject::create();
		const Util::UI::Window::Properties properties; // for default values

		eProperties->setAttribute(ATTR_borderless,EScript::Bool::create(properties.borderless));
		eProperties->setAttribute(ATTR_debug,EScript::Bool::create(properties.debug));
		eProperties->setAttribute(ATTR_compatibilityProfile,EScript::Bool::create(properties.compatibilityProfile));
		eProperties->setAttribute(ATTR_fullscreen,EScript::Bool::create(properties.fullscreen));
		eProperties->setAttribute(ATTR_multisampled,EScript::Bool::create(properties.multisampled));
		eProperties->setAttribute(ATTR_positioned,EScript::Bool::create(properties.positioned));
		eProperties->setAttribute(ATTR_resizable,EScript::Bool::create(properties.resizable));
		eProperties->setAttribute(ATTR_clientAreaWidth,EScript::Number::create(properties.clientAreaWidth));
		eProperties->setAttribute(ATTR_clientAreaHeight,EScript::Number::create(properties.clientAreaHeight));
		eProperties->setAttribute(ATTR_posX,EScript::Number::create(properties.posX));
		eProperties->setAttribute(ATTR_posY,EScript::Number::create(properties.posY));
		eProperties->setAttribute(ATTR_multisamples,EScript::Number::create(properties.multisamples));
		eProperties->setAttribute(ATTR_title,EScript::String::create(properties.title));
		eProperties->setAttribute(ATTR_shareContext,EScript::Bool::create(properties.shareContext));
		eProperties->setAttribute(ATTR_contextVersionMajor,EScript::Number::create(properties.contextVersionMajor));
		eProperties->setAttribute(ATTR_contextVersionMinor,EScript::Number::create(properties.contextVersionMinor));
		return eProperties.detachAndDecrease();
	})

	//! [ESMF] Window new Window(Properties)
	ES_CONSTRUCTOR(typeObject, 1, 1,{
		Util::UI::Window::Properties properties;
		Object * eProperties = parameter[0].get();

		Object * attr;
		if( (attr = eProperties->getAttribute(ATTR_borderless).getValue()) != nullptr)
			properties.borderless = attr->toBool();
		if( (attr = eProperties->getAttribute(ATTR_debug).getValue()) != nullptr)
			properties.debug = attr->toBool();
		if( (attr = eProperties->getAttribute(ATTR_compatibilityProfile).getValue()) != nullptr)
			properties.compatibilityProfile = attr->toBool();
		if( (attr = eProperties->getAttribute(ATTR_fullscreen).getValue()) != nullptr)
			properties.fullscreen = attr->toBool();
		if( (attr = eProperties->getAttribute(ATTR_multisampled).getValue()) != nullptr)
			properties.multisampled = attr->toBool();
		if( (attr = eProperties->getAttribute(ATTR_positioned).getValue()) != nullptr)
			properties.positioned = attr->toBool();
		if( (attr = eProperties->getAttribute(ATTR_resizable).getValue()) != nullptr)
			properties.resizable = attr->toBool();
		if( (attr = eProperties->getAttribute(ATTR_clientAreaWidth).getValue()) != nullptr)
			properties.clientAreaWidth = attr->toUInt();
		if( (attr = eProperties->getAttribute(ATTR_clientAreaHeight).getValue()) != nullptr)
			properties.clientAreaHeight = attr->toUInt();
		if( (attr = eProperties->getAttribute(ATTR_posX).getValue()) != nullptr)
			properties.posX = attr->toInt();
		if( (attr = eProperties->getAttribute(ATTR_posY).getValue()) != nullptr)
			properties.posY = attr->toInt();
		if( (attr = eProperties->getAttribute(ATTR_multisamples).getValue()) != nullptr)
			properties.multisamples = attr->toUInt();
		if( (attr = eProperties->getAttribute(ATTR_title).getValue()) != nullptr)
			properties.title = attr->toString();
		if( (attr = eProperties->getAttribute(ATTR_shareContext).getValue()) != nullptr)
			properties.shareContext = attr->toBool();
		if( (attr = eProperties->getAttribute(ATTR_contextVersionMajor).getValue()) != nullptr)
			properties.contextVersionMajor = attr->toUInt();
		if( (attr = eProperties->getAttribute(ATTR_contextVersionMinor).getValue()) != nullptr)
			properties.contextVersionMinor = attr->toUInt();
		return new E_Window(properties);
	})

	//! [ESMF] Void Window.destroy()
	ES_MFUN(typeObject, E_Window, "destroy", 0, 0, (thisObj->destroy(),thisEObj))

	//! [ESMF] thisObj Window.swapBuffers()
	ES_MFUN(typeObject, E_Window, "swapBuffers", 0, 0, ((**thisObj)->swapBuffers(), thisObj))

	//! [ESMF] Number Window.getSwapInterval()
	ES_MFUN(typeObject, E_Window, "getSwapInterval", 0, 0, (**thisObj)->getSwapInterval())

	//! [ESMF] self Window.grabInput()
	ES_MFUN(typeObject, E_Window, "grabInput", 0, 0, ((**thisObj)->grabInput(),thisEObj))

	//! [ESMF] thisObj Window.hideCursor()
	ES_MFUN(typeObject, E_Window, "hideCursor", 0, 0, ((**thisObj)->hideCursor(),thisEObj))

	//! [ESMF] thisObj Window.showCursor()
	ES_MFUN(typeObject, E_Window, "showCursor", 0, 0, ((**thisObj)->showCursor(), thisObj))

	//! [ESMF] self Window.ungrabInput()
	ES_MFUN(typeObject, E_Window, "ungrabInput", 0, 0, ((**thisObj)->ungrabInput(),thisEObj))

	//! [ESMF] thisObj Window.warpCursor(Number x, Number y)
	ES_MFUN(typeObject, E_Window, "warpCursor", 2, 2,
				 ((**thisObj)->warpCursor(parameter[0].toInt(), parameter[1].toInt()), thisObj))

	//! [ESMF] thisObj Window.setIcon(String imagePath)
	ES_MFUN(typeObject, E_Window, "setIcon", 1, 1,
				 ((**thisObj)->setIcon(*Util::Serialization::loadBitmap(Util::FileName(parameter[0].toString())).get()), thisObj))

	//! [ESMF] thisObj Window.makeCurrent()
	ES_MFUN(typeObject, E_Window, "makeCurrent", 0, 0, ((**thisObj)->makeCurrent(),thisEObj))
}

E_Window::E_Window(const Util::UI::Window::Properties & properties) :
	ReferenceObject_t(E_Window::getTypeObject(), Util::UI::createWindow(properties)) {
}

E_Window::~E_Window() = default;

void E_Window::destroy() {
	ref().reset();
}

}
}
<|endoftext|>


<commit_before>// Yue Wang Oct, 2015
//
// Exercise 11.7:
// Define a map for which the key is the family’s last name and
// the value is a vector of the children’s names. Write code to
// add new families and to add new children to an existing family.
//  Discussion on Stack Overflow:
//

#include <iostream>
#include <map>
#include <string>
#include <algorithm>
#include <vector>

using std::string;
using std::vector;
using std::map;
using std::cin;
using std::cout;
using Families = map<string, vector<string>>;

auto make_families()
{
    Families families;
    for (string ln; cout << "Last name:\n", cin >> ln && ln != "@q";)
        for (string cn; cout << "|-Children's names:\n", cin >> cn && cn != "@q";)
            families[ln].push_back(cn);
    return families;
}

auto print(Families const& families)
{
    for (auto const& family : families)
    {
        cout << family.first << ":\n";
        for (auto const& child : family.second)
            cout << child << " ";
        cout << "\n";
    }
}

int main()
{
    print(make_families());
    return 0;
}
<commit_msg>Update ex11_7.cpp<commit_after>// Yue Wang Oct, 2015
//
// Exercise 11.7:
// Define a map for which the key is the family’s last name and
// the value is a vector of the children’s names. Write code to
// add new families and to add new children to an existing family.
//

#include <iostream>
#include <map>
#include <string>
#include <algorithm>
#include <vector>

using std::string;
using std::vector;
using std::map;
using std::cin;
using std::cout;
using Families = map<string, vector<string>>;

auto make_families()
{
    Families families;
    for (string ln; cout << "Last name:\n", cin >> ln && ln != "@q";)
        for (string cn; cout << "|-Children's names:\n", cin >> cn && cn != "@q";)
            families[ln].push_back(cn);
    return families;
}

auto print(Families const& families)
{
    for (auto const& family : families)
    {
        cout << family.first << ":\n";
        for (auto const& child : family.second)
            cout << child << " ";
        cout << "\n";
    }
}

int main()
{
    print(make_families());
    return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2016 C. Brett Witherspoon
 */

#ifndef SIGNUM_OPENCL_ERROR_HPP_
#define SIGNUM_OPENCL_ERROR_HPP_

#include <stdexcept>
#include <string>

#include <CL/cl.h>
#include <CL/cl_ext.h>

namespace signum
{
namespace opencl
{

struct general_error : public std::runtime_error
{
    general_error(const std::string &what, const std::string &where)
        : runtime_error(where + ": OpenCL: " + what)
    { }
};

struct platform_not_found : public general_error
{
    platform_not_found(const std::string &where)
        : general_error("Platform not found", where)
    { }
};

struct device_not_found : public general_error
{
    device_not_found(const std::string &where)
        : general_error("Device not found", where)
    { }
};

struct invalid_value : public general_error
{
    invalid_value(const std::string &where)
        : general_error("Invalid value", where)
    { }
};

struct out_of_host_memory: public general_error
{
    out_of_host_memory(const std::string &where)
        : general_error("Out of host memory", where)
    { }
};

struct invalid_platform: public general_error
{
    invalid_platform(const std::string &where)
        : general_error("Invalid platform", where)
    { }
};

static inline void throw_on_error(const cl_int error, const std::string &where = "(unknown)")
{
    switch (error)
    {
    case CL_SUCCESS:
        return;
    case CL_PLATFORM_NOT_FOUND_KHR:
        throw platform_not_found(where);
    case CL_INVALID_VALUE:
        throw invalid_value(where);
    case CL_OUT_OF_HOST_MEMORY:
        throw out_of_host_memory(where);
    case CL_INVALID_PLATFORM:
        throw invalid_platform(where);
    default:
        throw general_error("General error", where);
    }
}

} // end namespace signum
} // end namespace opengl

#endif /* SIGNUM_OPENCL_ERROR_HPP_ */
<commit_msg>opencl: error: add more errors<commit_after>/*
 * Copyright 2016 C. Brett Witherspoon
 */

#ifndef SIGNUM_OPENCL_ERROR_HPP_
#define SIGNUM_OPENCL_ERROR_HPP_

#include <stdexcept>
#include <string>

#include <CL/cl.h>
#include <CL/cl_ext.h>

namespace signum
{
namespace opencl
{

struct general_error : public std::runtime_error
{
    general_error(const std::string &what, const std::string &where)
        : runtime_error(where + ": OpenCL: " + what)
    { }
};

struct platform_not_found : public general_error
{
    platform_not_found(const std::string &where)
        : general_error("Platform not found", where)
    { }
};

struct device_not_found : public general_error
{
    device_not_found(const std::string &where)
        : general_error("Device not found", where)
    { }
};

struct invalid_value : public general_error
{
    invalid_value(const std::string &where)
        : general_error("Invalid value", where)
    { }
};

struct out_of_host_memory : public general_error
{
    out_of_host_memory(const std::string &where)
        : general_error("Out of host memory", where)
    { }
};

struct invalid_platform : public general_error
{
    invalid_platform(const std::string &where)
        : general_error("Invalid platform", where)
    { }
};

struct build_program_failure : public general_error
{
    build_program_failure(const std::string &where)
        : general_error("Build program failure", where)
    { }
};

struct invalid_kernel_args : public general_error
{
    invalid_kernel_args(const std::string &where)
        : general_error("Invalid kernel arguments", where)
    { }
};

static inline void throw_on_error(const cl_int error, const std::string &where = "(unknown)")
{
    switch (error)
    {
    case CL_SUCCESS:
        return;
    case CL_PLATFORM_NOT_FOUND_KHR:
        throw platform_not_found(where);
    case CL_INVALID_VALUE:
        throw invalid_value(where);
    case CL_OUT_OF_HOST_MEMORY:
        throw out_of_host_memory(where);
    case CL_INVALID_PLATFORM:
        throw invalid_platform(where);
    case CL_BUILD_PROGRAM_FAILURE:
        throw build_program_failure(where);
    case CL_INVALID_KERNEL_ARGS:
        throw invalid_kernel_args(where);
    default:
        throw general_error("General error", where);
    }
}

} // end namespace signum
} // end namespace opengl

#endif /* SIGNUM_OPENCL_ERROR_HPP_ */
<|endoftext|>


<commit_before>#include <QTest>
#include "testangleutils.h"
#include "testgpsreader.hpp"
#include <vector>
#include <algorithm>
#include <iostream>
#include "teststringutils.hpp"
#include "testpositiontracker.hpp"
#include "testgpsutils.h"
#include "capturegpsandpostracker.hpp"

void RunTestCase(QObject* testCase, std::vector<std::string> args, bool runByDefault = true)
{
    if(runByDefault && ( args.size() == 0 || std::find(args.begin(), args.end(), testCase->metaObject()->className()) != args.end() ))
    {
        QTest::qExec(testCase);
    }
    else if(std::find(args.begin(), args.end(), testCase->metaObject()->className()) != args.end())
    {
        QTest::qExec(testCase);
    }
}

int main(int argc, const char* argv[])
{
    // Setup arguments vector
    std::vector<std::string> args;
    for(int i = 0; i < argc; i++)
        if(argv[i][0] != '/')
            args.push_back(argv[i]);
    if(std::find(args.begin(), args.end(), "all") != args.end())
        args.clear();
    if(args.size() == 0)
    {
        std::cout << "Running all tests." << std::endl;
    }
    else
    {
        std::cout << "Running ";
        for(uint i = 0; i < args.size() - 1; i++)
            std::cout << args[i] << ", ";
        std::cout << (args.size() > 1 ? "and " : "") << args[args.size()-1] << "." << std::endl;
    }

    // Execute selected test cases
    RunTestCase(new TestStringUtils(), args);
    RunTestCase(new TestPositionTracker(), args);
    RunTestCase(new TestGPSUtils(), args);
    RunTestCase(new TestAngleUtils(), args);
    RunTestCase(new TestGPSReader(), args);
    RunTestCase(new CaptureGPSAndPosTracker(), args, false);
}
<commit_msg>Minor bug fixes in test selection.<commit_after>#include <QTest>
#include "testangleutils.h"
#include "testgpsreader.hpp"
#include <vector>
#include <algorithm>
#include <iostream>
#include "teststringutils.hpp"
#include "testpositiontracker.hpp"
#include "testgpsutils.h"
#include "capturegpsandpostracker.hpp"

void RunTestCase(QObject* testCase, std::vector<std::string> args, bool runByDefault = true)
{
    if(runByDefault && ( args.size() == 0 ||
                         std::find(args.begin(), args.end(), testCase->metaObject()->className()) != args.end() ||
                         std::find(args.begin(), args.end(), "all") != args.end()))
    {
        QTest::qExec(testCase);
    }
    else if(std::find(args.begin(), args.end(), testCase->metaObject()->className()) != args.end())
    {
        QTest::qExec(testCase);
    }
}

int main(int argc, const char* argv[])
{
    // Setup arguments vector
    std::vector<std::string> args;
    for(int i = 0; i < argc; i++)
        if(argv[i][0] != '/')
            args.push_back(argv[i]);
    if(args.size() == 0)
    {
        std::cout << "Running all default tests." << std::endl;
    }
    else
    {
        std::cout << "Running ";
        for(uint i = 0; i < args.size() - 1; i++)
            std::cout << args[i] << ", ";
        std::cout << (args.size() > 1 ? "and " : "") << args[args.size()-1] << "." << std::endl;
    }

    // Execute selected test cases
    RunTestCase(new TestStringUtils(), args);
    RunTestCase(new TestPositionTracker(), args);
    RunTestCase(new TestGPSUtils(), args);
    RunTestCase(new TestAngleUtils(), args);
    RunTestCase(new TestGPSReader(), args);
    RunTestCase(new CaptureGPSAndPosTracker(), args, false);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: xmlColumn.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: hr $ $Date: 2004-08-02 15:18:40 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the License); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an AS IS basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef DBA_XMLCOLUMN_HXX
#include "xmlColumn.hxx"
#endif
#ifndef DBA_XMLFILTER_HXX
#include "xmlfilter.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef DBA_XMLENUMS_HXX
#include "xmlEnums.hxx"
#endif
#ifndef DBACCESS_SHARED_XMLSTRINGS_HRC
#include "xmlstrings.hrc"
#endif
#ifndef _COM_SUN_STAR_SDBCX_XDATADESCRIPTORFACTORY_HPP_
#include <com/sun/star/sdbcx/XDataDescriptorFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XAPPEND_HPP_
#include <com/sun/star/sdbcx/XAppend.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef DBA_XMLSTYLEIMPORT_HXX
#include "xmlStyleImport.hxx"
#endif

namespace dbaxml
{
    using namespace ::rtl;
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::sdbcx;
    using namespace ::com::sun::star::container;
    using namespace ::com::sun::star::xml::sax;

OXMLColumn::OXMLColumn( ODBFilter& rImport
                ,sal_uInt16 nPrfx
                ,const OUString& _sLocalName
                ,const Reference< XAttributeList > & _xAttrList
                ,const Reference< XNameAccess >& _xParentContainer
                ) :
    SvXMLImportContext( rImport, nPrfx, _sLocalName )
    ,m_xParentContainer(_xParentContainer)
    ,m_bHidden(sal_False)
{
    OSL_ENSURE(_xAttrList.is(),"Attribute list is NULL!");
    const SvXMLNamespaceMap& rMap = rImport.GetNamespaceMap();
    const SvXMLTokenMap& rTokenMap = rImport.GetColumnElemTokenMap();

    sal_Int16 nLength = (_xAttrList.is()) ? _xAttrList->getLength() : 0;
    sal_Bool bAutoEnabled = sal_False;
    for(sal_Int16 i = 0; i < nLength; ++i)
    {
        OUString sLocalName;
        rtl::OUString sAttrName = _xAttrList->getNameByIndex( i );
        sal_uInt16 nPrefix = rMap.GetKeyByAttrName( sAttrName,&sLocalName );
        rtl::OUString sValue = _xAttrList->getValueByIndex( i );

        switch( rTokenMap.Get( nPrefix, sLocalName ) )
        {
            case XML_TOK_COLUMN_NAME:
                m_sName = sValue;
                break;
            case XML_TOK_COLUMN_STYLE_NAME:
                m_sStyleName = sValue;
                break;
            case XML_TOK_COLUMN_HELP_MESSAGE:
                m_sHelpMessage = sValue;
                break;
            case XML_TOK_COLUMN_VISIBILITY:
                m_bHidden = !sValue.equalsAscii("visible");
                break;
        }
    }
    OSL_ENSURE(m_sName.getLength(),"Invalid column name of length: ZERO");
}
// -----------------------------------------------------------------------------

OXMLColumn::~OXMLColumn()
{
}
// -----------------------------------------------------------------------------
void OXMLColumn::EndElement()
{
    Reference<XDataDescriptorFactory> xFac(m_xParentContainer,UNO_QUERY);
    if ( xFac.is() && m_sName.getLength() )
    {
        Reference<XPropertySet> xProp(xFac->createDataDescriptor());
        if ( xProp.is() )
        {
            xProp->setPropertyValue(PROPERTY_NAME,makeAny(m_sName));
            xProp->setPropertyValue(PROPERTY_HIDDEN,makeAny(m_bHidden));
            if ( m_sHelpMessage.getLength() )
                xProp->setPropertyValue(PROPERTY_HELPTEXT,makeAny(m_sHelpMessage));

            if ( m_sStyleName.getLength() )
            {
                const SvXMLStylesContext* pAutoStyles = GetOwnImport().GetAutoStyles();
                if ( pAutoStyles )
                {
                    OTableStyleContext* pAutoStyle = PTR_CAST(OTableStyleContext,pAutoStyles->FindStyleChildContext(XML_STYLE_FAMILY_TABLE_COLUMN,m_sStyleName));
                    if ( pAutoStyle )
                    {
                        pAutoStyle->FillPropertySet(xProp);
                    }
                }
            }
            Reference<XAppend> xAppend(m_xParentContainer,UNO_QUERY);
            if ( xAppend.is() )
                xAppend->appendByDescriptor(xProp);
        }
    }
}
// -----------------------------------------------------------------------------
ODBFilter& OXMLColumn::GetOwnImport()
{
    return static_cast<ODBFilter&>(GetImport());
}
//----------------------------------------------------------------------------
} // namespace dbaxml
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS dba25 (1.2.102); FILE MERGED 2005/03/09 08:25:27 oj 1.2.102.2: #i44064# save the type as well 2005/03/04 14:23:47 oj 1.2.102.1: #i44064# export control default<commit_after>/*************************************************************************
 *
 *  $RCSfile: xmlColumn.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2005-03-18 10:05:57 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the License); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an AS IS basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef DBA_XMLCOLUMN_HXX
#include "xmlColumn.hxx"
#endif
#ifndef DBA_XMLFILTER_HXX
#include "xmlfilter.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include <xmloff/xmluconv.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include <xmloff/xmlnmspe.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef DBA_XMLENUMS_HXX
#include "xmlEnums.hxx"
#endif
#ifndef DBACCESS_SHARED_XMLSTRINGS_HRC
#include "xmlstrings.hrc"
#endif
#ifndef _COM_SUN_STAR_SDBCX_XDATADESCRIPTORFACTORY_HPP_
#include <com/sun/star/sdbcx/XDataDescriptorFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XAPPEND_HPP_
#include <com/sun/star/sdbcx/XAppend.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef DBA_XMLSTYLEIMPORT_HXX
#include "xmlStyleImport.hxx"
#endif

namespace dbaxml
{
    using namespace ::rtl;
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::sdbcx;
    using namespace ::com::sun::star::container;
    using namespace ::com::sun::star::xml::sax;

OXMLColumn::OXMLColumn( ODBFilter& rImport
                ,sal_uInt16 nPrfx
                ,const OUString& _sLocalName
                ,const Reference< XAttributeList > & _xAttrList
                ,const Reference< XNameAccess >& _xParentContainer
                ) :
    SvXMLImportContext( rImport, nPrfx, _sLocalName )
    ,m_xParentContainer(_xParentContainer)
    ,m_bHidden(sal_False)
{
    OSL_ENSURE(_xAttrList.is(),"Attribute list is NULL!");
    const SvXMLNamespaceMap& rMap = rImport.GetNamespaceMap();
    const SvXMLTokenMap& rTokenMap = rImport.GetColumnElemTokenMap();

    sal_Int16 nLength = (_xAttrList.is()) ? _xAttrList->getLength() : 0;
    sal_Bool bAutoEnabled = sal_False;
    ::rtl::OUString sType;
    for(sal_Int16 i = 0; i < nLength; ++i)
    {
        OUString sLocalName;
        rtl::OUString sAttrName = _xAttrList->getNameByIndex( i );
        sal_uInt16 nPrefix = rMap.GetKeyByAttrName( sAttrName,&sLocalName );
        rtl::OUString sValue = _xAttrList->getValueByIndex( i );

        switch( rTokenMap.Get( nPrefix, sLocalName ) )
        {
            case XML_TOK_COLUMN_NAME:
                m_sName = sValue;
                break;
            case XML_TOK_COLUMN_STYLE_NAME:
                m_sStyleName = sValue;
                break;
            case XML_TOK_COLUMN_HELP_MESSAGE:
                m_sHelpMessage = sValue;
                break;
            case XML_TOK_COLUMN_VISIBILITY:
                m_bHidden = !sValue.equalsAscii("visible");
                break;
            case XML_TOK_COLUMN_TYPE_NAME:
                sType = sValue;
                OSL_ENSURE(sType.getLength(),"No type name set");
                break;
            case XML_TOK_COLUMN_DEFAULT_VALUE:
                if ( sValue.getLength() && sType.getLength() )
                    SvXMLUnitConverter::convertAny(m_aDefaultValue,sType,sValue);
                break;
        }
    }
    OSL_ENSURE(m_sName.getLength(),"Invalid column name of length: ZERO");
}
// -----------------------------------------------------------------------------

OXMLColumn::~OXMLColumn()
{
}
// -----------------------------------------------------------------------------
void OXMLColumn::EndElement()
{
    Reference<XDataDescriptorFactory> xFac(m_xParentContainer,UNO_QUERY);
    if ( xFac.is() && m_sName.getLength() )
    {
        Reference<XPropertySet> xProp(xFac->createDataDescriptor());
        if ( xProp.is() )
        {
            xProp->setPropertyValue(PROPERTY_NAME,makeAny(m_sName));
            xProp->setPropertyValue(PROPERTY_HIDDEN,makeAny(m_bHidden));
            if ( m_sHelpMessage.getLength() )
                xProp->setPropertyValue(PROPERTY_HELPTEXT,makeAny(m_sHelpMessage));

            if ( m_aDefaultValue.hasValue() )
                xProp->setPropertyValue(PROPERTY_CONTROLDEFAULT,m_aDefaultValue);

            if ( m_sStyleName.getLength() )
            {
                const SvXMLStylesContext* pAutoStyles = GetOwnImport().GetAutoStyles();
                if ( pAutoStyles )
                {
                    OTableStyleContext* pAutoStyle = PTR_CAST(OTableStyleContext,pAutoStyles->FindStyleChildContext(XML_STYLE_FAMILY_TABLE_COLUMN,m_sStyleName));
                    if ( pAutoStyle )
                    {
                        pAutoStyle->FillPropertySet(xProp);
                    }
                }
            }
            Reference<XAppend> xAppend(m_xParentContainer,UNO_QUERY);
            if ( xAppend.is() )
                xAppend->appendByDescriptor(xProp);
        }
    }
}
// -----------------------------------------------------------------------------
ODBFilter& OXMLColumn::GetOwnImport()
{
    return static_cast<ODBFilter&>(GetImport());
}
//----------------------------------------------------------------------------
} // namespace dbaxml
// -----------------------------------------------------------------------------
<|endoftext|>


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

#define _POSIX_C_SOURCE 200809

/**  INCLUDES  ****************************************************************/

#include <memory>
#include <sstream>
#include <vector>

#include <cstdarg>		/* gate_state */
#include <cstdbool>		/* bool */
#include <cstdint>
#include <cstdlib>
#include <cstring>

#include <thread>
#include <chrono>

#ifdef WIN32
struct timespec
{
	time_t tv_sec;
	long tv_nsec;
};
#include <Winsock2.h>
#else
#include <time.h>		/* struct timespec */
#endif

#include "cuppa/cmd.h"		/* struct cmd, check_commands */
#include "cuppa/io.h"           /* response */

#include "audio.h"
#include "constants.h"
#include "messages.h"
#include "player.h"

/* This should be long enough to hold all the state names above separated with
 * spaces and null-terminated.
 */
#define STATE_NAME_BUF 256

/* Names of the states in enum state. */
const char	STATES[NUM_STATES][WORD_LEN] = {
	"Void",
	"Ejct",
	"Stop",
	"Play",
	"Quit",
};

enum state	GEND = S_VOID;

player::player(int device)
{
	this->cstate = S_EJCT;
	this->device = device;
	this->au = nullptr;
}

void
player::main_loop()
{
	enum error	err = E_OK;

	/* Set of commands that can be performed on the player. */
	command_set PLAYER_CMDS = {
		/* Nullary commands */
		{ "play", [&](const cmd_words &) { return this->cmd_play(); } },
		{ "stop", [&](const cmd_words &) { return this->cmd_stop(); } },
		{ "ejct", [&](const cmd_words &) { return this->cmd_ejct(); } },
		{ "quit", [&](const cmd_words &) { return this->cmd_quit(); } },
		/* Unary commands */
		{ "load", [&](const cmd_words &words) { return this->cmd_load(words[1]); } },
		{ "seek", [&](const cmd_words &words) { return this->cmd_load(words[1]); } }
	};

	response(R_OHAI, "%s", MSG_OHAI);	/* Say hello */
	while (state() != S_QUIT) {
		/*
		 * Possible Improvement: separate command checking and player
		 * updating into two threads.  Player updating is quite
		 * intensive and thus impairs the command checking latency.
		 * Do this if it doesn't make the code too complex.
		 */
		err = check_commands(PLAYER_CMDS);
		/* TODO: Check to see if err was fatal */
		loop_iter();

		std::this_thread::sleep_for(std::chrono::nanoseconds(LOOP_NSECS));
	}
	response(R_TTFN, "%s", MSG_TTFN);	/* Wave goodbye */
}

bool
player::cmd_ejct()
{
	bool valid = gate_state(S_STOP, S_PLAY, GEND);
	if (valid) {
		this->au = nullptr;
		set_state(S_EJCT);
		this->ptime = 0;
	}
	return valid;
}

bool
player::cmd_play()
{
	bool valid = gate_state(S_STOP, GEND) && (this->au != nullptr);
	if (valid) {
		this->au->start();
		set_state(S_PLAY);
	}
	return valid;
}

bool
player::cmd_quit()
{
	cmd_ejct();
	set_state(S_QUIT);

	return true; // Always a valid command.
}

bool
player::cmd_stop()
{
	bool valid = gate_state(S_PLAY, GEND);
	if (valid) {
		this->au->stop();
	}
	return valid;
}

bool
player::cmd_load(const std::string &filename)
{
	try {
		this->au = std::unique_ptr<audio>(new audio(filename, this->device));
		dbug("loaded %s", filename);
		set_state(S_STOP);
	}
	catch (enum error) {
		cmd_ejct();
	}

	return true; // Always a valid command.
}

bool
player::cmd_seek(const std::string &time_str)
{
	/* TODO: proper overflow checking */

	std::istringstream is(time_str);
	uint64_t time;
	std::string rest;
	is >> time >> rest;

	if (rest == "s" || rest == "sec") {
		time *= USECS_IN_SEC;
	}

	/* Weed out any unwanted states */
	bool valid = gate_state(S_PLAY, S_STOP, GEND);
	if (valid) {
		enum state current_state = this->cstate;

		cmd_stop(); // We need the player engine stopped in order to seek
		this->au->seek_usec(time);
		if (current_state == S_PLAY) {
			// If we were playing before we'd ideally like to resume
			cmd_play();
		}
	}

	return valid;
}

enum state
player::state()
{
	return this->cstate;
}

/* Performs an iteration of the player update loop. */
void
player::loop_iter()
{
	if (this->cstate == S_PLAY) {
		if (this->au->halted()) {
			cmd_ejct();
		} else {
			/* Send a time pulse upstream every TIME_USECS usecs */
			uint64_t time = this->au->usec();
			if (time / TIME_USECS > this->ptime / TIME_USECS) {
				response(R_TIME, "%u", time);
			}
			this->ptime = time;
		}
	}
	if (this->cstate == S_PLAY || this->cstate == S_STOP) {
		this->au->decode();
	}
}

/* Throws an error if the current state is not in the state set provided by
 * argument s1 and subsequent arguments up to 'GEND'.
 *
 * As a variadic function, the argument list MUST be terminated with 'GEND'.
 */
bool
player::gate_state(enum state s1,...)
{
	va_list		ap;
	int		i;
	enum error	err = E_OK;
	bool		in_state = false;

	va_start(ap, s1);
	for (i = (int)s1; !in_state && i != (int)GEND; i = va_arg(ap, int)) {
		if ((int)this->cstate == i) {
			in_state = true;
		}
	}
	va_end(ap);

	return in_state;
}

/* Sets the player state and honks accordingly. */
void
player::set_state(enum state state)
{
	enum state pstate = this->cstate;

	this->cstate = state;

	response(R_STAT, "%s %s", STATES[pstate], STATES[state]);
}
<commit_msg>Stop when stopping.<commit_after>/*-
 * Copyright (C) 2012  University Radio York Computing Team
 *
 * This file is a part of playslave.
 *
 * playslave is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * playslave is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * playslave; if not, write to the Free Software Foundation, Inc., 51 Franklin
 * Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#define _POSIX_C_SOURCE 200809

/**  INCLUDES  ****************************************************************/

#include <memory>
#include <sstream>
#include <vector>

#include <cstdarg>		/* gate_state */
#include <cstdbool>		/* bool */
#include <cstdint>
#include <cstdlib>
#include <cstring>

#include <thread>
#include <chrono>

#ifdef WIN32
struct timespec
{
	time_t tv_sec;
	long tv_nsec;
};
#include <Winsock2.h>
#else
#include <time.h>		/* struct timespec */
#endif

#include "cuppa/cmd.h"		/* struct cmd, check_commands */
#include "cuppa/io.h"           /* response */

#include "audio.h"
#include "constants.h"
#include "messages.h"
#include "player.h"

/* This should be long enough to hold all the state names above separated with
 * spaces and null-terminated.
 */
#define STATE_NAME_BUF 256

/* Names of the states in enum state. */
const char	STATES[NUM_STATES][WORD_LEN] = {
	"Void",
	"Ejct",
	"Stop",
	"Play",
	"Quit",
};

enum state	GEND = S_VOID;

player::player(int device)
{
	this->cstate = S_EJCT;
	this->device = device;
	this->au = nullptr;
}

void
player::main_loop()
{
	enum error	err = E_OK;

	/* Set of commands that can be performed on the player. */
	command_set PLAYER_CMDS = {
		/* Nullary commands */
		{ "play", [&](const cmd_words &) { return this->cmd_play(); } },
		{ "stop", [&](const cmd_words &) { return this->cmd_stop(); } },
		{ "ejct", [&](const cmd_words &) { return this->cmd_ejct(); } },
		{ "quit", [&](const cmd_words &) { return this->cmd_quit(); } },
		/* Unary commands */
		{ "load", [&](const cmd_words &words) { return this->cmd_load(words[1]); } },
		{ "seek", [&](const cmd_words &words) { return this->cmd_load(words[1]); } }
	};

	response(R_OHAI, "%s", MSG_OHAI);	/* Say hello */
	while (state() != S_QUIT) {
		/*
		 * Possible Improvement: separate command checking and player
		 * updating into two threads.  Player updating is quite
		 * intensive and thus impairs the command checking latency.
		 * Do this if it doesn't make the code too complex.
		 */
		err = check_commands(PLAYER_CMDS);
		/* TODO: Check to see if err was fatal */
		loop_iter();

		std::this_thread::sleep_for(std::chrono::nanoseconds(LOOP_NSECS));
	}
	response(R_TTFN, "%s", MSG_TTFN);	/* Wave goodbye */
}

bool
player::cmd_ejct()
{
	bool valid = gate_state(S_STOP, S_PLAY, GEND);
	if (valid) {
		this->au = nullptr;
		set_state(S_EJCT);
		this->ptime = 0;
	}
	return valid;
}

bool
player::cmd_play()
{
	bool valid = gate_state(S_STOP, GEND) && (this->au != nullptr);
	if (valid) {
		this->au->start();
		set_state(S_PLAY);
	}
	return valid;
}

bool
player::cmd_quit()
{
	cmd_ejct();
	set_state(S_QUIT);

	return true; // Always a valid command.
}

bool
player::cmd_stop()
{
	bool valid = gate_state(S_PLAY, GEND);
	if (valid) {
		this->au->stop();
		set_state(S_STOP);
	}
	return valid;
}

bool
player::cmd_load(const std::string &filename)
{
	try {
		this->au = std::unique_ptr<audio>(new audio(filename, this->device));
		dbug("loaded %s", filename);
		set_state(S_STOP);
	}
	catch (enum error) {
		cmd_ejct();
	}

	return true; // Always a valid command.
}

bool
player::cmd_seek(const std::string &time_str)
{
	/* TODO: proper overflow checking */

	std::istringstream is(time_str);
	uint64_t time;
	std::string rest;
	is >> time >> rest;

	if (rest == "s" || rest == "sec") {
		time *= USECS_IN_SEC;
	}

	/* Weed out any unwanted states */
	bool valid = gate_state(S_PLAY, S_STOP, GEND);
	if (valid) {
		enum state current_state = this->cstate;

		cmd_stop(); // We need the player engine stopped in order to seek
		this->au->seek_usec(time);
		if (current_state == S_PLAY) {
			// If we were playing before we'd ideally like to resume
			cmd_play();
		}
	}

	return valid;
}

enum state
player::state()
{
	return this->cstate;
}

/* Performs an iteration of the player update loop. */
void
player::loop_iter()
{
	if (this->cstate == S_PLAY) {
		if (this->au->halted()) {
			cmd_ejct();
		} else {
			/* Send a time pulse upstream every TIME_USECS usecs */
			uint64_t time = this->au->usec();
			if (time / TIME_USECS > this->ptime / TIME_USECS) {
				response(R_TIME, "%u", time);
			}
			this->ptime = time;
		}
	}
	if (this->cstate == S_PLAY || this->cstate == S_STOP) {
		this->au->decode();
	}
}

/* Throws an error if the current state is not in the state set provided by
 * argument s1 and subsequent arguments up to 'GEND'.
 *
 * As a variadic function, the argument list MUST be terminated with 'GEND'.
 */
bool
player::gate_state(enum state s1,...)
{
	va_list		ap;
	int		i;
	enum error	err = E_OK;
	bool		in_state = false;

	va_start(ap, s1);
	for (i = (int)s1; !in_state && i != (int)GEND; i = va_arg(ap, int)) {
		if ((int)this->cstate == i) {
			in_state = true;
		}
	}
	va_end(ap);

	return in_state;
}

/* Sets the player state and honks accordingly. */
void
player::set_state(enum state state)
{
	enum state pstate = this->cstate;

	this->cstate = state;

	response(R_STAT, "%s %s", STATES[pstate], STATES[state]);
}
<|endoftext|>


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

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

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

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#ifdef __BORLANDC__
#define ITK_LEAN_AND_MEAN
#endif

//  Software Guide : BeginCommandLineArgs
//    INPUTS: {ROISpot5.png}, {ROISpot5Warped.png}
//    OUTPUTS: {SIFTdeformationFieldOutput.png}
//  Software Guide : EndCommandLineArgs

// Software Guide : BeginLatex
//
// This example demonstrates the use of the
// \doxygen{otb}{KeyPointSetsMatchingFilter} for disparity map
// estimation. The idea here is to match SIFTs extracted from both the
// fixed and the moving images. The use of SIFTs is demonstrated in
// section \ref{sec:SIFTDetector}. The
// \doxygen{otb}{NearestPointDeformationFieldGenerator} will be used
// to generate a deformation field by using nearest neighbor
// interpolation on the deformation values from the point set. More
// advanced methods for deformation field interpolation are also
// available.
//
// The first step toward the use of these filters is to include the proper header files.
//
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet

#include "otbKeyPointSetsMatchingFilter.h"
#include "otbSiftFastImageFilter.h"
#include "itkDeformationFieldSource.h"
#include "itkWarpImageFilter.h"

// Software Guide : EndCodeSnippet

#include "otbImage.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkPointSet.h"
#include "otbMultiToMonoChannelExtractROI.h"

int main (int argc, char* argv[])
{
  if(argc!= 4)
    {
      std::cerr <<"Usage: "<<argv[0];
      std::cerr<<"fixedFileName movingFileName fieldOutName" << std::endl;
      return EXIT_FAILURE;
    }

  const unsigned int Dimension = 2;

   // Software Guide : BeginLatex
   //
   // Then we must decide what pixel type to use for the image. We choose to do
   // all the computation in floating point precision and rescale the results
   // between 0 and 255 in order to export PNG images.
   //
   // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  typedef double        RealType;
  typedef unsigned char OutputPixelType;

  typedef otb::Image<RealType,Dimension> ImageType;
  typedef otb::Image<OutputPixelType,Dimension> OutputImageType;

  // Software Guide : EndCodeSnippet
 // Software Guide : BeginLatex
   //
   // The SIFTs obtained for the matching will be stored in vector
   // form inside a point set. So we need the following types:
   //
   // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  typedef itk::VariableLengthVector<RealType> RealVectorType;
  typedef itk::PointSet<RealVectorType,Dimension> PointSetType;

    // Software Guide : EndCodeSnippet
 // Software Guide : BeginLatex
   //
   // The filter for computing the SIFTs has a type defined as follows:
   //
   // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  typedef otb::SiftFastImageFilter<ImageType,PointSetType>
                                    ImageToSIFTKeyPointSetFilterType;

  // Software Guide : EndCodeSnippet
 // Software Guide : BeginLatex
   //
   // Although many choices for evaluating the distances during the
   // matching procedure exist, we choose here to use a simple
   // Euclidean distance. We can then define the type for the matching filter.
   //
   // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  typedef itk::Statistics::EuclideanDistance<RealVectorType> DistanceType;
  typedef otb::KeyPointSetsMatchingFilter<PointSetType, DistanceType>
                                      EuclideanDistanceMatchingFilterType;
    // Software Guide : EndCodeSnippet
  // Software Guide : BeginLatex
   //
   // The following types are needed for dealing with the matched points.
   //
   // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  typedef PointSetType::PointType PointType;
  typedef std::pair<PointType,PointType> MatchType;
  typedef std::vector<MatchType> MatchVectorType;
  typedef EuclideanDistanceMatchingFilterType::LandmarkListType LandmarkListType;

  typedef PointSetType::PointsContainer PointsContainerType;
  typedef PointsContainerType::Iterator PointsIteratorType;
  typedef PointSetType::PointDataContainer PointDataContainerType;
  typedef PointDataContainerType::Iterator PointDataIteratorType;

  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // We define the type for the image reader.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  typedef otb::ImageFileReader<ImageType> ReaderType;

  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // Two readers are instantiated : one for the fixed image, and one for the moving image.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  ReaderType::Pointer fixedReader = ReaderType::New();
  ReaderType::Pointer movingReader = ReaderType::New();

  fixedReader->SetFileName(argv[1]);
  movingReader->SetFileName(argv[2]);
  fixedReader->UpdateOutputInformation();
  movingReader->UpdateOutputInformation();

  // Software Guide : EndCodeSnippet
  // Software Guide : BeginLatex
  //
  // We will now instantiate the 2 SIFT filters and the filter used
  // for the matching of the points.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  ImageToSIFTKeyPointSetFilterType::Pointer filter1 =
                              ImageToSIFTKeyPointSetFilterType::New();
  ImageToSIFTKeyPointSetFilterType::Pointer filter2 =
                              ImageToSIFTKeyPointSetFilterType::New();
  EuclideanDistanceMatchingFilterType::Pointer euclideanMatcher =
                           EuclideanDistanceMatchingFilterType::New();
  // Software Guide : EndCodeSnippet
  // Software Guide : BeginLatex
  //
  // We plug the pipeline and set the parameters.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  double secondOrderThreshold = 0.5;
  bool useBackMatching = 0;

  filter1->SetInput(0, fixedReader->GetOutput() );
  filter1->SetNumberOfScales(3);
  filter2->SetInput(0, movingReader->GetOutput() );
  filter2->SetNumberOfScales(3);

  euclideanMatcher->SetInput1(filter1->GetOutput());
  euclideanMatcher->SetInput2(filter2->GetOutput());
  euclideanMatcher->SetDistanceThreshold(secondOrderThreshold);
  euclideanMatcher->SetUseBackMatching(useBackMatching);
  euclideanMatcher->Update();

  // Software Guide : EndCodeSnippet
  // Software Guide : BeginLatex
  //
  // The matched points will be stored into a landmark list.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  LandmarkListType::Pointer landmarkList;
  landmarkList = euclideanMatcher->GetOutput();

  // Software Guide : EndCodeSnippet
  MatchVectorType trueSecondOrder;

  for(LandmarkListType::Iterator it = landmarkList->Begin(); it != landmarkList->End();++it)
    {
      PointType point1 = it.Get()->GetPoint1();
      PointType point2 = it.Get()->GetPoint2();

      trueSecondOrder.push_back(MatchType(point1,point2));
    }

    // Displaying the matches
  typedef itk::RescaleIntensityImageFilter<ImageType, OutputImageType>
    PrintableFilterType;

  PrintableFilterType::Pointer printable1 = PrintableFilterType::New();
  PrintableFilterType::Pointer printable2 = PrintableFilterType::New();

  printable1->SetInput(fixedReader->GetOutput());
  printable1->SetOutputMinimum(0);
  printable1->SetOutputMaximum(255);
  printable1->Update();

  printable2->SetInput(movingReader->GetOutput());
  printable2->SetOutputMinimum(0);
  printable2->SetOutputMaximum(255);
  printable2->Update();

  typedef otb::Image<itk::RGBPixel<unsigned char>,2> RGBImageType;

  RGBImageType::Pointer rgbimage1 = RGBImageType::New();
  rgbimage1->SetRegions(printable1->GetOutput()->GetLargestPossibleRegion());
  rgbimage1->Allocate();
  itk::ImageRegionIterator<RGBImageType> outIt1(rgbimage1,rgbimage1->GetLargestPossibleRegion());
  itk::ImageRegionIterator<OutputImageType> inIt1(printable1->GetOutput(),printable1->GetOutput()->GetLargestPossibleRegion());
  outIt1.GoToBegin();
  inIt1.GoToBegin();
  while(!inIt1.IsAtEnd() && !outIt1.IsAtEnd())
    {
      itk::RGBPixel<unsigned char> pixel;
      pixel.SetRed(inIt1.Get());
      pixel.SetGreen(inIt1.Get());
      pixel.SetBlue(inIt1.Get());
      outIt1.Set(pixel);
      ++inIt1;
      ++outIt1;
    }

  RGBImageType::Pointer rgbimage2 = RGBImageType::New();
  rgbimage2->SetRegions(printable2->GetOutput()->GetLargestPossibleRegion());
  rgbimage2->Allocate();
  itk::ImageRegionIterator<RGBImageType> outIt2(rgbimage2,rgbimage2->GetLargestPossibleRegion());
  itk::ImageRegionIterator<OutputImageType> inIt2(printable2->GetOutput(),printable2->GetOutput()->GetLargestPossibleRegion());
  outIt2.GoToBegin();
  inIt2.GoToBegin();
  while(!inIt2.IsAtEnd() && !outIt2.IsAtEnd())
    {
      itk::RGBPixel<unsigned char> pixel;
      pixel.SetRed(inIt2.Get());
      pixel.SetGreen(inIt2.Get());
      pixel.SetBlue(inIt2.Get());
      outIt2.Set(pixel);
      ++inIt2;
      ++outIt2;
    }

  // Software Guide : BeginLatex
  //
  // The landmarks are used for building a deformation field. The
  // deformation field is an image of vectors created by the
  // \doxygen{itk}{DeformationFieldSource} class.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  typedef   itk::Vector< RealType, Dimension >    VectorType;
  typedef   otb::Image< VectorType,  Dimension >   DeformationFieldType;

  typedef itk::DeformationFieldSource<
                                DeformationFieldType
                                             >  DeformationSourceType;

  DeformationSourceType::Pointer deformer = DeformationSourceType::New();

  // Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
  //
  // The deformation field needs information about the extent and
  // spacing of the images on which it is defined.
  //
  // Software Guide : EndLatex
    // Software Guide : BeginCodeSnippet
  ImageType::ConstPointer fixedImage = fixedReader->GetOutput();

  deformer->SetOutputSpacing( fixedImage->GetSpacing() );
  deformer->SetOutputOrigin(  fixedImage->GetOrigin() );
  deformer->SetOutputRegion(  fixedImage->GetLargestPossibleRegion() );

  // Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
  //
  // We will need some intermediate variables in order to pass the
  // matched SIFTs to the deformation field source.
  //
  // Software Guide : EndLatex

  typedef DeformationSourceType::LandmarkContainerPointer
                                              LandmarkContainerPointer;
  typedef DeformationSourceType::LandmarkContainer
                                                 LandmarkContainerType;
  typedef DeformationSourceType::LandmarkPointType          LandmarkPointType;

  LandmarkContainerType::Pointer sourceLandmarks = LandmarkContainerType::New();
  LandmarkContainerType::Pointer targetLandmarks = LandmarkContainerType::New();

  LandmarkPointType sourcePoint;
  LandmarkPointType targetPoint;

// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
  //
  // We can now iterate through the list of matched points and store
  // them in the intermediate landmark sets.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  unsigned int pointId = 0;

    for(LandmarkListType::Iterator it = landmarkList->Begin(); it != landmarkList->End();++it)
    {
      PointType point1 = it.Get()->GetPoint1();
      PointType point2 = it.Get()->GetPoint2();

      sourcePoint[0] = point1[0];
      sourcePoint[1] = point1[1];

      targetPoint[0] = point2[0];
      targetPoint[1] = point2[1];

      sourceLandmarks->InsertElement( pointId, sourcePoint );
      targetLandmarks->InsertElement( pointId, targetPoint );

      ++pointId;
    }

// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
  //
  // We pass the landmarks to the deformer and we run it.
  //
  // Software Guide : EndLatex

  deformer->SetSourceLandmarks( sourceLandmarks.GetPointer() );
  deformer->SetTargetLandmarks( targetLandmarks.GetPointer() );

  deformer->UpdateLargestPossibleRegion();

  DeformationFieldType::ConstPointer deformationField = deformer->GetOutput();

  deformer->Update();

  // Software Guide : EndCodeSnippet

  ImageType::Pointer outdf = ImageType::New();
  outdf->SetRegions(fixedReader->GetOutput()->GetLargestPossibleRegion());
  outdf->Allocate();

  itk::ImageRegionIterator<ImageType> outIt(outdf,outdf->GetLargestPossibleRegion());

  itk::ImageRegionIterator<DeformationFieldType> inIt(deformer->GetOutput(),deformer->GetOutput()->GetLargestPossibleRegion());
  outIt.GoToBegin();
  inIt.GoToBegin();

  while(!inIt.IsAtEnd() && !outIt.IsAtEnd())
    {

    std::cout << inIt.Get() << std::endl;

      outIt.Set(inIt.Get()[1]);

      ++inIt;
      ++outIt;
    }

  typedef itk::RescaleIntensityImageFilter< ImageType,
                                         OutputImageType> RescaleType;

  RescaleType::Pointer rescaler = RescaleType::New();
  rescaler->SetInput( outdf );
  rescaler->SetOutputMinimum(0);
  rescaler->SetOutputMaximum(255);

  typedef otb::ImageFileWriter< OutputImageType > WriterType;
  WriterType::Pointer writer = WriterType::New();

  writer->SetInput( rescaler->GetOutput() );
  writer->SetFileName( argv[3] );
  writer->Update();

    // Software Guide : BeginLatex
  //
  // Figure~\ref{fig:SIFTDME} shows the result of applying the SIFT
  // disparity map estimation. Only the horizontal component of the
  // deformation is shown.
  //
  // \begin{figure}
  // \center
  // \includegraphics[width=0.40\textwidth]{ROISpot5.eps}
  // \includegraphics[width=0.40\textwidth]{ROISpot5Warped.eps}
  // \includegraphics[width=0.40\textwidth]{SIFTdeformationFieldOutput.eps}
  // \itkcaption[Deformation field from SIFT disparity map estimation]{From left
  // to right and top to bottom: fixed input image, moving image with a sinusoid deformation,
  // estimated deformation field in the horizontal direction.}
  // \label{fig:SIFTDME}
  // \end{figure}
  //
  // Software Guide : EndLatex

  return EXIT_SUCCESS;
}

<commit_msg>BUG: endcode snipped<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

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

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#ifdef __BORLANDC__
#define ITK_LEAN_AND_MEAN
#endif

//  Software Guide : BeginCommandLineArgs
//    INPUTS: {ROISpot5.png}, {ROISpot5Warped.png}
//    OUTPUTS: {SIFTdeformationFieldOutput.png}
//  Software Guide : EndCommandLineArgs

// Software Guide : BeginLatex
//
// This example demonstrates the use of the
// \doxygen{otb}{KeyPointSetsMatchingFilter} for disparity map
// estimation. The idea here is to match SIFTs extracted from both the
// fixed and the moving images. The use of SIFTs is demonstrated in
// section \ref{sec:SIFTDetector}. The
// \doxygen{otb}{NearestPointDeformationFieldGenerator} will be used
// to generate a deformation field by using nearest neighbor
// interpolation on the deformation values from the point set. More
// advanced methods for deformation field interpolation are also
// available.
//
// The first step toward the use of these filters is to include the proper header files.
//
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet

#include "otbKeyPointSetsMatchingFilter.h"
#include "otbSiftFastImageFilter.h"
#include "itkDeformationFieldSource.h"
#include "itkWarpImageFilter.h"

// Software Guide : EndCodeSnippet

#include "otbImage.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "itkRescaleIntensityImageFilter.h"
#include "itkPointSet.h"
#include "otbMultiToMonoChannelExtractROI.h"

int main (int argc, char* argv[])
{
  if(argc!= 4)
    {
      std::cerr <<"Usage: "<<argv[0];
      std::cerr<<"fixedFileName movingFileName fieldOutName" << std::endl;
      return EXIT_FAILURE;
    }

  const unsigned int Dimension = 2;

   // Software Guide : BeginLatex
   //
   // Then we must decide what pixel type to use for the image. We choose to do
   // all the computation in floating point precision and rescale the results
   // between 0 and 255 in order to export PNG images.
   //
   // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  typedef double        RealType;
  typedef unsigned char OutputPixelType;

  typedef otb::Image<RealType,Dimension> ImageType;
  typedef otb::Image<OutputPixelType,Dimension> OutputImageType;

  // Software Guide : EndCodeSnippet
 // Software Guide : BeginLatex
   //
   // The SIFTs obtained for the matching will be stored in vector
   // form inside a point set. So we need the following types:
   //
   // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  typedef itk::VariableLengthVector<RealType> RealVectorType;
  typedef itk::PointSet<RealVectorType,Dimension> PointSetType;

    // Software Guide : EndCodeSnippet
 // Software Guide : BeginLatex
   //
   // The filter for computing the SIFTs has a type defined as follows:
   //
   // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  typedef otb::SiftFastImageFilter<ImageType,PointSetType>
                                    ImageToSIFTKeyPointSetFilterType;

  // Software Guide : EndCodeSnippet
 // Software Guide : BeginLatex
   //
   // Although many choices for evaluating the distances during the
   // matching procedure exist, we choose here to use a simple
   // Euclidean distance. We can then define the type for the matching filter.
   //
   // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  typedef itk::Statistics::EuclideanDistance<RealVectorType> DistanceType;
  typedef otb::KeyPointSetsMatchingFilter<PointSetType, DistanceType>
                                      EuclideanDistanceMatchingFilterType;
    // Software Guide : EndCodeSnippet
  // Software Guide : BeginLatex
   //
   // The following types are needed for dealing with the matched points.
   //
   // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  typedef PointSetType::PointType PointType;
  typedef std::pair<PointType,PointType> MatchType;
  typedef std::vector<MatchType> MatchVectorType;
  typedef EuclideanDistanceMatchingFilterType::LandmarkListType LandmarkListType;

  typedef PointSetType::PointsContainer PointsContainerType;
  typedef PointsContainerType::Iterator PointsIteratorType;
  typedef PointSetType::PointDataContainer PointDataContainerType;
  typedef PointDataContainerType::Iterator PointDataIteratorType;

  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // We define the type for the image reader.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  typedef otb::ImageFileReader<ImageType> ReaderType;

  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // Two readers are instantiated : one for the fixed image, and one for the moving image.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  ReaderType::Pointer fixedReader = ReaderType::New();
  ReaderType::Pointer movingReader = ReaderType::New();

  fixedReader->SetFileName(argv[1]);
  movingReader->SetFileName(argv[2]);
  fixedReader->UpdateOutputInformation();
  movingReader->UpdateOutputInformation();

  // Software Guide : EndCodeSnippet
  // Software Guide : BeginLatex
  //
  // We will now instantiate the 2 SIFT filters and the filter used
  // for the matching of the points.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  ImageToSIFTKeyPointSetFilterType::Pointer filter1 =
                              ImageToSIFTKeyPointSetFilterType::New();
  ImageToSIFTKeyPointSetFilterType::Pointer filter2 =
                              ImageToSIFTKeyPointSetFilterType::New();
  EuclideanDistanceMatchingFilterType::Pointer euclideanMatcher =
                           EuclideanDistanceMatchingFilterType::New();
  // Software Guide : EndCodeSnippet
  // Software Guide : BeginLatex
  //
  // We plug the pipeline and set the parameters.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  double secondOrderThreshold = 0.5;
  bool useBackMatching = 0;

  filter1->SetInput(0, fixedReader->GetOutput() );
  filter1->SetNumberOfScales(3);
  filter2->SetInput(0, movingReader->GetOutput() );
  filter2->SetNumberOfScales(3);

  euclideanMatcher->SetInput1(filter1->GetOutput());
  euclideanMatcher->SetInput2(filter2->GetOutput());
  euclideanMatcher->SetDistanceThreshold(secondOrderThreshold);
  euclideanMatcher->SetUseBackMatching(useBackMatching);
  euclideanMatcher->Update();

  // Software Guide : EndCodeSnippet
  // Software Guide : BeginLatex
  //
  // The matched points will be stored into a landmark list.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  LandmarkListType::Pointer landmarkList;
  landmarkList = euclideanMatcher->GetOutput();

  // Software Guide : EndCodeSnippet
  MatchVectorType trueSecondOrder;

  for(LandmarkListType::Iterator it = landmarkList->Begin(); it != landmarkList->End();++it)
    {
      PointType point1 = it.Get()->GetPoint1();
      PointType point2 = it.Get()->GetPoint2();

      trueSecondOrder.push_back(MatchType(point1,point2));
    }

    // Displaying the matches
  typedef itk::RescaleIntensityImageFilter<ImageType, OutputImageType>
    PrintableFilterType;

  PrintableFilterType::Pointer printable1 = PrintableFilterType::New();
  PrintableFilterType::Pointer printable2 = PrintableFilterType::New();

  printable1->SetInput(fixedReader->GetOutput());
  printable1->SetOutputMinimum(0);
  printable1->SetOutputMaximum(255);
  printable1->Update();

  printable2->SetInput(movingReader->GetOutput());
  printable2->SetOutputMinimum(0);
  printable2->SetOutputMaximum(255);
  printable2->Update();

  typedef otb::Image<itk::RGBPixel<unsigned char>,2> RGBImageType;

  RGBImageType::Pointer rgbimage1 = RGBImageType::New();
  rgbimage1->SetRegions(printable1->GetOutput()->GetLargestPossibleRegion());
  rgbimage1->Allocate();
  itk::ImageRegionIterator<RGBImageType> outIt1(rgbimage1,rgbimage1->GetLargestPossibleRegion());
  itk::ImageRegionIterator<OutputImageType> inIt1(printable1->GetOutput(),printable1->GetOutput()->GetLargestPossibleRegion());
  outIt1.GoToBegin();
  inIt1.GoToBegin();
  while(!inIt1.IsAtEnd() && !outIt1.IsAtEnd())
    {
      itk::RGBPixel<unsigned char> pixel;
      pixel.SetRed(inIt1.Get());
      pixel.SetGreen(inIt1.Get());
      pixel.SetBlue(inIt1.Get());
      outIt1.Set(pixel);
      ++inIt1;
      ++outIt1;
    }

  RGBImageType::Pointer rgbimage2 = RGBImageType::New();
  rgbimage2->SetRegions(printable2->GetOutput()->GetLargestPossibleRegion());
  rgbimage2->Allocate();
  itk::ImageRegionIterator<RGBImageType> outIt2(rgbimage2,rgbimage2->GetLargestPossibleRegion());
  itk::ImageRegionIterator<OutputImageType> inIt2(printable2->GetOutput(),printable2->GetOutput()->GetLargestPossibleRegion());
  outIt2.GoToBegin();
  inIt2.GoToBegin();
  while(!inIt2.IsAtEnd() && !outIt2.IsAtEnd())
    {
      itk::RGBPixel<unsigned char> pixel;
      pixel.SetRed(inIt2.Get());
      pixel.SetGreen(inIt2.Get());
      pixel.SetBlue(inIt2.Get());
      outIt2.Set(pixel);
      ++inIt2;
      ++outIt2;
    }

  // Software Guide : BeginLatex
  //
  // The landmarks are used for building a deformation field. The
  // deformation field is an image of vectors created by the
  // \doxygen{itk}{DeformationFieldSource} class.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet

  typedef   itk::Vector< RealType, Dimension >    VectorType;
  typedef   otb::Image< VectorType,  Dimension >   DeformationFieldType;

  typedef itk::DeformationFieldSource<
                                DeformationFieldType
                                             >  DeformationSourceType;

  DeformationSourceType::Pointer deformer = DeformationSourceType::New();

  // Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
  //
  // The deformation field needs information about the extent and
  // spacing of the images on which it is defined.
  //
  // Software Guide : EndLatex
    // Software Guide : BeginCodeSnippet
  ImageType::ConstPointer fixedImage = fixedReader->GetOutput();

  deformer->SetOutputSpacing( fixedImage->GetSpacing() );
  deformer->SetOutputOrigin(  fixedImage->GetOrigin() );
  deformer->SetOutputRegion(  fixedImage->GetLargestPossibleRegion() );

  // Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
  //
  // We will need some intermediate variables in order to pass the
  // matched SIFTs to the deformation field source.
  //
  // Software Guide : EndLatex
  // Software Guide : BeginCodeSnippet
  typedef DeformationSourceType::LandmarkContainerPointer
                                              LandmarkContainerPointer;
  typedef DeformationSourceType::LandmarkContainer
                                                 LandmarkContainerType;
  typedef DeformationSourceType::LandmarkPointType          LandmarkPointType;

  LandmarkContainerType::Pointer sourceLandmarks = LandmarkContainerType::New();
  LandmarkContainerType::Pointer targetLandmarks = LandmarkContainerType::New();

  LandmarkPointType sourcePoint;
  LandmarkPointType targetPoint;

// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
  //
  // We can now iterate through the list of matched points and store
  // them in the intermediate landmark sets.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  unsigned int pointId = 0;

    for(LandmarkListType::Iterator it = landmarkList->Begin(); it != landmarkList->End();++it)
    {
      PointType point1 = it.Get()->GetPoint1();
      PointType point2 = it.Get()->GetPoint2();

      sourcePoint[0] = point1[0];
      sourcePoint[1] = point1[1];

      targetPoint[0] = point2[0];
      targetPoint[1] = point2[1];

      sourceLandmarks->InsertElement( pointId, sourcePoint );
      targetLandmarks->InsertElement( pointId, targetPoint );

      ++pointId;
    }

// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
  //
  // We pass the landmarks to the deformer and we run it.
  //
  // Software Guide : EndLatex

  deformer->SetSourceLandmarks( sourceLandmarks.GetPointer() );
  deformer->SetTargetLandmarks( targetLandmarks.GetPointer() );

  deformer->UpdateLargestPossibleRegion();

  DeformationFieldType::ConstPointer deformationField = deformer->GetOutput();

  deformer->Update();

  // Software Guide : EndCodeSnippet

  ImageType::Pointer outdf = ImageType::New();
  outdf->SetRegions(fixedReader->GetOutput()->GetLargestPossibleRegion());
  outdf->Allocate();

  itk::ImageRegionIterator<ImageType> outIt(outdf,outdf->GetLargestPossibleRegion());

  itk::ImageRegionIterator<DeformationFieldType> inIt(deformer->GetOutput(),deformer->GetOutput()->GetLargestPossibleRegion());
  outIt.GoToBegin();
  inIt.GoToBegin();

  while(!inIt.IsAtEnd() && !outIt.IsAtEnd())
    {

    std::cout << inIt.Get() << std::endl;

      outIt.Set(inIt.Get()[1]);

      ++inIt;
      ++outIt;
    }

  typedef itk::RescaleIntensityImageFilter< ImageType,
                                         OutputImageType> RescaleType;

  RescaleType::Pointer rescaler = RescaleType::New();
  rescaler->SetInput( outdf );
  rescaler->SetOutputMinimum(0);
  rescaler->SetOutputMaximum(255);

  typedef otb::ImageFileWriter< OutputImageType > WriterType;
  WriterType::Pointer writer = WriterType::New();

  writer->SetInput( rescaler->GetOutput() );
  writer->SetFileName( argv[3] );
  writer->Update();

    // Software Guide : BeginLatex
  //
  // Figure~\ref{fig:SIFTDME} shows the result of applying the SIFT
  // disparity map estimation. Only the horizontal component of the
  // deformation is shown.
  //
  // \begin{figure}
  // \center
  // \includegraphics[width=0.40\textwidth]{ROISpot5.eps}
  // \includegraphics[width=0.40\textwidth]{ROISpot5Warped.eps}
  // \includegraphics[width=0.40\textwidth]{SIFTdeformationFieldOutput.eps}
  // \itkcaption[Deformation field from SIFT disparity map estimation]{From left
  // to right and top to bottom: fixed input image, moving image with a sinusoid deformation,
  // estimated deformation field in the horizontal direction.}
  // \label{fig:SIFTDME}
  // \end{figure}
  //
  // Software Guide : EndLatex

  return EXIT_SUCCESS;
}

<|endoftext|>