<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: QueryDesignView.hxx,v $
 *
 *  $Revision: 1.21 $
 *
 *  last change: $Author: kz $ $Date: 2007-05-10 10:28:25 $
 *
 *  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_QUERYDESIGNVIEW_HXX
#define DBAUI_QUERYDESIGNVIEW_HXX

#ifndef DBAUI_QUERYVIEW_HXX
#include "queryview.hxx"
#endif
#ifndef _SV_SPLIT_HXX
#include <vcl/split.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef DBAUI_ENUMTYPES_HXX
#include "QEnumTypes.hxx"
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef DBAUI_QUERYCONTROLLER_HXX
#include "querycontroller.hxx"
#endif
#ifndef DBAUI_CONNECTIONLINEDATA_HXX
#include "ConnectionLineData.hxx"
#endif

namespace connectivity
{
    class OSQLParseNode;
}

class ComboBox;
namespace dbaui
{
    enum SqlParseError
    {
        eIllegalJoin,
        eStatementTooLong,
        eNoConnection,
        eNoSelectStatement,
        eStatementTooComplex,
        eColumnInLikeNotFound,
        eNoColumnInLike,
        eColumnNotFound,
        eNativeMode,
        eTooManyTables,
        eTooManyConditions,
        eTooManyColumns,
        eIllegalJoinCondition,
        eOk
    };

    class OQueryViewSwitch;
    class OAddTableDlg;
    class OQueryTableWindow;
    class OSelectionBrowseBox;
    class OTableConnection;
    class OQueryTableConnectionData;
    class OQueryContainerWindow;

    class OQueryDesignView : public OQueryView
    {
        enum ChildFocusState
        {
            SELECTION,
            TABLEVIEW,
            NONE
        };

        Splitter                            m_aSplitter;

        ::com::sun::star::lang::Locale      m_aLocale;
        ::rtl::OUString                     m_sDecimalSep;

        OSelectionBrowseBox*                m_pSelectionBox;    // presents the lower window
        ChildFocusState                     m_eChildFocus;
        sal_Bool                            m_bInKeyEvent;
        sal_Bool                            m_bInSplitHandler;

    public:
        OQueryDesignView(OQueryContainerWindow* pParent, OQueryController* _pController,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& );
        virtual ~OQueryDesignView();

        virtual sal_Bool isCutAllowed();
        virtual sal_Bool isPasteAllowed();
        virtual sal_Bool isCopyAllowed();
        virtual void copy();
        virtual void cut();
        virtual void paste();
        // clears the whole query
        virtual void clear();
        // set the view readonly or not
        virtual void setReadOnly(sal_Bool _bReadOnly);
        // check if the statement is correct when not returning false
        virtual sal_Bool checkStatement();
        // set the statement for representation
        virtual void setStatement(const ::rtl::OUString& _rsStatement);
        // returns the current sql statement
        virtual ::rtl::OUString getStatement();
        /// late construction
        virtual void Construct();
        virtual void initialize();
        // window overloads
        virtual long PreNotify( NotifyEvent& rNEvt );
        virtual void GetFocus();

        sal_Bool isSlotEnabled(sal_Int32 _nSlotId);
        void setSlotEnabled(sal_Int32 _nSlotId,sal_Bool _bEnable);
        void setNoneVisbleRow(sal_Int32 _nRows);

        ::com::sun::star::lang::Locale      getLocale() const           { return m_aLocale;}
        ::rtl::OUString                     getDecimalSeparator() const { return m_sDecimalSep;}

        SqlParseError InsertField( const OTableFieldDescRef& rInfo, sal_Bool bVis=sal_True, sal_Bool bActivate = sal_True);
        // save the position of the table window and the pos of the splitters
        // called when fields are deleted
        void DeleteFields( const ::rtl::OUString& rAliasName );
        // called when a table from tabeview was deleted
        void TableDeleted(const ::rtl::OUString& rAliasName);

        BOOL getColWidth( const ::rtl::OUString& rAliasName, const ::rtl::OUString& rFieldName, sal_uInt32& nWidth );
        void fillValidFields(const ::rtl::OUString& strTableName, ComboBox* pFieldList);

        void SaveUIConfig();
        void stopTimer();
        void startTimer();
        void reset();
        sal_Bool InitFromParseNode();

        ::connectivity::OSQLParseNode* getPredicateTreeFromEntry(   OTableFieldDescRef pEntry,
                                                                    const String& _sCriteria,
                                                                    ::rtl::OUString& _rsErrorMessage,
                                                                    ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxColumn);
    protected:
        // return the Rectangle where I can paint myself
        virtual void resizeDocumentView(Rectangle& rRect);
        DECL_LINK( SplitHdl, void* );

    private:
        using OQueryView::SaveTabWinUIConfig;
    };
}
#endif // DBAUI_QUERYDESIGNVIEW_HXX

<commit_msg>INTEGRATION: CWS dba24b (1.21.46); FILE MERGED 2007/08/24 08:21:45 oj 1.21.46.1: #i69678# allow functions in group by<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: QueryDesignView.hxx,v $
 *
 *  $Revision: 1.22 $
 *
 *  last change: $Author: hr $ $Date: 2007-11-01 15:16:35 $
 *
 *  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_QUERYDESIGNVIEW_HXX
#define DBAUI_QUERYDESIGNVIEW_HXX

#ifndef DBAUI_QUERYVIEW_HXX
#include "queryview.hxx"
#endif
#ifndef _SV_SPLIT_HXX
#include <vcl/split.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef DBAUI_ENUMTYPES_HXX
#include "QEnumTypes.hxx"
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef DBAUI_QUERYCONTROLLER_HXX
#include "querycontroller.hxx"
#endif
#ifndef DBAUI_CONNECTIONLINEDATA_HXX
#include "ConnectionLineData.hxx"
#endif

namespace connectivity
{
    class OSQLParseNode;
}

class ComboBox;
namespace dbaui
{
    enum SqlParseError
    {
        eIllegalJoin,
        eStatementTooLong,
        eNoConnection,
        eNoSelectStatement,
        eStatementTooComplex,
        eColumnInLikeNotFound,
        eNoColumnInLike,
        eColumnNotFound,
        eNativeMode,
        eTooManyTables,
        eTooManyConditions,
        eTooManyColumns,
        eIllegalJoinCondition,
        eOk
    };

    class OQueryViewSwitch;
    class OAddTableDlg;
    class OQueryTableWindow;
    class OSelectionBrowseBox;
    class OTableConnection;
    class OQueryTableConnectionData;
    class OQueryContainerWindow;

    class OQueryDesignView : public OQueryView
    {
        enum ChildFocusState
        {
            SELECTION,
            TABLEVIEW,
            NONE
        };

        Splitter                            m_aSplitter;

        ::com::sun::star::lang::Locale      m_aLocale;
        ::rtl::OUString                     m_sDecimalSep;

        OSelectionBrowseBox*                m_pSelectionBox;    // presents the lower window
        ChildFocusState                     m_eChildFocus;
        sal_Bool                            m_bInKeyEvent;
        sal_Bool                            m_bInSplitHandler;

    public:
        OQueryDesignView(OQueryContainerWindow* pParent, OQueryController* _pController,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& );
        virtual ~OQueryDesignView();

        virtual sal_Bool isCutAllowed();
        virtual sal_Bool isPasteAllowed();
        virtual sal_Bool isCopyAllowed();
        virtual void copy();
        virtual void cut();
        virtual void paste();
        // clears the whole query
        virtual void clear();
        // set the view readonly or not
        virtual void setReadOnly(sal_Bool _bReadOnly);
        // check if the statement is correct when not returning false
        virtual sal_Bool checkStatement();
        // set the statement for representation
        virtual void setStatement(const ::rtl::OUString& _rsStatement);
        // returns the current sql statement
        virtual ::rtl::OUString getStatement();
        /// late construction
        virtual void Construct();
        virtual void initialize();
        // window overloads
        virtual long PreNotify( NotifyEvent& rNEvt );
        virtual void GetFocus();

        sal_Bool isSlotEnabled(sal_Int32 _nSlotId);
        void setSlotEnabled(sal_Int32 _nSlotId,sal_Bool _bEnable);
        void setNoneVisbleRow(sal_Int32 _nRows);

        ::com::sun::star::lang::Locale      getLocale() const           { return m_aLocale;}
        ::rtl::OUString                     getDecimalSeparator() const { return m_sDecimalSep;}

        SqlParseError InsertField( const OTableFieldDescRef& rInfo, sal_Bool bVis=sal_True, sal_Bool bActivate = sal_True);
        // save the position of the table window and the pos of the splitters
        // called when fields are deleted
        void DeleteFields( const ::rtl::OUString& rAliasName );
        // called when a table from tabeview was deleted
        void TableDeleted(const ::rtl::OUString& rAliasName);

        BOOL getColWidth( const ::rtl::OUString& rAliasName, const ::rtl::OUString& rFieldName, sal_uInt32& nWidth );
        void fillValidFields(const ::rtl::OUString& strTableName, ComboBox* pFieldList);

        void SaveUIConfig();
        void stopTimer();
        void startTimer();
        void reset();
        sal_Bool InitFromParseNode();

        ::connectivity::OSQLParseNode* getPredicateTreeFromEntry(   OTableFieldDescRef pEntry,
                                                                    const String& _sCriteria,
                                                                    ::rtl::OUString& _rsErrorMessage,
                                                                    ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>& _rxColumn) const;
    protected:
        // return the Rectangle where I can paint myself
        virtual void resizeDocumentView(Rectangle& rRect);
        DECL_LINK( SplitHdl, void* );

    private:
        using OQueryView::SaveTabWinUIConfig;
    };
}
#endif // DBAUI_QUERYDESIGNVIEW_HXX

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: RelControliFace.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 15:31:57 $
 *
 *  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_RELCONTROLIFACE_HXX
#define DBAUI_RELCONTROLIFACE_HXX

#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif

namespace dbaui
{
    class OTableConnectionData;
    class IRelationControlInterface
    {
    public:
        virtual ~IRelationControlInterface(){}

        /** getConnectionData returns the current connection data
            @return the current connectiondata
        */
        virtual OTableConnectionData* getConnectionData() const = 0;

        /** setValid set the valid inside, can be used for OK buttons
            @param  _bValid true when the using control allows an update
        */
        virtual void setValid(sal_Bool _bValid) = 0;

        virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > getConnection() = 0;

        /** notifyConnectionChange is callback which is called when the table selection has changed and a new connection exists
            @param  _pConnectionData    the connection which exists between the new tables
        */
        virtual void notifyConnectionChange(OTableConnectionData* _pConnectionData) = 0;
    };
}
#endif // DBAUI_RELCONTROLIFACE_HXX
<commit_msg>INTEGRATION: CWS warnings01 (1.2.50); FILE MERGED 2006/03/24 15:36:15 fs 1.2.50.1: #i57457# warning-free code (unxlngi6/.pro + unxsoli4.pro)<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: RelControliFace.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 03:12:55 $
 *
 *  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_RELCONTROLIFACE_HXX
#define DBAUI_RELCONTROLIFACE_HXX

#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif

namespace dbaui
{
    class OTableConnectionData;
    class IRelationControlInterface
    {
    public:
        virtual ~IRelationControlInterface(){}

        /** getConnectionData returns the current connection data
            @return the current connectiondata
        */
        virtual OTableConnectionData* getConnectionData() const = 0;

        /** setValid set the valid inside, can be used for OK buttons
            @param  _bValid true when the using control allows an update
        */
        virtual void setValid(sal_Bool _bValid) = 0;

        virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > getConnection() = 0;

        /** notifyConnectionChange is callback which is called when the table selection has changed and a new connection exists
            @param  _pConnectionData    the connection which exists between the new tables
        */
        virtual void notifyConnectionChange() = 0;
    };
}
#endif // DBAUI_RELCONTROLIFACE_HXX
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: linkeddocuments.hxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: kz $ $Date: 2007-05-10 10:33:02 $
 *
 *  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_LINKEDDOCUMENTS_HXX_
#define _DBAUI_LINKEDDOCUMENTS_HXX_

#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCOMPONENTLOADER_HPP_
#include <com/sun/star/frame/XComponentLoader.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCONTENT_HPP_
#include <com/sun/star/ucb/XContent.hpp>
#endif
#ifndef _LINK_HXX
#include <tools/link.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif

class Window;
//......................................................................
namespace dbaui
{
//......................................................................

    //==================================================================
    //= OLinkedDocumentsAccess
    //==================================================================
    class OLinkedDocumentsAccess
    {
    protected:
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >
                    m_xORB;
        ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >
                    m_xDocumentContainer;
        ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>
                    m_xConnection;
        Window*     m_pDialogParent;
        String      m_sCurrentlyEditing;
        ::rtl::OUString
                    m_sDataSourceName;

    public:
        OLinkedDocumentsAccess(
            Window* _pDialogParent
            ,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB
            ,const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& _rxContainer
            ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _xConnection
            ,const ::rtl::OUString& _sDataSourceName
            );
        ~OLinkedDocumentsAccess();

        enum EOpenMode
        {
            OPEN_NORMAL,
            OPEN_DESIGN,
            OPEN_FORMAIL
        };

        sal_Bool isConnected() const { return m_xConnection.is(); }

        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent>       open(const ::rtl::OUString& _rLinkName
                                                                                ,::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent>& _xDefinition
                                                                                , EOpenMode _eOpenMode = OPEN_NORMAL);

        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent>       newForm(sal_Int32 _nNewFormId
                                ,::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent>& _xDefinition);

        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent>       newWithPilot(
                            const char* _pWizardService
                            ,::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent>& _xDefinition
                            ,const sal_Int32 _nCommandType = -1
                            ,const ::rtl::OUString& _rObjectName = ::rtl::OUString()
                        );

        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent>       newFormWithPilot(
                            ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent>& _xDefinition
                            ,const sal_Int32 _nCommandType = -1
                            ,const ::rtl::OUString& _rObjectName = ::rtl::OUString()
                        );
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent>       newReportWithPilot(
                            ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent>& _xDefinition
                            ,const sal_Int32 _nCommandType = -1
                            ,const ::rtl::OUString& _rObjectName = ::rtl::OUString()
                        );
        void    newQueryWithPilot(
                            const sal_Int32 _nCommandType = -1
                            ,const ::rtl::OUString& _rObjectName = ::rtl::OUString()
                        );

        void    newTableWithPilot();

        enum RESULT
        {
            ERROR,
            SUCCESS,
            CANCEL
        };
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent>   implOpen(const ::rtl::OUString& _rLinkName
                                ,::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent>& _xDefinition
                                , EOpenMode _eOpenMode);
    };

//......................................................................
}   // namespace dbaui
//......................................................................

#endif // _DBAUI_LINKEDDOCUMENTS_HXX_

<commit_msg>INTEGRATION: CWS reportdesign01 (1.14.68); FILE MERGED 2007/09/21 10:51:39 oj 1.14.68.1: #i77690# add new context menu entry to create a report with prefilled table or query<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: linkeddocuments.hxx,v $
 *
 *  $Revision: 1.15 $
 *
 *  last change: $Author: ihi $ $Date: 2007-11-20 19:23:35 $
 *
 *  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_LINKEDDOCUMENTS_HXX_
#define _DBAUI_LINKEDDOCUMENTS_HXX_

#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCOMPONENTLOADER_HPP_
#include <com/sun/star/frame/XComponentLoader.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCONTENT_HPP_
#include <com/sun/star/ucb/XContent.hpp>
#endif
#ifndef _LINK_HXX
#include <tools/link.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif

class Window;
//......................................................................
namespace dbaui
{
//......................................................................

    //==================================================================
    //= OLinkedDocumentsAccess
    //==================================================================
    class OLinkedDocumentsAccess
    {
    protected:
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >
                    m_xORB;
        ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >
                    m_xDocumentContainer;
        ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>
                    m_xConnection;
        Window*     m_pDialogParent;
        String      m_sCurrentlyEditing;
        ::rtl::OUString
                    m_sDataSourceName;

    public:
        OLinkedDocumentsAccess(
            Window* _pDialogParent
            ,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB
            ,const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& _rxContainer
            ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _xConnection
            ,const ::rtl::OUString& _sDataSourceName
            );
        ~OLinkedDocumentsAccess();

        enum EOpenMode
        {
            OPEN_NORMAL,
            OPEN_DESIGN,
            OPEN_FORMAIL
        };

        inline sal_Bool isConnected() const { return m_xConnection.is(); }

        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent>       open(const ::rtl::OUString& _rLinkName
                                                                                ,::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent>& _xDefinition
                                                                                , EOpenMode _eOpenMode = OPEN_NORMAL);

        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent>       newDocument(sal_Int32 _nNewFormId
                                ,::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent>& _xDefinition
                                ,const sal_Int32 _nCommandType
                                ,const ::rtl::OUString& _sObjectName);

        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent>       newWithPilot(
                            const char* _pWizardService
                            ,::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent>& _xDefinition
                            ,const sal_Int32 _nCommandType = -1
                            ,const ::rtl::OUString& _rObjectName = ::rtl::OUString()
                        );

        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent>       newFormWithPilot(
                            ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent>& _xDefinition
                            ,const sal_Int32 _nCommandType = -1
                            ,const ::rtl::OUString& _rObjectName = ::rtl::OUString()
                        );
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent>       newReportWithPilot(
                            ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent>& _xDefinition
                            ,const sal_Int32 _nCommandType = -1
                            ,const ::rtl::OUString& _rObjectName = ::rtl::OUString()
                        );
        void    newQueryWithPilot(
                            const sal_Int32 _nCommandType = -1
                            ,const ::rtl::OUString& _rObjectName = ::rtl::OUString()
                        );

        void    newTableWithPilot();

        enum RESULT
        {
            ERROR,
            SUCCESS,
            CANCEL
        };
        ::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent>   implOpen(const ::rtl::OUString& _rLinkName
                                ,::com::sun::star::uno::Reference< ::com::sun::star::lang::XComponent>& _xDefinition
                                , EOpenMode _eOpenMode);
    };

//......................................................................
}   // namespace dbaui
//......................................................................

#endif // _DBAUI_LINKEDDOCUMENTS_HXX_

<|endoftext|>


<commit_before>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
 * Copyright 2014 Hewlett-Packard Development Company, L.P.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 *
 */

#include "config.h"
#include "common.h"
#include "statement.h"
#include "command.h"
#include "net.h"

bool attachsql_statement_prepare(attachsql_connect_t *con, size_t length, const char *statement, attachsql_error_t **error)
{
  if (con->status == ATTACHSQL_CON_STATUS_NOT_CONNECTED)
  {
    con->query_buffer= (char*)statement;
    con->query_buffer_length= length;
    con->query_buffer_alloc= false;
    con->query_buffer_statement= true;
    return attachsql_connect(con, error);
  }
  con->stmt= new (std::nothrow) attachsql_stmt_st;

  if (con->stmt == NULL)
  {
    con->local_errcode= ATTACHSQL_RET_OUT_OF_MEMORY_ERROR;
    con->command_status= ATTACHSQL_COMMAND_STATUS_SEND_FAILED;
    attachsql_error_client_create(error, ATTACHSQL_ERROR_CODE_ALLOC, ATTACHSQL_ERROR_LEVEL_ERROR, "82100", "Allocation failure for statement object");
    return false;
  }

  con->stmt->con= con;
  asdebug("Sending MySQL prepare");
  attachsql_command_send(con, ATTACHSQL_COMMAND_STMT_PREPARE, (char*)statement, length);

  return true;
}

bool attachsql_statement_execute(attachsql_connect_t *con, attachsql_error_t **error)
{
  if (con == NULL)
  {
    attachsql_error_client_create(error, ATTACHSQL_ERROR_CODE_PARAMETER, ATTACHSQL_ERROR_LEVEL_ERROR, "22023", "No connection provided");
    return false;
  }
  if (con->stmt == NULL)
  {
    attachsql_error_client_create(error, ATTACHSQL_ERROR_CODE_PARAMETER, ATTACHSQL_ERROR_LEVEL_ERROR, "22023", "No statement prepared");
    return false;
  }
  /* Free anything left over from last exec */
  attachsql_command_free(con);
  if (not attachsql_stmt_execute(con->stmt))
  {
    if (con->local_errcode == ATTACHSQL_RET_BAD_STMT_PARAMETER)
    {
      attachsql_error_client_create(error, ATTACHSQL_ERROR_CODE_PARAMETER, ATTACHSQL_ERROR_LEVEL_ERROR, "22023", "Bad parameter bound to statement");
      return false;
    }
    else
    {
      attachsql_error_client_create(error, ATTACHSQL_ERROR_CODE_ALLOC, ATTACHSQL_ERROR_LEVEL_ERROR, "82100", "Allocation failure for statement object");
      return false;
    }
  }
  return true;
}

bool attachsql_stmt_execute(attachsql_stmt_st *stmt)
{
  char *buffer_pos= NULL;
  uint16_t param_count= 0;

  /* Need minimum of 2K plus a bit extra for packet header */
  if (not attachsql_stmt_check_buffer_size(stmt, 2060))
  {
    return false;
  }
  buffer_pos= stmt->exec_buffer;

  /* statement ID */
  attachsql_pack_int4(buffer_pos, stmt->id);
  buffer_pos+= 4;
  /* cursor flags */
  buffer_pos[0]= ATTACHSQL_STMT_CURSOR_NONE;
  buffer_pos++;
  /* iteration count (always 1) */
  attachsql_pack_int4(buffer_pos, 1);
  buffer_pos+= 4;
  /* NULL bitmask */
  if (stmt->param_count > 0)
  {
    uint16_t null_bytes= (stmt->param_count + 7) / 8;
    memset(buffer_pos, 0, null_bytes);
    param_count= stmt->param_count;
    for (uint16_t param= 0; param < stmt->param_count; param++)
    {
      if (stmt->param_data[param].type == ATTACHSQL_COLUMN_TYPE_NULL)
      {
        buffer_pos[param/8] |= (1 << (param % 8));
        param_count--;
      }
    }
    buffer_pos+= null_bytes;
  }
  /* New bind? */
  buffer_pos[0]= stmt->new_bind;
  buffer_pos++;
  /* Bind params
   * First part is type of each parameter, 2 bytes per type
   * Second part is the parameters themselves
   * param_count is the number of params without NULL since they don't store type data
   */
  char *param_type_pos= buffer_pos;
  size_t param_bytes= 0;
  size_t buffer_bytes= 0;
  buffer_pos+= (param_count * 2);
  for (uint16_t param= 0; param < stmt->param_count; param++)
  {
    attachsql_stmt_param_st *param_data= &stmt->param_data[param];

    uint16_t type= (uint16_t)param_data->type;
    if (type == ATTACHSQL_COLUMN_TYPE_NULL)
    {
      continue;
    }
    if (param_data->is_unsigned)
    {
      type|= ATTACHSQL_STMT_PARAM_UNSIGNED_BIT;
    }
    attachsql_pack_int2(&param_type_pos[param * 2], type);

    /* Long data skipped */
    if (param_data->is_long_data)
    {
      continue;
    }

    /* Check buffer for at least attachsql_datetime_st bytes
     * restore pointers too
     */
    param_bytes= param_type_pos - stmt->exec_buffer;
    buffer_bytes= buffer_pos - stmt->exec_buffer;
    if (not attachsql_stmt_check_buffer_size(stmt, sizeof(attachsql_datetime_st)))
    {
      return false;
    }
    param_type_pos= stmt->exec_buffer + param_bytes;
    buffer_pos= stmt->exec_buffer + buffer_bytes;

    switch (param_data->type)
    {
      case ATTACHSQL_COLUMN_TYPE_TINY:
        buffer_pos[0]= param_data->data.tinyint_data;
        buffer_pos++;
        break;
      case ATTACHSQL_COLUMN_TYPE_SHORT:
        attachsql_pack_int2(buffer_pos, param_data->data.smallint_data);
        buffer_pos+= 2;
        break;
      case ATTACHSQL_COLUMN_TYPE_LONG:
        attachsql_pack_int4(buffer_pos, param_data->data.int_data);
        buffer_pos+= 4;
        break;
      case ATTACHSQL_COLUMN_TYPE_LONGLONG:
        attachsql_pack_int8(buffer_pos, param_data->data.bigint_data);
        buffer_pos+= 8;
        break;
      case ATTACHSQL_COLUMN_TYPE_FLOAT:
        memcpy(buffer_pos, &param_data->data.float_data, 4);
        buffer_pos+= 4;
        break;
      case ATTACHSQL_COLUMN_TYPE_DOUBLE:
        memcpy(buffer_pos, &param_data->data.double_data, 8);
        buffer_pos+= 8;
        break;
      case ATTACHSQL_COLUMN_TYPE_TIME:
        buffer_pos= attachsql_pack_time(buffer_pos, param_data->data.datetime_data);
        break;
      case ATTACHSQL_COLUMN_TYPE_DATE:
        buffer_pos= attachsql_pack_datetime(buffer_pos, param_data->data.datetime_data, true);
        break;
      case ATTACHSQL_COLUMN_TYPE_DATETIME:
      case ATTACHSQL_COLUMN_TYPE_TIMESTAMP:
        buffer_pos= attachsql_pack_datetime(buffer_pos, param_data->data.datetime_data, false);
        break;
      case ATTACHSQL_COLUMN_TYPE_STRING:
      case ATTACHSQL_COLUMN_TYPE_BLOB:
        /* check buffer for size */
        param_bytes= param_type_pos - stmt->exec_buffer;
        buffer_bytes= buffer_pos - stmt->exec_buffer;
        if (not attachsql_stmt_check_buffer_size(stmt, param_data->length))
        {
          return false;
        }
        param_type_pos= stmt->exec_buffer + param_bytes;
        buffer_pos= stmt->exec_buffer + buffer_bytes;
        buffer_pos= attachsql_pack_data(buffer_pos, param_data->length, param_data->data.string_data);
        break;
      case ATTACHSQL_COLUMN_TYPE_NULL:
        /* Already handled in the NULL bitmask we should not get here */
      /* The following should never happen, but are listed to make compilers happy bunnies */
      case ATTACHSQL_COLUMN_TYPE_INT24:
      case ATTACHSQL_COLUMN_TYPE_YEAR:
      case ATTACHSQL_COLUMN_TYPE_VARCHAR:
      case ATTACHSQL_COLUMN_TYPE_BIT:
      case ATTACHSQL_COLUMN_TYPE_NEWDECIMAL:
      case ATTACHSQL_COLUMN_TYPE_ENUM:
      case ATTACHSQL_COLUMN_TYPE_SET:
      case ATTACHSQL_COLUMN_TYPE_TINY_BLOB:
      case ATTACHSQL_COLUMN_TYPE_MEDIUM_BLOB:
      case ATTACHSQL_COLUMN_TYPE_LONG_BLOB:
      case ATTACHSQL_COLUMN_TYPE_VARSTRING:
      case ATTACHSQL_COLUMN_TYPE_GEOMETRY:
      case ATTACHSQL_COLUMN_TYPE_DECIMAL:
      case ATTACHSQL_COLUMN_TYPE_ERROR:
      default:
        stmt->con->local_errcode= ATTACHSQL_RET_BAD_STMT_PARAMETER;
        asdebug("Bad stmt parameter type provided: %d", param_data->type);
        stmt->con->command_status= ATTACHSQL_COMMAND_STATUS_SEND_FAILED;
        stmt->con->next_packet_queue_used= 0;
        return false;
        break;
    }
  }
  if (attachsql_command_send(stmt->con, ATTACHSQL_COMMAND_STMT_EXECUTE, stmt->exec_buffer, buffer_pos - stmt->exec_buffer) != ATTACHSQL_COMMAND_STATUS_SEND)
  {
    return false;
  }
  return true;
}

bool attachsql_stmt_check_buffer_size(attachsql_stmt_st *stmt, size_t required)
{
  char *realloc_buffer= NULL;

  if (stmt->exec_buffer_length < required)
  {
    size_t new_size= 0;
    if (stmt->exec_buffer_length == 0)
    {
      new_size= ATTACHSQL_STMT_EXEC_DEFAULT_SIZE;
    }
    else
    {
      new_size= stmt->exec_buffer_length * 2;
    }
    realloc_buffer= (char*)realloc(stmt->exec_buffer, new_size);
    if (realloc_buffer == NULL)
    {
      stmt->con->local_errcode= ATTACHSQL_RET_OUT_OF_MEMORY_ERROR;
      asdebug("Exec buffer realloc failure");
      stmt->con->command_status= ATTACHSQL_COMMAND_STATUS_SEND_FAILED;
      stmt->con->next_packet_queue_used= 0;
      return false;
    }
    stmt->exec_buffer= realloc_buffer;
    stmt->exec_buffer_length= new_size;
  }
  return true;
}

attachsql_command_status_t attachsql_stmt_fetch(attachsql_stmt_st *stmt)
{
  attachsql_buffer_packet_read_end(stmt->con->read_buffer);
  attachsql_packet_queue_push(stmt->con, ATTACHSQL_PACKET_TYPE_STMT_ROW);
  stmt->con->command_status= ATTACHSQL_COMMAND_STATUS_READ_STMT_ROW;
  attachsql_con_process_packets(stmt->con);
  return stmt->con->command_status;
}

void attachsql_statement_close(attachsql_connect_t *con)
{
  attachsql_stmt_st *stmt= con->stmt;
  if (con == NULL)
  {
    return;
  }

  if (con->stmt_row != NULL)
  {
    delete[] con->stmt_row;
  }
  con->stmt_row= NULL;

  if (stmt == NULL)
  {
    return;
  }

  if (stmt->param_count > 0)
  {
    delete[] stmt->params;
  }

  if (stmt->exec_buffer_length > 0)
  {
    free(stmt->exec_buffer);
  }

  if (stmt->param_data != NULL)
  {
    for (uint16_t param= 0; param < stmt->param_count; param++)
    {
      if (stmt->param_data[param].datetime_alloc)
      {
        delete stmt->param_data[param].data.datetime_data;
      }
    }
    delete[] stmt->param_data;
  }

  con->stmt= NULL;
  con->write_buffer_extra= 4;
  attachsql_command_free(con);
  attachsql_pack_int4(&con->write_buffer[1], stmt->id);
  attachsql_command_send(con, ATTACHSQL_COMMAND_STMT_CLOSE, NULL, 0);
  delete stmt;
}

bool attachsql_statement_reset(attachsql_connect_t *con, attachsql_error_t **error)
{
  if (con == NULL)
  {
    attachsql_error_client_create(error, ATTACHSQL_ERROR_CODE_PARAMETER, ATTACHSQL_ERROR_LEVEL_ERROR, "22023", "No connection provided");
    return false;
  }
  if (con->stmt == NULL)
  {
    attachsql_error_client_create(error, ATTACHSQL_ERROR_CODE_PARAMETER, ATTACHSQL_ERROR_LEVEL_ERROR, "22023", "No statement prepared");
    return false;
  }

  con->write_buffer_extra= 4;
  attachsql_pack_int4(&con->write_buffer[1], con->stmt->id);

  if (attachsql_command_send(con, ATTACHSQL_COMMAND_STMT_RESET, NULL, 0) == ATTACHSQL_COMMAND_STATUS_SEND_FAILED)
  {
    attachsql_error_client_create(error, ATTACHSQL_ERROR_CODE_SERVER_GONE, ATTACHSQL_ERROR_LEVEL_ERROR, "08006", con->errmsg);
    return false;
  }

  return true;
}

<commit_msg>Fix cppcheck detected error<commit_after>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
 * Copyright 2014 Hewlett-Packard Development Company, L.P.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may obtain
 * a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 *
 */

#include "config.h"
#include "common.h"
#include "statement.h"
#include "command.h"
#include "net.h"

bool attachsql_statement_prepare(attachsql_connect_t *con, size_t length, const char *statement, attachsql_error_t **error)
{
  if (con->status == ATTACHSQL_CON_STATUS_NOT_CONNECTED)
  {
    con->query_buffer= (char*)statement;
    con->query_buffer_length= length;
    con->query_buffer_alloc= false;
    con->query_buffer_statement= true;
    return attachsql_connect(con, error);
  }
  con->stmt= new (std::nothrow) attachsql_stmt_st;

  if (con->stmt == NULL)
  {
    con->local_errcode= ATTACHSQL_RET_OUT_OF_MEMORY_ERROR;
    con->command_status= ATTACHSQL_COMMAND_STATUS_SEND_FAILED;
    attachsql_error_client_create(error, ATTACHSQL_ERROR_CODE_ALLOC, ATTACHSQL_ERROR_LEVEL_ERROR, "82100", "Allocation failure for statement object");
    return false;
  }

  con->stmt->con= con;
  asdebug("Sending MySQL prepare");
  attachsql_command_send(con, ATTACHSQL_COMMAND_STMT_PREPARE, (char*)statement, length);

  return true;
}

bool attachsql_statement_execute(attachsql_connect_t *con, attachsql_error_t **error)
{
  if (con == NULL)
  {
    attachsql_error_client_create(error, ATTACHSQL_ERROR_CODE_PARAMETER, ATTACHSQL_ERROR_LEVEL_ERROR, "22023", "No connection provided");
    return false;
  }
  if (con->stmt == NULL)
  {
    attachsql_error_client_create(error, ATTACHSQL_ERROR_CODE_PARAMETER, ATTACHSQL_ERROR_LEVEL_ERROR, "22023", "No statement prepared");
    return false;
  }
  /* Free anything left over from last exec */
  attachsql_command_free(con);
  if (not attachsql_stmt_execute(con->stmt))
  {
    if (con->local_errcode == ATTACHSQL_RET_BAD_STMT_PARAMETER)
    {
      attachsql_error_client_create(error, ATTACHSQL_ERROR_CODE_PARAMETER, ATTACHSQL_ERROR_LEVEL_ERROR, "22023", "Bad parameter bound to statement");
      return false;
    }
    else
    {
      attachsql_error_client_create(error, ATTACHSQL_ERROR_CODE_ALLOC, ATTACHSQL_ERROR_LEVEL_ERROR, "82100", "Allocation failure for statement object");
      return false;
    }
  }
  return true;
}

bool attachsql_stmt_execute(attachsql_stmt_st *stmt)
{
  char *buffer_pos= NULL;
  uint16_t param_count= 0;

  /* Need minimum of 2K plus a bit extra for packet header */
  if (not attachsql_stmt_check_buffer_size(stmt, 2060))
  {
    return false;
  }
  buffer_pos= stmt->exec_buffer;

  /* statement ID */
  attachsql_pack_int4(buffer_pos, stmt->id);
  buffer_pos+= 4;
  /* cursor flags */
  buffer_pos[0]= ATTACHSQL_STMT_CURSOR_NONE;
  buffer_pos++;
  /* iteration count (always 1) */
  attachsql_pack_int4(buffer_pos, 1);
  buffer_pos+= 4;
  /* NULL bitmask */
  if (stmt->param_count > 0)
  {
    uint16_t null_bytes= (stmt->param_count + 7) / 8;
    memset(buffer_pos, 0, null_bytes);
    param_count= stmt->param_count;
    for (uint16_t param= 0; param < stmt->param_count; param++)
    {
      if (stmt->param_data[param].type == ATTACHSQL_COLUMN_TYPE_NULL)
      {
        buffer_pos[param/8] |= (1 << (param % 8));
        param_count--;
      }
    }
    buffer_pos+= null_bytes;
  }
  /* New bind? */
  buffer_pos[0]= stmt->new_bind;
  buffer_pos++;
  /* Bind params
   * First part is type of each parameter, 2 bytes per type
   * Second part is the parameters themselves
   * param_count is the number of params without NULL since they don't store type data
   */
  char *param_type_pos= buffer_pos;
  size_t param_bytes= 0;
  size_t buffer_bytes= 0;
  buffer_pos+= (param_count * 2);
  for (uint16_t param= 0; param < stmt->param_count; param++)
  {
    attachsql_stmt_param_st *param_data= &stmt->param_data[param];

    uint16_t type= (uint16_t)param_data->type;
    if (type == ATTACHSQL_COLUMN_TYPE_NULL)
    {
      continue;
    }
    if (param_data->is_unsigned)
    {
      type|= ATTACHSQL_STMT_PARAM_UNSIGNED_BIT;
    }
    attachsql_pack_int2(&param_type_pos[param * 2], type);

    /* Long data skipped */
    if (param_data->is_long_data)
    {
      continue;
    }

    /* Check buffer for at least attachsql_datetime_st bytes
     * restore pointers too
     */
    param_bytes= param_type_pos - stmt->exec_buffer;
    buffer_bytes= buffer_pos - stmt->exec_buffer;
    if (not attachsql_stmt_check_buffer_size(stmt, sizeof(attachsql_datetime_st)))
    {
      return false;
    }
    param_type_pos= stmt->exec_buffer + param_bytes;
    buffer_pos= stmt->exec_buffer + buffer_bytes;

    switch (param_data->type)
    {
      case ATTACHSQL_COLUMN_TYPE_TINY:
        buffer_pos[0]= param_data->data.tinyint_data;
        buffer_pos++;
        break;
      case ATTACHSQL_COLUMN_TYPE_SHORT:
        attachsql_pack_int2(buffer_pos, param_data->data.smallint_data);
        buffer_pos+= 2;
        break;
      case ATTACHSQL_COLUMN_TYPE_LONG:
        attachsql_pack_int4(buffer_pos, param_data->data.int_data);
        buffer_pos+= 4;
        break;
      case ATTACHSQL_COLUMN_TYPE_LONGLONG:
        attachsql_pack_int8(buffer_pos, param_data->data.bigint_data);
        buffer_pos+= 8;
        break;
      case ATTACHSQL_COLUMN_TYPE_FLOAT:
        memcpy(buffer_pos, &param_data->data.float_data, 4);
        buffer_pos+= 4;
        break;
      case ATTACHSQL_COLUMN_TYPE_DOUBLE:
        memcpy(buffer_pos, &param_data->data.double_data, 8);
        buffer_pos+= 8;
        break;
      case ATTACHSQL_COLUMN_TYPE_TIME:
        buffer_pos= attachsql_pack_time(buffer_pos, param_data->data.datetime_data);
        break;
      case ATTACHSQL_COLUMN_TYPE_DATE:
        buffer_pos= attachsql_pack_datetime(buffer_pos, param_data->data.datetime_data, true);
        break;
      case ATTACHSQL_COLUMN_TYPE_DATETIME:
      case ATTACHSQL_COLUMN_TYPE_TIMESTAMP:
        buffer_pos= attachsql_pack_datetime(buffer_pos, param_data->data.datetime_data, false);
        break;
      case ATTACHSQL_COLUMN_TYPE_STRING:
      case ATTACHSQL_COLUMN_TYPE_BLOB:
        /* check buffer for size */
        param_bytes= param_type_pos - stmt->exec_buffer;
        buffer_bytes= buffer_pos - stmt->exec_buffer;
        if (not attachsql_stmt_check_buffer_size(stmt, param_data->length))
        {
          return false;
        }
        param_type_pos= stmt->exec_buffer + param_bytes;
        buffer_pos= stmt->exec_buffer + buffer_bytes;
        buffer_pos= attachsql_pack_data(buffer_pos, param_data->length, param_data->data.string_data);
        break;
      case ATTACHSQL_COLUMN_TYPE_NULL:
        /* Already handled in the NULL bitmask we should not get here */
      /* The following should never happen, but are listed to make compilers happy bunnies */
      case ATTACHSQL_COLUMN_TYPE_INT24:
      case ATTACHSQL_COLUMN_TYPE_YEAR:
      case ATTACHSQL_COLUMN_TYPE_VARCHAR:
      case ATTACHSQL_COLUMN_TYPE_BIT:
      case ATTACHSQL_COLUMN_TYPE_NEWDECIMAL:
      case ATTACHSQL_COLUMN_TYPE_ENUM:
      case ATTACHSQL_COLUMN_TYPE_SET:
      case ATTACHSQL_COLUMN_TYPE_TINY_BLOB:
      case ATTACHSQL_COLUMN_TYPE_MEDIUM_BLOB:
      case ATTACHSQL_COLUMN_TYPE_LONG_BLOB:
      case ATTACHSQL_COLUMN_TYPE_VARSTRING:
      case ATTACHSQL_COLUMN_TYPE_GEOMETRY:
      case ATTACHSQL_COLUMN_TYPE_DECIMAL:
      case ATTACHSQL_COLUMN_TYPE_ERROR:
      default:
        stmt->con->local_errcode= ATTACHSQL_RET_BAD_STMT_PARAMETER;
        asdebug("Bad stmt parameter type provided: %d", param_data->type);
        stmt->con->command_status= ATTACHSQL_COMMAND_STATUS_SEND_FAILED;
        stmt->con->next_packet_queue_used= 0;
        return false;
        break;
    }
  }
  if (attachsql_command_send(stmt->con, ATTACHSQL_COMMAND_STMT_EXECUTE, stmt->exec_buffer, buffer_pos - stmt->exec_buffer) != ATTACHSQL_COMMAND_STATUS_SEND)
  {
    return false;
  }
  return true;
}

bool attachsql_stmt_check_buffer_size(attachsql_stmt_st *stmt, size_t required)
{
  char *realloc_buffer= NULL;

  if (stmt->exec_buffer_length < required)
  {
    size_t new_size= 0;
    if (stmt->exec_buffer_length == 0)
    {
      new_size= ATTACHSQL_STMT_EXEC_DEFAULT_SIZE;
    }
    else
    {
      new_size= stmt->exec_buffer_length * 2;
    }
    realloc_buffer= (char*)realloc(stmt->exec_buffer, new_size);
    if (realloc_buffer == NULL)
    {
      stmt->con->local_errcode= ATTACHSQL_RET_OUT_OF_MEMORY_ERROR;
      asdebug("Exec buffer realloc failure");
      stmt->con->command_status= ATTACHSQL_COMMAND_STATUS_SEND_FAILED;
      stmt->con->next_packet_queue_used= 0;
      return false;
    }
    stmt->exec_buffer= realloc_buffer;
    stmt->exec_buffer_length= new_size;
  }
  return true;
}

attachsql_command_status_t attachsql_stmt_fetch(attachsql_stmt_st *stmt)
{
  attachsql_buffer_packet_read_end(stmt->con->read_buffer);
  attachsql_packet_queue_push(stmt->con, ATTACHSQL_PACKET_TYPE_STMT_ROW);
  stmt->con->command_status= ATTACHSQL_COMMAND_STATUS_READ_STMT_ROW;
  attachsql_con_process_packets(stmt->con);
  return stmt->con->command_status;
}

void attachsql_statement_close(attachsql_connect_t *con)
{
  if (con == NULL)
  {
    return;
  }

  attachsql_stmt_st *stmt= con->stmt;

  if (con->stmt_row != NULL)
  {
    delete[] con->stmt_row;
  }
  con->stmt_row= NULL;

  if (stmt == NULL)
  {
    return;
  }

  if (stmt->param_count > 0)
  {
    delete[] stmt->params;
  }

  if (stmt->exec_buffer_length > 0)
  {
    free(stmt->exec_buffer);
  }

  if (stmt->param_data != NULL)
  {
    for (uint16_t param= 0; param < stmt->param_count; param++)
    {
      if (stmt->param_data[param].datetime_alloc)
      {
        delete stmt->param_data[param].data.datetime_data;
      }
    }
    delete[] stmt->param_data;
  }

  con->stmt= NULL;
  con->write_buffer_extra= 4;
  attachsql_command_free(con);
  attachsql_pack_int4(&con->write_buffer[1], stmt->id);
  attachsql_command_send(con, ATTACHSQL_COMMAND_STMT_CLOSE, NULL, 0);
  delete stmt;
}

bool attachsql_statement_reset(attachsql_connect_t *con, attachsql_error_t **error)
{
  if (con == NULL)
  {
    attachsql_error_client_create(error, ATTACHSQL_ERROR_CODE_PARAMETER, ATTACHSQL_ERROR_LEVEL_ERROR, "22023", "No connection provided");
    return false;
  }
  if (con->stmt == NULL)
  {
    attachsql_error_client_create(error, ATTACHSQL_ERROR_CODE_PARAMETER, ATTACHSQL_ERROR_LEVEL_ERROR, "22023", "No statement prepared");
    return false;
  }

  con->write_buffer_extra= 4;
  attachsql_pack_int4(&con->write_buffer[1], con->stmt->id);

  if (attachsql_command_send(con, ATTACHSQL_COMMAND_STMT_RESET, NULL, 0) == ATTACHSQL_COMMAND_STATUS_SEND_FAILED)
  {
    attachsql_error_client_create(error, ATTACHSQL_ERROR_CODE_SERVER_GONE, ATTACHSQL_ERROR_LEVEL_ERROR, "08006", con->errmsg);
    return false;
  }

  return true;
}

<|endoftext|>


<commit_before>#include <catch.hpp>

#include "stack.hpp"

TEST_CASE("Stack can be instantiated by various types", "[instantiation]") {
	REQUIRE_NOTHROW(stack<int> st1);
	REQUIRE_NOTHROW(stack<double> st1);
	REQUIRE_NOTHROW(stack<char> st1);
	REQUIRE_NOTHROW(stack<int*> st1);
	REQUIRE_NOTHROW(stack<stack<int>> st1);
}
TEST_CASE("Push, pop, top", "[push_pop_top]") {
	stack<int> st;
	st.push(1);
	st.push(2);
	REQUIRE(st.top() == 2);
	st.pop();
	REQUIRE(st.top() == 1);
}
TEST_CASE("count", "[count]") {
	stack<int> st;
	REQUIRE(st.count() == 0);
	st.push(1);
	REQUIRE(st.count() == 1);
	st.push(2);
	REQUIRE(st.count() == 2);
	st.pop();
	REQUIRE(st.count() == 1);
	st.pop();
	REQUIRE(st.count() == 0);
}
TEST_CASE("Copy constructor, =", "[copy_ctr, =]") {
	stack<int> st1;
	st1.push(1);
	st1.push(2);
	REQUIRE_NOTHROW(stack<int> st2 = st1);
	REQUIRE_NOTHROW(stack<int> st2;
	st2 = st1);

	stack<int> st3 = st1;
	stack<int> st4 = st1;
	REQUIRE(st1.top() == 2);
	REQUIRE(st3.top() == 2);
	st3.pop();
	REQUIRE(st3.top() == 1);
	REQUIRE(st4.top() == 2);
	st4.pop();
	REQUIRE(st4.top() == 1);
}
<commit_msg>return to v4 tests<commit_after>#include <catch.hpp>

#include "stack.hpp"

TEST_CASE("Stack can be instantiated by various types", "[instantiation]") {
	REQUIRE_NOTHROW(stack<int> st1);
	REQUIRE_NOTHROW(stack<double> st1);
	REQUIRE_NOTHROW(stack<char> st1);
	REQUIRE_NOTHROW(stack<int*> st1);
	REQUIRE_NOTHROW(stack<stack<int>> st1);
}
TEST_CASE("Push, pop", "[push_pop]") {
	stack<int> st;
	st.push(1);
	st.push(2);
	REQUIRE(st.pop() == 2);
	REQUIRE(st.pop() == 1);
}
TEST_CASE("count", "[count]") {
	stack<int> st;
	REQUIRE(st.count() == 0);
	st.push(1);
	REQUIRE(st.count() == 1);
	st.push(2);
	REQUIRE(st.count() == 2);
	st.pop();
	REQUIRE(st.count() == 1);
	st.pop();
	REQUIRE(st.count() == 0);
}
TEST_CASE("Copy constructor, =", "[copy_ctr, =]") {
	stack<int> st1;
	st1.push(1);
	st1.push(2);
	REQUIRE_NOTHROW(stack<int> st2 = st1);
	REQUIRE_NOTHROW(stack<int> st2;
		st2 = st1);

	stack<int> st3 = st1;
	REQUIRE(st1.pop() == 2);
	REQUIRE(st3.pop() == 2);
	st3.pop();
	REQUIRE(st3.count() == 0);
	REQUIRE(st1.pop() == 1);
}

int main(int argc, char* const argv[])
{
	// global setup...

	int result = Catch::Session().run(argc, argv);

	// global clean-up...
	system("pause");
	return result;
}
<|endoftext|>


<commit_before>#include <map>
#include <vector>
#include <string>

// Russian localization file

namespace i2p {
namespace i18n {
namespace russian { // language

	// See for language plural forms here:
	// https://localization-guide.readthedocs.io/en/latest/l10n/pluralforms.html
	int plural (int n) {
		return n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;
	}

	static std::map<std::string, std::string> strings
	{
		// HTTP Proxy
		{"Proxy error", "Ошибка прокси"},
		{"Proxy info", "Информация прокси"},
		{"Proxy error: Host not found", "Ошибка прокси: Адрес не найден"},
		{"Remote host not found in router's addressbook", "Запрошенный адрес не найден в адресной книге роутера"},
		{"You may try to find this host on jump services below", "Вы можете попробовать найти адрес на джамп сервисах ниже"},
		{"Invalid request", "Некорректный запрос"},
		{"Proxy unable to parse your request", "Прокси не может разобрать ваш запрос"},
		{"addresshelper is not supported", "addresshelper не поддерживается"},
		{"Host", "Адрес"},
		{"added to router's addressbook from helper", "добавлен в адресную книгу роутера через хелпер"},
		{"already in router's addressbook", "уже а адресной книге роутера"},
		{"Click", "Нажмите"},
		{"here", "здесь"},
		{"to proceed", "чтобы продолжить"},
		{"to update record", "чтобы обновить запись"},
		{"Addresshelper found", "Найден addresshelper"},
		{"invalid request uri", "некорректный URI запроса"},
		{"Can't detect destination host from request", "Не удалось определить адрес назначения из запроса"},
		{"Outproxy failure", "Ошибка внешнего прокси"},
		{"bad outproxy settings", "некорректные настройки внешнего прокси"},
		{"not inside I2P network, but outproxy is not enabled", "не в I2P сети, но внешний прокси не включен"},
		{"unknown outproxy url", "неизвестный URL внешнего прокси"},
		{"cannot resolve upstream proxy", "не удается определить внешний прокси"},
		{"hostname too long", "имя хоста слишком длинное"},
		{"cannot connect to upstream socks proxy", "не удается подключиться к вышестоящему SOCKS прокси"},
		{"Cannot negotiate with socks proxy", "Не удается договориться с вышестоящим SOCKS прокси"},
		{"CONNECT error", "Ошибка CONNECT запроса"},
		{"Failed to Connect", "Не удалось подключиться"},
		{"socks proxy error", "ошибка SOCKS прокси"},
		{"failed to send request to upstream", "не удалось отправить запрос вышестоящему прокси"},
		{"No Reply From socks proxy", "Нет ответа от SOCKS прокси сервера"},
		{"cannot connect", "не удалось подключиться"},
		{"http out proxy not implemented", "поддержка внешнего HTTP прокси сервера не реализована"},
		{"cannot connect to upstream http proxy", "не удалось подключиться к вышестоящему HTTP прокси серверу"},
		{"Host is down", "Адрес недоступен"},
		{"Can't create connection to requested host, it may be down. Please try again later.",
			"Не удалось установить соединение к запрошенному адресу, возможно он не в сети. Попробуйте повторить запрос позже."},

		// Webconsole //
		// cssStyles
		{"Disabled", "Выключено"},
		{"Enabled", "Включено"},
		// ShowTraffic
		{"KiB", "КиБ"},
		{"MiB", "МиБ"},
		{"GiB", "ГиБ"},
		// ShowTunnelDetails
		{"building", "строится"},
		{"failed", "неудачный"},
		{"expiring", "истекает"},
		{"established", "работает"},
		{"exploratory", "исследовательский"},
		{"unknown", "неизвестно"},
		{"i2pd webconsole", "Веб-консоль i2pd"},
		// ShowPageHead
		{"Main page", "Главная"},
		{"Router commands", "Команды роутера"},
		{"Local destinations", "Локальные назнач."},
		{"LeaseSets", "Лизсеты"},
		{"Tunnels", "Туннели"},
		{"Transit tunnels", "Транзит. туннели"},
		{"Transports", "Транспорты"},
		{"I2P tunnels", "I2P туннели"},
		{"SAM sessions", "SAM сессии"},
		// Network Status
		{"OK", "OK"},
		{"Testing", "Тестирование"},
		{"Firewalled", "Файрвол"},
		{"Unknown", "Неизвестно"},
		{"Proxy", "Прокси"},
		{"Mesh", "MESH-сеть"},
		{"Error", "Ошибка"},
		{"Clock skew", "Не точное время"},
		{"Offline", "Оффлайн"},
		{"Symmetric NAT", "Симметричный NAT"},
		// Status
		{"Uptime", "В сети"},
		{"Network status", "Сетевой статус"},
		{"Network status v6", "Сетевой статус v6"},
		{"Stopping in", "Остановка через"},
		{"Family", "Семейство"},
		{"Tunnel creation success rate", "Успешно построенных туннелей"},
		{"Received", "Получено"},
		{"Sent", "Отправлено"},
		{"Transit", "Транзит"},
		{"KiB/s", "КиБ/с"},
		{"Data path", "Путь к данным"},
		{"Hidden content. Press on text to see.", "Скрытый контент. Нажмите на текст чтобы отобразить."},
		{"Router Ident", "Идентификатор роутера"},
		{"Router Family", "Семейство роутера"},
		{"Router Caps", "Флаги роутера"},
		{"Version", "Версия"},
		{"Our external address", "Наш внешний адрес"},
		{"supported", "поддерживается"},
		{"Routers", "Роутеры"},
		{"Floodfills", "Флудфилы"},
		{"LeaseSets", "Лизсеты"},
		{"Client Tunnels", "Клиентские туннели"},
		{"Transit Tunnels", "Транзитные туннели"},
		{"Services", "Сервисы"},
		// ShowLocalDestinations
		{"Local Destinations", "Локальные назначения"},
		// ShowLeaseSetDestination
		{"Encrypted B33 address", "Шифрованные B33 адреса"},
		{"Address registration line", "Строка регистрации адреса"},
		{"Domain", "Домен"},
		{"Generate", "Сгенерировать"},
		{"Note: result string can be used only for registering 2LD domains (example.i2p). For registering subdomains please use i2pd-tools.",
			"Примечание: полученная строка может быть использована только для регистрации доменов второго уровня. Для регистрации поддоменов используйте i2pd-tools."},
		{"Address", "Адрес"},
		{"Type", "Тип"},
		{"EncType", "ТипШифр"},
		{"Inbound tunnels", "Входящие туннели"},
		{"Outbound tunnels", "Исходящие туннели"},
		{"ms", "мс"}, // milliseconds
		{"Tags", "Теги"},
		{"Incoming", "Входящие"},
		{"Outgoing", "Исходящие"},
		{"Destination", "Назначение"},
		{"Amount", "Количество"},
		{"Incoming Tags", "Входящие Теги"},
		{"Tags sessions", "Сессии Тегов"},
		{"Status", "Статус"},
		// ShowLocalDestination
		{"Local Destination", "Локальное назначение"},
		{"Streams", "Стримы"},
		{"Close stream", "Закрыть стрим"},
		// ShowI2CPLocalDestination
		{"I2CP session not found", "I2CP сессия не найдена"},
		{"I2CP is not enabled", "I2CP не включен"},
		// ShowLeasesSets
		{"Invalid", "Некорректный"},
		{"Store type", "Тип хранилища"},
		{"Expires", "Истекает"},
		{"Non Expired Leases", "Не истекшие Lease-ы"},
		{"Gateway", "Шлюз"},
		{"TunnelID", "ID туннеля"},
		{"EndDate", "Заканчивается"},
		{"not floodfill", "не флудфил"},
		// ShowTunnels
		{"Queue size", "Размер очереди"},
		// ShowCommands
		{"Run peer test", "Запустить тестирование"},
		{"Decline transit tunnels", "Отклонять транзитные туннели"},
		{"Accept transit tunnels", "Принимать транзитные туннели"},
		{"Cancel graceful shutdown", "Отменить плавную остановку"},
		{"Start graceful shutdown", "Запустить плавную остановку"},
		{"Force shutdown", "Принудительная остановка"},
		{"Note: any action done here are not persistent and not changes your config files.",
			"Примечание: любое действие произведенное здесь не является постоянным и не изменяет ваши конфигурационные файлы."},
		{"Logging level", "Уровень логирования"},
		{"Transit tunnels limit", "Лимит транзитных туннелей"},
		{"Change", "Изменить"},
		// ShowTransitTunnels
		{"no transit tunnels currently built", "нет построенных транзитных туннелей"},
		// ShowSAMSessions/ShowSAMSession
		{"SAM disabled", "SAM выключен"},
		{"SAM session not found", "SAM сессия не найдена"},
		{"no sessions currently running", "нет запущенных сессий"},
		{"SAM Session", "SAM сессия"},
		// ShowI2PTunnels
		{"Server Tunnels", "Серверные туннели"},
		{"Client Forwards", "Клиентские переадресации"},
		{"Server Forwards", "Серверные переадресации"},
		// HandlePage
		{"Unknown page", "Неизвестная страница"},
		// HandleCommand, ShowError
		{"Invalid token", "Неверный токен"},
		{"SUCCESS", "УСПЕШНО"},
		{"ERROR", "ОШИБКА"},
		{"Unknown command", "Неизвестная команда"},
		{"Command accepted", "Команда принята"},
		{"Back to commands list", "Вернуться к списку команд"},
		{"You will be redirected in 5 seconds", "Вы будете переадресованы через 5 секунд"},
		// HTTP_COMMAND_KILLSTREAM
		{"Stream closed", "Стрим закрыт"},
		{"Stream not found or already was closed", "Стрим не найден или уже закрыт"},
		{"Destination not found", "Точка назначения не найдена"},
		{"StreamID can't be null", "StreamID не может быть пустым"},
		{"Return to destination page", "Вернуться на страницу точки назначения"},
		{"You will be redirected back in 5 seconds", "Вы будете переадресованы назад через 5 секунд"},
		// HTTP_COMMAND_LIMITTRANSIT
		{"Transit tunnels count must not exceed 65535", "Число транзитных туннелей не должно превышать 65535"},
		// HTTP_COMMAND_GET_REG_STRING
		{"Register at reg.i2p", "Зарегистрировать на reg.i2p"},
		{"Description", "Описание"},
		{"A bit information about service on domain", "Немного информации о сервисе на домене"},
		{"Submit", "Отправить"},
		{"Domain can't end with .b32.i2p", "Домен не может заканчиваться на .b32.i2p"},
		{"Domain must end with .i2p", "Домен должен заканчиваться на .i2p"},
		{"Such destination is not found", "Такая точка назначения не найдена"},
		{"", ""},
	};

	static std::map<std::string, std::vector<std::string>> plurals
	{
		// ShowUptime
		{"days",    {"день", "дня", "дней"}},
		{"hours",   {"час", "часа", "часов"}},
		{"minutes", {"минуту", "минуты", "минут"}},
		{"seconds", {"секунду", "секунды", "секунд"}},
		{"", {"", ""}},
	};

	std::string GetString (std::string arg)
	{
		auto it = strings.find(arg);
		if (it == strings.end())
		{
			return arg;
		} else {
			return it->second;
		}
	}

	std::string GetPlural (std::string arg, int n)
	{
		auto it = plurals.find(arg);
		if (it == plurals.end())
		{
			return arg;
		} else {
			int form = plural(n);
			return it->second[form];
		}
	}

} // language
} // i18n
} // i2p
<commit_msg>[i18n] update russian translation<commit_after>#include <map>
#include <vector>
#include <string>

// Russian localization file

namespace i2p {
namespace i18n {
namespace russian { // language

	// See for language plural forms here:
	// https://localization-guide.readthedocs.io/en/latest/l10n/pluralforms.html
	int plural (int n) {
		return n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;
	}

	static std::map<std::string, std::string> strings
	{
		// HTTP Proxy
		{"Proxy error", "Ошибка прокси"},
		{"Proxy info", "Информация прокси"},
		{"Proxy error: Host not found", "Ошибка прокси: Адрес не найден"},
		{"Remote host not found in router's addressbook", "Запрошенный адрес не найден в адресной книге роутера"},
		{"You may try to find this host on jump services below", "Вы можете попробовать найти адрес на джамп сервисах ниже"},
		{"Invalid request", "Некорректный запрос"},
		{"Proxy unable to parse your request", "Прокси не может разобрать ваш запрос"},
		{"addresshelper is not supported", "addresshelper не поддерживается"},
		{"Host", "Адрес"},
		{"added to router's addressbook from helper", "добавлен в адресную книгу роутера через хелпер"},
		{"already in router's addressbook", "уже а адресной книге роутера"},
		{"Click", "Нажмите"},
		{"here", "здесь"},
		{"to proceed", "чтобы продолжить"},
		{"to update record", "чтобы обновить запись"},
		{"Addresshelper found", "Найден addresshelper"},
		{"invalid request uri", "некорректный URI запроса"},
		{"Can't detect destination host from request", "Не удалось определить адрес назначения из запроса"},
		{"Outproxy failure", "Ошибка внешнего прокси"},
		{"bad outproxy settings", "некорректные настройки внешнего прокси"},
		{"not inside I2P network, but outproxy is not enabled", "не в I2P сети, но внешний прокси не включен"},
		{"unknown outproxy url", "неизвестный URL внешнего прокси"},
		{"cannot resolve upstream proxy", "не удается определить внешний прокси"},
		{"hostname too long", "имя хоста слишком длинное"},
		{"cannot connect to upstream socks proxy", "не удается подключиться к вышестоящему SOCKS прокси"},
		{"Cannot negotiate with socks proxy", "Не удается договориться с вышестоящим SOCKS прокси"},
		{"CONNECT error", "Ошибка CONNECT запроса"},
		{"Failed to Connect", "Не удалось подключиться"},
		{"socks proxy error", "ошибка SOCKS прокси"},
		{"failed to send request to upstream", "не удалось отправить запрос вышестоящему прокси"},
		{"No Reply From socks proxy", "Нет ответа от SOCKS прокси сервера"},
		{"cannot connect", "не удалось подключиться"},
		{"http out proxy not implemented", "поддержка внешнего HTTP прокси сервера не реализована"},
		{"cannot connect to upstream http proxy", "не удалось подключиться к вышестоящему HTTP прокси серверу"},
		{"Host is down", "Адрес недоступен"},
		{"Can't create connection to requested host, it may be down. Please try again later.",
			"Не удалось установить соединение к запрошенному адресу, возможно он не в сети. Попробуйте повторить запрос позже."},

		// Webconsole //
		// cssStyles
		{"Disabled", "Выключено"},
		{"Enabled", "Включено"},
		// ShowTraffic
		{"KiB", "КиБ"},
		{"MiB", "МиБ"},
		{"GiB", "ГиБ"},
		// ShowTunnelDetails
		{"building", "строится"},
		{"failed", "неудачный"},
		{"expiring", "истекает"},
		{"established", "работает"},
		{"exploratory", "исследовательский"},
		{"unknown", "неизвестно"},
		{"i2pd webconsole", "Веб-консоль i2pd"},
		// ShowPageHead
		{"Main page", "Главная"},
		{"Router commands", "Команды роутера"},
		{"Local destinations", "Локальные назнач."},
		{"LeaseSets", "Лизсеты"},
		{"Tunnels", "Туннели"},
		{"Transit tunnels", "Транзит. туннели"},
		{"Transports", "Транспорты"},
		{"I2P tunnels", "I2P туннели"},
		{"SAM sessions", "SAM сессии"},
		// Network Status
		{"OK", "OK"},
		{"Testing", "Тестирование"},
		{"Firewalled", "Файрвол"},
		{"Unknown", "Неизвестно"},
		{"Proxy", "Прокси"},
		{"Mesh", "MESH-сеть"},
		{"Error", "Ошибка"},
		{"Clock skew", "Не точное время"},
		{"Offline", "Оффлайн"},
		{"Symmetric NAT", "Симметричный NAT"},
		// Status
		{"Uptime", "В сети"},
		{"Network status", "Сетевой статус"},
		{"Network status v6", "Сетевой статус v6"},
		{"Stopping in", "Остановка через"},
		{"Family", "Семейство"},
		{"Tunnel creation success rate", "Успешно построенных туннелей"},
		{"Received", "Получено"},
		{"Sent", "Отправлено"},
		{"Transit", "Транзит"},
		{"KiB/s", "КиБ/с"},
		{"Data path", "Путь к данным"},
		{"Hidden content. Press on text to see.", "Скрытый контент. Нажмите на текст чтобы отобразить."},
		{"Router Ident", "Идентификатор роутера"},
		{"Router Family", "Семейство роутера"},
		{"Router Caps", "Флаги роутера"},
		{"Version", "Версия"},
		{"Our external address", "Наш внешний адрес"},
		{"supported", "поддерживается"},
		{"Routers", "Роутеры"},
		{"Floodfills", "Флудфилы"},
		{"LeaseSets", "Лизсеты"},
		{"Client Tunnels", "Клиентские туннели"},
		{"Transit Tunnels", "Транзитные туннели"},
		{"Services", "Сервисы"},
		// ShowLocalDestinations
		{"Local Destinations", "Локальные назначения"},
		// ShowLeaseSetDestination
		{"Encrypted B33 address", "Шифрованные B33 адреса"},
		{"Address registration line", "Строка регистрации адреса"},
		{"Domain", "Домен"},
		{"Generate", "Сгенерировать"},
		{"Note: result string can be used only for registering 2LD domains (example.i2p). For registering subdomains please use i2pd-tools.",
			"Примечание: полученная строка может быть использована только для регистрации доменов второго уровня. Для регистрации поддоменов используйте i2pd-tools."},
		{"Address", "Адрес"},
		{"Type", "Тип"},
		{"EncType", "ТипШифр"},
		{"Inbound tunnels", "Входящие туннели"},
		{"Outbound tunnels", "Исходящие туннели"},
		{"ms", "мс"}, // milliseconds
		{"Tags", "Теги"},
		{"Incoming", "Входящие"},
		{"Outgoing", "Исходящие"},
		{"Destination", "Назначение"},
		{"Amount", "Количество"},
		{"Incoming Tags", "Входящие Теги"},
		{"Tags sessions", "Сессии Тегов"},
		{"Status", "Статус"},
		// ShowLocalDestination
		{"Local Destination", "Локальное назначение"},
		{"Streams", "Стримы"},
		{"Close stream", "Закрыть стрим"},
		// ShowI2CPLocalDestination
		{"I2CP session not found", "I2CP сессия не найдена"},
		{"I2CP is not enabled", "I2CP не включен"},
		// ShowLeasesSets
		{"Invalid", "Некорректный"},
		{"Store type", "Тип хранилища"},
		{"Expires", "Истекает"},
		{"Non Expired Leases", "Не истекшие Lease-ы"},
		{"Gateway", "Шлюз"},
		{"TunnelID", "ID туннеля"},
		{"EndDate", "Заканчивается"},
		{"not floodfill", "не флудфил"},
		// ShowTunnels
		{"Queue size", "Размер очереди"},
		// ShowCommands
		{"Run peer test", "Запустить тестирование"},
		{"Decline transit tunnels", "Отклонять транзитные туннели"},
		{"Accept transit tunnels", "Принимать транзитные туннели"},
		{"Cancel graceful shutdown", "Отменить плавную остановку"},
		{"Start graceful shutdown", "Запустить плавную остановку"},
		{"Force shutdown", "Принудительная остановка"},
		{"Note: any action done here are not persistent and not changes your config files.",
			"Примечание: любое действие произведенное здесь не является постоянным и не изменяет ваши конфигурационные файлы."},
		{"Logging level", "Уровень логирования"},
		{"Transit tunnels limit", "Лимит транзитных туннелей"},
		{"Change", "Изменить"},
		// ShowTransitTunnels
		{"no transit tunnels currently built", "нет построенных транзитных туннелей"},
		// ShowSAMSessions/ShowSAMSession
		{"SAM disabled", "SAM выключен"},
		{"SAM session not found", "SAM сессия не найдена"},
		{"no sessions currently running", "нет запущенных сессий"},
		{"SAM Session", "SAM сессия"},
		// ShowI2PTunnels
		{"Server Tunnels", "Серверные туннели"},
		{"Client Forwards", "Клиентские перенаправления"},
		{"Server Forwards", "Серверные перенаправления"},
		// HandlePage
		{"Unknown page", "Неизвестная страница"},
		// HandleCommand, ShowError
		{"Invalid token", "Неверный токен"},
		{"SUCCESS", "УСПЕШНО"},
		{"ERROR", "ОШИБКА"},
		{"Unknown command", "Неизвестная команда"},
		{"Command accepted", "Команда принята"},
		{"Back to commands list", "Вернуться к списку команд"},
		{"You will be redirected in 5 seconds", "Вы будете переадресованы через 5 секунд"},
		// HTTP_COMMAND_KILLSTREAM
		{"Stream closed", "Стрим закрыт"},
		{"Stream not found or already was closed", "Стрим не найден или уже закрыт"},
		{"Destination not found", "Точка назначения не найдена"},
		{"StreamID can't be null", "StreamID не может быть пустым"},
		{"Return to destination page", "Вернуться на страницу точки назначения"},
		{"You will be redirected back in 5 seconds", "Вы будете переадресованы назад через 5 секунд"},
		// HTTP_COMMAND_LIMITTRANSIT
		{"Transit tunnels count must not exceed 65535", "Число транзитных туннелей не должно превышать 65535"},
		// HTTP_COMMAND_GET_REG_STRING
		{"Register at reg.i2p", "Зарегистрировать на reg.i2p"},
		{"Description", "Описание"},
		{"A bit information about service on domain", "Немного информации о сервисе на домене"},
		{"Submit", "Отправить"},
		{"Domain can't end with .b32.i2p", "Домен не может заканчиваться на .b32.i2p"},
		{"Domain must end with .i2p", "Домен должен заканчиваться на .i2p"},
		{"Such destination is not found", "Такая точка назначения не найдена"},
		{"", ""},
	};

	static std::map<std::string, std::vector<std::string>> plurals
	{
		// ShowUptime
		{"days",    {"день", "дня", "дней"}},
		{"hours",   {"час", "часа", "часов"}},
		{"minutes", {"минуту", "минуты", "минут"}},
		{"seconds", {"секунду", "секунды", "секунд"}},
		{"", {"", ""}},
	};

	std::string GetString (std::string arg)
	{
		auto it = strings.find(arg);
		if (it == strings.end())
		{
			return arg;
		} else {
			return it->second;
		}
	}

	std::string GetPlural (std::string arg, int n)
	{
		auto it = plurals.find(arg);
		if (it == plurals.end())
		{
			return arg;
		} else {
			int form = plural(n);
			return it->second[form];
		}
	}

} // language
} // i18n
} // i2p
<|endoftext|>


<commit_before>#include "coverage.h"
#include "location.h"
#include "geos/geom/Coordinate.h"
#include "coordinate.h"
#include "box.h"
#include "coordinatesystem.h"
#include "rootdrawer.h"
#include "spatialdatadrawer.h"

using namespace Ilwis;
using namespace Geodrawer;

RootDrawer::RootDrawer(QObject *parent) : ComplexDrawer("RootDrawer",0,0, parent)
{
    valid(true);

}

void RootDrawer::addDrawer(DrawerInterface *newdrawer, bool overrule)
{
    overrule = drawerCount(ComplexDrawer::dtMAIN) == 0 || overrule;
    SpatialDataDrawer *datadrawer = dynamic_cast<SpatialDataDrawer *>(newdrawer);
    if ( overrule && datadrawer && datadrawer->coverage().isValid()) {
        ICoordinateSystem cs = datadrawer->coverage()->coordinateSystem();
        Envelope envelope =  envelope2RootEnvelope(cs, datadrawer->envelope());
        Envelope viewEnv = _viewRect;
        bool setViewEnv =  envelope != viewEnv;
        viewEnv += envelope;
        _coverageRect = datadrawer->envelope();
        if ( setViewEnv)
            envelopeView(viewEnv, true);

    }
    return ComplexDrawer::addDrawer(newdrawer);
}

void RootDrawer::addEnvelope(const ICoordinateSystem &csSource, const Envelope &env, bool overrule)
{
    if ( overrule || !_coverageRect.isValid() || _coverageRect.isNull()) {
        Envelope newEnvelope = envelope2RootEnvelope(csSource, env);
        _coverageRect += newEnvelope;
    }
    envelopeView(_coverageRect, overrule);
}

Envelope RootDrawer::viewEnvelope() const
{
    return _viewRect;
}

void RootDrawer::envelopeView(const Envelope &viewRect, bool overrule)
{
    if ( !_coverageRect.isValid() || _coverageRect.isNull()){
        ERROR2(ERR_NO_INITIALIZED_2,TR("Coverage area"), TR("Visualization"));
        return;
    }
    if ( !_pixelAreaSize.isValid()) {
        ERROR2(ERR_NO_INITIALIZED_2,TR("Pixel area"), TR("Visualization"));
        return;
    }
    if ( overrule || !_viewRect.isValid()) {
        _aspectRatioCoverage = _coverageRect.xlength() / _coverageRect.ylength();
        double w = viewRect.xlength();
        double h = viewRect.ylength();
        if ( _aspectRatioCoverage <= 1.0) { // coverage is higher than it is wide
            double pixwidth = (double)_pixelAreaSize.ysize() * _aspectRatioCoverage; // height is dominant, so width in pixels is derived from height
            double deltay = 0;
            if ( pixwidth > _pixelAreaSize.xsize()) { // if the width is bigger than the available width
                deltay = viewRect.ylength() * ( pixwidth / _pixelAreaSize.xsize() - 1.0); // we need to reduce the ysize else the coverage goes outside the window
                pixwidth = _pixelAreaSize.xsize(); // pixelwidth becomes the max available number of pix in x
            }
            double fracofWidth = 1.0 - (_pixelAreaSize.xsize() - pixwidth) / _pixelAreaSize.xsize(); // fraction of the width of _pixelArea actually used
            double crdWidth = w / fracofWidth; // the actual width used in coordinates (x)
            double delta = (crdWidth - w) / 2.0; // the difference between the requested view width and the realized view width
            // new extent of the viewrectangle (coords)
            _viewRect =  Envelope(Coordinate(viewRect.min_corner().x - delta, viewRect.min_corner().y - deltay /2.0,0),
                                  Coordinate(viewRect.max_corner().x + delta,viewRect.max_corner().y + deltay/ 2.0,0));
        } else {
            double pixheight = (double)_pixelAreaSize.xsize() / _aspectRatioCoverage; // width is dominant, so height in pixels is derived from width
            double deltax = 0;
            if ( pixheight > _pixelAreaSize.ysize()) {
                deltax = viewRect.xlength() * ( pixheight / _pixelAreaSize.ysize() - 1.0);
                pixheight = _pixelAreaSize.ysize();
            }
            double fracofHeight = 1.0 - abs(_pixelAreaSize.ysize() - pixheight) / (double)_pixelAreaSize.ysize();
            double crdHeight = h / fracofHeight;
            double delta = (crdHeight - h) / 2.0;
            _viewRect =  Envelope(Coordinate(viewRect.min_corner().x - deltax /2.0,viewRect.min_corner().y  - delta,0),
                                  Coordinate(viewRect.max_corner().x + deltax /2.0,viewRect.max_corner().y  + delta,0));

        }
        _zoomRect = _viewRect;
        viewPoint(_viewRect.center(), true);

        setMVP();
    }
}

void RootDrawer::setMVP()
{
    _projection.setToIdentity();
    _projection.ortho(_zoomRect.min_corner().x, _zoomRect.max_corner().x,_zoomRect.min_corner().y,_zoomRect.max_corner().y, -1, 1);
    _mvp = _model * _view * _projection;
    unprepare(DrawerInterface::ptMVP); // we reset the mvp so for all drawers a new value has to be set to the graphics card
}

void RootDrawer::pixelAreaSize(const Size<>& size)
{
    _aspectRatioView = (double)size.xsize() / (double)size.ysize();
    if ( _aspectRatioCoverage != 0 && !_viewRect.isNull() && !_zoomRect.isNull()){
        if ( _aspectRatioCoverage <= 1.0){
            if ( size.xsize() != _pixelAreaSize.xsize()){
                modifyEnvelopeZoomView(_viewRect.size().xsize(), _zoomRect.size().xsize(),(double)size.xsize() / _pixelAreaSize.xsize());
            }
            if ( size.ysize() != _pixelAreaSize.ysize()) { // make sure the zoomsize is changed if the cols change
                //modify_zoomRectView(_viewRect.size().xsize()(), _zoomRect.size().xsize()(),(double)_pixelAreaSize.ysize() / size.ysize());
                modifyEnvelopeZoomView(_viewRect.size().xsize(), _zoomRect.size().xsize(), (double)_pixelAreaSize.ysize() / (double)size.ysize() );
            }

        } else { // x < y
            if ( size.ysize() != _pixelAreaSize.ysize()){
                modifyEnvelopeZoomView(_viewRect.size().ysize(), _zoomRect.size().ysize(),(double)size.ysize() / _pixelAreaSize.ysize() );

            }
            if ( size.xsize() != _pixelAreaSize.xsize()) {
                modifyEnvelopeZoomView(_viewRect.size().ysize(), _zoomRect.size().ysize(),(double)_pixelAreaSize.xsize() / size.xsize() );
            }
        }
    }
    setMVP();
    _pixelAreaSize = size;

}

Size<> RootDrawer::pixelAreaSize() const
{
    return _pixelAreaSize;
}

void RootDrawer::modifyEnvelopeZoomView(double dview, double dzoom, double ratio) {
    double deltaview = dview - dview * ratio ;
    double deltazoom = dzoom - dzoom * ratio;
    if ( _aspectRatioCoverage < 1.0){
        _viewRect.min_corner().y -= deltaview / (2.0 * _aspectRatioView);
        _viewRect.max_corner().y += deltaview/ ( 2.0 * _aspectRatioView);
        if ( _viewRect.min_corner().y > _coverageRect.min_corner().y || _viewRect.min_corner().x < _coverageRect.min_corner().x){
            _viewRect.min_corner().y = _coverageRect.min_corner().y;
            _viewRect.max_corner().y = _coverageRect.max_corner().y;
            _viewRect.min_corner().x += deltaview  / 2.0;
            _viewRect.max_corner().x -= deltaview / 2.0;
        }
        _zoomRect.min_corner().y -= deltazoom/  (2.0 * _aspectRatioView);
        _zoomRect.max_corner().y += deltazoom /  (2.0 * _aspectRatioView);
        if ( _zoomRect.min_corner().y > _coverageRect.min_corner().y || _zoomRect.min_corner().x < _coverageRect.min_corner().x){
            _zoomRect.min_corner().y = _coverageRect.min_corner().y;
            _zoomRect.max_corner().y = _coverageRect.max_corner().y;
            _zoomRect.min_corner().x +=  deltazoom    / 2.0;
            _zoomRect.max_corner().x -= deltazoom  / 2.0;
        }

    }else {

    }
//    if ( _aspectRatioCoverage <= 1.0) {
//        _viewRect.min_corner().x = cMiddle.x - deltaview / 2.0;
//        _viewRect.max_corner().x = cMiddle.x + deltaview / 2.0;
//        _zoomRect.min_corner().x = cMiddle.x - deltazoom / 2.0;
//        _zoomRect.max_corner().x = cMiddle.x + deltazoom / 2.0;
//    } else {
//        _viewRect.min_corner().y = cMiddle.y - deltaview / 2.0;
//        _viewRect.max_corner().y = cMiddle.y + deltaview / 2.0;
//        _zoomRect.min_corner().y = cMiddle.y - deltazoom / 2.0;
//        _zoomRect.max_corner().y = cMiddle.y + deltazoom / 2.0;
//    }
}

const QMatrix4x4 &RootDrawer::mvpMatrix() const
{

    return _mvp;
}

const ICoordinateSystem &RootDrawer::coordinateSystem() const
{
    return _coordinateSystem;
}

void RootDrawer::coordinateSystem(const ICoordinateSystem &csy)
{
    _coordinateSystem = csy;
}

void RootDrawer::viewPoint(const Coordinate& viewCenter, bool setEyePoint){
    _viewPoint = viewCenter;
    if ( setEyePoint){
        _eyePoint.x = _viewPoint.x;
        _eyePoint.y = _viewPoint.y - _zoomRect.ylength() * 1.5;
        _eyePoint.z = _zoomRect.xlength() ;
    }
}

void RootDrawer::cleanUp()
{

}

bool RootDrawer::prepare(DrawerInterface::PreparationType prepType, const IOOptions &options, QOpenGLContext *openglContext)
{
    return ComplexDrawer::prepare(prepType, options, openglContext)    ;
}

Envelope RootDrawer::envelope2RootEnvelope(const ICoordinateSystem &csSource, const Envelope &env)
{
    Envelope envelope = (!_coordinateSystem.isValid() ||
                         !csSource.isValid() ||
                         _coordinateSystem->isEqual(csSource.ptr()) ||
                         _coordinateSystem->isUnknown() ||
                         csSource->isUnknown()) ?
                env : _coordinateSystem->convertEnvelope(csSource, env);

    return envelope;
}
<commit_msg>formatting<commit_after>#include "coverage.h"
#include "location.h"
#include "geos/geom/Coordinate.h"
#include "coordinate.h"
#include "box.h"
#include "coordinatesystem.h"
#include "rootdrawer.h"
#include "spatialdatadrawer.h"

using namespace Ilwis;
using namespace Geodrawer;

RootDrawer::RootDrawer(QObject *parent) : ComplexDrawer("RootDrawer",0,0, parent)
{
    valid(true);

}

void RootDrawer::addDrawer(DrawerInterface *newdrawer, bool overrule)
{
    overrule = drawerCount(ComplexDrawer::dtMAIN) == 0 || overrule;
    SpatialDataDrawer *datadrawer = dynamic_cast<SpatialDataDrawer *>(newdrawer);
    if ( overrule && datadrawer && datadrawer->coverage().isValid()) {
        ICoordinateSystem cs = datadrawer->coverage()->coordinateSystem();
        Envelope envelope =  envelope2RootEnvelope(cs, datadrawer->envelope());
        Envelope viewEnv = _viewRect;
        bool setViewEnv =  envelope != viewEnv;
        viewEnv += envelope;
        _coverageRect = datadrawer->envelope();
        if ( setViewEnv)
            envelopeView(viewEnv, true);

    }
    return ComplexDrawer::addDrawer(newdrawer);
}

void RootDrawer::addEnvelope(const ICoordinateSystem &csSource, const Envelope &env, bool overrule)
{
    if ( overrule || !_coverageRect.isValid() || _coverageRect.isNull()) {
        Envelope newEnvelope = envelope2RootEnvelope(csSource, env);
        _coverageRect += newEnvelope;
    }
    envelopeView(_coverageRect, overrule);
}

Envelope RootDrawer::viewEnvelope() const
{
    return _viewRect;
}

void RootDrawer::envelopeView(const Envelope &viewRect, bool overrule)
{
    if ( !_coverageRect.isValid() || _coverageRect.isNull()){
        ERROR2(ERR_NO_INITIALIZED_2,TR("Coverage area"), TR("Visualization"));
        return;
    }
    if ( !_pixelAreaSize.isValid()) {
        ERROR2(ERR_NO_INITIALIZED_2,TR("Pixel area"), TR("Visualization"));
        return;
    }
    if ( overrule || !_viewRect.isValid()) {
        _aspectRatioCoverage = _coverageRect.xlength() / _coverageRect.ylength();
        double w = viewRect.xlength();
        double h = viewRect.ylength();
        if ( _aspectRatioCoverage <= 1.0) { // coverage is higher than it is wide
            double pixwidth = (double)_pixelAreaSize.ysize() * _aspectRatioCoverage; // height is dominant, so width in pixels is derived from height
            double deltay = 0;
            if ( pixwidth > _pixelAreaSize.xsize()) { // if the width is bigger than the available width
                deltay = viewRect.ylength() * ( pixwidth / _pixelAreaSize.xsize() - 1.0); // we need to reduce the ysize else the coverage goes outside the window
                pixwidth = _pixelAreaSize.xsize(); // pixelwidth becomes the max available number of pix in x
            }
            double fracofWidth = 1.0 - (_pixelAreaSize.xsize() - pixwidth) / _pixelAreaSize.xsize(); // fraction of the width of _pixelArea actually used
            double crdWidth = w / fracofWidth; // the actual width used in coordinates (x)
            double delta = (crdWidth - w) / 2.0; // the difference between the requested view width and the realized view width
            // new extent of the viewrectangle (coords)
            _viewRect =  Envelope(Coordinate(viewRect.min_corner().x - delta, viewRect.min_corner().y - deltay /2.0,0),
                                  Coordinate(viewRect.max_corner().x + delta,viewRect.max_corner().y + deltay/ 2.0,0));
        } else {
            double pixheight = (double)_pixelAreaSize.xsize() / _aspectRatioCoverage; // width is dominant, so height in pixels is derived from width
            double deltax = 0;
            if ( pixheight > _pixelAreaSize.ysize()) {
                deltax = viewRect.xlength() * ( pixheight / _pixelAreaSize.ysize() - 1.0);
                pixheight = _pixelAreaSize.ysize();
            }
            double fracofHeight = 1.0 - abs(_pixelAreaSize.ysize() - pixheight) / (double)_pixelAreaSize.ysize();
            double crdHeight = h / fracofHeight;
            double delta = (crdHeight - h) / 2.0;
            _viewRect =  Envelope(Coordinate(viewRect.min_corner().x - deltax /2.0,viewRect.min_corner().y  - delta,0),
                                  Coordinate(viewRect.max_corner().x + deltax /2.0,viewRect.max_corner().y  + delta,0));

        }
        _zoomRect = _viewRect;
        viewPoint(_viewRect.center(), true);

        setMVP();
    }
}

void RootDrawer::setMVP()
{
    _projection.setToIdentity();
    _projection.ortho(_zoomRect.min_corner().x, _zoomRect.max_corner().x,_zoomRect.min_corner().y,_zoomRect.max_corner().y, -1, 1);
    _mvp = _model * _view * _projection;
    unprepare(DrawerInterface::ptMVP); // we reset the mvp so for all drawers a new value has to be set to the graphics card
}

void RootDrawer::pixelAreaSize(const Size<>& size)
{
    _aspectRatioView = (double)size.xsize() / (double)size.ysize();
    if ( _aspectRatioCoverage != 0 && !_viewRect.isNull() && !_zoomRect.isNull()){
        if ( _aspectRatioCoverage <= 1.0){
            if ( size.xsize() != _pixelAreaSize.xsize()){
                modifyEnvelopeZoomView(_viewRect.size().xsize(), _zoomRect.size().xsize(),(double)size.xsize() / _pixelAreaSize.xsize());
            }
            if ( size.ysize() != _pixelAreaSize.ysize()) { // make sure the zoomsize is changed if the cols change
                //modify_zoomRectView(_viewRect.size().xsize()(), _zoomRect.size().xsize()(),(double)_pixelAreaSize.ysize() / size.ysize());
                modifyEnvelopeZoomView(_viewRect.size().xsize(), _zoomRect.size().xsize(), (double)_pixelAreaSize.ysize() / (double)size.ysize() );
            }

        } else { // x < y
            if ( size.ysize() != _pixelAreaSize.ysize()){
                modifyEnvelopeZoomView(_viewRect.size().ysize(), _zoomRect.size().ysize(),(double)size.ysize() / _pixelAreaSize.ysize() );

            }
            if ( size.xsize() != _pixelAreaSize.xsize()) {
                modifyEnvelopeZoomView(_viewRect.size().ysize(), _zoomRect.size().ysize(),(double)_pixelAreaSize.xsize() / size.xsize() );
            }
        }
    }
    setMVP();
    _pixelAreaSize = size;

}

Size<> RootDrawer::pixelAreaSize() const
{
    return _pixelAreaSize;
}

void RootDrawer::modifyEnvelopeZoomView(double dview, double dzoom, double ratio) {
    double deltaview = dview - dview * ratio ;
    double deltazoom = dzoom - dzoom * ratio;
    //if ( _aspectRatioCoverage < 1.0){
    _viewRect.min_corner().y -= deltaview / (2.0 * _aspectRatioView);
    _viewRect.max_corner().y += deltaview/ ( 2.0 * _aspectRatioView);
    if ( _viewRect.min_corner().y > _coverageRect.min_corner().y || _viewRect.min_corner().x < _coverageRect.min_corner().x){
        _viewRect.min_corner().y = _coverageRect.min_corner().y;
        _viewRect.max_corner().y = _coverageRect.max_corner().y;
        _viewRect.min_corner().x += deltaview  / 2.0;
        _viewRect.max_corner().x -= deltaview / 2.0;
    }
    _zoomRect.min_corner().y -= deltazoom/  (2.0 * _aspectRatioView);
    _zoomRect.max_corner().y += deltazoom /  (2.0 * _aspectRatioView);
    if ( _zoomRect.min_corner().y > _coverageRect.min_corner().y || _zoomRect.min_corner().x < _coverageRect.min_corner().x){
        _zoomRect.min_corner().y = _coverageRect.min_corner().y;
        _zoomRect.max_corner().y = _coverageRect.max_corner().y;
        _zoomRect.min_corner().x +=  deltazoom    / 2.0;
        _zoomRect.max_corner().x -= deltazoom  / 2.0;
    }

    // }

}

const QMatrix4x4 &RootDrawer::mvpMatrix() const
{

    return _mvp;
}

const ICoordinateSystem &RootDrawer::coordinateSystem() const
{
    return _coordinateSystem;
}

void RootDrawer::coordinateSystem(const ICoordinateSystem &csy)
{
    _coordinateSystem = csy;
}

void RootDrawer::viewPoint(const Coordinate& viewCenter, bool setEyePoint){
    _viewPoint = viewCenter;
    if ( setEyePoint){
        _eyePoint.x = _viewPoint.x;
        _eyePoint.y = _viewPoint.y - _zoomRect.ylength() * 1.5;
        _eyePoint.z = _zoomRect.xlength() ;
    }
}

void RootDrawer::cleanUp()
{

}

bool RootDrawer::prepare(DrawerInterface::PreparationType prepType, const IOOptions &options, QOpenGLContext *openglContext)
{
    return ComplexDrawer::prepare(prepType, options, openglContext)    ;
}

Envelope RootDrawer::envelope2RootEnvelope(const ICoordinateSystem &csSource, const Envelope &env)
{
    Envelope envelope = (!_coordinateSystem.isValid() ||
                         !csSource.isValid() ||
                         _coordinateSystem->isEqual(csSource.ptr()) ||
                         _coordinateSystem->isUnknown() ||
                         csSource->isUnknown()) ?
                env : _coordinateSystem->convertEnvelope(csSource, env);

    return envelope;
}
<|endoftext|>