<commit_before>#include <iostream>
#include <cmath>

#include "acmacs-base/argc-argv.hh"
#include "acmacs-base/stream.hh"
#include "seqdb/seqdb.hh"
#include "acmacs-chart-2/factory-import.hh"
#include "tree.hh"
#include "tree-export.hh"

// ----------------------------------------------------------------------

int main(int argc, const char* argv[])
{
    using namespace std::string_literals;
    try {
        argc_argv args(argc, argv,
                       {
                           {"--db-dir", ""},
                           {"--seqdb", ""},
                           {"--chart", ""},
                           {"--max-leaf-offset", 80},

                           {"-v", false},
                           {"--verbose", false},
                           {"-h", false},
                           {"--help", false},
                       });

        if (args["-h"] || args["--help"] || args.number_of_arguments() != 1) {
            throw std::runtime_error("Usage: "s + args.program() + " [options] <tree.json>\n" + args.usage_options());
        }
        const bool verbose = args["-v"] || args["--verbose"];
        seqdb::setup_dbs(args["--db-dir"], verbose ? seqdb::report::yes : seqdb::report::no);
        if (args["--seqdb"])
            seqdb::setup(args["--seqdb"], verbose ? seqdb::report::yes : seqdb::report::no);

        Tree tree;
        tree::tree_import(args[0], tree);
        tree.match_seqdb(seqdb::get());
        if (args["--chart"]) {
            auto chart = acmacs::chart::import_from_file(args["--chart"], acmacs::chart::Verify::None, report_time::No);
            const auto matched_names = tree.match(*chart);
            if (matched_names)
                std::cout << "Tree sequences found in the chart: " << matched_names << std::endl;
        }
        tree.set_number_strains();
        tree.ladderize(Tree::LadderizeMethod::NumberOfLeaves);
        tree.compute_cumulative_edge_length();
        const auto [min_edge, max_edge] = tree.cumulative_edge_minmax();
        // std::cout << "mm: " << min_edge << ' ' << max_edge << '\n';
        const auto step = max_edge / static_cast<size_t>(args["--max-leaf-offset"]);

        for (const auto* node : tree.leaf_nodes()) {
            const auto edge = node->data.cumulative_edge_length / step;
            std::cout << std::string(static_cast<size_t>(std::lround(edge)), ' ') << node->seq_id;
            if (node->draw.chart_antigen_index)
                std::cout << " [antigen: " << *node->draw.chart_antigen_index << ']';
            std::cout << "  [cumul: " << node->data.cumulative_edge_length
                      << ']'
                      // << "  [edge: " << edge << ']'
                      << '\n';
        }

        return 0;
    }
    catch (std::exception& err) {
        std::cerr << "ERROR: " << err.what() << '\n';
        return 1;
    }
}

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>showing tree in the text format<commit_after>#include <iostream>
#include <cmath>

#include "acmacs-base/argc-argv.hh"
#include "acmacs-base/stream.hh"
#include "seqdb/seqdb.hh"
#include "acmacs-chart-2/factory-import.hh"
#include "tree.hh"
#include "tree-export.hh"

static void print_tree_leaves(const Tree& tree, double step);
static void print_tree(const Tree& tree, double step);

// ----------------------------------------------------------------------

int main(int argc, const char* argv[])
{
    using namespace std::string_literals;
    try {
        argc_argv args(argc, argv,
                       {
                           {"--db-dir", ""},
                           {"--seqdb", ""},
                           {"--chart", ""},
                           {"--max-leaf-offset", 80},

                           {"-v", false},
                           {"--verbose", false},
                           {"-h", false},
                           {"--help", false},
                       });

        if (args["-h"] || args["--help"] || args.number_of_arguments() != 1) {
            throw std::runtime_error("Usage: "s + args.program() + " [options] <tree.json>\n" + args.usage_options());
        }
        const bool verbose = args["-v"] || args["--verbose"];
        seqdb::setup_dbs(args["--db-dir"], verbose ? seqdb::report::yes : seqdb::report::no);
        if (args["--seqdb"])
            seqdb::setup(args["--seqdb"], verbose ? seqdb::report::yes : seqdb::report::no);

        Tree tree;
        tree::tree_import(args[0], tree);
        tree.match_seqdb(seqdb::get());
        if (args["--chart"]) {
            auto chart = acmacs::chart::import_from_file(args["--chart"], acmacs::chart::Verify::None, report_time::No);
            const auto matched_names = tree.match(*chart);
            if (matched_names)
                std::cout << "Tree sequences found in the chart: " << matched_names << std::endl;
        }
        tree.set_number_strains();
        tree.ladderize(Tree::LadderizeMethod::NumberOfLeaves);
        tree.compute_cumulative_edge_length();
        const auto [min_edge, max_edge] = tree.cumulative_edge_minmax();
        // std::cout << "mm: " << min_edge << ' ' << max_edge << '\n';
        const auto step = max_edge / static_cast<size_t>(args["--max-leaf-offset"]);

        print_tree(tree, step);
          // print_tree_leaves(tree, step);

        return 0;
    }
    catch (std::exception& err) {
        std::cerr << "ERROR: " << err.what() << '\n';
        return 1;
    }
}

// ----------------------------------------------------------------------

void print_tree(const Tree& tree, double step)
{
    auto print_prefix = [step](const Node& node) {
        const auto edge = node.data.cumulative_edge_length / step;
        std::cout << std::string(static_cast<size_t>(std::lround(edge)), ' ');
    };

    auto print_cumul = [](const Node& node) { std::cout << "  [cumul: " << node.data.cumulative_edge_length << ']'; };

    auto print_leaf = [&](const Node& node) {
        print_prefix(node);
        std::cout << node.seq_id;
        if (node.draw.chart_antigen_index)
            std::cout << " [antigen: " << *node.draw.chart_antigen_index << ']';
        print_cumul(node);
        std::cout << '\n';
    };

    auto print_node = [&](const Node& node) {
        print_prefix(node);
        std::cout << '+';
          // print_cumul(node);
        std::cout << '\n';
    };

    tree::iterate_leaf_pre(tree, print_leaf, print_node);

} // print_tree

// ----------------------------------------------------------------------

void print_tree_leaves(const Tree& tree, double step)
{
    for (const auto* node : tree.leaf_nodes()) {
        const auto edge = node->data.cumulative_edge_length / step;
        std::cout << std::string(static_cast<size_t>(std::lround(edge)), ' ') << node->seq_id;
        if (node->draw.chart_antigen_index)
            std::cout << " [antigen: " << *node->draw.chart_antigen_index << ']';
        std::cout << "  [cumul: " << node->data.cumulative_edge_length
                  << ']'
                  // << "  [edge: " << edge << ']'
                  << '\n';
    }

} // print_tree_leaves

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: AppDetailView.hxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: kz $ $Date: 2007-05-10 10:17:31 $
 *
 *  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_APPDETAILVIEW_HXX
#define DBAUI_APPDETAILVIEW_HXX

#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_
#include <com/sun/star/frame/XController.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCONTENT_HPP_
#include <com/sun/star/ucb/XContent.hpp>
#endif
#ifndef _SV_SPLIT_HXX
#include <vcl/split.hxx>
#endif
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef DBACCESS_TABLEDESIGN_ICLIPBOARDTEST_HXX
#include "IClipBoardTest.hxx"
#endif
#ifndef DBAUI_TITLE_WINDOW_HXX
#include "AppTitleWindow.hxx"
#endif
#ifndef DBAUI_APPELEMENTTYPE_HXX
#include "AppElementType.hxx"
#endif
#ifndef _SVTREEBOX_HXX
#include <svtools/svtreebx.hxx>
#endif
#ifndef DBAUI_VERTSPLITVIEW_HXX
#include "VertSplitView.hxx"
#endif

#include <vector>

class SvLBoxEntry;
namespace dbaui
{
    class OApplicationController;
    class OAppBorderWindow;
    class OApplicationDetailView;
    class OAppDetailPageHelper;
    class OTasksWindow;

    class OCreationList : public SvTreeListBox
    {
        OTasksWindow*   m_pTaskWindow;

        // members related to drawing the currently hovered/selected entry
        SvLBoxEntry*        m_pMouseDownEntry;
        SvLBoxEntry*        m_pLastActiveEntry;
        Color               m_aOriginalBackgroundColor;
        Font                m_aOriginalFont;

    public:
        OCreationList(OTasksWindow* _pParent);
        // window overloads
        virtual void MouseMove( const MouseEvent& rMEvt );
        virtual void MouseButtonDown( const MouseEvent& rMEvt );
        virtual void MouseButtonUp( const MouseEvent& rMEvt );
        virtual void KeyInput( const KeyEvent& rKEvt );
        virtual void Paint( const Rectangle& rRect );
        virtual void StartDrag( sal_Int8 _nAction, const Point& _rPosPixel );
        virtual void GetFocus();
        virtual void LoseFocus();

        inline void resetLastActive() { m_pLastActiveEntry = NULL;}

        void    updateHelpText();

    protected:
        virtual void        PreparePaint( SvLBoxEntry* _pEntry );
        virtual Rectangle   GetFocusRect( SvLBoxEntry* _pEntry, long _nLine );
        virtual void        ModelHasCleared();

    private:
        void    onSelected( SvLBoxEntry* _pEntry ) const;
        /** sets a new current entry, and invalidates the old and the new one, if necessary
            @return <TRUE/> if and only if the "current entry" changed
        */
        bool    setCurrentEntryInvalidate( SvLBoxEntry* _pEntry );
    };

    typedef ::std::pair< ::rtl::OUString,USHORT>                TResourcePair;
    typedef ::std::vector< ::std::pair<String, TResourcePair> > TResourceStruct;

    class OTasksWindow : public Window
    {
        ::std::vector< USHORT >             m_aHelpTextIds;
        OCreationList                       m_aCreation;
        FixedText                           m_aDescription;
        FixedText                           m_aHelpText;
        FixedLine                           m_aFL;
        OApplicationDetailView*             m_pDetailView;

        DECL_LINK( OnEntrySelectHdl,        SvTreeListBox* );
        void ImplInitSettings( BOOL bFont, BOOL bForeground, BOOL bBackground );
    protected:
        virtual void DataChanged(const DataChangedEvent& rDCEvt);
    public:
        OTasksWindow(Window* _pParent,OApplicationDetailView* _pDetailView);
        virtual ~OTasksWindow();

        // window overloads
        virtual void Resize();

        OApplicationDetailView* getDetailView() const { return m_pDetailView; }

        /** fills the Creation listbox with the necessary strings and images
            @param  _rList
                The strings and the id of the images and help texts to add.
        */
        void fillCreationNew( const TResourceStruct& _rList );

        void Clear();
        void setHelpText(USHORT _nId);
    };
    //==================================================================
    class OApplicationDetailView : public OSplitterView
                                 , public IClipboardTest
    {
        Splitter                            m_aHorzSplitter;
        OTitleWindow                        m_aTasks;
        OTitleWindow                        m_aContainer;
        OAppBorderWindow&                   m_rBorderWin;       // my parent
        OAppDetailPageHelper*               m_pControlHelper;

        void ImplInitSettings( BOOL bFont, BOOL bForeground, BOOL bBackground );
    protected:
        virtual void DataChanged(const DataChangedEvent& rDCEvt);
    public:
        OApplicationDetailView(OAppBorderWindow& _rParent,PreviewMode _ePreviewMode);
        virtual ~OApplicationDetailView();
        // window overloads
        //  virtual void Resize();
        virtual void GetFocus();

        /** creates the tables page
            @param  _xConnection
                The connection to get the table names
        */
        void createTablesPage(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _xConnection);

        /** creates the page for the specific type.
            @param  _eType
                The type which should be created. E_TABLE isn't allowed.
            @param  _xContainer
                The container of the elements to be inserted.
        */
        void createPage(ElementType _eType,const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& _xContainer);

        inline OAppBorderWindow& getBorderWin() const { return m_rBorderWin;}
        sal_Bool isCutAllowed() ;
        sal_Bool isCopyAllowed()    ;
        sal_Bool isPasteAllowed();
        virtual sal_Bool hasChildPathFocus() { return HasChildPathFocus(); }
        void copy();
        void cut();
        void paste();

        /** return the qualified name.
            @param  _pEntry
                The entry of a table, or query, form, report to get the qualified name.
                If the entry is <NULL/>, the first selected is chosen.
            @return
                the qualified name
        */
        ::rtl::OUString getQualifiedName( SvLBoxEntry* _pEntry ) const;

        /** returns if an entry is a leaf
            @param _pEntry
                The entry to check
            @return
                <TRUE/> if the entry is a leaf, otherwise <FALSE/>
        */
        sal_Bool isLeaf(SvLBoxEntry* _pEntry) const;

        /** returns if one of the selected entries is a leaf
            @return
                <TRUE/> if the entry is a leaf, otherwise <FALSE/>
        */
        sal_Bool isALeafSelected() const;

        /** select all entries in the detail page
        */
        void selectAll();

        /// returns <TRUE/> if it sorts ascending
        sal_Bool isSortUp() const;

        /// sort the entries in the detail page down
        void sortDown();

        /// sort the entries in the detail page up
        void sortUp();

        /// returns <TRUE/> when a detail page was filled
        sal_Bool isFilled() const;

        /// return the element of currently select entry
        ElementType getElementType() const;

        /** clears the detail pages.
            @param  _bTaskAlso
                If <TRUE/> the task window will also be cleared.
        */
        void clearPages(sal_Bool _bTaskAlso = sal_True);

        /// returns the count of entries
        sal_Int32 getElementCount();

        /// returns the count of selected entries
        sal_Int32 getSelectionCount();

        /** returns the element names which are selected
            @param  _rNames
                The list will be filled.
        */
        void getSelectionElementNames(::std::vector< ::rtl::OUString>& _rNames ) const;

        /** adds a new object to the detail page.
            @param  _eType
                The type where the entry shold be appended.
            @param  _rName
                The name of the object to be inserted
            @param  _rObject
                The object to add.
            @param  _rxConn
                If we insert a table, the connection must be set.
        */
        SvLBoxEntry* elementAdded(ElementType eType
                        ,const ::rtl::OUString& _rName
                        ,const ::com::sun::star::uno::Any& _rObject );

        /** replaces a objects name with a new one
            @param  _eType
                The type where the entry shold be appended.
            @param  _rOldName
                The old name of the object to be replaced
            @param  _rNewName
                The new name of the object to be replaced
            @param  _rxConn
                If we insert a table, the connection must be set.
            @param  _xObject
                The object which was replaced
        */
        void elementReplaced(ElementType eType
                        ,const ::rtl::OUString& _rOldName
                        ,const ::rtl::OUString& _rNewName );

        /** removes an element from the detail page.
            @param  _eType
                The type where the entry shold be appended.
            @param  _rName
                The name of the element to be removed.
            @param  _rxConn
                If we remove a table, the connection must be set.
        */
        void elementRemoved(ElementType _eType
                            ,const ::rtl::OUString& _rName );

        /// returns the preview mode
        PreviewMode getPreviewMode();

        /// <TRUE/> if the preview is enabled
        sal_Bool isPreviewEnabled();

        /** switches to the given preview mode
            @param  _eMode
                the mode to set for the preview
        */
        void switchPreview(PreviewMode _eMode);

        /** shows the Preview of the content when it is enabled.
            @param  _xContent
                The content which must support the "preview" command.
        */
        void showPreview(const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContent >& _xContent);

        /** shows the Preview of a table or query
            @param  _sDataSourceName
                the name of the data source
            @param  _sName
                the name of table or query
            @param  _bTable
                <TRUE/> if it is a table, otherwise <FALSE/>
            @return void
        */
        void showPreview(   const ::rtl::OUString& _sDataSourceName,
                            const ::rtl::OUString& _sName,
                            sal_Bool _bTable);

        SvLBoxEntry* getEntry( const Point& _aPoint ) const;

        /** a command entry was selected
            @param  _sCommand
                The command to be executed.
        */
        void onCreationClick( const ::rtl::OUString& _sCommand);
    };
}
#endif // DBAUI_APPDETAILVIEW_HXX

<commit_msg>INTEGRATION: CWS dba23ui (1.13.48); FILE MERGED 2007/05/19 21:25:35 fs 1.13.48.2: RESYNC: (1.13-1.14); FILE MERGED 2006/12/21 08:30:59 fs 1.13.48.1: #i72799# enhanced mnemonics handling, now also for the task pane / refactored the task pane initialization<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: AppDetailView.hxx,v $
 *
 *  $Revision: 1.15 $
 *
 *  last change: $Author: obo $ $Date: 2007-06-12 05:32:49 $
 *
 *  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_APPDETAILVIEW_HXX
#define DBAUI_APPDETAILVIEW_HXX

#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_
#include <com/sun/star/frame/XController.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCONTENT_HPP_
#include <com/sun/star/ucb/XContent.hpp>
#endif
#ifndef _SV_SPLIT_HXX
#include <vcl/split.hxx>
#endif
#ifndef _SV_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef _SV_MNEMONIC_HXX
#include <vcl/mnemonic.hxx>
#endif
#ifndef DBACCESS_TABLEDESIGN_ICLIPBOARDTEST_HXX
#include "IClipBoardTest.hxx"
#endif
#ifndef DBAUI_TITLE_WINDOW_HXX
#include "AppTitleWindow.hxx"
#endif
#ifndef DBAUI_APPELEMENTTYPE_HXX
#include "AppElementType.hxx"
#endif
#ifndef _SVTREEBOX_HXX
#include <svtools/svtreebx.hxx>
#endif
#ifndef DBAUI_VERTSPLITVIEW_HXX
#include "VertSplitView.hxx"
#endif

#include <vector>

class SvLBoxEntry;

namespace dbaui
{
    class OApplicationController;
    class OAppBorderWindow;
    class OApplicationDetailView;
    class OAppDetailPageHelper;
    class OTasksWindow;

    class OCreationList : public SvTreeListBox
    {
        OTasksWindow&   m_rTaskWindow;

        // members related to drawing the currently hovered/selected entry
        SvLBoxEntry*        m_pMouseDownEntry;
        SvLBoxEntry*        m_pLastActiveEntry;
        Color               m_aOriginalBackgroundColor;
        Font                m_aOriginalFont;

    public:
        OCreationList( OTasksWindow& _rParent );
        // window overloads
        virtual void MouseMove( const MouseEvent& rMEvt );
        virtual void MouseButtonDown( const MouseEvent& rMEvt );
        virtual void MouseButtonUp( const MouseEvent& rMEvt );
        virtual void KeyInput( const KeyEvent& rKEvt );
        virtual void Paint( const Rectangle& rRect );
        virtual void StartDrag( sal_Int8 _nAction, const Point& _rPosPixel );
        virtual void GetFocus();
        virtual void LoseFocus();

        inline void resetLastActive() { m_pLastActiveEntry = NULL;}

        void    updateHelpText();

    protected:
        virtual void        PreparePaint( SvLBoxEntry* _pEntry );
        virtual Rectangle   GetFocusRect( SvLBoxEntry* _pEntry, long _nLine );
        virtual void        ModelHasCleared();

        // IMnemonicEntryList
        virtual void        SelectSearchEntry( const void* _pEntry );
        virtual void        ExecuteSearchEntry( const void* _pEntry );

    private:
        void    onSelected( SvLBoxEntry* _pEntry ) const;
        /** sets a new current entry, and invalidates the old and the new one, if necessary
            @return <TRUE/> if and only if the "current entry" changed
        */
        bool    setCurrentEntryInvalidate( SvLBoxEntry* _pEntry );
    };

    struct TaskEntry
    {
        ::rtl::OUString sUNOCommand;
        USHORT          nHelpID;
        String          sTitle;
        bool            bHideWhenDisabled;
            // TODO: we should be consistent in the task pane and the menus/toolbars:
            // If an entry is disabled in the latter, it should also be disabled in the former.
            // If an entry is *hidden* in the former, it should also be hidden in the latter.

        TaskEntry( const sal_Char* _pAsciiUNOCommand, USHORT _nHelpID, USHORT _nTitleResourceID, bool _bHideWhenDisabled = false );
    };
    typedef ::std::vector< TaskEntry >  TaskEntryList;

    struct TaskPaneData
    {
        /// the tasks available in the pane
        TaskEntryList   aTasks;
        /// the resource ID for the title of the pane
        USHORT          nTitleId;
    };

    class OTasksWindow : public Window
    {
        OCreationList                       m_aCreation;
        FixedText                           m_aDescription;
        FixedText                           m_aHelpText;
        FixedLine                           m_aFL;
        OApplicationDetailView*             m_pDetailView;

        DECL_LINK( OnEntrySelectHdl,        SvTreeListBox* );
        void ImplInitSettings( BOOL bFont, BOOL bForeground, BOOL bBackground );
    protected:
        virtual void DataChanged(const DataChangedEvent& rDCEvt);
    public:
        OTasksWindow(Window* _pParent,OApplicationDetailView* _pDetailView);
        virtual ~OTasksWindow();

        // window overloads
        virtual void Resize();

        OApplicationDetailView* getDetailView() const { return m_pDetailView; }

        /// fills the Creation listbox with the necessary strings and images
        void fillTaskEntryList( const TaskEntryList& _rList );

        inline bool HandleKeyInput( const KeyEvent& _rKEvt )
        {
            return m_aCreation.HandleKeyInput( _rKEvt );
        }

        void Clear();
        void setHelpText(USHORT _nId);
    };
    //==================================================================
    class OApplicationDetailView : public OSplitterView
                                 , public IClipboardTest
    {
        Splitter                            m_aHorzSplitter;
        OTitleWindow                        m_aTasks;
        OTitleWindow                        m_aContainer;
        OAppBorderWindow&                   m_rBorderWin;       // my parent
        OAppDetailPageHelper*               m_pControlHelper;
        ::std::vector< TaskPaneData >       m_aTaskPaneData;
        MnemonicGenerator                   m_aExternalMnemonics;

        void ImplInitSettings( BOOL bFont, BOOL bForeground, BOOL bBackground );

    protected:
        virtual void DataChanged(const DataChangedEvent& rDCEvt);

    public:
        OApplicationDetailView(OAppBorderWindow& _rParent,PreviewMode _ePreviewMode);
        virtual ~OApplicationDetailView();
        // window overloads
        //  virtual void Resize();
        virtual void GetFocus();

        /** creates the tables page
            @param  _xConnection
                The connection to get the table names
        */
        void createTablesPage(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _xConnection);

        /** creates the page for the specific type.
            @param  _eType
                The type which should be created. E_TABLE isn't allowed.
            @param  _xContainer
                The container of the elements to be inserted.
        */
        void createPage(ElementType _eType,const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& _xContainer);

        void setTaskExternalMnemonics( MnemonicGenerator& _rMnemonics );

        /** called to give the window the chance to intercept key events, while it has not
            the focus

            @return <TRUE/> if and only if the event has been handled, and should not
                not be further processed
        */
        bool    interceptKeyInput( const KeyEvent& _rEvent );

        inline OAppBorderWindow& getBorderWin() const { return m_rBorderWin; }
        inline OTasksWindow& getTasksWindow() const { return *static_cast< OTasksWindow* >( m_aTasks.getChildWindow() ); }

        sal_Bool isCutAllowed() ;
        sal_Bool isCopyAllowed()    ;
        sal_Bool isPasteAllowed();
        virtual sal_Bool hasChildPathFocus() { return HasChildPathFocus(); }
        void copy();
        void cut();
        void paste();

        /** return the qualified name.
            @param  _pEntry
                The entry of a table, or query, form, report to get the qualified name.
                If the entry is <NULL/>, the first selected is chosen.
            @return
                the qualified name
        */
        ::rtl::OUString getQualifiedName( SvLBoxEntry* _pEntry ) const;

        /** returns if an entry is a leaf
            @param _pEntry
                The entry to check
            @return
                <TRUE/> if the entry is a leaf, otherwise <FALSE/>
        */
        sal_Bool isLeaf(SvLBoxEntry* _pEntry) const;

        /** returns if one of the selected entries is a leaf
            @return
                <TRUE/> if the entry is a leaf, otherwise <FALSE/>
        */
        sal_Bool isALeafSelected() const;

        /** select all entries in the detail page
        */
        void selectAll();

        /// returns <TRUE/> if it sorts ascending
        sal_Bool isSortUp() const;

        /// sort the entries in the detail page down
        void sortDown();

        /// sort the entries in the detail page up
        void sortUp();

        /// returns <TRUE/> when a detail page was filled
        sal_Bool isFilled() const;

        /// return the element of currently select entry
        ElementType getElementType() const;

        /** clears the detail pages.
            @param  _bTaskAlso
                If <TRUE/> the task window will also be cleared.
        */
        void clearPages(sal_Bool _bTaskAlso = sal_True);

        /// returns the count of entries
        sal_Int32 getElementCount();

        /// returns the count of selected entries
        sal_Int32 getSelectionCount();

        /** returns the element names which are selected
            @param  _rNames
                The list will be filled.
        */
        void getSelectionElementNames(::std::vector< ::rtl::OUString>& _rNames ) const;

        /** adds a new object to the detail page.
            @param  _eType
                The type where the entry shold be appended.
            @param  _rName
                The name of the object to be inserted
            @param  _rObject
                The object to add.
            @param  _rxConn
                If we insert a table, the connection must be set.
        */
        SvLBoxEntry* elementAdded(ElementType eType
                        ,const ::rtl::OUString& _rName
                        ,const ::com::sun::star::uno::Any& _rObject );

        /** replaces a objects name with a new one
            @param  _eType
                The type where the entry shold be appended.
            @param  _rOldName
                The old name of the object to be replaced
            @param  _rNewName
                The new name of the object to be replaced
            @param  _rxConn
                If we insert a table, the connection must be set.
            @param  _xObject
                The object which was replaced
        */
        void elementReplaced(ElementType eType
                        ,const ::rtl::OUString& _rOldName
                        ,const ::rtl::OUString& _rNewName );

        /** removes an element from the detail page.
            @param  _eType
                The type where the entry shold be appended.
            @param  _rName
                The name of the element to be removed.
            @param  _rxConn
                If we remove a table, the connection must be set.
        */
        void elementRemoved(ElementType _eType
                            ,const ::rtl::OUString& _rName );

        /// returns the preview mode
        PreviewMode getPreviewMode();

        /// <TRUE/> if the preview is enabled
        sal_Bool isPreviewEnabled();

        /** switches to the given preview mode
            @param  _eMode
                the mode to set for the preview
        */
        void switchPreview(PreviewMode _eMode);

        /** shows the Preview of the content when it is enabled.
            @param  _xContent
                The content which must support the "preview" command.
        */
        void showPreview(const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContent >& _xContent);

        /** shows the Preview of a table or query
            @param  _sDataSourceName
                the name of the data source
            @param  _sName
                the name of table or query
            @param  _bTable
                <TRUE/> if it is a table, otherwise <FALSE/>
            @return void
        */
        void showPreview(   const ::rtl::OUString& _sDataSourceName,
                            const ::rtl::OUString& _sName,
                            sal_Bool _bTable);

        SvLBoxEntry* getEntry( const Point& _aPoint ) const;

        /** a command entry was selected
            @param  _sCommand
                The command to be executed.
        */
        void onCreationClick( const ::rtl::OUString& _sCommand);

    private:
        void                impl_createPage(
                                ElementType _eType,
                                const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& _rxConnection,
                                const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& _rxNonTableElements
                            );

        const TaskPaneData& impl_getTaskPaneData( ElementType _eType );
        void                impl_fillTaskPaneData( ElementType _eType, TaskPaneData& _rData ) const;
    };
}
#endif // DBAUI_APPDETAILVIEW_HXX

<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include <StaticJsonBuffer.h>
#include <JsonValue.h>

class JsonArray_Parser_Tests : public testing::Test
{
protected:
    StaticJsonBuffer<42> json;
};

TEST_F(JsonArray_Parser_Tests, EmptyArray)
{
    JsonArray array = json.parseArray("[]");

    EXPECT_TRUE(array.success());
    EXPECT_EQ(0, array.size());
}

TEST_F(JsonArray_Parser_Tests, ArrayWithNoEnd)
{
    JsonArray array = json.parseArray("[");

    EXPECT_FALSE(array.success());
    EXPECT_EQ(0, array.size());
}

TEST_F(JsonArray_Parser_Tests, EmptyArrayWithLeadingSpaces)
{
    JsonArray array = json.parseArray("  []");

    EXPECT_TRUE(array.success());
    EXPECT_EQ(0, array.size());
}

TEST_F(JsonArray_Parser_Tests, Garbage)
{
    JsonArray array = json.parseArray("%*$£¤");

    EXPECT_FALSE(array.success());
    EXPECT_EQ(0, array.size());
}

TEST_F(JsonArray_Parser_Tests, OneInteger)
{
    JsonArray array = json.parseArray("[42]");

    EXPECT_TRUE(array.success());
    EXPECT_EQ(1, array.size());
    EXPECT_EQ(42, static_cast<int>(array[0]));
}

TEST_F(JsonArray_Parser_Tests, TwoIntegers)
{
    JsonArray array = json.parseArray("[42,84]");

    EXPECT_TRUE(array.success());

    EXPECT_EQ(2, array.size());
    EXPECT_EQ(42, static_cast<int>(array[0]));
    EXPECT_EQ(84, static_cast<int>(array[1]));
}<commit_msg>Added test for spaces in arrays<commit_after>#include <gtest/gtest.h>
#include <StaticJsonBuffer.h>
#include <JsonValue.h>

class JsonArray_Parser_Tests : public testing::Test
{
protected:
    StaticJsonBuffer<42> json;
};

TEST_F(JsonArray_Parser_Tests, EmptyArray)
{
    JsonArray array = json.parseArray("[]");

    EXPECT_TRUE(array.success());
    EXPECT_EQ(0, array.size());
}

TEST_F(JsonArray_Parser_Tests, ArrayWithNoEnd)
{
    JsonArray array = json.parseArray("[");

    EXPECT_FALSE(array.success());
    EXPECT_EQ(0, array.size());
}

TEST_F(JsonArray_Parser_Tests, EmptyArrayWithLeadingSpaces)
{
    JsonArray array = json.parseArray("  []");

    EXPECT_TRUE(array.success());
    EXPECT_EQ(0, array.size());
}

TEST_F(JsonArray_Parser_Tests, Garbage)
{
    JsonArray array = json.parseArray("%*$£¤");

    EXPECT_FALSE(array.success());
    EXPECT_EQ(0, array.size());
}

TEST_F(JsonArray_Parser_Tests, OneInteger)
{
    JsonArray array = json.parseArray("[42]");

    EXPECT_TRUE(array.success());
    EXPECT_EQ(1, array.size());
    EXPECT_EQ(42, static_cast<int>(array[0]));
}

TEST_F(JsonArray_Parser_Tests, OneIntegerWithSpacesBefore)
{
    JsonArray array = json.parseArray("[ \t\r\n42]");

    EXPECT_TRUE(array.success());
    EXPECT_EQ(1, array.size());
    EXPECT_EQ(42, static_cast<int>(array[0]));
}

TEST_F(JsonArray_Parser_Tests, OneIntegerWithSpaceAfter)
{
    JsonArray array = json.parseArray("[42 \t\r\n]");

    EXPECT_TRUE(array.success());
    EXPECT_EQ(1, array.size());
    EXPECT_EQ(42, static_cast<int>(array[0]));
}

TEST_F(JsonArray_Parser_Tests, TwoIntegers)
{
    JsonArray array = json.parseArray("[42,84]");

    EXPECT_TRUE(array.success());

    EXPECT_EQ(2, array.size());
    EXPECT_EQ(42, static_cast<int>(array[0]));
    EXPECT_EQ(84, static_cast<int>(array[1]));
}<|endoftext|>


<commit_before>#ifndef ITER_DROPWHILE_H_
#define ITER_DROPWHILE_H_

#include "iterbase.hpp"

#include <utility>
#include <iterator>
#include <initializer_list>

namespace iter {

  template <typename FilterFunc, typename Container>
  class DropWhile;

  template <typename FilterFunc, typename Container>
  DropWhile<FilterFunc, Container> dropwhile(FilterFunc, Container&&);

  template <typename FilterFunc, typename T>
  DropWhile<FilterFunc, std::initializer_list<T>> dropwhile(
      FilterFunc, std::initializer_list<T>);

  template <typename FilterFunc, typename Container>
  class DropWhile {
   private:
    Container container;
    FilterFunc filter_func;

    friend DropWhile dropwhile<FilterFunc, Container>(FilterFunc, Container&&);

    template <typename FF, typename T>
    friend DropWhile<FF, std::initializer_list<T>> dropwhile(
        FF, std::initializer_list<T>);

    DropWhile(FilterFunc in_filter_func, Container&& in_container)
        : container(std::forward<Container>(in_container)),
          filter_func(in_filter_func) {}

   public:
    class Iterator : public std::iterator<std::input_iterator_tag,
                         iterator_traits_deref<Container>> {
     private:
      using Holder = DerefHolder<iterator_deref<Container>>;
      iterator_type<Container> sub_iter;
      iterator_type<Container> sub_end;
      Holder item;
      FilterFunc* filter_func;

      void inc_sub_iter() {
        ++this->sub_iter;
        if (this->sub_iter != this->sub_end) {
          this->item.reset(*this->sub_iter);
        }
      }

      // skip all values for which the predicate is true
      void skip_passes() {
        while (this->sub_iter != this->sub_end
               && (*this->filter_func)(this->item.get())) {
          this->inc_sub_iter();
        }
      }

     public:
      Iterator(iterator_type<Container>&& iter, iterator_type<Container>&& end,
          FilterFunc& in_filter_func)
          : sub_iter{std::move(iter)},
            sub_end{std::move(end)},
            filter_func(&in_filter_func) {
        if (this->sub_iter != this->sub_end) {
          this->item.reset(*this->sub_iter);
        }
        this->skip_passes();
      }

      typename Holder::reference operator*() {
        return this->item.get();
      }

      typename Holder::pointer operator->() {
        return this->item.get_ptr();
      }

      Iterator& operator++() {
        this->inc_sub_iter();
        return *this;
      }

      Iterator operator++(int) {
        auto ret = *this;
        ++*this;
        return ret;
      }

      bool operator!=(const Iterator& other) const {
        return this->sub_iter != other.sub_iter;
      }

      bool operator==(const Iterator& other) const {
        return !(*this != other);
      }
    };

    Iterator begin() {
      return {std::begin(this->container), std::end(this->container),
          this->filter_func};
    }

    Iterator end() {
      return {std::end(this->container), std::end(this->container),
          this->filter_func};
    }
  };

  template <typename FilterFunc, typename Container>
  DropWhile<FilterFunc, Container> dropwhile(
      FilterFunc filter_func, Container&& container) {
    return {filter_func, std::forward<Container>(container)};
  }

  template <typename FilterFunc, typename T>
  DropWhile<FilterFunc, std::initializer_list<T>> dropwhile(
      FilterFunc filter_func, std::initializer_list<T> il) {
    return {filter_func, std::move(il)};
  }
}

#endif
<commit_msg>moves Dropper into impl{ }<commit_after>#ifndef ITER_DROPWHILE_H_
#define ITER_DROPWHILE_H_

#include "iterbase.hpp"

#include <utility>
#include <iterator>
#include <initializer_list>

namespace iter {
  namespace impl {
    template <typename FilterFunc, typename Container>
    class Dropper;
  }

  template <typename FilterFunc, typename Container>
  impl::Dropper<FilterFunc, Container> dropwhile(FilterFunc, Container&&);

  template <typename FilterFunc, typename T>
  impl::Dropper<FilterFunc, std::initializer_list<T>> dropwhile(
      FilterFunc, std::initializer_list<T>);
}

template <typename FilterFunc, typename Container>
class iter::impl::Dropper {
 private:
  Container container;
  FilterFunc filter_func;

  friend Dropper iter::dropwhile<FilterFunc, Container>(
      FilterFunc, Container&&);

  template <typename FF, typename T>
  friend Dropper<FF, std::initializer_list<T>> iter::dropwhile(
      FF, std::initializer_list<T>);

  Dropper(FilterFunc in_filter_func, Container&& in_container)
      : container(std::forward<Container>(in_container)),
        filter_func(in_filter_func) {}

 public:
  class Iterator : public std::iterator<std::input_iterator_tag,
                       iterator_traits_deref<Container>> {
   private:
    using Holder = DerefHolder<iterator_deref<Container>>;
    iterator_type<Container> sub_iter;
    iterator_type<Container> sub_end;
    Holder item;
    FilterFunc* filter_func;

    void inc_sub_iter() {
      ++this->sub_iter;
      if (this->sub_iter != this->sub_end) {
        this->item.reset(*this->sub_iter);
      }
    }

    // skip all values for which the predicate is true
    void skip_passes() {
      while (this->sub_iter != this->sub_end
             && (*this->filter_func)(this->item.get())) {
        this->inc_sub_iter();
      }
    }

   public:
    Iterator(iterator_type<Container>&& iter, iterator_type<Container>&& end,
        FilterFunc& in_filter_func)
        : sub_iter{std::move(iter)},
          sub_end{std::move(end)},
          filter_func(&in_filter_func) {
      if (this->sub_iter != this->sub_end) {
        this->item.reset(*this->sub_iter);
      }
      this->skip_passes();
    }

    typename Holder::reference operator*() {
      return this->item.get();
    }

    typename Holder::pointer operator->() {
      return this->item.get_ptr();
    }

    Iterator& operator++() {
      this->inc_sub_iter();
      return *this;
    }

    Iterator operator++(int) {
      auto ret = *this;
      ++*this;
      return ret;
    }

    bool operator!=(const Iterator& other) const {
      return this->sub_iter != other.sub_iter;
    }

    bool operator==(const Iterator& other) const {
      return !(*this != other);
    }
  };

  Iterator begin() {
    return {std::begin(this->container), std::end(this->container),
        this->filter_func};
  }

  Iterator end() {
    return {std::end(this->container), std::end(this->container),
        this->filter_func};
  }
};

template <typename FilterFunc, typename Container>
iter::impl::Dropper<FilterFunc, Container> iter::dropwhile(
    FilterFunc filter_func, Container&& container) {
  return {filter_func, std::forward<Container>(container)};
}

template <typename FilterFunc, typename T>
iter::impl::Dropper<FilterFunc, std::initializer_list<T>> iter::dropwhile(
    FilterFunc filter_func, std::initializer_list<T> il) {
  return {filter_func, std::move(il)};
}

#endif
<|endoftext|>


<commit_before>/***********************************************************************************************************************
 * Copyright (C) 2016 Andrew Zonenberg and contributors                                                                *
 *                                                                                *
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General   *
 * Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) *
 * any later version.                                                                                *
 *                                                                                *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied  *
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for     *
 * more details.                                                                                *
 *                                                                                *
 * You should have received a copy of the GNU Lesser General Public License along with this program; if not, you may   *
 * find one here:                                                                                *
 * https://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt                                                              *
 * or you may search the http://www.gnu.org website for the version 2.1 license, or you may write to the Free Software *
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA                                      *
 **********************************************************************************************************************/

#include <log.h>
#include <Greenpak4.h>

using namespace std;

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Construction / destruction

Greenpak4Comparator::Greenpak4Comparator(
		Greenpak4Device* device,
		unsigned int cmpnum,
		unsigned int matrix,
		unsigned int ibase,
		unsigned int oword,
		unsigned int cbase_isrc,
		unsigned int cbase_bw,
		unsigned int cbase_gain,
		unsigned int cbase_vin,
		unsigned int cbase_hyst,
		unsigned int cbase_vref
		)
		: Greenpak4BitstreamEntity(device, matrix, ibase, oword, -1)
		, m_pwren(device->GetGround())
		, m_vin(device->GetGround())
		, m_vref(device->GetGround())
		, m_cmpNum(cmpnum)
		, m_cbaseIsrc(cbase_isrc)
		, m_cbaseBw(cbase_bw)
		, m_cbaseGain(cbase_gain)
		, m_cbaseVin(cbase_vin)
		, m_cbaseHyst(cbase_hyst)
		, m_cbaseVref(cbase_vref)
		, m_bandwidthHigh(true)
		, m_vinAtten(1)
		, m_isrcEn(false)
		, m_hysteresis(0)
{
}

Greenpak4Comparator::~Greenpak4Comparator()
{

}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Accessors

string Greenpak4Comparator::GetDescription()
{
	char buf[128];
	snprintf(buf, sizeof(buf), "ACMP_%u", m_cmpNum);
	return string(buf);
}

vector<string> Greenpak4Comparator::GetInputPorts() const
{
	vector<string> r;
	r.push_back("PWREN");
	return r;
}

void Greenpak4Comparator::SetInput(string port, Greenpak4EntityOutput src)
{
	if(port == "PWREN")
		m_pwren = src;
	if(port == "VIN")
		m_vin = src;
	if(port == "VREF")
		m_vref = src;

	//ignore anything else silently (should not be possible since synthesis would error out)
}

vector<string> Greenpak4Comparator::GetOutputPorts() const
{
	vector<string> r;
	r.push_back("OUT");
	return r;
}

unsigned int Greenpak4Comparator::GetOutputNetNumber(string port)
{
	if(port == "OUT")
		return m_outputBaseWord;
	else
		return -1;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Serialization

bool Greenpak4Comparator::CommitChanges()
{
	//Get our cell, or bail if we're unassigned
	auto ncell = dynamic_cast<Greenpak4NetlistCell*>(GetNetlistEntity());
	if(ncell == NULL)
		return true;

	if(ncell->HasParameter("BANDWIDTH"))
		m_bandwidthHigh = (ncell->m_parameters["BANDWIDTH"] == "HIGH") ? true : false;

	if(ncell->HasParameter("VIN_ATTEN"))
		m_vinAtten = (atoi(ncell->m_parameters["VIN_ATTEN"].c_str()));

	if(ncell->HasParameter("VIN_ISRC_EN"))
		m_isrcEn = (ncell->m_parameters["VIN_ISRC_EN"] == "1") ? true : false;

	if(ncell->HasParameter("HYSTERESIS"))
		m_hysteresis = (atoi(ncell->m_parameters["HYSTERESIS"].c_str()));

	return true;
}

bool Greenpak4Comparator::Load(bool* /*bitstream*/)
{
	//TODO: Do our inputs
	LogError("Unimplemented\n");
	return false;
}

bool Greenpak4Comparator::Save(bool* bitstream)
{
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// INPUT BUS

	if(!WriteMatrixSelector(bitstream, m_inputBaseWord, m_pwren))
		return false;

	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// CONFIGURATION

	//Input current source (iff present)
	if(m_cbaseIsrc > 0)
		bitstream[m_cbaseIsrc] = m_isrcEn;

	//Low bandwidth selector
	if(m_cbaseBw > 0)
		bitstream[m_cbaseBw] = !m_bandwidthHigh;

	//Gain selector
	if(m_cbaseGain > 0)
	{
		switch(m_vinAtten)
		{
			case 1:
				bitstream[m_cbaseGain + 1] = false;
				bitstream[m_cbaseGain + 0] = false;
				break;

			case 2:
				bitstream[m_cbaseGain + 1] = false;
				bitstream[m_cbaseGain + 0] = true;
				break;

			case 3:
				bitstream[m_cbaseGain + 1] = true;
				bitstream[m_cbaseGain + 0] = false;
				break;

			case 4:
				bitstream[m_cbaseGain + 1] = true;
				bitstream[m_cbaseGain + 0] = true;
				break;

			default:
				LogError("Invalid ACMP attenuation (must be 1/2/3/4)\n");
				return false;
		}
	}
	else
	{
		if(m_vinAtten != 1)
		{
			LogError("Invalid ACMP attenuation (must be 1 for %s)\n",
			         GetDescription().c_str());
		}
	}

	//Hysteresis
	if(m_cbaseHyst > 0)
	{
		switch(m_hysteresis)
		{
			case 0:
				bitstream[m_cbaseHyst + 1] = false;
				bitstream[m_cbaseHyst + 0] = false;
				break;

			case 25:
				bitstream[m_cbaseHyst + 1] = false;
				bitstream[m_cbaseHyst + 0] = true;
				break;

			case 50:
				bitstream[m_cbaseHyst + 1] = true;
				bitstream[m_cbaseHyst + 0] = false;
				break;

			case 200:
				bitstream[m_cbaseHyst + 1] = true;
				bitstream[m_cbaseHyst + 0] = true;
				break;

			default:
				LogError("Invalid ACMP hysteresis (must be 0/25/50/200)\n");
				return false;
		}
	}
	else
	{
		if(m_hysteresis != 0)
		{
			LogError("Invalid ACMP hysteresis (must be 0 for %s)\n",
			         GetDescription().c_str());
		}
	}

	//If input is ground, then don't hook it up (we're not active)
	if(m_vin.IsPowerRail() && !m_vin.GetPowerRailValue())
	{}

	//Invalid input
	else if(m_muxsels.find(m_vin) == m_muxsels.end())
	{
		LogError("Invalid ACMP input (tried to feed %s to %s)\n",
			m_vin.GetDescription().c_str(), GetDescription().c_str());
		return false;
	}

	//Valid input, hook it up
	else
	{
		unsigned int sel = m_muxsels[m_vin];

		//Bitstream is zero-cleared at start of the writing process so high zero bits don't need to be written

		//2-bit mux selector? Write the high bit
		if(sel & 2)
			bitstream[m_cbaseVin + 1] = true;

		//Write the low bit
		bitstream[m_cbaseVin] = (sel & 1) ? true : false;
	}

	//Configure the voltage reference cell
	unsigned int muxsel = 0;
	if(m_vref.IsVoltageReference())
	{
		Greenpak4VoltageReference* vref = dynamic_cast<Greenpak4VoltageReference*>(m_vref.GetRealEntity());
		muxsel = vref->GetACMPMuxSel();

		if(muxsel > 0x1F)
		{
			LogError("Invalid mux selector %u (should be 0...31)\n", muxsel);
			return false;
		}
	}

	//Unused vrefs can be tied to ground
	else if(m_vref.IsPowerRail() && !m_vref.GetPowerRailValue())
	{
		//emulate ground by setting 50 mV, the lowest threshold
		muxsel = 0;
	}

	//Vref must be sourced by a GP_VREF cell, complain if it's not
	else
	{
		LogError(
			"Invalid ACMP reference voltage source for %s\n"
			"	(got %s, must be buffered by a GP_VREF)\n",
			GetDescription().c_str(),
			m_vref.GetOutputName().c_str()
			);
	}

	bitstream[m_cbaseVref + 0] = (muxsel & 1) ? true : false;
	bitstream[m_cbaseVref + 1] = (muxsel & 2) ? true : false;
	bitstream[m_cbaseVref + 2] = (muxsel & 4) ? true : false;
	bitstream[m_cbaseVref + 3] = (muxsel & 8) ? true : false;
	bitstream[m_cbaseVref + 4] = (muxsel & 16) ? true : false;

	return true;
}
<commit_msg>Greenpak4Comparator: Don't clobber random bitstream addresses when configuring ACMP_5 (which has no input mux)<commit_after>/***********************************************************************************************************************
 * Copyright (C) 2016 Andrew Zonenberg and contributors                                                                *
 *                                                                                *
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General   *
 * Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) *
 * any later version.                                                                                *
 *                                                                                *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied  *
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for     *
 * more details.                                                                                *
 *                                                                                *
 * You should have received a copy of the GNU Lesser General Public License along with this program; if not, you may   *
 * find one here:                                                                                *
 * https://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt                                                              *
 * or you may search the http://www.gnu.org website for the version 2.1 license, or you may write to the Free Software *
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA                                      *
 **********************************************************************************************************************/

#include <log.h>
#include <Greenpak4.h>

using namespace std;

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Construction / destruction

Greenpak4Comparator::Greenpak4Comparator(
		Greenpak4Device* device,
		unsigned int cmpnum,
		unsigned int matrix,
		unsigned int ibase,
		unsigned int oword,
		unsigned int cbase_isrc,
		unsigned int cbase_bw,
		unsigned int cbase_gain,
		unsigned int cbase_vin,
		unsigned int cbase_hyst,
		unsigned int cbase_vref
		)
		: Greenpak4BitstreamEntity(device, matrix, ibase, oword, -1)
		, m_pwren(device->GetGround())
		, m_vin(device->GetGround())
		, m_vref(device->GetGround())
		, m_cmpNum(cmpnum)
		, m_cbaseIsrc(cbase_isrc)
		, m_cbaseBw(cbase_bw)
		, m_cbaseGain(cbase_gain)
		, m_cbaseVin(cbase_vin)
		, m_cbaseHyst(cbase_hyst)
		, m_cbaseVref(cbase_vref)
		, m_bandwidthHigh(true)
		, m_vinAtten(1)
		, m_isrcEn(false)
		, m_hysteresis(0)
{
}

Greenpak4Comparator::~Greenpak4Comparator()
{

}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Accessors

string Greenpak4Comparator::GetDescription()
{
	char buf[128];
	snprintf(buf, sizeof(buf), "ACMP_%u", m_cmpNum);
	return string(buf);
}

vector<string> Greenpak4Comparator::GetInputPorts() const
{
	vector<string> r;
	r.push_back("PWREN");
	return r;
}

void Greenpak4Comparator::SetInput(string port, Greenpak4EntityOutput src)
{
	if(port == "PWREN")
		m_pwren = src;
	if(port == "VIN")
		m_vin = src;
	if(port == "VREF")
		m_vref = src;

	//ignore anything else silently (should not be possible since synthesis would error out)
}

vector<string> Greenpak4Comparator::GetOutputPorts() const
{
	vector<string> r;
	r.push_back("OUT");
	return r;
}

unsigned int Greenpak4Comparator::GetOutputNetNumber(string port)
{
	if(port == "OUT")
		return m_outputBaseWord;
	else
		return -1;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Serialization

bool Greenpak4Comparator::CommitChanges()
{
	//Get our cell, or bail if we're unassigned
	auto ncell = dynamic_cast<Greenpak4NetlistCell*>(GetNetlistEntity());
	if(ncell == NULL)
		return true;

	if(ncell->HasParameter("BANDWIDTH"))
		m_bandwidthHigh = (ncell->m_parameters["BANDWIDTH"] == "HIGH") ? true : false;

	if(ncell->HasParameter("VIN_ATTEN"))
		m_vinAtten = (atoi(ncell->m_parameters["VIN_ATTEN"].c_str()));

	if(ncell->HasParameter("VIN_ISRC_EN"))
		m_isrcEn = (ncell->m_parameters["VIN_ISRC_EN"] == "1") ? true : false;

	if(ncell->HasParameter("HYSTERESIS"))
		m_hysteresis = (atoi(ncell->m_parameters["HYSTERESIS"].c_str()));

	return true;
}

bool Greenpak4Comparator::Load(bool* /*bitstream*/)
{
	//TODO: Do our inputs
	LogError("Unimplemented\n");
	return false;
}

bool Greenpak4Comparator::Save(bool* bitstream)
{
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// INPUT BUS

	if(!WriteMatrixSelector(bitstream, m_inputBaseWord, m_pwren))
		return false;

	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// CONFIGURATION

	//Input current source (iff present)
	if(m_cbaseIsrc > 0)
		bitstream[m_cbaseIsrc] = m_isrcEn;

	//Low bandwidth selector
	if(m_cbaseBw > 0)
		bitstream[m_cbaseBw] = !m_bandwidthHigh;

	//Gain selector
	if(m_cbaseGain > 0)
	{
		switch(m_vinAtten)
		{
			case 1:
				bitstream[m_cbaseGain + 1] = false;
				bitstream[m_cbaseGain + 0] = false;
				break;

			case 2:
				bitstream[m_cbaseGain + 1] = false;
				bitstream[m_cbaseGain + 0] = true;
				break;

			case 3:
				bitstream[m_cbaseGain + 1] = true;
				bitstream[m_cbaseGain + 0] = false;
				break;

			case 4:
				bitstream[m_cbaseGain + 1] = true;
				bitstream[m_cbaseGain + 0] = true;
				break;

			default:
				LogError("Invalid ACMP attenuation (must be 1/2/3/4)\n");
				return false;
		}
	}
	else
	{
		if(m_vinAtten != 1)
		{
			LogError("Invalid ACMP attenuation (must be 1 for %s)\n",
			         GetDescription().c_str());
		}
	}

	//Hysteresis
	if(m_cbaseHyst > 0)
	{
		switch(m_hysteresis)
		{
			case 0:
				bitstream[m_cbaseHyst + 1] = false;
				bitstream[m_cbaseHyst + 0] = false;
				break;

			case 25:
				bitstream[m_cbaseHyst + 1] = false;
				bitstream[m_cbaseHyst + 0] = true;
				break;

			case 50:
				bitstream[m_cbaseHyst + 1] = true;
				bitstream[m_cbaseHyst + 0] = false;
				break;

			case 200:
				bitstream[m_cbaseHyst + 1] = true;
				bitstream[m_cbaseHyst + 0] = true;
				break;

			default:
				LogError("Invalid ACMP hysteresis (must be 0/25/50/200)\n");
				return false;
		}
	}
	else
	{
		if(m_hysteresis != 0)
		{
			LogError("Invalid ACMP hysteresis (must be 0 for %s)\n",
			         GetDescription().c_str());
		}
	}

	//If input is ground, then don't hook it up (we're not active)
	if(m_vin.IsPowerRail() && !m_vin.GetPowerRailValue())
	{}

	//Invalid input
	else if(m_muxsels.find(m_vin) == m_muxsels.end())
	{
		LogError("Invalid ACMP input (tried to feed %s to %s)\n",
			m_vin.GetDescription().c_str(), GetDescription().c_str());
		return false;
	}

	//Valid input, hook it up.
	//BUGFIX: If we only have one input there's no vin config bits so don't write to m_cbaseVin
	else if(m_muxsels.size() > 1)
	{
		unsigned int sel = m_muxsels[m_vin];

		//Bitstream is zero-cleared at start of the writing process so high zero bits don't need to be written

		//2-bit mux selector? Write the high bit
		if(sel & 2)
			bitstream[m_cbaseVin + 1] = true;

		//Write the low bit
		bitstream[m_cbaseVin] = (sel & 1) ? true : false;
	}

	//Configure the voltage reference cell
	unsigned int muxsel = 0;
	if(m_vref.IsVoltageReference())
	{
		Greenpak4VoltageReference* vref = dynamic_cast<Greenpak4VoltageReference*>(m_vref.GetRealEntity());
		muxsel = vref->GetACMPMuxSel();

		if(muxsel > 0x1F)
		{
			LogError("Invalid mux selector %u (should be 0...31)\n", muxsel);
			return false;
		}
	}

	//Unused vrefs can be tied to ground
	else if(m_vref.IsPowerRail() && !m_vref.GetPowerRailValue())
	{
		//emulate ground by setting 50 mV, the lowest threshold
		muxsel = 0;
	}

	//Vref must be sourced by a GP_VREF cell, complain if it's not
	else
	{
		LogError(
			"Invalid ACMP reference voltage source for %s\n"
			"	(got %s, must be buffered by a GP_VREF)\n",
			GetDescription().c_str(),
			m_vref.GetOutputName().c_str()
			);
	}

	bitstream[m_cbaseVref + 0] = (muxsel & 1) ? true : false;
	bitstream[m_cbaseVref + 1] = (muxsel & 2) ? true : false;
	bitstream[m_cbaseVref + 2] = (muxsel & 4) ? true : false;
	bitstream[m_cbaseVref + 3] = (muxsel & 8) ? true : false;
	bitstream[m_cbaseVref + 4] = (muxsel & 16) ? true : false;

	return true;
}
<|endoftext|>


<commit_before>/*
* CallADIOSData.cpp
*
* Copyright (C) 2018 by Universitaet Stuttgart (VISUS).
* Alle Rechte vorbehalten.
*/

#include "stdafx.h"
#include "adios_plugin/CallADIOSData.h"
#include "mmcore/utility/log/Log.h"
#include <algorithm>

namespace megamol {
namespace adios {

CallADIOSData::CallADIOSData()
    : dataHash(0)
    , time(0)
    , frameCount(0)
    , dataptr(nullptr) {
}

/**
 * \brief
 */
CallADIOSData::~CallADIOSData(void) = default;

/**
 * \brief CallADIOSData::setTime
 * \param time
 */
void CallADIOSData::setTime(float time) { this->time = time; }

/**
 * \brief
 * \return
 */
float CallADIOSData::getTime() const { return this->time; }

/**
 * \brief Sets variable to inquire.
 * \param varname: The name of the variable.
 * \return Returns false if variable is not available, true otherwise.
 */
bool CallADIOSData::inquire(const std::string &varname) {
    if (!this->availableVars.empty()) {
        if (std::find(this->availableVars.begin(), this->availableVars.end(), varname) != this->availableVars.end()) {
            this->inqVars.push_back(varname);
        } else {
            megamol::core::utility::log::Log::DefaultLog.WriteError("[CallADIOSData] Variable %s is not in available varialbes", varname.c_str());
            return false;
        }
    } else {
        megamol::core::utility::log::Log::DefaultLog.WriteError("[CallADIOSData] No available Vars. Read header first.");
        return false;
    }
    // erase non-unique occurrences
    std::sort(this->inqVars.begin(), this->inqVars.end());
    const auto last = std::unique(this->inqVars.begin(), this->inqVars.end());
    this->inqVars.erase(last, this->inqVars.end());
    return true;
}

std::vector<std::string> CallADIOSData::getVarsToInquire() const { return inqVars; }

std::vector<std::string> CallADIOSData::getAvailableVars() const { return availableVars; }

void CallADIOSData::setAvailableVars(const std::vector<std::string> &avars) { this->availableVars = avars; }

void CallADIOSData::setData(std::shared_ptr<adiosDataMap> _dta) {
    this->dataptr = _dta; }

std::shared_ptr<abstractContainer> CallADIOSData::getData(std::string _str) const { return this->dataptr->at(_str); }

bool CallADIOSData::isInVars(std::string var) {
    return std::find(this->availableVars.begin(), this->availableVars.end(), var) != this->availableVars.end();
}

} // end namespace adios
} // end namespace megamol<commit_msg>setting the data map now also sets the available vars<commit_after>/*
* CallADIOSData.cpp
*
* Copyright (C) 2018 by Universitaet Stuttgart (VISUS).
* Alle Rechte vorbehalten.
*/

#include "stdafx.h"
#include "adios_plugin/CallADIOSData.h"
#include "mmcore/utility/log/Log.h"
#include <algorithm>

namespace megamol {
namespace adios {

CallADIOSData::CallADIOSData()
    : dataHash(0)
    , time(0)
    , frameCount(0)
    , dataptr(nullptr) {
}

/**
 * \brief
 */
CallADIOSData::~CallADIOSData(void) = default;

/**
 * \brief CallADIOSData::setTime
 * \param time
 */
void CallADIOSData::setTime(float time) { this->time = time; }

/**
 * \brief
 * \return
 */
float CallADIOSData::getTime() const { return this->time; }

/**
 * \brief Sets variable to inquire.
 * \param varname: The name of the variable.
 * \return Returns false if variable is not available, true otherwise.
 */
bool CallADIOSData::inquire(const std::string &varname) {
    if (!this->availableVars.empty()) {
        if (std::find(this->availableVars.begin(), this->availableVars.end(), varname) != this->availableVars.end()) {
            this->inqVars.push_back(varname);
        } else {
            megamol::core::utility::log::Log::DefaultLog.WriteError("[CallADIOSData] Variable %s is not in available varialbes", varname.c_str());
            return false;
        }
    } else {
        megamol::core::utility::log::Log::DefaultLog.WriteError("[CallADIOSData] No available Vars. Read header first.");
        return false;
    }
    // erase non-unique occurrences
    std::sort(this->inqVars.begin(), this->inqVars.end());
    const auto last = std::unique(this->inqVars.begin(), this->inqVars.end());
    this->inqVars.erase(last, this->inqVars.end());
    return true;
}

std::vector<std::string> CallADIOSData::getVarsToInquire() const { return inqVars; }

std::vector<std::string> CallADIOSData::getAvailableVars() const { return availableVars; }

void CallADIOSData::setAvailableVars(const std::vector<std::string> &avars) { this->availableVars = avars; }

void CallADIOSData::setData(std::shared_ptr<adiosDataMap> _dta) {
    this->dataptr = _dta;
    availableVars.clear();
    availableVars.reserve(dataptr->size());
    for (auto& entry : *dataptr) {
        availableVars.emplace_back(entry.first);
    }
}

std::shared_ptr<abstractContainer> CallADIOSData::getData(std::string _str) const { return this->dataptr->at(_str); }

bool CallADIOSData::isInVars(std::string var) {
    return std::find(this->availableVars.begin(), this->availableVars.end(), var) != this->availableVars.end();
}

} // end namespace adios
} // end namespace megamol
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: JoinTableView.hxx,v $
 *
 *  $Revision: 1.25 $
 *
 *  last change: $Author: hr $ $Date: 2007-11-01 15:16:03 $
 *
 *  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_JOINTABLEVIEW_HXX
#define DBAUI_JOINTABLEVIEW_HXX

#ifndef _SV_WINDOW_HXX
#include <vcl/window.hxx>
#endif
#ifndef _SV_TIMER_HXX
#include <vcl/timer.hxx>
#endif
#ifndef _SV_SCRBAR_HXX
#include <vcl/scrbar.hxx>
#endif
#ifndef _RTTI_HXX
#include <tools/rtti.hxx>
#endif
#ifndef _TRANSFER_HXX
#include <svtools/transfer.hxx>
#endif

#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#ifndef _DBACCESS_UI_CALLBACKS_HXX_
#include "callbacks.hxx"
#endif
#include "TableConnectionData.hxx"
#include "TableWindowData.hxx"
#include <memory>
#include <vector>

struct AcceptDropEvent;
struct ExecuteDropEvent;
class SfxUndoAction;
namespace dbaui
{
    class OTableConnection;
    class OTableWindow;
    struct OJoinExchangeData;
    class OJoinDesignView;
    class OTableWindowData;
    class OJoinDesignViewAccess;

    // this class conatins only the scrollbars to avoid that the tablewindows clip the scrollbars
    class OJoinTableView;
    class OScrollWindowHelper : public Window
    {
        ScrollBar           m_aHScrollBar;
        ScrollBar           m_aVScrollBar;
        Window*             m_pCornerWindow;
        OJoinTableView*     m_pTableView;

    protected:
        virtual void Resize();
    public:
        OScrollWindowHelper( Window* pParent);
        ~OScrollWindowHelper();

        void setTableView(OJoinTableView* _pTableView);

        void resetRange(const Point& _aSize);

        // own methods
        ScrollBar* GetHScrollBar() { return &m_aHScrollBar; }
        ScrollBar* GetVScrollBar() { return &m_aVScrollBar; }
    };

    class OJoinTableView :  public Window
                            ,public IDragTransferableListener
                            ,public DropTargetHelper
    {
        friend class OJoinMoveTabWinUndoAct;
    public:
        DECLARE_STL_USTRINGACCESS_MAP(OTableWindow*,OTableWindowMap);
    private:
        OTableWindowMap     m_aTableMap;
        ::std::vector<OTableConnection*>    m_vTableConnection;

        Timer               m_aDragScrollTimer;
        Rectangle           m_aDragRect;
        Rectangle           m_aSizingRect;
        Point               m_aDragOffset;
        Point               m_aScrollOffset;
        Point               m_ptPrevDraggingPos;
        Size                m_aOutputSize;

        OTableWindow*           m_pDragWin;
        OTableWindow*           m_pSizingWin;
        OTableConnection*       m_pSelectedConn;

        BOOL                    m_bTrackingInitiallyMoved;

        DECL_LINK(OnDragScrollTimer, void*);

    protected:
        OTableWindow*               m_pLastFocusTabWin;
        OJoinDesignView*            m_pView;
        OJoinDesignViewAccess*      m_pAccessible;

    public:
        OJoinTableView( Window* pParent, OJoinDesignView* pView );
        virtual ~OJoinTableView();

        // window override
        virtual void StateChanged( StateChangedType nStateChange );
        virtual void GetFocus();
        virtual void LoseFocus();
        virtual void KeyInput( const KeyEvent& rEvt );
        // Accessibility
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > CreateAccessible();

        // own methods
        ScrollBar* GetHScrollBar() { return static_cast<OScrollWindowHelper*>(GetParent())->GetHScrollBar(); }
        ScrollBar* GetVScrollBar() { return static_cast<OScrollWindowHelper*>(GetParent())->GetVScrollBar(); }
        DECL_LINK( ScrollHdl, ScrollBar* );

        void DrawConnections( const Rectangle& rRect );
        void InvalidateConnections();

        void BeginChildMove( OTableWindow* pTabWin, const Point& rMousePos );
        void BeginChildSizing( OTableWindow* pTabWin, const Pointer& rPointer );

        void NotifyTitleClicked( OTableWindow* pTabWin, const Point rMousePos );

        virtual void AddTabWin(const ::rtl::OUString& _rComposedName, const ::rtl::OUString& rWinName, BOOL bNewTable = FALSE);
        virtual void RemoveTabWin( OTableWindow* pTabWin );

        // alle TabWins verstecken (NICHT loeschen, sie werden in eine Undo-Action gepackt)
        virtual void    HideTabWins();

        virtual void AddConnection(const OJoinExchangeData& jxdSource, const OJoinExchangeData& jxdDest) = 0;

        /** RemoveConnection allows to remove connections from join table view, it implies that the same as addConnection

            @param  _pConnection
                    the connection which should be removed
            @param  _bDelete
                    when truie then the connection will be deleted

            @return an iterator to next valid connection, so it can be used in any loop
        */
        virtual ::std::vector<OTableConnection*>::const_iterator RemoveConnection(OTableConnection* _pConnection,sal_Bool _bDelete);

        /** allows to add new connections to join table view, it implies an invalidation of the features
            ID_BROWSER_ADDTABLE and SID_RELATION_ADD_RELATION also the modified flag will be set to true
            @param  _pConnection
                    the connection which should be added
            @param  _bAddData
                    <TRUE/> when the data should also be appended
        */
        void addConnection(OTableConnection* _pConnection,sal_Bool _bAddData = sal_True);

        BOOL            ScrollPane( long nDelta, BOOL bHoriz, BOOL bPaintScrollBars );
        ULONG           GetTabWinCount();
        Point           GetScrollOffset() const { return m_aScrollOffset; }

        OJoinDesignView*            getDesignView() const { return m_pView; }
        OTableWindow*               GetTabWindow( const String& rName );

        OTableConnection*           GetSelectedConn() { return m_pSelectedConn; }
        void                        DeselectConn(OTableConnection* pConn);  // NULL ist ausdruecklich zugelassen, dann passiert nichts
        void                        SelectConn(OTableConnection* pConn);

        OTableWindowMap*            GetTabWinMap() { return &m_aTableMap; }
        const OTableWindowMap*      GetTabWinMap() const { return &m_aTableMap; }

        /** gives a read only access to the connection vector
        */
        const ::std::vector<OTableConnection*>* getTableConnections() const { return &m_vTableConnection; }

        BOOL                        ExistsAConn(const OTableWindow* pFromWin) const;

        /** getTableConnections searchs for all connections of a table
            @param  _pFromWin   the table for which connections should be found

            @return an iterator which can be used to travel all connections of the table
        */
        ::std::vector<OTableConnection*>::const_iterator getTableConnections(const OTableWindow* _pFromWin) const;

        /** getConnectionCount returns how many connection belongs to single table
            @param  _pFromWin   the table for which connections should be found

            @return the count of connections wich belongs to this table
        */
        sal_Int32 getConnectionCount(const OTableWindow* _pFromWin) const;

        OTableConnection* GetTabConn(const OTableWindow* pLhs,const OTableWindow* pRhs,bool _bSupressCrossOrNaturalJoin = false,const OTableConnection* _rpFirstAfter = NULL) const;

        // clears the window map and connection vector without destroying it
        // that means teh data of the windows and connection will be untouched
        void clearLayoutInformation();

        // set the focus to that tab win which most recently had it (or to the first available one)
        void GrabTabWinFocus();

        // ReSync ist dazu gedacht, aus dem Dokument alle WinData und ConnData zu holen und entsprechend Wins und Conns anzulegen
        virtual void ReSync() { }
        // ClearAll implementiert ein hartes Loeschen, es werden alle Conns und alle Wins aus ihren jeweiligen Listen geloescht
        // sowie die entsprechenden Datas aus dem Dokument ausgetragen
        virtual void ClearAll();

        // wird vom AddTabDlg benutzt, um festzustellen, ob noch Tabellen hinzugefuegt werden duerfen
        virtual BOOL IsAddAllowed();
        virtual long PreNotify(NotifyEvent& rNEvt);

        // DnD stuff
        virtual void        StartDrag( sal_Int8 nAction, const Point& rPosPixel );
        virtual sal_Int8    AcceptDrop( const AcceptDropEvent& rEvt );
        virtual sal_Int8    ExecuteDrop( const ExecuteDropEvent& rEvt );

        /**
            can be used in derevied classes to make some special ui handling
            after d&d
        */
        virtual void lookForUiActivities();

        // wird nach Verschieben/Groessenaenderung der TabWins aufgerufen (die Standardimplementation reicht die neuen Daten einfach
        // an die Daten des Wins weiter)
        virtual void TabWinMoved(OTableWindow* ptWhich, const Point& ptOldPosition);
            // die Position ist "virtuell" : der Container hat sozusagen eine virtuelle Flaeche, von der immer nur ein bestimmter Bereich
            // - der mittels der Scrollbar veraendert werden kann - zu sehen ist. Insbesondere hat ptOldPosition immer positive Koordinaten,
            // auch wenn er einen Punkt oberhalb des aktuell sichtbaren Bereichs bezeichnet, dessen physische Ordinate eigentlich
            // negativ ist.
        virtual void TabWinSized(OTableWindow* ptWhich, const Point& ptOldPosition, const Size& szOldSize);

        void modified();

        /** returns if teh given window is visible.
            @param  _rPoint
                The Point to check
            @param  _rSize
                The Size to be check as well
            @return
                <TRUE/> if the area is visible otherwise <FALSE/>

        */
        BOOL isMovementAllowed(const Point& _rPoint,const Size& _rSize);

        Size getRealOutputSize() const { return m_aOutputSize; }

        virtual void EnsureVisible(const OTableWindow* _pWin);
        virtual void EnsureVisible(const Point& _rPoint,const Size& _rSize);

        TTableWindowData::value_type createTableWindowData(const ::rtl::OUString& _rComposedName
                                            ,const ::rtl::OUString& _sTableName
                                            ,const ::rtl::OUString& _rWinName);

    protected:
        virtual void MouseButtonUp( const MouseEvent& rEvt );
        virtual void MouseButtonDown( const MouseEvent& rEvt );
        virtual void Tracking( const TrackingEvent& rTEvt );
        virtual void Paint( const Rectangle& rRect );
        virtual void ConnDoubleClicked( OTableConnection* pConnection );
        virtual void SetDefaultTabWinPosSize( OTableWindow* pTabWin );
        virtual void DataChanged( const DataChangedEvent& rDCEvt );

        virtual void Resize();

        virtual void dragFinished( );
        // hier ist die Position (die sich waehrend des Sizings aendern kann) physisch, da waehrend des Sizens nicht gescrollt wird
        virtual void Command(const CommandEvent& rEvt);

        virtual OTableWindowData* CreateImpl(const ::rtl::OUString& _rComposedName
                                            ,const ::rtl::OUString& _sTableName
                                            ,const ::rtl::OUString& _rWinName);

        /** factory method to create table windows
            @param  _pData
                The data corresponding to the window.
            @return
                The new TableWindow
        */
        virtual OTableWindow* createWindow(const TTableWindowData::value_type& _pData) = 0;

        /** determines whether the classes Init method should accept a query name, or only table names
        */
        virtual bool    allowQueries() const;

        /** called when init fails at the tablewindowdata because the m_xTable object could not provide columns, but no
            exception was thrown. Expected to throw.
        */
        virtual void    onNoColumns_throw();

        virtual bool supressCrossNaturalJoin(const TTableConnectionData::value_type& _pData) const;

    private:
        void    InitColors();
        BOOL    ScrollWhileDragging();

        /** executePopup opens the context menu to delate a connection
            @param  _aPos               the position where the popup menu should appear
            @param  _pSelConnection     the connection which should be deleted
        */
        void executePopup(const Point& _aPos,OTableConnection* _pSelConnection);

        /** invalidateAndModify invalidates this window without children and
            set the controller modified
            @param  _pAction a possible undo action to add at the controller
        */
        void invalidateAndModify(SfxUndoAction *_pAction=NULL);

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

#ifndef _SV_WINDOW_HXX
#include <vcl/window.hxx>
#endif
#ifndef _SV_TIMER_HXX
#include <vcl/timer.hxx>
#endif
#ifndef _SV_SCRBAR_HXX
#include <vcl/scrbar.hxx>
#endif
#ifndef _RTTI_HXX
#include <tools/rtti.hxx>
#endif
#ifndef _TRANSFER_HXX
#include <svtools/transfer.hxx>
#endif

#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#ifndef _DBACCESS_UI_CALLBACKS_HXX_
#include "callbacks.hxx"
#endif
#include "TableConnectionData.hxx"
#include "TableWindowData.hxx"
#include <memory>
#include <vector>

struct AcceptDropEvent;
struct ExecuteDropEvent;
class SfxUndoAction;
namespace dbaui
{
    class OTableConnection;
    class OTableWindow;
    struct OJoinExchangeData;
    class OJoinDesignView;
    class OTableWindowData;
    class OJoinDesignViewAccess;

    // this class conatins only the scrollbars to avoid that the tablewindows clip the scrollbars
    class OJoinTableView;
    class OScrollWindowHelper : public Window
    {
        ScrollBar           m_aHScrollBar;
        ScrollBar           m_aVScrollBar;
        Window*             m_pCornerWindow;
        OJoinTableView*     m_pTableView;

    protected:
        virtual void Resize();
    public:
        OScrollWindowHelper( Window* pParent);
        ~OScrollWindowHelper();

        void setTableView(OJoinTableView* _pTableView);

        void resetRange(const Point& _aSize);

        // own methods
        ScrollBar* GetHScrollBar() { return &m_aHScrollBar; }
        ScrollBar* GetVScrollBar() { return &m_aVScrollBar; }
    };

    class OJoinTableView :  public Window
                            ,public IDragTransferableListener
                            ,public DropTargetHelper
    {
        friend class OJoinMoveTabWinUndoAct;
    public:
        DECLARE_STL_USTRINGACCESS_MAP(OTableWindow*,OTableWindowMap);
    private:
        OTableWindowMap     m_aTableMap;
        ::std::vector<OTableConnection*>    m_vTableConnection;

        Timer               m_aDragScrollTimer;
        Rectangle           m_aDragRect;
        Rectangle           m_aSizingRect;
        Point               m_aDragOffset;
        Point               m_aScrollOffset;
        Point               m_ptPrevDraggingPos;
        Size                m_aOutputSize;

        OTableWindow*           m_pDragWin;
        OTableWindow*           m_pSizingWin;
        OTableConnection*       m_pSelectedConn;

        BOOL                    m_bTrackingInitiallyMoved;

        DECL_LINK(OnDragScrollTimer, void*);

    protected:
        OTableWindow*               m_pLastFocusTabWin;
        OJoinDesignView*            m_pView;
        OJoinDesignViewAccess*      m_pAccessible;

    public:
        OJoinTableView( Window* pParent, OJoinDesignView* pView );
        virtual ~OJoinTableView();

        // window override
        virtual void StateChanged( StateChangedType nStateChange );
        virtual void GetFocus();
        virtual void LoseFocus();
        virtual void KeyInput( const KeyEvent& rEvt );
        // Accessibility
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > CreateAccessible();

        // own methods
        ScrollBar* GetHScrollBar() { return static_cast<OScrollWindowHelper*>(GetParent())->GetHScrollBar(); }
        ScrollBar* GetVScrollBar() { return static_cast<OScrollWindowHelper*>(GetParent())->GetVScrollBar(); }
        DECL_LINK( ScrollHdl, ScrollBar* );

        void DrawConnections( const Rectangle& rRect );
        void InvalidateConnections();

        void BeginChildMove( OTableWindow* pTabWin, const Point& rMousePos );
        void BeginChildSizing( OTableWindow* pTabWin, const Pointer& rPointer );

        void NotifyTitleClicked( OTableWindow* pTabWin, const Point rMousePos );

        virtual void AddTabWin(const ::rtl::OUString& _rComposedName, const ::rtl::OUString& rWinName, BOOL bNewTable = FALSE);
        virtual void RemoveTabWin( OTableWindow* pTabWin );

        // alle TabWins verstecken (NICHT loeschen, sie werden in eine Undo-Action gepackt)
        virtual void    HideTabWins();

        virtual void AddConnection(const OJoinExchangeData& jxdSource, const OJoinExchangeData& jxdDest) = 0;

        /** RemoveConnection allows to remove connections from join table view, it implies that the same as addConnection

            @param  _pConnection
                    the connection which should be removed
            @param  _bDelete
                    when truie then the connection will be deleted

            @return an iterator to next valid connection, so it can be used in any loop
        */
        virtual ::std::vector<OTableConnection*>::const_iterator RemoveConnection(OTableConnection* _pConnection,sal_Bool _bDelete);

        /** allows to add new connections to join table view, it implies an invalidation of the features
            ID_BROWSER_ADDTABLE and SID_RELATION_ADD_RELATION also the modified flag will be set to true
            @param  _pConnection
                    the connection which should be added
            @param  _bAddData
                    <TRUE/> when the data should also be appended
        */
        void addConnection(OTableConnection* _pConnection,sal_Bool _bAddData = sal_True);

        BOOL            ScrollPane( long nDelta, BOOL bHoriz, BOOL bPaintScrollBars );
        ULONG           GetTabWinCount();
        Point           GetScrollOffset() const { return m_aScrollOffset; }

        OJoinDesignView*            getDesignView() const { return m_pView; }
        OTableWindow*               GetTabWindow( const String& rName );

        OTableConnection*           GetSelectedConn() { return m_pSelectedConn; }
        void                        DeselectConn(OTableConnection* pConn);  // NULL ist ausdruecklich zugelassen, dann passiert nichts
        void                        SelectConn(OTableConnection* pConn);

        OTableWindowMap*            GetTabWinMap() { return &m_aTableMap; }
        const OTableWindowMap*      GetTabWinMap() const { return &m_aTableMap; }

        /** gives a read only access to the connection vector
        */
        const ::std::vector<OTableConnection*>* getTableConnections() const { return &m_vTableConnection; }

        BOOL                        ExistsAConn(const OTableWindow* pFromWin) const;

        /** getTableConnections searchs for all connections of a table
            @param  _pFromWin   the table for which connections should be found

            @return an iterator which can be used to travel all connections of the table
        */
        ::std::vector<OTableConnection*>::const_iterator getTableConnections(const OTableWindow* _pFromWin) const;

        /** getConnectionCount returns how many connection belongs to single table
            @param  _pFromWin   the table for which connections should be found

            @return the count of connections wich belongs to this table
        */
        sal_Int32 getConnectionCount(const OTableWindow* _pFromWin) const;

        OTableConnection* GetTabConn(const OTableWindow* pLhs,const OTableWindow* pRhs,bool _bSupressCrossOrNaturalJoin = false,const OTableConnection* _rpFirstAfter = NULL) const;

        // clears the window map and connection vector without destroying it
        // that means teh data of the windows and connection will be untouched
        void clearLayoutInformation();

        // set the focus to that tab win which most recently had it (or to the first available one)
        void GrabTabWinFocus();

        // ReSync ist dazu gedacht, aus dem Dokument alle WinData und ConnData zu holen und entsprechend Wins und Conns anzulegen
        virtual void ReSync() { }
        // ClearAll implementiert ein hartes Loeschen, es werden alle Conns und alle Wins aus ihren jeweiligen Listen geloescht
        // sowie die entsprechenden Datas aus dem Dokument ausgetragen
        virtual void ClearAll();

        // wird vom AddTabDlg benutzt, um festzustellen, ob noch Tabellen hinzugefuegt werden duerfen
        virtual BOOL IsAddAllowed();
        virtual long PreNotify(NotifyEvent& rNEvt);

        // DnD stuff
        virtual void        StartDrag( sal_Int8 nAction, const Point& rPosPixel );
        virtual sal_Int8    AcceptDrop( const AcceptDropEvent& rEvt );
        virtual sal_Int8    ExecuteDrop( const ExecuteDropEvent& rEvt );

        /**
            can be used in derevied classes to make some special ui handling
            after d&d
        */
        virtual void lookForUiActivities();

        // wird nach Verschieben/Groessenaenderung der TabWins aufgerufen (die Standardimplementation reicht die neuen Daten einfach
        // an die Daten des Wins weiter)
        virtual void TabWinMoved(OTableWindow* ptWhich, const Point& ptOldPosition);
            // die Position ist "virtuell" : der Container hat sozusagen eine virtuelle Flaeche, von der immer nur ein bestimmter Bereich
            // - der mittels der Scrollbar veraendert werden kann - zu sehen ist. Insbesondere hat ptOldPosition immer positive Koordinaten,
            // auch wenn er einen Punkt oberhalb des aktuell sichtbaren Bereichs bezeichnet, dessen physische Ordinate eigentlich
            // negativ ist.
        virtual void TabWinSized(OTableWindow* ptWhich, const Point& ptOldPosition, const Size& szOldSize);

        void modified();

        /** returns if teh given window is visible.
            @param  _rPoint
                The Point to check
            @param  _rSize
                The Size to be check as well
            @return
                <TRUE/> if the area is visible otherwise <FALSE/>

        */
        BOOL isMovementAllowed(const Point& _rPoint,const Size& _rSize);

        Size getRealOutputSize() const { return m_aOutputSize; }

        virtual void EnsureVisible(const OTableWindow* _pWin);
        virtual void EnsureVisible(const Point& _rPoint,const Size& _rSize);

        TTableWindowData::value_type createTableWindowData(const ::rtl::OUString& _rComposedName
                                            ,const ::rtl::OUString& _sTableName
                                            ,const ::rtl::OUString& _rWinName);

    protected:
        virtual void MouseButtonUp( const MouseEvent& rEvt );
        virtual void MouseButtonDown( const MouseEvent& rEvt );
        virtual void Tracking( const TrackingEvent& rTEvt );
        virtual void Paint( const Rectangle& rRect );
        virtual void ConnDoubleClicked( OTableConnection* pConnection );
        virtual void SetDefaultTabWinPosSize( OTableWindow* pTabWin );
        virtual void DataChanged( const DataChangedEvent& rDCEvt );

        virtual void Resize();

        virtual void dragFinished( );
        // hier ist die Position (die sich waehrend des Sizings aendern kann) physisch, da waehrend des Sizens nicht gescrollt wird
        virtual void Command(const CommandEvent& rEvt);

        virtual OTableWindowData* CreateImpl(const ::rtl::OUString& _rComposedName
                                            ,const ::rtl::OUString& _sTableName
                                            ,const ::rtl::OUString& _rWinName);

        /** factory method to create table windows
            @param  _pData
                The data corresponding to the window.
            @return
                The new TableWindow
        */
        virtual OTableWindow* createWindow(const TTableWindowData::value_type& _pData) = 0;

        /** determines whether the classes Init method should accept a query name, or only table names
        */
        virtual bool    allowQueries() const;

        /** called when init fails at the tablewindowdata because the m_xTable object could not provide columns, but no
            exception was thrown. Expected to throw.
        */
        virtual void    onNoColumns_throw();

        virtual bool supressCrossNaturalJoin(const TTableConnectionData::value_type& _pData) const;

    private:
        void    InitColors();
        BOOL    ScrollWhileDragging();

        /** executePopup opens the context menu to delate a connection
            @param  _aPos               the position where the popup menu should appear
            @param  _pSelConnection     the connection which should be deleted
        */
        void executePopup(const Point& _aPos,OTableConnection* _pSelConnection);

        /** invalidateAndModify invalidates this window without children and
            set the controller modified
            @param  _pAction a possible undo action to add at the controller
        */
        void invalidateAndModify(SfxUndoAction *_pAction=NULL);

    private:
        using Window::Scroll;
    };
}
#endif // DBAUI_JOINTABLEVIEW_HXX
<|endoftext|>