<commit_before>/*************************************************************************
 *
 *  $RCSfile: dialmgr.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hjs $ $Date: 2004-06-25 11:52:21 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

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

#include "dialmgr.hxx"
#include <tools/rc.hxx>
#include <svtools/solar.hrc>
#include <vcl/svapp.hxx>

static ResMgr* pResMgr=0;

// struct DialogsResMgr --------------------------------------------------
ResMgr* DialogsResMgr::GetResMgr()
{
    if ( !pResMgr )
    {
        ByteString aName( "svx" );
        INT32 nSolarUpd(SOLARUPD);
        aName += ByteString::CreateFromInt32( nSolarUpd );
        pResMgr = ResMgr::CreateResMgr( aName.GetBuffer(), Application::GetSettings().GetUILocale() );
    }

    return pResMgr;
}
<commit_msg>INTEGRATION: CWS visibility01 (1.3.224); FILE MERGED 2004/12/06 08:11:25 mnicel 1.3.224.2: Part of symbol visibility markup - #i35758# 2004/11/01 20:17:17 mhu 1.3.224.1: #i35758# Undefine SVX_DLLIMPLEMENTATION for objects going into 'cui' library.<commit_after>/*************************************************************************
 *
 *  $RCSfile: dialmgr.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: kz $ $Date: 2005-01-21 16:34:33 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

//#ifdef SVX_DLLIMPLEMENTATION
//#undef SVX_DLLIMPLEMENTATION
//#endif

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

#include "dialmgr.hxx"
#include <tools/rc.hxx>
#include <svtools/solar.hrc>
#include <vcl/svapp.hxx>

static ResMgr* pResMgr=0;

// struct DialogsResMgr --------------------------------------------------
ResMgr* DialogsResMgr::GetResMgr()
{
    if ( !pResMgr )
    {
        ByteString aName( "svx" );
        INT32 nSolarUpd(SOLARUPD);
        aName += ByteString::CreateFromInt32( nSolarUpd );
        pResMgr = ResMgr::CreateResMgr( aName.GetBuffer(), Application::GetSettings().GetUILocale() );
    }

    return pResMgr;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: optdict.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 17:26:10 $
 *
 *  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 _SVX_OPTDICT_HXX
#define _SVX_OPTDICT_HXX

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

#ifndef _SV_DIALOG_HXX //autogen
#include <vcl/dialog.hxx>
#endif
#ifndef _SV_FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif
#ifndef _SV_LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif
#ifndef _SV_BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#ifndef _SV_GROUP_HXX //autogen
#include <vcl/group.hxx>
#endif
#ifndef _SV_COMBOBOX_HXX //autogen
#include <vcl/combobox.hxx>
#endif

#ifndef _SV_TIMER_HXX //autogen
#include <vcl/timer.hxx>
#endif
#ifndef _SV_EDIT_HXX //autogen
#include <vcl/edit.hxx>
#endif

#ifndef _SV_DECOVIEW_HXX //autogen
#include <vcl/decoview.hxx>
#endif

#ifndef _COM_SUN_STAR_UTIL_LANGUAGE_HPP_
#include <com/sun/star/util/Language.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif

#ifndef _SVX_SIMPTABL_HXX
#include <svx/simptabl.hxx>
#endif
#ifndef _SVX_LANGBOX_HXX
#include <svx/langbox.hxx>
#endif

namespace com{namespace sun{namespace star{
namespace linguistic2{
    class XDictionary;
    class XDictionary1;
    class XSpellChecker1;
    class XSpellChecker;
}}}}

// forward ---------------------------------------------------------------

// class SvxNewDictionaryDialog ------------------------------------------

class SvxNewDictionaryDialog : public ModalDialog
{
private:
    FixedText           aNameText;
    Edit                aNameEdit;
    FixedText           aLanguageText;
    SvxLanguageBox      aLanguageLB;
    CheckBox            aExceptBtn;
    FixedLine            aNewDictBox;
    OKButton            aOKBtn;
    CancelButton        aCancelBtn;
    HelpButton          aHelpBtn;
    ::com::sun::star::uno::Reference<
        ::com::sun::star::linguistic2::XSpellChecker1 >     xSpell;
    ::com::sun::star::uno::Reference<
        ::com::sun::star::linguistic2::XDictionary1 >   xNewDic;

#ifdef _SVX_OPTDICT_CXX
    DECL_LINK( OKHdl_Impl, Button * );
    DECL_LINK( ModifyHdl_Impl, Edit * );
#endif

public:
    SvxNewDictionaryDialog( Window* pParent,
            ::com::sun::star::uno::Reference<
                ::com::sun::star::linguistic2::XSpellChecker1 >  &xSpl );

    ::com::sun::star::uno::Reference<
        ::com::sun::star::linguistic2::XDictionary1 >
                GetNewDictionary() { return xNewDic; }
};

// class SvxDictEdit ----------------------------------------------------

class SvxDictEdit : public Edit
{
    Link    aActionLink;
    sal_Bool    bSpaces;

    public:
                    SvxDictEdit(Window* pParent, const ResId& rResId) :
                        Edit(pParent, rResId), bSpaces(sal_False){}

    void            SetActionHdl( const Link& rLink )
                                { aActionLink = rLink;}

    void            SetSpaces(sal_Bool bSet)
                                {bSpaces = bSet;}

    virtual void    KeyInput( const KeyEvent& rKEvent );
};

// class SvxEditDictionaryDialog -----------------------------------------

class SvxEditDictionaryDialog : public ModalDialog
{
private:

    FixedText               aBookFT;
    ListBox                 aAllDictsLB;
    FixedText               aLangFT;
    SvxLanguageBox          aLangLB;

    FixedText               aWordFT;
    SvxDictEdit             aWordED;
    FixedText               aReplaceFT;
    SvxDictEdit             aReplaceED;
    SvTabListBox            aWordsLB;
    PushButton              aNewReplacePB;
    PushButton              aDeletePB;
    FixedLine                aEditDictsBox;

    CancelButton            aCloseBtn;
    HelpButton              aHelpBtn;
    String                  sModify;
    String                  sNew;
    DecorationView          aDecoView;

    ::com::sun::star::uno::Sequence<
        ::com::sun::star::uno::Reference<
            ::com::sun::star::linguistic2::XDictionary >  > aDics;  //! snapshot copy to work on
    ::com::sun::star::uno::Reference<
        ::com::sun::star::linguistic2::XSpellChecker1 >     xSpell;

    short               nOld;
    long                nWidth;
    sal_Bool            bFirstSelect;
    sal_Bool            bDoNothing;
    BOOL                bDicIsReadonly;

#ifdef _SVX_OPTDICT_CXX
    DECL_LINK( SelectBookHdl_Impl, ListBox * );
    DECL_LINK( SelectLangHdl_Impl, ListBox * );
    DECL_LINK(SelectHdl, SvTabListBox*);
    DECL_LINK(NewDelHdl, PushButton*);
    DECL_LINK(ModifyHdl, Edit*);

    void            ShowWords_Impl( sal_uInt16 nId );
    void            SetLanguage_Impl( ::com::sun::star::util::Language nLanguage );
    sal_Bool            IsDicReadonly_Impl() const { return bDicIsReadonly; }
    void            SetDicReadonly_Impl( ::com::sun::star::uno::Reference<
                            ::com::sun::star::linguistic2::XDictionary1 >  &xDic );

    void            RemoveDictEntry(SvLBoxEntry* pEntry);
    USHORT          GetLBInsertPos(const String &rDicWord);

#endif

protected:

    virtual void    Paint( const Rectangle& rRect );

public:
    SvxEditDictionaryDialog( Window* pParent,
            const String& rName,
            ::com::sun::star::uno::Reference<
                ::com::sun::star::linguistic2::XSpellChecker1> &xSpl );
    ~SvxEditDictionaryDialog();

    sal_uInt16 GetSelectedDict() {return aAllDictsLB.GetSelectEntryPos();}
};

#endif

<commit_msg>INTEGRATION: CWS changefileheader (1.4.368); FILE MERGED 2008/04/01 15:50:27 thb 1.4.368.3: #i85898# Stripping all external header guards 2008/04/01 12:48:17 thb 1.4.368.2: #i85898# Stripping all external header guards 2008/03/31 14:19:58 rt 1.4.368.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: optdict.hxx,v $
 * $Revision: 1.5 $
 *
 * 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 _SVX_OPTDICT_HXX
#define _SVX_OPTDICT_HXX

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

#include <vcl/dialog.hxx>
#include <vcl/fixed.hxx>
#include <vcl/lstbox.hxx>
#ifndef _SV_BUTTON_HXX //autogen
#include <vcl/button.hxx>
#endif
#include <vcl/group.hxx>
#include <vcl/combobox.hxx>
#include <vcl/timer.hxx>
#include <vcl/edit.hxx>
#include <vcl/decoview.hxx>
#include <com/sun/star/util/Language.hpp>
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/uno/Sequence.hxx>

#include <svx/simptabl.hxx>
#include <svx/langbox.hxx>

namespace com{namespace sun{namespace star{
namespace linguistic2{
    class XDictionary;
    class XDictionary1;
    class XSpellChecker1;
    class XSpellChecker;
}}}}

// forward ---------------------------------------------------------------

// class SvxNewDictionaryDialog ------------------------------------------

class SvxNewDictionaryDialog : public ModalDialog
{
private:
    FixedText           aNameText;
    Edit                aNameEdit;
    FixedText           aLanguageText;
    SvxLanguageBox      aLanguageLB;
    CheckBox            aExceptBtn;
    FixedLine            aNewDictBox;
    OKButton            aOKBtn;
    CancelButton        aCancelBtn;
    HelpButton          aHelpBtn;
    ::com::sun::star::uno::Reference<
        ::com::sun::star::linguistic2::XSpellChecker1 >     xSpell;
    ::com::sun::star::uno::Reference<
        ::com::sun::star::linguistic2::XDictionary1 >   xNewDic;

#ifdef _SVX_OPTDICT_CXX
    DECL_LINK( OKHdl_Impl, Button * );
    DECL_LINK( ModifyHdl_Impl, Edit * );
#endif

public:
    SvxNewDictionaryDialog( Window* pParent,
            ::com::sun::star::uno::Reference<
                ::com::sun::star::linguistic2::XSpellChecker1 >  &xSpl );

    ::com::sun::star::uno::Reference<
        ::com::sun::star::linguistic2::XDictionary1 >
                GetNewDictionary() { return xNewDic; }
};

// class SvxDictEdit ----------------------------------------------------

class SvxDictEdit : public Edit
{
    Link    aActionLink;
    sal_Bool    bSpaces;

    public:
                    SvxDictEdit(Window* pParent, const ResId& rResId) :
                        Edit(pParent, rResId), bSpaces(sal_False){}

    void            SetActionHdl( const Link& rLink )
                                { aActionLink = rLink;}

    void            SetSpaces(sal_Bool bSet)
                                {bSpaces = bSet;}

    virtual void    KeyInput( const KeyEvent& rKEvent );
};

// class SvxEditDictionaryDialog -----------------------------------------

class SvxEditDictionaryDialog : public ModalDialog
{
private:

    FixedText               aBookFT;
    ListBox                 aAllDictsLB;
    FixedText               aLangFT;
    SvxLanguageBox          aLangLB;

    FixedText               aWordFT;
    SvxDictEdit             aWordED;
    FixedText               aReplaceFT;
    SvxDictEdit             aReplaceED;
    SvTabListBox            aWordsLB;
    PushButton              aNewReplacePB;
    PushButton              aDeletePB;
    FixedLine                aEditDictsBox;

    CancelButton            aCloseBtn;
    HelpButton              aHelpBtn;
    String                  sModify;
    String                  sNew;
    DecorationView          aDecoView;

    ::com::sun::star::uno::Sequence<
        ::com::sun::star::uno::Reference<
            ::com::sun::star::linguistic2::XDictionary >  > aDics;  //! snapshot copy to work on
    ::com::sun::star::uno::Reference<
        ::com::sun::star::linguistic2::XSpellChecker1 >     xSpell;

    short               nOld;
    long                nWidth;
    sal_Bool            bFirstSelect;
    sal_Bool            bDoNothing;
    BOOL                bDicIsReadonly;

#ifdef _SVX_OPTDICT_CXX
    DECL_LINK( SelectBookHdl_Impl, ListBox * );
    DECL_LINK( SelectLangHdl_Impl, ListBox * );
    DECL_LINK(SelectHdl, SvTabListBox*);
    DECL_LINK(NewDelHdl, PushButton*);
    DECL_LINK(ModifyHdl, Edit*);

    void            ShowWords_Impl( sal_uInt16 nId );
    void            SetLanguage_Impl( ::com::sun::star::util::Language nLanguage );
    sal_Bool            IsDicReadonly_Impl() const { return bDicIsReadonly; }
    void            SetDicReadonly_Impl( ::com::sun::star::uno::Reference<
                            ::com::sun::star::linguistic2::XDictionary1 >  &xDic );

    void            RemoveDictEntry(SvLBoxEntry* pEntry);
    USHORT          GetLBInsertPos(const String &rDicWord);

#endif

protected:

    virtual void    Paint( const Rectangle& rRect );

public:
    SvxEditDictionaryDialog( Window* pParent,
            const String& rName,
            ::com::sun::star::uno::Reference<
                ::com::sun::star::linguistic2::XSpellChecker1> &xSpl );
    ~SvxEditDictionaryDialog();

    sal_uInt16 GetSelectedDict() {return aAllDictsLB.GetSelectEntryPos();}
};

#endif

<|endoftext|>


<commit_before>/*
 * transform_ext.cc
 *
 *  Copyright (C) 2013 Diamond Light Source
 *
 *  Author: James Parkhurst
 *
 *  This code is distributed under the BSD license, a copy of which is
 *  included in the root directory of this package.
 */
#include <boost/python.hpp>
#include <boost/python/def.hpp>
#include <dials/algorithms/reflexion_basis/rebin_pixels.h>
#include <dials/algorithms/reflexion_basis/map_frames.h>
#include <dials/algorithms/reflexion_basis/beam_vector_map.h>
#include <dials/algorithms/reflexion_basis/map_pixels.h>
#include <dials/algorithms/reflexion_basis/forward.h>

namespace dials { namespace algorithms { namespace reflexion_basis {
  namespace transform { namespace boost_python {

  using namespace boost::python;
  using scitbx::af::int2;
  using scitbx::af::flex_grid;

  inline
  flex_double rebin_pixels_wrapper(const flex_double &input,
      const flex_vec2_double &inputxy, int2 size) {
    flex_double output(flex_grid<>(size[0], size[1]));
    rebin_pixels(output, input, inputxy);
    return output;
  }

  void export_rebin_pixels()
  {
    def("rebin_pixels", &rebin_pixels_wrapper, (
      arg("input"), arg("inputxy"), arg("size")));
  }

  void export_map_frames()
  {
    class_<MapFramesForward>(
        "MapFramesForward", no_init)
      .def(init<double, double, double, double, int>((
          arg("starting_angle"),
          arg("oscillation"),
          arg("mosaicity"),
          arg("n_sigma"),
          arg("grid_size_e3"))))
      .def("__call__",
        &MapFramesForward::operator(), (
          arg("frames"),
          arg("phi"),
          arg("zeta")));

    class_<MapFramesReverse>(
        "MapFramesReverse", no_init)
      .def(init<double, double, double, double, int>((
          arg("starting_angle"),
          arg("oscillation"),
          arg("mosaicity"),
          arg("n_sigma"),
          arg("grid_size_e3"))))
      .def("__call__",
        &MapFramesReverse::operator(), (
          arg("frames"),
          arg("phi"),
          arg("zeta")));
  }

  void export_beam_vector_map()
  {
    flex_vec3_double (*overload1)(const Detector&,
      const Beam&, std::size_t, bool) = &beam_vector_map;
    flex_vec3_double (*overload2)(const Detector&,
      const Beam&, bool) = &beam_vector_map;
    flex_vec3_double (*overload3)(const Detector&,
      const Beam&) = &beam_vector_map;

    def("beam_vector_map", overload1, (
      arg("detector"),
      arg("beam"),
      arg("n_div"),
      arg("corners")));
    def("beam_vector_map", overload2, (
      arg("detector"),
      arg("beam"),
      arg("corners")));
    def("beam_vector_map", overload3, (
      arg("detector"),
      arg("beam")));
  }

  void export_map_pixels()
  {
    class_<GridIndexGenerator>("GridIndexGenerator", no_init)
      .def(init<const CoordinateSystem&, int, int, vec2<double>,
                std::size_t, const flex_vec3_double>((
          arg("cs"),
          arg("x0"),
          arg("y0"),
          arg("step_size"),
          arg("grid_half_size"),
          arg("s1_map"))))
      .def("__call__", &GridIndexGenerator::operator());

    flex_double (MapPixelsForward::*call_forward)(const CoordinateSystem&, int6,
        const flex_double&, const flex_bool&, const flex_double&) const =
          &MapPixelsForward::operator();

    flex_double (MapPixelsReverse::*call_reverse)(const CoordinateSystem&, int6,
        const flex_double&, const flex_double&) const =
          &MapPixelsReverse::operator();

    class_<MapPixelsForward>("MapPixelsForward", no_init)
      .def(init<const flex_vec3_double &,
                std::size_t,
                vec2<double> >((
        arg("s1_map"),
        arg("grid_half_size"),
        arg("step_size"))))
      .def("__call__", call_forward, (
        arg("cs"),
        arg("bbox"),
        arg("image"),
        arg("mask")));

    class_<MapPixelsReverse>("MapPixelsReverse", no_init)
      .def(init<const flex_vec3_double &,
                std::size_t,
                vec2<double> >((
        arg("s1_map"),
        arg("grid_half_size"),
        arg("step_size"))))
      .def("__call__", call_reverse, (
        arg("cs"),
        arg("bbox"),
        arg("grid")));
  }

  void export_transform()
  {
    class_<Forward>("Forward", no_init)
      .def(init<const Beam&, const Detector&, const Scan&,
                double, std::size_t, std::size_t>((
        arg("beam"),
        arg("detector"),
        arg("scan"),
        arg("mosaicity"),
        arg("n_sigma"),
        arg("grid_half_size"))))
      .def("__call__", &Forward::operator(), (
        arg("cs"),
        arg("bbox"),
        arg("image"),
        arg("mask")));

    class_<Reverse>("Reverse", no_init)
      .def(init<const Beam&, const Detector&, const Scan&,
                double, std::size_t, std::size_t>((
        arg("beam"),
        arg("detector"),
        arg("scan"),
        arg("mosaicity"),
        arg("n_sigma"),
        arg("grid_half_size"))))
      .def("__call__", &Forward::operator(), (
        arg("cs"),
        arg("bbox"),
        arg("grid")));
  }

  BOOST_PYTHON_MODULE(dials_algorithms_reflexion_basis_transform_ext)
  {
    export_rebin_pixels();
    export_map_frames();
    export_beam_vector_map();
    export_map_pixels();
  }

}}}}} // namespace = dials::algorithms::reflexion_basis::transform::boost_python
<commit_msg>Modified #include for transform.h<commit_after>/*
 * transform_ext.cc
 *
 *  Copyright (C) 2013 Diamond Light Source
 *
 *  Author: James Parkhurst
 *
 *  This code is distributed under the BSD license, a copy of which is
 *  included in the root directory of this package.
 */
#include <boost/python.hpp>
#include <boost/python/def.hpp>
#include <dials/algorithms/reflexion_basis/rebin_pixels.h>
#include <dials/algorithms/reflexion_basis/map_frames.h>
#include <dials/algorithms/reflexion_basis/beam_vector_map.h>
#include <dials/algorithms/reflexion_basis/map_pixels.h>
#include <dials/algorithms/reflexion_basis/transform.h>

namespace dials { namespace algorithms { namespace reflexion_basis {
  namespace transform { namespace boost_python {

  using namespace boost::python;
  using scitbx::af::int2;
  using scitbx::af::flex_grid;

  inline
  flex_double rebin_pixels_wrapper(const flex_double &input,
      const flex_vec2_double &inputxy, int2 size) {
    flex_double output(flex_grid<>(size[0], size[1]));
    rebin_pixels(output, input, inputxy);
    return output;
  }

  void export_rebin_pixels()
  {
    def("rebin_pixels", &rebin_pixels_wrapper, (
      arg("input"), arg("inputxy"), arg("size")));
  }

  void export_map_frames()
  {
    class_<MapFramesForward>(
        "MapFramesForward", no_init)
      .def(init<double, double, double, double, int>((
          arg("starting_angle"),
          arg("oscillation"),
          arg("mosaicity"),
          arg("n_sigma"),
          arg("grid_size_e3"))))
      .def("__call__",
        &MapFramesForward::operator(), (
          arg("frames"),
          arg("phi"),
          arg("zeta")));

    class_<MapFramesReverse>(
        "MapFramesReverse", no_init)
      .def(init<double, double, double, double, int>((
          arg("starting_angle"),
          arg("oscillation"),
          arg("mosaicity"),
          arg("n_sigma"),
          arg("grid_size_e3"))))
      .def("__call__",
        &MapFramesReverse::operator(), (
          arg("frames"),
          arg("phi"),
          arg("zeta")));
  }

  void export_beam_vector_map()
  {
    flex_vec3_double (*overload1)(const Detector&,
      const Beam&, std::size_t, bool) = &beam_vector_map;
    flex_vec3_double (*overload2)(const Detector&,
      const Beam&, bool) = &beam_vector_map;
    flex_vec3_double (*overload3)(const Detector&,
      const Beam&) = &beam_vector_map;

    def("beam_vector_map", overload1, (
      arg("detector"),
      arg("beam"),
      arg("n_div"),
      arg("corners")));
    def("beam_vector_map", overload2, (
      arg("detector"),
      arg("beam"),
      arg("corners")));
    def("beam_vector_map", overload3, (
      arg("detector"),
      arg("beam")));
  }

  void export_map_pixels()
  {
    class_<GridIndexGenerator>("GridIndexGenerator", no_init)
      .def(init<const CoordinateSystem&, int, int, vec2<double>,
                std::size_t, const flex_vec3_double>((
          arg("cs"),
          arg("x0"),
          arg("y0"),
          arg("step_size"),
          arg("grid_half_size"),
          arg("s1_map"))))
      .def("__call__", &GridIndexGenerator::operator());

    flex_double (MapPixelsForward::*call_forward)(const CoordinateSystem&, int6,
        const flex_double&, const flex_bool&, const flex_double&) const =
          &MapPixelsForward::operator();

    flex_double (MapPixelsReverse::*call_reverse)(const CoordinateSystem&, int6,
        const flex_double&, const flex_double&) const =
          &MapPixelsReverse::operator();

    class_<MapPixelsForward>("MapPixelsForward", no_init)
      .def(init<const flex_vec3_double &,
                std::size_t,
                vec2<double> >((
        arg("s1_map"),
        arg("grid_half_size"),
        arg("step_size"))))
      .def("__call__", call_forward, (
        arg("cs"),
        arg("bbox"),
        arg("image"),
        arg("mask")));

    class_<MapPixelsReverse>("MapPixelsReverse", no_init)
      .def(init<const flex_vec3_double &,
                std::size_t,
                vec2<double> >((
        arg("s1_map"),
        arg("grid_half_size"),
        arg("step_size"))))
      .def("__call__", call_reverse, (
        arg("cs"),
        arg("bbox"),
        arg("grid")));
  }

  void export_transform()
  {
    class_<Forward>("Forward", no_init)
      .def(init<const Beam&, const Detector&, const Scan&,
                double, std::size_t, std::size_t>((
        arg("beam"),
        arg("detector"),
        arg("scan"),
        arg("mosaicity"),
        arg("n_sigma"),
        arg("grid_half_size"))))
      .def("__call__", &Forward::operator(), (
        arg("cs"),
        arg("bbox"),
        arg("image"),
        arg("mask")));

    class_<Reverse>("Reverse", no_init)
      .def(init<const Beam&, const Detector&, const Scan&,
                double, std::size_t, std::size_t>((
        arg("beam"),
        arg("detector"),
        arg("scan"),
        arg("mosaicity"),
        arg("n_sigma"),
        arg("grid_half_size"))))
      .def("__call__", &Forward::operator(), (
        arg("cs"),
        arg("bbox"),
        arg("grid")));
  }

  BOOST_PYTHON_MODULE(dials_algorithms_reflexion_basis_transform_ext)
  {
    export_rebin_pixels();
    export_map_frames();
    export_beam_vector_map();
    export_map_pixels();
  }

}}}}} // namespace = dials::algorithms::reflexion_basis::transform::boost_python
<|endoftext|>


<commit_before>void fun();

class Smurf {
public:
    Smurf();
    ~Smurf() {}
};

namespace foo {
void gun();

namespace bar {

class Smurf {
public:
    Smurf();
    ~Smurf() {}
};

} // NS: bar

} // NS: foo
<commit_msg>test: comment class_func.hpp<commit_after>// should ignore C++ code in global namespace

void fun();

class Smurf {
public:
    Smurf();
    ~Smurf() {}
};

namespace foo {
void gun();

namespace bar {

class Smurf {
public:
    Smurf();
    ~Smurf() {}
};

} // NS: bar

} // NS: foo
<|endoftext|>


<commit_before>/* Copyright (c) 2017, EPL-Vizards
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the EPL-Vizards nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL EPL-Vizards BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
/*!
 * \file networkgraphmodel.cpp
 */

#include "networkgraphmodel.hpp"
#include "mainwindow.hpp"

using namespace EPL_Viz;
using namespace EPL_DataCollect;

NetworkGraphModel::NetworkGraphModel(MainWindow *mw) { graph = mw->getNetworkGraph(); }

NetworkGraphModel::~NetworkGraphModel() {}

void NetworkGraphModel::init() {}

void NetworkGraphModel::update(Cycle *cycle) {
  auto list = cycle->getNodeList();

  for (uint8_t id : list) {
    Node *n = cycle->getNode(id);
    auto  s = nodeMap.find(id);

    if (s == nodeMap.end() || s.key() != id) {
      // The node is not yet added as a widget and has to be created
      NodeWidget *nw = new NodeWidget(n, graph);
      nodeMap.insert(id, nw);
      graph->layout()->addWidget(nw);
    } else {
      // The node is added as widget and has to be updated
      nodeMap[id]->updateData(n);
    }
  }
}
<commit_msg>Added highlighting to the network graph model<commit_after>/* Copyright (c) 2017, EPL-Vizards
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the EPL-Vizards nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL EPL-Vizards BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
/*!
 * \file networkgraphmodel.cpp
 */

#include "networkgraphmodel.hpp"
#include "mainwindow.hpp"

using namespace EPL_Viz;
using namespace EPL_DataCollect;

NetworkGraphModel::NetworkGraphModel(MainWindow *mw) { graph = mw->getNetworkGraph(); }

NetworkGraphModel::~NetworkGraphModel() {}

void NetworkGraphModel::init() {}

void NetworkGraphModel::update(Cycle *cycle) {
  auto list = cycle->getNodeList();

  for (uint8_t id : list) {
    Node *n = cycle->getNode(id);
    auto  s = nodeMap.find(id);

    if (s == nodeMap.end() || s.key() != id) {
      // The node is not yet added as a widget and has to be created
      NodeWidget *nw = new NodeWidget(n, graph);
      nodeMap.insert(id, nw);
      graph->layout()->addWidget(nw);
    } else {
      // The node is added as widget and has to be updated
      nodeMap[id]->updateData(n);
    }

    nodeMap[id]->setHighlightingLevel(0);
  }

  auto events = cycle->getActiveEvents();

  for (auto event : events) {
    switch (event->getType()) {
      case EvType::VIEW_EV_HIGHLIGHT_MN:
      case EvType::VIEW_EV_HIGHLIGHT_CN: {
        uint64_t node  = event->getEventFlags();             // EventFlags is the NodeID for these events
        int      level = std::stoi(event->getDescription()); // Description is the highlighting level for these events

        // Invalid node
        if (cycle->getNode(node) == nullptr)
          break;

        // Check if event valid
        if ((event->getType() == EvType::VIEW_EV_HIGHLIGHT_CN && node < 240) ||
            (event->getType() == EvType::VIEW_EV_HIGHLIGHT_CN && node == 240)) {
          // Set highlighting
          nodeMap[node]->setHighlightingLevel(level);
        }
        break;
      }
      default: break;
    }
  }

  for (uint8_t id : list) {
    nodeMap[id]->updateStyleSheet();
  }
}
<|endoftext|>


<commit_before>/*
  sbus.cpp

  Copyright (c) 2017, Fabrizio Di Vittorio (fdivitto2013@gmail.com)

  This library 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 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "sbus.h"

// quick IO functions
#define portOfPin(P)        (((P) >= 0 && (P) < 8) ? &PORTD : (((P) > 7 && (P) < 14) ? &PORTB : &PORTC))
#define ddrOfPin(P)         (((P) >= 0 && (P) < 8) ? &DDRD : (((P) > 7 && (P) < 14) ? &DDRB : &DDRC))
#define pinOfPin(P)         (((P) >= 0 && (P) < 8) ? &PIND : (((P) > 7 && (P) < 14) ? &PINB : &PINC))
#define pinIndex(P)         ((uint8_t)(P > 13 ? P - 14 : P & 7))
#define pinMask(P)          ((uint8_t)(1 << pinIndex(P)))
#define pinAsInput(P)       (*(ddrOfPin(P)) &= ~pinMask(P))
#define pinAsInputPullUp(P) (*(ddrOfPin(P)) &= ~pinMask(P); digitalHigh(P))
#define pinAsOutput(P)      (*(ddrOfPin(P)) |= pinMask(P))
#define digitalLow(P)       (*(portOfPin(P)) &= ~pinMask(P))
#define digitalHigh(P)      (*(portOfPin(P)) |= pinMask(P))
#define isHigh(P)           ((*(pinOfPin(P)) & pinMask(P)) > 0)
#define isLow(P)            ((*(pinOfPin(P)) & pinMask(P)) == 0)
#define pinGet(pin, mask)   (((*(pin)) & (mask)) > 0)

static uint8_t * s_pin;
static uint8_t s_pinMask;
static uint8_t s_PCICRMask;

static volatile mode_t s_mode;

// contains which word is currently receiving (0..24, 24 is the last word)
static volatile uint8_t s_receivingWordIndex = 0;

// received frame
static volatile uint8_t s_frame[23];

struct chinfo_t {
  uint8_t idx;
  uint8_t shift1;
  uint8_t shift2;
  uint8_t shift3; // 11 = byte 3 ignored
};

static const chinfo_t CHINFO[16] PROGMEM = { {0,  0, 8, 11}, {1,  3, 5, 11}, {2,  6, 2, 10}, {4,  1, 7, 11}, {5,  4, 4, 11},
                                           {6,  7, 1, 9},  {8,  2, 6, 11}, {9,  5, 3, 11}, {11, 0, 8, 11}, {12, 3, 5, 11},
                                           {13, 6, 2, 10}, {15, 1, 7, 11}, {16, 4, 4, 11}, {17, 7, 1, 9},  {19, 2, 6, 11},  {20, 5, 3, 11} };

// flag field
#define FLAG_CHANNEL_17  1
#define FLAG_CHANNEL_18  2
#define FLAG_SIGNAL_LOSS 4
#define FLAG_FAILSAFE    8

#define CHANNEL_MIN 173
#define CHANNEL_MAX 1812

inline void enablePinChangeInterrupts()
{
  // clear any outstanding interrupt
  PCIFR |= s_PCICRMask;

  // enable interrupt for the group
  PCICR |= s_PCICRMask;
}

inline void disablePinChangeInterrupts()
{
  PCICR &= ~s_PCICRMask;
}

// handle pin change interrupt for D0 to D7 here
ISR(PCINT2_vect)
{
  // start bit?
  if (pinGet(s_pin, s_pinMask) > 0) {

    // reset timer 2 counter
    TCNT2 = 0;

    // start bit received
    uint8_t receivedBitIndex = 1;
    uint8_t receivingWord = 0;

    // receive other bits

    // reset OCF2A flag by writing "1"
    TIFR2 |= 1 << OCF2A;

    uint8_t calc_parity = 0xFF;

    while (true) {

      // wait for TCNT2 == OCR2A
      while (!(TIFR2 & (1 << OCF2A)))
        ;

      // reset OCF2A flag by writing "1"
      TIFR2 |= 1 << OCF2A;

      // sample current bit
      if (receivedBitIndex >= 1 && receivedBitIndex <= 8) {
        if (pinGet(s_pin, s_pinMask) > 0)
          receivingWord |= 1 << (receivedBitIndex - 1);
        else
          calc_parity = ~calc_parity;
      }

      // last bit?
      if (receivedBitIndex == 9) {

        // check parity
        uint8_t in_parity = pinGet(s_pin, s_pinMask) > 0;
        if ((calc_parity && !in_parity) || (!calc_parity && in_parity)) {
          // parity check failed!
          s_receivingWordIndex = 0;
          break;
        }

        receivingWord = ~receivingWord;

        if (s_receivingWordIndex == 0) {

          //  start byte (must be 0x0F)
          if (receivingWord != 0x0F) {
            // wrong start byte, restart word count
            s_receivingWordIndex = 0;
            break;
          }

        } else if (s_receivingWordIndex == 24) {

          // last word, restart word count
          if (s_mode == sbusBlocking)
            disablePinChangeInterrupts();
          s_receivingWordIndex = 0;
          break;

        } else {

          // channels and flags
          s_frame[s_receivingWordIndex - 1] = receivingWord;

        }

        // prepare for the next word
        ++s_receivingWordIndex;

        break;

      } else {

        // other bits required, continue loop

        ++receivedBitIndex;

      }

      // exit loop, a pin change (start bit) is required to restart

    }

    // reset pin change interrupt flag
    PCIFR = 0xFF;

  }

}

// used only for blocking operations (mode = sbusBlocking)
bool SBUS::waitFrame(uint32_t timeOut)
{
  if (s_mode == sbusBlocking) {
    enablePinChangeInterrupts();
    // wait until Pin change bit return back to 0
    uint32_t t0 = millis();
    while (PCICR & s_PCICRMask)
      if (millis() - t0 >= timeOut)  // note: this millis() compare is overflow safe due unsigned diffs
        return false; // timeout!
  }

  return true;
}

// channels start from 1 to 18
// returns value 173..1812 (a received by SBUS)
uint16_t SBUS::getChannelRaw(uint8_t channelIndex)
{
  if (channelIndex >= 1 && channelIndex <= 16) {

    chinfo_t chinfo;
    memcpy_P(&chinfo, CHINFO + channelIndex - 1, sizeof(chinfo_t));

    uint8_t idx = chinfo.idx;

    noInterrupts();
    uint8_t b1 = s_frame[idx++];
    uint8_t b2 = s_frame[idx++];
    uint8_t b3 = s_frame[idx];
    interrupts();

    return ((b1 >> chinfo.shift1) | (b2 << chinfo.shift2) | (b3 << chinfo.shift3)) & 0x7FF;

  } else if (channelIndex == 17 || channelIndex == 18) {

    if (channelIndex == 17)
      return s_frame[22] & FLAG_CHANNEL_17 ? CHANNEL_MAX : CHANNEL_MIN;
    else
      return s_frame[22] & FLAG_CHANNEL_18 ? CHANNEL_MAX : CHANNEL_MIN;

  } else

    return 0; // error
}

// channels start from 1 to 18
// returns value 988..2012 (cleanflight friendly)
uint16_t SBUS::getChannel(uint8_t channelIndex)
{
  return 5 * getChannelRaw(channelIndex) / 8 + 880;
}

bool SBUS::signalLossActive()
{
  return s_frame[22] & FLAG_SIGNAL_LOSS;
}

bool SBUS::failsafeActive()
{
  return s_frame[22] & FLAG_FAILSAFE;
}

// if mode = sbusNonBlocking, an interrupt is always generated for every frame received. getChannel (or getChannelRaw) is no-blocking
// if mode = sbusBlocking, interrupts are enabled only inside getChannel (or getChannelRaw), which becomes blocking (until arrive of a new frame)
void SBUS::begin(uint8_t pin, mode_t mode)
{
  s_mode = mode;

  s_pin        = pinOfPin(pin);
  s_pinMask    = pinMask(pin);
  s_PCICRMask  = 1 << digitalPinToPCICRbit(pin);

  //// setup TIMER 2 CTC

  // select "Clear Timer on Compare (CTC)" mode
  TCCR2A = 1 << WGM21;

  // no prescaling
  TCCR2B = 1 << CS20;

  // set TOP timer 2 value
  // with no-prescaler 1/16000000=0.00000000625, each bit requires 10us, so reset timer 2 every 10us, so reset timer every 10/0.0625 = 160 ticks
  OCR2A = F_CPU / 1000000 * 10 - 1; // for 16MHz = 159;

  //// setup pin change interrupt

  pinAsInput(pin);

  // enable pin
  *digitalPinToPCMSK(pin) |= 1 << digitalPinToPCMSKbit(pin);

  if (mode == sbusNonBlocking)
    enablePinChangeInterrupts();
}

<commit_msg>improved compatibility with Servo library<commit_after>/*
  sbus.cpp

  Copyright (c) 2017, Fabrizio Di Vittorio (fdivitto2013@gmail.com)

  This library 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 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "sbus.h"

// quick IO functions
#define portOfPin(P)        (((P) >= 0 && (P) < 8) ? &PORTD : (((P) > 7 && (P) < 14) ? &PORTB : &PORTC))
#define ddrOfPin(P)         (((P) >= 0 && (P) < 8) ? &DDRD : (((P) > 7 && (P) < 14) ? &DDRB : &DDRC))
#define pinOfPin(P)         (((P) >= 0 && (P) < 8) ? &PIND : (((P) > 7 && (P) < 14) ? &PINB : &PINC))
#define pinIndex(P)         ((uint8_t)(P > 13 ? P - 14 : P & 7))
#define pinMask(P)          ((uint8_t)(1 << pinIndex(P)))
#define pinAsInput(P)       (*(ddrOfPin(P)) &= ~pinMask(P))
#define pinAsInputPullUp(P) (*(ddrOfPin(P)) &= ~pinMask(P); digitalHigh(P))
#define pinAsOutput(P)      (*(ddrOfPin(P)) |= pinMask(P))
#define digitalLow(P)       (*(portOfPin(P)) &= ~pinMask(P))
#define digitalHigh(P)      (*(portOfPin(P)) |= pinMask(P))
#define isHigh(P)           ((*(pinOfPin(P)) & pinMask(P)) > 0)
#define isLow(P)            ((*(pinOfPin(P)) & pinMask(P)) == 0)
#define pinGet(pin, mask)   (((*(pin)) & (mask)) > 0)

static uint8_t * s_pin;
static uint8_t s_pinMask;
static uint8_t s_PCICRMask;

static volatile mode_t s_mode;

// contains which word is currently receiving (0..24, 24 is the last word)
static volatile uint8_t s_receivingWordIndex = 0;

// received frame
static volatile uint8_t s_frame[23];

struct chinfo_t {
  uint8_t idx;
  uint8_t shift1;
  uint8_t shift2;
  uint8_t shift3; // 11 = byte 3 ignored
};

static const chinfo_t CHINFO[16] PROGMEM = { {0,  0, 8, 11}, {1,  3, 5, 11}, {2,  6, 2, 10}, {4,  1, 7, 11}, {5,  4, 4, 11},
                                           {6,  7, 1, 9},  {8,  2, 6, 11}, {9,  5, 3, 11}, {11, 0, 8, 11}, {12, 3, 5, 11},
                                           {13, 6, 2, 10}, {15, 1, 7, 11}, {16, 4, 4, 11}, {17, 7, 1, 9},  {19, 2, 6, 11},  {20, 5, 3, 11} };

// flag field
#define FLAG_CHANNEL_17  1
#define FLAG_CHANNEL_18  2
#define FLAG_SIGNAL_LOSS 4
#define FLAG_FAILSAFE    8

#define CHANNEL_MIN 173
#define CHANNEL_MAX 1812

inline void enablePinChangeInterrupts()
{
  // clear any outstanding interrupt
  PCIFR |= s_PCICRMask;

  // enable interrupt for the group
  PCICR |= s_PCICRMask;
}

inline void disablePinChangeInterrupts()
{
  PCICR &= ~s_PCICRMask;
}

// handle pin change interrupt for D0 to D7 here
ISR(PCINT2_vect)
{

  // start bit?
  if (pinGet(s_pin, s_pinMask)) {

    // reset timer 2 counter
    TCNT2 = 0;

    disablePinChangeInterrupts();

    // start bit received
    uint8_t receivingWord = 0;

    // reset OCF2A flag by writing "1"
    TIFR2 |= 1 << OCF2A;

    uint8_t parity = 0xFF;

    // receive other bits (including parity bit, ignore stop bits)
    for (uint8_t receivedBitIndex = 0; receivedBitIndex < 9; ++receivedBitIndex) {

      // wait for TCNT2 == OCR2A
      // warn: inside this loop interrupts are re-enabled to allow other libraries to work correctly (ie Servo library)
      interrupts();
      while (!(TIFR2 & (1 << OCF2A)))
        ;
      noInterrupts();

      // reset OCF2A flag by writing "1"
      TIFR2 |= 1 << OCF2A;

      // sample current bit
      if (pinGet(s_pin, s_pinMask))
        receivingWord |= 1 << receivedBitIndex; // parity shift here as >7 bit, so it is just discarded
      else
        parity = ~parity;

    }

    // check parity
    if (!parity) {

      // parity check failed!
      s_receivingWordIndex = 0;

    } else {

      // parity ok

      receivingWord = ~receivingWord;

      if (s_receivingWordIndex == 0) {

        //  check start word (must be 0x0F)
        if (receivingWord == 0x0F)
          ++s_receivingWordIndex; // bypass this word

      } else if (s_receivingWordIndex == 24) {

        if (receivingWord == 0x00)
          ++s_receivingWordIndex; // bypass this word

      } else {

        // save channels and flags and last ending word
        s_frame[s_receivingWordIndex - 1] = receivingWord;

        // next word
        ++s_receivingWordIndex;

      }

    }

    // reset pin change interrupt flag
    PCIFR |= s_PCICRMask;

    if (s_receivingWordIndex < 25 || s_mode == sbusNonBlocking)
      enablePinChangeInterrupts();

    if (s_receivingWordIndex == 25)
        s_receivingWordIndex = 0;    // last word, restart word count

  }

}

// used only for blocking operations (mode = sbusBlocking)
bool SBUS::waitFrame(uint32_t timeOut)
{
  if (s_mode == sbusBlocking) {

    // will be disabled inside the ISR
    enablePinChangeInterrupts();

    // wait until Pin change bit return back to 0
    uint32_t t0 = millis();
    while (PCICR & s_PCICRMask)
      if (millis() - t0 >= timeOut)  // note: this millis() compare is overflow safe due unsigned diffs
        return false; // timeout!
  }

  return true;
}

// channels start from 1 to 18
// returns value 173..1812 (a received by SBUS)
uint16_t SBUS::getChannelRaw(uint8_t channelIndex)
{
  if (channelIndex >= 1 && channelIndex <= 16) {

    chinfo_t chinfo;
    memcpy_P(&chinfo, CHINFO + channelIndex - 1, sizeof(chinfo_t));

    uint8_t idx = chinfo.idx;

    noInterrupts();
    uint8_t b1 = s_frame[idx++];
    uint8_t b2 = s_frame[idx++];
    uint8_t b3 = s_frame[idx];
    interrupts();

    return ((b1 >> chinfo.shift1) | (b2 << chinfo.shift2) | (b3 << chinfo.shift3)) & 0x7FF;

  } else if (channelIndex == 17 || channelIndex == 18) {

    if (channelIndex == 17)
      return s_frame[22] & FLAG_CHANNEL_17 ? CHANNEL_MAX : CHANNEL_MIN;
    else
      return s_frame[22] & FLAG_CHANNEL_18 ? CHANNEL_MAX : CHANNEL_MIN;

  } else

    return 0; // error
}

// channels start from 1 to 18
// returns value 988..2012 (cleanflight friendly)
uint16_t SBUS::getChannel(uint8_t channelIndex)
{
  return 5 * getChannelRaw(channelIndex) / 8 + 880;
}

bool SBUS::signalLossActive()
{
  return s_frame[22] & FLAG_SIGNAL_LOSS;
}

bool SBUS::failsafeActive()
{
  return s_frame[22] & FLAG_FAILSAFE;
}

// if mode = sbusNonBlocking, an interrupt is always generated for every frame received. getChannel (or getChannelRaw) is no-blocking
// if mode = sbusBlocking, interrupts are enabled only inside getChannel (or getChannelRaw), which becomes blocking (until arrive of a new frame)
void SBUS::begin(uint8_t pin, mode_t mode)
{
  s_mode = mode;

  s_pin        = pinOfPin(pin);
  s_pinMask    = pinMask(pin);
  s_PCICRMask  = 1 << digitalPinToPCICRbit(pin);

  //// setup TIMER 2 CTC

  // select "Clear Timer on Compare (CTC)" mode
  TCCR2A = 1 << WGM21;

  // no prescaling
  TCCR2B = 1 << CS20;

  // set TOP timer 2 value
  // with no-prescaler 1/16000000=0.00000000625, each bit requires 10us, so reset timer 2 every 10us, so reset timer every 10/0.0625 = 160 ticks
  OCR2A = F_CPU / 1000000 * 10 - 1; // for 16MHz = 159;

  //// setup pin change interrupt

  pinAsInput(pin);

  // enable pin
  *digitalPinToPCMSK(pin) |= 1 << digitalPinToPCMSKbit(pin);

  if (mode == sbusNonBlocking)
    enablePinChangeInterrupts();
}

<|endoftext|>


<commit_before>/*
 * Copyright 2007-2017 Content Management AG
 * All rights reserved.
 *
 * author: Max Kellermann <mk@cm4all.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the
 * distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "http_server/http_server.hxx"
#include "http_server/Request.hxx"
#include "http_server/Handler.hxx"
#include "http_client.hxx"
#include "http_headers.hxx"
#include "HttpResponseHandler.hxx"
#include "lease.hxx"
#include "direct.hxx"
#include "PInstance.hxx"
#include "pool/pool.hxx"
#include "istream/UnusedPtr.hxx"
#include "istream/HeadIstream.hxx"
#include "istream/BlockIstream.hxx"
#include "istream/istream_catch.hxx"
#include "istream/Sink.hxx"
#include "fb_pool.hxx"
#include "fs/FilteredSocket.hxx"
#include "net/UniqueSocketDescriptor.hxx"
#include "system/Error.hxx"
#include "util/Cancellable.hxx"
#include "util/PrintException.hxx"

#include <functional>

#include <stdio.h>
#include <stdlib.h>

class Instance final
    : HttpServerConnectionHandler, Lease, BufferedSocketHandler
{
    struct pool *pool;

    HttpServerConnection *connection = nullptr;

    std::function<void(HttpServerRequest &request,
                       CancellablePointer &cancel_ptr)> request_handler;

    FilteredSocket client_fs;

    bool client_fs_released = false;

public:
    Instance(struct pool &_pool, EventLoop &event_loop);

    ~Instance() noexcept {
        CheckCloseConnection();
    }

    struct pool &GetPool() noexcept {
        return *pool;
    }

    template<typename T>
    void SetRequestHandler(T &&handler) noexcept {
        request_handler = std::forward<T>(handler);
    }

    void CloseConnection() noexcept {
        http_server_connection_close(connection);
        connection = nullptr;
    }

    void CheckCloseConnection() noexcept {
        if (connection != nullptr)
            CloseConnection();
    }

    void SendRequest(http_method_t method, const char *uri,
                     HttpHeaders &&headers,
                     UnusedIstreamPtr body, bool expect_100,
                     HttpResponseHandler &handler,
                     CancellablePointer &cancel_ptr) noexcept {
        http_client_request(*pool, client_fs, *this,
                            "foo",
                            method, uri, std::move(headers),
                            std::move(body), expect_100,
                            handler, cancel_ptr);
    }

    void CloseClientSocket() noexcept {
        if (client_fs.IsValid() && client_fs.IsConnected()) {
            client_fs.Close();
            client_fs.Destroy();
        }
    }

private:
    /* virtual methods from class HttpServerConnectionHandler */
    void HandleHttpRequest(HttpServerRequest &request,
                           CancellablePointer &cancel_ptr) noexcept override;

    void LogHttpRequest(HttpServerRequest &,
                        http_status_t, int64_t,
                        uint64_t, uint64_t) noexcept override {}

    void HttpConnectionError(std::exception_ptr e) noexcept override;
    void HttpConnectionClosed() noexcept override;

    /* virtual methods from class Lease */
    void ReleaseLease(bool reuse) noexcept override {
        client_fs_released = true;

        if (reuse && client_fs.IsValid() && client_fs.IsConnected()) {
            client_fs.Reinit(Event::Duration(-1), Event::Duration(-1), *this);
            client_fs.UnscheduleWrite();
        } else {
            CloseClientSocket();
        }
    }

    /* virtual methods from class BufferedSocketHandler */
    BufferedResult OnBufferedData() override {
        fprintf(stderr, "unexpected data in idle TCP connection");
        CloseClientSocket();
        return BufferedResult::CLOSED;
    }

    bool OnBufferedClosed() noexcept override {
        CloseClientSocket();
        return false;
    }

    gcc_noreturn
    bool OnBufferedWrite() override {
        /* should never be reached because we never schedule
           writing */
        gcc_unreachable();
    }

    void OnBufferedError(std::exception_ptr e) noexcept override {
        PrintException(e);
        CloseClientSocket();
    }
};

class Client final : HttpResponseHandler, IstreamSink {
    CancellablePointer client_cancel_ptr;

    std::exception_ptr response_error;
    std::string response_body;
    http_status_t status{};

    bool response_eof = false;

public:
    void SendRequest(Instance &instance,
                     http_method_t method, const char *uri,
                     HttpHeaders &&headers,
                     UnusedIstreamPtr body, bool expect_100=false) noexcept {
        instance.SendRequest(method, uri, std::move(headers),
                             std::move(body), expect_100,
                             *this, client_cancel_ptr);
    }

    bool IsClientDone() const noexcept {
        return response_error || response_eof;
    }

    void RethrowResponseError() const {
        if (response_error)
            std::rethrow_exception(response_error);
    }

private:
    /* virtual methods from class HttpResponseHandler */
    void OnHttpResponse(http_status_t _status, StringMap &&headers,
                        UnusedIstreamPtr body) noexcept override {
        status = _status;

        (void)headers;

        IstreamSink::SetInput(std::move(body));
        input.Read();
    }

    void OnHttpError(std::exception_ptr ep) noexcept override {
        response_error = std::move(ep);
    }

    /* virtual methods from class IstreamHandler */

    size_t OnData(const void *data, size_t length) override {
        response_body.append((const char *)data, length);
        return length;
    }

    void OnEof() noexcept override {
        IstreamSink::ClearInput();
        response_eof = true;
    }

    void OnError(std::exception_ptr ep) noexcept override {
        IstreamSink::ClearInput();
        response_error = std::move(ep);
    }
};

Instance::Instance(struct pool &_pool, EventLoop &event_loop)
    :pool(pool_new_libc(&_pool, "catch")),
     client_fs(event_loop)
{
    UniqueSocketDescriptor client_socket, server_socket;
    if (!UniqueSocketDescriptor::CreateSocketPair(AF_LOCAL, SOCK_STREAM, 0,
                                                  client_socket, server_socket))
        throw MakeErrno("socketpair() failed");

    connection = http_server_connection_new(pool, event_loop,
                                            std::move(server_socket),
                                            FdType::FD_SOCKET,
                                            nullptr,
                                            nullptr, nullptr,
                                            true, *this);

    client_fs.InitDummy(client_socket.Release(), FdType::FD_SOCKET);

    pool_unref(pool);
}

static std::exception_ptr
catch_callback(std::exception_ptr ep, gcc_unused void *ctx) noexcept
{
    PrintException(ep);
    return {};
}

void
Instance::HandleHttpRequest(HttpServerRequest &request,
                            CancellablePointer &cancel_ptr) noexcept
{
    request_handler(request, cancel_ptr);
}

void
Instance::HttpConnectionError(std::exception_ptr e) noexcept
{
    connection = nullptr;

    PrintException(e);
}

void
Instance::HttpConnectionClosed() noexcept
{
    connection = nullptr;
}

static void
test_catch(EventLoop &event_loop, struct pool *_pool)
{
    Instance instance(*_pool, event_loop);

    instance.SetRequestHandler([&instance](HttpServerRequest &request, CancellablePointer &) noexcept {
        http_server_response(&request, HTTP_STATUS_OK, HttpHeaders(request.pool),
                             istream_catch_new(&request.pool,
                                               std::move(request.body),
                                               catch_callback, nullptr));
        instance.CloseConnection();
    });

    Client client;

    client.SendRequest(instance,
                       HTTP_METHOD_POST, "/", HttpHeaders(instance.GetPool()),
                       istream_head_new(instance.GetPool(),
                                        istream_block_new(instance.GetPool()),
                                        1024, true));

    while (!client.IsClientDone())
        event_loop.LoopOnce();

    instance.CloseClientSocket();
    client.RethrowResponseError();

    event_loop.Dispatch();
}

int
main(int argc, char **argv) noexcept
try {
    (void)argc;
    (void)argv;

    direct_global_init();
    const ScopeFbPoolInit fb_pool_init;
    PInstance instance;

    test_catch(instance.event_loop, instance.root_pool);
} catch (...) {
    PrintException(std::current_exception());
    return EXIT_FAILURE;
}
<commit_msg>test/t_http_server: rename Instance to Server<commit_after>/*
 * Copyright 2007-2017 Content Management AG
 * All rights reserved.
 *
 * author: Max Kellermann <mk@cm4all.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the
 * distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "http_server/http_server.hxx"
#include "http_server/Request.hxx"
#include "http_server/Handler.hxx"
#include "http_client.hxx"
#include "http_headers.hxx"
#include "HttpResponseHandler.hxx"
#include "lease.hxx"
#include "direct.hxx"
#include "PInstance.hxx"
#include "pool/pool.hxx"
#include "istream/UnusedPtr.hxx"
#include "istream/HeadIstream.hxx"
#include "istream/BlockIstream.hxx"
#include "istream/istream_catch.hxx"
#include "istream/Sink.hxx"
#include "fb_pool.hxx"
#include "fs/FilteredSocket.hxx"
#include "net/UniqueSocketDescriptor.hxx"
#include "system/Error.hxx"
#include "util/Cancellable.hxx"
#include "util/PrintException.hxx"

#include <functional>

#include <stdio.h>
#include <stdlib.h>

class Server final
    : HttpServerConnectionHandler, Lease, BufferedSocketHandler
{
    struct pool *pool;

    HttpServerConnection *connection = nullptr;

    std::function<void(HttpServerRequest &request,
                       CancellablePointer &cancel_ptr)> request_handler;

    FilteredSocket client_fs;

    bool client_fs_released = false;

public:
    Server(struct pool &_pool, EventLoop &event_loop);

    ~Server() noexcept {
        CheckCloseConnection();
    }

    struct pool &GetPool() noexcept {
        return *pool;
    }

    template<typename T>
    void SetRequestHandler(T &&handler) noexcept {
        request_handler = std::forward<T>(handler);
    }

    void CloseConnection() noexcept {
        http_server_connection_close(connection);
        connection = nullptr;
    }

    void CheckCloseConnection() noexcept {
        if (connection != nullptr)
            CloseConnection();
    }

    void SendRequest(http_method_t method, const char *uri,
                     HttpHeaders &&headers,
                     UnusedIstreamPtr body, bool expect_100,
                     HttpResponseHandler &handler,
                     CancellablePointer &cancel_ptr) noexcept {
        http_client_request(*pool, client_fs, *this,
                            "foo",
                            method, uri, std::move(headers),
                            std::move(body), expect_100,
                            handler, cancel_ptr);
    }

    void CloseClientSocket() noexcept {
        if (client_fs.IsValid() && client_fs.IsConnected()) {
            client_fs.Close();
            client_fs.Destroy();
        }
    }

private:
    /* virtual methods from class HttpServerConnectionHandler */
    void HandleHttpRequest(HttpServerRequest &request,
                           CancellablePointer &cancel_ptr) noexcept override;

    void LogHttpRequest(HttpServerRequest &,
                        http_status_t, int64_t,
                        uint64_t, uint64_t) noexcept override {}

    void HttpConnectionError(std::exception_ptr e) noexcept override;
    void HttpConnectionClosed() noexcept override;

    /* virtual methods from class Lease */
    void ReleaseLease(bool reuse) noexcept override {
        client_fs_released = true;

        if (reuse && client_fs.IsValid() && client_fs.IsConnected()) {
            client_fs.Reinit(Event::Duration(-1), Event::Duration(-1), *this);
            client_fs.UnscheduleWrite();
        } else {
            CloseClientSocket();
        }
    }

    /* virtual methods from class BufferedSocketHandler */
    BufferedResult OnBufferedData() override {
        fprintf(stderr, "unexpected data in idle TCP connection");
        CloseClientSocket();
        return BufferedResult::CLOSED;
    }

    bool OnBufferedClosed() noexcept override {
        CloseClientSocket();
        return false;
    }

    gcc_noreturn
    bool OnBufferedWrite() override {
        /* should never be reached because we never schedule
           writing */
        gcc_unreachable();
    }

    void OnBufferedError(std::exception_ptr e) noexcept override {
        PrintException(e);
        CloseClientSocket();
    }
};

class Client final : HttpResponseHandler, IstreamSink {
    CancellablePointer client_cancel_ptr;

    std::exception_ptr response_error;
    std::string response_body;
    http_status_t status{};

    bool response_eof = false;

public:
    void SendRequest(Server &server,
                     http_method_t method, const char *uri,
                     HttpHeaders &&headers,
                     UnusedIstreamPtr body, bool expect_100=false) noexcept {
        server.SendRequest(method, uri, std::move(headers),
                             std::move(body), expect_100,
                             *this, client_cancel_ptr);
    }

    bool IsClientDone() const noexcept {
        return response_error || response_eof;
    }

    void RethrowResponseError() const {
        if (response_error)
            std::rethrow_exception(response_error);
    }

private:
    /* virtual methods from class HttpResponseHandler */
    void OnHttpResponse(http_status_t _status, StringMap &&headers,
                        UnusedIstreamPtr body) noexcept override {
        status = _status;

        (void)headers;

        IstreamSink::SetInput(std::move(body));
        input.Read();
    }

    void OnHttpError(std::exception_ptr ep) noexcept override {
        response_error = std::move(ep);
    }

    /* virtual methods from class IstreamHandler */

    size_t OnData(const void *data, size_t length) override {
        response_body.append((const char *)data, length);
        return length;
    }

    void OnEof() noexcept override {
        IstreamSink::ClearInput();
        response_eof = true;
    }

    void OnError(std::exception_ptr ep) noexcept override {
        IstreamSink::ClearInput();
        response_error = std::move(ep);
    }
};

Server::Server(struct pool &_pool, EventLoop &event_loop)
    :pool(pool_new_libc(&_pool, "catch")),
     client_fs(event_loop)
{
    UniqueSocketDescriptor client_socket, server_socket;
    if (!UniqueSocketDescriptor::CreateSocketPair(AF_LOCAL, SOCK_STREAM, 0,
                                                  client_socket, server_socket))
        throw MakeErrno("socketpair() failed");

    connection = http_server_connection_new(pool, event_loop,
                                            std::move(server_socket),
                                            FdType::FD_SOCKET,
                                            nullptr,
                                            nullptr, nullptr,
                                            true, *this);

    client_fs.InitDummy(client_socket.Release(), FdType::FD_SOCKET);

    pool_unref(pool);
}

static std::exception_ptr
catch_callback(std::exception_ptr ep, gcc_unused void *ctx) noexcept
{
    PrintException(ep);
    return {};
}

void
Server::HandleHttpRequest(HttpServerRequest &request,
                            CancellablePointer &cancel_ptr) noexcept
{
    request_handler(request, cancel_ptr);
}

void
Server::HttpConnectionError(std::exception_ptr e) noexcept
{
    connection = nullptr;

    PrintException(e);
}

void
Server::HttpConnectionClosed() noexcept
{
    connection = nullptr;
}

static void
test_catch(EventLoop &event_loop, struct pool *_pool)
{
    Server server(*_pool, event_loop);

    server.SetRequestHandler([&server](HttpServerRequest &request, CancellablePointer &) noexcept {
        http_server_response(&request, HTTP_STATUS_OK, HttpHeaders(request.pool),
                             istream_catch_new(&request.pool,
                                               std::move(request.body),
                                               catch_callback, nullptr));
        server.CloseConnection();
    });

    Client client;

    client.SendRequest(server,
                       HTTP_METHOD_POST, "/", HttpHeaders(server.GetPool()),
                       istream_head_new(server.GetPool(),
                                        istream_block_new(server.GetPool()),
                                        1024, true));

    while (!client.IsClientDone())
        event_loop.LoopOnce();

    server.CloseClientSocket();
    client.RethrowResponseError();

    event_loop.Dispatch();
}

int
main(int argc, char **argv) noexcept
try {
    (void)argc;
    (void)argv;

    direct_global_init();
    const ScopeFbPoolInit fb_pool_init;
    PInstance instance;

    test_catch(instance.event_loop, instance.root_pool);
} catch (...) {
    PrintException(std::current_exception());
    return EXIT_FAILURE;
}
<|endoftext|>


<commit_before>#include <stan/math/prim/meta.hpp>
#include <test/unit/math/prim/fun/expect_matrix_eq.hpp>
#include <gtest/gtest.h>

TEST(MathMetaPrim, ref_type_non_eigen) {
  using stan::ref_type_t;
  std::vector<int> a{1, 2, 3};
  ref_type_t<std::vector<int>> a_ref1 = a;
  ref_type_t<std::vector<int>&> a_ref2 = a;
  ref_type_t<std::vector<int>&&> a_ref3 = std::vector<int>{1, 2, 3};

  double b = 3;
  ref_type_t<double> b_ref1 = b;
  ref_type_t<double&> b_ref2 = b;
  ref_type_t<double&&> b_ref3 = 3;

  const std::vector<double> c{0.5, 4, 0.7};
  ref_type_t<const std::vector<double>> c_ref1 = c;
  ref_type_t<const std::vector<double>&> c_ref2 = c;

  expect_std_vector_eq(a_ref1, a);
  expect_std_vector_eq(a_ref2, a);
  expect_std_vector_eq(a_ref3, a);
  EXPECT_EQ(b_ref1, b);
  EXPECT_EQ(b_ref2, b);
  EXPECT_EQ(b_ref3, b);
  expect_std_vector_eq(c_ref1, c);
  expect_std_vector_eq(c_ref2, c);
  EXPECT_TRUE(std::is_lvalue_reference<ref_type_t<double>>::value);
  EXPECT_TRUE(std::is_lvalue_reference<ref_type_t<double&>>::value);
  EXPECT_FALSE(std::is_reference<ref_type_t<double&&>>::value);
  EXPECT_TRUE(std::is_lvalue_reference<ref_type_t<const std::vector<double>>>::value);
  EXPECT_TRUE(std::is_lvalue_reference<ref_type_t<const std::vector<double>&>>::value);
  EXPECT_FALSE(std::is_reference<ref_type_t<const std::vector<double>&&>>::value);
}

TEST(MathMetaPrim, ref_type_eigen_directly_accessible) {
  using stan::ref_type_t;
  Eigen::MatrixXd a(3, 3);
  a << 1, 2, 3, 4, 5, 6, 7, 8, 9;
  Eigen::MatrixXd a2 = a;
  ref_type_t<Eigen::MatrixXd> a_ref1 = a;
  ref_type_t<Eigen::MatrixXd&> a_ref2 = a;
  ref_type_t<Eigen::MatrixXd&&> a_ref3 = std::move(a2);

  auto b = a.block(1, 0, 2, 2);
  ref_type_t<decltype(b)> b_ref1 = b;
  ref_type_t<decltype(b)&> b_ref2 = b;
  ref_type_t<decltype(b)&&> b_ref3 = a.block(1, 0, 2, 2);

  Eigen::Ref<Eigen::MatrixXd> c = a;
  Eigen::Ref<Eigen::MatrixXd> c2 = a;
  ref_type_t<Eigen::Ref<Eigen::MatrixXd>> c_ref1 = c;
  ref_type_t<Eigen::Ref<Eigen::MatrixXd>&> c_ref2 = c;
  ref_type_t<Eigen::Ref<Eigen::MatrixXd>&&> c_ref3 = std::move(c2);

  expect_matrix_eq(a_ref1, a);
  expect_matrix_eq(a_ref2, a);
  expect_matrix_eq(a_ref3, a);

  expect_matrix_eq(b_ref1, b);
  expect_matrix_eq(b_ref2, b);
  expect_matrix_eq(b_ref3, b);

  expect_matrix_eq(c_ref1, c);
  expect_matrix_eq(c_ref2, c);
  expect_matrix_eq(c_ref3, c);
  EXPECT_TRUE((std::is_same<decltype(a), ref_type_t<decltype(a)&&>>::value));
  EXPECT_TRUE((std::is_same<decltype(b), ref_type_t<decltype(b)&&>>::value));
  EXPECT_TRUE((std::is_same<decltype(c), ref_type_t<decltype(c)&&>>::value));
  EXPECT_TRUE(std::is_lvalue_reference<ref_type_t<Eigen::MatrixXd>>::value);
  EXPECT_TRUE(std::is_lvalue_reference<ref_type_t<Eigen::MatrixXd&>>::value);
  EXPECT_FALSE(std::is_reference<ref_type_t<Eigen::MatrixXd&&>>::value);
}

TEST(MathMetaPrim, ref_type_eigen_expression) {
  using stan::plain_type_t;
  using stan::ref_type_t;
  Eigen::MatrixXd m(3, 3);
  m << 1, 2, 3, 4, 5, 6, 7, 8, 9;
  auto a = m * 3;
  ref_type_t<decltype(a)> a_ref1 = a;
  ref_type_t<decltype(a)&> a_ref2 = a;
  ref_type_t<decltype(a)&&> a_ref3 = m * 3;

  Eigen::MatrixXd a_eval = a;
  expect_matrix_eq(a_ref1, a_eval);
  expect_matrix_eq(a_ref2, a_eval);
  expect_matrix_eq(a_ref3, a_eval);

  EXPECT_TRUE((std::is_same<plain_type_t<decltype(a)>,
                            ref_type_t<decltype(a)>>::value));
  EXPECT_TRUE((std::is_same<plain_type_t<decltype(a)>,
                            ref_type_t<decltype(a)&>>::value));
  EXPECT_TRUE((std::is_same<plain_type_t<decltype(a)>,
                            ref_type_t<decltype(a)&&>>::value));
}
<commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2 (tags/RELEASE_600/final)<commit_after>#include <stan/math/prim/meta.hpp>
#include <test/unit/math/prim/fun/expect_matrix_eq.hpp>
#include <gtest/gtest.h>

TEST(MathMetaPrim, ref_type_non_eigen) {
  using stan::ref_type_t;
  std::vector<int> a{1, 2, 3};
  ref_type_t<std::vector<int>> a_ref1 = a;
  ref_type_t<std::vector<int>&> a_ref2 = a;
  ref_type_t<std::vector<int>&&> a_ref3 = std::vector<int>{1, 2, 3};

  double b = 3;
  ref_type_t<double> b_ref1 = b;
  ref_type_t<double&> b_ref2 = b;
  ref_type_t<double&&> b_ref3 = 3;

  const std::vector<double> c{0.5, 4, 0.7};
  ref_type_t<const std::vector<double>> c_ref1 = c;
  ref_type_t<const std::vector<double>&> c_ref2 = c;

  expect_std_vector_eq(a_ref1, a);
  expect_std_vector_eq(a_ref2, a);
  expect_std_vector_eq(a_ref3, a);
  EXPECT_EQ(b_ref1, b);
  EXPECT_EQ(b_ref2, b);
  EXPECT_EQ(b_ref3, b);
  expect_std_vector_eq(c_ref1, c);
  expect_std_vector_eq(c_ref2, c);
  EXPECT_TRUE(std::is_lvalue_reference<ref_type_t<double>>::value);
  EXPECT_TRUE(std::is_lvalue_reference<ref_type_t<double&>>::value);
  EXPECT_FALSE(std::is_reference<ref_type_t<double&&>>::value);
  EXPECT_TRUE(
      std::is_lvalue_reference<ref_type_t<const std::vector<double>>>::value);
  EXPECT_TRUE(
      std::is_lvalue_reference<ref_type_t<const std::vector<double>&>>::value);
  EXPECT_FALSE(
      std::is_reference<ref_type_t<const std::vector<double>&&>>::value);
}

TEST(MathMetaPrim, ref_type_eigen_directly_accessible) {
  using stan::ref_type_t;
  Eigen::MatrixXd a(3, 3);
  a << 1, 2, 3, 4, 5, 6, 7, 8, 9;
  Eigen::MatrixXd a2 = a;
  ref_type_t<Eigen::MatrixXd> a_ref1 = a;
  ref_type_t<Eigen::MatrixXd&> a_ref2 = a;
  ref_type_t<Eigen::MatrixXd&&> a_ref3 = std::move(a2);

  auto b = a.block(1, 0, 2, 2);
  ref_type_t<decltype(b)> b_ref1 = b;
  ref_type_t<decltype(b)&> b_ref2 = b;
  ref_type_t<decltype(b)&&> b_ref3 = a.block(1, 0, 2, 2);

  Eigen::Ref<Eigen::MatrixXd> c = a;
  Eigen::Ref<Eigen::MatrixXd> c2 = a;
  ref_type_t<Eigen::Ref<Eigen::MatrixXd>> c_ref1 = c;
  ref_type_t<Eigen::Ref<Eigen::MatrixXd>&> c_ref2 = c;
  ref_type_t<Eigen::Ref<Eigen::MatrixXd>&&> c_ref3 = std::move(c2);

  expect_matrix_eq(a_ref1, a);
  expect_matrix_eq(a_ref2, a);
  expect_matrix_eq(a_ref3, a);

  expect_matrix_eq(b_ref1, b);
  expect_matrix_eq(b_ref2, b);
  expect_matrix_eq(b_ref3, b);

  expect_matrix_eq(c_ref1, c);
  expect_matrix_eq(c_ref2, c);
  expect_matrix_eq(c_ref3, c);
  EXPECT_TRUE((std::is_same<decltype(a), ref_type_t<decltype(a)&&>>::value));
  EXPECT_TRUE((std::is_same<decltype(b), ref_type_t<decltype(b)&&>>::value));
  EXPECT_TRUE((std::is_same<decltype(c), ref_type_t<decltype(c)&&>>::value));
  EXPECT_TRUE(std::is_lvalue_reference<ref_type_t<Eigen::MatrixXd>>::value);
  EXPECT_TRUE(std::is_lvalue_reference<ref_type_t<Eigen::MatrixXd&>>::value);
  EXPECT_FALSE(std::is_reference<ref_type_t<Eigen::MatrixXd&&>>::value);
}

TEST(MathMetaPrim, ref_type_eigen_expression) {
  using stan::plain_type_t;
  using stan::ref_type_t;
  Eigen::MatrixXd m(3, 3);
  m << 1, 2, 3, 4, 5, 6, 7, 8, 9;
  auto a = m * 3;
  ref_type_t<decltype(a)> a_ref1 = a;
  ref_type_t<decltype(a)&> a_ref2 = a;
  ref_type_t<decltype(a)&&> a_ref3 = m * 3;

  Eigen::MatrixXd a_eval = a;
  expect_matrix_eq(a_ref1, a_eval);
  expect_matrix_eq(a_ref2, a_eval);
  expect_matrix_eq(a_ref3, a_eval);

  EXPECT_TRUE((
      std::is_same<plain_type_t<decltype(a)>, ref_type_t<decltype(a)>>::value));
  EXPECT_TRUE((std::is_same<plain_type_t<decltype(a)>,
                            ref_type_t<decltype(a)&>>::value));
  EXPECT_TRUE((std::is_same<plain_type_t<decltype(a)>,
                            ref_type_t<decltype(a)&&>>::value));
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: xmlcnitm.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2004-01-20 13:18:39 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _COM_SUN_STAR_XML_ATTRIBUTEDATA_HPP_
#include <com/sun/star/xml/AttributeData.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif

#ifndef _XMLOFF_XMLCNIMP_HXX
#include <xmloff/xmlcnimp.hxx>
#endif
#ifndef _XMLOFF_XMLCNITM_HXX
#include <xmloff/unoatrcn.hxx>
#endif
#include "xmlcnitm.hxx"

using namespace rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::xml;

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

TYPEINIT1(SvXMLAttrContainerItem, SfxPoolItem);

SvXMLAttrContainerItem::SvXMLAttrContainerItem( USHORT nWhich ) :
    SfxPoolItem( nWhich )
{
    pImpl = new SvXMLAttrContainerData;
}

SvXMLAttrContainerItem::SvXMLAttrContainerItem(
                                        const SvXMLAttrContainerItem& rItem ) :
    SfxPoolItem( rItem )
{
    pImpl = new SvXMLAttrContainerData( *rItem.pImpl );
}

SvXMLAttrContainerItem::~SvXMLAttrContainerItem()
{
    delete pImpl;
}

int SvXMLAttrContainerItem::operator==( const SfxPoolItem& rItem ) const
{
    DBG_ASSERT( rItem.ISA(SvXMLAttrContainerItem),
               "SvXMLAttrContainerItem::operator ==(): Bad type");
    return *pImpl == *((const SvXMLAttrContainerItem&)rItem).pImpl;
}

int SvXMLAttrContainerItem::Compare( const SfxPoolItem &rWith ) const
{
    DBG_ASSERT( !this, "not yet implemented" );

    return 0;
}

SfxItemPresentation SvXMLAttrContainerItem::GetPresentation(
                    SfxItemPresentation ePresentation,
                    SfxMapUnit eCoreMetric,
                    SfxMapUnit ePresentationMetric,
                    XubString &rText,
                    const IntlWrapper *pIntlWrapper ) const
{
    return SFX_ITEM_PRESENTATION_NONE;
}

USHORT SvXMLAttrContainerItem::GetVersion( USHORT nFileFormatVersion ) const
{
    // This item should never be stored
    return USHRT_MAX;
}

BOOL  SvXMLAttrContainerItem::QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId ) const
{
    Reference<XNameContainer> xContainer =
        new SvUnoAttributeContainer( new SvXMLAttrContainerData( *pImpl ) );

    rVal.setValue( &xContainer, ::getCppuType((Reference<XNameContainer>*)0) );
    return TRUE;
}
BOOL SvXMLAttrContainerItem::PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId )
{
    Reference<XInterface> xRef;
    SvUnoAttributeContainer* pContainer = NULL;

    if( rVal.getValue() != NULL && rVal.getValueType().getTypeClass() == TypeClass_INTERFACE )
    {
        xRef = *(Reference<XInterface>*)rVal.getValue();
        Reference<XUnoTunnel> xTunnel(xRef, UNO_QUERY);
        if( xTunnel.is() )
            pContainer = (SvUnoAttributeContainer*)xTunnel->getSomething(SvUnoAttributeContainer::getUnoTunnelId());
    }

    if( pContainer )
    {
        delete pImpl;
        pImpl = new SvXMLAttrContainerData( * pContainer->GetContainerImpl() );
    }
    else
    {
        SvXMLAttrContainerData* pNewImpl = new SvXMLAttrContainerData;

        try
        {
            Reference<XNameContainer> xContainer( xRef, UNO_QUERY );
            if( !xContainer.is() )
                return FALSE;

            const Sequence< OUString > aNameSequence( xContainer->getElementNames() );
            const OUString* pNames = aNameSequence.getConstArray();
            const INT32 nCount = aNameSequence.getLength();
            Any aAny;
            AttributeData* pData;
            INT32 nAttr;

            for( nAttr = 0; nAttr < nCount; nAttr++ )
            {
                const OUString aName( *pNames++ );

                aAny = xContainer->getByName( aName );
                if( aAny.getValue() == NULL || aAny.getValueType() != ::getCppuType((AttributeData*)0) )
                    return FALSE;

                pData = (AttributeData*)aAny.getValue();
                USHORT pos = aName.indexOf( sal_Unicode(':') );
                if( pos != -1 )
                {
                    const OUString aPrefix( aName.copy( 0, pos ));
                    const OUString aLName( aName.copy( pos+1 ));

                    if( pData->Namespace.getLength() == 0 )
                    {
                        if( !pNewImpl->AddAttr( aPrefix, aLName, pData->Value ) )
                            break;
                    }
                    else
                    {
                        if( !pNewImpl->AddAttr( aPrefix, pData->Namespace, aLName, pData->Value ) )
                            break;
                    }
                }
                else
                {
                    if( !pNewImpl->AddAttr( aName, pData->Value ) )
                        break;
                }
            }

            if( nAttr == nCount )
            {
                delete pImpl;
                pImpl = pNewImpl;
            }
            else
            {
                delete pNewImpl;
                return FALSE;
            }
        }
        catch(...)
        {
            delete pNewImpl;
            return FALSE;
        }
    }
    return TRUE;
}

BOOL SvXMLAttrContainerItem::AddAttr( const OUString& rLName,
                                        const OUString& rValue )
{
    return pImpl->AddAttr( rLName, rValue );
}

BOOL SvXMLAttrContainerItem::AddAttr( const OUString& rPrefix,
          const OUString& rNamespace, const OUString& rLName,
          const OUString& rValue )
{
    return pImpl->AddAttr( rPrefix, rNamespace, rLName, rValue );
}

USHORT SvXMLAttrContainerItem::GetAttrCount() const
{
    return (USHORT)pImpl->GetAttrCount();
}

OUString SvXMLAttrContainerItem::GetAttrNamespace( USHORT i ) const
{
    return pImpl->GetAttrNamespace( i );
}

OUString SvXMLAttrContainerItem::GetAttrPrefix( USHORT i ) const
{
    return pImpl->GetAttrPrefix( i );
}

const OUString& SvXMLAttrContainerItem::GetAttrLName( USHORT i ) const
{
    return pImpl->GetAttrLName( i );
}

const OUString& SvXMLAttrContainerItem::GetAttrValue( USHORT i ) const
{
    return pImpl->GetAttrValue( i );
}

USHORT SvXMLAttrContainerItem::GetFirstNamespaceIndex() const
{
    return pImpl->GetFirstNamespaceIndex();
}

USHORT SvXMLAttrContainerItem::GetNextNamespaceIndex( USHORT nIdx ) const
{
    return pImpl->GetNextNamespaceIndex( nIdx );
}

const OUString& SvXMLAttrContainerItem::GetNamespace( USHORT i ) const
{
    return pImpl->GetNamespace( i );
}

const OUString& SvXMLAttrContainerItem::GetPrefix( USHORT i ) const
{
    return pImpl->GetPrefix( i );
}

<commit_msg>INTEGRATION: CWS ooo19126 (1.4.1054); FILE MERGED 2005/09/05 14:25:51 rt 1.4.1054.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xmlcnitm.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 23:42:11 $
 *
 *  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 _COM_SUN_STAR_XML_ATTRIBUTEDATA_HPP_
#include <com/sun/star/xml/AttributeData.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif

#ifndef _XMLOFF_XMLCNIMP_HXX
#include <xmloff/xmlcnimp.hxx>
#endif
#ifndef _XMLOFF_XMLCNITM_HXX
#include <xmloff/unoatrcn.hxx>
#endif
#include "xmlcnitm.hxx"

using namespace rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::xml;

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

TYPEINIT1(SvXMLAttrContainerItem, SfxPoolItem);

SvXMLAttrContainerItem::SvXMLAttrContainerItem( USHORT nWhich ) :
    SfxPoolItem( nWhich )
{
    pImpl = new SvXMLAttrContainerData;
}

SvXMLAttrContainerItem::SvXMLAttrContainerItem(
                                        const SvXMLAttrContainerItem& rItem ) :
    SfxPoolItem( rItem )
{
    pImpl = new SvXMLAttrContainerData( *rItem.pImpl );
}

SvXMLAttrContainerItem::~SvXMLAttrContainerItem()
{
    delete pImpl;
}

int SvXMLAttrContainerItem::operator==( const SfxPoolItem& rItem ) const
{
    DBG_ASSERT( rItem.ISA(SvXMLAttrContainerItem),
               "SvXMLAttrContainerItem::operator ==(): Bad type");
    return *pImpl == *((const SvXMLAttrContainerItem&)rItem).pImpl;
}

int SvXMLAttrContainerItem::Compare( const SfxPoolItem &rWith ) const
{
    DBG_ASSERT( !this, "not yet implemented" );

    return 0;
}

SfxItemPresentation SvXMLAttrContainerItem::GetPresentation(
                    SfxItemPresentation ePresentation,
                    SfxMapUnit eCoreMetric,
                    SfxMapUnit ePresentationMetric,
                    XubString &rText,
                    const IntlWrapper *pIntlWrapper ) const
{
    return SFX_ITEM_PRESENTATION_NONE;
}

USHORT SvXMLAttrContainerItem::GetVersion( USHORT nFileFormatVersion ) const
{
    // This item should never be stored
    return USHRT_MAX;
}

BOOL  SvXMLAttrContainerItem::QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId ) const
{
    Reference<XNameContainer> xContainer =
        new SvUnoAttributeContainer( new SvXMLAttrContainerData( *pImpl ) );

    rVal.setValue( &xContainer, ::getCppuType((Reference<XNameContainer>*)0) );
    return TRUE;
}
BOOL SvXMLAttrContainerItem::PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId )
{
    Reference<XInterface> xRef;
    SvUnoAttributeContainer* pContainer = NULL;

    if( rVal.getValue() != NULL && rVal.getValueType().getTypeClass() == TypeClass_INTERFACE )
    {
        xRef = *(Reference<XInterface>*)rVal.getValue();
        Reference<XUnoTunnel> xTunnel(xRef, UNO_QUERY);
        if( xTunnel.is() )
            pContainer = (SvUnoAttributeContainer*)xTunnel->getSomething(SvUnoAttributeContainer::getUnoTunnelId());
    }

    if( pContainer )
    {
        delete pImpl;
        pImpl = new SvXMLAttrContainerData( * pContainer->GetContainerImpl() );
    }
    else
    {
        SvXMLAttrContainerData* pNewImpl = new SvXMLAttrContainerData;

        try
        {
            Reference<XNameContainer> xContainer( xRef, UNO_QUERY );
            if( !xContainer.is() )
                return FALSE;

            const Sequence< OUString > aNameSequence( xContainer->getElementNames() );
            const OUString* pNames = aNameSequence.getConstArray();
            const INT32 nCount = aNameSequence.getLength();
            Any aAny;
            AttributeData* pData;
            INT32 nAttr;

            for( nAttr = 0; nAttr < nCount; nAttr++ )
            {
                const OUString aName( *pNames++ );

                aAny = xContainer->getByName( aName );
                if( aAny.getValue() == NULL || aAny.getValueType() != ::getCppuType((AttributeData*)0) )
                    return FALSE;

                pData = (AttributeData*)aAny.getValue();
                USHORT pos = aName.indexOf( sal_Unicode(':') );
                if( pos != -1 )
                {
                    const OUString aPrefix( aName.copy( 0, pos ));
                    const OUString aLName( aName.copy( pos+1 ));

                    if( pData->Namespace.getLength() == 0 )
                    {
                        if( !pNewImpl->AddAttr( aPrefix, aLName, pData->Value ) )
                            break;
                    }
                    else
                    {
                        if( !pNewImpl->AddAttr( aPrefix, pData->Namespace, aLName, pData->Value ) )
                            break;
                    }
                }
                else
                {
                    if( !pNewImpl->AddAttr( aName, pData->Value ) )
                        break;
                }
            }

            if( nAttr == nCount )
            {
                delete pImpl;
                pImpl = pNewImpl;
            }
            else
            {
                delete pNewImpl;
                return FALSE;
            }
        }
        catch(...)
        {
            delete pNewImpl;
            return FALSE;
        }
    }
    return TRUE;
}

BOOL SvXMLAttrContainerItem::AddAttr( const OUString& rLName,
                                        const OUString& rValue )
{
    return pImpl->AddAttr( rLName, rValue );
}

BOOL SvXMLAttrContainerItem::AddAttr( const OUString& rPrefix,
          const OUString& rNamespace, const OUString& rLName,
          const OUString& rValue )
{
    return pImpl->AddAttr( rPrefix, rNamespace, rLName, rValue );
}

USHORT SvXMLAttrContainerItem::GetAttrCount() const
{
    return (USHORT)pImpl->GetAttrCount();
}

OUString SvXMLAttrContainerItem::GetAttrNamespace( USHORT i ) const
{
    return pImpl->GetAttrNamespace( i );
}

OUString SvXMLAttrContainerItem::GetAttrPrefix( USHORT i ) const
{
    return pImpl->GetAttrPrefix( i );
}

const OUString& SvXMLAttrContainerItem::GetAttrLName( USHORT i ) const
{
    return pImpl->GetAttrLName( i );
}

const OUString& SvXMLAttrContainerItem::GetAttrValue( USHORT i ) const
{
    return pImpl->GetAttrValue( i );
}

USHORT SvXMLAttrContainerItem::GetFirstNamespaceIndex() const
{
    return pImpl->GetFirstNamespaceIndex();
}

USHORT SvXMLAttrContainerItem::GetNextNamespaceIndex( USHORT nIdx ) const
{
    return pImpl->GetNextNamespaceIndex( nIdx );
}

const OUString& SvXMLAttrContainerItem::GetNamespace( USHORT i ) const
{
    return pImpl->GetNamespace( i );
}

const OUString& SvXMLAttrContainerItem::GetPrefix( USHORT i ) const
{
    return pImpl->GetPrefix( i );
}

<|endoftext|>