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

#ifndef DBAUI_JOINCONTROLLER_HXX
#include "JoinController.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XSQLQUERYCOMPOSER_HPP_
#include <com/sun/star/sdb/XSQLQueryComposer.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATTER_HPP_
#include <com/sun/star/util/XNumberFormatter.hpp>
#endif
#ifndef DBAUI_QUERYVIEW_HXX
#include "queryview.hxx"
#endif
#ifndef _UNDO_HXX
#include <svtools/undo.hxx>
#endif
#ifndef _CONNECTIVITY_PARSE_SQLITERATOR_HXX_
#include <connectivity/sqliterator.hxx>
#endif
#ifndef _CONNECTIVITY_SQLPARSE_HXX
#include <connectivity/sqlparse.hxx>
#endif
#ifndef _CONNECTIVITY_SQLNODE_HXX
#include <connectivity/sqlnode.hxx>
#endif
#ifndef _COM_SUN_STAR_IO_XOBJECTOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XObjectOutputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOBJECTINPUTSTREAM_HPP_
#include <com/sun/star/io/XObjectInputStream.hpp>
#endif
#ifndef DBAUI_JOINTABLEVIEW_HXX
#include "JoinTableView.hxx"
#endif
#ifndef SVX_QUERYDESIGNCONTEXT_HXX
#include "svx/ParseContext.hxx"
#endif
#ifndef DBAUI_QUERYCONTAINERWINDOW_HXX
#include "querycontainerwindow.hxx"
#endif
#ifndef DBAUI_TABLEFIELDDESC_HXX
#include "TableFieldDescription.hxx"
#endif

class VCLXWindow;
namespace dbaui
{
    class OQueryView;
    class OQueryContainerWindow;
    class OTableConnectionData;
    class OTableWindowData;
    class OAddTableDlg;
    class OTableFieldDesc;
    class OQueryTableWindow;

    class OQueryController : public OJoinController
    {
        OTableFields                            m_vTableFieldDesc;
        OTableFields                            m_vUnUsedFieldsDesc; // contains fields which aren't visible and don't have any criteria

        ::svxform::OSystemParseContext*             m_pParseContext;
        ::connectivity::OSQLParser*             m_pSqlParser;   // to parse sql statements
        ::connectivity::OSQLParseTreeIterator*  m_pSqlIterator; // to iterate through them
        ::std::vector<sal_uInt32>               m_vColumnWidth;

        ::com::sun::star::uno::Reference< ::com::sun::star::sdb::XSQLQueryComposer >    m_xComposer;
        ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >    m_xFormatter;   // a number formatter working with the connection's NumberFormatsSupplier

        ::rtl::OUString m_sStatement;           // contains the sql statement
        ::rtl::OUString m_sUpdateCatalogName;   // catalog for update data
        ::rtl::OUString m_sUpdateSchemaName;    // schema for update data
        ::rtl::OUString m_sUpdateTableName;     // table for update data
        ::rtl::OUString m_sName;                // name of the query

        sal_Int32       m_nVisibleRows;     // which rows the selection browse should show
        sal_Int32       m_nSplitPos;        // the position of the splitter
        sal_Bool        m_bDesign;          // if design is true then we show the complete design otherwise only the text format
        sal_Bool        m_bDistinct;        // true when you want "select distinct" otherwise false
        sal_Bool        m_bViewAlias;       // show the alias row in the design view
        sal_Bool        m_bViewTable;       // show the table row in the design view
        sal_Bool        m_bViewFunction;    // show the function row in the design view
        sal_Bool        m_bEsacpeProcessing;// is true when we shouldn't parse the statement
        sal_Bool        m_bCreateView;      // set to true when we should create a view otherwise we create a normal query
        sal_Bool        m_bIndependent;     // are we creating an "independent" SQL command (which does *not* belong to a data source)?

        ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess> getElements() const;
        sal_Bool askForNewName( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess>& _xElements,
                            sal_Bool _bSaveAs);
        // creates the querycomposer
        void setQueryComposer();
        void deleteIterator();
        void executeQuery();
        void doSaveAsDoc(sal_Bool _bSaveAs);

        void saveViewSettings(::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue>& _rViewProps);
        void loadViewSettings(const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue>& _rViewProps);
        ::rtl::OUString translateStatement( bool _bFireStatementChange = true );

    protected:
        // all the features which should be handled by this class
        virtual void            describeSupportedFeatures();
        // state of a feature. 'feature' may be the handle of a ::com::sun::star::util::URL somebody requested a dispatch interface for OR a toolbar slot.
        virtual FeatureState    GetState(sal_uInt16 nId) const;
        // execute a feature
        virtual void            Execute(sal_uInt16 nId, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue>& aArgs);

        virtual void            reconnect( sal_Bool _bUI );
        virtual void            updateTitle( );

        OQueryContainerWindow*  getContainer() const { return static_cast< OQueryContainerWindow* >( getView() ); }

    public:
        OQueryController(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM);

        ~OQueryController();
        OTableFields&   getTableFieldDesc()         { return m_vTableFieldDesc; }
        OTableFields&   getUnUsedFields()           { return m_vUnUsedFieldsDesc; }

        void            clearFields();

        virtual void    setModified(sal_Bool _bModified=sal_True);

        // should the statement be parsed by our own sql parser
        sal_Bool        isEsacpeProcessing()    const { return m_bEsacpeProcessing; }
        sal_Bool        isDesignMode()          const { return m_bDesign; }
        sal_Bool        isDistinct()            const { return m_bDistinct; }

        ::rtl::OUString getStatement()          const { return m_sStatement; }
        sal_Int32       getSplitPos()           const { return m_nSplitPos;}
        sal_Int32       getVisibleRows()        const { return m_nVisibleRows; }

        void            setDistinct(sal_Bool _bDistinct)        { m_bDistinct = _bDistinct;}
        void            setSplitPos(sal_Int32 _nSplitPos)       { m_nSplitPos = _nSplitPos;}
        void            setVisibleRows(sal_Int32 _nVisibleRows) { m_nVisibleRows = _nVisibleRows;}

        ::connectivity::OSQLParser*             getParser()         { return m_pSqlParser;  }
        ::connectivity::OSQLParseTreeIterator&  getParseIterator()  { return *m_pSqlIterator; }
        sal_uInt32 getColWidth(sal_uInt16 _nPos) const
        {
            return m_vColumnWidth.size() < _nPos ? m_vColumnWidth[_nPos] : sal_uInt32(0);
        }

        virtual sal_Bool Construct(Window* pParent);

        ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >    getNumberFormatter()const   { return m_xFormatter; }
        // XEventListener
        virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw(::com::sun::star::uno::RuntimeException);

        // ::com::sun::star::lang::XComponent
        virtual void        SAL_CALL disposing();

        // XServiceInfo
        virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);
        // need by registration
        static ::rtl::OUString getImplementationName_Static() throw( ::com::sun::star::uno::RuntimeException );
        static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(void) throw( ::com::sun::star::uno::RuntimeException );
        static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
                SAL_CALL Create(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&);

    protected:
        virtual void    onLoadedMenu(const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XLayoutManager >& _xLayoutManager);

        virtual OTableWindowData* createTableWindowData();
        virtual OJoinDesignView*  getJoinView();
        // ask the user if the design should be saved when it is modified
        virtual short saveModified();
        virtual void reset();
        virtual void impl_initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments );

        void        resetImpl();

        /// sets m_sStatement, and notifies our respective property change listeners
        void    setStatement_fireEvent( const ::rtl::OUString& _rNewStatement, bool _bFireStatementChange = true );

    private:
        DECL_LINK( OnExecuteAddTable, void* );
    };
}
#endif // DBAUI_QUERYCONTROLLER_HXX

<commit_msg>INTEGRATION: CWS qiq (1.32.124); FILE MERGED 2006/05/17 04:30:48 fs 1.32.124.3: #i51143# changed signature of OSQLParseTreeIterator 2006/05/12 13:47:01 fs 1.32.124.2: #i51143# refactoring of controller initialization, which allows accessing the load arguments even during Construct (and not only in the - later - impl_initialize) 2006/05/12 11:09:55 fs 1.32.124.1: #i51143# +allowViews/+allowQueries<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: querycontroller.hxx,v $
 *
 *  $Revision: 1.33 $
 *
 *  last change: $Author: obo $ $Date: 2006-07-10 15:33:14 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef DBAUI_QUERYCONTROLLER_HXX
#define DBAUI_QUERYCONTROLLER_HXX

#ifndef DBAUI_JOINCONTROLLER_HXX
#include "JoinController.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_SDB_XSQLQUERYCOMPOSER_HPP_
#include <com/sun/star/sdb/XSQLQueryComposer.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATTER_HPP_
#include <com/sun/star/util/XNumberFormatter.hpp>
#endif
#ifndef DBAUI_QUERYVIEW_HXX
#include "queryview.hxx"
#endif
#ifndef _UNDO_HXX
#include <svtools/undo.hxx>
#endif
#ifndef _CONNECTIVITY_PARSE_SQLITERATOR_HXX_
#include <connectivity/sqliterator.hxx>
#endif
#ifndef _CONNECTIVITY_SQLPARSE_HXX
#include <connectivity/sqlparse.hxx>
#endif
#ifndef _CONNECTIVITY_SQLNODE_HXX
#include <connectivity/sqlnode.hxx>
#endif
#ifndef _COM_SUN_STAR_IO_XOBJECTOUTPUTSTREAM_HPP_
#include <com/sun/star/io/XObjectOutputStream.hpp>
#endif
#ifndef _COM_SUN_STAR_IO_XOBJECTINPUTSTREAM_HPP_
#include <com/sun/star/io/XObjectInputStream.hpp>
#endif
#ifndef DBAUI_JOINTABLEVIEW_HXX
#include "JoinTableView.hxx"
#endif
#ifndef SVX_QUERYDESIGNCONTEXT_HXX
#include "svx/ParseContext.hxx"
#endif
#ifndef DBAUI_QUERYCONTAINERWINDOW_HXX
#include "querycontainerwindow.hxx"
#endif
#ifndef DBAUI_TABLEFIELDDESC_HXX
#include "TableFieldDescription.hxx"
#endif

class VCLXWindow;
namespace dbaui
{
    class OQueryView;
    class OQueryContainerWindow;
    class OTableConnectionData;
    class OTableWindowData;
    class OAddTableDlg;
    class OTableFieldDesc;
    class OQueryTableWindow;

    class OQueryController : public OJoinController
    {
        OTableFields                            m_vTableFieldDesc;
        OTableFields                            m_vUnUsedFieldsDesc; // contains fields which aren't visible and don't have any criteria

        ::svxform::OSystemParseContext*         m_pParseContext;
        ::connectivity::OSQLParser              m_aSqlParser;
        ::connectivity::OSQLParseTreeIterator*  m_pSqlIterator;
        ::std::vector<sal_uInt32>               m_vColumnWidth;

        ::com::sun::star::uno::Reference< ::com::sun::star::sdb::XSQLQueryComposer >    m_xComposer;
        ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >    m_xFormatter;   // a number formatter working with the connection's NumberFormatsSupplier

        ::rtl::OUString m_sStatement;           // contains the sql statement
        ::rtl::OUString m_sUpdateCatalogName;   // catalog for update data
        ::rtl::OUString m_sUpdateSchemaName;    // schema for update data
        ::rtl::OUString m_sUpdateTableName;     // table for update data
        ::rtl::OUString m_sName;                // name of the query

        sal_Int32       m_nVisibleRows;     // which rows the selection browse should show
        sal_Int32       m_nSplitPos;        // the position of the splitter
        sal_Bool        m_bDesign;          // if design is true then we show the complete design otherwise only the text format
        sal_Bool        m_bDistinct;        // true when you want "select distinct" otherwise false
        sal_Bool        m_bViewAlias;       // show the alias row in the design view
        sal_Bool        m_bViewTable;       // show the table row in the design view
        sal_Bool        m_bViewFunction;    // show the function row in the design view
        sal_Bool        m_bEsacpeProcessing;// is true when we shouldn't parse the statement
        sal_Bool        m_bCreateView;      // set to true when we should create a view otherwise we create a normal query
        sal_Bool        m_bIndependent;     // are we creating an "independent" SQL command (which does *not* belong to a data source)?

        ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess> getElements() const;
        sal_Bool askForNewName( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess>& _xElements,
                            sal_Bool _bSaveAs);
        // creates the querycomposer
        void setQueryComposer();
        void deleteIterator();
        void executeQuery();
        void doSaveAsDoc(sal_Bool _bSaveAs);

        void saveViewSettings(::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue>& _rViewProps);
        void loadViewSettings(const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue>& _rViewProps);
        ::rtl::OUString translateStatement( bool _bFireStatementChange = true );

    protected:
        // all the features which should be handled by this class
        virtual void            describeSupportedFeatures();
        // state of a feature. 'feature' may be the handle of a ::com::sun::star::util::URL somebody requested a dispatch interface for OR a toolbar slot.
        virtual FeatureState    GetState(sal_uInt16 nId) const;
        // execute a feature
        virtual void            Execute(sal_uInt16 nId, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue>& aArgs);

        virtual void            reconnect( sal_Bool _bUI );
        virtual void            updateTitle( );

        OQueryContainerWindow*  getContainer() const { return static_cast< OQueryContainerWindow* >( getView() ); }

    public:
        OQueryController(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM);

        ~OQueryController();
        OTableFields&   getTableFieldDesc()         { return m_vTableFieldDesc; }
        OTableFields&   getUnUsedFields()           { return m_vUnUsedFieldsDesc; }

        void            clearFields();

        virtual void    setModified(sal_Bool _bModified=sal_True);

        // should the statement be parsed by our own sql parser
        sal_Bool        isEsacpeProcessing()    const { return m_bEsacpeProcessing; }
        sal_Bool        isDesignMode()          const { return m_bDesign; }
        sal_Bool        isDistinct()            const { return m_bDistinct; }

        ::rtl::OUString getStatement()          const { return m_sStatement; }
        sal_Int32       getSplitPos()           const { return m_nSplitPos;}
        sal_Int32       getVisibleRows()        const { return m_nVisibleRows; }

        void            setDistinct(sal_Bool _bDistinct)        { m_bDistinct = _bDistinct;}
        void            setSplitPos(sal_Int32 _nSplitPos)       { m_nSplitPos = _nSplitPos;}
        void            setVisibleRows(sal_Int32 _nVisibleRows) { m_nVisibleRows = _nVisibleRows;}

        ::connectivity::OSQLParser&             getParser()         { return m_aSqlParser;  }
        ::connectivity::OSQLParseTreeIterator&  getParseIterator()  { return *m_pSqlIterator; }
        sal_uInt32 getColWidth(sal_uInt16 _nPos) const
        {
            return m_vColumnWidth.size() < _nPos ? m_vColumnWidth[_nPos] : sal_uInt32(0);
        }

        virtual sal_Bool Construct(Window* pParent);

        ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter >    getNumberFormatter()const   { return m_xFormatter; }
        // XEventListener
        virtual void SAL_CALL disposing( const ::com::sun::star::lang::EventObject& Source ) throw(::com::sun::star::uno::RuntimeException);

        // ::com::sun::star::lang::XComponent
        virtual void        SAL_CALL disposing();

        // XServiceInfo
        virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);
        // need by registration
        static ::rtl::OUString getImplementationName_Static() throw( ::com::sun::star::uno::RuntimeException );
        static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(void) throw( ::com::sun::star::uno::RuntimeException );
        static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
                SAL_CALL Create(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&);

    protected:
        virtual void    onLoadedMenu(const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XLayoutManager >& _xLayoutManager);

        virtual OTableWindowData* createTableWindowData();
        virtual OJoinDesignView*  getJoinView();
        // ask the user if the design should be saved when it is modified
        virtual short saveModified();
        virtual void reset();
        virtual void impl_initialize();

        void        resetImpl();

        /// sets m_sStatement, and notifies our respective property change listeners
        void    setStatement_fireEvent( const ::rtl::OUString& _rNewStatement, bool _bFireStatementChange = true );

        // OJoinController overridables
        virtual bool allowViews() const;
        virtual bool allowQueries() const;

    private:
        DECL_LINK( OnExecuteAddTable, void* );
    };
}
#endif // DBAUI_QUERYCONTROLLER_HXX

<|endoftext|>


<commit_before>/**
 * Daniel Sebastian Iliescu, http://dansil.net
 * MIT License (MIT), http://opensource.org/licenses/MIT
 *
 * Tester for the various sorting algorithms.
 */

#include "sorts/bubble_sort.hpp"
#include "sorts/selection_sort.hpp"
#include "sorts/insertion_sort.hpp"
#include "sorts/merge_sort.hpp"
#include "sorts/quick_sort.hpp"

#include "utilities/generator.hpp"

#include <catch.hpp>

namespace
{
	const std::string UNIT_NAME = "sort_";
}

namespace dsa
{
	template< typename SortImplementation >
	void sort_tester()
	{
		using value_type = std::int32_t;
		constexpr auto ITERATIONS = 1000U;

		std::array< value_type, ITERATIONS > container;

		generator< value_type > generator;
		generator.fill_buffer(
			std::begin( container ),
			std::end( container ) );

		SortImplementation::sort(
			std::begin( container ),
			std::end( container ) );

		REQUIRE(
			std::is_sorted(
				std::cbegin( container ),
				std::cend( container ) ) );
	}

	TEST_CASE( ( UNIT_NAME + "bubble sort" ).c_str() )
	{
		sort_tester< bubble >();
	}

	TEST_CASE( ( UNIT_NAME + "selection sort (std implementation)" ).c_str() )
	{
		sort_tester< selection::std_implementation >();
	}

	TEST_CASE( ( UNIT_NAME + "selection sort (custom implementation)" ).c_str() )
	{
		sort_tester< selection::custom_implementation >();
	}

	TEST_CASE( ( UNIT_NAME + "insertion sort (std implementation)" ).c_str() )
	{
		sort_tester< insertion::std_implementation >();
	}

	TEST_CASE( ( UNIT_NAME + "insertion sort (custom implementation)" ).c_str() )
	{
		sort_tester< insertion::custom_implementation >();
	}

	TEST_CASE( ( UNIT_NAME + "merge sort (std implementation)" ).c_str() )
	{
		sort_tester< merge::std_implementation >();
	}

	TEST_CASE( ( UNIT_NAME + "merge sort (custom implementation)" ).c_str() )
	{
		sort_tester< merge::custom_implementation >();
	}

	TEST_CASE( ( UNIT_NAME + "quick sort" ).c_str() )
	{
		sort_tester< quick::std_implementation >();
	}

	TEST_CASE( ( UNIT_NAME + "quick sort (custom implementation)" ).c_str() )
	{
		sort_tester< quick::custom_implementation >();
	}

}
<commit_msg>Fix clang failures<commit_after>/**
 * Daniel Sebastian Iliescu, http://dansil.net
 * MIT License (MIT), http://opensource.org/licenses/MIT
 *
 * Tester for the various sorting algorithms.
 */

#include "sorts/bubble_sort.hpp"
#include "sorts/selection_sort.hpp"
#include "sorts/insertion_sort.hpp"
#include "sorts/merge_sort.hpp"
#include "sorts/quick_sort.hpp"

#include "utilities/generator.hpp"

#include <catch.hpp>

#include <array>

namespace
{
	const std::string UNIT_NAME = "sort_";
}

namespace dsa
{
	template< typename SortImplementation >
	void sort_tester()
	{
		using value_type = std::int32_t;
		constexpr auto ITERATIONS = 1000U;

		std::array< value_type, ITERATIONS > container;

		generator< value_type > generator;
		generator.fill_buffer(
			std::begin( container ),
			std::end( container ) );

		SortImplementation::sort(
			std::begin( container ),
			std::end( container ) );

		REQUIRE(
			std::is_sorted(
				std::cbegin( container ),
				std::cend( container ) ) );
	}

	TEST_CASE( ( UNIT_NAME + "bubble sort" ).c_str() )
	{
		sort_tester< bubble >();
	}

	TEST_CASE( ( UNIT_NAME + "selection sort (std implementation)" ).c_str() )
	{
		sort_tester< selection::std_implementation >();
	}

	TEST_CASE( ( UNIT_NAME + "selection sort (custom implementation)" ).c_str() )
	{
		sort_tester< selection::custom_implementation >();
	}

	TEST_CASE( ( UNIT_NAME + "insertion sort (std implementation)" ).c_str() )
	{
		sort_tester< insertion::std_implementation >();
	}

	TEST_CASE( ( UNIT_NAME + "insertion sort (custom implementation)" ).c_str() )
	{
		sort_tester< insertion::custom_implementation >();
	}

	TEST_CASE( ( UNIT_NAME + "merge sort (std implementation)" ).c_str() )
	{
		sort_tester< merge::std_implementation >();
	}

	TEST_CASE( ( UNIT_NAME + "merge sort (custom implementation)" ).c_str() )
	{
		sort_tester< merge::custom_implementation >();
	}

	TEST_CASE( ( UNIT_NAME + "quick sort" ).c_str() )
	{
		sort_tester< quick::std_implementation >();
	}

	TEST_CASE( ( UNIT_NAME + "quick sort (custom implementation)" ).c_str() )
	{
		sort_tester< quick::custom_implementation >();
	}

}
<|endoftext|>


<commit_before>// Copyright (c) 2017 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "shell/browser/api/electron_api_browser_view.h"

#include <vector>

#include "shell/browser/api/electron_api_web_contents.h"
#include "shell/browser/browser.h"
#include "shell/browser/native_browser_view.h"
#include "shell/browser/ui/drag_util.h"
#include "shell/common/color_util.h"
#include "shell/common/gin_converters/gfx_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "ui/gfx/geometry/rect.h"

namespace gin {

template <>
struct Converter<electron::AutoResizeFlags> {
  static bool FromV8(v8::Isolate* isolate,
                     v8::Local<v8::Value> val,
                     electron::AutoResizeFlags* auto_resize_flags) {
    gin_helper::Dictionary params;
    if (!ConvertFromV8(isolate, val, &params)) {
      return false;
    }

    uint8_t flags = 0;
    bool width = false;
    if (params.Get("width", &width) && width) {
      flags |= electron::kAutoResizeWidth;
    }
    bool height = false;
    if (params.Get("height", &height) && height) {
      flags |= electron::kAutoResizeHeight;
    }
    bool horizontal = false;
    if (params.Get("horizontal", &horizontal) && horizontal) {
      flags |= electron::kAutoResizeHorizontal;
    }
    bool vertical = false;
    if (params.Get("vertical", &vertical) && vertical) {
      flags |= electron::kAutoResizeVertical;
    }

    *auto_resize_flags = static_cast<electron::AutoResizeFlags>(flags);
    return true;
  }
};

}  // namespace gin

namespace {

int32_t GetNextId() {
  static int32_t next_id = 1;
  return next_id++;
}

}  // namespace

namespace electron {

namespace api {

gin::WrapperInfo BrowserView::kWrapperInfo = {gin::kEmbedderNativeGin};

BrowserView::BrowserView(gin::Arguments* args,
                         const gin_helper::Dictionary& options)
    : id_(GetNextId()) {
  v8::Isolate* isolate = args->isolate();
  gin_helper::Dictionary web_preferences =
      gin::Dictionary::CreateEmpty(isolate);
  options.Get(options::kWebPreferences, &web_preferences);
  web_preferences.Set("type", "browserView");

  v8::Local<v8::Value> value;

  // Copy the webContents option to webPreferences. This is only used internally
  // to implement nativeWindowOpen option.
  if (options.Get("webContents", &value)) {
    web_preferences.SetHidden("webContents", value);
  }

  auto web_contents =
      WebContents::CreateFromWebPreferences(args->isolate(), web_preferences);

  web_contents_.Reset(isolate, web_contents.ToV8());
  api_web_contents_ = web_contents.get();
  api_web_contents_->AddObserver(this);
  Observe(web_contents->web_contents());

  view_.reset(
      NativeBrowserView::Create(api_web_contents_->inspectable_web_contents()));
}

void BrowserView::SetOwnerWindow(NativeWindow* window) {
  // Ensure WebContents and BrowserView owner windows are in sync.
  if (web_contents())
    web_contents()->SetOwnerWindow(window);

  owner_window_ = window ? window->GetWeakPtr() : nullptr;
}

BrowserView::~BrowserView() {
  if (web_contents()) {  // destroy() called without closing WebContents
    web_contents()->RemoveObserver(this);
    web_contents()->Destroy();
  }
}

void BrowserView::WebContentsDestroyed() {
  api_web_contents_ = nullptr;
  web_contents_.Reset();
  Unpin();
}

void BrowserView::OnDraggableRegionsUpdated(
    const std::vector<mojom::DraggableRegionPtr>& regions) {
  view_->UpdateDraggableRegions(regions);
}

// static
gin::Handle<BrowserView> BrowserView::New(gin_helper::ErrorThrower thrower,
                                          gin::Arguments* args) {
  if (!Browser::Get()->is_ready()) {
    thrower.ThrowError("Cannot create BrowserView before app is ready");
    return gin::Handle<BrowserView>();
  }

  gin::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate());
  args->GetNext(&options);

  auto handle =
      gin::CreateHandle(args->isolate(), new BrowserView(args, options));
  handle->Pin(args->isolate());
  return handle;
}

void BrowserView::SetAutoResize(AutoResizeFlags flags) {
  view_->SetAutoResizeFlags(flags);
}

void BrowserView::SetBounds(const gfx::Rect& bounds) {
  view_->SetBounds(bounds);
}

gfx::Rect BrowserView::GetBounds() {
  return view_->GetBounds();
}

void BrowserView::SetBackgroundColor(const std::string& color_name) {
  if (!web_contents())
    return;

  auto* wc = web_contents()->web_contents();
  wc->SetPageBaseBackgroundColor(ParseHexColor(color_name));
}

v8::Local<v8::Value> BrowserView::GetWebContents(v8::Isolate* isolate) {
  if (web_contents_.IsEmpty()) {
    return v8::Null(isolate);
  }

  return v8::Local<v8::Value>::New(isolate, web_contents_);
}

// static
v8::Local<v8::ObjectTemplate> BrowserView::FillObjectTemplate(
    v8::Isolate* isolate,
    v8::Local<v8::ObjectTemplate> templ) {
  return gin::ObjectTemplateBuilder(isolate, "BrowserView", templ)
      .SetMethod("setAutoResize", &BrowserView::SetAutoResize)
      .SetMethod("setBounds", &BrowserView::SetBounds)
      .SetMethod("getBounds", &BrowserView::GetBounds)
      .SetMethod("setBackgroundColor", &BrowserView::SetBackgroundColor)
      .SetProperty("webContents", &BrowserView::GetWebContents)
      .Build();
}

}  // namespace api

}  // namespace electron

namespace {

using electron::api::BrowserView;

void Initialize(v8::Local<v8::Object> exports,
                v8::Local<v8::Value> unused,
                v8::Local<v8::Context> context,
                void* priv) {
  v8::Isolate* isolate = context->GetIsolate();

  gin_helper::Dictionary dict(isolate, exports);
  dict.Set("BrowserView", BrowserView::GetConstructor(context));
}

}  // namespace

NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_browser_view, Initialize)
<commit_msg>fix: BrowserView setBackgroundColor needs two calls (#31863)<commit_after>// Copyright (c) 2017 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "shell/browser/api/electron_api_browser_view.h"

#include <vector>

#include "shell/browser/api/electron_api_web_contents.h"
#include "shell/browser/browser.h"
#include "shell/browser/native_browser_view.h"
#include "shell/browser/ui/drag_util.h"
#include "shell/common/color_util.h"
#include "shell/common/gin_converters/gfx_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/object_template_builder.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "ui/gfx/geometry/rect.h"

namespace gin {

template <>
struct Converter<electron::AutoResizeFlags> {
  static bool FromV8(v8::Isolate* isolate,
                     v8::Local<v8::Value> val,
                     electron::AutoResizeFlags* auto_resize_flags) {
    gin_helper::Dictionary params;
    if (!ConvertFromV8(isolate, val, &params)) {
      return false;
    }

    uint8_t flags = 0;
    bool width = false;
    if (params.Get("width", &width) && width) {
      flags |= electron::kAutoResizeWidth;
    }
    bool height = false;
    if (params.Get("height", &height) && height) {
      flags |= electron::kAutoResizeHeight;
    }
    bool horizontal = false;
    if (params.Get("horizontal", &horizontal) && horizontal) {
      flags |= electron::kAutoResizeHorizontal;
    }
    bool vertical = false;
    if (params.Get("vertical", &vertical) && vertical) {
      flags |= electron::kAutoResizeVertical;
    }

    *auto_resize_flags = static_cast<electron::AutoResizeFlags>(flags);
    return true;
  }
};

}  // namespace gin

namespace {

int32_t GetNextId() {
  static int32_t next_id = 1;
  return next_id++;
}

}  // namespace

namespace electron {

namespace api {

gin::WrapperInfo BrowserView::kWrapperInfo = {gin::kEmbedderNativeGin};

BrowserView::BrowserView(gin::Arguments* args,
                         const gin_helper::Dictionary& options)
    : id_(GetNextId()) {
  v8::Isolate* isolate = args->isolate();
  gin_helper::Dictionary web_preferences =
      gin::Dictionary::CreateEmpty(isolate);
  options.Get(options::kWebPreferences, &web_preferences);
  web_preferences.Set("type", "browserView");

  v8::Local<v8::Value> value;

  // Copy the webContents option to webPreferences. This is only used internally
  // to implement nativeWindowOpen option.
  if (options.Get("webContents", &value)) {
    web_preferences.SetHidden("webContents", value);
  }

  auto web_contents =
      WebContents::CreateFromWebPreferences(args->isolate(), web_preferences);

  web_contents_.Reset(isolate, web_contents.ToV8());
  api_web_contents_ = web_contents.get();
  api_web_contents_->AddObserver(this);
  Observe(web_contents->web_contents());

  view_.reset(
      NativeBrowserView::Create(api_web_contents_->inspectable_web_contents()));
}

void BrowserView::SetOwnerWindow(NativeWindow* window) {
  // Ensure WebContents and BrowserView owner windows are in sync.
  if (web_contents())
    web_contents()->SetOwnerWindow(window);

  owner_window_ = window ? window->GetWeakPtr() : nullptr;
}

BrowserView::~BrowserView() {
  if (web_contents()) {  // destroy() called without closing WebContents
    web_contents()->RemoveObserver(this);
    web_contents()->Destroy();
  }
}

void BrowserView::WebContentsDestroyed() {
  api_web_contents_ = nullptr;
  web_contents_.Reset();
  Unpin();
}

void BrowserView::OnDraggableRegionsUpdated(
    const std::vector<mojom::DraggableRegionPtr>& regions) {
  view_->UpdateDraggableRegions(regions);
}

// static
gin::Handle<BrowserView> BrowserView::New(gin_helper::ErrorThrower thrower,
                                          gin::Arguments* args) {
  if (!Browser::Get()->is_ready()) {
    thrower.ThrowError("Cannot create BrowserView before app is ready");
    return gin::Handle<BrowserView>();
  }

  gin::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate());
  args->GetNext(&options);

  auto handle =
      gin::CreateHandle(args->isolate(), new BrowserView(args, options));
  handle->Pin(args->isolate());
  return handle;
}

void BrowserView::SetAutoResize(AutoResizeFlags flags) {
  view_->SetAutoResizeFlags(flags);
}

void BrowserView::SetBounds(const gfx::Rect& bounds) {
  view_->SetBounds(bounds);
}

gfx::Rect BrowserView::GetBounds() {
  return view_->GetBounds();
}

void BrowserView::SetBackgroundColor(const std::string& color_name) {
  view_->SetBackgroundColor(ParseHexColor(color_name));

  if (web_contents()) {
    auto* wc = web_contents()->web_contents();
    wc->SetPageBaseBackgroundColor(ParseHexColor(color_name));
  }
}

v8::Local<v8::Value> BrowserView::GetWebContents(v8::Isolate* isolate) {
  if (web_contents_.IsEmpty()) {
    return v8::Null(isolate);
  }

  return v8::Local<v8::Value>::New(isolate, web_contents_);
}

// static
v8::Local<v8::ObjectTemplate> BrowserView::FillObjectTemplate(
    v8::Isolate* isolate,
    v8::Local<v8::ObjectTemplate> templ) {
  return gin::ObjectTemplateBuilder(isolate, "BrowserView", templ)
      .SetMethod("setAutoResize", &BrowserView::SetAutoResize)
      .SetMethod("setBounds", &BrowserView::SetBounds)
      .SetMethod("getBounds", &BrowserView::GetBounds)
      .SetMethod("setBackgroundColor", &BrowserView::SetBackgroundColor)
      .SetProperty("webContents", &BrowserView::GetWebContents)
      .Build();
}

}  // namespace api

}  // namespace electron

namespace {

using electron::api::BrowserView;

void Initialize(v8::Local<v8::Object> exports,
                v8::Local<v8::Value> unused,
                v8::Local<v8::Context> context,
                void* priv) {
  v8::Isolate* isolate = context->GetIsolate();

  gin_helper::Dictionary dict(isolate, exports);
  dict.Set("BrowserView", BrowserView::GetConstructor(context));
}

}  // namespace

NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_browser_view, Initialize)
<|endoftext|>


<commit_before>/*
 * AbstractView_EventConsumption.cpp
 *
 * Copyright (C) 2020 by Universitaet Stuttgart (VIS).
 * Alle Rechte vorbehalten.
 */

#include "mmcore/view/AbstractView_EventConsumption.h"

#include "Framebuffer_Events.h"
#include "KeyboardMouse_Events.h"
#include "Window_Events.h"

#include <chrono>

namespace megamol {
namespace core {
namespace view {

using namespace megamol::frontend_resources;

// shorthand notation to unpack a FrontendResource to some type.
// if the type is present in the resource is made available as an 'events' variable in the if statemtnt.
// note that when using this macro there is no visible opening bracket { for the if statements because it is hidden inside the macro
#define GET_RESOURCE(TYPENAME) \
    { \
        TYPENAME const& events = resource.getResource<TYPENAME>();

void view_consume_keyboard_events(AbstractView& view, megamol::frontend::FrontendResource const& resource) {
    GET_RESOURCE(KeyboardEvents)//{
        for (auto& e : events.key_events)
            view.OnKey(std::get<0>(e), std::get<1>(e), std::get<2>(e));

        for (auto& e : events.codepoint_events)
            view.OnChar(e);
    }
}

void view_consume_mouse_events(AbstractView& view, megamol::frontend::FrontendResource const& resource) {
    GET_RESOURCE(MouseEvents)//{
        for (auto& e : events.buttons_events)
            view.OnMouseButton(std::get<0>(e), std::get<1>(e), std::get<2>(e));

        for (auto& e : events.position_events)
            view.OnMouseMove(std::get<0>(e), std::get<1>(e));

        for (auto& e : events.scroll_events)
            view.OnMouseScroll(std::get<0>(e), std::get<1>(e));

        //for (auto& e: events.enter_events) {}
    }
}

void view_consume_window_events(AbstractView& view, megamol::frontend::FrontendResource const& resource) {
    GET_RESOURCE(WindowEvents)//{
        events.is_focused_events;
    }
}

// this is a weird place to measure passed program time, but we do it here so we satisfy _mmcRenderViewContext and nobody else needs to know
static std::chrono::high_resolution_clock::time_point render_view_context_timer_start;

void view_poke_rendering(AbstractView& view, megamol::frontend_resources::RenderInput const& render_input, megamol::frontend_resources::ImageWrapper& result_image) {
    static bool started_timer = false;
    if (!started_timer) {
        render_view_context_timer_start = std::chrono::high_resolution_clock::now();
        started_timer = true;
    }

    const auto render = [&]() {
        const double instanceTime = std::chrono::duration_cast<std::chrono::milliseconds>(
            std::chrono::high_resolution_clock::now() - render_view_context_timer_start)
            .count() / static_cast<double>(1000);

        const double time = view.DefaultTime(instanceTime);

        result_image = view.Render(time, instanceTime);
    };

    render();
}

std::vector<std::string> get_view_runtime_resources_requests() {
    return {"ViewRenderInput", "KeyboardEvents", "MouseEvents", "WindowEvents"};
}

bool view_rendering_execution(
      void* module_ptr
    , std::vector<megamol::frontend::FrontendResource> const& resources
    , megamol::frontend_resources::ImageWrapper& result_image
) {
    megamol::core::view::AbstractView* view_ptr =
        dynamic_cast<megamol::core::view::AbstractView*>(static_cast<megamol::core::Module*>(module_ptr));

    if (!view_ptr) {
        std::cout << "error. module is not a view module. could not use as rendering entry point." << std::endl;
        return false;
    }

    megamol::core::view::AbstractView& view = *view_ptr;

    // resources are in order of initial requests from get_view_runtime_resources_requests()
    megamol::core::view::view_consume_keyboard_events(view, resources[1]);
    megamol::core::view::view_consume_mouse_events(view, resources[2]);
    megamol::core::view::view_consume_window_events(view, resources[3]);
    megamol::core::view::view_poke_rendering(view, resources[0].getResource<megamol::frontend_resources::RenderInput>(), result_image);

    return true;
}

} /* end namespace view */
} /* end namespace core */
} /* end namespace megamol */

<commit_msg>AbstractView EventConsumption uses RenderInput resolution<commit_after>/*
 * AbstractView_EventConsumption.cpp
 *
 * Copyright (C) 2020 by Universitaet Stuttgart (VIS).
 * Alle Rechte vorbehalten.
 */

#include "mmcore/view/AbstractView_EventConsumption.h"

#include "Framebuffer_Events.h"
#include "KeyboardMouse_Events.h"
#include "Window_Events.h"

#include <chrono>

namespace megamol {
namespace core {
namespace view {

using namespace megamol::frontend_resources;

// shorthand notation to unpack a FrontendResource to some type.
// if the type is present in the resource is made available as an 'events' variable in the if statemtnt.
// note that when using this macro there is no visible opening bracket { for the if statements because it is hidden inside the macro
#define GET_RESOURCE(TYPENAME) \
    { \
        TYPENAME const& events = resource.getResource<TYPENAME>();

void view_consume_keyboard_events(AbstractView& view, megamol::frontend::FrontendResource const& resource) {
    GET_RESOURCE(KeyboardEvents)//{
        for (auto& e : events.key_events)
            view.OnKey(std::get<0>(e), std::get<1>(e), std::get<2>(e));

        for (auto& e : events.codepoint_events)
            view.OnChar(e);
    }
}

void view_consume_mouse_events(AbstractView& view, megamol::frontend::FrontendResource const& resource) {
    GET_RESOURCE(MouseEvents)//{
        for (auto& e : events.buttons_events)
            view.OnMouseButton(std::get<0>(e), std::get<1>(e), std::get<2>(e));

        for (auto& e : events.position_events)
            view.OnMouseMove(std::get<0>(e), std::get<1>(e));

        for (auto& e : events.scroll_events)
            view.OnMouseScroll(std::get<0>(e), std::get<1>(e));

        //for (auto& e: events.enter_events) {}
    }
}

void view_consume_window_events(AbstractView& view, megamol::frontend::FrontendResource const& resource) {
    GET_RESOURCE(WindowEvents)//{
        events.is_focused_events;
    }
}

// this is a weird place to measure passed program time, but we do it here so we satisfy _mmcRenderViewContext and nobody else needs to know
static std::chrono::high_resolution_clock::time_point render_view_context_timer_start;

void view_poke_rendering(AbstractView& view, megamol::frontend_resources::RenderInput const& render_input, megamol::frontend_resources::ImageWrapper& result_image) {
    static bool started_timer = false;
    if (!started_timer) {
        render_view_context_timer_start = std::chrono::high_resolution_clock::now();
        started_timer = true;
    }

    const double instanceTime_sec = std::chrono::duration_cast<std::chrono::milliseconds>(
        std::chrono::high_resolution_clock::now() - render_view_context_timer_start)
        .count() / static_cast<double>(1000);

    const double time_sec = view.DefaultTime(instanceTime_sec);

    // copy render inputs from frontend so we can update time
    auto renderinput = render_input;

    renderinput.instanceTime_sec = instanceTime_sec;
    renderinput.time_sec = time_sec;

    view.Resize(renderinput.local_view_framebuffer_resolution.x, renderinput.local_view_framebuffer_resolution.y);

    result_image = view.Render(renderinput.time_sec, renderinput.instanceTime_sec);
}

std::vector<std::string> get_view_runtime_resources_requests() {
    return {"ViewRenderInput", "KeyboardEvents", "MouseEvents", "WindowEvents"};
}

bool view_rendering_execution(
      void* module_ptr
    , std::vector<megamol::frontend::FrontendResource> const& resources
    , megamol::frontend_resources::ImageWrapper& result_image
) {
    megamol::core::view::AbstractView* view_ptr =
        dynamic_cast<megamol::core::view::AbstractView*>(static_cast<megamol::core::Module*>(module_ptr));

    if (!view_ptr) {
        std::cout << "error. module is not a view module. could not use as rendering entry point." << std::endl;
        return false;
    }

    megamol::core::view::AbstractView& view = *view_ptr;

    // resources are in order of initial requests from get_view_runtime_resources_requests()
    megamol::core::view::view_consume_keyboard_events(view, resources[1]);
    megamol::core::view::view_consume_mouse_events(view, resources[2]);
    megamol::core::view::view_consume_window_events(view, resources[3]);
    megamol::core::view::view_poke_rendering(view, resources[0].getResource<megamol::frontend_resources::RenderInput>(), result_image);

    return true;
}

} /* end namespace view */
} /* end namespace core */
} /* end namespace megamol */

<|endoftext|>


<commit_before>// Copyright (c) 2016 Jon Taylor
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "cli.h"

#include <sstream>
#include <unistd.h>   // open and close
#include <sys/stat.h> // temp because we removed util
#include <fcntl.h> // temp removed util.h
#include <time.h>
#include "ecdsacrypto.h"
#include "functions/functions.h"
#include "wallet.h"

/**
* printCommands
*
* Description: Print a list of commands that are accepted.
*/
void CCLI::printCommands(){
	std::cout << "Commands:\n" <<
	" join     - request membership in the network.\n" <<
	" balance  - print balance and transaction summary.\n" <<
	" sent     - print sent transaction list details.\n" <<
	" received - print received transaction list details.\n" <<
	" network  - print network stats including currency and volumes.\n" <<
	" send     - send a payment to another user address.\n" <<
	" receive  - prints your public key address to have others send you payments.\n" <<
    " advanced - more commands for admin and testing functions.\n" <<
	" quit     - shutdown the application.\n " << std::endl;

}

void CCLI::printAdvancedCommands(){
    std::cout << " Advanced: \n" <<
    " tests    - Run tests to verify this build is functioning correctly.\n " <<
    std::endl;
}

/**
* processUserInput
*
* Description: process user commands and print results
*/
void CCLI::processUserInput(){
	bool running = true;
	printCommands();
	while(running){
		std::cout << ">";

		std::string command;
		std::cin >> command;

		if( command.find("join") != std::string::npos ){

			CFunctions functions;
                        std::string privateKey;
                        std::string publicKey;
                        CWallet wallet;
                        bool e = wallet.fileExists("wallet.dat");
                        if(e != 0){
                                // Load wallet
                                wallet.read(privateKey, publicKey);
                                functions.parseBlockFile( publicKey );

                        }

			if(functions.joined == true){
				std::cout << "Allready joined network. \n" << std::endl;
			} else {
				std::cout << "Joining request sending... \n" << std::endl;

				// TODO: send request or say allready sent.
			}

			// Print if pending or allready accepted.
		} else if ( command.find("balance") != std::string::npos ){

			CFunctions functions;
			std::string privateKey;
			std::string publicKey;
			CWallet wallet;
			bool e = wallet.fileExists("wallet.dat");
			if(e != 0){
				// Load wallet
				wallet.read(privateKey, publicKey);

				functions.parseBlockFile( publicKey );
				std::cout << " Your balance: " << functions.balance << " sfr" << std::endl;

			}
		} else if ( command.find("sent") != std::string::npos ){
			std::cout << "This feature is not implemented yet.\n" << std::endl;

        } else if ( command.find("receive") != std::string::npos ){

            std::cout << "This feature is not implemented yet.\n" << std::endl;

        } else if ( command.find("send") != std::string::npos ){
            std::cout << "Enter destination address: \n" << std::endl;
            std::string destination_address;
            std::cin >> destination_address;
            std::cout << "Enter amount to send: \n" << std::endl;
            std::string amount;
            std::cin >> amount;
            std::cout << "Sending " << amount << " to user: " << destination_address << " \n" << std::endl;

        } else if ( command.find("network") != std::string::npos ){

		CFunctions functions;
                        std::string privateKey;
                        std::string publicKey;
                        CWallet wallet;
                        bool e = wallet.fileExists("wallet.dat");
                        if(e != 0){
                                // Load wallet
                                wallet.read(privateKey, publicKey);

                                functions.parseBlockFile( publicKey );
                                std::cout << " Currency: " << functions.currency_circulation << " sfr" << std::endl;

                        }

		// Block chain size?
		// Active connections?
            //std::cout << "This feature is not implemented yet.\n" << std::endl;

	} else if ( command.find("quit") != std::string::npos ){
			running = false;

        } else if ( command.find("advanced") != std::string::npos ){
            printAdvancedCommands();
        } else if ( command.find("tests") != std::string::npos ){
            CECDSACrypto ecdsa;
            ecdsa.runTests();
		} else {
			printCommands();
		}

	}
}

<commit_msg>send payment adds request to queue file.<commit_after>// Copyright (c) 2016 Jon Taylor
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "cli.h"

#include <sstream>
#include <unistd.h>   // open and close
#include <sys/stat.h> // temp because we removed util
#include <fcntl.h> // temp removed util.h
#include <time.h>
#include "ecdsacrypto.h"
#include "functions/functions.h"
#include "wallet.h"

/**
* printCommands
*
* Description: Print a list of commands that are accepted.
*/
void CCLI::printCommands(){
	std::cout << "Commands:\n" <<
	" join     - request membership in the network.\n" <<
	" balance  - print balance and transaction summary.\n" <<
	" sent     - print sent transaction list details.\n" <<
	" received - print received transaction list details.\n" <<
	" network  - print network stats including currency and volumes.\n" <<
	" send     - send a payment to another user address.\n" <<
	" receive  - prints your public key address to have others send you payments.\n" <<
	" advanced - more commands for admin and testing functions.\n" <<
	" quit     - shutdown the application.\n " << std::endl;

}

void CCLI::printAdvancedCommands(){
    std::cout << " Advanced: \n" <<
    " tests    - Run tests to verify this build is functioning correctly.\n " <<
    std::endl;
}

/**
* processUserInput
*
* Description: process user commands and print results
*/
void CCLI::processUserInput(){
	bool running = true;
	CECDSACrypto ecdsa;
	CFunctions functions;
	std::string privateKey;
	std::string publicKey;
	CWallet wallet;
	bool e = wallet.fileExists("wallet.dat");
	if(e != 0){
		// Load wallet
		wallet.read(privateKey, publicKey);
		functions.parseBlockFile(publicKey);
	}

	printCommands();
	while(running){
		std::cout << ">";

		std::string command;
		std::cin >> command;

		if( command.find("join") != std::string::npos ){

			//CFunctions functions;
                        //std::string privateKey;
                        //std::string publicKey;
                        //CWallet wallet;
                        //bool e = wallet.fileExists("wallet.dat");
                        //if(e != 0){
                                // Load wallet
                                //wallet.read(privateKey, publicKey);
                                functions.parseBlockFile( publicKey );
                        //}

			if(functions.joined == true){
				std::cout << "Allready joined network. \n" << std::endl;
			} else {
				std::cout << "Joining request sending... \n" << std::endl;

				CFunctions::record_structure joinRecord;
				time_t  timev;
				time(&timev);
				std::stringstream ss;
				ss << timev;
				std::string ts = ss.str();
				joinRecord.time = ts;
				joinRecord.transaction_type = CFunctions::JOIN_NETWORK;
				joinRecord.amount = 0.0;
				joinRecord.sender_public_key = "";
				joinRecord.recipient_public_key = publicKey;
				std::string message_siganture = "";
				ecdsa.SignMessage(privateKey, "" + publicKey, message_siganture);
				joinRecord.message_signature = message_siganture;
				functions.addToQueue( joinRecord );

				// TODO: send request or say allready sent.
			}

			// Print if pending or allready accepted.
		} else if ( command.find("balance") != std::string::npos ){

			//CFunctions functions;
			//std::string privateKey;
			//std::string publicKey;
			//CWallet wallet;
			//bool e = wallet.fileExists("wallet.dat");
			//if(e != 0){
				// Load wallet
				//wallet.read(privateKey, publicKey);

				functions.parseBlockFile( publicKey );
				std::cout << " Your balance: " << functions.balance << " sfr" << std::endl;

			//}
		} else if ( command.find("sent") != std::string::npos ){
			std::cout << "This feature is not implemented yet.\n" << std::endl;

        } else if ( command.find("receive") != std::string::npos ){

            std::cout << "This feature is not implemented yet.\n" << std::endl;

        } else if ( command.find("send") != std::string::npos ){
            std::cout << "Enter destination address: \n" << std::endl;
            std::string destination_address;
            std::cin >> destination_address;
            std::cout << "Enter amount to send: \n" << std::endl;
            std::string amount;
            std::cin >> amount;
            std::cout << "Sending " << amount << " to user: " << destination_address << " \n" << std::endl;

		double d_amount = ::atof(amount.c_str());

		// TODO also check balance adjusted using sent requests in queue....
		// TODO check destination address is an accepted user
		if(d_amount > functions.balance ){
			std::cout << "Insuficient balance. Unable to send transfer request. " << std::endl;
		} else {

		CFunctions::record_structure sendRecord;
                                time_t  timev;
                                time(&timev);
                                std::stringstream ss;
                                ss << timev;
                                std::string ts = ss.str();
                                sendRecord.time = ts;
                                sendRecord.transaction_type = CFunctions::TRANSFER_CURRENCY;
                                sendRecord.amount = d_amount;
                                sendRecord.sender_public_key = publicKey;
                                sendRecord.recipient_public_key = publicKey;
                                std::string message_siganture = destination_address;
                                ecdsa.SignMessage(privateKey, "" + publicKey, message_siganture);
                                sendRecord.message_signature = message_siganture;
                                functions.addToQueue( sendRecord );
			std::cout << "Sent transfer request. " << std::endl;
		}

        } else if ( command.find("network") != std::string::npos ){

		CFunctions functions;
                        std::string privateKey;
                        std::string publicKey;
                        CWallet wallet;
                        bool e = wallet.fileExists("wallet.dat");
                        if(e != 0){
                                // Load wallet
                                wallet.read(privateKey, publicKey);

                                functions.parseBlockFile( publicKey );
                                std::cout << " Currency: " << functions.currency_circulation << " sfr" << std::endl;

                        }

		// Block chain size?
	 	std::cout << " Blockchain size: " << " 0MB" << std::endl;

		std::cout << " Pending transactions: " << " 0" << std::endl;

		// Active connections?
            //std::cout << "This feature is not implemented yet.\n" << std::endl;

	} else if ( command.find("quit") != std::string::npos ){
			running = false;

        } else if ( command.find("advanced") != std::string::npos ){
            printAdvancedCommands();
        } else if ( command.find("tests") != std::string::npos ){
            CECDSACrypto ecdsa;
            ecdsa.runTests();
		} else {
			printCommands();
		}

	}
}

<|endoftext|>


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

  Program:   Monteverdi2
  Language:  C++

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

  Monteverdi2 is distributed under the CeCILL licence version 2. See
  Licence_CeCILL_V2-en.txt or
  http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.

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

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

#include "mvdImageViewManipulator.h"

//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.

//
// System includes (sorted by alphabetic order)

//
// ITK includes (sorted by alphabetic order)

//
// OTB includes (sorted by alphabetic order)

//
// Monteverdi includes (sorted by alphabetic order)

namespace mvd
{
/*
  TRANSLATOR mvd::ImageViewManipulator

  Necessary for lupdate to be aware of C++ namespaces.

  Context comment for translator.
*/

/*****************************************************************************/
ImageViewManipulator
::ImageViewManipulator( QObject* parent ) :
  AbstractViewManipulator( parent ),
  m_PreviousIsotropicZoom(1.)
{
}

/*****************************************************************************/
ImageViewManipulator
::~ImageViewManipulator()
{
}

/*****************************************************************************/
bool
ImageViewManipulator
::HasZoomChanged() const
{
  bool res = false;

  if (vcl_abs(m_IsotropicZoom - m_PreviousIsotropicZoom) > 0.00000001 )
    {
    res = true;
    }

  return res;
}

/******************************************************************************/
void
ImageViewManipulator
::mousePressEvent(QMouseEvent * event)
{
  // Update the context with the pressed position
  m_MouseContext.x = event->x();
  m_MouseContext.y = event->y();

  // Update the context with the pressed position for the mouseMoveEvent
  m_MouseContext.xMove = event->x();
  m_MouseContext.yMove = event->y();
}

/******************************************************************************/
void
ImageViewManipulator
::mouseMoveEvent( QMouseEvent * event)
{
  m_PreviousIsotropicZoom = m_IsotropicZoom;

  // Update the mouse context
  m_MouseContext.dx = -event->x() + m_MouseContext.xMove;
  m_MouseContext.dy = -event->y() + m_MouseContext.yMove;

  // moveRegion
  this->moveRegion( m_MouseContext.dx,  m_MouseContext.dy);

  // Update the position of the first press to take into account the
  // last drag
  m_MouseContext.xMove -=  m_MouseContext.dx;
  m_MouseContext.yMove -=  m_MouseContext.dy;
}

/******************************************************************************/
void
ImageViewManipulator
::moveRegion(double dx, double dy)
{
  // Update the navigation context
  ImageRegionType & currentRegion = m_NavigationContext.m_ViewportImageRegion;

  // Apply the offset to the (start) index of the stored region
  ImageRegionType::OffsetType offset;

  offset[0] = static_cast<ImageRegionType::OffsetType::OffsetValueType> (dx/m_IsotropicZoom + 0.5);
  offset[1] = static_cast<ImageRegionType::OffsetType::OffsetValueType> (dy/m_IsotropicZoom + 0.5);

  // Apply the offset to the (start) index of the stored region
  IndexType    index = currentRegion.GetIndex() + offset;
  currentRegion.SetIndex(index);

  // Constraint the region to the largestPossibleRegion
  this->ConstrainRegion(currentRegion, m_NavigationContext.m_ModelImageRegion);
}

/******************************************************************************/
void
ImageViewManipulator
::mouseReleaseEvent(  QMouseEvent * event)
{
  //TODO: Implement mouseReleaseEvent.
  //std::cout <<" Not Implemented yet ..." << std::endl;
}

/******************************************************************************/
void ImageViewManipulator
::resizeEvent( QResizeEvent * event )
{
  this->ResizeRegion( event->size().width(),
                      event->size().height());
}

/******************************************************************************/
void ImageViewManipulator
::ResizeRegion(unsigned int w, unsigned int h)
{
  // Update the navigation context
  ImageRegionType & currentRegion = m_NavigationContext.m_ViewportImageRegion;

  // Get the new widget size
  ImageRegionType::SizeType size;
  size[0] = w;
  size[1] = h;

  // Update the stored region with the new size
  currentRegion.SetSize(size);

  // Recompute the size before
  m_NavigationContext.m_SizeXBeforeConstrain = (double)size[0] / this->GetIsotropicZoom();
  m_NavigationContext.m_SizeYBeforeConstrain = (double)size[1] / this->GetIsotropicZoom();

  // Constraint this region to the LargestPossibleRegion
  this->ConstrainRegion(currentRegion, m_NavigationContext.m_ModelImageRegion);

  // call the rescale method with the same zoom as before (scale = 1)
  this->Zoom(1.);
}

/******************************************************************************/
void
ImageViewManipulator
::wheelEvent(  QWheelEvent * event)
{
  // compute the new scale
  double scaleRatio = 1.25;
  double numDegrees = event->delta() / 8.;
  int    nbSteps    = static_cast<int>(numDegrees / 15.);

  double scale = vcl_pow(scaleRatio, nbSteps);

  // center the region on the center of the previous region
  this->CenterRegion(scale);

  // rescale the viewport region
  this->Zoom(scale);
}

/******************************************************************************/
void
ImageViewManipulator
::Zoom(const double scale)
{
  m_PreviousIsotropicZoom = m_IsotropicZoom;

  // compute the new size
  double sizeX = m_NavigationContext.m_SizeXBeforeConstrain / scale;
  double sizeY = m_NavigationContext.m_SizeYBeforeConstrain / scale;

  // check that the new size is greater than 30x30
  // check that the new isoZoom is not too low and not too large
  // TODO : compute automatically the minSize and the isoZoom range ???
  if (sizeX > 30 && sizeY > 30  &&
      m_IsotropicZoom * scale > 0.01 &&
      m_IsotropicZoom * scale < 10.)
    {
    // Update the the sizeBeforeConstrain
    m_NavigationContext.m_SizeXBeforeConstrain = sizeX;
    m_NavigationContext.m_SizeYBeforeConstrain = sizeY;

    // Update the viewort region with the new size
    ImageRegionType::SizeType size;
    size[0] = static_cast<unsigned int>(sizeX);
    size[1] = static_cast<unsigned int>(sizeY);

    // The viewPort Region must be adapted to this zoom ratio
    ImageRegionType & currentRegion = m_NavigationContext.m_ViewportImageRegion;

    // Update the stored region with the new size
    currentRegion.SetSize(size);

    // Constraint this region to the LargestPossibleRegion
    this->ConstrainRegion(currentRegion, m_NavigationContext.m_ModelImageRegion);

    // Update the isotropicZoom
    m_IsotropicZoom *= scale;
    }
}

/******************************************************************************/
void
ImageViewManipulator
::CenterRegion(double scale)
{
  if( m_IsotropicZoom * scale > 0.01 && m_IsotropicZoom * scale < 10.)
    {
    // The viewPort Region must be adapted to this zoom ratio
    ImageRegionType & currentRegion = m_NavigationContext.m_ViewportImageRegion;

    // center the region on the position under the cursor
    IndexType        origin = currentRegion.GetIndex();
    double centerX = (double)(origin[0]) + (double)(currentRegion.GetSize()[0])/2.;
    double centerY = (double)(origin[1]) + (double)(currentRegion.GetSize()[1])/2.;

    // new origin
    IndexType  newIndex;
    newIndex[0] = centerX - currentRegion.GetSize()[0]/scale/2.;
    if (newIndex[0] < 0) newIndex[0] = 0;

    newIndex[1] = centerY - currentRegion.GetSize()[1]/scale/2.;
    if (newIndex[1] < 0) newIndex[1] = 0;

    // set the new origin
    currentRegion.SetIndex(newIndex);

    // Constraint this region to the LargestPossibleRegion
    this->ConstrainRegion(currentRegion, m_NavigationContext.m_ModelImageRegion);
    }
}

/******************************************************************************/
void
ImageViewManipulator
::ConstrainRegion( ImageRegionType& region, const ImageRegionType& largest)
{
  ImageRegionType::SizeType zeroSize;
  zeroSize.Fill(0);

  if (largest.GetSize() != zeroSize)
    {
    // Else we can constrain it
    IndexType                     index = region.GetIndex();
    ImageRegionType::SizeType size = region.GetSize();

    // If region is larger than big, then crop
    if (region.GetSize()[0] > largest.GetSize()[0])
      {
      size[0] = largest.GetSize()[0];
      }
    if (region.GetSize()[1] > largest.GetSize()[1])
      {
      size[1] = largest.GetSize()[1];
      }

    // Else we can constrain it
    // For each dimension
    for (unsigned int dim = 0; dim < ImageRegionType::ImageDimension; ++dim)
      {
      // push left if necessary
      if (region.GetIndex()[dim] < largest.GetIndex()[dim])
        {
        index[dim] = largest.GetIndex()[dim];
        }
      // push right if necessary
      if (index[dim] + size[dim] >= largest.GetIndex()[dim] + largest.GetSize()[dim])
        {
        index[dim] = largest.GetIndex()[dim] + largest.GetSize()[dim] - size[dim];
        }
      }
    region.SetSize(size);
    region.SetIndex(index);
    }
}

/******************************************************************************/
void
ImageViewManipulator
::keyPressEvent( QKeyEvent * event )
{
  switch(event->key())
    {
    case Qt::Key_Minus:
      CenterRegion(0.8);
      Zoom(0.8);
      break;
    case Qt::Key_Plus:
      CenterRegion(1.25);
      Zoom(1.25);
      break;
    case Qt::Key_Left:
      moveRegion(-static_cast<double>(m_NavigationContext.m_ViewportImageRegion.GetSize(0))*m_IsotropicZoom/4 ,0);
      break;
    case Qt::Key_Right:
      moveRegion(static_cast<double>(m_NavigationContext.m_ViewportImageRegion.GetSize(0))*m_IsotropicZoom/4 ,0);
      break;
    case Qt::Key_Up:
      moveRegion(0,-static_cast<double>(m_NavigationContext.m_ViewportImageRegion.GetSize(1))*m_IsotropicZoom/4 );
      break;
    case Qt::Key_Down:
      moveRegion(0,static_cast<double>(m_NavigationContext.m_ViewportImageRegion.GetSize(1))*m_IsotropicZoom/4 );
      break;
    default:
      break;
    }
}

/*****************************************************************************/
/* SLOTS                                                                     */
/*****************************************************************************/

/*****************************************************************************/
void ImageViewManipulator
::OnModelImageRegionChanged(const ImageRegionType & largestRegion, const SpacingType& spacing)
{
  // update the spacing
  SetSpacing(spacing);

  // set back the zoom to 1
  m_IsotropicZoom = 1.;

  m_PreviousIsotropicZoom = 1.;

  // store the image largest region
  m_NavigationContext.m_ModelImageRegion = largestRegion;

  // set back the origin to O
  IndexType nullIndex;
  nullIndex.Fill(0);
  m_NavigationContext.m_ViewportImageRegion.SetIndex(nullIndex);

  // get the widget size and use it to resize the Viewport region
  QWidget* parent_widget = qobject_cast< QWidget* >( parent() );

  if (parent_widget)
    {
    this->ResizeRegion(parent_widget->width(), parent_widget->height());
    }

  // compute the intial scale factor to fit to screen
  double factorX = (double)m_NavigationContext.m_ViewportImageRegion.GetSize()[0]
    /(double)(largestRegion.GetSize()[0]);
  double factorY = (double)m_NavigationContext.m_ViewportImageRegion.GetSize()[1]
    /(double)(largestRegion.GetSize()[1]);

  double scale = std::min(factorX, factorY);
  this->Zoom(scale);
}

/*****************************************************************************/
void ImageViewManipulator
::OnViewportRegionChanged(double Xpc, double Ypc)
{
  // Update the navigation context
  ImageRegionType & currentRegion = m_NavigationContext.m_ViewportImageRegion;

  // center the region on the position under the cursor
  IndexType   origin;
  origin[0] = ( Xpc / vcl_abs(GetSpacing()[0]) - currentRegion.GetSize()[0] / 2 );
  origin[1] = ( Ypc / vcl_abs(GetSpacing()[1]) - currentRegion.GetSize()[1] / 2 );
  currentRegion.SetIndex(origin);

  // Constraint this region to the LargestPossibleRegion
  this->ConstrainRegion(currentRegion, m_NavigationContext.m_ModelImageRegion);

  // force repaintGL
  qobject_cast< QWidget* >( parent() )->update();
}

} // end namespace 'mvd'
<commit_msg>BUG: Fixing chaotic handling of mouse move event (several calls to event->x() and event->y() which change between calls<commit_after>/*=========================================================================

  Program:   Monteverdi2
  Language:  C++

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

  Monteverdi2 is distributed under the CeCILL licence version 2. See
  Licence_CeCILL_V2-en.txt or
  http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.

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

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

#include "mvdImageViewManipulator.h"

//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.

//
// System includes (sorted by alphabetic order)

//
// ITK includes (sorted by alphabetic order)

//
// OTB includes (sorted by alphabetic order)

//
// Monteverdi includes (sorted by alphabetic order)

namespace mvd
{
/*
  TRANSLATOR mvd::ImageViewManipulator

  Necessary for lupdate to be aware of C++ namespaces.

  Context comment for translator.
*/

/*****************************************************************************/
ImageViewManipulator
::ImageViewManipulator( QObject* parent ) :
  AbstractViewManipulator( parent ),
  m_PreviousIsotropicZoom(1.)
{
}

/*****************************************************************************/
ImageViewManipulator
::~ImageViewManipulator()
{
}

/*****************************************************************************/
bool
ImageViewManipulator
::HasZoomChanged() const
{
  bool res = false;

  if (vcl_abs(m_IsotropicZoom - m_PreviousIsotropicZoom) > 0.00000001 )
    {
    res = true;
    }

  return res;
}

/******************************************************************************/
void
ImageViewManipulator
::mousePressEvent(QMouseEvent * event)
{
  // Update the context with the pressed position
  m_MouseContext.x = event->x();
  m_MouseContext.y = event->y();

  // Update the context with the pressed position for the mouseMoveEvent
  m_MouseContext.xMove = event->x();
  m_MouseContext.yMove = event->y();
}

/******************************************************************************/
void
ImageViewManipulator
::mouseMoveEvent( QMouseEvent * event)
{
  m_PreviousIsotropicZoom = m_IsotropicZoom;

  // Update the context with the pressed position
  m_MouseContext.x = event->x();
  m_MouseContext.y = event->y();

  // Update the mouse context
  m_MouseContext.dx =  m_MouseContext.xMove - m_MouseContext.x;
  m_MouseContext.dy =  m_MouseContext.yMove - m_MouseContext.y;

  // moveRegion
  this->moveRegion( m_MouseContext.dx,  m_MouseContext.dy);

  // Update the position of the first press to take into account the
  // last drag
  m_MouseContext.xMove = m_MouseContext.x;
  m_MouseContext.yMove = m_MouseContext.y;
}

/******************************************************************************/
void
ImageViewManipulator
::moveRegion(double dx, double dy)
{
  // Update the navigation context
  ImageRegionType & currentRegion = m_NavigationContext.m_ViewportImageRegion;

  // Apply the offset to the (start) index of the stored region
  ImageRegionType::OffsetType offset;

  offset[0] = static_cast<ImageRegionType::OffsetType::OffsetValueType> (dx/m_IsotropicZoom + 0.5);
  offset[1] = static_cast<ImageRegionType::OffsetType::OffsetValueType> (dy/m_IsotropicZoom + 0.5);

  // Apply the offset to the (start) index of the stored region
  IndexType    index = currentRegion.GetIndex() + offset;
  currentRegion.SetIndex(index);

  // Constraint the region to the largestPossibleRegion
  this->ConstrainRegion(currentRegion, m_NavigationContext.m_ModelImageRegion);
}

/******************************************************************************/
void
ImageViewManipulator
::mouseReleaseEvent(  QMouseEvent * event)
{
  //TODO: Implement mouseReleaseEvent.
  //std::cout <<" Not Implemented yet ..." << std::endl;
}

/******************************************************************************/
void ImageViewManipulator
::resizeEvent( QResizeEvent * event )
{
  this->ResizeRegion( event->size().width(),
                      event->size().height());
}

/******************************************************************************/
void ImageViewManipulator
::ResizeRegion(unsigned int w, unsigned int h)
{
  // Update the navigation context
  ImageRegionType & currentRegion = m_NavigationContext.m_ViewportImageRegion;

  // Get the new widget size
  ImageRegionType::SizeType size;
  size[0] = w;
  size[1] = h;

  // Update the stored region with the new size
  currentRegion.SetSize(size);

  // Recompute the size before
  m_NavigationContext.m_SizeXBeforeConstrain = (double)size[0] / this->GetIsotropicZoom();
  m_NavigationContext.m_SizeYBeforeConstrain = (double)size[1] / this->GetIsotropicZoom();

  // Constraint this region to the LargestPossibleRegion
  this->ConstrainRegion(currentRegion, m_NavigationContext.m_ModelImageRegion);

  // call the rescale method with the same zoom as before (scale = 1)
  this->Zoom(1.);
}

/******************************************************************************/
void
ImageViewManipulator
::wheelEvent(  QWheelEvent * event)
{
  // compute the new scale
  double scaleRatio = 1.25;
  double numDegrees = event->delta() / 8.;
  int    nbSteps    = static_cast<int>(numDegrees / 15.);

  double scale = vcl_pow(scaleRatio, nbSteps);

  // center the region on the center of the previous region
  this->CenterRegion(scale);

  // rescale the viewport region
  this->Zoom(scale);
}

/******************************************************************************/
void
ImageViewManipulator
::Zoom(const double scale)
{
  m_PreviousIsotropicZoom = m_IsotropicZoom;

  // compute the new size
  double sizeX = m_NavigationContext.m_SizeXBeforeConstrain / scale;
  double sizeY = m_NavigationContext.m_SizeYBeforeConstrain / scale;

  // check that the new size is greater than 30x30
  // check that the new isoZoom is not too low and not too large
  // TODO : compute automatically the minSize and the isoZoom range ???
  if (sizeX > 30 && sizeY > 30  &&
      m_IsotropicZoom * scale > 0.01 &&
      m_IsotropicZoom * scale < 10.)
    {
    // Update the the sizeBeforeConstrain
    m_NavigationContext.m_SizeXBeforeConstrain = sizeX;
    m_NavigationContext.m_SizeYBeforeConstrain = sizeY;

    // Update the viewort region with the new size
    ImageRegionType::SizeType size;
    size[0] = static_cast<unsigned int>(sizeX);
    size[1] = static_cast<unsigned int>(sizeY);

    // The viewPort Region must be adapted to this zoom ratio
    ImageRegionType & currentRegion = m_NavigationContext.m_ViewportImageRegion;

    // Update the stored region with the new size
    currentRegion.SetSize(size);

    // Constraint this region to the LargestPossibleRegion
    this->ConstrainRegion(currentRegion, m_NavigationContext.m_ModelImageRegion);

    // Update the isotropicZoom
    m_IsotropicZoom *= scale;
    }
}

/******************************************************************************/
void
ImageViewManipulator
::CenterRegion(double scale)
{
  if( m_IsotropicZoom * scale > 0.01 && m_IsotropicZoom * scale < 10.)
    {
    // The viewPort Region must be adapted to this zoom ratio
    ImageRegionType & currentRegion = m_NavigationContext.m_ViewportImageRegion;

    // center the region on the position under the cursor
    IndexType        origin = currentRegion.GetIndex();
    double centerX = (double)(origin[0]) + (double)(currentRegion.GetSize()[0])/2.;
    double centerY = (double)(origin[1]) + (double)(currentRegion.GetSize()[1])/2.;

    // new origin
    IndexType  newIndex;
    newIndex[0] = centerX - currentRegion.GetSize()[0]/scale/2.;
    if (newIndex[0] < 0) newIndex[0] = 0;

    newIndex[1] = centerY - currentRegion.GetSize()[1]/scale/2.;
    if (newIndex[1] < 0) newIndex[1] = 0;

    // set the new origin
    currentRegion.SetIndex(newIndex);

    // Constraint this region to the LargestPossibleRegion
    this->ConstrainRegion(currentRegion, m_NavigationContext.m_ModelImageRegion);
    }
}

/******************************************************************************/
void
ImageViewManipulator
::ConstrainRegion( ImageRegionType& region, const ImageRegionType& largest)
{
  ImageRegionType::SizeType zeroSize;
  zeroSize.Fill(0);

  if (largest.GetSize() != zeroSize)
    {
    // Else we can constrain it
    IndexType                     index = region.GetIndex();
    ImageRegionType::SizeType size = region.GetSize();

    // If region is larger than big, then crop
    if (region.GetSize()[0] > largest.GetSize()[0])
      {
      size[0] = largest.GetSize()[0];
      }
    if (region.GetSize()[1] > largest.GetSize()[1])
      {
      size[1] = largest.GetSize()[1];
      }

    // Else we can constrain it
    // For each dimension
    for (unsigned int dim = 0; dim < ImageRegionType::ImageDimension; ++dim)
      {
      // push left if necessary
      if (region.GetIndex()[dim] < largest.GetIndex()[dim])
        {
        index[dim] = largest.GetIndex()[dim];
        }
      // push right if necessary
      if (index[dim] + size[dim] >= largest.GetIndex()[dim] + largest.GetSize()[dim])
        {
        index[dim] = largest.GetIndex()[dim] + largest.GetSize()[dim] - size[dim];
        }
      }
    region.SetSize(size);
    region.SetIndex(index);
    }
}

/******************************************************************************/
void
ImageViewManipulator
::keyPressEvent( QKeyEvent * event )
{
  switch(event->key())
    {
    case Qt::Key_Minus:
      CenterRegion(0.8);
      Zoom(0.8);
      break;
    case Qt::Key_Plus:
      CenterRegion(1.25);
      Zoom(1.25);
      break;
    case Qt::Key_Left:
      moveRegion(-static_cast<double>(m_NavigationContext.m_ViewportImageRegion.GetSize(0))*m_IsotropicZoom/4 ,0);
      break;
    case Qt::Key_Right:
      moveRegion(static_cast<double>(m_NavigationContext.m_ViewportImageRegion.GetSize(0))*m_IsotropicZoom/4 ,0);
      break;
    case Qt::Key_Up:
      moveRegion(0,-static_cast<double>(m_NavigationContext.m_ViewportImageRegion.GetSize(1))*m_IsotropicZoom/4 );
      break;
    case Qt::Key_Down:
      moveRegion(0,static_cast<double>(m_NavigationContext.m_ViewportImageRegion.GetSize(1))*m_IsotropicZoom/4 );
      break;
    default:
      break;
    }
}

/*****************************************************************************/
/* SLOTS                                                                     */
/*****************************************************************************/

/*****************************************************************************/
void ImageViewManipulator
::OnModelImageRegionChanged(const ImageRegionType & largestRegion, const SpacingType& spacing)
{
  // update the spacing
  SetSpacing(spacing);

  // set back the zoom to 1
  m_IsotropicZoom = 1.;

  m_PreviousIsotropicZoom = 1.;

  // store the image largest region
  m_NavigationContext.m_ModelImageRegion = largestRegion;

  // set back the origin to O
  IndexType nullIndex;
  nullIndex.Fill(0);
  m_NavigationContext.m_ViewportImageRegion.SetIndex(nullIndex);

  // get the widget size and use it to resize the Viewport region
  QWidget* parent_widget = qobject_cast< QWidget* >( parent() );

  if (parent_widget)
    {
    this->ResizeRegion(parent_widget->width(), parent_widget->height());
    }

  // compute the intial scale factor to fit to screen
  double factorX = (double)m_NavigationContext.m_ViewportImageRegion.GetSize()[0]
    /(double)(largestRegion.GetSize()[0]);
  double factorY = (double)m_NavigationContext.m_ViewportImageRegion.GetSize()[1]
    /(double)(largestRegion.GetSize()[1]);

  double scale = std::min(factorX, factorY);
  this->Zoom(scale);
}

/*****************************************************************************/
void ImageViewManipulator
::OnViewportRegionChanged(double Xpc, double Ypc)
{
  // Update the navigation context
  ImageRegionType & currentRegion = m_NavigationContext.m_ViewportImageRegion;

  // center the region on the position under the cursor
  IndexType   origin;
  origin[0] = ( Xpc / vcl_abs(GetSpacing()[0]) - currentRegion.GetSize()[0] / 2 );
  origin[1] = ( Ypc / vcl_abs(GetSpacing()[1]) - currentRegion.GetSize()[1] / 2 );
  currentRegion.SetIndex(origin);

  // Constraint this region to the LargestPossibleRegion
  this->ConstrainRegion(currentRegion, m_NavigationContext.m_ModelImageRegion);

  // force repaintGL
  qobject_cast< QWidget* >( parent() )->update();
}

} // end namespace 'mvd'
<|endoftext|>