<commit_before>/*************************************************************************
 *
 *  $RCSfile: tbxdraw.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2004-07-06 13:07:44 $
 *
 *  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 _TBXDRAW_HXX
#define _TBXDRAW_HXX

// include ---------------------------------------------------------------

#ifndef _SFXTBXMGR_HXX //autogen
#include <sfx2/tbxmgr.hxx>
#endif
#ifndef _SFXTBXCTRL_HXX //autogen
#include <sfx2/tbxctrl.hxx>
#endif

// class SvxPopupWindowTbxMgr --------------------------------------------

class SvxPopupWindowTbxMgr : public SfxPopupWindow
{
//  SfxToolBoxManager   aTbx;
    void*               pNiemalsDenPointerAufDieErzeugendeToolBoxMerken; // MI!
    ResId               aRIdWinTemp;
    ResId               aRIdTbxTemp;

    Link                aTbxClickHdl;

    DECL_LINK( TbxSelectHdl, ToolBox*);
    DECL_LINK( TbxClickHdl, ToolBox*);

public:
    SvxPopupWindowTbxMgr(   USHORT nId,
                            SfxToolBoxControl* pTbxCtl,
                            ResId aRIdWin,
                            ResId aRIdTbx );
    SvxPopupWindowTbxMgr(   USHORT nId,
                            WindowAlign eAlign,
                            ResId aRIdWin,
                            ResId aRIdTbx );
    ~SvxPopupWindowTbxMgr();

    virtual void                StateChanged( USHORT nSID, SfxItemState eState,
                                              const SfxPoolItem* pState);
    virtual SfxPopupWindow*     Clone() const;
    virtual void                PopupModeEnd();

    void                        StartSelection();
//  inline SfxToolBoxManager&   GetTbxMgr() { return aTbx; }

    // toolbox click or execute may chage the default selection in the tools toolbox
    virtual void                UserEvent( ULONG nEvent, void* pEventData );
};

#endif      // _TBX_DRAW_HXX

<commit_msg>INTEGRATION: CWS fwkbugfix04 (1.3.332); FILE MERGED 2004/12/14 22:41:29 mba 1.3.332.1: tbxmgr.hxx obsolete<commit_after>/*************************************************************************
 *
 *  $RCSfile: tbxdraw.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: kz $ $Date: 2005-01-18 15:31:16 $
 *
 *  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 _TBXDRAW_HXX
#define _TBXDRAW_HXX

// include ---------------------------------------------------------------

#ifndef _SFXTBXCTRL_HXX //autogen
#include <sfx2/tbxctrl.hxx>
#endif

// class SvxPopupWindowTbxMgr --------------------------------------------

class SvxPopupWindowTbxMgr : public SfxPopupWindow
{
//  SfxToolBoxManager   aTbx;
    void*               pNiemalsDenPointerAufDieErzeugendeToolBoxMerken; // MI!
    ResId               aRIdWinTemp;
    ResId               aRIdTbxTemp;

    Link                aTbxClickHdl;

    DECL_LINK( TbxSelectHdl, ToolBox*);
    DECL_LINK( TbxClickHdl, ToolBox*);

public:
    SvxPopupWindowTbxMgr(   USHORT nId,
                            SfxToolBoxControl* pTbxCtl,
                            ResId aRIdWin,
                            ResId aRIdTbx );
    SvxPopupWindowTbxMgr(   USHORT nId,
                            WindowAlign eAlign,
                            ResId aRIdWin,
                            ResId aRIdTbx );
    ~SvxPopupWindowTbxMgr();

    virtual void                StateChanged( USHORT nSID, SfxItemState eState,
                                              const SfxPoolItem* pState);
    virtual SfxPopupWindow*     Clone() const;
    virtual void                PopupModeEnd();

    void                        StartSelection();
//  inline SfxToolBoxManager&   GetTbxMgr() { return aTbx; }

    // toolbox click or execute may chage the default selection in the tools toolbox
    virtual void                UserEvent( ULONG nEvent, void* pEventData );
};

#endif      // _TBX_DRAW_HXX

<|endoftext|>


<commit_before><commit_msg>convert sw/inc/swbaslnk.hxx from String to OUString<commit_after><|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <iomanip>
#include <istream>
#include <sstream>
#include <iostream>
#include <string>

#include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>
#include <boost/spirit/include/phoenix_object.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/variant/recursive_variant.hpp>

#include <boost/spirit/include/classic_position_iterator.hpp>

#include "parser/SpiritParser.hpp"
#include "lexer/SpiritLexer.hpp"

#include "ast/Program.hpp"

namespace qi = boost::spirit::qi;

using namespace eddic;

std::string readI(const std::string& file){
    std::ifstream in(file.c_str());
    in.unsetf(std::ios::skipws);
    std::string storage;

    std::copy(
            std::istream_iterator<char>(in),
            std::istream_iterator<char>(),
            std::back_inserter(storage));

    return storage;
}

template <typename Iterator, typename Lexer>
struct EddiGrammar : qi::grammar<Iterator, ASTProgram()> {
    EddiGrammar(const Lexer& lexer) : EddiGrammar::base_type(program, "EDDI Grammar") {
        /*
        value = additiveValue.alias();

        additiveValue =
        multiplicativeValue
        >> *(   (tok.addition > multiplicativeValue)
        |   (tok.subtraction > multiplicativeValue)
        );

        multiplicativeValue =
        unaryValue
        >> *(   (tok.multiplication > unaryValue)
        |   (tok.division > unaryValue)
        |   (tok.modulo > unaryValue)
        );

        //TODO Support + - primaryValue
        unaryValue =
        primaryValue.alias();

        primaryValue = constant | tok.word | (tok.left_parenth > value > tok.right_parenth);

        globalDeclaration %= tok.word >> identifier >> tok.assign >> constant;
        declaration = tok.word >> tok.word >> tok.assign >> value;
        assignment = tok.word >> tok.assign >> value;

        binary_operator = tok.equals | tok.not_equals | tok.greater | tok.less | tok.greater_equals | tok.less_equals;
        condition = (value >> binary_operator >> value) | tok.true_ | tok.false_;

        while_ =
        tok.while_ >> tok.left_parenth >> condition >> tok.right_parenth >> tok.left_brace
        >> *(instruction)
        >> tok.right_brace;

        for_ =
        tok.for_ >> tok.left_parenth >> -declaration >> tok.stop >> -condition >> tok.stop >> -repeatable_instruction >> tok.right_parenth >> tok.left_brace
        >> (*instruction)
        >> tok.right_brace;

        foreach_ =
        tok.foreach_ >> tok.left_parenth >> tok.word >> tok.word >> tok.from_ >> tok.integer >> tok.to_ >> tok.integer >> tok.right_parenth >> tok.left_brace
        >> *(instruction)
        >> tok.right_brace;

        elseif_ =
        tok.else_ >> tok.if_ >> tok.left_parenth >> condition >> tok.right_parenth >> tok.left_brace
        >> *(instruction)
        >> tok.right_brace;

        else_ =
        tok.else_ >> tok.left_brace
        >> *(instruction)
        >> tok.right_brace;

        if_ =
        tok.if_ >> tok.left_parenth >> condition >> tok.right_parenth >> tok.left_brace
        >> *(instruction)
        >> tok.right_brace
        >> *(elseif_)
        >> -(else_);

        functionCall =
        tok.word >> tok.left_parenth
        >> -( value >> *( tok.comma >> value))
            >> tok.right_parenth;

        repeatable_instruction = assignment | declaration | swap;

        instruction =
            ((assignment | declaration | functionCall | swap) >> tok.stop)
            | if_ | while_ | for_ | foreach_;

        function %=
            tok.word >> identifier >> tok.left_parenth
            >> -( arg >> *( tok.comma >> arg))
            >> tok.right_parenth >> tok.left_brace
            >> *(instruction)
            >> tok.right_brace;*/

        integer %=
                qi::eps
            >>  lexer.integer;

        litteral %=
                qi::eps
            >> lexer.litteral;

        constant %=
                qi::eps
            >>  (integer | litteral);

        value %=
                qi::eps
            >>  (integer | litteral);

        globalDeclaration %=
                lexer.word
            >>  lexer.word
            >>  lexer.assign
            >>  constant
            >>  lexer.stop;

        functionCall %=
                lexer.word
            >>  lexer.left_parenth
            >>  -( value >> *( lexer.comma >> value))
            >>  lexer.right_parenth;

        swap %=
                lexer.word
            >>  lexer.swap
            >>  lexer.word;

        instruction %=
                (functionCall | swap)
            >>  lexer.stop;

        arg %=
                lexer.word
            >>  lexer.word;

        function %=
                lexer.word
            >>  lexer.word
            >>  lexer.left_parenth
            >>  -( arg >> *( lexer.comma >> arg))
            >>  lexer.right_parenth
            >>  lexer.left_brace
            >>  *(instruction)
            >>  lexer.right_brace;

        program %=
                qi::eps
            >>  *(globalDeclaration | function);

        //Name the rules
        globalDeclaration.name("EDDI global variable");
        function.name("EDDI function declaration");
        program.name("EDDI program");
   }

   qi::rule<Iterator, ASTProgram()> program;
   qi::rule<Iterator, GlobalVariableDeclaration()> globalDeclaration;
   qi::rule<Iterator, FunctionDeclaration()> function;
   qi::rule<Iterator, FunctionParameter()> arg;

   qi::rule<Iterator, ASTInstruction()> instruction;
   qi::rule<Iterator, ASTSwap()> swap;
   qi::rule<Iterator, ASTFunctionCall()> functionCall;

   qi::rule<Iterator, ASTValue()> value;
   qi::rule<Iterator, ASTValue()> constant;
   qi::rule<Iterator, ASTInteger()> integer;
   qi::rule<Iterator, ASTLitteral()> litteral;

   /*qi::rule<Iterator> value;
   qi::rule<Iterator> additiveValue;
   qi::rule<Iterator> multiplicativeValue;
   qi::rule<Iterator> unaryValue;
   qi::rule<Iterator> primaryValue;
   qi::rule<Iterator> constant;

   qi::rule<Iterator> repeatable_instruction;
   qi::rule<Iterator> declaration;
   qi::rule<Iterator> assignment;
   qi::rule<Iterator> condition;
   qi::rule<Iterator> binary_operator;

   qi::rule<Iterator> while_;
   qi::rule<Iterator> for_;
   qi::rule<Iterator> foreach_;
   qi::rule<Iterator> if_;
   qi::rule<Iterator> else_;
   qi::rule<Iterator> elseif_;*/
};

#include <boost/exception/all.hpp>

bool SpiritParser::parse(const std::string& file, ASTProgram& program){
    std::string contents = readI(file);

    pos_iterator_type position_begin(contents.begin(), contents.end(), file);
    pos_iterator_type position_end;

    SimpleLexer<lexer_type> lexer;
    EddiGrammar<lexer_type::iterator_type, SimpleLexer<lexer_type>> grammar(lexer);

    try {
        bool r = lex::tokenize_and_parse(position_begin, position_end, lexer, grammar, program);

        if(r && position_begin == position_end) {
            std::cout << "Parsing passed" << std::endl;

            return true;
        } else {
            std::cout << "Parsing failed" << std::endl;
            const spirit::classic::file_position_base<std::string>& pos = position_begin.get_position();
            std::cout <<
                "Error at file " << pos.file << " line " << pos.line << " column " << pos.column << std::endl <<
                "'" << position_begin.get_currentline() << "'" << std::endl <<
                std::setw(pos.column) << " " << "^- here";

            return false;
        }
    } catch (const qi::expectation_failure<lexer_type::iterator_type>& exception) {
        std::cout << "Parsing failed" << std::endl;

        //TODO Improve to get information from exception
        const spirit::classic::file_position_base<std::string>& pos = position_begin.get_position();

        std::cout <<
            "Error at file " << pos.file << " line " << pos.line << " column " << pos.column << " Expecting " << exception.what_ << std::endl <<
            "'" << position_begin.get_currentline() << "'" << std::endl <<
            std::setw(pos.column) << " " << "^- here" << std::endl;

        return false;
    }
}
<commit_msg>Cleanup<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <iomanip>
#include <istream>
#include <sstream>
#include <iostream>
#include <string>

#include <boost/config/warning_disable.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_fusion.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>
#include <boost/spirit/include/phoenix_object.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/variant/recursive_variant.hpp>

#include <boost/spirit/include/classic_position_iterator.hpp>

#include "parser/SpiritParser.hpp"
#include "lexer/SpiritLexer.hpp"

#include "ast/Program.hpp"

namespace qi = boost::spirit::qi;

using namespace eddic;

std::string readI(const std::string& file){
    std::ifstream in(file.c_str());
    in.unsetf(std::ios::skipws);
    std::string storage;

    std::copy(
            std::istream_iterator<char>(in),
            std::istream_iterator<char>(),
            std::back_inserter(storage));

    return storage;
}

template <typename Iterator, typename Lexer>
struct EddiGrammar : qi::grammar<Iterator, ASTProgram()> {
    EddiGrammar(const Lexer& lexer) : EddiGrammar::base_type(program, "EDDI Grammar") {
        /*
        value = additiveValue.alias();

        additiveValue =
        multiplicativeValue
        >> *(   (tok.addition > multiplicativeValue)
        |   (tok.subtraction > multiplicativeValue)
        );

        multiplicativeValue =
        unaryValue
        >> *(   (tok.multiplication > unaryValue)
        |   (tok.division > unaryValue)
        |   (tok.modulo > unaryValue)
        );

        //TODO Support + - primaryValue
        unaryValue =
        primaryValue.alias();

        primaryValue = constant | tok.word | (tok.left_parenth > value > tok.right_parenth);

        globalDeclaration %= tok.word >> identifier >> tok.assign >> constant;
        declaration = tok.word >> tok.word >> tok.assign >> value;
        assignment = tok.word >> tok.assign >> value;

        binary_operator = tok.equals | tok.not_equals | tok.greater | tok.less | tok.greater_equals | tok.less_equals;
        condition = (value >> binary_operator >> value) | tok.true_ | tok.false_;

        while_ =
        tok.while_ >> tok.left_parenth >> condition >> tok.right_parenth >> tok.left_brace
        >> *(instruction)
        >> tok.right_brace;

        for_ =
        tok.for_ >> tok.left_parenth >> -declaration >> tok.stop >> -condition >> tok.stop >> -repeatable_instruction >> tok.right_parenth >> tok.left_brace
        >> (*instruction)
        >> tok.right_brace;

        foreach_ =
        tok.foreach_ >> tok.left_parenth >> tok.word >> tok.word >> tok.from_ >> tok.integer >> tok.to_ >> tok.integer >> tok.right_parenth >> tok.left_brace
        >> *(instruction)
        >> tok.right_brace;

        elseif_ =
        tok.else_ >> tok.if_ >> tok.left_parenth >> condition >> tok.right_parenth >> tok.left_brace
        >> *(instruction)
        >> tok.right_brace;

        else_ =
        tok.else_ >> tok.left_brace
        >> *(instruction)
        >> tok.right_brace;

        if_ =
        tok.if_ >> tok.left_parenth >> condition >> tok.right_parenth >> tok.left_brace
        >> *(instruction)
        >> tok.right_brace
        >> *(elseif_)
        >> -(else_);

        functionCall =
        tok.word >> tok.left_parenth
        >> -( value >> *( tok.comma >> value))
            >> tok.right_parenth;

        repeatable_instruction = assignment | declaration | swap;

        instruction =
            ((assignment | declaration | functionCall | swap) >> tok.stop)
            | if_ | while_ | for_ | foreach_;*/

        integer %=
                qi::eps
            >>  lexer.integer;

        litteral %=
                qi::eps
            >> lexer.litteral;

        constant %=
                qi::eps
            >>  (integer | litteral);

        value %=
                qi::eps
            >>  (integer | litteral);

        globalDeclaration %=
                lexer.word
            >>  lexer.word
            >>  lexer.assign
            >>  constant
            >>  lexer.stop;

        functionCall %=
                lexer.word
            >>  lexer.left_parenth
            >>  -( value >> *( lexer.comma >> value))
            >>  lexer.right_parenth;

        swap %=
                lexer.word
            >>  lexer.swap
            >>  lexer.word;

        instruction %=
                (functionCall | swap)
            >>  lexer.stop;

        arg %=
                lexer.word
            >>  lexer.word;

        function %=
                lexer.word
            >>  lexer.word
            >>  lexer.left_parenth
            >>  -( arg >> *( lexer.comma >> arg))
            >>  lexer.right_parenth
            >>  lexer.left_brace
            >>  *(instruction)
            >>  lexer.right_brace;

        program %=
                qi::eps
            >>  *(globalDeclaration | function);

        //Name the rules
        globalDeclaration.name("EDDI global variable");
        function.name("EDDI function declaration");
        program.name("EDDI program");
   }

   qi::rule<Iterator, ASTProgram()> program;
   qi::rule<Iterator, GlobalVariableDeclaration()> globalDeclaration;
   qi::rule<Iterator, FunctionDeclaration()> function;
   qi::rule<Iterator, FunctionParameter()> arg;

   qi::rule<Iterator, ASTInstruction()> instruction;
   qi::rule<Iterator, ASTSwap()> swap;
   qi::rule<Iterator, ASTFunctionCall()> functionCall;

   qi::rule<Iterator, ASTValue()> value;
   qi::rule<Iterator, ASTValue()> constant;
   qi::rule<Iterator, ASTInteger()> integer;
   qi::rule<Iterator, ASTLitteral()> litteral;

   /*qi::rule<Iterator> value;
   qi::rule<Iterator> additiveValue;
   qi::rule<Iterator> multiplicativeValue;
   qi::rule<Iterator> unaryValue;
   qi::rule<Iterator> primaryValue;
   qi::rule<Iterator> constant;

   qi::rule<Iterator> repeatable_instruction;
   qi::rule<Iterator> declaration;
   qi::rule<Iterator> assignment;
   qi::rule<Iterator> condition;
   qi::rule<Iterator> binary_operator;

   qi::rule<Iterator> while_;
   qi::rule<Iterator> for_;
   qi::rule<Iterator> foreach_;
   qi::rule<Iterator> if_;
   qi::rule<Iterator> else_;
   qi::rule<Iterator> elseif_;*/
};

#include <boost/exception/all.hpp>

bool SpiritParser::parse(const std::string& file, ASTProgram& program){
    std::string contents = readI(file);

    pos_iterator_type position_begin(contents.begin(), contents.end(), file);
    pos_iterator_type position_end;

    SimpleLexer<lexer_type> lexer;
    EddiGrammar<lexer_type::iterator_type, SimpleLexer<lexer_type>> grammar(lexer);

    try {
        bool r = lex::tokenize_and_parse(position_begin, position_end, lexer, grammar, program);

        if(r && position_begin == position_end) {
            std::cout << "Parsing passed" << std::endl;

            return true;
        } else {
            std::cout << "Parsing failed" << std::endl;
            const spirit::classic::file_position_base<std::string>& pos = position_begin.get_position();
            std::cout <<
                "Error at file " << pos.file << " line " << pos.line << " column " << pos.column << std::endl <<
                "'" << position_begin.get_currentline() << "'" << std::endl <<
                std::setw(pos.column) << " " << "^- here";

            return false;
        }
    } catch (const qi::expectation_failure<lexer_type::iterator_type>& exception) {
        std::cout << "Parsing failed" << std::endl;

        //TODO Improve to get information from exception
        const spirit::classic::file_position_base<std::string>& pos = position_begin.get_position();

        std::cout <<
            "Error at file " << pos.file << " line " << pos.line << " column " << pos.column << " Expecting " << exception.what_ << std::endl <<
            "'" << position_begin.get_currentline() << "'" << std::endl <<
            std::setw(pos.column) << " " << "^- here" << std::endl;

        return false;
    }
}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include "parser/ValueGrammar.hpp"
#include "lexer/adapttokens.hpp"
#include "lexer/position.hpp"

using namespace eddic;

parser::ValueGrammar::ValueGrammar(const lexer::Lexer& lexer, const lexer::pos_iterator_type& position_begin) :
        ValueGrammar::base_type(value, "Value Grammar"),
        type(lexer, position_begin),
        position_begin(position_begin){

    /* Match operators into symbols */
    //TODO Find a way to avoid duplication of these things
    additive_op.add
        ("+", ast::Operator::ADD)
        ("-", ast::Operator::SUB)
        ;

    multiplicative_op.add
        ("/", ast::Operator::DIV)
        ("*", ast::Operator::MUL)
        ("%", ast::Operator::MOD)
        ;

    relational_op.add
        (">=", ast::Operator::GREATER_EQUALS)
        (">", ast::Operator::GREATER)
        ("<=", ast::Operator::LESS_EQUALS)
        ("<", ast::Operator::LESS)
        ("!=", ast::Operator::NOT_EQUALS)
        ("==", ast::Operator::EQUALS)
        ;

    logical_and_op.add
        ("&&", ast::Operator::AND)
        ;

    logical_or_op.add
        ("||", ast::Operator::OR)
        ;

    suffix_op.add
        ("++", ast::Operator::INC)
        ("--", ast::Operator::DEC)
        ;

    prefix_op.add
        ("++", ast::Operator::INC)
        ("--", ast::Operator::DEC)
        ;

    builtin_op.add
        ("size", ast::BuiltinType::SIZE)
        ("length", ast::BuiltinType::LENGTH)
        ;

    //TODO Use unary_op symbols and use a UnaryValue to represent plus and minus for a value

    /* Define values */

    value = logicalOrValue.alias();

    logicalOrValue %=
            qi::position(position_begin)
        >>  logicalAndValue
        >>  *(qi::adapttokens[logical_or_op] > logicalAndValue);

    logicalAndValue %=
            qi::position(position_begin)
        >>  relationalValue
        >>  *(qi::adapttokens[logical_and_op] > relationalValue);

    relationalValue %=
            qi::position(position_begin)
        >>  additiveValue
        >>  *(qi::adapttokens[relational_op] > additiveValue);

    additiveValue %=
            qi::position(position_begin)
        >>  multiplicativeValue
        >>  *(qi::adapttokens[additive_op] > multiplicativeValue);

    multiplicativeValue %=
            qi::position(position_begin)
        >>  unaryValue
        >>  *(qi::adapttokens[multiplicative_op] > unaryValue);

    unaryValue %=
            negatedValue
        |   plusValue
        |   castValue
        |   primaryValue;

    negatedValue =
            lexer.subtraction
         >> primaryValue;

    negatedConstantValue =
            lexer.subtraction
         >> integer;

    plusValue %=
            lexer.addition
         >> primaryValue;

    castValue %=
            qi::position(position_begin)
        >>  lexer.left_parenth
        >>  type.type
        >>  lexer.right_parenth
        >>  primaryValue;

    primaryValue =
            assignment
        |   integer_suffix
        |   integer
        |   float_
        |   litteral
        |   builtin_operator
        |   functionCall
        |   prefix_operation
        |   suffix_operation
        |   arrayValue
        |   variable_value
        |   struct_value
        |   true_
        |   false_
        |   (lexer.left_parenth >> value > lexer.right_parenth);

    true_ %=
            qi::eps
        >>  lexer.true_;

    false_ %=
            qi::eps
        >>  lexer.false_;

    integer %=
            qi::eps
        >>  lexer.integer;

    integer_suffix %=
            qi::eps
        >>  lexer.integer
        >>  lexer.identifier;

    float_ %=
            qi::eps
        >>  lexer.float_;

    variable_value %=
            qi::position(position_begin)
        >>  lexer.identifier;

    struct_value %=
            qi::position(position_begin)
        >>  lexer.identifier
        >>  lexer.dot
        >>  lexer.identifier;

    arrayValue %=
            qi::position(position_begin)
        >>  lexer.identifier
        >>  lexer.left_bracket
        >>  value
        >>  lexer.right_bracket;

    litteral %=
            qi::eps
        >> lexer.litteral;

    constant =
            negatedConstantValue
        |   integer
        |   litteral;

    builtin_operator %=
            qi::position(position_begin)
        >>  qi::adapttokens[builtin_op]
        >>  lexer.left_parenth
        >>  -( value >> *( lexer.comma > value))
        >   lexer.right_parenth;

    functionCall %=
            qi::position(position_begin)
        >>  lexer.identifier
        >>  lexer.left_parenth
        >>  -( value >> *( lexer.comma > value))
        >   lexer.right_parenth;

    assignment %=
            qi::position(position_begin)
        >>  lexer.identifier
        >>  lexer.assign
        >>  value;

    prefix_operation %=
            qi::position(position_begin)
        >>  qi::adapttokens[prefix_op]
        >>  lexer.identifier;

    suffix_operation %=
            qi::position(position_begin)
        >>  lexer.identifier
        >>  qi::adapttokens[suffix_op];
}
<commit_msg>Fix the order of values<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include "parser/ValueGrammar.hpp"
#include "lexer/adapttokens.hpp"
#include "lexer/position.hpp"

using namespace eddic;

parser::ValueGrammar::ValueGrammar(const lexer::Lexer& lexer, const lexer::pos_iterator_type& position_begin) :
        ValueGrammar::base_type(value, "Value Grammar"),
        type(lexer, position_begin),
        position_begin(position_begin){

    /* Match operators into symbols */
    //TODO Find a way to avoid duplication of these things
    additive_op.add
        ("+", ast::Operator::ADD)
        ("-", ast::Operator::SUB)
        ;

    multiplicative_op.add
        ("/", ast::Operator::DIV)
        ("*", ast::Operator::MUL)
        ("%", ast::Operator::MOD)
        ;

    relational_op.add
        (">=", ast::Operator::GREATER_EQUALS)
        (">", ast::Operator::GREATER)
        ("<=", ast::Operator::LESS_EQUALS)
        ("<", ast::Operator::LESS)
        ("!=", ast::Operator::NOT_EQUALS)
        ("==", ast::Operator::EQUALS)
        ;

    logical_and_op.add
        ("&&", ast::Operator::AND)
        ;

    logical_or_op.add
        ("||", ast::Operator::OR)
        ;

    suffix_op.add
        ("++", ast::Operator::INC)
        ("--", ast::Operator::DEC)
        ;

    prefix_op.add
        ("++", ast::Operator::INC)
        ("--", ast::Operator::DEC)
        ;

    builtin_op.add
        ("size", ast::BuiltinType::SIZE)
        ("length", ast::BuiltinType::LENGTH)
        ;

    //TODO Use unary_op symbols and use a UnaryValue to represent plus and minus for a value

    /* Define values */

    value = logicalOrValue.alias();

    logicalOrValue %=
            qi::position(position_begin)
        >>  logicalAndValue
        >>  *(qi::adapttokens[logical_or_op] > logicalAndValue);

    logicalAndValue %=
            qi::position(position_begin)
        >>  relationalValue
        >>  *(qi::adapttokens[logical_and_op] > relationalValue);

    relationalValue %=
            qi::position(position_begin)
        >>  additiveValue
        >>  *(qi::adapttokens[relational_op] > additiveValue);

    additiveValue %=
            qi::position(position_begin)
        >>  multiplicativeValue
        >>  *(qi::adapttokens[additive_op] > multiplicativeValue);

    multiplicativeValue %=
            qi::position(position_begin)
        >>  unaryValue
        >>  *(qi::adapttokens[multiplicative_op] > unaryValue);

    unaryValue %=
            negatedValue
        |   plusValue
        |   castValue
        |   primaryValue;

    negatedValue =
            lexer.subtraction
         >> primaryValue;

    negatedConstantValue =
            lexer.subtraction
         >> integer;

    plusValue %=
            lexer.addition
         >> primaryValue;

    castValue %=
            qi::position(position_begin)
        >>  lexer.left_parenth
        >>  type.type
        >>  lexer.right_parenth
        >>  primaryValue;

    primaryValue =
            assignment
        |   integer_suffix
        |   integer
        |   float_
        |   litteral
        |   builtin_operator
        |   functionCall
        |   prefix_operation
        |   suffix_operation
        |   struct_value
        |   arrayValue
        |   variable_value
        |   true_
        |   false_
        |   (lexer.left_parenth >> value > lexer.right_parenth);

    true_ %=
            qi::eps
        >>  lexer.true_;

    false_ %=
            qi::eps
        >>  lexer.false_;

    integer %=
            qi::eps
        >>  lexer.integer;

    integer_suffix %=
            qi::eps
        >>  lexer.integer
        >>  lexer.identifier;

    float_ %=
            qi::eps
        >>  lexer.float_;

    variable_value %=
            qi::position(position_begin)
        >>  lexer.identifier;

    struct_value %=
            qi::position(position_begin)
        >>  lexer.identifier
        >>  lexer.dot
        >>  lexer.identifier;

    arrayValue %=
            qi::position(position_begin)
        >>  lexer.identifier
        >>  lexer.left_bracket
        >>  value
        >>  lexer.right_bracket;

    litteral %=
            qi::eps
        >> lexer.litteral;

    constant =
            negatedConstantValue
        |   integer
        |   litteral;

    builtin_operator %=
            qi::position(position_begin)
        >>  qi::adapttokens[builtin_op]
        >>  lexer.left_parenth
        >>  -( value >> *( lexer.comma > value))
        >   lexer.right_parenth;

    functionCall %=
            qi::position(position_begin)
        >>  lexer.identifier
        >>  lexer.left_parenth
        >>  -( value >> *( lexer.comma > value))
        >   lexer.right_parenth;

    assignment %=
            qi::position(position_begin)
        >>  lexer.identifier
        >>  lexer.assign
        >>  value;

    prefix_operation %=
            qi::position(position_begin)
        >>  qi::adapttokens[prefix_op]
        >>  lexer.identifier;

    suffix_operation %=
            qi::position(position_begin)
        >>  lexer.identifier
        >>  qi::adapttokens[suffix_op];
}
<|endoftext|>


<commit_before>#include "mainwindow.h"
#include "pagefactory.h"
#include "dcppage.h"
#include <duinavigationbar.h>
#include <duideviceprofile.h>

MainWindow::MainWindow()
{
   connect(navigationBar(), SIGNAL(homeClicked()), this, SLOT(homeClicked()));
   connect(navigationBar(), SIGNAL(backClicked()), this, SLOT(backClicked()));
   Pages::Handle handle = {Pages::MAIN, ""};
   changePage(handle);
}

void MainWindow::homeClicked()
{
//   changePage(Pages::MAIN);
   onRotateClicked();
}

void MainWindow::backClicked()
{
    DcpPage* page = PageFactory::page(currentPage());
    changePage(page->referer());
}

MainWindow::~MainWindow()
{
}

void
MainWindow::changePage(Pages::Handle handle)
{

  if (handle.id == Pages::NOPAGE)
        return;
    DcpPage* page = PageFactory::instance()->create(handle.id, handle.param);
    connect (page, SIGNAL(openSubPage(Pages::Handle)), this,
		SLOT(changePage(Pages::Handle)));
    qDebug() << Q_FUNC_INFO;
    DcpPage* oldPage = PageFactory::page(currentPage());
    if (oldPage)
      {
	if (page->referer().id == Pages::NOPAGE)
	    page->setReferer(oldPage->handle());
	oldPage->dissappearNow();
      }
    page->handle().id == Pages::MAIN ?
       navigationBar()->showCloseButton()
    :
       navigationBar()->showBackButton();

   page->appearNow(DuiSceneWindow::DestroyWhenDone);
   navigationBar()->setViewMenuButtonText(page->title());
}

void MainWindow::onRotateClicked()
{
    DuiDeviceProfile *profile = DuiDeviceProfile::instance();
   // m_Category->onOrientationChange(profile->orientation());

    if ( profile->orientation() == Dui::Portrait ) {
        qDebug() << "mode changes to Angle0";
        profile->setOrientationAngle (DuiDeviceProfile::Angle0);
    } else {
        qDebug() << "mode changes to Angle90";
        profile->setOrientationAngle (DuiDeviceProfile::Angle90);
    }
}
<commit_msg>Fix for compiling with new dui<commit_after>#include "mainwindow.h"
#include "pagefactory.h"
#include "dcppage.h"
#include <duinavigationbar.h>
#include <duideviceprofile.h>

MainWindow::MainWindow()
{
   connect(navigationBar(), SIGNAL(homeClicked()), this, SLOT(homeClicked()));
   connect(navigationBar(), SIGNAL(backClicked()), this, SLOT(backClicked()));
   Pages::Handle handle = {Pages::MAIN, ""};
   changePage(handle);
}

void MainWindow::homeClicked()
{
//   changePage(Pages::MAIN);
   onRotateClicked();
}

void MainWindow::backClicked()
{
    DcpPage* page = PageFactory::page(currentPage());
    changePage(page->referer());
}

MainWindow::~MainWindow()
{
}

void
MainWindow::changePage(Pages::Handle handle)
{

  if (handle.id == Pages::NOPAGE)
        return;
    DcpPage* page = PageFactory::instance()->create(handle.id, handle.param);
    connect (page, SIGNAL(openSubPage(Pages::Handle)), this,
		SLOT(changePage(Pages::Handle)));
    qDebug() << Q_FUNC_INFO;
    DcpPage* oldPage = PageFactory::page(currentPage());
    if (oldPage)
      {
	if (page->referer().id == Pages::NOPAGE)
	    page->setReferer(oldPage->handle());
        oldPage->disappearNow();
      }
    page->handle().id == Pages::MAIN ?
       navigationBar()->showCloseButton()
    :
       navigationBar()->showBackButton();

   page->appearNow(DuiSceneWindow::DestroyWhenDone);
   navigationBar()->setViewMenuButtonText(page->title());
}

void MainWindow::onRotateClicked()
{
    DuiDeviceProfile *profile = DuiDeviceProfile::instance();
   // m_Category->onOrientationChange(profile->orientation());

    if ( profile->orientation() == Dui::Portrait ) {
        qDebug() << "mode changes to Angle0";
        profile->setOrientationAngle (DuiDeviceProfile::Angle0);
    } else {
        qDebug() << "mode changes to Angle90";
        profile->setOrientationAngle (DuiDeviceProfile::Angle90);
    }
}
<|endoftext|>


<commit_before>/** \brief Tool to determine the frequency for krim keywords
 *  \author Johannes Riedl
 *
 *  \copyright 2021 Universitätsbibliothek Tübingen.  All rights reserved.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <iostream>
#include <unordered_map>
#include "Compiler.h"
#include "FileUtil.h"
#include "StringUtil.h"
#include "TextUtil.h"
#include "util.h"

namespace {

[[noreturn]] void Usage() {
    std::cerr << "Usage: " << ::progname << " A-Z_output keyword_frequeny.csv\n";
    std::exit(EXIT_FAILURE);
}

void ParseFrequencyTable(const std::string &path, std::unordered_map<std::string, std::string> * const all_frequency_map) {
    std::vector<std::vector<std::string>> keywords_and_frequencies;
    TextUtil::ParseCSVFileOrDie(path, &keywords_and_frequencies);
    for (const auto &keyword_and_frequency : keywords_and_frequencies) {
         if (keyword_and_frequency.size() != 2)
            LOG_ERROR("Invalid keyword and frequency for entry " +
                       StringUtil::Join(keyword_and_frequency, ","));
         all_frequency_map->emplace(keyword_and_frequency[0], keyword_and_frequency[1]);
    }
}

} //unnamed namespace

int Main(int argc, char *argv[]) {
    if (argc != 3)
        Usage();

    std::unordered_map<std::string, std::string> all_frequencies_map;
    ParseFrequencyTable(argv[2], &all_frequencies_map);
    std::vector<std::pair<std::string, unsigned>> local_keyword_frequencies;
    for (const auto &line : FileUtil::ReadLines(argv[1])) {
        std::vector<std::string> tokens;
        StringUtil::Split(line, ';', &tokens, true /* suppress empty */);
        unsigned frequency_with_variants(0);
        for (const auto &token : tokens) {
            if (not std::all_of(token.begin(),token.end(),isspace)) {
                if (all_frequencies_map.contains(token))
                    frequency_with_variants += std::stoi(all_frequencies_map[token]);
            }
        }
        local_keyword_frequencies.emplace_back(std::make_pair(tokens[0], frequency_with_variants));

    }
    for (const auto &[token, frequency] : local_keyword_frequencies)
        std::cerr << token << " --- " << frequency << '\n';
    return EXIT_SUCCESS;
}
<commit_msg>Separator<commit_after>/** \brief Tool to determine the frequency for krim keywords
 *  \author Johannes Riedl
 *
 *  \copyright 2021 Universitätsbibliothek Tübingen.  All rights reserved.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <iostream>
#include <unordered_map>
#include "Compiler.h"
#include "FileUtil.h"
#include "StringUtil.h"
#include "TextUtil.h"
#include "util.h"

namespace {

[[noreturn]] void Usage() {
    std::cerr << "Usage: " << ::progname << " A-Z_output keyword_frequeny.csv\n";
    std::exit(EXIT_FAILURE);
}

void ParseFrequencyTable(const std::string &path, std::unordered_map<std::string, std::string> * const all_frequency_map) {
    std::vector<std::vector<std::string>> keywords_and_frequencies;
    TextUtil::ParseCSVFileOrDie(path, &keywords_and_frequencies);
    for (const auto &keyword_and_frequency : keywords_and_frequencies) {
         if (keyword_and_frequency.size() != 2)
            LOG_ERROR("Invalid keyword and frequency for entry " +
                       StringUtil::Join(keyword_and_frequency, ","));
         all_frequency_map->emplace(keyword_and_frequency[0], keyword_and_frequency[1]);
    }
}

} //unnamed namespace

int Main(int argc, char *argv[]) {
    if (argc != 3)
        Usage();

    std::unordered_map<std::string, std::string> all_frequencies_map;
    ParseFrequencyTable(argv[2], &all_frequencies_map);
    std::vector<std::pair<std::string, unsigned>> local_keyword_frequencies;
    for (const auto &line : FileUtil::ReadLines(argv[1])) {
        std::vector<std::string> tokens;
        StringUtil::Split(line, ';', &tokens, true /* suppress empty */);
        unsigned frequency_with_variants(0);
        for (const auto &token : tokens) {
            if (not std::all_of(token.begin(),token.end(),isspace)) {
                if (all_frequencies_map.contains(token))
                    frequency_with_variants += std::stoi(all_frequencies_map[token]);
            }
        }
        local_keyword_frequencies.emplace_back(std::make_pair(tokens[0], frequency_with_variants));

    }
    for (const auto &[token, frequency] : local_keyword_frequencies)
        std::cout << token << ";" << frequency << '\n';
    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/// HEADER
#include "flip.h"

/// PROJECT
#include <csapex/utility/register_apex_plugin.h>
#include <csapex/msg/io.h>
#include <csapex/param/parameter_factory.h>
#include <csapex_opencv/cv_mat_message.h>
#include <csapex/model/node_modifier.h>

using namespace csapex;
using namespace csapex::connection_types;
using namespace csapex;

CSAPEX_REGISTER_CLASS(csapex::Flip, csapex::Node)

Flip::Flip()
{
}

void Flip::process()
{
    CvMatMessage::ConstPtr in = msg::getMessage<connection_types::CvMatMessage>(input_);
    CvMatMessage::Ptr out(new connection_types::CvMatMessage(in->getEncoding(), in->frame_id, in->stamp_micro_seconds));

    switch(mode_) {
    case -1:
    case 0:
    case 1:
        cv::flip(in->value, out->value, mode_);
        break;

    case 2: // +90
        cv::transpose(in->value, out->value);
        cv::flip(out->value, out->value, 0);
        break;

    case 3: // -90
        cv::transpose(in->value, out->value);
        cv::flip(out->value, out->value, 1);
        break;

    }
    msg::publish(output_, out);
}

void Flip::setup(NodeModifier& node_modifier)
{
    input_ = node_modifier.addInput<CvMatMessage>("original");
    output_ = node_modifier.addOutput<CvMatMessage>("flipped");
}

void Flip::setupParameters(Parameterizable& parameters)
{
    std::map<std::string, int> types = {
        {"v", 0},
        {"h", 1},
        {"+90", 2},
        {"-90", 3},
        {"v+h", -1}
    };
    parameters.addParameter(csapex::param::ParameterFactory::declareParameterSet("type", types, -1),
                            mode_);
}
<commit_msg>vision: flip - add none flip option, needed for templated configs<commit_after>/// HEADER
#include "flip.h"

/// PROJECT
#include <csapex/utility/register_apex_plugin.h>
#include <csapex/msg/io.h>
#include <csapex/param/parameter_factory.h>
#include <csapex_opencv/cv_mat_message.h>
#include <csapex/model/node_modifier.h>

using namespace csapex;
using namespace csapex::connection_types;
using namespace csapex;

CSAPEX_REGISTER_CLASS(csapex::Flip, csapex::Node)

Flip::Flip()
{
}

void Flip::process()
{
    CvMatMessage::ConstPtr in = msg::getMessage<connection_types::CvMatMessage>(input_);
    CvMatMessage::Ptr out(new connection_types::CvMatMessage(in->getEncoding(), in->frame_id, in->stamp_micro_seconds));

    switch(mode_) {
    case -1:
    case 0:
    case 1:
        cv::flip(in->value, out->value, mode_);
        break;

    case 2: // +90
        cv::transpose(in->value, out->value);
        cv::flip(out->value, out->value, 0);
        break;

    case 3: // -90
        cv::transpose(in->value, out->value);
        cv::flip(out->value, out->value, 1);
        break;

    case 4: // none
        out->value = in->value;
        break;
    }
    msg::publish(output_, out);
}

void Flip::setup(NodeModifier& node_modifier)
{
    input_ = node_modifier.addInput<CvMatMessage>("original");
    output_ = node_modifier.addOutput<CvMatMessage>("flipped");
}

void Flip::setupParameters(Parameterizable& parameters)
{
    std::map<std::string, int> types = {
        {"v", 0},
        {"h", 1},
        {"+90", 2},
        {"-90", 3},
        {"none", 4},
        {"v+h", -1}
    };
    parameters.addParameter(csapex::param::ParameterFactory::declareParameterSet("type", types, -1),
                            mode_);
}
<|endoftext|>


<commit_before>#include "BrainStdAfx.h"
#include "IO_Board_RPi.h"
#include "utils/Json_Helpers.h"
#include "utils/Timed_Scope.h"

#define USE_MPU9250
#define USE_MS5611

#ifdef USE_MPU9250
#   include "chips/MPU9250.h"
#else
#   error "No IMU selected"
#endif

#ifdef USE_MS5611
#   include "chips/MS5611.h"
#else
#   error "No Barometer selected"
#endif

using namespace silk;
using namespace boost::asio;

struct IO_Board_RPi::Private
{
#ifdef USE_MPU9250
    MPU9250 mpu;
#endif

#ifdef USE_MS5611
    MS5611 baro;
#endif
};

///////////////////////////////////////////////////////////////

IO_Board_RPi::IO_Board_RPi()
{
    load_settings();

    m_p.reset(new Private);
}

IO_Board_RPi::~IO_Board_RPi()
{
}

auto IO_Board_RPi::load_settings() -> bool
{
    q::data::File_Source fs(q::Path("io_board.cfg"));
    if (!fs.is_open())
    {
        return false;
    }

    auto size = fs.get_size();

    std::vector<char> data(size + 1);
    auto result = fs.read(reinterpret_cast<uint8_t*>(data.data()), size);
    if (result != size)
    {
        SILK_WARNING("Failed to read settings.");
        return false;
    }

    data[size] = 0;
    if (m_settings.document.Parse<0>(data.data()).HasParseError())
    {
        SILK_WARNING("Failed to parse settings: {}:{}", m_settings.document.GetErrorOffset(), m_settings.document.GetParseError());
        return false;
    }

    auto finder = jsonutil::Member_Finder(m_settings.document, "calibration_config");
    if (!finder.is_valid())
    {
        SILK_WARNING("Cannot find root");
        return false;
    }
    auto& calibration_config = finder.get_value();

    {
        auto& json = calibration_config;
        auto abias = jsonutil::get_vec3_value<float>(json, "accelerometer_bias");
        auto ascale = jsonutil::get_vec3_value<float>(json, "accelerometer_scale");
        auto gbias = jsonutil::get_vec3_value<float>(json, "gyroscope_bias");
        auto cbias = jsonutil::get_vec3_value<float>(json, "compass_bias");
        if (!abias || !ascale || !gbias || !cbias)
        {
            SILK_WARNING("Cannot read calibration config");
            return false;
        }
        m_calibration_config.accelerometer_bias = *abias;
        m_calibration_config.accelerometer_scale = *ascale;
        m_calibration_config.gyroscope_bias = *gbias;
        m_calibration_config.compass_bias = *cbias;
    }

    return true;
}
void IO_Board_RPi::save_settings()
{
    TIMED_FUNCTION();
    if (!m_settings.document.IsObject())
    {
        m_settings.document.SetObject();
    }

    auto& allocator = m_settings.document.GetAllocator();

    auto& calibration_config = jsonutil::get_or_add_member(m_settings.document, "calibration_config", rapidjson::kObjectType, allocator);

    {
        auto& json = calibration_config;
        jsonutil::set_vec3_value(json, "accelerometer_bias", m_calibration_config.accelerometer_bias, allocator);
        jsonutil::set_vec3_value(json, "accelerometer_scale", m_calibration_config.accelerometer_scale, allocator);
        jsonutil::set_vec3_value(json, "gyroscope_bias", m_calibration_config.gyroscope_bias, allocator);
        jsonutil::set_vec3_value(json, "compass_bias", m_calibration_config.compass_bias, allocator);
    }

    typedef rapidjson::UTF8<> JSONCharset;
    typedef rapidjson::GenericStringBuffer<JSONCharset> JSONBuffer;
    typedef rapidjson::PrettyWriter<JSONBuffer> JSONWriter;

    JSONBuffer buffer;
    JSONWriter writer(buffer);
    m_settings.document.Accept(writer);

    q::data::File_Sink fs(q::Path("io_board.cfg"));
    if (!fs.is_open())
    {
        SILK_WARNING("Cannot open file to save settings");
        return;
    }

    fs.write(reinterpret_cast<uint8_t const*>(buffer.GetString()), buffer.GetSize());
}

auto IO_Board_RPi::connect() -> Connection_Result
{
    if (!is_disconnected())
    {
        return Connection_Result::OK;
    }

#ifdef USE_MS5611
    m_p->baro.init("/dev/i2c-1");
#endif

#ifdef USE_MPU9250
    m_p->mpu.init("/dev/i2c-1", MPU9250::Gyroscope_Range::_500_DPS, MPU9250::Accelerometer_Range::_4_G);
#endif

//    return Connection_Result::FAILED;

    m_is_connected = true;
    return Connection_Result::OK;
}

void IO_Board_RPi::disconnect()
{
    m_is_connected = false;
}
bool IO_Board_RPi::is_disconnected() const
{
    return !m_is_connected;
}
bool IO_Board_RPi::is_running() const
{
    return m_is_connected;
}

void IO_Board_RPi::set_motor_output(size_t motor_idx, float output)
{
    QASSERT(motor_idx < 12);
    if (motor_idx >= 12)
    {
        return;
    }

    if (motor_idx >= m_motor_outputs.size())
    {
        m_motor_outputs.resize(motor_idx + 1);
    }
    m_motor_outputs[motor_idx] = output;
}

void IO_Board_RPi::set_accelerometer_calibration_data(math::vec3f const& bias, math::vec3f const& scale)
{
    m_calibration_config.accelerometer_bias = bias;
    m_calibration_config.accelerometer_scale = scale;
    save_settings();
}
void IO_Board_RPi::get_accelerometer_calibration_data(math::vec3f &bias, math::vec3f &scale) const
{
    bias = m_calibration_config.accelerometer_bias;
    scale = m_calibration_config.accelerometer_scale;
}

void IO_Board_RPi::set_gyroscope_calibration_data(math::vec3f const& bias)
{
    m_calibration_config.gyroscope_bias = bias;
    save_settings();
}
void IO_Board_RPi::get_gyroscope_calibration_data(math::vec3f &bias) const
{
    bias = m_calibration_config.gyroscope_bias;
}

void IO_Board_RPi::set_compass_calibration_data(math::vec3f const& bias)
{
    m_calibration_config.compass_bias = bias;
    save_settings();
}
void IO_Board_RPi::get_compass_calibration_data(math::vec3f &bias) const
{
    bias = m_calibration_config.compass_bias;
}

auto IO_Board_RPi::get_sensor_samples() const -> std::vector<Sensor_Sample> const&
{
    return m_sensor_samples;
}

size_t IO_Board_RPi::get_error_count() const
{
    return m_error_count;
}

void IO_Board_RPi::process()
{
    if (is_disconnected())
    {
        connect();
        return;
    }

    m_sensor_samples.clear();

    auto start = q::Clock::now();

#ifdef USE_MPU9250
    auto a_sample_time = m_p->mpu.get_sample_time();
    auto g_sample_time = a_sample_time;
    m_p->mpu.process();
    auto const& g_samples = m_p->mpu.get_gyroscope_samples();
    auto const& a_samples = m_p->mpu.get_accelerometer_samples();
    auto compass_sample = m_p->mpu.read_compass();
    if (compass_sample)
    {
        m_sensors.compass.value = *compass_sample - m_calibration_config.compass_bias;
        m_sensors.compass.sample_idx++;
    }
#endif

#ifdef USE_MS5611
    m_p->baro.process();
    auto baro_sample = m_p->baro.read_pressure();
    if (baro_sample)
    {
        m_sensors.barometer.value = *baro_sample;
        m_sensors.barometer.sample_idx++;
    }
    auto temp_sample = m_p->baro.read_temperature();
    if (temp_sample)
    {
        m_sensors.thermometer.value = *temp_sample;
        m_sensors.thermometer.sample_idx++;
    }
#endif

    QASSERT(a_samples.size() == g_samples.size());
    m_sensor_samples.resize(a_samples.size());
    for (size_t i = 0; i < a_samples.size(); i++)
    {
        auto& sample = m_sensor_samples[i];

        {
            sample.accelerometer.value.acceleration = (a_samples[i] - m_calibration_config.accelerometer_bias) * m_calibration_config.accelerometer_scale;
            sample.accelerometer.value.dt = a_sample_time;
            sample.accelerometer.sample_idx = m_sensors.accelerometer.sample_idx++;
        }
        {
            sample.gyroscope.value.angular_velocity = g_samples[i] - m_calibration_config.gyroscope_bias;
            sample.gyroscope.value.dt = g_sample_time;
            sample.gyroscope.sample_idx = m_sensors.gyroscope.sample_idx++;
        }

        sample.barometer = m_sensors.barometer;
        sample.thermometer = m_sensors.thermometer;
        sample.compass = m_sensors.compass;
    }

//    auto d = q::Clock::now() - start;
//    SILK_INFO("d = {}, {}", d, m_sensor_samples.size());
}

<commit_msg>! small fix<commit_after>#include "BrainStdAfx.h"
#include "IO_Board_RPi.h"
#include "utils/Json_Helpers.h"
#include "utils/Timed_Scope.h"

#define USE_MPU9250
#define USE_MS5611

#ifdef USE_MPU9250
#   include "chips/MPU9250.h"
#else
#   error "No IMU selected"
#endif

#ifdef USE_MS5611
#   include "chips/MS5611.h"
#else
#   error "No Barometer selected"
#endif

using namespace silk;
using namespace boost::asio;

struct IO_Board_RPi::Private
{
#ifdef USE_MPU9250
    MPU9250 mpu;
#endif

#ifdef USE_MS5611
    MS5611 baro;
#endif
};

///////////////////////////////////////////////////////////////

IO_Board_RPi::IO_Board_RPi()
{
    load_settings();

    m_p.reset(new Private);
}

IO_Board_RPi::~IO_Board_RPi()
{
}

auto IO_Board_RPi::load_settings() -> bool
{
    q::data::File_Source fs(q::Path("io_board.cfg"));
    if (!fs.is_open())
    {
        return false;
    }

    auto size = fs.get_size();

    std::vector<char> data(size + 1);
    auto result = fs.read(reinterpret_cast<uint8_t*>(data.data()), size);
    if (result != size)
    {
        SILK_WARNING("Failed to read settings.");
        return false;
    }

    data[size] = 0;
    if (m_settings.document.Parse<0>(data.data()).HasParseError())
    {
        SILK_WARNING("Failed to parse settings: {}:{}", m_settings.document.GetErrorOffset(), m_settings.document.GetParseError());
        return false;
    }

    auto finder = jsonutil::Member_Finder(m_settings.document, "calibration_config");
    if (!finder.is_valid())
    {
        SILK_WARNING("Cannot find root");
        return false;
    }
    auto& calibration_config = finder.get_value();

    {
        auto& json = calibration_config;
        auto abias = jsonutil::get_vec3_value<float>(json, "accelerometer_bias");
        auto ascale = jsonutil::get_vec3_value<float>(json, "accelerometer_scale");
        auto gbias = jsonutil::get_vec3_value<float>(json, "gyroscope_bias");
        auto cbias = jsonutil::get_vec3_value<float>(json, "compass_bias");
        if (!abias || !ascale || !gbias || !cbias)
        {
            SILK_WARNING("Cannot read calibration config");
            return false;
        }
        m_calibration_config.accelerometer_bias = *abias;
        m_calibration_config.accelerometer_scale = *ascale;
        m_calibration_config.gyroscope_bias = *gbias;
        m_calibration_config.compass_bias = *cbias;
    }

    return true;
}
void IO_Board_RPi::save_settings()
{
    TIMED_FUNCTION();
    if (!m_settings.document.IsObject())
    {
        m_settings.document.SetObject();
    }

    auto& allocator = m_settings.document.GetAllocator();

    auto& calibration_config = jsonutil::get_or_add_member(m_settings.document, "calibration_config", rapidjson::kObjectType, allocator);

    {
        auto& json = calibration_config;
        jsonutil::set_vec3_value(json, "accelerometer_bias", m_calibration_config.accelerometer_bias, allocator);
        jsonutil::set_vec3_value(json, "accelerometer_scale", m_calibration_config.accelerometer_scale, allocator);
        jsonutil::set_vec3_value(json, "gyroscope_bias", m_calibration_config.gyroscope_bias, allocator);
        jsonutil::set_vec3_value(json, "compass_bias", m_calibration_config.compass_bias, allocator);
    }

    typedef rapidjson::UTF8<> JSONCharset;
    typedef rapidjson::GenericStringBuffer<JSONCharset> JSONBuffer;
    typedef rapidjson::PrettyWriter<JSONBuffer> JSONWriter;

    JSONBuffer buffer;
    JSONWriter writer(buffer);
    m_settings.document.Accept(writer);

    q::data::File_Sink fs(q::Path("io_board.cfg"));
    if (!fs.is_open())
    {
        SILK_WARNING("Cannot open file to save settings");
        return;
    }

    fs.write(reinterpret_cast<uint8_t const*>(buffer.GetString()), buffer.GetSize());
}

auto IO_Board_RPi::connect() -> Connection_Result
{
    if (!is_disconnected())
    {
        return Connection_Result::OK;
    }

#ifdef USE_MS5611
    m_p->baro.init("/dev/i2c-1");
#endif

#ifdef USE_MPU9250
    m_p->mpu.init("/dev/i2c-1", MPU9250::Gyroscope_Range::_500_DPS, MPU9250::Accelerometer_Range::_4_G);
#endif

    m_is_connected = true;
    return Connection_Result::OK;
}

void IO_Board_RPi::disconnect()
{
    m_is_connected = false;
}
bool IO_Board_RPi::is_disconnected() const
{
    return !m_is_connected;
}
bool IO_Board_RPi::is_running() const
{
    return m_is_connected;
}

void IO_Board_RPi::set_motor_output(size_t motor_idx, float output)
{
    QASSERT(motor_idx < 12);
    if (motor_idx >= 12)
    {
        return;
    }

    if (motor_idx >= m_motor_outputs.size())
    {
        m_motor_outputs.resize(motor_idx + 1);
    }
    m_motor_outputs[motor_idx] = output;
}

void IO_Board_RPi::set_accelerometer_calibration_data(math::vec3f const& bias, math::vec3f const& scale)
{
    m_calibration_config.accelerometer_bias = bias;
    m_calibration_config.accelerometer_scale = scale;
    save_settings();
}
void IO_Board_RPi::get_accelerometer_calibration_data(math::vec3f &bias, math::vec3f &scale) const
{
    bias = m_calibration_config.accelerometer_bias;
    scale = m_calibration_config.accelerometer_scale;
}

void IO_Board_RPi::set_gyroscope_calibration_data(math::vec3f const& bias)
{
    m_calibration_config.gyroscope_bias = bias;
    save_settings();
}
void IO_Board_RPi::get_gyroscope_calibration_data(math::vec3f &bias) const
{
    bias = m_calibration_config.gyroscope_bias;
}

void IO_Board_RPi::set_compass_calibration_data(math::vec3f const& bias)
{
    m_calibration_config.compass_bias = bias;
    save_settings();
}
void IO_Board_RPi::get_compass_calibration_data(math::vec3f &bias) const
{
    bias = m_calibration_config.compass_bias;
}

auto IO_Board_RPi::get_sensor_samples() const -> std::vector<Sensor_Sample> const&
{
    return m_sensor_samples;
}

size_t IO_Board_RPi::get_error_count() const
{
    return m_error_count;
}

void IO_Board_RPi::process()
{
    if (is_disconnected())
    {
        connect();
        return;
    }

    m_sensor_samples.clear();

    auto start = q::Clock::now();

#ifdef USE_MPU9250
    auto a_sample_time = m_p->mpu.get_sample_time();
    auto g_sample_time = a_sample_time;
    m_p->mpu.process();
    auto const& g_samples = m_p->mpu.get_gyroscope_samples();
    auto const& a_samples = m_p->mpu.get_accelerometer_samples();
    auto compass_sample = m_p->mpu.read_compass();
    if (compass_sample)
    {
        m_sensors.compass.value = *compass_sample - m_calibration_config.compass_bias;
        m_sensors.compass.sample_idx++;
    }
#endif

#ifdef USE_MS5611
    m_p->baro.process();
    auto baro_sample = m_p->baro.read_pressure();
    if (baro_sample)
    {
        m_sensors.barometer.value = *baro_sample;
        m_sensors.barometer.sample_idx++;
    }
    auto temp_sample = m_p->baro.read_temperature();
    if (temp_sample)
    {
        m_sensors.thermometer.value = *temp_sample;
        m_sensors.thermometer.sample_idx++;
    }
#endif

    QASSERT(a_samples.size() == g_samples.size());
    m_sensor_samples.resize(a_samples.size());
    for (size_t i = 0; i < a_samples.size(); i++)
    {
        auto& sample = m_sensor_samples[i];

        {
            sample.accelerometer.value.acceleration = (a_samples[i] - m_calibration_config.accelerometer_bias) * m_calibration_config.accelerometer_scale;
            sample.accelerometer.value.dt = a_sample_time;
            sample.accelerometer.sample_idx = m_sensors.accelerometer.sample_idx++;
        }
        {
            sample.gyroscope.value.angular_velocity = g_samples[i] - m_calibration_config.gyroscope_bias;
            sample.gyroscope.value.dt = g_sample_time;
            sample.gyroscope.sample_idx = m_sensors.gyroscope.sample_idx++;
        }

        sample.barometer = m_sensors.barometer;
        sample.thermometer = m_sensors.thermometer;
        sample.compass = m_sensors.compass;
    }

//    auto d = q::Clock::now() - start;
//    SILK_INFO("d = {}, {}", d, m_sensor_samples.size());
}

<|endoftext|>


<commit_before>#include "QMLVideoSurface.h"
#include "Video_Decoder.h"
#include <QResizeEvent>
#include <QTimer>
#include <QThread>

#include <chrono>
#include <thread>
#include <mutex>

#define EGL_SYNC_FENCE_KHR                      0x30F9

static QMLVideoTexture* s_videoTexture = nullptr;
static std::mutex s_videoDataMutex;
static math::vec2u16 s_videoResolution;
static bool s_videoResolutionDirty = false;

QMLVideoTexture::QMLVideoTexture(uint32_t videoTextureId)
    : m_subRect(0, 0, 1, 1)
    , m_textureSize(1280, 720)
    , m_textureId(videoTextureId)
    , m_updated(false)
{
}

QMLVideoTexture::~QMLVideoTexture()
{
    releaseTexture();
}

int QMLVideoTexture::textureId() const
{
    return m_textureId;
}

QSize QMLVideoTexture::textureSize() const
{
    return m_textureSize;
}

void QMLVideoTexture::setTextureSize(const QSize &size)
{
    m_textureSize = size;
}

bool QMLVideoTexture::hasAlphaChannel() const
{
    return false;
}

bool QMLVideoTexture::hasMipmaps() const
{
    return false;
}

QRectF QMLVideoTexture::normalizedTextureSubRect() const
{
    return m_subRect;
}

void QMLVideoTexture::bind()
{
    if (m_textureId != 0)
    {
        glBindTexture(GL_TEXTURE_EXTERNAL_OES, m_textureId);
    }
}

bool QMLVideoTexture::updateTexture()
{
//    static const PFNGLEGLIMAGETARGETTEXTURE2DOESPROC glEGLImageTargetTexture2DOES
//            = reinterpret_cast<PFNGLEGLIMAGETARGETTEXTURE2DOESPROC>(eglGetProcAddress("glEGLImageTargetTexture2DOES"));

//    if (m_updated)
//    {
//        return true;
//    }

//    NemoGstVideoTexture *sink = NEMO_GST_VIDEO_TEXTURE(m_sink);

//    if (!nemo_gst_video_texture_acquire_frame(sink))
//    {
//        return false;
//    }

//    int left = 0;
//    int top = 0;
//    int right = 0;
//    int bottom = 0;
//    if (GstMeta *meta = nemo_gst_video_texture_get_frame_meta (sink, GST_VIDEO_CROP_META_API_TYPE))
//    {
//        GstVideoCropMeta *crop = (GstVideoCropMeta *) meta;
//        left = crop->x;
//        top = crop->y;
//        right = crop->width + left;
//        bottom = crop->height + top;
//    }

//    // All the calculations below are based on ideas from Android GLConsumer.
//    // The difference between us and Android is we rely on texture coordinates
//    // while Android relies on a matxrix for cropping
//    qreal x = 0.0, y = 0.0, width = 1.0, height = 1.0;

//    // This value is taken from Android GLConsumer
//    qreal shrinkAmount = 1.0;
//    if (right - left < m_textureSize.width())
//    {
//        x = (left + shrinkAmount) / m_textureSize.width();
//        width = ((right - left) - (2.0f * shrinkAmount)) / m_textureSize.width();
//    }

//    if (bottom - top < m_textureSize.height())
//    {
//        y = (top + shrinkAmount) / m_textureSize.height();
//        height = (bottom - top - (2.0 * shrinkAmount)) / m_textureSize.height();
//    }

//    m_subRect = QRectF(x, y, width, height);

//    EGLImageKHR image;
//    if (!nemo_gst_video_texture_bind_frame(sink, &image))
//    {
//        if (m_textureId)
//        {
//            glDeleteTextures(1, &m_textureId);
//            m_textureId = 0;
//        }
//        nemo_gst_video_texture_release_frame(sink, NULL);
//        return false;
//    } else {
//        if (!m_textureId) {
//            glGenTextures(1, &m_textureId);
//            glBindTexture(GL_TEXTURE_EXTERNAL_OES, m_textureId);
//            glTexParameterf(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
//            glTexParameterf(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
//            glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
//            glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
//        } else {
//            glBindTexture(GL_TEXTURE_EXTERNAL_OES, m_textureId);
//        }
//        glEGLImageTargetTexture2DOES(GL_TEXTURE_EXTERNAL_OES, image);
//        m_updated = true;
//        return true;
//    }
    return true;
}

void QMLVideoTexture::invalidateTexture()
{
}

void QMLVideoTexture::releaseTexture()
{
    if (m_updated)
    {
        m_updated = false;
    }
}

class VideoMaterialShader : public QSGMaterialShader
{
public:
    static QSGMaterialType type;

    void updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect);
    char const *const *attributeNames() const;

protected:
    void initialize();

    const char *vertexShader() const;
    const char *fragmentShader() const;

private:
    int m_id_matrix = 0;
    int m_id_subrect = 0;
    int m_id_opacity = 0;
    int m_id_texture = 0;
};

void VideoMaterialShader::updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect)
{
    QMLVideoMaterial *material = static_cast<QMLVideoMaterial *>(newEffect);

    if (state.isMatrixDirty())
    {
        program()->setUniformValue(m_id_matrix, state.combinedMatrix());
    }

    if (state.isOpacityDirty())
    {
        program()->setUniformValue(m_id_opacity, state.opacity());
    }

    if (!oldEffect)
    {
        program()->setUniformValue(m_id_texture, 0);
    }

    const QRectF subRect = material->m_texture->normalizedTextureSubRect();
    program()->setUniformValue(m_id_subrect, QVector4D(subRect.x(), subRect.y(), subRect.width(), subRect.height()));

    glActiveTexture(GL_TEXTURE0);
    material->m_texture->bind();
}

char const *const *VideoMaterialShader::attributeNames() const
{
    static char const *const attr[] = { "position", "texcoord", 0 };
    return attr;
}

void VideoMaterialShader::initialize()
{
    m_id_matrix = program()->uniformLocation("matrix");
    m_id_subrect = program()->uniformLocation("subrect");
    m_id_opacity = program()->uniformLocation("opacity");
    m_id_texture = program()->uniformLocation("texture");
}

QSGMaterialType VideoMaterialShader::type;

const char *VideoMaterialShader::vertexShader() const
{
    return  "\n uniform highp mat4 matrix;"
            "\n uniform highp vec4 subrect;"
            "\n attribute highp vec4 position;"
            "\n attribute highp vec2 texcoord;"
            "\n varying highp vec2 v_texcoord;"
            "\n void main(void)"
            "\n {"
            "\n     gl_Position = matrix * position;"
            "\n     v_texcoord = (texcoord * subrect.zw) + subrect.xy;"
            "\n }";
}

const char *VideoMaterialShader::fragmentShader() const
{
    return  "\n #extension GL_OES_EGL_image_external : require"
            "\n uniform samplerExternalOES texture;"
            "\n uniform lowp float opacity;\n"
            "\n varying highp vec2 v_texcoord;"
            "\n void main(void)"
            "\n {"
            "\n     gl_FragColor = opacity * texture2D(texture, v_texcoord.st);"
            "\n }";
}

QMLVideoMaterial::QMLVideoMaterial(QMLVideoTexture *texture)
    : m_texture(texture)
{
}

QSGMaterialShader *QMLVideoMaterial::createShader() const
{
    return new VideoMaterialShader;
}

QSGMaterialType *QMLVideoMaterial::type() const
{
    return &VideoMaterialShader::type;
}

int QMLVideoMaterial::compare(const QSGMaterial *other) const
{
    return m_texture - static_cast<const QMLVideoMaterial *>(other)->m_texture;
}

QMLVideoNode::QMLVideoNode(QMLVideoTexture *texture)
    : m_material(texture)
    , m_geometry(QSGGeometry::defaultAttributes_TexturedPoint2D(), 4)
{
    setGeometry(&m_geometry);
    setMaterial(&m_material);
    setFlag(UsePreprocess);
}

QMLVideoNode::~QMLVideoNode()
{
    //m_material.m_texture->deleteLater();
}

void QMLVideoNode::preprocess()
{
    QMLVideoTexture *t = m_material.m_texture;
    if (t && t->updateTexture())
    {
        markDirty(QSGNode::DirtyMaterial);
    }
}

void QMLVideoNode::setBoundingRect(const QRectF &rect, int orientation, bool horizontalMirror, bool verticalMirror)
{
    // Texture vertices clock wise from top left: or tl, tr, br, lf
    // Vertex order is tl, bl, tr, br. So unrotated the texture indexes are [0, 3, 1, 2] and
    // by shifting the array left and wrapping we rotate the image in 90 degree increments.
    const float tx[] = { 0, 1, 1, 0 };
    const float ty[] = { 0, 0, 1, 1 };

    // Texture coordinates are 0, or 1 so flip by subtracting the cooridinate from 1 and
    // taking the absolute value. 1 - 0 = 1, 1 - 1 = 0.  The absolute of 0 take the coordinate
    // gives back the original value. 0 - 0 = 0, 0 - 1 = -1.
    const float hm = horizontalMirror ? 1 : 0;
    const float vm = verticalMirror ? 1 : 0;

    const int offset = orientation / 90;
    QSGGeometry::TexturedPoint2D vertices[] =
    {
        { (float)rect.left() , (float)rect.top()   , qAbs(hm - tx[(0 + offset) % 4]), qAbs(vm - ty[(0 + offset) % 4]) },
        { (float)rect.left() , (float)rect.bottom(), qAbs(hm - tx[(3 + offset) % 4]), qAbs(vm - ty[(3 + offset) % 4]) },
        { (float)rect.right(), (float)rect.top()   , qAbs(hm - tx[(1 + offset) % 4]), qAbs(vm - ty[(1 + offset) % 4]) },
        { (float)rect.right(), (float)rect.bottom(), qAbs(hm - tx[(2 + offset) % 4]), qAbs(vm - ty[(2 + offset) % 4]) }
    };

    memcpy(m_geometry.vertexDataAsTexturedPoint2D(), vertices, sizeof(vertices));
}

/*----------------------------------------------------------------------
|    VideoSurface::VideoSurface
+---------------------------------------------------------------------*/
QMLVideoSurface::QMLVideoSurface(QQuickItem *parent)
    : QQuickItem(parent)
{
    setFlag(QQuickItem::ItemHasContents, true);

//    QTimer* timer = new QTimer;
//    connect(timer, SIGNAL(timeout()), this, SLOT(doUpdate()));
//    timer->setSingleShot(false);
//    timer->start(1);
}

void QMLVideoSurface::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)
{
    QQuickItem::geometryChanged(newGeometry, oldGeometry);
    if (newGeometry != oldGeometry)
    {
        m_isGeomertyDirty = true;
    }
}

/*----------------------------------------------------------------------
|    VideoSurface::paint
+---------------------------------------------------------------------*/
QSGNode* QMLVideoSurface::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *)
{
    QMLVideoNode* node = static_cast<QMLVideoNode*>(oldNode);

    if (!s_videoTexture)
    {
        return nullptr;
    }

    if (!node)
    {
        node = new QMLVideoNode(s_videoTexture);
        m_isGeomertyDirty = true;
    }

    std::lock_guard<std::mutex> lg(s_videoDataMutex);

    if (m_isGeomertyDirty || s_videoResolutionDirty)
    {
        QLOGI("Resolution changed to: {}", s_videoResolution);
        const QRectF br = boundingRect();
        QRectF rect = QRectF(QPointF(0, 0), QSizeF(s_videoResolution.x, s_videoResolution.y).scaled(br.size(), Qt::KeepAspectRatio));
        rect.moveCenter(br.center());

        //align left, top
        float dx = (br.width() - rect.width()) / 2.f;
        float dy = (br.height() - rect.height()) / 2.f;
        rect.translate(-dx, -dy);

        int orientation = 0;//(m_orientation - m_textureOrientation) % 360;
        if (orientation < 0)
            orientation += 360;
        node->setBoundingRect(
                    rect,
                    orientation,
                    false,
                    false);
        node->markDirty(QSGNode::DirtyGeometry);

        QLOGI("Node rect size: {}x{}", rect.width(), rect.height());

        m_isGeomertyDirty = false;
        s_videoResolutionDirty = false;
    }

    node->markDirty(QSGNode::DirtyMaterial);
    update();

    return node;
}

void QMLVideoSurface::init(Video_Decoder& decoder)
{
    if (!s_videoTexture)
    {
        s_videoTexture = new QMLVideoTexture(decoder.get_video_texture_id());
    }
}

void QMLVideoSurface::setResolution(math::vec2u16 const& resolution)
{
    std::lock_guard<std::mutex> lg(s_videoDataMutex);
    if (s_videoResolution != resolution)
    {
        //s_videoResolution = math::vec2u16(1280, 720);
        s_videoResolution = resolution;
        s_videoResolutionDirty = true;
    }
}

<commit_msg>Centered video surface<commit_after>#include "QMLVideoSurface.h"
#include "Video_Decoder.h"
#include <QResizeEvent>
#include <QTimer>
#include <QThread>

#include <chrono>
#include <thread>
#include <mutex>

#define EGL_SYNC_FENCE_KHR                      0x30F9

static QMLVideoTexture* s_videoTexture = nullptr;
static std::mutex s_videoDataMutex;
static math::vec2u16 s_videoResolution;
static bool s_videoResolutionDirty = false;

QMLVideoTexture::QMLVideoTexture(uint32_t videoTextureId)
    : m_subRect(0, 0, 1, 1)
    , m_textureSize(1280, 720)
    , m_textureId(videoTextureId)
    , m_updated(false)
{
}

QMLVideoTexture::~QMLVideoTexture()
{
    releaseTexture();
}

int QMLVideoTexture::textureId() const
{
    return m_textureId;
}

QSize QMLVideoTexture::textureSize() const
{
    return m_textureSize;
}

void QMLVideoTexture::setTextureSize(const QSize &size)
{
    m_textureSize = size;
}

bool QMLVideoTexture::hasAlphaChannel() const
{
    return false;
}

bool QMLVideoTexture::hasMipmaps() const
{
    return false;
}

QRectF QMLVideoTexture::normalizedTextureSubRect() const
{
    return m_subRect;
}

void QMLVideoTexture::bind()
{
    if (m_textureId != 0)
    {
        glBindTexture(GL_TEXTURE_EXTERNAL_OES, m_textureId);
    }
}

bool QMLVideoTexture::updateTexture()
{
//    static const PFNGLEGLIMAGETARGETTEXTURE2DOESPROC glEGLImageTargetTexture2DOES
//            = reinterpret_cast<PFNGLEGLIMAGETARGETTEXTURE2DOESPROC>(eglGetProcAddress("glEGLImageTargetTexture2DOES"));

//    if (m_updated)
//    {
//        return true;
//    }

//    NemoGstVideoTexture *sink = NEMO_GST_VIDEO_TEXTURE(m_sink);

//    if (!nemo_gst_video_texture_acquire_frame(sink))
//    {
//        return false;
//    }

//    int left = 0;
//    int top = 0;
//    int right = 0;
//    int bottom = 0;
//    if (GstMeta *meta = nemo_gst_video_texture_get_frame_meta (sink, GST_VIDEO_CROP_META_API_TYPE))
//    {
//        GstVideoCropMeta *crop = (GstVideoCropMeta *) meta;
//        left = crop->x;
//        top = crop->y;
//        right = crop->width + left;
//        bottom = crop->height + top;
//    }

//    // All the calculations below are based on ideas from Android GLConsumer.
//    // The difference between us and Android is we rely on texture coordinates
//    // while Android relies on a matxrix for cropping
//    qreal x = 0.0, y = 0.0, width = 1.0, height = 1.0;

//    // This value is taken from Android GLConsumer
//    qreal shrinkAmount = 1.0;
//    if (right - left < m_textureSize.width())
//    {
//        x = (left + shrinkAmount) / m_textureSize.width();
//        width = ((right - left) - (2.0f * shrinkAmount)) / m_textureSize.width();
//    }

//    if (bottom - top < m_textureSize.height())
//    {
//        y = (top + shrinkAmount) / m_textureSize.height();
//        height = (bottom - top - (2.0 * shrinkAmount)) / m_textureSize.height();
//    }

//    m_subRect = QRectF(x, y, width, height);

//    EGLImageKHR image;
//    if (!nemo_gst_video_texture_bind_frame(sink, &image))
//    {
//        if (m_textureId)
//        {
//            glDeleteTextures(1, &m_textureId);
//            m_textureId = 0;
//        }
//        nemo_gst_video_texture_release_frame(sink, NULL);
//        return false;
//    } else {
//        if (!m_textureId) {
//            glGenTextures(1, &m_textureId);
//            glBindTexture(GL_TEXTURE_EXTERNAL_OES, m_textureId);
//            glTexParameterf(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
//            glTexParameterf(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
//            glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
//            glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
//        } else {
//            glBindTexture(GL_TEXTURE_EXTERNAL_OES, m_textureId);
//        }
//        glEGLImageTargetTexture2DOES(GL_TEXTURE_EXTERNAL_OES, image);
//        m_updated = true;
//        return true;
//    }
    return true;
}

void QMLVideoTexture::invalidateTexture()
{
}

void QMLVideoTexture::releaseTexture()
{
    if (m_updated)
    {
        m_updated = false;
    }
}

class VideoMaterialShader : public QSGMaterialShader
{
public:
    static QSGMaterialType type;

    void updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect);
    char const *const *attributeNames() const;

protected:
    void initialize();

    const char *vertexShader() const;
    const char *fragmentShader() const;

private:
    int m_id_matrix = 0;
    int m_id_subrect = 0;
    int m_id_opacity = 0;
    int m_id_texture = 0;
};

void VideoMaterialShader::updateState(const RenderState &state, QSGMaterial *newEffect, QSGMaterial *oldEffect)
{
    QMLVideoMaterial *material = static_cast<QMLVideoMaterial *>(newEffect);

    if (state.isMatrixDirty())
    {
        program()->setUniformValue(m_id_matrix, state.combinedMatrix());
    }

    if (state.isOpacityDirty())
    {
        program()->setUniformValue(m_id_opacity, state.opacity());
    }

    if (!oldEffect)
    {
        program()->setUniformValue(m_id_texture, 0);
    }

    const QRectF subRect = material->m_texture->normalizedTextureSubRect();
    program()->setUniformValue(m_id_subrect, QVector4D(subRect.x(), subRect.y(), subRect.width(), subRect.height()));

    glActiveTexture(GL_TEXTURE0);
    material->m_texture->bind();
}

char const *const *VideoMaterialShader::attributeNames() const
{
    static char const *const attr[] = { "position", "texcoord", 0 };
    return attr;
}

void VideoMaterialShader::initialize()
{
    m_id_matrix = program()->uniformLocation("matrix");
    m_id_subrect = program()->uniformLocation("subrect");
    m_id_opacity = program()->uniformLocation("opacity");
    m_id_texture = program()->uniformLocation("texture");
}

QSGMaterialType VideoMaterialShader::type;

const char *VideoMaterialShader::vertexShader() const
{
    return  "\n uniform highp mat4 matrix;"
            "\n uniform highp vec4 subrect;"
            "\n attribute highp vec4 position;"
            "\n attribute highp vec2 texcoord;"
            "\n varying highp vec2 v_texcoord;"
            "\n void main(void)"
            "\n {"
            "\n     gl_Position = matrix * position;"
            "\n     v_texcoord = (texcoord * subrect.zw) + subrect.xy;"
            "\n }";
}

const char *VideoMaterialShader::fragmentShader() const
{
    return  "\n #extension GL_OES_EGL_image_external : require"
            "\n uniform samplerExternalOES texture;"
            "\n uniform lowp float opacity;\n"
            "\n varying highp vec2 v_texcoord;"
            "\n void main(void)"
            "\n {"
            "\n     gl_FragColor = opacity * texture2D(texture, v_texcoord.st);"
            "\n }";
}

QMLVideoMaterial::QMLVideoMaterial(QMLVideoTexture *texture)
    : m_texture(texture)
{
}

QSGMaterialShader *QMLVideoMaterial::createShader() const
{
    return new VideoMaterialShader;
}

QSGMaterialType *QMLVideoMaterial::type() const
{
    return &VideoMaterialShader::type;
}

int QMLVideoMaterial::compare(const QSGMaterial *other) const
{
    return m_texture - static_cast<const QMLVideoMaterial *>(other)->m_texture;
}

QMLVideoNode::QMLVideoNode(QMLVideoTexture *texture)
    : m_material(texture)
    , m_geometry(QSGGeometry::defaultAttributes_TexturedPoint2D(), 4)
{
    setGeometry(&m_geometry);
    setMaterial(&m_material);
    setFlag(UsePreprocess);
}

QMLVideoNode::~QMLVideoNode()
{
    //m_material.m_texture->deleteLater();
}

void QMLVideoNode::preprocess()
{
    QMLVideoTexture *t = m_material.m_texture;
    if (t && t->updateTexture())
    {
        markDirty(QSGNode::DirtyMaterial);
    }
}

void QMLVideoNode::setBoundingRect(const QRectF &rect, int orientation, bool horizontalMirror, bool verticalMirror)
{
    // Texture vertices clock wise from top left: or tl, tr, br, lf
    // Vertex order is tl, bl, tr, br. So unrotated the texture indexes are [0, 3, 1, 2] and
    // by shifting the array left and wrapping we rotate the image in 90 degree increments.
    const float tx[] = { 0, 1, 1, 0 };
    const float ty[] = { 0, 0, 1, 1 };

    // Texture coordinates are 0, or 1 so flip by subtracting the cooridinate from 1 and
    // taking the absolute value. 1 - 0 = 1, 1 - 1 = 0.  The absolute of 0 take the coordinate
    // gives back the original value. 0 - 0 = 0, 0 - 1 = -1.
    const float hm = horizontalMirror ? 1 : 0;
    const float vm = verticalMirror ? 1 : 0;

    const int offset = orientation / 90;
    QSGGeometry::TexturedPoint2D vertices[] =
    {
        { (float)rect.left() , (float)rect.top()   , qAbs(hm - tx[(0 + offset) % 4]), qAbs(vm - ty[(0 + offset) % 4]) },
        { (float)rect.left() , (float)rect.bottom(), qAbs(hm - tx[(3 + offset) % 4]), qAbs(vm - ty[(3 + offset) % 4]) },
        { (float)rect.right(), (float)rect.top()   , qAbs(hm - tx[(1 + offset) % 4]), qAbs(vm - ty[(1 + offset) % 4]) },
        { (float)rect.right(), (float)rect.bottom(), qAbs(hm - tx[(2 + offset) % 4]), qAbs(vm - ty[(2 + offset) % 4]) }
    };

    memcpy(m_geometry.vertexDataAsTexturedPoint2D(), vertices, sizeof(vertices));
}

/*----------------------------------------------------------------------
|    VideoSurface::VideoSurface
+---------------------------------------------------------------------*/
QMLVideoSurface::QMLVideoSurface(QQuickItem *parent)
    : QQuickItem(parent)
{
    setFlag(QQuickItem::ItemHasContents, true);

//    QTimer* timer = new QTimer;
//    connect(timer, SIGNAL(timeout()), this, SLOT(doUpdate()));
//    timer->setSingleShot(false);
//    timer->start(1);
}

void QMLVideoSurface::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)
{
    QQuickItem::geometryChanged(newGeometry, oldGeometry);
    if (newGeometry != oldGeometry)
    {
        m_isGeomertyDirty = true;
    }
}

/*----------------------------------------------------------------------
|    VideoSurface::paint
+---------------------------------------------------------------------*/
QSGNode* QMLVideoSurface::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *)
{
    QMLVideoNode* node = static_cast<QMLVideoNode*>(oldNode);

    if (!s_videoTexture)
    {
        return nullptr;
    }

    if (!node)
    {
        node = new QMLVideoNode(s_videoTexture);
        m_isGeomertyDirty = true;
    }

    std::lock_guard<std::mutex> lg(s_videoDataMutex);

    if (m_isGeomertyDirty || s_videoResolutionDirty)
    {
        QLOGI("Resolution changed to: {}", s_videoResolution);
        const QRectF br = boundingRect();
        QRectF rect = QRectF(QPointF(0, 0), QSizeF(s_videoResolution.x, s_videoResolution.y).scaled(br.size(), Qt::KeepAspectRatio));
        rect.moveCenter(br.center());

        //align left, top
//        float dx = (br.width() - rect.width()) / 2.f;
//        float dy = (br.height() - rect.height()) / 2.f;
//        rect.translate(-dx, -dy);

        int orientation = 0;//(m_orientation - m_textureOrientation) % 360;
        if (orientation < 0)
            orientation += 360;
        node->setBoundingRect(
                    rect,
                    orientation,
                    false,
                    false);
        node->markDirty(QSGNode::DirtyGeometry);

        QLOGI("Node rect size: {}x{}", rect.width(), rect.height());

        m_isGeomertyDirty = false;
        s_videoResolutionDirty = false;
    }

    node->markDirty(QSGNode::DirtyMaterial);
    update();

    return node;
}

void QMLVideoSurface::init(Video_Decoder& decoder)
{
    if (!s_videoTexture)
    {
        s_videoTexture = new QMLVideoTexture(decoder.get_video_texture_id());
    }
}

void QMLVideoSurface::setResolution(math::vec2u16 const& resolution)
{
    std::lock_guard<std::mutex> lg(s_videoDataMutex);
    if (s_videoResolution != resolution)
    {
        //s_videoResolution = math::vec2u16(1280, 720);
        s_videoResolution = resolution;
        s_videoResolutionDirty = true;
    }
}

<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// drop_plan.cpp
//
// Identification: src/planner/drop_plan.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "planner/update_plan.h"

#include "planner/project_info.h"
#include "common/types.h"

#include "storage/data_table.h"
#include "catalog/bootstrapper.h"
#include "parser/statement_update.h"
#include "parser/table_ref.h"

namespace peloton {
namespace planner {

UpdatePlan::UpdatePlan(storage::DataTable *table,
		std::unique_ptr<const planner::ProjectInfo> project_info) :
		target_table_(table), project_info_(std::move(project_info)), updates(
				NULL), where(NULL) {
}

UpdatePlan::UpdatePlan(parser::UpdateStatement *parse_tree) {
	auto t_ref = parse_tree->table;
	table_name = std::string(t_ref->name);
	target_table_ = catalog::Bootstrapper::global_catalog->GetTableFromDatabase(
			DEFAULT_DB_NAME, table_name);
	updates = new std::vector<parser::UpdateClause*>();
	for(auto update : *parse_tree->updates) {
		updates->emplace_back(update->Copy());
	}

	TargetList tlist;
	DirectMapList dmlist;
	oid_t col_id;
	auto schema = target_table_->GetSchema();

	std::vector<oid_t> columns;
	for (auto update : *updates) {

		// get oid_t of the column and push it to the vector;
		col_id = schema->GetColumnID(std::string(update->column));

		LOG_INFO("This is the column ID -------------------------> %d" , col_id);

		columns.push_back(col_id);
		tlist.emplace_back(col_id, update->value);
	}

	for (uint i = 0; i < schema->GetColumns().size(); i++) {
		if(schema->GetColumns()[i].column_name != schema->GetColumns()[col_id].column_name)
		dmlist.emplace_back(i,
				std::pair<oid_t, oid_t>(0, i));
	}

	std::unique_ptr<const planner::ProjectInfo> project_info(
			new planner::ProjectInfo(std::move(tlist), std::move(dmlist)));
	project_info_ = std::move(project_info);

	where = parse_tree->where->Copy();
	auto expr = where->Copy();

	ReplaceColumnExpressions(expr);
	// auto right_expr = (expression::AbstractExpression*)expr->GetRight();
	// auto left_expr = (expression::AbstractExpression*)expr->GetLeft();

	// std::unique_ptr<expression::AbstractExpression> unique_right_expr(std::move(right_expr));
	// std::unique_ptr<expression::AbstractExpression> unique_left_expr(std::move(left_expr));

	// LOG_INFO("right_expr TYPE =========-----------------> %s" ,ExpressionTypeToString(right_expr->GetExpressionType()).c_str());
	// LOG_INFO("left_expr TYPE =========-----------------> %s" ,ExpressionTypeToString(left_expr->GetExpressionType()).c_str());

	// auto predicate = new expression::ComparisonExpression<expression::CmpGt>(
 //      expr->GetExpressionType(), unique_left_expr.release(), unique_right_expr.release());

	std::unique_ptr<planner::SeqScanPlan> seq_scan_node(
			new planner::SeqScanPlan(target_table_, expr, columns));
	AddChild(std::move(seq_scan_node));
}

void UpdatePlan::ReplaceColumnExpressions(expression::AbstractExpression* expression) {
  LOG_INFO("Expression Type --> %s", ExpressionTypeToString(expression->GetExpressionType()).c_str());
  LOG_INFO("Left Type --> %s", ExpressionTypeToString(expression->GetLeft()->GetExpressionType()).c_str());
  LOG_INFO("Right Type --> %s", ExpressionTypeToString(expression->GetRight()->GetExpressionType()).c_str());
  if(expression->GetLeft()->GetExpressionType() == EXPRESSION_TYPE_COLUMN_REF) {
    auto expr = expression->GetLeft();
    std::string col_name(expr->getName());
    LOG_INFO("Column name: %s", col_name.c_str());
    delete expr;
    expression->setLeft(ConvertToTupleValueExpression(col_name));
  }
  else if (expression->GetRight()->GetExpressionType() == EXPRESSION_TYPE_COLUMN_REF) {
    auto expr = expression->GetRight();
    std::string col_name(expr->getName());
    LOG_INFO("Column name: %s", col_name.c_str());
    delete expr;
    expression->setRight(ConvertToTupleValueExpression(col_name));
  }
  else {
	  ReplaceColumnExpressions(expression->GetModifiableLeft());
	  ReplaceColumnExpressions(expression->GetModifiableRight());

  }
}
/**
 * This function generates a TupleValue expression from the column name
 */
expression::AbstractExpression* UpdatePlan::ConvertToTupleValueExpression (std::string column_name) {
	auto schema = target_table_->GetSchema();
    auto column_id = schema->GetColumnID(column_name);
    LOG_INFO("Column id in table: %u", column_id);
    expression::TupleValueExpression *expr =
        new expression::TupleValueExpression(schema->GetType(column_id), 0, column_id);
	return expr;
}

}  // namespace planner
}  // namespace peloton
<commit_msg>Resolving conflicts<commit_after>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// drop_plan.cpp
//
// Identification: src/planner/drop_plan.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "planner/update_plan.h"

#include "planner/project_info.h"
#include "common/types.h"

#include "storage/data_table.h"
#include "catalog/bootstrapper.h"
#include "parser/statement_update.h"
#include "parser/table_ref.h"

namespace peloton {
namespace planner {

UpdatePlan::UpdatePlan(storage::DataTable *table,
		std::unique_ptr<const planner::ProjectInfo> project_info) :
		target_table_(table), project_info_(std::move(project_info)), updates(
				NULL), where(NULL) {
}

UpdatePlan::UpdatePlan(parser::UpdateStatement *parse_tree) {
	auto t_ref = parse_tree->table;
	table_name = std::string(t_ref->name);
	target_table_ = catalog::Bootstrapper::global_catalog->GetTableFromDatabase(
			DEFAULT_DB_NAME, table_name);

	updates = new std::vector<parser::UpdateClause*>();
	for(auto update : *parse_tree->updates) {
		updates->emplace_back(update->Copy());
	}

	TargetList tlist;
	DirectMapList dmlist;
	oid_t col_id;
	auto schema = target_table_->GetSchema();

	std::vector<oid_t> columns;
	for (auto update : *updates) {

		// get oid_t of the column and push it to the vector;
		col_id = schema->GetColumnID(std::string(update->column));

		LOG_INFO("This is the column ID -------------------------> %d" , col_id);

		columns.push_back(col_id);
		tlist.emplace_back(col_id, update->value);
	}

	for (uint i = 0; i < schema->GetColumns().size(); i++) {
		if(schema->GetColumns()[i].column_name != schema->GetColumns()[col_id].column_name)
		dmlist.emplace_back(i,
				std::pair<oid_t, oid_t>(0, i));
	}

	std::unique_ptr<const planner::ProjectInfo> project_info(
			new planner::ProjectInfo(std::move(tlist), std::move(dmlist)));
	project_info_ = std::move(project_info);

	auto expr = parse_tree->where->Copy();
	ReplaceColumnExpressions(expr);

	std::unique_ptr<planner::SeqScanPlan> seq_scan_node(
			new planner::SeqScanPlan(target_table_, expr, columns));
	AddChild(std::move(seq_scan_node));
}

void UpdatePlan::ReplaceColumnExpressions(expression::AbstractExpression* expression) {
  LOG_INFO("Expression Type --> %s", ExpressionTypeToString(expression->GetExpressionType()).c_str());
  LOG_INFO("Left Type --> %s", ExpressionTypeToString(expression->GetLeft()->GetExpressionType()).c_str());
  LOG_INFO("Right Type --> %s", ExpressionTypeToString(expression->GetRight()->GetExpressionType()).c_str());
  if(expression->GetLeft()->GetExpressionType() == EXPRESSION_TYPE_COLUMN_REF) {
    auto expr = expression->GetLeft();
    std::string col_name(expr->getName());
    LOG_INFO("Column name: %s", col_name.c_str());
    delete expr;
    expression->setLeft(ConvertToTupleValueExpression(col_name));
  }
  else if (expression->GetRight()->GetExpressionType() == EXPRESSION_TYPE_COLUMN_REF) {
    auto expr = expression->GetRight();
    std::string col_name(expr->getName());
    LOG_INFO("Column name: %s", col_name.c_str());
    delete expr;
    expression->setRight(ConvertToTupleValueExpression(col_name));
  }
  else {
	  ReplaceColumnExpressions(expression->GetModifiableLeft());
	  ReplaceColumnExpressions(expression->GetModifiableRight());

  }
}
/**
 * This function generates a TupleValue expression from the column name
 */
expression::AbstractExpression* UpdatePlan::ConvertToTupleValueExpression (std::string column_name) {
	auto schema = target_table_->GetSchema();
    auto column_id = schema->GetColumnID(column_name);
    LOG_INFO("Column id in table: %u", column_id);
    expression::TupleValueExpression *expr =
        new expression::TupleValueExpression(schema->GetType(column_id), 0, column_id);
	return expr;
}

}  // namespace planner
}  // namespace peloton
<|endoftext|>


<commit_before><commit_msg>Quality of life<commit_after><|endoftext|>