text stringlengths 54 60.6k |
|---|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon
*
* 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
*
*****************************************************************************/
//$Id$
#include <boost/python.hpp>
#include <boost/python/implicit.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
#include <mapnik/rule.hpp>
#include <mapnik/filter_factory.hpp>
using namespace boost::python;
using mapnik::rule_type;
using mapnik::filter;
using mapnik::filter_ptr;
using mapnik::filter_factory;
using mapnik::Feature;
using mapnik::point_symbolizer;
using mapnik::line_symbolizer;
using mapnik::line_pattern_symbolizer;
using mapnik::polygon_symbolizer;
using mapnik::polygon_pattern_symbolizer;
using mapnik::raster_symbolizer;
using mapnik::shield_symbolizer;
using mapnik::text_symbolizer;
using mapnik::building_symbolizer;
using mapnik::symbolizer;
using mapnik::symbolizers;
struct rule_pickle_suite : boost::python::pickle_suite
{
static boost::python::tuple
getinitargs(const rule_type& r)
{
return boost::python::make_tuple(r.get_name(),r.get_title(),r.get_min_scale(),r.get_max_scale());
}
static boost::python::tuple
getstate(const rule_type& r)
{
boost::python::list syms;
symbolizers::const_iterator it = r.begin();
symbolizers::const_iterator end = r.end();
for (; it != end; ++it)
{
syms.append( *it );
}
// Here the filter string is used rather than the actual Filter object
// Need to look into how to get the Filter object
std::string filter_expr = r.get_filter()->to_string();
return boost::python::make_tuple(r.get_abstract(),filter_expr,r.has_else_filter(),syms);
}
static void
setstate (rule_type& r, boost::python::tuple state)
{
using namespace boost::python;
if (len(state) != 4)
{
PyErr_SetObject(PyExc_ValueError,
("expected 4-item tuple in call to __setstate__; got %s"
% state).ptr()
);
throw_error_already_set();
}
if (state[0])
{
r.set_title(extract<std::string>(state[0]));
}
if (state[1])
{
std::string filter_expr=extract<std::string>(state[1]);
r.set_filter(mapnik::create_filter(filter_expr,"utf8"));
}
if (state[2])
{
r.set_else(true);
}
boost::python::list syms=extract<boost::python::list>(state[3]);
for (int i=0;i<len(syms);++i)
{
r.append(extract<symbolizer>(syms[i]));
}
}
};
void export_rule()
{
implicitly_convertible<point_symbolizer,symbolizer>();
implicitly_convertible<line_symbolizer,symbolizer>();
implicitly_convertible<line_pattern_symbolizer,symbolizer>();
implicitly_convertible<polygon_symbolizer,symbolizer>();
implicitly_convertible<building_symbolizer,symbolizer>();
implicitly_convertible<polygon_pattern_symbolizer,symbolizer>();
implicitly_convertible<raster_symbolizer,symbolizer>();
implicitly_convertible<shield_symbolizer,symbolizer>();
implicitly_convertible<text_symbolizer,symbolizer>();
class_<symbolizers>("Symbolizers",init<>("TODO"))
.def(vector_indexing_suite<symbolizers>())
;
class_<rule_type>("Rule",init<>("default constructor"))
.def(init<std::string const&,
boost::python::optional<std::string const&,double,double> >())
.def_pickle(rule_pickle_suite()
)
.add_property("name",make_function
(&rule_type::get_name,
return_value_policy<copy_const_reference>()),
&rule_type::set_name)
.add_property("title",make_function
(&rule_type::get_title,return_value_policy<copy_const_reference>()),
&rule_type::set_title)
.add_property("abstract",make_function
(&rule_type::get_abstract,return_value_policy<copy_const_reference>()),
&rule_type::set_abstract)
.add_property("filter",make_function
(&rule_type::get_filter,return_value_policy<copy_const_reference>()),
&rule_type::set_filter)
.add_property("min_scale",&rule_type::get_min_scale,&rule_type::set_min_scale)
.add_property("max_scale",&rule_type::get_max_scale,&rule_type::set_max_scale)
.def("set_else",&rule_type::set_else)
.def("has_else",&rule_type::has_else_filter)
.def("active",&rule_type::active)
.add_property("symbols",make_function
(&rule_type::get_symbolizers,return_value_policy<reference_existing_object>()))
;
}
<commit_msg>move the boost::python namespace back to original location<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko, Jean-Francois Doyon
*
* 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
*
*****************************************************************************/
//$Id$
#include <boost/python.hpp>
#include <boost/python/implicit.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
#include <mapnik/rule.hpp>
#include <mapnik/filter_factory.hpp>
using mapnik::rule_type;
using mapnik::filter;
using mapnik::filter_ptr;
using mapnik::filter_factory;
using mapnik::Feature;
using mapnik::point_symbolizer;
using mapnik::line_symbolizer;
using mapnik::line_pattern_symbolizer;
using mapnik::polygon_symbolizer;
using mapnik::polygon_pattern_symbolizer;
using mapnik::raster_symbolizer;
using mapnik::shield_symbolizer;
using mapnik::text_symbolizer;
using mapnik::building_symbolizer;
using mapnik::symbolizer;
using mapnik::symbolizers;
struct rule_pickle_suite : boost::python::pickle_suite
{
static boost::python::tuple
getinitargs(const rule_type& r)
{
return boost::python::make_tuple(r.get_name(),r.get_title(),r.get_min_scale(),r.get_max_scale());
}
static boost::python::tuple
getstate(const rule_type& r)
{
boost::python::list syms;
symbolizers::const_iterator it = r.begin();
symbolizers::const_iterator end = r.end();
for (; it != end; ++it)
{
syms.append( *it );
}
// Here the filter string is used rather than the actual Filter object
// Need to look into how to get the Filter object
std::string filter_expr = r.get_filter()->to_string();
return boost::python::make_tuple(r.get_abstract(),filter_expr,r.has_else_filter(),syms);
}
static void
setstate (rule_type& r, boost::python::tuple state)
{
using namespace boost::python;
if (len(state) != 4)
{
PyErr_SetObject(PyExc_ValueError,
("expected 4-item tuple in call to __setstate__; got %s"
% state).ptr()
);
throw_error_already_set();
}
if (state[0])
{
r.set_title(extract<std::string>(state[0]));
}
if (state[1])
{
std::string filter_expr=extract<std::string>(state[1]);
r.set_filter(mapnik::create_filter(filter_expr,"utf8"));
}
if (state[2])
{
r.set_else(true);
}
boost::python::list syms=extract<boost::python::list>(state[3]);
for (int i=0;i<len(syms);++i)
{
r.append(extract<symbolizer>(syms[i]));
}
}
};
void export_rule()
{
using namespace boost::python;
implicitly_convertible<point_symbolizer,symbolizer>();
implicitly_convertible<line_symbolizer,symbolizer>();
implicitly_convertible<line_pattern_symbolizer,symbolizer>();
implicitly_convertible<polygon_symbolizer,symbolizer>();
implicitly_convertible<building_symbolizer,symbolizer>();
implicitly_convertible<polygon_pattern_symbolizer,symbolizer>();
implicitly_convertible<raster_symbolizer,symbolizer>();
implicitly_convertible<shield_symbolizer,symbolizer>();
implicitly_convertible<text_symbolizer,symbolizer>();
class_<symbolizers>("Symbolizers",init<>("TODO"))
.def(vector_indexing_suite<symbolizers>())
;
class_<rule_type>("Rule",init<>("default constructor"))
.def(init<std::string const&,
boost::python::optional<std::string const&,double,double> >())
.def_pickle(rule_pickle_suite()
)
.add_property("name",make_function
(&rule_type::get_name,
return_value_policy<copy_const_reference>()),
&rule_type::set_name)
.add_property("title",make_function
(&rule_type::get_title,return_value_policy<copy_const_reference>()),
&rule_type::set_title)
.add_property("abstract",make_function
(&rule_type::get_abstract,return_value_policy<copy_const_reference>()),
&rule_type::set_abstract)
.add_property("filter",make_function
(&rule_type::get_filter,return_value_policy<copy_const_reference>()),
&rule_type::set_filter)
.add_property("min_scale",&rule_type::get_min_scale,&rule_type::set_min_scale)
.add_property("max_scale",&rule_type::get_max_scale,&rule_type::set_max_scale)
.def("set_else",&rule_type::set_else)
.def("has_else",&rule_type::has_else_filter)
.def("active",&rule_type::active)
.add_property("symbols",make_function
(&rule_type::get_symbolizers,return_value_policy<reference_existing_object>()))
;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: StartMarker.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2007-07-09 11:56:33 $
*
* 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
*
************************************************************************/
#include "precompiled_reportdesign.hxx"
#ifndef RPTUI_STARTMARKER_HXX
#include "StartMarker.hxx"
#endif
#ifndef _SV_IMAGE_HXX
#include <vcl/image.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _RPTUI_DLGRESID_HRC
#include "RptResId.hrc"
#endif
#ifndef _RPTUI_MODULE_HELPER_RPT_HXX_
#include "ModuleHelper.hxx"
#endif
#ifndef RPTUI_COLORCHANGER_HXX
#include "ColorChanger.hxx"
#endif
#ifndef RPTUI_REPORT_DEFINES_HXX
#include "ReportDefines.hxx"
#endif
#ifndef RPTUI_SECTIONSWINDOW_HXX
#include "SectionsWindow.hxx"
#endif
#ifndef RTPUI_REPORTDESIGN_HELPID_HRC
#include "helpids.hrc"
#endif
#ifndef _SV_HELP_HXX
#include <vcl/help.hxx>
#endif
#include <vcl/gradient.hxx>
#include <vcl/lineinfo.hxx>
#ifndef _SFXSMPLHINT_HXX
#include <svtools/smplhint.hxx>
#endif
#define CORNER_SPACE 5
#define TEXT_WIDTH 10
#define STRT_BORDER 6
//=====================================================================
namespace rptui
{
//=====================================================================
Image* OStartMarker::s_pDefCollapsed = NULL;
Image* OStartMarker::s_pDefExpanded = NULL;
Image* OStartMarker::s_pDefCollapsedHC = NULL;
Image* OStartMarker::s_pDefExpandedHC = NULL;
oslInterlockedCount OStartMarker::s_nImageRefCount = 0;
DBG_NAME( rpt_OStartMarker )
// -----------------------------------------------------------------------------
OStartMarker::OStartMarker(OSectionsWindow* _pParent,const ::rtl::OUString& _sColorEntry)
: OColorListener(_pParent,_sColorEntry)
,m_aVRuler(this,WB_VERT)
,m_aText(this,WB_WORDBREAK)
,m_aImage(this,WB_LEFT|WB_TOP)
,m_pParent(_pParent)
,m_nCornerSize(CORNER_SPACE)
,m_bShowRuler(sal_True)
{
DBG_CTOR( rpt_OStartMarker,NULL);
SetUniqueId(HID_STARTMARKER);
osl_incrementInterlockedCount(&s_nImageRefCount);
initDefaultNodeImages();
ImplInitSettings();
m_aText.SetHelpId(HID_START_TITLE);
m_aImage.SetHelpId(HID_START_IMAGE);
m_aText.Show();
m_aImage.Show();
m_aVRuler.Show();
m_aVRuler.Activate();
m_aVRuler.SetPagePos(0);
m_aVRuler.SetBorders();
m_aVRuler.SetIndents();
m_aVRuler.SetMargin1();
m_aVRuler.SetMargin2();
}
// -----------------------------------------------------------------------------
OStartMarker::~OStartMarker()
{
DBG_DTOR( rpt_OStartMarker,NULL);
if ( osl_decrementInterlockedCount(&s_nImageRefCount) == 0 )
{
DELETEZ(s_pDefCollapsed);
DELETEZ(s_pDefExpanded);
DELETEZ(s_pDefCollapsedHC);
DELETEZ(s_pDefExpandedHC);
} // if ( osl_decrementInterlockedCount(&s_nImageRefCount) == 0 )
}
// -----------------------------------------------------------------------------
sal_Int32 OStartMarker::getWidth() const
{
return (GetDisplayBackground().GetColor().IsDark() ? s_pDefExpandedHC : s_pDefCollapsed)->GetSizePixel().Width() + GetTextWidth(m_aText.GetText(),0,::std::min<USHORT>(TEXT_WIDTH,m_aText.GetText().Len())) + 2*REPORT_EXTRA_SPACE;
}
// -----------------------------------------------------------------------------
sal_Int32 OStartMarker::getMinHeight() const
{
return m_aText.GetTextHeight() + 2*STRT_BORDER + 2;
}
// -----------------------------------------------------------------------------
void OStartMarker::Paint( const Rectangle& rRect )
{
Window::Paint( rRect );
//SetUpdateMode(FALSE);
Size aSize = GetSizePixel();
long nSize = aSize.Width();
if ( !isCollapsed() )
nSize = aSize.Width() - m_aVRuler.GetSizePixel().Width() - m_nCornerSize;
SetClipRegion(Region(Rectangle(Point(),Size( nSize,aSize.Height()))));
aSize.Width() += m_nCornerSize;
Rectangle aWholeRect(Point(),aSize);
{
const ColorChanger aColors( this, m_nTextBoundaries, m_nColor );
//aGradient.SetBorder(static_cast<USHORT>(m_nCornerSize));
PolyPolygon aPoly;
aPoly.Insert(Polygon(aWholeRect,m_nCornerSize,m_nCornerSize));
Color aStartColor(m_nColor);
aStartColor.IncreaseLuminance(10);
USHORT nHue = 0;
USHORT nSat = 0;
USHORT nBri = 0;
aStartColor.RGBtoHSB(nHue, nSat, nBri);
nSat += 40;
Color aEndColor(Color::HSBtoRGB(nHue, nSat, nBri));
Gradient aGradient(GRADIENT_LINEAR,aStartColor,aEndColor);
aGradient.SetSteps(static_cast<USHORT>(aSize.Height()));
DrawGradient(aPoly ,aGradient);
}
if ( m_bMarked )
{
#define DIFF_DIST 2
Rectangle aRect( Point(m_nCornerSize,m_nCornerSize),
Size(aSize.Width() - m_nCornerSize- m_nCornerSize,aSize.Height() - m_nCornerSize- m_nCornerSize));
ColorChanger aColors( this, COL_WHITE, COL_WHITE );
DrawPolyLine(Polygon(aRect),LineInfo(LINE_SOLID,2));
}
}
// -----------------------------------------------------------------------------
void OStartMarker::setColor()
{
const Color aColor(m_nColor);
Color aTextColor = GetTextColor();
if ( aColor.GetLuminance() < 128 )
aTextColor = COL_WHITE;
m_aText.SetTextColor(aTextColor);
m_aText.SetLineColor(m_nColor);
}
// -----------------------------------------------------------------------
void OStartMarker::MouseButtonUp( const MouseEvent& rMEvt )
{
if ( !rMEvt.IsLeft() )
return;
Point aPos( rMEvt.GetPosPixel());
const Size aOutputSize = GetOutputSizePixel();
if( aPos.X() > aOutputSize.Width() || aPos.Y() > aOutputSize.Height() )
return;
Rectangle aRect(m_aImage.GetPosPixel(),m_aImage.GetImage().GetSizePixel());
if ( rMEvt.GetClicks() == 2 || aRect.IsInside( aPos ) )
{
m_bCollapsed = !m_bCollapsed;
Image* pImage = NULL;
if ( GetDisplayBackground().GetColor().IsDark() )
pImage = m_bCollapsed ? s_pDefCollapsedHC : s_pDefExpandedHC;
else
pImage = m_bCollapsed ? s_pDefCollapsed : s_pDefExpanded;
m_aImage.SetImage(*pImage);
m_aVRuler.Show(!m_bCollapsed && m_bShowRuler);
m_nCornerSize = CORNER_SPACE;
if ( m_aCollapsedLink.IsSet() )
m_aCollapsedLink.Call(this);
}
m_pParent->showProperties(this);
}
// -----------------------------------------------------------------------
void OStartMarker::initDefaultNodeImages()
{
if ( !s_pDefCollapsed )
{
s_pDefCollapsed = new Image( ModuleRes( RID_IMG_TREENODE_COLLAPSED) );
s_pDefCollapsedHC = new Image( ModuleRes( RID_IMG_TREENODE_COLLAPSED_HC ) );
s_pDefExpanded = new Image( ModuleRes( RID_IMG_TREENODE_EXPANDED ) );
s_pDefExpandedHC = new Image( ModuleRes( RID_IMG_TREENODE_EXPANDED_HC ) );
}
Image* pImage = NULL;
if ( GetDisplayBackground().GetColor().IsDark() )
{
pImage = m_bCollapsed ? s_pDefCollapsedHC : s_pDefExpandedHC;
}
else
{
pImage = m_bCollapsed ? s_pDefCollapsed : s_pDefExpanded;
}
m_aImage.SetImage(*pImage);
m_aImage.SetMouseTransparent(TRUE);
m_aImage.SetBackground();
m_aText.SetBackground();
m_aText.SetMouseTransparent(TRUE);
}
// -----------------------------------------------------------------------
void OStartMarker::ImplInitSettings()
{
SetBackground( Wallpaper( Application::GetSettings().GetStyleSettings().GetDialogColor() ) );
SetFillColor( Application::GetSettings().GetStyleSettings().GetDialogColor() );
//SetTextFillColor( Application::GetSettings().GetStyleSettings().GetDarkShadowColor() );
setColor();
}
//------------------------------------------------------------------------------
void OStartMarker::Resize()
{
const Size aOutputSize( GetOutputSize() );
const long nOutputWidth = aOutputSize.Width();
const long nOutputHeight = aOutputSize.Height();
const Size aImageSize = m_aImage.GetImage().GetSizePixel();
sal_Int32 nY = ::std::min<sal_Int32>(static_cast<sal_Int32>(REPORT_EXTRA_SPACE),static_cast<sal_Int32>((nOutputHeight - aImageSize.Height()) * 0.5));
if ( m_bCollapsed )
nY = static_cast<sal_Int32>((nOutputHeight - aImageSize.Height()) * 0.5);
Point aPos(REPORT_EXTRA_SPACE,nY);
m_aImage.SetPosSizePixel(aPos,Size(aImageSize.Width() + REPORT_EXTRA_SPACE,nOutputHeight - 2*nY));
aPos.X() += aImageSize.Width() + REPORT_EXTRA_SPACE;
aPos.Y() -= 2;
const long nVRulerWidth = m_aVRuler.GetSizePixel().Width();
const Point aRulerPos(nOutputWidth - nVRulerWidth - 5,0);
m_aText.SetPosSizePixel(aPos,Size(aRulerPos.X() - aPos.X(),nOutputHeight - 2*aPos.Y()));
m_aVRuler.SetPosSizePixel(aRulerPos,Size(nVRulerWidth,nOutputHeight));
}
// -----------------------------------------------------------------------------
void OStartMarker::setTitle(const String& _sTitle)
{
m_aText.SetText(_sTitle);
}
// -----------------------------------------------------------------------------
void OStartMarker::Notify(SfxBroadcaster & rBc, SfxHint const & rHint)
{
OColorListener::Notify(rBc, rHint);
if (rHint.ISA(SfxSimpleHint)
&& (static_cast< SfxSimpleHint const & >(rHint).GetId()
== SFX_HINT_COLORS_CHANGED))
{
setColor();
//m_aText.Invalidate();
Invalidate(INVALIDATE_CHILDREN);
}
}
//----------------------------------------------------------------------------
void OStartMarker::showRuler(sal_Bool _bShow)
{
m_bShowRuler = _bShow;
m_aVRuler.Show(!m_bCollapsed && m_bShowRuler);
}
//------------------------------------------------------------------------------
sal_Int32 OStartMarker::getRulerOffset() const
{
return m_aVRuler.GetSizePixel().Width();
}
//------------------------------------------------------------------------------
void OStartMarker::RequestHelp( const HelpEvent& rHEvt )
{
if( m_aText.GetText().Len())
{
// Hilfe anzeigen
Rectangle aItemRect(rHEvt.GetMousePosPixel(),Size(GetSizePixel().Width(),getMinHeight()));
//aItemRect = LogicToPixel( aItemRect );
Point aPt = OutputToScreenPixel( aItemRect.TopLeft() );
aItemRect.Left() = aPt.X();
aItemRect.Top() = aPt.Y();
aPt = OutputToScreenPixel( aItemRect.BottomRight() );
aItemRect.Right() = aPt.X();
aItemRect.Bottom() = aPt.Y();
if( rHEvt.GetMode() == HELPMODE_BALLOON )
Help::ShowBalloon( this, aItemRect.Center(), aItemRect, m_aText.GetText());
else
Help::ShowQuickHelp( this, aItemRect, m_aText.GetText() );
}
}
// -----------------------------------------------------------------------------
void OStartMarker::setCollapsed(sal_Bool _bCollapsed)
{
OColorListener::setCollapsed(_bCollapsed);
showRuler(_bCollapsed);
}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
// =======================================================================
}
// =======================================================================
<commit_msg>INTEGRATION: CWS rpt23fix02 (1.2.4); FILE MERGED 2007/07/30 05:36:12 oj 1.2.4.1: #80161# apply gcc3 patch for strings<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: StartMarker.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: hr $ $Date: 2007-08-03 10:04:34 $
*
* 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
*
************************************************************************/
#include "precompiled_reportdesign.hxx"
#ifndef RPTUI_STARTMARKER_HXX
#include "StartMarker.hxx"
#endif
#ifndef _SV_IMAGE_HXX
#include <vcl/image.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _RPTUI_DLGRESID_HRC
#include "RptResId.hrc"
#endif
#ifndef _RPTUI_MODULE_HELPER_RPT_HXX_
#include "ModuleHelper.hxx"
#endif
#ifndef RPTUI_COLORCHANGER_HXX
#include "ColorChanger.hxx"
#endif
#ifndef RPTUI_REPORT_DEFINES_HXX
#include "ReportDefines.hxx"
#endif
#ifndef RPTUI_SECTIONSWINDOW_HXX
#include "SectionsWindow.hxx"
#endif
#ifndef RTPUI_REPORTDESIGN_HELPID_HRC
#include "helpids.hrc"
#endif
#ifndef _SV_HELP_HXX
#include <vcl/help.hxx>
#endif
#include <vcl/gradient.hxx>
#include <vcl/lineinfo.hxx>
#ifndef _SFXSMPLHINT_HXX
#include <svtools/smplhint.hxx>
#endif
#define CORNER_SPACE 5
#define TEXT_WIDTH 10
#define STRT_BORDER 6
//=====================================================================
namespace rptui
{
//=====================================================================
Image* OStartMarker::s_pDefCollapsed = NULL;
Image* OStartMarker::s_pDefExpanded = NULL;
Image* OStartMarker::s_pDefCollapsedHC = NULL;
Image* OStartMarker::s_pDefExpandedHC = NULL;
oslInterlockedCount OStartMarker::s_nImageRefCount = 0;
DBG_NAME( rpt_OStartMarker )
// -----------------------------------------------------------------------------
OStartMarker::OStartMarker(OSectionsWindow* _pParent,const ::rtl::OUString& _sColorEntry)
: OColorListener(_pParent,_sColorEntry)
,m_aVRuler(this,WB_VERT)
,m_aText(this,WB_WORDBREAK)
,m_aImage(this,WB_LEFT|WB_TOP)
,m_pParent(_pParent)
,m_nCornerSize(CORNER_SPACE)
,m_bShowRuler(sal_True)
{
DBG_CTOR( rpt_OStartMarker,NULL);
SetUniqueId(HID_STARTMARKER);
osl_incrementInterlockedCount(&s_nImageRefCount);
initDefaultNodeImages();
ImplInitSettings();
m_aText.SetHelpId(HID_START_TITLE);
m_aImage.SetHelpId(HID_START_IMAGE);
m_aText.Show();
m_aImage.Show();
m_aVRuler.Show();
m_aVRuler.Activate();
m_aVRuler.SetPagePos(0);
m_aVRuler.SetBorders();
m_aVRuler.SetIndents();
m_aVRuler.SetMargin1();
m_aVRuler.SetMargin2();
}
// -----------------------------------------------------------------------------
OStartMarker::~OStartMarker()
{
DBG_DTOR( rpt_OStartMarker,NULL);
if ( osl_decrementInterlockedCount(&s_nImageRefCount) == 0 )
{
DELETEZ(s_pDefCollapsed);
DELETEZ(s_pDefExpanded);
DELETEZ(s_pDefCollapsedHC);
DELETEZ(s_pDefExpandedHC);
} // if ( osl_decrementInterlockedCount(&s_nImageRefCount) == 0 )
}
// -----------------------------------------------------------------------------
sal_Int32 OStartMarker::getWidth() const
{
return (GetDisplayBackground().GetColor().IsDark() ? s_pDefExpandedHC : s_pDefCollapsed)->GetSizePixel().Width() + GetTextWidth(m_aText.GetText(),0,::std::min<USHORT>(TEXT_WIDTH,m_aText.GetText().Len())) + 2*REPORT_EXTRA_SPACE;
}
// -----------------------------------------------------------------------------
sal_Int32 OStartMarker::getMinHeight() const
{
return m_aText.GetTextHeight() + 2*STRT_BORDER + 2;
}
// -----------------------------------------------------------------------------
void OStartMarker::Paint( const Rectangle& rRect )
{
Window::Paint( rRect );
//SetUpdateMode(FALSE);
Size aSize = GetSizePixel();
long nSize = aSize.Width();
if ( !isCollapsed() )
nSize = aSize.Width() - m_aVRuler.GetSizePixel().Width() - m_nCornerSize;
SetClipRegion(Region(Rectangle(Point(),Size( nSize,aSize.Height()))));
aSize.Width() += m_nCornerSize;
Point aGcc3WorkaroundTemporary;
Rectangle aWholeRect(aGcc3WorkaroundTemporary,aSize);
{
const ColorChanger aColors( this, m_nTextBoundaries, m_nColor );
//aGradient.SetBorder(static_cast<USHORT>(m_nCornerSize));
PolyPolygon aPoly;
aPoly.Insert(Polygon(aWholeRect,m_nCornerSize,m_nCornerSize));
Color aStartColor(m_nColor);
aStartColor.IncreaseLuminance(10);
USHORT nHue = 0;
USHORT nSat = 0;
USHORT nBri = 0;
aStartColor.RGBtoHSB(nHue, nSat, nBri);
nSat += 40;
Color aEndColor(Color::HSBtoRGB(nHue, nSat, nBri));
Gradient aGradient(GRADIENT_LINEAR,aStartColor,aEndColor);
aGradient.SetSteps(static_cast<USHORT>(aSize.Height()));
DrawGradient(aPoly ,aGradient);
}
if ( m_bMarked )
{
#define DIFF_DIST 2
Rectangle aRect( Point(m_nCornerSize,m_nCornerSize),
Size(aSize.Width() - m_nCornerSize- m_nCornerSize,aSize.Height() - m_nCornerSize- m_nCornerSize));
ColorChanger aColors( this, COL_WHITE, COL_WHITE );
DrawPolyLine(Polygon(aRect),LineInfo(LINE_SOLID,2));
}
}
// -----------------------------------------------------------------------------
void OStartMarker::setColor()
{
const Color aColor(m_nColor);
Color aTextColor = GetTextColor();
if ( aColor.GetLuminance() < 128 )
aTextColor = COL_WHITE;
m_aText.SetTextColor(aTextColor);
m_aText.SetLineColor(m_nColor);
}
// -----------------------------------------------------------------------
void OStartMarker::MouseButtonUp( const MouseEvent& rMEvt )
{
if ( !rMEvt.IsLeft() )
return;
Point aPos( rMEvt.GetPosPixel());
const Size aOutputSize = GetOutputSizePixel();
if( aPos.X() > aOutputSize.Width() || aPos.Y() > aOutputSize.Height() )
return;
Rectangle aRect(m_aImage.GetPosPixel(),m_aImage.GetImage().GetSizePixel());
if ( rMEvt.GetClicks() == 2 || aRect.IsInside( aPos ) )
{
m_bCollapsed = !m_bCollapsed;
Image* pImage = NULL;
if ( GetDisplayBackground().GetColor().IsDark() )
pImage = m_bCollapsed ? s_pDefCollapsedHC : s_pDefExpandedHC;
else
pImage = m_bCollapsed ? s_pDefCollapsed : s_pDefExpanded;
m_aImage.SetImage(*pImage);
m_aVRuler.Show(!m_bCollapsed && m_bShowRuler);
m_nCornerSize = CORNER_SPACE;
if ( m_aCollapsedLink.IsSet() )
m_aCollapsedLink.Call(this);
}
m_pParent->showProperties(this);
}
// -----------------------------------------------------------------------
void OStartMarker::initDefaultNodeImages()
{
if ( !s_pDefCollapsed )
{
s_pDefCollapsed = new Image( ModuleRes( RID_IMG_TREENODE_COLLAPSED) );
s_pDefCollapsedHC = new Image( ModuleRes( RID_IMG_TREENODE_COLLAPSED_HC ) );
s_pDefExpanded = new Image( ModuleRes( RID_IMG_TREENODE_EXPANDED ) );
s_pDefExpandedHC = new Image( ModuleRes( RID_IMG_TREENODE_EXPANDED_HC ) );
}
Image* pImage = NULL;
if ( GetDisplayBackground().GetColor().IsDark() )
{
pImage = m_bCollapsed ? s_pDefCollapsedHC : s_pDefExpandedHC;
}
else
{
pImage = m_bCollapsed ? s_pDefCollapsed : s_pDefExpanded;
}
m_aImage.SetImage(*pImage);
m_aImage.SetMouseTransparent(TRUE);
m_aImage.SetBackground();
m_aText.SetBackground();
m_aText.SetMouseTransparent(TRUE);
}
// -----------------------------------------------------------------------
void OStartMarker::ImplInitSettings()
{
SetBackground( Wallpaper( Application::GetSettings().GetStyleSettings().GetDialogColor() ) );
SetFillColor( Application::GetSettings().GetStyleSettings().GetDialogColor() );
//SetTextFillColor( Application::GetSettings().GetStyleSettings().GetDarkShadowColor() );
setColor();
}
//------------------------------------------------------------------------------
void OStartMarker::Resize()
{
const Size aOutputSize( GetOutputSize() );
const long nOutputWidth = aOutputSize.Width();
const long nOutputHeight = aOutputSize.Height();
const Size aImageSize = m_aImage.GetImage().GetSizePixel();
sal_Int32 nY = ::std::min<sal_Int32>(static_cast<sal_Int32>(REPORT_EXTRA_SPACE),static_cast<sal_Int32>((nOutputHeight - aImageSize.Height()) * 0.5));
if ( m_bCollapsed )
nY = static_cast<sal_Int32>((nOutputHeight - aImageSize.Height()) * 0.5);
Point aPos(REPORT_EXTRA_SPACE,nY);
m_aImage.SetPosSizePixel(aPos,Size(aImageSize.Width() + REPORT_EXTRA_SPACE,nOutputHeight - 2*nY));
aPos.X() += aImageSize.Width() + REPORT_EXTRA_SPACE;
aPos.Y() -= 2;
const long nVRulerWidth = m_aVRuler.GetSizePixel().Width();
const Point aRulerPos(nOutputWidth - nVRulerWidth - 5,0);
m_aText.SetPosSizePixel(aPos,Size(aRulerPos.X() - aPos.X(),nOutputHeight - 2*aPos.Y()));
m_aVRuler.SetPosSizePixel(aRulerPos,Size(nVRulerWidth,nOutputHeight));
}
// -----------------------------------------------------------------------------
void OStartMarker::setTitle(const String& _sTitle)
{
m_aText.SetText(_sTitle);
}
// -----------------------------------------------------------------------------
void OStartMarker::Notify(SfxBroadcaster & rBc, SfxHint const & rHint)
{
OColorListener::Notify(rBc, rHint);
if (rHint.ISA(SfxSimpleHint)
&& (static_cast< SfxSimpleHint const & >(rHint).GetId()
== SFX_HINT_COLORS_CHANGED))
{
setColor();
//m_aText.Invalidate();
Invalidate(INVALIDATE_CHILDREN);
}
}
//----------------------------------------------------------------------------
void OStartMarker::showRuler(sal_Bool _bShow)
{
m_bShowRuler = _bShow;
m_aVRuler.Show(!m_bCollapsed && m_bShowRuler);
}
//------------------------------------------------------------------------------
sal_Int32 OStartMarker::getRulerOffset() const
{
return m_aVRuler.GetSizePixel().Width();
}
//------------------------------------------------------------------------------
void OStartMarker::RequestHelp( const HelpEvent& rHEvt )
{
if( m_aText.GetText().Len())
{
// Hilfe anzeigen
Rectangle aItemRect(rHEvt.GetMousePosPixel(),Size(GetSizePixel().Width(),getMinHeight()));
//aItemRect = LogicToPixel( aItemRect );
Point aPt = OutputToScreenPixel( aItemRect.TopLeft() );
aItemRect.Left() = aPt.X();
aItemRect.Top() = aPt.Y();
aPt = OutputToScreenPixel( aItemRect.BottomRight() );
aItemRect.Right() = aPt.X();
aItemRect.Bottom() = aPt.Y();
if( rHEvt.GetMode() == HELPMODE_BALLOON )
Help::ShowBalloon( this, aItemRect.Center(), aItemRect, m_aText.GetText());
else
Help::ShowQuickHelp( this, aItemRect, m_aText.GetText() );
}
}
// -----------------------------------------------------------------------------
void OStartMarker::setCollapsed(sal_Bool _bCollapsed)
{
OColorListener::setCollapsed(_bCollapsed);
showRuler(_bCollapsed);
}
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
// =======================================================================
}
// =======================================================================
<|endoftext|> |
<commit_before>#include "Board.h"
#include "Pawn.h"
#include "Rook.h"
#include "Knight.h"
#include "Bishop.h"
#include "Queen.h"
#include "King.h"
#include <iostream>
#include <sstream>
namespace Chess {
Board::Board() {
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
pieces[x][y] = nullptr;
}
}
// Black pawns
for (int x = 0; x < 8; x++) {
pieces[x][6] = new Pawn(Position(x, 6), false);
}
// White pawns
for (int x = 0; x < 8; x++) {
pieces[x][1] = new Pawn(Position(x, 1), true);
}
// Rooks
pieces[0][7] = new Rook(Position(0, 7), false);
pieces[7][7] = new Rook(Position(7, 7), false);
pieces[0][0] = new Rook(Position(0, 0), true);
pieces[7][0] = new Rook(Position(7, 0), true);
// Knights
pieces[1][7] = new Knight(Position(1, 7), false);
pieces[6][7] = new Knight(Position(6, 7), false);
pieces[1][0] = new Knight(Position(1, 0), true);
pieces[6][0] = new Knight(Position(6, 0), true);
// Bishops
pieces[2][7] = new Bishop(Position(2, 7), false);
pieces[5][7] = new Bishop(Position(5, 7), false);
pieces[2][0] = new Bishop(Position(2, 0), true);
pieces[5][0] = new Bishop(Position(5, 0), true);
// Queens
pieces[3][7] = new Queen(Position(3, 7), false);
pieces[3][0] = new Queen(Position(3, 0), true);
// Kings
pieces[4][7] = new King(Position(4, 7), false);
pieces[4][0] = new King(Position(4, 0), true);
addBoardToMap();
}
Board::~Board() {
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
if (pieces[x][y] != nullptr)
delete pieces[x][y];
}
}
}
GameState Board::getState() const {
return state;
}
Piece* Board::getPiece(const Position& position) const {
return pieces[position.x][position.y];
}
bool Board::mustPromote() {
return needsToPromote;
}
bool Board::move(const Position& oldPosition, const Position& newPosition) {
Piece* piece = getPiece(oldPosition);
Piece* targetPiece = getPiece(newPosition);
if (piece != nullptr) {
// Check if the piece is of the right color.
if (piece->isWhite() == (turn % 2 == 0)) {
halfMovesSinceCapture++;
// Check if the move is legal.
if (piece->isLegal(*this, newPosition)) {
pieces[oldPosition.x][oldPosition.y] = nullptr;
// En passant.
if (pieces[newPosition.x][newPosition.y] == nullptr && (piece->notation() == 'p' || piece->notation() == 'P') && newPosition.x != oldPosition.x){
if (piece->isWhite()) {
delete pieces[newPosition.x][newPosition.y - 1];
pieces[newPosition.x][newPosition.y - 1] = nullptr;
halfMovesSinceCapture = 0;
} else {
delete pieces[newPosition.x][newPosition.y + 1];
pieces[newPosition.x][newPosition.y + 1] = nullptr;
halfMovesSinceCapture = 0;
}
}
// Castling
if (piece->notation() == 'k' || piece->notation() == 'K') {
if (newPosition.x - oldPosition.x == 2){
Piece* tempPiece = getPiece(Position(7, newPosition.y));
pieces[7][newPosition.y] = nullptr;
pieces[5][newPosition.y] = tempPiece;
tempPiece->move(Position(5, newPosition.y));
} else if (newPosition.x - oldPosition.x == -2) {
Piece* tempPiece = getPiece(Position(0, newPosition.y));
pieces[0][newPosition.y] = nullptr;
pieces[3][newPosition.y] = tempPiece;
tempPiece->move(Position(3, newPosition.y));
}
}
// Delete captured enemy piece.
if (pieces[newPosition.x][newPosition.y] != nullptr){
delete pieces[newPosition.x][newPosition.y];
halfMovesSinceCapture = 0;
}
// Update pieces and piece position
pieces[newPosition.x][newPosition.y] = piece;
if (piece->notation() == 'p' || piece->notation() == 'P')
halfMovesSinceCapture = 0;
piece->move(newPosition);
// Promote pawns
if(newPosition.y == 7 || newPosition.y == 0){
if (piece->notation() == 'p' || piece->notation() == 'P'){
needsToPromote = true;
}
}
if ( (piece->notation() == 'p' || piece->notation() == 'P') ){
if (abs(oldPosition.y - newPosition.y) == 2) {
if (piece->notation() == 'p')
enPassantPossible = Position(newPosition.x, newPosition.y + 1);
else if (piece->notation() == 'P')
enPassantPossible = Position(newPosition.x, newPosition.y - 1);
}
}
else {
enPassantPossible = Position(-1, -1);
}
printf("En passant possible at:\n X:%d, Y:%d\n", enPassantPossible.x, enPassantPossible.y);
// Set and reset lastMovedPiece
if (lastMovedPawn != nullptr){
if (lastMovedPawn->getLastMoveWasDouble()){
//lastMovedPawn->resetLastMoveWasDouble(); //orsakar krasch..
}
}
lastMovedPawn = dynamic_cast<Pawn*>(getPiece(newPosition));
turn++;
if (state == GameState::BLACKPLAYS)
state = GameState::WHITEPLAYS;
else
state = GameState::BLACKPLAYS;
std::string tempstring = toFENString(false);
std::cout << tempstring << '\n';
addBoardToMap();
if(isThreeFoldRepitition())
state = GameState::DRAW;
if (isFiftyMoveSincePawnOrCapture())
state = GameState::DRAW;
if (!sufficientMaterial())
state = GameState::DRAW;
checkWin();
return true;
}
}
}
return false;
}
bool Board::willLeaveKingChecked(const Position& oldPosition, const Position& newPosition) {
Piece* oldPiece = getPiece(oldPosition);
Piece* newPiece = getPiece(newPosition);
Piece* piece;
switch (oldPiece->notation()) {
case 'Q':
case 'q':
piece = new Queen(oldPiece->getPosition(), oldPiece->isWhite());
break;
case 'K':
case 'k':
piece = new King(oldPiece->getPosition(), oldPiece->isWhite());
break;
case 'P':
case 'p':
piece = new Pawn(oldPiece->getPosition(), oldPiece->isWhite());
break;
case 'R':
case 'r':
piece = new Rook(oldPiece->getPosition(), oldPiece->isWhite());
break;
case 'B':
case 'b':
piece = new Bishop(oldPiece->getPosition(), oldPiece->isWhite());
break;
case 'N':
case 'n':
piece = new Knight(oldPiece->getPosition(), oldPiece->isWhite());
break;
}
pieces[newPosition.x][newPosition.y] = piece;
piece->move(newPosition);
pieces[oldPosition.x][oldPosition.y] = nullptr;
King* king = getKing((turn % 2 == 0));
bool checked = king->isChecked(*this);
delete piece;
pieces[newPosition.x][newPosition.y] = newPiece;
pieces[oldPosition.x][oldPosition.y] = oldPiece;
return checked;
}
void Board::promotePawn(Piece* pawn, PromoteTypes type) {
Position position = pawn->getPosition();
bool white = pawn->isWhite();
delete pawn;
switch (type) {
case PromoteTypes::QUEEN:
pieces[position.x][position.y] = new Queen(position, white);
break;
case PromoteTypes::ROOK:
pieces[position.x][position.y] = new Rook(position, white);
break;
case PromoteTypes::BISHOP:
pieces[position.x][position.y] = new Bishop(position, white);
break;
case PromoteTypes::KNIGHT:
pieces[position.x][position.y] = new Knight(position, white);
break;
}
checkWin();
needsToPromote = false;
}
void Board::addBoardToMap() {
std::string tempstring = toFENString(false);
if (previousBoards.find(tempstring) == previousBoards.end()) {
previousBoards[tempstring] = 0;
} else{
previousBoards[tempstring] += 1;
}
}
std::string Board::toFENString(bool addExtraData) const {
std::string tempstring;
int emptyCounter = 0;
for (int y = 7; y >= 0; y--) {
for (int x = 0; x < 8; x++){
if (pieces[x][y] == nullptr)
emptyCounter++;
else {
if (emptyCounter != 0)
tempstring += std::to_string(emptyCounter);
tempstring.append(1, pieces[x][y]->notation());
emptyCounter = 0;
}
}
if (emptyCounter != 0) {
tempstring += std::to_string(emptyCounter);
emptyCounter = 0;
}
tempstring += '/';
}
// Who played the turn?
if (state == GameState::BLACKPLAYS)
tempstring += "w";
else
tempstring += "b";
if (addExtraData) {
// Number of half turns since last capture or pawn move.
tempstring += ' ' + std::to_string(halfMovesSinceCapture) + ' ';
// Number of full moves.
tempstring += std::to_string((turn+1) / 2);
}
return tempstring;
}
bool Board::isThreeFoldRepitition() {
return previousBoards[toFENString(false)] == 3;
}
bool Board::isFiftyMoveSincePawnOrCapture() const {
return halfMovesSinceCapture >= 100;
}
void Board::checkWin() {
bool white = (state == GameState::WHITEPLAYS);
bool canMove = false;
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
Piece* piece = getPiece(Position(x, y));
if (piece != nullptr && piece->isWhite() == white) {
if (!piece->legalMoves(*this).empty()) {
canMove = true;
break;
}
}
}
}
if (!canMove) {
if (getKing(white)->isChecked(*this)) {
if (white)
state = GameState::BLACKWIN;
else
state = GameState::WHITEWIN;
} else {
state = GameState::DRAW;
}
}
}
bool Board::sufficientMaterial() const {
// Get the material on the board.
int pieceTypes[6] = { 0 };
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
Piece* piece = getPiece(Position(x, y));
if (piece != nullptr) {
switch (piece->notation()) {
case 'Q':
case 'q':
pieceTypes[0]++;
break;
case 'P':
case 'p':
pieceTypes[1]++;
break;
case 'R':
case 'r':
pieceTypes[2]++;
break;
case 'N':
case 'n':
pieceTypes[3]++;
break;
case 'B':
case 'b':
pieceTypes[((x + y) % 2 == 0) ? 4 : 5]++;
break;
}
}
}
}
// If there's a queen, pawn or rook on the board, there is sufficient material.
if (pieceTypes[0] > 0 || pieceTypes[1] > 0 || pieceTypes[2] > 0)
return true;
// If there are 2 or more knights on the board, there is sufficient material.
if (pieceTypes[3] > 1)
return true;
// If there are pieces from 2 or more categories (knight, bishop on light square, bishop on dark square), there is sufficient material.
if ((pieceTypes[3] > 0) + (pieceTypes[4] > 0) + (pieceTypes[5] > 0) >= 2)
return true;
return false;
}
King* Board::getKing(bool white) const {
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
Piece* piece = getPiece(Position(x, y));
if (piece != nullptr && piece->notation() == (white ? 'K' : 'k'))
return dynamic_cast<King*>(piece);
}
}
return nullptr;
}
}<commit_msg>Updated toFENString<commit_after>#include "Board.h"
#include "Pawn.h"
#include "Rook.h"
#include "Knight.h"
#include "Bishop.h"
#include "Queen.h"
#include "King.h"
#include <iostream>
#include <sstream>
namespace Chess {
Board::Board() {
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
pieces[x][y] = nullptr;
}
}
// Black pawns
for (int x = 0; x < 8; x++) {
pieces[x][6] = new Pawn(Position(x, 6), false);
}
// White pawns
for (int x = 0; x < 8; x++) {
pieces[x][1] = new Pawn(Position(x, 1), true);
}
// Rooks
pieces[0][7] = new Rook(Position(0, 7), false);
pieces[7][7] = new Rook(Position(7, 7), false);
pieces[0][0] = new Rook(Position(0, 0), true);
pieces[7][0] = new Rook(Position(7, 0), true);
// Knights
pieces[1][7] = new Knight(Position(1, 7), false);
pieces[6][7] = new Knight(Position(6, 7), false);
pieces[1][0] = new Knight(Position(1, 0), true);
pieces[6][0] = new Knight(Position(6, 0), true);
// Bishops
pieces[2][7] = new Bishop(Position(2, 7), false);
pieces[5][7] = new Bishop(Position(5, 7), false);
pieces[2][0] = new Bishop(Position(2, 0), true);
pieces[5][0] = new Bishop(Position(5, 0), true);
// Queens
pieces[3][7] = new Queen(Position(3, 7), false);
pieces[3][0] = new Queen(Position(3, 0), true);
// Kings
pieces[4][7] = new King(Position(4, 7), false);
pieces[4][0] = new King(Position(4, 0), true);
addBoardToMap();
}
Board::~Board() {
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
if (pieces[x][y] != nullptr)
delete pieces[x][y];
}
}
}
GameState Board::getState() const {
return state;
}
Piece* Board::getPiece(const Position& position) const {
return pieces[position.x][position.y];
}
bool Board::mustPromote() {
return needsToPromote;
}
bool Board::move(const Position& oldPosition, const Position& newPosition) {
Piece* piece = getPiece(oldPosition);
Piece* targetPiece = getPiece(newPosition);
if (piece != nullptr) {
// Check if the piece is of the right color.
if (piece->isWhite() == (turn % 2 == 0)) {
halfMovesSinceCapture++;
// Check if the move is legal.
if (piece->isLegal(*this, newPosition)) {
pieces[oldPosition.x][oldPosition.y] = nullptr;
// En passant.
if (pieces[newPosition.x][newPosition.y] == nullptr && (piece->notation() == 'p' || piece->notation() == 'P') && newPosition.x != oldPosition.x){
if (piece->isWhite()) {
delete pieces[newPosition.x][newPosition.y - 1];
pieces[newPosition.x][newPosition.y - 1] = nullptr;
halfMovesSinceCapture = 0;
} else {
delete pieces[newPosition.x][newPosition.y + 1];
pieces[newPosition.x][newPosition.y + 1] = nullptr;
halfMovesSinceCapture = 0;
}
}
// Castling
if (piece->notation() == 'k' || piece->notation() == 'K') {
if (newPosition.x - oldPosition.x == 2){
Piece* tempPiece = getPiece(Position(7, newPosition.y));
pieces[7][newPosition.y] = nullptr;
pieces[5][newPosition.y] = tempPiece;
tempPiece->move(Position(5, newPosition.y));
} else if (newPosition.x - oldPosition.x == -2) {
Piece* tempPiece = getPiece(Position(0, newPosition.y));
pieces[0][newPosition.y] = nullptr;
pieces[3][newPosition.y] = tempPiece;
tempPiece->move(Position(3, newPosition.y));
}
}
// Delete captured enemy piece.
if (pieces[newPosition.x][newPosition.y] != nullptr){
delete pieces[newPosition.x][newPosition.y];
halfMovesSinceCapture = 0;
}
// Update pieces and piece position
pieces[newPosition.x][newPosition.y] = piece;
if (piece->notation() == 'p' || piece->notation() == 'P')
halfMovesSinceCapture = 0;
piece->move(newPosition);
// Promote pawns
if(newPosition.y == 7 || newPosition.y == 0){
if (piece->notation() == 'p' || piece->notation() == 'P'){
needsToPromote = true;
}
}
if ( (piece->notation() == 'p' || piece->notation() == 'P') ){
if (abs(oldPosition.y - newPosition.y) == 2) {
if (piece->notation() == 'p')
enPassantPossible = Position(newPosition.x, newPosition.y + 1);
else if (piece->notation() == 'P')
enPassantPossible = Position(newPosition.x, newPosition.y - 1);
}
}
else {
enPassantPossible = Position(-1, -1);
}
printf("En passant possible at:\n X:%d, Y:%d\n", enPassantPossible.x, enPassantPossible.y);
// Set and reset lastMovedPiece
if (lastMovedPawn != nullptr){
if (lastMovedPawn->getLastMoveWasDouble()){
//lastMovedPawn->resetLastMoveWasDouble(); //orsakar krasch..
}
}
lastMovedPawn = dynamic_cast<Pawn*>(getPiece(newPosition));
turn++;
if (state == GameState::BLACKPLAYS)
state = GameState::WHITEPLAYS;
else
state = GameState::BLACKPLAYS;
std::string tempstring = toFENString(true);
std::cout << tempstring << '\n';
addBoardToMap();
if(isThreeFoldRepitition())
state = GameState::DRAW;
if (isFiftyMoveSincePawnOrCapture())
state = GameState::DRAW;
if (!sufficientMaterial())
state = GameState::DRAW;
checkWin();
return true;
}
}
}
return false;
}
bool Board::willLeaveKingChecked(const Position& oldPosition, const Position& newPosition) {
Piece* oldPiece = getPiece(oldPosition);
Piece* newPiece = getPiece(newPosition);
Piece* piece;
switch (oldPiece->notation()) {
case 'Q':
case 'q':
piece = new Queen(oldPiece->getPosition(), oldPiece->isWhite());
break;
case 'K':
case 'k':
piece = new King(oldPiece->getPosition(), oldPiece->isWhite());
break;
case 'P':
case 'p':
piece = new Pawn(oldPiece->getPosition(), oldPiece->isWhite());
break;
case 'R':
case 'r':
piece = new Rook(oldPiece->getPosition(), oldPiece->isWhite());
break;
case 'B':
case 'b':
piece = new Bishop(oldPiece->getPosition(), oldPiece->isWhite());
break;
case 'N':
case 'n':
piece = new Knight(oldPiece->getPosition(), oldPiece->isWhite());
break;
}
pieces[newPosition.x][newPosition.y] = piece;
piece->move(newPosition);
pieces[oldPosition.x][oldPosition.y] = nullptr;
King* king = getKing((turn % 2 == 0));
bool checked = king->isChecked(*this);
delete piece;
pieces[newPosition.x][newPosition.y] = newPiece;
pieces[oldPosition.x][oldPosition.y] = oldPiece;
return checked;
}
void Board::promotePawn(Piece* pawn, PromoteTypes type) {
Position position = pawn->getPosition();
bool white = pawn->isWhite();
delete pawn;
switch (type) {
case PromoteTypes::QUEEN:
pieces[position.x][position.y] = new Queen(position, white);
break;
case PromoteTypes::ROOK:
pieces[position.x][position.y] = new Rook(position, white);
break;
case PromoteTypes::BISHOP:
pieces[position.x][position.y] = new Bishop(position, white);
break;
case PromoteTypes::KNIGHT:
pieces[position.x][position.y] = new Knight(position, white);
break;
}
checkWin();
needsToPromote = false;
}
void Board::addBoardToMap() {
std::string tempstring = toFENString(false);
if (previousBoards.find(tempstring) == previousBoards.end()) {
previousBoards[tempstring] = 0;
} else{
previousBoards[tempstring] += 1;
}
}
std::string Board::toFENString(bool addExtraData) const {
std::string tempstring;
int emptyCounter = 0;
for (int y = 7; y >= 0; y--) {
for (int x = 0; x < 8; x++){
if (pieces[x][y] == nullptr)
emptyCounter++;
else {
if (emptyCounter != 0)
tempstring += std::to_string(emptyCounter);
tempstring.append(1, pieces[x][y]->notation());
emptyCounter = 0;
}
}
if (emptyCounter != 0) {
tempstring += std::to_string(emptyCounter);
emptyCounter = 0;
}
tempstring += '/';
}
// Who played the turn?
if (state == GameState::BLACKPLAYS)
tempstring += "w";
else
tempstring += "b";
if (addExtraData) {
tempstring += '/' + std::to_string(enPassantPossible.x) + '.' + std::to_string(enPassantPossible.y);
// Number of half turns since last capture or pawn move.
tempstring += '/' + std::to_string(halfMovesSinceCapture) + '/';
// Number of full moves.
tempstring += std::to_string((turn+1) / 2);
}
return tempstring;
}
bool Board::isThreeFoldRepitition() {
return previousBoards[toFENString(false)] == 3;
}
bool Board::isFiftyMoveSincePawnOrCapture() const {
return halfMovesSinceCapture >= 100;
}
void Board::checkWin() {
bool white = (state == GameState::WHITEPLAYS);
bool canMove = false;
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
Piece* piece = getPiece(Position(x, y));
if (piece != nullptr && piece->isWhite() == white) {
if (!piece->legalMoves(*this).empty()) {
canMove = true;
break;
}
}
}
}
if (!canMove) {
if (getKing(white)->isChecked(*this)) {
if (white)
state = GameState::BLACKWIN;
else
state = GameState::WHITEWIN;
} else {
state = GameState::DRAW;
}
}
}
bool Board::sufficientMaterial() const {
// Get the material on the board.
int pieceTypes[6] = { 0 };
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
Piece* piece = getPiece(Position(x, y));
if (piece != nullptr) {
switch (piece->notation()) {
case 'Q':
case 'q':
pieceTypes[0]++;
break;
case 'P':
case 'p':
pieceTypes[1]++;
break;
case 'R':
case 'r':
pieceTypes[2]++;
break;
case 'N':
case 'n':
pieceTypes[3]++;
break;
case 'B':
case 'b':
pieceTypes[((x + y) % 2 == 0) ? 4 : 5]++;
break;
}
}
}
}
// If there's a queen, pawn or rook on the board, there is sufficient material.
if (pieceTypes[0] > 0 || pieceTypes[1] > 0 || pieceTypes[2] > 0)
return true;
// If there are 2 or more knights on the board, there is sufficient material.
if (pieceTypes[3] > 1)
return true;
// If there are pieces from 2 or more categories (knight, bishop on light square, bishop on dark square), there is sufficient material.
if ((pieceTypes[3] > 0) + (pieceTypes[4] > 0) + (pieceTypes[5] > 0) >= 2)
return true;
return false;
}
King* Board::getKing(bool white) const {
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
Piece* piece = getPiece(Position(x, y));
if (piece != nullptr && piece->notation() == (white ? 'K' : 'k'))
return dynamic_cast<King*>(piece);
}
}
return nullptr;
}
}<|endoftext|> |
<commit_before>// test_keypairsign.cpp -- Test sodium::keypairsign
//
// ISC License
//
// Copyright (C) 2018 Farid Hajji <farid@hajji.name>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE sodium::keypairsign Test
#include <boost/test/included/unit_test.hpp>
#include "common.h"
#include "keypairsign.h"
#include "helpers.h"
#include "random.h"
#include <stdexcept>
#include <sodium.h>
using sodium::keypairsign;
using bytes = sodium::bytes;
static constexpr std::size_t ks_pub = keypairsign<>::KEYSIZE_PUBLIC_KEY;
static constexpr std::size_t ks_priv = keypairsign<>::KEYSIZE_PRIVATE_KEY;
static constexpr std::size_t ks_seed = keypairsign<>::KEYSIZE_SEEDBYTES;
struct SodiumFixture {
SodiumFixture() {
BOOST_REQUIRE(sodium_init() != -1);
// BOOST_TEST_MESSAGE("SodiumFixture(): sodium_init() successful.");
}
~SodiumFixture() {
// BOOST_TEST_MESSAGE("~SodiumFixture(): teardown -- no-op.");
}
};
BOOST_FIXTURE_TEST_SUITE ( sodium_test_suite, SodiumFixture )
BOOST_AUTO_TEST_CASE( sodium_test_keypairsign_size_ctor_default )
{
keypairsign<> keypair;
BOOST_TEST(keypair.public_key().size() == ks_pub);
BOOST_TEST(keypair.private_key().size() == ks_priv);
}
BOOST_AUTO_TEST_CASE( sodium_test_keypairsign_size_ctor_seed )
{
bytes seed(ks_seed);
sodium::randombytes_buf_inplace(seed);
keypairsign<> keypair(seed);
BOOST_TEST(keypair.public_key().size() == ks_pub);
BOOST_TEST(keypair.private_key().size() == ks_priv);
}
BOOST_AUTO_TEST_CASE( sodium_test_keypairsign_size_ctor_privkey )
{
keypairsign<> keypair1;
keypairsign<> keypair2(keypair1.private_key().data(), keypair1.private_key().size());
BOOST_TEST(keypair2.public_key().size() == ks_pub);
BOOST_TEST(keypair2.private_key().size() == ks_priv);
}
BOOST_AUTO_TEST_CASE ( sodium_test_keypairsign_copy_ctor )
{
keypairsign<> keypair;
keypairsign<> keypair_copy {keypair};
BOOST_TEST((keypair == keypair_copy)); // check also operator==()
BOOST_TEST((keypair.private_key() == keypair_copy.private_key())); // key::operator==()
BOOST_TEST(keypair.public_key() == keypair_copy.public_key()); // std::vector::operator==()
}
BOOST_AUTO_TEST_CASE ( sodium_test_keypairsign_copy_assignement )
{
keypairsign<> keypair;
keypairsign<> keypair_copy = keypair;
BOOST_TEST((keypair == keypair_copy));
BOOST_TEST((keypair.private_key() == keypair_copy.private_key()));
BOOST_TEST(keypair.public_key() == keypair_copy.public_key());
}
BOOST_AUTO_TEST_CASE( sodium_test_keypairsign_nonzero_ctor_default )
{
keypairsign<> keypair;
BOOST_TEST(!sodium::is_zero(keypair.public_key()));
BOOST_TEST(!sodium::is_zero(keypair.private_key()));
}
BOOST_AUTO_TEST_CASE( sodium_test_keypairsign_nonzero_ctor_seed )
{
bytes seed(ks_seed);
sodium::randombytes_buf_inplace(seed);
keypairsign<> keypair(seed);
BOOST_TEST(!sodium::is_zero(keypair.public_key()));
BOOST_TEST(!sodium::is_zero(keypair.private_key()));
}
BOOST_AUTO_TEST_CASE( sodium_test_keypairsign_nonzero_ctor_privkey )
{
keypairsign<> keypair1;
keypairsign<> keypair2(keypair1.private_key().data(), keypair1.private_key().size());
BOOST_TEST(!sodium::is_zero(keypair2.public_key()));
BOOST_TEST(!sodium::is_zero(keypair2.private_key()));
}
BOOST_AUTO_TEST_CASE( sodium_test_keypairsign_seedcompare_ctor_same_seed )
{
bytes seed(ks_seed);
sodium::randombytes_buf_inplace(seed);
keypairsign<> keypair1(seed);
keypairsign<> keypair2(seed); // same seed
BOOST_TEST(sodium::compare(keypair1.public_key(),
keypair2.public_key()));
BOOST_TEST(sodium::compare(keypair1.private_key(),
keypair2.private_key()));
BOOST_TEST((keypair1 == keypair2)); // check also operator==()
BOOST_TEST((keypair1.private_key() == keypair2.private_key()));
BOOST_TEST(keypair1.public_key() == keypair2.public_key());
}
BOOST_AUTO_TEST_CASE( sodium_test_keypairsign_seedcompare_ctor_different_seed )
{
bytes seed1(ks_seed);
sodium::randombytes_buf_inplace(seed1);
bytes seed2(ks_seed);
sodium::randombytes_buf_inplace(seed2);
BOOST_TEST(seed1 != seed2); // very unlikely that they are the same
keypairsign<> keypair1(seed1);
keypairsign<> keypair2(seed2); // different seed
BOOST_TEST(!sodium::compare(keypair1.public_key(),
keypair2.public_key()));
BOOST_TEST(!sodium::compare(keypair1.private_key(),
keypair2.private_key()));
BOOST_TEST((keypair1 != keypair2)); // check also operator!=()
}
BOOST_AUTO_TEST_CASE( sodium_test_keypairsign_seedcompare_extract_seed )
{
bytes seed1(ks_seed);
sodium::randombytes_buf_inplace(seed1);
keypairsign<> keypair(seed1);
// reconstruct seed from private key stored in keypair
bytes seed2 = keypair.seed();
BOOST_TEST(seed1 == seed2);
}
BOOST_AUTO_TEST_SUITE_END ()
<commit_msg>Added unit tests to sodium::keypairsign w/ different PK.<commit_after>// test_keypairsign.cpp -- Test sodium::keypairsign
//
// ISC License
//
// Copyright (C) 2018 Farid Hajji <farid@hajji.name>
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE sodium::keypairsign Test
#include <boost/test/included/unit_test.hpp>
#include "common.h"
#include "keypairsign.h"
#include "helpers.h"
#include "random.h"
#include <stdexcept>
#include <sodium.h>
using sodium::keypairsign;
using bytes = sodium::bytes;
static constexpr std::size_t ks_pub = keypairsign<>::KEYSIZE_PUBLIC_KEY;
static constexpr std::size_t ks_priv = keypairsign<>::KEYSIZE_PRIVATE_KEY;
static constexpr std::size_t ks_seed = keypairsign<>::KEYSIZE_SEEDBYTES;
struct SodiumFixture {
SodiumFixture() {
BOOST_REQUIRE(sodium_init() != -1);
// BOOST_TEST_MESSAGE("SodiumFixture(): sodium_init() successful.");
}
~SodiumFixture() {
// BOOST_TEST_MESSAGE("~SodiumFixture(): teardown -- no-op.");
}
};
BOOST_FIXTURE_TEST_SUITE ( sodium_test_suite, SodiumFixture )
// 1. sodium::bytes -------------------------------------------------------
BOOST_AUTO_TEST_CASE( sodium_test_keypairsign_size_ctor_default_bytes )
{
keypairsign<> keypair;
BOOST_TEST(keypair.public_key().size() == ks_pub);
BOOST_TEST(keypair.private_key().size() == ks_priv);
}
BOOST_AUTO_TEST_CASE( sodium_test_keypairsign_size_ctor_seed_bytes )
{
bytes seed(ks_seed);
sodium::randombytes_buf_inplace(seed);
keypairsign<> keypair(seed);
BOOST_TEST(keypair.public_key().size() == ks_pub);
BOOST_TEST(keypair.private_key().size() == ks_priv);
}
BOOST_AUTO_TEST_CASE( sodium_test_keypairsign_size_ctor_privkey_bytes )
{
keypairsign<> keypair1;
keypairsign<> keypair2(keypair1.private_key().data(), keypair1.private_key().size());
BOOST_TEST(keypair2.public_key().size() == ks_pub);
BOOST_TEST(keypair2.private_key().size() == ks_priv);
}
BOOST_AUTO_TEST_CASE ( sodium_test_keypairsign_copy_ctor_bytes )
{
keypairsign<> keypair;
keypairsign<> keypair_copy {keypair};
BOOST_TEST((keypair == keypair_copy)); // check also operator==()
BOOST_TEST((keypair.private_key() == keypair_copy.private_key())); // key::operator==()
BOOST_TEST(keypair.public_key() == keypair_copy.public_key()); // std::vector::operator==()
}
BOOST_AUTO_TEST_CASE ( sodium_test_keypairsign_copy_assignement_bytes )
{
keypairsign<> keypair;
keypairsign<> keypair_copy = keypair;
BOOST_TEST((keypair == keypair_copy));
BOOST_TEST((keypair.private_key() == keypair_copy.private_key()));
BOOST_TEST(keypair.public_key() == keypair_copy.public_key());
}
BOOST_AUTO_TEST_CASE( sodium_test_keypairsign_nonzero_ctor_default_bytes )
{
keypairsign<> keypair;
BOOST_TEST(!sodium::is_zero(keypair.public_key()));
BOOST_TEST(!sodium::is_zero(keypair.private_key()));
}
BOOST_AUTO_TEST_CASE( sodium_test_keypairsign_nonzero_ctor_seed_bytes )
{
bytes seed(ks_seed);
sodium::randombytes_buf_inplace(seed);
keypairsign<> keypair(seed);
BOOST_TEST(!sodium::is_zero(keypair.public_key()));
BOOST_TEST(!sodium::is_zero(keypair.private_key()));
}
BOOST_AUTO_TEST_CASE( sodium_test_keypairsign_nonzero_ctor_privkey_bytes )
{
keypairsign<> keypair1;
keypairsign<> keypair2(keypair1.private_key().data(), keypair1.private_key().size());
BOOST_TEST(!sodium::is_zero(keypair2.public_key()));
BOOST_TEST(!sodium::is_zero(keypair2.private_key()));
}
BOOST_AUTO_TEST_CASE( sodium_test_keypairsign_seedcompare_ctor_same_seed_bytes )
{
bytes seed(ks_seed);
sodium::randombytes_buf_inplace(seed);
keypairsign<> keypair1(seed);
keypairsign<> keypair2(seed); // same seed
BOOST_TEST(sodium::compare(keypair1.public_key(),
keypair2.public_key()));
BOOST_TEST(sodium::compare(keypair1.private_key(),
keypair2.private_key()));
BOOST_TEST((keypair1 == keypair2)); // check also operator==()
BOOST_TEST((keypair1.private_key() == keypair2.private_key()));
BOOST_TEST(keypair1.public_key() == keypair2.public_key());
}
BOOST_AUTO_TEST_CASE( sodium_test_keypairsign_seedcompare_ctor_different_seed_bytes )
{
bytes seed1(ks_seed);
sodium::randombytes_buf_inplace(seed1);
bytes seed2(ks_seed);
sodium::randombytes_buf_inplace(seed2);
BOOST_TEST(seed1 != seed2); // very unlikely that they are the same
keypairsign<> keypair1(seed1);
keypairsign<> keypair2(seed2); // different seed
BOOST_TEST(!sodium::compare(keypair1.public_key(),
keypair2.public_key()));
BOOST_TEST(!sodium::compare(keypair1.private_key(),
keypair2.private_key()));
BOOST_TEST((keypair1 != keypair2)); // check also operator!=()
}
BOOST_AUTO_TEST_CASE( sodium_test_keypairsign_seedcompare_extract_seed_bytes )
{
bytes seed1(ks_seed);
sodium::randombytes_buf_inplace(seed1);
keypairsign<> keypair(seed1);
// reconstruct seed from private key stored in keypair
bytes seed2 = keypair.seed();
BOOST_TEST(seed1 == seed2);
}
// 2. sodium::bytes_protected ----------------------------------------
BOOST_AUTO_TEST_CASE(sodium_test_keypairsign_size_ctor_default_bytes_protected)
{
keypairsign<sodium::bytes_protected> keypair;
BOOST_TEST(keypair.public_key().size() == ks_pub);
BOOST_TEST(keypair.private_key().size() == ks_priv);
}
BOOST_AUTO_TEST_CASE(sodium_test_keypairsign_size_ctor_seed_bytes_protected)
{
bytes seed(ks_seed);
sodium::randombytes_buf_inplace(seed);
keypairsign<sodium::bytes_protected> keypair(seed);
BOOST_TEST(keypair.public_key().size() == ks_pub);
BOOST_TEST(keypair.private_key().size() == ks_priv);
}
BOOST_AUTO_TEST_CASE(sodium_test_keypairsign_size_ctor_privkey_bytes_protected)
{
keypairsign<sodium::bytes_protected> keypair1;
keypairsign<sodium::bytes_protected> keypair2(keypair1.private_key().data(), keypair1.private_key().size());
BOOST_TEST(keypair2.public_key().size() == ks_pub);
BOOST_TEST(keypair2.private_key().size() == ks_priv);
}
BOOST_AUTO_TEST_CASE(sodium_test_keypairsign_copy_ctor_bytes_protected)
{
keypairsign<sodium::bytes_protected> keypair;
keypairsign<sodium::bytes_protected> keypair_copy{ keypair };
BOOST_TEST((keypair == keypair_copy)); // check also operator==()
BOOST_TEST((keypair.private_key() == keypair_copy.private_key())); // key::operator==()
BOOST_TEST(keypair.public_key() == keypair_copy.public_key()); // std::vector::operator==()
}
BOOST_AUTO_TEST_CASE(sodium_test_keypairsign_copy_assignement_bytes_protected)
{
keypairsign<sodium::bytes_protected> keypair;
keypairsign<sodium::bytes_protected> keypair_copy = keypair;
BOOST_TEST((keypair == keypair_copy));
BOOST_TEST((keypair.private_key() == keypair_copy.private_key()));
BOOST_TEST(keypair.public_key() == keypair_copy.public_key());
}
BOOST_AUTO_TEST_CASE(sodium_test_keypairsign_nonzero_ctor_default_bytes_protected)
{
keypairsign<sodium::bytes_protected> keypair;
BOOST_TEST(!sodium::is_zero(keypair.public_key()));
BOOST_TEST(!sodium::is_zero(keypair.private_key()));
}
BOOST_AUTO_TEST_CASE(sodium_test_keypairsign_nonzero_ctor_seed_bytes_protected)
{
bytes seed(ks_seed);
sodium::randombytes_buf_inplace(seed);
keypairsign<sodium::bytes_protected> keypair(seed);
BOOST_TEST(!sodium::is_zero(keypair.public_key()));
BOOST_TEST(!sodium::is_zero(keypair.private_key()));
}
BOOST_AUTO_TEST_CASE(sodium_test_keypairsign_nonzero_ctor_privkey_bytes_protected)
{
keypairsign<sodium::bytes_protected> keypair1;
keypairsign<sodium::bytes_protected> keypair2(keypair1.private_key().data(), keypair1.private_key().size());
BOOST_TEST(!sodium::is_zero(keypair2.public_key()));
BOOST_TEST(!sodium::is_zero(keypair2.private_key()));
}
BOOST_AUTO_TEST_CASE(sodium_test_keypairsign_seedcompare_ctor_same_seed_bytes_protected)
{
bytes seed(ks_seed);
sodium::randombytes_buf_inplace(seed);
keypairsign<sodium::bytes_protected> keypair1(seed);
keypairsign<sodium::bytes_protected> keypair2(seed); // same seed
BOOST_TEST(sodium::compare(keypair1.public_key(),
keypair2.public_key()));
BOOST_TEST(sodium::compare(keypair1.private_key(),
keypair2.private_key()));
BOOST_TEST((keypair1 == keypair2)); // check also operator==()
BOOST_TEST((keypair1.private_key() == keypair2.private_key()));
BOOST_TEST(keypair1.public_key() == keypair2.public_key());
}
BOOST_AUTO_TEST_CASE(sodium_test_keypairsign_seedcompare_ctor_different_seed_bytes_protected)
{
bytes seed1(ks_seed);
sodium::randombytes_buf_inplace(seed1);
bytes seed2(ks_seed);
sodium::randombytes_buf_inplace(seed2);
BOOST_TEST(seed1 != seed2); // very unlikely that they are the same
keypairsign<sodium::bytes_protected> keypair1(seed1);
keypairsign<sodium::bytes_protected> keypair2(seed2); // different seed
BOOST_TEST(!sodium::compare(keypair1.public_key(),
keypair2.public_key()));
BOOST_TEST(!sodium::compare(keypair1.private_key(),
keypair2.private_key()));
BOOST_TEST((keypair1 != keypair2)); // check also operator!=()
}
BOOST_AUTO_TEST_CASE(sodium_test_keypairsign_seedcompare_extract_seed_bytes_protected)
{
bytes seed1(ks_seed);
sodium::randombytes_buf_inplace(seed1);
keypairsign<sodium::bytes_protected> keypair(seed1);
// reconstruct seed from private key stored in keypair
bytes seed2 = keypair.seed();
BOOST_TEST(seed1 == seed2);
}
// 3. sodium::chars -------------------------------------------------------
BOOST_AUTO_TEST_CASE(sodium_test_keypairsign_size_ctor_default_chars)
{
keypairsign<sodium::chars> keypair;
BOOST_TEST(keypair.public_key().size() == ks_pub);
BOOST_TEST(keypair.private_key().size() == ks_priv);
}
BOOST_AUTO_TEST_CASE(sodium_test_keypairsign_size_ctor_seed_chars)
{
bytes seed(ks_seed);
sodium::randombytes_buf_inplace(seed);
keypairsign<sodium::chars> keypair(seed);
BOOST_TEST(keypair.public_key().size() == ks_pub);
BOOST_TEST(keypair.private_key().size() == ks_priv);
}
BOOST_AUTO_TEST_CASE(sodium_test_keypairsign_size_ctor_privkey_chars)
{
keypairsign<sodium::chars> keypair1;
keypairsign<sodium::chars> keypair2(keypair1.private_key().data(), keypair1.private_key().size());
BOOST_TEST(keypair2.public_key().size() == ks_pub);
BOOST_TEST(keypair2.private_key().size() == ks_priv);
}
BOOST_AUTO_TEST_CASE(sodium_test_keypairsign_copy_ctor_chars)
{
keypairsign<sodium::chars> keypair;
keypairsign<sodium::chars> keypair_copy{ keypair };
BOOST_TEST((keypair == keypair_copy)); // check also operator==()
BOOST_TEST((keypair.private_key() == keypair_copy.private_key())); // key::operator==()
BOOST_TEST(keypair.public_key() == keypair_copy.public_key()); // std::vector::operator==()
}
BOOST_AUTO_TEST_CASE(sodium_test_keypairsign_copy_assignement_chars)
{
keypairsign<sodium::chars> keypair;
keypairsign<sodium::chars> keypair_copy = keypair;
BOOST_TEST((keypair == keypair_copy));
BOOST_TEST((keypair.private_key() == keypair_copy.private_key()));
BOOST_TEST(keypair.public_key() == keypair_copy.public_key());
}
BOOST_AUTO_TEST_CASE(sodium_test_keypairsign_nonzero_ctor_default_chars)
{
keypairsign<sodium::chars> keypair;
BOOST_TEST(!sodium::is_zero(keypair.public_key()));
BOOST_TEST(!sodium::is_zero(keypair.private_key()));
}
BOOST_AUTO_TEST_CASE(sodium_test_keypairsign_nonzero_ctor_seed_chars)
{
bytes seed(ks_seed);
sodium::randombytes_buf_inplace(seed);
keypairsign<sodium::chars> keypair(seed);
BOOST_TEST(!sodium::is_zero(keypair.public_key()));
BOOST_TEST(!sodium::is_zero(keypair.private_key()));
}
BOOST_AUTO_TEST_CASE(sodium_test_keypairsign_nonzero_ctor_privkey_chars)
{
keypairsign<sodium::chars> keypair1;
keypairsign<sodium::chars> keypair2(keypair1.private_key().data(), keypair1.private_key().size());
BOOST_TEST(!sodium::is_zero(keypair2.public_key()));
BOOST_TEST(!sodium::is_zero(keypair2.private_key()));
}
BOOST_AUTO_TEST_CASE(sodium_test_keypairsign_seedcompare_ctor_same_seed_chars)
{
bytes seed(ks_seed);
sodium::randombytes_buf_inplace(seed);
keypairsign<sodium::chars> keypair1(seed);
keypairsign<sodium::chars> keypair2(seed); // same seed
BOOST_TEST(sodium::compare(keypair1.public_key(),
keypair2.public_key()));
BOOST_TEST(sodium::compare(keypair1.private_key(),
keypair2.private_key()));
BOOST_TEST((keypair1 == keypair2)); // check also operator==()
BOOST_TEST((keypair1.private_key() == keypair2.private_key()));
BOOST_TEST(keypair1.public_key() == keypair2.public_key());
}
BOOST_AUTO_TEST_CASE(sodium_test_keypairsign_seedcompare_ctor_different_seed_chars)
{
bytes seed1(ks_seed);
sodium::randombytes_buf_inplace(seed1);
bytes seed2(ks_seed);
sodium::randombytes_buf_inplace(seed2);
BOOST_TEST(seed1 != seed2); // very unlikely that they are the same
keypairsign<sodium::chars> keypair1(seed1);
keypairsign<sodium::chars> keypair2(seed2); // different seed
BOOST_TEST(!sodium::compare(keypair1.public_key(),
keypair2.public_key()));
BOOST_TEST(!sodium::compare(keypair1.private_key(),
keypair2.private_key()));
BOOST_TEST((keypair1 != keypair2)); // check also operator!=()
}
BOOST_AUTO_TEST_CASE(sodium_test_keypairsign_seedcompare_extract_seed_chars)
{
bytes seed1(ks_seed);
sodium::randombytes_buf_inplace(seed1);
keypairsign<sodium::chars> keypair(seed1);
// reconstruct seed from private key stored in keypair
bytes seed2 = keypair.seed();
BOOST_TEST(seed1 == seed2);
}
BOOST_AUTO_TEST_SUITE_END ()
<|endoftext|> |
<commit_before>#include "controlpanel.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
controlPanel::controlPanel(QWidget *parent) :
QWidget(parent),
_playPauseButton(new QPushButton("Play/Pause")),
_nextButton(new QPushButton("Next")),
_previousButton(new QPushButton("Previous")),
_volumeSlider(new QSlider(Qt::Horizontal)),
_currentState(controlPanel::Paused)
{
_volumeSlider->setRange(0,100);
_volumeSlider->setValue(50);
QVBoxLayout * layout = new QVBoxLayout;
QHBoxLayout * buttonLayout = new QHBoxLayout;
QHBoxLayout * optionsLayout = new QHBoxLayout;
buttonLayout->addWidget(_previousButton);
buttonLayout->addWidget(_playPauseButton);
buttonLayout->addWidget(_nextButton);
optionsLayout->addWidget(_volumeSlider);
layout->addLayout(optionsLayout);
layout->addLayout(buttonLayout);
this->setLayout(layout);
}
const QObject * controlPanel::widget(Widget widget)
{
if(widget == controlPanel::PlayPauseButton)
return _playPauseButton;
else if(widget == controlPanel::NextButton)
return _nextButton;
else if(widget == controlPanel::PreviousButton)
return _previousButton;
else if(widget == controlPanel::VolumeSlider)
return _volumeSlider;
else return new QObject;
}
void controlPanel::setPlayButtonIcon(const QIcon &icon)
{
_playButtonIcon = icon;
_playPauseButton->text().clear();
if(_currentState == controlPanel::Paused)
_playPauseButton->setIcon(icon);
}
void controlPanel::setPauseButtonIcon(const QIcon &icon)
{
_pauseButtonIcon = icon;
_playPauseButton->text().clear();
if(_currentState == controlPanel::Playing)
_playPauseButton->setIcon(icon);
}
void controlPanel::setNextButtonIcon(const QIcon &icon)
{
_nextButton->text().clear();
_nextButton->setIcon(icon);
}
void controlPanel::setPreviousButtonIcon(const QIcon &icon)
{
_previousButton->text().clear();
_previousButton->setIcon(icon);
}
void controlPanel::togglePlayPauseState()
{
if(_currentState == controlPanel::Paused)
{
_currentState = controlPanel::Playing;
if(!_playButtonIcon.isNull())
_playPauseButton->setIcon(_pauseButtonIcon);
else
{
_playPauseButton->setIcon(QIcon());
_playPauseButton->setText("Pause");
}
}
else if(_currentState == controlPanel::Playing)
{
_currentState = controlPanel::Paused;
if(!_pauseButtonIcon.isNull())
_playPauseButton->setIcon(_playButtonIcon);
else
{
_playPauseButton->setIcon(QIcon());
_playPauseButton->setText("Play");
}
}
}
<commit_msg>Got rid of unecessary code in togglePlayPauseState function.<commit_after>#include "controlpanel.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
controlPanel::controlPanel(QWidget *parent) :
QWidget(parent),
_playPauseButton(new QPushButton("Play/Pause")),
_nextButton(new QPushButton("Next")),
_previousButton(new QPushButton("Previous")),
_volumeSlider(new QSlider(Qt::Horizontal)),
_currentState(controlPanel::Paused)
{
_volumeSlider->setRange(0,100);
_volumeSlider->setValue(50);
QVBoxLayout * layout = new QVBoxLayout;
QHBoxLayout * buttonLayout = new QHBoxLayout;
QHBoxLayout * optionsLayout = new QHBoxLayout;
buttonLayout->addWidget(_previousButton);
buttonLayout->addWidget(_playPauseButton);
buttonLayout->addWidget(_nextButton);
optionsLayout->addWidget(_volumeSlider);
layout->addLayout(optionsLayout);
layout->addLayout(buttonLayout);
this->setLayout(layout);
}
const QObject * controlPanel::widget(Widget widget)
{
if(widget == controlPanel::PlayPauseButton)
return _playPauseButton;
else if(widget == controlPanel::NextButton)
return _nextButton;
else if(widget == controlPanel::PreviousButton)
return _previousButton;
else if(widget == controlPanel::VolumeSlider)
return _volumeSlider;
else return new QObject;
}
void controlPanel::setPlayButtonIcon(const QIcon &icon)
{
_playButtonIcon = icon;
_playPauseButton->text().clear();
if(_currentState == controlPanel::Paused)
_playPauseButton->setIcon(icon);
}
void controlPanel::setPauseButtonIcon(const QIcon &icon)
{
_pauseButtonIcon = icon;
_playPauseButton->text().clear();
if(_currentState == controlPanel::Playing)
_playPauseButton->setIcon(icon);
}
void controlPanel::setNextButtonIcon(const QIcon &icon)
{
_nextButton->text().clear();
_nextButton->setIcon(icon);
}
void controlPanel::setPreviousButtonIcon(const QIcon &icon)
{
_previousButton->text().clear();
_previousButton->setIcon(icon);
}
void controlPanel::togglePlayPauseState()
{
if(_currentState == controlPanel::Paused)
{
_currentState = controlPanel::Playing;
if(!_playButtonIcon.isNull())
_playPauseButton->setIcon(_pauseButtonIcon);
else
_playPauseButton->setIcon(QIcon());
}
else if(_currentState == controlPanel::Playing)
{
_currentState = controlPanel::Paused;
if(!_pauseButtonIcon.isNull())
_playPauseButton->setIcon(_playButtonIcon);
else
_playPauseButton->setIcon(QIcon());
}
}
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Modified by Cloudius Systems.
* Copyright 2015 Cloudius Systems.
*/
#pragma once
#include "types.hh"
#include "core/sstring.hh"
#include "util/serialization.hh"
#include "gms/gossip_digest.hh"
namespace gms {
/**
* This is the first message that gets sent out as a start of the Gossip protocol in a
* round.
*/
class gossip_digest_syn {
private:
const sstring _cluster_id;
const sstring _partioner;
const std::vector<gossip_digest> _digests;
public:
gossip_digest_syn(sstring id, sstring p, std::vector<gossip_digest> digests)
: _cluster_id(id)
, _partioner(p)
, _digests(digests) {
}
std::vector<gossip_digest> get_gossip_digests() {
return _digests;
}
// The following replaces GossipDigestSynSerializer from the Java code
void serialize(bytes::iterator& out) const {
serialize_string(out, _cluster_id);
serialize_string(out, _partioner);
gossip_digest_serialization_helper::serialize(out, _digests);
}
static gossip_digest_syn deserialize(bytes_view& v) {
sstring cluster_id = read_simple_short_string(v);
sstring partioner = read_simple_short_string(v);
std::vector<gossip_digest> digests = gossip_digest_serialization_helper::deserialize(v);
return gossip_digest_syn(cluster_id, partioner, std::move(digests));
}
size_t serialized_size() const {
return serialize_string_size(_cluster_id) + serialize_string_size(_partioner) +
gossip_digest_serialization_helper::serialized_size(_digests);
}
};
}
<commit_msg>gossip: Remove const for gossip_digest_syn<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Modified by Cloudius Systems.
* Copyright 2015 Cloudius Systems.
*/
#pragma once
#include "types.hh"
#include "core/sstring.hh"
#include "util/serialization.hh"
#include "gms/gossip_digest.hh"
namespace gms {
/**
* This is the first message that gets sent out as a start of the Gossip protocol in a
* round.
*/
class gossip_digest_syn {
private:
sstring _cluster_id;
sstring _partioner;
std::vector<gossip_digest> _digests;
public:
gossip_digest_syn(sstring id, sstring p, std::vector<gossip_digest> digests)
: _cluster_id(id)
, _partioner(p)
, _digests(digests) {
}
std::vector<gossip_digest> get_gossip_digests() {
return _digests;
}
// The following replaces GossipDigestSynSerializer from the Java code
void serialize(bytes::iterator& out) const {
serialize_string(out, _cluster_id);
serialize_string(out, _partioner);
gossip_digest_serialization_helper::serialize(out, _digests);
}
static gossip_digest_syn deserialize(bytes_view& v) {
sstring cluster_id = read_simple_short_string(v);
sstring partioner = read_simple_short_string(v);
std::vector<gossip_digest> digests = gossip_digest_serialization_helper::deserialize(v);
return gossip_digest_syn(cluster_id, partioner, std::move(digests));
}
size_t serialized_size() const {
return serialize_string_size(_cluster_id) + serialize_string_size(_partioner) +
gossip_digest_serialization_helper::serialized_size(_digests);
}
};
}
<|endoftext|> |
<commit_before>/*
* Copyright 2017 CodiLime
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <QAction>
#include <QApplication>
#include <QFileDialog>
#include <QMenuBar>
#include <QMessageBox>
#include <QUrl>
#include <QMenu>
#include "db/db.h"
#include "dbif/method.h"
#include "dbif/promise.h"
#include "dbif/types.h"
#include "dbif/universe.h"
#include "client/dbif.h"
#include "util/version.h"
#include "ui/databaseinfo.h"
#include "ui/veles_mainwindow.h"
#include "ui/hexeditwidget.h"
#include "ui/nodetreewidget.h"
#include "ui/optionsdialog.h"
#include "ui/logwidget.h"
#include "ui/nodewidget.h"
namespace veles {
namespace ui {
/*****************************************************************************/
/* VelesMainWindow - Public methods */
/*****************************************************************************/
VelesMainWindow::VelesMainWindow() : MainWindowWithDetachableDockWidgets(),
database_dock_widget_(0), log_dock_widget_(0) {
setAcceptDrops(true);
resize(1024, 768);
init();
}
void VelesMainWindow::addFile(const QString& path) {
files_to_upload_once_connected_.push_back(path);
}
/*****************************************************************************/
/* VelesMainWindow - Protected methods */
/*****************************************************************************/
void VelesMainWindow::dropEvent(QDropEvent *ev) {
QList<QUrl> urls = ev->mimeData()->urls();
for (auto url : urls) {
if (!url.isLocalFile()) {
continue;
}
createFileBlob(url.toLocalFile());
}
}
void VelesMainWindow::dragEnterEvent(QDragEnterEvent *ev) { ev->accept(); }
void VelesMainWindow::showEvent(QShowEvent* event) {
emit shown();
}
/*****************************************************************************/
/* VelesMainWindow - Private Slots */
/*****************************************************************************/
void VelesMainWindow::open() {
QString fileName = QFileDialog::getOpenFileName(this);
if (!fileName.isEmpty()) {
createFileBlob(fileName);
}
}
void VelesMainWindow::newFile() { createFileBlob(""); }
void VelesMainWindow::about() {
QMessageBox::about(
this, tr("About Veles"),
tr("This is Veles, a binary analysis tool and editor.\n"
"Version: %1\n"
"\n"
"Report bugs to contact@veles.io\n"
"https://veles.io/\n"
"\n"
"Copyright 2017 CodiLime\n"
"Licensed under the Apache License, Version 2.0\n"
).arg(util::version::string));
}
/*****************************************************************************/
/* VelesMainWindow - Private methods */
/*****************************************************************************/
void VelesMainWindow::init() {
connection_manager_ = new ConnectionManager(this);
createActions();
createMenus();
createLogWindow();
createDb();
options_dialog_ = new OptionsDialog(this);
connect(options_dialog_, &QDialog::accepted, [this]() {
for(auto main_window : MainWindowWithDetachableDockWidgets
::getMainWindows()) {
QList<View*> views = main_window->findChildren<View*>();
for(auto view : views) {
view->reapplySettings();
}
}
});
tool_bar_ = addToolBar("Connection");
tool_bar_->setContextMenuPolicy(Qt::PreventContextMenu);
ConnectionsWidget* connections_widget = new ConnectionsWidget(this);
tool_bar_->addWidget(connections_widget);
connect(connection_manager_, &ConnectionManager::connectionStatusChanged,
connections_widget,
&ConnectionsWidget::updateConnectionStatus);
connect(connection_manager_, &ConnectionManager::connectionsChanged,
connections_widget, &ConnectionsWidget::updateConnections);
connection_notification_widget_ = new ConnectionNotificationWidget(this);
connect(connection_manager_, &ConnectionManager::connectionStatusChanged,
connection_notification_widget_,
&ConnectionNotificationWidget::updateConnectionStatus);
connect(connection_manager_, &ConnectionManager::connectionStatusChanged,
this, &VelesMainWindow::updateConnectionStatus, Qt::QueuedConnection);
tool_bar_->addWidget(connection_notification_widget_);
bringDockWidgetToFront(log_dock_widget_);
log_dock_widget_->setFocus(Qt::OtherFocusReason);
connection_manager_->connectionDialogAccepted();
connect(this, &VelesMainWindow::shown,
connection_manager_, &ConnectionManager::raiseConnectionDialog,
Qt::QueuedConnection);
updateConnectionStatus(
client::NetworkClient::ConnectionStatus::NotConnected);
}
void VelesMainWindow::createActions() {
new_file_act_ = new QAction(tr("&New..."), this);
new_file_act_->setShortcuts(QKeySequence::New);
new_file_act_->setStatusTip(tr("Open a new file"));
connect(new_file_act_, SIGNAL(triggered()), this, SLOT(newFile()));
open_act_ = new QAction(QIcon(":/images/open.png"), tr("&Open..."), this);
open_act_->setShortcuts(QKeySequence::Open);
open_act_->setStatusTip(tr("Open an existing file"));
connect(open_act_, SIGNAL(triggered()), this, SLOT(open()));
exit_act_ = new QAction(tr("E&xit"), this);
exit_act_->setShortcuts(QKeySequence::Quit);
exit_act_->setStatusTip(tr("Exit the application"));
connect(exit_act_, SIGNAL(triggered()), qApp, SLOT(closeAllWindows()));
show_database_act_ = new QAction(tr("Show database view"), this);
show_database_act_->setStatusTip(tr("Show database view"));
connect(show_database_act_, SIGNAL(triggered()), this, SLOT(showDatabase()));
show_log_act_ = new QAction(tr("Show log"), this);
show_log_act_->setStatusTip(tr("Show log"));
connect(show_log_act_, SIGNAL(triggered()), this, SLOT(showLog()));
about_act_ = new QAction(tr("&About"), this);
about_act_->setStatusTip(tr("Show the application's About box"));
connect(about_act_, SIGNAL(triggered()), this, SLOT(about()));
about_qt_act_ = new QAction(tr("About &Qt"), this);
about_qt_act_->setStatusTip(tr("Show the Qt library's About box"));
connect(about_qt_act_, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
options_act_ = new QAction(tr("&Options"), this);
options_act_->setStatusTip(
tr("Show the Dialog to select applications options"));
connect(options_act_, &QAction::triggered, this,
[this]() { options_dialog_->show(); });
}
void VelesMainWindow::createMenus() {
file_menu_ = menuBar()->addMenu(tr("&File"));
//Not implemented yet.
//fileMenu->addAction(newFileAct);
file_menu_->addAction(open_act_);
file_menu_->addSeparator();
file_menu_->addAction(options_act_);
file_menu_->addSeparator();
file_menu_->addAction(exit_act_);
view_menu_ = menuBar()->addMenu(tr("&View"));
view_menu_->addAction(show_database_act_);
view_menu_->addAction(show_log_act_);
QMenu* connection_menu = menuBar()->addMenu(tr("Connection"));
connection_menu->addAction(
connection_manager_->showConnectionDialogAction());
connection_menu->addAction(connection_manager_->disconnectAction());
connection_menu->addAction(
connection_manager_->killLocallyCreatedServerAction());
help_menu_ = menuBar()->addMenu(tr("&Help"));
help_menu_->addAction(about_act_);
help_menu_->addAction(about_qt_act_);
}
void VelesMainWindow::updateParsers(dbif::PInfoReply reply) {
parsers_list_ = reply.dynamicCast<dbif::ParsersListRequest::ReplyType>()->parserIds;
QList<QDockWidget*> dock_widgets = findChildren<QDockWidget*>();
for(auto dock : dock_widgets) {
if(auto hex_tab = dynamic_cast<HexEditWidget *>(dock->widget())) {
hex_tab->setParserIds(parsers_list_);
} else if(auto node_tab = dynamic_cast<NodeTreeWidget *>(dock->widget())) {
node_tab->setParserIds(parsers_list_);
}
}
}
void VelesMainWindow::showDatabase() {
if (database_dock_widget_ == nullptr) {
createDb();
}
database_dock_widget_->raise();
if (database_dock_widget_->window()->isMinimized()) {
database_dock_widget_->window()->showNormal();
}
database_dock_widget_->window()->raise();
}
void VelesMainWindow::showLog() {
if (log_dock_widget_ == nullptr) {
createLogWindow();
}
log_dock_widget_->raise();
if(log_dock_widget_->window()->isMinimized()) {
log_dock_widget_->window()->showNormal();
}
log_dock_widget_->window()->raise();
}
void VelesMainWindow::updateConnectionStatus(
client::NetworkClient::ConnectionStatus connection_status) {
if (connection_status
== client::NetworkClient::ConnectionStatus::NotConnected) {
auto main_windows = MainWindowWithDetachableDockWidgets::allMainWindows();
for (auto main_window : main_windows) {
auto docks = main_window->findChildren<DockWidget*>();
for(auto dock : docks) {
if(dock != log_dock_widget_ && dock != database_dock_widget_) {
dock->close();
}
}
}
database_dock_widget_->widget()->setEnabled(false);
open_act_->setEnabled(false);
} else if (connection_status
== client::NetworkClient::ConnectionStatus::Connected) {
database_dock_widget_->widget()->setEnabled(true);
open_act_->setEnabled(true);
if (!files_to_upload_once_connected_.empty()) {
QTextStream out(LogWidget::output());
out << "Uploading files specified as command line arguments:" << endl;
for (const auto& path : files_to_upload_once_connected_) {
out << " " << path << endl;
createFileBlob(path);
QApplication::processEvents();
}
files_to_upload_once_connected_.clear();
}
}
}
void VelesMainWindow::createDb() {
if (database_ == nullptr) {
#if 0
database_ = db::create_db();
#else
auto nc = new client::NCWrapper(
connection_manager_->networkClient(), this);
database_ = QSharedPointer<client::NCObjectHandle>::create(
nc, *data::NodeID::getRootNodeId(), dbif::ObjectType::ROOT);
#endif
}
auto database_info = new DatabaseInfo(database_);
DockWidget* dock_widget = new DockWidget;
dock_widget->setAllowedAreas(Qt::AllDockWidgetAreas);
dock_widget->setWindowTitle("Database");
dock_widget->setFeatures(
QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable);
dock_widget->setWidget(database_info);
dock_widget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
auto children = findChildren<DockWidget*>();
if (!children.empty()) {
tabifyDockWidget(children.back(), dock_widget);
} else {
addDockWidget(Qt::LeftDockWidgetArea, dock_widget);
}
connect(database_info, &DatabaseInfo::goFile,
[this](dbif::ObjectHandle fileBlob, QString fileName) {
createHexEditTab(fileName, fileBlob);
});
connect(database_info, &DatabaseInfo::newFile, [this]() { open(); });
auto promise = database_->asyncSubInfo<dbif::ParsersListRequest>(this);
connect(promise, &dbif::InfoPromise::gotInfo, this, &VelesMainWindow::updateParsers);
database_dock_widget_ = dock_widget;
QApplication::processEvents();
updateDocksAndTabs();
}
void VelesMainWindow::createFileBlob(QString fileName) {
data::BinData data(8, 0);
if (!fileName.isEmpty()) {
QFile file(fileName);
file.setFileName(fileName);
if(!file.open(QIODevice::ReadOnly)){
QMessageBox::warning(
this, tr("Failed to open"),
QString(tr("Failed to open \"%1\".")).arg(fileName));
return;
}
QByteArray bytes = file.readAll();
if(bytes.size() == 0 && file.size() != bytes.size()) {
QMessageBox::warning(
this, tr("File too large"),
QString(tr("Failed to open \"%1\" due to current size limitation.")
).arg(fileName));
return;
}
data = data::BinData(8, bytes.size(),
reinterpret_cast<uint8_t *>(bytes.data()));
}
auto promise =
database_->asyncRunMethod<dbif::RootCreateFileBlobFromDataRequest>(
this, data, fileName);
connect(promise, &dbif::MethodResultPromise::gotResult,
[this, fileName](dbif::PMethodReply reply) {
createHexEditTab(
fileName.isEmpty() ? "untitled" : fileName,
reply.dynamicCast<dbif::RootCreateFileBlobFromDataRequest::ReplyType>()
->object);
});
connect(promise, &dbif::MethodResultPromise::gotError,
[this, fileName](dbif::PError error) {
QMessageBox::warning(this, tr("Veles"),
tr("Cannot load file %1.").arg(fileName));
});
}
void VelesMainWindow::createHexEditTab(QString fileName,
dbif::ObjectHandle fileBlob) {
QSharedPointer<FileBlobModel> data_model(
new FileBlobModel(fileBlob, {QFileInfo(fileName).fileName()}));
QSharedPointer<QItemSelectionModel> selection_model(
new QItemSelectionModel(data_model.data()));
NodeWidget* node_widget = new NodeWidget(this, data_model, selection_model);
addTab(node_widget, data_model->path().join(" : "), nullptr);
}
void VelesMainWindow::createLogWindow() {
DockWidget* dock_widget = new DockWidget;
dock_widget->setAllowedAreas(Qt::AllDockWidgetAreas);
dock_widget->setWindowTitle("Log");
dock_widget->setFeatures(
QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable);
dock_widget->setWidget(new LogWidget);
dock_widget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
auto children = findChildren<DockWidget*>();
if (!children.empty()) {
tabifyDockWidget(children.back(), dock_widget);
} else {
addDockWidget(Qt::LeftDockWidgetArea, dock_widget);
}
log_dock_widget_ = dock_widget;
QApplication::processEvents();
updateDocksAndTabs();
}
} // namespace ui
} // namespace veles
<commit_msg>(Dis)connecting doesn't cause a crash when database tab is closed<commit_after>/*
* Copyright 2017 CodiLime
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <QAction>
#include <QApplication>
#include <QFileDialog>
#include <QMenuBar>
#include <QMessageBox>
#include <QUrl>
#include <QMenu>
#include "db/db.h"
#include "dbif/method.h"
#include "dbif/promise.h"
#include "dbif/types.h"
#include "dbif/universe.h"
#include "client/dbif.h"
#include "util/version.h"
#include "ui/databaseinfo.h"
#include "ui/veles_mainwindow.h"
#include "ui/hexeditwidget.h"
#include "ui/nodetreewidget.h"
#include "ui/optionsdialog.h"
#include "ui/logwidget.h"
#include "ui/nodewidget.h"
namespace veles {
namespace ui {
/*****************************************************************************/
/* VelesMainWindow - Public methods */
/*****************************************************************************/
VelesMainWindow::VelesMainWindow() : MainWindowWithDetachableDockWidgets(),
database_dock_widget_(0), log_dock_widget_(0) {
setAcceptDrops(true);
resize(1024, 768);
init();
}
void VelesMainWindow::addFile(const QString& path) {
files_to_upload_once_connected_.push_back(path);
}
/*****************************************************************************/
/* VelesMainWindow - Protected methods */
/*****************************************************************************/
void VelesMainWindow::dropEvent(QDropEvent *ev) {
QList<QUrl> urls = ev->mimeData()->urls();
for (auto url : urls) {
if (!url.isLocalFile()) {
continue;
}
createFileBlob(url.toLocalFile());
}
}
void VelesMainWindow::dragEnterEvent(QDragEnterEvent *ev) { ev->accept(); }
void VelesMainWindow::showEvent(QShowEvent* event) {
emit shown();
}
/*****************************************************************************/
/* VelesMainWindow - Private Slots */
/*****************************************************************************/
void VelesMainWindow::open() {
QString fileName = QFileDialog::getOpenFileName(this);
if (!fileName.isEmpty()) {
createFileBlob(fileName);
}
}
void VelesMainWindow::newFile() { createFileBlob(""); }
void VelesMainWindow::about() {
QMessageBox::about(
this, tr("About Veles"),
tr("This is Veles, a binary analysis tool and editor.\n"
"Version: %1\n"
"\n"
"Report bugs to contact@veles.io\n"
"https://veles.io/\n"
"\n"
"Copyright 2017 CodiLime\n"
"Licensed under the Apache License, Version 2.0\n"
).arg(util::version::string));
}
/*****************************************************************************/
/* VelesMainWindow - Private methods */
/*****************************************************************************/
void VelesMainWindow::init() {
connection_manager_ = new ConnectionManager(this);
createActions();
createMenus();
createLogWindow();
createDb();
options_dialog_ = new OptionsDialog(this);
connect(options_dialog_, &QDialog::accepted, [this]() {
for(auto main_window : MainWindowWithDetachableDockWidgets
::getMainWindows()) {
QList<View*> views = main_window->findChildren<View*>();
for(auto view : views) {
view->reapplySettings();
}
}
});
tool_bar_ = addToolBar("Connection");
tool_bar_->setContextMenuPolicy(Qt::PreventContextMenu);
ConnectionsWidget* connections_widget = new ConnectionsWidget(this);
tool_bar_->addWidget(connections_widget);
connect(connection_manager_, &ConnectionManager::connectionStatusChanged,
connections_widget,
&ConnectionsWidget::updateConnectionStatus);
connect(connection_manager_, &ConnectionManager::connectionsChanged,
connections_widget, &ConnectionsWidget::updateConnections);
connection_notification_widget_ = new ConnectionNotificationWidget(this);
connect(connection_manager_, &ConnectionManager::connectionStatusChanged,
connection_notification_widget_,
&ConnectionNotificationWidget::updateConnectionStatus);
connect(connection_manager_, &ConnectionManager::connectionStatusChanged,
this, &VelesMainWindow::updateConnectionStatus, Qt::QueuedConnection);
tool_bar_->addWidget(connection_notification_widget_);
bringDockWidgetToFront(log_dock_widget_);
log_dock_widget_->setFocus(Qt::OtherFocusReason);
connection_manager_->connectionDialogAccepted();
connect(this, &VelesMainWindow::shown,
connection_manager_, &ConnectionManager::raiseConnectionDialog,
Qt::QueuedConnection);
updateConnectionStatus(
client::NetworkClient::ConnectionStatus::NotConnected);
}
void VelesMainWindow::createActions() {
new_file_act_ = new QAction(tr("&New..."), this);
new_file_act_->setShortcuts(QKeySequence::New);
new_file_act_->setStatusTip(tr("Open a new file"));
connect(new_file_act_, SIGNAL(triggered()), this, SLOT(newFile()));
open_act_ = new QAction(QIcon(":/images/open.png"), tr("&Open..."), this);
open_act_->setShortcuts(QKeySequence::Open);
open_act_->setStatusTip(tr("Open an existing file"));
connect(open_act_, SIGNAL(triggered()), this, SLOT(open()));
exit_act_ = new QAction(tr("E&xit"), this);
exit_act_->setShortcuts(QKeySequence::Quit);
exit_act_->setStatusTip(tr("Exit the application"));
connect(exit_act_, SIGNAL(triggered()), qApp, SLOT(closeAllWindows()));
show_database_act_ = new QAction(tr("Show database view"), this);
show_database_act_->setStatusTip(tr("Show database view"));
connect(show_database_act_, SIGNAL(triggered()), this, SLOT(showDatabase()));
show_log_act_ = new QAction(tr("Show log"), this);
show_log_act_->setStatusTip(tr("Show log"));
connect(show_log_act_, SIGNAL(triggered()), this, SLOT(showLog()));
about_act_ = new QAction(tr("&About"), this);
about_act_->setStatusTip(tr("Show the application's About box"));
connect(about_act_, SIGNAL(triggered()), this, SLOT(about()));
about_qt_act_ = new QAction(tr("About &Qt"), this);
about_qt_act_->setStatusTip(tr("Show the Qt library's About box"));
connect(about_qt_act_, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
options_act_ = new QAction(tr("&Options"), this);
options_act_->setStatusTip(
tr("Show the Dialog to select applications options"));
connect(options_act_, &QAction::triggered, this,
[this]() { options_dialog_->show(); });
}
void VelesMainWindow::createMenus() {
file_menu_ = menuBar()->addMenu(tr("&File"));
//Not implemented yet.
//fileMenu->addAction(newFileAct);
file_menu_->addAction(open_act_);
file_menu_->addSeparator();
file_menu_->addAction(options_act_);
file_menu_->addSeparator();
file_menu_->addAction(exit_act_);
view_menu_ = menuBar()->addMenu(tr("&View"));
view_menu_->addAction(show_database_act_);
view_menu_->addAction(show_log_act_);
QMenu* connection_menu = menuBar()->addMenu(tr("Connection"));
connection_menu->addAction(
connection_manager_->showConnectionDialogAction());
connection_menu->addAction(connection_manager_->disconnectAction());
connection_menu->addAction(
connection_manager_->killLocallyCreatedServerAction());
help_menu_ = menuBar()->addMenu(tr("&Help"));
help_menu_->addAction(about_act_);
help_menu_->addAction(about_qt_act_);
}
void VelesMainWindow::updateParsers(dbif::PInfoReply reply) {
parsers_list_ = reply.dynamicCast<dbif::ParsersListRequest::ReplyType>()->parserIds;
QList<QDockWidget*> dock_widgets = findChildren<QDockWidget*>();
for(auto dock : dock_widgets) {
if(auto hex_tab = dynamic_cast<HexEditWidget *>(dock->widget())) {
hex_tab->setParserIds(parsers_list_);
} else if(auto node_tab = dynamic_cast<NodeTreeWidget *>(dock->widget())) {
node_tab->setParserIds(parsers_list_);
}
}
}
void VelesMainWindow::showDatabase() {
if (database_dock_widget_ == nullptr) {
createDb();
}
database_dock_widget_->raise();
if (database_dock_widget_->window()->isMinimized()) {
database_dock_widget_->window()->showNormal();
}
database_dock_widget_->window()->raise();
}
void VelesMainWindow::showLog() {
if (log_dock_widget_ == nullptr) {
createLogWindow();
}
log_dock_widget_->raise();
if(log_dock_widget_->window()->isMinimized()) {
log_dock_widget_->window()->showNormal();
}
log_dock_widget_->window()->raise();
}
void VelesMainWindow::updateConnectionStatus(
client::NetworkClient::ConnectionStatus connection_status) {
if (connection_status
== client::NetworkClient::ConnectionStatus::NotConnected) {
auto main_windows = MainWindowWithDetachableDockWidgets::allMainWindows();
for (auto main_window : main_windows) {
auto docks = main_window->findChildren<DockWidget*>();
for(auto dock : docks) {
if(dock != log_dock_widget_ && dock != database_dock_widget_) {
dock->close();
}
}
}
if (database_dock_widget_) {
database_dock_widget_->widget()->setEnabled(false);
}
open_act_->setEnabled(false);
} else if (connection_status
== client::NetworkClient::ConnectionStatus::Connected) {
if (database_dock_widget_) {
database_dock_widget_->widget()->setEnabled(true);
}
open_act_->setEnabled(true);
if (!files_to_upload_once_connected_.empty()) {
QTextStream out(LogWidget::output());
out << "Uploading files specified as command line arguments:" << endl;
for (const auto& path : files_to_upload_once_connected_) {
out << " " << path << endl;
createFileBlob(path);
QApplication::processEvents();
}
files_to_upload_once_connected_.clear();
}
}
}
void VelesMainWindow::createDb() {
if (database_ == nullptr) {
#if 0
database_ = db::create_db();
#else
auto nc = new client::NCWrapper(
connection_manager_->networkClient(), this);
database_ = QSharedPointer<client::NCObjectHandle>::create(
nc, *data::NodeID::getRootNodeId(), dbif::ObjectType::ROOT);
#endif
}
auto database_info = new DatabaseInfo(database_);
DockWidget* dock_widget = new DockWidget;
dock_widget->setAllowedAreas(Qt::AllDockWidgetAreas);
dock_widget->setWindowTitle("Database");
dock_widget->setFeatures(
QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable);
dock_widget->setWidget(database_info);
dock_widget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
auto children = findChildren<DockWidget*>();
if (!children.empty()) {
tabifyDockWidget(children.back(), dock_widget);
} else {
addDockWidget(Qt::LeftDockWidgetArea, dock_widget);
}
connect(database_info, &DatabaseInfo::goFile,
[this](dbif::ObjectHandle fileBlob, QString fileName) {
createHexEditTab(fileName, fileBlob);
});
connect(database_info, &DatabaseInfo::newFile, [this]() { open(); });
database_info->setEnabled(
connection_manager_->networkClient()->connectionStatus()
== client::NetworkClient::ConnectionStatus::Connected);
auto promise = database_->asyncSubInfo<dbif::ParsersListRequest>(this);
connect(promise, &dbif::InfoPromise::gotInfo, this, &VelesMainWindow::updateParsers);
database_dock_widget_ = dock_widget;
QApplication::processEvents();
updateDocksAndTabs();
}
void VelesMainWindow::createFileBlob(QString fileName) {
data::BinData data(8, 0);
if (!fileName.isEmpty()) {
QFile file(fileName);
file.setFileName(fileName);
if(!file.open(QIODevice::ReadOnly)){
QMessageBox::warning(
this, tr("Failed to open"),
QString(tr("Failed to open \"%1\".")).arg(fileName));
return;
}
QByteArray bytes = file.readAll();
if(bytes.size() == 0 && file.size() != bytes.size()) {
QMessageBox::warning(
this, tr("File too large"),
QString(tr("Failed to open \"%1\" due to current size limitation.")
).arg(fileName));
return;
}
data = data::BinData(8, bytes.size(),
reinterpret_cast<uint8_t *>(bytes.data()));
}
auto promise =
database_->asyncRunMethod<dbif::RootCreateFileBlobFromDataRequest>(
this, data, fileName);
connect(promise, &dbif::MethodResultPromise::gotResult,
[this, fileName](dbif::PMethodReply reply) {
createHexEditTab(
fileName.isEmpty() ? "untitled" : fileName,
reply.dynamicCast<dbif::RootCreateFileBlobFromDataRequest::ReplyType>()
->object);
});
connect(promise, &dbif::MethodResultPromise::gotError,
[this, fileName](dbif::PError error) {
QMessageBox::warning(this, tr("Veles"),
tr("Cannot load file %1.").arg(fileName));
});
}
void VelesMainWindow::createHexEditTab(QString fileName,
dbif::ObjectHandle fileBlob) {
QSharedPointer<FileBlobModel> data_model(
new FileBlobModel(fileBlob, {QFileInfo(fileName).fileName()}));
QSharedPointer<QItemSelectionModel> selection_model(
new QItemSelectionModel(data_model.data()));
NodeWidget* node_widget = new NodeWidget(this, data_model, selection_model);
addTab(node_widget, data_model->path().join(" : "), nullptr);
}
void VelesMainWindow::createLogWindow() {
DockWidget* dock_widget = new DockWidget;
dock_widget->setAllowedAreas(Qt::AllDockWidgetAreas);
dock_widget->setWindowTitle("Log");
dock_widget->setFeatures(
QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable);
dock_widget->setWidget(new LogWidget);
dock_widget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
auto children = findChildren<DockWidget*>();
if (!children.empty()) {
tabifyDockWidget(children.back(), dock_widget);
} else {
addDockWidget(Qt::LeftDockWidgetArea, dock_widget);
}
log_dock_widget_ = dock_widget;
QApplication::processEvents();
updateDocksAndTabs();
}
} // namespace ui
} // namespace veles
<|endoftext|> |
<commit_before>#include "ezgraver.h"
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QDebug>
#include <QBitmap>
#include <QBuffer>
#include <iterator>
#include <algorithm>
#include <functional>
EzGraver::EzGraver(std::shared_ptr<QSerialPort> serial) : _serial{serial} {}
void EzGraver::start(unsigned char const& burnTime) {
_setBurnTime(burnTime);
qDebug() << "starting engrave process";
_transmit(0xF1);
}
void EzGraver::_setBurnTime(unsigned char const& burnTime) {
if(burnTime < 0x01 || burnTime > 0xF0) {
throw new std::out_of_range("burntime out of range");
}
qDebug() << "setting burn time to:" << qPrintable(burnTime);
_transmit(burnTime);
}
void EzGraver::pause() {
qDebug() << "pausing engrave process";
_transmit(0xF2);
}
void EzGraver::reset() {
qDebug() << "resetting";
_transmit(0xF9);
}
void EzGraver::home() {
qDebug() << "moving to home";
_transmit(0xF3);
}
void EzGraver::center() {
qDebug() << "moving to center";
_transmit(0xFB);
}
void EzGraver::preview() {
qDebug() << "drawing image preview";
_transmit(0xF4);
}
void EzGraver::up() {
qDebug() << "moving up";
_transmit(0xF5);
}
void EzGraver::down() {
qDebug() << "moving down";
_transmit(0xF6);
}
void EzGraver::left() {
qDebug() << "moving left";
_transmit(0xF7);
}
void EzGraver::right() {
qDebug() << "moving right";
_transmit(0xF8);
}
void EzGraver::erase() {
qDebug() << "erasing EEPROM";
QByteArray bytes{8, static_cast<char>(0xFE)};
_transmit(bytes);
}
#include <QFile>
void EzGraver::uploadImage(QImage const& originalImage) {
qDebug() << "converting image to bitmap";
QImage image{originalImage
.scaled(512, 512)
.mirrored()
.convertToFormat(QImage::Format_Mono)};
image.invertPixels();
QByteArray bytes{};
QBuffer buffer{&bytes};
image.save(&buffer, "BMP");
uploadImage(bytes);
}
void EzGraver::uploadImage(QByteArray const& image) {
qDebug() << "uploading image";
_transmit(image);
}
void EzGraver::awaitTransmission(int msecs) {
_serial->waitForBytesWritten(msecs);
}
void EzGraver::_transmit(unsigned char const& data) {
_transmit(QByteArray{1, static_cast<char>(data)});
}
void EzGraver::_transmit(QByteArray const& data) {
QString hex{data.count() < 10 ? data.toHex() : ""};
qDebug() << "transmitting" << data.length() << "bytes:" << hex;
_serial->write(data);
}
EzGraver::~EzGraver() {
qDebug() << "EzGraver is being destroyed, closing serial port";
_serial->close();
}
QStringList EzGraver::availablePorts() {
auto toPortName = [](QSerialPortInfo const& port) { return port.portName(); };
auto ports = QSerialPortInfo::availablePorts();
QStringList result{};
std::transform(ports.cbegin(), ports.cend(), std::back_inserter<QStringList>(result), toPortName);
return result;
}
std::shared_ptr<EzGraver> EzGraver::create(QString const& portName) {
qDebug() << "instantiating EzGraver on port" << portName;
std::shared_ptr<QSerialPort> serial{new QSerialPort(portName)};
serial->setBaudRate(QSerialPort::Baud57600, QSerialPort::AllDirections);
serial->setParity(QSerialPort::Parity::NoParity);
serial->setDataBits(QSerialPort::DataBits::Data8);
serial->setStopBits(QSerialPort::StopBits::OneStop);
if(!serial->open(QIODevice::ReadWrite)) {
qDebug() << "failed to establish a connection on port" << portName;
qDebug() << serial->errorString();
throw std::runtime_error{QString{"failed to connect to port %1 (%2)"}.arg(portName, serial->errorString()).toStdString()};
}
return std::shared_ptr<EzGraver>{new EzGraver(serial)};
}
<commit_msg>Fixed truncation warning on MSVC.<commit_after>#include "ezgraver.h"
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QDebug>
#include <QBitmap>
#include <QBuffer>
#include <iterator>
#include <algorithm>
#include <functional>
EzGraver::EzGraver(std::shared_ptr<QSerialPort> serial) : _serial{serial} {}
void EzGraver::start(unsigned char const& burnTime) {
_setBurnTime(burnTime);
qDebug() << "starting engrave process";
_transmit(0xF1);
}
void EzGraver::_setBurnTime(unsigned char const& burnTime) {
if(burnTime < 0x01 || burnTime > 0xF0) {
throw new std::out_of_range("burntime out of range");
}
qDebug() << "setting burn time to:" << qPrintable(burnTime);
_transmit(burnTime);
}
void EzGraver::pause() {
qDebug() << "pausing engrave process";
_transmit(0xF2);
}
void EzGraver::reset() {
qDebug() << "resetting";
_transmit(0xF9);
}
void EzGraver::home() {
qDebug() << "moving to home";
_transmit(0xF3);
}
void EzGraver::center() {
qDebug() << "moving to center";
_transmit(0xFB);
}
void EzGraver::preview() {
qDebug() << "drawing image preview";
_transmit(0xF4);
}
void EzGraver::up() {
qDebug() << "moving up";
_transmit(0xF5);
}
void EzGraver::down() {
qDebug() << "moving down";
_transmit(0xF6);
}
void EzGraver::left() {
qDebug() << "moving left";
_transmit(0xF7);
}
void EzGraver::right() {
qDebug() << "moving right";
_transmit(0xF8);
}
void EzGraver::erase() {
qDebug() << "erasing EEPROM";
_transmit(QByteArray{8, '\xFE'});
}
#include <QFile>
void EzGraver::uploadImage(QImage const& originalImage) {
qDebug() << "converting image to bitmap";
QImage image{originalImage
.scaled(512, 512)
.mirrored()
.convertToFormat(QImage::Format_Mono)};
image.invertPixels();
QByteArray bytes{};
QBuffer buffer{&bytes};
image.save(&buffer, "BMP");
uploadImage(bytes);
}
void EzGraver::uploadImage(QByteArray const& image) {
qDebug() << "uploading image";
_transmit(image);
}
void EzGraver::awaitTransmission(int msecs) {
_serial->waitForBytesWritten(msecs);
}
void EzGraver::_transmit(unsigned char const& data) {
_transmit(QByteArray{1, static_cast<char>(data)});
}
void EzGraver::_transmit(QByteArray const& data) {
QString hex{data.count() < 10 ? data.toHex() : ""};
qDebug() << "transmitting" << data.length() << "bytes:" << hex;
_serial->write(data);
}
EzGraver::~EzGraver() {
qDebug() << "EzGraver is being destroyed, closing serial port";
_serial->close();
}
QStringList EzGraver::availablePorts() {
auto toPortName = [](QSerialPortInfo const& port) { return port.portName(); };
auto ports = QSerialPortInfo::availablePorts();
QStringList result{};
std::transform(ports.cbegin(), ports.cend(), std::back_inserter<QStringList>(result), toPortName);
return result;
}
std::shared_ptr<EzGraver> EzGraver::create(QString const& portName) {
qDebug() << "instantiating EzGraver on port" << portName;
std::shared_ptr<QSerialPort> serial{new QSerialPort(portName)};
serial->setBaudRate(QSerialPort::Baud57600, QSerialPort::AllDirections);
serial->setParity(QSerialPort::Parity::NoParity);
serial->setDataBits(QSerialPort::DataBits::Data8);
serial->setStopBits(QSerialPort::StopBits::OneStop);
if(!serial->open(QIODevice::ReadWrite)) {
qDebug() << "failed to establish a connection on port" << portName;
qDebug() << serial->errorString();
throw std::runtime_error{QString{"failed to connect to port %1 (%2)"}.arg(portName, serial->errorString()).toStdString()};
}
return std::shared_ptr<EzGraver>{new EzGraver(serial)};
}
<|endoftext|> |
<commit_before>// @(#)root/roostats:$Id: FrequentistCalculator.cxx 37084 2010-11-29 21:37:13Z moneta $
// Author: Kyle Cranmer, Sven Kreiss 23/05/10
/*************************************************************************
* Copyright (C) 1995-2008, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
/**
Does a frequentist hypothesis test. Nuisance parameters are fixed to their
MLEs.
*/
#include "RooStats/FrequentistCalculator.h"
#include "RooStats/ToyMCSampler.h"
ClassImp(RooStats::FrequentistCalculator)
using namespace RooStats;
int FrequentistCalculator::PreNullHook(RooArgSet *parameterPoint, double obsTestStat) const {
// ****** any TestStatSampler ********
// note: making nll or profile class variables can only be done in the constructor
// as all other hooks are const (which has to be because GetHypoTest is const). However,
// when setting it only in constructor, they would have to be changed every time SetNullModel
// or SetAltModel is called. Simply put, converting them into class variables breaks
// encapsulation.
RooFit::MsgLevel msglevel = RooMsgService::instance().globalKillBelow();
RooMsgService::instance().setGlobalKillBelow(RooFit::FATAL);
// create profile keeping everything but nuisance parameters fixed
RooArgSet allButNuisance(*fNullModel->GetPdf()->getParameters(*fData));
allButNuisance.remove(*fNullModel->GetNuisanceParameters());
// remove also the constant parameters otherwise RooProfileLL will float them
RemoveConstantParameters(&allButNuisance);
RooAbsReal* nll = fNullModel->GetPdf()->createNLL(*const_cast<RooAbsData*>(fData), RooFit::CloneData(kFALSE));
RooAbsReal* profile = nll->createProfile(allButNuisance);
profile->getVal(); // this will do fit and set nuisance parameters to profiled values
// add nuisance parameters to parameter point
if(fNullModel->GetNuisanceParameters())
parameterPoint->add(*fNullModel->GetNuisanceParameters());
delete profile;
delete nll;
RooMsgService::instance().setGlobalKillBelow(msglevel);
// ***** ToyMCSampler specific *******
// check whether TestStatSampler is a ToyMCSampler
ToyMCSampler *toymcs = dynamic_cast<ToyMCSampler*>(GetTestStatSampler());
if(toymcs) {
oocoutI((TObject*)0,InputArguments) << "Using a ToyMCSampler. Now configuring for Null." << endl;
// variable number of toys
if(fNToysNull) toymcs->SetNToys(fNToysNull);
// adaptive sampling
if(fNToysNullTail) {
oocoutI((TObject*)0,InputArguments) << "Adaptive Sampling" << endl;
if(GetTestStatSampler()->GetTestStatistic()->PValueIsRightTail()) {
toymcs->SetToysRightTail(fNToysNullTail, obsTestStat);
}else{
toymcs->SetToysLeftTail(fNToysNullTail, obsTestStat);
}
}else{
toymcs->SetToysBothTails(0, 0, obsTestStat); // disable adaptive sampling
}
// importance sampling
if(fNullImportanceDensity) {
oocoutI((TObject*)0,InputArguments) << "Importance Sampling" << endl;
toymcs->SetImportanceDensity(fNullImportanceDensity);
if(fNullImportanceSnapshot) toymcs->SetImportanceSnapshot(*fNullImportanceSnapshot);
}else{
toymcs->SetImportanceDensity(NULL); // disable importance sampling
}
GetNullModel()->LoadSnapshot();
}
return 0;
}
int FrequentistCalculator::PreAltHook(RooArgSet *parameterPoint, double obsTestStat) const {
// ****** any TestStatSampler ********
RooFit::MsgLevel msglevel = RooMsgService::instance().globalKillBelow();
RooMsgService::instance().setGlobalKillBelow(RooFit::FATAL);
// create profile keeping everything but nuisance parameters fixed
RooArgSet allButNuisance(*fAltModel->GetPdf()->getParameters(*fData));
allButNuisance.remove(*fAltModel->GetNuisanceParameters());
// remove also the constant parameters otherwise RooProfileLL will float them
RemoveConstantParameters(&allButNuisance);
RooAbsReal* nll = fAltModel->GetPdf()->createNLL(*const_cast<RooAbsData*>(fData), RooFit::CloneData(kFALSE));
RooAbsReal* profile = nll->createProfile(allButNuisance);
profile->getVal(); // this will do fit and set nuisance parameters to profiled values
// add nuisance parameters to parameter point
if(fAltModel->GetNuisanceParameters())
parameterPoint->add(*fAltModel->GetNuisanceParameters());
delete profile;
delete nll;
RooMsgService::instance().setGlobalKillBelow(msglevel);
// ***** ToyMCSampler specific *******
// check whether TestStatSampler is a ToyMCSampler
ToyMCSampler *toymcs = dynamic_cast<ToyMCSampler*>(GetTestStatSampler());
if(toymcs) {
oocoutI((TObject*)0,InputArguments) << "Using a ToyMCSampler. Now configuring for Alt." << endl;
// variable number of toys
if(fNToysAlt) toymcs->SetNToys(fNToysAlt);
// adaptive sampling
if(fNToysAltTail) {
oocoutI((TObject*)0,InputArguments) << "Adaptive Sampling" << endl;
if(GetTestStatSampler()->GetTestStatistic()->PValueIsRightTail()) {
toymcs->SetToysLeftTail(fNToysAltTail, obsTestStat);
}else{
toymcs->SetToysRightTail(fNToysAltTail, obsTestStat);
}
}else{
toymcs->SetToysBothTails(0, 0, obsTestStat); // disable adaptive sampling
}
// importance sampling
if(fAltImportanceDensity) {
oocoutI((TObject*)0,InputArguments) << "Importance Sampling" << endl;
toymcs->SetImportanceDensity(fAltImportanceDensity);
if(fAltImportanceSnapshot) toymcs->SetImportanceSnapshot(*fAltImportanceSnapshot);
}else{
toymcs->SetImportanceDensity(NULL); // disable importance sampling
}
}
return 0;
}
<commit_msg>add a fix from Gregory in case of a model without nuisance parameters<commit_after>// @(#)root/roostats:$Id: FrequentistCalculator.cxx 37084 2010-11-29 21:37:13Z moneta $
// Author: Kyle Cranmer, Sven Kreiss 23/05/10
/*************************************************************************
* Copyright (C) 1995-2008, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
/**
Does a frequentist hypothesis test. Nuisance parameters are fixed to their
MLEs.
*/
#include "RooStats/FrequentistCalculator.h"
#include "RooStats/ToyMCSampler.h"
ClassImp(RooStats::FrequentistCalculator)
using namespace RooStats;
int FrequentistCalculator::PreNullHook(RooArgSet *parameterPoint, double obsTestStat) const {
// ****** any TestStatSampler ********
// note: making nll or profile class variables can only be done in the constructor
// as all other hooks are const (which has to be because GetHypoTest is const). However,
// when setting it only in constructor, they would have to be changed every time SetNullModel
// or SetAltModel is called. Simply put, converting them into class variables breaks
// encapsulation.
RooFit::MsgLevel msglevel = RooMsgService::instance().globalKillBelow();
RooMsgService::instance().setGlobalKillBelow(RooFit::FATAL);
// create profile keeping everything but nuisance parameters fixed
RooArgSet allButNuisance(*fNullModel->GetPdf()->getParameters(*fData));
if (fNullModel->GetNuisanceParameters()) allButNuisance.remove(*fNullModel->GetNuisanceParameters());
// remove also the constant parameters otherwise RooProfileLL will float them
RemoveConstantParameters(&allButNuisance);
RooAbsReal* nll = fNullModel->GetPdf()->createNLL(*const_cast<RooAbsData*>(fData), RooFit::CloneData(kFALSE));
RooAbsReal* profile = nll->createProfile(allButNuisance);
profile->getVal(); // this will do fit and set nuisance parameters to profiled values
// add nuisance parameters to parameter point
if(fNullModel->GetNuisanceParameters())
parameterPoint->add(*fNullModel->GetNuisanceParameters());
delete profile;
delete nll;
RooMsgService::instance().setGlobalKillBelow(msglevel);
// ***** ToyMCSampler specific *******
// check whether TestStatSampler is a ToyMCSampler
ToyMCSampler *toymcs = dynamic_cast<ToyMCSampler*>(GetTestStatSampler());
if(toymcs) {
oocoutI((TObject*)0,InputArguments) << "Using a ToyMCSampler. Now configuring for Null." << endl;
// variable number of toys
if(fNToysNull) toymcs->SetNToys(fNToysNull);
// adaptive sampling
if(fNToysNullTail) {
oocoutI((TObject*)0,InputArguments) << "Adaptive Sampling" << endl;
if(GetTestStatSampler()->GetTestStatistic()->PValueIsRightTail()) {
toymcs->SetToysRightTail(fNToysNullTail, obsTestStat);
}else{
toymcs->SetToysLeftTail(fNToysNullTail, obsTestStat);
}
}else{
toymcs->SetToysBothTails(0, 0, obsTestStat); // disable adaptive sampling
}
// importance sampling
if(fNullImportanceDensity) {
oocoutI((TObject*)0,InputArguments) << "Importance Sampling" << endl;
toymcs->SetImportanceDensity(fNullImportanceDensity);
if(fNullImportanceSnapshot) toymcs->SetImportanceSnapshot(*fNullImportanceSnapshot);
}else{
toymcs->SetImportanceDensity(NULL); // disable importance sampling
}
GetNullModel()->LoadSnapshot();
}
return 0;
}
int FrequentistCalculator::PreAltHook(RooArgSet *parameterPoint, double obsTestStat) const {
// ****** any TestStatSampler ********
RooFit::MsgLevel msglevel = RooMsgService::instance().globalKillBelow();
RooMsgService::instance().setGlobalKillBelow(RooFit::FATAL);
// create profile keeping everything but nuisance parameters fixed
RooArgSet allButNuisance(*fAltModel->GetPdf()->getParameters(*fData));
if (fAltModel->GetNuisanceParameters()) allButNuisance.remove(*fAltModel->GetNuisanceParameters());
// remove also the constant parameters otherwise RooProfileLL will float them
RemoveConstantParameters(&allButNuisance);
RooAbsReal* nll = fAltModel->GetPdf()->createNLL(*const_cast<RooAbsData*>(fData), RooFit::CloneData(kFALSE));
RooAbsReal* profile = nll->createProfile(allButNuisance);
profile->getVal(); // this will do fit and set nuisance parameters to profiled values
// add nuisance parameters to parameter point
if(fAltModel->GetNuisanceParameters())
parameterPoint->add(*fAltModel->GetNuisanceParameters());
delete profile;
delete nll;
RooMsgService::instance().setGlobalKillBelow(msglevel);
// ***** ToyMCSampler specific *******
// check whether TestStatSampler is a ToyMCSampler
ToyMCSampler *toymcs = dynamic_cast<ToyMCSampler*>(GetTestStatSampler());
if(toymcs) {
oocoutI((TObject*)0,InputArguments) << "Using a ToyMCSampler. Now configuring for Alt." << endl;
// variable number of toys
if(fNToysAlt) toymcs->SetNToys(fNToysAlt);
// adaptive sampling
if(fNToysAltTail) {
oocoutI((TObject*)0,InputArguments) << "Adaptive Sampling" << endl;
if(GetTestStatSampler()->GetTestStatistic()->PValueIsRightTail()) {
toymcs->SetToysLeftTail(fNToysAltTail, obsTestStat);
}else{
toymcs->SetToysRightTail(fNToysAltTail, obsTestStat);
}
}else{
toymcs->SetToysBothTails(0, 0, obsTestStat); // disable adaptive sampling
}
// importance sampling
if(fAltImportanceDensity) {
oocoutI((TObject*)0,InputArguments) << "Importance Sampling" << endl;
toymcs->SetImportanceDensity(fAltImportanceDensity);
if(fAltImportanceSnapshot) toymcs->SetImportanceSnapshot(*fAltImportanceSnapshot);
}else{
toymcs->SetImportanceDensity(NULL); // disable importance sampling
}
}
return 0;
}
<|endoftext|> |
<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
*
* Razor - a lightweight, Qt based, desktop toolset
* https://sourceforge.net/projects/razor-qt/
*
* Copyright: 2010-2011 Razor team
* Authors:
* Alexander Sokoloff <sokoloff.a@gmail.ru>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; only version 2 of
* the License is valid for this program.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* END_COMMON_COPYRIGHT_HEADER */
#include "razormainmenu.h"
//#include "razor.h"
#include <QDebug>
#include <QtGui/QMenu>
#include <razorqt/xdgdesktopfile.h>
#include <razorqt/xdgmenu.h>
#include <razorqt/domhelper.h>
#include <QSettings>
#include <QFileInfo>
#include <QAction>
#include <QtGui/QMessageBox>
#include <razorqt/powermanager.h>
#include <razorqt/xdgenv.h>
//#include <razorbar.h>
#include <razorqt/xdgicon.h>
#include <razorqt/xdgdesktopfile.h>
#include <razorqt/xdgmenuwidget.h>
#include <QStack>
#include <QCursor>
EXPORT_RAZOR_PANEL_PLUGIN_CPP(RazorMainMenu)
/************************************************
************************************************/
RazorMainMenu::RazorMainMenu(const RazorPanelPluginStartInfo* startInfo, QWidget* parent):
RazorPanelPlugin(startInfo, parent),
mMenu(0)
{
setObjectName("MainMenu");
addWidget(&mButton);
connect(&mButton, SIGNAL(clicked()), this, SLOT(showMenu()));
mPowerManager = new PowerManager(this);
mPowerManager->setParentWidget(panel());
settingsChanged();
QSizePolicy sp = mButton.sizePolicy();
sp.setVerticalPolicy(QSizePolicy::Minimum);
mButton.setSizePolicy(sp);
}
/************************************************
************************************************/
RazorMainMenu::~RazorMainMenu()
{
settings().setValue("text", mButton.text());
settings().setValue("icon_size", mMenuStyle.iconSize());
settings().setValue("top_icon_size", mTopMenuStyle.iconSize());
}
/************************************************
************************************************/
void RazorMainMenu::showMenu()
{
if (!mMenu)
buildMenu();
int x, y;
switch (panel()->position())
{
case RazorPanel::PositionTop:
x = mButton.mapToGlobal(QPoint(0, 0)).x();
y = panel()->mapToGlobal(QPoint(0, panel()->sizeHint().height())).y();
break;
case RazorPanel::PositionBottom:
x = mButton.mapToGlobal(QPoint(0, 0)).x();
y = panel()->mapToGlobal(QPoint(0, 0)).y() - mMenu->sizeHint().height();
break;
case RazorPanel::PositionLeft:
x = panel()->mapToGlobal(QPoint(panel()->sizeHint().width(), 0)).x();
y = mButton.mapToGlobal(QPoint(0, 0)).y();
break;
case RazorPanel::PositionRight:
x = panel()->mapToGlobal(QPoint(0, 0)).x() - mMenu->sizeHint().width();
y = mButton.mapToGlobal(QPoint(0, 0)).y();
break;
}
QPoint pos(x, y);
mMenu->exec(pos);
}
/************************************************
************************************************/
void RazorMainMenu::settingsChanged()
{
mButton.setText(settings().value("text", "").toString());
mLogDir = settings().value("log_dir", "").toString();
mMenuStyle.setIconSize(settings().value("icon_size", 16).toInt());
mTopMenuStyle.setIconSize(settings().value("top_icon_size", 16).toInt());
mMenuFile = settings().value("menu_file", "").toString();
if (mMenuFile.isEmpty())
mMenuFile = XdgMenu::getMenuFileName();
QIcon icon = XdgIcon::fromTheme(settings().value("button_icon").toString());
if (!icon.isNull())
mButton.setIcon(icon);
}
/************************************************
************************************************/
void RazorMainMenu::buildMenu()
{
XdgMenu xdgMenu(mMenuFile);
xdgMenu.setLogDir(mLogDir);
bool res = xdgMenu.read();
if (res)
{
mMenu = new XdgMenuWidget(xdgMenu, "", this);
mMenu->setObjectName("TopLevelMainMenu");
mMenu->setStyle(&mTopMenuStyle);
}
else
{
QMessageBox::warning(this, "Parse error", xdgMenu.errorString());
}
mMenu->addSeparator();
QMenu* leaveMenu = mMenu->addMenu(XdgIcon::fromTheme("system-shutdown"), tr("Leave"));
leaveMenu->addActions(mPowerManager->availableActions());
}
<commit_msg>Segfault in MainMenu if xdg-menu file not found.<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
*
* Razor - a lightweight, Qt based, desktop toolset
* https://sourceforge.net/projects/razor-qt/
*
* Copyright: 2010-2011 Razor team
* Authors:
* Alexander Sokoloff <sokoloff.a@gmail.ru>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; only version 2 of
* the License is valid for this program.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* END_COMMON_COPYRIGHT_HEADER */
#include "razormainmenu.h"
//#include "razor.h"
#include <QDebug>
#include <QtGui/QMenu>
#include <razorqt/xdgdesktopfile.h>
#include <razorqt/xdgmenu.h>
#include <razorqt/domhelper.h>
#include <QSettings>
#include <QFileInfo>
#include <QAction>
#include <QtGui/QMessageBox>
#include <razorqt/powermanager.h>
#include <razorqt/xdgenv.h>
//#include <razorbar.h>
#include <razorqt/xdgicon.h>
#include <razorqt/xdgdesktopfile.h>
#include <razorqt/xdgmenuwidget.h>
#include <QStack>
#include <QCursor>
EXPORT_RAZOR_PANEL_PLUGIN_CPP(RazorMainMenu)
/************************************************
************************************************/
RazorMainMenu::RazorMainMenu(const RazorPanelPluginStartInfo* startInfo, QWidget* parent):
RazorPanelPlugin(startInfo, parent),
mMenu(0)
{
setObjectName("MainMenu");
addWidget(&mButton);
connect(&mButton, SIGNAL(clicked()), this, SLOT(showMenu()));
mPowerManager = new PowerManager(this);
mPowerManager->setParentWidget(panel());
settingsChanged();
QSizePolicy sp = mButton.sizePolicy();
sp.setVerticalPolicy(QSizePolicy::Minimum);
mButton.setSizePolicy(sp);
}
/************************************************
************************************************/
RazorMainMenu::~RazorMainMenu()
{
settings().setValue("text", mButton.text());
settings().setValue("icon_size", mMenuStyle.iconSize());
settings().setValue("top_icon_size", mTopMenuStyle.iconSize());
}
/************************************************
************************************************/
void RazorMainMenu::showMenu()
{
if (!mMenu)
buildMenu();
if (!mMenu)
return;
int x, y;
switch (panel()->position())
{
case RazorPanel::PositionTop:
x = mButton.mapToGlobal(QPoint(0, 0)).x();
y = panel()->mapToGlobal(QPoint(0, panel()->sizeHint().height())).y();
break;
case RazorPanel::PositionBottom:
x = mButton.mapToGlobal(QPoint(0, 0)).x();
y = panel()->mapToGlobal(QPoint(0, 0)).y() - mMenu->sizeHint().height();
break;
case RazorPanel::PositionLeft:
x = panel()->mapToGlobal(QPoint(panel()->sizeHint().width(), 0)).x();
y = mButton.mapToGlobal(QPoint(0, 0)).y();
break;
case RazorPanel::PositionRight:
x = panel()->mapToGlobal(QPoint(0, 0)).x() - mMenu->sizeHint().width();
y = mButton.mapToGlobal(QPoint(0, 0)).y();
break;
}
QPoint pos(x, y);
mMenu->exec(pos);
}
/************************************************
************************************************/
void RazorMainMenu::settingsChanged()
{
mButton.setText(settings().value("text", "").toString());
mLogDir = settings().value("log_dir", "").toString();
mMenuStyle.setIconSize(settings().value("icon_size", 16).toInt());
mTopMenuStyle.setIconSize(settings().value("top_icon_size", 16).toInt());
mMenuFile = settings().value("menu_file", "").toString();
if (mMenuFile.isEmpty())
mMenuFile = XdgMenu::getMenuFileName();
QIcon icon = XdgIcon::fromTheme(settings().value("button_icon").toString());
if (!icon.isNull())
mButton.setIcon(icon);
}
/************************************************
************************************************/
void RazorMainMenu::buildMenu()
{
XdgMenu xdgMenu(mMenuFile);
xdgMenu.setLogDir(mLogDir);
bool res = xdgMenu.read();
if (res)
{
mMenu = new XdgMenuWidget(xdgMenu, "", this);
mMenu->setObjectName("TopLevelMainMenu");
mMenu->setStyle(&mTopMenuStyle);
}
else
{
QMessageBox::warning(this, "Parse error", xdgMenu.errorString());
return;
}
mMenu->addSeparator();
QMenu* leaveMenu = mMenu->addMenu(XdgIcon::fromTheme("system-shutdown"), tr("Leave"));
leaveMenu->addActions(mPowerManager->availableActions());
}
<|endoftext|> |
<commit_before>// SkipList: A STL-map like container using skip-list
// Copyright (c) 2015 Guo Xiao <guoxiao08@gmail.com>
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#pragma once
#include <vector>
#include <assert.h>
#include <cstdlib>
#include <stdexcept>
#ifndef NDEBUG
#include <iostream>
#endif
namespace guoxiao {
namespace skiplist {
template <typename KeyType, typename ValueType>
struct SkipNode {
KeyType key;
ValueType value;
size_t level;
std::vector<SkipNode *> next;
SkipNode() : level(0), next(1) {}
SkipNode(SkipNode &&rhs) : level(rhs.level), next(std::move(rhs.next)) {}
SkipNode(const SkipNode &) = delete;
SkipNode &operator=(const SkipNode &) = delete;
};
template <typename T>
class Iterator {
public:
Iterator() : ptr(nullptr){};
explicit Iterator(T *p) : ptr(p){};
Iterator operator=(T *p) {
ptr = p;
return *this;
}
Iterator &operator++() {
ptr = ptr->next[0];
return *this;
}
Iterator operator++(int) {
Iterator temp = *this;
ptr = ptr->next[0];
return temp;
}
bool operator!=(const Iterator &rhs) const { return ptr != rhs.ptr; }
bool operator==(const Iterator &rhs) const { return ptr == rhs.ptr; }
bool operator==(const T *p) const { return ptr == p; }
bool operator!=(const T *p) const { return ptr != p; }
operator bool() const { return ptr != nullptr; }
operator T *() const { return ptr; }
T *operator->() const { return ptr; }
T &operator*() const { return *ptr; }
private:
T *ptr;
};
template <typename Key, typename T>
class SkipList {
public:
typedef Key key_type;
typedef T mapped_type;
typedef std::pair<Key, T> value_type;
typedef SkipNode<Key, T> node_type;
typedef Iterator<node_type> iterator;
typedef Iterator<node_type> const_iterator;
SkipList() : size_(0), level_(0), head_(new node_type()) {}
~SkipList() noexcept {
iterator node = head_, temp;
while (node) {
temp = node;
node = node->next[0];
delete temp;
}
}
// Move Ctor
SkipList(SkipList &&s) noexcept : size_(s.size_),
level_(s.level_),
head_(s.head_) {
s.head_ = new node_type();
s.level_ = 0;
s.size_ = 0;
}
// Copy Ctor
SkipList(const SkipList &s)
: size_(s.size_), level_(s.level_), head_(new node_type()) {
iterator snode = s.head_, node = head_;
std::vector<iterator> last(level_ + 1);
head_->level = level_;
head_->next.resize(level_ + 1);
for (int i = level_; i >= 0; i--) {
last[i] = head_;
}
snode = snode->next[0];
while (snode) {
node = new node_type();
node->key = snode->key;
node->value = snode->value;
node->level = snode->level;
node->next.resize(snode->next.size());
for (int i = snode->level; i >= 0; i--) {
last[i]->next[i] = node;
last[i] = node;
}
snode = snode->next[0];
}
}
// Copy Assignment
SkipList &operator=(const SkipList &s) {
if (this == &s)
return *this;
SkipList tmp(s);
return *this = std::move(tmp);
}
// Move Assignment
SkipList &operator=(SkipList &&s) noexcept {
this->~SkipList();
size_ = s.size_;
level_ = s.level_;
head_ = s.head_;
s.head_ = new node_type();
s.level_ = 0;
s.size_ = 0;
return *this;
}
size_t size() const { return size_; }
bool empty() const { return size_ == 0; }
size_t level() const { return level_; }
iterator begin() noexcept { return iterator(head_->next[0]); }
const_iterator begin() const noexcept { return iterator(head_->next[0]); }
const_iterator cbegin() noexcept { return iterator(head_->next[0]); }
const_iterator cend() const noexcept { return iterator(); }
iterator end() noexcept { return iterator(); }
const_iterator end() const noexcept { return iterator(); }
template <typename K, typename V>
iterator emplace(K &&key, V &&value) {
iterator node = head_;
std::vector<iterator> update(level_ + 1 + 1);
for (int i = level_; i >= 0; i--) {
assert(static_cast<int>(node->level) >= i);
while (node->next[i] && node->next[i]->key < key) {
node = node->next[i];
}
update[i] = node;
if (node->next[i] && node->next[i]->key == key) {
throw std::runtime_error("conflict");
}
}
node_type *n = new node_type();
n->key = std::forward<K>(key);
n->value = std::forward<V>(value);
size_t level = getRandomLevel();
if (level > level_) {
level = level_ + 1;
head_->next.resize(level + 1);
head_->level = level;
update[level] = head_;
level_ = level;
}
n->next.resize(level + 1);
n->level = level;
for (int i = level; i >= 0; i--) {
if (update[i]) {
n->next[i] = update[i]->next[i];
update[i]->next[i] = n;
}
}
++size_;
return iterator(n);
}
iterator insert(const value_type &value) {
return emplace(value.first, value.second);
}
iterator insert(value_type &&value) {
return emplace(std::move(value.first), std::move(value.second));
}
iterator find(const key_type &key) const {
iterator node = head_;
for (int i = level_; i >= 0; i--) {
while (node->next[i] && node->next[i]->key < key) {
node = node->next[i];
}
if (node->next[i] && node->next[i]->key == key) {
return iterator(node->next[i]);
}
}
return end();
}
void erase(const key_type &key) {
iterator node = head_;
std::vector<iterator> update(level_ + 1);
for (int i = level_; i >= 0; i--) {
while (node->next[i] && node->next[i]->key < key) {
node = node->next[i];
}
if (node->next[i] && node->next[i]->key == key) {
update[i] = node;
}
}
node = node->next[0];
if (node == end()) {
throw std::out_of_range("skiplist::erase");
}
assert(node->key == key);
for (int i = level_; i >= 0; i--) {
if (update[i]) {
assert(node == iterator(update[i]->next[i]));
update[i]->next[i] = node->next[i];
}
}
delete node;
--size_;
if (level_ > 0 && head_->next[level_] == end()) {
level_--;
head_->level = level_;
head_->next.resize(level_ + 1);
}
}
void erase(iterator it) {
erase(it->key);
}
mapped_type &operator[](const key_type &key) {
iterator node = find(key);
if (node == end()) {
mapped_type value;
node = emplace(key, value);
}
return node->value;
}
mapped_type &at(const key_type &key) {
iterator node = find(key);
if (node == end()) {
throw std::out_of_range("skiplist::at");
}
return node->value;
}
const mapped_type &at(const key_type &key) const {
iterator node = find(key);
if (node == end()) {
throw std::out_of_range("skiplist::at");
}
return node->value;
}
#ifndef NDEBUG
void dump() const {
std::cout << "====== level: " << level_ << " size: " << size_ << std::endl;
for (int i = level_; i >= 0; i--) {
std::cout << "====== level " << i << std::endl;
auto node = head_;
while (node->next[i]) {
std::cout << node->next[i]->key << " : " << node->next[i]->value
<< std::endl;
node = node->next[i];
}
}
}
#endif
private:
size_t size_;
size_t level_;
iterator head_;
static size_t getRandomLevel() {
size_t level = 0;
while (rand() % 2) {
++level;
}
return level;
}
};
} // namespace skiplist
} // namespace guoxiao
<commit_msg>Add count()<commit_after>// SkipList: A STL-map like container using skip-list
// Copyright (c) 2015 Guo Xiao <guoxiao08@gmail.com>
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#pragma once
#include <vector>
#include <assert.h>
#include <cstdlib>
#include <stdexcept>
#ifndef NDEBUG
#include <iostream>
#endif
namespace guoxiao {
namespace skiplist {
template <typename KeyType, typename ValueType>
struct SkipNode {
KeyType key;
ValueType value;
size_t level;
std::vector<SkipNode *> next;
SkipNode() : level(0), next(1) {}
SkipNode(SkipNode &&rhs) : level(rhs.level), next(std::move(rhs.next)) {}
SkipNode(const SkipNode &) = delete;
SkipNode &operator=(const SkipNode &) = delete;
};
template <typename T>
class Iterator {
public:
Iterator() : ptr(nullptr){};
explicit Iterator(T *p) : ptr(p){};
Iterator operator=(T *p) {
ptr = p;
return *this;
}
Iterator &operator++() {
ptr = ptr->next[0];
return *this;
}
Iterator operator++(int) {
Iterator temp = *this;
ptr = ptr->next[0];
return temp;
}
bool operator!=(const Iterator &rhs) const { return ptr != rhs.ptr; }
bool operator==(const Iterator &rhs) const { return ptr == rhs.ptr; }
bool operator==(const T *p) const { return ptr == p; }
bool operator!=(const T *p) const { return ptr != p; }
operator bool() const { return ptr != nullptr; }
operator T *() const { return ptr; }
T *operator->() const { return ptr; }
T &operator*() const { return *ptr; }
private:
T *ptr;
};
template <typename Key, typename T>
class SkipList {
public:
typedef Key key_type;
typedef T mapped_type;
typedef std::pair<Key, T> value_type;
typedef SkipNode<Key, T> node_type;
typedef Iterator<node_type> iterator;
typedef Iterator<node_type> const_iterator;
SkipList() : size_(0), level_(0), head_(new node_type()) {}
~SkipList() noexcept {
iterator node = head_, temp;
while (node) {
temp = node;
node = node->next[0];
delete temp;
}
}
// Move Ctor
SkipList(SkipList &&s) noexcept : size_(s.size_),
level_(s.level_),
head_(s.head_) {
s.head_ = new node_type();
s.level_ = 0;
s.size_ = 0;
}
// Copy Ctor
SkipList(const SkipList &s)
: size_(s.size_), level_(s.level_), head_(new node_type()) {
iterator snode = s.head_, node = head_;
std::vector<iterator> last(level_ + 1);
head_->level = level_;
head_->next.resize(level_ + 1);
for (int i = level_; i >= 0; i--) {
last[i] = head_;
}
snode = snode->next[0];
while (snode) {
node = new node_type();
node->key = snode->key;
node->value = snode->value;
node->level = snode->level;
node->next.resize(snode->next.size());
for (int i = snode->level; i >= 0; i--) {
last[i]->next[i] = node;
last[i] = node;
}
snode = snode->next[0];
}
}
// Copy Assignment
SkipList &operator=(const SkipList &s) {
if (this == &s)
return *this;
SkipList tmp(s);
return *this = std::move(tmp);
}
// Move Assignment
SkipList &operator=(SkipList &&s) noexcept {
this->~SkipList();
size_ = s.size_;
level_ = s.level_;
head_ = s.head_;
s.head_ = new node_type();
s.level_ = 0;
s.size_ = 0;
return *this;
}
size_t size() const { return size_; }
bool empty() const { return size_ == 0; }
size_t level() const { return level_; }
iterator begin() noexcept { return iterator(head_->next[0]); }
const_iterator begin() const noexcept { return iterator(head_->next[0]); }
const_iterator cbegin() noexcept { return iterator(head_->next[0]); }
const_iterator cend() const noexcept { return iterator(); }
iterator end() noexcept { return iterator(); }
const_iterator end() const noexcept { return iterator(); }
template <typename K, typename V>
iterator emplace(K &&key, V &&value) {
iterator node = head_;
std::vector<iterator> update(level_ + 1 + 1);
for (int i = level_; i >= 0; i--) {
assert(static_cast<int>(node->level) >= i);
while (node->next[i] && node->next[i]->key < key) {
node = node->next[i];
}
update[i] = node;
if (node->next[i] && node->next[i]->key == key) {
throw std::runtime_error("conflict");
}
}
node_type *n = new node_type();
n->key = std::forward<K>(key);
n->value = std::forward<V>(value);
size_t level = getRandomLevel();
if (level > level_) {
level = level_ + 1;
head_->next.resize(level + 1);
head_->level = level;
update[level] = head_;
level_ = level;
}
n->next.resize(level + 1);
n->level = level;
for (int i = level; i >= 0; i--) {
if (update[i]) {
n->next[i] = update[i]->next[i];
update[i]->next[i] = n;
}
}
++size_;
return iterator(n);
}
iterator insert(const value_type &value) {
return emplace(value.first, value.second);
}
iterator insert(value_type &&value) {
return emplace(std::move(value.first), std::move(value.second));
}
iterator find(const key_type &key) const {
iterator node = head_;
for (int i = level_; i >= 0; i--) {
while (node->next[i] && node->next[i]->key < key) {
node = node->next[i];
}
if (node->next[i] && node->next[i]->key == key) {
return iterator(node->next[i]);
}
}
return end();
}
size_t count(const key_type &key) const {
return find(key) ? 1 : 0;
}
void erase(const key_type &key) {
iterator node = head_;
std::vector<iterator> update(level_ + 1);
for (int i = level_; i >= 0; i--) {
while (node->next[i] && node->next[i]->key < key) {
node = node->next[i];
}
if (node->next[i] && node->next[i]->key == key) {
update[i] = node;
}
}
node = node->next[0];
if (node == end()) {
throw std::out_of_range("skiplist::erase");
}
assert(node->key == key);
for (int i = level_; i >= 0; i--) {
if (update[i]) {
assert(node == iterator(update[i]->next[i]));
update[i]->next[i] = node->next[i];
}
}
delete node;
--size_;
if (level_ > 0 && head_->next[level_] == end()) {
level_--;
head_->level = level_;
head_->next.resize(level_ + 1);
}
}
void erase(iterator it) {
erase(it->key);
}
mapped_type &operator[](const key_type &key) {
iterator node = find(key);
if (node == end()) {
mapped_type value;
node = emplace(key, value);
}
return node->value;
}
mapped_type &at(const key_type &key) {
iterator node = find(key);
if (node == end()) {
throw std::out_of_range("skiplist::at");
}
return node->value;
}
const mapped_type &at(const key_type &key) const {
iterator node = find(key);
if (node == end()) {
throw std::out_of_range("skiplist::at");
}
return node->value;
}
#ifndef NDEBUG
void dump() const {
std::cout << "====== level: " << level_ << " size: " << size_ << std::endl;
for (int i = level_; i >= 0; i--) {
std::cout << "====== level " << i << std::endl;
auto node = head_;
while (node->next[i]) {
std::cout << node->next[i]->key << " : " << node->next[i]->value
<< std::endl;
node = node->next[i];
}
}
}
#endif
private:
size_t size_;
size_t level_;
iterator head_;
static size_t getRandomLevel() {
size_t level = 0;
while (rand() % 2) {
++level;
}
return level;
}
};
} // namespace skiplist
} // namespace guoxiao
<|endoftext|> |
<commit_before>#define GLM_FORCE_RADIANS
#include <glm/gtc/matrix_transform.hpp>
#include <linux/input-event-codes.h>
#include <wayfire/compositor-surface.hpp>
#include <wayfire/output.hpp>
#include <wayfire/opengl.hpp>
#include <wayfire/core.hpp>
#include <wayfire/decorator.hpp>
#include <wayfire/view-transform.hpp>
#include <wayfire/signal-definitions.hpp>
#include "deco-subsurface.hpp"
#include "deco-layout.hpp"
#include "deco-theme.hpp"
#include <wayfire/plugins/common/cairo-util.hpp>
#include <cairo.h>
extern "C"
{
#define static
#include <wlr/render/wlr_renderer.h>
#include <wlr/types/wlr_matrix.h>
#include <wlr/types/wlr_xcursor_manager.h>
#undef static
}
class simple_decoration_surface : public wf::surface_interface_t,
public wf::compositor_surface_t, public wf::decorator_frame_t_t
{
bool _mapped = true;
int current_thickness;
int current_titlebar;
wayfire_view view;
wf::signal_callback_t title_set = [=] (wf::signal_data_t *data)
{
if (get_signaled_view(data) == view)
view->damage(); // trigger re-render
};
void update_title(int width, int height, double scale)
{
int target_width = width * scale;
int target_height = height * scale;
if (title_texture.tex.width != target_width ||
title_texture.tex.height != target_height ||
title_texture.current_text != view->get_title())
{
auto surface = theme.render_text(view->get_title(),
target_width, target_height);
cairo_surface_upload_to_texture(surface, title_texture.tex);
title_texture.current_text = view->get_title();
}
}
int width = 100, height = 100;
bool active = true; // when views are mapped, they are usually activated
struct {
wf::simple_texture_t tex;
std::string current_text = "";
} title_texture;
wf::decor::decoration_theme_t theme;
wf::decor::decoration_layout_t layout;
wf::region_t cached_region;
public:
simple_decoration_surface(wayfire_view view) :
theme{},
layout{theme, [=] (wlr_box box) {this->damage_surface_box(box); }}
{
this->view = view;
view->connect_signal("title-changed", &title_set);
// make sure to hide frame if the view is fullscreen
update_decoration_size();
}
virtual ~simple_decoration_surface()
{
_mapped = false;
wf::emit_map_state_change(this);
view->disconnect_signal("title-changed", &title_set);
}
/* wf::surface_interface_t implementation */
virtual bool is_mapped() const final
{
return _mapped;
}
wf::point_t get_offset() final
{
return { -current_thickness, -current_titlebar };
}
virtual wf::dimensions_t get_size() const final
{
return {width, height};
}
void render_title(const wf::framebuffer_t& fb,
wf::geometry_t geometry)
{
update_title(geometry.width, geometry.height, fb.scale);
OpenGL::render_texture(title_texture.tex.tex, fb, geometry,
glm::vec4(1.0f), OpenGL::TEXTURE_TRANSFORM_INVERT_Y);
}
void render_scissor_box(const wf::framebuffer_t& fb, wf::point_t origin,
const wlr_box& scissor)
{
/* Clear background */
wlr_box geometry {origin.x, origin.y, width, height};
theme.render_background(fb, geometry, scissor, active);
/* Draw title & buttons */
auto renderables = layout.get_renderable_areas();
for (auto item : renderables)
{
if (item->get_type() == wf::decor::DECORATION_AREA_TITLE) {
OpenGL::render_begin(fb);
fb.logic_scissor(scissor);
render_title(fb, item->get_geometry() + origin);
OpenGL::render_end();
} else { // button
item->as_button().render(fb,
item->get_geometry() + origin, scissor);
}
}
}
virtual void simple_render(const wf::framebuffer_t& fb, int x, int y,
const wf::region_t& damage) override
{
wf::region_t frame = this->cached_region + wf::point_t{x, y};
frame &= damage;
for (const auto& box : frame)
render_scissor_box(fb, {x, y}, wlr_box_from_pixman_box(box));
}
bool accepts_input(int32_t sx, int32_t sy) override
{
return pixman_region32_contains_point(cached_region.to_pixman(),
sx, sy, NULL);
}
/* wf::compositor_surface_t implementation */
virtual void on_pointer_enter(int x, int y) override
{ layout.handle_motion(x, y); }
virtual void on_pointer_leave() override
{ layout.handle_focus_lost(); }
virtual void on_pointer_motion(int x, int y) override
{ layout.handle_motion(x, y); }
void send_move_request()
{
move_request_signal move_request;
move_request.view = view;
get_output()->emit_signal("move-request", &move_request);
}
void send_resize_request(uint32_t edges)
{
resize_request_signal resize_request;
resize_request.view = view;
resize_request.edges = edges;
get_output()->emit_signal("resize-request", &resize_request);
}
virtual void on_pointer_button(uint32_t button, uint32_t state) override
{
if (button != BTN_LEFT)
return;
handle_action(layout.handle_press_event(state == WLR_BUTTON_PRESSED));
}
void handle_action(wf::decor::decoration_layout_t::action_response_t action)
{
switch (action.action)
{
case wf::decor::DECORATION_ACTION_MOVE:
return send_move_request();
case wf::decor::DECORATION_ACTION_RESIZE:
return send_resize_request(action.edges);
case wf::decor::DECORATION_ACTION_CLOSE:
return view->close();
case wf::decor::DECORATION_ACTION_TOGGLE_MAXIMIZE:
if (view->tiled_edges) {
view->tile_request(0);
} else {
view->tile_request(wf::TILED_EDGES_ALL);
}
break;
case wf::decor::DECORATION_ACTION_MINIMIZE:
view->minimize_request(true);
break;
default:
break;
}
}
virtual void on_touch_down(int x, int y) override
{
layout.handle_motion(x, y);
handle_action(layout.handle_press_event());
}
virtual void on_touch_motion(int x, int y) override
{ layout.handle_motion(x, y); }
virtual void on_touch_up() override
{
handle_action(layout.handle_press_event(false));
layout.handle_focus_lost();
}
/* frame implementation */
virtual wf::geometry_t expand_wm_geometry(
wf::geometry_t contained_wm_geometry) override
{
contained_wm_geometry.x -= current_thickness;
contained_wm_geometry.y -= current_titlebar;
contained_wm_geometry.width += 2 * current_thickness;
contained_wm_geometry.height += current_thickness + current_titlebar;
return contained_wm_geometry;
}
virtual void calculate_resize_size(
int& target_width, int& target_height) override
{
target_width -= 2 * current_thickness;
target_height -= current_thickness + current_titlebar;
target_width = std::max(target_width, 1);
target_height = std::max(target_height, 1);
}
virtual void notify_view_activated(bool active) override
{
if (this->active != active)
view->damage();
this->active = active;
}
virtual void notify_view_resized(wf::geometry_t view_geometry) override
{
view->damage();
width = view_geometry.width;
height = view_geometry.height;
layout.resize(width, height);
if (!view->fullscreen)
this->cached_region = layout.calculate_region();
view->damage();
};
virtual void notify_view_tiled() override
{ }
void update_decoration_size()
{
if (view->fullscreen)
{
current_thickness = 0;
current_titlebar = 0;
this->cached_region.clear();
} else
{
current_thickness = theme.get_border_size();
current_titlebar =
theme.get_title_height() + theme.get_border_size();
this->cached_region = layout.calculate_region();
}
}
virtual void notify_view_fullscreen() override
{
update_decoration_size();
if (!view->fullscreen)
notify_view_resized(view->get_wm_geometry());
};
};
void init_view(wayfire_view view)
{
auto surf = std::make_unique<simple_decoration_surface>(view);
nonstd::observer_ptr<simple_decoration_surface> ptr{surf};
view->add_subsurface(std::move(surf), true);
view->set_decoration(ptr.get());
view->damage();
}
<commit_msg>decoration: fix memory leak of text texture<commit_after>#define GLM_FORCE_RADIANS
#include <glm/gtc/matrix_transform.hpp>
#include <linux/input-event-codes.h>
#include <wayfire/compositor-surface.hpp>
#include <wayfire/output.hpp>
#include <wayfire/opengl.hpp>
#include <wayfire/core.hpp>
#include <wayfire/decorator.hpp>
#include <wayfire/view-transform.hpp>
#include <wayfire/signal-definitions.hpp>
#include "deco-subsurface.hpp"
#include "deco-layout.hpp"
#include "deco-theme.hpp"
#include <wayfire/plugins/common/cairo-util.hpp>
#include <cairo.h>
extern "C"
{
#define static
#include <wlr/render/wlr_renderer.h>
#include <wlr/types/wlr_matrix.h>
#include <wlr/types/wlr_xcursor_manager.h>
#undef static
}
class simple_decoration_surface : public wf::surface_interface_t,
public wf::compositor_surface_t, public wf::decorator_frame_t_t
{
bool _mapped = true;
int current_thickness;
int current_titlebar;
wayfire_view view;
wf::signal_callback_t title_set = [=] (wf::signal_data_t *data)
{
if (get_signaled_view(data) == view)
view->damage(); // trigger re-render
};
void update_title(int width, int height, double scale)
{
int target_width = width * scale;
int target_height = height * scale;
if (title_texture.tex.width != target_width ||
title_texture.tex.height != target_height ||
title_texture.current_text != view->get_title())
{
auto surface = theme.render_text(view->get_title(),
target_width, target_height);
cairo_surface_upload_to_texture(surface, title_texture.tex);
cairo_surface_destroy(surface);
title_texture.current_text = view->get_title();
}
}
int width = 100, height = 100;
bool active = true; // when views are mapped, they are usually activated
struct {
wf::simple_texture_t tex;
std::string current_text = "";
} title_texture;
wf::decor::decoration_theme_t theme;
wf::decor::decoration_layout_t layout;
wf::region_t cached_region;
public:
simple_decoration_surface(wayfire_view view) :
theme{},
layout{theme, [=] (wlr_box box) {this->damage_surface_box(box); }}
{
this->view = view;
view->connect_signal("title-changed", &title_set);
// make sure to hide frame if the view is fullscreen
update_decoration_size();
}
virtual ~simple_decoration_surface()
{
_mapped = false;
wf::emit_map_state_change(this);
view->disconnect_signal("title-changed", &title_set);
}
/* wf::surface_interface_t implementation */
virtual bool is_mapped() const final
{
return _mapped;
}
wf::point_t get_offset() final
{
return { -current_thickness, -current_titlebar };
}
virtual wf::dimensions_t get_size() const final
{
return {width, height};
}
void render_title(const wf::framebuffer_t& fb,
wf::geometry_t geometry)
{
update_title(geometry.width, geometry.height, fb.scale);
OpenGL::render_texture(title_texture.tex.tex, fb, geometry,
glm::vec4(1.0f), OpenGL::TEXTURE_TRANSFORM_INVERT_Y);
}
void render_scissor_box(const wf::framebuffer_t& fb, wf::point_t origin,
const wlr_box& scissor)
{
/* Clear background */
wlr_box geometry {origin.x, origin.y, width, height};
theme.render_background(fb, geometry, scissor, active);
/* Draw title & buttons */
auto renderables = layout.get_renderable_areas();
for (auto item : renderables)
{
if (item->get_type() == wf::decor::DECORATION_AREA_TITLE) {
OpenGL::render_begin(fb);
fb.logic_scissor(scissor);
render_title(fb, item->get_geometry() + origin);
OpenGL::render_end();
} else { // button
item->as_button().render(fb,
item->get_geometry() + origin, scissor);
}
}
}
virtual void simple_render(const wf::framebuffer_t& fb, int x, int y,
const wf::region_t& damage) override
{
wf::region_t frame = this->cached_region + wf::point_t{x, y};
frame &= damage;
for (const auto& box : frame)
render_scissor_box(fb, {x, y}, wlr_box_from_pixman_box(box));
}
bool accepts_input(int32_t sx, int32_t sy) override
{
return pixman_region32_contains_point(cached_region.to_pixman(),
sx, sy, NULL);
}
/* wf::compositor_surface_t implementation */
virtual void on_pointer_enter(int x, int y) override
{ layout.handle_motion(x, y); }
virtual void on_pointer_leave() override
{ layout.handle_focus_lost(); }
virtual void on_pointer_motion(int x, int y) override
{ layout.handle_motion(x, y); }
void send_move_request()
{
move_request_signal move_request;
move_request.view = view;
get_output()->emit_signal("move-request", &move_request);
}
void send_resize_request(uint32_t edges)
{
resize_request_signal resize_request;
resize_request.view = view;
resize_request.edges = edges;
get_output()->emit_signal("resize-request", &resize_request);
}
virtual void on_pointer_button(uint32_t button, uint32_t state) override
{
if (button != BTN_LEFT)
return;
handle_action(layout.handle_press_event(state == WLR_BUTTON_PRESSED));
}
void handle_action(wf::decor::decoration_layout_t::action_response_t action)
{
switch (action.action)
{
case wf::decor::DECORATION_ACTION_MOVE:
return send_move_request();
case wf::decor::DECORATION_ACTION_RESIZE:
return send_resize_request(action.edges);
case wf::decor::DECORATION_ACTION_CLOSE:
return view->close();
case wf::decor::DECORATION_ACTION_TOGGLE_MAXIMIZE:
if (view->tiled_edges) {
view->tile_request(0);
} else {
view->tile_request(wf::TILED_EDGES_ALL);
}
break;
case wf::decor::DECORATION_ACTION_MINIMIZE:
view->minimize_request(true);
break;
default:
break;
}
}
virtual void on_touch_down(int x, int y) override
{
layout.handle_motion(x, y);
handle_action(layout.handle_press_event());
}
virtual void on_touch_motion(int x, int y) override
{ layout.handle_motion(x, y); }
virtual void on_touch_up() override
{
handle_action(layout.handle_press_event(false));
layout.handle_focus_lost();
}
/* frame implementation */
virtual wf::geometry_t expand_wm_geometry(
wf::geometry_t contained_wm_geometry) override
{
contained_wm_geometry.x -= current_thickness;
contained_wm_geometry.y -= current_titlebar;
contained_wm_geometry.width += 2 * current_thickness;
contained_wm_geometry.height += current_thickness + current_titlebar;
return contained_wm_geometry;
}
virtual void calculate_resize_size(
int& target_width, int& target_height) override
{
target_width -= 2 * current_thickness;
target_height -= current_thickness + current_titlebar;
target_width = std::max(target_width, 1);
target_height = std::max(target_height, 1);
}
virtual void notify_view_activated(bool active) override
{
if (this->active != active)
view->damage();
this->active = active;
}
virtual void notify_view_resized(wf::geometry_t view_geometry) override
{
view->damage();
width = view_geometry.width;
height = view_geometry.height;
layout.resize(width, height);
if (!view->fullscreen)
this->cached_region = layout.calculate_region();
view->damage();
};
virtual void notify_view_tiled() override
{ }
void update_decoration_size()
{
if (view->fullscreen)
{
current_thickness = 0;
current_titlebar = 0;
this->cached_region.clear();
} else
{
current_thickness = theme.get_border_size();
current_titlebar =
theme.get_title_height() + theme.get_border_size();
this->cached_region = layout.calculate_region();
}
}
virtual void notify_view_fullscreen() override
{
update_decoration_size();
if (!view->fullscreen)
notify_view_resized(view->get_wm_geometry());
};
};
void init_view(wayfire_view view)
{
auto surf = std::make_unique<simple_decoration_surface>(view);
nonstd::observer_ptr<simple_decoration_surface> ptr{surf};
view->add_subsurface(std::move(surf), true);
view->set_decoration(ptr.get());
view->damage();
}
<|endoftext|> |
<commit_before>/*
* Copyright © 2014 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "brw_fs.h"
#include "brw_fs_live_variables.h"
#include "brw_cfg.h"
/** @file brw_fs_cmod_propagation.cpp
*
* Implements a pass that propagates the conditional modifier from a CMP x 0.0
* instruction into the instruction that generated x. For instance, in this
* sequence
*
* add(8) g70<1>F g69<8,8,1>F 4096F
* cmp.ge.f0(8) null g70<8,8,1>F 0F
*
* we can do the comparison as part of the ADD instruction directly:
*
* add.ge.f0(8) g70<1>F g69<8,8,1>F 4096F
*
* If there had been a use of the flag register and another CMP using g70
*
* add.ge.f0(8) g70<1>F g69<8,8,1>F 4096F
* (+f0) sel(8) g71<F> g72<8,8,1>F g73<8,8,1>F
* cmp.ge.f0(8) null g70<8,8,1>F 0F
*
* we can recognize that the CMP is generating the flag value that already
* exists and therefore remove the instruction.
*/
static bool
opt_cmod_propagation_local(fs_visitor *v, bblock_t *block)
{
bool progress = false;
int ip = block->end_ip + 1;
foreach_inst_in_block_reverse_safe(fs_inst, inst, block) {
ip--;
if ((inst->opcode != BRW_OPCODE_CMP &&
inst->opcode != BRW_OPCODE_MOV) ||
inst->predicate != BRW_PREDICATE_NONE ||
!inst->dst.is_null() ||
inst->src[0].file != GRF ||
inst->src[0].abs)
continue;
if (inst->opcode == BRW_OPCODE_CMP && !inst->src[1].is_zero())
continue;
if (inst->opcode == BRW_OPCODE_MOV &&
(inst->conditional_mod != BRW_CONDITIONAL_NZ ||
inst->src[0].negate))
continue;
bool read_flag = false;
foreach_inst_in_block_reverse_starting_from(fs_inst, scan_inst, inst,
block) {
if (scan_inst->overwrites_reg(inst->src[0])) {
if (scan_inst->is_partial_write() ||
scan_inst->dst.reg_offset != inst->src[0].reg_offset)
break;
if (inst->opcode == BRW_OPCODE_MOV) {
if (!scan_inst->writes_flag())
break;
inst->remove(block);
progress = true;
break;
}
enum brw_conditional_mod cond =
inst->src[0].negate ? brw_swap_cmod(inst->conditional_mod)
: inst->conditional_mod;
if (scan_inst->can_do_cmod() &&
((!read_flag && scan_inst->conditional_mod == BRW_CONDITIONAL_NONE) ||
scan_inst->conditional_mod == cond)) {
scan_inst->conditional_mod = cond;
inst->remove(block);
progress = true;
}
break;
}
if (scan_inst->writes_flag())
break;
read_flag = read_flag || scan_inst->reads_flag();
}
}
return progress;
}
bool
fs_visitor::opt_cmod_propagation()
{
bool progress = false;
foreach_block_reverse(block, cfg) {
progress = opt_cmod_propagation_local(this, block) || progress;
}
if (progress)
invalidate_live_intervals();
return progress;
}
<commit_msg>i965: Handle CMP.nz ... 0 and MOV.nz similarly in cmod propagation.<commit_after>/*
* Copyright © 2014 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include "brw_fs.h"
#include "brw_fs_live_variables.h"
#include "brw_cfg.h"
/** @file brw_fs_cmod_propagation.cpp
*
* Implements a pass that propagates the conditional modifier from a CMP x 0.0
* instruction into the instruction that generated x. For instance, in this
* sequence
*
* add(8) g70<1>F g69<8,8,1>F 4096F
* cmp.ge.f0(8) null g70<8,8,1>F 0F
*
* we can do the comparison as part of the ADD instruction directly:
*
* add.ge.f0(8) g70<1>F g69<8,8,1>F 4096F
*
* If there had been a use of the flag register and another CMP using g70
*
* add.ge.f0(8) g70<1>F g69<8,8,1>F 4096F
* (+f0) sel(8) g71<F> g72<8,8,1>F g73<8,8,1>F
* cmp.ge.f0(8) null g70<8,8,1>F 0F
*
* we can recognize that the CMP is generating the flag value that already
* exists and therefore remove the instruction.
*/
static bool
opt_cmod_propagation_local(fs_visitor *v, bblock_t *block)
{
bool progress = false;
int ip = block->end_ip + 1;
foreach_inst_in_block_reverse_safe(fs_inst, inst, block) {
ip--;
if ((inst->opcode != BRW_OPCODE_CMP &&
inst->opcode != BRW_OPCODE_MOV) ||
inst->predicate != BRW_PREDICATE_NONE ||
!inst->dst.is_null() ||
inst->src[0].file != GRF ||
inst->src[0].abs)
continue;
if (inst->opcode == BRW_OPCODE_CMP && !inst->src[1].is_zero())
continue;
if (inst->opcode == BRW_OPCODE_MOV &&
inst->conditional_mod != BRW_CONDITIONAL_NZ)
continue;
bool read_flag = false;
foreach_inst_in_block_reverse_starting_from(fs_inst, scan_inst, inst,
block) {
if (scan_inst->overwrites_reg(inst->src[0])) {
if (scan_inst->is_partial_write() ||
scan_inst->dst.reg_offset != inst->src[0].reg_offset)
break;
/* If the instruction generating inst's source also wrote the
* flag, and inst is doing a simple .nz comparison, then inst
* is redundant - the appropriate value is already in the flag
* register. Delete inst.
*/
if (inst->conditional_mod == BRW_CONDITIONAL_NZ &&
!inst->src[0].negate &&
scan_inst->writes_flag()) {
inst->remove(block);
progress = true;
break;
}
/* Otherwise, try propagating the conditional. */
enum brw_conditional_mod cond =
inst->src[0].negate ? brw_swap_cmod(inst->conditional_mod)
: inst->conditional_mod;
if (scan_inst->can_do_cmod() &&
((!read_flag && scan_inst->conditional_mod == BRW_CONDITIONAL_NONE) ||
scan_inst->conditional_mod == cond)) {
scan_inst->conditional_mod = cond;
inst->remove(block);
progress = true;
}
break;
}
if (scan_inst->writes_flag())
break;
read_flag = read_flag || scan_inst->reads_flag();
}
}
return progress;
}
bool
fs_visitor::opt_cmod_propagation()
{
bool progress = false;
foreach_block_reverse(block, cfg) {
progress = opt_cmod_propagation_local(this, block) || progress;
}
if (progress)
invalidate_live_intervals();
return progress;
}
<|endoftext|> |
<commit_before>/**
* @file range_search_impl.hpp
* @author Ryan Curtin
*
* Implementation of the RangeSearch class.
*/
#ifndef __MLPACK_METHODS_RANGE_SEARCH_RANGE_SEARCH_IMPL_HPP
#define __MLPACK_METHODS_RANGE_SEARCH_RANGE_SEARCH_IMPL_HPP
// Just in case it hasn't been included.
#include "range_search.hpp"
// The rules for traversal.
#include "range_search_rules.hpp"
namespace mlpack {
namespace range {
template<typename TreeType>
TreeType* BuildTree(
typename TreeType::Mat& dataset,
std::vector<size_t>& oldFromNew,
typename boost::enable_if_c<
tree::TreeTraits<TreeType>::RearrangesDataset == true, TreeType*
>::type = 0)
{
return new TreeType(dataset, oldFromNew);
}
//! Call the tree constructor that does not do mapping.
template<typename TreeType>
TreeType* BuildTree(
const typename TreeType::Mat& dataset,
const std::vector<size_t>& /* oldFromNew */,
const typename boost::enable_if_c<
tree::TreeTraits<TreeType>::RearrangesDataset == false, TreeType*
>::type = 0)
{
return new TreeType(dataset);
}
template<typename MetricType,
typename MatType,
template<typename TreeMetricType,
typename TreeStatType,
typename TreeMatType> class TreeType>
RangeSearch<MetricType, MatType, TreeType>::RangeSearch(
const MatType& referenceSetIn,
const bool naive,
const bool singleMode,
const MetricType metric) :
referenceTree(naive ? NULL : BuildTree<Tree>(
const_cast<MatType&>(referenceSetIn), oldFromNewReferences)),
referenceSet(naive ? referenceSetIn : referenceTree->Dataset()),
treeOwner(!naive), // If in naive mode, we are not building any trees.
naive(naive),
singleMode(!naive && singleMode), // Naive overrides single mode.
metric(metric),
baseCases(0),
scores(0)
{
// Nothing to do.
}
template<typename MetricType,
typename MatType,
template<typename TreeMetricType,
typename TreeStatType,
typename TreeMatType> class TreeType>
RangeSearch<MetricType, MatType, TreeType>::RangeSearch(
Tree* referenceTree,
const bool singleMode,
const MetricType metric) :
referenceTree(referenceTree),
referenceSet(referenceTree->Dataset()),
treeOwner(false),
naive(false),
singleMode(singleMode),
metric(metric)
{
// Nothing else to initialize.
}
template<typename MetricType,
typename MatType,
template<typename TreeMetricType,
typename TreeStatType,
typename TreeMatType> class TreeType>
RangeSearch<MetricType, MatType, TreeType>::~RangeSearch()
{
if (treeOwner && referenceTree)
delete referenceTree;
}
template<typename MetricType,
typename MatType,
template<typename TreeMetricType,
typename TreeStatType,
typename TreeMatType> class TreeType>
void RangeSearch<MetricType, MatType, TreeType>::Search(
const MatType& querySet,
const math::Range& range,
std::vector<std::vector<size_t>>& neighbors,
std::vector<std::vector<double>>& distances)
{
Timer::Start("range_search/computing_neighbors");
// This will hold mappings for query points, if necessary.
std::vector<size_t> oldFromNewQueries;
// If we have built the trees ourselves, then we will have to map all the
// indices back to their original indices when this computation is finished.
// To avoid extra copies, we will store the unmapped neighbors and distances
// in a separate object.
std::vector<std::vector<size_t>>* neighborPtr = &neighbors;
std::vector<std::vector<double>>* distancePtr = &distances;
// Mapping is only necessary if the tree rearranges points.
if (tree::TreeTraits<Tree>::RearrangesDataset)
{
// Query indices only need to be mapped if we are building the query tree
// ourselves.
if (!singleMode && !naive)
distancePtr = new std::vector<std::vector<double>>;
// Reference indices only need to be mapped if we built the reference tree
// ourselves.
if (treeOwner)
neighborPtr = new std::vector<std::vector<size_t>>;
}
// Resize each vector.
neighborPtr->clear(); // Just in case there was anything in it.
neighborPtr->resize(querySet.n_cols);
distancePtr->clear();
distancePtr->resize(querySet.n_cols);
// Create the helper object for the traversal.
typedef RangeSearchRules<MetricType, Tree> RuleType;
// Reset counts.
baseCases = 0;
scores = 0;
if (naive)
{
RuleType rules(referenceSet, querySet, range, *neighborPtr, *distancePtr,
metric);
// The naive brute-force solution.
for (size_t i = 0; i < querySet.n_cols; ++i)
for (size_t j = 0; j < referenceSet.n_cols; ++j)
rules.BaseCase(i, j);
baseCases += (querySet.n_cols * referenceSet->n_cols);
}
else if (singleMode)
{
// Create the traverser.
RuleType rules(referenceSet, querySet, range, *neighborPtr, *distancePtr,
metric);
typename Tree::template SingleTreeTraverser<RuleType> traverser(rules);
// Now have it traverse for each point.
for (size_t i = 0; i < querySet.n_cols; ++i)
traverser.Traverse(i, *referenceTree);
baseCases += rules.BaseCases();
scores += rules.Scores();
}
else // Dual-tree recursion.
{
// Build the query tree.
Timer::Stop("range_search/computing_neighbors");
Timer::Start("range_search/tree_building");
Tree* queryTree = BuildTree<Tree>(const_cast<MatType&>(querySet),
oldFromNewQueries);
Timer::Stop("range_search/tree_building");
Timer::Start("range_search/computing_neighbors");
// Create the traverser.
RuleType rules(referenceSet, queryTree->Dataset(), range, *neighborPtr,
*distancePtr, metric);
typename Tree::template DualTreeTraverser<RuleType> traverser(rules);
traverser.Traverse(*queryTree, *referenceTree);
baseCases += rules.BaseCases();
scores += rules.Scores();
// Clean up tree memory.
delete queryTree;
}
Timer::Stop("range_search/computing_neighbors");
// Map points back to original indices, if necessary.
if (tree::TreeTraits<Tree>::RearrangesDataset)
{
if (!singleMode && !naive && treeOwner)
{
// We must map both query and reference indices.
neighbors.clear();
neighbors.resize(querySet.n_cols);
distances.clear();
distances.resize(querySet.n_cols);
for (size_t i = 0; i < distances.size(); i++)
{
// Map distances (copy a column).
const size_t queryMapping = oldFromNewQueries[i];
distances[queryMapping] = (*distancePtr)[i];
// Copy each neighbor individually, because we need to map it.
neighbors[queryMapping].resize(distances[queryMapping].size());
for (size_t j = 0; j < distances[queryMapping].size(); j++)
neighbors[queryMapping][j] =
oldFromNewReferences[(*neighborPtr)[i][j]];
}
// Finished with temporary objects.
delete neighborPtr;
delete distancePtr;
}
else if (!singleMode && !naive)
{
// We must map query indices only.
neighbors.clear();
neighbors.resize(querySet.n_cols);
distances.clear();
distances.resize(querySet.n_cols);
for (size_t i = 0; i < distances.size(); ++i)
{
// Map distances and neighbors (copy a column).
const size_t queryMapping = oldFromNewQueries[i];
distances[queryMapping] = (*distancePtr)[i];
neighbors[queryMapping] = (*neighborPtr)[i];
}
// Finished with temporary objects.
delete neighborPtr;
delete distancePtr;
}
else if (treeOwner)
{
// We must map reference indices only.
neighbors.clear();
neighbors.resize(querySet.n_cols);
for (size_t i = 0; i < neighbors.size(); i++)
{
neighbors[i].resize((*neighborPtr)[i].size());
for (size_t j = 0; j < neighbors[i].size(); j++)
neighbors[i][j] = oldFromNewReferences[(*neighborPtr)[i][j]];
}
// Finished with temporary object.
delete neighborPtr;
}
}
}
template<typename MetricType,
typename MatType,
template<typename TreeMetricType,
typename TreeStatType,
typename TreeMatType> class TreeType>
void RangeSearch<MetricType, MatType, TreeType>::Search(
Tree* queryTree,
const math::Range& range,
std::vector<std::vector<size_t>>& neighbors,
std::vector<std::vector<double>>& distances)
{
Timer::Start("range_search/computing_neighbors");
// Get a reference to the query set.
const MatType& querySet = queryTree->Dataset();
// Make sure we are in dual-tree mode.
if (singleMode || naive)
throw std::invalid_argument("cannot call RangeSearch::Search() with a "
"query tree when naive or singleMode are set to true");
// We won't need to map query indices, but will we need to map distances?
std::vector<std::vector<size_t>>* neighborPtr = &neighbors;
if (treeOwner && tree::TreeTraits<Tree>::RearrangesDataset)
neighborPtr = new std::vector<std::vector<size_t>>;
// Resize each vector.
neighborPtr->clear(); // Just in case there was anything in it.
neighborPtr->resize(querySet.n_cols);
distances.clear();
distances.resize(querySet.n_cols);
// Create the helper object for the traversal.
typedef RangeSearchRules<MetricType, Tree> RuleType;
RuleType rules(referenceSet, queryTree->Dataset(), range, *neighborPtr,
distances, metric);
// Create the traverser.
typename Tree::template DualTreeTraverser<RuleType> traverser(rules);
traverser.Traverse(*queryTree, *referenceTree);
Timer::Stop("range_search/computing_neighbors");
baseCases = rules.BaseCases();
scores = rules.Scores();
// Do we need to map indices?
if (treeOwner && tree::TreeTraits<Tree>::RearrangesDataset)
{
// We must map reference indices only.
neighbors.clear();
neighbors.resize(querySet.n_cols);
for (size_t i = 0; i < neighbors.size(); i++)
{
neighbors[i].resize((*neighborPtr)[i].size());
for (size_t j = 0; j < neighbors[i].size(); j++)
neighbors[i][j] = oldFromNewReferences[(*neighborPtr)[i][j]];
}
// Finished with temporary object.
delete neighborPtr;
}
}
template<typename MetricType,
typename MatType,
template<typename TreeMetricType,
typename TreeStatType,
typename TreeMatType> class TreeType>
void RangeSearch<MetricType, MatType, TreeType>::Search(
const math::Range& range,
std::vector<std::vector<size_t>>& neighbors,
std::vector<std::vector<double>>& distances)
{
Timer::Start("range_search/computing_neighbors");
// Here, we will use the query set as the reference set.
std::vector<std::vector<size_t>>* neighborPtr = &neighbors;
std::vector<std::vector<double>>* distancePtr = &distances;
if (tree::TreeTraits<Tree>::RearrangesDataset && treeOwner)
{
// We will always need to rearrange in this case.
distancePtr = new std::vector<std::vector<double>>;
neighborPtr = new std::vector<std::vector<size_t>>;
}
// Resize each vector.
neighborPtr->clear(); // Just in case there was anything in it.
neighborPtr->resize(referenceSet.n_cols);
distancePtr->clear();
distancePtr->resize(referenceSet.n_cols);
// Create the helper object for the traversal.
typedef RangeSearchRules<MetricType, Tree> RuleType;
RuleType rules(referenceSet, referenceSet, range, *neighborPtr, *distancePtr,
metric, true /* don't return the query point in the results */);
if (naive)
{
// The naive brute-force solution.
for (size_t i = 0; i < referenceSet.n_cols; ++i)
for (size_t j = 0; j < referenceSet.n_cols; ++j)
rules.BaseCase(i, j);
}
else if (singleMode)
{
// Create the traverser.
typename Tree::template SingleTreeTraverser<RuleType> traverser(rules);
// Now have it traverse for each point.
for (size_t i = 0; i < referenceSet.n_cols; ++i)
traverser.Traverse(i, *referenceTree);
baseCases = rules.BaseCases();
scores = rules.Scores();
}
else // Dual-tree recursion.
{
// Create the traverser.
typename Tree::template DualTreeTraverser<RuleType> traverser(rules);
traverser.Traverse(*referenceTree, *referenceTree);
baseCases = rules.BaseCases();
scores = rules.Scores();
}
Timer::Stop("range_search/computing_neighbors");
// Do we need to map the reference indices?
if (treeOwner && tree::TreeTraits<Tree>::RearrangesDataset)
{
neighbors.clear();
neighbors.resize(referenceSet.n_cols);
distances.clear();
distances.resize(referenceSet.n_cols);
for (size_t i = 0; i < distances.size(); i++)
{
// Map distances (copy a column).
const size_t refMapping = oldFromNewReferences[i];
distances[refMapping] = (*distancePtr)[i];
// Copy each neighbor individually, because we need to map it.
neighbors[refMapping].resize(distances[refMapping].size());
for (size_t j = 0; j < distances[refMapping].size(); j++)
{
neighbors[refMapping][j] = oldFromNewReferences[(*neighborPtr)[i][j]];
}
}
// Finished with temporary objects.
delete neighborPtr;
delete distancePtr;
}
}
template<typename MetricType,
typename MatType,
template<typename TreeMetricType,
typename TreeStatType,
typename TreeMatType> class TreeType>
std::string RangeSearch<MetricType, MatType, TreeType>::ToString() const
{
std::ostringstream convert;
convert << "Range Search [" << this << "]" << std::endl;
if (treeOwner)
convert << " Tree Owner: TRUE" << std::endl;
if (naive)
convert << " Naive: TRUE" << std::endl;
convert << " Metric: " << std::endl <<
mlpack::util::Indent(metric.ToString(),2);
return convert.str();
}
} // namespace range
} // namespace mlpack
#endif
<commit_msg>Initialize baseCases and scores correctly.<commit_after>/**
* @file range_search_impl.hpp
* @author Ryan Curtin
*
* Implementation of the RangeSearch class.
*/
#ifndef __MLPACK_METHODS_RANGE_SEARCH_RANGE_SEARCH_IMPL_HPP
#define __MLPACK_METHODS_RANGE_SEARCH_RANGE_SEARCH_IMPL_HPP
// Just in case it hasn't been included.
#include "range_search.hpp"
// The rules for traversal.
#include "range_search_rules.hpp"
namespace mlpack {
namespace range {
template<typename TreeType>
TreeType* BuildTree(
typename TreeType::Mat& dataset,
std::vector<size_t>& oldFromNew,
typename boost::enable_if_c<
tree::TreeTraits<TreeType>::RearrangesDataset == true, TreeType*
>::type = 0)
{
return new TreeType(dataset, oldFromNew);
}
//! Call the tree constructor that does not do mapping.
template<typename TreeType>
TreeType* BuildTree(
const typename TreeType::Mat& dataset,
const std::vector<size_t>& /* oldFromNew */,
const typename boost::enable_if_c<
tree::TreeTraits<TreeType>::RearrangesDataset == false, TreeType*
>::type = 0)
{
return new TreeType(dataset);
}
template<typename MetricType,
typename MatType,
template<typename TreeMetricType,
typename TreeStatType,
typename TreeMatType> class TreeType>
RangeSearch<MetricType, MatType, TreeType>::RangeSearch(
const MatType& referenceSetIn,
const bool naive,
const bool singleMode,
const MetricType metric) :
referenceTree(naive ? NULL : BuildTree<Tree>(
const_cast<MatType&>(referenceSetIn), oldFromNewReferences)),
referenceSet(naive ? referenceSetIn : referenceTree->Dataset()),
treeOwner(!naive), // If in naive mode, we are not building any trees.
naive(naive),
singleMode(!naive && singleMode), // Naive overrides single mode.
metric(metric),
baseCases(0),
scores(0)
{
// Nothing to do.
}
template<typename MetricType,
typename MatType,
template<typename TreeMetricType,
typename TreeStatType,
typename TreeMatType> class TreeType>
RangeSearch<MetricType, MatType, TreeType>::RangeSearch(
Tree* referenceTree,
const bool singleMode,
const MetricType metric) :
referenceTree(referenceTree),
referenceSet(referenceTree->Dataset()),
treeOwner(false),
naive(false),
singleMode(singleMode),
metric(metric),
baseCases(0),
scores(0)
{
// Nothing else to initialize.
}
template<typename MetricType,
typename MatType,
template<typename TreeMetricType,
typename TreeStatType,
typename TreeMatType> class TreeType>
RangeSearch<MetricType, MatType, TreeType>::~RangeSearch()
{
if (treeOwner && referenceTree)
delete referenceTree;
}
template<typename MetricType,
typename MatType,
template<typename TreeMetricType,
typename TreeStatType,
typename TreeMatType> class TreeType>
void RangeSearch<MetricType, MatType, TreeType>::Search(
const MatType& querySet,
const math::Range& range,
std::vector<std::vector<size_t>>& neighbors,
std::vector<std::vector<double>>& distances)
{
Timer::Start("range_search/computing_neighbors");
// This will hold mappings for query points, if necessary.
std::vector<size_t> oldFromNewQueries;
// If we have built the trees ourselves, then we will have to map all the
// indices back to their original indices when this computation is finished.
// To avoid extra copies, we will store the unmapped neighbors and distances
// in a separate object.
std::vector<std::vector<size_t>>* neighborPtr = &neighbors;
std::vector<std::vector<double>>* distancePtr = &distances;
// Mapping is only necessary if the tree rearranges points.
if (tree::TreeTraits<Tree>::RearrangesDataset)
{
// Query indices only need to be mapped if we are building the query tree
// ourselves.
if (!singleMode && !naive)
distancePtr = new std::vector<std::vector<double>>;
// Reference indices only need to be mapped if we built the reference tree
// ourselves.
if (treeOwner)
neighborPtr = new std::vector<std::vector<size_t>>;
}
// Resize each vector.
neighborPtr->clear(); // Just in case there was anything in it.
neighborPtr->resize(querySet.n_cols);
distancePtr->clear();
distancePtr->resize(querySet.n_cols);
// Create the helper object for the traversal.
typedef RangeSearchRules<MetricType, Tree> RuleType;
// Reset counts.
baseCases = 0;
scores = 0;
if (naive)
{
RuleType rules(referenceSet, querySet, range, *neighborPtr, *distancePtr,
metric);
// The naive brute-force solution.
for (size_t i = 0; i < querySet.n_cols; ++i)
for (size_t j = 0; j < referenceSet.n_cols; ++j)
rules.BaseCase(i, j);
baseCases += (querySet.n_cols * referenceSet->n_cols);
}
else if (singleMode)
{
// Create the traverser.
RuleType rules(referenceSet, querySet, range, *neighborPtr, *distancePtr,
metric);
typename Tree::template SingleTreeTraverser<RuleType> traverser(rules);
// Now have it traverse for each point.
for (size_t i = 0; i < querySet.n_cols; ++i)
traverser.Traverse(i, *referenceTree);
baseCases += rules.BaseCases();
scores += rules.Scores();
}
else // Dual-tree recursion.
{
// Build the query tree.
Timer::Stop("range_search/computing_neighbors");
Timer::Start("range_search/tree_building");
Tree* queryTree = BuildTree<Tree>(const_cast<MatType&>(querySet),
oldFromNewQueries);
Timer::Stop("range_search/tree_building");
Timer::Start("range_search/computing_neighbors");
// Create the traverser.
RuleType rules(referenceSet, queryTree->Dataset(), range, *neighborPtr,
*distancePtr, metric);
typename Tree::template DualTreeTraverser<RuleType> traverser(rules);
traverser.Traverse(*queryTree, *referenceTree);
baseCases += rules.BaseCases();
scores += rules.Scores();
// Clean up tree memory.
delete queryTree;
}
Timer::Stop("range_search/computing_neighbors");
// Map points back to original indices, if necessary.
if (tree::TreeTraits<Tree>::RearrangesDataset)
{
if (!singleMode && !naive && treeOwner)
{
// We must map both query and reference indices.
neighbors.clear();
neighbors.resize(querySet.n_cols);
distances.clear();
distances.resize(querySet.n_cols);
for (size_t i = 0; i < distances.size(); i++)
{
// Map distances (copy a column).
const size_t queryMapping = oldFromNewQueries[i];
distances[queryMapping] = (*distancePtr)[i];
// Copy each neighbor individually, because we need to map it.
neighbors[queryMapping].resize(distances[queryMapping].size());
for (size_t j = 0; j < distances[queryMapping].size(); j++)
neighbors[queryMapping][j] =
oldFromNewReferences[(*neighborPtr)[i][j]];
}
// Finished with temporary objects.
delete neighborPtr;
delete distancePtr;
}
else if (!singleMode && !naive)
{
// We must map query indices only.
neighbors.clear();
neighbors.resize(querySet.n_cols);
distances.clear();
distances.resize(querySet.n_cols);
for (size_t i = 0; i < distances.size(); ++i)
{
// Map distances and neighbors (copy a column).
const size_t queryMapping = oldFromNewQueries[i];
distances[queryMapping] = (*distancePtr)[i];
neighbors[queryMapping] = (*neighborPtr)[i];
}
// Finished with temporary objects.
delete neighborPtr;
delete distancePtr;
}
else if (treeOwner)
{
// We must map reference indices only.
neighbors.clear();
neighbors.resize(querySet.n_cols);
for (size_t i = 0; i < neighbors.size(); i++)
{
neighbors[i].resize((*neighborPtr)[i].size());
for (size_t j = 0; j < neighbors[i].size(); j++)
neighbors[i][j] = oldFromNewReferences[(*neighborPtr)[i][j]];
}
// Finished with temporary object.
delete neighborPtr;
}
}
}
template<typename MetricType,
typename MatType,
template<typename TreeMetricType,
typename TreeStatType,
typename TreeMatType> class TreeType>
void RangeSearch<MetricType, MatType, TreeType>::Search(
Tree* queryTree,
const math::Range& range,
std::vector<std::vector<size_t>>& neighbors,
std::vector<std::vector<double>>& distances)
{
Timer::Start("range_search/computing_neighbors");
// Get a reference to the query set.
const MatType& querySet = queryTree->Dataset();
// Make sure we are in dual-tree mode.
if (singleMode || naive)
throw std::invalid_argument("cannot call RangeSearch::Search() with a "
"query tree when naive or singleMode are set to true");
// We won't need to map query indices, but will we need to map distances?
std::vector<std::vector<size_t>>* neighborPtr = &neighbors;
if (treeOwner && tree::TreeTraits<Tree>::RearrangesDataset)
neighborPtr = new std::vector<std::vector<size_t>>;
// Resize each vector.
neighborPtr->clear(); // Just in case there was anything in it.
neighborPtr->resize(querySet.n_cols);
distances.clear();
distances.resize(querySet.n_cols);
// Create the helper object for the traversal.
typedef RangeSearchRules<MetricType, Tree> RuleType;
RuleType rules(referenceSet, queryTree->Dataset(), range, *neighborPtr,
distances, metric);
// Create the traverser.
typename Tree::template DualTreeTraverser<RuleType> traverser(rules);
traverser.Traverse(*queryTree, *referenceTree);
Timer::Stop("range_search/computing_neighbors");
baseCases = rules.BaseCases();
scores = rules.Scores();
// Do we need to map indices?
if (treeOwner && tree::TreeTraits<Tree>::RearrangesDataset)
{
// We must map reference indices only.
neighbors.clear();
neighbors.resize(querySet.n_cols);
for (size_t i = 0; i < neighbors.size(); i++)
{
neighbors[i].resize((*neighborPtr)[i].size());
for (size_t j = 0; j < neighbors[i].size(); j++)
neighbors[i][j] = oldFromNewReferences[(*neighborPtr)[i][j]];
}
// Finished with temporary object.
delete neighborPtr;
}
}
template<typename MetricType,
typename MatType,
template<typename TreeMetricType,
typename TreeStatType,
typename TreeMatType> class TreeType>
void RangeSearch<MetricType, MatType, TreeType>::Search(
const math::Range& range,
std::vector<std::vector<size_t>>& neighbors,
std::vector<std::vector<double>>& distances)
{
Timer::Start("range_search/computing_neighbors");
// Here, we will use the query set as the reference set.
std::vector<std::vector<size_t>>* neighborPtr = &neighbors;
std::vector<std::vector<double>>* distancePtr = &distances;
if (tree::TreeTraits<Tree>::RearrangesDataset && treeOwner)
{
// We will always need to rearrange in this case.
distancePtr = new std::vector<std::vector<double>>;
neighborPtr = new std::vector<std::vector<size_t>>;
}
// Resize each vector.
neighborPtr->clear(); // Just in case there was anything in it.
neighborPtr->resize(referenceSet.n_cols);
distancePtr->clear();
distancePtr->resize(referenceSet.n_cols);
// Create the helper object for the traversal.
typedef RangeSearchRules<MetricType, Tree> RuleType;
RuleType rules(referenceSet, referenceSet, range, *neighborPtr, *distancePtr,
metric, true /* don't return the query point in the results */);
if (naive)
{
// The naive brute-force solution.
for (size_t i = 0; i < referenceSet.n_cols; ++i)
for (size_t j = 0; j < referenceSet.n_cols; ++j)
rules.BaseCase(i, j);
}
else if (singleMode)
{
// Create the traverser.
typename Tree::template SingleTreeTraverser<RuleType> traverser(rules);
// Now have it traverse for each point.
for (size_t i = 0; i < referenceSet.n_cols; ++i)
traverser.Traverse(i, *referenceTree);
baseCases = rules.BaseCases();
scores = rules.Scores();
}
else // Dual-tree recursion.
{
// Create the traverser.
typename Tree::template DualTreeTraverser<RuleType> traverser(rules);
traverser.Traverse(*referenceTree, *referenceTree);
baseCases = rules.BaseCases();
scores = rules.Scores();
}
Timer::Stop("range_search/computing_neighbors");
// Do we need to map the reference indices?
if (treeOwner && tree::TreeTraits<Tree>::RearrangesDataset)
{
neighbors.clear();
neighbors.resize(referenceSet.n_cols);
distances.clear();
distances.resize(referenceSet.n_cols);
for (size_t i = 0; i < distances.size(); i++)
{
// Map distances (copy a column).
const size_t refMapping = oldFromNewReferences[i];
distances[refMapping] = (*distancePtr)[i];
// Copy each neighbor individually, because we need to map it.
neighbors[refMapping].resize(distances[refMapping].size());
for (size_t j = 0; j < distances[refMapping].size(); j++)
{
neighbors[refMapping][j] = oldFromNewReferences[(*neighborPtr)[i][j]];
}
}
// Finished with temporary objects.
delete neighborPtr;
delete distancePtr;
}
}
template<typename MetricType,
typename MatType,
template<typename TreeMetricType,
typename TreeStatType,
typename TreeMatType> class TreeType>
std::string RangeSearch<MetricType, MatType, TreeType>::ToString() const
{
std::ostringstream convert;
convert << "Range Search [" << this << "]" << std::endl;
if (treeOwner)
convert << " Tree Owner: TRUE" << std::endl;
if (naive)
convert << " Naive: TRUE" << std::endl;
convert << " Metric: " << std::endl <<
mlpack::util::Indent(metric.ToString(),2);
return convert.str();
}
} // namespace range
} // namespace mlpack
#endif
<|endoftext|> |
<commit_before>/* Copyright (C) 2006 Imperial College London and others.
Please see the AUTHORS file in the main source directory for a full list
of copyright holders.
Prof. C Pain
Applied Modelling and Computation Group
Department of Earth Science and Engineering
Imperial College London
C.Pain@Imperial.ac.uk
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,
version 2.1 of the License.
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
*/
#include <cstring>
#include <iostream>
#include <stdlib.h>
#include "confdefs.h"
#include "c++debug.h"
#ifdef HAVE_MPI
#include <mpi.h>
#endif
using namespace std;
extern "C"{
#define pseudo_mesh F77_FUNC(pseudo_mesh, PSEUDO_MESH)
void pseudo_mesh(const char* filename, const int* filename_len, const int* target_elements);
}
void Usage(){
cout << "Usage: pseudo_mesh TRIANGLE_BASENAME\n"
<< "\n"
<< "Generates a new mesh with approximately the same local nodal density as the\n"
<< "input mesh\n"
<< "\n"
<< "Options:\n"
<< "\n"
<< "-h\t\tDisplay this help\n"
<< "-t\t\tLimit the adaptivity metric to target the same number of\n"
<< "\t\telements in the pseudo mesh as in the target mesh\n"
<< "-v\t\tVerbose mode" << endl;
}
int main(int argc, char** argv){
#ifdef HAVE_MPI
MPI::Init(argc, argv);
// Undo some MPI init shenanigans
chdir(getenv("PWD"));
#endif
if(argc < 2){
Usage();
return -1;
}
// Modified version of flredecomp argument parsing
// Get any command line arguments
// Reset optarg so we can detect changes
optarg = NULL;
char c;
map<char, string> args;
while((c = getopt(argc, argv, "htv")) != -1){
if (c != '?'){
if(optarg == NULL){
args[c] = "true";
}else{
args[c] = optarg;
}
}else{
if(isprint(optopt)){
cerr << "Unknown option " << optopt << endl;
}else{
cerr << "Unknown option " << hex << optopt << endl;
}
Usage();
exit(-1);
}
}
// Help
if(args.count('h')){
Usage();
exit(0);
}
// Verbosity
int verbosity = 0;
if(args.count('v') > 0){
verbosity = 3;
}
set_global_debug_level_fc(&verbosity);
int target_elements;
target_elements = args.count('t') > 0 ? 1 : 0;
int filename_len = strlen(argv[optind]);
pseudo_mesh(argv[optind], &filename_len, &target_elements);
#ifdef HAVE_MPI
MPI::Finalize();
#endif
return 0;
}
<commit_msg>Avoid a seg fault on invalid input<commit_after>/* Copyright (C) 2006 Imperial College London and others.
Please see the AUTHORS file in the main source directory for a full list
of copyright holders.
Prof. C Pain
Applied Modelling and Computation Group
Department of Earth Science and Engineering
Imperial College London
C.Pain@Imperial.ac.uk
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,
version 2.1 of the License.
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
*/
#include <cstring>
#include <iostream>
#include <stdlib.h>
#include "confdefs.h"
#include "c++debug.h"
#ifdef HAVE_MPI
#include <mpi.h>
#endif
using namespace std;
extern "C"{
#define pseudo_mesh F77_FUNC(pseudo_mesh, PSEUDO_MESH)
void pseudo_mesh(const char* filename, const int* filename_len, const int* target_elements);
}
void Usage(){
cout << "Usage: pseudo_mesh TRIANGLE_BASENAME\n"
<< "\n"
<< "Generates a new mesh with approximately the same local nodal density as the\n"
<< "input mesh\n"
<< "\n"
<< "Options:\n"
<< "\n"
<< "-h\t\tDisplay this help\n"
<< "-t\t\tLimit the adaptivity metric to target the same number of\n"
<< "\t\telements in the pseudo mesh as in the target mesh\n"
<< "-v\t\tVerbose mode" << endl;
}
int main(int argc, char** argv){
#ifdef HAVE_MPI
MPI::Init(argc, argv);
// Undo some MPI init shenanigans
chdir(getenv("PWD"));
#endif
if(argc < 2){
Usage();
return -1;
}
// Modified version of flredecomp argument parsing
// Get any command line arguments
// Reset optarg so we can detect changes
optarg = NULL;
char c;
map<char, string> args;
while((c = getopt(argc, argv, "htv")) != -1){
if (c != '?'){
if(optarg == NULL){
args[c] = "true";
}else{
args[c] = optarg;
}
}else{
if(isprint(optopt)){
cerr << "Unknown option " << optopt << endl;
}else{
cerr << "Unknown option " << hex << optopt << endl;
}
Usage();
exit(-1);
}
}
// Help
if(args.count('h')){
Usage();
exit(0);
}
if (optind != argc - 1){
cerr << "Need exactly one non-option argument" << endl;
Usage();
exit(-1);
}
// Verbosity
int verbosity = 0;
if(args.count('v') > 0){
verbosity = 3;
}
set_global_debug_level_fc(&verbosity);
int target_elements;
target_elements = args.count('t') > 0 ? 1 : 0;
int filename_len = strlen(argv[optind]);
pseudo_mesh(argv[optind], &filename_len, &target_elements);
#ifdef HAVE_MPI
MPI::Finalize();
#endif
return 0;
}
<|endoftext|> |
<commit_before>/*
* This source file is part of ArkGameFrame
* For the latest info, see https://github.com/ArkGame
*
* Copyright (c) 2013-2018 ArkGame authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#pragma once
#include "SDK/Core/AFMacros.hpp"
template <typename TD, bool NEEDSMART>
struct MapSmartPtrType
{
typedef TD* VALUE;
};
template <typename TD>
struct MapSmartPtrType<TD, true>
{
typedef ARK_SHARE_PTR<TD> VALUE;
};
template <typename TD>
struct MapSmartPtrType<TD, false>
{
typedef TD* VALUE;
};
template <typename T, typename TD, bool NEEDSMART>
class AFMapBase
{
public:
typedef typename MapSmartPtrType<TD, NEEDSMART>::VALUE PTRTYPE;
typedef std::map<T, PTRTYPE > MAP_DATA;
AFMapBase()
{
mNullPtr = nullptr;
}
virtual ~AFMapBase() = default;
virtual bool AddElement(const T& name, const PTRTYPE data)
{
typename MAP_DATA::iterator iter = mxObjectList.find(name);
if (iter == mxObjectList.end())
{
mxObjectList.insert(typename MAP_DATA::value_type(name, data));
return true;
}
return false;
}
virtual bool SetElement(const T& name, const PTRTYPE data)
{
mxObjectList[name] = data;
return true;
}
virtual bool RemoveElement(const T& name)
{
typename MAP_DATA::iterator iter = mxObjectList.find(name);
if (iter != mxObjectList.end())
{
mxObjectList.erase(iter);
return true;
}
return false;
}
virtual const PTRTYPE& GetElement(const T& name)
{
typename MAP_DATA::iterator iter = mxObjectList.find(name);
if (iter != mxObjectList.end())
{
return iter->second;
}
else
{
return mNullPtr;
}
}
virtual const PTRTYPE& First()
{
if (mxObjectList.size() <= 0)
{
return mNullPtr;
}
mxObjectCurIter = mxObjectList.begin();
if (mxObjectCurIter != mxObjectList.end())
{
return mxObjectCurIter->second;
}
else
{
return mNullPtr;
}
}
virtual const PTRTYPE& Next()
{
if (mxObjectCurIter == mxObjectList.end())
{
return mNullPtr;
}
++mxObjectCurIter;
if (mxObjectCurIter != mxObjectList.end())
{
return mxObjectCurIter->second;
}
else
{
return mNullPtr;
}
}
virtual const PTRTYPE& First(T& name)
{
if (mxObjectList.size() <= 0)
{
return mNullPtr;
}
mxObjectCurIter = mxObjectList.begin();
if (mxObjectCurIter != mxObjectList.end())
{
name = mxObjectCurIter->first;
return mxObjectCurIter->second;
}
else
{
return mNullPtr;
}
}
virtual const PTRTYPE& Next(T& name)
{
if (mxObjectCurIter == mxObjectList.end())
{
return mNullPtr;
}
mxObjectCurIter++;
if (mxObjectCurIter != mxObjectList.end())
{
name = mxObjectCurIter->first;
return mxObjectCurIter->second;
}
else
{
return mNullPtr;
}
}
int GetCount()
{
return (int)mxObjectList.size();
}
bool ClearAll()
{
mxObjectList.clear();
return true;
}
bool Begin()
{
mxObjectCurIter = mxObjectList.begin();
return mxObjectCurIter != mxObjectList.end();
}
bool Increase()
{
if (mxObjectCurIter != mxObjectList.end())
{
++mxObjectCurIter;
if (mxObjectCurIter != mxObjectList.end())
{
return true;
}
}
return false;
}
const PTRTYPE& GetCurrentData()
{
if (mxObjectCurIter != mxObjectList.end())
{
return mxObjectCurIter->second;
}
else
{
return mNullPtr;
}
}
private:
MAP_DATA mxObjectList;
typename MAP_DATA::iterator mxObjectCurIter;
PTRTYPE mNullPtr;
};
template <typename T, typename TD>
class AFMapEx: public AFMapBase<T, TD, true >
{
};
template <typename T, typename TD>
class AFMap: public AFMapBase<T, TD, false >
{
};
<commit_msg>test sonarcloud<commit_after>/*
* This source file is part of ArkGameFrame
* For the latest info, see https://github.com/ArkGame
*
* Copyright (c) 2013-2018 ArkGame authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#pragma once
#include "SDK/Core/AFMacros.hpp"
template <typename TD, bool NEEDSMART>
struct MapSmartPtrType
{
typedef TD* VALUE;
};
template <typename TD>
struct MapSmartPtrType<TD, true>
{
typedef ARK_SHARE_PTR<TD> VALUE;
};
template <typename TD>
struct MapSmartPtrType<TD, false>
{
typedef TD* VALUE;
};
template <typename T, typename TD, bool NEEDSMART>
class AFMapBase
{
public:
typedef typename MapSmartPtrType<TD, NEEDSMART>::VALUE PTRTYPE;
typedef std::map<T, PTRTYPE > MAP_DATA;
AFMapBase()
{
mNullPtr = nullptr;
}
virtual ~AFMapBase() = default;
virtual bool AddElement(const T& name, const PTRTYPE data)
{
typename MAP_DATA::iterator iter = mxObjectList.find(name);
if (iter == mxObjectList.end())
{
mxObjectList.insert(typename MAP_DATA::value_type(name, data));
return true;
}
return false;
}
virtual bool SetElement(const T& name, const PTRTYPE data)
{
mxObjectList[name] = data;
return true;
}
virtual bool RemoveElement(const T& name)
{
typename MAP_DATA::iterator iter = mxObjectList.find(name);
if (iter != mxObjectList.end())
{
mxObjectList.erase(iter);
return true;
}
return false;
}
virtual const PTRTYPE& GetElement(const T& name)
{
typename MAP_DATA::iterator iter = mxObjectList.find(name);
if (iter != mxObjectList.end())
{
return iter->second;
}
else
{
return mNullPtr;
}
}
virtual const PTRTYPE& First()
{
if (mxObjectList.size() <= 0)
{
return mNullPtr;
}
mxObjectCurIter = mxObjectList.begin();
if (mxObjectCurIter != mxObjectList.end())
{
return mxObjectCurIter->second;
}
else
{
return mNullPtr;
}
}
virtual const PTRTYPE& Next()
{
if (mxObjectCurIter == mxObjectList.end())
{
return mNullPtr;
}
++mxObjectCurIter;
if (mxObjectCurIter != mxObjectList.end())
{
return mxObjectCurIter->second;
}
else
{
return mNullPtr;
}
}
virtual const PTRTYPE& First(T& name)
{
if (mxObjectList.size() <= 0)
{
return mNullPtr;
}
mxObjectCurIter = mxObjectList.begin();
if (mxObjectCurIter != mxObjectList.end())
{
name = mxObjectCurIter->first;
return mxObjectCurIter->second;
}
else
{
return mNullPtr;
}
}
virtual const PTRTYPE& Next(T& name)
{
if (mxObjectCurIter == mxObjectList.end())
{
return mNullPtr;
}
mxObjectCurIter++;
if (mxObjectCurIter != mxObjectList.end())
{
name = mxObjectCurIter->first;
return mxObjectCurIter->second;
}
else
{
return mNullPtr;
}
}
int GetCount()
{
return (int)mxObjectList.size();
}
bool ClearAll()
{
mxObjectList.clear();
return true;
}
bool Begin()
{
mxObjectCurIter = mxObjectList.begin();
return mxObjectCurIter != mxObjectList.end();
}
bool Increase()
{
if (mxObjectCurIter != mxObjectList.end())
{
++mxObjectCurIter;
if (mxObjectCurIter != mxObjectList.end())
{
return true;
}
}
return false;
}
const PTRTYPE& GetCurrentData()
{
if (mxObjectCurIter != mxObjectList.end())
{
return mxObjectCurIter->second;
}
else
{
return mNullPtr;
}
}
private:
MAP_DATA mxObjectList;
typename MAP_DATA::iterator mxObjectCurIter;
PTRTYPE mNullPtr;
};
template <typename T, typename TD>
class AFMapEx: public AFMapBase<T, TD, true >
{
};
template <typename T, typename TD>
class AFMap: public AFMapBase<T, TD, false >
{
};
<|endoftext|> |
<commit_before>#include <iostream>
#include <algorithm>
#include <cassert>
using namespace std;
// 大域変数
const int T = 9; // 全ターン数
const int P = 4; // プレイヤー数
const int N = 6; // プログラミングの言語数
const int maxpt = 6;
const int minpt = 3;
const int wdays = 5;
const int hdays = 2;
int A[N]; // 言語の注目数
int priority[N];
/*
priority[0] 取りに行く言語1
priority[1] 取りに行く言語2
priority[2] 落とさない言語1
priority[3] 落とさない言語2 できれば取りにいく
priority[4] 落とさない言語3
priority[5] 捨てる言語
*/
// ターンでの変数
int turn; // 現在のターン
bool isweekday; // 平日か?
int B[N][P]; // B[n][p] = プレイヤーpの言語nへの信者数
int R[N]; // 自分の本当の投票数
int W[N]; // 前の休日までの、明らかになっていない休日の布教回数(自分を除く)
int days; // 最大数
int L[wdays]; // 出力
void first_init() {
// 初期化・入力
int x;
cin >> x;
cin >> x;
cin >> x;
for (int i=0; i<N; i++) {
cin >> A[i];
}
fill(W, W+N, 0);
// priorityの確定
bool used[N];
fill(used, used+N, false);
// priority[2]の確定
for (int i=maxpt; i>=minpt; i--) {
for (int j=0; j<N; j++) {
if (A[j] == i) {
priority[2] = j;
used[j] = true;
goto EXIT_OF_PRIORITY_2;
}
}
}
EXIT_OF_PRIORITY_2:
// priority[0][1]の確定
int count = 0;
for (int i=maxpt; i>=minpt; i--) {
for (int j=N-1; j>=0; j--) {
if (!used[j] && A[j] == i) {
priority[count++] = j;
used[j] = true;
if (count == 2) {
goto EXIT_OF_PRIORITY_01;
}
}
}
}
EXIT_OF_PRIORITY_01:
// priority[3][4][5]の確定
count = 3;
for (int i=maxpt; i>=minpt; i--) {
for (int j=N-1; j>=0; j--) {
if (!used[j] && A[j] == i) {
priority[count++] = j;
used[j] = true;
if (count == 5) {
goto EXIT_OF_PRIORITY_345;
}
}
}
}
EXIT_OF_PRIORITY_345:
return;
}
void turn_init() {
cin >> turn;
char D;
cin >> D;
isweekday = (D == 'W');
if (isweekday) {
days = wdays;
} else {
days = hdays;
}
for (int i=0; i<N; i++) {
for (int j=0; j<P; j++) {
cin >> B[i][j];
}
}
for (int i=0; i<N; i++) {
cin >> R[i];
}
if (turn == 6) {
fill(W, W+P, 0);
}
if (isweekday) {
for (int i=0; i<N; i++) {
int w;
cin >> w;
W[i] += w;
}
}
}
bool hantei(int lang, bool istop) {
// // cerr << "days = " << days << endl;
int m = B[lang][1];
for (int i=1; i<P; i++) {
if (istop) {
m = max(m, B[lang][i]);
} else {
m = min(m, B[lang][i]);
}
}
return (R[lang] >= m + W[lang]);
}
bool isgood(int lang_priority) {
int lang = priority[lang_priority];
if (lang_priority <= 1) {
return hantei(lang, true);
} else {
return hantei(lang, false);
}
}
void determine_L() {
if (turn == 1) {
for (int i=0; i<days; i++) {
L[i] = priority[4-i];
}
} else if (turn == 2) {
for (int i=0; i<days; i++) {
L[i] = priority[0];
}
} else {
int now_c = 0;
int now_p = 0;
// 戦略に基づき割り振る
while (now_p < 5 && now_c < days) {
if (!isgood(now_p)) {
int lang = priority[now_p];
L[now_c++] = lang;
R[lang] += ((isweekday) ? 1 : 2);
} else {
now_p++;
}
}
// 枠が余ったら
while (now_c < days) {
L[now_c++] = priority[3];
}
}
}
void turn_output() {
determine_L();
for (int i=0; i<days; i++) {
cout << L[i];
if (i != days-1) {
cout << " ";
}
if(!isweekday) {
W[L[i]]--;
}
}
cout << endl;
}
int main() {
cout << "READY" << endl;
// ゲーム設定の入力
first_init();
// ターン情報の入力
for (int t=1; t<=T; t++) {
turn_init();
turn_output();
}
}
<commit_msg>Kを追加。係数がポイントだと気づいたので。<commit_after>#include <iostream>
#include <algorithm>
#include <cassert>
using namespace std;
// 大域変数
const int T = 9; // 全ターン数
const int P = 4; // プレイヤー数
const int N = 6; // プログラミングの言語数
const int maxpt = 6;
const int minpt = 3;
const int wdays = 5;
const int hdays = 2;
int A[N]; // 言語の注目数
int priority[N];
/*
priority[0] 取りに行く言語1
priority[1] 取りに行く言語2
priority[2] 落とさない言語1
priority[3] 落とさない言語2 できれば取りにいく
priority[4] 落とさない言語3
priority[5] 捨てる言語
*/
double K = 1.3;
// ターンでの変数
int turn; // 現在のターン
bool isweekday; // 平日か?
int B[N][P]; // B[n][p] = プレイヤーpの言語nへの信者数
int R[N]; // 自分の本当の投票数
int W[N]; // 前の休日までの、明らかになっていない休日の布教回数(自分を除く)
int days; // 最大数
int L[wdays]; // 出力
void first_init() {
// 初期化・入力
int x;
cin >> x;
cin >> x;
cin >> x;
for (int i=0; i<N; i++) {
cin >> A[i];
}
fill(W, W+N, 0);
// priorityの確定
bool used[N];
fill(used, used+N, false);
// priority[2]の確定
for (int i=maxpt; i>=minpt; i--) {
for (int j=0; j<N; j++) {
if (A[j] == i) {
priority[2] = j;
used[j] = true;
goto EXIT_OF_PRIORITY_2;
}
}
}
EXIT_OF_PRIORITY_2:
// priority[0][1]の確定
int count = 0;
for (int i=maxpt; i>=minpt; i--) {
for (int j=N-1; j>=0; j--) {
if (!used[j] && A[j] == i) {
priority[count++] = j;
used[j] = true;
if (count == 2) {
goto EXIT_OF_PRIORITY_01;
}
}
}
}
EXIT_OF_PRIORITY_01:
// priority[3][4][5]の確定
count = 3;
for (int i=maxpt; i>=minpt; i--) {
for (int j=N-1; j>=0; j--) {
if (!used[j] && A[j] == i) {
priority[count++] = j;
used[j] = true;
if (count == 5) {
goto EXIT_OF_PRIORITY_345;
}
}
}
}
EXIT_OF_PRIORITY_345:
return;
}
void turn_init() {
cin >> turn;
char D;
cin >> D;
isweekday = (D == 'W');
if (isweekday) {
days = wdays;
} else {
days = hdays;
}
for (int i=0; i<N; i++) {
for (int j=0; j<P; j++) {
cin >> B[i][j];
}
}
for (int i=0; i<N; i++) {
cin >> R[i];
}
if (turn == 6) {
fill(W, W+P, 0);
}
if (isweekday) {
for (int i=0; i<N; i++) {
int w;
cin >> w;
W[i] += w;
}
}
}
bool hantei(int lang, bool istop) {
// // cerr << "days = " << days << endl;
int m = B[lang][1];
for (int i=1; i<P; i++) {
if (istop) {
m = max(m, B[lang][i]);
} else {
m = min(m, B[lang][i]);
}
}
return (R[lang] >= m + K*W[lang]);
}
bool isgood(int lang_priority) {
int lang = priority[lang_priority];
if (lang_priority <= 1) {
return hantei(lang, true);
} else {
return hantei(lang, false);
}
}
void determine_L() {
if (turn == 1) {
for (int i=0; i<days; i++) {
L[i] = priority[4-i];
}
} else if (turn == 2) {
for (int i=0; i<days; i++) {
L[i] = priority[0];
}
} else {
int now_c = 0;
int now_p = 0;
// 戦略に基づき割り振る
while (now_p < 5 && now_c < days) {
if (!isgood(now_p)) {
int lang = priority[now_p];
L[now_c++] = lang;
R[lang] += ((isweekday) ? 1 : 2);
} else {
now_p++;
}
}
// 枠が余ったら
while (now_c < days) {
L[now_c++] = priority[3];
}
}
}
void turn_output() {
determine_L();
for (int i=0; i<days; i++) {
cout << L[i];
if (i != days-1) {
cout << " ";
}
if(!isweekday) {
W[L[i]]--;
}
}
cout << endl;
}
int main() {
cout << "READY" << endl;
// ゲーム設定の入力
first_init();
// ターン情報の入力
for (int t=1; t<=T; t++) {
turn_init();
turn_output();
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <nix/hdf5/RepresentationHDF5.hpp>
using namespace std;
namespace nix {
namespace hdf5 {
string linkTypeToString(LinkType link_type) {
static vector<string> type_names = {"tagged", "untagged", "indexed"};
return type_names[static_cast<int>(link_type)];
}
LinkType linkTypeFromString(const string &str) {
if (str == "tagged")
return LinkType::Tagged;
else if (str == "untagged")
return LinkType::Untagged;
else if (str == "indexed")
return LinkType::Indexed;
else
throw runtime_error("Unable to create a LinkType from the string: " + str);
}
RepresentationHDF5::RepresentationHDF5(const RepresentationHDF5 &representation)
: EntityHDF5(representation.file(), representation.group(), representation.id()),
block(representation.block)
{}
RepresentationHDF5::RepresentationHDF5(const File &file, const Block &block, const Group &group,
const string &id)
: EntityHDF5(file, group, id), block(block)
{}
RepresentationHDF5::RepresentationHDF5(const File &file, const Block &block, const Group &group,
const string &id, time_t time)
: EntityHDF5(file, group, id, time), block(block)
{}
void RepresentationHDF5::linkType(LinkType link_type) {
group().setAttr("link_type", linkTypeToString(link_type));
forceUpdatedAt();
}
void RepresentationHDF5::data(const std::string &data_array_id){
group().setAttr("data", data_array_id);
forceUpdatedAt();
}
DataArray RepresentationHDF5::data() const{
string dataId;
group().getAttr("data", dataId);
return block.getDataArray(dataId);
}
LinkType RepresentationHDF5::linkType() const {
string link_type;
group().getAttr("link_type", link_type);
return linkTypeFromString(link_type);
}
RepresentationHDF5::~RepresentationHDF5() {}
} // namespace hdf5
} // namespace nix
<commit_msg>Modified "data" and "linkType" getters in "Representation" to check whether fields exist.<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <nix/hdf5/RepresentationHDF5.hpp>
using namespace std;
namespace nix {
namespace hdf5 {
string linkTypeToString(LinkType link_type) {
static vector<string> type_names = {"tagged", "untagged", "indexed"};
return type_names[static_cast<int>(link_type)];
}
LinkType linkTypeFromString(const string &str) {
if (str == "tagged")
return LinkType::Tagged;
else if (str == "untagged")
return LinkType::Untagged;
else if (str == "indexed")
return LinkType::Indexed;
else
throw runtime_error("Unable to create a LinkType from the string: " + str);
}
RepresentationHDF5::RepresentationHDF5(const RepresentationHDF5 &representation)
: EntityHDF5(representation.file(), representation.group(), representation.id()),
block(representation.block)
{}
RepresentationHDF5::RepresentationHDF5(const File &file, const Block &block, const Group &group,
const string &id)
: EntityHDF5(file, group, id), block(block)
{}
RepresentationHDF5::RepresentationHDF5(const File &file, const Block &block, const Group &group,
const string &id, time_t time)
: EntityHDF5(file, group, id, time), block(block)
{}
void RepresentationHDF5::linkType(LinkType link_type) {
group().setAttr("link_type", linkTypeToString(link_type));
forceUpdatedAt();
}
void RepresentationHDF5::data(const std::string &data_array_id){
group().setAttr("data", data_array_id);
forceUpdatedAt();
}
DataArray RepresentationHDF5::data() const{
if(group().hasAttr("data")) {
string dataId;
group().getAttr("data", dataId);
if(block.hasDataArray(dataId)) {
return block.getDataArray(dataId);
} else {
throw std::runtime_error("Data array not found by id in Block");
}
} else {
throw std::runtime_error("data field not set in group");
}
}
LinkType RepresentationHDF5::linkType() const {
if(group().hasAttr("link_type")) {
string link_type;
group().getAttr("link_type", link_type);
return linkTypeFromString(link_type);
} else {
throw std::runtime_error("link_type field not set in group");
}
}
RepresentationHDF5::~RepresentationHDF5() {}
} // namespace hdf5
} // namespace nix
<|endoftext|> |
<commit_before>/*
* Copyright © 2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include <stdlib.h>
#include "glsl_symbol_table.h"
#include "glsl_parser_extras.h"
#include "glsl_types.h"
#include "ir.h"
static void
generate_unop(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type,
enum ir_expression_operation op)
{
ir_dereference *const retval = new ir_dereference(declarations[16]);
ir_dereference *const arg = new ir_dereference(declarations[0]);
ir_rvalue *result;
result = new ir_expression(op, type, arg, NULL);
ir_instruction *inst = new ir_assignment(retval, result, NULL);
instructions->push_tail(inst);
}
static void
generate_binop(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type,
enum ir_expression_operation op)
{
ir_dereference *const retval = new ir_dereference(declarations[16]);
ir_dereference *const arg1 = new ir_dereference(declarations[0]);
ir_dereference *const arg2 = new ir_dereference(declarations[1]);
ir_rvalue *result;
result = new ir_expression(op, type, arg1, arg2);
ir_instruction *inst = new ir_assignment(retval, result, NULL);
instructions->push_tail(inst);
}
static void
generate_exp(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type)
{
generate_unop(instructions, declarations, type, ir_unop_exp);
}
static void
generate_log(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type)
{
generate_unop(instructions, declarations, type, ir_unop_log);
}
static void
generate_exp2(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type)
{
generate_unop(instructions, declarations, type, ir_unop_exp2);
}
static void
generate_log2(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type)
{
generate_unop(instructions, declarations, type, ir_unop_log2);
}
static void
generate_rsq(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type)
{
generate_unop(instructions, declarations, type, ir_unop_rsq);
}
static void
generate_sqrt(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type)
{
generate_unop(instructions, declarations, type, ir_unop_sqrt);
}
static void
generate_abs(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type)
{
generate_unop(instructions, declarations, type, ir_unop_abs);
}
static void
generate_ceil(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type)
{
generate_unop(instructions, declarations, type, ir_unop_ceil);
}
static void
generate_floor(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type)
{
generate_unop(instructions, declarations, type, ir_unop_floor);
}
static void
generate_mod(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type)
{
generate_binop(instructions, declarations, type, ir_binop_mod);
}
static void
generate_min(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type)
{
generate_binop(instructions, declarations, type, ir_binop_min);
}
static void
generate_max(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type)
{
generate_binop(instructions, declarations, type, ir_binop_max);
}
static void
generate_pow(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type)
{
generate_binop(instructions, declarations, type, ir_binop_pow);
}
void
generate_function_instance(ir_function *f,
const char *name,
exec_list *instructions,
int n_args,
void (*generate)(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type),
const glsl_type *ret_type,
const glsl_type *type)
{
ir_variable *declarations[17];
ir_function_signature *const sig = new ir_function_signature(type);
f->signatures.push_tail(sig);
ir_label *const label = new ir_label(name);
instructions->push_tail(label);
sig->definition = label;
static const char *arg_names[] = {
"arg0",
"arg1"
};
int i;
for (i = 0; i < n_args; i++) {
ir_variable *var = new ir_variable(type, arg_names[i]);
var->mode = ir_var_in;
sig->parameters.push_tail(var);
var = new ir_variable(type, arg_names[i]);
declarations[i] = var;
}
ir_variable *retval = new ir_variable(ret_type, "__retval");
instructions->push_tail(retval);
declarations[16] = retval;
generate(instructions, declarations, type);
}
void
make_gentype_function(glsl_symbol_table *symtab, exec_list *instructions,
const char *name,
int n_args,
void (*generate)(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type))
{
ir_function *const f = new ir_function(name);
const glsl_type *float_type = glsl_type::float_type;
const glsl_type *vec2_type = glsl_type::get_instance(GLSL_TYPE_FLOAT, 2, 1);
const glsl_type *vec3_type = glsl_type::get_instance(GLSL_TYPE_FLOAT, 3, 1);
const glsl_type *vec4_type = glsl_type::get_instance(GLSL_TYPE_FLOAT, 4, 1);
bool added = symtab->add_function(name, f);
assert(added);
generate_function_instance(f, name, instructions, n_args, generate,
float_type, float_type);
generate_function_instance(f, name, instructions, n_args, generate,
vec2_type, vec2_type);
generate_function_instance(f, name, instructions, n_args, generate,
vec3_type, vec3_type);
generate_function_instance(f, name, instructions, n_args, generate,
vec4_type, vec4_type);
}
static void
generate_length(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type)
{
ir_dereference *const retval = new ir_dereference(declarations[16]);
ir_dereference *const arg = new ir_dereference(declarations[0]);
ir_rvalue *result, *temp;
(void)type;
/* FINISHME: implement the abs(arg) variant for length(float f) */
temp = new ir_expression(ir_binop_dot, glsl_type::float_type, arg, arg);
result = new ir_expression(ir_unop_sqrt, glsl_type::float_type, temp, NULL);
ir_instruction *inst = new ir_assignment(retval, result, NULL);
instructions->push_tail(inst);
}
void
generate_length_functions(glsl_symbol_table *symtab, exec_list *instructions)
{
const char *name = "length";
ir_function *const f = new ir_function(name);
const glsl_type *float_type = glsl_type::float_type;
const glsl_type *vec2_type = glsl_type::get_instance(GLSL_TYPE_FLOAT, 2, 1);
const glsl_type *vec3_type = glsl_type::get_instance(GLSL_TYPE_FLOAT, 3, 1);
const glsl_type *vec4_type = glsl_type::get_instance(GLSL_TYPE_FLOAT, 4, 1);
bool added = symtab->add_function(name, f);
assert(added);
generate_function_instance(f, name, instructions, 1, generate_length,
float_type, float_type);
generate_function_instance(f, name, instructions, 1, generate_length,
float_type, vec2_type);
generate_function_instance(f, name, instructions, 1, generate_length,
float_type, vec3_type);
generate_function_instance(f, name, instructions, 1, generate_length,
float_type, vec4_type);
}
static void
generate_dot(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type)
{
ir_dereference *const retval = new ir_dereference(declarations[16]);
ir_dereference *const arg = new ir_dereference(declarations[0]);
ir_rvalue *result;
(void)type;
result = new ir_expression(ir_binop_dot, glsl_type::float_type, arg, arg);
ir_instruction *inst = new ir_assignment(retval, result, NULL);
instructions->push_tail(inst);
}
void
generate_dot_functions(glsl_symbol_table *symtab, exec_list *instructions)
{
const char *name = "dot";
ir_function *const f = new ir_function(name);
const glsl_type *float_type = glsl_type::float_type;
const glsl_type *vec2_type = glsl_type::get_instance(GLSL_TYPE_FLOAT, 2, 1);
const glsl_type *vec3_type = glsl_type::get_instance(GLSL_TYPE_FLOAT, 3, 1);
const glsl_type *vec4_type = glsl_type::get_instance(GLSL_TYPE_FLOAT, 4, 1);
bool added = symtab->add_function(name, f);
assert(added);
generate_function_instance(f, name, instructions, 1, generate_dot,
float_type, float_type);
generate_function_instance(f, name, instructions, 1, generate_dot,
float_type, vec2_type);
generate_function_instance(f, name, instructions, 1, generate_dot,
float_type, vec3_type);
generate_function_instance(f, name, instructions, 1, generate_dot,
float_type, vec4_type);
}
void
generate_110_functions(glsl_symbol_table *symtab, exec_list *instructions)
{
/* FINISHME: radians() */
/* FINISHME: degrees() */
/* FINISHME: sin() */
/* FINISHME: cos() */
/* FINISHME: tan() */
/* FINISHME: asin() */
/* FINISHME: acos() */
/* FINISHME: atan(y,x) */
/* FINISHME: atan(y/x) */
make_gentype_function(symtab, instructions, "pow", 2, generate_pow);
make_gentype_function(symtab, instructions, "exp", 1, generate_exp);
make_gentype_function(symtab, instructions, "log", 1, generate_log);
make_gentype_function(symtab, instructions, "exp2", 1, generate_exp2);
make_gentype_function(symtab, instructions, "log2", 1, generate_log2);
make_gentype_function(symtab, instructions, "sqrt", 1, generate_sqrt);
make_gentype_function(symtab, instructions, "inversesqrt", 1, generate_rsq);
make_gentype_function(symtab, instructions, "abs", 1, generate_abs);
/* FINISHME: sign() */
make_gentype_function(symtab, instructions, "floor", 1, generate_floor);
make_gentype_function(symtab, instructions, "ceil", 1, generate_ceil);
/* FINISHME: fract() */
/* FINISHME: mod(x, float y) */
make_gentype_function(symtab, instructions, "mod", 2, generate_mod);
make_gentype_function(symtab, instructions, "min", 2, generate_min);
/* FINISHME: min(x, float y) */
make_gentype_function(symtab, instructions, "max", 2, generate_max);
/* FINISHME: max(x, float y) */
/* FINISHME: clamp() */
/* FINISHME: clamp() */
/* FINISHME: mix() */
/* FINISHME: mix() */
/* FINISHME: step() */
/* FINISHME: step() */
/* FINISHME: smoothstep() */
/* FINISHME: smoothstep() */
/* FINISHME: floor() */
/* FINISHME: step() */
generate_length_functions(symtab, instructions);
/* FINISHME: distance() */
generate_dot_functions(symtab, instructions);
/* FINISHME: cross() */
/* FINISHME: normalize() */
/* FINISHME: ftransform() */
/* FINISHME: faceforward() */
/* FINISHME: reflect() */
/* FINISHME: refract() */
/* FINISHME: matrixCompMult() */
/* FINISHME: lessThan() */
/* FINISHME: lessThanEqual() */
/* FINISHME: greaterThan() */
/* FINISHME: greaterThanEqual() */
/* FINISHME: equal() */
/* FINISHME: notEqual() */
/* FINISHME: any() */
/* FINISHME: all() */
/* FINISHME: not() */
/* FINISHME: texture*() */
/* FINISHME: shadow*() */
/* FINISHME: dFd[xy]() */
/* FINISHME: fwidth() */
}
void
_mesa_glsl_initialize_functions(exec_list *instructions,
struct _mesa_glsl_parse_state *state)
{
generate_110_functions(state->symbols, instructions);
}
<commit_msg>Add the instruction for the parameter variable declarations of builtin funcs.<commit_after>/*
* Copyright © 2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include <stdlib.h>
#include "glsl_symbol_table.h"
#include "glsl_parser_extras.h"
#include "glsl_types.h"
#include "ir.h"
static void
generate_unop(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type,
enum ir_expression_operation op)
{
ir_dereference *const retval = new ir_dereference(declarations[16]);
ir_dereference *const arg = new ir_dereference(declarations[0]);
ir_rvalue *result;
result = new ir_expression(op, type, arg, NULL);
ir_instruction *inst = new ir_assignment(retval, result, NULL);
instructions->push_tail(inst);
}
static void
generate_binop(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type,
enum ir_expression_operation op)
{
ir_dereference *const retval = new ir_dereference(declarations[16]);
ir_dereference *const arg1 = new ir_dereference(declarations[0]);
ir_dereference *const arg2 = new ir_dereference(declarations[1]);
ir_rvalue *result;
result = new ir_expression(op, type, arg1, arg2);
ir_instruction *inst = new ir_assignment(retval, result, NULL);
instructions->push_tail(inst);
}
static void
generate_exp(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type)
{
generate_unop(instructions, declarations, type, ir_unop_exp);
}
static void
generate_log(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type)
{
generate_unop(instructions, declarations, type, ir_unop_log);
}
static void
generate_exp2(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type)
{
generate_unop(instructions, declarations, type, ir_unop_exp2);
}
static void
generate_log2(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type)
{
generate_unop(instructions, declarations, type, ir_unop_log2);
}
static void
generate_rsq(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type)
{
generate_unop(instructions, declarations, type, ir_unop_rsq);
}
static void
generate_sqrt(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type)
{
generate_unop(instructions, declarations, type, ir_unop_sqrt);
}
static void
generate_abs(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type)
{
generate_unop(instructions, declarations, type, ir_unop_abs);
}
static void
generate_ceil(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type)
{
generate_unop(instructions, declarations, type, ir_unop_ceil);
}
static void
generate_floor(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type)
{
generate_unop(instructions, declarations, type, ir_unop_floor);
}
static void
generate_mod(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type)
{
generate_binop(instructions, declarations, type, ir_binop_mod);
}
static void
generate_min(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type)
{
generate_binop(instructions, declarations, type, ir_binop_min);
}
static void
generate_max(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type)
{
generate_binop(instructions, declarations, type, ir_binop_max);
}
static void
generate_pow(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type)
{
generate_binop(instructions, declarations, type, ir_binop_pow);
}
void
generate_function_instance(ir_function *f,
const char *name,
exec_list *instructions,
int n_args,
void (*generate)(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type),
const glsl_type *ret_type,
const glsl_type *type)
{
ir_variable *declarations[17];
ir_function_signature *const sig = new ir_function_signature(type);
f->signatures.push_tail(sig);
ir_label *const label = new ir_label(name);
instructions->push_tail(label);
sig->definition = label;
static const char *arg_names[] = {
"arg0",
"arg1"
};
int i;
for (i = 0; i < n_args; i++) {
ir_variable *var = new ir_variable(type, arg_names[i]);
var = new ir_variable(type, arg_names[i]);
var->mode = ir_var_in;
sig->parameters.push_tail(var);
var = new ir_variable(type, arg_names[i]);
var->mode = ir_var_in;
instructions->push_tail(var);
declarations[i] = var;
}
ir_variable *retval = new ir_variable(ret_type, "__retval");
instructions->push_tail(retval);
declarations[16] = retval;
generate(instructions, declarations, type);
}
void
make_gentype_function(glsl_symbol_table *symtab, exec_list *instructions,
const char *name,
int n_args,
void (*generate)(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type))
{
ir_function *const f = new ir_function(name);
const glsl_type *float_type = glsl_type::float_type;
const glsl_type *vec2_type = glsl_type::get_instance(GLSL_TYPE_FLOAT, 2, 1);
const glsl_type *vec3_type = glsl_type::get_instance(GLSL_TYPE_FLOAT, 3, 1);
const glsl_type *vec4_type = glsl_type::get_instance(GLSL_TYPE_FLOAT, 4, 1);
bool added = symtab->add_function(name, f);
assert(added);
generate_function_instance(f, name, instructions, n_args, generate,
float_type, float_type);
generate_function_instance(f, name, instructions, n_args, generate,
vec2_type, vec2_type);
generate_function_instance(f, name, instructions, n_args, generate,
vec3_type, vec3_type);
generate_function_instance(f, name, instructions, n_args, generate,
vec4_type, vec4_type);
}
static void
generate_length(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type)
{
ir_dereference *const retval = new ir_dereference(declarations[16]);
ir_dereference *const arg = new ir_dereference(declarations[0]);
ir_rvalue *result, *temp;
(void)type;
/* FINISHME: implement the abs(arg) variant for length(float f) */
temp = new ir_expression(ir_binop_dot, glsl_type::float_type, arg, arg);
result = new ir_expression(ir_unop_sqrt, glsl_type::float_type, temp, NULL);
ir_instruction *inst = new ir_assignment(retval, result, NULL);
instructions->push_tail(inst);
}
void
generate_length_functions(glsl_symbol_table *symtab, exec_list *instructions)
{
const char *name = "length";
ir_function *const f = new ir_function(name);
const glsl_type *float_type = glsl_type::float_type;
const glsl_type *vec2_type = glsl_type::get_instance(GLSL_TYPE_FLOAT, 2, 1);
const glsl_type *vec3_type = glsl_type::get_instance(GLSL_TYPE_FLOAT, 3, 1);
const glsl_type *vec4_type = glsl_type::get_instance(GLSL_TYPE_FLOAT, 4, 1);
bool added = symtab->add_function(name, f);
assert(added);
generate_function_instance(f, name, instructions, 1, generate_length,
float_type, float_type);
generate_function_instance(f, name, instructions, 1, generate_length,
float_type, vec2_type);
generate_function_instance(f, name, instructions, 1, generate_length,
float_type, vec3_type);
generate_function_instance(f, name, instructions, 1, generate_length,
float_type, vec4_type);
}
static void
generate_dot(exec_list *instructions,
ir_variable **declarations,
const glsl_type *type)
{
ir_dereference *const retval = new ir_dereference(declarations[16]);
ir_dereference *const arg = new ir_dereference(declarations[0]);
ir_rvalue *result;
(void)type;
result = new ir_expression(ir_binop_dot, glsl_type::float_type, arg, arg);
ir_instruction *inst = new ir_assignment(retval, result, NULL);
instructions->push_tail(inst);
}
void
generate_dot_functions(glsl_symbol_table *symtab, exec_list *instructions)
{
const char *name = "dot";
ir_function *const f = new ir_function(name);
const glsl_type *float_type = glsl_type::float_type;
const glsl_type *vec2_type = glsl_type::get_instance(GLSL_TYPE_FLOAT, 2, 1);
const glsl_type *vec3_type = glsl_type::get_instance(GLSL_TYPE_FLOAT, 3, 1);
const glsl_type *vec4_type = glsl_type::get_instance(GLSL_TYPE_FLOAT, 4, 1);
bool added = symtab->add_function(name, f);
assert(added);
generate_function_instance(f, name, instructions, 1, generate_dot,
float_type, float_type);
generate_function_instance(f, name, instructions, 1, generate_dot,
float_type, vec2_type);
generate_function_instance(f, name, instructions, 1, generate_dot,
float_type, vec3_type);
generate_function_instance(f, name, instructions, 1, generate_dot,
float_type, vec4_type);
}
void
generate_110_functions(glsl_symbol_table *symtab, exec_list *instructions)
{
/* FINISHME: radians() */
/* FINISHME: degrees() */
/* FINISHME: sin() */
/* FINISHME: cos() */
/* FINISHME: tan() */
/* FINISHME: asin() */
/* FINISHME: acos() */
/* FINISHME: atan(y,x) */
/* FINISHME: atan(y/x) */
make_gentype_function(symtab, instructions, "pow", 2, generate_pow);
make_gentype_function(symtab, instructions, "exp", 1, generate_exp);
make_gentype_function(symtab, instructions, "log", 1, generate_log);
make_gentype_function(symtab, instructions, "exp2", 1, generate_exp2);
make_gentype_function(symtab, instructions, "log2", 1, generate_log2);
make_gentype_function(symtab, instructions, "sqrt", 1, generate_sqrt);
make_gentype_function(symtab, instructions, "inversesqrt", 1, generate_rsq);
make_gentype_function(symtab, instructions, "abs", 1, generate_abs);
/* FINISHME: sign() */
make_gentype_function(symtab, instructions, "floor", 1, generate_floor);
make_gentype_function(symtab, instructions, "ceil", 1, generate_ceil);
/* FINISHME: fract() */
/* FINISHME: mod(x, float y) */
make_gentype_function(symtab, instructions, "mod", 2, generate_mod);
make_gentype_function(symtab, instructions, "min", 2, generate_min);
/* FINISHME: min(x, float y) */
make_gentype_function(symtab, instructions, "max", 2, generate_max);
/* FINISHME: max(x, float y) */
/* FINISHME: clamp() */
/* FINISHME: clamp() */
/* FINISHME: mix() */
/* FINISHME: mix() */
/* FINISHME: step() */
/* FINISHME: step() */
/* FINISHME: smoothstep() */
/* FINISHME: smoothstep() */
/* FINISHME: floor() */
/* FINISHME: step() */
generate_length_functions(symtab, instructions);
/* FINISHME: distance() */
generate_dot_functions(symtab, instructions);
/* FINISHME: cross() */
/* FINISHME: normalize() */
/* FINISHME: ftransform() */
/* FINISHME: faceforward() */
/* FINISHME: reflect() */
/* FINISHME: refract() */
/* FINISHME: matrixCompMult() */
/* FINISHME: lessThan() */
/* FINISHME: lessThanEqual() */
/* FINISHME: greaterThan() */
/* FINISHME: greaterThanEqual() */
/* FINISHME: equal() */
/* FINISHME: notEqual() */
/* FINISHME: any() */
/* FINISHME: all() */
/* FINISHME: not() */
/* FINISHME: texture*() */
/* FINISHME: shadow*() */
/* FINISHME: dFd[xy]() */
/* FINISHME: fwidth() */
}
void
_mesa_glsl_initialize_functions(exec_list *instructions,
struct _mesa_glsl_parse_state *state)
{
generate_110_functions(state->symbols, instructions);
}
<|endoftext|> |
<commit_before><commit_msg>When removing a body from the scene, remove it also from the list of objects in contact<commit_after><|endoftext|> |
<commit_before>// Copyright 2014 MongoDB Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <cstdint>
#include "bson/builder.hpp"
#include "driver/libmongoc.hpp"
#include "driver/base/private/client.hpp"
#include "driver/base/private/collection.hpp"
#include "driver/base/private/database.hpp"
#include "driver/base/private/pipeline.hpp"
#include "driver/model/private/bulk_write.hpp"
#include "driver/base/collection.hpp"
#include "driver/base/client.hpp"
#include "driver/model/aggregate.hpp"
#include "driver/model/find.hpp"
#include "driver/model/find_one_and_replace.hpp"
#include "driver/model/find_one_and_delete.hpp"
#include "driver/model/find_one_and_update.hpp"
#include "driver/model/insert_one.hpp"
#include "driver/model/update_one.hpp"
#include "driver/result/bulk_write.hpp"
#include "driver/result/insert_many.hpp"
#include "driver/result/insert_one.hpp"
#include "driver/result/delete.hpp"
#include "driver/result/replace_one.hpp"
#include "driver/result/update.hpp"
#include "driver/result/write.hpp"
#include "driver/result/bulk_write.hpp"
#include "driver/request/insert.hpp"
#include "driver/util/libbson.hpp"
#include "driver/model/bulk_write.hpp"
#include "driver/model/write.hpp"
#include "driver/base/private/write_concern.hpp"
#include "driver/base/private/read_preference.hpp"
namespace mongo {
namespace driver {
using namespace bson::libbson;
collection::collection(collection&&) = default;
collection& collection::operator=(collection&&) = default;
collection::~collection() = default;
collection::collection(const database& database, const std::string& collection_name)
: _impl(new impl{
mongoc_database_get_collection(database._impl->database_t, collection_name.c_str()),
&database, database._impl->client, collection_name.c_str()}) {}
result::bulk_write collection::bulk_write(const model::bulk_write& model) {
using namespace model;
mongoc_bulk_operation_t* b = model._impl->operation_t;
mongoc_bulk_operation_set_database(b, _impl->database->_impl->name.c_str());
mongoc_bulk_operation_set_collection(b, _impl->name.c_str());
mongoc_bulk_operation_set_client(b, _impl->client->_impl->client_t);
if (model.write_concern()) {
priv::write_concern wc(*model.write_concern());
mongoc_bulk_operation_set_write_concern(b, wc.get_write_concern());
} else {
mongoc_bulk_operation_set_write_concern(
b, mongoc_collection_get_write_concern(_impl->collection_t));
}
result::bulk_write result;
scoped_bson_t reply;
reply.flag_init();
bson_error_t error;
if (!mongoc_bulk_operation_execute(b, reply.bson(), &error)) {
throw std::runtime_error(error.message);
}
bson::document::view reply_view = reply.view();
result.is_acknowledged = true;
result.inserted_count = reply_view["nInserted"].get_int32();
result.matched_count = reply_view["nMatched"].get_int32();
result.modified_count = reply_view["nModified"].get_int32();
result.deleted_count = reply_view["nRemoved"].get_int32();
result.upserted_count = reply_view["nUpserted"].get_int32();
return result;
}
cursor collection::find(const model::find& model) const {
using namespace bson;
builder::document filter_builder;
scoped_bson_t filter;
scoped_bson_t projection(model.projection());
if (model.modifiers()) {
filter_builder << "$query" << types::b_document{model.criteria()}
<< builder::helpers::concat{model.modifiers().value_or(document::view{})};
filter.init_from_static(filter_builder.view());
} else {
filter.init_from_static(model.criteria());
}
optional<priv::read_preference> read_prefs;
const mongoc_read_prefs_t* rp_ptr;
if (model.read_preference()) {
read_prefs = priv::read_preference{*model.read_preference()};
rp_ptr = read_prefs->get_read_preference();
} else {
rp_ptr = mongoc_collection_get_read_prefs(_impl->collection_t);
}
return cursor(mongoc_collection_find(
_impl->collection_t, (mongoc_query_flags_t)model.cursor_flags().value_or(0),
model.skip().value_or(0), model.limit().value_or(0), model.batch_size().value_or(0),
filter.bson(), projection.bson(), rp_ptr));
}
optional<bson::document::value> collection::find_one(const model::find& model) const {
model::find copy(model);
copy.limit(1);
return bson::document::value{*find(copy).begin()};
}
cursor collection::aggregate(const model::aggregate& model) {
using namespace bson::builder::helpers;
scoped_bson_t pipeline(model.stages()._impl->view());
bson::builder::document b;
if (model.allow_disk_use()) {
/* TODO */
}
if (model.use_cursor()) {
auto inner = b << "cursor" << open_doc;
if (model.batch_size()) {
inner << "batchSize" << *model.batch_size();
}
inner << close_doc;
}
if (model.max_time_ms()) {
/* TODO */
}
scoped_bson_t options(b.view());
optional<priv::read_preference> read_prefs;
const mongoc_read_prefs_t* rp_ptr;
if (model.read_preference()) {
read_prefs = priv::read_preference{*model.read_preference()};
rp_ptr = read_prefs->get_read_preference();
} else {
rp_ptr = mongoc_collection_get_read_prefs(_impl->collection_t);
}
return cursor(mongoc_collection_aggregate(_impl->collection_t,
static_cast<mongoc_query_flags_t>(0), pipeline.bson(),
options.bson(), rp_ptr));
}
result::insert_one collection::insert_one(const model::insert_one& model) {
result::bulk_write res(bulk_write(model::bulk_write(false).append(model)));
result::insert_one result;
result.is_acknowledged = true;
return result;
}
result::insert_many collection::insert_many(const model::insert_many& model) {
result::bulk_write res(bulk_write(model::bulk_write(false).append(model)));
result::insert_many result;
result.is_acknowledged = true;
return result;
}
result::replace_one collection::replace_one(const model::replace_one& /* model */) {
return result::replace_one();
}
result::update collection::update_many(const model::update_many& /* model */) {
return result::update();
}
result::delete_result collection::delete_many(const model::delete_many& model) {
result::bulk_write res(bulk_write(model::bulk_write(false).append(model)));
result::delete_result result;
result.is_acknowledged = true;
return result;
}
result::update collection::update_one(const model::update_one& model) {
result::bulk_write res(bulk_write(model::bulk_write(false).append(model)));
result::update result;
result.is_acknowledged = true;
return result;
}
result::delete_result collection::delete_one(const model::delete_one& model) {
result::bulk_write res(bulk_write(model::bulk_write(false).append(model)));
result::delete_result result;
result.is_acknowledged = true;
return result;
}
optional<bson::document::value> collection::find_one_and_replace(
const model::find_one_and_replace& model) {
scoped_bson_t criteria{model.criteria()};
scoped_bson_t sort{model.sort()};
scoped_bson_t replacement{model.replacement()};
scoped_bson_t projection{model.projection()};
scoped_bson_t reply;
reply.flag_init();
bson_error_t error;
bool r = mongoc_collection_find_and_modify(
_impl->collection_t, criteria.bson(), sort.bson(), replacement.bson(), projection.bson(),
false, model.upsert().value_or(false), model.return_replacement().value_or(false),
reply.bson(), &error);
if (!r) {
throw std::runtime_error("shits fucked");
}
bson::document::view result = reply.view();
if (result["value"].type() == bson::type::k_null) {
return optional<bson::document::value>{};
} else {
using namespace bson::builder::helpers;
bson::builder::document b;
b << concat{result["value"].get_document()};
return b.extract();
}
}
optional<bson::document::value> collection::find_one_and_update(
const model::find_one_and_update& model) {
scoped_bson_t criteria{model.criteria()};
scoped_bson_t sort{model.sort()};
scoped_bson_t update{model.update()};
scoped_bson_t projection{model.projection()};
scoped_bson_t reply;
reply.flag_init();
bson_error_t error;
bool r = mongoc_collection_find_and_modify(
_impl->collection_t, criteria.bson(), sort.bson(), update.bson(), projection.bson(), false,
model.upsert().value_or(false), model.return_replacement().value_or(false), reply.bson(),
&error);
if (!r) {
throw std::runtime_error("shits fucked");
}
bson::document::view result = reply.view();
if (result["value"].type() == bson::type::k_null) {
return optional<bson::document::value>{};
} else {
using namespace bson::builder::helpers;
bson::builder::document b;
b << concat{result["value"].get_document()};
return b.extract();
}
}
optional<bson::document::value> collection::find_one_and_delete(
const model::find_one_and_delete& model) {
scoped_bson_t criteria{model.criteria()};
scoped_bson_t sort{model.sort()};
scoped_bson_t projection{model.projection()};
scoped_bson_t reply;
reply.flag_init();
bson_error_t error;
bool r = mongoc_collection_find_and_modify(_impl->collection_t, criteria.bson(), sort.bson(),
nullptr, projection.bson(), true, false, false,
reply.bson(), &error);
if (!r) {
throw std::runtime_error("shits fucked");
}
bson::document::view result = reply.view();
if (result["value"].type() == bson::type::k_null) {
return optional<bson::document::value>{};
} else {
using namespace bson::builder::helpers;
bson::builder::document b;
b << concat{result["value"].get_document()};
return b.extract();
}
}
bson::document::value collection::explain(const model::explain& /*model*/) const {
return bson::document::value((const std::uint8_t*)nullptr, 0);
}
std::int64_t collection::count(const model::count& model) const {
scoped_bson_t criteria{model.criteria()};
bson_error_t error;
optional<priv::read_preference> read_prefs;
const mongoc_read_prefs_t* rp_ptr;
if (model.read_preference()) {
read_prefs = priv::read_preference{*model.read_preference()};
rp_ptr = read_prefs->get_read_preference();
} else {
rp_ptr = mongoc_collection_get_read_prefs(_impl->collection_t);
}
auto result = mongoc_collection_count(_impl->collection_t, static_cast<mongoc_query_flags_t>(0),
criteria.bson(), model.skip().value_or(0),
model.limit().value_or(0), rp_ptr, &error);
/* TODO throw an exception if error
if (result < 0)
*/
return result;
}
void collection::drop() {
bson_error_t error;
if (mongoc_collection_drop(_impl->collection_t, &error)) {
/* TODO handle errors */
}
}
void collection::read_preference(class read_preference rp) {
_impl->read_preference(std::move(rp));
}
const class read_preference& collection::read_preference() const {
return _impl->read_preference();
}
void collection::write_concern(class write_concern wc) { _impl->write_concern(std::move(wc)); }
const class write_concern& collection::write_concern() const { return _impl->write_concern(); }
} // namespace driver
} // namespace mongo
<commit_msg>use provided write concern for writes<commit_after>// Copyright 2014 MongoDB Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <cstdint>
#include "bson/builder.hpp"
#include "driver/libmongoc.hpp"
#include "driver/base/private/client.hpp"
#include "driver/base/private/collection.hpp"
#include "driver/base/private/database.hpp"
#include "driver/base/private/pipeline.hpp"
#include "driver/model/private/bulk_write.hpp"
#include "driver/base/collection.hpp"
#include "driver/base/client.hpp"
#include "driver/model/aggregate.hpp"
#include "driver/model/find.hpp"
#include "driver/model/find_one_and_replace.hpp"
#include "driver/model/find_one_and_delete.hpp"
#include "driver/model/find_one_and_update.hpp"
#include "driver/model/insert_one.hpp"
#include "driver/model/update_one.hpp"
#include "driver/result/bulk_write.hpp"
#include "driver/result/insert_many.hpp"
#include "driver/result/insert_one.hpp"
#include "driver/result/delete.hpp"
#include "driver/result/replace_one.hpp"
#include "driver/result/update.hpp"
#include "driver/result/write.hpp"
#include "driver/result/bulk_write.hpp"
#include "driver/request/insert.hpp"
#include "driver/util/libbson.hpp"
#include "driver/model/bulk_write.hpp"
#include "driver/model/write.hpp"
#include "driver/base/private/write_concern.hpp"
#include "driver/base/private/read_preference.hpp"
namespace mongo {
namespace driver {
using namespace bson::libbson;
collection::collection(collection&&) = default;
collection& collection::operator=(collection&&) = default;
collection::~collection() = default;
collection::collection(const database& database, const std::string& collection_name)
: _impl(new impl{
mongoc_database_get_collection(database._impl->database_t, collection_name.c_str()),
&database, database._impl->client, collection_name.c_str()}) {}
result::bulk_write collection::bulk_write(const model::bulk_write& model) {
using namespace model;
mongoc_bulk_operation_t* b = model._impl->operation_t;
mongoc_bulk_operation_set_database(b, _impl->database->_impl->name.c_str());
mongoc_bulk_operation_set_collection(b, _impl->name.c_str());
mongoc_bulk_operation_set_client(b, _impl->client->_impl->client_t);
if (model.write_concern()) {
priv::write_concern wc(*model.write_concern());
mongoc_bulk_operation_set_write_concern(b, wc.get_write_concern());
} else {
mongoc_bulk_operation_set_write_concern(
b, mongoc_collection_get_write_concern(_impl->collection_t));
}
result::bulk_write result;
scoped_bson_t reply;
reply.flag_init();
bson_error_t error;
if (!mongoc_bulk_operation_execute(b, reply.bson(), &error)) {
throw std::runtime_error(error.message);
}
bson::document::view reply_view = reply.view();
result.is_acknowledged = true;
result.inserted_count = reply_view["nInserted"].get_int32();
result.matched_count = reply_view["nMatched"].get_int32();
result.modified_count = reply_view["nModified"].get_int32();
result.deleted_count = reply_view["nRemoved"].get_int32();
result.upserted_count = reply_view["nUpserted"].get_int32();
return result;
}
cursor collection::find(const model::find& model) const {
using namespace bson;
builder::document filter_builder;
scoped_bson_t filter;
scoped_bson_t projection(model.projection());
if (model.modifiers()) {
filter_builder << "$query" << types::b_document{model.criteria()}
<< builder::helpers::concat{model.modifiers().value_or(document::view{})};
filter.init_from_static(filter_builder.view());
} else {
filter.init_from_static(model.criteria());
}
optional<priv::read_preference> read_prefs;
const mongoc_read_prefs_t* rp_ptr;
if (model.read_preference()) {
read_prefs = priv::read_preference{*model.read_preference()};
rp_ptr = read_prefs->get_read_preference();
} else {
rp_ptr = mongoc_collection_get_read_prefs(_impl->collection_t);
}
return cursor(mongoc_collection_find(
_impl->collection_t, (mongoc_query_flags_t)model.cursor_flags().value_or(0),
model.skip().value_or(0), model.limit().value_or(0), model.batch_size().value_or(0),
filter.bson(), projection.bson(), rp_ptr));
}
optional<bson::document::value> collection::find_one(const model::find& model) const {
model::find copy(model);
copy.limit(1);
return bson::document::value{*find(copy).begin()};
}
cursor collection::aggregate(const model::aggregate& model) {
using namespace bson::builder::helpers;
scoped_bson_t pipeline(model.stages()._impl->view());
bson::builder::document b;
if (model.allow_disk_use()) {
/* TODO */
}
if (model.use_cursor()) {
auto inner = b << "cursor" << open_doc;
if (model.batch_size()) {
inner << "batchSize" << *model.batch_size();
}
inner << close_doc;
}
if (model.max_time_ms()) {
/* TODO */
}
scoped_bson_t options(b.view());
optional<priv::read_preference> read_prefs;
const mongoc_read_prefs_t* rp_ptr;
if (model.read_preference()) {
read_prefs = priv::read_preference{*model.read_preference()};
rp_ptr = read_prefs->get_read_preference();
} else {
rp_ptr = mongoc_collection_get_read_prefs(_impl->collection_t);
}
return cursor(mongoc_collection_aggregate(_impl->collection_t,
static_cast<mongoc_query_flags_t>(0), pipeline.bson(),
options.bson(), rp_ptr));
}
result::insert_one collection::insert_one(const model::insert_one& model) {
model::bulk_write bulk_op(false);
bulk_op.append(model);
if (model.write_concern())
bulk_op.write_concern(*model.write_concern());
result::bulk_write res(bulk_write(bulk_op));
result::insert_one result;
result.is_acknowledged = true;
return result;
}
result::insert_many collection::insert_many(const model::insert_many& model) {
model::bulk_write bulk_op(false);
bulk_op.append(model);
if (model.write_concern())
bulk_op.write_concern(*model.write_concern());
result::bulk_write res(bulk_write(bulk_op));
result::insert_many result;
result.is_acknowledged = true;
return result;
}
result::replace_one collection::replace_one(const model::replace_one& /* model */) {
return result::replace_one();
}
result::update collection::update_many(const model::update_many& /* model */) {
return result::update();
}
result::delete_result collection::delete_many(const model::delete_many& model) {
model::bulk_write bulk_op(false);
bulk_op.append(model);
if (model.write_concern())
bulk_op.write_concern(*model.write_concern());
result::bulk_write res(bulk_write(bulk_op));
result::delete_result result;
result.is_acknowledged = true;
return result;
}
result::update collection::update_one(const model::update_one& model) {
model::bulk_write bulk_op(false);
bulk_op.append(model);
if (model.write_concern())
bulk_op.write_concern(*model.write_concern());
result::bulk_write res(bulk_write(bulk_op));
result::update result;
result.is_acknowledged = true;
return result;
}
result::delete_result collection::delete_one(const model::delete_one& model) {
model::bulk_write bulk_op(false);
bulk_op.append(model);
if (model.write_concern())
bulk_op.write_concern(*model.write_concern());
result::bulk_write res(bulk_write(bulk_op));
result::delete_result result;
result.is_acknowledged = true;
return result;
}
optional<bson::document::value> collection::find_one_and_replace(
const model::find_one_and_replace& model) {
scoped_bson_t criteria{model.criteria()};
scoped_bson_t sort{model.sort()};
scoped_bson_t replacement{model.replacement()};
scoped_bson_t projection{model.projection()};
scoped_bson_t reply;
reply.flag_init();
bson_error_t error;
bool r = mongoc_collection_find_and_modify(
_impl->collection_t, criteria.bson(), sort.bson(), replacement.bson(), projection.bson(),
false, model.upsert().value_or(false), model.return_replacement().value_or(false),
reply.bson(), &error);
if (!r) {
throw std::runtime_error("shits fucked");
}
bson::document::view result = reply.view();
if (result["value"].type() == bson::type::k_null) {
return optional<bson::document::value>{};
} else {
using namespace bson::builder::helpers;
bson::builder::document b;
b << concat{result["value"].get_document()};
return b.extract();
}
}
optional<bson::document::value> collection::find_one_and_update(
const model::find_one_and_update& model) {
scoped_bson_t criteria{model.criteria()};
scoped_bson_t sort{model.sort()};
scoped_bson_t update{model.update()};
scoped_bson_t projection{model.projection()};
scoped_bson_t reply;
reply.flag_init();
bson_error_t error;
bool r = mongoc_collection_find_and_modify(
_impl->collection_t, criteria.bson(), sort.bson(), update.bson(), projection.bson(), false,
model.upsert().value_or(false), model.return_replacement().value_or(false), reply.bson(),
&error);
if (!r) {
throw std::runtime_error("shits fucked");
}
bson::document::view result = reply.view();
if (result["value"].type() == bson::type::k_null) {
return optional<bson::document::value>{};
} else {
using namespace bson::builder::helpers;
bson::builder::document b;
b << concat{result["value"].get_document()};
return b.extract();
}
}
optional<bson::document::value> collection::find_one_and_delete(
const model::find_one_and_delete& model) {
scoped_bson_t criteria{model.criteria()};
scoped_bson_t sort{model.sort()};
scoped_bson_t projection{model.projection()};
scoped_bson_t reply;
reply.flag_init();
bson_error_t error;
bool r = mongoc_collection_find_and_modify(_impl->collection_t, criteria.bson(), sort.bson(),
nullptr, projection.bson(), true, false, false,
reply.bson(), &error);
if (!r) {
throw std::runtime_error("shits fucked");
}
bson::document::view result = reply.view();
if (result["value"].type() == bson::type::k_null) {
return optional<bson::document::value>{};
} else {
using namespace bson::builder::helpers;
bson::builder::document b;
b << concat{result["value"].get_document()};
return b.extract();
}
}
bson::document::value collection::explain(const model::explain& /*model*/) const {
return bson::document::value((const std::uint8_t*)nullptr, 0);
}
std::int64_t collection::count(const model::count& model) const {
scoped_bson_t criteria{model.criteria()};
bson_error_t error;
optional<priv::read_preference> read_prefs;
const mongoc_read_prefs_t* rp_ptr;
if (model.read_preference()) {
read_prefs = priv::read_preference{*model.read_preference()};
rp_ptr = read_prefs->get_read_preference();
} else {
rp_ptr = mongoc_collection_get_read_prefs(_impl->collection_t);
}
auto result = mongoc_collection_count(_impl->collection_t, static_cast<mongoc_query_flags_t>(0),
criteria.bson(), model.skip().value_or(0),
model.limit().value_or(0), rp_ptr, &error);
/* TODO throw an exception if error
if (result < 0)
*/
return result;
}
void collection::drop() {
bson_error_t error;
if (mongoc_collection_drop(_impl->collection_t, &error)) {
/* TODO handle errors */
}
}
void collection::read_preference(class read_preference rp) {
_impl->read_preference(std::move(rp));
}
const class read_preference& collection::read_preference() const {
return _impl->read_preference();
}
void collection::write_concern(class write_concern wc) { _impl->write_concern(std::move(wc)); }
const class write_concern& collection::write_concern() const { return _impl->write_concern(); }
} // namespace driver
} // namespace mongo
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the QtFeedback module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtQml/QQmlExtensionPlugin>
#include "qdeclarativehapticseffect_p.h"
#include "qdeclarativefileeffect_p.h"
#include "qdeclarativethemeeffect_p.h"
#include "qdeclarativefeedbackeffect_p.h"
#include "qdeclarativefeedbackactuator_p.h"
QT_USE_NAMESPACE
static QObject *createDeclarativeThemeEfect(QDeclarativeEngine *engine, QJSEngine *jsengine)
{
Q_UNUSED(engine)
Q_UNUSED(jsengine)
return new QDeclarativeThemeEffect;
}
class QDeclarativeFeedbackPlugin : public QDeclarativeExtensionPlugin
{
Q_OBJECT
Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QQmlExtensionInterface" FILE "plugin.json")
public:
virtual void registerTypes(const char *uri)
{
Q_ASSERT(QLatin1String(uri) == QLatin1String("QtFeedback"));
int major = 5;
int minor = 0;
qmlRegisterUncreatableType<QDeclarativeFeedbackEffect>(uri, major, minor, "Feedback", "this is the feedback namespace");
qmlRegisterUncreatableType<QDeclarativeFeedbackEffect>(uri, major, minor, "FeedbackEffect", "this is the base feedback effect class");
qmlRegisterType<QDeclarativeFeedbackActuator>(uri, major, minor, "Actuator");
qmlRegisterType<QDeclarativeFileEffect>(uri, major, minor, "FileEffect");
qmlRegisterType<QDeclarativeHapticsEffect>(uri, major, minor, "HapticsEffect");
qmlRegisterType<QDeclarativeThemeEffect>(uri, major, minor, "ThemeEffect");
qmlRegisterModuleApi("QtFeedback.ThemeEffect", major, minor, createDeclarativeThemeEfect);
}
};
#include "plugin.moc"
<commit_msg>Use templated qmlRegisterModuleApi()<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the QtFeedback module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtQml/QQmlExtensionPlugin>
#include "qdeclarativehapticseffect_p.h"
#include "qdeclarativefileeffect_p.h"
#include "qdeclarativethemeeffect_p.h"
#include "qdeclarativefeedbackeffect_p.h"
#include "qdeclarativefeedbackactuator_p.h"
QT_USE_NAMESPACE
static QObject *createDeclarativeThemeEfect(QDeclarativeEngine *engine, QJSEngine *jsengine)
{
Q_UNUSED(engine)
Q_UNUSED(jsengine)
return new QDeclarativeThemeEffect;
}
class QDeclarativeFeedbackPlugin : public QDeclarativeExtensionPlugin
{
Q_OBJECT
Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QQmlExtensionInterface" FILE "plugin.json")
public:
virtual void registerTypes(const char *uri)
{
Q_ASSERT(QLatin1String(uri) == QLatin1String("QtFeedback"));
int major = 5;
int minor = 0;
qmlRegisterUncreatableType<QDeclarativeFeedbackEffect>(uri, major, minor, "Feedback", "this is the feedback namespace");
qmlRegisterUncreatableType<QDeclarativeFeedbackEffect>(uri, major, minor, "FeedbackEffect", "this is the base feedback effect class");
qmlRegisterType<QDeclarativeFeedbackActuator>(uri, major, minor, "Actuator");
qmlRegisterType<QDeclarativeFileEffect>(uri, major, minor, "FileEffect");
qmlRegisterType<QDeclarativeHapticsEffect>(uri, major, minor, "HapticsEffect");
qmlRegisterType<QDeclarativeThemeEffect>(uri, major, minor, "ThemeEffect");
qmlRegisterModuleApi<QDeclarativeThemeEffect>("QtFeedback.ThemeEffect", major, minor, createDeclarativeThemeEfect);
}
};
#include "plugin.moc"
<|endoftext|> |
<commit_before>#ifndef BEAM_DUPLEX_UNORDERED_MIXED_HPP
#define BEAM_DUPLEX_UNORDERED_MIXED_HPP
#include <chrono>
#include <functional>
#include <memory>
#include <tuple>
#include <unordered_map>
#include <asio/strand.hpp>
#include <beam/duplex/common.hpp>
#include <beam/internet/endpoint.hpp>
#include <beam/message/buffer_pool.hpp>
#include <beam/message/capnproto.hpp>
#include <enet/enet.h>
#include <kj/array.h>
namespace beam {
namespace duplex {
namespace unordered_mixed {
namespace channel_id
{
enum type
{
unreliable = 0,
reliable = 1
};
}
struct key;
template <class unreliable_msg_t, class reliable_msg_t>
class in_connection
{
public:
typedef unreliable_msg_t unreliable_msg_type;
typedef reliable_msg_t reliable_msg_type;
struct event_handlers
{
std::function<void(const event_handlers& current)> on_timeout;
std::function<void(const in_connection& connection)> on_connect;
std::function<void(const in_connection& connection)> on_disconnect;
std::function<void(const in_connection& connection, beam::message::capnproto::payload<unreliable_msg_t>&& payload)> on_receive_unreliable_msg;
std::function<void(const in_connection& connection, beam::message::capnproto::payload<reliable_msg_t>&& payload)> on_receive_reliable_msg;
};
in_connection(const key&, asio::io_service::strand& strand, beam::message::buffer_pool& pool, ENetHost& host, ENetPeer& peer);
beam::internet::endpoint_id get_source_id() const;
private:
in_connection() = delete;
asio::io_service::strand& strand_;
beam::message::buffer_pool& pool_;
ENetHost& host_;
ENetPeer& peer_;
};
template <class unreliable_msg_t, class reliable_msg_t>
class out_connection
{
public:
struct delivery_metadata
{
inline delivery_metadata(
beam::message::buffer_pool* p,
std::unordered_map<beam::message::buffer_pool::capacity_type, delivery_metadata>* m)
:
pool(p),
metadata_map(m)
{ }
beam::message::buffer_pool* pool;
std::unordered_map<beam::message::buffer_pool::capacity_type, delivery_metadata>* metadata_map;
};
typedef std::unordered_map<beam::message::buffer_pool::capacity_type, delivery_metadata> metadata_map_type;
typedef unreliable_msg_t unreliable_msg_type;
typedef reliable_msg_t reliable_msg_type;
out_connection(
const key&,
asio::io_service::strand& strand,
beam::message::buffer_pool& pool,
metadata_map_type& metadata,
ENetHost& host,
ENetPeer& peer);
beam::internet::endpoint_id get_destination_id() const;
void send_unreliable(beam::message::capnproto::payload<unreliable_msg_t>& message);
void send_reliable(beam::message::capnproto::payload<reliable_msg_t>& message);
private:
out_connection() = delete;
static uint32_t get_packet_flags(channel_id::type channel);
static void return_message(ENetPacket* packet);
void send(beam::message::buffer& message, channel_id::type channel);
asio::io_service::strand& strand_;
beam::message::buffer_pool& pool_;
metadata_map_type& metadata_;
ENetHost& host_;
ENetPeer& peer_;
};
struct perf_params
{
perf_params(
std::size_t max,
std::size_t window,
std::chrono::milliseconds timeout = std::chrono::milliseconds(15000),
std::size_t download = 0,
std::size_t upload = 0);
std::size_t max_connections;
std::size_t window_size;
std::chrono::milliseconds connection_timeout;
std::size_t download_bytes_per_sec;
std::size_t upload_bytes_per_sec;
};
enum class connection_result
{
success,
already_connected,
failure
};
template <class in_connection_t, class out_connection_t>
class initiator
{
public:
typedef in_connection_t in_connection_type;
typedef out_connection_t out_connection_type;
initiator(asio::io_service::strand& strand, perf_params&& params);
inline bool is_connected() const { return peer_.get() != nullptr; }
connection_result connect(std::vector<beam::internet::ipv4::address>&& receive_candidates, beam::duplex::common::port port);
void disconnect();
void async_send(std::function<void(out_connection_t&)> callback);
void async_receive(const typename in_connection_t::event_handlers& handlers);
private:
initiator() = delete;
initiator(const initiator&) = delete;
initiator& operator=(const initiator&) = delete;
void exec_send(std::function<void(out_connection_t&)> callback);
void exec_receive(const typename in_connection_t::event_handlers& handlers);
asio::io_service::strand& strand_;
perf_params params_;
beam::message::buffer_pool pool_;
typename out_connection_type::metadata_map_type metadata_;
std::unique_ptr<ENetHost, std::function<void(ENetHost*)>> host_;
std::unique_ptr<ENetPeer, std::function<void(ENetPeer*)>> peer_;
std::unique_ptr<out_connection_t> out_;
// TODO add a peer_map
};
enum class bind_result
{
success,
already_bound,
failure
};
template <class in_connection_t, class out_connection_t>
class responder
{
public:
typedef in_connection_t in_connection_type;
typedef out_connection_t out_connection_type;
responder(asio::io_service::strand& strand, perf_params&& params);
inline bool is_bound() const { return host_.get() != nullptr; }
inline bool has_connections() const { return !peer_map_.empty(); }
bind_result bind(const beam::internet::endpoint_id& id);
void unbind();
void async_send(std::function<void(std::function<out_connection_t*(const beam::internet::endpoint_id&)>)> callback);
void async_receive(const typename in_connection_t::event_handlers& handlers);
private:
responder() = delete;
responder(const responder&) = delete;
responder& operator=(const responder&) = delete;
void exec_unbind();
void exec_send(std::function<void(std::function<out_connection_t*(const beam::internet::endpoint_id&)>)> callback);
void exec_receive(const typename in_connection_t::event_handlers& handlers);
asio::io_service::strand& strand_;
perf_params params_;
beam::message::buffer_pool pool_;
typename out_connection_type::metadata_map_type metadata_;
std::unique_ptr<ENetHost, std::function<void(ENetHost*)>> host_;
std::unordered_map<beam::internet::endpoint_id, std::tuple<in_connection_t, out_connection_t>> peer_map_;
};
} // namespace unordered_mixed
} // namespace duplex
} // namespace beam
#endif
<commit_msg>responder can now return the bound endpoint_id<commit_after>#ifndef BEAM_DUPLEX_UNORDERED_MIXED_HPP
#define BEAM_DUPLEX_UNORDERED_MIXED_HPP
#include <chrono>
#include <functional>
#include <memory>
#include <tuple>
#include <unordered_map>
#include <asio/strand.hpp>
#include <beam/duplex/common.hpp>
#include <beam/internet/endpoint.hpp>
#include <beam/message/buffer_pool.hpp>
#include <beam/message/capnproto.hpp>
#include <enet/enet.h>
#include <kj/array.h>
namespace beam {
namespace duplex {
namespace unordered_mixed {
namespace channel_id
{
enum type
{
unreliable = 0,
reliable = 1
};
}
struct key;
template <class unreliable_msg_t, class reliable_msg_t>
class in_connection
{
public:
typedef unreliable_msg_t unreliable_msg_type;
typedef reliable_msg_t reliable_msg_type;
struct event_handlers
{
std::function<void(const event_handlers& current)> on_timeout;
std::function<void(const in_connection& connection)> on_connect;
std::function<void(const in_connection& connection)> on_disconnect;
std::function<void(const in_connection& connection, beam::message::capnproto::payload<unreliable_msg_t>&& payload)> on_receive_unreliable_msg;
std::function<void(const in_connection& connection, beam::message::capnproto::payload<reliable_msg_t>&& payload)> on_receive_reliable_msg;
};
in_connection(const key&, asio::io_service::strand& strand, beam::message::buffer_pool& pool, ENetHost& host, ENetPeer& peer);
beam::internet::endpoint_id get_source_id() const;
private:
in_connection() = delete;
asio::io_service::strand& strand_;
beam::message::buffer_pool& pool_;
ENetHost& host_;
ENetPeer& peer_;
};
template <class unreliable_msg_t, class reliable_msg_t>
class out_connection
{
public:
struct delivery_metadata
{
inline delivery_metadata(
beam::message::buffer_pool* p,
std::unordered_map<beam::message::buffer_pool::capacity_type, delivery_metadata>* m)
:
pool(p),
metadata_map(m)
{ }
beam::message::buffer_pool* pool;
std::unordered_map<beam::message::buffer_pool::capacity_type, delivery_metadata>* metadata_map;
};
typedef std::unordered_map<beam::message::buffer_pool::capacity_type, delivery_metadata> metadata_map_type;
typedef unreliable_msg_t unreliable_msg_type;
typedef reliable_msg_t reliable_msg_type;
out_connection(
const key&,
asio::io_service::strand& strand,
beam::message::buffer_pool& pool,
metadata_map_type& metadata,
ENetHost& host,
ENetPeer& peer);
beam::internet::endpoint_id get_destination_id() const;
void send_unreliable(beam::message::capnproto::payload<unreliable_msg_t>& message);
void send_reliable(beam::message::capnproto::payload<reliable_msg_t>& message);
private:
out_connection() = delete;
static uint32_t get_packet_flags(channel_id::type channel);
static void return_message(ENetPacket* packet);
void send(beam::message::buffer& message, channel_id::type channel);
asio::io_service::strand& strand_;
beam::message::buffer_pool& pool_;
metadata_map_type& metadata_;
ENetHost& host_;
ENetPeer& peer_;
};
struct perf_params
{
perf_params(
std::size_t max,
std::size_t window,
std::chrono::milliseconds timeout = std::chrono::milliseconds(15000),
std::size_t download = 0,
std::size_t upload = 0);
std::size_t max_connections;
std::size_t window_size;
std::chrono::milliseconds connection_timeout;
std::size_t download_bytes_per_sec;
std::size_t upload_bytes_per_sec;
};
enum class connection_result
{
success,
already_connected,
failure
};
template <class in_connection_t, class out_connection_t>
class initiator
{
public:
typedef in_connection_t in_connection_type;
typedef out_connection_t out_connection_type;
initiator(asio::io_service::strand& strand, perf_params&& params);
inline bool is_connected() const { return peer_.get() != nullptr; }
connection_result connect(std::vector<beam::internet::ipv4::address>&& receive_candidates, beam::duplex::common::port port);
void disconnect();
void async_send(std::function<void(out_connection_t&)> callback);
void async_receive(const typename in_connection_t::event_handlers& handlers);
private:
initiator() = delete;
initiator(const initiator&) = delete;
initiator& operator=(const initiator&) = delete;
void exec_send(std::function<void(out_connection_t&)> callback);
void exec_receive(const typename in_connection_t::event_handlers& handlers);
asio::io_service::strand& strand_;
perf_params params_;
beam::message::buffer_pool pool_;
typename out_connection_type::metadata_map_type metadata_;
std::unique_ptr<ENetHost, std::function<void(ENetHost*)>> host_;
std::unique_ptr<ENetPeer, std::function<void(ENetPeer*)>> peer_;
std::unique_ptr<out_connection_t> out_;
// TODO add a peer_map
};
enum class bind_result
{
success,
already_bound,
failure
};
template <class in_connection_t, class out_connection_t>
class responder
{
public:
typedef in_connection_t in_connection_type;
typedef out_connection_t out_connection_type;
responder(asio::io_service::strand& strand, perf_params&& params);
inline bool is_bound() const { return host_.get() != nullptr; }
inline bool has_connections() const { return !peer_map_.empty(); }
inline beam::internet::endpoint_id get_binding() const
{
return is_bound()
? beam::internet::endpoint_id(host_->address.host, host_->address.port)
: beam::internet::endpoint_id();
}
bind_result bind(const beam::internet::endpoint_id& id);
void unbind();
void async_send(std::function<void(std::function<out_connection_t*(const beam::internet::endpoint_id&)>)> callback);
void async_receive(const typename in_connection_t::event_handlers& handlers);
private:
responder() = delete;
responder(const responder&) = delete;
responder& operator=(const responder&) = delete;
void exec_unbind();
void exec_send(std::function<void(std::function<out_connection_t*(const beam::internet::endpoint_id&)>)> callback);
void exec_receive(const typename in_connection_t::event_handlers& handlers);
asio::io_service::strand& strand_;
perf_params params_;
beam::message::buffer_pool pool_;
typename out_connection_type::metadata_map_type metadata_;
std::unique_ptr<ENetHost, std::function<void(ENetHost*)>> host_;
std::unordered_map<beam::internet::endpoint_id, std::tuple<in_connection_t, out_connection_t>> peer_map_;
};
} // namespace unordered_mixed
} // namespace duplex
} // namespace beam
#endif
<|endoftext|> |
<commit_before>//===-- gold-plugin.cpp - Plugin to gold for Link Time Optimization ------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is a gold plugin for LLVM. It provides an LLVM implementation of the
// interface described in http://gcc.gnu.org/wiki/whopr/driver .
//
//===----------------------------------------------------------------------===//
#include "plugin-api.h"
#include "llvm-c/lto.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/System/Path.h"
#include <cstdlib>
#include <cstring>
#include <list>
#include <vector>
#include <cerrno>
using namespace llvm;
namespace {
ld_plugin_status discard_message(int level, const char *format, ...) {
// Die loudly. Recent versions of Gold pass ld_plugin_message as the first
// callback in the transfer vector. This should never be called.
abort();
}
ld_plugin_add_symbols add_symbols = NULL;
ld_plugin_get_symbols get_symbols = NULL;
ld_plugin_add_input_file add_input_file = NULL;
ld_plugin_message message = discard_message;
int api_version = 0;
int gold_version = 0;
struct claimed_file {
lto_module_t M;
void *handle;
void *buf;
std::vector<ld_plugin_symbol> syms;
};
lto_codegen_model output_type = LTO_CODEGEN_PIC_MODEL_STATIC;
std::list<claimed_file> Modules;
std::vector<sys::Path> Cleanup;
}
ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
int *claimed);
ld_plugin_status all_symbols_read_hook(void);
ld_plugin_status cleanup_hook(void);
extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
ld_plugin_status onload(ld_plugin_tv *tv) {
// We're given a pointer to the first transfer vector. We read through them
// until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
// contain pointers to functions that we need to call to register our own
// hooks. The others are addresses of functions we can use to call into gold
// for services.
bool registeredClaimFile = false;
bool registeredAllSymbolsRead = false;
bool registeredCleanup = false;
for (; tv->tv_tag != LDPT_NULL; ++tv) {
switch (tv->tv_tag) {
case LDPT_API_VERSION:
api_version = tv->tv_u.tv_val;
break;
case LDPT_GOLD_VERSION: // major * 100 + minor
gold_version = tv->tv_u.tv_val;
break;
case LDPT_LINKER_OUTPUT:
switch (tv->tv_u.tv_val) {
case LDPO_REL: // .o
case LDPO_DYN: // .so
output_type = LTO_CODEGEN_PIC_MODEL_DYNAMIC;
break;
case LDPO_EXEC: // .exe
output_type = LTO_CODEGEN_PIC_MODEL_STATIC;
break;
default:
(*message)(LDPL_ERROR, "Unknown output file type %d",
tv->tv_u.tv_val);
return LDPS_ERR;
}
// TODO: add an option to disable PIC.
//output_type = LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC;
break;
case LDPT_OPTION:
(*message)(LDPL_WARNING, "Ignoring flag %s", tv->tv_u.tv_string);
break;
case LDPT_REGISTER_CLAIM_FILE_HOOK: {
ld_plugin_register_claim_file callback;
callback = tv->tv_u.tv_register_claim_file;
if ((*callback)(claim_file_hook) != LDPS_OK)
return LDPS_ERR;
registeredClaimFile = true;
} break;
case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
ld_plugin_register_all_symbols_read callback;
callback = tv->tv_u.tv_register_all_symbols_read;
if ((*callback)(all_symbols_read_hook) != LDPS_OK)
return LDPS_ERR;
registeredAllSymbolsRead = true;
} break;
case LDPT_REGISTER_CLEANUP_HOOK: {
ld_plugin_register_cleanup callback;
callback = tv->tv_u.tv_register_cleanup;
if ((*callback)(cleanup_hook) != LDPS_OK)
return LDPS_ERR;
registeredCleanup = true;
} break;
case LDPT_ADD_SYMBOLS:
add_symbols = tv->tv_u.tv_add_symbols;
break;
case LDPT_GET_SYMBOLS:
get_symbols = tv->tv_u.tv_get_symbols;
break;
case LDPT_ADD_INPUT_FILE:
add_input_file = tv->tv_u.tv_add_input_file;
break;
case LDPT_MESSAGE:
message = tv->tv_u.tv_message;
break;
default:
break;
}
}
if (!registeredClaimFile || !registeredAllSymbolsRead || !registeredCleanup ||
!add_symbols || !get_symbols || !add_input_file) {
(*message)(LDPL_ERROR, "Not all hooks registered for LLVMgold.");
return LDPS_ERR;
}
return LDPS_OK;
}
/// claim_file_hook - called by gold to see whether this file is one that
/// our plugin can handle. We'll try to open it and register all the symbols
/// with add_symbol if possible.
ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
int *claimed) {
void *buf = NULL;
// If set, this means gold found IR in an ELF section. LLVM doesn't wrap its
// IR in ELF, so we know it's not us. But it can also be an .a file containing
// LLVM IR.
if (file->offset) {
if (lseek(file->fd, file->offset, SEEK_SET) == -1) {
(*message)(LDPL_ERROR,
"Failed to seek to archive member of %s at offset %d: %s\n",
file->name,
file->offset, strerror(errno));
return LDPS_ERR;
}
buf = malloc(file->filesize);
if (!buf) {
(*message)(LDPL_ERROR,
"Failed to allocate buffer for archive member of size: %d\n",
file->filesize);
return LDPS_ERR;
}
if (read(file->fd, buf, file->filesize) != file->filesize) {
(*message)(LDPL_ERROR,
"Failed to read archive member of %s at offset %d: %s\n",
file->name,
file->offset,
strerror(errno));
free(buf);
return LDPS_ERR;
}
if (!lto_module_is_object_file_in_memory(buf, file->filesize)) {
free(buf);
return LDPS_OK;
}
} else if (!lto_module_is_object_file(file->name))
return LDPS_OK;
*claimed = 1;
Modules.resize(Modules.size() + 1);
claimed_file &cf = Modules.back();
cf.M = buf ? lto_module_create_from_memory(buf, file->filesize) :
lto_module_create(file->name);
cf.buf = buf;
if (!cf.M) {
(*message)(LDPL_ERROR, "Failed to create LLVM module: %s",
lto_get_error_message());
return LDPS_ERR;
}
cf.handle = file->handle;
unsigned sym_count = lto_module_get_num_symbols(cf.M);
cf.syms.reserve(sym_count);
for (unsigned i = 0; i != sym_count; ++i) {
lto_symbol_attributes attrs = lto_module_get_symbol_attribute(cf.M, i);
if ((attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL)
continue;
cf.syms.push_back(ld_plugin_symbol());
ld_plugin_symbol &sym = cf.syms.back();
sym.name = const_cast<char *>(lto_module_get_symbol_name(cf.M, i));
sym.version = NULL;
int scope = attrs & LTO_SYMBOL_SCOPE_MASK;
switch (scope) {
case LTO_SYMBOL_SCOPE_HIDDEN:
sym.visibility = LDPV_HIDDEN;
break;
case LTO_SYMBOL_SCOPE_PROTECTED:
sym.visibility = LDPV_PROTECTED;
break;
case 0: // extern
case LTO_SYMBOL_SCOPE_DEFAULT:
sym.visibility = LDPV_DEFAULT;
break;
default:
(*message)(LDPL_ERROR, "Unknown scope attribute: %d", scope);
free(buf);
return LDPS_ERR;
}
int definition = attrs & LTO_SYMBOL_DEFINITION_MASK;
switch (definition) {
case LTO_SYMBOL_DEFINITION_REGULAR:
sym.def = LDPK_DEF;
break;
case LTO_SYMBOL_DEFINITION_UNDEFINED:
sym.def = LDPK_UNDEF;
break;
case LTO_SYMBOL_DEFINITION_TENTATIVE:
sym.def = LDPK_COMMON;
break;
case LTO_SYMBOL_DEFINITION_WEAK:
sym.def = LDPK_WEAKDEF;
break;
default:
(*message)(LDPL_ERROR, "Unknown definition attribute: %d", definition);
free(buf);
return LDPS_ERR;
}
// LLVM never emits COMDAT.
sym.size = 0;
sym.comdat_key = NULL;
sym.resolution = LDPR_UNKNOWN;
}
cf.syms.reserve(cf.syms.size());
if (!cf.syms.empty()) {
if ((*add_symbols)(cf.handle, cf.syms.size(), &cf.syms[0]) != LDPS_OK) {
(*message)(LDPL_ERROR, "Unable to add symbols!");
free(buf);
return LDPS_ERR;
}
}
return LDPS_OK;
}
/// all_symbols_read_hook - gold informs us that all symbols have been read.
/// At this point, we use get_symbols to see if any of our definitions have
/// been overridden by a native object file. Then, perform optimization and
/// codegen.
ld_plugin_status all_symbols_read_hook(void) {
lto_code_gen_t cg = lto_codegen_create();
for (std::list<claimed_file>::iterator I = Modules.begin(),
E = Modules.end(); I != E; ++I)
lto_codegen_add_module(cg, I->M);
// If we don't preserve any symbols, libLTO will assume that all symbols are
// needed. Keep all symbols unless we're producing a final executable.
if (output_type == LTO_CODEGEN_PIC_MODEL_STATIC) {
bool anySymbolsPreserved = false;
for (std::list<claimed_file>::iterator I = Modules.begin(),
E = Modules.end(); I != E; ++I) {
(*get_symbols)(I->handle, I->syms.size(), &I->syms[0]);
for (unsigned i = 0, e = I->syms.size(); i != e; i++) {
(*message)(LDPL_WARNING, "def: %d visibility: %d resolution %d",
I->syms[i].def, I->syms[i].visibility, I->syms[i].resolution);
if (I->syms[i].resolution == LDPR_PREVAILING_DEF) {
lto_codegen_add_must_preserve_symbol(cg, I->syms[i].name);
anySymbolsPreserved = true;
}
}
}
if (!anySymbolsPreserved) {
// This entire file is unnecessary!
lto_codegen_dispose(cg);
return LDPS_OK;
}
}
lto_codegen_set_pic_model(cg, output_type);
lto_codegen_set_debug_model(cg, LTO_DEBUG_MODEL_DWARF);
size_t bufsize = 0;
const char *buffer = static_cast<const char *>(lto_codegen_compile(cg,
&bufsize));
std::string ErrMsg;
sys::Path uniqueObjPath("/tmp/llvmgold.o");
if (uniqueObjPath.createTemporaryFileOnDisk(true, &ErrMsg)) {
(*message)(LDPL_ERROR, "%s", ErrMsg.c_str());
return LDPS_ERR;
}
raw_fd_ostream *objFile = new raw_fd_ostream(uniqueObjPath.c_str(), true,
ErrMsg);
if (!ErrMsg.empty()) {
delete objFile;
(*message)(LDPL_ERROR, "%s", ErrMsg.c_str());
return LDPS_ERR;
}
objFile->write(buffer, bufsize);
objFile->close();
lto_codegen_dispose(cg);
for (std::list<claimed_file>::iterator I = Modules.begin(),
E = Modules.end(); I != E; ++I) {
free(I->buf);
}
if ((*add_input_file)(const_cast<char*>(uniqueObjPath.c_str())) != LDPS_OK) {
(*message)(LDPL_ERROR, "Unable to add .o file to the link.");
(*message)(LDPL_ERROR, "File left behind in: %s", uniqueObjPath.c_str());
return LDPS_ERR;
}
Cleanup.push_back(uniqueObjPath);
return LDPS_OK;
}
ld_plugin_status cleanup_hook(void) {
std::string ErrMsg;
for (int i = 0, e = Cleanup.size(); i != e; ++i)
if (Cleanup[i].eraseFromDisk(false, &ErrMsg))
(*message)(LDPL_ERROR, "Failed to delete '%s': %s", Cleanup[i].c_str(),
ErrMsg.c_str());
return LDPS_OK;
}
<commit_msg>Alphabetize includes. Update comment.<commit_after>//===-- gold-plugin.cpp - Plugin to gold for Link Time Optimization ------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is a gold plugin for LLVM. It provides an LLVM implementation of the
// interface described in http://gcc.gnu.org/wiki/whopr/driver .
//
//===----------------------------------------------------------------------===//
#include "plugin-api.h"
#include "llvm-c/lto.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/System/Path.h"
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <list>
#include <vector>
using namespace llvm;
namespace {
ld_plugin_status discard_message(int level, const char *format, ...) {
// Die loudly. Recent versions of Gold pass ld_plugin_message as the first
// callback in the transfer vector. This should never be called.
abort();
}
ld_plugin_add_symbols add_symbols = NULL;
ld_plugin_get_symbols get_symbols = NULL;
ld_plugin_add_input_file add_input_file = NULL;
ld_plugin_message message = discard_message;
int api_version = 0;
int gold_version = 0;
struct claimed_file {
lto_module_t M;
void *handle;
void *buf;
std::vector<ld_plugin_symbol> syms;
};
lto_codegen_model output_type = LTO_CODEGEN_PIC_MODEL_STATIC;
std::list<claimed_file> Modules;
std::vector<sys::Path> Cleanup;
}
ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
int *claimed);
ld_plugin_status all_symbols_read_hook(void);
ld_plugin_status cleanup_hook(void);
extern "C" ld_plugin_status onload(ld_plugin_tv *tv);
ld_plugin_status onload(ld_plugin_tv *tv) {
// We're given a pointer to the first transfer vector. We read through them
// until we find one where tv_tag == LDPT_NULL. The REGISTER_* tagged values
// contain pointers to functions that we need to call to register our own
// hooks. The others are addresses of functions we can use to call into gold
// for services.
bool registeredClaimFile = false;
bool registeredAllSymbolsRead = false;
bool registeredCleanup = false;
for (; tv->tv_tag != LDPT_NULL; ++tv) {
switch (tv->tv_tag) {
case LDPT_API_VERSION:
api_version = tv->tv_u.tv_val;
break;
case LDPT_GOLD_VERSION: // major * 100 + minor
gold_version = tv->tv_u.tv_val;
break;
case LDPT_LINKER_OUTPUT:
switch (tv->tv_u.tv_val) {
case LDPO_REL: // .o
case LDPO_DYN: // .so
output_type = LTO_CODEGEN_PIC_MODEL_DYNAMIC;
break;
case LDPO_EXEC: // .exe
output_type = LTO_CODEGEN_PIC_MODEL_STATIC;
break;
default:
(*message)(LDPL_ERROR, "Unknown output file type %d",
tv->tv_u.tv_val);
return LDPS_ERR;
}
// TODO: add an option to disable PIC.
//output_type = LTO_CODEGEN_PIC_MODEL_DYNAMIC_NO_PIC;
break;
case LDPT_OPTION:
(*message)(LDPL_WARNING, "Ignoring flag %s", tv->tv_u.tv_string);
break;
case LDPT_REGISTER_CLAIM_FILE_HOOK: {
ld_plugin_register_claim_file callback;
callback = tv->tv_u.tv_register_claim_file;
if ((*callback)(claim_file_hook) != LDPS_OK)
return LDPS_ERR;
registeredClaimFile = true;
} break;
case LDPT_REGISTER_ALL_SYMBOLS_READ_HOOK: {
ld_plugin_register_all_symbols_read callback;
callback = tv->tv_u.tv_register_all_symbols_read;
if ((*callback)(all_symbols_read_hook) != LDPS_OK)
return LDPS_ERR;
registeredAllSymbolsRead = true;
} break;
case LDPT_REGISTER_CLEANUP_HOOK: {
ld_plugin_register_cleanup callback;
callback = tv->tv_u.tv_register_cleanup;
if ((*callback)(cleanup_hook) != LDPS_OK)
return LDPS_ERR;
registeredCleanup = true;
} break;
case LDPT_ADD_SYMBOLS:
add_symbols = tv->tv_u.tv_add_symbols;
break;
case LDPT_GET_SYMBOLS:
get_symbols = tv->tv_u.tv_get_symbols;
break;
case LDPT_ADD_INPUT_FILE:
add_input_file = tv->tv_u.tv_add_input_file;
break;
case LDPT_MESSAGE:
message = tv->tv_u.tv_message;
break;
default:
break;
}
}
if (!registeredClaimFile || !registeredAllSymbolsRead || !registeredCleanup ||
!add_symbols || !get_symbols || !add_input_file) {
(*message)(LDPL_ERROR, "Not all hooks registered for LLVMgold.");
return LDPS_ERR;
}
return LDPS_OK;
}
/// claim_file_hook - called by gold to see whether this file is one that
/// our plugin can handle. We'll try to open it and register all the symbols
/// with add_symbol if possible.
ld_plugin_status claim_file_hook(const ld_plugin_input_file *file,
int *claimed) {
void *buf = NULL;
if (file->offset) {
/* This is probably an archive member containing either an ELF object, or
* LLVM IR. Find out which one it is */
if (lseek(file->fd, file->offset, SEEK_SET) == -1) {
(*message)(LDPL_ERROR,
"Failed to seek to archive member of %s at offset %d: %s\n",
file->name,
file->offset, strerror(errno));
return LDPS_ERR;
}
buf = malloc(file->filesize);
if (!buf) {
(*message)(LDPL_ERROR,
"Failed to allocate buffer for archive member of size: %d\n",
file->filesize);
return LDPS_ERR;
}
if (read(file->fd, buf, file->filesize) != file->filesize) {
(*message)(LDPL_ERROR,
"Failed to read archive member of %s at offset %d: %s\n",
file->name,
file->offset,
strerror(errno));
free(buf);
return LDPS_ERR;
}
if (!lto_module_is_object_file_in_memory(buf, file->filesize)) {
free(buf);
return LDPS_OK;
}
} else if (!lto_module_is_object_file(file->name))
return LDPS_OK;
*claimed = 1;
Modules.resize(Modules.size() + 1);
claimed_file &cf = Modules.back();
cf.M = buf ? lto_module_create_from_memory(buf, file->filesize) :
lto_module_create(file->name);
cf.buf = buf;
if (!cf.M) {
(*message)(LDPL_ERROR, "Failed to create LLVM module: %s",
lto_get_error_message());
return LDPS_ERR;
}
cf.handle = file->handle;
unsigned sym_count = lto_module_get_num_symbols(cf.M);
cf.syms.reserve(sym_count);
for (unsigned i = 0; i != sym_count; ++i) {
lto_symbol_attributes attrs = lto_module_get_symbol_attribute(cf.M, i);
if ((attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL)
continue;
cf.syms.push_back(ld_plugin_symbol());
ld_plugin_symbol &sym = cf.syms.back();
sym.name = const_cast<char *>(lto_module_get_symbol_name(cf.M, i));
sym.version = NULL;
int scope = attrs & LTO_SYMBOL_SCOPE_MASK;
switch (scope) {
case LTO_SYMBOL_SCOPE_HIDDEN:
sym.visibility = LDPV_HIDDEN;
break;
case LTO_SYMBOL_SCOPE_PROTECTED:
sym.visibility = LDPV_PROTECTED;
break;
case 0: // extern
case LTO_SYMBOL_SCOPE_DEFAULT:
sym.visibility = LDPV_DEFAULT;
break;
default:
(*message)(LDPL_ERROR, "Unknown scope attribute: %d", scope);
free(buf);
return LDPS_ERR;
}
int definition = attrs & LTO_SYMBOL_DEFINITION_MASK;
switch (definition) {
case LTO_SYMBOL_DEFINITION_REGULAR:
sym.def = LDPK_DEF;
break;
case LTO_SYMBOL_DEFINITION_UNDEFINED:
sym.def = LDPK_UNDEF;
break;
case LTO_SYMBOL_DEFINITION_TENTATIVE:
sym.def = LDPK_COMMON;
break;
case LTO_SYMBOL_DEFINITION_WEAK:
sym.def = LDPK_WEAKDEF;
break;
default:
(*message)(LDPL_ERROR, "Unknown definition attribute: %d", definition);
free(buf);
return LDPS_ERR;
}
// LLVM never emits COMDAT.
sym.size = 0;
sym.comdat_key = NULL;
sym.resolution = LDPR_UNKNOWN;
}
cf.syms.reserve(cf.syms.size());
if (!cf.syms.empty()) {
if ((*add_symbols)(cf.handle, cf.syms.size(), &cf.syms[0]) != LDPS_OK) {
(*message)(LDPL_ERROR, "Unable to add symbols!");
free(buf);
return LDPS_ERR;
}
}
return LDPS_OK;
}
/// all_symbols_read_hook - gold informs us that all symbols have been read.
/// At this point, we use get_symbols to see if any of our definitions have
/// been overridden by a native object file. Then, perform optimization and
/// codegen.
ld_plugin_status all_symbols_read_hook(void) {
lto_code_gen_t cg = lto_codegen_create();
for (std::list<claimed_file>::iterator I = Modules.begin(),
E = Modules.end(); I != E; ++I)
lto_codegen_add_module(cg, I->M);
// If we don't preserve any symbols, libLTO will assume that all symbols are
// needed. Keep all symbols unless we're producing a final executable.
if (output_type == LTO_CODEGEN_PIC_MODEL_STATIC) {
bool anySymbolsPreserved = false;
for (std::list<claimed_file>::iterator I = Modules.begin(),
E = Modules.end(); I != E; ++I) {
(*get_symbols)(I->handle, I->syms.size(), &I->syms[0]);
for (unsigned i = 0, e = I->syms.size(); i != e; i++) {
(*message)(LDPL_WARNING, "def: %d visibility: %d resolution %d",
I->syms[i].def, I->syms[i].visibility, I->syms[i].resolution);
if (I->syms[i].resolution == LDPR_PREVAILING_DEF) {
lto_codegen_add_must_preserve_symbol(cg, I->syms[i].name);
anySymbolsPreserved = true;
}
}
}
if (!anySymbolsPreserved) {
// This entire file is unnecessary!
lto_codegen_dispose(cg);
return LDPS_OK;
}
}
lto_codegen_set_pic_model(cg, output_type);
lto_codegen_set_debug_model(cg, LTO_DEBUG_MODEL_DWARF);
size_t bufsize = 0;
const char *buffer = static_cast<const char *>(lto_codegen_compile(cg,
&bufsize));
std::string ErrMsg;
sys::Path uniqueObjPath("/tmp/llvmgold.o");
if (uniqueObjPath.createTemporaryFileOnDisk(true, &ErrMsg)) {
(*message)(LDPL_ERROR, "%s", ErrMsg.c_str());
return LDPS_ERR;
}
raw_fd_ostream *objFile = new raw_fd_ostream(uniqueObjPath.c_str(), true,
ErrMsg);
if (!ErrMsg.empty()) {
delete objFile;
(*message)(LDPL_ERROR, "%s", ErrMsg.c_str());
return LDPS_ERR;
}
objFile->write(buffer, bufsize);
objFile->close();
lto_codegen_dispose(cg);
for (std::list<claimed_file>::iterator I = Modules.begin(),
E = Modules.end(); I != E; ++I) {
free(I->buf);
}
if ((*add_input_file)(const_cast<char*>(uniqueObjPath.c_str())) != LDPS_OK) {
(*message)(LDPL_ERROR, "Unable to add .o file to the link.");
(*message)(LDPL_ERROR, "File left behind in: %s", uniqueObjPath.c_str());
return LDPS_ERR;
}
Cleanup.push_back(uniqueObjPath);
return LDPS_OK;
}
ld_plugin_status cleanup_hook(void) {
std::string ErrMsg;
for (int i = 0, e = Cleanup.size(); i != e; ++i)
if (Cleanup[i].eraseFromDisk(false, &ErrMsg))
(*message)(LDPL_ERROR, "Failed to delete '%s': %s", Cleanup[i].c_str(),
ErrMsg.c_str());
return LDPS_OK;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: resmgr.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2008-02-25 15:58:27 $
*
* 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 _TOOLS_RESMGR_HXX
#define _TOOLS_RESMGR_HXX
#ifndef INCLUDED_TOOLSDLLAPI_H
#include "tools/toolsdllapi.h"
#endif
#ifndef INCLUDED_I18NPOOL_LANG_H
#include <i18npool/lang.h>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _REF_HXX
#include <tools/ref.hxx>
#endif
#ifndef _TOOLS_RESID_HXX
#include <tools/resid.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_LOCALE_HPP_
#include <com/sun/star/lang/Locale.hpp>
#endif
#define CREATEVERSIONRESMGR_NAME( Name ) #Name
#define CREATEVERSIONRESMGR( Name ) ResMgr::CreateResMgr( #Name )
#define LOCALE_MAX_FALLBACK 6
#include <vector>
class SvStream;
class InternalResMgr;
// -----------------
// - RSHEADER_TYPE -
// -----------------
// Definition der Struktur, aus denen die Resource aufgebaut ist
struct RSHEADER_TYPE
{
private:
sal_uInt32 nId; // Identifier der Resource
RESOURCE_TYPE nRT; // Resource Typ
sal_uInt32 nGlobOff; // Globaler Offset
sal_uInt32 nLocalOff; // Lokaler Offset
public:
inline sal_uInt32 GetId(); // Identifier der Resource
inline RESOURCE_TYPE GetRT(); // Resource Typ
inline sal_uInt32 GetGlobOff(); // Globaler Offset
inline sal_uInt32 GetLocalOff(); // Lokaler Offset
};
// ----------
// - ResMgr -
// ----------
typedef void (*ResHookProc)( UniString& rStr );
// ----------
// - ResMgr -
// ----------
// Initialisierung
#define RC_NOTYPE 0x00
// Globale Resource
#define RC_GLOBAL 0x01
#define RC_AUTORELEASE 0x02
#define RC_NOTFOUND 0x04
#define RC_FALLBACK_DOWN 0x08
#define RC_FALLBACK_UP 0x10
class Resource;
class ResMgr;
struct ImpRCStack
{
// pResource and pClassRes equal NULL: resource was not loaded
RSHEADER_TYPE * pResource; // pointer to resource
void * pClassRes; // pointer to class specified init data
short Flags; // resource status
void * aResHandle; // Resource-Identifier from InternalResMgr
const Resource* pResObj; // pointer to Resource object
sal_uInt32 nId; // ResId used for error message
ResMgr* pResMgr; // ResMgr for Resource pResObj
void Clear();
void Init( ResMgr * pMgr, const Resource * pObj, sal_uInt32 nId );
};
class TOOLS_DLLPUBLIC ResMgr
{
private:
InternalResMgr* pImpRes;
std::vector< ImpRCStack > aStack; // resource context stack
int nCurStack;
ResMgr* pFallbackResMgr; // fallback ResMgr in case the Resource
// was not contained in this ResMgr
ResMgr* pOriginalResMgr; // the res mgr that fell back to this
// stack level
TOOLS_DLLPRIVATE void incStack();
TOOLS_DLLPRIVATE void decStack();
TOOLS_DLLPRIVATE const ImpRCStack * StackTop( sal_uInt32 nOff = 0 ) const
{
return (((int)nOff >= nCurStack) ? NULL : &aStack[nCurStack-nOff]);
}
TOOLS_DLLPRIVATE void Init( const rtl::OUString& rFileName );
TOOLS_DLLPRIVATE ResMgr( InternalResMgr * pImp );
#ifdef DBG_UTIL
TOOLS_DLLPRIVATE static void RscError_Impl( const sal_Char* pMessage, ResMgr* pResMgr,
RESOURCE_TYPE nRT, sal_uInt32 nId,
std::vector< ImpRCStack >& rResStack, int nDepth );
#endif
// called from within GetResource() if a resource could not be found
TOOLS_DLLPRIVATE ResMgr* CreateFallbackResMgr( const ResId& rId, const Resource* pResource );
// creates a 1k sized buffer set to zero for unfound resources
// used in case RC_NOTFOUND
static void* pEmptyBuffer;
TOOLS_DLLPRIVATE static void* getEmptyBuffer();
// the next two methods are needed to prevent the string hook called
// with the res mgr mutex locked
// like GetString, but doesn't call the string hook
TOOLS_DLLPRIVATE static sal_uInt32 GetStringWithoutHook( UniString& rStr, const BYTE* pStr );
// like ReadString but doesn't call the string hook
TOOLS_DLLPRIVATE UniString ReadStringWithoutHook();
static ResMgr* ImplCreateResMgr( InternalResMgr* pImpl ) { return new ResMgr( pImpl ); }
//No copying
ResMgr(const ResMgr&);
ResMgr& operator=(const ResMgr&);
public:
static void DestroyAllResMgr(); // Wird gerufen, wenn App beendet wird
~ResMgr();
// Sprachabhaengige Ressource Library
static const sal_Char* GetLang( LanguageType& eLanguage, USHORT nPrio = 0 ); //depricated! see "tools/source/rc/resmgr.cxx"
static ResMgr* SearchCreateResMgr( const sal_Char* pPrefixName,
com::sun::star::lang::Locale& rLocale );
static ResMgr* CreateResMgr( const sal_Char* pPrefixName,
com::sun::star::lang::Locale aLocale = com::sun::star::lang::Locale( rtl::OUString(),
rtl::OUString(),
rtl::OUString()));
// Testet ob Resource noch da ist
void TestStack( const Resource * );
// ist Resource verfuegbar
BOOL IsAvailable( const ResId& rId,
const Resource* = NULL) const;
// Resource suchen und laden
BOOL GetResource( const ResId& rId, const Resource * = NULL );
static void * GetResourceSkipHeader( const ResId& rResId, ResMgr ** ppResMgr );
// Kontext freigeben
void PopContext( const Resource* = NULL );
// Resourcezeiger erhoehen
void* Increment( sal_uInt32 nSize );
// Groesse ein Objektes in der Resource
static sal_uInt32 GetObjSize( RSHEADER_TYPE* pHT )
{ return( pHT->GetGlobOff() ); }
// Liefert einen String aus der Resource
static sal_uInt32 GetString( UniString& rStr, const BYTE* pStr );
// Groesse eines Strings in der Resource
static sal_uInt32 GetStringSize( sal_uInt32 nLen )
{ nLen++; return (nLen + nLen%2); }
static sal_uInt32 GetStringSize( const BYTE* pStr );
// return a int64
static sal_uInt64 GetUInt64( void* pDatum );
// Gibt einen long zurueck
static INT32 GetLong( void * pLong );
// return a short
static INT16 GetShort( void * pShort );
// Gibt einen Zeiger auf die Resource zurueck
void * GetClass();
RSHEADER_TYPE * CreateBlock( const ResId & rId );
// Gibt die verbleibende Groesse zurueck
sal_uInt32 GetRemainSize();
const rtl::OUString&GetFileName() const;
INT16 ReadShort();
INT32 ReadLong();
UniString ReadString();
// generate auto help id for current resource stack
ULONG GetAutoHelpId();
static void SetReadStringHook( ResHookProc pProc );
static ResHookProc GetReadStringHook();
static void SetDefaultLocale( const com::sun::star::lang::Locale& rLocale );
};
inline sal_uInt32 RSHEADER_TYPE::GetId()
{
return (sal_uInt32)ResMgr::GetLong( &nId );
}
inline RESOURCE_TYPE RSHEADER_TYPE::GetRT()
{
return (RESOURCE_TYPE)ResMgr::GetLong( &nRT );
}
inline sal_uInt32 RSHEADER_TYPE::GetGlobOff()
{
return (sal_uInt32)ResMgr::GetLong( &nGlobOff );
}
inline sal_uInt32 RSHEADER_TYPE::GetLocalOff()
{
return (sal_uInt32)ResMgr::GetLong( &nLocalOff );
}
#endif // _SV_RESMGR_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.4.16); FILE MERGED 2008/04/01 16:01:28 thb 1.4.16.3: #i85898# Stripping all external header guards 2008/04/01 12:57:22 thb 1.4.16.2: #i85898# Stripping all external header guards 2008/03/28 15:41:12 rt 1.4.16.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: resmgr.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 _TOOLS_RESMGR_HXX
#define _TOOLS_RESMGR_HXX
#include "tools/toolsdllapi.h"
#include <i18npool/lang.h>
#include <tools/string.hxx>
#include <tools/ref.hxx>
#include <tools/resid.hxx>
#include <com/sun/star/lang/Locale.hpp>
#define CREATEVERSIONRESMGR_NAME( Name ) #Name
#define CREATEVERSIONRESMGR( Name ) ResMgr::CreateResMgr( #Name )
#define LOCALE_MAX_FALLBACK 6
#include <vector>
class SvStream;
class InternalResMgr;
// -----------------
// - RSHEADER_TYPE -
// -----------------
// Definition der Struktur, aus denen die Resource aufgebaut ist
struct RSHEADER_TYPE
{
private:
sal_uInt32 nId; // Identifier der Resource
RESOURCE_TYPE nRT; // Resource Typ
sal_uInt32 nGlobOff; // Globaler Offset
sal_uInt32 nLocalOff; // Lokaler Offset
public:
inline sal_uInt32 GetId(); // Identifier der Resource
inline RESOURCE_TYPE GetRT(); // Resource Typ
inline sal_uInt32 GetGlobOff(); // Globaler Offset
inline sal_uInt32 GetLocalOff(); // Lokaler Offset
};
// ----------
// - ResMgr -
// ----------
typedef void (*ResHookProc)( UniString& rStr );
// ----------
// - ResMgr -
// ----------
// Initialisierung
#define RC_NOTYPE 0x00
// Globale Resource
#define RC_GLOBAL 0x01
#define RC_AUTORELEASE 0x02
#define RC_NOTFOUND 0x04
#define RC_FALLBACK_DOWN 0x08
#define RC_FALLBACK_UP 0x10
class Resource;
class ResMgr;
struct ImpRCStack
{
// pResource and pClassRes equal NULL: resource was not loaded
RSHEADER_TYPE * pResource; // pointer to resource
void * pClassRes; // pointer to class specified init data
short Flags; // resource status
void * aResHandle; // Resource-Identifier from InternalResMgr
const Resource* pResObj; // pointer to Resource object
sal_uInt32 nId; // ResId used for error message
ResMgr* pResMgr; // ResMgr for Resource pResObj
void Clear();
void Init( ResMgr * pMgr, const Resource * pObj, sal_uInt32 nId );
};
class TOOLS_DLLPUBLIC ResMgr
{
private:
InternalResMgr* pImpRes;
std::vector< ImpRCStack > aStack; // resource context stack
int nCurStack;
ResMgr* pFallbackResMgr; // fallback ResMgr in case the Resource
// was not contained in this ResMgr
ResMgr* pOriginalResMgr; // the res mgr that fell back to this
// stack level
TOOLS_DLLPRIVATE void incStack();
TOOLS_DLLPRIVATE void decStack();
TOOLS_DLLPRIVATE const ImpRCStack * StackTop( sal_uInt32 nOff = 0 ) const
{
return (((int)nOff >= nCurStack) ? NULL : &aStack[nCurStack-nOff]);
}
TOOLS_DLLPRIVATE void Init( const rtl::OUString& rFileName );
TOOLS_DLLPRIVATE ResMgr( InternalResMgr * pImp );
#ifdef DBG_UTIL
TOOLS_DLLPRIVATE static void RscError_Impl( const sal_Char* pMessage, ResMgr* pResMgr,
RESOURCE_TYPE nRT, sal_uInt32 nId,
std::vector< ImpRCStack >& rResStack, int nDepth );
#endif
// called from within GetResource() if a resource could not be found
TOOLS_DLLPRIVATE ResMgr* CreateFallbackResMgr( const ResId& rId, const Resource* pResource );
// creates a 1k sized buffer set to zero for unfound resources
// used in case RC_NOTFOUND
static void* pEmptyBuffer;
TOOLS_DLLPRIVATE static void* getEmptyBuffer();
// the next two methods are needed to prevent the string hook called
// with the res mgr mutex locked
// like GetString, but doesn't call the string hook
TOOLS_DLLPRIVATE static sal_uInt32 GetStringWithoutHook( UniString& rStr, const BYTE* pStr );
// like ReadString but doesn't call the string hook
TOOLS_DLLPRIVATE UniString ReadStringWithoutHook();
static ResMgr* ImplCreateResMgr( InternalResMgr* pImpl ) { return new ResMgr( pImpl ); }
//No copying
ResMgr(const ResMgr&);
ResMgr& operator=(const ResMgr&);
public:
static void DestroyAllResMgr(); // Wird gerufen, wenn App beendet wird
~ResMgr();
// Sprachabhaengige Ressource Library
static const sal_Char* GetLang( LanguageType& eLanguage, USHORT nPrio = 0 ); //depricated! see "tools/source/rc/resmgr.cxx"
static ResMgr* SearchCreateResMgr( const sal_Char* pPrefixName,
com::sun::star::lang::Locale& rLocale );
static ResMgr* CreateResMgr( const sal_Char* pPrefixName,
com::sun::star::lang::Locale aLocale = com::sun::star::lang::Locale( rtl::OUString(),
rtl::OUString(),
rtl::OUString()));
// Testet ob Resource noch da ist
void TestStack( const Resource * );
// ist Resource verfuegbar
BOOL IsAvailable( const ResId& rId,
const Resource* = NULL) const;
// Resource suchen und laden
BOOL GetResource( const ResId& rId, const Resource * = NULL );
static void * GetResourceSkipHeader( const ResId& rResId, ResMgr ** ppResMgr );
// Kontext freigeben
void PopContext( const Resource* = NULL );
// Resourcezeiger erhoehen
void* Increment( sal_uInt32 nSize );
// Groesse ein Objektes in der Resource
static sal_uInt32 GetObjSize( RSHEADER_TYPE* pHT )
{ return( pHT->GetGlobOff() ); }
// Liefert einen String aus der Resource
static sal_uInt32 GetString( UniString& rStr, const BYTE* pStr );
// Groesse eines Strings in der Resource
static sal_uInt32 GetStringSize( sal_uInt32 nLen )
{ nLen++; return (nLen + nLen%2); }
static sal_uInt32 GetStringSize( const BYTE* pStr );
// return a int64
static sal_uInt64 GetUInt64( void* pDatum );
// Gibt einen long zurueck
static INT32 GetLong( void * pLong );
// return a short
static INT16 GetShort( void * pShort );
// Gibt einen Zeiger auf die Resource zurueck
void * GetClass();
RSHEADER_TYPE * CreateBlock( const ResId & rId );
// Gibt die verbleibende Groesse zurueck
sal_uInt32 GetRemainSize();
const rtl::OUString&GetFileName() const;
INT16 ReadShort();
INT32 ReadLong();
UniString ReadString();
// generate auto help id for current resource stack
ULONG GetAutoHelpId();
static void SetReadStringHook( ResHookProc pProc );
static ResHookProc GetReadStringHook();
static void SetDefaultLocale( const com::sun::star::lang::Locale& rLocale );
};
inline sal_uInt32 RSHEADER_TYPE::GetId()
{
return (sal_uInt32)ResMgr::GetLong( &nId );
}
inline RESOURCE_TYPE RSHEADER_TYPE::GetRT()
{
return (RESOURCE_TYPE)ResMgr::GetLong( &nRT );
}
inline sal_uInt32 RSHEADER_TYPE::GetGlobOff()
{
return (sal_uInt32)ResMgr::GetLong( &nGlobOff );
}
inline sal_uInt32 RSHEADER_TYPE::GetLocalOff()
{
return (sal_uInt32)ResMgr::GetLong( &nLocalOff );
}
#endif // _SV_RESMGR_HXX
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://www.qt.io/licensing. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "jsonwizard.h"
#include "jsonwizardgeneratorfactory.h"
#include <utils/algorithm.h>
#include <utils/qtcassert.h>
#include <QFileInfo>
#include <QMessageBox>
#include <QVariant>
namespace ProjectExplorer {
JsonWizard::JsonWizard(QWidget *parent) :
Utils::Wizard(parent)
{
setMinimumSize(800, 500);
m_expander.registerExtraResolver([this](const QString &name, QString *ret) -> bool {
QVariant v = value(name);
if (v.isValid()) {
if (v.type() == QVariant::Bool)
*ret = v.toBool() ? QLatin1String("true") : QString();
else
*ret = v.toString();
}
return v.isValid();
});
m_expander.registerPrefix("Exists", tr("Check whether a variable exists. Returns \"true\" if it does and an empty string if not."),
[this](const QString &value) -> QString
{
const QString key = QString::fromLatin1("%{") + value + QLatin1Char('}');
return m_expander.expand(key) == key ? QString() : QLatin1String("true");
});
}
JsonWizard::~JsonWizard()
{
qDeleteAll(m_generators);
}
void JsonWizard::addGenerator(JsonWizardGenerator *gen)
{
QTC_ASSERT(gen, return);
QTC_ASSERT(!m_generators.contains(gen), return);
m_generators.append(gen);
}
Utils::MacroExpander *JsonWizard::expander()
{
return &m_expander;
}
void JsonWizard::resetFileList()
{
m_files.clear();
}
JsonWizard::GeneratorFiles JsonWizard::fileList()
{
QString errorMessage;
GeneratorFiles list;
QString targetPath = value(QLatin1String("TargetPath")).toString();
if (targetPath.isEmpty()) {
errorMessage = tr("Could not determine target path. \"TargetPath\" was not set on any page.");
return list;
}
if (m_files.isEmpty()) {
emit preGenerateFiles();
foreach (JsonWizardGenerator *gen, m_generators) {
Core::GeneratedFiles tmp = gen->fileList(&m_expander, value(QStringLiteral("WizardDir")).toString(),
targetPath, &errorMessage);
if (!errorMessage.isEmpty())
break;
list.append(Utils::transform(tmp, [&gen](const Core::GeneratedFile &f)
{ return JsonWizard::GeneratorFile(f, gen); }));
}
if (errorMessage.isEmpty())
m_files = list;
emit postGenerateFiles(m_files);
}
if (!errorMessage.isEmpty()) {
QMessageBox::critical(this, tr("File Generation Failed"),
tr("The wizard failed to generate files.<br>"
"The error message was: \"%1\".").arg(errorMessage));
reject();
return GeneratorFiles();
}
return m_files;
}
QVariant JsonWizard::value(const QString &n) const
{
QVariant v = property(n.toUtf8());
if (v.isValid()) {
if (v.type() == QVariant::String)
return m_expander.expand(v.toString());
else
return v;
}
if (hasField(n))
return field(n); // Can not contain macros!
return QVariant();
}
void JsonWizard::setValue(const QString &key, const QVariant &value)
{
setProperty(key.toUtf8(), value);
}
bool JsonWizard::boolFromVariant(const QVariant &v, Utils::MacroExpander *expander)
{
if (v.type() == QVariant::String)
return !expander->expand(v.toString()).isEmpty();
return v.toBool();
}
void JsonWizard::removeAttributeFromAllFiles(Core::GeneratedFile::Attribute a)
{
for (int i = 0; i < m_files.count(); ++i)
m_files[i].file.setAttributes(m_files.at(i).file.attributes() ^ a);
}
void JsonWizard::accept()
{
Utils::Wizard::accept();
QString errorMessage;
GeneratorFiles list = fileList();
if (list.isEmpty())
return;
emit prePromptForOverwrite(m_files);
JsonWizardGenerator::OverwriteResult overwrite =
JsonWizardGenerator::promptForOverwrite(&list, &errorMessage);
if (overwrite == JsonWizardGenerator::OverwriteError) {
if (!errorMessage.isEmpty())
QMessageBox::warning(this, tr("Failed to Overwrite Files"), errorMessage);
return;
}
emit preFormatFiles(m_files);
if (!JsonWizardGenerator::formatFiles(this, &list, &errorMessage)) {
if (!errorMessage.isEmpty())
QMessageBox::warning(this, tr("Failed to Format Files"), errorMessage);
return;
}
emit preWriteFiles(m_files);
if (!JsonWizardGenerator::writeFiles(this, &list, &errorMessage)) {
if (!errorMessage.isEmpty())
QMessageBox::warning(this, tr("Failed to Write Files"), errorMessage);
return;
}
emit postProcessFiles(m_files);
if (!JsonWizardGenerator::postWrite(this, &list, &errorMessage)) {
if (!errorMessage.isEmpty())
QMessageBox::warning(this, tr("Failed to Post-Process Files"), errorMessage);
return;
}
emit filesReady(m_files);
if (!JsonWizardGenerator::allDone(this, &list, &errorMessage)) {
if (!errorMessage.isEmpty())
QMessageBox::warning(this, tr("Failed to Open Files"), errorMessage);
return;
}
emit allDone(m_files);
}
} // namespace ProjectExplorer
<commit_msg>JsonWizard: Use up-to-date file information<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://www.qt.io/licensing. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "jsonwizard.h"
#include "jsonwizardgeneratorfactory.h"
#include <utils/algorithm.h>
#include <utils/qtcassert.h>
#include <QFileInfo>
#include <QMessageBox>
#include <QVariant>
namespace ProjectExplorer {
JsonWizard::JsonWizard(QWidget *parent) :
Utils::Wizard(parent)
{
setMinimumSize(800, 500);
m_expander.registerExtraResolver([this](const QString &name, QString *ret) -> bool {
QVariant v = value(name);
if (v.isValid()) {
if (v.type() == QVariant::Bool)
*ret = v.toBool() ? QLatin1String("true") : QString();
else
*ret = v.toString();
}
return v.isValid();
});
m_expander.registerPrefix("Exists", tr("Check whether a variable exists. Returns \"true\" if it does and an empty string if not."),
[this](const QString &value) -> QString
{
const QString key = QString::fromLatin1("%{") + value + QLatin1Char('}');
return m_expander.expand(key) == key ? QString() : QLatin1String("true");
});
}
JsonWizard::~JsonWizard()
{
qDeleteAll(m_generators);
}
void JsonWizard::addGenerator(JsonWizardGenerator *gen)
{
QTC_ASSERT(gen, return);
QTC_ASSERT(!m_generators.contains(gen), return);
m_generators.append(gen);
}
Utils::MacroExpander *JsonWizard::expander()
{
return &m_expander;
}
void JsonWizard::resetFileList()
{
m_files.clear();
}
JsonWizard::GeneratorFiles JsonWizard::fileList()
{
QString errorMessage;
GeneratorFiles list;
QString targetPath = value(QLatin1String("TargetPath")).toString();
if (targetPath.isEmpty()) {
errorMessage = tr("Could not determine target path. \"TargetPath\" was not set on any page.");
return list;
}
if (m_files.isEmpty()) {
emit preGenerateFiles();
foreach (JsonWizardGenerator *gen, m_generators) {
Core::GeneratedFiles tmp = gen->fileList(&m_expander, value(QStringLiteral("WizardDir")).toString(),
targetPath, &errorMessage);
if (!errorMessage.isEmpty())
break;
list.append(Utils::transform(tmp, [&gen](const Core::GeneratedFile &f)
{ return JsonWizard::GeneratorFile(f, gen); }));
}
if (errorMessage.isEmpty())
m_files = list;
emit postGenerateFiles(m_files);
}
if (!errorMessage.isEmpty()) {
QMessageBox::critical(this, tr("File Generation Failed"),
tr("The wizard failed to generate files.<br>"
"The error message was: \"%1\".").arg(errorMessage));
reject();
return GeneratorFiles();
}
return m_files;
}
QVariant JsonWizard::value(const QString &n) const
{
QVariant v = property(n.toUtf8());
if (v.isValid()) {
if (v.type() == QVariant::String)
return m_expander.expand(v.toString());
else
return v;
}
if (hasField(n))
return field(n); // Can not contain macros!
return QVariant();
}
void JsonWizard::setValue(const QString &key, const QVariant &value)
{
setProperty(key.toUtf8(), value);
}
bool JsonWizard::boolFromVariant(const QVariant &v, Utils::MacroExpander *expander)
{
if (v.type() == QVariant::String)
return !expander->expand(v.toString()).isEmpty();
return v.toBool();
}
void JsonWizard::removeAttributeFromAllFiles(Core::GeneratedFile::Attribute a)
{
for (int i = 0; i < m_files.count(); ++i)
m_files[i].file.setAttributes(m_files.at(i).file.attributes() ^ a);
}
void JsonWizard::accept()
{
Utils::Wizard::accept();
QString errorMessage;
if (fileList().isEmpty())
return;
emit prePromptForOverwrite(m_files);
JsonWizardGenerator::OverwriteResult overwrite =
JsonWizardGenerator::promptForOverwrite(&m_files, &errorMessage);
if (overwrite == JsonWizardGenerator::OverwriteError) {
if (!errorMessage.isEmpty())
QMessageBox::warning(this, tr("Failed to Overwrite Files"), errorMessage);
return;
}
emit preFormatFiles(m_files);
if (!JsonWizardGenerator::formatFiles(this, &m_files, &errorMessage)) {
if (!errorMessage.isEmpty())
QMessageBox::warning(this, tr("Failed to Format Files"), errorMessage);
return;
}
emit preWriteFiles(m_files);
if (!JsonWizardGenerator::writeFiles(this, &m_files, &errorMessage)) {
if (!errorMessage.isEmpty())
QMessageBox::warning(this, tr("Failed to Write Files"), errorMessage);
return;
}
emit postProcessFiles(m_files);
if (!JsonWizardGenerator::postWrite(this, &m_files, &errorMessage)) {
if (!errorMessage.isEmpty())
QMessageBox::warning(this, tr("Failed to Post-Process Files"), errorMessage);
return;
}
emit filesReady(m_files);
if (!JsonWizardGenerator::allDone(this, &m_files, &errorMessage)) {
if (!errorMessage.isEmpty())
QMessageBox::warning(this, tr("Failed to Open Files"), errorMessage);
return;
}
emit allDone(m_files);
}
} // namespace ProjectExplorer
<|endoftext|> |
<commit_before>#include <assert.h>
#include <cstdio>
#include <set>
#ifndef HAVE_LLVM
#error "This code needs LLVM enabled"
#endif
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Instructions.h>
#include <llvm/Support/SourceMgr.h>
#include <llvm/Support/raw_os_ostream.h>
#include <llvm/IRReader/IRReader.h>
#include <llvm/Bitcode/ReaderWriter.h>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include "llvm/analysis/PointsTo.h"
#include "analysis/PointsTo/PointsToFlowInsensitive.h"
#include "analysis/PointsTo/PointsToFlowSensitive.h"
#include "analysis/PointsTo/Pointer.h"
#include "Utils.h"
using namespace dg;
using namespace dg::analysis::pss;
using llvm::errs;
enum PTType {
FLOW_SENSITIVE = 1,
FLOW_INSENSITIVE,
};
static std::string
getInstName(const llvm::Value *val)
{
std::ostringstream ostr;
llvm::raw_os_ostream ro(ostr);
assert(val);
ro << *val;
ro.flush();
// break the string if it is too long
return ostr.str();
}
static void
printName(PSSNode *node)
{
const char *name = node->getName();
std::string nm;
if (!name) {
if (!node->getUserData<llvm::Value>()) {
printf("%p\n", node);
return;
}
nm = getInstName(node->getUserData<llvm::Value>());
name = nm.c_str();
}
// escape the " character
for (int i = 0; name[i] != '\0'; ++i) {
// crop long names
if (i >= 70) {
printf(" ...");
break;
}
if (name[i] == '"')
putchar('\\');
putchar(name[i]);
}
}
static void
dumpPSSNode(PSSNode *n)
{
const char *name = n->getName();
printf("NODE: ");
printName(n);
if (n->getSize() || n->isHeap() || n->isZeroInitialized())
printf(" [size: %lu, heap: %u, zeroed: %u]",
n->getSize(), n->isHeap(), n->isZeroInitialized());
if (n->pointsTo.empty()) {
puts(" -- no points-to");
return;
} else
putchar('\n');
for (const Pointer& ptr : n->pointsTo) {
printf(" -> ");
printName(ptr.target);
if (ptr.offset.isUnknown())
puts(" + UNKNOWN_OFFSET");
else
printf(" + %lu\n", *ptr.offset);
}
}
static bool verify_ptsets(LLVMPointsToAnalysis *fi, LLVMPointsToAnalysis *fs)
{
bool ok = true;
const std::unordered_map<const llvm::Value *, PSSNode *>& mp = fi->getNodesMap();
for (auto it : mp) {
PSSNode *fsnode = fs->getPointsTo(it.first);
if (!fsnode) {
llvm::errs() << "FS don't have points-to for: " << *it.first << "\n"
<< "but FI has:\n";
dumpPSSNode(it.second);
ok = false;
continue;
}
if (!it.second) {
llvm::errs() << "PSS node is null: " << *it.first << "\n";
ok = false;
continue;
}
for (const Pointer& ptr : fsnode->pointsTo) {
bool found = false;
for (const Pointer& ptr2 : it.second->pointsTo) {
// FIXME: what about UNKNOWN_OFFSETS?
if ((ptr2.target->getUserData<llvm::Value>()
== ptr.target->getUserData<llvm::Value>())
&& (ptr2.offset == ptr.offset)) {
found = true;
break;
}
}
if (!found) {
llvm::errs() << "FS not subset of FI: " << *it.first << "\n";
llvm::errs() << "FI:\n";
dumpPSSNode(it.second);
llvm::errs() << "FS:\n";
dumpPSSNode(fsnode);
llvm::errs() << " ---- \n";
ok = false;
}
}
}
return ok;
}
int main(int argc, char *argv[])
{
llvm::Module *M;
llvm::LLVMContext context;
llvm::SMDiagnostic SMD;
const char *module = nullptr;
unsigned type = FLOW_SENSITIVE | FLOW_INSENSITIVE;
// parse options
for (int i = 1; i < argc; ++i) {
// run only given points-to analysis
if (strcmp(argv[i], "-pta") == 0) {
if (strcmp(argv[i+1], "fs") == 0)
type = FLOW_SENSITIVE;
else if (strcmp(argv[i+1], "fi") == 0)
type = FLOW_INSENSITIVE;
else {
errs() << "Unknown PTA type" << argv[i + 1] << "\n";
abort();
}
/*} else if (strcmp(argv[i], "-v") == 0) {
verbose = true;*/
} else {
module = argv[i];
}
}
if (!module) {
errs() << "Usage: % llvm-pss-compare [-pta fs|fi] IR_module\n";
return 1;
}
#if (LLVM_VERSION_MINOR < 5)
M = llvm::ParseIRFile(module, SMD, context);
#else
auto _M = llvm::parseIRFile(module, SMD, context);
// _M is unique pointer, we need to get Module *
M = &*_M;
#endif
debug::TimeMeasure tm;
LLVMPointsToAnalysis *PTAfs;
LLVMPointsToAnalysis *PTAfi;
if (type & FLOW_INSENSITIVE) {
PTAfi = new LLVMPointsToAnalysisImpl<analysis::pss::PointsToFlowInsensitive>(M);
tm.start();
PTAfi->run();
tm.stop();
tm.report("INFO: Points-to flow-insensitive analysis took");
}
if (type & FLOW_SENSITIVE) {
PTAfs = new LLVMPointsToAnalysisImpl<analysis::pss::PointsToFlowSensitive>(M);
tm.start();
PTAfs->run();
tm.stop();
tm.report("INFO: Points-to flow-sensitive analysis took");
}
int ret = 0;
if (type == (FLOW_SENSITIVE | FLOW_INSENSITIVE)) {
ret = !verify_ptsets(PTAfi, PTAfs);
if (ret == 0)
llvm::errs() << "FS is a subset of FI, all OK\n";
}
return ret;
}
<commit_msg>llvm-pss-compare: handle UNKNOWN_OFFSET<commit_after>#include <assert.h>
#include <cstdio>
#include <set>
#ifndef HAVE_LLVM
#error "This code needs LLVM enabled"
#endif
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Instructions.h>
#include <llvm/Support/SourceMgr.h>
#include <llvm/Support/raw_os_ostream.h>
#include <llvm/IRReader/IRReader.h>
#include <llvm/Bitcode/ReaderWriter.h>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include "llvm/analysis/PointsTo.h"
#include "analysis/PointsTo/PointsToFlowInsensitive.h"
#include "analysis/PointsTo/PointsToFlowSensitive.h"
#include "analysis/PointsTo/Pointer.h"
#include "Utils.h"
using namespace dg;
using namespace dg::analysis::pss;
using llvm::errs;
enum PTType {
FLOW_SENSITIVE = 1,
FLOW_INSENSITIVE,
};
static std::string
getInstName(const llvm::Value *val)
{
std::ostringstream ostr;
llvm::raw_os_ostream ro(ostr);
assert(val);
ro << *val;
ro.flush();
// break the string if it is too long
return ostr.str();
}
static void
printName(PSSNode *node)
{
const char *name = node->getName();
std::string nm;
if (!name) {
if (!node->getUserData<llvm::Value>()) {
printf("%p\n", node);
return;
}
nm = getInstName(node->getUserData<llvm::Value>());
name = nm.c_str();
}
// escape the " character
for (int i = 0; name[i] != '\0'; ++i) {
// crop long names
if (i >= 70) {
printf(" ...");
break;
}
if (name[i] == '"')
putchar('\\');
putchar(name[i]);
}
}
static void
dumpPSSNode(PSSNode *n)
{
const char *name = n->getName();
printf("NODE: ");
printName(n);
if (n->getSize() || n->isHeap() || n->isZeroInitialized())
printf(" [size: %lu, heap: %u, zeroed: %u]",
n->getSize(), n->isHeap(), n->isZeroInitialized());
if (n->pointsTo.empty()) {
puts(" -- no points-to");
return;
} else
putchar('\n');
for (const Pointer& ptr : n->pointsTo) {
printf(" -> ");
printName(ptr.target);
if (ptr.offset.isUnknown())
puts(" + UNKNOWN_OFFSET");
else
printf(" + %lu\n", *ptr.offset);
}
}
static bool verify_ptsets(LLVMPointsToAnalysis *fi, LLVMPointsToAnalysis *fs)
{
bool ok = true;
const std::unordered_map<const llvm::Value *, PSSNode *>& mp = fi->getNodesMap();
for (auto it : mp) {
PSSNode *fsnode = fs->getPointsTo(it.first);
if (!fsnode) {
llvm::errs() << "FS don't have points-to for: " << *it.first << "\n"
<< "but FI has:\n";
dumpPSSNode(it.second);
ok = false;
continue;
}
if (!it.second) {
llvm::errs() << "PSS node is null: " << *it.first << "\n";
ok = false;
continue;
}
for (const Pointer& ptr : fsnode->pointsTo) {
bool found = false;
for (const Pointer& ptr2 : it.second->pointsTo) {
// either the pointer is there or
// FS has (target, offset) and FI has (target, UNKNOWN_OFFSET),
// than everything is fine. The other case (FS has UNKNOWN_OFFSET)
// we don't consider here, since that should not happen
if ((ptr2.target->getUserData<llvm::Value>()
== ptr.target->getUserData<llvm::Value>())
&& (ptr2.offset == ptr.offset ||
ptr2.offset.isUnknown()
/* || ptr.offset.isUnknown()*/)) {
found = true;
break;
}
}
if (!found) {
llvm::errs() << "FS not subset of FI: " << *it.first << "\n";
llvm::errs() << "FI:\n";
dumpPSSNode(it.second);
llvm::errs() << "FS:\n";
dumpPSSNode(fsnode);
llvm::errs() << " ---- \n";
ok = false;
}
}
}
return ok;
}
int main(int argc, char *argv[])
{
llvm::Module *M;
llvm::LLVMContext context;
llvm::SMDiagnostic SMD;
const char *module = nullptr;
unsigned type = FLOW_SENSITIVE | FLOW_INSENSITIVE;
// parse options
for (int i = 1; i < argc; ++i) {
// run only given points-to analysis
if (strcmp(argv[i], "-pta") == 0) {
if (strcmp(argv[i+1], "fs") == 0)
type = FLOW_SENSITIVE;
else if (strcmp(argv[i+1], "fi") == 0)
type = FLOW_INSENSITIVE;
else {
errs() << "Unknown PTA type" << argv[i + 1] << "\n";
abort();
}
/*} else if (strcmp(argv[i], "-v") == 0) {
verbose = true;*/
} else {
module = argv[i];
}
}
if (!module) {
errs() << "Usage: % llvm-pss-compare [-pta fs|fi] IR_module\n";
return 1;
}
#if (LLVM_VERSION_MINOR < 5)
M = llvm::ParseIRFile(module, SMD, context);
#else
auto _M = llvm::parseIRFile(module, SMD, context);
// _M is unique pointer, we need to get Module *
M = &*_M;
#endif
debug::TimeMeasure tm;
LLVMPointsToAnalysis *PTAfs;
LLVMPointsToAnalysis *PTAfi;
if (type & FLOW_INSENSITIVE) {
PTAfi = new LLVMPointsToAnalysisImpl<analysis::pss::PointsToFlowInsensitive>(M);
tm.start();
PTAfi->run();
tm.stop();
tm.report("INFO: Points-to flow-insensitive analysis took");
}
if (type & FLOW_SENSITIVE) {
PTAfs = new LLVMPointsToAnalysisImpl<analysis::pss::PointsToFlowSensitive>(M);
tm.start();
PTAfs->run();
tm.stop();
tm.report("INFO: Points-to flow-sensitive analysis took");
}
int ret = 0;
if (type == (FLOW_SENSITIVE | FLOW_INSENSITIVE)) {
ret = !verify_ptsets(PTAfi, PTAfs);
if (ret == 0)
llvm::errs() << "FS is a subset of FI, all OK\n";
}
return ret;
}
<|endoftext|> |
<commit_before>#include <vector>
#include <fstream>
#include "board.hpp"
#include "config.hpp"
#include "log.hpp"
namespace roadagain
{
Log::Log(int y, int x, BoardState stone) : y(y), x(x), stone(stone)
{
}
void log_records(std::vector<Log>& logs, BoardState winner)
{
int size = logs.size();
std::ofstream log_file(Config::instance().log_file().c_str());
for (int i = 0; i < size; i++){
if (logs[i].stone == BLACK){
log_file << 'B';
}
else {
log_file << 'W';
}
log_file << ' ' << (char)('a' + logs[i].x);
log_file << ' ' << logs[i].y;
log_file << '\n';
}
if (winner == BLACK){
log_file << "Winner is Blackn";
}
else if (winner == WHITE){
log_file << "Winner is Whiten";
}
else {
log_file << "Drawn";
}
log_file << '\n';
log_file.close();
}
}
<commit_msg>Check log is available<commit_after>#include <vector>
#include <fstream>
#include "board.hpp"
#include "config.hpp"
#include "log.hpp"
namespace roadagain
{
Log::Log(int y, int x, BoardState stone) : y(y), x(x), stone(stone)
{
}
void log_records(std::vector<Log>& logs, BoardState winner)
{
Config& config = Config::instance();
if (config.log_file().empty()){
return;
}
int size = logs.size();
std::ofstream log_file(config.log_file().c_str());
for (int i = 0; i < size; i++){
if (logs[i].stone == BLACK){
log_file << 'B';
}
else {
log_file << 'W';
}
log_file << ' ' << (char)('a' + logs[i].x);
log_file << ' ' << logs[i].y;
log_file << '\n';
}
if (winner == BLACK){
log_file << "Winner is Blackn";
}
else if (winner == WHITE){
log_file << "Winner is Whiten";
}
else {
log_file << "Drawn";
}
log_file << '\n';
log_file.close();
}
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
#include "sync/impl/apple/network_reachability_observer.hpp"
#if NETWORK_REACHABILITY_AVAILABLE
using namespace realm;
namespace {
static NetworkReachabilityStatus reachability_status_for_flags(SCNetworkReachabilityFlags flags)
{
if (!(flags & kSCNetworkReachabilityFlagsReachable))
return NotReachable;
if (flags & kSCNetworkReachabilityFlagsConnectionRequired) {
if (!(flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) ||
(flags & kSCNetworkReachabilityFlagsInterventionRequired)) {
return NotReachable;
}
}
NetworkReachabilityStatus status = ReachableViaWiFi;
#if TARGET_OS_IPHONE
if (flags & kSCNetworkReachabilityFlagsIsWWAN) {
status = ReachableViaWWAN;
}
#endif
return status;
}
static void reachability_callback(SCNetworkReachabilityRef, SCNetworkReachabilityFlags, void* info)
{
auto callback = reinterpret_cast<std::function<void ()> *>(info);
(*callback)();
}
} // (anonymous namespace)
NetworkReachabilityObserver::NetworkReachabilityObserver(util::Optional<std::string> hostname,
std::function<void (const NetworkReachabilityStatus)> handler)
: m_callback_queue(dispatch_queue_create("io.realm.sync.reachability", DISPATCH_QUEUE_SERIAL))
, m_reachability_callback([=]() { reachability_changed(); })
, m_change_handler(std::move(handler))
{
if (hostname) {
m_reachability_ref = util::adoptCF(SCNetworkReachabilityCreateWithName(nullptr, hostname->c_str()));
} else {
struct sockaddr zeroAddress = {};
zeroAddress.sa_len = sizeof(zeroAddress);
zeroAddress.sa_family = AF_INET;
m_reachability_ref = util::adoptCF(SCNetworkReachabilityCreateWithAddress(nullptr, &zeroAddress));
}
}
NetworkReachabilityObserver::~NetworkReachabilityObserver()
{
stop_observing();
dispatch_release(m_callback_queue);
}
NetworkReachabilityStatus NetworkReachabilityObserver::reachability_status() const
{
SCNetworkReachabilityFlags flags;
if (SCNetworkReachabilityGetFlags(m_reachability_ref.get(), &flags)) {
return reachability_status_for_flags(flags);
}
return NotReachable;
}
bool NetworkReachabilityObserver::start_observing()
{
m_previous_status = reachability_status();
SCNetworkReachabilityContext context = {0, &m_reachability_callback, nullptr, nullptr, nullptr};
if (!SCNetworkReachabilitySetCallback(m_reachability_ref.get(), reachability_callback, &context)) {
return false;
}
if (!SCNetworkReachabilitySetDispatchQueue(m_reachability_ref.get(), m_callback_queue)) {
return false;
}
return true;
}
void NetworkReachabilityObserver::stop_observing()
{
SCNetworkReachabilitySetDispatchQueue(m_reachability_ref.get(), nullptr);
SCNetworkReachabilitySetCallback(m_reachability_ref.get(), nullptr, nullptr);
// Wait for all previously-enqueued blocks to execute to guarantee that
// no callback will be called after returning from this method
dispatch_sync(m_callback_queue, ^{});
}
void NetworkReachabilityObserver::reachability_changed()
{
auto current_status = reachability_status();
// When observing reachability of the specific host the callback might be called
// several times (because of DNS queries) with the same reachability flags while
// the caller should be notified only when the reachability status is really changed.
if (current_status != m_previous_status) {
m_change_handler(current_status);
m_previous_status = current_status;
}
}
#endif
<commit_msg>remove extra braces<commit_after>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
#include "sync/impl/apple/network_reachability_observer.hpp"
#if NETWORK_REACHABILITY_AVAILABLE
using namespace realm;
namespace {
static NetworkReachabilityStatus reachability_status_for_flags(SCNetworkReachabilityFlags flags)
{
if (!(flags & kSCNetworkReachabilityFlagsReachable))
return NotReachable;
if (flags & kSCNetworkReachabilityFlagsConnectionRequired) {
if (!(flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) ||
(flags & kSCNetworkReachabilityFlagsInterventionRequired))
return NotReachable;
}
NetworkReachabilityStatus status = ReachableViaWiFi;
#if TARGET_OS_IPHONE
if (flags & kSCNetworkReachabilityFlagsIsWWAN) {
status = ReachableViaWWAN;
}
#endif
return status;
}
static void reachability_callback(SCNetworkReachabilityRef, SCNetworkReachabilityFlags, void* info)
{
auto callback = reinterpret_cast<std::function<void ()> *>(info);
(*callback)();
}
} // (anonymous namespace)
NetworkReachabilityObserver::NetworkReachabilityObserver(util::Optional<std::string> hostname,
std::function<void (const NetworkReachabilityStatus)> handler)
: m_callback_queue(dispatch_queue_create("io.realm.sync.reachability", DISPATCH_QUEUE_SERIAL))
, m_reachability_callback([=]() { reachability_changed(); })
, m_change_handler(std::move(handler))
{
if (hostname) {
m_reachability_ref = util::adoptCF(SCNetworkReachabilityCreateWithName(nullptr, hostname->c_str()));
} else {
struct sockaddr zeroAddress = {};
zeroAddress.sa_len = sizeof(zeroAddress);
zeroAddress.sa_family = AF_INET;
m_reachability_ref = util::adoptCF(SCNetworkReachabilityCreateWithAddress(nullptr, &zeroAddress));
}
}
NetworkReachabilityObserver::~NetworkReachabilityObserver()
{
stop_observing();
dispatch_release(m_callback_queue);
}
NetworkReachabilityStatus NetworkReachabilityObserver::reachability_status() const
{
SCNetworkReachabilityFlags flags;
if (SCNetworkReachabilityGetFlags(m_reachability_ref.get(), &flags)) {
return reachability_status_for_flags(flags);
}
return NotReachable;
}
bool NetworkReachabilityObserver::start_observing()
{
m_previous_status = reachability_status();
SCNetworkReachabilityContext context = {0, &m_reachability_callback, nullptr, nullptr, nullptr};
if (!SCNetworkReachabilitySetCallback(m_reachability_ref.get(), reachability_callback, &context)) {
return false;
}
if (!SCNetworkReachabilitySetDispatchQueue(m_reachability_ref.get(), m_callback_queue)) {
return false;
}
return true;
}
void NetworkReachabilityObserver::stop_observing()
{
SCNetworkReachabilitySetDispatchQueue(m_reachability_ref.get(), nullptr);
SCNetworkReachabilitySetCallback(m_reachability_ref.get(), nullptr, nullptr);
// Wait for all previously-enqueued blocks to execute to guarantee that
// no callback will be called after returning from this method
dispatch_sync(m_callback_queue, ^{});
}
void NetworkReachabilityObserver::reachability_changed()
{
auto current_status = reachability_status();
// When observing reachability of the specific host the callback might be called
// several times (because of DNS queries) with the same reachability flags while
// the caller should be notified only when the reachability status is really changed.
if (current_status != m_previous_status) {
m_change_handler(current_status);
m_previous_status = current_status;
}
}
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (c) 1998-2001, Index Data.
* See the file LICENSE for details.
*
* $Id: yaz-socket-manager.cpp,v 1.20 2003-07-25 19:27:36 adam Exp $
*/
#include <assert.h>
#ifdef WIN32
#include <winsock.h>
#else
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#endif
#include <errno.h>
#include <string.h>
#include <yaz/log.h>
#include <yaz++/socket-manager.h>
Yaz_SocketManager::YazSocketEntry **Yaz_SocketManager::lookupObserver(
IYazSocketObserver *observer)
{
YazSocketEntry **se;
for (se = &m_observers; *se; se = &(*se)->next)
if ((*se)->observer == observer)
break;
return se;
}
void Yaz_SocketManager::addObserver(int fd, IYazSocketObserver *observer)
{
YazSocketEntry *se;
se = *lookupObserver(observer);
if (!se)
{
se = new YazSocketEntry;
se->next= m_observers;
m_observers = se;
se->observer = observer;
}
se->fd = fd;
se->mask = 0;
se->last_activity = 0;
se->timeout = 0;
}
void Yaz_SocketManager::deleteObserver(IYazSocketObserver *observer)
{
YazSocketEntry **se = lookupObserver(observer);
if (*se)
{
removeEvent (observer);
YazSocketEntry *se_tmp = *se;
*se = (*se)->next;
delete se_tmp;
}
}
void Yaz_SocketManager::deleteObservers()
{
YazSocketEntry *se = m_observers;
while (se)
{
YazSocketEntry *se_next = se->next;
delete se;
se = se_next;
}
m_observers = 0;
}
void Yaz_SocketManager::maskObserver(IYazSocketObserver *observer, int mask)
{
YazSocketEntry *se;
yaz_log(m_log, "obs=%p read=%d write=%d except=%d", observer,
mask & YAZ_SOCKET_OBSERVE_READ,
mask & YAZ_SOCKET_OBSERVE_WRITE,
mask & YAZ_SOCKET_OBSERVE_EXCEPT);
se = *lookupObserver(observer);
if (se)
se->mask = mask;
}
void Yaz_SocketManager::timeoutObserver(IYazSocketObserver *observer,
unsigned timeout)
{
YazSocketEntry *se;
se = *lookupObserver(observer);
if (se)
se->timeout = timeout;
}
int Yaz_SocketManager::processEvent()
{
YazSocketEntry *p;
YazSocketEvent *event = getEvent();
unsigned timeout = 0;
yaz_log (m_log, "Yaz_SocketManager::processEvent manager=%p", this);
if (event)
{
event->observer->socketNotify(event->event);
delete event;
return 1;
}
fd_set in, out, except;
int res;
int max = 0;
int no = 0;
FD_ZERO(&in);
FD_ZERO(&out);
FD_ZERO(&except);
time_t now = time(0);
for (p = m_observers; p; p = p->next)
{
int fd = p->fd;
if (p->mask)
no++;
if (p->mask & YAZ_SOCKET_OBSERVE_READ)
{
yaz_log (m_log, "Yaz_SocketManager::select fd=%d read", fd);
FD_SET(fd, &in);
}
if (p->mask & YAZ_SOCKET_OBSERVE_WRITE)
{
yaz_log (m_log, "Yaz_SocketManager::select fd=%d write", fd);
FD_SET(fd, &out);
}
if (p->mask & YAZ_SOCKET_OBSERVE_EXCEPT)
{
yaz_log (m_log, "Yaz_SocketManager::select fd=%d except", fd);
FD_SET(fd, &except);
}
if (fd > max)
max = fd;
if (p->timeout)
{
unsigned timeout_this;
timeout_this = p->timeout;
if (p->last_activity)
timeout_this -= now - p->last_activity;
else
p->last_activity = now;
if (timeout_this < 1 || timeout_this > 2147483646)
timeout_this = 1;
if (!timeout || timeout_this < timeout)
timeout = timeout_this;
p->timeout_this = timeout_this;
yaz_log (m_log, "Yaz_SocketManager::select timeout_this=%d",
p->timeout_this);
}
}
if (!no)
{
yaz_log (m_log, "no pending events return 0");
if (!m_observers)
yaz_log (m_log, "no observers");
return 0;
}
struct timeval to;
to.tv_sec = timeout;
to.tv_usec = 0;
yaz_log (m_log, "Yaz_SocketManager::select begin no=%d timeout=%d",
no, timeout);
while ((res = select(max + 1, &in, &out, &except, timeout ? &to : 0)) < 0)
if (errno != EINTR)
{
yaz_log (LOG_LOG|LOG_WARN, "select");
return -1;
}
now = time(0);
for (p = m_observers; p; p = p->next)
{
int fd = p->fd;
int mask = 0;
if (FD_ISSET(fd, &in))
mask |= YAZ_SOCKET_OBSERVE_READ;
if (FD_ISSET(fd, &out))
mask |= YAZ_SOCKET_OBSERVE_WRITE;
if (FD_ISSET(fd, &except))
mask |= YAZ_SOCKET_OBSERVE_EXCEPT;
if (mask)
{
YazSocketEvent *event = new YazSocketEvent;
p->last_activity = now;
event->observer = p->observer;
event->event = mask;
putEvent (event);
}
else if (res == 0 && p->timeout && p->timeout_this == timeout)
{
YazSocketEvent *event = new YazSocketEvent;
assert (p->last_activity);
yaz_log (m_log, "timeout, now = %ld last_activity=%ld timeout=%d",
now, p->last_activity, p->timeout);
p->last_activity = now;
event->observer = p->observer;
event->event = YAZ_SOCKET_OBSERVE_TIMEOUT;
putEvent (event);
}
}
if ((event = getEvent()))
{
event->observer->socketNotify(event->event);
delete event;
return 1;
}
yaz_log (LOG_WARN, "unhandled event in processEvent");
return 1;
}
// n p n p ...... n p n p
// front back
void Yaz_SocketManager::putEvent(YazSocketEvent *event)
{
// put in back of queue
if (m_queue_back)
{
m_queue_back->prev = event;
assert (m_queue_front);
}
else
{
assert (!m_queue_front);
m_queue_front = event;
}
event->next = m_queue_back;
event->prev = 0;
m_queue_back = event;
}
Yaz_SocketManager::YazSocketEvent *Yaz_SocketManager::getEvent()
{
// get from front of queue
YazSocketEvent *event = m_queue_front;
if (!event)
return 0;
assert (m_queue_back);
m_queue_front = event->prev;
if (m_queue_front)
{
assert (m_queue_back);
m_queue_front->next = 0;
}
else
m_queue_back = 0;
return event;
}
void Yaz_SocketManager::removeEvent(IYazSocketObserver *observer)
{
YazSocketEvent *ev = m_queue_back;
while (ev)
{
YazSocketEvent *ev_next = ev->next;
if (observer == ev->observer)
{
if (ev->prev)
ev->prev->next = ev->next;
else
m_queue_back = ev->next;
if (ev->next)
ev->next->prev = ev->prev;
else
m_queue_front = ev->prev;
delete ev;
}
ev = ev_next;
}
}
Yaz_SocketManager::Yaz_SocketManager()
{
m_observers = 0;
m_queue_front = 0;
m_queue_back = 0;
m_log = LOG_DEBUG;
}
Yaz_SocketManager::~Yaz_SocketManager()
{
deleteObservers();
}
<commit_msg>Timeout event was not fired when select returned I/O (res > 0).<commit_after>/*
* Copyright (c) 1998-2001, Index Data.
* See the file LICENSE for details.
*
* $Id: yaz-socket-manager.cpp,v 1.21 2003-12-16 11:26:14 adam Exp $
*/
#include <assert.h>
#ifdef WIN32
#include <winsock.h>
#else
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#endif
#include <errno.h>
#include <string.h>
#include <yaz/log.h>
#include <yaz++/socket-manager.h>
Yaz_SocketManager::YazSocketEntry **Yaz_SocketManager::lookupObserver(
IYazSocketObserver *observer)
{
YazSocketEntry **se;
for (se = &m_observers; *se; se = &(*se)->next)
if ((*se)->observer == observer)
break;
return se;
}
void Yaz_SocketManager::addObserver(int fd, IYazSocketObserver *observer)
{
YazSocketEntry *se;
se = *lookupObserver(observer);
if (!se)
{
se = new YazSocketEntry;
se->next= m_observers;
m_observers = se;
se->observer = observer;
}
se->fd = fd;
se->mask = 0;
se->last_activity = 0;
se->timeout = 0;
}
void Yaz_SocketManager::deleteObserver(IYazSocketObserver *observer)
{
YazSocketEntry **se = lookupObserver(observer);
if (*se)
{
removeEvent (observer);
YazSocketEntry *se_tmp = *se;
*se = (*se)->next;
delete se_tmp;
}
}
void Yaz_SocketManager::deleteObservers()
{
YazSocketEntry *se = m_observers;
while (se)
{
YazSocketEntry *se_next = se->next;
delete se;
se = se_next;
}
m_observers = 0;
}
void Yaz_SocketManager::maskObserver(IYazSocketObserver *observer, int mask)
{
YazSocketEntry *se;
yaz_log(m_log, "obs=%p read=%d write=%d except=%d", observer,
mask & YAZ_SOCKET_OBSERVE_READ,
mask & YAZ_SOCKET_OBSERVE_WRITE,
mask & YAZ_SOCKET_OBSERVE_EXCEPT);
se = *lookupObserver(observer);
if (se)
se->mask = mask;
}
void Yaz_SocketManager::timeoutObserver(IYazSocketObserver *observer,
unsigned timeout)
{
YazSocketEntry *se;
se = *lookupObserver(observer);
if (se)
se->timeout = timeout;
}
int Yaz_SocketManager::processEvent()
{
YazSocketEntry *p;
YazSocketEvent *event = getEvent();
unsigned timeout = 0;
yaz_log (m_log, "Yaz_SocketManager::processEvent manager=%p", this);
if (event)
{
event->observer->socketNotify(event->event);
delete event;
return 1;
}
fd_set in, out, except;
int res;
int max = 0;
int no = 0;
FD_ZERO(&in);
FD_ZERO(&out);
FD_ZERO(&except);
time_t now = time(0);
for (p = m_observers; p; p = p->next)
{
int fd = p->fd;
if (p->mask)
no++;
if (p->mask & YAZ_SOCKET_OBSERVE_READ)
{
yaz_log (m_log, "Yaz_SocketManager::select fd=%d read", fd);
FD_SET(fd, &in);
}
if (p->mask & YAZ_SOCKET_OBSERVE_WRITE)
{
yaz_log (m_log, "Yaz_SocketManager::select fd=%d write", fd);
FD_SET(fd, &out);
}
if (p->mask & YAZ_SOCKET_OBSERVE_EXCEPT)
{
yaz_log (m_log, "Yaz_SocketManager::select fd=%d except", fd);
FD_SET(fd, &except);
}
if (fd > max)
max = fd;
if (p->timeout)
{
unsigned timeout_this;
timeout_this = p->timeout;
if (p->last_activity)
timeout_this -= now - p->last_activity;
else
p->last_activity = now;
if (timeout_this < 1 || timeout_this > 2147483646)
timeout_this = 1;
if (!timeout || timeout_this < timeout)
timeout = timeout_this;
p->timeout_this = timeout_this;
yaz_log (m_log, "Yaz_SocketManager::select timeout_this=%d",
p->timeout_this);
}
}
if (!no)
{
yaz_log (m_log, "no pending events return 0");
if (!m_observers)
yaz_log (m_log, "no observers");
return 0;
}
struct timeval to;
to.tv_sec = timeout;
to.tv_usec = 0;
yaz_log (m_log, "Yaz_SocketManager::select begin no=%d timeout=%d",
no, timeout);
while ((res = select(max + 1, &in, &out, &except, timeout ? &to : 0)) < 0)
if (errno != EINTR)
{
yaz_log (LOG_LOG|LOG_WARN, "select");
return -1;
}
now = time(0);
for (p = m_observers; p; p = p->next)
{
int fd = p->fd;
int mask = 0;
if (FD_ISSET(fd, &in))
mask |= YAZ_SOCKET_OBSERVE_READ;
if (FD_ISSET(fd, &out))
mask |= YAZ_SOCKET_OBSERVE_WRITE;
if (FD_ISSET(fd, &except))
mask |= YAZ_SOCKET_OBSERVE_EXCEPT;
if (mask)
{
YazSocketEvent *event = new YazSocketEvent;
p->last_activity = now;
event->observer = p->observer;
event->event = mask;
putEvent (event);
yaz_log (m_log, "putEvent I/O mask=%d", mask);
}
else if (p->timeout && (now - p->last_activity) >= p->timeout)
{
YazSocketEvent *event = new YazSocketEvent;
assert (p->last_activity);
yaz_log (m_log, "putEvent timeout, now = %ld last_activity=%ld timeout=%d",
now, p->last_activity, p->timeout);
p->last_activity = now;
event->observer = p->observer;
event->event = YAZ_SOCKET_OBSERVE_TIMEOUT;
putEvent (event);
}
}
if ((event = getEvent()))
{
event->observer->socketNotify(event->event);
delete event;
return 1;
}
yaz_log (LOG_WARN, "unhandled event in processEvent");
return 1;
}
// n p n p ...... n p n p
// front back
void Yaz_SocketManager::putEvent(YazSocketEvent *event)
{
// put in back of queue
if (m_queue_back)
{
m_queue_back->prev = event;
assert (m_queue_front);
}
else
{
assert (!m_queue_front);
m_queue_front = event;
}
event->next = m_queue_back;
event->prev = 0;
m_queue_back = event;
}
Yaz_SocketManager::YazSocketEvent *Yaz_SocketManager::getEvent()
{
// get from front of queue
YazSocketEvent *event = m_queue_front;
if (!event)
return 0;
assert (m_queue_back);
m_queue_front = event->prev;
if (m_queue_front)
{
assert (m_queue_back);
m_queue_front->next = 0;
}
else
m_queue_back = 0;
return event;
}
void Yaz_SocketManager::removeEvent(IYazSocketObserver *observer)
{
YazSocketEvent *ev = m_queue_back;
while (ev)
{
YazSocketEvent *ev_next = ev->next;
if (observer == ev->observer)
{
if (ev->prev)
ev->prev->next = ev->next;
else
m_queue_back = ev->next;
if (ev->next)
ev->next->prev = ev->prev;
else
m_queue_front = ev->prev;
delete ev;
}
ev = ev_next;
}
}
Yaz_SocketManager::Yaz_SocketManager()
{
m_observers = 0;
m_queue_front = 0;
m_queue_back = 0;
m_log = LOG_DEBUG;
}
Yaz_SocketManager::~Yaz_SocketManager()
{
deleteObservers();
}
<|endoftext|> |
<commit_before>#include "vga/vga.h"
#include "lib/common/attribute_macros.h"
#include "lib/armv7m/exceptions.h"
#include "lib/stm32f4xx/adv_timer.h"
#include "lib/stm32f4xx/ahb.h"
#include "lib/stm32f4xx/apb.h"
#include "lib/stm32f4xx/dma.h"
#include "lib/stm32f4xx/gpio.h"
#include "lib/stm32f4xx/interrupts.h"
#include "lib/stm32f4xx/rcc.h"
#include "lib/stm32f4xx/syscfg.h"
using stm32f4xx::AdvTimer;
using stm32f4xx::AhbPeripheral;
using stm32f4xx::ApbPeripheral;
using stm32f4xx::Dma;
using stm32f4xx::dma2;
using stm32f4xx::Gpio;
using stm32f4xx::gpioc;
using stm32f4xx::gpioe;
using stm32f4xx::Interrupt;
using stm32f4xx::rcc;
using stm32f4xx::syscfg;
using stm32f4xx::tim8;
using stm32f4xx::Word;
#define IN_SCAN_RAM SECTION(".vga_scan_ram")
namespace vga {
/*******************************************************************************
* Driver state and configuration.
*/
// Used to adjust size of scan_buffer, below.
static constexpr unsigned max_pixels_per_line = 800;
// The current mode, set by select_mode.
static VideoMode const *current_mode;
// [0, current_mode.video_end_line). Updated at front porch interrupt.
static unsigned volatile current_line;
/*
* The vertical timing state. This is a Gray code and the bits have meaning.
* See the inspector functions below.
*/
enum class State {
blank = 0b00,
starting = 0b01,
active = 0b11,
finishing = 0b10,
};
// Should we be producing a video signal?
inline bool is_displayed_state(State s) {
return static_cast<unsigned>(s) & 0b10;
}
// Should we be rendering a scanline?
inline bool is_rendered_state(State s) {
return static_cast<unsigned>(s) & 0b01;
}
// Finally, the actual variable.
static State volatile state;
// This is the DMA source for scan-out, filled during pend_sv.
ALIGNED(4) IN_SCAN_RAM
static unsigned char scan_buffer[max_pixels_per_line + 4];
/*******************************************************************************
* Driver API.
*/
void init() {
// Turn on I/O compensation cell to reduce noise on power supply.
rcc.enable_clock(ApbPeripheral::syscfg);
syscfg.write_cmpcr(syscfg.read_cmpcr().with_cmp_pd(true));
// Turn a bunch of stuff on.
rcc.enable_clock(ApbPeripheral::tim8);
rcc.enable_clock(AhbPeripheral::gpioc); // Sync signals
rcc.enable_clock(AhbPeripheral::gpioe); // Video
rcc.enable_clock(AhbPeripheral::dma2);
// Hold TIM8 in reset until we do mode-setting.
rcc.enter_reset(ApbPeripheral::tim8);
set_irq_priority(Interrupt::tim8_cc, 0);
set_exception_priority(armv7m::Exception::pend_sv, 0xFF);
video_off();
}
void video_off() {
// Tristate all output ports.
gpioc.set_mode((1 << 6) | (1 << 7), Gpio::Mode::input);
gpioc.set_pull((1 << 6) | (1 << 7), Gpio::Pull::none);
gpioe.set_mode(0xFF00, Gpio::Mode::input);
gpioe.set_pull(0xFF00, Gpio::Pull::none);
}
void video_on() {
// Configure PC6 to produce hsync using TIM8_CH1
gpioc.set_alternate_function(Gpio::p6, 3);
gpioc.set_output_type(Gpio::p6, Gpio::OutputType::push_pull);
gpioc.set_output_speed(Gpio::p6, Gpio::OutputSpeed::fast_50mhz);
gpioc.set_mode(Gpio::p6, Gpio::Mode::alternate);
// Configure PC7 as GPIO output.
gpioc.set_output_type(Gpio::p7, Gpio::OutputType::push_pull);
gpioc.set_output_speed(Gpio::p7, Gpio::OutputSpeed::fast_50mhz);
gpioc.set_mode(Gpio::p7, Gpio::Mode::gpio);
// Configure the high byte of port E for parallel video.
// Using 100MHz output speed gets slightly sharper transitions than 50MHz.
gpioe.set_output_type(0xFF00, Gpio::OutputType::push_pull);
gpioe.set_output_speed(0xFF00, Gpio::OutputSpeed::high_100mhz);
gpioe.set_mode(0xFF00, Gpio::Mode::gpio);
}
void select_mode(VideoMode const &mode) {
// Disable outputs during mode change.
video_off();
// Place TIM8 in reset, stopping all timing, and disable its interrupt.
rcc.enter_reset(ApbPeripheral::tim8);
disable_irq(Interrupt::tim8_cc);
// Busy-wait for pending DMA to complete.
while (dma2.stream1.read_cr().get_en());
// TODO: apply buffered changes.
// Switch to new CPU clock settings.
rcc.configure_clocks(mode.clock_config);
// Configure TIM8 for horizontal sync generation.
rcc.leave_reset(ApbPeripheral::tim8);
tim8.write_psc(4 - 1); // Count in pixels, 1 pixel = 4 CCLK
tim8.write_arr(mode.line_pixels - 1);
tim8.write_ccr1(mode.sync_pixels);
tim8.write_ccr2(mode.sync_pixels + mode.back_porch_pixels - mode.video_lead);
tim8.write_ccr3(
mode.sync_pixels + mode.back_porch_pixels + mode.video_pixels);
tim8.write_ccmr1(AdvTimer::ccmr1_value_t()
.with_oc1m(AdvTimer::OcMode::pwm1)
.with_cc1s(AdvTimer::ccmr1_value_t::cc1s_t::output));
tim8.write_bdtr(AdvTimer::bdtr_value_t()
.with_ossr(true)
.with_moe(true));
tim8.write_ccer(AdvTimer::ccer_value_t()
.with_cc1e(true)
.with_cc1p(
mode.hsync_polarity == VideoMode::Polarity::negative));
tim8.write_dier(AdvTimer::dier_value_t()
.with_cc2ie(true) // Interrupt at start of active video.
.with_cc3ie(true)); // Interrupt at end of active video.
// Note: TIM8 is still not running.
switch (mode.vsync_polarity) {
case VideoMode::Polarity::positive: gpioc.clear(1 << 7); break;
case VideoMode::Polarity::negative: gpioc.set (1 << 7); break;
}
// Scribble over scan buffer to help catch bugs.
for (unsigned i = 0; i < sizeof(scan_buffer) - 4; i += 2) {
scan_buffer[i] = 0xFF;
scan_buffer[i + 1] = 0x00;
}
// But the final four must be black.
scan_buffer[sizeof(scan_buffer) - 4] = 0;
scan_buffer[sizeof(scan_buffer) - 3] = 0;
scan_buffer[sizeof(scan_buffer) - 2] = 0;
scan_buffer[sizeof(scan_buffer) - 1] = 0;
// Set up global state.
current_mode = &mode; // TODO(cbiffle): copy into RAM for less jitter?
current_line = 0;
// Start the timer.
enable_irq(Interrupt::tim8_cc);
tim8.write_cr1(tim8.read_cr1().with_cen(true));
// Enable display and sync signals.
video_on();
}
} // namespace vga
/*******************************************************************************
* Horizontal timing interrupt.
*/
extern "C" void stm32f4xx_tim8_cc_handler() {
// We have to clear our interrupt flags, or this will recur.
auto sr = tim8.read_sr();
tim8.write_sr(sr.with_cc2if(false).with_cc3if(false));
vga::VideoMode const &mode = *vga::current_mode;
if (sr.get_cc2if()) {
// CC2 indicates start of active video (end of back porch).
// This only matters in displayed states.
if (is_displayed_state(vga::state)) {
// Clear stream 1 flags (lifcr is a write-1-to-clear register).
dma2.write_lifcr(Dma::lifcr_value_t()
.with_cdmeif1(true)
.with_cteif1(true)
.with_chtif1(true)
.with_ctcif1(true));
auto &st = dma2.stream1;
// Shut off stream 1 by zeroing CR.
// TODO(cbiffle): necessary?
st.write_cr(Dma::Stream::cr_value_t());
// Prepare to transfer pixels as words, plus the final black word.
st.write_ndtr(mode.video_pixels / 4 + 1);
// Set addresses. Note that we're using memory as the peripheral side.
// This DMA controller is a little odd.
st.write_par(reinterpret_cast<Word>(&vga::scan_buffer));
st.write_m0ar(0x40021015); // High byte of GPIOE ODR (hack hack)
// Configure FIFO.
st.write_fcr(Dma::Stream::fcr_value_t()
.with_fth(Dma::Stream::fcr_value_t::fth_t::quarter)
.with_dmdis(true)
.with_feie(false));
/*
* Configure and enable the DMA stream. The configuration used here
* deserves more discussion.
*
* As noted above, our "peripheral" is RAM and our "memory" is the GPIO
* unit. In memory-to-memory mode (which we use) the distinction is
* not useful, since the peripherals are memory-mapped; the controller
* insists that "peripheral" be source and "memory" be destination in that
* mode. The key here is that the transfer runs at full speed. On the
* STM32F407 the transfer will not exceed one unit per 4 AHB cycles. The
* reason for this is not obvious.
*
* Address incrementation on this chip is independent from whether an
* address is considered "peripheral" or "memory." Here we auto-increment
* the peripheral address (to walk through the scan buffer) while leaving
* the memory address fixed (at the appropriate byte of the GPIO port).
*
* Because we're using memory-to-memory, the hardware enforces several
* restrictions:
*
* 1. We're stuck using DMA2. DMA1 can't do it.
* 2. We're required to use the FIFO -- direct mode is verboten.
* 3. We can't use circular mode. (Double-buffer mode appears permitted,
* but I haven't tried it.)
*
* Fortunately we can tie the FIFO to a tree by giving it a really low
* threshold level.
*
* I have not experimented with burst modes, but I suspect they'll make
* the timing less regular.
*
* Note that the priority (pl field) is only used for arbitration between
* streams of the same DMA controller. The STM32F4 does not provide any
* control over the AHB matrix arbitration scheme, unlike (say) the NXP
* LPC1788. Shame, that. It means we have to be very careful about our
* use of the bus matrix during scan-out.
*/
typedef Dma::Stream::cr_value_t cr_t;
st.write_cr(Dma::Stream::cr_value_t()
// Originally chosen to play nice with TIM8. Now, arbitrary.
.with_chsel(7)
.with_pl(cr_t::pl_t::very_high)
.with_dir(cr_t::dir_t::memory_to_memory)
// Input settings:
.with_pburst(Dma::Stream::BurstSize::single)
.with_psize(Dma::Stream::TransferSize::word)
.with_pinc(true)
// Output settings:
.with_mburst(Dma::Stream::BurstSize::single)
.with_msize(Dma::Stream::TransferSize::byte)
.with_minc(false)
// Look at all these options we don't use:
.with_dbm(false)
.with_pincos(false)
.with_circ(false)
.with_pfctrl(false)
.with_tcie(false)
.with_htie(false)
.with_teie(false)
.with_dmeie(false)
// Finally, enable.
.with_en(true));
} else {
// Not displayed state. Ensure pins are black.
// TODO(cbiffle): almost certainly not necessary...
gpioe.clear(0xFF00);
}
}
if (sr.get_cc3if()) {
// CC3 indicates end of active video (start of front porch).
unsigned line = vga::current_line;
if (line == 0) {
// Start of frame! Time to stop displaying pixels.
vga::state = vga::State::blank;
// TODO(cbiffle): suppress video output.
// TODO(cbiffle): latch configuration changes.
} else if (line == mode.vsync_start_line
|| line == mode.vsync_end_line) {
// Either edge of vsync pulse.
gpioc.toggle(Gpio::p7);
} else if (line == static_cast<unsigned short>(mode.video_start_line - 1)) {
// Time to start generating the first scan buffer.
vga::state = vga::State::starting;
} else if (line == mode.video_start_line) {
// Time to start output.
vga::state = vga::State::active;
} else if (line == static_cast<unsigned short>(mode.video_end_line - 1)) {
// Time to stop rendering new scan buffers.
vga::state = vga::State::finishing;
line = static_cast<unsigned>(-1); // Make line roll over to zero.
}
vga::current_line = line + 1;
if (is_rendered_state(vga::state)) {
// TODO(cbiffle): PendSV to kick off a buffer flip and rasterization.
}
}
}
<commit_msg>vga: clean up some TODOs and paranoid code.<commit_after>#include "vga/vga.h"
#include "lib/common/attribute_macros.h"
#include "lib/armv7m/exceptions.h"
#include "lib/stm32f4xx/adv_timer.h"
#include "lib/stm32f4xx/ahb.h"
#include "lib/stm32f4xx/apb.h"
#include "lib/stm32f4xx/dma.h"
#include "lib/stm32f4xx/gpio.h"
#include "lib/stm32f4xx/interrupts.h"
#include "lib/stm32f4xx/rcc.h"
#include "lib/stm32f4xx/syscfg.h"
using stm32f4xx::AdvTimer;
using stm32f4xx::AhbPeripheral;
using stm32f4xx::ApbPeripheral;
using stm32f4xx::Dma;
using stm32f4xx::dma2;
using stm32f4xx::Gpio;
using stm32f4xx::gpioc;
using stm32f4xx::gpioe;
using stm32f4xx::Interrupt;
using stm32f4xx::rcc;
using stm32f4xx::syscfg;
using stm32f4xx::tim8;
using stm32f4xx::Word;
#define IN_SCAN_RAM SECTION(".vga_scan_ram")
namespace vga {
/*******************************************************************************
* Driver state and configuration.
*/
// Used to adjust size of scan_buffer, below.
static constexpr unsigned max_pixels_per_line = 800;
// The current mode, set by select_mode.
static VideoMode const *current_mode;
// [0, current_mode.video_end_line). Updated at front porch interrupt.
static unsigned volatile current_line;
/*
* The vertical timing state. This is a Gray code and the bits have meaning.
* See the inspector functions below.
*/
enum class State {
blank = 0b00,
starting = 0b01,
active = 0b11,
finishing = 0b10,
};
// Should we be producing a video signal?
inline bool is_displayed_state(State s) {
return static_cast<unsigned>(s) & 0b10;
}
// Should we be rendering a scanline?
inline bool is_rendered_state(State s) {
return static_cast<unsigned>(s) & 0b01;
}
// Finally, the actual variable.
static State volatile state;
// This is the DMA source for scan-out, filled during pend_sv.
ALIGNED(4) IN_SCAN_RAM
static unsigned char scan_buffer[max_pixels_per_line + 4];
/*******************************************************************************
* Driver API.
*/
void init() {
// Turn on I/O compensation cell to reduce noise on power supply.
rcc.enable_clock(ApbPeripheral::syscfg);
syscfg.write_cmpcr(syscfg.read_cmpcr().with_cmp_pd(true));
// Turn a bunch of stuff on.
rcc.enable_clock(ApbPeripheral::tim8);
rcc.enable_clock(AhbPeripheral::gpioc); // Sync signals
rcc.enable_clock(AhbPeripheral::gpioe); // Video
rcc.enable_clock(AhbPeripheral::dma2);
// Hold TIM8 in reset until we do mode-setting.
rcc.enter_reset(ApbPeripheral::tim8);
set_irq_priority(Interrupt::tim8_cc, 0);
set_exception_priority(armv7m::Exception::pend_sv, 0xFF);
video_off();
}
void video_off() {
// Tristate all output ports.
gpioc.set_mode((1 << 6) | (1 << 7), Gpio::Mode::input);
gpioc.set_pull((1 << 6) | (1 << 7), Gpio::Pull::none);
gpioe.set_mode(0xFF00, Gpio::Mode::input);
gpioe.set_pull(0xFF00, Gpio::Pull::none);
}
void video_on() {
// Configure PC6 to produce hsync using TIM8_CH1
gpioc.set_alternate_function(Gpio::p6, 3);
gpioc.set_output_type(Gpio::p6, Gpio::OutputType::push_pull);
gpioc.set_output_speed(Gpio::p6, Gpio::OutputSpeed::fast_50mhz);
gpioc.set_mode(Gpio::p6, Gpio::Mode::alternate);
// Configure PC7 as GPIO output.
gpioc.set_output_type(Gpio::p7, Gpio::OutputType::push_pull);
gpioc.set_output_speed(Gpio::p7, Gpio::OutputSpeed::fast_50mhz);
gpioc.set_mode(Gpio::p7, Gpio::Mode::gpio);
// Configure the high byte of port E for parallel video.
// Using 100MHz output speed gets slightly sharper transitions than 50MHz.
gpioe.set_output_type(0xFF00, Gpio::OutputType::push_pull);
gpioe.set_output_speed(0xFF00, Gpio::OutputSpeed::high_100mhz);
gpioe.set_mode(0xFF00, Gpio::Mode::gpio);
}
void select_mode(VideoMode const &mode) {
// Disable outputs during mode change.
video_off();
// Place TIM8 in reset, stopping all timing, and disable its interrupt.
rcc.enter_reset(ApbPeripheral::tim8);
disable_irq(Interrupt::tim8_cc);
// Busy-wait for pending DMA to complete.
while (dma2.stream1.read_cr().get_en());
// TODO: apply buffered changes.
// Switch to new CPU clock settings.
rcc.configure_clocks(mode.clock_config);
// Configure TIM8 for horizontal sync generation.
rcc.leave_reset(ApbPeripheral::tim8);
tim8.write_psc(4 - 1); // Count in pixels, 1 pixel = 4 CCLK
tim8.write_arr(mode.line_pixels - 1);
tim8.write_ccr1(mode.sync_pixels);
tim8.write_ccr2(mode.sync_pixels + mode.back_porch_pixels - mode.video_lead);
tim8.write_ccr3(
mode.sync_pixels + mode.back_porch_pixels + mode.video_pixels);
tim8.write_ccmr1(AdvTimer::ccmr1_value_t()
.with_oc1m(AdvTimer::OcMode::pwm1)
.with_cc1s(AdvTimer::ccmr1_value_t::cc1s_t::output));
tim8.write_bdtr(AdvTimer::bdtr_value_t()
.with_ossr(true)
.with_moe(true));
tim8.write_ccer(AdvTimer::ccer_value_t()
.with_cc1e(true)
.with_cc1p(
mode.hsync_polarity == VideoMode::Polarity::negative));
tim8.write_dier(AdvTimer::dier_value_t()
.with_cc2ie(true) // Interrupt at start of active video.
.with_cc3ie(true)); // Interrupt at end of active video.
// Note: TIM8 is still not running.
switch (mode.vsync_polarity) {
case VideoMode::Polarity::positive: gpioc.clear(1 << 7); break;
case VideoMode::Polarity::negative: gpioc.set (1 << 7); break;
}
// Scribble over scan buffer to help catch bugs.
for (unsigned i = 0; i < sizeof(scan_buffer) - 4; i += 2) {
scan_buffer[i] = 0xFF;
scan_buffer[i + 1] = 0x00;
}
// But the final four must be black.
scan_buffer[sizeof(scan_buffer) - 4] = 0;
scan_buffer[sizeof(scan_buffer) - 3] = 0;
scan_buffer[sizeof(scan_buffer) - 2] = 0;
scan_buffer[sizeof(scan_buffer) - 1] = 0;
// Set up global state.
current_mode = &mode; // TODO(cbiffle): copy into RAM for less jitter?
current_line = 0;
// Start the timer.
enable_irq(Interrupt::tim8_cc);
tim8.write_cr1(tim8.read_cr1().with_cen(true));
// Enable display and sync signals.
video_on();
}
} // namespace vga
/*******************************************************************************
* Horizontal timing interrupt.
*/
extern "C" void stm32f4xx_tim8_cc_handler() {
// We have to clear our interrupt flags, or this will recur.
auto sr = tim8.read_sr();
tim8.write_sr(sr.with_cc2if(false).with_cc3if(false));
vga::VideoMode const &mode = *vga::current_mode;
if (sr.get_cc2if()) {
// CC2 indicates start of active video (end of back porch).
// This only matters in displayed states.
if (is_displayed_state(vga::state)) {
// Clear stream 1 flags (lifcr is a write-1-to-clear register).
dma2.write_lifcr(Dma::lifcr_value_t()
.with_cdmeif1(true)
.with_cteif1(true)
.with_chtif1(true)
.with_ctcif1(true));
auto &st = dma2.stream1;
// Prepare to transfer pixels as words, plus the final black word.
st.write_ndtr(mode.video_pixels / 4 + 1);
// Set addresses. Note that we're using memory as the peripheral side.
// This DMA controller is a little odd.
st.write_par(reinterpret_cast<Word>(&vga::scan_buffer));
st.write_m0ar(0x40021015); // High byte of GPIOE ODR (hack hack)
// Configure FIFO.
st.write_fcr(Dma::Stream::fcr_value_t()
.with_fth(Dma::Stream::fcr_value_t::fth_t::quarter)
.with_dmdis(true)
.with_feie(false));
/*
* Configure and enable the DMA stream. The configuration used here
* deserves more discussion.
*
* As noted above, our "peripheral" is RAM and our "memory" is the GPIO
* unit. In memory-to-memory mode (which we use) the distinction is
* not useful, since the peripherals are memory-mapped; the controller
* insists that "peripheral" be source and "memory" be destination in that
* mode. The key here is that the transfer runs at full speed. On the
* STM32F407 the transfer will not exceed one unit per 4 AHB cycles. The
* reason for this is not obvious.
*
* Address incrementation on this chip is independent from whether an
* address is considered "peripheral" or "memory." Here we auto-increment
* the peripheral address (to walk through the scan buffer) while leaving
* the memory address fixed (at the appropriate byte of the GPIO port).
*
* Because we're using memory-to-memory, the hardware enforces several
* restrictions:
*
* 1. We're stuck using DMA2. DMA1 can't do it.
* 2. We're required to use the FIFO -- direct mode is verboten.
* 3. We can't use circular mode. (Double-buffer mode appears permitted,
* but I haven't tried it.)
*
* Fortunately we can tie the FIFO to a tree by giving it a really low
* threshold level.
*
* I have not experimented with burst modes, but I suspect they'll make
* the timing less regular.
*
* Note that the priority (pl field) is only used for arbitration between
* streams of the same DMA controller. The STM32F4 does not provide any
* control over the AHB matrix arbitration scheme, unlike (say) the NXP
* LPC1788. Shame, that. It means we have to be very careful about our
* use of the bus matrix during scan-out.
*/
typedef Dma::Stream::cr_value_t cr_t;
st.write_cr(Dma::Stream::cr_value_t()
// Originally chosen to play nice with TIM8. Now, arbitrary.
.with_chsel(7)
.with_pl(cr_t::pl_t::very_high)
.with_dir(cr_t::dir_t::memory_to_memory)
// Input settings:
.with_pburst(Dma::Stream::BurstSize::single)
.with_psize(Dma::Stream::TransferSize::word)
.with_pinc(true)
// Output settings:
.with_mburst(Dma::Stream::BurstSize::single)
.with_msize(Dma::Stream::TransferSize::byte)
.with_minc(false)
// Look at all these options we don't use:
.with_dbm(false)
.with_pincos(false)
.with_circ(false)
.with_pfctrl(false)
.with_tcie(false)
.with_htie(false)
.with_teie(false)
.with_dmeie(false)
// Finally, enable.
.with_en(true));
}
}
if (sr.get_cc3if()) {
// CC3 indicates end of active video (start of front porch).
unsigned line = vga::current_line;
if (line == 0) {
// Start of frame! Time to stop displaying pixels.
vga::state = vga::State::blank;
// TODO(cbiffle): latch configuration changes.
} else if (line == mode.vsync_start_line
|| line == mode.vsync_end_line) {
// Either edge of vsync pulse.
gpioc.toggle(Gpio::p7);
} else if (line == static_cast<unsigned short>(mode.video_start_line - 1)) {
// Time to start generating the first scan buffer.
vga::state = vga::State::starting;
} else if (line == mode.video_start_line) {
// Time to start output.
vga::state = vga::State::active;
} else if (line == static_cast<unsigned short>(mode.video_end_line - 1)) {
// Time to stop rendering new scan buffers.
vga::state = vga::State::finishing;
line = static_cast<unsigned>(-1); // Make line roll over to zero.
}
vga::current_line = line + 1;
if (is_rendered_state(vga::state)) {
// TODO(cbiffle): PendSV to kick off a buffer flip and rasterization.
}
}
}
<|endoftext|> |
<commit_before>// tOleInPlaceSite.cpp: implementation of the tOleInPlaceSite class.
//
//////////////////////////////////////////////////////////////////////
#include "tOleInPlaceSite.h"
#include "tOleHandler.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
BOOL g_fSwitchingActive=FALSE;
/*
* tOleInPlaceSite::tOleInPlaceSite
* tOleInPlaceSite::~tOleInPlaceSite
*
* Parameters (Constructor):
* pTen PCTenant of the tenant we're in.
* pUnkOuter LPUNKNOWN to which we delegate.
*/
tOleInPlaceSite::tOleInPlaceSite(class tOleHandler *pTen
, LPUNKNOWN pUnkOuter)
{
m_cRef=0;
m_pTen=pTen;
m_pUnkOuter=pUnkOuter;
m_oleinplaceframe = new tOleInPlaceFrame(m_pTen->m_hWnd);
return;
}
tOleInPlaceSite::~tOleInPlaceSite(void)
{
return;
}
/*
* tOleInPlaceSite::QueryInterface
* tOleInPlaceSite::AddRef
* tOleInPlaceSite::Release
*
* Purpose:
* IUnknown members for tOleInPlaceSite object.
*/
STDMETHODIMP tOleInPlaceSite::QueryInterface(REFIID riid
, LPVOID *ppv)
{
return m_pUnkOuter->QueryInterface(riid, ppv);
}
STDMETHODIMP_(ULONG) tOleInPlaceSite::AddRef(void)
{
++m_cRef;
return m_pUnkOuter->AddRef();
}
STDMETHODIMP_(ULONG) tOleInPlaceSite::Release(void)
{
--m_cRef;
return m_pUnkOuter->Release();
}
/*
* tOleInPlaceActiveObject::GetWindow
*
* Purpose:
* Retrieves the handle of the window associated with the object
* on which this interface is implemented.
*
* Parameters:
* phWnd HWND * in which to store the window handle.
*
* Return Value:
* HRESULT NOERROR if successful, E_FAIL if there is no
* window.
*/
STDMETHODIMP tOleInPlaceSite::GetWindow(HWND *phWnd)
{
*phWnd=m_pTen->m_hWnd;
return NOERROR;
}
/*
* tOleInPlaceActiveObject::ContextSensitiveHelp
*
* Purpose:
* Instructs the object on which this interface is implemented to
* enter or leave a context-sensitive help mode.
*
* Parameters:
* fEnterMode BOOL TRUE to enter the mode, FALSE otherwise.
*
* Return Value:
* HRESULT NOERROR
*/
STDMETHODIMP tOleInPlaceSite::ContextSensitiveHelp
(BOOL fEnterMode)
{
return E_NOTIMPL;
}
/*
* tOleInPlaceSite::CanInPlaceActivate
*
* Purpose:
* Answers the server whether or not we can currently in-place
* activate its object. By implementing this interface we say
* that we support in-place activation, but through this function
* we indicate whether the object can currently be activated
* in-place. Iconic aspects, for example, cannot, meaning we
* return S_FALSE.
*
* Parameters:
* None
*
* Return Value:
* HRESULT NOERROR if we can in-place activate the object
* in this site, S_FALSE if not.
*/
STDMETHODIMP tOleInPlaceSite::CanInPlaceActivate(void)
{
if (DVASPECT_CONTENT!=m_pTen->m_fe.dwAspect)
return ResultFromScode(S_FALSE);
return NOERROR;
}
/*
* tOleInPlaceSite::OnInPlaceActivate
*
* Purpose:
* Informs the container that an object is being activated in-place
* such that the container can prepare appropriately. The
* container does not, however, make any user interface changes at
* this point. See OnUIActivate.
*
* Parameters:
* None
*
* Return Value:
* HRESULT NOERROR or an appropriate error code.
*/
STDMETHODIMP tOleInPlaceSite::OnInPlaceActivate(void)
{
//CHAPTER24MOD
m_pTen->m_fPendingDeactivate=FALSE;
//End CHAPTER24MOD
//m_pIOleIPObject is our in-place flag.
m_pTen->m_pObj->QueryInterface(IID_IOleInPlaceObject
, (PPVOID)&m_pTen->m_pIOleIPObject);
return NOERROR;
}
/*
* tOleInPlaceSite::OnInPlaceDeactivate
*
* Purpose:
* Notifies the container that the object has deactivated itself
* from an in-place state. Opposite of OnInPlaceActivate. The
* container does not change any UI at this point.
*
* Parameters:
* None
*
* Return Value:
* HRESULT NOERROR or an appropriate error code.
*/
STDMETHODIMP tOleInPlaceSite::OnInPlaceDeactivate(void)
{
/*
* Since we don't have an Undo command, we can tell the object
* right away to discard its Undo state.
*/
m_pTen->Activate(OLEIVERB_DISCARDUNDOSTATE, NULL);
ReleaseInterface(m_pTen->m_pIOleIPObject);
return NOERROR;
}
/*
* tOleInPlaceSite::OnUIActivate
*
* Purpose:
* Informs the container that the object is going to start munging
* around with user interface, like replacing the menu. The
* container should remove any relevant UI in preparation.
*
* Parameters:
* None
*
* Return Value:
* HRESULT NOERROR or an appropriate error code.
*/
STDMETHODIMP tOleInPlaceSite::OnUIActivate(void)
{
//CHAPTER24MOD
m_pTen->m_fPendingDeactivate=FALSE;
//End CHAPTER24MOD
/*
* Change the currently selected tenant in the page. This
* will UIDeactivate the currently UI Active tenant.
*/
g_fSwitchingActive=TRUE;
//m_pTen->m_pPG->m_pPageCur->SwitchActiveTenant(m_pTen);
g_fSwitchingActive=FALSE;
return NOERROR;
}
/*
* tOleInPlaceSite::OnUIDeactivate
*
* Purpose:
* Informs the container that the object is deactivating its
* in-place user interface at which time the container may
* reinstate its own. Opposite of OnUIActivate.
*
* Parameters:
* fUndoable BOOL indicating if the object will actually
* perform an Undo if the container calls
* ReactivateAndUndo.
*
* Return Value:
* HRESULT NOERROR or an appropriate error code.
*/
STDMETHODIMP tOleInPlaceSite::OnUIDeactivate(BOOL fUndoable)
{
MSG msg;
/*
* Ignore this notification if we're switching between
* multiple active objects.
*/
if (g_fSwitchingActive)
return NOERROR;
//If in shutdown (NULL storage), don't check messages.
/* if (NULL==m_pTen->m_pIStorage)
{
g_pFR->ReinstateUI();
return NOERROR;
}*/
//If there's a pending double-click, delay showing our UI
/* if (!PeekMessage(&msg, pDoc->Window(), WM_LBUTTONDBLCLK
, WM_LBUTTONDBLCLK, PM_NOREMOVE | PM_NOYIELD))
{
//Turn everything back on.
g_pFR->ReinstateUI();
}
else*/
return NOERROR;
}
/*
* tOleInPlaceSite::DeactivateAndUndo
*
* Purpose:
* If immediately after activation the object does an Undo, the
* action being undone is the activation itself, and this call
* informs the container that this is, in fact, what happened.
* The container should call IOleInPlaceObject::UIDeactivate.
*
* Parameters:
* None
*
* Return Value:
* HRESULT NOERROR or an appropriate error code.
*/
STDMETHODIMP tOleInPlaceSite::DeactivateAndUndo(void)
{
//CHAPTER24MOD
/*
* Note that we don't pay attention to the locking
* from IOleControlSite::LockInPlaceActive since only
* the object calls this function and should know
* that it's going to be deactivated.
*/
//End CHAPTER24MOD
m_pTen->m_pIOleIPObject->InPlaceDeactivate();
return NOERROR;
}
/*
* tOleInPlaceSite::DiscardUndoState
*
* Purpose:
* Informs the container that something happened in the object
* that means the container should discard any undo information
* it currently maintains for the object.
*
* Parameters:
* None
*
* Return Value:
* HRESULT NOERROR or an appropriate error code.
*/
STDMETHODIMP tOleInPlaceSite::DiscardUndoState(void)
{
return ResultFromScode(E_NOTIMPL);
}
/*
* tOleInPlaceSite::GetWindowContext
*
* Purpose:
* Provides an in-place object with pointers to the frame and
* document level in-place interfaces (IOleInPlaceFrame and
* IOleInPlaceUIWindow) such that the object can do border
* negotiation and so forth. Also requests the position and
* clipping rectangles of the object in the container and a
* pointer to an OLEINPLACEFRAME info structure which contains
* accelerator information.
*
* Note that the two interfaces this call returns are not
* available through QueryInterface on IOleInPlaceSite since they
* live with the frame and document, but not the site.
*
* Parameters:
* ppIIPFrame LPOLEINPLACEFRAME * in which to return the
* AddRef'd pointer to the container's
* IOleInPlaceFrame.
* ppIIPUIWindow LPOLEINPLACEUIWINDOW * in which to return
* the AddRef'd pointer to the container document's
* IOleInPlaceUIWindow.
* prcPos LPRECT in which to store the object's position.
* prcClip LPRECT in which to store the object's visible
* region.
* pFI LPOLEINPLACEFRAMEINFO to fill with accelerator
* stuff.
*
* Return Value:
* HRESULT NOERROR
*/
STDMETHODIMP tOleInPlaceSite::GetWindowContext
(LPOLEINPLACEFRAME *ppIIPFrame, LPOLEINPLACEUIWINDOW
*ppIIPUIWindow, LPRECT prcPos, LPRECT prcClip
, LPOLEINPLACEFRAMEINFO pFI)
{
RECTL rcl;
*ppIIPUIWindow=NULL;
*ppIIPFrame=m_oleinplaceframe;
m_oleinplaceframe->AddRef();
GetClientRect(m_pTen->m_hWnd, prcPos);
GetClientRect(m_pTen->m_hWnd, prcClip);
/* *ppIIPFrame=(LPOLEINPLACEFRAME)g_pFR;
g_pFR->AddRef();*/
/* if (NULL!=pDoc)
{
pDoc->QueryInterface(IID_IOleInPlaceUIWindow
, (PPVOID)ppIIPUIWindow);
}*/
//Now get the rectangles and frame information.
/*m_pTen->RectGet(&rcl, TRUE);
RECTFROMRECTL(*prcPos, rcl);
0
//Include scroll position here.
OffsetRect(prcPos, -(int)m_pTen->m_pPG->m_xPos
, -(int)m_pTen->m_pPG->m_yPos);
SetRect(prcClip, 0, 0, 32767, 32767);
*/
pFI->cb=sizeof(OLEINPLACEFRAMEINFO);
pFI->fMDIApp=FALSE;
pFI->hwndFrame=m_pTen->m_hWnd;
pFI->haccel=NULL;
pFI->cAccelEntries=0;
return NOERROR;
}
/*
* tOleInPlaceSite::Scroll
*
* Purpose:
* Asks the container to scroll the document, and thus the object,
* by the given amounts in the sz parameter.
*
* Parameters:
* sz SIZE containing signed horizontal and vertical
* extents by which the container should scroll.
* These are in device units.
*
* Return Value:
* HRESULT NOERROR
*/
STDMETHODIMP tOleInPlaceSite::Scroll(SIZE sz)
{
/*int x, y;
x=m_pTen->m_pPG->m_xPos+sz.cx;
y=m_pTen->m_pPG->m_yPos+sz.cy;
SendScrollPosition(m_pTen->m_hWnd, WM_HSCROLL, x);
SendScrollPosition(m_pTen->m_hWnd, WM_VSCROLL, y);*/
return NOERROR;
}
/*
* tOleInPlaceSite::OnPosRectChange
*
* Purpose:
* Informs the container that the in-place object was resized.
* The container must call IOleInPlaceObject::SetObjectRects.
* This does not change the site's rectangle in any case.
*
* Parameters:
* prcPos LPCRECT containing the new size of the object.
*
* Return Value:
* HRESULT NOERROR
*/
STDMETHODIMP tOleInPlaceSite::OnPosRectChange(LPCRECT prcPos)
{
if (NULL!=prcPos)
m_pTen->m_rcPos=*prcPos;
m_pTen->UpdateInPlaceObjectRects(prcPos, FALSE);
return NOERROR;
}
<commit_msg>Fixed: object position in IupOleControl.<commit_after>// tOleInPlaceSite.cpp: implementation of the tOleInPlaceSite class.
//
//////////////////////////////////////////////////////////////////////
#include "tOleInPlaceSite.h"
#include "tOleHandler.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
BOOL g_fSwitchingActive=FALSE;
/*
* tOleInPlaceSite::tOleInPlaceSite
* tOleInPlaceSite::~tOleInPlaceSite
*
* Parameters (Constructor):
* pTen PCTenant of the tenant we're in.
* pUnkOuter LPUNKNOWN to which we delegate.
*/
tOleInPlaceSite::tOleInPlaceSite(class tOleHandler *pTen
, LPUNKNOWN pUnkOuter)
{
m_cRef=0;
m_pTen=pTen;
m_pUnkOuter=pUnkOuter;
m_oleinplaceframe = new tOleInPlaceFrame(m_pTen->m_hWnd);
return;
}
tOleInPlaceSite::~tOleInPlaceSite(void)
{
return;
}
/*
* tOleInPlaceSite::QueryInterface
* tOleInPlaceSite::AddRef
* tOleInPlaceSite::Release
*
* Purpose:
* IUnknown members for tOleInPlaceSite object.
*/
STDMETHODIMP tOleInPlaceSite::QueryInterface(REFIID riid
, LPVOID *ppv)
{
return m_pUnkOuter->QueryInterface(riid, ppv);
}
STDMETHODIMP_(ULONG) tOleInPlaceSite::AddRef(void)
{
++m_cRef;
return m_pUnkOuter->AddRef();
}
STDMETHODIMP_(ULONG) tOleInPlaceSite::Release(void)
{
--m_cRef;
return m_pUnkOuter->Release();
}
/*
* tOleInPlaceActiveObject::GetWindow
*
* Purpose:
* Retrieves the handle of the window associated with the object
* on which this interface is implemented.
*
* Parameters:
* phWnd HWND * in which to store the window handle.
*
* Return Value:
* HRESULT NOERROR if successful, E_FAIL if there is no
* window.
*/
STDMETHODIMP tOleInPlaceSite::GetWindow(HWND *phWnd)
{
*phWnd=m_pTen->m_hWnd;
return NOERROR;
}
/*
* tOleInPlaceActiveObject::ContextSensitiveHelp
*
* Purpose:
* Instructs the object on which this interface is implemented to
* enter or leave a context-sensitive help mode.
*
* Parameters:
* fEnterMode BOOL TRUE to enter the mode, FALSE otherwise.
*
* Return Value:
* HRESULT NOERROR
*/
STDMETHODIMP tOleInPlaceSite::ContextSensitiveHelp
(BOOL fEnterMode)
{
return E_NOTIMPL;
}
/*
* tOleInPlaceSite::CanInPlaceActivate
*
* Purpose:
* Answers the server whether or not we can currently in-place
* activate its object. By implementing this interface we say
* that we support in-place activation, but through this function
* we indicate whether the object can currently be activated
* in-place. Iconic aspects, for example, cannot, meaning we
* return S_FALSE.
*
* Parameters:
* None
*
* Return Value:
* HRESULT NOERROR if we can in-place activate the object
* in this site, S_FALSE if not.
*/
STDMETHODIMP tOleInPlaceSite::CanInPlaceActivate(void)
{
if (DVASPECT_CONTENT!=m_pTen->m_fe.dwAspect)
return ResultFromScode(S_FALSE);
return NOERROR;
}
/*
* tOleInPlaceSite::OnInPlaceActivate
*
* Purpose:
* Informs the container that an object is being activated in-place
* such that the container can prepare appropriately. The
* container does not, however, make any user interface changes at
* this point. See OnUIActivate.
*
* Parameters:
* None
*
* Return Value:
* HRESULT NOERROR or an appropriate error code.
*/
STDMETHODIMP tOleInPlaceSite::OnInPlaceActivate(void)
{
//CHAPTER24MOD
m_pTen->m_fPendingDeactivate=FALSE;
//End CHAPTER24MOD
//m_pIOleIPObject is our in-place flag.
m_pTen->m_pObj->QueryInterface(IID_IOleInPlaceObject
, (PPVOID)&m_pTen->m_pIOleIPObject);
return NOERROR;
}
/*
* tOleInPlaceSite::OnInPlaceDeactivate
*
* Purpose:
* Notifies the container that the object has deactivated itself
* from an in-place state. Opposite of OnInPlaceActivate. The
* container does not change any UI at this point.
*
* Parameters:
* None
*
* Return Value:
* HRESULT NOERROR or an appropriate error code.
*/
STDMETHODIMP tOleInPlaceSite::OnInPlaceDeactivate(void)
{
/*
* Since we don't have an Undo command, we can tell the object
* right away to discard its Undo state.
*/
m_pTen->Activate(OLEIVERB_DISCARDUNDOSTATE, NULL);
ReleaseInterface(m_pTen->m_pIOleIPObject);
return NOERROR;
}
/*
* tOleInPlaceSite::OnUIActivate
*
* Purpose:
* Informs the container that the object is going to start munging
* around with user interface, like replacing the menu. The
* container should remove any relevant UI in preparation.
*
* Parameters:
* None
*
* Return Value:
* HRESULT NOERROR or an appropriate error code.
*/
STDMETHODIMP tOleInPlaceSite::OnUIActivate(void)
{
//CHAPTER24MOD
m_pTen->m_fPendingDeactivate=FALSE;
//End CHAPTER24MOD
/*
* Change the currently selected tenant in the page. This
* will UIDeactivate the currently UI Active tenant.
*/
g_fSwitchingActive=TRUE;
//m_pTen->m_pPG->m_pPageCur->SwitchActiveTenant(m_pTen);
g_fSwitchingActive=FALSE;
return NOERROR;
}
/*
* tOleInPlaceSite::OnUIDeactivate
*
* Purpose:
* Informs the container that the object is deactivating its
* in-place user interface at which time the container may
* reinstate its own. Opposite of OnUIActivate.
*
* Parameters:
* fUndoable BOOL indicating if the object will actually
* perform an Undo if the container calls
* ReactivateAndUndo.
*
* Return Value:
* HRESULT NOERROR or an appropriate error code.
*/
STDMETHODIMP tOleInPlaceSite::OnUIDeactivate(BOOL fUndoable)
{
MSG msg;
/*
* Ignore this notification if we're switching between
* multiple active objects.
*/
if (g_fSwitchingActive)
return NOERROR;
//If in shutdown (NULL storage), don't check messages.
/* if (NULL==m_pTen->m_pIStorage)
{
g_pFR->ReinstateUI();
return NOERROR;
}*/
//If there's a pending double-click, delay showing our UI
/* if (!PeekMessage(&msg, pDoc->Window(), WM_LBUTTONDBLCLK
, WM_LBUTTONDBLCLK, PM_NOREMOVE | PM_NOYIELD))
{
//Turn everything back on.
g_pFR->ReinstateUI();
}
else*/
return NOERROR;
}
/*
* tOleInPlaceSite::DeactivateAndUndo
*
* Purpose:
* If immediately after activation the object does an Undo, the
* action being undone is the activation itself, and this call
* informs the container that this is, in fact, what happened.
* The container should call IOleInPlaceObject::UIDeactivate.
*
* Parameters:
* None
*
* Return Value:
* HRESULT NOERROR or an appropriate error code.
*/
STDMETHODIMP tOleInPlaceSite::DeactivateAndUndo(void)
{
//CHAPTER24MOD
/*
* Note that we don't pay attention to the locking
* from IOleControlSite::LockInPlaceActive since only
* the object calls this function and should know
* that it's going to be deactivated.
*/
//End CHAPTER24MOD
m_pTen->m_pIOleIPObject->InPlaceDeactivate();
return NOERROR;
}
/*
* tOleInPlaceSite::DiscardUndoState
*
* Purpose:
* Informs the container that something happened in the object
* that means the container should discard any undo information
* it currently maintains for the object.
*
* Parameters:
* None
*
* Return Value:
* HRESULT NOERROR or an appropriate error code.
*/
STDMETHODIMP tOleInPlaceSite::DiscardUndoState(void)
{
return ResultFromScode(E_NOTIMPL);
}
/*
* tOleInPlaceSite::GetWindowContext
*
* Purpose:
* Provides an in-place object with pointers to the frame and
* document level in-place interfaces (IOleInPlaceFrame and
* IOleInPlaceUIWindow) such that the object can do border
* negotiation and so forth. Also requests the position and
* clipping rectangles of the object in the container and a
* pointer to an OLEINPLACEFRAME info structure which contains
* accelerator information.
*
* Note that the two interfaces this call returns are not
* available through QueryInterface on IOleInPlaceSite since they
* live with the frame and document, but not the site.
*
* Parameters:
* ppIIPFrame LPOLEINPLACEFRAME * in which to return the
* AddRef'd pointer to the container's
* IOleInPlaceFrame.
* ppIIPUIWindow LPOLEINPLACEUIWINDOW * in which to return
* the AddRef'd pointer to the container document's
* IOleInPlaceUIWindow.
* prcPos LPRECT in which to store the object's position.
* prcClip LPRECT in which to store the object's visible
* region.
* pFI LPOLEINPLACEFRAMEINFO to fill with accelerator
* stuff.
*
* Return Value:
* HRESULT NOERROR
*/
STDMETHODIMP tOleInPlaceSite::GetWindowContext
(LPOLEINPLACEFRAME *ppIIPFrame, LPOLEINPLACEUIWINDOW
*ppIIPUIWindow, LPRECT prcPos, LPRECT prcClip
, LPOLEINPLACEFRAMEINFO pFI)
{
RECTL rcl;
*ppIIPUIWindow=NULL;
*ppIIPFrame=m_oleinplaceframe;
m_oleinplaceframe->AddRef();
GetClientRect(m_pTen->m_hWnd, prcPos);
GetClientRect(m_pTen->m_hWnd, prcClip);
/* *ppIIPFrame=(LPOLEINPLACEFRAME)g_pFR;
g_pFR->AddRef();*/
/* if (NULL!=pDoc)
{
pDoc->QueryInterface(IID_IOleInPlaceUIWindow
, (PPVOID)ppIIPUIWindow);
}*/
//Now get the rectangles and frame information.
/*m_pTen->RectGet(&rcl, TRUE);
RECTFROMRECTL(*prcPos, rcl);
0
//Include scroll position here.
OffsetRect(prcPos, -(int)m_pTen->m_pPG->m_xPos
, -(int)m_pTen->m_pPG->m_yPos);
SetRect(prcClip, 0, 0, 32767, 32767);
*/
pFI->cb=sizeof(OLEINPLACEFRAMEINFO);
pFI->fMDIApp=FALSE;
pFI->hwndFrame=m_pTen->m_hWnd;
pFI->haccel=NULL;
pFI->cAccelEntries=0;
return NOERROR;
}
/*
* tOleInPlaceSite::Scroll
*
* Purpose:
* Asks the container to scroll the document, and thus the object,
* by the given amounts in the sz parameter.
*
* Parameters:
* sz SIZE containing signed horizontal and vertical
* extents by which the container should scroll.
* These are in device units.
*
* Return Value:
* HRESULT NOERROR
*/
STDMETHODIMP tOleInPlaceSite::Scroll(SIZE sz)
{
/*int x, y;
x=m_pTen->m_pPG->m_xPos+sz.cx;
y=m_pTen->m_pPG->m_yPos+sz.cy;
SendScrollPosition(m_pTen->m_hWnd, WM_HSCROLL, x);
SendScrollPosition(m_pTen->m_hWnd, WM_VSCROLL, y);*/
return NOERROR;
}
/*
* tOleInPlaceSite::OnPosRectChange
*
* Purpose:
* Informs the container that the in-place object was resized.
* The container must call IOleInPlaceObject::SetObjectRects.
* This does not change the site's rectangle in any case.
*
* Parameters:
* prcPos LPCRECT containing the new size of the object.
*
* Return Value:
* HRESULT NOERROR
*/
STDMETHODIMP tOleInPlaceSite::OnPosRectChange(LPCRECT prcPos)
{
if (NULL!=prcPos)
{
// This change was necessary because some controls were not working, and being positioned in a wrong place.
// Contribution by Kommit
LPRECT pPos = (LPRECT)prcPos; // convert the const pointer to non-const pointer to modify it's member values.
pPos->right -= pPos->left;
pPos->bottom -= pPos->top;
pPos->left = 0;
pPos->top = 0;
m_pTen->m_rcPos=*prcPos;
}
m_pTen->UpdateInPlaceObjectRects(prcPos, FALSE);
return NOERROR;
}
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_PRIM_FUN_LOG_HPP
#define STAN_MATH_PRIM_FUN_LOG_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/rev/meta.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/fun/isinf.hpp>
#include <stan/math/prim/fun/is_inf.hpp>
#include <stan/math/prim/fun/is_nan.hpp>
#include <cmath>
#include <complex>
#include <limits>
namespace stan {
namespace math {
/**
* Structure to wrap `log()` so that it can be vectorized.
*/
struct log_fun {
/**
* Return natural log of specified argument.
*
* @tparam T type of argument
* @param[in] x argument
* @return Natural log of x.
*/
template <typename T>
static inline T fun(const T& x) {
using std::log;
return log(x);
}
};
/**
* Return the elementwise natural log of the specified argument,
* which may be a scalar or any Stan container of numeric scalars.
* The return type is the same as the argument type.
*
* @tparam Container type of container
* @param[in] x container
* @return Elementwise application of natural log to the argument.
*/
template <typename Container,
require_not_container_st<std::is_arithmetic, Container>* = nullptr>
inline auto log(const Container& x) {
return apply_scalar_unary<log_fun, Container>::apply(x);
}
/**
* Version of `log()` that accepts std::vectors, Eigen Matrix/Array objects
* or expressions, and containers of these.
*
* @tparam Container Type of x
* @param x Container
* @return Natural log of each variable in the container.
*/
template <typename Container,
require_container_st<std::is_arithmetic, Container>* = nullptr>
inline auto log(const Container& x) {
return apply_vector_unary<Container>::apply(
x, [](const auto& v) { return v.array().log(); });
}
namespace internal {
/**
* Return the natural logarithm of the complex argument.
*
* @tparam V value type of argument
* @param[in] z argument
* @return natural logarithm of the argument
*/
template <typename V>
inline std::complex<V> complex_log(const std::complex<V>& z) {
static const double inf = std::numeric_limits<double>::infinity();
static const double nan = std::numeric_limits<double>::quiet_NaN();
if ((is_nan(z.real()) && is_inf(z.imag()))
|| (is_inf(z.real()) && is_nan(z.imag()))) {
return {inf, nan};
}
V r = sqrt(norm(z));
V theta = arg(z);
return {log(r), theta};
}
} // namespace internal
} // namespace math
} // namespace stan
#endif
<commit_msg>restrict dependencies for prim/fun/log to prim<commit_after>#ifndef STAN_MATH_PRIM_FUN_LOG_HPP
#define STAN_MATH_PRIM_FUN_LOG_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/fun/isinf.hpp>
#include <stan/math/prim/fun/is_inf.hpp>
#include <stan/math/prim/fun/is_nan.hpp>
#include <cmath>
#include <complex>
#include <limits>
namespace stan {
namespace math {
/**
* Structure to wrap `log()` so that it can be vectorized.
*/
struct log_fun {
/**
* Return natural log of specified argument.
*
* @tparam T type of argument
* @param[in] x argument
* @return Natural log of x.
*/
template <typename T>
static inline T fun(const T& x) {
using std::log;
return log(x);
}
};
/**
* Return the elementwise natural log of the specified argument,
* which may be a scalar or any Stan container of numeric scalars.
* The return type is the same as the argument type.
*
* @tparam Container type of container
* @param[in] x container
* @return Elementwise application of natural log to the argument.
*/
template <typename Container,
require_not_container_st<std::is_arithmetic, Container>* = nullptr>
inline auto log(const Container& x) {
return apply_scalar_unary<log_fun, Container>::apply(x);
}
/**
* Version of `log()` that accepts std::vectors, Eigen Matrix/Array objects
* or expressions, and containers of these.
*
* @tparam Container Type of x
* @param x Container
* @return Natural log of each variable in the container.
*/
template <typename Container,
require_container_st<std::is_arithmetic, Container>* = nullptr>
inline auto log(const Container& x) {
return apply_vector_unary<Container>::apply(
x, [](const auto& v) { return v.array().log(); });
}
namespace internal {
/**
* Return the natural logarithm of the complex argument.
*
* @tparam V value type of argument
* @param[in] z argument
* @return natural logarithm of the argument
*/
template <typename V>
inline std::complex<V> complex_log(const std::complex<V>& z) {
static const double inf = std::numeric_limits<double>::infinity();
static const double nan = std::numeric_limits<double>::quiet_NaN();
if ((is_nan(z.real()) && is_inf(z.imag()))
|| (is_inf(z.real()) && is_nan(z.imag()))) {
return {inf, nan};
}
V r = sqrt(norm(z));
V theta = arg(z);
return {log(r), theta};
}
} // namespace internal
} // namespace math
} // namespace stan
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: config.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: rt $ $Date: 2005-09-07 15:05:21 $
*
* 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
*
************************************************************************/
#pragma hdrstop
#ifndef _SFXITEMSET_HXX //autogen
#include <svtools/itemset.hxx>
#endif
#ifndef _SFXHINT_HXX //autogen
#include <svtools/hint.hxx>
#endif
#ifndef _SFXSMPLHINT_HXX //autogen
#include <svtools/smplhint.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#include <svtools/pathoptions.hxx>
#endif
#ifndef _SFXSIDS_HRC //autogen
#include <sfx2/sfxsids.hrc>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXITEMPOOL_HXX //autogen
#include <svtools/itempool.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef CONFIG_HXX
#include "config.hxx"
#endif
#ifndef FORMAT_HXX
#include "format.hxx"
#endif
#ifndef _SMMOD_HXX
#include "smmod.hxx"
#endif
#ifndef _STARMATH_HRC
#include "starmath.hrc"
#endif
/////////////////////////////////////////////////////////////////
SmConfig::SmConfig()
{
}
SmConfig::~SmConfig()
{
}
void SmConfig::ItemSetToConfig(const SfxItemSet &rSet)
{
const SfxPoolItem *pItem = NULL;
UINT16 nU16;
BOOL bVal;
if (rSet.GetItemState(SID_PRINTSIZE, TRUE, &pItem) == SFX_ITEM_SET)
{ nU16 = ((const SfxUInt16Item *) pItem)->GetValue();
SetPrintSize( (SmPrintSize) nU16 );
}
if (rSet.GetItemState(SID_PRINTZOOM, TRUE, &pItem) == SFX_ITEM_SET)
{ nU16 = ((const SfxUInt16Item *) pItem)->GetValue();
SetPrintZoomFactor( nU16 );
}
if (rSet.GetItemState(SID_PRINTTITLE, TRUE, &pItem) == SFX_ITEM_SET)
{ bVal = ((const SfxBoolItem *) pItem)->GetValue();
SetPrintTitle( bVal );
}
if (rSet.GetItemState(SID_PRINTTEXT, TRUE, &pItem) == SFX_ITEM_SET)
{ bVal = ((const SfxBoolItem *) pItem)->GetValue();
SetPrintFormulaText( bVal );
}
if (rSet.GetItemState(SID_PRINTFRAME, TRUE, &pItem) == SFX_ITEM_SET)
{ bVal = ((const SfxBoolItem *) pItem)->GetValue();
SetPrintFrame( bVal );
}
if (rSet.GetItemState(SID_AUTOREDRAW, TRUE, &pItem) == SFX_ITEM_SET)
{ bVal = ((const SfxBoolItem *) pItem)->GetValue();
SetAutoRedraw( bVal );
}
if (rSet.GetItemState(SID_NO_RIGHT_SPACES, TRUE, &pItem) == SFX_ITEM_SET)
{ bVal = ((const SfxBoolItem *) pItem)->GetValue();
if (IsIgnoreSpacesRight() != bVal)
{
SetIgnoreSpacesRight( bVal );
// (angezeigte) Formeln muessen entsprechen neu formatiert werden.
// Das erreichen wir mit:
Broadcast(SfxSimpleHint(HINT_FORMATCHANGED));
}
}
}
void SmConfig::ConfigToItemSet(SfxItemSet &rSet) const
{
const SfxItemPool *pPool = rSet.GetPool();
rSet.Put(SfxUInt16Item(pPool->GetWhich(SID_PRINTSIZE),
(UINT16) GetPrintSize()));
rSet.Put(SfxUInt16Item(pPool->GetWhich(SID_PRINTZOOM),
(UINT16) GetPrintZoomFactor()));
rSet.Put(SfxBoolItem(pPool->GetWhich(SID_PRINTTITLE), IsPrintTitle()));
rSet.Put(SfxBoolItem(pPool->GetWhich(SID_PRINTTEXT), IsPrintFormulaText()));
rSet.Put(SfxBoolItem(pPool->GetWhich(SID_PRINTFRAME), IsPrintFrame()));
rSet.Put(SfxBoolItem(pPool->GetWhich(SID_AUTOREDRAW), IsAutoRedraw()));
rSet.Put(SfxBoolItem(pPool->GetWhich(SID_NO_RIGHT_SPACES), IsIgnoreSpacesRight()));
}
/////////////////////////////////////////////////////////////////
<commit_msg>INTEGRATION: CWS swqbf40 (1.9.24); FILE MERGED 2005/10/17 12:54:08 tl 1.9.24.1: #i55936# calling of SaveOther/SaveForamt fixed. Configuration will now be updated (again).<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: config.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: hr $ $Date: 2005-10-27 15:55:23 $
*
* 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
*
************************************************************************/
#pragma hdrstop
#ifndef _SFXITEMSET_HXX //autogen
#include <svtools/itemset.hxx>
#endif
#ifndef _SFXHINT_HXX //autogen
#include <svtools/hint.hxx>
#endif
#ifndef _SFXSMPLHINT_HXX //autogen
#include <svtools/smplhint.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_PATHOPTIONS_HXX
#include <svtools/pathoptions.hxx>
#endif
#ifndef _SFXSIDS_HRC //autogen
#include <sfx2/sfxsids.hrc>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXITEMPOOL_HXX //autogen
#include <svtools/itempool.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef CONFIG_HXX
#include "config.hxx"
#endif
#ifndef FORMAT_HXX
#include "format.hxx"
#endif
#ifndef _SMMOD_HXX
#include "smmod.hxx"
#endif
#ifndef _STARMATH_HRC
#include "starmath.hrc"
#endif
/////////////////////////////////////////////////////////////////
SmConfig::SmConfig()
{
}
SmConfig::~SmConfig()
{
}
void SmConfig::ItemSetToConfig(const SfxItemSet &rSet)
{
const SfxPoolItem *pItem = NULL;
UINT16 nU16;
BOOL bVal;
if (rSet.GetItemState(SID_PRINTSIZE, TRUE, &pItem) == SFX_ITEM_SET)
{ nU16 = ((const SfxUInt16Item *) pItem)->GetValue();
SetPrintSize( (SmPrintSize) nU16 );
}
if (rSet.GetItemState(SID_PRINTZOOM, TRUE, &pItem) == SFX_ITEM_SET)
{ nU16 = ((const SfxUInt16Item *) pItem)->GetValue();
SetPrintZoomFactor( nU16 );
}
if (rSet.GetItemState(SID_PRINTTITLE, TRUE, &pItem) == SFX_ITEM_SET)
{ bVal = ((const SfxBoolItem *) pItem)->GetValue();
SetPrintTitle( bVal );
}
if (rSet.GetItemState(SID_PRINTTEXT, TRUE, &pItem) == SFX_ITEM_SET)
{ bVal = ((const SfxBoolItem *) pItem)->GetValue();
SetPrintFormulaText( bVal );
}
if (rSet.GetItemState(SID_PRINTFRAME, TRUE, &pItem) == SFX_ITEM_SET)
{ bVal = ((const SfxBoolItem *) pItem)->GetValue();
SetPrintFrame( bVal );
}
if (rSet.GetItemState(SID_AUTOREDRAW, TRUE, &pItem) == SFX_ITEM_SET)
{ bVal = ((const SfxBoolItem *) pItem)->GetValue();
SetAutoRedraw( bVal );
}
if (rSet.GetItemState(SID_NO_RIGHT_SPACES, TRUE, &pItem) == SFX_ITEM_SET)
{ bVal = ((const SfxBoolItem *) pItem)->GetValue();
if (IsIgnoreSpacesRight() != bVal)
{
SetIgnoreSpacesRight( bVal );
// (angezeigte) Formeln muessen entsprechen neu formatiert werden.
// Das erreichen wir mit:
Broadcast(SfxSimpleHint(HINT_FORMATCHANGED));
}
}
SaveOther();
}
void SmConfig::ConfigToItemSet(SfxItemSet &rSet) const
{
const SfxItemPool *pPool = rSet.GetPool();
rSet.Put(SfxUInt16Item(pPool->GetWhich(SID_PRINTSIZE),
(UINT16) GetPrintSize()));
rSet.Put(SfxUInt16Item(pPool->GetWhich(SID_PRINTZOOM),
(UINT16) GetPrintZoomFactor()));
rSet.Put(SfxBoolItem(pPool->GetWhich(SID_PRINTTITLE), IsPrintTitle()));
rSet.Put(SfxBoolItem(pPool->GetWhich(SID_PRINTTEXT), IsPrintFormulaText()));
rSet.Put(SfxBoolItem(pPool->GetWhich(SID_PRINTFRAME), IsPrintFrame()));
rSet.Put(SfxBoolItem(pPool->GetWhich(SID_AUTOREDRAW), IsAutoRedraw()));
rSet.Put(SfxBoolItem(pPool->GetWhich(SID_NO_RIGHT_SPACES), IsIgnoreSpacesRight()));
}
/////////////////////////////////////////////////////////////////
<|endoftext|> |
<commit_before>/*------------------------------------------------------------------------------
| This file is distributed under the BSD 2-Clause License.
| See LICENSE for details.
*-----------------------------------------------------------------------------*/
#pragma once
#include <cassert>
#include <cstdint>
namespace lsy {
/*------------------------------------------------------------------------------
| cube32
| ------
| TLDR: efficient cube data structure for Boolean functions with up to 32
| variables
|
| A cube is the Boolean AND or 'k' literals. Given a Boolean function with N
| variables, there are 2*N literals. In a cube of this function each literal
| can either appear as a positive literal ('1'), as a negative literal ('0') or
| not appear at all (don't care, '-').
|
| Since each literal can assume one to these three values, we need at least two
| bits to represent the state of each literal. Thus, if we limit the number of
| variables in the function to 32, it's clear we only need 64 bits to encode a
| cube.
|
| Here, 'mask' tells us if a literal appears ('1') or not ('0' - don't care).
| For the cases where the literal appears in the cube, the 'polarity' indicates
| it's polarity (duh :)
|
| * A constant 1 is represented by all literal being don't care.
*-----------------------------------------------------------------------------*/
struct cube32 {
using ui32_t = std::uint32_t;
using ui64_t = std::uint64_t;
using c32_t = struct cube32;
union {
struct {
ui32_t polarity;
ui32_t mask;
};
ui64_t value;
};
cube32()
: value{0u}
{ }
cube32(const ui64_t v)
: value{v}
{ }
constexpr cube32(const ui32_t m, const ui32_t p)
: polarity{p}, mask{m}
{ }
bool operator==(const c32_t that) const
{ return value == that.value; }
bool operator!=(const c32_t that) const
{ return value != that.value; }
bool operator< (const c32_t that) const
{ return value < that.value; }
bool operator==(const ui64_t v) const
{ return value == v; }
bool operator!=(const ui64_t v) const
{ return value != v; }
c32_t operator&(const c32_t that) const
{
const auto tmp_mask = mask & that.mask;
if ((polarity ^ that.polarity) & tmp_mask)
return cube32{0xFFFFFFFFu, 0x00000000u};
return cube32{value | that.value};
}
ui32_t n_lits() const
{ return __builtin_popcount(mask); }
void add_lit(const ui32_t var, const ui32_t p)
{
assert(p <= 1);
mask |= (1 << var);
polarity |= (p << var);
}
};
constexpr auto cube32_zero = cube32{0xFFFFFFFFu, 0x00000000u};
constexpr auto cube32_one = cube32{0u, 0u};
} // namespace lsy
<commit_msg>Adding "normal" include guards.<commit_after>/*------------------------------------------------------------------------------
| This file is distributed under the BSD 2-Clause License.
| See LICENSE for details.
*-----------------------------------------------------------------------------*/
#ifndef LOSYS_CUBE32_HPP
#define LOSYS_CUBE32_HPP
#include <cassert>
#include <cstdint>
namespace lsy {
/*------------------------------------------------------------------------------
| cube32
| ------
| TLDR: efficient cube data structure for Boolean functions with up to 32
| variables
|
| A cube is the Boolean AND or 'k' literals. Given a Boolean function with N
| variables, there are 2*N literals. In a cube of this function each literal
| can either appear as a positive literal ('1'), as a negative literal ('0') or
| not appear at all (don't care, '-').
|
| Since each literal can assume one to these three values, we need at least two
| bits to represent the state of each literal. Thus, if we limit the number of
| variables in the function to 32, it's clear we only need 64 bits to encode a
| cube.
|
| Here, 'mask' tells us if a literal appears ('1') or not ('0' - don't care).
| For the cases where the literal appears in the cube, the 'polarity' indicates
| it's polarity (duh :)
|
| * A constant 1 is represented by all literal being don't care.
*-----------------------------------------------------------------------------*/
struct cube32 {
using ui32_t = std::uint32_t;
using ui64_t = std::uint64_t;
using c32_t = struct cube32;
union {
struct {
ui32_t polarity;
ui32_t mask;
};
ui64_t value;
};
cube32()
: value{0u}
{ }
cube32(const ui64_t v)
: value{v}
{ }
constexpr cube32(const ui32_t m, const ui32_t p)
: polarity{p}, mask{m}
{ }
bool operator==(const c32_t that) const
{ return value == that.value; }
bool operator!=(const c32_t that) const
{ return value != that.value; }
bool operator< (const c32_t that) const
{ return value < that.value; }
bool operator==(const ui64_t v) const
{ return value == v; }
bool operator!=(const ui64_t v) const
{ return value != v; }
c32_t operator&(const c32_t that) const
{
const auto tmp_mask = mask & that.mask;
if ((polarity ^ that.polarity) & tmp_mask)
return cube32{0xFFFFFFFFu, 0x00000000u};
return cube32{value | that.value};
}
ui32_t n_lits() const
{ return __builtin_popcount(mask); }
void add_lit(const ui32_t var, const ui32_t p)
{
assert(p <= 1);
mask |= (1 << var);
polarity |= (p << var);
}
};
constexpr auto cube32_zero = cube32{0xFFFFFFFFu, 0x00000000u};
constexpr auto cube32_one = cube32{0u, 0u};
} // namespace lsy
#endif
<|endoftext|> |
<commit_before>// Copyright 2013 Mirus Project
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// kernel.cpp - main source file + kernel entry point
// we all have to begin somewhere, right?
//
#include <stdafx.hpp>
#include <boot/multiboot.hpp>
#include <cpu/gdt.hpp>
#include <cpu/idt.hpp>
#include <cpu/isr.hpp>
#include <cpu/irq.hpp>
#include <hardware/timer.hpp>
#include <hardware/serial.hpp>
#include <hardware/rtc.hpp>
#include <msg/message_handler.hpp>
#include <msg/message.hpp>
namespace mirus
{
//
// kernel_main - our kernel entry point
//
extern "C" void kernel_main(multiboot_info_t* mbd,
unsigned int magic)
{
// Print debug stub
debug::debugger::writeln("[log] Mirus 0.2.5-dev");
debug::debugger::flush();
uintptr_t ramdisk_top = 0;
char* ramdisk;
// Get avalible memory
if (magic != MULTIBOOT_BOOTLOADER_MAGIC)
debug::debugger::writeln("[error] Multiboot bootloader magic doesn't match!");
int memory_size = 0;
if (mbd->flags & 1)
{
debug::debugger::writeln("[log] Reading multiboot header");
memory_map_t* mmap = (memory_map_t*)mbd->mmap_addr;
// parse entries
while ((unsigned int)mmap < (unsigned int)(mbd->mmap_addr) + mbd->mmap_length)
{
memory_size += mmap->length_low;
mmap = (memory_map_t*)((unsigned int)mmap + mmap->size + sizeof(unsigned int));
}
debug::debugger::write("[log] Avalible memory: ");
debug::debugger::write((memory_size / 1024) / 1024);
debug::debugger::writeln("m");
debug::debugger::writeln("[log] Trying to get ramdisk.");
// Check for any modules, the only of which should be the ramdisk
if (mbd->mods_count > 0)
{
uint32_t* module_start = ((uint32_t*)mbd->mods_addr);
uint32_t* module_end = ((uint32_t*)(mbd->mods_addr + 4));
ramdisk = (char*)0x30000000;
ramdisk_top = (uintptr_t)ramdisk + (module_end - module_start);
// TODO: do we need to move the ramdisk somewhere
// more convinient
debug::debugger::write("[log] Ramdisk top: ");
debug::debugger::writeln((const char*)ramdisk_top);
}
else
{
debug::debugger::writeln("[log] No modules found.");
}
}
if (((memory_size / 1024) / 1024) < 512)
debug::debugger::writeln("[warning] Memory is less than expected minimum");
// Install CPU hardware devices
cpu::gdt::install();
cpu::idt::install();
cpu::isr::install();
cpu::irq::install();
// Set up screen
screen::terminal::install();
// Set up additional hardware
hardware::pit::install();
hardware::serial::install();
// Testing the message system
system::message_t msg;
msg.pid_sender = 0;
msg.pid_dest = 0;
msg.priority = 0;
msg.type = (int)system::message_request_type::pingback;
msg.data = "this is your kernel speaking, enjoy the ride.";
// message_handler::dispatch_message(msg);
// WE MUST NEVER RETURN!!!!
while (true);
}
} // !namespace
<commit_msg>Find those modules!<commit_after>// Copyright 2013 Mirus Project
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// kernel.cpp - main source file + kernel entry point
// we all have to begin somewhere, right?
//
#include <stdafx.hpp>
#include <boot/multiboot.hpp>
#include <cpu/gdt.hpp>
#include <cpu/idt.hpp>
#include <cpu/isr.hpp>
#include <cpu/irq.hpp>
#include <hardware/timer.hpp>
#include <hardware/serial.hpp>
#include <hardware/rtc.hpp>
#include <msg/message_handler.hpp>
#include <msg/message.hpp>
namespace mirus
{
//
// kernel_main - our kernel entry point
//
extern "C" void kernel_main(multiboot_info_t* mbd,
unsigned int magic)
{
// Print debug stub
debug::debugger::writeln("[log] Mirus 0.2.5-dev");
debug::debugger::flush();
uintptr_t ramdisk_top = 0;
char* ramdisk;
// Get avalible memory
if (magic != MULTIBOOT_BOOTLOADER_MAGIC)
debug::debugger::writeln("[error] Multiboot bootloader magic doesn't match!");
int memory_size = 0;
if (mbd->flags & 1)
{
debug::debugger::writeln("[log] Reading multiboot header");
memory_map_t* mmap = (memory_map_t*)mbd->mmap_addr;
// parse entries
while ((unsigned int)mmap < (unsigned int)(mbd->mmap_addr) + mbd->mmap_length)
{
memory_size += mmap->length_low;
mmap = (memory_map_t*)((unsigned int)mmap + mmap->size + sizeof(unsigned int));
}
debug::debugger::write("[log] Avalible memory: ");
debug::debugger::write((memory_size / 1024) / 1024);
debug::debugger::writeln("m");
debug::debugger::writeln("[log] Trying to get ramdisk.");
// Check for any modules, the only of which should be the ramdisk
if (mbd->mods_count > 0)
{
debug::debugger::write("[log] Modules found: ");
debug::debugger::write((int)mbd->mods_count);
debug::debugger::flush();
uint32_t* module_start = ((uint32_t*)mbd->mods_addr);
uint32_t* module_end = ((uint32_t*)(mbd->mods_addr + 4));
// TODO: do we need to move the ramdisk somewhere
// more convinient
debug::debugger::write("[log] Module start: ");
debug::debugger::write((int)&module_start);
debug::debugger::flush();
}
else
{
debug::debugger::writeln("[log] No modules found.");
}
}
if (((memory_size / 1024) / 1024) < 512)
debug::debugger::writeln("[warning] Memory is less than expected minimum");
// Install CPU hardware devices
cpu::gdt::install();
cpu::idt::install();
cpu::isr::install();
cpu::irq::install();
// Set up screen
screen::terminal::install();
// Set up additional hardware
hardware::pit::install();
hardware::serial::install();
// Testing the message system
system::message_t msg;
msg.pid_sender = 0;
msg.pid_dest = 0;
msg.priority = 0;
msg.type = (int)system::message_request_type::pingback;
msg.data = "this is your kernel speaking, enjoy the ride.";
// message_handler::dispatch_message(msg);
// WE MUST NEVER RETURN!!!!
while (true);
}
} // !namespace
<|endoftext|> |
<commit_before>//
// Area.cpp
// Phantasma
//
// Created by Thomas Harte on 25/12/2013.
// Copyright (c) 2013 Thomas Harte. All rights reserved.
//
#include "Area.h"
#include "Object.h"
#include <list>
Object *Area::objectWithIDFromMap(ObjectMap *map, uint16_t objectID)
{
if(!map) return NULL;
if(!map->count(objectID)) return NULL;
return (*map)[objectID];
}
Object *Area::objectWithID(uint16_t objectID)
{
return objectWithIDFromMap(objectsByID, objectID);
}
Object *Area::entranceWithID(uint16_t objectID)
{
return objectWithIDFromMap(entrancesByID, objectID);
}
uint16_t Area::getAreaID()
{
return areaID;
}
Area::Area(
uint16_t _areaID,
ObjectMap *_objectsByID,
ObjectMap *_entrancesByID)
{
areaID = _areaID;
objectsByID = _objectsByID;
entrancesByID = _entrancesByID;
areaBuffer = nullptr;
// create a list of drawable obejcts only
// int c = 0;
for(ObjectMap::iterator iterator = objectsByID->begin(); iterator != objectsByID->end(); iterator++)
{
if(iterator->second->isDrawable())
{
// c++;
// if(
// (c == 5) ||
// (c == 6) ||
// (c == 7)
// )
drawableObjects.push_back(iterator->second);
}
}
}
Area::~Area()
{
for(ObjectMap::iterator iterator = entrancesByID->begin(); iterator != entrancesByID->end(); iterator++)
delete iterator->second;
for(ObjectMap::iterator iterator = objectsByID->begin(); iterator != objectsByID->end(); iterator++)
delete iterator->second;
delete entrancesByID;
delete objectsByID;
}
void Area::setupOpenGL()
{
delete areaBuffer;
areaBuffer = GeometricObject::newVertexBuffer();
for(ObjectMap::iterator iterator = objectsByID->begin(); iterator != objectsByID->end(); iterator++)
iterator->second->setupOpenGL(areaBuffer);
}
int compareObjects(Object *object1, Object *object2, float *position)
{
Vector3d objectOrigins[2] = { object1->getOrigin(), object2->getOrigin() };
Vector3d objectSizes[2] = { object1->getSize(), object2->getSize() };
int results[3] = {0, 0, 0};
for(int axis = 0; axis < 3; axis++)
{
// figure out which box is lower down this axis than the other
int invertResult;
int lowerObject;
if(objectOrigins[1][axis] < objectOrigins[0][axis])
{
invertResult = -1;
lowerObject = 1;
}
else
{
invertResult = 1;
lowerObject = 0;
}
// is there a separating plane between these two at all?
uint16_t endOfLowerObject = objectOrigins[lowerObject][axis] + objectSizes[lowerObject][axis];
if(endOfLowerObject <= objectOrigins[lowerObject ^ 1][axis])
{
// if so, is the player positioned within the gap? We don't have
// an opinion on draw order if that's the case
if((position[axis] < endOfLowerObject) || (position[axis] > objectOrigins[lowerObject ^ 1][axis]))
{
int result = (position[axis] >= endOfLowerObject) ? 1 : -1;
result *= invertResult;
results[axis] = result;
}
}
}
// if no opinion was expressed then the two are coplanar, so compare by ID
if(!results[0] && !results[1] && !results[2])
return (object1->getObjectID() < object2->getObjectID()) ? -1 : 1;
// otherwise we need all axes with opinions to match
int result = 0;
for(int c = 0; c < 3; c++)
{
if(results[c])
{
if(!result)
{
result = results[c];
}
else
{
if(results[c] != result)
return 0;
}
}
}
return result;
}
void Area::draw(float *playerPosition)
{
/*
Here's a relic for you: we're going to use painter's algorithm
(ie, back-to-front drawing, no depth testing, overdraw to obscure)
to draw the scene. Why? Because:
(1) the original engine appears to use the painter's algorith;
I've concluded this by observing that it cannot deal with
mutual overlap;
(2) because the original engine uses painter's algorithm and
because of the geometry involved it's standard practive to
use coplanar geometry for doors and adornments;
(3) depth buffers deal very poorly with coplanar geometry,
with even use of polygon offsets being difficult to scale
to the arbitrary case; and
(4) with the tiny amount of geometry involved and absolutely
trivial single-coloured surfaces involved, the cost of
overdraw is not a concern.
*/
std::list <Object *> orderedObjects;
for(std::vector<Object *>::iterator incomingIterator = drawableObjects.begin(); incomingIterator != drawableObjects.end(); incomingIterator++)
{
bool didInsert = false;
for(std::list<Object *>::iterator existingIterator = orderedObjects.begin(); existingIterator != orderedObjects.end(); existingIterator++)
{
int comparison = compareObjects(*incomingIterator, *existingIterator, playerPosition);
if(comparison > 0)
{
didInsert = true;
orderedObjects.insert(existingIterator, *incomingIterator);
break;
}
}
if(!didInsert)
orderedObjects.push_back(*incomingIterator);
}
for(std::list<Object *>::iterator iterator = orderedObjects.begin(); iterator != orderedObjects.end(); iterator++)
{
(*iterator)->draw(areaBuffer);
}
}
<commit_msg>Fixed: the object ID comparison occurs only if no separating axis was found.<commit_after>//
// Area.cpp
// Phantasma
//
// Created by Thomas Harte on 25/12/2013.
// Copyright (c) 2013 Thomas Harte. All rights reserved.
//
#include "Area.h"
#include "Object.h"
#include <list>
Object *Area::objectWithIDFromMap(ObjectMap *map, uint16_t objectID)
{
if(!map) return NULL;
if(!map->count(objectID)) return NULL;
return (*map)[objectID];
}
Object *Area::objectWithID(uint16_t objectID)
{
return objectWithIDFromMap(objectsByID, objectID);
}
Object *Area::entranceWithID(uint16_t objectID)
{
return objectWithIDFromMap(entrancesByID, objectID);
}
uint16_t Area::getAreaID()
{
return areaID;
}
Area::Area(
uint16_t _areaID,
ObjectMap *_objectsByID,
ObjectMap *_entrancesByID)
{
areaID = _areaID;
objectsByID = _objectsByID;
entrancesByID = _entrancesByID;
areaBuffer = nullptr;
// create a list of drawable obejcts only
// int c = 0;
for(ObjectMap::iterator iterator = objectsByID->begin(); iterator != objectsByID->end(); iterator++)
{
if(iterator->second->isDrawable())
{
// c++;
// if(
// (c == 5) ||
// (c == 6) ||
// (c == 7)
// )
drawableObjects.push_back(iterator->second);
}
}
}
Area::~Area()
{
for(ObjectMap::iterator iterator = entrancesByID->begin(); iterator != entrancesByID->end(); iterator++)
delete iterator->second;
for(ObjectMap::iterator iterator = objectsByID->begin(); iterator != objectsByID->end(); iterator++)
delete iterator->second;
delete entrancesByID;
delete objectsByID;
}
void Area::setupOpenGL()
{
delete areaBuffer;
areaBuffer = GeometricObject::newVertexBuffer();
for(ObjectMap::iterator iterator = objectsByID->begin(); iterator != objectsByID->end(); iterator++)
iterator->second->setupOpenGL(areaBuffer);
}
int compareObjects(Object *object1, Object *object2, float *position)
{
Vector3d objectOrigins[2] = { object1->getOrigin(), object2->getOrigin() };
Vector3d objectSizes[2] = { object1->getSize(), object2->getSize() };
int results[3] = {0, 0, 0};
int separations = 0;
for(int axis = 0; axis < 3; axis++)
{
// figure out which box is lower down this axis than the other
int invertResult;
int lowerObject;
if(objectOrigins[1][axis] < objectOrigins[0][axis])
{
invertResult = -1;
lowerObject = 1;
}
else
{
invertResult = 1;
lowerObject = 0;
}
// is there a separating plane between these two at all?
uint16_t endOfLowerObject = objectOrigins[lowerObject][axis] + objectSizes[lowerObject][axis];
if(endOfLowerObject <= objectOrigins[lowerObject ^ 1][axis])
{
// if so, is the player positioned within the gap? We don't have
// an opinion on draw order if that's the case
if((position[axis] < endOfLowerObject) || (position[axis] > objectOrigins[lowerObject ^ 1][axis]))
{
int result = (position[axis] >= endOfLowerObject) ? 1 : -1;
result *= invertResult;
results[axis] = result;
}
}
else
separations |= (1 << axis);
}
// if no opinion was expressed then the two are coplanar, so compare by ID
if(separations == 0x7)
return (object1->getObjectID() < object2->getObjectID()) ? -1 : 1;
// otherwise we need all axes with opinions to match
int result = 0;
for(int c = 0; c < 3; c++)
{
if(results[c])
{
if(!result)
{
result = results[c];
}
else
{
if(results[c] != result)
return 0;
}
}
}
return result;
}
void Area::draw(float *playerPosition)
{
/*
Here's a relic for you: we're going to use painter's algorithm
(ie, back-to-front drawing, no depth testing, overdraw to obscure)
to draw the scene. Why? Because:
(1) the original engine appears to use the painter's algorith;
I've concluded this by observing that it cannot deal with
mutual overlap;
(2) because the original engine uses painter's algorithm and
because of the geometry involved it's standard practive to
use coplanar geometry for doors and adornments;
(3) depth buffers deal very poorly with coplanar geometry,
with even use of polygon offsets being difficult to scale
to the arbitrary case; and
(4) with the tiny amount of geometry involved and absolutely
trivial single-coloured surfaces involved, the cost of
overdraw is not a concern.
*/
std::list <Object *> orderedObjects;
for(std::vector<Object *>::iterator incomingIterator = drawableObjects.begin(); incomingIterator != drawableObjects.end(); incomingIterator++)
{
bool didInsert = false;
for(std::list<Object *>::iterator existingIterator = orderedObjects.begin(); existingIterator != orderedObjects.end(); existingIterator++)
{
int comparison = compareObjects(*incomingIterator, *existingIterator, playerPosition);
if(comparison > 0)
{
didInsert = true;
orderedObjects.insert(existingIterator, *incomingIterator);
break;
}
}
if(!didInsert)
orderedObjects.push_back(*incomingIterator);
}
for(std::list<Object *>::iterator iterator = orderedObjects.begin(); iterator != orderedObjects.end(); iterator++)
{
(*iterator)->draw(areaBuffer);
}
}
<|endoftext|> |
<commit_before>#include "nimble/nimbleGraph.h"
graphNode::graphNode(int inputCgraphID, NODETYPE inputType, const string &inputName ) :
role(UNKNOWNROLE),
type(inputType),
CgraphID(inputCgraphID),
name(inputName),
touched(false),
numChildren(0) {
RgraphID = CgraphID + 1;
};
void graphNode::addChild( graphNode *toNode, int childParentExpressionID) {
#ifdef _DEBUGNIMGRAPH
PRINTF("adding child %s to parent %s\n", toNode->name.c_str(), name.c_str());
#endif
children.push_back(toNode);
childrenParentExpressionIDs.push_back(childParentExpressionID);
numChildren++;
toNode->addParent(this);
};
void graphNode::addParent(graphNode *fromNode) {
#ifdef _DEBUGNIMGRAPH
PRINTF("adding parent %s to child %s\n", fromNode->name.c_str(), name.c_str());
#endif
parents.push_back(fromNode);
};
void SEXP_2_nodeType(SEXP Stypes, vector<NODETYPE> &ans) {
// enum NODETYPE {UNKNOWNTYPE, STOCH, DETERM, RHSONLY};
if(!isString(Stypes)) {
PRINTF("Error: called for SEXP that is not a string!\n");
return;
}
int nn = LENGTH(Stypes);
ans.resize(nn);
string oneString;
for(int i = 0; i < nn; i++) {
oneString.assign(CHAR(STRING_ELT(Stypes, i)), LENGTH(STRING_ELT(Stypes, i)));
if(oneString == "stoch")
ans[i] = STOCH;
else if(oneString == "determ")
ans[i] = DETERM;
else if(oneString == "RHSonly")
ans[i] = RHSONLY;
else if(oneString == "LHSinferred")
ans[i] = LHSINFERRED;
else if(oneString == "unknown")
ans[i] = UNKNOWNTYPE;
else {
ans[i] = UNKNOWNTYPE;
PRINTF("In SEXP_2_nodeType: unknown string type label %s\n", oneString.c_str());
}
}
}
SEXP setGraph(SEXP SedgesFrom, SEXP SedgesTo, SEXP SedgesFrom2ParentExprIDs, SEXP Stypes, SEXP Snames, SEXP SnumNodes) {
vector<int> edgesFrom = SEXP_2_vectorInt(SedgesFrom, -1); // -1 subtracted here
vector<int> edgesTo = SEXP_2_vectorInt(SedgesTo, -1); // -1 substracted here
vector<int> edgesFrom2ParentExprIDs = SEXP_2_vectorInt(SedgesFrom2ParentExprIDs);
vector<NODETYPE> types;
SEXP_2_nodeType(Stypes, types);
vector<string> names;
STRSEXP_2_vectorString(Snames, names);
int numNodes = SEXP_2_int(SnumNodes);
nimbleGraph *newGraph = new nimbleGraph;
newGraph->setNodes(edgesFrom, edgesTo, edgesFrom2ParentExprIDs, types, names, numNodes);
SEXP SextPtrAns;
PROTECT(SextPtrAns = R_MakeExternalPtr(newGraph, R_NilValue, R_NilValue));
R_RegisterCFinalizerEx(SextPtrAns, &nimbleGraphFinalizer, TRUE);
UNPROTECT(1);
return(SextPtrAns);
};
void nimbleGraphFinalizer(SEXP SgraphExtPtr) {
nimbleGraph *graphPtr = static_cast<nimbleGraph *>(R_ExternalPtrAddr(SgraphExtPtr));
delete graphPtr;
}
nimbleGraph::~nimbleGraph() {
int n = graphNodeVec.size();
for(int i = 0; i < n; i++) {
delete graphNodeVec[i];
}
}
SEXP anyStochDependencies(SEXP SgraphExtPtr) {
nimbleGraph *graphPtr = static_cast<nimbleGraph *>(R_ExternalPtrAddr(SgraphExtPtr));
vector<int> ans(graphPtr->anyStochDependencies());
SEXP Sans;
PROTECT(Sans = allocVector(LGLSXP, ans.size()));
int *SansPtr = INTEGER(Sans);
for(int i = 0; i < ans.size(); i++) {
if(ans[i] == 0) PRINTF("Element %i was not processed\n", i);
SansPtr[i] = ans[i]==2 ? 1 : 0;
}
UNPROTECT(1);
return(Sans);
}
SEXP getDependencies(SEXP SgraphExtPtr, SEXP Snodes, SEXP Somit, SEXP Sdownstream) {
nimbleGraph *graphPtr = static_cast<nimbleGraph *>(R_ExternalPtrAddr(SgraphExtPtr));
vector<int> nodes = SEXP_2_vectorInt(Snodes, -1); // subtract 1 index for C
vector<int> omit = SEXP_2_vectorInt(Somit, -1);
bool downstream = SEXP_2_bool(Sdownstream);
vector<int> ans = graphPtr->getDependencies(nodes, omit, downstream);
return(vectorInt_2_SEXP(ans, 1)); // add 1 index for R
}
SEXP anyStochParents(SEXP SgraphExtPtr) {
nimbleGraph *graphPtr = static_cast<nimbleGraph *>(R_ExternalPtrAddr(SgraphExtPtr));
vector<int> ans(graphPtr->anyStochParents());
SEXP Sans;
PROTECT(Sans = allocVector(LGLSXP, ans.size()));
int *SansPtr = INTEGER(Sans);
for(int i = 0; i < ans.size(); i++) {
if(ans[i] == 0) PRINTF("Element %i was not processed\n", i);
SansPtr[i] = ans[i]==2 ? 1 : 0;
}
UNPROTECT(1);
return(Sans);
}
void nimbleGraph::setNodes(const vector<int> &edgesFrom, const vector<int> &edgesTo,
const vector<int> &edgesFrom2ParentExprIDs,
const vector<NODETYPE> &types,
const vector<string> &names,
int inputNumNodes) {
numNodes = inputNumNodes;
int numEdges = edgesFrom.size();
#ifdef _DEBUGNIMGRAPH
PRINTF("numNodes %i\n", numNodes);
PRINTF("numEdges %i\n", numEdges);
#endif
if(numEdges != edgesTo.size() | numEdges != edgesFrom2ParentExprIDs.size() | numNodes != types.size() | numNodes != names.size()) {
PRINTF("Something is not the right size\n");
return;
}
graphNodeVec.resize(numNodes);
for(int iNode = 0; iNode < numNodes; iNode++) {
graphNodeVec[iNode] = new graphNode(iNode, types[iNode], names[iNode]);
}
for(int iEdge = 0; iEdge < numEdges; iEdge++) {
graphNodeVec[ edgesFrom[iEdge]]->addChild( graphNodeVec[edgesTo[iEdge]], edgesFrom2ParentExprIDs[iEdge] );
}
}
vector<int> nimbleGraph::anyStochDependencies() {
vector<int> ans(numNodes, 0);
for(int i = 0; i < numNodes; i++) {
anyStochDependenciesOneNode(ans, i);
}
return(ans);
}
bool nimbleGraph::anyStochDependenciesOneNode(vector<int> &anyStochDependencies, int CgraphID) {
// 0 = untouched, 1 = false, 2 = true
if(anyStochDependencies[CgraphID] != 0) return(anyStochDependencies[CgraphID] == 2);
bool thisHasAstochDep(false);
graphNode *thisGraphNode = graphNodeVec[CgraphID];
graphNode *thisChildNode;
int numChildren = thisGraphNode->numChildren;
/* If no children, answer is false */
if(numChildren == 0) {
anyStochDependencies[CgraphID] = 1;
return(false);
}
int i(0);
/* Check type of children without recursing. If any are STOCH, answer is true */
while((i < numChildren) & (!thisHasAstochDep)) {
if(thisGraphNode->children[i]->type == STOCH) {
thisHasAstochDep = true;
}
i++;
}
/* If answer was true, we're done */
if(thisHasAstochDep) {
anyStochDependencies[CgraphID] = 2;
return(true);
}
/* all children were not STOCH, so now recurse through children */
i = 0;
while((i < numChildren) & (!thisHasAstochDep)) {
thisChildNode = thisGraphNode->children[i];
if(anyStochDependenciesOneNode(anyStochDependencies, thisChildNode->CgraphID)) {
thisHasAstochDep = true;
}
i++;
}
if(thisHasAstochDep) {
anyStochDependencies[CgraphID] = 2;
return(true);
}
anyStochDependencies[CgraphID] = 1;
return(false);
}
vector<int> nimbleGraph::anyStochParents() {
vector<int> ans(numNodes, 0);
for(int i = numNodes - 1; i >= 0; i--) {
anyStochParentsOneNode(ans, i);
}
return(ans);
}
bool nimbleGraph::anyStochParentsOneNode(vector<int> &anyStochParents, int CgraphID) {
// 0 = untouched, 1 = false, 2 = true
if(anyStochParents[CgraphID] != 0) return(anyStochParents[CgraphID] == 2);
bool thisHasAstochParent(false);
graphNode *thisGraphNode = graphNodeVec[CgraphID];
graphNode *thisParentNode;
int numParents = thisGraphNode->parents.size();
if(numParents == 0) {
anyStochParents[CgraphID] = 1;
return(false);
}
int i(0);
while((i < numParents) & (!thisHasAstochParent)) {
if(thisGraphNode->parents[i]->type == STOCH) {
thisHasAstochParent = true;
}
i++;
}
if(thisHasAstochParent) {
anyStochParents[CgraphID] = 2;
return(true);
}
i = 0;
while((i < numParents) & (!thisHasAstochParent)) {
thisParentNode = thisGraphNode->parents[i];
if(anyStochParentsOneNode(anyStochParents, thisParentNode->CgraphID)) {
thisHasAstochParent = true;
}
i++;
}
if(thisHasAstochParent) {
anyStochParents[CgraphID] = 2;
return(true);
}
anyStochParents[CgraphID] = 1;
return(false);
}
//#define _DEBUG_GETDEPS
vector<int> nimbleGraph::getDependencies(const vector<int> &Cnodes, const vector<int> &Comit, bool downstream) {
// assume on entry that touched = false on all nodes
// Cnodes and Comit are C-indices (meaning they start at 0)
int n = Comit.size();
int i;
vector<int> ans;
// touch omit nodes
#ifdef _DEBUG_GETDEPS
int iDownstream = static_cast<int>(downstream);
PRINTF("debugging output for getDependencies with %i nodes, %i omits, and downstream = %i. C indices (graphIDs) shown are 0-based\n", Cnodes.size(), Comit.size(), iDownstream);
#endif
for(i = 0; i < n; i++) {
graphNodeVec[ Comit[i] ]->touched = true;
#ifdef _DEBUG_GETDEPS
PRINTF("touching %i to omit\n", Comit[i]);
#endif
}
n = Cnodes.size();
graphNode *thisGraphNode;
int thisGraphNodeID;
for(i = 0; i < n; i++) {
thisGraphNodeID = Cnodes[i];
thisGraphNode = graphNodeVec[ thisGraphNodeID ];
#ifdef _DEBUG_GETDEPS
PRINTF("Working on input node %i\n", thisGraphNodeID);
#endif
if(!thisGraphNode->touched) {
#ifdef _DEBUG_GETDEPS
PRINTF(" Adding node %i to ans and recursing\n", thisGraphNodeID);
#endif
ans.push_back(thisGraphNodeID);
thisGraphNode->touched = true;
getDependenciesOneNode(ans, thisGraphNodeID, downstream, 1);
} else {
#ifdef _DEBUG_GETDEPS
PRINTF(" Node %i was already touched\n", thisGraphNodeID);
#endif
}
}
// untouch nodes and omit
n = Comit.size();
for(i = 0; i < n; i++) {
graphNodeVec[ Comit[i] ]->touched = false;
}
n = ans.size();
for(i = 0; i < n; i++) {
graphNodeVec[ ans[i] ]->touched = false;
}
std::sort(ans.begin(), ans.end());
return(ans);
}
void nimbleGraph::getDependenciesOneNode(vector<int> &deps, int CgraphID, bool downstream, int recursionDepth) {
if(recursionDepth > graphNodeVec.size()) {
PRINTF("ERROR: getDependencies has recursed too far. Something must be wrong.\n");
return;
}
#ifdef _DEBUG_GETDEPS
PRINTF(" Entering recursion for node %i\n", CgraphID);
#endif
graphNode *thisGraphNode = graphNodeVec[CgraphID];
int numChildren = thisGraphNode->numChildren;
int i(0);
graphNode *thisChildNode;
int thisChildCgraphID;
#ifdef _DEBUG_GETDEPS
PRINTF(" Starting to iterate through %i children of node %i\n", numChildren, CgraphID);
#endif
for(; i < numChildren; i++) {
thisChildNode = thisGraphNode->children[i];
if(thisChildNode->touched) continue;
thisChildCgraphID = thisChildNode->CgraphID;
#ifdef _DEBUG_GETDEPS
PRINTF(" Adding child node %i\n", thisChildCgraphID);
#endif
deps.push_back(thisChildNode->CgraphID);
thisChildNode->touched = true;
if(downstream | (thisChildNode->type != STOCH)) {
#ifdef _DEBUG_GETDEPS
PRINTF(" Recursing into child node %i\n", thisChildCgraphID);
#endif
getDependenciesOneNode(deps, thisChildCgraphID, downstream, recursionDepth + 1);
}
}
#ifdef _DEBUG_GETDEPS
PRINTF(" Done iterating through %i children of node %i\n", numChildren, CgraphID);
#endif
}
<commit_msg>clean nimbleGraph.cpp out of src<commit_after><|endoftext|> |
<commit_before>// Petter Strandmark 2013.
#include <cstdio>
#include <queue>
#include <set>
#include <sstream>
#include <spii/solver.h>
#include <spii/spii.h>
namespace spii {
struct GlobalQueueEntry
{
double volume;
IntervalVector box;
double best_known_lower_bound;
bool operator < (const GlobalQueueEntry& rhs) const
{
return this->volume < rhs.volume;
}
};
typedef std::priority_queue<GlobalQueueEntry> IntervalQueue;
std::ostream& operator << (std::ostream& out, IntervalQueue queue)
{
while (!queue.empty()) {
const auto box = queue.top().box;
queue.pop();
out << box[0] << "; ";
}
out << std::endl;
return out;
}
void midpoint(const IntervalVector& x, Eigen::VectorXd* x_mid)
{
x_mid->resize(x.size());
for (int i = 0; i < x.size(); ++i) {
(*x_mid)[i] = (x[i].get_upper() + x[i].get_lower()) / 2.0;
}
}
double volume(const IntervalVector& x)
{
if (x.empty()) {
return 0.0;
}
double vol = 1.0;
for (auto itr = x.begin(); itr != x.end(); ++itr) {
const auto& interval = *itr;
vol *= interval.get_upper() - interval.get_lower();
}
return vol;
}
IntervalVector get_bounding_box(const IntervalQueue& queue_in,
double* function_lower_bound,
double* sum_of_volumes)
{
*sum_of_volumes = 0;
if (queue_in.empty()) {
return IntervalVector();
}
// Make copy.
auto queue = queue_in;
auto n = queue_in.top().box.size();
std::vector<double> upper_bound(n, -1e100);
std::vector<double> lower_bound(n, 1e100);
*function_lower_bound = std::numeric_limits<double>::infinity();
while (!queue.empty()) {
const auto& box = queue.top().box;
for (int i = 0; i < n; ++i) {
lower_bound[i] = std::min(lower_bound[i], box[i].get_lower());
upper_bound[i] = std::max(upper_bound[i], box[i].get_upper());
}
*sum_of_volumes += spii::volume(box);
*function_lower_bound = std::min(*function_lower_bound, queue.top().best_known_lower_bound);
queue.pop();
}
IntervalVector out(n);
for (int i = 0; i < n; ++i) {
out[i] = Interval<double>(lower_bound[i], upper_bound[i]);
}
return out;
}
void split_interval(const IntervalVector& x,
double lower_bound,
IntervalQueue* queue)
{
auto n = x.size();
std::vector<int> split(n, 0);
Eigen::VectorXd mid;
midpoint(x, &mid);
while (true) {
IntervalVector x_split(n);
double volume = 1.0;
for (int i = 0; i < n; ++i) {
double a, b;
if (split[i] == 0) {
a = x[i].get_lower();
b = mid[i];
}
else {
a = mid[i];
b = x[i].get_upper();
}
x_split[i] = Interval<double>(a, b);
volume *= b - a;
}
GlobalQueueEntry entry;
entry.volume = volume;
entry.box = x_split;
entry.best_known_lower_bound = lower_bound;
queue->push(entry);
// Move to the next binary vector
// 000001
// 000010
// 000011
// ...
// 111111
int i = 0;
split[i]++;
while (split[i] > 1) {
split[i] = 0;
i++;
if (i < n) {
split[i]++;
}
else {
break;
}
}
if (i == n) {
break;
}
}
}
void GlobalSolver::solve(const Function& function,
SolverResults* results) const
{
spii_assert(false, "GlobalSolver::solve_global should be called.");
}
IntervalVector GlobalSolver::solve_global(const Function& function,
const IntervalVector& x_interval,
SolverResults* results) const
{
using namespace std;
double global_start_time = wall_time();
check(x_interval.size() == function.get_number_of_scalars(),
"solve_global: input vector does not match the function's number of scalars");
auto n = x_interval.size();
IntervalQueue queue;
GlobalQueueEntry entry;
entry.volume = 1e100;
entry.box = x_interval;
queue.push(entry);
auto bounds = function.evaluate(x_interval);
double upper_bound = bounds.get_upper();
double lower_bound = - std::numeric_limits<double>::infinity();
Eigen::VectorXd best_x(n);
IntervalVector best_interval;
int iterations = 0;
results->exit_condition = SolverResults::INTERNAL_ERROR;
while (!queue.empty()) {
double start_time = wall_time();
if (iterations >= this->maximum_iterations) {
results->exit_condition = SolverResults::NO_CONVERGENCE;
break;
}
const auto box = queue.top().box;
best_interval = box;
// Remove current element from queue.
queue.pop();
auto bounds = function.evaluate(box);
//cerr << "-- Processing " << box << " resulting in " << bounds << ". Upper bound is " << upper_bound << endl;
if (bounds.get_lower() < upper_bound) {
// Evaluate middle point.
Eigen::VectorXd x(box.size());
midpoint(box, &x);
double value = function.evaluate(x);
if (value < upper_bound) {
upper_bound = value;
best_x = x;
}
// Add new elements to queue.
split_interval(box, bounds.get_lower(), &queue);
}
results->function_evaluation_time += wall_time() - start_time;
iterations++;
start_time = wall_time();
int log_interval = 1;
if (iterations > 20) {
log_interval = 10;
}
if (iterations > 200) {
log_interval = 100;
}
if (iterations > 2000) {
log_interval = 1000;
}
if (iterations > 20000) {
log_interval = 10000;
}
if (iterations > 200000) {
log_interval = 100000;
}
if (iterations >= this->maximum_iterations - 2) {
log_interval = 1;
}
if (iterations % log_interval == 0) {
double volumes_sum;
lower_bound = upper_bound; // Default lower bound if queue is empty (problem is solved).
auto bounding_box = get_bounding_box(queue, &lower_bound, &volumes_sum);
double vol_bounding = volume(bounding_box);
double avg_magnitude = (std::abs(lower_bound) + std::abs(upper_bound)) / 2.0;
double relative_gap = (upper_bound - lower_bound) / avg_magnitude;
results->stopping_criteria_time += wall_time() - start_time;
start_time = wall_time();
if (this->log_function) {
if (iterations == 1) {
this->log_function("Iteration Q-size l.bound u.bound rel.gap bounding volume");
this->log_function("----------------------------------------------------------------------");
}
char tmp[1024];
sprintf(tmp, "%9d %6d %+10.3e %+10.3e %10.2e %10.3e %10.3e",
iterations,
int(queue.size()),
lower_bound,
upper_bound,
relative_gap,
vol_bounding,
volumes_sum);
this->log_function(tmp);
}
results->log_time += wall_time() - start_time;
if (relative_gap <= this->function_improvement_tolerance) {
results->exit_condition = SolverResults::FUNCTION_TOLERANCE;
break;
}
if (vol_bounding <= this->argument_improvement_tolerance) {
results->exit_condition = SolverResults::ARGUMENT_TOLERANCE;
break;
}
}
}
double tmp1, tmp2;
auto bounding_box = get_bounding_box(queue, &tmp1, &tmp2);
if (bounding_box.empty()) {
// Problem was solved exactly (queue empty)
spii_assert(queue.empty());
results->exit_condition = SolverResults::FUNCTION_TOLERANCE;
bounding_box = best_interval;
}
function.copy_global_to_user(best_x);
results->optimum_lower = lower_bound;
results->optimum_upper = upper_bound;
results->total_time = wall_time() - global_start_time;
return bounding_box;
}
} // namespace spii
<commit_msg>Performance improvements to global solver.<commit_after>// Petter Strandmark 2013.
#include <algorithm>
#include <cstdio>
#include <queue>
#include <set>
#include <sstream>
#include <spii/solver.h>
#include <spii/spii.h>
namespace spii {
struct GlobalQueueEntry
{
double volume;
IntervalVector box;
double best_known_lower_bound;
bool operator < (const GlobalQueueEntry& rhs) const
{
return this->volume < rhs.volume;
}
};
typedef std::vector<GlobalQueueEntry> IntervalQueue;
std::ostream& operator << (std::ostream& out, IntervalQueue queue)
{
while (!queue.empty()) {
const auto box = queue.front().box;
std::pop_heap(begin(queue), end(queue)); queue.pop_back();
out << box[0] << "; ";
}
out << std::endl;
return out;
}
void midpoint(const IntervalVector& x, Eigen::VectorXd* x_mid)
{
x_mid->resize(x.size());
for (int i = 0; i < x.size(); ++i) {
(*x_mid)[i] = (x[i].get_upper() + x[i].get_lower()) / 2.0;
}
}
double volume(const IntervalVector& x)
{
if (x.empty()) {
return 0.0;
}
double vol = 1.0;
for (auto itr = x.begin(); itr != x.end(); ++itr) {
const auto& interval = *itr;
vol *= interval.get_upper() - interval.get_lower();
}
return vol;
}
IntervalVector get_bounding_box(const IntervalQueue& queue_in,
double* function_lower_bound,
double* sum_of_volumes)
{
*sum_of_volumes = 0;
if (queue_in.empty()) {
return IntervalVector();
}
auto n = queue_in.front().box.size();
std::vector<double> upper_bound(n, -1e100);
std::vector<double> lower_bound(n, 1e100);
*function_lower_bound = std::numeric_limits<double>::infinity();
for (const auto& elem: queue_in) {
const auto& box = elem.box;
for (int i = 0; i < n; ++i) {
lower_bound[i] = std::min(lower_bound[i], box[i].get_lower());
upper_bound[i] = std::max(upper_bound[i], box[i].get_upper());
}
*sum_of_volumes += spii::volume(box);
*function_lower_bound = std::min(*function_lower_bound, elem.best_known_lower_bound);
}
IntervalVector out(n);
for (int i = 0; i < n; ++i) {
out[i] = Interval<double>(lower_bound[i], upper_bound[i]);
}
return out;
}
void split_interval(const IntervalVector& x,
double lower_bound,
IntervalQueue* queue)
{
auto n = x.size();
std::vector<int> split(n, 0);
Eigen::VectorXd mid;
midpoint(x, &mid);
while (true) {
queue->emplace_back();
GlobalQueueEntry& entry = queue->back();
IntervalVector& x_split = entry.box;
x_split.resize(n);
double volume = 1.0;
for (int i = 0; i < n; ++i) {
double a, b;
if (split[i] == 0) {
a = x[i].get_lower();
b = mid[i];
}
else {
a = mid[i];
b = x[i].get_upper();
}
x_split[i] = Interval<double>(a, b);
volume *= b - a;
}
entry.volume = volume;
entry.best_known_lower_bound = lower_bound;
std::push_heap(begin(*queue), end(*queue));
// Move to the next binary vector
// 000001
// 000010
// 000011
// ...
// 111111
int i = 0;
split[i]++;
while (split[i] > 1) {
split[i] = 0;
i++;
if (i < n) {
split[i]++;
}
else {
break;
}
}
if (i == n) {
break;
}
}
}
void GlobalSolver::solve(const Function& function,
SolverResults* results) const
{
spii_assert(false, "GlobalSolver::solve_global should be called.");
}
IntervalVector GlobalSolver::solve_global(const Function& function,
const IntervalVector& x_interval,
SolverResults* results) const
{
using namespace std;
double global_start_time = wall_time();
check(x_interval.size() == function.get_number_of_scalars(),
"solve_global: input vector does not match the function's number of scalars");
auto n = x_interval.size();
IntervalQueue queue;
queue.reserve(2 * this->maximum_iterations);
GlobalQueueEntry entry;
entry.volume = 1e100;
entry.box = x_interval;
queue.push_back(entry);
auto bounds = function.evaluate(x_interval);
double upper_bound = bounds.get_upper();
double lower_bound = - std::numeric_limits<double>::infinity();
Eigen::VectorXd best_x(n);
IntervalVector best_interval;
int iterations = 0;
results->exit_condition = SolverResults::INTERNAL_ERROR;
while (!queue.empty()) {
double start_time = wall_time();
if (iterations >= this->maximum_iterations) {
results->exit_condition = SolverResults::NO_CONVERGENCE;
break;
}
const auto box = queue.front().box;
best_interval = box;
// Remove current element from queue.
pop_heap(begin(queue), end(queue)); queue.pop_back();
auto bounds = function.evaluate(box);
//cerr << "-- Processing " << box << " resulting in " << bounds << ". Upper bound is " << upper_bound << endl;
if (bounds.get_lower() < upper_bound) {
// Evaluate middle point.
Eigen::VectorXd x(box.size());
midpoint(box, &x);
double value = function.evaluate(x);
if (value < upper_bound) {
upper_bound = value;
best_x = x;
}
// Add new elements to queue.
split_interval(box, bounds.get_lower(), &queue);
}
results->function_evaluation_time += wall_time() - start_time;
iterations++;
start_time = wall_time();
int log_interval = 1;
if (iterations > 20) {
log_interval = 10;
}
if (iterations > 200) {
log_interval = 100;
}
if (iterations > 2000) {
log_interval = 1000;
}
if (iterations > 20000) {
log_interval = 10000;
}
if (iterations > 200000) {
log_interval = 100000;
}
if (iterations >= this->maximum_iterations - 2) {
log_interval = 1;
}
if (iterations % log_interval == 0) {
double volumes_sum;
lower_bound = upper_bound; // Default lower bound if queue is empty (problem is solved).
auto bounding_box = get_bounding_box(queue, &lower_bound, &volumes_sum);
double vol_bounding = volume(bounding_box);
double avg_magnitude = (std::abs(lower_bound) + std::abs(upper_bound)) / 2.0;
double relative_gap = (upper_bound - lower_bound) / avg_magnitude;
results->stopping_criteria_time += wall_time() - start_time;
start_time = wall_time();
if (this->log_function) {
if (iterations == 1) {
this->log_function("Iteration Q-size l.bound u.bound rel.gap bounding volume");
this->log_function("----------------------------------------------------------------------");
}
char tmp[1024];
sprintf(tmp, "%9d %6d %+10.3e %+10.3e %10.2e %10.3e %10.3e",
iterations,
int(queue.size()),
lower_bound,
upper_bound,
relative_gap,
vol_bounding,
volumes_sum);
this->log_function(tmp);
}
results->log_time += wall_time() - start_time;
if (relative_gap <= this->function_improvement_tolerance) {
results->exit_condition = SolverResults::FUNCTION_TOLERANCE;
break;
}
if (vol_bounding <= this->argument_improvement_tolerance) {
results->exit_condition = SolverResults::ARGUMENT_TOLERANCE;
break;
}
}
}
double tmp1, tmp2;
auto bounding_box = get_bounding_box(queue, &tmp1, &tmp2);
if (bounding_box.empty()) {
// Problem was solved exactly (queue empty)
spii_assert(queue.empty());
results->exit_condition = SolverResults::FUNCTION_TOLERANCE;
bounding_box = best_interval;
}
function.copy_global_to_user(best_x);
results->optimum_lower = lower_bound;
results->optimum_upper = upper_bound;
results->total_time = wall_time() - global_start_time;
return bounding_box;
}
} // namespace spii
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <mutex>
// class recursive_timed_mutex;
// template <class Rep, class Period>
// bool try_lock_for(const chrono::duration<Rep, Period>& rel_time);
#include <mutex>
#include <thread>
#include <cstdlib>
#include <cassert>
std::recursive_timed_mutex m;
typedef std::chrono::monotonic_clock Clock;
typedef Clock::time_point time_point;
typedef Clock::duration duration;
typedef std::chrono::milliseconds ms;
typedef std::chrono::nanoseconds ns;
void f1()
{
time_point t0 = Clock::now();
assert(m.try_lock_for(ms(300)) == true);
time_point t1 = Clock::now();
assert(m.try_lock());
m.unlock();
m.unlock();
ns d = t1 - t0 - ms(250);
assert(d < ns(5000000)); // within 5ms
}
void f2()
{
time_point t0 = Clock::now();
assert(m.try_lock_for(ms(250)) == false);
time_point t1 = Clock::now();
ns d = t1 - t0 - ms(250);
assert(d < ns(5000000)); // within 5ms
}
int main()
{
{
m.lock();
std::thread t(f1);
std::this_thread::sleep_for(ms(250));
m.unlock();
t.join();
}
{
m.lock();
std::thread t(f2);
std::this_thread::sleep_for(ms(300));
m.unlock();
t.join();
}
}
<commit_msg>Relaxing timing test a bit to avoid spurious test failures under load<commit_after>//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <mutex>
// class recursive_timed_mutex;
// template <class Rep, class Period>
// bool try_lock_for(const chrono::duration<Rep, Period>& rel_time);
#include <mutex>
#include <thread>
#include <cstdlib>
#include <cassert>
std::recursive_timed_mutex m;
typedef std::chrono::monotonic_clock Clock;
typedef Clock::time_point time_point;
typedef Clock::duration duration;
typedef std::chrono::milliseconds ms;
typedef std::chrono::nanoseconds ns;
void f1()
{
time_point t0 = Clock::now();
assert(m.try_lock_for(ms(300)) == true);
time_point t1 = Clock::now();
assert(m.try_lock());
m.unlock();
m.unlock();
ns d = t1 - t0 - ms(250);
assert(d < ns(50000000)); // within 50ms
}
void f2()
{
time_point t0 = Clock::now();
assert(m.try_lock_for(ms(250)) == false);
time_point t1 = Clock::now();
ns d = t1 - t0 - ms(250);
assert(d < ns(50000000)); // within 50ms
}
int main()
{
{
m.lock();
std::thread t(f1);
std::this_thread::sleep_for(ms(250));
m.unlock();
t.join();
}
{
m.lock();
std::thread t(f2);
std::this_thread::sleep_for(ms(300));
m.unlock();
t.join();
}
}
<|endoftext|> |
<commit_before>/*
Similar to #132. We need to look for factors q of \phi(9p) of the form q =
2^a5^b such that 9n | 10^q. Unlike #132, the restriction that 0 <= a, b <= 9
is removed here.
*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include "number_util.h"
#include "prime_util.h"
bool is_factor(int p)
{
int order_max = p == 3 ? 18 : 6 * (p - 1);
int a_max = 0;
int b_max = 0;
while (order_max % 2 == 0)
{
a_max++;
order_max /= 2;
}
while (order_max % 5 == 0)
{
b_max++;
order_max /= 5;
}
for (int a = 0; a <= a_max; a++)
{
for (int b = 0; b <= b_max; b++)
{
unsigned long int q = std::pow(2, a) * std::pow(5, b);
if (util::pow(mpz_class(10), q) % (9 * p) == 1)
return true;
}
}
return false;
}
int main()
{
int s = 0;
std::vector<int> primes = util::get_primes(100000 - 1);
for (int &prime : primes)
if (!is_factor(prime))
s += prime;
std::cout << s;
}
<commit_msg>Changed to pow_mod.<commit_after>/*
Similar to #132. We need to look for factors q of \phi(9p) of the form q =
2^a5^b such that 9n | 10^q. Unlike #132, the restriction that 0 <= a, b <= 9
is removed here.
*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include "number_util.h"
#include "prime_util.h"
bool is_factor(int p)
{
int order_max = p == 3 ? 18 : 6 * (p - 1);
int a_max = 0;
int b_max = 0;
while (order_max % 2 == 0)
{
a_max++;
order_max /= 2;
}
while (order_max % 5 == 0)
{
b_max++;
order_max /= 5;
}
for (int a = 0; a <= a_max; a++)
{
for (int b = 0; b <= b_max; b++)
{
unsigned long int q = std::pow(2, a) * std::pow(5, b);
if (util::pow_mod(mpz_class(10), q, mpz_class(9 * p)) == 1)
return true;
}
}
return false;
}
int main()
{
int s = 0;
std::vector<int> primes = util::get_primes(100000 - 1);
for (int &prime : primes)
if (!is_factor(prime))
s += prime;
std::cout << s;
}
<|endoftext|> |
<commit_before>#include <windows.h>
#include <gl\gl.h>
#ifdef _MSC_VER
#define _USE_MATH_DEFINES
#endif
#include <math.h>
#include "Window.h"
#include "Body.h"
#include "Error.h"
#include "Info.h"
#define NAME_FONT_NAME "Arial"
#define NAME_FONT_SIZE_AT_H600 24
#define NAME_FONT_SIZE (int)(NAME_FONT_SIZE_AT_H600*scrheight/600)
#define NAME_TEXT_COLOR_R 1.00f
#define NAME_TEXT_COLOR_G 1.00f
#define NAME_TEXT_COLOR_B 1.00f
#define NAME_TEXT_COLOR_A 0.50f
#define INFO_FONT_NAME "Arial"
#define INFO_FONT_SIZE_AT_H600 16
#define INFO_FONT_SIZE (int)(INFO_FONT_SIZE_AT_H600*scrheight/600)
#define INFO_TEXT_COLOR_R 1.00f
#define INFO_TEXT_COLOR_G 1.00f
#define INFO_TEXT_COLOR_B 1.00f
#define INFO_TEXT_COLOR_A 0.50f
#define SCREEN_SIZE_RATIO_STD (4.0f/3.0f)
#define FONT_SIZE_COEFF (4.6f/3.0f) // do not change!
#define SPACING_COEF 1.15f
#define LINES_AFTER_NAME 1.00f
#define WINDOW_COLOR_R 0.50f
#define WINDOW_COLOR_G 0.50f
#define WINDOW_COLOR_B 0.50f
#define WINDOW_COLOR_A 0.25f
#define MAX_FADE_TIME 3.0f
#define FADE_TIME_RATIO 0.10f
#define FADE_TIME(totaltime) min(MAX_FADE_TIME, (totaltime)*FADE_TIME_RATIO)
#define WINDOW_BORDER_REL 0.0125f
#define WINDOW_BORDER (int)(WINDOW_BORDER_REL*scrheight)
#define MARGIN_TOP_REL 0.0250f
#define MARGIN_BOTTOM_REL 0.0050f
#define MARGIN_LEFT_REL (0.0200f*SCREEN_SIZE_RATIO_STD)
#define MARGIN_LEFT_WIDTH (int)(MARGIN_LEFT_REL*scrheight)
#define MARGIN_TOP_HEIGHT (int)(MARGIN_TOP_REL*scrheight)
#define MARGIN_BOTTOM_HEIGHT (int)(MARGIN_BOTTOM_REL*scrheight)
#define WINDOW_WIDTH_REL_Y (0.3050f*SCREEN_SIZE_RATIO_STD)
#define WINDOW_WIDTH (int)(WINDOW_WIDTH_REL_Y*scrheight)
#define WINDOW_HEIGHT (MARGIN_TOP_HEIGHT+MARGIN_BOTTOM_HEIGHT+(int)(NAME_FONT_SIZE*LINES_AFTER_NAME*SPACING_COEF*FONT_SIZE_COEFF)+3*(int)(INFO_FONT_SIZE*SPACING_COEF*FONT_SIZE_COEFF))
#define WINDOW_POS_X1 (WINDOW_BORDER)
#define WINDOW_POS_Y1 (WINDOW_BORDER)
#define WINDOW_POS_X2 (WINDOW_POS_X1+WINDOW_WIDTH)
#define WINDOW_POS_Y2 (WINDOW_POS_Y1+WINDOW_HEIGHT)
CInfo::CInfo()
{
Init();
}
CInfo::~CInfo()
{
Free();
}
void CInfo::Init()
{
loaded=false;
scrwidth=0;
scrheight=0;
winlist=0;
namelist=infolist=0;
time=0;
starttime=endtime=0;
fadetime=1;
alpha=0;
}
void CInfo::Free()
{
nametext.Free();
infotext.Free();
if (winlist)
{
if (glIsList(winlist))
glDeleteLists(winlist,3);
}
Init();
}
bool CInfo::Load()
{
Free();
scrwidth=CWindow::GetWidth();
scrheight=CWindow::GetHeight();
winlist=glGenLists(3);
if (!winlist)
{
CError::LogError(WARNING_CODE,"Unable to load planet info - failed to generate display lists.");
Free();
return false;
}
namelist=winlist+1;
infolist=namelist+1;
MakeWindow(winlist);
loaded=true;
loaded&=nametext.BuildFTFont(NAME_FONT_NAME,NAME_FONT_SIZE);
loaded&=infotext.BuildFTFont(INFO_FONT_NAME,INFO_FONT_SIZE);
if (!loaded)
{
CError::LogError(WARNING_CODE,"Unable to load planet info - failed to load font.");
Free();
}
return loaded;
}
void CInfo::MakeWindow(int list)
{
glNewList(list,GL_COMPILE);
{
int l=WINDOW_POS_X1;
int r=WINDOW_POS_X2;
int b=WINDOW_POS_Y1;
int t=WINDOW_POS_Y2;
glDisable(GL_TEXTURE_2D);
glLoadIdentity();
glBegin(GL_QUADS);
{
glVertex2f((float)l,(float)b);
glVertex2f((float)r,(float)b);
glVertex2f((float)r,(float)t);
glVertex2f((float)l,(float)t);
}
glEnd();
}
glEndList();
}
void CInfo::GetNameCoords(const char *text, int *x, int *y)
{
float tw;
nametext.GetTextSize(text,&tw,NULL);
int th=NAME_FONT_SIZE;
if (x) *x=WINDOW_POS_X1+(WINDOW_WIDTH-(int)tw)/2;
if (y) *y=WINDOW_POS_Y2-MARGIN_TOP_HEIGHT-th;
}
void CInfo::GetInfoCoords(int linenum, int *x, int *y)
{
int ymargin=WINDOW_POS_Y2-MARGIN_TOP_HEIGHT;
float nameheight;
nametext.GetTextSize("",NULL,&nameheight);
float nameadd;
nameadd=nameheight*SPACING_COEF*LINES_AFTER_NAME;
int ioffset=INFO_FONT_SIZE;
float th;
infotext.GetTextSize("",NULL,&th);
th*=SPACING_COEF;
int thi=(int)th*(linenum-1);
if (x) *x=WINDOW_POS_X1+MARGIN_LEFT_WIDTH;
if (y) *y=ymargin-(int)nameadd-ioffset-thi;
}
void CInfo::MakeName(int list, char *targetname)
{
if (!targetname) return;
if (*targetname==' ') targetname++;
int x,y;
GetNameCoords(targetname,&x,&y);
glNewList(list,GL_COMPILE);
{
glEnable(GL_TEXTURE_2D);
glLoadIdentity();
glTranslatef((float)x,(float)y,0);
nametext.Print(targetname);
}
glEndList();
}
void CInfo::MakeInfoLine(int linenum, char *line)
{
int x,y;
GetInfoCoords(linenum,&x,&y);
glPushMatrix();
glTranslatef((float)x,(float)y,0);
infotext.Print(line);
glPopMatrix();
}
void CInfo::MakeInfo(int list, CBody *targetbody)
{
bool star=(targetbody==NULL);
if (star) targetbody=CBody::bodycache[0];
glNewList(list,GL_COMPILE);
{
int n=0;
glEnable(GL_TEXTURE_2D);
glLoadIdentity();
if (star)
{
char line[64];
n++;
sprintf(line,"star name: %s",targetbody->name);
MakeInfoLine(n,line);
}
for (int i=0;i<targetbody->info.numlines;i++)
{
if (targetbody->info.textlines[i][0]=='/') continue;
n++;
MakeInfoLine(n,targetbody->info.textlines[i]);
}
}
glEndList();
}
void CInfo::Start(float seconds, float duration, char *targetname, CBody *targetbody)
{
if (!loaded)
return;
char name[32];
strcpy(name,targetname);
int l=strlen(name);
for (int i=0;i<l;i++)
if (name[i]=='_')
name[i]=' ';
starttime=seconds;
endtime=starttime+duration;
fadetime=FADE_TIME(duration);
MakeName(namelist,name);
MakeInfo(infolist,targetbody);
}
void CInfo::Update(float seconds)
{
time=seconds;
if (time<(endtime-fadetime))
alpha=min(1,(time-starttime)/fadetime);
else
alpha=max(0,(endtime-time)/fadetime);
}
void CInfo::Restart()
{
starttime-=time;
endtime-=time;
time=0;
}
void CInfo::Draw()
{
if (!alpha || !loaded)
return;
glDisable(GL_LIGHTING);
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
glEnable(GL_BLEND);
glColor4f(WINDOW_COLOR_R,WINDOW_COLOR_G,WINDOW_COLOR_B,WINDOW_COLOR_A*alpha);
glCallList(winlist);
glColor4f(NAME_TEXT_COLOR_R,NAME_TEXT_COLOR_G,NAME_TEXT_COLOR_B,NAME_TEXT_COLOR_A*alpha);
glCallList(namelist);
glColor4f(INFO_TEXT_COLOR_R,INFO_TEXT_COLOR_G,INFO_TEXT_COLOR_B,INFO_TEXT_COLOR_A*alpha);
glCallList(infolist);
}
<commit_msg>Adjustments to info parameters.<commit_after>#include <windows.h>
#include <gl\gl.h>
#ifdef _MSC_VER
#define _USE_MATH_DEFINES
#endif
#include <math.h>
#include "Window.h"
#include "Body.h"
#include "Error.h"
#include "Info.h"
#define NAME_FONT_NAME "Arial"
#define NAME_FONT_SIZE_AT_H600 24
#define NAME_FONT_SIZE (int)(NAME_FONT_SIZE_AT_H600*scrheight/600)
#define NAME_TEXT_COLOR_R 1.00f
#define NAME_TEXT_COLOR_G 1.00f
#define NAME_TEXT_COLOR_B 1.00f
#define NAME_TEXT_COLOR_A 0.50f
#define INFO_FONT_NAME "Arial"
#define INFO_FONT_SIZE_AT_H600 16
#define INFO_FONT_SIZE (int)(INFO_FONT_SIZE_AT_H600*scrheight/600)
#define INFO_TEXT_COLOR_R 1.00f
#define INFO_TEXT_COLOR_G 1.00f
#define INFO_TEXT_COLOR_B 1.00f
#define INFO_TEXT_COLOR_A 0.50f
#define SCREEN_SIZE_RATIO_STD (4.0f/3.0f)
#define FONT_SIZE_COEFF (4.6f/3.0f) // do not change!
#define SPACING_COEF 1.15f
#define LINES_AFTER_NAME 1.125f
#define WINDOW_COLOR_R 0.50f
#define WINDOW_COLOR_G 0.50f
#define WINDOW_COLOR_B 0.50f
#define WINDOW_COLOR_A 0.25f
#define MAX_FADE_TIME 3.0f
#define FADE_TIME_RATIO 0.10f
#define FADE_TIME(totaltime) min(MAX_FADE_TIME, (totaltime)*FADE_TIME_RATIO)
#define WINDOW_BORDER_REL 0.0125f
#define WINDOW_BORDER (int)(WINDOW_BORDER_REL*scrheight)
#define MARGIN_TOP_REL 0.0250f
#define MARGIN_BOTTOM_REL 0.0050f
#define MARGIN_LEFT_REL (0.0200f*SCREEN_SIZE_RATIO_STD)
#define MARGIN_LEFT_WIDTH (int)(MARGIN_LEFT_REL*scrheight)
#define MARGIN_TOP_HEIGHT (int)(MARGIN_TOP_REL*scrheight)
#define MARGIN_BOTTOM_HEIGHT (int)(MARGIN_BOTTOM_REL*scrheight)
#define WINDOW_WIDTH_REL_Y (0.3050f*SCREEN_SIZE_RATIO_STD)
#define WINDOW_WIDTH (int)(WINDOW_WIDTH_REL_Y*scrheight)
#define WINDOW_HEIGHT (MARGIN_TOP_HEIGHT+MARGIN_BOTTOM_HEIGHT+(int)(NAME_FONT_SIZE*LINES_AFTER_NAME*SPACING_COEF*FONT_SIZE_COEFF)+3*(int)(INFO_FONT_SIZE*SPACING_COEF*FONT_SIZE_COEFF))
#define WINDOW_POS_X1 (WINDOW_BORDER)
#define WINDOW_POS_Y1 (WINDOW_BORDER)
#define WINDOW_POS_X2 (WINDOW_POS_X1+WINDOW_WIDTH)
#define WINDOW_POS_Y2 (WINDOW_POS_Y1+WINDOW_HEIGHT)
CInfo::CInfo()
{
Init();
}
CInfo::~CInfo()
{
Free();
}
void CInfo::Init()
{
loaded=false;
scrwidth=0;
scrheight=0;
winlist=0;
namelist=infolist=0;
time=0;
starttime=endtime=0;
fadetime=1;
alpha=0;
}
void CInfo::Free()
{
nametext.Free();
infotext.Free();
if (winlist)
{
if (glIsList(winlist))
glDeleteLists(winlist,3);
}
Init();
}
bool CInfo::Load()
{
Free();
scrwidth=CWindow::GetWidth();
scrheight=CWindow::GetHeight();
winlist=glGenLists(3);
if (!winlist)
{
CError::LogError(WARNING_CODE,"Unable to load planet info - failed to generate display lists.");
Free();
return false;
}
namelist=winlist+1;
infolist=namelist+1;
MakeWindow(winlist);
loaded=true;
loaded&=nametext.BuildFTFont(NAME_FONT_NAME,NAME_FONT_SIZE);
loaded&=infotext.BuildFTFont(INFO_FONT_NAME,INFO_FONT_SIZE);
if (!loaded)
{
CError::LogError(WARNING_CODE,"Unable to load planet info - failed to load font.");
Free();
}
return loaded;
}
void CInfo::MakeWindow(int list)
{
glNewList(list,GL_COMPILE);
{
int l=WINDOW_POS_X1;
int r=WINDOW_POS_X2;
int b=WINDOW_POS_Y1;
int t=WINDOW_POS_Y2;
glDisable(GL_TEXTURE_2D);
glLoadIdentity();
glBegin(GL_QUADS);
{
glVertex2f((float)l,(float)b);
glVertex2f((float)r,(float)b);
glVertex2f((float)r,(float)t);
glVertex2f((float)l,(float)t);
}
glEnd();
}
glEndList();
}
void CInfo::GetNameCoords(const char *text, int *x, int *y)
{
float tw;
nametext.GetTextSize(text,&tw,NULL);
int th=NAME_FONT_SIZE;
if (x) *x=WINDOW_POS_X1+(WINDOW_WIDTH-(int)tw)/2;
if (y) *y=WINDOW_POS_Y2-MARGIN_TOP_HEIGHT-th;
}
void CInfo::GetInfoCoords(int linenum, int *x, int *y)
{
int ymargin=WINDOW_POS_Y2-MARGIN_TOP_HEIGHT;
float nameheight;
nametext.GetTextSize("",NULL,&nameheight);
float nameadd;
nameadd=nameheight*SPACING_COEF*LINES_AFTER_NAME;
int ioffset=INFO_FONT_SIZE;
float th;
infotext.GetTextSize("",NULL,&th);
th*=SPACING_COEF;
int thi=(int)th*(linenum-1);
if (x) *x=WINDOW_POS_X1+MARGIN_LEFT_WIDTH;
if (y) *y=ymargin-(int)nameadd-ioffset-thi;
}
void CInfo::MakeName(int list, char *targetname)
{
if (!targetname) return;
if (*targetname==' ') targetname++;
int x,y;
GetNameCoords(targetname,&x,&y);
glNewList(list,GL_COMPILE);
{
glEnable(GL_TEXTURE_2D);
glLoadIdentity();
glTranslatef((float)x,(float)y,0);
nametext.Print(targetname);
}
glEndList();
}
void CInfo::MakeInfoLine(int linenum, char *line)
{
int x,y;
GetInfoCoords(linenum,&x,&y);
glPushMatrix();
glTranslatef((float)x,(float)y,0);
infotext.Print(line);
glPopMatrix();
}
void CInfo::MakeInfo(int list, CBody *targetbody)
{
bool star=(targetbody==NULL);
if (star) targetbody=CBody::bodycache[0];
glNewList(list,GL_COMPILE);
{
int n=0;
glEnable(GL_TEXTURE_2D);
glLoadIdentity();
if (star)
{
char line[64];
n++;
sprintf(line,"star name: %s",targetbody->name);
MakeInfoLine(n,line);
}
for (int i=0;i<targetbody->info.numlines;i++)
{
if (targetbody->info.textlines[i][0]=='/') continue;
n++;
MakeInfoLine(n,targetbody->info.textlines[i]);
}
}
glEndList();
}
void CInfo::Start(float seconds, float duration, char *targetname, CBody *targetbody)
{
if (!loaded)
return;
char name[32];
strcpy(name,targetname);
int l=strlen(name);
for (int i=0;i<l;i++)
if (name[i]=='_')
name[i]=' ';
starttime=seconds;
endtime=starttime+duration;
fadetime=FADE_TIME(duration);
MakeName(namelist,name);
MakeInfo(infolist,targetbody);
}
void CInfo::Update(float seconds)
{
time=seconds;
if (time<(endtime-fadetime))
alpha=min(1,(time-starttime)/fadetime);
else
alpha=max(0,(endtime-time)/fadetime);
}
void CInfo::Restart()
{
starttime-=time;
endtime-=time;
time=0;
}
void CInfo::Draw()
{
if (!alpha || !loaded)
return;
glDisable(GL_LIGHTING);
glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE);
glEnable(GL_BLEND);
glColor4f(WINDOW_COLOR_R,WINDOW_COLOR_G,WINDOW_COLOR_B,WINDOW_COLOR_A*alpha);
glCallList(winlist);
glColor4f(NAME_TEXT_COLOR_R,NAME_TEXT_COLOR_G,NAME_TEXT_COLOR_B,NAME_TEXT_COLOR_A*alpha);
glCallList(namelist);
glColor4f(INFO_TEXT_COLOR_R,INFO_TEXT_COLOR_G,INFO_TEXT_COLOR_B,INFO_TEXT_COLOR_A*alpha);
glCallList(infolist);
}
<|endoftext|> |
<commit_before>#include "LICM.h"
#include "CSE.h"
#include "ExprUsesVar.h"
#include "IREquality.h"
#include "IRMutator.h"
#include "IROperator.h"
#include "Scope.h"
#include "Simplify.h"
#include "Substitute.h"
namespace Halide {
namespace Internal {
using std::string;
using std::map;
using std::vector;
using std::pair;
using std::set;
// Is it safe to lift an Expr out of a loop (and potentially across a device boundary)
class CanLift : public IRVisitor {
using IRVisitor::visit;
void visit(const Call *op) {
if (!op->is_pure()) {
result = false;
} else {
IRVisitor::visit(op);
}
}
void visit(const Load *op) {
result = false;
}
void visit(const Variable *op) {
if (varying.contains(op->name)) {
result = false;
}
}
const Scope<int> &varying;
public:
bool result {true};
CanLift(const Scope<int> &v) : varying(v) {}
};
// Lift pure loop invariants to the top level. Applied independently
// to each loop.
class LiftLoopInvariants : public IRMutator2 {
using IRMutator2::visit;
Scope<int> varying;
bool can_lift(const Expr &e) {
CanLift check(varying);
e.accept(&check);
return check.result;
}
bool should_lift(const Expr &e) {
if (!can_lift(e)) return false;
if (e.as<Variable>()) return false;
if (e.as<Broadcast>()) return false;
if (is_const(e)) return false;
// bool vectors are buggy enough in LLVM that lifting them is a bad idea.
// (We just skip all vectors on the principle that we don't want them
// on the stack anyway.)
if (e.type().is_vector()) return false;
return true;
}
Expr visit(const Let *op) override {
ScopedBinding<int> p(varying, op->name, 0);
return IRMutator2::visit(op);
}
Stmt visit(const LetStmt *op) override {
ScopedBinding<int> p(varying, op->name, 0);
return IRMutator2::visit(op);
}
Stmt visit(const For *op) override {
ScopedBinding<int> p(varying, op->name, 0);
return IRMutator2::visit(op);
}
public:
using IRMutator2::mutate;
Expr mutate(const Expr &e) override {
if (should_lift(e)) {
// Lift it in canonical form
Expr lifted_expr = simplify(e);
auto it = lifted.find(lifted_expr);
if (it == lifted.end()) {
string name = unique_name('t');
lifted[lifted_expr] = name;
return Variable::make(e.type(), name);
} else {
return Variable::make(e.type(), it->second);
}
} else {
return IRMutator2::mutate(e);
}
}
map<Expr, string, IRDeepCompare> lifted;
};
class LICM : public IRMutator2 {
using IRMutator2::visit;
bool in_gpu_loop{false};
// Compute the cost of computing an expression inside the inner
// loop, compared to just loading it as a parameter.
int cost(const Expr &e, const set<string> &vars) {
if (is_const(e)) {
return 0;
} else if (const Variable *var = e.as<Variable>()) {
if (vars.count(var->name)) {
// We're loading this already
return 0;
} else {
// Would have to load this
return 1;
}
} else if (const Add *add = e.as<Add>()) {
return cost(add->a, vars) + cost(add->b, vars) + 1;
} else if (const Sub *sub = e.as<Sub>()) {
return cost(sub->a, vars) + cost(sub->b, vars) + 1;
} else if (const Mul *mul = e.as<Mul>()) {
return cost(mul->a, vars) + cost(mul->b, vars) + 1;
} else {
return 0x7fffffff;
}
}
Stmt visit(const For *op) override {
ScopedValue<bool> old_in_gpu_loop(in_gpu_loop);
in_gpu_loop =
(op->for_type == ForType::GPUBlock ||
op->for_type == ForType::GPUThread);
if (old_in_gpu_loop && in_gpu_loop) {
// Don't lift lets to in-between gpu blocks/threads
return IRMutator2::visit(op);
} else if (op->device_api == DeviceAPI::GLSL ||
op->device_api == DeviceAPI::OpenGLCompute) {
// Don't lift anything out of OpenGL loops
return IRMutator2::visit(op);
} else {
// Lift invariants
LiftLoopInvariants lifter;
Stmt new_stmt = lifter.mutate(op);
// As an optimization to reduce register pressure, take
// the set of expressions to lift and check if any can
// cheaply be computed from others. If so it's better to
// do that than to load multiple related values off the
// stack. We currently only consider expressions that are
// the sum, difference, or product of two variables
// already used in the kernel, or a variable plus a
// constant.
// Linearize all the exprs and names
vector<Expr> exprs;
vector<string> names;
for (const auto &p : lifter.lifted) {
exprs.push_back(p.first);
names.push_back(p.second);
}
// Jointly CSE the lifted exprs put putting them together into a dummy Expr
Expr dummy_call = Call::make(Int(32), "dummy", exprs, Call::Extern);
dummy_call = common_subexpression_elimination(dummy_call, true);
// Peel off containing lets. These will be lifted.
vector<pair<string, Expr>> lets;
while (const Let *let = dummy_call.as<Let>()) {
lets.push_back({let->name, let->value});
dummy_call = let->body;
}
// Track the set of variables used by the inner loop
class CollectVars : public IRVisitor {
using IRVisitor::visit;
void visit(const Variable *op) {
vars.insert(op->name);
}
public:
set<string> vars;
} vars;
new_stmt.accept(&vars);
// Now consider substituting back in each use
const Call *call = dummy_call.as<Call>();
internal_assert(call);
bool converged;
do {
converged = true;
for (size_t i = 0; i < exprs.size(); i++) {
if (!exprs[i].defined()) continue;
Expr e = call->args[i];
if (cost(e, vars.vars) <= 1) {
// Just subs it back in - computing it is as cheap
// as loading it.
e.accept(&vars);
new_stmt = substitute(names[i], e, new_stmt);
names[i].clear();
exprs[i] = Expr();
converged = false;
} else {
exprs[i] = e;
}
}
} while (!converged);
// Recurse
const For *loop = new_stmt.as<For>();
internal_assert(loop);
new_stmt = For::make(loop->name, loop->min, loop->extent,
loop->for_type, loop->device_api, mutate(loop->body));
// Wrap lets for the lifted invariants
for (size_t i = 0; i < exprs.size(); i++) {
if (exprs[i].defined()) {
new_stmt = LetStmt::make(names[i], exprs[i], new_stmt);
}
}
// Wrap the lets pulled out by CSE
while (!lets.empty()) {
new_stmt = LetStmt::make(lets.back().first, lets.back().second, new_stmt);
lets.pop_back();
}
return new_stmt;
}
}
};
// Reassociate summations to group together the loop invariants. Useful to run before LICM.
class GroupLoopInvariants : public IRMutator2 {
using IRMutator2::visit;
Scope<int> var_depth;
class ExprDepth : public IRVisitor {
using IRVisitor::visit;
const Scope<int> &depth;
void visit(const Variable *op) {
if (depth.contains(op->name)) {
result = std::max(result, depth.get(op->name));
}
}
public:
int result = 0;
ExprDepth(const Scope<int> &var_depth) : depth(var_depth) {}
};
int expr_depth(const Expr &e) {
ExprDepth depth(var_depth);
e.accept(&depth);
return depth.result;
}
struct Term {
Expr expr;
bool positive;
int depth;
};
vector<Term> extract_summation(const Expr &e) {
vector<Term> pending, terms;
pending.push_back({e, true, 0});
while (!pending.empty()) {
Term next = pending.back();
pending.pop_back();
const Add *add = next.expr.as<Add>();
const Sub *sub = next.expr.as<Sub>();
if (add) {
pending.push_back({add->a, next.positive, 0});
pending.push_back({add->b, next.positive, 0});
} else if (sub) {
pending.push_back({sub->a, next.positive, 0});
pending.push_back({sub->b, !next.positive, 0});
} else {
next.expr = mutate(next.expr);
if (next.expr.as<Add>() || next.expr.as<Sub>()) {
// After mutation it became an add or sub, throw it back on the pending queue.
pending.push_back(next);
} else {
next.depth = expr_depth(next.expr);
terms.push_back(next);
}
}
}
// Sort the terms by loop depth. Terms of equal depth are
// likely already in a good order, so don't mess with them.
std::stable_sort(terms.begin(), terms.end(),
[](const Term &a, const Term &b) {
return a.depth > b.depth;
});
return terms;
}
Expr reassociate_summation(const Expr &e) {
vector<Term> terms = extract_summation(e);
Expr result;
bool positive = true;
while (!terms.empty()) {
Term next = terms.back();
terms.pop_back();
if (result.defined()) {
if (next.positive == positive) {
result += next.expr;
} else if (next.positive) {
result = next.expr - result;
positive = true;
} else {
result -= next.expr;
}
} else {
result = next.expr;
positive = next.positive;
}
}
if (!positive) {
result = make_zero(result.type()) - result;
}
return result;
}
Expr visit(const Sub *op) override {
return reassociate_summation(op);
}
Expr visit(const Add *op) override {
return reassociate_summation(op);
}
int depth = 0;
Stmt visit(const For *op) override {
depth++;
ScopedBinding<int> bind(var_depth, op->name, depth);
Stmt stmt = IRMutator2::visit(op);
depth--;
return stmt;
}
Expr visit(const Let *op) override {
ScopedBinding<int> bind(var_depth, op->name, expr_depth(op->value));
return IRMutator2::visit(op);
}
Stmt visit(const LetStmt *op) override {
ScopedBinding<int> bind(var_depth, op->name, expr_depth(op->value));
return IRMutator2::visit(op);
}
};
// Turn for loops of size one into let statements
Stmt loop_invariant_code_motion(Stmt s) {
s = GroupLoopInvariants().mutate(s);
s = common_subexpression_elimination(s);
s = LICM().mutate(s);
s = simplify_exprs(s);
return s;
}
}
}
<commit_msg>Fix overflow bug in LICM<commit_after>#include "LICM.h"
#include "CSE.h"
#include "ExprUsesVar.h"
#include "IREquality.h"
#include "IRMutator.h"
#include "IROperator.h"
#include "Scope.h"
#include "Simplify.h"
#include "Substitute.h"
namespace Halide {
namespace Internal {
using std::string;
using std::map;
using std::vector;
using std::pair;
using std::set;
// Is it safe to lift an Expr out of a loop (and potentially across a device boundary)
class CanLift : public IRVisitor {
using IRVisitor::visit;
void visit(const Call *op) {
if (!op->is_pure()) {
result = false;
} else {
IRVisitor::visit(op);
}
}
void visit(const Load *op) {
result = false;
}
void visit(const Variable *op) {
if (varying.contains(op->name)) {
result = false;
}
}
const Scope<int> &varying;
public:
bool result {true};
CanLift(const Scope<int> &v) : varying(v) {}
};
// Lift pure loop invariants to the top level. Applied independently
// to each loop.
class LiftLoopInvariants : public IRMutator2 {
using IRMutator2::visit;
Scope<int> varying;
bool can_lift(const Expr &e) {
CanLift check(varying);
e.accept(&check);
return check.result;
}
bool should_lift(const Expr &e) {
if (!can_lift(e)) return false;
if (e.as<Variable>()) return false;
if (e.as<Broadcast>()) return false;
if (is_const(e)) return false;
// bool vectors are buggy enough in LLVM that lifting them is a bad idea.
// (We just skip all vectors on the principle that we don't want them
// on the stack anyway.)
if (e.type().is_vector()) return false;
return true;
}
Expr visit(const Let *op) override {
ScopedBinding<int> p(varying, op->name, 0);
return IRMutator2::visit(op);
}
Stmt visit(const LetStmt *op) override {
ScopedBinding<int> p(varying, op->name, 0);
return IRMutator2::visit(op);
}
Stmt visit(const For *op) override {
ScopedBinding<int> p(varying, op->name, 0);
return IRMutator2::visit(op);
}
public:
using IRMutator2::mutate;
Expr mutate(const Expr &e) override {
if (should_lift(e)) {
// Lift it in canonical form
Expr lifted_expr = simplify(e);
auto it = lifted.find(lifted_expr);
if (it == lifted.end()) {
string name = unique_name('t');
lifted[lifted_expr] = name;
return Variable::make(e.type(), name);
} else {
return Variable::make(e.type(), it->second);
}
} else {
return IRMutator2::mutate(e);
}
}
map<Expr, string, IRDeepCompare> lifted;
};
class LICM : public IRMutator2 {
using IRMutator2::visit;
bool in_gpu_loop{false};
// Compute the cost of computing an expression inside the inner
// loop, compared to just loading it as a parameter.
int cost(const Expr &e, const set<string> &vars) {
if (is_const(e)) {
return 0;
} else if (const Variable *var = e.as<Variable>()) {
if (vars.count(var->name)) {
// We're loading this already
return 0;
} else {
// Would have to load this
return 1;
}
} else if (const Add *add = e.as<Add>()) {
return cost(add->a, vars) + cost(add->b, vars) + 1;
} else if (const Sub *sub = e.as<Sub>()) {
return cost(sub->a, vars) + cost(sub->b, vars) + 1;
} else if (const Mul *mul = e.as<Mul>()) {
return cost(mul->a, vars) + cost(mul->b, vars) + 1;
} else {
return 100;
}
}
Stmt visit(const For *op) override {
ScopedValue<bool> old_in_gpu_loop(in_gpu_loop);
in_gpu_loop =
(op->for_type == ForType::GPUBlock ||
op->for_type == ForType::GPUThread);
if (old_in_gpu_loop && in_gpu_loop) {
// Don't lift lets to in-between gpu blocks/threads
return IRMutator2::visit(op);
} else if (op->device_api == DeviceAPI::GLSL ||
op->device_api == DeviceAPI::OpenGLCompute) {
// Don't lift anything out of OpenGL loops
return IRMutator2::visit(op);
} else {
// Lift invariants
LiftLoopInvariants lifter;
Stmt new_stmt = lifter.mutate(op);
// As an optimization to reduce register pressure, take
// the set of expressions to lift and check if any can
// cheaply be computed from others. If so it's better to
// do that than to load multiple related values off the
// stack. We currently only consider expressions that are
// the sum, difference, or product of two variables
// already used in the kernel, or a variable plus a
// constant.
// Linearize all the exprs and names
vector<Expr> exprs;
vector<string> names;
for (const auto &p : lifter.lifted) {
exprs.push_back(p.first);
names.push_back(p.second);
}
// Jointly CSE the lifted exprs put putting them together into a dummy Expr
Expr dummy_call = Call::make(Int(32), "dummy", exprs, Call::Extern);
dummy_call = common_subexpression_elimination(dummy_call, true);
// Peel off containing lets. These will be lifted.
vector<pair<string, Expr>> lets;
while (const Let *let = dummy_call.as<Let>()) {
lets.push_back({let->name, let->value});
dummy_call = let->body;
}
// Track the set of variables used by the inner loop
class CollectVars : public IRVisitor {
using IRVisitor::visit;
void visit(const Variable *op) {
vars.insert(op->name);
}
public:
set<string> vars;
} vars;
new_stmt.accept(&vars);
// Now consider substituting back in each use
const Call *call = dummy_call.as<Call>();
internal_assert(call);
bool converged;
do {
converged = true;
for (size_t i = 0; i < exprs.size(); i++) {
if (!exprs[i].defined()) continue;
Expr e = call->args[i];
if (cost(e, vars.vars) <= 1) {
// Just subs it back in - computing it is as cheap
// as loading it.
e.accept(&vars);
new_stmt = substitute(names[i], e, new_stmt);
names[i].clear();
exprs[i] = Expr();
converged = false;
} else {
exprs[i] = e;
}
}
} while (!converged);
// Recurse
const For *loop = new_stmt.as<For>();
internal_assert(loop);
new_stmt = For::make(loop->name, loop->min, loop->extent,
loop->for_type, loop->device_api, mutate(loop->body));
// Wrap lets for the lifted invariants
for (size_t i = 0; i < exprs.size(); i++) {
if (exprs[i].defined()) {
new_stmt = LetStmt::make(names[i], exprs[i], new_stmt);
}
}
// Wrap the lets pulled out by CSE
while (!lets.empty()) {
new_stmt = LetStmt::make(lets.back().first, lets.back().second, new_stmt);
lets.pop_back();
}
return new_stmt;
}
}
};
// Reassociate summations to group together the loop invariants. Useful to run before LICM.
class GroupLoopInvariants : public IRMutator2 {
using IRMutator2::visit;
Scope<int> var_depth;
class ExprDepth : public IRVisitor {
using IRVisitor::visit;
const Scope<int> &depth;
void visit(const Variable *op) {
if (depth.contains(op->name)) {
result = std::max(result, depth.get(op->name));
}
}
public:
int result = 0;
ExprDepth(const Scope<int> &var_depth) : depth(var_depth) {}
};
int expr_depth(const Expr &e) {
ExprDepth depth(var_depth);
e.accept(&depth);
return depth.result;
}
struct Term {
Expr expr;
bool positive;
int depth;
};
vector<Term> extract_summation(const Expr &e) {
vector<Term> pending, terms;
pending.push_back({e, true, 0});
while (!pending.empty()) {
Term next = pending.back();
pending.pop_back();
const Add *add = next.expr.as<Add>();
const Sub *sub = next.expr.as<Sub>();
if (add) {
pending.push_back({add->a, next.positive, 0});
pending.push_back({add->b, next.positive, 0});
} else if (sub) {
pending.push_back({sub->a, next.positive, 0});
pending.push_back({sub->b, !next.positive, 0});
} else {
next.expr = mutate(next.expr);
if (next.expr.as<Add>() || next.expr.as<Sub>()) {
// After mutation it became an add or sub, throw it back on the pending queue.
pending.push_back(next);
} else {
next.depth = expr_depth(next.expr);
terms.push_back(next);
}
}
}
// Sort the terms by loop depth. Terms of equal depth are
// likely already in a good order, so don't mess with them.
std::stable_sort(terms.begin(), terms.end(),
[](const Term &a, const Term &b) {
return a.depth > b.depth;
});
return terms;
}
Expr reassociate_summation(const Expr &e) {
vector<Term> terms = extract_summation(e);
Expr result;
bool positive = true;
while (!terms.empty()) {
Term next = terms.back();
terms.pop_back();
if (result.defined()) {
if (next.positive == positive) {
result += next.expr;
} else if (next.positive) {
result = next.expr - result;
positive = true;
} else {
result -= next.expr;
}
} else {
result = next.expr;
positive = next.positive;
}
}
if (!positive) {
result = make_zero(result.type()) - result;
}
return result;
}
Expr visit(const Sub *op) override {
return reassociate_summation(op);
}
Expr visit(const Add *op) override {
return reassociate_summation(op);
}
int depth = 0;
Stmt visit(const For *op) override {
depth++;
ScopedBinding<int> bind(var_depth, op->name, depth);
Stmt stmt = IRMutator2::visit(op);
depth--;
return stmt;
}
Expr visit(const Let *op) override {
ScopedBinding<int> bind(var_depth, op->name, expr_depth(op->value));
return IRMutator2::visit(op);
}
Stmt visit(const LetStmt *op) override {
ScopedBinding<int> bind(var_depth, op->name, expr_depth(op->value));
return IRMutator2::visit(op);
}
};
// Turn for loops of size one into let statements
Stmt loop_invariant_code_motion(Stmt s) {
s = GroupLoopInvariants().mutate(s);
s = common_subexpression_elimination(s);
s = LICM().mutate(s);
s = simplify_exprs(s);
return s;
}
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <stdexcept>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <unordered_map>
#include "global.hpp"
#include "operators.hpp"
#include "tokens.hpp"
#include "nodes.hpp"
#include "builtins.hpp"
#include "operator_maps.hpp"
namespace lang {
class Parser {
private:
std::vector<Token> tokens {};
inline void skipCharacters(unsigned int& i, int by) {i += by;}
// If we're already at the next character, but the loop will increment i by 1
inline void preventIncrement(unsigned int& i) {i--;}
std::vector<Token> variables {};
std::vector<std::string> keywords {"define", "if", "while"};
std::vector<std::string> constructKeywords {"do", "end", "else"};
public:
AST tree = AST();
Parser(std::string code) {
if (PARSER_PRINT_INPUT) print(code, "\n");
try {
tokenize(code);
if (PARSER_PRINT_TOKENS) for (auto tok : tokens) print(tok, "\n");
if (PARSER_PRINT_AS_EXPR) for (auto tok : ExpressionNode(tokens).getRPNOutput()) print(tok.data, " ");
buildTree(tokens);
} catch (SyntaxError &e) {
print(e.toString(), "\n");
}
}
void tokenize(std::string code) {
unsigned int lines = 0;
for (unsigned int i = 0; i < code.length(); ++i) {
if (code[i] == '/' && code[i + 1] == '/') while(code[i] != '\n' && code[i] != '\0') skipCharacters(i, 1);
if (code[i] == '\n') lines++;
// Ignore whitespace
if (isspace(code[i])) continue;
// Block begin/end
// Parenthesis
// Semicolons
if (code[i] == '{' || code[i] == '}' ||
code[i] == '(' || code[i] == ')' ||
code[i] == ';') {
tokens.push_back(Token(std::string(1, code[i]), CONSTRUCT, lines));
continue;
}
// Operators
auto initTokSize = tokens.size();
std::for_each(opList.begin(), opList.end(), [this, initTokSize, code, i, lines](Operator& op) {
if (initTokSize < tokens.size()) return; // If there are more tokens than before for_each, the operator was already added, so return.
if (op.toString().length() + i > code.length()) return; // If the operator is longer than the source string, ignore it.
if (op.toString() == code.substr(i, op.toString().length())) {
Operator* tmp = &op;
// TODO: apply DRY on these ifs
if (tmp->toString() == "++" || tmp->toString() == "--") {
// Prefix version
if (tokens.back().type == OPERATOR || tokens.back().type == CONSTRUCT) tmp = new Operator(tmp->toString(), 12, ASSOCIATE_FROM_RIGHT, UNARY);
// Postfix version
else tmp = new Operator(tmp->toString(), 13, ASSOCIATE_FROM_RIGHT, UNARY);
}
if (tmp->toString() == "+" || tmp->toString() == "-") {
// Unary version
if (tokens.back().type == OPERATOR || tokens.back().type == CONSTRUCT) tmp = new Operator(tmp->toString(), 12, ASSOCIATE_FROM_RIGHT, UNARY);
// Binary version
else tmp = new Operator(tmp->toString(), 10);
}
if (PARSER_PRINT_OPERATOR_TOKENS) print("Parser found Token with Operator ", *tmp, ", at address ", tmp, "\n");
tokens.push_back(Token(tmp, OPERATOR, lines));
}
});
if (initTokSize < tokens.size()) {
skipCharacters(i, tokens.back().data.length() - 1);
continue; // Token added, continue.
}
// Numbers
if (isdigit(code[i])) {
int base = 10;
std::string current = "";
if (code[i] == '0') {
switch (code[i + 1]) {
case 'x': base = 16; skipCharacters(i, 2); break;
case 'b': base = 2; skipCharacters(i, 2); break;
case 'o': base = 8; skipCharacters(i, 2); break;
default: break;
}
}
bool isFloat = false;
while (isdigit(code[i]) || code[i] == '.') {
current += code[i];
if (code[i] == '.') {
if (isFloat) throw SyntaxError("Malformed float, multiple decimal points: \"" + current + "\"", lines);
isFloat = true;
}
skipCharacters(i, 1);
}
preventIncrement(i);
if (current[current.length() - 1] == '.') throw SyntaxError("Malformed float, missing digits after decimal point: \"" + current + "\"", lines);
if (base != 10 && isFloat) throw SyntaxError("Floating point numbers must be used with base 10 numbers: \"" + current + "\"", lines);
Token t;
if (isFloat) t = Token(new Float(current), FLOAT, lines);
else t = Token(new Integer(current, base), INTEGER, lines);
tokens.push_back(t);
continue;
}
// String literals
if (code[i] == '"') {
skipCharacters(i, 1); // Skip the double quote
std::string current = "";
while (code[i] != '"') {
// TODO: add escape sequences
current += code[i];
skipCharacters(i, 1);
}
// Don't call preventIncrement here so the other double quote is skipped
tokens.push_back(Token(new String(current), STRING, lines));
continue;
}
// Others
Token token = Token();
while (!isspace(code[i])) {
if (isReservedChar(code[i]) || code[i] == '\0') break;
token.data += code[i];
skipCharacters(i, 1);
}
// Check if the thing is a Boolean
if (token.data == "true" || token.data == "false") {
token.type = BOOLEAN;
token.typeData = new Boolean(token.data);
}
// Check if the thing references a variable
for (auto tok : variables)
if (tok.data == token.data) {
token = tok;
break;
}
// Check if the thing is a new variable
if (tokens.size() > 0 && ((tokens.back().type == KEYWORD && tokens.back().data == "define") || tokens.back().type == TYPE)) {
token.type = VARIABLE;
variables.push_back(token);
}
// Check if the thing is a keyword
if (contains(token.data, keywords)) token.type = KEYWORD;
if (contains(token.data, constructKeywords)) token.type = CONSTRUCT;
// Push token
preventIncrement(i);
token.line = lines;
tokens.push_back(token);
}
}
ExpressionNode* evaluateCondition(std::vector<Token>& toks) {
std::vector<Token> exprToks = std::vector<Token>(toks.begin() + 1, toks.end() - 1);
ExpressionNode* condition = new ExpressionNode(exprToks);
condition->buildSubtree();
return condition;
}
void buildTree(std::vector<Token> tokens) {
static std::vector<BlockNode*> blockStack {};
auto addToBlock = [this](ASTNode* child) {
if (blockStack.size() == 0) tree.addRootChild(child);
else blockStack.back()->addChild(child);
};
auto logicalLines = splitVector(tokens, isNewLine);
for (uint64 i = 0; i < logicalLines.size(); i++) {
std::vector<Token>& toks = logicalLines[i];
if (toks.size() == 0) continue;
// TODO: check for solid types here as well
if (toks[0].data == "define" && toks[0].type == KEYWORD) {
DeclarationNode* decl = new DeclarationNode("define", toks[1]);
decl->setLineNumber(toks[1].line);
if (toks[2].data != ";" || toks[2].type != CONSTRUCT) {
std::vector<Token> exprToks(toks.begin() + 1, toks.end());
ExpressionNode* expr = new ExpressionNode(exprToks);
expr->buildSubtree();
decl->addChild(expr);
}
if (PARSER_PRINT_DECL_TREE) decl->printTree(blockStack.size());
addToBlock(decl);
} else if (toks[0].data == "while" && toks[0].type == KEYWORD) {
auto wBlock = new WhileNode(evaluateCondition(toks), new BlockNode());
if (PARSER_PRINT_WHILE_TREE) wBlock->printTree(blockStack.size());
addToBlock(wBlock);
blockStack.push_back(wBlock);
} else if (toks[0].data == "if" && toks[0].type == KEYWORD) {
auto cBlock = new ConditionalNode(evaluateCondition(toks), new BlockNode(), new BlockNode());
if (PARSER_PRINT_COND_TREE) cBlock->printTree(blockStack.size());
addToBlock(cBlock);
blockStack.push_back(cBlock);
} else if (toks[0].data == "else" && toks[0].type == CONSTRUCT) {
auto cNode = dynamic_cast<ConditionalNode*>(blockStack.back());
if (cNode == nullptr) throw SyntaxError("Cannot find conditional structure for token `else`.\n", blockStack.back()->getLineNumber());
cNode->nextBlock();
} else if (toks[0].data == "end" && toks[0].type == CONSTRUCT) {
blockStack.pop_back();
} else {
ExpressionNode* expr = new ExpressionNode(toks);
expr->buildSubtree();
expr->setLineNumber(dynamic_cast<ExpressionChildNode*>(expr->getChildren()[0])->t.line);
if (PARSER_PRINT_EXPR_TREE) expr->printTree(blockStack.size());
addToBlock(expr);
}
}
}
std::vector<Token> getTokens() {
return tokens;
}
};
class Interpreter {
private:
AST tree;
public:
Interpreter(AST tree): tree(tree) {
interpret(tree.getRootChildren());
}
private:
void interpret(ChildrenNodes nodes) {
for (uint64 i = 0; i < nodes.size(); ++i) {
auto nodeType = nodes[i]->getNodeType();
if (nodeType == "ExpressionNode") {
interpretExpression(dynamic_cast<ExpressionChildNode*>(nodes[i]->getChildren()[0]))->printTree(0);
} else if (nodeType == "DeclarationNode") {
registerDeclaration(dynamic_cast<DeclarationNode*>(nodes[i]));
} else if (nodeType == "ConditionalNode") {
resolveCondition(dynamic_cast<ConditionalNode*>(nodes[i]));
} else if (nodeType == "WhileNode") {
doWhileLoop(dynamic_cast<WhileNode*>(nodes[i]));
}
}
}
void doWhileLoop(WhileNode* node) {
while (true) {
auto condition = interpretExpression(dynamic_cast<ExpressionChildNode*>(node->getCondition()->getChild()));
if (!static_cast<Object*>(condition->t.typeData)->isTruthy()) break;
interpret(node->getLoopNode()->getChildren());
}
}
void resolveCondition(ConditionalNode* node) {
auto condRes = interpretExpression(dynamic_cast<ExpressionChildNode*>(node->getCondition()->getChild()));
if (static_cast<Object*>(condRes->t.typeData)->isTruthy()) {
interpret(node->getTrueBlock()->getChildren());
} else {
interpret(node->getFalseBlock()->getChildren());
}
}
void registerDeclaration(DeclarationNode* node) {
node->getParentScope()->insert({node->identifier.data, new Variable()});
if (node->getChildren().size() == 1) {
(*node->getParentScope())[node->identifier.data]->assign(
static_cast<Object*>(interpretExpression(dynamic_cast<ExpressionChildNode*>(node->getChild()->getChildren()[0]))->t.typeData)
);
}
}
ExpressionChildNode* interpretExpression(ExpressionChildNode* node) {
if (node->getChildren().size() == 0) return node;
if (node->t.type == OPERATOR) {
ExpressionChildNode* processed = new ExpressionChildNode(node->t);
processed->setParent(node->getParent());
auto ch = node->getChildren();
std::for_each(ch.begin(), ch.end(), [=](ASTNode*& n) {
auto node = dynamic_cast<ExpressionChildNode*>(n);
if (node->getChildren().size() != 0) processed->addChild(interpretExpression(node));
else processed->addChild(node);
});
return new ExpressionChildNode(Token(runOperator(processed), UNPROCESSED, PHONY_TOKEN));
}
throw std::runtime_error("Wrong type of token.\n");
}
};
} /* namespace lang */
void printHelp() {
print(
"Use -c to read from constants.data and inputs.data, -e [CODE] to evaluate code and -f [PATH] to load code from a file.\n",
"Examples:\n",
" lang -c\n",
" lang -e \"if true != false do 1 + 1; end\"\n",
" lang -f \"/path/to/file.txt\"\n"
);
}
int main(int argc, char** argv) {
if (argc == 1) {
printHelp();
return 1;
}
else if (std::string(argv[1]) == "-c") getConstants();
else if (std::string(argv[1]) == "-e") INPUT = argv[2];
else if (std::string(argv[1]) == "-f") {
std::ifstream in(argv[2]);
std::string contents((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
INPUT = contents;
} else {
printHelp();
return 1;
}
try {
lang::Parser a(INPUT);
lang::Interpreter in(a.tree);
} catch(SyntaxError& se) {
print(se.toString(), "\n");
} catch(TypeError& te) {
print(te.toString(), "\n");
}
return 0;
}
<commit_msg>Fixed bug with finding pre/postfix operators<commit_after>#include <iostream>
#include <fstream>
#include <stdexcept>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <unordered_map>
#include "global.hpp"
#include "operators.hpp"
#include "tokens.hpp"
#include "nodes.hpp"
#include "builtins.hpp"
#include "operator_maps.hpp"
namespace lang {
class Parser {
private:
std::vector<Token> tokens {};
inline void skipCharacters(unsigned int& i, int by) {i += by;}
// If we're already at the next character, but the loop will increment i by 1
inline void preventIncrement(unsigned int& i) {i--;}
std::vector<Token> variables {};
std::vector<std::string> keywords {"define", "if", "while"};
std::vector<std::string> constructKeywords {"do", "end", "else"};
public:
AST tree = AST();
Parser(std::string code) {
if (PARSER_PRINT_INPUT) print(code, "\n");
try {
tokenize(code);
if (PARSER_PRINT_TOKENS) for (auto tok : tokens) print(tok, "\n");
if (PARSER_PRINT_AS_EXPR) for (auto tok : ExpressionNode(tokens).getRPNOutput()) print(tok.data, " ");
buildTree(tokens);
} catch (SyntaxError &e) {
print(e.toString(), "\n");
}
}
void tokenize(std::string code) {
unsigned int lines = 0;
for (unsigned int i = 0; i < code.length(); ++i) {
if (code[i] == '/' && code[i + 1] == '/') while(code[i] != '\n' && code[i] != '\0') skipCharacters(i, 1);
if (code[i] == '\n') lines++;
// Ignore whitespace
if (isspace(code[i])) continue;
// Block begin/end
// Parenthesis
// Semicolons
if (code[i] == '{' || code[i] == '}' ||
code[i] == '(' || code[i] == ')' ||
code[i] == ';') {
tokens.push_back(Token(std::string(1, code[i]), CONSTRUCT, lines));
continue;
}
// Operators
auto initTokSize = tokens.size();
std::for_each(opList.begin(), opList.end(), [this, initTokSize, code, i, lines](Operator& op) {
if (initTokSize < tokens.size()) return; // If there are more tokens than before for_each, the operator was already added, so return.
if (op.toString().length() + i > code.length()) return; // If the operator is longer than the source string, ignore it.
if (op.toString() == code.substr(i, op.toString().length())) {
Operator* tmp = &op;
// TODO: apply DRY on these ifs
if (tmp->toString() == "++" || tmp->toString() == "--") {
// Prefix version
if (tokens.back().type == OPERATOR || tokens.back().type == CONSTRUCT) tmp = new Operator(tmp->toString(), 12, ASSOCIATE_FROM_RIGHT, UNARY);
// Postfix version
else tmp = new Operator(tmp->toString(), 13, ASSOCIATE_FROM_LEFT, UNARY);
}
if (tmp->toString() == "+" || tmp->toString() == "-") {
// Unary version
if (tokens.back().type == OPERATOR || tokens.back().type == CONSTRUCT) tmp = new Operator(tmp->toString(), 12, ASSOCIATE_FROM_RIGHT, UNARY);
// Binary version
else tmp = new Operator(tmp->toString(), 10);
}
if (PARSER_PRINT_OPERATOR_TOKENS) print("Parser found Token with Operator ", *tmp, ", at address ", tmp, "\n");
tokens.push_back(Token(tmp, OPERATOR, lines));
}
});
if (initTokSize < tokens.size()) {
skipCharacters(i, tokens.back().data.length() - 1);
continue; // Token added, continue.
}
// Numbers
if (isdigit(code[i])) {
int base = 10;
std::string current = "";
if (code[i] == '0') {
switch (code[i + 1]) {
case 'x': base = 16; skipCharacters(i, 2); break;
case 'b': base = 2; skipCharacters(i, 2); break;
case 'o': base = 8; skipCharacters(i, 2); break;
default: break;
}
}
bool isFloat = false;
while (isdigit(code[i]) || code[i] == '.') {
current += code[i];
if (code[i] == '.') {
if (isFloat) throw SyntaxError("Malformed float, multiple decimal points: \"" + current + "\"", lines);
isFloat = true;
}
skipCharacters(i, 1);
}
preventIncrement(i);
if (current[current.length() - 1] == '.') throw SyntaxError("Malformed float, missing digits after decimal point: \"" + current + "\"", lines);
if (base != 10 && isFloat) throw SyntaxError("Floating point numbers must be used with base 10 numbers: \"" + current + "\"", lines);
Token t;
if (isFloat) t = Token(new Float(current), FLOAT, lines);
else t = Token(new Integer(current, base), INTEGER, lines);
tokens.push_back(t);
continue;
}
// String literals
if (code[i] == '"') {
skipCharacters(i, 1); // Skip the double quote
std::string current = "";
while (code[i] != '"') {
// TODO: add escape sequences
current += code[i];
skipCharacters(i, 1);
}
// Don't call preventIncrement here so the other double quote is skipped
tokens.push_back(Token(new String(current), STRING, lines));
continue;
}
// Others
Token token = Token();
while (!isspace(code[i])) {
if (isReservedChar(code[i]) || code[i] == '\0') break;
token.data += code[i];
skipCharacters(i, 1);
}
// Check if the thing is a Boolean
if (token.data == "true" || token.data == "false") {
token.type = BOOLEAN;
token.typeData = new Boolean(token.data);
}
// Check if the thing references a variable
for (auto tok : variables)
if (tok.data == token.data) {
token = tok;
break;
}
// Check if the thing is a new variable
if (tokens.size() > 0 && ((tokens.back().type == KEYWORD && tokens.back().data == "define") || tokens.back().type == TYPE)) {
token.type = VARIABLE;
variables.push_back(token);
}
// Check if the thing is a keyword
if (contains(token.data, keywords)) token.type = KEYWORD;
if (contains(token.data, constructKeywords)) token.type = CONSTRUCT;
// Push token
preventIncrement(i);
token.line = lines;
tokens.push_back(token);
}
}
ExpressionNode* evaluateCondition(std::vector<Token>& toks) {
std::vector<Token> exprToks = std::vector<Token>(toks.begin() + 1, toks.end() - 1);
ExpressionNode* condition = new ExpressionNode(exprToks);
condition->buildSubtree();
return condition;
}
void buildTree(std::vector<Token> tokens) {
static std::vector<BlockNode*> blockStack {};
auto addToBlock = [this](ASTNode* child) {
if (blockStack.size() == 0) tree.addRootChild(child);
else blockStack.back()->addChild(child);
};
auto logicalLines = splitVector(tokens, isNewLine);
for (uint64 i = 0; i < logicalLines.size(); i++) {
std::vector<Token>& toks = logicalLines[i];
if (toks.size() == 0) continue;
// TODO: check for solid types here as well
if (toks[0].data == "define" && toks[0].type == KEYWORD) {
DeclarationNode* decl = new DeclarationNode("define", toks[1]);
decl->setLineNumber(toks[1].line);
if (toks[2].data != ";" || toks[2].type != CONSTRUCT) {
std::vector<Token> exprToks(toks.begin() + 1, toks.end());
ExpressionNode* expr = new ExpressionNode(exprToks);
expr->buildSubtree();
decl->addChild(expr);
}
if (PARSER_PRINT_DECL_TREE) decl->printTree(blockStack.size());
addToBlock(decl);
} else if (toks[0].data == "while" && toks[0].type == KEYWORD) {
auto wBlock = new WhileNode(evaluateCondition(toks), new BlockNode());
if (PARSER_PRINT_WHILE_TREE) wBlock->printTree(blockStack.size());
addToBlock(wBlock);
blockStack.push_back(wBlock);
} else if (toks[0].data == "if" && toks[0].type == KEYWORD) {
auto cBlock = new ConditionalNode(evaluateCondition(toks), new BlockNode(), new BlockNode());
if (PARSER_PRINT_COND_TREE) cBlock->printTree(blockStack.size());
addToBlock(cBlock);
blockStack.push_back(cBlock);
} else if (toks[0].data == "else" && toks[0].type == CONSTRUCT) {
auto cNode = dynamic_cast<ConditionalNode*>(blockStack.back());
if (cNode == nullptr) throw SyntaxError("Cannot find conditional structure for token `else`.\n", blockStack.back()->getLineNumber());
cNode->nextBlock();
} else if (toks[0].data == "end" && toks[0].type == CONSTRUCT) {
blockStack.pop_back();
} else {
ExpressionNode* expr = new ExpressionNode(toks);
expr->buildSubtree();
expr->setLineNumber(dynamic_cast<ExpressionChildNode*>(expr->getChildren()[0])->t.line);
if (PARSER_PRINT_EXPR_TREE) expr->printTree(blockStack.size());
addToBlock(expr);
}
}
}
std::vector<Token> getTokens() {
return tokens;
}
};
class Interpreter {
private:
AST tree;
public:
Interpreter(AST tree): tree(tree) {
interpret(tree.getRootChildren());
}
private:
void interpret(ChildrenNodes nodes) {
for (uint64 i = 0; i < nodes.size(); ++i) {
auto nodeType = nodes[i]->getNodeType();
if (nodeType == "ExpressionNode") {
interpretExpression(dynamic_cast<ExpressionChildNode*>(nodes[i]->getChildren()[0]))->printTree(0);
} else if (nodeType == "DeclarationNode") {
registerDeclaration(dynamic_cast<DeclarationNode*>(nodes[i]));
} else if (nodeType == "ConditionalNode") {
resolveCondition(dynamic_cast<ConditionalNode*>(nodes[i]));
} else if (nodeType == "WhileNode") {
doWhileLoop(dynamic_cast<WhileNode*>(nodes[i]));
}
}
}
void doWhileLoop(WhileNode* node) {
while (true) {
auto condition = interpretExpression(dynamic_cast<ExpressionChildNode*>(node->getCondition()->getChild()));
if (!static_cast<Object*>(condition->t.typeData)->isTruthy()) break;
interpret(node->getLoopNode()->getChildren());
}
}
void resolveCondition(ConditionalNode* node) {
auto condRes = interpretExpression(dynamic_cast<ExpressionChildNode*>(node->getCondition()->getChild()));
if (static_cast<Object*>(condRes->t.typeData)->isTruthy()) {
interpret(node->getTrueBlock()->getChildren());
} else {
interpret(node->getFalseBlock()->getChildren());
}
}
void registerDeclaration(DeclarationNode* node) {
node->getParentScope()->insert({node->identifier.data, new Variable()});
if (node->getChildren().size() == 1) {
(*node->getParentScope())[node->identifier.data]->assign(
static_cast<Object*>(interpretExpression(dynamic_cast<ExpressionChildNode*>(node->getChild()->getChildren()[0]))->t.typeData)
);
}
}
ExpressionChildNode* interpretExpression(ExpressionChildNode* node) {
if (node->getChildren().size() == 0) return node;
if (node->t.type == OPERATOR) {
ExpressionChildNode* processed = new ExpressionChildNode(node->t);
processed->setParent(node->getParent());
auto ch = node->getChildren();
std::for_each(ch.begin(), ch.end(), [=](ASTNode*& n) {
auto node = dynamic_cast<ExpressionChildNode*>(n);
if (node->getChildren().size() != 0) processed->addChild(interpretExpression(node));
else processed->addChild(node);
});
return new ExpressionChildNode(Token(runOperator(processed), UNPROCESSED, PHONY_TOKEN));
}
throw std::runtime_error("Wrong type of token.\n");
}
};
} /* namespace lang */
void printHelp() {
print(
"Use -c to read from constants.data and inputs.data, -e [CODE] to evaluate code and -f [PATH] to load code from a file.\n",
"Examples:\n",
" lang -c\n",
" lang -e \"if true != false do 1 + 1; end\"\n",
" lang -f \"/path/to/file.txt\"\n"
);
}
int main(int argc, char** argv) {
if (argc == 1) {
printHelp();
return 1;
}
else if (std::string(argv[1]) == "-c") getConstants();
else if (std::string(argv[1]) == "-e") INPUT = argv[2];
else if (std::string(argv[1]) == "-f") {
std::ifstream in(argv[2]);
std::string contents((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
INPUT = contents;
} else {
printHelp();
return 1;
}
try {
lang::Parser a(INPUT);
lang::Interpreter in(a.tree);
} catch(SyntaxError& se) {
print(se.toString(), "\n");
} catch(TypeError& te) {
print(te.toString(), "\n");
}
return 0;
}
<|endoftext|> |
<commit_before>//
// MCMC.cpp
// EpiGenMCMC
//
// Created by Lucy Li on 06/05/2016.
// Copyright (c) 2016 Lucy Li, Imperial College London. All rights reserved.
//
#define MATHLIB_STANDALONE
#include <iostream>
#include "MCMC.h"
namespace EpiGenMCMC_MCMC {
void initialise_logfile(std::string filename, Parameter model_params, MCMCoptions options, unsigned int seed1, unsigned int seed2) {
std::chrono::time_point<std::chrono::system_clock> curr_time = std::chrono::system_clock::now();
std::time_t start_time = std::chrono::system_clock::to_time_t(curr_time);
std::cout << filename << std::endl;
std::ofstream file(filename);
file << "# Seeds: " << seed1 << ", " << seed2 << std::endl;
file << "# Start time: " << std::ctime(&start_time) << std::endl;
file << "# Starting parameters:" << std::endl;
for (int i=0; i!=model_params.get_total_params(); ++i) {
file << "# " << model_params.getname(i) << " ";
file << model_params.get(i) << std::endl;
}
file << "# MCMC details:" << std::endl;
file << "# " << options.iterations << " iterations" << std::endl;
file << "# " << options.particles << " particles" << std::endl;
file << "# Log parameters every " << options.log_every << " iterations" << std::endl;
file << "# Filter at most every " << options.pfilter_every << " time steps" << std::endl;
file << "# Filter if ESS < " << options.pfilter_threshold*100.0 << "% of particles" << std::endl;
file << "# Likelihood based on ";
if (options.which_likelihood == 0) {
file << "both epidemiologic and genealogical data";
if (options.num_trees > 1) file << "(" << options.num_trees << " trees)";
}
else if (options.which_likelihood == 1) file << "epidemiologic data";
else file << "genealogical data";
file << std::endl;
file << "state\tposterior\tlikelihood\tprior";
for (int i=0; i!=model_params.get_total_params(); ++i) {
if (model_params.is_estim(i)) file << "\t" << model_params.getname(i);
}
// file << std::endl << "0";
// for (int i=0; i!=model_params.get_total_params(); ++i) {
// if (model_params.is_estim(i)) file << "\t" << model_params.get(i);
// }
file << std::endl;
file.close();
}
void mcmc_log(std::string filename, Parameter model_params, int iteration, double loglik, double logprior) {
std::ofstream file(filename, std::ios::app);
if (!std::isfinite(logprior)) logprior = -0.1*std::numeric_limits<double>::max();
file << iteration << "\t" << loglik+logprior << "\t" << loglik << "\t" << logprior;
for (int i=0; i!=model_params.get_total_params(); ++i) {
if (model_params.is_estim(i)) file << "\t" << model_params.get(i);
}
file << std::endl;
file.close();
}
void lhs(Parameter model_params, MCMCoptions options, std::vector <double> & lower_bounds, std::vector <double> & upper_bounds, int divides, int index_ML, bool verbose) {
// Latin Hypercube Sampling
double min_val;
double max_val;
double interval_size;
double value;
if (lower_bounds.size() < 1) { // First iteration of sampling
for (int i=0; i!=model_params.get_total_params_to_estim(); ++i) {
int j = model_params.get_estim_index(i);
min_val = model_params.get_lower(j);
max_val = model_params.get_upper(j);
interval_size = (max_val - min_val) / (double) divides;
for (int interval_i=0; interval_i!=divides; ++interval_i) {
value = min_val+(double)interval_i*interval_size;
lower_bounds.push_back(value);
upper_bounds.push_back(value+interval_size);
}
}
if (verbose) std::cout << "Drawing a Latin Hypercube Sample for " << lower_bounds.size()/divides << " parameters ";
if (verbose) std::cout << "each divided into " << divides << " partitions." << std::endl;
}
else {
for (int i=0; i!=model_params.get_total_params_to_estim(); ++i) {
int j = model_params.get_estim_index(i);
min_val = lower_bounds[i*divides+index_ML];
max_val = upper_bounds[i*divides+index_ML];
interval_size = (max_val - min_val) / (double) divides;
for (int interval_i=0; interval_i!=divides; ++interval_i) {
value = min_val+(double)interval_i*interval_size;
lower_bounds[i*divides+interval_i] = std::max(model_params.get_lower(j), value);
upper_bounds[i*divides+interval_i] = std::min(model_params.get_upper(j), value+interval_size);
}
}
}
std::vector <int> indices (divides);
for (int i=0; i!=divides; ++i) indices[i] = i;
int param_index;
std::vector <double> lowers_matrix (lower_bounds.size());
std::vector <double> uppers_matrix = lowers_matrix;
// Construct grid of parameter value combinations to calculate the likelihood
for (int i=0; i!=model_params.get_total_params_to_estim(); ++i) {
gsl_ran_shuffle(options.rng[0], &indices[0], indices.size(), sizeof(int));
for (int j=0; j!=indices.size(); ++j) {
param_index = i*divides+indices[j];
lowers_matrix[i*divides+j] = lower_bounds[param_index];
uppers_matrix[i*divides+j] = upper_bounds[param_index];
}
}
lowers_matrix.swap(lower_bounds);
uppers_matrix.swap(upper_bounds);
}
int mcmc (Parameter & model_params, MCMCoptions & options, Trajectory & traj, TimeSeriesData & epi_data, TreeData & tree_data, MultiTreeData & multitree_data) {
if (options.verbose) std::cout << "Begin MCMC" << std::endl;
if (options.verbose) std::cout << "Using " << options.num_threads << " cores." << std::endl;
unsigned int seed1 = (int)time(0);
unsigned int seed2 = (int)time(0)+10;
options.seed = seed1;
const gsl_rng_type * rng_t = gsl_rng_rand;
gsl_rng **rng;
rng = (gsl_rng **) malloc(options.num_threads * sizeof(gsl_rng *));
for (int i = 0; i != options.num_threads; ++i) {
rng[i] = gsl_rng_alloc(rng_t);
gsl_rng_set(rng[i], seed1+i);
}
options.rng = rng;
initialise_logfile(options.log_filename, model_params, options, seed1, seed2);
if (options.verbose) std::cout << "MCMC log file initialised" << std::endl;
double loglik;
double newloglik;
double prior_ratio;
double correction_factor;
double accept_with_prob;
double ran_num;
bool accept;
Trajectory temptraj = traj;
Particle particles(options.particles, traj);
Model sim_model;
if (options.use_lhs) {
bool save_traj_in_mcmc_chain = options.save_traj;
if (options.save_traj) options.save_traj = false;
std::vector <double> lower_bounds;
std::vector <double> upper_bounds;
int index_max = 0;
for (int i=0; i!=options.lhs_iterations; ++i) {
if (options.verbose) std::cout << "Iteration 1" << std::endl;
lhs(model_params, options, lower_bounds, upper_bounds, options.lhs_divides, index_max, options.verbose);
double loglik = -std::numeric_limits<double>::max();
double max_posterior = loglik;
for (int j=0; j!=options.lhs_divides; ++j) {
if (options.verbose) std::cout << j << ") ";
// Set parameter values to the next combination
for (int param_i=0; param_i!=model_params.get_total_params_to_estim(); ++param_i) {
int curr_param_index = model_params.get_estim_index(param_i);
int grid_index = param_i*options.lhs_divides+j;
double curr_param_value = (lower_bounds[grid_index]+upper_bounds[grid_index])/2.0;
model_params.set(curr_param_index, curr_param_value);
model_params.transform_param(curr_param_index, true);
std::cout << model_params.get(curr_param_index) << " ";
}
// Likelihood of current parameter combination
// loglik = -std::numeric_limits<double>::max();
loglik = EpiGenPfilter::pfilter(sim_model, model_params, options, particles, temptraj, epi_data, tree_data, multitree_data);
if (options.verbose) std::cout << "loglik: " << loglik << std::endl;
if (j==0) {
max_posterior = loglik + model_params.get_prior_all();
index_max = 0;
}
else {
if (loglik + model_params.get_prior_all() > max_posterior) {
// If a new maximum posterior density is found, update index_ML
// to the index of the current parameter combination
index_max = j;
max_posterior = loglik + model_params.get_prior_all();
}
}
}
}
// Set initial parameter values to those that produced the maximum posterior density
for (int param_i=0; param_i!=model_params.get_total_params_to_estim(); ++param_i) {
int curr_param_index = model_params.get_estim_index(param_i);
int grid_index = param_i*options.lhs_divides+index_max;
double curr_param_value = (lower_bounds[grid_index]+upper_bounds[grid_index])/2.0;
model_params.set(curr_param_index, curr_param_value);
model_params.transform_param(curr_param_index, true);
}
if (save_traj_in_mcmc_chain) options.save_traj = true;
}
std::chrono::time_point<std::chrono::system_clock> time1 = std::chrono::system_clock::now(), time2;
std::chrono::duration<double> elapsed_seconds;
if (options.verbose) time1 = std::chrono::system_clock::now();
loglik = EpiGenPfilter::pfilter(sim_model, model_params, options, particles, traj, epi_data, tree_data, multitree_data);
if (options.verbose) {
time2 = std::chrono::system_clock::now();
elapsed_seconds = time2-time1;
time1 = time2;
std::cout << "State TimeInterval Acceptance" << std::endl;
std::cout << "0 " << elapsed_seconds.count() << " 0.0"<< std::endl;
}
if (options.save_traj) traj.print_to_file(0, options.traj_filename, options.pfilter_every, true);
mcmc_log(options.log_filename, model_params, 0, loglik, model_params.get_prior_all());
if (options.heat_factor > 1.0) model_params.stop_adapt();
for (int iter = 1; iter != options.iterations; ++iter) {
correction_factor = model_params.propose(options.rng[0]);
particles.reset_weights();
newloglik = EpiGenPfilter::pfilter(sim_model, model_params, options, particles, temptraj, epi_data, tree_data, multitree_data);
prior_ratio = model_params.get_prior_ratio();
accept_with_prob = (newloglik - loglik) + prior_ratio + correction_factor;
if (options.heat_factor > 1.0) {
if (iter <= (options.heat_length*model_params.get_total_params_to_estim())) accept_with_prob += log(options.heat_factor);
else {
if ((iter % model_params.get_total_params_to_estim())==0) {
options.heat_factor -= std::min(options.heat_factor-1.0, options.cool_rate);
accept_with_prob += log(options.heat_factor);
if (options.heat_factor <= 1.0) {
model_params.start_adapt();
}
}
}
}
accept = accept_with_prob >= 0.0;
if (!accept) {
ran_num = gsl_rng_uniform(options.rng[0]);
if (log(ran_num) < accept_with_prob) accept = true;
}
if (accept) {
loglik = newloglik;
traj = temptraj;
model_params.accept();
}
else {
model_params.reject();
}
if ((iter)%options.log_every == 0) {
if (options.save_traj) traj.print_to_file(iter, options.traj_filename, options.pfilter_every, true);
mcmc_log(options.log_filename, model_params, iter, loglik, model_params.get_prior_all());
if (options.verbose) {
time2 = std::chrono::system_clock::now();
elapsed_seconds = time2-time1;
time1 = time2;
std::cout << iter << " " << elapsed_seconds.count() << " ";
std::cout << model_params.get_acceptance() << std::endl;
}
}
}
particles.clear();
return (1);
}
}
<commit_msg>rng no long consecutive<commit_after>//
// MCMC.cpp
// EpiGenMCMC
//
// Created by Lucy Li on 06/05/2016.
// Copyright (c) 2016 Lucy Li, Imperial College London. All rights reserved.
//
#define MATHLIB_STANDALONE
#include <iostream>
#include "MCMC.h"
namespace EpiGenMCMC_MCMC {
void initialise_logfile(std::string filename, Parameter model_params, MCMCoptions options, unsigned int seed1, unsigned int seed2) {
std::chrono::time_point<std::chrono::system_clock> curr_time = std::chrono::system_clock::now();
std::time_t start_time = std::chrono::system_clock::to_time_t(curr_time);
std::cout << filename << std::endl;
std::ofstream file(filename);
file << "# Seeds: " << seed1 << ", " << seed2 << std::endl;
file << "# Start time: " << std::ctime(&start_time) << std::endl;
file << "# Starting parameters:" << std::endl;
for (int i=0; i!=model_params.get_total_params(); ++i) {
file << "# " << model_params.getname(i) << " ";
file << model_params.get(i) << std::endl;
}
file << "# MCMC details:" << std::endl;
file << "# " << options.iterations << " iterations" << std::endl;
file << "# " << options.particles << " particles" << std::endl;
file << "# Log parameters every " << options.log_every << " iterations" << std::endl;
file << "# Filter at most every " << options.pfilter_every << " time steps" << std::endl;
file << "# Filter if ESS < " << options.pfilter_threshold*100.0 << "% of particles" << std::endl;
file << "# Likelihood based on ";
if (options.which_likelihood == 0) {
file << "both epidemiologic and genealogical data";
if (options.num_trees > 1) file << "(" << options.num_trees << " trees)";
}
else if (options.which_likelihood == 1) file << "epidemiologic data";
else file << "genealogical data";
file << std::endl;
file << "state\tposterior\tlikelihood\tprior";
for (int i=0; i!=model_params.get_total_params(); ++i) {
if (model_params.is_estim(i)) file << "\t" << model_params.getname(i);
}
// file << std::endl << "0";
// for (int i=0; i!=model_params.get_total_params(); ++i) {
// if (model_params.is_estim(i)) file << "\t" << model_params.get(i);
// }
file << std::endl;
file.close();
}
void mcmc_log(std::string filename, Parameter model_params, int iteration, double loglik, double logprior) {
std::ofstream file(filename, std::ios::app);
if (!std::isfinite(logprior)) logprior = -0.1*std::numeric_limits<double>::max();
file << iteration << "\t" << loglik+logprior << "\t" << loglik << "\t" << logprior;
for (int i=0; i!=model_params.get_total_params(); ++i) {
if (model_params.is_estim(i)) file << "\t" << model_params.get(i);
}
file << std::endl;
file.close();
}
void lhs(Parameter model_params, MCMCoptions options, std::vector <double> & lower_bounds, std::vector <double> & upper_bounds, int divides, int index_ML, bool verbose) {
// Latin Hypercube Sampling
double min_val;
double max_val;
double interval_size;
double value;
if (lower_bounds.size() < 1) { // First iteration of sampling
for (int i=0; i!=model_params.get_total_params_to_estim(); ++i) {
int j = model_params.get_estim_index(i);
min_val = model_params.get_lower(j);
max_val = model_params.get_upper(j);
interval_size = (max_val - min_val) / (double) divides;
for (int interval_i=0; interval_i!=divides; ++interval_i) {
value = min_val+(double)interval_i*interval_size;
lower_bounds.push_back(value);
upper_bounds.push_back(value+interval_size);
}
}
if (verbose) std::cout << "Drawing a Latin Hypercube Sample for " << lower_bounds.size()/divides << " parameters ";
if (verbose) std::cout << "each divided into " << divides << " partitions." << std::endl;
}
else {
for (int i=0; i!=model_params.get_total_params_to_estim(); ++i) {
int j = model_params.get_estim_index(i);
min_val = lower_bounds[i*divides+index_ML];
max_val = upper_bounds[i*divides+index_ML];
interval_size = (max_val - min_val) / (double) divides;
for (int interval_i=0; interval_i!=divides; ++interval_i) {
value = min_val+(double)interval_i*interval_size;
lower_bounds[i*divides+interval_i] = std::max(model_params.get_lower(j), value);
upper_bounds[i*divides+interval_i] = std::min(model_params.get_upper(j), value+interval_size);
}
}
}
std::vector <int> indices (divides);
for (int i=0; i!=divides; ++i) indices[i] = i;
int param_index;
std::vector <double> lowers_matrix (lower_bounds.size());
std::vector <double> uppers_matrix = lowers_matrix;
// Construct grid of parameter value combinations to calculate the likelihood
for (int i=0; i!=model_params.get_total_params_to_estim(); ++i) {
gsl_ran_shuffle(options.rng[0], &indices[0], indices.size(), sizeof(int));
for (int j=0; j!=indices.size(); ++j) {
param_index = i*divides+indices[j];
lowers_matrix[i*divides+j] = lower_bounds[param_index];
uppers_matrix[i*divides+j] = upper_bounds[param_index];
}
}
lowers_matrix.swap(lower_bounds);
uppers_matrix.swap(upper_bounds);
}
int mcmc (Parameter & model_params, MCMCoptions & options, Trajectory & traj, TimeSeriesData & epi_data, TreeData & tree_data, MultiTreeData & multitree_data) {
if (options.verbose) std::cout << "Begin MCMC" << std::endl;
if (options.verbose) std::cout << "Using " << options.num_threads << " cores." << std::endl;
unsigned int seed1 = (int)time(0);
unsigned int seed2 = (int)time(0)+10;
options.seed = seed1;
const gsl_rng_type * rng_t = gsl_rng_rand;
gsl_rng **rng;
rng = (gsl_rng **) malloc(options.num_threads * sizeof(gsl_rng *));
for (int i = 0; i != options.num_threads; ++i) {
rng[i] = gsl_rng_alloc(rng_t);
gsl_rng_set(rng[i], seed1+i*options.particles);
}
options.rng = rng;
initialise_logfile(options.log_filename, model_params, options, seed1, seed2);
if (options.verbose) std::cout << "MCMC log file initialised" << std::endl;
double loglik;
double newloglik;
double prior_ratio;
double correction_factor;
double accept_with_prob;
double ran_num;
bool accept;
Trajectory temptraj = traj;
Particle particles(options.particles, traj);
Model sim_model;
if (options.use_lhs) {
bool save_traj_in_mcmc_chain = options.save_traj;
if (options.save_traj) options.save_traj = false;
std::vector <double> lower_bounds;
std::vector <double> upper_bounds;
int index_max = 0;
for (int i=0; i!=options.lhs_iterations; ++i) {
if (options.verbose) std::cout << "Iteration 1" << std::endl;
lhs(model_params, options, lower_bounds, upper_bounds, options.lhs_divides, index_max, options.verbose);
double loglik = -std::numeric_limits<double>::max();
double max_posterior = loglik;
for (int j=0; j!=options.lhs_divides; ++j) {
if (options.verbose) std::cout << j << ") ";
// Set parameter values to the next combination
for (int param_i=0; param_i!=model_params.get_total_params_to_estim(); ++param_i) {
int curr_param_index = model_params.get_estim_index(param_i);
int grid_index = param_i*options.lhs_divides+j;
double curr_param_value = (lower_bounds[grid_index]+upper_bounds[grid_index])/2.0;
model_params.set(curr_param_index, curr_param_value);
model_params.transform_param(curr_param_index, true);
std::cout << model_params.get(curr_param_index) << " ";
}
// Likelihood of current parameter combination
// loglik = -std::numeric_limits<double>::max();
loglik = EpiGenPfilter::pfilter(sim_model, model_params, options, particles, temptraj, epi_data, tree_data, multitree_data);
if (options.verbose) std::cout << "loglik: " << loglik << std::endl;
if (j==0) {
max_posterior = loglik + model_params.get_prior_all();
index_max = 0;
}
else {
if (loglik + model_params.get_prior_all() > max_posterior) {
// If a new maximum posterior density is found, update index_ML
// to the index of the current parameter combination
index_max = j;
max_posterior = loglik + model_params.get_prior_all();
}
}
}
}
// Set initial parameter values to those that produced the maximum posterior density
for (int param_i=0; param_i!=model_params.get_total_params_to_estim(); ++param_i) {
int curr_param_index = model_params.get_estim_index(param_i);
int grid_index = param_i*options.lhs_divides+index_max;
double curr_param_value = (lower_bounds[grid_index]+upper_bounds[grid_index])/2.0;
model_params.set(curr_param_index, curr_param_value);
model_params.transform_param(curr_param_index, true);
}
if (save_traj_in_mcmc_chain) options.save_traj = true;
}
std::chrono::time_point<std::chrono::system_clock> time1 = std::chrono::system_clock::now(), time2;
std::chrono::duration<double> elapsed_seconds;
if (options.verbose) time1 = std::chrono::system_clock::now();
loglik = EpiGenPfilter::pfilter(sim_model, model_params, options, particles, traj, epi_data, tree_data, multitree_data);
if (options.verbose) {
time2 = std::chrono::system_clock::now();
elapsed_seconds = time2-time1;
time1 = time2;
std::cout << "State TimeInterval Acceptance" << std::endl;
std::cout << "0 " << elapsed_seconds.count() << " 0.0"<< std::endl;
}
if (options.save_traj) traj.print_to_file(0, options.traj_filename, options.pfilter_every, true);
mcmc_log(options.log_filename, model_params, 0, loglik, model_params.get_prior_all());
if (options.heat_factor > 1.0) model_params.stop_adapt();
for (int iter = 1; iter != options.iterations; ++iter) {
correction_factor = model_params.propose(options.rng[0]);
particles.reset_weights();
newloglik = EpiGenPfilter::pfilter(sim_model, model_params, options, particles, temptraj, epi_data, tree_data, multitree_data);
prior_ratio = model_params.get_prior_ratio();
accept_with_prob = (newloglik - loglik) + prior_ratio + correction_factor;
if (options.heat_factor > 1.0) {
if (iter <= (options.heat_length*model_params.get_total_params_to_estim())) accept_with_prob += log(options.heat_factor);
else {
if ((iter % model_params.get_total_params_to_estim())==0) {
options.heat_factor -= std::min(options.heat_factor-1.0, options.cool_rate);
accept_with_prob += log(options.heat_factor);
if (options.heat_factor <= 1.0) {
model_params.start_adapt();
}
}
}
}
accept = accept_with_prob >= 0.0;
if (!accept) {
ran_num = gsl_rng_uniform(options.rng[0]);
if (log(ran_num) < accept_with_prob) accept = true;
}
if (accept) {
loglik = newloglik;
traj = temptraj;
model_params.accept();
}
else {
model_params.reject();
}
if ((iter)%options.log_every == 0) {
if (options.save_traj) traj.print_to_file(iter, options.traj_filename, options.pfilter_every, true);
mcmc_log(options.log_filename, model_params, iter, loglik, model_params.get_prior_all());
if (options.verbose) {
time2 = std::chrono::system_clock::now();
elapsed_seconds = time2-time1;
time1 = time2;
std::cout << iter << " " << elapsed_seconds.count() << " ";
std::cout << model_params.get_acceptance() << std::endl;
}
}
}
particles.clear();
return (1);
}
}
<|endoftext|> |
<commit_before>#include "test/Test.h"
#include <cstdio>
int main()
{
Penciloid::PenciloidTest::RunTestAll();
char c;
printf("Press any key to continue...");
scanf_s("%c", &c);
return 0;
}<commit_msg>Remove 'Press any key...'<commit_after>#include "test/Test.h"
#include <cstdio>
int main()
{
Penciloid::PenciloidTest::RunTestAll();
return 0;
}<|endoftext|> |
<commit_before>#include "event.h"
#include "augs/ensure.h"
namespace augs {
namespace window {
namespace event {
change::change() {
std::memset(this, 0, sizeof(change));
}
key_change change::get_key_change() const {
switch (msg) {
case message::ltripleclick: return key_change::PRESSED;
case message::keydown: return key_change::PRESSED;
case message::keyup: return key_change::RELEASED;
case message::ldoubleclick: return key_change::PRESSED;
case message::mdoubleclick: return key_change::PRESSED;
case message::rdoubleclick: return key_change::PRESSED;
case message::ldown: return key_change::PRESSED;
case message::lup: return key_change::RELEASED;
case message::mdown: return key_change::PRESSED;
case message::mup: return key_change::RELEASED;
case message::xdown: return key_change::PRESSED;
case message::xup: return key_change::RELEASED;
case message::rdown: return key_change::PRESSED;
case message::rup: return key_change::RELEASED;
default: return key_change::NO_CHANGE; break;
}
}
bool change::operator==(const change& c) const {
return !std::memcmp(this, &c, sizeof(change));
}
bool change::uses_mouse() const {
return msg == message::mousemotion
|| (get_key_change() != key_change::NO_CHANGE && msg != message::keydown && msg != message::keyup)
;
}
bool change::was_any_key_pressed() const {
return get_key_change() == key_change::PRESSED;
}
bool change::was_any_key_released() const {
return get_key_change() == key_change::RELEASED;
}
bool change::was_key_pressed(const keys::key k) const {
return was_any_key_pressed() && key.key == k;
}
bool change::was_key_released(const keys::key k) const {
return was_any_key_released() && key.key == k;
}
void state::apply(const change& dt) {
const auto ch = dt.get_key_change();
if (ch == key_change::PRESSED) {
keys.set(static_cast<size_t>(dt.key.key), true);
}
else if (ch == key_change::RELEASED) {
keys.set(static_cast<size_t>(dt.key.key), false);
}
else if (dt.msg == message::mousemotion) {
mouse.pos += dt.mouse.rel;
mouse.pos.clamp_from_zero_to(vec2i{ screen_size.x - 1, screen_size.y - 1 });
if (!get_mouse_key(0)) {
mouse.ldrag.x = mouse.pos.x;
mouse.ldrag.y = mouse.pos.y;
}
if (!get_mouse_key(1)) {
mouse.rdrag.x = mouse.pos.x;
mouse.rdrag.y = mouse.pos.y;
}
}
}
bool state::get_mouse_key(const unsigned n) const {
switch (n) {
case 0: return keys.test(static_cast<size_t>(keys::key::LMOUSE));
case 1: return keys.test(static_cast<size_t>(keys::key::RMOUSE));
case 2: return keys.test(static_cast<size_t>(keys::key::MMOUSE));
case 3: return keys.test(static_cast<size_t>(keys::key::MOUSE4));
case 4: return keys.test(static_cast<size_t>(keys::key::MOUSE5));
default: ensure(false); return false;
}
}
bool state::is_set(const keys::key k) const {
return keys.test(static_cast<size_t>(k));
}
void state::unset_keys() {
keys.reset();
}
namespace keys {
bool is_numpad_key(const key k) {
if(static_cast<int>(k) >= static_cast<int>(key::NUMPAD0) && static_cast<int>(k) <= static_cast<int>(key::NUMPAD9)) return true;
return false;
}
std::wstring key_to_wstring(const key k) {
switch (k) {
case key::INVALID: return L"INVALID"; break;
case key::LMOUSE: return L"Left Mouse Button"; break;
case key::RMOUSE: return L"Right Mouse Button"; break;
case key::MMOUSE: return L"Middle Mouse Button"; break;
case key::MOUSE4: return L"Mouse Button 4"; break;
case key::MOUSE5: return L"Mouse Button 5"; break;
case key::CANCEL: return L"Cancel"; break;
case key::BACKSPACE: return L"Backspace"; break;
case key::TAB: return L"Tab"; break;
case key::CLEAR: return L"Clear"; break;
case key::ENTER: return L"Enter"; break;
case key::SHIFT: return L"Shift"; break;
case key::CTRL: return L"Control"; break;
case key::ALT: return L"Alt"; break;
case key::PAUSE: return L"Pause"; break;
case key::CAPSLOCK: return L"Caps Lock"; break;
case key::ESC: return L"Escape"; break;
case key::SPACE: return L"Space"; break;
case key::PAGEUP: return L"Page Up"; break;
case key::PAGEDOWN: return L"Page Down"; break;
case key::END: return L"End"; break;
case key::HOME: return L"Home"; break;
case key::LEFT: return L"Left Arrow"; break;
case key::UP: return L"Up Arrow"; break;
case key::RIGHT: return L"Right Arrow"; break;
case key::DOWN: return L"Down Arrow"; break;
case key::SELECT: return L"Select"; break;
case key::PRINT: return L"Print"; break;
case key::EXECUTE: return L"Execute"; break;
case key::PRINTSCREEN: return L"Print Screen"; break;
case key::INSERT: return L"Insert"; break;
case key::DEL: return L"Del"; break;
case key::HELP: return L"Help"; break;
case key::LWIN: return L"Left Windows Key"; break;
case key::RWIN: return L"Right Windows Key"; break;
case key::APPS: return L"Apps"; break;
case key::SLEEP: return L"Sleep"; break;
case key::NUMPAD0: return L"Numpad 0"; break;
case key::NUMPAD1: return L"Numpad 1"; break;
case key::NUMPAD2: return L"Numpad 2"; break;
case key::NUMPAD3: return L"Numpad 3"; break;
case key::NUMPAD4: return L"Numpad 4"; break;
case key::NUMPAD5: return L"Numpad 5"; break;
case key::NUMPAD6: return L"Numpad 6"; break;
case key::NUMPAD7: return L"Numpad 7"; break;
case key::NUMPAD8: return L"Numpad 8"; break;
case key::NUMPAD9: return L"Numpad 9"; break;
case key::MULTIPLY: return L"Multiply"; break;
case key::ADD: return L"Add"; break;
case key::SEPARATOR: return L"Separator"; break;
case key::SUBTRACT: return L"Subtract"; break;
case key::DECIMAL: return L"Decimal"; break;
case key::DIVIDE: return L"Divide"; break;
case key::F1: return L"F1"; break;
case key::F2: return L"F2"; break;
case key::F3: return L"F3"; break;
case key::F4: return L"F4"; break;
case key::F5: return L"F5"; break;
case key::F6: return L"F6"; break;
case key::F7: return L"F7"; break;
case key::F8: return L"F8"; break;
case key::F9: return L"F9"; break;
case key::F10: return L"F10"; break;
case key::F11: return L"F11"; break;
case key::F12: return L"F12"; break;
case key::F13: return L"F13"; break;
case key::F14: return L"F14"; break;
case key::F15: return L"F15"; break;
case key::F16: return L"F16"; break;
case key::F17: return L"F17"; break;
case key::F18: return L"F18"; break;
case key::F19: return L"F19"; break;
case key::F20: return L"F20"; break;
case key::F21: return L"F21"; break;
case key::F22: return L"F22"; break;
case key::F23: return L"F23"; break;
case key::F24: return L"F24"; break;
case key::A: return L"A"; break;
case key::B: return L"B"; break;
case key::C: return L"C"; break;
case key::D: return L"D"; break;
case key::E: return L"E"; break;
case key::F: return L"F"; break;
case key::G: return L"G"; break;
case key::H: return L"H"; break;
case key::I: return L"I"; break;
case key::J: return L"J"; break;
case key::K: return L"K"; break;
case key::L: return L"L"; break;
case key::M: return L"M"; break;
case key::N: return L"N"; break;
case key::O: return L"O"; break;
case key::P: return L"P"; break;
case key::Q: return L"Q"; break;
case key::R: return L"R"; break;
case key::S: return L"S"; break;
case key::T: return L"T"; break;
case key::U: return L"U"; break;
case key::V: return L"V"; break;
case key::W: return L"W"; break;
case key::X: return L"X"; break;
case key::Y: return L"Y"; break;
case key::Z: return L"Z"; break;
case key::_0: return L"0"; break;
case key::_1: return L"1"; break;
case key::_2: return L"2"; break;
case key::_3: return L"3"; break;
case key::_4: return L"4"; break;
case key::_5: return L"5"; break;
case key::_6: return L"6"; break;
case key::_7: return L"7"; break;
case key::_8: return L"8"; break;
case key::_9: return L"9"; break;
case key::NUMLOCK: return L"Num Lock"; break;
case key::SCROLL: return L"Scroll"; break;
case key::LSHIFT: return L"Left Shift"; break;
case key::RSHIFT: return L"Right Shift"; break;
case key::LCTRL: return L"Left Control"; break;
case key::RCTRL: return L"Right Control"; break;
case key::LALT: return L"Left Alt"; break;
case key::RALT: return L"Right Alt"; break;
case key::DASH: return L"Dash"; break;
default: return L"Invalid key"; break;
}
}
key wstring_to_key(const std::wstring& wstr) {
for (key i = key::INVALID; i < key::COUNT; i = key(int(i) + 1)) {
if(key_to_wstring(i) == wstr) {
return i;
}
}
return key::INVALID;
}
}
}
}
}<commit_msg>fixed key descriptions<commit_after>#include "event.h"
#include "augs/ensure.h"
namespace augs {
namespace window {
namespace event {
change::change() {
std::memset(this, 0, sizeof(change));
}
key_change change::get_key_change() const {
switch (msg) {
case message::ltripleclick: return key_change::PRESSED;
case message::keydown: return key_change::PRESSED;
case message::keyup: return key_change::RELEASED;
case message::ldoubleclick: return key_change::PRESSED;
case message::mdoubleclick: return key_change::PRESSED;
case message::rdoubleclick: return key_change::PRESSED;
case message::ldown: return key_change::PRESSED;
case message::lup: return key_change::RELEASED;
case message::mdown: return key_change::PRESSED;
case message::mup: return key_change::RELEASED;
case message::xdown: return key_change::PRESSED;
case message::xup: return key_change::RELEASED;
case message::rdown: return key_change::PRESSED;
case message::rup: return key_change::RELEASED;
default: return key_change::NO_CHANGE; break;
}
}
bool change::operator==(const change& c) const {
return !std::memcmp(this, &c, sizeof(change));
}
bool change::uses_mouse() const {
return msg == message::mousemotion
|| (get_key_change() != key_change::NO_CHANGE && msg != message::keydown && msg != message::keyup)
;
}
bool change::was_any_key_pressed() const {
return get_key_change() == key_change::PRESSED;
}
bool change::was_any_key_released() const {
return get_key_change() == key_change::RELEASED;
}
bool change::was_key_pressed(const keys::key k) const {
return was_any_key_pressed() && key.key == k;
}
bool change::was_key_released(const keys::key k) const {
return was_any_key_released() && key.key == k;
}
void state::apply(const change& dt) {
const auto ch = dt.get_key_change();
if (ch == key_change::PRESSED) {
keys.set(static_cast<size_t>(dt.key.key), true);
}
else if (ch == key_change::RELEASED) {
keys.set(static_cast<size_t>(dt.key.key), false);
}
else if (dt.msg == message::mousemotion) {
mouse.pos += dt.mouse.rel;
mouse.pos.clamp_from_zero_to(vec2i{ screen_size.x - 1, screen_size.y - 1 });
if (!get_mouse_key(0)) {
mouse.ldrag.x = mouse.pos.x;
mouse.ldrag.y = mouse.pos.y;
}
if (!get_mouse_key(1)) {
mouse.rdrag.x = mouse.pos.x;
mouse.rdrag.y = mouse.pos.y;
}
}
}
bool state::get_mouse_key(const unsigned n) const {
switch (n) {
case 0: return keys.test(static_cast<size_t>(keys::key::LMOUSE));
case 1: return keys.test(static_cast<size_t>(keys::key::RMOUSE));
case 2: return keys.test(static_cast<size_t>(keys::key::MMOUSE));
case 3: return keys.test(static_cast<size_t>(keys::key::MOUSE4));
case 4: return keys.test(static_cast<size_t>(keys::key::MOUSE5));
default: ensure(false); return false;
}
}
bool state::is_set(const keys::key k) const {
return keys.test(static_cast<size_t>(k));
}
void state::unset_keys() {
keys.reset();
}
namespace keys {
bool is_numpad_key(const key k) {
if(static_cast<int>(k) >= static_cast<int>(key::NUMPAD0) && static_cast<int>(k) <= static_cast<int>(key::NUMPAD9)) return true;
return false;
}
std::wstring key_to_wstring(const key k) {
switch (k) {
case key::INVALID: return L"INVALID"; break;
case key::LMOUSE: return L"Left Mouse Button"; break;
case key::RMOUSE: return L"Right Mouse Button"; break;
case key::MMOUSE: return L"Middle Mouse Button"; break;
case key::MOUSE4: return L"Mouse Button 4"; break;
case key::MOUSE5: return L"Mouse Button 5"; break;
case key::CANCEL: return L"Cancel"; break;
case key::BACKSPACE: return L"Backspace"; break;
case key::TAB: return L"Tab"; break;
case key::CLEAR: return L"Clear"; break;
case key::ENTER: return L"Enter"; break;
case key::SHIFT: return L"Shift"; break;
case key::CTRL: return L"Control"; break;
case key::ALT: return L"Alt"; break;
case key::PAUSE: return L"Pause"; break;
case key::CAPSLOCK: return L"Caps Lock"; break;
case key::ESC: return L"Escape"; break;
case key::SPACE: return L"Space"; break;
case key::PAGEUP: return L"Page Up"; break;
case key::PAGEDOWN: return L"Page Down"; break;
case key::END: return L"End"; break;
case key::HOME: return L"Home"; break;
case key::LEFT: return L"Left Arrow"; break;
case key::UP: return L"Up Arrow"; break;
case key::RIGHT: return L"Right Arrow"; break;
case key::DOWN: return L"Down Arrow"; break;
case key::SELECT: return L"Select"; break;
case key::PRINT: return L"Print"; break;
case key::EXECUTE: return L"Execute"; break;
case key::PRINTSCREEN: return L"Print Screen"; break;
case key::INSERT: return L"Insert"; break;
case key::DEL: return L"Del"; break;
case key::HELP: return L"Help"; break;
case key::LWIN: return L"Left Windows Key"; break;
case key::RWIN: return L"Right Windows Key"; break;
case key::APPS: return L"Apps"; break;
case key::SLEEP: return L"Sleep"; break;
case key::NUMPAD0: return L"Numpad 0"; break;
case key::NUMPAD1: return L"Numpad 1"; break;
case key::NUMPAD2: return L"Numpad 2"; break;
case key::NUMPAD3: return L"Numpad 3"; break;
case key::NUMPAD4: return L"Numpad 4"; break;
case key::NUMPAD5: return L"Numpad 5"; break;
case key::NUMPAD6: return L"Numpad 6"; break;
case key::NUMPAD7: return L"Numpad 7"; break;
case key::NUMPAD8: return L"Numpad 8"; break;
case key::NUMPAD9: return L"Numpad 9"; break;
case key::MULTIPLY: return L"Multiply"; break;
case key::ADD: return L"Add"; break;
case key::SEPARATOR: return L"Separator"; break;
case key::SUBTRACT: return L"Subtract"; break;
case key::DECIMAL: return L"Decimal"; break;
case key::DIVIDE: return L"Divide"; break;
case key::F1: return L"F1"; break;
case key::F2: return L"F2"; break;
case key::F3: return L"F3"; break;
case key::F4: return L"F4"; break;
case key::F5: return L"F5"; break;
case key::F6: return L"F6"; break;
case key::F7: return L"F7"; break;
case key::F8: return L"F8"; break;
case key::F9: return L"F9"; break;
case key::F10: return L"F10"; break;
case key::F11: return L"F11"; break;
case key::F12: return L"F12"; break;
case key::F13: return L"F13"; break;
case key::F14: return L"F14"; break;
case key::F15: return L"F15"; break;
case key::F16: return L"F16"; break;
case key::F17: return L"F17"; break;
case key::F18: return L"F18"; break;
case key::F19: return L"F19"; break;
case key::F20: return L"F20"; break;
case key::F21: return L"F21"; break;
case key::F22: return L"F22"; break;
case key::F23: return L"F23"; break;
case key::F24: return L"F24"; break;
case key::A: return L"A"; break;
case key::B: return L"B"; break;
case key::C: return L"C"; break;
case key::D: return L"D"; break;
case key::E: return L"E"; break;
case key::F: return L"F"; break;
case key::G: return L"G"; break;
case key::H: return L"H"; break;
case key::I: return L"I"; break;
case key::J: return L"J"; break;
case key::K: return L"K"; break;
case key::L: return L"L"; break;
case key::M: return L"M"; break;
case key::N: return L"N"; break;
case key::O: return L"O"; break;
case key::P: return L"P"; break;
case key::Q: return L"Q"; break;
case key::R: return L"R"; break;
case key::S: return L"S"; break;
case key::T: return L"T"; break;
case key::U: return L"U"; break;
case key::V: return L"V"; break;
case key::W: return L"W"; break;
case key::X: return L"X"; break;
case key::Y: return L"Y"; break;
case key::Z: return L"Z"; break;
case key::_0: return L"0"; break;
case key::_1: return L"1"; break;
case key::_2: return L"2"; break;
case key::_3: return L"3"; break;
case key::_4: return L"4"; break;
case key::_5: return L"5"; break;
case key::_6: return L"6"; break;
case key::_7: return L"7"; break;
case key::_8: return L"8"; break;
case key::_9: return L"9"; break;
case key::NUMLOCK: return L"Num Lock"; break;
case key::SCROLL: return L"Scroll"; break;
case key::LSHIFT: return L"Left Shift"; break;
case key::RSHIFT: return L"Right Shift"; break;
case key::LCTRL: return L"Left Control"; break;
case key::RCTRL: return L"Right Control"; break;
case key::LALT: return L"Left Alt"; break;
case key::RALT: return L"Right Alt"; break;
case key::DASH: return L"Dash"; break;
case key::EQUAL: return L"Equal"; break;
case key::NEXT_TRACK: return L"Next Track"; break;
case key::PREV_TRACK: return L"Prev Track"; break;
case key::STOP_TRACK: return L"Stop Track"; break;
case key::PLAY_PAUSE_TRACK: return L"Play Or Pause"; break;
case key::SEMICOLON: return L"Semicolon"; break;
case key::PLUS: return L"Plus"; break;
case key::COMMA: return L"Comma"; break;
case key::MINUS: return L"Minus"; break;
case key::PERIOD: return L"Period"; break;
case key::SLASH: return L"Slash"; break;
case key::OPEN_SQUARE_BRACKET: return L"Open Square Bracket"; break;
case key::BACKSLASH: return L"Backslash"; break;
case key::CLOSE_SQUARE_BRACKET: return L"Close Square Bracket"; break;
case key::APOSTROPHE: return L"Apostrophe"; break;
default: return L"Invalid key"; break;
}
}
key wstring_to_key(const std::wstring& wstr) {
for (key i = key::INVALID; i < key::COUNT; i = key(int(i) + 1)) {
if(key_to_wstring(i) == wstr) {
return i;
}
}
return key::INVALID;
}
}
}
}
}<|endoftext|> |
<commit_before>/*
* O ,-
* o . - ' ,-
* . ` . ,
* ( )) . (
* `-;_ . - `.`.
* `._'
*
* Copyright (c) 2007-2011 Markus Fisch <mf@markusfisch.de>
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*/
#include "Menu.h"
#include "WindowManager.h"
#include <X11/Xutil.h>
#include <unistd.h>
#include <stdlib.h>
#include <sstream>
using namespace PieDock;
/**
* Initialize menu
*
* @param a - application
*/
Menu::Menu( Application *a ) :
app( a ),
selected( 0 ),
menuItems( 0 )
{
}
/**
* Update menu
*
* @param menuName - menu name
*/
bool Menu::update( std::string menuName )
{
if( !(menuItems = app->getSettings()->getMenu( menuName )) )
return false;
// multiple windows per icon
typedef std::map<Icon *, MenuItem *> IconToItem;
IconToItem iconToItem;
// one icon per window
typedef std::map<Window, MenuItem *> WindowToItem;
WindowToItem windowToItem;
IconMap *iconMap = &app->getSettings()->getIconMap();
// clear windows and make sure all items have valid icons
{
MenuItems::iterator si = menuItems->end();
for( MenuItems::iterator i = menuItems->begin();
i != menuItems->end();
i++ )
{
Icon *icon;
if( !(icon = (*i)->getIcon()) )
{
if( !(icon = iconMap->getIconByName( (*i)->getTitle() )) )
icon = iconMap->getMissingIcon( (*i)->getTitle() );
(*i)->setIcon( icon );
}
if( menuItems->oneIconPerWindow() )
{
windowToItem[(*i)->getNextWindow()] = (*i);
if( *i == selected )
si = i;
}
iconToItem[icon] = (*i);
(*i)->clearWindows();
}
// move menu item to the top when one icon per window is used
if( si != menuItems->end() )
{
menuItems->erase( si );
menuItems->push_front( selected );
}
}
// get filter
std::string classFilter;
if( menuItems->onlyFromActive() )
{
Window w = WindowManager::getActive( app->getDisplay() );
XClassHint xch;
if( w &&
XGetClassHint( app->getDisplay(), w, &xch ) )
{
classFilter = xch.res_class;
XFree( xch.res_name );
XFree( xch.res_class );
}
}
// assign windows to menu items; this is done by evaluating name, class
// and title of the windows since you just can't trust window IDs over time
{
WindowManager::WindowList wl( app->getDisplay() );
for( WindowManager::WindowList::iterator i = wl.begin();
i != wl.end();
i++ )
{
if( !WindowManager::isNormalWindow( app->getDisplay(), (*i) ) )
continue;
XClassHint xch;
if( !XGetClassHint( app->getDisplay(), (*i), &xch ) )
continue;
if( (!menuItems->oneIconPerWindow() &&
app->getSettings()->ignoreWindow( xch.res_name )) ||
(menuItems->onlyFromActive() &&
classFilter.compare( xch.res_class )) )
{
XFree( xch.res_name );
XFree( xch.res_class );
continue;
}
std::string windowTitle = WindowManager::getTitle(
app->getDisplay(),
(*i) );
Icon *icon = iconMap->getIcon(
windowTitle,
xch.res_class,
xch.res_name );
if( !icon ||
icon->getType() == Icon::Missing )
{
ArgbSurface *s;
if( (s = WindowManager::getIcon( app->getDisplay(), (*i) )) )
{
icon = iconMap->createIcon(
*s,
xch.res_name,
Icon::Window );
delete s;
}
else if( !icon )
icon = iconMap->getMissingIcon( xch.res_name );
}
XFree( xch.res_name );
XFree( xch.res_class );
if( menuItems->oneIconPerWindow() )
{
WindowToItem::iterator w;
// use existing icon
if( (w = windowToItem.find( (*i) )) != windowToItem.end() )
{
// always get icon anew when reusing a window ID
if( icon )
{
(*w).second->setIcon( icon );
(*w).second->setTitle( windowTitle );
}
(*w).second->addWindow( app->getDisplay(), (*i) );
continue;
}
// create new icon
MenuItem *item = new MenuItem( icon );
item->addWindow( app->getDisplay(), (*i) );
item->setTitle( windowTitle );
menuItems->push_back( item );
continue;
}
// find existing icon or create a new one
{
IconToItem::iterator m;
if( (m = iconToItem.find( icon )) != iconToItem.end() )
(*m).second->addWindow( app->getDisplay(), (*i) );
else if( menuItems->includeWindows() )
{
MenuItem *item = new MenuItem( icon );
item->addWindow( app->getDisplay(), (*i) );
item->setTitle( windowTitle );
iconToItem[icon] = item;
menuItems->push_back( item );
}
}
}
}
// remove all menu items that have no windows and
// are not sticky
{
MenuItems::iterator i = menuItems->begin();
while( i != menuItems->end() )
if( !(*i)->isSticky() &&
!(*i)->hasWindows() )
{
delete (*i);
i = menuItems->erase( i );
}
else
++i;
}
// fill menu with dummy icons if there is a minimum number
{
int m = app->getSettings()->getMinimumNumber();
if( m > 0 &&
menuItems->size() < m )
{
for( m -= menuItems->size(); m--; )
menuItems->push_back( new MenuItem(
iconMap->getFillerIcon() ) );
}
}
name = menuName;
return true;
}
/**
* Check if item points to another menu and if so, change to it
*
* @param a - action to execute (optional)
*/
bool Menu::change( Settings::Action a )
{
if( !selected ||
(
a != Settings::Launch &&
a != Settings::ShowNext &&
a != Settings::ShowPrevious
) )
return false;
std::string cmd = selected->getCommand();
// check if this menu should launch another menu
if( !cmd.compare( 0, 1, ":" ) )
{
update( cmd.substr( 1 ) );
return true;
}
return false;
}
/**
* Execute some action for the seleced icon
*
* @param a - action to execute (optional)
*/
void Menu::execute( Settings::Action a )
{
if( !selected )
return;
// if there are no windows only Launch is allowed
if( !selected->hasWindows() )
{
if( a != Settings::Launch &&
a != Settings::ShowNext &&
a != Settings::ShowPrevious )
return;
a = Settings::Launch;
}
switch( a )
{
case Settings::Launch:
{
std::string cmd = selected->getCommand();
// substitute $WID with window ID
{
std::string::size_type p;
if( (p = cmd.find( "$WID" )) != std::string::npos )
{
std::ostringstream oss;
oss << cmd.substr( 0, p ) <<
"0x" <<
std::hex << WindowManager::getClientWindow(
app->getDisplay(),
getWindowBelowCursor() ) <<
cmd.substr( p+4 );
cmd = oss.str();
}
}
run( cmd );
}
break;
case Settings::ShowNext:
WindowManager::activate(
app->getDisplay(),
selected->getNextWindow() );
break;
case Settings::ShowPrevious:
WindowManager::activate(
app->getDisplay(),
selected->getPreviousWindow() );
break;
case Settings::Hide:
WindowManager::iconify(
app->getDisplay(),
selected->getNextWindow() );
break;
case Settings::Close:
WindowManager::close(
app->getDisplay(),
selected->getNextWindow() );
break;
}
}
/**
* Return item title
*/
std::string Menu::getItemTitle() const
{
if( selected )
return selected->getTitle();
return "";
};
/**
* Run some command
*
* @param command - command to execute
*/
int Menu::run( std::string command ) const
{
int pid = fork();
if( pid < 0 )
throw "fork failed";
else if( pid )
return pid;
char *shell = getenv( "SHELL" );
if( !shell )
shell = const_cast<char *>( "/bin/sh" );
setsid();
execl( shell, shell, "-c", command.c_str(), NULL );
throw "exec failed";
// make compiler happy
return 0;
}
<commit_msg>storing of menu name relocated for better overview<commit_after>/*
* O ,-
* o . - ' ,-
* . ` . ,
* ( )) . (
* `-;_ . - `.`.
* `._'
*
* Copyright (c) 2007-2011 Markus Fisch <mf@markusfisch.de>
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*/
#include "Menu.h"
#include "WindowManager.h"
#include <X11/Xutil.h>
#include <unistd.h>
#include <stdlib.h>
#include <sstream>
using namespace PieDock;
/**
* Initialize menu
*
* @param a - application
*/
Menu::Menu( Application *a ) :
app( a ),
selected( 0 ),
menuItems( 0 )
{
}
/**
* Update menu
*
* @param menuName - menu name
*/
bool Menu::update( std::string menuName )
{
if( !(menuItems = app->getSettings()->getMenu( menuName )) )
return false;
name = menuName;
// multiple windows per icon
typedef std::map<Icon *, MenuItem *> IconToItem;
IconToItem iconToItem;
// one icon per window
typedef std::map<Window, MenuItem *> WindowToItem;
WindowToItem windowToItem;
IconMap *iconMap = &app->getSettings()->getIconMap();
// clear windows and make sure all items have valid icons
{
MenuItems::iterator si = menuItems->end();
for( MenuItems::iterator i = menuItems->begin();
i != menuItems->end();
i++ )
{
Icon *icon;
if( !(icon = (*i)->getIcon()) )
{
if( !(icon = iconMap->getIconByName( (*i)->getTitle() )) )
icon = iconMap->getMissingIcon( (*i)->getTitle() );
(*i)->setIcon( icon );
}
if( menuItems->oneIconPerWindow() )
{
windowToItem[(*i)->getNextWindow()] = (*i);
if( *i == selected )
si = i;
}
iconToItem[icon] = (*i);
(*i)->clearWindows();
}
// move menu item to the top when one icon per window is used
if( si != menuItems->end() )
{
menuItems->erase( si );
menuItems->push_front( selected );
}
}
// get filter
std::string classFilter;
if( menuItems->onlyFromActive() )
{
Window w = WindowManager::getActive( app->getDisplay() );
XClassHint xch;
if( w &&
XGetClassHint( app->getDisplay(), w, &xch ) )
{
classFilter = xch.res_class;
XFree( xch.res_name );
XFree( xch.res_class );
}
}
// assign windows to menu items; this is done by evaluating name, class
// and title of the windows since you just can't trust window IDs over time
{
WindowManager::WindowList wl( app->getDisplay() );
for( WindowManager::WindowList::iterator i = wl.begin();
i != wl.end();
i++ )
{
if( !WindowManager::isNormalWindow( app->getDisplay(), (*i) ) )
continue;
XClassHint xch;
if( !XGetClassHint( app->getDisplay(), (*i), &xch ) )
continue;
if( (!menuItems->oneIconPerWindow() &&
app->getSettings()->ignoreWindow( xch.res_name )) ||
(menuItems->onlyFromActive() &&
classFilter.compare( xch.res_class )) )
{
XFree( xch.res_name );
XFree( xch.res_class );
continue;
}
std::string windowTitle = WindowManager::getTitle(
app->getDisplay(),
(*i) );
Icon *icon = iconMap->getIcon(
windowTitle,
xch.res_class,
xch.res_name );
if( !icon ||
icon->getType() == Icon::Missing )
{
ArgbSurface *s;
if( (s = WindowManager::getIcon( app->getDisplay(), (*i) )) )
{
icon = iconMap->createIcon(
*s,
xch.res_name,
Icon::Window );
delete s;
}
else if( !icon )
icon = iconMap->getMissingIcon( xch.res_name );
}
XFree( xch.res_name );
XFree( xch.res_class );
if( menuItems->oneIconPerWindow() )
{
WindowToItem::iterator w;
// use existing icon
if( (w = windowToItem.find( (*i) )) != windowToItem.end() )
{
// always get icon anew when reusing a window ID
if( icon )
{
(*w).second->setIcon( icon );
(*w).second->setTitle( windowTitle );
}
(*w).second->addWindow( app->getDisplay(), (*i) );
continue;
}
// create new icon
MenuItem *item = new MenuItem( icon );
item->addWindow( app->getDisplay(), (*i) );
item->setTitle( windowTitle );
menuItems->push_back( item );
continue;
}
// find existing icon or create a new one
{
IconToItem::iterator m;
if( (m = iconToItem.find( icon )) != iconToItem.end() )
(*m).second->addWindow( app->getDisplay(), (*i) );
else if( menuItems->includeWindows() )
{
MenuItem *item = new MenuItem( icon );
item->addWindow( app->getDisplay(), (*i) );
item->setTitle( windowTitle );
iconToItem[icon] = item;
menuItems->push_back( item );
}
}
}
}
// remove all menu items that have no windows and
// are not sticky
{
MenuItems::iterator i = menuItems->begin();
while( i != menuItems->end() )
if( !(*i)->isSticky() &&
!(*i)->hasWindows() )
{
delete (*i);
i = menuItems->erase( i );
}
else
++i;
}
// fill menu with dummy icons if there is a minimum number
{
int m = app->getSettings()->getMinimumNumber();
if( m > 0 &&
menuItems->size() < m )
{
for( m -= menuItems->size(); m--; )
menuItems->push_back( new MenuItem(
iconMap->getFillerIcon() ) );
}
}
return true;
}
/**
* Check if item points to another menu and if so, change to it
*
* @param a - action to execute (optional)
*/
bool Menu::change( Settings::Action a )
{
if( !selected ||
(
a != Settings::Launch &&
a != Settings::ShowNext &&
a != Settings::ShowPrevious
) )
return false;
std::string cmd = selected->getCommand();
// check if this menu should launch another menu
if( !cmd.compare( 0, 1, ":" ) )
{
update( cmd.substr( 1 ) );
return true;
}
return false;
}
/**
* Execute some action for the seleced icon
*
* @param a - action to execute (optional)
*/
void Menu::execute( Settings::Action a )
{
if( !selected )
return;
// if there are no windows only Launch is allowed
if( !selected->hasWindows() )
{
if( a != Settings::Launch &&
a != Settings::ShowNext &&
a != Settings::ShowPrevious )
return;
a = Settings::Launch;
}
switch( a )
{
case Settings::Launch:
{
std::string cmd = selected->getCommand();
// substitute $WID with window ID
{
std::string::size_type p;
if( (p = cmd.find( "$WID" )) != std::string::npos )
{
std::ostringstream oss;
oss << cmd.substr( 0, p ) <<
"0x" <<
std::hex << WindowManager::getClientWindow(
app->getDisplay(),
getWindowBelowCursor() ) <<
cmd.substr( p+4 );
cmd = oss.str();
}
}
run( cmd );
}
break;
case Settings::ShowNext:
WindowManager::activate(
app->getDisplay(),
selected->getNextWindow() );
break;
case Settings::ShowPrevious:
WindowManager::activate(
app->getDisplay(),
selected->getPreviousWindow() );
break;
case Settings::Hide:
WindowManager::iconify(
app->getDisplay(),
selected->getNextWindow() );
break;
case Settings::Close:
WindowManager::close(
app->getDisplay(),
selected->getNextWindow() );
break;
}
}
/**
* Return item title
*/
std::string Menu::getItemTitle() const
{
if( selected )
return selected->getTitle();
return "";
};
/**
* Run some command
*
* @param command - command to execute
*/
int Menu::run( std::string command ) const
{
int pid = fork();
if( pid < 0 )
throw "fork failed";
else if( pid )
return pid;
char *shell = getenv( "SHELL" );
if( !shell )
shell = const_cast<char *>( "/bin/sh" );
setsid();
execl( shell, shell, "-c", command.c_str(), NULL );
throw "exec failed";
// make compiler happy
return 0;
}
<|endoftext|> |
<commit_before>#include "Page.h"
Page::Page() {
for (int i = 0; i < MAX_SEQUENCERS; i++) {
sequencer[i] = NULL;
}
addNewLine(-1);
cursor = 0;
tool_seq_add = new Tool("+\nSEQ", OF_KEY_RETURN,
new Change(TARGET_LEVEL_PAGE, OP_SEQ_ADD, 0));
tool_seq_add->key_string = "RET";
tool_step_prev = new Tool("<<\nSTEP", 'h',
new Change(TARGET_LEVEL_SEQUENCER, OP_STEP_DELTA, -1));
tool_step_prev->addKey(OF_KEY_LEFT);
tool_seq_next = new Tool("NEXT\nSEQ", 'j',
new Change(TARGET_LEVEL_PAGE, OP_SEQ_DELTA, 1));
tool_seq_next->addKey(OF_KEY_DOWN);
tool_seq_prev = new Tool("PREV\nSEQ", 'k',
new Change(TARGET_LEVEL_PAGE, OP_SEQ_DELTA, -1));
tool_seq_prev->addKey(OF_KEY_UP);
tool_step_next = new Tool(">>\nSTEP", 'l',
new Change(TARGET_LEVEL_SEQUENCER, OP_STEP_DELTA, 1));
tool_step_next->addKey(OF_KEY_RIGHT);
tool_add_note = new Tool("+\nNOTE", 'n',
new Change(TARGET_LEVEL_SEQUENCER, OP_ADD_STEP_NOTE, 0));
tool_add_div = new Tool("+\nDIV", 'd',
new Change(TARGET_LEVEL_SEQUENCER, OP_ADD_STEP_DIVISION, 8));
tool_add_output = new Tool("+\nOUT", 'O',
new Change(TARGET_LEVEL_SEQUENCER, OP_ADD_STEP_OUTPUT, 0));
tool_add_sync = new Tool("+\nSYNC", 'S',
new Change(TARGET_LEVEL_SEQUENCER, OP_ADD_STEP_SYNC, 0));
tool_del_step = new Tool("DEL", OF_KEY_DEL,
new Change(TARGET_LEVEL_PAGE, OP_STEP_DEL, -1));
tool_del_step->key_string = "DEL";
}
Page::~Page() {
for (int i = 0; i < MAX_SEQUENCERS; i++) {
if (sequencer[i] != NULL) {
delete sequencer[i];
sequencer[i] = NULL;
}
}
delete tool_seq_add;
delete tool_seq_next;
delete tool_seq_prev;
delete tool_step_prev;
delete tool_step_next;
delete tool_add_note;
delete tool_add_div;
delete tool_add_output;
delete tool_add_sync;
delete tool_del_step;
}
void Page::step(TickBuffer* buffer, OutputRouter* output_router) {
for (int i = 0; i < MAX_SEQUENCERS; i++) {
if (sequencer[i] == NULL) {
break;
}
sequencer[i]->step(buffer, output_router);
}
}
void Page::draw(int x, int y, int width, int height, ofTrueTypeFont font) {
ofSetColor(0);
ofDrawRectangle(x, y, width, height);
for (int i = 0; i < MAX_SEQUENCERS; i++) {
if (sequencer[i] == NULL) {
break;
}
sequencer[i]->draw(i, i==cursor, font);
}
}
void Page::mousePressed(int x, int y, int button){
int col = x / 50;
int row = y / 50;
if (row >= MAX_SEQUENCERS) {
return;
}
if (sequencer[row] == NULL) {
return;
}
sequencer[row]->setCursor(col);
if (sequencer[row]->cursor == col) {
sequencer[row]->cursorClick();
}
}
void Page::populate(Toolbar* toolbar) {
toolbar->push(tool_seq_add);
toolbar->push(tool_step_prev);
toolbar->push(tool_seq_prev);
toolbar->push(tool_seq_next);
toolbar->push(tool_step_next);
toolbar->push(tool_add_note);
toolbar->push(tool_add_div);
toolbar->push(tool_add_output);
toolbar->push(tool_add_sync);
toolbar->push(tool_del_step);
if (sequencer[cursor] != NULL) {
sequencer[cursor]->populate(toolbar);
}
}
void Page::change(ChangeSet* changes, TickBuffer* buffer) {
if (changes == NULL) {
return;
}
changes->rewind();
Change* change;
while ((change = changes->next(TARGET_LEVEL_PAGE)) != NULL) {
switch (change->operation) {
case OP_SEQ_ADD:
addNewLine(cursor);
break;
case OP_SEQ_DELTA:
if (change->value > 0) {
cursorDown();
} else if (change->value < 0) {
cursorUp();
}
break;
case OP_SYNC:
for (int i = 0; i < MAX_SEQUENCERS; i++) {
if (sequencer[i] != NULL) {
int label = sequencer[i]->label;
if (label != 0) {
if (change->value == 0 || label == change->value) {
sequencer[i]->sync();
}
}
} else {
break;
}
buffer->reset();
}
break;
case OP_STEP_DEL:
if (sequencer[cursor] != NULL) {
if (sequencer[cursor]->cursor == 0) {
deleteLine(cursor);
} else {
sequencer[cursor]->cursorDelete();
}
}
break;
}
}
if (sequencer[cursor] != NULL) {
sequencer[cursor]->change(changes, buffer);
}
}
void Page::cursorUp() {
if (cursor > 0) {
cursor--;
sequencer[cursor]->setCursor(sequencer[cursor + 1]->cursor);
}
}
void Page::cursorDown() {
if (cursor < (MAX_SEQUENCERS - 1)) {
if (sequencer[cursor + 1] != NULL) {
cursor++;
sequencer[cursor]->setCursor(sequencer[cursor - 1]->cursor);
}
}
}
void Page::deleteLine(int line) {
if (sequencer[line] != NULL) {
if (line == 0 && sequencer[1] == NULL) {
return; // can't delete the last line
}
Sequencer* retired = sequencer[line];
for (int i = line; i < (MAX_SEQUENCERS - 1); i++) {
sequencer[i] = sequencer[i + 1];
}
if (line == cursor && sequencer[line] != NULL) {
sequencer[line]->setCursor(retired->cursor);
}
sequencer[MAX_SEQUENCERS - 1] = NULL;
if (sequencer[cursor] == NULL) {
cursor--;
}
delete retired;
}
}
void Page::addNewLine(int afterLine) {
if (afterLine >= MAX_SEQUENCERS) {
return;
}
if (sequencer[afterLine + 1] == NULL) {
sequencer[afterLine + 1] = new Sequencer();
if (cursor == afterLine) {
cursor++;
}
} else if (sequencer[MAX_SEQUENCERS-1] == NULL && afterLine > 0) {
for (int i = MAX_SEQUENCERS - 1; i > afterLine; i--) {
sequencer[i] = sequencer[i - 1];
}
sequencer[afterLine + 1] = new Sequencer();
if (cursor >= afterLine) {
cursor++;
}
}
}
<commit_msg>Page: OP_SYNC should not reset buffer, only pull back sequencers<commit_after>#include "Page.h"
Page::Page() {
for (int i = 0; i < MAX_SEQUENCERS; i++) {
sequencer[i] = NULL;
}
addNewLine(-1);
cursor = 0;
tool_seq_add = new Tool("+\nSEQ", OF_KEY_RETURN,
new Change(TARGET_LEVEL_PAGE, OP_SEQ_ADD, 0));
tool_seq_add->key_string = "RET";
tool_step_prev = new Tool("<<\nSTEP", 'h',
new Change(TARGET_LEVEL_SEQUENCER, OP_STEP_DELTA, -1));
tool_step_prev->addKey(OF_KEY_LEFT);
tool_seq_next = new Tool("NEXT\nSEQ", 'j',
new Change(TARGET_LEVEL_PAGE, OP_SEQ_DELTA, 1));
tool_seq_next->addKey(OF_KEY_DOWN);
tool_seq_prev = new Tool("PREV\nSEQ", 'k',
new Change(TARGET_LEVEL_PAGE, OP_SEQ_DELTA, -1));
tool_seq_prev->addKey(OF_KEY_UP);
tool_step_next = new Tool(">>\nSTEP", 'l',
new Change(TARGET_LEVEL_SEQUENCER, OP_STEP_DELTA, 1));
tool_step_next->addKey(OF_KEY_RIGHT);
tool_add_note = new Tool("+\nNOTE", 'n',
new Change(TARGET_LEVEL_SEQUENCER, OP_ADD_STEP_NOTE, 0));
tool_add_div = new Tool("+\nDIV", 'd',
new Change(TARGET_LEVEL_SEQUENCER, OP_ADD_STEP_DIVISION, 8));
tool_add_output = new Tool("+\nOUT", 'O',
new Change(TARGET_LEVEL_SEQUENCER, OP_ADD_STEP_OUTPUT, 0));
tool_add_sync = new Tool("+\nSYNC", 'S',
new Change(TARGET_LEVEL_SEQUENCER, OP_ADD_STEP_SYNC, 0));
tool_del_step = new Tool("DEL", OF_KEY_DEL,
new Change(TARGET_LEVEL_PAGE, OP_STEP_DEL, -1));
tool_del_step->key_string = "DEL";
}
Page::~Page() {
for (int i = 0; i < MAX_SEQUENCERS; i++) {
if (sequencer[i] != NULL) {
delete sequencer[i];
sequencer[i] = NULL;
}
}
delete tool_seq_add;
delete tool_seq_next;
delete tool_seq_prev;
delete tool_step_prev;
delete tool_step_next;
delete tool_add_note;
delete tool_add_div;
delete tool_add_output;
delete tool_add_sync;
delete tool_del_step;
}
void Page::step(TickBuffer* buffer, OutputRouter* output_router) {
for (int i = 0; i < MAX_SEQUENCERS; i++) {
if (sequencer[i] == NULL) {
break;
}
sequencer[i]->step(buffer, output_router);
}
}
void Page::draw(int x, int y, int width, int height, ofTrueTypeFont font) {
ofSetColor(0);
ofDrawRectangle(x, y, width, height);
for (int i = 0; i < MAX_SEQUENCERS; i++) {
if (sequencer[i] == NULL) {
break;
}
sequencer[i]->draw(i, i==cursor, font);
}
}
void Page::mousePressed(int x, int y, int button){
int col = x / 50;
int row = y / 50;
if (row >= MAX_SEQUENCERS) {
return;
}
if (sequencer[row] == NULL) {
return;
}
sequencer[row]->setCursor(col);
if (sequencer[row]->cursor == col) {
sequencer[row]->cursorClick();
}
}
void Page::populate(Toolbar* toolbar) {
toolbar->push(tool_seq_add);
toolbar->push(tool_step_prev);
toolbar->push(tool_seq_prev);
toolbar->push(tool_seq_next);
toolbar->push(tool_step_next);
toolbar->push(tool_add_note);
toolbar->push(tool_add_div);
toolbar->push(tool_add_output);
toolbar->push(tool_add_sync);
toolbar->push(tool_del_step);
if (sequencer[cursor] != NULL) {
sequencer[cursor]->populate(toolbar);
}
}
void Page::change(ChangeSet* changes, TickBuffer* buffer) {
if (changes == NULL) {
return;
}
changes->rewind();
Change* change;
while ((change = changes->next(TARGET_LEVEL_PAGE)) != NULL) {
switch (change->operation) {
case OP_SEQ_ADD:
addNewLine(cursor);
break;
case OP_SEQ_DELTA:
if (change->value > 0) {
cursorDown();
} else if (change->value < 0) {
cursorUp();
}
break;
case OP_SYNC:
for (int i = 0; i < MAX_SEQUENCERS; i++) {
if (sequencer[i] != NULL) {
int label = sequencer[i]->label;
if (label != 0) {
if (change->value == 0 || label == change->value) {
sequencer[i]->sync();
}
}
} else {
break;
}
}
break;
case OP_STEP_DEL:
if (sequencer[cursor] != NULL) {
if (sequencer[cursor]->cursor == 0) {
deleteLine(cursor);
} else {
sequencer[cursor]->cursorDelete();
}
}
break;
}
}
if (sequencer[cursor] != NULL) {
sequencer[cursor]->change(changes, buffer);
}
}
void Page::cursorUp() {
if (cursor > 0) {
cursor--;
sequencer[cursor]->setCursor(sequencer[cursor + 1]->cursor);
}
}
void Page::cursorDown() {
if (cursor < (MAX_SEQUENCERS - 1)) {
if (sequencer[cursor + 1] != NULL) {
cursor++;
sequencer[cursor]->setCursor(sequencer[cursor - 1]->cursor);
}
}
}
void Page::deleteLine(int line) {
if (sequencer[line] != NULL) {
if (line == 0 && sequencer[1] == NULL) {
return; // can't delete the last line
}
Sequencer* retired = sequencer[line];
for (int i = line; i < (MAX_SEQUENCERS - 1); i++) {
sequencer[i] = sequencer[i + 1];
}
if (line == cursor && sequencer[line] != NULL) {
sequencer[line]->setCursor(retired->cursor);
}
sequencer[MAX_SEQUENCERS - 1] = NULL;
if (sequencer[cursor] == NULL) {
cursor--;
}
delete retired;
}
}
void Page::addNewLine(int afterLine) {
if (afterLine >= MAX_SEQUENCERS) {
return;
}
if (sequencer[afterLine + 1] == NULL) {
sequencer[afterLine + 1] = new Sequencer();
if (cursor == afterLine) {
cursor++;
}
} else if (sequencer[MAX_SEQUENCERS-1] == NULL && afterLine > 0) {
for (int i = MAX_SEQUENCERS - 1; i > afterLine; i--) {
sequencer[i] = sequencer[i - 1];
}
sequencer[afterLine + 1] = new Sequencer();
if (cursor >= afterLine) {
cursor++;
}
}
}
<|endoftext|> |
<commit_before>#include <ygo/deck/User.h>
#include <ygo/deck/DB.h>
#include <ygo/deck/DeckSet.h>
#include <mindbw/SQLite3.h>
#include <ygo/data/Serialize.h>
#include <cassert>
#include <stdexcept>
namespace ygo
{
namespace deck
{
User::User(std::string name, bool create) :
mName(std::move(name))
{
// check if the user already exists
auto exists = false;
std::string userid;
mindbw::SQLite3 db(DB::get().path());
db.select(mindbw::KeyList({"name","user_id"}),"users",
mindbw::Equal("name",mName),
[&](mindbw::DataMap data) {
exists = true;
userid = data["user_id"];
});
if (exists) {
mID = userid;
} else if (create) {
mID = db.insert("users",mindbw::ValueList({mName}));
} else {
throw std::runtime_error("User " + mName + " does not exist");
}
}
std::vector<DeckSet> User::deckSets() const
{
// return all deck sets for a given user
std::vector<std::string> deckids;
assert(!DB::get().path().empty());
mindbw::SQLite3 db(DB::get().path());
db.select(mindbw::Unique("deck_set_id"),"user_to_decks",
mindbw::Equal("user_id",id()),
[&](mindbw::DataMap data) {
deckids.push_back(data["deck_set_id"]);
});
// look up the deck set ids and convert them into objects
std::vector<DeckSet> ret;
for (auto&& i : deckids) {
db.select(mindbw::All(),"deck_set",
mindbw::Equal("deck_set_id",i),
[&](mindbw::DataMap data) {
// extract the format
Format f(data::toFormat(data["format"]),
data["format_date"]);
// add a new DBDeckSet
ret.emplace_back(DeckSet{data["name"],*this,f});
});
}
return ret;
}
void User::remove()
{
// delete all the deck sets associated with this user
auto sets = deckSets();
for (auto&& s : sets) {
s.remove();
}
// delete the user
mindbw::SQLite3 db(DB::get().path());
db.del("users",mindbw::Equal("user_id",mID));
}
}
}
<commit_msg>We don't need unique<commit_after>#include <ygo/deck/User.h>
#include <ygo/deck/DB.h>
#include <ygo/deck/DeckSet.h>
#include <mindbw/SQLite3.h>
#include <ygo/data/Serialize.h>
#include <cassert>
#include <stdexcept>
namespace ygo
{
namespace deck
{
User::User(std::string name, bool create) :
mName(std::move(name))
{
// check if the user already exists
auto exists = false;
std::string userid;
mindbw::SQLite3 db(DB::get().path());
db.select(mindbw::KeyList({"name","user_id"}),"users",
mindbw::Equal("name",mName),
[&](mindbw::DataMap data) {
exists = true;
userid = data["user_id"];
});
if (exists) {
mID = userid;
} else if (create) {
mID = db.insert("users",mindbw::ValueList({mName}));
} else {
throw std::runtime_error("User " + mName + " does not exist");
}
}
std::vector<DeckSet> User::deckSets() const
{
// return all deck sets for a given user
std::vector<std::string> deckids;
assert(!DB::get().path().empty());
mindbw::SQLite3 db(DB::get().path());
db.select("deck_set_id","user_to_decks",
mindbw::Equal("user_id",id()),
[&](mindbw::DataMap data) {
deckids.push_back(data["deck_set_id"]);
});
// look up the deck set ids and convert them into objects
std::vector<DeckSet> ret;
for (auto&& i : deckids) {
db.select(mindbw::All(),"deck_set",
mindbw::Equal("deck_set_id",i),
[&](mindbw::DataMap data) {
// extract the format
Format f(data::toFormat(data["format"]),
data["format_date"]);
// add a new DBDeckSet
ret.emplace_back(DeckSet{data["name"],*this,f});
});
}
return ret;
}
void User::remove()
{
// delete all the deck sets associated with this user
auto sets = deckSets();
for (auto&& s : sets) {
s.remove();
}
// delete the user
mindbw::SQLite3 db(DB::get().path());
db.del("users",mindbw::Equal("user_id",mID));
}
}
}
<|endoftext|> |
<commit_before>
#include "Utf8.h"
#include <Arduino.h>
#define ENSURE(condition) do { if (!(condition)) {Serial.println("ENSURE failed at: "#condition); while(1); } } while(0)
#define SIZE_OF_ARRAY(array) (sizeof((array))/sizeof((array)[0]))
#define PTR_OFFSET_BYTES(ptr, nBytes) ((void*)(((char *)(ptr)) + (nBytes)))
#define PTR_OFFSET_BETWEEN(ptrBegin, ptrEnd) ((char*)(ptrEnd) - (char*)(ptrBegin))
size_t
utf8GetBytesToNextChar( const char aChar )
{
/**
* utf-8 skip data extract from glibc.
* the last 0xFE, 0xFF use as special using ( file BOM header )
*/
static const uint8_t s_skip_data[256] PROGMEM =
{
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,6,6,1,1,
};
return (uint8_t)pgm_read_byte(s_skip_data + (uint8_t)(aChar));
}
uint8_t
utf8GetHeaderMask( uint8_t bytesToNextChar )
{
/** the 0 element is unused */
static const uint8_t s_header_mask[7] PROGMEM =
{
0x00, 0x7F, 0x1F, 0x0F, 0x07, 0x03, 0x01,
};
ENSURE( bytesToNextChar < SIZE_OF_ARRAY(s_header_mask) );
return (uint8_t)pgm_read_byte(s_header_mask + (uint8_t)(bytesToNextChar));
}
uint8_t
utf8GetHeaderShift( const uint8_t bytesToNextChar )
{
return ( bytesToNextChar - 1 ) * 6;
}
uint32_t
utf8ToUtf32( const char * str )
{
uint8_t bytesToNextChar;
size_t shift = 0;
uint32_t result = 0;
bytesToNextChar = utf8GetBytesToNextChar( *str );
shift = utf8GetHeaderShift( bytesToNextChar );
result |= ( ((*str) & utf8GetHeaderMask( bytesToNextChar )) << shift );
while( shift > 0 )
{
++ str;
shift -= 6;
result |= ( ( (*str) & 0x3F ) << shift );
}
return result;
}
size_t
utf8ToUtf32String(
uint32_t * utf32Str,
const char * str,
const size_t strSize
)
{
uint32_t * utf32StrBegin = utf32Str;
if( strSize )
{
const char * utf8_end = (const char * )PTR_OFFSET_BYTES( str, strSize );
while( str < utf8_end )
{
*( utf32Str ++ ) = utf8ToUtf32( str );
str = utf8FindNextChar( str );
}
}
else
{
/* wait for '\0' */
while( *str )
{
*( utf32Str ++ ) = utf8ToUtf32( str );
str = utf8FindNextChar( str );
}
}
*utf32Str = 0; /* last character must be 0 */
return PTR_OFFSET_BETWEEN( utf32StrBegin, utf32Str );
}
size_t
utf8CalculateSizeFromUtf32( const uint32_t value )
{
if( value <= 0x7F )
{
return 1;
}
else if( value <= 0x07FF )
{
return 2;
}
else if( value <= 0xFFFF )
{
return 3;
}
else if( value <= 0x1FFFFF )
{
return 4;
}
else if( value <= 0x3FFFFFF )
{
return 5;
}
else if( value <= 0x7FFFFFFF )
{
return 6;
}
else
{ /* invalid values */
return 0;
}
}
size_t
utf8CalculateSizeFromUtf32String( const uint32_t *strBegin, const uint32_t * strEnd )
{
const uint32_t * iterator = strBegin;
size_t result = 0;
while( iterator < strEnd )
{
result += utf8CalculateSizeFromUtf32( *iterator );
}
return result;
}
size_t
utf8FromUtf32( char * str, const uint32_t value )
{
static const char headerMarks[8] PROGMEM =
{
0,
0,
(char)192,
(char)224,
(char)240,
(char)248,
(char)252,
0, /* unused */
};
size_t shift = 0;
uint8_t bytesToNextChar;
char * begin = str;
bytesToNextChar = utf8CalculateSizeFromUtf32( value ) ;
shift = utf8GetHeaderShift( bytesToNextChar );
*str = ( ( value >> shift ) & utf8GetHeaderMask( bytesToNextChar ) )
| (uint8_t)pgm_read_byte(headerMarks + (uint8_t)(bytesToNextChar));
while( shift > 0 )
{
++ str;
shift -= 6;
*str = 0x80 | ( ( value >> shift ) & 0x3F );
}
return bytesToNextChar;
}
size_t
utf8FromUtf32String(
char * str,
const uint32_t *utf32Str,
const size_t utf32StrSize
)
{
size_t result = 0;
if( utf32StrSize )
{
const uint32_t *utf32StrEnd = (const uint32_t *)PTR_OFFSET_BYTES( utf32Str, utf32StrSize );
while( utf32Str < utf32StrEnd )
{
result += utf8FromUtf32( str, *utf32Str );
++ utf32Str;
}
}
else
{
while( *utf32Str )
{
result += utf8FromUtf32( str, *utf32Str );
++ utf32Str;
}
}
*str = 0; /* last character must be 0 */
return result;
}
bool
utf8IsStartMarker( const char aChar )
{
return 0x80 != ( aChar & 0xC0 );
}
char *
utf8FindNextChar( const char * str )
{
/* validate the current str */
if( ! utf8IsStartMarker( *str ) )
{
while( !utf8IsStartMarker( * ( ++ str ) ) ) {};
return const_cast<char*>( str );
}
return (char *)PTR_OFFSET_BYTES( str, utf8GetBytesToNextChar( *str ) );
};
char *
utf8FindPriorChar( const char * str )
{
while( !utf8IsStartMarker( * ( -- str ) ) ) {};
return const_cast<char *>(str);
};
char *
utf8SkipCharsForward( const char *str, size_t distance )
{
while( ( distance > 0 ) && ( *str != 0 ) )
{
str = utf8FindNextChar( str );
-- distance;
};
return const_cast<char *>( str );
}
char *
utf8SkipCharsBackward( const char *str, size_t distance )
{
while( distance > 0 )
{
str = utf8FindPriorChar( str );
-- distance;
};
return const_cast<char *>( str );
}
size_t
utf8GetLength( const char * str )
{
size_t length = 0;
while( * str )
{
++ length;
str = utf8FindNextChar( str );
}
return length;
};
void
utf8GetLengthAndSize( const char * str, size_t &length, size_t &size )
{
size_t skipBytes;
length = 0;
size = 0;
while( * str )
{
skipBytes = utf8GetBytesToNextChar( *str );
++ length;
size += skipBytes;
str = (const char *)PTR_OFFSET_BYTES( str, skipBytes );
}
}
size_t
utf8GetLengthBetween( const char * strBegin, const char * strEnd )
{
size_t result = 0;
while( strBegin < strEnd )
{
strBegin = utf8FindNextChar( strBegin );
++ result;
}
return result;
}
size_t
utf8GetSizeBetween( const char * strBegin, const char * strEnd )
{
const char * iterator = strBegin;
while( iterator < strEnd )
{
iterator = utf8FindNextChar( iterator );
}
return PTR_OFFSET_BETWEEN( strBegin, strEnd ) ;
}
void
utf8GetLengthAndSizeBetween(
const char * strBegin,
const char * strEnd,
size_t &length,
size_t &size )
{
const char * iterator = strBegin;
length = 0;
while( iterator < strEnd )
{
iterator = utf8FindNextChar( iterator );
++ length;
}
size = PTR_OFFSET_BETWEEN( strBegin, strEnd );
}
ptrdiff_t
utf8GetSizeFromLength( const char * str, size_t length )
{
const char * strBegin = str;
while( length -- > 0 )
{
str = utf8FindNextChar( str );
};
return PTR_OFFSET_BETWEEN( strBegin, str );
}
<commit_msg>Fixed some characters be converted to 0 through utf8ToUtf32()<commit_after>
#include "Utf8.h"
#include <Arduino.h>
#define ENSURE(condition) do { if (!(condition)) {Serial.println("ENSURE failed at: "#condition); while(1); } } while(0)
#define SIZE_OF_ARRAY(array) (sizeof((array))/sizeof((array)[0]))
#define PTR_OFFSET_BYTES(ptr, nBytes) ((void*)(((char *)(ptr)) + (nBytes)))
#define PTR_OFFSET_BETWEEN(ptrBegin, ptrEnd) ((char*)(ptrEnd) - (char*)(ptrBegin))
size_t
utf8GetBytesToNextChar( const char aChar )
{
/**
* utf-8 skip data extract from glibc.
* the last 0xFE, 0xFF use as special using ( file BOM header )
*/
static const uint8_t s_skip_data[256] PROGMEM =
{
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,6,6,1,1,
};
return (uint8_t)pgm_read_byte(s_skip_data + (uint8_t)(aChar));
}
uint8_t
utf8GetHeaderMask( uint8_t bytesToNextChar )
{
/** the 0 element is unused */
static const uint8_t s_header_mask[7] PROGMEM =
{
0x00, 0x7F, 0x1F, 0x0F, 0x07, 0x03, 0x01,
};
ENSURE( bytesToNextChar < SIZE_OF_ARRAY(s_header_mask) );
return (uint8_t)pgm_read_byte(s_header_mask + (uint8_t)(bytesToNextChar));
}
uint8_t
utf8GetHeaderShift( const uint8_t bytesToNextChar )
{
return ( bytesToNextChar - 1 ) * 6;
}
uint32_t
utf8ToUtf32( const char * str )
{
uint8_t bytesToNextChar;
size_t shift = 0;
uint32_t result = 0;
bytesToNextChar = utf8GetBytesToNextChar( *str );
shift = utf8GetHeaderShift( bytesToNextChar );
result |= ( (((uint32_t)(uint8_t)*str) & (uint32_t)utf8GetHeaderMask( bytesToNextChar )) << shift );
while( shift > 0 )
{
++ str;
shift -= 6;
result |= ( ( ((uint32_t)(uint8_t)*str) & 0x3F ) << shift );
}
return result;
}
size_t
utf8ToUtf32String(
uint32_t * utf32Str,
const char * str,
const size_t strSize
)
{
uint32_t * utf32StrBegin = utf32Str;
if( strSize )
{
const char * utf8_end = (const char * )PTR_OFFSET_BYTES( str, strSize );
while( str < utf8_end )
{
*( utf32Str ++ ) = utf8ToUtf32( str );
str = utf8FindNextChar( str );
}
}
else
{
/* wait for '\0' */
while( *str )
{
*( utf32Str ++ ) = utf8ToUtf32( str );
str = utf8FindNextChar( str );
}
}
*utf32Str = 0; /* last character must be 0 */
return PTR_OFFSET_BETWEEN( utf32StrBegin, utf32Str );
}
size_t
utf8CalculateSizeFromUtf32( const uint32_t value )
{
if( value <= 0x7F )
{
return 1;
}
else if( value <= 0x07FF )
{
return 2;
}
else if( value <= 0xFFFF )
{
return 3;
}
else if( value <= 0x1FFFFF )
{
return 4;
}
else if( value <= 0x3FFFFFF )
{
return 5;
}
else if( value <= 0x7FFFFFFF )
{
return 6;
}
else
{ /* invalid values */
return 0;
}
}
size_t
utf8CalculateSizeFromUtf32String( const uint32_t *strBegin, const uint32_t * strEnd )
{
const uint32_t * iterator = strBegin;
size_t result = 0;
while( iterator < strEnd )
{
result += utf8CalculateSizeFromUtf32( *iterator );
}
return result;
}
size_t
utf8FromUtf32( char * str, const uint32_t value )
{
static const char headerMarks[8] PROGMEM =
{
0,
0,
(char)192,
(char)224,
(char)240,
(char)248,
(char)252,
0, /* unused */
};
size_t shift = 0;
uint8_t bytesToNextChar;
char * begin = str;
bytesToNextChar = utf8CalculateSizeFromUtf32( value ) ;
shift = utf8GetHeaderShift( bytesToNextChar );
*str = ( ( value >> shift ) & utf8GetHeaderMask( bytesToNextChar ) )
| (uint8_t)pgm_read_byte(headerMarks + (uint8_t)(bytesToNextChar));
while( shift > 0 )
{
++ str;
shift -= 6;
*str = 0x80 | ( ( value >> shift ) & 0x3F );
}
return bytesToNextChar;
}
size_t
utf8FromUtf32String(
char * str,
const uint32_t *utf32Str,
const size_t utf32StrSize
)
{
size_t result = 0;
if( utf32StrSize )
{
const uint32_t *utf32StrEnd = (const uint32_t *)PTR_OFFSET_BYTES( utf32Str, utf32StrSize );
while( utf32Str < utf32StrEnd )
{
result += utf8FromUtf32( str, *utf32Str );
++ utf32Str;
}
}
else
{
while( *utf32Str )
{
result += utf8FromUtf32( str, *utf32Str );
++ utf32Str;
}
}
*str = 0; /* last character must be 0 */
return result;
}
bool
utf8IsStartMarker( const char aChar )
{
return 0x80 != ( aChar & 0xC0 );
}
char *
utf8FindNextChar( const char * str )
{
/* validate the current str */
if( ! utf8IsStartMarker( *str ) )
{
while( !utf8IsStartMarker( * ( ++ str ) ) ) {};
return const_cast<char*>( str );
}
return (char *)PTR_OFFSET_BYTES( str, utf8GetBytesToNextChar( *str ) );
};
char *
utf8FindPriorChar( const char * str )
{
while( !utf8IsStartMarker( * ( -- str ) ) ) {};
return const_cast<char *>(str);
};
char *
utf8SkipCharsForward( const char *str, size_t distance )
{
while( ( distance > 0 ) && ( *str != 0 ) )
{
str = utf8FindNextChar( str );
-- distance;
};
return const_cast<char *>( str );
}
char *
utf8SkipCharsBackward( const char *str, size_t distance )
{
while( distance > 0 )
{
str = utf8FindPriorChar( str );
-- distance;
};
return const_cast<char *>( str );
}
size_t
utf8GetLength( const char * str )
{
size_t length = 0;
while( * str )
{
++ length;
str = utf8FindNextChar( str );
}
return length;
};
void
utf8GetLengthAndSize( const char * str, size_t &length, size_t &size )
{
size_t skipBytes;
length = 0;
size = 0;
while( * str )
{
skipBytes = utf8GetBytesToNextChar( *str );
++ length;
size += skipBytes;
str = (const char *)PTR_OFFSET_BYTES( str, skipBytes );
}
}
size_t
utf8GetLengthBetween( const char * strBegin, const char * strEnd )
{
size_t result = 0;
while( strBegin < strEnd )
{
strBegin = utf8FindNextChar( strBegin );
++ result;
}
return result;
}
size_t
utf8GetSizeBetween( const char * strBegin, const char * strEnd )
{
const char * iterator = strBegin;
while( iterator < strEnd )
{
iterator = utf8FindNextChar( iterator );
}
return PTR_OFFSET_BETWEEN( strBegin, strEnd ) ;
}
void
utf8GetLengthAndSizeBetween(
const char * strBegin,
const char * strEnd,
size_t &length,
size_t &size )
{
const char * iterator = strBegin;
length = 0;
while( iterator < strEnd )
{
iterator = utf8FindNextChar( iterator );
++ length;
}
size = PTR_OFFSET_BETWEEN( strBegin, strEnd );
}
ptrdiff_t
utf8GetSizeFromLength( const char * str, size_t length )
{
const char * strBegin = str;
while( length -- > 0 )
{
str = utf8FindNextChar( str );
};
return PTR_OFFSET_BETWEEN( strBegin, str );
}
<|endoftext|> |
<commit_before>
#include "Utf8.h"
#include <Arduino.h>
#define ENSURE(condition) do { if (!(condition)) {Serial.println("ENSURE failed at: "#condition); while(1); } } while(0)
#define SIZE_OF_ARRAY(array) (sizeof((array))/sizeof((array)[0]))
#define PTR_OFFSET_BYTES(ptr, nBytes) ((void*)(((char *)(ptr)) + (nBytes)))
#define PTR_OFFSET_BETWEEN(ptrBegin, ptrEnd) ((char*)(ptrEnd) - (char*)(ptrBegin))
size_t
utf8GetBytesToNextChar( const char aChar )
{
/**
* utf-8 skip data extract from glibc.
* the last 0xFE, 0xFF use as special using ( file BOM header )
*/
static const uint8_t s_skip_data[256] =
{
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,6,6,1,1,
};
return s_skip_data[ static_cast<uint8_t>( aChar ) ];
}
uint8_t
utf8GetHeaderMask( uint8_t bytesToNextChar )
{
/** the 0 element is unused */
static const uint8_t s_header_mask[7] =
{
0x00, 0x7F, 0x1F, 0x0F, 0x07, 0x03, 0x01,
};
ENSURE( bytesToNextChar < SIZE_OF_ARRAY(s_header_mask) );
return s_header_mask[bytesToNextChar];
}
uint8_t
utf8GetHeaderShift( const uint8_t bytesToNextChar )
{
return ( bytesToNextChar - 1 ) * 6;
}
uint32_t
utf8ToUtf32( const char * str )
{
uint8_t bytesToNextChar;
size_t shift = 0;
uint32_t result = 0;
bytesToNextChar = utf8GetBytesToNextChar( *str );
shift = utf8GetHeaderShift( bytesToNextChar );
result |= ( ((*str) & utf8GetHeaderMask( bytesToNextChar )) << shift );
while( shift > 0 )
{
++ str;
shift -= 6;
result |= ( ( (*str) & 0x3F ) << shift );
}
return result;
}
size_t
utf8ToUtf32String(
uint32_t * utf32Str,
const char * str,
const size_t strSize
)
{
uint32_t * utf32StrBegin = utf32Str;
if( strSize )
{
const char * utf8_end = (const char * )PTR_OFFSET_BYTES( str, strSize );
while( str < utf8_end )
{
*( utf32Str ++ ) = utf8ToUtf32( str );
str = utf8FindNextChar( str );
}
}
else
{
/* wait for '\0' */
while( *str )
{
*( utf32Str ++ ) = utf8ToUtf32( str );
str = utf8FindNextChar( str );
}
}
*utf32Str = 0; /* last character must be 0 */
return PTR_OFFSET_BETWEEN( utf32StrBegin, utf32Str );
}
size_t
utf8CalculateSizeFromUtf32( const uint32_t value )
{
if( value <= 0x7F )
{
return 1;
}
else if( value <= 0x07FF )
{
return 2;
}
else if( value <= 0xFFFF )
{
return 3;
}
else if( value <= 0x1FFFFF )
{
return 4;
}
else if( value <= 0x3FFFFFF )
{
return 5;
}
else if( value <= 0x7FFFFFFF )
{
return 6;
}
else
{ /* invalid values */
return 0;
}
}
size_t
utf8CalculateSizeFromUtf32String( const uint32_t *strBegin, const uint32_t * strEnd )
{
const uint32_t * iterator = strBegin;
size_t result = 0;
while( iterator < strEnd )
{
result += utf8CalculateSizeFromUtf32( *iterator );
}
return result;
}
size_t
utf8FromUtf32( char * str, const uint32_t value )
{
static char headerMarks[8] =
{
0,
0,
(char)192,
(char)224,
(char)240,
(char)248,
(char)252,
0, /* unused */
};
size_t shift = 0;
uint8_t bytesToNextChar;
char * begin = str;
bytesToNextChar = utf8CalculateSizeFromUtf32( value ) ;
shift = utf8GetHeaderShift( bytesToNextChar );
*str = ( ( value >> shift ) & utf8GetHeaderMask( bytesToNextChar ) )
| headerMarks[bytesToNextChar] ;
while( shift > 0 )
{
++ str;
shift -= 6;
*str = 0x80 | ( ( value >> shift ) & 0x3F );
}
return bytesToNextChar;
}
size_t
utf8FromUtf32String(
char * str,
const uint32_t *utf32Str,
const size_t utf32StrSize
)
{
size_t result = 0;
if( utf32StrSize )
{
const uint32_t *utf32StrEnd = (const uint32_t *)PTR_OFFSET_BYTES( utf32Str, utf32StrSize );
while( utf32Str < utf32StrEnd )
{
result += utf8FromUtf32( str, *utf32Str );
++ utf32Str;
}
}
else
{
while( *utf32Str )
{
result += utf8FromUtf32( str, *utf32Str );
++ utf32Str;
}
}
*str = 0; /* last character must be 0 */
return result;
}
bool
utf8IsStartMarker( const char aChar )
{
return 0x80 != ( aChar & 0xC0 );
}
char *
utf8FindNextChar( const char * str )
{
/* validate the current str */
if( ! utf8IsStartMarker( *str ) )
{
while( !utf8IsStartMarker( * ( ++ str ) ) ) {};
return const_cast<char*>( str );
}
return (char *)PTR_OFFSET_BYTES( str, utf8GetBytesToNextChar( *str ) );
};
char *
utf8FindPriorChar( const char * str )
{
while( !utf8IsStartMarker( * ( -- str ) ) ) {};
return const_cast<char *>(str);
};
char *
utf8SkipCharsForward( const char *str, size_t distance )
{
while( ( distance > 0 ) && ( *str != 0 ) )
{
str = utf8FindNextChar( str );
-- distance;
};
return const_cast<char *>( str );
}
char *
utf8SkipCharsBackward( const char *str, size_t distance )
{
while( distance > 0 )
{
str = utf8FindPriorChar( str );
-- distance;
};
return const_cast<char *>( str );
}
size_t
utf8GetLength( const char * str )
{
size_t length = 0;
while( * str )
{
++ length;
str = utf8FindNextChar( str );
}
return length;
};
void
utf8GetLengthAndSize( const char * str, size_t &length, size_t &size )
{
size_t skipBytes;
length = 0;
size = 0;
while( * str )
{
skipBytes = utf8GetBytesToNextChar( *str );
++ length;
size += skipBytes;
str = (const char *)PTR_OFFSET_BYTES( str, skipBytes );
}
}
size_t
utf8GetLengthBetween( const char * strBegin, const char * strEnd )
{
size_t result = 0;
while( strBegin < strEnd )
{
strBegin = utf8FindNextChar( strBegin );
++ result;
}
return result;
}
size_t
utf8GetSizeBetween( const char * strBegin, const char * strEnd )
{
const char * iterator = strBegin;
while( iterator < strEnd )
{
iterator = utf8FindNextChar( iterator );
}
return PTR_OFFSET_BETWEEN( strBegin, strEnd ) ;
}
void
utf8GetLengthAndSizeBetween(
const char * strBegin,
const char * strEnd,
size_t &length,
size_t &size )
{
const char * iterator = strBegin;
length = 0;
while( iterator < strEnd )
{
iterator = utf8FindNextChar( iterator );
++ length;
}
size = PTR_OFFSET_BETWEEN( strBegin, strEnd );
}
ptrdiff_t
utf8GetSizeFromLength( const char * str, size_t length )
{
const char * strBegin = str;
while( length -- > 0 )
{
str = utf8FindNextChar( str );
};
return PTR_OFFSET_BETWEEN( strBegin, str );
}
<commit_msg>Stored all data array into flash memory (Reduce SRAM using)<commit_after>
#include "Utf8.h"
#include <Arduino.h>
#define ENSURE(condition) do { if (!(condition)) {Serial.println("ENSURE failed at: "#condition); while(1); } } while(0)
#define SIZE_OF_ARRAY(array) (sizeof((array))/sizeof((array)[0]))
#define PTR_OFFSET_BYTES(ptr, nBytes) ((void*)(((char *)(ptr)) + (nBytes)))
#define PTR_OFFSET_BETWEEN(ptrBegin, ptrEnd) ((char*)(ptrEnd) - (char*)(ptrBegin))
size_t
utf8GetBytesToNextChar( const char aChar )
{
/**
* utf-8 skip data extract from glibc.
* the last 0xFE, 0xFF use as special using ( file BOM header )
*/
static const uint8_t s_skip_data[256] PROGMEM =
{
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,6,6,1,1,
};
return (uint8_t)pgm_read_byte(s_skip_data + (uint8_t)(aChar));
}
uint8_t
utf8GetHeaderMask( uint8_t bytesToNextChar )
{
/** the 0 element is unused */
static const uint8_t s_header_mask[7] PROGMEM =
{
0x00, 0x7F, 0x1F, 0x0F, 0x07, 0x03, 0x01,
};
ENSURE( bytesToNextChar < SIZE_OF_ARRAY(s_header_mask) );
return (uint8_t)pgm_read_byte(s_header_mask + (uint8_t)(bytesToNextChar));
}
uint8_t
utf8GetHeaderShift( const uint8_t bytesToNextChar )
{
return ( bytesToNextChar - 1 ) * 6;
}
uint32_t
utf8ToUtf32( const char * str )
{
uint8_t bytesToNextChar;
size_t shift = 0;
uint32_t result = 0;
bytesToNextChar = utf8GetBytesToNextChar( *str );
shift = utf8GetHeaderShift( bytesToNextChar );
result |= ( ((*str) & utf8GetHeaderMask( bytesToNextChar )) << shift );
while( shift > 0 )
{
++ str;
shift -= 6;
result |= ( ( (*str) & 0x3F ) << shift );
}
return result;
}
size_t
utf8ToUtf32String(
uint32_t * utf32Str,
const char * str,
const size_t strSize
)
{
uint32_t * utf32StrBegin = utf32Str;
if( strSize )
{
const char * utf8_end = (const char * )PTR_OFFSET_BYTES( str, strSize );
while( str < utf8_end )
{
*( utf32Str ++ ) = utf8ToUtf32( str );
str = utf8FindNextChar( str );
}
}
else
{
/* wait for '\0' */
while( *str )
{
*( utf32Str ++ ) = utf8ToUtf32( str );
str = utf8FindNextChar( str );
}
}
*utf32Str = 0; /* last character must be 0 */
return PTR_OFFSET_BETWEEN( utf32StrBegin, utf32Str );
}
size_t
utf8CalculateSizeFromUtf32( const uint32_t value )
{
if( value <= 0x7F )
{
return 1;
}
else if( value <= 0x07FF )
{
return 2;
}
else if( value <= 0xFFFF )
{
return 3;
}
else if( value <= 0x1FFFFF )
{
return 4;
}
else if( value <= 0x3FFFFFF )
{
return 5;
}
else if( value <= 0x7FFFFFFF )
{
return 6;
}
else
{ /* invalid values */
return 0;
}
}
size_t
utf8CalculateSizeFromUtf32String( const uint32_t *strBegin, const uint32_t * strEnd )
{
const uint32_t * iterator = strBegin;
size_t result = 0;
while( iterator < strEnd )
{
result += utf8CalculateSizeFromUtf32( *iterator );
}
return result;
}
size_t
utf8FromUtf32( char * str, const uint32_t value )
{
static const char headerMarks[8] PROGMEM =
{
0,
0,
(char)192,
(char)224,
(char)240,
(char)248,
(char)252,
0, /* unused */
};
size_t shift = 0;
uint8_t bytesToNextChar;
char * begin = str;
bytesToNextChar = utf8CalculateSizeFromUtf32( value ) ;
shift = utf8GetHeaderShift( bytesToNextChar );
*str = ( ( value >> shift ) & utf8GetHeaderMask( bytesToNextChar ) )
| (uint8_t)pgm_read_byte(headerMarks + (uint8_t)(bytesToNextChar));
while( shift > 0 )
{
++ str;
shift -= 6;
*str = 0x80 | ( ( value >> shift ) & 0x3F );
}
return bytesToNextChar;
}
size_t
utf8FromUtf32String(
char * str,
const uint32_t *utf32Str,
const size_t utf32StrSize
)
{
size_t result = 0;
if( utf32StrSize )
{
const uint32_t *utf32StrEnd = (const uint32_t *)PTR_OFFSET_BYTES( utf32Str, utf32StrSize );
while( utf32Str < utf32StrEnd )
{
result += utf8FromUtf32( str, *utf32Str );
++ utf32Str;
}
}
else
{
while( *utf32Str )
{
result += utf8FromUtf32( str, *utf32Str );
++ utf32Str;
}
}
*str = 0; /* last character must be 0 */
return result;
}
bool
utf8IsStartMarker( const char aChar )
{
return 0x80 != ( aChar & 0xC0 );
}
char *
utf8FindNextChar( const char * str )
{
/* validate the current str */
if( ! utf8IsStartMarker( *str ) )
{
while( !utf8IsStartMarker( * ( ++ str ) ) ) {};
return const_cast<char*>( str );
}
return (char *)PTR_OFFSET_BYTES( str, utf8GetBytesToNextChar( *str ) );
};
char *
utf8FindPriorChar( const char * str )
{
while( !utf8IsStartMarker( * ( -- str ) ) ) {};
return const_cast<char *>(str);
};
char *
utf8SkipCharsForward( const char *str, size_t distance )
{
while( ( distance > 0 ) && ( *str != 0 ) )
{
str = utf8FindNextChar( str );
-- distance;
};
return const_cast<char *>( str );
}
char *
utf8SkipCharsBackward( const char *str, size_t distance )
{
while( distance > 0 )
{
str = utf8FindPriorChar( str );
-- distance;
};
return const_cast<char *>( str );
}
size_t
utf8GetLength( const char * str )
{
size_t length = 0;
while( * str )
{
++ length;
str = utf8FindNextChar( str );
}
return length;
};
void
utf8GetLengthAndSize( const char * str, size_t &length, size_t &size )
{
size_t skipBytes;
length = 0;
size = 0;
while( * str )
{
skipBytes = utf8GetBytesToNextChar( *str );
++ length;
size += skipBytes;
str = (const char *)PTR_OFFSET_BYTES( str, skipBytes );
}
}
size_t
utf8GetLengthBetween( const char * strBegin, const char * strEnd )
{
size_t result = 0;
while( strBegin < strEnd )
{
strBegin = utf8FindNextChar( strBegin );
++ result;
}
return result;
}
size_t
utf8GetSizeBetween( const char * strBegin, const char * strEnd )
{
const char * iterator = strBegin;
while( iterator < strEnd )
{
iterator = utf8FindNextChar( iterator );
}
return PTR_OFFSET_BETWEEN( strBegin, strEnd ) ;
}
void
utf8GetLengthAndSizeBetween(
const char * strBegin,
const char * strEnd,
size_t &length,
size_t &size )
{
const char * iterator = strBegin;
length = 0;
while( iterator < strEnd )
{
iterator = utf8FindNextChar( iterator );
++ length;
}
size = PTR_OFFSET_BETWEEN( strBegin, strEnd );
}
ptrdiff_t
utf8GetSizeFromLength( const char * str, size_t length )
{
const char * strBegin = str;
while( length -- > 0 )
{
str = utf8FindNextChar( str );
};
return PTR_OFFSET_BETWEEN( strBegin, str );
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
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.
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 COPYRIGHT HOLDER 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.
*/
/** \file fclaw2d_face_neighbors.cpp
* Average, coarsen and copy between grids at faces.
**/
#include <fclaw2d_global.h>
#include <fclaw2d_ghost_fill.h>
#include <fclaw2d_clawpatch.hpp>
#include <ClawPatch.H>
/* This is used to determine neighbor patch relative level (finer, coarser or samesize) */
enum
{
COARSER_GRID = -1,
SAMESIZE_GRID,
FINER_GRID
};
/* This function is a bit overkill, but I put it here so the logic in both
the corner fill and face fill are the same */
static
void get_face_type(fclaw2d_domain_t *domain,
int iface,
fclaw_bool intersects_phys_bdry[],
fclaw_bool intersects_block[],
fclaw_bool *is_block_face,
fclaw_bool *is_interior_face)
{
*is_block_face = intersects_block[iface];
*is_interior_face = !intersects_phys_bdry[iface];
}
static
void get_face_neighbors(fclaw2d_domain_t *domain,
int this_block_idx,
int this_patch_idx,
int iface,
int is_block_face,
int *neighbor_block_idx,
fclaw2d_patch_t* neighbor_patches[],
int **ref_flag_ptr,
int **fine_grid_pos_ptr,
int **iface_neighbor_ptr,
int ftransform[])
{
int rproc[p4est_refineFactor];
int rblockno;
int rpatchno[p4est_refineFactor];
int rfaceno;
int num_neighbors;
for(int ir = 0; ir < p4est_refineFactor; ir++)
{
neighbor_patches[ir] = NULL;
}
fclaw2d_patch_relation_t neighbor_type =
fclaw2d_patch_face_neighbors(domain,
this_block_idx,
this_patch_idx,
iface,
rproc,
&rblockno,
rpatchno,
&rfaceno);
/* ------------------------------
neighbor_type is one of :
FCLAW2D_PATCH_BOUNDARY, -- physical boundary
FCLAW2D_PATCH_HALFSIZE,
FCLAW2D_PATCH_SAMESIZE,
FCLAW2D_PATCH_DOUBLESIZE
------------------------------- */
if (neighbor_type == FCLAW2D_PATCH_BOUNDARY)
{
/* This case should be excluded by earlier checkes */
printf("get_face_neighbors (fclaw2d_face_neighbors.cpp) : No patch found\n");
exit(0);
}
else
{
*neighbor_block_idx = is_block_face ? rblockno : -1;
/* Get encoding of transforming a neighbor coordinate across a face */
fclaw2d_patch_face_transformation (iface, rfaceno, ftransform);
if (!is_block_face)
{
/* If we are within one patch this is a special case */
FCLAW_ASSERT (*neighbor_block_idx == -1);
ftransform[8] = 4;
}
if (neighbor_type == FCLAW2D_PATCH_SAMESIZE)
{
**ref_flag_ptr = 0;
*fine_grid_pos_ptr = NULL;
num_neighbors = 1;
}
else if (neighbor_type == FCLAW2D_PATCH_DOUBLESIZE)
{
**ref_flag_ptr = -1;
**fine_grid_pos_ptr = rproc[1]; /* Special storage for fine grid info */
num_neighbors = 1;
}
else if (neighbor_type == FCLAW2D_PATCH_HALFSIZE)
{
/* Patch has two neighbors */
**ref_flag_ptr = 1; /* patches are at one level finer */
*fine_grid_pos_ptr = NULL;
num_neighbors = p4est_refineFactor;
}
else
{
printf ("Illegal fclaw2d_patch_face_neighbors return value\n");
exit (1);
}
for(int ir = 0; ir < num_neighbors; ir++)
{
fclaw2d_patch_t *neighbor;
if (rproc[ir] == domain->mpirank)
{
/* neighbor patch is local */
fclaw2d_block_t *neighbor_block = &domain->blocks[rblockno];
neighbor = &neighbor_block->patches[rpatchno[ir]];
}
else
{
/* neighbor patch is on a remote processor */
neighbor = &domain->ghost_patches[rpatchno[ir]];
}
neighbor_patches[ir] = neighbor;
}
**iface_neighbor_ptr = iface;
fclaw2d_patch_face_swap(*iface_neighbor_ptr,&rfaceno);
}
}
/**
* \ingroup Averaging
**/
void cb_face_fill(fclaw2d_domain_t *domain,
fclaw2d_patch_t *this_patch,
int this_block_idx,
int this_patch_idx,
void *user)
{
fclaw2d_exchange_info_t *filltype = (fclaw2d_exchange_info_t*) user;
fclaw_bool time_interp = filltype->time_interp;
fclaw_bool is_coarse = filltype->grid_type == FCLAW2D_IS_COARSE;
fclaw_bool is_fine = filltype->grid_type == FCLAW2D_IS_FINE;
fclaw_bool read_parallel_patches = filltype->read_parallel_patches;
fclaw_bool copy_from_neighbor = filltype->exchange_type == FCLAW2D_COPY;
fclaw_bool average_from_neighbor = filltype->exchange_type == FCLAW2D_AVERAGE;
fclaw_bool interpolate_to_neighbor = filltype->exchange_type == FCLAW2D_INTERPOLATE;
const amr_options_t *gparms = get_domain_parms(domain);
const int refratio = gparms->refratio;
fclaw_bool intersects_phys_bdry[NumFaces];
fclaw_bool intersects_block[NumFaces];
fclaw2d_get_physical_bc(domain,this_block_idx,this_patch_idx,
intersects_phys_bdry);
fclaw2d_block_get_block_boundary(domain, this_patch, intersects_block);
/* Transform data needed at block boundaries */
fclaw2d_transform_data_t transform_data;
transform_data.mx = gparms->mx;
transform_data.my = gparms->my;
transform_data.based = 1; /* cell-centered data in this routine. */
transform_data.this_patch = this_patch;
transform_data.neighbor_patch = NULL; /* gets filled in below. */
fclaw2d_transform_data_t transform_data_finegrid;
transform_data_finegrid.mx = gparms->mx;
transform_data_finegrid.my = gparms->my;
transform_data_finegrid.based = 1; // cell-centered data in this routine.
ClawPatch *this_cp = fclaw2d_clawpatch_get_cp(this_patch);
for (int iface = 0; iface < NumFaces; iface++)
{
int idir = iface/2;
fclaw_bool is_block_face;
fclaw_bool is_interior_face;
get_face_type(domain,
iface,
intersects_phys_bdry,
intersects_block,
&is_block_face,
&is_interior_face);
if (is_interior_face) /* Not on a physical boundary */
{
/* Output arguments */
int neighbor_block_idx;
int neighbor_level; /* = -1, 0, 1 */
int *ref_flag_ptr = &neighbor_level;
int fine_grid_pos = -1;
int *fine_grid_pos_ptr = &fine_grid_pos;
/* Get the face neighbor relative to the neighbor's coordinate
orientation (this isn't used here) */
int iface_neighbor;
int *iface_neighbor_ptr = &iface_neighbor;
fclaw2d_patch_t* neighbor_patches[p4est_refineFactor];
/* Reset this in case it got set in a remote copy */
transform_data.this_patch = this_patch;
this_cp = fclaw2d_clawpatch_get_cp(this_patch);
/* transform_data.block_iface = iface; */
get_face_neighbors(domain,
this_block_idx,
this_patch_idx,
iface,
is_block_face,
&neighbor_block_idx,
neighbor_patches,
&ref_flag_ptr,
&fine_grid_pos_ptr,
&iface_neighbor_ptr,
transform_data.transform);
/* fclaw_bool block_boundary = (neighbor_block_idx >= 0); */
if (ref_flag_ptr == NULL)
{
/* We should never end up here */
printf("cb_face_fill (fclaw2d_face_neighbors.cpp) : no face found\n");
exit(0);
}
/* Parallel distribution keeps siblings on same processor */
fclaw_bool remote_neighbor;
remote_neighbor = fclaw2d_patch_is_ghost(neighbor_patches[0]);
if (is_coarse && ((read_parallel_patches && remote_neighbor) || !remote_neighbor))
{
if (neighbor_level == FINER_GRID)
{
for (int igrid = 0; igrid < p4est_refineFactor; igrid++)
{
ClawPatch *fine_neighbor_cp =
fclaw2d_clawpatch_get_cp(neighbor_patches[igrid]);
transform_data.neighbor_patch = neighbor_patches[igrid];
if (interpolate_to_neighbor && !remote_neighbor)
{
/* interpolate to igrid */
this_cp->interpolate_face_ghost(idir,iface,p4est_refineFactor,
refratio,fine_neighbor_cp,
time_interp,igrid,
&transform_data);
}
else if (average_from_neighbor)
{
/* average from igrid */
this_cp->average_face_ghost(idir,iface,p4est_refineFactor,
refratio,fine_neighbor_cp,
time_interp,igrid,
&transform_data);
}
}
}
else if (neighbor_level == SAMESIZE_GRID && copy_from_neighbor)
{
/* Copy to same size patch */
fclaw2d_patch_t *neighbor_patch = neighbor_patches[0];
ClawPatch *neighbor_cp = fclaw2d_clawpatch_get_cp(neighbor_patch);
transform_data.neighbor_patch = neighbor_patch;
this_cp->exchange_face_ghost(iface,neighbor_cp,&transform_data);
if (remote_neighbor)
{
/* We also need to copy _to_ the remote neighbor; switch contexts, but
use ClawPatches that are only in scope here, to avoid
conflicts with above uses of the same variables */
ClawPatch *neighbor_cp = this_cp;
ClawPatch *this_cp = fclaw2d_clawpatch_get_cp(neighbor_patch);
transform_data.this_patch = neighbor_patch;
transform_data.neighbor_patch = this_patch;
int this_iface = iface_neighbor;
if (neighbor_block_idx >= 0)
{
fclaw2d_patch_face_transformation (this_iface, iface,
transform_data.transform);
}
this_cp->exchange_face_ghost(this_iface,neighbor_cp,&transform_data);
}
}
}
else if (is_fine && neighbor_level == COARSER_GRID && remote_neighbor
&& read_parallel_patches)
{
/* Swap 'this_patch' and the neighbor patch */
ClawPatch *coarse_cp = fclaw2d_clawpatch_get_cp(neighbor_patches[0]);
ClawPatch *fine_cp = this_cp;
int iface_coarse = iface_neighbor;
int iface_fine = iface;
#if 0
transform_data.this_patch = neighbor_patches[0]; /* only one (coarse) neighbor */
transform_data.neighbor_patch = this_patch;
#endif
transform_data_finegrid.this_patch = neighbor_patches[0];
transform_data_finegrid.neighbor_patch = this_patch;
/* Redo the transformation */
if (neighbor_block_idx >= 0)
{
fclaw2d_patch_face_transformation (iface_coarse, iface_fine,
transform_data_finegrid.transform);
}
#if 0
transform_data_finegrid.this_patch = neighbor_patches[0];
transform_data_finegrid.neighbor_patch = this_patch;
#endif
int igrid = fine_grid_pos;
if (average_from_neighbor)
{
/* Average from 'this' grid (fine grid) to remote grid (coarse grid) */
coarse_cp->average_face_ghost(idir,iface_coarse,
p4est_refineFactor,refratio,
fine_cp,time_interp,
igrid, &transform_data_finegrid);
}
else if (interpolate_to_neighbor)
{
/* Interpolate from remote neighbor to 'this' patch (the finer grid */
coarse_cp->interpolate_face_ghost(idir,iface_coarse,
p4est_refineFactor,refratio,
fine_cp,time_interp,
igrid, &transform_data_finegrid);
}
}
} /* End of interior face */
} /* End of iface loop */
}
<commit_msg>More testing<commit_after>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
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.
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 COPYRIGHT HOLDER 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.
*/
/** \file fclaw2d_face_neighbors.cpp
* Average, coarsen and copy between grids at faces.
**/
#include <fclaw2d_global.h>
#include <fclaw2d_ghost_fill.h>
#include <fclaw2d_clawpatch.hpp>
#include <ClawPatch.H>
/* This is used to determine neighbor patch relative level (finer, coarser or samesize) */
enum
{
COARSER_GRID = -1,
SAMESIZE_GRID,
FINER_GRID
};
/* This function is a bit overkill, but I put it here so the logic in both
the corner fill and face fill are the same */
static
void get_face_type(fclaw2d_domain_t *domain,
int iface,
fclaw_bool intersects_phys_bdry[],
fclaw_bool intersects_block[],
fclaw_bool *is_block_face,
fclaw_bool *is_interior_face)
{
*is_block_face = intersects_block[iface];
*is_interior_face = !intersects_phys_bdry[iface];
}
static
void get_face_neighbors(fclaw2d_domain_t *domain,
int this_block_idx,
int this_patch_idx,
int iface,
int is_block_face,
int *neighbor_block_idx,
fclaw2d_patch_t* neighbor_patches[],
int **ref_flag_ptr,
int **fine_grid_pos_ptr,
int **iface_neighbor_ptr,
int ftransform[])
{
int rproc[p4est_refineFactor];
int rblockno;
int rpatchno[p4est_refineFactor];
int rfaceno;
int num_neighbors;
for(int ir = 0; ir < p4est_refineFactor; ir++)
{
neighbor_patches[ir] = NULL;
}
fclaw2d_patch_relation_t neighbor_type =
fclaw2d_patch_face_neighbors(domain,
this_block_idx,
this_patch_idx,
iface,
rproc,
&rblockno,
rpatchno,
&rfaceno);
/* ------------------------------
neighbor_type is one of :
FCLAW2D_PATCH_BOUNDARY, -- physical boundary
FCLAW2D_PATCH_HALFSIZE,
FCLAW2D_PATCH_SAMESIZE,
FCLAW2D_PATCH_DOUBLESIZE
------------------------------- */
if (neighbor_type == FCLAW2D_PATCH_BOUNDARY)
{
/* This case should be excluded by earlier checkes */
printf("get_face_neighbors (fclaw2d_face_neighbors.cpp) : No patch found\n");
exit(0);
}
else
{
*neighbor_block_idx = is_block_face ? rblockno : -1;
/* Get encoding of transforming a neighbor coordinate across a face */
fclaw2d_patch_face_transformation (iface, rfaceno, ftransform);
if (!is_block_face)
{
/* If we are within one patch this is a special case */
FCLAW_ASSERT (*neighbor_block_idx == -1);
ftransform[8] = 4;
}
if (neighbor_type == FCLAW2D_PATCH_SAMESIZE)
{
**ref_flag_ptr = 0;
*fine_grid_pos_ptr = NULL;
num_neighbors = 1;
}
else if (neighbor_type == FCLAW2D_PATCH_DOUBLESIZE)
{
**ref_flag_ptr = -1;
**fine_grid_pos_ptr = rproc[1]; /* Special storage for fine grid info */
num_neighbors = 1;
}
else if (neighbor_type == FCLAW2D_PATCH_HALFSIZE)
{
/* Patch has two neighbors */
**ref_flag_ptr = 1; /* patches are at one level finer */
*fine_grid_pos_ptr = NULL;
num_neighbors = p4est_refineFactor;
}
else
{
printf ("Illegal fclaw2d_patch_face_neighbors return value\n");
exit (1);
}
for(int ir = 0; ir < num_neighbors; ir++)
{
fclaw2d_patch_t *neighbor;
if (rproc[ir] == domain->mpirank)
{
/* neighbor patch is local */
fclaw2d_block_t *neighbor_block = &domain->blocks[rblockno];
neighbor = &neighbor_block->patches[rpatchno[ir]];
}
else
{
/* neighbor patch is on a remote processor */
neighbor = &domain->ghost_patches[rpatchno[ir]];
}
neighbor_patches[ir] = neighbor;
}
**iface_neighbor_ptr = iface;
fclaw2d_patch_face_swap(*iface_neighbor_ptr,&rfaceno);
}
}
/**
* \ingroup Averaging
**/
void cb_face_fill(fclaw2d_domain_t *domain,
fclaw2d_patch_t *this_patch,
int this_block_idx,
int this_patch_idx,
void *user)
{
fclaw2d_exchange_info_t *filltype = (fclaw2d_exchange_info_t*) user;
fclaw_bool time_interp = filltype->time_interp;
fclaw_bool is_coarse = filltype->grid_type == FCLAW2D_IS_COARSE;
fclaw_bool is_fine = filltype->grid_type == FCLAW2D_IS_FINE;
fclaw_bool read_parallel_patches = filltype->read_parallel_patches;
fclaw_bool copy_from_neighbor = filltype->exchange_type == FCLAW2D_COPY;
fclaw_bool average_from_neighbor = filltype->exchange_type == FCLAW2D_AVERAGE;
fclaw_bool interpolate_to_neighbor = filltype->exchange_type == FCLAW2D_INTERPOLATE;
const amr_options_t *gparms = get_domain_parms(domain);
const int refratio = gparms->refratio;
fclaw_bool intersects_phys_bdry[NumFaces];
fclaw_bool intersects_block[NumFaces];
fclaw2d_get_physical_bc(domain,this_block_idx,this_patch_idx,
intersects_phys_bdry);
fclaw2d_block_get_block_boundary(domain, this_patch, intersects_block);
/* Transform data needed at block boundaries */
fclaw2d_transform_data_t transform_data;
transform_data.mx = gparms->mx;
transform_data.my = gparms->my;
transform_data.based = 1; /* cell-centered data in this routine. */
transform_data.this_patch = this_patch;
transform_data.neighbor_patch = NULL; /* gets filled in below. */
fclaw2d_transform_data_t transform_data_finegrid;
transform_data_finegrid.mx = gparms->mx;
transform_data_finegrid.my = gparms->my;
transform_data_finegrid.based = 1; // cell-centered data in this routine.
ClawPatch *this_cp = fclaw2d_clawpatch_get_cp(this_patch);
for (int iface = 0; iface < NumFaces; iface++)
{
int idir = iface/2;
fclaw_bool is_block_face;
fclaw_bool is_interior_face;
get_face_type(domain,
iface,
intersects_phys_bdry,
intersects_block,
&is_block_face,
&is_interior_face);
if (is_interior_face) /* Not on a physical boundary */
{
/* Output arguments */
int neighbor_block_idx;
int neighbor_level; /* = -1, 0, 1 */
int *ref_flag_ptr = &neighbor_level;
int fine_grid_pos = -1;
int *fine_grid_pos_ptr = &fine_grid_pos;
/* Get the face neighbor relative to the neighbor's coordinate
orientation (this isn't used here) */
int iface_neighbor;
int *iface_neighbor_ptr = &iface_neighbor;
fclaw2d_patch_t* neighbor_patches[p4est_refineFactor];
/* Reset this in case it got set in a remote copy */
transform_data.this_patch = this_patch;
this_cp = fclaw2d_clawpatch_get_cp(this_patch);
/* transform_data.block_iface = iface; */
get_face_neighbors(domain,
this_block_idx,
this_patch_idx,
iface,
is_block_face,
&neighbor_block_idx,
neighbor_patches,
&ref_flag_ptr,
&fine_grid_pos_ptr,
&iface_neighbor_ptr,
transform_data.transform);
/* fclaw_bool block_boundary = (neighbor_block_idx >= 0); */
if (ref_flag_ptr == NULL)
{
/* We should never end up here */
printf("cb_face_fill (fclaw2d_face_neighbors.cpp) : no face found\n");
exit(0);
}
/* Parallel distribution keeps siblings on same processor */
fclaw_bool remote_neighbor;
remote_neighbor = fclaw2d_patch_is_ghost(neighbor_patches[0]);
if (is_coarse && ((read_parallel_patches && remote_neighbor) || !remote_neighbor))
{
if (neighbor_level == FINER_GRID)
{
for (int igrid = 0; igrid < p4est_refineFactor; igrid++)
{
ClawPatch *fine_neighbor_cp =
fclaw2d_clawpatch_get_cp(neighbor_patches[igrid]);
transform_data.neighbor_patch = neighbor_patches[igrid];
if (interpolate_to_neighbor && !remote_neighbor)
{
/* interpolate to igrid */
this_cp->interpolate_face_ghost(idir,iface,p4est_refineFactor,
refratio,fine_neighbor_cp,
time_interp,igrid,
&transform_data);
}
else if (average_from_neighbor)
{
/* average from igrid */
this_cp->average_face_ghost(idir,iface,p4est_refineFactor,
refratio,fine_neighbor_cp,
time_interp,igrid,
&transform_data);
}
}
}
else if (neighbor_level == SAMESIZE_GRID && copy_from_neighbor)
{
/* Copy to same size patch */
fclaw2d_patch_t *neighbor_patch = neighbor_patches[0];
ClawPatch *neighbor_cp = fclaw2d_clawpatch_get_cp(neighbor_patch);
transform_data.neighbor_patch = neighbor_patch;
this_cp->exchange_face_ghost(iface,neighbor_cp,&transform_data);
if (remote_neighbor)
{
/* We also need to copy _to_ the remote neighbor; switch contexts, but
use ClawPatches that are only in scope here, to avoid
conflicts with above uses of the same variables */
ClawPatch *neighbor_cp = this_cp;
ClawPatch *this_cp = fclaw2d_clawpatch_get_cp(neighbor_patch);
transform_data.this_patch = neighbor_patch;
transform_data.neighbor_patch = this_patch;
int this_iface = iface_neighbor;
if (neighbor_block_idx >= 0)
{
fclaw2d_patch_face_transformation (this_iface, iface,
transform_data.transform);
}
this_cp->exchange_face_ghost(this_iface,neighbor_cp,&transform_data);
}
}
}
else if (is_fine && neighbor_level == COARSER_GRID && remote_neighbor
&& read_parallel_patches)
{
/* fclaw2d_transform_data_t transform_data; */
transform_data.mx = gparms->mx;
transform_data.my = gparms->my;
transform_data.based = 1; // cell-centered data in this routine.
/* Swap 'this_patch' and the neighbor patch */
ClawPatch *coarse_cp = fclaw2d_clawpatch_get_cp(neighbor_patches[0]);
ClawPatch *fine_cp = this_cp;
int iface_coarse = iface_neighbor;
int iface_fine = iface;
/* Redo the transformation */
if (neighbor_block_idx >= 0)
{
fclaw2d_patch_face_transformation (iface_coarse, iface_fine,
transform_data.transform);
}
transform_data.this_patch = neighbor_patches[0];
transform_data.neighbor_patch = this_patch;
int igrid = fine_grid_pos;
if (average_from_neighbor)
{
/* Average from 'this' grid (fine grid) to remote grid (coarse grid) */
coarse_cp->average_face_ghost(idir,iface_coarse,
p4est_refineFactor,refratio,
fine_cp,time_interp,
igrid, &transform_data);
}
else if (interpolate_to_neighbor)
{
/* Interpolate from remote neighbor to 'this' patch (the finer grid */
coarse_cp->interpolate_face_ghost(idir,iface_coarse,
p4est_refineFactor,refratio,
fine_cp,time_interp,
igrid, &transform_data);
}
}
} /* End of interior face */
} /* End of iface loop */
}
<|endoftext|> |
<commit_before>
#include "Util.hpp"
// C++ headers
#include <cstdlib>
#include <sstream>
#include <stdexcept>
// C headers
#include <pwd.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
using namespace mksrc;
std::string util::GetHomeDirectory() {
const char *homestr = std::getenv("HOME");
if(homestr == nullptr) {
errno = 0;
struct passwd *password = getpwuid(geteuid());
if(errno != 0 || password == nullptr) {
std::stringstream fmt("Could not get Home directory: errno = ");
fmt << errno << " \"" << strerror(errno) << "\"";
throw std::runtime_error(fmt.str());
}
homestr = password->pw_dir;
}
if(homestr == nullptr) {
throw std::runtime_error("User has no Home directory");
}
return std::string(homestr);
}
<commit_msg>Added function to get environment string and convert to std::string<commit_after>
#include "Util.hpp"
// C++ headers
#include <cstdlib>
#include <sstream>
#include <stdexcept>
// C headers
#include <pwd.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
using namespace mksrc;
std::string util::GetHomeDirectory() {
const char *homestr = std::getenv("HOME");
if(homestr == nullptr) {
errno = 0;
struct passwd *password = getpwuid(geteuid());
if(errno != 0 || password == nullptr) {
std::stringstream fmt("Could not get Home directory: errno = ");
fmt << errno << " \"" << strerror(errno) << "\"";
throw std::runtime_error(fmt.str());
}
homestr = password->pw_dir;
}
if(homestr == nullptr) {
throw std::runtime_error("User has no Home directory");
}
return std::string(homestr);
}
std::string util::GetEnv(const char *name) {
const char *value = std::getenv(name);
return ((value == nullptr) ? std::string() : std::string(value));
}
<|endoftext|> |
<commit_before>/*
Copyright 2008-2009 Larry Gritz and the other authors and contributors.
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 software's owners 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 THE COPYRIGHT
OWNER 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.
(This is the Modified BSD License)
*/
#include <cstdlib>
#include "fits_pvt.h"
// Obligatory material to make this a recognizeable imageio plugin
extern "C" {
DLLEXPORT int fits_imageio_version = OPENIMAGEIO_PLUGIN_VERSION;
DLLEXPORT ImageInput *fits_input_imageio_create () {
return new FitsInput;
}
DLLEXPORT const char *fits_input_extensions[] = {
"fits", NULL
};
}
bool
FitsInput::open (const std::string &name, ImageSpec &spec)
{
// saving 'name' for later use
m_filename = name;
// checking if the file exists and can be opened in READ mode
m_fd = fopen (m_filename.c_str (), "rb");
if (!m_fd) {
error ("Could not open file \"%s\"", m_filename.c_str ());
return false;
}
// checking if the file is FITS file
char magic[6] = {0};
fread(magic, 1, 6, m_fd);
if(strncmp (magic, "SIMPLE", 6)) {
error ("%s isn't a FITS file", m_filename.c_str ());
close ();
return false;
}
// moving back to the start of the file
fseek (m_fd, 0, SEEK_SET);
subimage_search ();
set_spec_info ();
spec = m_spec;
return true;
};
bool
FitsInput::read_native_scanline (int y, int z, void *data)
{
// we return true just to support 0x0 images
if (!m_naxes)
return true;
std::vector<unsigned char> data_tmp (m_spec.scanline_bytes ());
long scanline_off = (m_spec.height - y) * m_spec.scanline_bytes ();
fseek (m_fd, scanline_off, SEEK_CUR);
fread (&data_tmp[0], 1, m_spec.scanline_bytes(), m_fd);
// in FITS image data is stored in big-endian so we have to switch to
// little-endian on little-endian machines
if (littleendian ()) {
if (m_spec.format == TypeDesc::USHORT)
swap_endian ((unsigned short*)&data_tmp[0],
data_tmp.size () / sizeof (unsigned short));
else if (m_spec.format == TypeDesc::UINT)
swap_endian ((unsigned int*)&data_tmp[0],
data_tmp.size () / sizeof (unsigned int));
else if (m_spec.format == TypeDesc::FLOAT)
swap_endian ((float*)&data_tmp[0],
data_tmp.size () / sizeof (float));
else if (m_spec.format == TypeDesc::DOUBLE)
swap_endian ((double*)&data_tmp[0],
data_tmp.size () / sizeof (double));
}
memcpy (data, &data_tmp[0], data_tmp.size ());
// after reading scanline we set file pointer to the start of image data
fsetpos (m_fd, &m_filepos);
return true;
};
bool
FitsInput::seek_subimage (int index, ImageSpec &newspec)
{
if (index < 0 || index >= (int)m_subimages.size ())
return false;
if (index == m_cur_subimage) {
newspec = m_spec;
return true;
}
// setting file pointer to the beginning of IMAGE extension
m_cur_subimage = index;
fseek (m_fd, m_subimages[m_cur_subimage].offset, SEEK_SET);
set_spec_info ();
newspec = m_spec;
return true;
}
void
FitsInput::set_spec_info ()
{
keys.clear ();
// FITS spec doesn't say anything about color space or
// number of channels, so we read all images as if they
// all were one-channel images
m_spec = ImageSpec(0, 0, 1, TypeDesc::UNKNOWN);
// reading info about current subimage
read_fits_header ();
// we don't deal with one dimension images
// it's some kind of spectral data
if (! m_spec.width || ! m_spec.height) {
m_spec.width = m_spec.full_width = 0;
m_spec.height = m_spec.full_height = 0;
}
// now we can get the current position in the file
// this is the start of the image data
// we will need it in the read_native_scanline method
fgetpos(m_fd, &m_filepos);
if (m_bitpix == 8)
m_spec.set_format (TypeDesc::UCHAR);
else if (m_bitpix == 16)
m_spec.set_format (TypeDesc::USHORT);
else if (m_bitpix == 32)
m_spec.set_format (TypeDesc::UINT);
else if (m_bitpix == -32)
m_spec.set_format (TypeDesc::FLOAT);
else if (m_bitpix == -64)
m_spec.set_format (TypeDesc::DOUBLE);
}
bool
FitsInput::close (void)
{
if (m_fd)
fclose (m_fd);
init ();
return true;
}
void
FitsInput::read_fits_header (void)
{
std::string fits_header (HEADER_SIZE, 0);
// we read whole header at once
fread (&fits_header[0], 1, HEADER_SIZE, m_fd);
for (int i = 0; i < CARDS_PER_HEADER; ++i) {
std::string card (CARD_SIZE, 0);
// reading card number i
memcpy (&card[0], &fits_header[i*CARD_SIZE], CARD_SIZE);
std::string keyname, value;
fits_pvt::unpack_card (card, keyname, value);
// END means that this is end of the FITS header
if (keyname == "END")
return;
if (keyname == "SIMPLE" || keyname == "XTENSION")
continue;
// setting up some important fields
// m_bitpix - format of the data (eg. bpp)
// m_naxes - number of axes
// width, height and depth of the image
if (keyname == "BITPIX") {
m_bitpix = atoi (&card[10]);
continue;
}
if (keyname == "NAXIS") {
m_naxes = atoi (&card[10]);
continue;
}
if (keyname == "NAXIS1") {
m_spec.width = atoi (&card[10]);
m_spec.full_width = m_spec.width;
continue;
}
if (keyname == "NAXIS2") {
m_spec.height = atoi (&card[10]);
m_spec.full_height = m_spec.height;
continue;
}
// ignoring other axis
if (keyname.substr (0,5) == "NAXIS") {
continue;
}
if (keyname == "ORIENTAT") {
add_to_spec ("Orientation", value);
continue;
}
if (keyname == "DATE") {
add_to_spec ("DateTime", convert_date (value));
continue;
}
// Some keywords can occure more than one time: COMMENT, HISTORY,
// HIERARCH. We can't store more than one key with the same name in
// ImageSpec. The workaround for this is to append a num to the keyname
// that occurs more then one time
if (keyname == "COMMENT" || keyname == "HISTORY"
|| keyname == "HIERARCH")
keyname += Strutil::format ("%d", keys[keyname]++);
add_to_spec (pystring::capitalize(keyname), value);
}
// if we didn't found END keyword in current header, we read next one
read_fits_header ();
}
void
FitsInput::add_to_spec (const std::string &keyname, const std::string &value)
{
// we don't add empty keys (or keys with empty values) to ImageSpec
if (!keyname.size() || !value.size ())
return;
// COMMENT, HISTORY, HIERARCH keywords we save AS-IS
if (keyname.substr (0, 7) == "Comment" || keyname.substr (0, 7) == "History"
||keyname.substr (0, 8) == "Hierarch" || keyname == "DateTime") {
m_spec.attribute (keyname, value);
return;
}
// converting string to float or integer
bool isNumSign = (value[0] == '+' || value[0] == '-' || value[0] == '.');
if (isdigit (value[0]) || isNumSign) {
float val = atof (value.c_str ());
if (val == (int)val)
m_spec.attribute (keyname, (int)val);
else
m_spec.attribute (keyname, val);
}
else
m_spec.attribute (keyname, value);
}
void
FitsInput::subimage_search ()
{
// saving position of the file, just for safe)
fpos_t fpos;
fgetpos (m_fd, &fpos);
// starting reading headers from the beginning of the file
fseek (m_fd, 0, SEEK_SET);
// we search for subimages by reading whole header and checking if it
// starts by "SIMPLE" keyword (primary header is always image header)
// or by "XTENSION= 'IMAGE '" (it is image extensions)
std::string hdu (HEADER_SIZE, 0);
size_t offset = 0;
while (fread (&hdu[0], 1, HEADER_SIZE, m_fd) == HEADER_SIZE) {
if (!strncmp (&hdu[0], "SIMPLE", 6) ||
!strncmp (&hdu[0], "XTENSION= 'IMAGE '", 20)) {
fits_pvt::Subimage newSub;
newSub.number = m_subimages.size ();
newSub.offset = offset;
m_subimages.push_back (newSub);
}
offset += HEADER_SIZE;
}
fsetpos (m_fd, &fpos);
}
std::string
FitsInput::convert_date (const std::string &date)
{
std::string ndate;
if (date[4] == '-') {
// YYYY-MM-DDThh:mm:ss convention is used since 1 January 2000
ndate = Strutil::format ("%04u:%02u:%02u", atoi(&date[0]),
atoi(&date[5]), atoi(&date[8]));
if (date.size () >= 11 && date[10] == 'T')
ndate += Strutil::format ("%02u:%02u:%02u", atoi (&date[11]),
atoi (&date[14]), atoi (&date[17]));
return ndate;
}
if (date[2] == '/') {
// DD/MM/YY convention was used before 1 January 2000
ndate = Strutil::format ("19%02u:%02u:%02u 00:00:00", atoi(&date[6]),
atoi(&date[3]), atoi(&date[0]));
return ndate;
}
// unrecognized format
return date;
}
<commit_msg>FITS fix: incorrectly-formatted date.<commit_after>/*
Copyright 2008-2009 Larry Gritz and the other authors and contributors.
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 software's owners 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 THE COPYRIGHT
OWNER 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.
(This is the Modified BSD License)
*/
#include <cstdlib>
#include "fits_pvt.h"
// Obligatory material to make this a recognizeable imageio plugin
extern "C" {
DLLEXPORT int fits_imageio_version = OPENIMAGEIO_PLUGIN_VERSION;
DLLEXPORT ImageInput *fits_input_imageio_create () {
return new FitsInput;
}
DLLEXPORT const char *fits_input_extensions[] = {
"fits", NULL
};
}
bool
FitsInput::open (const std::string &name, ImageSpec &spec)
{
// saving 'name' for later use
m_filename = name;
// checking if the file exists and can be opened in READ mode
m_fd = fopen (m_filename.c_str (), "rb");
if (!m_fd) {
error ("Could not open file \"%s\"", m_filename.c_str ());
return false;
}
// checking if the file is FITS file
char magic[6] = {0};
fread(magic, 1, 6, m_fd);
if(strncmp (magic, "SIMPLE", 6)) {
error ("%s isn't a FITS file", m_filename.c_str ());
close ();
return false;
}
// moving back to the start of the file
fseek (m_fd, 0, SEEK_SET);
subimage_search ();
set_spec_info ();
spec = m_spec;
return true;
};
bool
FitsInput::read_native_scanline (int y, int z, void *data)
{
// we return true just to support 0x0 images
if (!m_naxes)
return true;
std::vector<unsigned char> data_tmp (m_spec.scanline_bytes ());
long scanline_off = (m_spec.height - y) * m_spec.scanline_bytes ();
fseek (m_fd, scanline_off, SEEK_CUR);
fread (&data_tmp[0], 1, m_spec.scanline_bytes(), m_fd);
// in FITS image data is stored in big-endian so we have to switch to
// little-endian on little-endian machines
if (littleendian ()) {
if (m_spec.format == TypeDesc::USHORT)
swap_endian ((unsigned short*)&data_tmp[0],
data_tmp.size () / sizeof (unsigned short));
else if (m_spec.format == TypeDesc::UINT)
swap_endian ((unsigned int*)&data_tmp[0],
data_tmp.size () / sizeof (unsigned int));
else if (m_spec.format == TypeDesc::FLOAT)
swap_endian ((float*)&data_tmp[0],
data_tmp.size () / sizeof (float));
else if (m_spec.format == TypeDesc::DOUBLE)
swap_endian ((double*)&data_tmp[0],
data_tmp.size () / sizeof (double));
}
memcpy (data, &data_tmp[0], data_tmp.size ());
// after reading scanline we set file pointer to the start of image data
fsetpos (m_fd, &m_filepos);
return true;
};
bool
FitsInput::seek_subimage (int index, ImageSpec &newspec)
{
if (index < 0 || index >= (int)m_subimages.size ())
return false;
if (index == m_cur_subimage) {
newspec = m_spec;
return true;
}
// setting file pointer to the beginning of IMAGE extension
m_cur_subimage = index;
fseek (m_fd, m_subimages[m_cur_subimage].offset, SEEK_SET);
set_spec_info ();
newspec = m_spec;
return true;
}
void
FitsInput::set_spec_info ()
{
keys.clear ();
// FITS spec doesn't say anything about color space or
// number of channels, so we read all images as if they
// all were one-channel images
m_spec = ImageSpec(0, 0, 1, TypeDesc::UNKNOWN);
// reading info about current subimage
read_fits_header ();
// we don't deal with one dimension images
// it's some kind of spectral data
if (! m_spec.width || ! m_spec.height) {
m_spec.width = m_spec.full_width = 0;
m_spec.height = m_spec.full_height = 0;
}
// now we can get the current position in the file
// this is the start of the image data
// we will need it in the read_native_scanline method
fgetpos(m_fd, &m_filepos);
if (m_bitpix == 8)
m_spec.set_format (TypeDesc::UCHAR);
else if (m_bitpix == 16)
m_spec.set_format (TypeDesc::USHORT);
else if (m_bitpix == 32)
m_spec.set_format (TypeDesc::UINT);
else if (m_bitpix == -32)
m_spec.set_format (TypeDesc::FLOAT);
else if (m_bitpix == -64)
m_spec.set_format (TypeDesc::DOUBLE);
}
bool
FitsInput::close (void)
{
if (m_fd)
fclose (m_fd);
init ();
return true;
}
void
FitsInput::read_fits_header (void)
{
std::string fits_header (HEADER_SIZE, 0);
// we read whole header at once
fread (&fits_header[0], 1, HEADER_SIZE, m_fd);
for (int i = 0; i < CARDS_PER_HEADER; ++i) {
std::string card (CARD_SIZE, 0);
// reading card number i
memcpy (&card[0], &fits_header[i*CARD_SIZE], CARD_SIZE);
std::string keyname, value;
fits_pvt::unpack_card (card, keyname, value);
// END means that this is end of the FITS header
if (keyname == "END")
return;
if (keyname == "SIMPLE" || keyname == "XTENSION")
continue;
// setting up some important fields
// m_bitpix - format of the data (eg. bpp)
// m_naxes - number of axes
// width, height and depth of the image
if (keyname == "BITPIX") {
m_bitpix = atoi (&card[10]);
continue;
}
if (keyname == "NAXIS") {
m_naxes = atoi (&card[10]);
continue;
}
if (keyname == "NAXIS1") {
m_spec.width = atoi (&card[10]);
m_spec.full_width = m_spec.width;
continue;
}
if (keyname == "NAXIS2") {
m_spec.height = atoi (&card[10]);
m_spec.full_height = m_spec.height;
continue;
}
// ignoring other axis
if (keyname.substr (0,5) == "NAXIS") {
continue;
}
if (keyname == "ORIENTAT") {
add_to_spec ("Orientation", value);
continue;
}
if (keyname == "DATE") {
add_to_spec ("DateTime", convert_date (value));
continue;
}
// Some keywords can occure more than one time: COMMENT, HISTORY,
// HIERARCH. We can't store more than one key with the same name in
// ImageSpec. The workaround for this is to append a num to the keyname
// that occurs more then one time
if (keyname == "COMMENT" || keyname == "HISTORY"
|| keyname == "HIERARCH")
keyname += Strutil::format ("%d", keys[keyname]++);
add_to_spec (pystring::capitalize(keyname), value);
}
// if we didn't found END keyword in current header, we read next one
read_fits_header ();
}
void
FitsInput::add_to_spec (const std::string &keyname, const std::string &value)
{
// we don't add empty keys (or keys with empty values) to ImageSpec
if (!keyname.size() || !value.size ())
return;
// COMMENT, HISTORY, HIERARCH keywords we save AS-IS
if (keyname.substr (0, 7) == "Comment" || keyname.substr (0, 7) == "History"
||keyname.substr (0, 8) == "Hierarch" || keyname == "DateTime") {
m_spec.attribute (keyname, value);
return;
}
// converting string to float or integer
bool isNumSign = (value[0] == '+' || value[0] == '-' || value[0] == '.');
if (isdigit (value[0]) || isNumSign) {
float val = atof (value.c_str ());
if (val == (int)val)
m_spec.attribute (keyname, (int)val);
else
m_spec.attribute (keyname, val);
}
else
m_spec.attribute (keyname, value);
}
void
FitsInput::subimage_search ()
{
// saving position of the file, just for safe)
fpos_t fpos;
fgetpos (m_fd, &fpos);
// starting reading headers from the beginning of the file
fseek (m_fd, 0, SEEK_SET);
// we search for subimages by reading whole header and checking if it
// starts by "SIMPLE" keyword (primary header is always image header)
// or by "XTENSION= 'IMAGE '" (it is image extensions)
std::string hdu (HEADER_SIZE, 0);
size_t offset = 0;
while (fread (&hdu[0], 1, HEADER_SIZE, m_fd) == HEADER_SIZE) {
if (!strncmp (&hdu[0], "SIMPLE", 6) ||
!strncmp (&hdu[0], "XTENSION= 'IMAGE '", 20)) {
fits_pvt::Subimage newSub;
newSub.number = m_subimages.size ();
newSub.offset = offset;
m_subimages.push_back (newSub);
}
offset += HEADER_SIZE;
}
fsetpos (m_fd, &fpos);
}
std::string
FitsInput::convert_date (const std::string &date)
{
std::string ndate;
if (date[4] == '-') {
// YYYY-MM-DDThh:mm:ss convention is used since 1 January 2000
ndate = Strutil::format ("%04u:%02u:%02u", atoi(&date[0]),
atoi(&date[5]), atoi(&date[8]));
if (date.size () >= 11 && date[10] == 'T')
ndate += Strutil::format (" %02u:%02u:%02u", atoi (&date[11]),
atoi (&date[14]), atoi (&date[17]));
return ndate;
}
if (date[2] == '/') {
// DD/MM/YY convention was used before 1 January 2000
ndate = Strutil::format ("19%02u:%02u:%02u 00:00:00", atoi(&date[6]),
atoi(&date[3]), atoi(&date[0]));
return ndate;
}
// unrecognized format
return date;
}
<|endoftext|> |
<commit_before>/******************************************************************************
nomlib - C++11 cross-platform game engine
Copyright (c) 2013, 2014 Jeffrey Carpenter <i8degrees@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. 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 COPYRIGHT OWNER 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 "nomlib/graphics/sprite/Sprite.hpp"
namespace nom {
Sprite::Sprite ( void ) : state_ ( 0 ), scale_factor ( 1 )
{
NOM_LOG_TRACE ( NOM );
}
Sprite::~Sprite ( void )
{
NOM_LOG_TRACE ( NOM );
}
Sprite::Sprite ( int32 width, int32 height ) :
Transformable { Coords ( 0, 0, width, height ) }, state_ ( 0 ),
scale_factor ( 1 )
{
NOM_LOG_TRACE ( NOM );
}
Sprite& Sprite::operator = ( const Sprite& other )
{
this->sprite_ = other.sprite_;
this->set_position ( other.position().x, other.position().y );
this->set_state ( other.state() );
this->scale_factor = other.scale_factor;
return *this;
}
SDL_TEXTURE::RawPtr Sprite::texture ( void ) const
{
return this->sprite_.texture();
}
const Point2i Sprite::size ( void ) const
{
return Point2i ( this->sprite_.width(), this->sprite_.height() );
}
const Point2i Sprite::position ( void ) const
{
// FIXME
return Point2i ( this->position_.x, this->position_.y );
}
uint32 Sprite::state ( void ) const
{
return this->state_;
}
void Sprite::set_state ( uint32 state )
{
this->state_ = state;
}
bool Sprite::load (
const std::string& filename,
bool use_cache,
enum Texture::Access type
)
{
this->sprite_.load ( filename, use_cache, type );
if ( this->sprite_.valid() == false )
{
NOM_LOG_ERR ( NOM, "Could not load sprite image file: " + filename );
return false;
}
this->setSize ( this->sprite_.width(), this->sprite_.height() );
return true;
}
void Sprite::update ( void )
{
// FIXME
this->sprite_.set_position ( Point2i ( this->position_.x, this->position_.y ) );
}
void Sprite::draw ( RenderTarget target ) const
{
NOM_ASSERT ( this->sprite_.valid() );
this->sprite_.draw ( target.renderer() );
}
void Sprite::draw ( RenderTarget target, const double degrees ) const
{
this->sprite_.draw ( target.renderer(), degrees );
}
bool Sprite::resize ( enum Texture::ResizeAlgorithm scaling_algorithm )
{
if ( this->sprite_.valid() == false )
{
NOM_LOG_ERR ( NOM, "Video surface is invalid." );
return false;
}
if ( this->sprite_.resize ( scaling_algorithm ) == false )
{
NOM_LOG_ERR ( NOM, "Failed to resize the video surface." );
return false;
}
this->scale_factor = this->sprite_.scale_factor ( scaling_algorithm );
this->update();
return true;
}
} // namespace nom
<commit_msg>Sprite: Clean up err handling a bit inside load method<commit_after>/******************************************************************************
nomlib - C++11 cross-platform game engine
Copyright (c) 2013, 2014 Jeffrey Carpenter <i8degrees@gmail.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. 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 COPYRIGHT OWNER 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 "nomlib/graphics/sprite/Sprite.hpp"
namespace nom {
Sprite::Sprite ( void ) : state_ ( 0 ), scale_factor ( 1 )
{
NOM_LOG_TRACE ( NOM );
}
Sprite::~Sprite ( void )
{
NOM_LOG_TRACE ( NOM );
}
Sprite::Sprite ( int32 width, int32 height ) :
Transformable { Coords ( 0, 0, width, height ) }, state_ ( 0 ),
scale_factor ( 1 )
{
NOM_LOG_TRACE ( NOM );
}
Sprite& Sprite::operator = ( const Sprite& other )
{
this->sprite_ = other.sprite_;
this->set_position ( other.position().x, other.position().y );
this->set_state ( other.state() );
this->scale_factor = other.scale_factor;
return *this;
}
SDL_TEXTURE::RawPtr Sprite::texture ( void ) const
{
return this->sprite_.texture();
}
const Point2i Sprite::size ( void ) const
{
return Point2i ( this->sprite_.width(), this->sprite_.height() );
}
const Point2i Sprite::position ( void ) const
{
// FIXME
return Point2i ( this->position_.x, this->position_.y );
}
uint32 Sprite::state ( void ) const
{
return this->state_;
}
void Sprite::set_state ( uint32 state )
{
this->state_ = state;
}
bool Sprite::load (
const std::string& filename,
bool use_cache,
enum Texture::Access type
)
{
if ( this->sprite_.load ( filename, use_cache, type ) == false )
{
NOM_LOG_ERR ( NOM, "Could not load sprite image file: " + filename );
return false;
}
this->setSize ( this->sprite_.width(), this->sprite_.height() );
return true;
}
void Sprite::update ( void )
{
// FIXME
this->sprite_.set_position ( Point2i ( this->position_.x, this->position_.y ) );
}
void Sprite::draw ( RenderTarget target ) const
{
NOM_ASSERT ( this->sprite_.valid() );
this->sprite_.draw ( target.renderer() );
}
void Sprite::draw ( RenderTarget target, const double degrees ) const
{
this->sprite_.draw ( target.renderer(), degrees );
}
bool Sprite::resize ( enum Texture::ResizeAlgorithm scaling_algorithm )
{
if ( this->sprite_.valid() == false )
{
NOM_LOG_ERR ( NOM, "Video surface is invalid." );
return false;
}
if ( this->sprite_.resize ( scaling_algorithm ) == false )
{
NOM_LOG_ERR ( NOM, "Failed to resize the video surface." );
return false;
}
this->scale_factor = this->sprite_.scale_factor ( scaling_algorithm );
this->update();
return true;
}
} // namespace nom
<|endoftext|> |
<commit_before>// Copyright 2008-present Contributors to the OpenImageIO project.
// SPDX-License-Identifier: BSD-3-Clause
// https://github.com/OpenImageIO/oiio/blob/master/LICENSE.md
#include <OpenImageIO/imageio.h>
#include <OpenImageIO/tiffutils.h>
#include <libheif/heif_cxx.h>
// This plugin utilises libheif:
// https://github.com/strukturag/libheif
//
// General information about HEIF/HEIC:
//
// Sources of sample images:
// https://github.com/nokiatech/heif/tree/gh-pages/content
OIIO_PLUGIN_NAMESPACE_BEGIN
class HeifInput final : public ImageInput {
public:
HeifInput() {}
virtual ~HeifInput() { close(); }
virtual const char* format_name(void) const override { return "heif"; }
virtual int supports(string_view feature) const override
{
return feature == "exif";
}
// virtual bool valid_file(const std::string& filename) const override;
virtual bool open(const std::string& name, ImageSpec& newspec) override;
virtual bool open(const std::string& name, ImageSpec& newspec,
const ImageSpec& config) override;
virtual bool close() override;
virtual bool seek_subimage(int subimage, int miplevel) override;
virtual bool read_native_scanline(int subimage, int miplevel, int y, int z,
void* data) override;
private:
std::string m_filename;
int m_subimage = -1;
int m_num_subimages = 0;
int m_has_alpha = false;
std::unique_ptr<heif::Context> m_ctx;
heif_item_id m_primary_id; // id of primary image
std::vector<heif_item_id> m_item_ids; // ids of all other images
heif::ImageHandle m_ihandle;
heif::Image m_himage;
};
// Export version number and create function symbols
OIIO_PLUGIN_EXPORTS_BEGIN
OIIO_EXPORT int heif_imageio_version = OIIO_PLUGIN_VERSION;
OIIO_EXPORT const char*
heif_imageio_library_version()
{
return "libheif " LIBHEIF_VERSION;
}
OIIO_EXPORT ImageInput*
heif_input_imageio_create()
{
return new HeifInput;
}
OIIO_EXPORT const char* heif_input_extensions[] = { "heic", "heif", "heics",
nullptr };
OIIO_PLUGIN_EXPORTS_END
#if 0
bool
HeifInput::valid_file(const std::string& filename) const
{
const size_t magic_size = 12;
uint8_t magic[magic_size];
FILE *file = Filesystem::fopen(filename, "rb");
fread (magic, magic_size, 1, file);
fclose (file);
heif_filetype_result filetype_check = heif_check_filetype(magic,12);
return filetype_check != heif_filetype_no
&& filetype_check != heif_filetype_yes_unsupported
// This is what the libheif example said to do, but I can't find
// the filetype constants declared anywhere. Are they obsolete?
}
#endif
bool
HeifInput::open(const std::string& name, ImageSpec& newspec)
{
// If user doesn't want to provide any config, just use an empty spec.
ImageSpec config;
return open(name, newspec, config);
}
bool
HeifInput::open(const std::string& name, ImageSpec& newspec,
const ImageSpec& /*config*/)
{
m_filename = name;
m_subimage = -1;
m_ctx.reset(new heif::Context);
m_himage = heif::Image();
m_ihandle = heif::ImageHandle();
try {
m_ctx->read_from_file(name);
// FIXME: should someday be read_from_reader to give full flexibility
m_item_ids = m_ctx->get_list_of_top_level_image_IDs();
m_primary_id = m_ctx->get_primary_image_ID();
for (size_t i = 0; i < m_item_ids.size(); ++i)
if (m_item_ids[i] == m_primary_id) {
m_item_ids.erase(m_item_ids.begin() + i);
break;
}
// std::cout << " primary id: " << m_primary_id << "\n";
// std::cout << " item ids: " << Strutil::join(m_item_ids, ", ") << "\n";
m_num_subimages = 1 + int(m_item_ids.size());
} catch (const heif::Error& err) {
std::string e = err.get_message();
errorf("%s", e.empty() ? "unknown exception" : e.c_str());
return false;
} catch (const std::exception& err) {
std::string e = err.what();
errorf("%s", e.empty() ? "unknown exception" : e.c_str());
return false;
}
bool ok = seek_subimage(0, 0);
newspec = spec();
return ok;
}
bool
HeifInput::close()
{
m_himage = heif::Image();
m_ihandle = heif::ImageHandle();
m_ctx.reset();
m_subimage = -1;
m_num_subimages = 0;
return true;
}
bool
HeifInput::seek_subimage(int subimage, int miplevel)
{
if (miplevel != 0)
return false;
if (subimage == m_subimage) {
return true; // already there
}
if (subimage >= m_num_subimages) {
return false;
}
try {
auto id = (subimage == 0) ? m_primary_id : m_item_ids[subimage - 1];
m_ihandle = m_ctx->get_image_handle(id);
m_has_alpha = m_ihandle.has_alpha_channel();
auto chroma = m_has_alpha ? heif_chroma_interleaved_RGBA
: heif_chroma_interleaved_RGB;
m_himage = m_ihandle.decode_image(heif_colorspace_RGB, chroma);
} catch (const heif::Error& err) {
std::string e = err.get_message();
errorf("%s", e.empty() ? "unknown exception" : e.c_str());
return false;
} catch (const std::exception& err) {
std::string e = err.what();
errorf("%s", e.empty() ? "unknown exception" : e.c_str());
return false;
}
int bits = m_himage.get_bits_per_pixel(heif_channel_interleaved);
m_spec = ImageSpec(m_ihandle.get_width(), m_ihandle.get_height(), bits / 8,
TypeUInt8);
m_spec.attribute("oiio:ColorSpace", "sRGB");
auto meta_ids = m_ihandle.get_list_of_metadata_block_IDs();
// std::cout << "nmeta? " << meta_ids.size() << "\n";
for (auto m : meta_ids) {
std::vector<uint8_t> metacontents;
try {
metacontents = m_ihandle.get_metadata(m);
} catch (const heif::Error& err) {
if (err.get_code() == heif_error_Usage_error
&& err.get_subcode() == heif_suberror_Null_pointer_argument) {
// a bug in heif_cxx.h means a 0 byte metadata causes a null
// ptr error code, which we ignore
continue;
}
}
if (Strutil::iequals(m_ihandle.get_metadata_type(m), "Exif")
&& metacontents.size() >= 10) {
cspan<uint8_t> s(&metacontents[10], metacontents.size() - 10);
decode_exif(s, m_spec);
} else if (0 // For now, skip this, I haven't seen anything useful
&& Strutil::iequals(m_ihandle.get_metadata_type(m), "mime")
&& Strutil::iequals(m_ihandle.get_metadata_content_type(m),
"application/rdf+xml")) {
decode_xmp(metacontents, m_spec);
} else {
#ifdef DEBUG
std::cout << "Don't know how to decode meta " << m
<< " type=" << m_ihandle.get_metadata_type(m)
<< " contenttype='"
<< m_ihandle.get_metadata_content_type(m) << "'\n";
std::cout << "---\n"
<< string_view((const char*)&metacontents[0],
metacontents.size())
<< "\n---\n";
#endif
}
}
// Erase the orientation metadata becaue libheif appears to be doing
// the rotation-to-canonical-direction for us.
m_spec.erase_attribute("Orientation");
m_subimage = subimage;
return true;
}
bool
HeifInput::read_native_scanline(int subimage, int miplevel, int y, int /*z*/,
void* data)
{
lock_guard lock(*this);
if (!seek_subimage(subimage, miplevel))
return false;
if (y < 0 || y >= m_spec.height) // out of range scanline
return false;
int ystride = 0;
const uint8_t* hdata = m_himage.get_plane(heif_channel_interleaved,
&ystride);
if (!hdata) {
errorf("Unknown read error");
return false;
}
hdata += (y - m_spec.y) * ystride;
memcpy(data, hdata, m_spec.width * m_spec.pixel_bytes());
return true;
}
OIIO_PLUGIN_NAMESPACE_END
<commit_msg>Re-add the HeifInput valid_file check (#2810)<commit_after>// Copyright 2008-present Contributors to the OpenImageIO project.
// SPDX-License-Identifier: BSD-3-Clause
// https://github.com/OpenImageIO/oiio/blob/master/LICENSE.md
#include <OpenImageIO/filesystem.h>
#include <OpenImageIO/imageio.h>
#include <OpenImageIO/tiffutils.h>
#include <libheif/heif_cxx.h>
// This plugin utilises libheif:
// https://github.com/strukturag/libheif
//
// General information about HEIF/HEIC:
//
// Sources of sample images:
// https://github.com/nokiatech/heif/tree/gh-pages/content
OIIO_PLUGIN_NAMESPACE_BEGIN
class HeifInput final : public ImageInput {
public:
HeifInput() {}
virtual ~HeifInput() { close(); }
virtual const char* format_name(void) const override { return "heif"; }
virtual int supports(string_view feature) const override
{
return feature == "exif";
}
virtual bool valid_file(const std::string& filename) const override;
virtual bool open(const std::string& name, ImageSpec& newspec) override;
virtual bool open(const std::string& name, ImageSpec& newspec,
const ImageSpec& config) override;
virtual bool close() override;
virtual bool seek_subimage(int subimage, int miplevel) override;
virtual bool read_native_scanline(int subimage, int miplevel, int y, int z,
void* data) override;
private:
std::string m_filename;
int m_subimage = -1;
int m_num_subimages = 0;
int m_has_alpha = false;
std::unique_ptr<heif::Context> m_ctx;
heif_item_id m_primary_id; // id of primary image
std::vector<heif_item_id> m_item_ids; // ids of all other images
heif::ImageHandle m_ihandle;
heif::Image m_himage;
};
// Export version number and create function symbols
OIIO_PLUGIN_EXPORTS_BEGIN
OIIO_EXPORT int heif_imageio_version = OIIO_PLUGIN_VERSION;
OIIO_EXPORT const char*
heif_imageio_library_version()
{
return "libheif " LIBHEIF_VERSION;
}
OIIO_EXPORT ImageInput*
heif_input_imageio_create()
{
return new HeifInput;
}
OIIO_EXPORT const char* heif_input_extensions[] = { "heic", "heif", "heics",
nullptr };
OIIO_PLUGIN_EXPORTS_END
bool
HeifInput::valid_file(const std::string& filename) const
{
uint8_t magic[12];
if (Filesystem::read_bytes(filename, magic, sizeof(magic)) != sizeof(magic))
return false;
heif_filetype_result filetype_check = heif_check_filetype(magic,
sizeof(magic));
return filetype_check != heif_filetype_no
&& filetype_check != heif_filetype_yes_unsupported;
}
bool
HeifInput::open(const std::string& name, ImageSpec& newspec)
{
// If user doesn't want to provide any config, just use an empty spec.
ImageSpec config;
return open(name, newspec, config);
}
bool
HeifInput::open(const std::string& name, ImageSpec& newspec,
const ImageSpec& /*config*/)
{
m_filename = name;
m_subimage = -1;
m_ctx.reset(new heif::Context);
m_himage = heif::Image();
m_ihandle = heif::ImageHandle();
try {
m_ctx->read_from_file(name);
// FIXME: should someday be read_from_reader to give full flexibility
m_item_ids = m_ctx->get_list_of_top_level_image_IDs();
m_primary_id = m_ctx->get_primary_image_ID();
for (size_t i = 0; i < m_item_ids.size(); ++i)
if (m_item_ids[i] == m_primary_id) {
m_item_ids.erase(m_item_ids.begin() + i);
break;
}
// std::cout << " primary id: " << m_primary_id << "\n";
// std::cout << " item ids: " << Strutil::join(m_item_ids, ", ") << "\n";
m_num_subimages = 1 + int(m_item_ids.size());
} catch (const heif::Error& err) {
std::string e = err.get_message();
errorf("%s", e.empty() ? "unknown exception" : e.c_str());
return false;
} catch (const std::exception& err) {
std::string e = err.what();
errorf("%s", e.empty() ? "unknown exception" : e.c_str());
return false;
}
bool ok = seek_subimage(0, 0);
newspec = spec();
return ok;
}
bool
HeifInput::close()
{
m_himage = heif::Image();
m_ihandle = heif::ImageHandle();
m_ctx.reset();
m_subimage = -1;
m_num_subimages = 0;
return true;
}
bool
HeifInput::seek_subimage(int subimage, int miplevel)
{
if (miplevel != 0)
return false;
if (subimage == m_subimage) {
return true; // already there
}
if (subimage >= m_num_subimages) {
return false;
}
try {
auto id = (subimage == 0) ? m_primary_id : m_item_ids[subimage - 1];
m_ihandle = m_ctx->get_image_handle(id);
m_has_alpha = m_ihandle.has_alpha_channel();
auto chroma = m_has_alpha ? heif_chroma_interleaved_RGBA
: heif_chroma_interleaved_RGB;
m_himage = m_ihandle.decode_image(heif_colorspace_RGB, chroma);
} catch (const heif::Error& err) {
std::string e = err.get_message();
errorf("%s", e.empty() ? "unknown exception" : e.c_str());
return false;
} catch (const std::exception& err) {
std::string e = err.what();
errorf("%s", e.empty() ? "unknown exception" : e.c_str());
return false;
}
int bits = m_himage.get_bits_per_pixel(heif_channel_interleaved);
m_spec = ImageSpec(m_ihandle.get_width(), m_ihandle.get_height(), bits / 8,
TypeUInt8);
m_spec.attribute("oiio:ColorSpace", "sRGB");
auto meta_ids = m_ihandle.get_list_of_metadata_block_IDs();
// std::cout << "nmeta? " << meta_ids.size() << "\n";
for (auto m : meta_ids) {
std::vector<uint8_t> metacontents;
try {
metacontents = m_ihandle.get_metadata(m);
} catch (const heif::Error& err) {
if (err.get_code() == heif_error_Usage_error
&& err.get_subcode() == heif_suberror_Null_pointer_argument) {
// a bug in heif_cxx.h means a 0 byte metadata causes a null
// ptr error code, which we ignore
continue;
}
}
if (Strutil::iequals(m_ihandle.get_metadata_type(m), "Exif")
&& metacontents.size() >= 10) {
cspan<uint8_t> s(&metacontents[10], metacontents.size() - 10);
decode_exif(s, m_spec);
} else if (0 // For now, skip this, I haven't seen anything useful
&& Strutil::iequals(m_ihandle.get_metadata_type(m), "mime")
&& Strutil::iequals(m_ihandle.get_metadata_content_type(m),
"application/rdf+xml")) {
decode_xmp(metacontents, m_spec);
} else {
#ifdef DEBUG
std::cout << "Don't know how to decode meta " << m
<< " type=" << m_ihandle.get_metadata_type(m)
<< " contenttype='"
<< m_ihandle.get_metadata_content_type(m) << "'\n";
std::cout << "---\n"
<< string_view((const char*)&metacontents[0],
metacontents.size())
<< "\n---\n";
#endif
}
}
// Erase the orientation metadata becaue libheif appears to be doing
// the rotation-to-canonical-direction for us.
m_spec.erase_attribute("Orientation");
m_subimage = subimage;
return true;
}
bool
HeifInput::read_native_scanline(int subimage, int miplevel, int y, int /*z*/,
void* data)
{
lock_guard lock(*this);
if (!seek_subimage(subimage, miplevel))
return false;
if (y < 0 || y >= m_spec.height) // out of range scanline
return false;
int ystride = 0;
const uint8_t* hdata = m_himage.get_plane(heif_channel_interleaved,
&ystride);
if (!hdata) {
errorf("Unknown read error");
return false;
}
hdata += (y - m_spec.y) * ystride;
memcpy(data, hdata, m_spec.width * m_spec.pixel_bytes());
return true;
}
OIIO_PLUGIN_NAMESPACE_END
<|endoftext|> |
<commit_before>#include "scan/Scan.h"
#include "scan/ScanIO.h"
#include "diffusion/Diffusion.h"
#include "settings.h"
int main(int argc, char* argv[]) {
Settings settings(argc, argv);
Scan scan = ScanIO::read_from(settings.inputScan);
scan.transform()->scale_values(0, 255);
const int& nx = scan.data()->get_nx();
const int& ny = scan.data()->get_ny();
const int& nz = scan.data()->get_nz();
ImageData imageData;
imageData.set_values(scan.data()->get_values(), nx, ny, nz, 0, 0, 0);
Image image(imageData);
Diffusion diffusion(image, settings.diffusionSettings);
image = diffusion.get_result();
image.data().set_boundary_sizes(0, 0, 0);
scan.data()->set_data(image.data().values);
ScanIO::write_to(settings.outputScan, scan);
}
<commit_msg>switched to new image classes<commit_after>#include "image/Image.h"
#include "settings.h"
int main(int argc, char* argv[]) {
Settings settings(argc, argv);
Image scan;
scan.read().from(settings.inputScan);
scan.values().scale(0, 255);
const double stepSize = 0.125;
scan.filter().diffusion(
settings.diffusionSettings.timeSteps,
stepSize,
settings.diffusionSettings.contrastLambda,
settings.diffusionSettings.integrationRho,
settings.diffusionSettings.presmoothSigma
);
scan.write().to(settings.outputScan);
return 0;
}
<|endoftext|> |
<commit_before>//
// main.cpp
// antlr4-cpp-demo
//
// Created by Mike Lischke on 13.03.16.
//
#include <iostream>
#include "ANTLRInputStream.h"
#include "CommonTokenStream.h"
#include "TLexer.h"
#include "TParser.h"
#include "Strings.h"
using namespace antlrcpptest;
using namespace org::antlr::v4::runtime;
int main(int argc, const char * argv[]) {
ANTLRInputStream input(L"x * y + z;");
TLexer lexer(&input);
CommonTokenStream tokens(&lexer);
TParser parser(&tokens);
Ref<tree::ParseTree> tree = parser.main();
std::cout << antlrcpp::ws2s(tree->toStringTree(&parser)) << std::endl;
return 0;
}
<commit_msg>A bit more complex expression in demo parser.<commit_after>//
// main.cpp
// antlr4-cpp-demo
//
// Created by Mike Lischke on 13.03.16.
//
#include <iostream>
#include "ANTLRInputStream.h"
#include "CommonTokenStream.h"
#include "TLexer.h"
#include "TParser.h"
#include "Strings.h"
using namespace antlrcpptest;
using namespace org::antlr::v4::runtime;
int main(int argc, const char * argv[]) {
ANTLRInputStream input(L"(((x))) * y + z; a + (x * (y ? 0 : 1) + z);");
TLexer lexer(&input);
CommonTokenStream tokens(&lexer);
TParser parser(&tokens);
Ref<tree::ParseTree> tree = parser.main();
std::cout << antlrcpp::ws2s(tree->toStringTree(&parser)) << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>#include "Halide.h"
using namespace Halide;
Expr lerp(Expr a, Expr b, Expr alpha) {
return (1.0f - alpha)*a + alpha*b;
}
int main(int argc, char **argv) {
if (argc < 2) {
printf("Spatial sigma is a compile-time parameter, please provide it as an argument.\n"
"(llvm's ptx backend doesn't handle integer mods by non-consts yet)\n");
return 0;
}
UniformImage input(Float(32), 2);
Uniform<float> r_sigma;
int s_sigma = atoi(argv[1]);
Var x, y, z, c;
// Add a boundary condition
Func clamped;
clamped(x, y) = input(clamp(x, 0, input.width()-1),
clamp(y, 0, input.height()-1));
// Construct the bilateral grid
RDom r(0, s_sigma, 0, s_sigma);
Expr val = clamped(x * s_sigma + r.x - s_sigma/2, y * s_sigma + r.y - s_sigma/2);
val = clamp(val, 0.0f, 1.0f);
Expr zi = cast<int>(val * (1.0f/r_sigma) + 0.5f);
Func grid;
grid(x, y, zi, c) += select(c == 0, val, 1.0f);
// Blur the grid using a five-tap filter
Func blurx, blury, blurz;
blurx(x, y, z) = grid(x-2, y, z) + grid(x-1, y, z)*4 + grid(x, y, z)*6 + grid(x+1, y, z)*4 + grid(x+2, y, z);
blury(x, y, z) = blurx(x, y-2, z) + blurx(x, y-1, z)*4 + blurx(x, y, z)*6 + blurx(x, y+1, z)*4 + blurx(x, y+2, z);
blurz(x, y, z) = blury(x, y, z-2) + blury(x, y, z-1)*4 + blury(x, y, z)*6 + blury(x, y, z+1)*4 + blury(x, y, z+2);
// Take trilinear samples to compute the output
val = clamp(clamped(x, y), 0.0f, 1.0f);
Expr zv = val * (1.0f/r_sigma);
zi = cast<int>(zv);
Expr zf = zv - zi;
Expr xf = cast<float>(x % s_sigma) / s_sigma;
Expr yf = cast<float>(y % s_sigma) / s_sigma;
Expr xi = x/s_sigma;
Expr yi = y/s_sigma;
Func interpolated;
interpolated(x, y) =
lerp(lerp(lerp(blurz(xi, yi, zi), blurz(xi+1, yi, zi), xf),
lerp(blurz(xi, yi+1, zi), blurz(xi+1, yi+1, zi), xf), yf),
lerp(lerp(blurz(xi, yi, zi+1), blurz(xi+1, yi, zi+1), xf),
lerp(blurz(xi, yi+1, zi+1), blurz(xi+1, yi+1, zi+1), xf), yf), zf);
// Normalize
Func smoothed;
smoothed(x, y) = interpolated(x, y, 0)/interpolated(x, y, 1);
#ifndef USE_GPU
// Best schedule for CPU
printf("Compiling for CPU\n");
grid.root().parallel(z);
grid.update().transpose(y, c).transpose(x, c).parallel(y);
blurx.root().parallel(z).vectorize(x, 4);
blury.root().parallel(z).vectorize(x, 4);
blurz.root().parallel(z).vectorize(x, 4);
smoothed.root().parallel(y).vectorize(x, 4);
#else
printf("Compiling for GPU");
Var gridz = grid.arg(2);
grid.transpose(y, gridz).transpose(x, gridz).transpose(y, c).transpose(x, c)
.root().cudaTile(x, y, 16, 16);
grid.update().transpose(y, c).transpose(x, c).transpose(i, c).transpose(j, c)
.root().cudaTile(x, y, 16, 16);
c = blurx.arg(3);
blurx.transpose(y, z).transpose(x, z).transpose(y, c).transpose(x, c)
.root().cudaTile(x, y, 8, 8);
c = blury.arg(3);
blury.transpose(y, z).transpose(x, z).transpose(y, c).transpose(x, c)
.root().cudaTile(x, y, 8, 8);
c = blurz.arg(3);
blurz.transpose(y, z).transpose(x, z).transpose(y, c).transpose(x, c)
.root().cudaTile(x, y, 8, 8);
smoothed.root().cudaTile(x, y, s_sigma, s_sigma);
#endif
smoothed.compileToFile("bilateral_grid", {r_sigma, input});
// Compared to Sylvain Paris' implementation from his webpage (on
// which this is based), for filter params s_sigma 0.1, on a 4 megapixel
// input, on a four core x86 (2 socket core2 mac pro)
// Filter s_sigma: 2 4 8 16 32
// Paris (ms): 5350 1345 472 245 184
// Us (ms): 383 142 77 62 65
// Speedup: 14 9.5 6.1 3.9 2.8
// Our schedule and inlining are roughly the same as his, so the
// gain is all down to vectorizing and parallelizing. In general
// for larger blurs our win shrinks to roughly the number of
// cores, as the stages we don't vectorize as well dominate (we
// don't vectorize them well because they do gathers and scatters,
// which don't work well on x86). For smaller blurs, our win
// grows, because the stages that we vectorize take up all the
// time.
return 0;
}
<commit_msg>Cleaned up bilateral grid gpu scheduling<commit_after>#include "Halide.h"
using namespace Halide;
Expr lerp(Expr a, Expr b, Expr alpha) {
return (1.0f - alpha)*a + alpha*b;
}
int main(int argc, char **argv) {
if (argc < 2) {
printf("Spatial sigma is a compile-time parameter, please provide it as an argument.\n"
"(llvm's ptx backend doesn't handle integer mods by non-consts yet)\n");
return 0;
}
UniformImage input(Float(32), 2);
Uniform<float> r_sigma;
int s_sigma = atoi(argv[1]);
Var x, y, z, c;
// Add a boundary condition
Func clamped;
clamped(x, y) = input(clamp(x, 0, input.width()-1),
clamp(y, 0, input.height()-1));
// Construct the bilateral grid
RDom r(0, s_sigma, 0, s_sigma);
Expr val = clamped(x * s_sigma + r.x - s_sigma/2, y * s_sigma + r.y - s_sigma/2);
val = clamp(val, 0.0f, 1.0f);
Expr zi = cast<int>(val * (1.0f/r_sigma) + 0.5f);
Func grid;
grid(x, y, zi, c) += select(c == 0, val, 1.0f);
// Blur the grid using a five-tap filter
Func blurx, blury, blurz;
blurx(x, y, z) = grid(x-2, y, z) + grid(x-1, y, z)*4 + grid(x, y, z)*6 + grid(x+1, y, z)*4 + grid(x+2, y, z);
blury(x, y, z) = blurx(x, y-2, z) + blurx(x, y-1, z)*4 + blurx(x, y, z)*6 + blurx(x, y+1, z)*4 + blurx(x, y+2, z);
blurz(x, y, z) = blury(x, y, z-2) + blury(x, y, z-1)*4 + blury(x, y, z)*6 + blury(x, y, z+1)*4 + blury(x, y, z+2);
// Take trilinear samples to compute the output
val = clamp(clamped(x, y), 0.0f, 1.0f);
Expr zv = val * (1.0f/r_sigma);
zi = cast<int>(zv);
Expr zf = zv - zi;
Expr xf = cast<float>(x % s_sigma) / s_sigma;
Expr yf = cast<float>(y % s_sigma) / s_sigma;
Expr xi = x/s_sigma;
Expr yi = y/s_sigma;
Func interpolated;
interpolated(x, y) =
lerp(lerp(lerp(blurz(xi, yi, zi), blurz(xi+1, yi, zi), xf),
lerp(blurz(xi, yi+1, zi), blurz(xi+1, yi+1, zi), xf), yf),
lerp(lerp(blurz(xi, yi, zi+1), blurz(xi+1, yi, zi+1), xf),
lerp(blurz(xi, yi+1, zi+1), blurz(xi+1, yi+1, zi+1), xf), yf), zf);
// Normalize
Func smoothed;
smoothed(x, y) = interpolated(x, y, 0)/interpolated(x, y, 1);
#ifndef USE_GPU
// Best schedule for CPU
printf("Compiling for CPU\n");
grid.root().parallel(z);
grid.update().transpose(y, c).transpose(x, c).parallel(y);
blurx.root().parallel(z).vectorize(x, 4);
blury.root().parallel(z).vectorize(x, 4);
blurz.root().parallel(z).vectorize(x, 4);
smoothed.root().parallel(y).vectorize(x, 4);
#else
printf("Compiling for GPU");
Var gridz = grid.arg(2);
grid.root().cudaTile(x, y, 16, 16);
grid.update().root().cudaTile(x, y, 16, 16);
blurx.root().cudaTile(x, y, 8, 8);
blury.root().cudaTile(x, y, 8, 8);
blurz.root().cudaTile(x, y, 8, 8);
smoothed.root().cudaTile(x, y, s_sigma, s_sigma);
#endif
smoothed.compileToFile("bilateral_grid", {r_sigma, input});
// Compared to Sylvain Paris' implementation from his webpage (on
// which this is based), for filter params s_sigma 0.1, on a 4 megapixel
// input, on a four core x86 (2 socket core2 mac pro)
// Filter s_sigma: 2 4 8 16 32
// Paris (ms): 5350 1345 472 245 184
// Us (ms): 383 142 77 62 65
// Speedup: 14 9.5 6.1 3.9 2.8
// Our schedule and inlining are roughly the same as his, so the
// gain is all down to vectorizing and parallelizing. In general
// for larger blurs our win shrinks to roughly the number of
// cores, as the stages we don't vectorize as well dominate (we
// don't vectorize them well because they do gathers and scatters,
// which don't work well on x86). For smaller blurs, our win
// grows, because the stages that we vectorize take up all the
// time.
return 0;
}
<|endoftext|> |
<commit_before>/*!
* a tool to combine different set of features into binary buffer
* not well organized code, but does it's job
* \author Tianqi Chen: tianqi.tchen@gmail.com
*/
#define _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_DEPRECATE
#include <cstdio>
#include <cstring>
#include <ctime>
#include <cmath>
#include "../regrank/xgboost_regrank_data.h"
#include "../utils/xgboost_utils.h"
using namespace xgboost;
using namespace xgboost::booster;
using namespace xgboost::regrank;
// header in dataset
struct Header{
FILE *fi;
int tmp_num;
int base;
int num_feat;
// whether it's dense format
bool is_dense;
bool warned;
Header( void ){ this->warned = false; this->is_dense = false; }
inline void CheckBase( unsigned findex ){
if( findex >= (unsigned)num_feat && ! warned ) {
fprintf( stderr, "warning:some feature exceed bound, num_feat=%d\n", num_feat );
warned = true;
}
}
};
inline int norm( std::vector<Header> &vec, int base = 0 ){
int n = base;
for( size_t i = 0; i < vec.size(); i ++ ){
if( vec[i].is_dense ) vec[i].num_feat = 1;
vec[i].base = n; n += vec[i].num_feat;
}
return n;
}
inline void vclose( std::vector<Header> &vec ){
for( size_t i = 0; i < vec.size(); i ++ ){
fclose( vec[i].fi );
}
}
inline int readnum( std::vector<Header> &vec ){
int n = 0;
for( size_t i = 0; i < vec.size(); i ++ ){
if( !vec[i].is_dense ){
utils::Assert( fscanf( vec[i].fi, "%d", &vec[i].tmp_num ) == 1, "load num" );
n += vec[i].tmp_num;
}else{
n ++;
}
}
return n;
}
inline void vskip( std::vector<Header> &vec ){
for( size_t i = 0; i < vec.size(); i ++ ){
if( !vec[i].is_dense ){
utils::Assert( fscanf( vec[i].fi, "%*d%*[^\n]\n" ) >= 0 );
}else{
utils::Assert( fscanf( vec[i].fi, "%*f\n" ) >= 0 );
}
}
}
class DataLoader: public DMatrix{
public:
// whether to do node and edge feature renormalization
int rescale;
int linelimit;
public:
FILE *fp, *fwlist, *fgroup;
std::vector<Header> fheader;
std::vector<FMatrixS::REntry> entry;
DataLoader( void ){
rescale = 0;
linelimit = -1;
fp = NULL; fwlist = NULL; fgroup = NULL;
}
private:
inline void Load( std::vector<unsigned> &findex, std::vector<float> &fvalue, std::vector<Header> &vec ){
unsigned fidx; float fv;
for( size_t i = 0; i < vec.size(); i ++ ){
if( !vec[i].is_dense ) {
for( int j = 0; j < vec[i].tmp_num; j ++ ){
utils::Assert( fscanf ( vec[i].fi, "%u:%f", &fidx, &fv ) == 2, "Error when load feat" );
vec[i].CheckBase( fidx );
fidx += vec[i].base;
findex.push_back( fidx ); fvalue.push_back( fv );
}
}else{
utils::Assert( fscanf ( vec[i].fi, "%f", &fv ) == 1, "load feat" );
fidx = vec[i].base;
findex.push_back( fidx ); fvalue.push_back( fv );
}
}
}
inline void DoRescale( std::vector<float> &vec ){
double sum = 0.0;
for( size_t i = 0; i < vec.size(); i ++ ){
sum += vec[i] * vec[i];
}
sum = sqrt( sum );
for( size_t i = 0; i < vec.size(); i ++ ){
vec[i] /= sum;
}
}
public:
// basically we are loading all the data inside
inline void Load( void ){
this->data.Clear();
float label;
unsigned ngleft = 0, ngacc = 0;
if( fgroup != NULL ){
info.group_ptr.clear();
info.group_ptr.push_back(0);
}
while( fscanf( fp, "%f", &label ) == 1 ){
if( ngleft == 0 && fgroup != NULL ){
utils::Assert( fscanf( fgroup, "%u", &ngleft ) == 1 );
}
ngleft -= 1; ngacc += 1;
if( fwlist != NULL ){
int pass;
utils::Assert( fscanf( fwlist, "%u", &pass ) ==1 );
if( pass == 0 ){
vskip( fheader ); ngacc -= 1;
}
}
const int nfeat = readnum( fheader );
std::vector<unsigned> findex;
std::vector<float> fvalue;
// pairs
this->Load( findex, fvalue, fheader );
utils::Assert( findex.size() == (unsigned)nfeat );
if( rescale != 0 ) this->DoRescale( fvalue );
// push back data :)
this->info.labels.push_back( label );
this->data.AddRow( findex, fvalue );
if( ngleft == 0 && fgroup != NULL && ngacc != 0 ){
info.group_ptr.push_back( info.group_ptr.back() + ngacc );
utils::Assert( info.group_ptr.back() == data.NumRow(), "group size must match num rows" );
ngacc = 0;
}
// linelimit
if( linelimit >= 0 ) {
if( -- linelimit <= 0 ) break;
}
}
if( ngleft == 0 && fgroup != NULL && ngacc != 0 ){
info.group_ptr.push_back( info.group_ptr.back() + ngacc );
utils::Assert( info.group_ptr.back() == data.NumRow(), "group size must match num rows" );
}
this->data.InitData();
}
};
const char *folder = "features";
int main( int argc, char *argv[] ){
if( argc < 3 ){
printf("Usage:xgcombine_buffer <inname> <outname> [options] -f [features] -fd [densefeatures]\n"\
"options: -rescale -linelimit -fgroup <groupfilename> -wlist <whitelistinstance>\n");
return 0;
}
DataLoader loader;
time_t start = time( NULL );
int mode = 0;
for( int i = 3; i < argc; i ++ ){
if( !strcmp( argv[i], "-f") ){
mode = 0; continue;
}
if( !strcmp( argv[i], "-fd") ){
mode = 2; continue;
}
if( !strcmp( argv[i], "-rescale") ){
loader.rescale = 1; continue;
}
if( !strcmp( argv[i], "-wlist") ){
loader.fwlist = utils::FopenCheck( argv[ ++i ], "r" ); continue;
}
if( !strcmp( argv[i], "-fgroup") ){
loader.fgroup = utils::FopenCheck( argv[ ++i ], "r" ); continue;
}
if( !strcmp( argv[i], "-linelimit") ){
loader.linelimit = atoi( argv[ ++i ] ); continue;
}
char name[ 256 ];
sprintf( name, "%s/%s.%s", folder, argv[1], argv[i] );
Header h;
h.fi = utils::FopenCheck( name, "r" );
if( mode == 2 ){
h.is_dense = true; h.num_feat = 1;
loader.fheader.push_back( h );
}else{
utils::Assert( fscanf( h.fi, "%d", &h.num_feat ) == 1, "num feat" );
switch( mode ){
case 0: loader.fheader.push_back( h ); break;
default: ;
}
}
}
loader.fp = utils::FopenCheck( argv[1], "r" );
printf("num_features=%d\n", norm( loader.fheader ) );
printf("start creating buffer...\n");
loader.Load();
loader.SaveBinary( argv[2] );
// close files
fclose( loader.fp );
if( loader.fwlist != NULL ) fclose( loader.fwlist );
if( loader.fgroup != NULL ) fclose( loader.fgroup );
vclose( loader.fheader );
printf("all generation end, %lu sec used\n", (unsigned long)(time(NULL) - start) );
return 0;
}
<commit_msg>pass test<commit_after>/*!
* a tool to combine different set of features into binary buffer
* not well organized code, but does it's job
* \author Tianqi Chen: tianqi.tchen@gmail.com
*/
#define _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_DEPRECATE
#include <cstdio>
#include <cstring>
#include <ctime>
#include <cmath>
#include "../regrank/xgboost_regrank_data.h"
#include "../utils/xgboost_utils.h"
using namespace xgboost;
using namespace xgboost::booster;
using namespace xgboost::regrank;
// header in dataset
struct Header{
FILE *fi;
int tmp_num;
int base;
int num_feat;
// whether it's dense format
bool is_dense;
bool warned;
Header( void ){ this->warned = false; this->is_dense = false; }
inline void CheckBase( unsigned findex ){
if( findex >= (unsigned)num_feat && ! warned ) {
fprintf( stderr, "warning:some feature exceed bound, num_feat=%d\n", num_feat );
warned = true;
}
}
};
inline int norm( std::vector<Header> &vec, int base = 0 ){
int n = base;
for( size_t i = 0; i < vec.size(); i ++ ){
if( vec[i].is_dense ) vec[i].num_feat = 1;
vec[i].base = n; n += vec[i].num_feat;
}
return n;
}
inline void vclose( std::vector<Header> &vec ){
for( size_t i = 0; i < vec.size(); i ++ ){
fclose( vec[i].fi );
}
}
inline int readnum( std::vector<Header> &vec ){
int n = 0;
for( size_t i = 0; i < vec.size(); i ++ ){
if( !vec[i].is_dense ){
utils::Assert( fscanf( vec[i].fi, "%d", &vec[i].tmp_num ) == 1, "load num" );
n += vec[i].tmp_num;
}else{
n ++;
}
}
return n;
}
inline void vskip( std::vector<Header> &vec ){
for( size_t i = 0; i < vec.size(); i ++ ){
if( !vec[i].is_dense ){
utils::Assert( fscanf( vec[i].fi, "%*d%*[^\n]\n" ) >= 0 );
}else{
utils::Assert( fscanf( vec[i].fi, "%*f\n" ) >= 0 );
}
}
}
class DataLoader: public DMatrix{
public:
// whether to do node and edge feature renormalization
int rescale;
int linelimit;
public:
FILE *fp, *fwlist, *fgroup;
std::vector<Header> fheader;
std::vector<FMatrixS::REntry> entry;
DataLoader( void ){
rescale = 0;
linelimit = -1;
fp = NULL; fwlist = NULL; fgroup = NULL;
}
private:
inline void Load( std::vector<unsigned> &findex, std::vector<float> &fvalue, std::vector<Header> &vec ){
unsigned fidx; float fv;
for( size_t i = 0; i < vec.size(); i ++ ){
if( !vec[i].is_dense ) {
for( int j = 0; j < vec[i].tmp_num; j ++ ){
utils::Assert( fscanf ( vec[i].fi, "%u:%f", &fidx, &fv ) == 2, "Error when load feat" );
vec[i].CheckBase( fidx );
fidx += vec[i].base;
findex.push_back( fidx ); fvalue.push_back( fv );
}
}else{
utils::Assert( fscanf ( vec[i].fi, "%f", &fv ) == 1, "load feat" );
fidx = vec[i].base;
findex.push_back( fidx ); fvalue.push_back( fv );
}
}
}
inline void DoRescale( std::vector<float> &vec ){
double sum = 0.0;
for( size_t i = 0; i < vec.size(); i ++ ){
sum += vec[i] * vec[i];
}
sum = sqrt( sum );
for( size_t i = 0; i < vec.size(); i ++ ){
vec[i] /= sum;
}
}
public:
// basically we are loading all the data inside
inline void Load( void ){
this->data.Clear();
float label;
unsigned ngleft = 0, ngacc = 0;
if( fgroup != NULL ){
info.group_ptr.clear();
info.group_ptr.push_back(0);
}
while( fscanf( fp, "%f", &label ) == 1 ){
if( ngleft == 0 && fgroup != NULL ){
utils::Assert( fscanf( fgroup, "%u", &ngleft ) == 1 );
}
ngleft -= 1; ngacc += 1;
int pass = 1;
if( fwlist != NULL ){
utils::Assert( fscanf( fwlist, "%u", &pass ) ==1 );
}
if( pass == 0 ){
vskip( fheader ); ngacc -= 1;
}else{
const int nfeat = readnum( fheader );
std::vector<unsigned> findex;
std::vector<float> fvalue;
// pairs
this->Load( findex, fvalue, fheader );
utils::Assert( findex.size() == (unsigned)nfeat );
if( rescale != 0 ) this->DoRescale( fvalue );
// push back data :)
this->info.labels.push_back( label );
this->data.AddRow( findex, fvalue );
}
if( ngleft == 0 && fgroup != NULL && ngacc != 0 ){
info.group_ptr.push_back( info.group_ptr.back() + ngacc );
utils::Assert( info.group_ptr.back() == data.NumRow(), "group size must match num rows" );
ngacc = 0;
}
// linelimit
if( linelimit >= 0 ) {
if( -- linelimit <= 0 ) break;
}
}
if( ngleft == 0 && fgroup != NULL && ngacc != 0 ){
info.group_ptr.push_back( info.group_ptr.back() + ngacc );
utils::Assert( info.group_ptr.back() == data.NumRow(), "group size must match num rows" );
}
this->data.InitData();
}
};
const char *folder = "features";
int main( int argc, char *argv[] ){
if( argc < 3 ){
printf("Usage:xgcombine_buffer <inname> <outname> [options] -f [features] -fd [densefeatures]\n"\
"options: -rescale -linelimit -fgroup <groupfilename> -wlist <whitelistinstance>\n");
return 0;
}
DataLoader loader;
time_t start = time( NULL );
int mode = 0;
for( int i = 3; i < argc; i ++ ){
if( !strcmp( argv[i], "-f") ){
mode = 0; continue;
}
if( !strcmp( argv[i], "-fd") ){
mode = 2; continue;
}
if( !strcmp( argv[i], "-rescale") ){
loader.rescale = 1; continue;
}
if( !strcmp( argv[i], "-wlist") ){
loader.fwlist = utils::FopenCheck( argv[ ++i ], "r" ); continue;
}
if( !strcmp( argv[i], "-fgroup") ){
loader.fgroup = utils::FopenCheck( argv[ ++i ], "r" ); continue;
}
if( !strcmp( argv[i], "-linelimit") ){
loader.linelimit = atoi( argv[ ++i ] ); continue;
}
char name[ 256 ];
sprintf( name, "%s/%s.%s", folder, argv[1], argv[i] );
Header h;
h.fi = utils::FopenCheck( name, "r" );
if( mode == 2 ){
h.is_dense = true; h.num_feat = 1;
loader.fheader.push_back( h );
}else{
utils::Assert( fscanf( h.fi, "%d", &h.num_feat ) == 1, "num feat" );
switch( mode ){
case 0: loader.fheader.push_back( h ); break;
default: ;
}
}
}
loader.fp = utils::FopenCheck( argv[1], "r" );
printf("num_features=%d\n", norm( loader.fheader ) );
printf("start creating buffer...\n");
loader.Load();
loader.SaveBinary( argv[2] );
// close files
fclose( loader.fp );
if( loader.fwlist != NULL ) fclose( loader.fwlist );
if( loader.fgroup != NULL ) fclose( loader.fgroup );
vclose( loader.fheader );
printf("all generation end, %lu sec used\n", (unsigned long)(time(NULL) - start) );
return 0;
}
<|endoftext|> |
<commit_before>class Solution {
public:
/**
* @param s: a string
* @return: an integer
*/
std::map<char, int> mapCtoSub;
int lengthOfLongestSubstring(string s) {
// write your code here
int i,j,k,l_s=s.size();
int max_len=0;
for (char c='a';c<='z';c++)
mapCtoSub[c]=-1;
// cout<<s<<l_s<<endl;
for (i=0,j=0;j<l_s;j++){
// cout<<i<<" "<<j<<endl;
if (mapCtoSub[s[j]]>-1) i=max(i,mapCtoSub[s[j]]);
mapCtoSub[s[j]]=j;
int tmp_len=j-i;
if (tmp_len>max_len) max_len=tmp_len;
// cout<<i<<" "<<j<<endl;
}
return max_len;
}
};<commit_msg>testing<commit_after>class Solution {
public:
/**
* @param s: a string
* @return: an integer
*/
std::map<char, int> mapCtoSub;
int lengthOfLongestSubstring(string s) {
// write your code here
int i,j,k,l_s=s.size();
int max_len=0;
for (char c='a';c<='z';c++)
mapCtoSub[c]=-1;
// cout<<s<<l_s<<endl;
for (i=-1,j=0;j<l_s;j++){
// cout<<i<<" "<<j<<endl;
if (mapCtoSub[s[j]]>-1) i=max(i,mapCtoSub[s[j]]);
mapCtoSub[s[j]]=j;
int tmp_len=j-i;
if (tmp_len>max_len) max_len=tmp_len;
// cout<<i<<" "<<j<<endl;
}
return max_len;
}
};<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: EnhancedCustomShapeEngine.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2006-06-19 14:56:40 $
*
* 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 _ENHANCED_CUSTOMSHAPE_ENGINE_HXX
#define _ENHANCED_CUSTOMSHAPE_ENGINE_HXX
#ifndef _DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _STACK_HXX
#include <tools/stack.hxx>
#endif
#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/RuntimeException.hpp>
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/registry/XRegistryKey.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#ifndef _CPPUHELPER_IMPLBASE3_HXX_
#include <cppuhelper/implbase3.hxx>
#endif
#ifndef __com_sun_star_awt_Rectangle_hpp_
#include <com/sun/star/awt/Rectangle.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_POLYPOLYGONBEZIERCOORDS_HPP_
#include <com/sun/star/drawing/PolyPolygonBezierCoords.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_
#include <com/sun/star/lang/XInitialization.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XCUSTOMSHAPEENGINE_HPP_
#include <com/sun/star/drawing/XCustomShapeEngine.hpp>
#endif
// -----------------------------------------------------------------------------
#define NMSP_IO com::sun::star::io
#define NMSP_UNO com::sun::star::uno
#define NMSP_BEANS com::sun::star::beans
#define NMSP_LANG com::sun::star::lang
#define NMSP_UTIL com::sun::star::util
#define NMSP_SAX com::sun::star::xml::sax
#define NMSP_LOGGING NMSP_UTIL::logging
#define REF( _def_Obj ) NMSP_UNO::Reference< _def_Obj >
#define SEQ( _def_Obj ) NMSP_UNO::Sequence< _def_Obj >
#define B2UCONST( _def_pChar ) (rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(_def_pChar )))
// ---------------------------
// - EnhancedCustomShapeEngine -
// ---------------------------
//
class SdrObject;
class SdrObjCustomShape;
class EnhancedCustomShapeEngine : public cppu::WeakImplHelper3
<
com::sun::star::lang::XInitialization,
com::sun::star::lang::XServiceInfo,
com::sun::star::drawing::XCustomShapeEngine
>
{
REF( NMSP_LANG::XMultiServiceFactory ) mxFact;
REF( com::sun::star::drawing::XShape ) mxShape;
sal_Bool mbForceGroupWithText;
SdrObject* ImplForceGroupWithText( const SdrObjCustomShape* pCustoObj, SdrObject* pRenderedShape );
public:
EnhancedCustomShapeEngine( const REF( NMSP_LANG::XMultiServiceFactory )& rxMgr );
virtual ~EnhancedCustomShapeEngine();
// XInterface
virtual void SAL_CALL acquire() throw();
virtual void SAL_CALL release() throw();
// XInitialization
virtual void SAL_CALL initialize( const SEQ( NMSP_UNO::Any )& aArguments )
throw ( NMSP_UNO::Exception, NMSP_UNO::RuntimeException );
// XServiceInfo
virtual rtl::OUString SAL_CALL getImplementationName()
throw ( NMSP_UNO::RuntimeException );
virtual sal_Bool SAL_CALL supportsService( const rtl::OUString& rServiceName )
throw ( NMSP_UNO::RuntimeException );
virtual SEQ( rtl::OUString ) SAL_CALL getSupportedServiceNames()
throw ( NMSP_UNO::RuntimeException );
// XCustomShapeEngine
virtual REF( com::sun::star::drawing::XShape ) SAL_CALL render()
throw ( NMSP_UNO::RuntimeException );
virtual com::sun::star::awt::Rectangle SAL_CALL getTextBounds()
throw ( NMSP_UNO::RuntimeException );
virtual com::sun::star::drawing::PolyPolygonBezierCoords SAL_CALL getLineGeometry()
throw ( NMSP_UNO::RuntimeException );
virtual SEQ( REF( com::sun::star::drawing::XCustomShapeHandle ) ) SAL_CALL getInteraction()
throw ( NMSP_UNO::RuntimeException );
};
rtl::OUString EnhancedCustomShapeEngine_getImplementationName()
throw ( NMSP_UNO::RuntimeException );
sal_Bool SAL_CALL EnhancedCustomShapeEngine_supportsService( const rtl::OUString& rServiceName )
throw( NMSP_UNO::RuntimeException );
SEQ( rtl::OUString ) SAL_CALL EnhancedCustomShapeEngine_getSupportedServiceNames()
throw( NMSP_UNO::RuntimeException );
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.6.852); FILE MERGED 2008/04/01 15:50:10 thb 1.6.852.3: #i85898# Stripping all external header guards 2008/04/01 12:48:02 thb 1.6.852.2: #i85898# Stripping all external header guards 2008/03/31 14:19:17 rt 1.6.852.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: EnhancedCustomShapeEngine.hxx,v $
* $Revision: 1.7 $
*
* 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 _ENHANCED_CUSTOMSHAPE_ENGINE_HXX
#define _ENHANCED_CUSTOMSHAPE_ENGINE_HXX
#include <tools/debug.hxx>
#include <tools/string.hxx>
#include <tools/stack.hxx>
#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/RuntimeException.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/registry/XRegistryKey.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <cppuhelper/implbase3.hxx>
#ifndef __com_sun_star_awt_Rectangle_hpp_
#include <com/sun/star/awt/Rectangle.hpp>
#endif
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/drawing/PolyPolygonBezierCoords.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/drawing/XCustomShapeEngine.hpp>
// -----------------------------------------------------------------------------
#define NMSP_IO com::sun::star::io
#define NMSP_UNO com::sun::star::uno
#define NMSP_BEANS com::sun::star::beans
#define NMSP_LANG com::sun::star::lang
#define NMSP_UTIL com::sun::star::util
#define NMSP_SAX com::sun::star::xml::sax
#define NMSP_LOGGING NMSP_UTIL::logging
#define REF( _def_Obj ) NMSP_UNO::Reference< _def_Obj >
#define SEQ( _def_Obj ) NMSP_UNO::Sequence< _def_Obj >
#define B2UCONST( _def_pChar ) (rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(_def_pChar )))
// ---------------------------
// - EnhancedCustomShapeEngine -
// ---------------------------
//
class SdrObject;
class SdrObjCustomShape;
class EnhancedCustomShapeEngine : public cppu::WeakImplHelper3
<
com::sun::star::lang::XInitialization,
com::sun::star::lang::XServiceInfo,
com::sun::star::drawing::XCustomShapeEngine
>
{
REF( NMSP_LANG::XMultiServiceFactory ) mxFact;
REF( com::sun::star::drawing::XShape ) mxShape;
sal_Bool mbForceGroupWithText;
SdrObject* ImplForceGroupWithText( const SdrObjCustomShape* pCustoObj, SdrObject* pRenderedShape );
public:
EnhancedCustomShapeEngine( const REF( NMSP_LANG::XMultiServiceFactory )& rxMgr );
virtual ~EnhancedCustomShapeEngine();
// XInterface
virtual void SAL_CALL acquire() throw();
virtual void SAL_CALL release() throw();
// XInitialization
virtual void SAL_CALL initialize( const SEQ( NMSP_UNO::Any )& aArguments )
throw ( NMSP_UNO::Exception, NMSP_UNO::RuntimeException );
// XServiceInfo
virtual rtl::OUString SAL_CALL getImplementationName()
throw ( NMSP_UNO::RuntimeException );
virtual sal_Bool SAL_CALL supportsService( const rtl::OUString& rServiceName )
throw ( NMSP_UNO::RuntimeException );
virtual SEQ( rtl::OUString ) SAL_CALL getSupportedServiceNames()
throw ( NMSP_UNO::RuntimeException );
// XCustomShapeEngine
virtual REF( com::sun::star::drawing::XShape ) SAL_CALL render()
throw ( NMSP_UNO::RuntimeException );
virtual com::sun::star::awt::Rectangle SAL_CALL getTextBounds()
throw ( NMSP_UNO::RuntimeException );
virtual com::sun::star::drawing::PolyPolygonBezierCoords SAL_CALL getLineGeometry()
throw ( NMSP_UNO::RuntimeException );
virtual SEQ( REF( com::sun::star::drawing::XCustomShapeHandle ) ) SAL_CALL getInteraction()
throw ( NMSP_UNO::RuntimeException );
};
rtl::OUString EnhancedCustomShapeEngine_getImplementationName()
throw ( NMSP_UNO::RuntimeException );
sal_Bool SAL_CALL EnhancedCustomShapeEngine_supportsService( const rtl::OUString& rServiceName )
throw( NMSP_UNO::RuntimeException );
SEQ( rtl::OUString ) SAL_CALL EnhancedCustomShapeEngine_getSupportedServiceNames()
throw( NMSP_UNO::RuntimeException );
#endif
<|endoftext|> |
<commit_before>/*
* This istream filter removes HTTP chunking.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "istream_dechunk.hxx"
#include "http/ChunkParser.hxx"
#include "FacadeIstream.hxx"
#include "pool.hxx"
#include <algorithm>
#include <glib.h>
#include <assert.h>
#include <string.h>
class DechunkIstream final : public FacadeIstream {
HttpChunkParser parser;
bool eof = false, closed = false;
bool had_input, had_output;
/**
* Copy chunked data verbatim to handler?
*
* @see istream_dechunk_check_verbatim()
*/
bool verbatim = false;
/**
* Was the end-of-file chunk seen at the end of #pending_verbatim?
*/
bool eof_verbatim;
/**
* Number of bytes to be passed to handler verbatim, which have
* already been parsed but have not yet been consumed by the
* handler.
*/
size_t pending_verbatim;
DechunkHandler &dechunk_handler;
public:
DechunkIstream(struct pool &p, Istream &_input,
DechunkHandler &_dechunk_handler)
:FacadeIstream(p, _input), dechunk_handler(_dechunk_handler)
{
}
static DechunkIstream *CheckCast(Istream &i) {
return dynamic_cast<DechunkIstream *>(&i);
}
void SetVerbatim() {
verbatim = true;
eof_verbatim = false;
pending_verbatim = 0;
}
private:
void Abort(GError *error);
/**
* @return false if the istream_dechunk has been aborted
* indirectly (by a callback)
*/
bool EofDetected();
size_t Feed(const void *data, size_t length);
public:
/* virtual methods from class Istream */
off_t _GetAvailable(bool partial) override;
void _Read() override;
void _Close() override;
protected:
/* virtual methods from class IstreamHandler */
size_t OnData(const void *data, size_t length) override;
void OnEof() override;
void OnError(GError *error) override;
};
void
DechunkIstream::Abort(GError *error)
{
assert(!closed);
assert(!parser.HasEnded());
assert(input.IsDefined());
closed = true;
input.ClearAndClose();
DestroyError(error);
}
bool
DechunkIstream::EofDetected()
{
assert(input.IsDefined());
assert(parser.HasEnded());
assert(!eof);
eof = true;
dechunk_handler.OnDechunkEnd();
assert(input.IsDefined());
assert(parser.HasEnded());
const ScopePoolRef ref(GetPool() TRACE_ARGS);
DestroyEof();
if (closed) {
assert(!input.IsDefined());
return false;
} else {
/* we must deinitialize the "input" after emitting "eof",
because we must give the callback a chance to call
dechunk_input_abort() on us; if we'd clear the handler too
early, we wouldn't receive that event, and
dechunk_input_data() couldn't change its return value to
0 */
assert(input.IsDefined());
input.ClearHandler();
return true;
}
}
size_t
DechunkIstream::Feed(const void *data0, size_t length)
{
assert(!closed);
assert(input.IsDefined());
assert(!verbatim || !eof_verbatim);
had_input = true;
const auto src_begin = (const char *)data0;
const auto src_end = src_begin + length;
auto src = src_begin;
if (verbatim)
/* skip the part that has already been parsed in the last
invocation, but could not be consumed by the handler */
src += pending_verbatim;
while (src != src_end) {
GError *error = nullptr;
const ConstBuffer<char> src_remaining(src, src_end - src);
auto data = ConstBuffer<char>::FromVoid(parser.Parse(src_remaining.ToVoid(),
&error));
if (data.IsNull()) {
Abort(error);
return 0;
}
assert(data.data >= src);
assert(data.data <= src_end);
assert(data.end() <= src_end);
src = data.data;
if (!data.IsEmpty()) {
assert(!parser.HasEnded());
size_t nbytes;
if (verbatim) {
/* postpone this data chunk; try to send it all later in
one big block */
nbytes = data.size;
} else {
had_output = true;
nbytes = InvokeData(src, data.size);
assert(nbytes <= data.size);
if (nbytes == 0) {
if (closed)
return 0;
else
break;
}
}
src += nbytes;
bool finished = parser.Consume(nbytes);
if (!finished && !verbatim)
break;
} else if (parser.HasEnded()) {
break;
} else {
assert(src == src_end);
}
}
const size_t position = src - src_begin;
if (verbatim && position > 0) {
/* send all chunks in one big block */
had_output = true;
size_t nbytes = InvokeData(src_begin, position);
if (closed)
return 0;
/* postpone the rest that was not handled; it will not be
parsed again */
pending_verbatim = position - nbytes;
if (parser.HasEnded()) {
if (pending_verbatim > 0)
/* not everything could be sent; postpone to
next call */
eof_verbatim = true;
else if (!EofDetected())
return 0;
}
return nbytes;
} else if (parser.HasEnded() && !EofDetected())
return 0;
return position;
}
/*
* istream handler
*
*/
size_t
DechunkIstream::OnData(const void *data, size_t length)
{
assert(!verbatim || length >= pending_verbatim);
if (verbatim && eof_verbatim) {
/* during the last call, the EOF chunk was parsed, but we
could not handle it yet, because the handler did not
consume all data yet; try to send the remaining pre-EOF
data again and then handle the EOF chunk */
assert(pending_verbatim > 0);
assert(length >= pending_verbatim);
had_output = true;
size_t nbytes = InvokeData(data, pending_verbatim);
if (nbytes == 0)
return 0;
pending_verbatim -= nbytes;
if (pending_verbatim > 0)
/* more data needed */
return nbytes;
return EofDetected() ? nbytes : 0;
}
const ScopePoolRef ref(GetPool() TRACE_ARGS);
return Feed(data, length);
}
void
DechunkIstream::OnEof()
{
assert(!closed);
input.Clear();
closed = true;
if (eof)
return;
GError *error =
g_error_new_literal(dechunk_quark(), 0,
"premature EOF in dechunker");
DestroyError(error);
}
void
DechunkIstream::OnError(GError *error)
{
input.Clear();
closed = true;
if (eof)
g_error_free(error);
else
DestroyError(error);
}
/*
* istream implementation
*
*/
off_t
DechunkIstream::_GetAvailable(bool partial)
{
if (partial)
return (off_t)parser.GetAvailable();
return (off_t)-1;
}
void
DechunkIstream::_Read()
{
const ScopePoolRef ref(GetPool() TRACE_ARGS);
had_output = false;
do {
had_input = false;
input.Read();
} while (input.IsDefined() && had_input && !had_output);
}
void
DechunkIstream::_Close()
{
assert(!eof);
assert(!closed);
closed = true;
input.ClearAndClose();
Destroy();
}
/*
* constructor
*
*/
Istream *
istream_dechunk_new(struct pool *pool, Istream &input,
DechunkHandler &dechunk_handler)
{
return NewIstream<DechunkIstream>(*pool, input, dechunk_handler);
}
bool
istream_dechunk_check_verbatim(Istream &i)
{
auto *dechunk = DechunkIstream::CheckCast(i);
if (dechunk == nullptr)
/* not a DechunkIstream instance */
return false;
dechunk->SetVerbatim();
return true;
}
<commit_msg>istream/dechunk: fix indent<commit_after>/*
* This istream filter removes HTTP chunking.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "istream_dechunk.hxx"
#include "http/ChunkParser.hxx"
#include "FacadeIstream.hxx"
#include "pool.hxx"
#include <algorithm>
#include <glib.h>
#include <assert.h>
#include <string.h>
class DechunkIstream final : public FacadeIstream {
HttpChunkParser parser;
bool eof = false, closed = false;
bool had_input, had_output;
/**
* Copy chunked data verbatim to handler?
*
* @see istream_dechunk_check_verbatim()
*/
bool verbatim = false;
/**
* Was the end-of-file chunk seen at the end of #pending_verbatim?
*/
bool eof_verbatim;
/**
* Number of bytes to be passed to handler verbatim, which have
* already been parsed but have not yet been consumed by the
* handler.
*/
size_t pending_verbatim;
DechunkHandler &dechunk_handler;
public:
DechunkIstream(struct pool &p, Istream &_input,
DechunkHandler &_dechunk_handler)
:FacadeIstream(p, _input), dechunk_handler(_dechunk_handler)
{
}
static DechunkIstream *CheckCast(Istream &i) {
return dynamic_cast<DechunkIstream *>(&i);
}
void SetVerbatim() {
verbatim = true;
eof_verbatim = false;
pending_verbatim = 0;
}
private:
void Abort(GError *error);
/**
* @return false if the istream_dechunk has been aborted
* indirectly (by a callback)
*/
bool EofDetected();
size_t Feed(const void *data, size_t length);
public:
/* virtual methods from class Istream */
off_t _GetAvailable(bool partial) override;
void _Read() override;
void _Close() override;
protected:
/* virtual methods from class IstreamHandler */
size_t OnData(const void *data, size_t length) override;
void OnEof() override;
void OnError(GError *error) override;
};
void
DechunkIstream::Abort(GError *error)
{
assert(!closed);
assert(!parser.HasEnded());
assert(input.IsDefined());
closed = true;
input.ClearAndClose();
DestroyError(error);
}
bool
DechunkIstream::EofDetected()
{
assert(input.IsDefined());
assert(parser.HasEnded());
assert(!eof);
eof = true;
dechunk_handler.OnDechunkEnd();
assert(input.IsDefined());
assert(parser.HasEnded());
const ScopePoolRef ref(GetPool() TRACE_ARGS);
DestroyEof();
if (closed) {
assert(!input.IsDefined());
return false;
} else {
/* we must deinitialize the "input" after emitting "eof",
because we must give the callback a chance to call
dechunk_input_abort() on us; if we'd clear the handler too
early, we wouldn't receive that event, and
dechunk_input_data() couldn't change its return value to
0 */
assert(input.IsDefined());
input.ClearHandler();
return true;
}
}
size_t
DechunkIstream::Feed(const void *data0, size_t length)
{
assert(!closed);
assert(input.IsDefined());
assert(!verbatim || !eof_verbatim);
had_input = true;
const auto src_begin = (const char *)data0;
const auto src_end = src_begin + length;
auto src = src_begin;
if (verbatim)
/* skip the part that has already been parsed in the last
invocation, but could not be consumed by the handler */
src += pending_verbatim;
while (src != src_end) {
GError *error = nullptr;
const ConstBuffer<char> src_remaining(src, src_end - src);
auto data = ConstBuffer<char>::FromVoid(parser.Parse(src_remaining.ToVoid(),
&error));
if (data.IsNull()) {
Abort(error);
return 0;
}
assert(data.data >= src);
assert(data.data <= src_end);
assert(data.end() <= src_end);
src = data.data;
if (!data.IsEmpty()) {
assert(!parser.HasEnded());
size_t nbytes;
if (verbatim) {
/* postpone this data chunk; try to send it all later in
one big block */
nbytes = data.size;
} else {
had_output = true;
nbytes = InvokeData(src, data.size);
assert(nbytes <= data.size);
if (nbytes == 0) {
if (closed)
return 0;
else
break;
}
}
src += nbytes;
bool finished = parser.Consume(nbytes);
if (!finished && !verbatim)
break;
} else if (parser.HasEnded()) {
break;
} else {
assert(src == src_end);
}
}
const size_t position = src - src_begin;
if (verbatim && position > 0) {
/* send all chunks in one big block */
had_output = true;
size_t nbytes = InvokeData(src_begin, position);
if (closed)
return 0;
/* postpone the rest that was not handled; it will not be
parsed again */
pending_verbatim = position - nbytes;
if (parser.HasEnded()) {
if (pending_verbatim > 0)
/* not everything could be sent; postpone to
next call */
eof_verbatim = true;
else if (!EofDetected())
return 0;
}
return nbytes;
} else if (parser.HasEnded() && !EofDetected())
return 0;
return position;
}
/*
* istream handler
*
*/
size_t
DechunkIstream::OnData(const void *data, size_t length)
{
assert(!verbatim || length >= pending_verbatim);
if (verbatim && eof_verbatim) {
/* during the last call, the EOF chunk was parsed, but we
could not handle it yet, because the handler did not
consume all data yet; try to send the remaining pre-EOF
data again and then handle the EOF chunk */
assert(pending_verbatim > 0);
assert(length >= pending_verbatim);
had_output = true;
size_t nbytes = InvokeData(data, pending_verbatim);
if (nbytes == 0)
return 0;
pending_verbatim -= nbytes;
if (pending_verbatim > 0)
/* more data needed */
return nbytes;
return EofDetected() ? nbytes : 0;
}
const ScopePoolRef ref(GetPool() TRACE_ARGS);
return Feed(data, length);
}
void
DechunkIstream::OnEof()
{
assert(!closed);
input.Clear();
closed = true;
if (eof)
return;
GError *error =
g_error_new_literal(dechunk_quark(), 0,
"premature EOF in dechunker");
DestroyError(error);
}
void
DechunkIstream::OnError(GError *error)
{
input.Clear();
closed = true;
if (eof)
g_error_free(error);
else
DestroyError(error);
}
/*
* istream implementation
*
*/
off_t
DechunkIstream::_GetAvailable(bool partial)
{
if (partial)
return (off_t)parser.GetAvailable();
return (off_t)-1;
}
void
DechunkIstream::_Read()
{
const ScopePoolRef ref(GetPool() TRACE_ARGS);
had_output = false;
do {
had_input = false;
input.Read();
} while (input.IsDefined() && had_input && !had_output);
}
void
DechunkIstream::_Close()
{
assert(!eof);
assert(!closed);
closed = true;
input.ClearAndClose();
Destroy();
}
/*
* constructor
*
*/
Istream *
istream_dechunk_new(struct pool *pool, Istream &input,
DechunkHandler &dechunk_handler)
{
return NewIstream<DechunkIstream>(*pool, input, dechunk_handler);
}
bool
istream_dechunk_check_verbatim(Istream &i)
{
auto *dechunk = DechunkIstream::CheckCast(i);
if (dechunk == nullptr)
/* not a DechunkIstream instance */
return false;
dechunk->SetVerbatim();
return true;
}
<|endoftext|> |
<commit_before>#pragma once
#include "physics/jacobi_coordinates.hpp"
#include <experimental/optional>
#include <iterator>
namespace principia {
namespace physics {
template<typename Frame>
JacobiCoordinates<Frame>::JacobiCoordinates(MassiveBody const& primary) {
DegreesOfFreedom<PrimocentricFrame> motionless_origin = {
PrimocentricFrame::origin, Velocity<PrimocentricFrame>()};
primocentric_dof_.emplace_back(motionless_origin);
system_barycentre_.Add(primocentric_dof_.back(),
primary.gravitational_parameter());
}
template<typename Frame>
void JacobiCoordinates<Frame>::Add(
MassiveBody const& body,
RelativeDegreesOfFreedom<Frame> const& dof_wrt_system) {
primocentric_dof_.emplace_back(system_barycentre_.Get() +
id_fp_(dof_wrt_system));
system_barycentre_.Add(primocentric_dof_.back(),
body.gravitational_parameter());
}
template<typename Frame>
void JacobiCoordinates<Frame>::Add(
MassiveBody const& body,
KeplerianElements<Frame> const& osculating_elements_wrt_system) {
Instant const epoch;
Add(body,
KeplerOrbit<Frame>(/*primary=*/System(),
/*secondary=*/body,
osculating_elements_wrt_system,
epoch).StateVectors(epoch));
}
template<typename Frame>
MassiveBody JacobiCoordinates<Frame>::System() const {
return MassiveBody(system_barycentre_.weight());
}
template<typename Frame>
std::vector<RelativeDegreesOfFreedom<Frame>>
JacobiCoordinates<Frame>::BarycentricCoordinates() const {
std::vector<RelativeDegreesOfFreedom<Frame>> result;
DegreesOfFreedom<PrimocentricFrame> system_barycentre =
system_barycentre_.Get();
for (auto const& dof : primocentric_dof_) {
result.emplace_back(id_pf_(dof - system_barycentre));
}
return result;
}
template<typename Frame>
Identity<typename JacobiCoordinates<Frame>::PrimocentricFrame, Frame> const
JacobiCoordinates<Frame>::id_pf_;
template<typename Frame>
Identity<Frame, typename JacobiCoordinates<Frame>::PrimocentricFrame> const
JacobiCoordinates<Frame>::id_fp_;
template<typename Frame>
HierarchicalSystem<Frame>::HierarchicalSystem(
not_null<std::unique_ptr<MassiveBody const>> primary)
: system_(std::move(primary)) {
subsystems_[system_.primary.get()] = &system_;
}
template<typename Frame>
void HierarchicalSystem<Frame>::Add(
not_null<std::unique_ptr<MassiveBody const>> body,
not_null<MassiveBody const*> const parent,
KeplerianElements<Frame> const& jacobi_osculating_elements) {
System& parent_system = *subsystems_[parent];
parent_system.satellites.emplace_back(
make_not_null_unique<Subsystem>(std::move(body)));
not_null<Subsystem*> inserted_system = parent_system.satellites.back().get();
{
not_null<MassiveBody const*> body = inserted_system->primary.get();
subsystems_[body] = inserted_system;
inserted_system->jacobi_osculating_elements = jacobi_osculating_elements;
}
}
template<typename Frame>
typename HierarchicalSystem<Frame>::BarycentricSystem
HierarchicalSystem<Frame>::Get() {
auto const semimajor_axis_less_than = [](
not_null<std::unique_ptr<Subsystem>> const& left,
not_null<std::unique_ptr<Subsystem>> const& right) -> bool {
return left->jacobi_osculating_elements.semimajor_axis <
right->jacobi_osculating_elements.semimajor_axis;
};
// Data about a |Subsystem|.
struct BarycentricSubystem {
// A |MassiveBody| with the mass of the whole subsystem.
std::unique_ptr<MassiveBody> equivalent_body;
// The bodies composing the subsystem.
std::vector<not_null<std::unique_ptr<MassiveBody const>>> bodies;
// Their |DegreesOfFreedom| with respect to the barycentre of the subsystem.
std::vector<RelativeDegreesOfFreedom<Frame>> barycentric_degrees_of_freedom;
};
std::function<BarycentricSubystem(System&)> to_barycentric =
[&semimajor_axis_less_than, &to_barycentric](System& system) {
std::sort(system.satellites.begin(),
system.satellites.end(),
semimajor_axis_less_than);
BarycentricSubystem result;
// A reference frame wherein the barycentre of |system| is motionless
// at the origin.
// TODO(egg): declaring these frame tags to make sure that local frames
// don't go out of scope is a bit cumbersome.
enum class LocalFrameTag { kFrameTag };
using SystemBarycentre = geometry::Frame<LocalFrameTag,
LocalFrameTag::kFrameTag,
/*frame_is_inertial=*/false>;
static DegreesOfFreedom<SystemBarycentre> const system_barycentre = {
SystemBarycentre::origin, Velocity<SystemBarycentre>()};
static Identity<SystemBarycentre, Frame> const id_bf;
static Identity<Frame, SystemBarycentre> const id_fb;
// Jacobi coordinates for |system|, with satellite subsystems treated
// as point masses at their barycentres.
JacobiCoordinates<Frame> jacobi_coordinates(*system.primary);
result.bodies.emplace_back(std::move(system.primary));
// The |n|th element of |satellite_degrees_of_freedom| contains the list
// of degrees of freedom of the bodies in the |n|th satellite subsystem
// with respect to their barycentre.
std::vector<std::vector<RelativeDegreesOfFreedom<Frame>>>
satellite_degrees_of_freedom;
// Fill |satellite_degrees_of_freedom|, |jacobi_coordinates|, and
// |result.bodies|.
for (auto const& subsystem : system.satellites) {
BarycentricSubystem barycentric_satellite_subsystem =
to_barycentric(*subsystem);
satellite_degrees_of_freedom.emplace_back(std::move(
barycentric_satellite_subsystem.barycentric_degrees_of_freedom));
jacobi_coordinates.Add(
*barycentric_satellite_subsystem.equivalent_body,
subsystem->jacobi_osculating_elements);
std::move(barycentric_satellite_subsystem.bodies.begin(),
barycentric_satellite_subsystem.bodies.end(),
std::back_inserter(result.bodies));
}
std::vector<DegreesOfFreedom<SystemBarycentre>>
barycentres_of_subsystems;
{
// TODO(egg): should BarycentricCoordinates return DegreesOfFreedom?
// In what frame?
auto const barycentric_coordinates =
jacobi_coordinates.BarycentricCoordinates();
for (auto const& dof : barycentric_coordinates) {
barycentres_of_subsystems.push_back(system_barycentre + id_fb(dof));
}
}
// Fill |result.barycentric_degrees_of_freedom|.
// The primary.
result.barycentric_degrees_of_freedom.emplace_back(
id_bf(barycentres_of_subsystems.front() - system_barycentre));
for (int n = 0; n < satellite_degrees_of_freedom.size(); ++n) {
// |n + 1| because the primary is at |barycentres_of_subsystems[0]|.
DegreesOfFreedom<SystemBarycentre> const subsystem_barycentre =
barycentres_of_subsystems[n + 1];
for (RelativeDegreesOfFreedom<Frame> const& body_dof_wrt_subsystem_barycentre :
satellite_degrees_of_freedom[n]) {
DegreesOfFreedom<SystemBarycentre> const body_dof =
subsystem_barycentre + id_fb(body_dof_wrt_subsystem_barycentre);
result.barycentric_degrees_of_freedom.emplace_back(
id_bf(body_dof - system_barycentre));
}
}
result.equivalent_body =
std::make_unique<MassiveBody>(jacobi_coordinates.System());
return std::move(result);
};
to_barycentric(system_);
return BarycentricSystem();
}
} // namespace physics
} // namespace principia
<commit_msg>minor cleanup<commit_after>#pragma once
#include "physics/jacobi_coordinates.hpp"
#include <experimental/optional>
#include <iterator>
namespace principia {
namespace physics {
template<typename Frame>
JacobiCoordinates<Frame>::JacobiCoordinates(MassiveBody const& primary) {
DegreesOfFreedom<PrimocentricFrame> motionless_origin = {
PrimocentricFrame::origin, Velocity<PrimocentricFrame>()};
primocentric_dof_.emplace_back(motionless_origin);
system_barycentre_.Add(primocentric_dof_.back(),
primary.gravitational_parameter());
}
template<typename Frame>
void JacobiCoordinates<Frame>::Add(
MassiveBody const& body,
RelativeDegreesOfFreedom<Frame> const& dof_wrt_system) {
primocentric_dof_.emplace_back(system_barycentre_.Get() +
id_fp_(dof_wrt_system));
system_barycentre_.Add(primocentric_dof_.back(),
body.gravitational_parameter());
}
template<typename Frame>
void JacobiCoordinates<Frame>::Add(
MassiveBody const& body,
KeplerianElements<Frame> const& osculating_elements_wrt_system) {
Instant const epoch;
Add(body,
KeplerOrbit<Frame>(/*primary=*/System(),
/*secondary=*/body,
osculating_elements_wrt_system,
epoch).StateVectors(epoch));
}
template<typename Frame>
MassiveBody JacobiCoordinates<Frame>::System() const {
return MassiveBody(system_barycentre_.weight());
}
template<typename Frame>
std::vector<RelativeDegreesOfFreedom<Frame>>
JacobiCoordinates<Frame>::BarycentricCoordinates() const {
std::vector<RelativeDegreesOfFreedom<Frame>> result;
DegreesOfFreedom<PrimocentricFrame> system_barycentre =
system_barycentre_.Get();
for (auto const& dof : primocentric_dof_) {
result.emplace_back(id_pf_(dof - system_barycentre));
}
return result;
}
template<typename Frame>
Identity<typename JacobiCoordinates<Frame>::PrimocentricFrame, Frame> const
JacobiCoordinates<Frame>::id_pf_;
template<typename Frame>
Identity<Frame, typename JacobiCoordinates<Frame>::PrimocentricFrame> const
JacobiCoordinates<Frame>::id_fp_;
template<typename Frame>
HierarchicalSystem<Frame>::HierarchicalSystem(
not_null<std::unique_ptr<MassiveBody const>> primary)
: system_(std::move(primary)) {
subsystems_[system_.primary.get()] = &system_;
}
template<typename Frame>
void HierarchicalSystem<Frame>::Add(
not_null<std::unique_ptr<MassiveBody const>> body,
not_null<MassiveBody const*> const parent,
KeplerianElements<Frame> const& jacobi_osculating_elements) {
System& parent_system = *subsystems_[parent];
parent_system.satellites.emplace_back(
make_not_null_unique<Subsystem>(std::move(body)));
not_null<Subsystem*> inserted_system = parent_system.satellites.back().get();
{
not_null<MassiveBody const*> body = inserted_system->primary.get();
subsystems_[body] = inserted_system;
inserted_system->jacobi_osculating_elements = jacobi_osculating_elements;
}
}
template<typename Frame>
typename HierarchicalSystem<Frame>::BarycentricSystem
HierarchicalSystem<Frame>::Get() {
auto const semimajor_axis_less_than = [](
not_null<std::unique_ptr<Subsystem>> const& left,
not_null<std::unique_ptr<Subsystem>> const& right) -> bool {
return left->jacobi_osculating_elements.semimajor_axis <
right->jacobi_osculating_elements.semimajor_axis;
};
// Data about a |Subsystem|.
struct BarycentricSubystem {
// A |MassiveBody| with the mass of the whole subsystem.
std::unique_ptr<MassiveBody> equivalent_body;
// The bodies composing the subsystem.
std::vector<not_null<std::unique_ptr<MassiveBody const>>> bodies;
// Their |DegreesOfFreedom| with respect to the barycentre of the subsystem.
std::vector<RelativeDegreesOfFreedom<Frame>> barycentric_degrees_of_freedom;
};
std::function<BarycentricSubystem(System&)> to_barycentric =
[&semimajor_axis_less_than, &to_barycentric](System& system) {
std::sort(system.satellites.begin(),
system.satellites.end(),
semimajor_axis_less_than);
BarycentricSubystem result;
// A reference frame wherein the barycentre of |system| is motionless
// at the origin.
// TODO(egg): declaring these frame tags to make sure that local frames
// don't go out of scope is a bit cumbersome.
enum class LocalFrameTag { kFrameTag };
using SystemBarycentre = geometry::Frame<LocalFrameTag,
LocalFrameTag::kFrameTag,
/*frame_is_inertial=*/false>;
static DegreesOfFreedom<SystemBarycentre> const system_barycentre = {
SystemBarycentre::origin, Velocity<SystemBarycentre>()};
static Identity<SystemBarycentre, Frame> const id_bf;
static Identity<Frame, SystemBarycentre> const id_fb;
// Jacobi coordinates for |system|, with satellite subsystems treated
// as point masses at their barycentres.
JacobiCoordinates<Frame> jacobi_coordinates(*system.primary);
result.bodies.emplace_back(std::move(system.primary));
// The |n|th element of |satellite_degrees_of_freedom| contains the list
// of degrees of freedom of the bodies in the |n|th satellite subsystem
// with respect to their barycentre.
std::vector<std::vector<RelativeDegreesOfFreedom<Frame>>>
satellite_degrees_of_freedom;
// Fill |satellite_degrees_of_freedom|, |jacobi_coordinates|, and
// |result.bodies|.
for (auto const& subsystem : system.satellites) {
BarycentricSubystem barycentric_satellite_subsystem =
to_barycentric(*subsystem);
satellite_degrees_of_freedom.emplace_back(std::move(
barycentric_satellite_subsystem.barycentric_degrees_of_freedom));
jacobi_coordinates.Add(
*barycentric_satellite_subsystem.equivalent_body,
subsystem->jacobi_osculating_elements);
std::move(barycentric_satellite_subsystem.bodies.begin(),
barycentric_satellite_subsystem.bodies.end(),
std::back_inserter(result.bodies));
}
std::vector<DegreesOfFreedom<SystemBarycentre>>
barycentres_of_subsystems;
{
// TODO(egg): should BarycentricCoordinates return DegreesOfFreedom?
// In what frame?
auto const barycentric_coordinates =
jacobi_coordinates.BarycentricCoordinates();
for (auto const& barycentric_dof : barycentric_coordinates) {
barycentres_of_subsystems.push_back(system_barycentre +
id_fb(barycentric_dof));
}
}
// Fill |result.barycentric_degrees_of_freedom|.
// The primary.
result.barycentric_degrees_of_freedom.emplace_back(
id_bf(barycentres_of_subsystems.front() - system_barycentre));
// The bodies in satellite subsystems.
for (int n = 0; n < satellite_degrees_of_freedom.size(); ++n) {
// |n + 1| because the primary is at |barycentres_of_subsystems[0]|.
DegreesOfFreedom<SystemBarycentre> const subsystem_barycentre =
barycentres_of_subsystems[n + 1];
for (auto const& body_dof_wrt_subsystem_barycentre :
satellite_degrees_of_freedom[n]) {
DegreesOfFreedom<SystemBarycentre> const body_dof =
subsystem_barycentre + id_fb(body_dof_wrt_subsystem_barycentre);
result.barycentric_degrees_of_freedom.emplace_back(
id_bf(body_dof - system_barycentre));
}
}
result.equivalent_body =
std::make_unique<MassiveBody>(jacobi_coordinates.System());
return std::move(result);
};
to_barycentric(system_);
return BarycentricSystem();
}
} // namespace physics
} // namespace principia
<|endoftext|> |
<commit_before>/*
* Part of HTTPP.
*
* Distributed under the 3-clause BSD licence (See LICENCE.TXT file at the
* project root).
*
* Copyright (c) 2014 Thomas Sanchez. All rights reserved.
*
*/
#include "Connection.hpp"
#include <curl/curl.h>
#include <memory>
#include <iostream>
#include <vector>
#include <thread>
#include <boost/log/trivial.hpp>
#include <boost/asio.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/exception_ptr.hpp>
#include "httpp/http/Protocol.hpp"
#include "httpp/http/client/Request.hpp"
#include "httpp/http/client/Response.hpp"
#include "httpp/utils/Exception.hpp"
#include "Manager.hpp"
namespace HTTPP {
namespace HTTP {
namespace client {
namespace detail {
Connection::Connection(Manager& manager, boost::asio::io_service& service)
: handler(manager)
, handle(curl_easy_init())
, service(service)
{
if (!handle)
{
throw std::runtime_error("Cannot initialize curl handle");
}
}
Connection::~Connection()
{
if (http_headers)
{
curl_slist_free_all(http_headers);
}
if (handle)
{
curl_easy_cleanup(handle);
handle = nullptr;
}
if (!cancelled && !result_notified)
{
try
{
BOOST_LOG_TRIVIAL(error)
<< "Destroy a not completed connection: " << this;
complete(std::make_exception_ptr(
std::runtime_error("Destroy a non completed connection")));
}
catch (const std::exception& ex)
{
BOOST_LOG_TRIVIAL(error)
<< "Error happened completing the connection: " << ex.what();
}
}
}
void Connection::init(std::map<curl_socket_t, boost::asio::ip::tcp::socket*>& sockets)
{
if (!result_notified)
{
throw std::runtime_error("Recycle a not completed connection");
}
curl_easy_reset(handle);
this->sockets = std::addressof(sockets);
conn_setopt(CURLOPT_HEADERFUNCTION, &writeHd);
conn_setopt(CURLOPT_WRITEHEADER, this);
conn_setopt(CURLOPT_WRITEFUNCTION, &writefn);
conn_setopt(CURLOPT_WRITEDATA, this);
conn_setopt(CURLOPT_ERRORBUFFER, this->error_buffer);
conn_setopt(CURLOPT_PRIVATE, this);
conn_setopt(CURLOPT_OPENSOCKETDATA, this);
conn_setopt(CURLOPT_OPENSOCKETFUNCTION, &opensocket);
conn_setopt(CURLOPT_CLOSESOCKETDATA, this->sockets);
conn_setopt(CURLOPT_CLOSESOCKETFUNCTION, &closesocket);
conn_setopt(CURLOPT_ERRORBUFFER, this->error_buffer);
conn_setopt(CURLOPT_PRIVATE, this);
if (http_headers)
{
curl_slist_free_all(http_headers);
http_headers = nullptr;
}
expect_continue = false;
header.clear();
buffer.clear();
promise = std::promise<client::Response>();
completion_handler = CompletionHandler();
response = Response();
poll_action = 0;
}
Connection::ConnectionPtr
Connection::createConnection(Manager& manager, boost::asio::io_service& service)
{
return std::make_shared<Connection>(manager, service);
}
size_t Connection::writeHd(char* buffer, size_t size, size_t nmemb, void* userdata)
{
Connection* conn = (Connection*)userdata;
auto actual_size = size * nmemb;
conn->header.insert(std::end(conn->header), buffer, buffer + actual_size);
return actual_size;
}
size_t Connection::writefn(char* buffer, size_t size, size_t nmemb, void* userdata)
{
Connection* conn = (Connection*)userdata;
auto actual_size = size * nmemb;
conn->buffer.insert(std::end(conn->buffer), buffer, buffer + actual_size);
return actual_size;
}
curl_socket_t Connection::opensocket(void* clientp,
curlsocktype purpose,
struct curl_sockaddr* address)
{
Connection* conn = (Connection*)clientp;
if (purpose == CURLSOCKTYPE_IPCXN)
{
boost::system::error_code ec;
boost::asio::ip::tcp::socket* socket =
new boost::asio::ip::tcp::socket(conn->service);
if (address->family == AF_INET)
{
socket->open(boost::asio::ip::tcp::v4(), ec);
}
else
{
socket->open(boost::asio::ip::tcp::v6(), ec);
}
if (ec)
{
BOOST_LOG_TRIVIAL(error)
<< "Cannot open a socket: " << ec.message();
return CURL_SOCKET_BAD;
}
auto handle = socket->native_handle();
(*conn->sockets)[handle] = socket;
return handle;
}
return CURL_SOCKET_BAD;
}
int Connection::closesocket(void* clientp, curl_socket_t curl_socket)
{
std::map<curl_socket_t, boost::asio::ip::tcp::socket*>* sockets;
sockets = (decltype(sockets)) clientp;
auto it = sockets->find(curl_socket);
if (it == std::end(*sockets))
{
BOOST_LOG_TRIVIAL(error) << "Cannot find a socket to close";
return 1;
}
delete it->second;
sockets->erase(it);
return 0;
}
void Connection::setSocket(curl_socket_t curl_socket)
{
auto it = sockets->find(curl_socket);
if (it == std::end(*sockets))
{
throw std::runtime_error("Cannot find socket: " +
std::to_string(curl_socket));
}
socket = it->second;
}
void Connection::configureRequest(HTTPP::HTTP::Method method)
{
switch (method)
{
case HTTPP::HTTP::Method::GET:
conn_setopt(CURLOPT_HTTPGET, 1L);
break;
case HTTPP::HTTP::Method::POST:
conn_setopt(CURLOPT_POST, 1L);
break;
case HTTPP::HTTP::Method::HEAD:
conn_setopt(CURLOPT_NOBODY, 1L);
break;
case HTTPP::HTTP::Method::PUT:
case HTTPP::HTTP::Method::DELETE_:
case HTTPP::HTTP::Method::OPTIONS:
case HTTPP::HTTP::Method::TRACE:
case HTTPP::HTTP::Method::CONNECT:
std::string method_str = to_string(method);
conn_setopt(CURLOPT_CUSTOMREQUEST, method_str.data());
break;
}
if (!request.query_params_.empty())
{
std::string url = request.url_ + "?";
bool add_sep = false;
for (const auto& query_param : request.query_params_)
{
if (add_sep)
{
url += "&";
}
url += query_param.first + "=" + query_param.second;
add_sep = true;
}
conn_setopt(CURLOPT_URL, url.data());
}
else
{
conn_setopt(CURLOPT_URL, request.url_.data());
}
if (request.follow_redirect_)
{
conn_setopt(CURLOPT_FOLLOWLOCATION, 1L);
conn_setopt(CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
}
if (!request.post_params_.empty() && !request.content_.empty())
{
throw std::runtime_error(
"Cannot mix multipart and x-formurl-encoded post data");
}
struct curl_httppost* post = NULL;
struct curl_httppost* last = NULL;
if (!request.post_params_.empty())
{
for (const auto& e : request.post_params_)
{
curl_formadd(&post,
&last,
CURLFORM_COPYNAME,
e.first.data(),
CURLFORM_COPYCONTENTS,
e.second.data(),
CURLFORM_END);
}
conn_setopt(CURLOPT_HTTPPOST, post);
expect_continue = true;
}
if (!request.content_.empty())
{
conn_setopt(CURLOPT_POSTFIELDS, request.content_.data());
conn_setopt(CURLOPT_POSTFIELDSIZE, request.content_.size());
}
conn_setopt(CURLOPT_NOSIGNAL, 1L);
// only on curl > 7.25, disable it for now
//conn_setopt(CURLOPT_TCP_KEEPALIVE, 1L);
if (!request.http_headers_.empty())
{
http_headers = nullptr;
for (const auto& h : request.http_headers_)
{
http_headers = curl_slist_append(
http_headers, (h.first + ": " + h.second).data());
}
conn_setopt(CURLOPT_HTTPHEADER, http_headers);
}
cancelled = false;
result_notified = false;
}
void Connection::cancel()
{
bool expected = false;
if (cancelled.compare_exchange_strong(expected, true))
{
handler.cancelConnection(shared_from_this());
}
else
{
BOOST_LOG_TRIVIAL(warning) << "Connection already cancelled";
}
}
void Connection::buildResponse(CURLcode code)
{
if (code != CURLE_OK)
{
complete(std::make_exception_ptr(std::runtime_error(
curl_easy_strerror(code) + std::string(this->error_buffer))));
return;
}
try
{
response.code = static_cast<HTTPP::HTTP::HttpCode>(
conn_getinfo<long>(CURLINFO_RESPONSE_CODE));
response.request = std::move(request);
long redirection = 0;
if (request.follow_redirect_)
{
redirection = conn_getinfo<long>(CURLINFO_REDIRECT_COUNT);
}
redirection += expect_continue ? 1 : 0;
while (redirection)
{
auto begin = std::begin(header);
auto end = std::end(header);
auto it = std::search(begin,
end,
std::begin(HEADER_BODY_SEP),
std::end(HEADER_BODY_SEP));
if (it != end)
{
header.erase(std::begin(header), it + 4);
}
--redirection;
}
response.body.swap(buffer);
parseCurlResponseHeader(header, response);
complete();
}
catch (const std::exception& exc)
{
BOOST_LOG_TRIVIAL(error)
<< "Error when building the response: " << exc.what();
complete(std::current_exception());
return;
}
}
void Connection::complete(std::exception_ptr ex)
{
bool expected = false;
if (!result_notified.compare_exchange_strong(expected, true))
{
BOOST_LOG_TRIVIAL(error)
<< "Response already notified, cancel notification";
return;
}
if (ex)
{
promise.set_exception(ex);
}
else
{
promise.set_value(std::move(response));
}
if (completion_handler)
{
auto ptr = shared_from_this();
dispatch->post([ptr]
{ ptr->completion_handler(ptr->promise.get_future()); });
}
}
} // namespace detail
} // namespace client
} // namespace HTTP
} // namespace HTTPP
<commit_msg>Do not dispatch the completion_handler call when we call complete from the destructor<commit_after>/*
* Part of HTTPP.
*
* Distributed under the 3-clause BSD licence (See LICENCE.TXT file at the
* project root).
*
* Copyright (c) 2014 Thomas Sanchez. All rights reserved.
*
*/
#include "Connection.hpp"
#include <curl/curl.h>
#include <memory>
#include <iostream>
#include <vector>
#include <thread>
#include <boost/log/trivial.hpp>
#include <boost/asio.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/exception_ptr.hpp>
#include "httpp/http/Protocol.hpp"
#include "httpp/http/client/Request.hpp"
#include "httpp/http/client/Response.hpp"
#include "httpp/utils/Exception.hpp"
#include "Manager.hpp"
namespace HTTPP {
namespace HTTP {
namespace client {
namespace detail {
Connection::Connection(Manager& manager, boost::asio::io_service& service)
: handler(manager)
, handle(curl_easy_init())
, service(service)
{
if (!handle)
{
throw std::runtime_error("Cannot initialize curl handle");
}
}
Connection::~Connection()
{
if (http_headers)
{
curl_slist_free_all(http_headers);
}
if (handle)
{
curl_easy_cleanup(handle);
handle = nullptr;
}
dispatch = nullptr;
if (!cancelled && !result_notified)
{
try
{
BOOST_LOG_TRIVIAL(error)
<< "Destroy a not completed connection: " << this;
complete(std::make_exception_ptr(
std::runtime_error("Destroy a non completed connection")));
}
catch (const std::exception& ex)
{
BOOST_LOG_TRIVIAL(error)
<< "Error happened completing the connection: " << ex.what();
}
}
}
void Connection::init(std::map<curl_socket_t, boost::asio::ip::tcp::socket*>& sockets)
{
if (!result_notified)
{
throw std::runtime_error("Recycle a not completed connection");
}
curl_easy_reset(handle);
this->sockets = std::addressof(sockets);
conn_setopt(CURLOPT_HEADERFUNCTION, &writeHd);
conn_setopt(CURLOPT_WRITEHEADER, this);
conn_setopt(CURLOPT_WRITEFUNCTION, &writefn);
conn_setopt(CURLOPT_WRITEDATA, this);
conn_setopt(CURLOPT_ERRORBUFFER, this->error_buffer);
conn_setopt(CURLOPT_PRIVATE, this);
conn_setopt(CURLOPT_OPENSOCKETDATA, this);
conn_setopt(CURLOPT_OPENSOCKETFUNCTION, &opensocket);
conn_setopt(CURLOPT_CLOSESOCKETDATA, this->sockets);
conn_setopt(CURLOPT_CLOSESOCKETFUNCTION, &closesocket);
conn_setopt(CURLOPT_ERRORBUFFER, this->error_buffer);
conn_setopt(CURLOPT_PRIVATE, this);
if (http_headers)
{
curl_slist_free_all(http_headers);
http_headers = nullptr;
}
expect_continue = false;
header.clear();
buffer.clear();
promise = std::promise<client::Response>();
completion_handler = CompletionHandler();
response = Response();
poll_action = 0;
}
Connection::ConnectionPtr
Connection::createConnection(Manager& manager, boost::asio::io_service& service)
{
return std::make_shared<Connection>(manager, service);
}
size_t Connection::writeHd(char* buffer, size_t size, size_t nmemb, void* userdata)
{
Connection* conn = (Connection*)userdata;
auto actual_size = size * nmemb;
conn->header.insert(std::end(conn->header), buffer, buffer + actual_size);
return actual_size;
}
size_t Connection::writefn(char* buffer, size_t size, size_t nmemb, void* userdata)
{
Connection* conn = (Connection*)userdata;
auto actual_size = size * nmemb;
conn->buffer.insert(std::end(conn->buffer), buffer, buffer + actual_size);
return actual_size;
}
curl_socket_t Connection::opensocket(void* clientp,
curlsocktype purpose,
struct curl_sockaddr* address)
{
Connection* conn = (Connection*)clientp;
if (purpose == CURLSOCKTYPE_IPCXN)
{
boost::system::error_code ec;
boost::asio::ip::tcp::socket* socket =
new boost::asio::ip::tcp::socket(conn->service);
if (address->family == AF_INET)
{
socket->open(boost::asio::ip::tcp::v4(), ec);
}
else
{
socket->open(boost::asio::ip::tcp::v6(), ec);
}
if (ec)
{
BOOST_LOG_TRIVIAL(error)
<< "Cannot open a socket: " << ec.message();
return CURL_SOCKET_BAD;
}
auto handle = socket->native_handle();
(*conn->sockets)[handle] = socket;
return handle;
}
return CURL_SOCKET_BAD;
}
int Connection::closesocket(void* clientp, curl_socket_t curl_socket)
{
std::map<curl_socket_t, boost::asio::ip::tcp::socket*>* sockets;
sockets = (decltype(sockets)) clientp;
auto it = sockets->find(curl_socket);
if (it == std::end(*sockets))
{
BOOST_LOG_TRIVIAL(error) << "Cannot find a socket to close";
return 1;
}
delete it->second;
sockets->erase(it);
return 0;
}
void Connection::setSocket(curl_socket_t curl_socket)
{
auto it = sockets->find(curl_socket);
if (it == std::end(*sockets))
{
throw std::runtime_error("Cannot find socket: " +
std::to_string(curl_socket));
}
socket = it->second;
}
void Connection::configureRequest(HTTPP::HTTP::Method method)
{
switch (method)
{
case HTTPP::HTTP::Method::GET:
conn_setopt(CURLOPT_HTTPGET, 1L);
break;
case HTTPP::HTTP::Method::POST:
conn_setopt(CURLOPT_POST, 1L);
break;
case HTTPP::HTTP::Method::HEAD:
conn_setopt(CURLOPT_NOBODY, 1L);
break;
case HTTPP::HTTP::Method::PUT:
case HTTPP::HTTP::Method::DELETE_:
case HTTPP::HTTP::Method::OPTIONS:
case HTTPP::HTTP::Method::TRACE:
case HTTPP::HTTP::Method::CONNECT:
std::string method_str = to_string(method);
conn_setopt(CURLOPT_CUSTOMREQUEST, method_str.data());
break;
}
if (!request.query_params_.empty())
{
std::string url = request.url_ + "?";
bool add_sep = false;
for (const auto& query_param : request.query_params_)
{
if (add_sep)
{
url += "&";
}
url += query_param.first + "=" + query_param.second;
add_sep = true;
}
conn_setopt(CURLOPT_URL, url.data());
}
else
{
conn_setopt(CURLOPT_URL, request.url_.data());
}
if (request.follow_redirect_)
{
conn_setopt(CURLOPT_FOLLOWLOCATION, 1L);
conn_setopt(CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);
}
if (!request.post_params_.empty() && !request.content_.empty())
{
throw std::runtime_error(
"Cannot mix multipart and x-formurl-encoded post data");
}
struct curl_httppost* post = NULL;
struct curl_httppost* last = NULL;
if (!request.post_params_.empty())
{
for (const auto& e : request.post_params_)
{
curl_formadd(&post,
&last,
CURLFORM_COPYNAME,
e.first.data(),
CURLFORM_COPYCONTENTS,
e.second.data(),
CURLFORM_END);
}
conn_setopt(CURLOPT_HTTPPOST, post);
expect_continue = true;
}
if (!request.content_.empty())
{
conn_setopt(CURLOPT_POSTFIELDS, request.content_.data());
conn_setopt(CURLOPT_POSTFIELDSIZE, request.content_.size());
}
conn_setopt(CURLOPT_NOSIGNAL, 1L);
// only on curl > 7.25, disable it for now
//conn_setopt(CURLOPT_TCP_KEEPALIVE, 1L);
if (!request.http_headers_.empty())
{
http_headers = nullptr;
for (const auto& h : request.http_headers_)
{
http_headers = curl_slist_append(
http_headers, (h.first + ": " + h.second).data());
}
conn_setopt(CURLOPT_HTTPHEADER, http_headers);
}
cancelled = false;
result_notified = false;
}
void Connection::cancel()
{
bool expected = false;
if (cancelled.compare_exchange_strong(expected, true))
{
handler.cancelConnection(shared_from_this());
}
else
{
BOOST_LOG_TRIVIAL(warning) << "Connection already cancelled";
}
}
void Connection::buildResponse(CURLcode code)
{
if (code != CURLE_OK)
{
complete(std::make_exception_ptr(std::runtime_error(
curl_easy_strerror(code) + std::string(this->error_buffer))));
return;
}
try
{
response.code = static_cast<HTTPP::HTTP::HttpCode>(
conn_getinfo<long>(CURLINFO_RESPONSE_CODE));
response.request = std::move(request);
long redirection = 0;
if (request.follow_redirect_)
{
redirection = conn_getinfo<long>(CURLINFO_REDIRECT_COUNT);
}
redirection += expect_continue ? 1 : 0;
while (redirection)
{
auto begin = std::begin(header);
auto end = std::end(header);
auto it = std::search(begin,
end,
std::begin(HEADER_BODY_SEP),
std::end(HEADER_BODY_SEP));
if (it != end)
{
header.erase(std::begin(header), it + 4);
}
--redirection;
}
response.body.swap(buffer);
parseCurlResponseHeader(header, response);
complete();
}
catch (const std::exception& exc)
{
BOOST_LOG_TRIVIAL(error)
<< "Error when building the response: " << exc.what();
complete(std::current_exception());
return;
}
}
void Connection::complete(std::exception_ptr ex)
{
bool expected = false;
if (!result_notified.compare_exchange_strong(expected, true))
{
BOOST_LOG_TRIVIAL(error)
<< "Response already notified, cancel notification";
return;
}
if (ex)
{
promise.set_exception(ex);
}
else
{
promise.set_value(std::move(response));
}
if (completion_handler)
{
if (dispatch)
{
auto ptr = shared_from_this();
dispatch->post([ptr]
{ ptr->completion_handler(ptr->promise.get_future()); });
}
else
{
completion_handler(promise.get_future());
}
}
}
} // namespace detail
} // namespace client
} // namespace HTTP
} // namespace HTTPP
<|endoftext|> |
<commit_before>// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "platform/globals.h"
#if defined(HOST_OS_WINDOWS)
#include "bin/file_system_watcher.h"
#include <WinIoCtl.h> // NOLINT
#include "bin/builtin.h"
#include "bin/eventhandler.h"
#include "bin/utils.h"
#include "bin/utils_win.h"
#include "platform/syslog.h"
namespace dart {
namespace bin {
bool FileSystemWatcher::IsSupported() {
return true;
}
intptr_t FileSystemWatcher::Init() {
return 0;
}
void FileSystemWatcher::Close(intptr_t id) {
USE(id);
}
intptr_t FileSystemWatcher::WatchPath(intptr_t id,
Namespace* namespc,
const char* path,
int events,
bool recursive) {
USE(id);
Utf8ToWideScope name(path);
HANDLE dir = CreateFileW(
name.wide(), FILE_LIST_DIRECTORY,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, NULL);
if (dir == INVALID_HANDLE_VALUE) {
return -1;
}
int list_events = 0;
if ((events & (kCreate | kMove | kDelete)) != 0) {
list_events |= FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME;
}
if ((events & kModifyContent) != 0) {
list_events |= FILE_NOTIFY_CHANGE_LAST_WRITE;
}
DirectoryWatchHandle* handle =
new DirectoryWatchHandle(dir, list_events, recursive);
// Issue a read directly, to be sure events are tracked from now on. This is
// okay, since in Dart, we create the socket and start reading immidiately.
handle->EnsureInitialized(EventHandler::delegate());
handle->IssueRead();
return reinterpret_cast<intptr_t>(handle);
}
void FileSystemWatcher::UnwatchPath(intptr_t id, intptr_t path_id) {
USE(id);
DirectoryWatchHandle* handle =
reinterpret_cast<DirectoryWatchHandle*>(path_id);
handle->Stop();
}
intptr_t FileSystemWatcher::GetSocketId(intptr_t id, intptr_t path_id) {
USE(id);
return path_id;
}
Dart_Handle FileSystemWatcher::ReadEvents(intptr_t id, intptr_t path_id) {
USE(id);
const intptr_t kEventSize = sizeof(FILE_NOTIFY_INFORMATION);
DirectoryWatchHandle* dir = reinterpret_cast<DirectoryWatchHandle*>(path_id);
intptr_t available = dir->Available();
intptr_t max_count = available / kEventSize + 1;
Dart_Handle events = Dart_NewList(max_count);
uint8_t* buffer = Dart_ScopeAllocate(available);
intptr_t bytes = dir->Read(buffer, available);
intptr_t offset = 0;
intptr_t i = 0;
while (offset < bytes) {
FILE_NOTIFY_INFORMATION* e =
reinterpret_cast<FILE_NOTIFY_INFORMATION*>(buffer + offset);
Dart_Handle event = Dart_NewList(5);
int mask = 0;
if (e->Action == FILE_ACTION_ADDED) {
mask |= kCreate;
}
if (e->Action == FILE_ACTION_REMOVED) {
mask |= kDelete;
}
if (e->Action == FILE_ACTION_MODIFIED) {
mask |= kModifyContent;
}
if (e->Action == FILE_ACTION_RENAMED_OLD_NAME) {
mask |= kMove;
}
if (e->Action == FILE_ACTION_RENAMED_NEW_NAME) {
mask |= kMove;
}
Dart_ListSetAt(event, 0, Dart_NewInteger(mask));
// Move events come in pairs. Just 'enable' by default.
Dart_ListSetAt(event, 1, Dart_NewInteger(1));
Dart_ListSetAt(
event, 2,
Dart_NewStringFromUTF16(reinterpret_cast<uint16_t*>(e->FileName),
e->FileNameLength / 2));
Dart_ListSetAt(event, 3, Dart_NewBoolean(true));
Dart_ListSetAt(event, 4, Dart_NewInteger(path_id));
Dart_ListSetAt(events, i, event);
i++;
if (e->NextEntryOffset == 0) {
break;
}
offset += e->NextEntryOffset;
}
return events;
}
} // namespace bin
} // namespace dart
#endif // defined(HOST_OS_WINDOWS)
<commit_msg>[io/watcher] Fix crash in file event watcher functionality on Windows.<commit_after>// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "platform/globals.h"
#if defined(HOST_OS_WINDOWS)
#include "bin/file_system_watcher.h"
#include <WinIoCtl.h> // NOLINT
#include "bin/builtin.h"
#include "bin/eventhandler.h"
#include "bin/utils.h"
#include "bin/utils_win.h"
#include "platform/syslog.h"
namespace dart {
namespace bin {
bool FileSystemWatcher::IsSupported() {
return true;
}
intptr_t FileSystemWatcher::Init() {
return 0;
}
void FileSystemWatcher::Close(intptr_t id) {
USE(id);
}
intptr_t FileSystemWatcher::WatchPath(intptr_t id,
Namespace* namespc,
const char* path,
int events,
bool recursive) {
USE(id);
Utf8ToWideScope name(path);
HANDLE dir = CreateFileW(
name.wide(), FILE_LIST_DIRECTORY,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, NULL);
if (dir == INVALID_HANDLE_VALUE) {
return -1;
}
int list_events = 0;
if ((events & (kCreate | kMove | kDelete)) != 0) {
list_events |= FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME;
}
if ((events & kModifyContent) != 0) {
list_events |= FILE_NOTIFY_CHANGE_LAST_WRITE;
}
DirectoryWatchHandle* handle =
new DirectoryWatchHandle(dir, list_events, recursive);
// Issue a read directly, to be sure events are tracked from now on. This is
// okay, since in Dart, we create the socket and start reading immidiately.
handle->EnsureInitialized(EventHandler::delegate());
handle->IssueRead();
return reinterpret_cast<intptr_t>(handle);
}
void FileSystemWatcher::UnwatchPath(intptr_t id, intptr_t path_id) {
USE(id);
DirectoryWatchHandle* handle =
reinterpret_cast<DirectoryWatchHandle*>(path_id);
handle->Stop();
}
intptr_t FileSystemWatcher::GetSocketId(intptr_t id, intptr_t path_id) {
USE(id);
return path_id;
}
Dart_Handle FileSystemWatcher::ReadEvents(intptr_t id, intptr_t path_id) {
USE(id);
const intptr_t kEventSize = sizeof(FILE_NOTIFY_INFORMATION);
DirectoryWatchHandle* dir = reinterpret_cast<DirectoryWatchHandle*>(path_id);
intptr_t available = dir->Available();
if (available <= 0) {
return Dart_NewList(0);
}
intptr_t max_count = available / kEventSize + 1;
Dart_Handle events = Dart_NewList(max_count);
uint8_t* buffer = Dart_ScopeAllocate(available);
intptr_t bytes = dir->Read(buffer, available);
intptr_t offset = 0;
intptr_t i = 0;
while (offset < bytes) {
FILE_NOTIFY_INFORMATION* e =
reinterpret_cast<FILE_NOTIFY_INFORMATION*>(buffer + offset);
Dart_Handle event = Dart_NewList(5);
int mask = 0;
if (e->Action == FILE_ACTION_ADDED) {
mask |= kCreate;
}
if (e->Action == FILE_ACTION_REMOVED) {
mask |= kDelete;
}
if (e->Action == FILE_ACTION_MODIFIED) {
mask |= kModifyContent;
}
if (e->Action == FILE_ACTION_RENAMED_OLD_NAME) {
mask |= kMove;
}
if (e->Action == FILE_ACTION_RENAMED_NEW_NAME) {
mask |= kMove;
}
Dart_ListSetAt(event, 0, Dart_NewInteger(mask));
// Move events come in pairs. Just 'enable' by default.
Dart_ListSetAt(event, 1, Dart_NewInteger(1));
Dart_ListSetAt(
event, 2,
Dart_NewStringFromUTF16(reinterpret_cast<uint16_t*>(e->FileName),
e->FileNameLength / 2));
Dart_ListSetAt(event, 3, Dart_NewBoolean(true));
Dart_ListSetAt(event, 4, Dart_NewInteger(path_id));
Dart_ListSetAt(events, i, event);
i++;
if (e->NextEntryOffset == 0) {
break;
}
offset += e->NextEntryOffset;
}
return events;
}
} // namespace bin
} // namespace dart
#endif // defined(HOST_OS_WINDOWS)
<|endoftext|> |
<commit_before>//
// MultiClassify.cpp
//
//
// Created by tim on 23/03/2017.
//
//
#include <fstream>
#include <memory>
#include "SingleShotDetector.hpp"
#include "MultiClassify.hpp"
#include "GraphLoader.hpp"
#include "Classifier.hpp"
#include "FaceAlign.hpp"
#include "Multibox.hpp"
#include "timer.hpp"
#include "log.hpp"
#include "tensorflow/cc/client/client_session.h"
#include "tensorflow/cc/ops/standard_ops.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/public/session.h"
using namespace ml;
using namespace image;
using namespace metrics;
using namespace tensorflow;
using namespace tensorflow::ops;
//
// Create the sesson by loading all the models
// - we need all models to load correctly so throw exceptions on failure
//
//
MultiClassify::MultiClassify(std::string root, std::string logLevel){
FILELog::ReportingLevel() = FILELog::FromString(logLevel);
LOG(INFO) << "Starting init";
inceptionSize = 299;
multiboxSize = 224;
GraphDef ssdGraphDef;
GraphDef boxGraphDef;
GraphDef classifyGraphDef;
GraphDef faceGraphDef;
std::unique_ptr<GraphLoader> graphLoader;
graphLoader.reset(new GraphLoader(root));
//load the ssd graph
std::string ssdGraphPath = "data/ssd.pb";
auto ssdLoadStatus = graphLoader->LoadGraphDef(&ssdGraphDef, ssdGraphPath);
if (!ssdLoadStatus.ok()) {
LOG(ERROR) << "Loading model failed: " << ssdLoadStatus;
throw std::exception();
}
else {
FILE_LOG(logDEBUG) << "Loaded ssd model";
}
auto ssdSessionStatus = graphLoader->InitializeSessionGraph(&ssdSession, &ssdGraphDef);
if (!ssdSessionStatus.ok()) {
LOG(ERROR) << "Starting session failed: " << ssdSessionStatus;
throw std::exception();
}
else {
FILE_LOG(logDEBUG) << "Started ssd session";
}
//finished ssd graph loading
std::string boxGraphPath = "data/multibox_model.pb";
auto multiboxLoadStatus = graphLoader->LoadGraphDef(&boxGraphDef, boxGraphPath);
if (!multiboxLoadStatus.ok()) {
LOG(ERROR) << "Loading model failed: " << multiboxLoadStatus;
throw std::exception();
}
else {
FILE_LOG(logDEBUG) << "Loaded multibox model";
}
auto multiboxSessionStatus = graphLoader->InitializeSessionGraph(&boxSession, &boxGraphDef);
if (!multiboxSessionStatus.ok()) {
LOG(ERROR) << "Starting session failed: " << multiboxSessionStatus;
throw std::exception();
}
else {
FILE_LOG(logDEBUG) << "Started multibox session";
}
//graphLoader->InitializeSessionGraph(&boxSession, &boxGraphDef);
std::string classifyGraphPath = "data/inception_v4.pb";
auto inceptionLoadStatus = graphLoader->LoadGraphDef(&classifyGraphDef, classifyGraphPath);
if (!inceptionLoadStatus.ok()) {
LOG(ERROR) << "Loading model failed: " << inceptionLoadStatus;
throw std::exception();
}
else {
FILE_LOG(logDEBUG) << "Loaded inception model";
}
auto inceptionSessionStatus = graphLoader->InitializeSessionGraph(&classifySession, &classifyGraphDef);
if (!inceptionSessionStatus.ok()) {
LOG(ERROR) << "Starting session failed: " << inceptionSessionStatus;
throw std::exception();
}
else {
FILE_LOG(logDEBUG) << "Started inception session";
}
std::string faceGraphPath = "data/face_align.pb";
auto faceLoadStatus = graphLoader->LoadGraphDef(&faceGraphDef, faceGraphPath);
if (!faceLoadStatus.ok()) {
LOG(ERROR) << "Loading model failed: " << faceLoadStatus;
throw std::exception();
}
else {
FILE_LOG(logDEBUG) << "Loaded face model";
}
auto faceSessionStatus = graphLoader->InitializeSessionGraph(&faceSession, &faceGraphDef);
if (!faceSessionStatus.ok()) {
LOG(ERROR) << "Starting session failed: " << faceSessionStatus;
throw std::exception();
}
else {
FILE_LOG(logDEBUG) << "Started face session";
}
std::string labelsFile = root + "data/inception_labels.txt";
//inception v3 "mul" "softmax"
//inception v4 "input:0" "InceptionV4/Logits/Predictions"
classifier.reset(new Classifier(labelsFile, "input:0", "InceptionV4/Logits/Predictions"));
multibox.reset(new Multibox(root));
faceAlign.reset(new FaceAlign());
std::string ssdLabelsFile = root + "data/ssd_labels.txt";
singleShotDetector.reset(new SingleShotDetector(ssdLabelsFile, &ssdSession));
imageGraph.reset(new ImageGraph());
LOG(INFO) << "Finished multiclassify init";
}
void MultiClassify::ClassifyFile(std::string fileName){
FILE_LOG(logDEBUG) << "Reading image from file: " << fileName;
auto root = tensorflow::Scope::NewRootScope();
tensorflow::Output fileReader = tensorflow::ops::ReadFile(root.WithOpName("file_reader"),
fileName);
ClientSession session(root);
std::vector<Tensor> outputs;
Status result = session.Run({}, {fileReader}, &outputs);
auto imageString = outputs[0];
auto asString = imageString.scalar<string>()();
LOG(INFO) << "Got imageString";
std::string scores = "";
std::string* json = &scores;
timestamp_t t0 = timer::get_timestamp();
Align(asString, 1, json);
LOG(INFO) << "Got align: ";
Box(asString, 1, json);
LOG(INFO) << "Got boxes: ";
Classify(asString, 1, json);
LOG(INFO) << "Got classify: ";
Detect(asString, 1, json);
LOG(INFO) << "Got detect: ";
LOG(INFO) << *json;
timestamp_t t1 = timer::get_timestamp();
double classifyTime = (t1 - t0);
LOG(INFO) << "Classify time was: " << classifyTime;
}
int MultiClassify::Align(std::string byteString, int encoding, std::string* json){
if ( sizeof(byteString)==0 ){
FILE_LOG(logWARNING) << "No data in byteString";
return -1;
}
std::vector<Tensor> imageTensors;
auto importStatus = imageGraph->ProccessImage(byteString, encoding, &imageTensors);
LOG(INFO) << "Processed align image";
int width = imageTensors[0].shape().dim_size(2);
int height = imageTensors[0].shape().dim_size(1);
float maximum = std::max(width, height);
if (maximum>600){
float scaling = 600.0 / maximum;
int newWidth = (int)(width * scaling);
int newHeight = (int)(height * scaling);
LOG(INFO) << "Scaling to max size " << newWidth << ", " << newHeight;
Scope localRoot = Scope::NewRootScope();
std::vector<Tensor> resizeOutputs;
auto imageOutput = ResizeBilinear(localRoot,
imageTensors[0],
{newHeight, newWidth});
FILE_LOG(logDEBUG) << "Scaling to max size " << newWidth << ", " << newHeight;
ClientSession session(localRoot);
auto scaleStatus = session.Run({imageOutput}, &resizeOutputs);
imageTensors[0] = resizeOutputs[0];
}
return faceAlign -> ReadAndRun(&imageTensors, json, &faceSession);
}
int MultiClassify::Classify(std::string byteString, int encoding, std::string* json){
if ( sizeof(byteString)==0 ){
FILE_LOG(logWARNING) << "No data in byteString";
return -1;
}
std::vector<Tensor> imageTensors;
auto importStatus = imageGraph->ProccessImage(byteString, encoding, &imageTensors);
Scope localRoot = Scope::NewRootScope();
std::vector<Tensor> resizeOutputs;
auto imageOutput = ResizeBilinear(localRoot,
imageTensors[0],
{inceptionSize, inceptionSize});
FILE_LOG(logDEBUG) << "Scaling to inception input: " << imageTensors[0].DebugString();
ClientSession session(localRoot);
auto scaleStatus = session.Run({imageOutput}, &resizeOutputs);
FILE_LOG(logDEBUG) << "resizeOutputs: " << resizeOutputs[0].DebugString();
return classifier -> ReadAndRun(&resizeOutputs, json, &classifySession);
}
int MultiClassify::Detect(std::string byteString, int encoding, std::string* json){
if ( sizeof(byteString)==0 ){
FILE_LOG(logWARNING) << "No data in byteString";
return -1;
}
std::vector<Tensor> imageTensors;
auto importStatus = imageGraph->ProccessImage(byteString, encoding, &imageTensors);
//do a basic dimension check on the returned image
auto imageShape = imageTensors[0].shape();
FILE_LOG(logDEBUG) << "Image dimensions: " << imageShape.dim_size(0) << ", " << imageShape.dim_size(1) << ", " << imageShape.dim_size(2);
if (imageShape.dim_size(1) == 0){
return -1;
}
Scope localRoot = Scope::NewRootScope();
std::vector<Tensor> resizeOutputs;
auto imageOutput = ResizeBilinear(localRoot,
imageTensors[0],
{inceptionSize, inceptionSize});
FILE_LOG(logDEBUG) << "Scaling to sdd input: " << imageTensors[0].DebugString();
ClientSession session(localRoot);
auto scaleStatus = session.Run({imageOutput}, &resizeOutputs);
FILE_LOG(logDEBUG) << "resizeOutputs: " << resizeOutputs[0].DebugString();
imageTensors.push_back(resizeOutputs[0]);
return singleShotDetector -> ReadAndRun(&imageTensors, json, &ssdSession);
}
int MultiClassify::Box(std::string byteString, int encoding, std::string* json){
if ( sizeof(byteString)==0 ){
FILE_LOG(logWARNING) << "No data in byteString";
return -1;
}
std::vector<Tensor> imageTensors;
auto importStatus = imageGraph->ProccessImage(byteString, encoding, &imageTensors);
Scope localRoot = Scope::NewRootScope();
ClientSession session(localRoot);
std::vector<Tensor> resizeOutputs;
auto imageOutput = ResizeBilinear(localRoot,
imageTensors[0],
{multiboxSize, multiboxSize});
FILE_LOG(logDEBUG) << "Scaling to box input: " << imageTensors[0].DebugString();
auto scaleStatus = session.Run({imageOutput}, &resizeOutputs);
imageTensors.push_back(resizeOutputs[0]);
return multibox -> ReadAndRun(&imageTensors, json, &boxSession);
}
MultiClassify::~MultiClassify(){
LOG(INFO) << "destructing";
auto closedBoxSession = boxSession->Close();
auto closedClassifySession = classifySession->Close();
auto closedFaceSession = faceSession->Close();
auto closedSsdSession = ssdSession->Close();
FILE_LOG(logDEBUG) << "Closed sessions: " << closedBoxSession << ", " << closedClassifySession << ", " << closedFaceSession << ", " << closedSsdSession;
}
<commit_msg>Image process guard<commit_after>//
// MultiClassify.cpp
//
//
// Created by tim on 23/03/2017.
//
//
#include <fstream>
#include <memory>
#include "SingleShotDetector.hpp"
#include "MultiClassify.hpp"
#include "GraphLoader.hpp"
#include "Classifier.hpp"
#include "FaceAlign.hpp"
#include "Multibox.hpp"
#include "timer.hpp"
#include "log.hpp"
#include "tensorflow/cc/client/client_session.h"
#include "tensorflow/cc/ops/standard_ops.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/public/session.h"
using namespace ml;
using namespace image;
using namespace metrics;
using namespace tensorflow;
using namespace tensorflow::ops;
//
// Create the sesson by loading all the models
// - we need all models to load correctly so throw exceptions on failure
//
//
MultiClassify::MultiClassify(std::string root, std::string logLevel){
FILELog::ReportingLevel() = FILELog::FromString(logLevel);
LOG(INFO) << "Starting init";
inceptionSize = 299;
multiboxSize = 224;
GraphDef ssdGraphDef;
GraphDef boxGraphDef;
GraphDef classifyGraphDef;
GraphDef faceGraphDef;
std::unique_ptr<GraphLoader> graphLoader;
graphLoader.reset(new GraphLoader(root));
//load the ssd graph
std::string ssdGraphPath = "data/ssd.pb";
auto ssdLoadStatus = graphLoader->LoadGraphDef(&ssdGraphDef, ssdGraphPath);
if (!ssdLoadStatus.ok()) {
LOG(ERROR) << "Loading model failed: " << ssdLoadStatus;
throw std::exception();
}
else {
FILE_LOG(logDEBUG) << "Loaded ssd model";
}
auto ssdSessionStatus = graphLoader->InitializeSessionGraph(&ssdSession, &ssdGraphDef);
if (!ssdSessionStatus.ok()) {
LOG(ERROR) << "Starting session failed: " << ssdSessionStatus;
throw std::exception();
}
else {
FILE_LOG(logDEBUG) << "Started ssd session";
}
//finished ssd graph loading
std::string boxGraphPath = "data/multibox_model.pb";
auto multiboxLoadStatus = graphLoader->LoadGraphDef(&boxGraphDef, boxGraphPath);
if (!multiboxLoadStatus.ok()) {
LOG(ERROR) << "Loading model failed: " << multiboxLoadStatus;
throw std::exception();
}
else {
FILE_LOG(logDEBUG) << "Loaded multibox model";
}
auto multiboxSessionStatus = graphLoader->InitializeSessionGraph(&boxSession, &boxGraphDef);
if (!multiboxSessionStatus.ok()) {
LOG(ERROR) << "Starting session failed: " << multiboxSessionStatus;
throw std::exception();
}
else {
FILE_LOG(logDEBUG) << "Started multibox session";
}
//graphLoader->InitializeSessionGraph(&boxSession, &boxGraphDef);
std::string classifyGraphPath = "data/inception_v4.pb";
auto inceptionLoadStatus = graphLoader->LoadGraphDef(&classifyGraphDef, classifyGraphPath);
if (!inceptionLoadStatus.ok()) {
LOG(ERROR) << "Loading model failed: " << inceptionLoadStatus;
throw std::exception();
}
else {
FILE_LOG(logDEBUG) << "Loaded inception model";
}
auto inceptionSessionStatus = graphLoader->InitializeSessionGraph(&classifySession, &classifyGraphDef);
if (!inceptionSessionStatus.ok()) {
LOG(ERROR) << "Starting session failed: " << inceptionSessionStatus;
throw std::exception();
}
else {
FILE_LOG(logDEBUG) << "Started inception session";
}
std::string faceGraphPath = "data/face_align.pb";
auto faceLoadStatus = graphLoader->LoadGraphDef(&faceGraphDef, faceGraphPath);
if (!faceLoadStatus.ok()) {
LOG(ERROR) << "Loading model failed: " << faceLoadStatus;
throw std::exception();
}
else {
FILE_LOG(logDEBUG) << "Loaded face model";
}
auto faceSessionStatus = graphLoader->InitializeSessionGraph(&faceSession, &faceGraphDef);
if (!faceSessionStatus.ok()) {
LOG(ERROR) << "Starting session failed: " << faceSessionStatus;
throw std::exception();
}
else {
FILE_LOG(logDEBUG) << "Started face session";
}
std::string labelsFile = root + "data/inception_labels.txt";
//inception v3 "mul" "softmax"
//inception v4 "input:0" "InceptionV4/Logits/Predictions"
classifier.reset(new Classifier(labelsFile, "input:0", "InceptionV4/Logits/Predictions"));
multibox.reset(new Multibox(root));
faceAlign.reset(new FaceAlign());
std::string ssdLabelsFile = root + "data/ssd_labels.txt";
singleShotDetector.reset(new SingleShotDetector(ssdLabelsFile, &ssdSession));
imageGraph.reset(new ImageGraph());
LOG(INFO) << "Finished multiclassify init";
}
void MultiClassify::ClassifyFile(std::string fileName){
FILE_LOG(logDEBUG) << "Reading image from file: " << fileName;
auto root = tensorflow::Scope::NewRootScope();
tensorflow::Output fileReader = tensorflow::ops::ReadFile(root.WithOpName("file_reader"),
fileName);
ClientSession session(root);
std::vector<Tensor> outputs;
Status result = session.Run({}, {fileReader}, &outputs);
auto imageString = outputs[0];
auto asString = imageString.scalar<string>()();
LOG(INFO) << "Got imageString";
std::string scores = "";
std::string* json = &scores;
timestamp_t t0 = timer::get_timestamp();
Align(asString, 1, json);
LOG(INFO) << "Got align: ";
Box(asString, 1, json);
LOG(INFO) << "Got boxes: ";
Classify(asString, 1, json);
LOG(INFO) << "Got classify: ";
Detect(asString, 1, json);
LOG(INFO) << "Got detect: ";
LOG(INFO) << *json;
timestamp_t t1 = timer::get_timestamp();
double classifyTime = (t1 - t0);
LOG(INFO) << "Classify time was: " << classifyTime;
}
int MultiClassify::Align(std::string byteString, int encoding, std::string* json){
if ( sizeof(byteString)==0 ){
FILE_LOG(logWARNING) << "No data in byteString";
return -1;
}
std::vector<Tensor> imageTensors;
auto importStatus = imageGraph->ProccessImage(byteString, encoding, &imageTensors);
if (!importStatus.ok()) {
LOG(ERROR) << "processing image failed: " << importStatus;
return -1;
}
else {
FILE_LOG(logDEBUG) << "got image";
}
auto imageShape = imageTensors[0].shape();
FILE_LOG(logDEBUG) << "Image dimensions: " << imageShape.dim_size(0) << ", " << imageShape.dim_size(1) << ", " << imageShape.dim_size(2);
if (imageShape.dim_size(1) == 0){
return -1;
}
LOG(INFO) << "Processed align image";
int width = imageTensors[0].shape().dim_size(2);
int height = imageTensors[0].shape().dim_size(1);
float maximum = std::max(width, height);
if (maximum>600){
float scaling = 600.0 / maximum;
int newWidth = (int)(width * scaling);
int newHeight = (int)(height * scaling);
LOG(INFO) << "Scaling to max size " << newWidth << ", " << newHeight;
Scope localRoot = Scope::NewRootScope();
std::vector<Tensor> resizeOutputs;
auto imageOutput = ResizeBilinear(localRoot,
imageTensors[0],
{newHeight, newWidth});
FILE_LOG(logDEBUG) << "Scaling to max size " << newWidth << ", " << newHeight;
ClientSession session(localRoot);
auto scaleStatus = session.Run({imageOutput}, &resizeOutputs);
imageTensors[0] = resizeOutputs[0];
}
return faceAlign -> ReadAndRun(&imageTensors, json, &faceSession);
}
int MultiClassify::Classify(std::string byteString, int encoding, std::string* json){
if ( sizeof(byteString)==0 ){
FILE_LOG(logWARNING) << "No data in byteString";
return -1;
}
std::vector<Tensor> imageTensors;
auto importStatus = imageGraph->ProccessImage(byteString, encoding, &imageTensors);
if (!importStatus.ok()) {
LOG(ERROR) << "processing image failed: " << importStatus;
return -1;
}
else {
FILE_LOG(logDEBUG) << "got image";
}
auto imageShape = imageTensors[0].shape();
FILE_LOG(logDEBUG) << "Image dimensions: " << imageShape.dim_size(0) << ", " << imageShape.dim_size(1) << ", " << imageShape.dim_size(2);
if (imageShape.dim_size(1) == 0){
return -1;
}
Scope localRoot = Scope::NewRootScope();
std::vector<Tensor> resizeOutputs;
auto imageOutput = ResizeBilinear(localRoot,
imageTensors[0],
{inceptionSize, inceptionSize});
FILE_LOG(logDEBUG) << "Scaling to inception input: " << imageTensors[0].DebugString();
ClientSession session(localRoot);
auto scaleStatus = session.Run({imageOutput}, &resizeOutputs);
FILE_LOG(logDEBUG) << "resizeOutputs: " << resizeOutputs[0].DebugString();
return classifier -> ReadAndRun(&resizeOutputs, json, &classifySession);
}
int MultiClassify::Detect(std::string byteString, int encoding, std::string* json){
if ( sizeof(byteString)==0 ){
FILE_LOG(logWARNING) << "No data in byteString";
return -1;
}
std::vector<Tensor> imageTensors;
auto importStatus = imageGraph->ProccessImage(byteString, encoding, &imageTensors);
if (!importStatus.ok()) {
LOG(ERROR) << "processing image failed: " << importStatus;
return -1;
}
else {
FILE_LOG(logDEBUG) << "got image";
}
//do a basic dimension check on the returned image
auto imageShape = imageTensors[0].shape();
FILE_LOG(logDEBUG) << "Image dimensions: " << imageShape.dim_size(0) << ", " << imageShape.dim_size(1) << ", " << imageShape.dim_size(2);
if (imageShape.dim_size(1) == 0){
return -1;
}
Scope localRoot = Scope::NewRootScope();
std::vector<Tensor> resizeOutputs;
auto imageOutput = ResizeBilinear(localRoot,
imageTensors[0],
{inceptionSize, inceptionSize});
FILE_LOG(logDEBUG) << "Scaling to sdd input: " << imageTensors[0].DebugString();
ClientSession session(localRoot);
auto scaleStatus = session.Run({imageOutput}, &resizeOutputs);
FILE_LOG(logDEBUG) << "resizeOutputs: " << resizeOutputs[0].DebugString();
imageTensors.push_back(resizeOutputs[0]);
return singleShotDetector -> ReadAndRun(&imageTensors, json, &ssdSession);
}
int MultiClassify::Box(std::string byteString, int encoding, std::string* json){
if ( sizeof(byteString)==0 ){
FILE_LOG(logWARNING) << "No data in byteString";
return -1;
}
std::vector<Tensor> imageTensors;
auto importStatus = imageGraph->ProccessImage(byteString, encoding, &imageTensors);
if (!importStatus.ok()) {
LOG(ERROR) << "processing image failed: " << importStatus;
return -1;
}
else {
FILE_LOG(logDEBUG) << "got image";
}
auto imageShape = imageTensors[0].shape();
FILE_LOG(logDEBUG) << "Image dimensions: " << imageShape.dim_size(0) << ", " << imageShape.dim_size(1) << ", " << imageShape.dim_size(2);
if (imageShape.dim_size(1) == 0){
return -1;
}
Scope localRoot = Scope::NewRootScope();
ClientSession session(localRoot);
std::vector<Tensor> resizeOutputs;
auto imageOutput = ResizeBilinear(localRoot,
imageTensors[0],
{multiboxSize, multiboxSize});
FILE_LOG(logDEBUG) << "Scaling to box input: " << imageTensors[0].DebugString();
auto scaleStatus = session.Run({imageOutput}, &resizeOutputs);
imageTensors.push_back(resizeOutputs[0]);
return multibox -> ReadAndRun(&imageTensors, json, &boxSession);
}
MultiClassify::~MultiClassify(){
LOG(INFO) << "destructing";
auto closedBoxSession = boxSession->Close();
auto closedClassifySession = classifySession->Close();
auto closedFaceSession = faceSession->Close();
auto closedSsdSession = ssdSession->Close();
FILE_LOG(logDEBUG) << "Closed sessions: " << closedBoxSession << ", " << closedClassifySession << ", " << closedFaceSession << ", " << closedSsdSession;
}
<|endoftext|> |
<commit_before>#pragma once
#include <stack>
#include <memory>
#include "acmacs-base/fmt.hh"
// ----------------------------------------------------------------------
namespace in_json
{
inline namespace v1
{
class error : public std::runtime_error
{
public:
template <typename S> error(size_t line_no, ssize_t column_no, S&& message) : std::runtime_error(fmt::format("in_json error at {}:{}: {}", line_no, column_no, message)) {}
};
class parse_error : public std::runtime_error
{
public:
parse_error(std::string_view m1) : std::runtime_error{fmt::format("in_json parsing error: {}", m1)} {}
parse_error(std::string_view m1, std::string_view m2) : parse_error(fmt::format("{}{}", m1, m2)) {}
};
namespace detail
{
template <typename Iter> Iter read_string(Iter first, Iter last, Iter& line_start, size_t& line_no)
{
bool esc = false;
for (; first != last; ++first) {
switch (*first) {
case '"':
if (!esc)
return first;
esc = false;
break;
case '\\':
esc = !esc;
break;
case '\n':
esc = false;
++line_no;
line_start = first + 1;
break;
default:
esc = false;
break;
}
}
throw error(line_no, first - line_start, "unexpected EOF");
}
enum class number_is { integer, real };
template <typename Iter> std::pair<Iter, number_is> read_number(Iter first, Iter last)
{
number_is nis = number_is::integer;
for (; first != last; ++first) {
switch (*first) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
break;
case '.':
case '-':
case 'e':
case 'E':
nis = number_is::real;
break;
default:
return {first, nis};
}
}
throw error(0, 0, "read_number internal");
}
} // namespace detail
// ----------------------------------------------------------------------
template <typename Sink, typename Iter> void parse(Sink& sink, Iter first, Iter last)
{
using namespace fmt::literals;
auto line_start = first;
size_t line_no = 1;
while (first != last) {
switch (*first) {
case ' ':
case ',':
case ':':
break;
case '\n':
line_start = first + 1;
++line_no;
break;
case '{':
sink.injson_object_start();
break;
case '}':
sink.injson_object_end();
break;
case '[':
sink.injson_array_start();
break;
case ']':
sink.injson_array_end();
break;
case '"': {
const auto end = detail::read_string(first + 1, last, line_start, line_no); // may throw error on EOF
sink.injson_string(first + 1, end);
first = end; // end points to terminating double-quotes
} break;
case '+':
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': {
const auto [end, nis] = detail::read_number(first + 1, last);
switch (nis) {
case detail::number_is::integer:
sink.injson_integer(first, end);
break;
case detail::number_is::real:
sink.injson_real(first, end);
break;
}
first = end - 1; // incremented after switch
} break;
default:
throw error(line_no, first - line_start, "unexpected '{}'"_format(*first));
}
++first;
}
}
// ----------------------------------------------------------------------
class stack_entry
{
public:
stack_entry() = default;
stack_entry(const stack_entry&) = default;
virtual ~stack_entry() = default;
virtual const char* injson_name() = 0;
virtual std::unique_ptr<stack_entry> injson_put_object() { throw in_json::parse_error(fmt::format("{}: unexpected subobject for key \"{}\"", injson_name(), key_)); }
virtual void injson_put_key(std::string_view data) { key_ = data; }
virtual void injson_put_string(std::string_view data) { throw parse_error(fmt::format("{}: unexpected string \"{}\" for key \"{}\"", injson_name(), data, key_)); }
virtual void injson_put_integer(std::string_view data) { throw parse_error(fmt::format("{}: unexpected integer {} for key \"{}\"", injson_name(), data, key_)); }
virtual void injson_put_real(std::string_view data) { throw parse_error(fmt::format("{}: unexpected real {} for key \"{}\"", injson_name(), data, key_)); }
virtual void injson_put_array() { throw parse_error(fmt::format("{}: unexpected array for key \"{}\"", injson_name(), key_)); }
virtual void injson_pop_array() {} // throw parse_error("stack_entry::injson_pop_array");
bool key_empty() const { return key_.empty(); }
protected:
std::string_view key_{};
void reset_key() { key_ = std::string_view{}; }
};
template <typename TargetContainer, typename ToplevelStackEntry> class object_sink
{
public:
object_sink(TargetContainer& target) : target_{target} {}
void injson_object_start()
{
if (stack_.empty())
stack_.push(std::make_unique<ToplevelStackEntry>(target_));
else
stack_.push(stack_.top()->injson_put_object());
}
void injson_object_end() { stack_.pop(); }
void injson_array_start() { stack_.top()->injson_put_array(); }
void injson_array_end() { stack_.top()->injson_pop_array(); }
template <typename Iter> void injson_string(Iter first, Iter last)
{
const std::string_view data{&*first, static_cast<size_t>(last - first)};
if (auto& tar = *stack_.top(); tar.key_empty())
tar.injson_put_key(data);
else
tar.injson_put_string(data);
}
template <typename Iter> void injson_integer(Iter first, Iter last) { stack_.top()->injson_put_integer({&*first, static_cast<size_t>(last - first)}); }
template <typename Iter> void injson_real(Iter first, Iter last) { stack_.top()->injson_put_real({&*first, static_cast<size_t>(last - first)}); }
private:
TargetContainer& target_;
std::stack<std::unique_ptr<stack_entry>> stack_;
};
} // namespace v1
} // namespace in_json
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>in_json::error keeps line, column, message<commit_after>#pragma once
#include <stack>
#include <memory>
#include "acmacs-base/fmt.hh"
// ----------------------------------------------------------------------
namespace in_json
{
inline namespace v1
{
class error : public std::runtime_error
{
public:
template <typename S> error(size_t a_line_no, ssize_t a_column_no, S&& a_message) : std::runtime_error(fmt::format("in_json error at {}:{}: {}", a_line_no, a_column_no, a_message)), line_no{a_line_no}, column_no{a_column_no}, message{a_message} {}
size_t line_no;
ssize_t column_no;
std::string message;
};
class parse_error : public std::runtime_error
{
public:
parse_error(std::string_view m1) : std::runtime_error{fmt::format("in_json parsing error: {}", m1)} {}
parse_error(std::string_view m1, std::string_view m2) : parse_error(fmt::format("{}{}", m1, m2)) {}
};
namespace detail
{
template <typename Iter> Iter read_string(Iter first, Iter last, Iter& line_start, size_t& line_no)
{
bool esc = false;
for (; first != last; ++first) {
switch (*first) {
case '"':
if (!esc)
return first;
esc = false;
break;
case '\\':
esc = !esc;
break;
case '\n':
esc = false;
++line_no;
line_start = first + 1;
break;
default:
esc = false;
break;
}
}
throw error(line_no, first - line_start, "unexpected EOF");
}
enum class number_is { integer, real };
template <typename Iter> std::pair<Iter, number_is> read_number(Iter first, Iter last)
{
number_is nis = number_is::integer;
for (; first != last; ++first) {
switch (*first) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
break;
case '.':
case '-':
case 'e':
case 'E':
nis = number_is::real;
break;
default:
return {first, nis};
}
}
throw error(0, 0, "read_number internal");
}
} // namespace detail
// ----------------------------------------------------------------------
template <typename Sink, typename Iter> void parse(Sink& sink, Iter first, Iter last)
{
using namespace fmt::literals;
auto line_start = first;
size_t line_no = 1;
while (first != last) {
switch (*first) {
case ' ':
case ',':
case ':':
break;
case '\n':
line_start = first + 1;
++line_no;
break;
case '{':
sink.injson_object_start();
break;
case '}':
sink.injson_object_end();
break;
case '[':
sink.injson_array_start();
break;
case ']':
sink.injson_array_end();
break;
case '"': {
const auto end = detail::read_string(first + 1, last, line_start, line_no); // may throw error on EOF
sink.injson_string(first + 1, end);
first = end; // end points to terminating double-quotes
} break;
case '+':
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': {
const auto [end, nis] = detail::read_number(first + 1, last);
switch (nis) {
case detail::number_is::integer:
sink.injson_integer(first, end);
break;
case detail::number_is::real:
sink.injson_real(first, end);
break;
}
first = end - 1; // incremented after switch
} break;
default:
throw error(line_no, first - line_start, "unexpected '{}'"_format(*first));
}
++first;
}
}
// ----------------------------------------------------------------------
class stack_entry
{
public:
stack_entry() = default;
stack_entry(const stack_entry&) = default;
virtual ~stack_entry() = default;
virtual const char* injson_name() = 0;
virtual std::unique_ptr<stack_entry> injson_put_object() { throw in_json::parse_error(fmt::format("{}: unexpected subobject for key \"{}\"", injson_name(), key_)); }
virtual void injson_put_key(std::string_view data) { key_ = data; }
virtual void injson_put_string(std::string_view data) { throw parse_error(fmt::format("{}: unexpected string \"{}\" for key \"{}\"", injson_name(), data, key_)); }
virtual void injson_put_integer(std::string_view data) { throw parse_error(fmt::format("{}: unexpected integer {} for key \"{}\"", injson_name(), data, key_)); }
virtual void injson_put_real(std::string_view data) { throw parse_error(fmt::format("{}: unexpected real {} for key \"{}\"", injson_name(), data, key_)); }
virtual void injson_put_array() { throw parse_error(fmt::format("{}: unexpected array for key \"{}\"", injson_name(), key_)); }
virtual void injson_pop_array() {} // throw parse_error("stack_entry::injson_pop_array");
bool key_empty() const { return key_.empty(); }
protected:
std::string_view key_{};
void reset_key() { key_ = std::string_view{}; }
};
template <typename TargetContainer, typename ToplevelStackEntry> class object_sink
{
public:
object_sink(TargetContainer& target) : target_{target} {}
void injson_object_start()
{
if (stack_.empty())
stack_.push(std::make_unique<ToplevelStackEntry>(target_));
else
stack_.push(stack_.top()->injson_put_object());
}
void injson_object_end() { stack_.pop(); }
void injson_array_start() { stack_.top()->injson_put_array(); }
void injson_array_end() { stack_.top()->injson_pop_array(); }
template <typename Iter> void injson_string(Iter first, Iter last)
{
const std::string_view data{&*first, static_cast<size_t>(last - first)};
if (auto& tar = *stack_.top(); tar.key_empty())
tar.injson_put_key(data);
else
tar.injson_put_string(data);
}
template <typename Iter> void injson_integer(Iter first, Iter last) { stack_.top()->injson_put_integer({&*first, static_cast<size_t>(last - first)}); }
template <typename Iter> void injson_real(Iter first, Iter last) { stack_.top()->injson_put_real({&*first, static_cast<size_t>(last - first)}); }
private:
TargetContainer& target_;
std::stack<std::unique_ptr<stack_entry>> stack_;
};
} // namespace v1
} // namespace in_json
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|> |
<commit_before>#include "serialworker.h"
#include <QSerialPort>
#include <QDebug>
SerialWorker::SerialWorker(QObject *parent) : QObject(parent)
{
serial = NULL;
rx_state = IDLE;
rx_step = 0;
buildFrame = new CANFrame;
}
SerialWorker::~SerialWorker()
{
if (serial != NULL) delete serial;
}
void SerialWorker::setSerialPort(QSerialPortInfo *port)
{
if (!(serial == NULL))
{
if (serial->isOpen())
{
serial->close();
}
delete serial;
}
serial = new QSerialPort(*port);
qDebug() << "Serial port name is " << port->portName();
serial->open(QIODevice::ReadWrite);
QByteArray output;
output.append(0xE7);
output.append(0xE7);
serial->write(output);
///isConnected = true;
connect(serial, SIGNAL(readyRead()), this, SLOT(readSerialData()));
}
void SerialWorker::readSerialData()
{
QByteArray data = serial->readAll();
unsigned char c;
qDebug() << (tr("Got data from serial. Len = %0").arg(data.length()));
for (int i = 0; i < data.length(); i++)
{
c = data.at(i);
procRXChar(c);
}
}
void SerialWorker::sendFrame(const CANFrame *frame, int bus = 0)
{
QByteArray buffer;
int c;
int ID;
qDebug() << "Sending out frame with id " << frame->ID;
ID = frame->ID;
if (frame->extended) ID |= 1 << 31;
buffer[0] = 0xF1; //start of a command over serial
buffer[1] = 0; //command ID for sending a CANBUS frame
buffer[2] = (unsigned char)(ID & 0xFF); //four bytes of ID LSB first
buffer[3] = (unsigned char)(ID >> 8);
buffer[4] = (unsigned char)(ID >> 16);
buffer[5] = (unsigned char)(ID >> 24);
buffer[6] = (unsigned char)(bus & 1);
buffer[7] = (unsigned char)frame->len;
for (c = 0; c < frame->len; c++)
{
buffer[8 + c] = frame->data[c];
}
buffer[8 + frame->len] = 0;
if (serial == NULL) return;
if (!serial->isOpen()) return;
qDebug() << "writing " << buffer.length() << " bytes to serial port";
serial->write(buffer);
}
void SerialWorker::updateBaudRates(int Speed1, int Speed2)
{
QByteArray buffer;
qDebug() << "Got signal to update bauds. 1: " << Speed1 <<" 2: " << Speed2;
buffer[0] = 0xF1; //start of a command over serial
buffer[1] = 5; //setup canbus
buffer[2] = (unsigned char)(Speed1 & 0xFF); //four bytes of ID LSB first
buffer[3] = (unsigned char)(Speed1 >> 8);
buffer[4] = (unsigned char)(Speed1 >> 16);
buffer[5] = (unsigned char)(Speed1 >> 24);
buffer[6] = (unsigned char)(Speed2 & 0xFF); //four bytes of ID LSB first
buffer[7] = (unsigned char)(Speed2 >> 8);
buffer[8] = (unsigned char)(Speed2 >> 16);
buffer[9] = (unsigned char)(Speed2 >> 24);
buffer[10] = 0;
if (serial == NULL) return;
if (!serial->isOpen()) return;
serial->write(buffer);
}
void SerialWorker::procRXChar(unsigned char c)
{
switch (rx_state)
{
case IDLE:
if (c == 0xF1) rx_state = GET_COMMAND;
break;
case GET_COMMAND:
switch (c)
{
case 0: //receiving a can frame
rx_state = BUILD_CAN_FRAME;
rx_step = 0;
break;
case 1: //we don't accept time sync commands from the firmware
rx_state = IDLE;
break;
case 2: //process a return reply for digital input states.
rx_state = GET_DIG_INPUTS;
rx_step = 0;
break;
case 3: //process a return reply for analog inputs
rx_state = GET_ANALOG_INPUTS;
break;
case 4: //we set digital outputs we don't accept replies so nothing here.
rx_state = IDLE;
break;
case 5: //we set canbus specs we don't accept replies.
rx_state = IDLE;
break;
}
break;
case BUILD_CAN_FRAME:
switch (rx_step)
{
case 0:
buildFrame->timestamp = c;
break;
case 1:
buildFrame->timestamp |= (uint)(c << 8);
break;
case 2:
buildFrame->timestamp |= (uint)c << 16;
break;
case 3:
buildFrame->timestamp |= (uint)c << 24;
break;
case 4:
buildFrame->ID = c;
break;
case 5:
buildFrame->ID |= c << 8;
break;
case 6:
buildFrame->ID |= c << 16;
break;
case 7:
buildFrame->ID |= c << 24;
if ((buildFrame->ID & 1 << 31) == 1 << 31)
{
buildFrame->ID &= 0x7FFFFFFF;
buildFrame->extended = true;
}
else buildFrame->extended = false;
break;
case 8:
buildFrame->len = c & 0xF;
if (buildFrame->len > 8) buildFrame->len = 8;
buildFrame->bus = (c & 0xF0) >> 4;
break;
default:
if (rx_step < buildFrame->len + 9)
{
buildFrame->data[rx_step - 9] = c;
}
else
{
rx_state = IDLE;
rx_step = 0;
qDebug() << "emit from serial handler to main form id: " << buildFrame->ID;
emit receivedFrame(buildFrame);
buildFrame = new CANFrame;
}
break;
}
rx_step++;
break;
case GET_ANALOG_INPUTS: //get 9 bytes - 2 per analog input plus checksum
switch (rx_step)
{
case 0:
break;
}
rx_step++;
break;
case GET_DIG_INPUTS: //get two bytes. One for digital in status and one for checksum.
switch (rx_step)
{
case 0:
break;
case 1:
rx_state = IDLE;
break;
}
rx_step++;
break;
}
}
<commit_msg>Fix to make serial work much better with the candue boards.<commit_after>#include "serialworker.h"
#include <QSerialPort>
#include <QDebug>
SerialWorker::SerialWorker(QObject *parent) : QObject(parent)
{
serial = NULL;
rx_state = IDLE;
rx_step = 0;
buildFrame = new CANFrame;
}
SerialWorker::~SerialWorker()
{
if (serial != NULL) delete serial;
}
void SerialWorker::setSerialPort(QSerialPortInfo *port)
{
if (!(serial == NULL))
{
if (serial->isOpen())
{
serial->close();
}
delete serial;
}
serial = new QSerialPort(*port);
qDebug() << "Serial port name is " << port->portName();
serial->setBaudRate(serial->Baud115200);
serial->setDataBits(serial->Data8);
serial->setFlowControl(serial->HardwareControl);
serial->open(QIODevice::ReadWrite);
serial->setDataTerminalReady(true);
serial->setRequestToSend(true);
QByteArray output;
output.append(0xE7);
output.append(0xE7);
serial->write(output);
///isConnected = true;
connect(serial, SIGNAL(readyRead()), this, SLOT(readSerialData()));
}
void SerialWorker::readSerialData()
{
QByteArray data = serial->readAll();
unsigned char c;
qDebug() << (tr("Got data from serial. Len = %0").arg(data.length()));
for (int i = 0; i < data.length(); i++)
{
c = data.at(i);
procRXChar(c);
}
}
void SerialWorker::sendFrame(const CANFrame *frame, int bus = 0)
{
QByteArray buffer;
int c;
int ID;
qDebug() << "Sending out frame with id " << frame->ID;
ID = frame->ID;
if (frame->extended) ID |= 1 << 31;
buffer[0] = 0xF1; //start of a command over serial
buffer[1] = 0; //command ID for sending a CANBUS frame
buffer[2] = (unsigned char)(ID & 0xFF); //four bytes of ID LSB first
buffer[3] = (unsigned char)(ID >> 8);
buffer[4] = (unsigned char)(ID >> 16);
buffer[5] = (unsigned char)(ID >> 24);
buffer[6] = (unsigned char)(bus & 1);
buffer[7] = (unsigned char)frame->len;
for (c = 0; c < frame->len; c++)
{
buffer[8 + c] = frame->data[c];
}
buffer[8 + frame->len] = 0;
if (serial == NULL) return;
if (!serial->isOpen()) return;
qDebug() << "writing " << buffer.length() << " bytes to serial port";
serial->write(buffer);
}
void SerialWorker::updateBaudRates(int Speed1, int Speed2)
{
QByteArray buffer;
qDebug() << "Got signal to update bauds. 1: " << Speed1 <<" 2: " << Speed2;
buffer[0] = 0xF1; //start of a command over serial
buffer[1] = 5; //setup canbus
buffer[2] = (unsigned char)(Speed1 & 0xFF); //four bytes of ID LSB first
buffer[3] = (unsigned char)(Speed1 >> 8);
buffer[4] = (unsigned char)(Speed1 >> 16);
buffer[5] = (unsigned char)(Speed1 >> 24);
buffer[6] = (unsigned char)(Speed2 & 0xFF); //four bytes of ID LSB first
buffer[7] = (unsigned char)(Speed2 >> 8);
buffer[8] = (unsigned char)(Speed2 >> 16);
buffer[9] = (unsigned char)(Speed2 >> 24);
buffer[10] = 0;
if (serial == NULL) return;
if (!serial->isOpen()) return;
serial->write(buffer);
}
void SerialWorker::procRXChar(unsigned char c)
{
switch (rx_state)
{
case IDLE:
if (c == 0xF1) rx_state = GET_COMMAND;
break;
case GET_COMMAND:
switch (c)
{
case 0: //receiving a can frame
rx_state = BUILD_CAN_FRAME;
rx_step = 0;
break;
case 1: //we don't accept time sync commands from the firmware
rx_state = IDLE;
break;
case 2: //process a return reply for digital input states.
rx_state = GET_DIG_INPUTS;
rx_step = 0;
break;
case 3: //process a return reply for analog inputs
rx_state = GET_ANALOG_INPUTS;
break;
case 4: //we set digital outputs we don't accept replies so nothing here.
rx_state = IDLE;
break;
case 5: //we set canbus specs we don't accept replies.
rx_state = IDLE;
break;
}
break;
case BUILD_CAN_FRAME:
switch (rx_step)
{
case 0:
buildFrame->timestamp = c;
break;
case 1:
buildFrame->timestamp |= (uint)(c << 8);
break;
case 2:
buildFrame->timestamp |= (uint)c << 16;
break;
case 3:
buildFrame->timestamp |= (uint)c << 24;
break;
case 4:
buildFrame->ID = c;
break;
case 5:
buildFrame->ID |= c << 8;
break;
case 6:
buildFrame->ID |= c << 16;
break;
case 7:
buildFrame->ID |= c << 24;
if ((buildFrame->ID & 1 << 31) == 1 << 31)
{
buildFrame->ID &= 0x7FFFFFFF;
buildFrame->extended = true;
}
else buildFrame->extended = false;
break;
case 8:
buildFrame->len = c & 0xF;
if (buildFrame->len > 8) buildFrame->len = 8;
buildFrame->bus = (c & 0xF0) >> 4;
break;
default:
if (rx_step < buildFrame->len + 9)
{
buildFrame->data[rx_step - 9] = c;
}
else
{
rx_state = IDLE;
rx_step = 0;
qDebug() << "emit from serial handler to main form id: " << buildFrame->ID;
emit receivedFrame(buildFrame);
buildFrame = new CANFrame;
}
break;
}
rx_step++;
break;
case GET_ANALOG_INPUTS: //get 9 bytes - 2 per analog input plus checksum
switch (rx_step)
{
case 0:
break;
}
rx_step++;
break;
case GET_DIG_INPUTS: //get two bytes. One for digital in status and one for checksum.
switch (rx_step)
{
case 0:
break;
case 1:
rx_state = IDLE;
break;
}
rx_step++;
break;
}
}
<|endoftext|> |
<commit_before>/*******************************************************************************
* c7a/api/sort.hpp
*
* Part of Project c7a.
*
* Copyright (C) 2015 Alexander Noe <aleexnoe@gmail.com>
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#pragma once
#ifndef C7A_API_SORT_HEADER
#define C7A_API_SORT_HEADER
#include <c7a/api/function_stack.hpp>
#include <c7a/api/dia.hpp>
#include <c7a/api/context.hpp>
#include <c7a/net/group.hpp>
#include <c7a/net/collective_communication.hpp>
#include <c7a/net/flow_control_channel.hpp>
#include <c7a/net/flow_control_manager.hpp>
#include <c7a/common/logger.hpp>
#include <cmath>
namespace c7a {
namespace api {
template <typename ValueType, typename ParentStack, typename CompareFunction>
class SortNode : public DOpNode<ValueType>
{
static const bool debug = true;
using Super = DOpNode<ValueType>;
using Super::context_;
using Super::data_id_;
using ParentInput = typename ParentStack::Input;
public:
SortNode(Context& ctx,
std::shared_ptr<DIANode<ParentInput> > parent,
const ParentStack& parent_stack,
CompareFunction compare_function)
: DOpNode<ValueType>(ctx, { parent }),
compare_function_(compare_function),
channel_id_samples_(ctx.data_manager().AllocateNetworkChannel()),
emitters_samples_(ctx.data_manager().
template GetNetworkEmitters<ValueType>(channel_id_samples_)),
channel_id_data_(ctx.data_manager().AllocateNetworkChannel()),
emitters_data_(ctx.data_manager().
template GetNetworkEmitters<ValueType>(channel_id_data_))
{
// Hook PreOp(s)
auto pre_op_fn = [=](const ValueType& input) {
PreOp(input);
};
auto lop_chain = parent_stack.push(pre_op_fn).emit();
parent->RegisterChild(lop_chain);
}
virtual ~SortNode() { }
//! Executes the sum operation.
void Execute() override {
MainOp();
}
/*!
* Produces an 'empty' function stack, which only contains the identity
* emitter function.
*
* \return Empty function stack
*/
auto ProduceStack() {
// Hook Identity
auto id_fn = [=](ValueType t, auto emit_func) {
return emit_func(t);
};
return MakeFunctionStack<ValueType>(id_fn);
}
/*!
* Returns "[SortNode]" as a string.
* \return "[SortNode]"
*/
std::string ToString() override {
return "[PrefixSumNode] Id:" + data_id_.ToString();
}
private:
//! The sum function which is applied to two elements.
CompareFunction compare_function_;
//! Local data
std::vector<ValueType> data_;
//!Emitter to send samples to process 0
data::ChannelId channel_id_samples_;
std::vector<data::Emitter<ValueType> > emitters_samples_;
//!Emitters to send data to other workers specified by splitters.
data::ChannelId channel_id_data_;
std::vector<data::Emitter<ValueType> > emitters_data_;
//epsilon
double desired_imbalance = 0.25;
void PreOp(ValueType input) {
//LOG << "Input: " << input;
data_.push_back(input);
}
void MainOp() {
//LOG << "MainOp processing";
size_t samplesize = std::ceil(log2((double) data_.size()) *
(1 / (desired_imbalance * desired_imbalance)));
std::random_device random_device;
std::default_random_engine generator(random_device());
std::uniform_int_distribution<int> distribution(0, data_.size() - 1);
//Send samples to worker 0
for (size_t i = 0; i < samplesize; i++) {
size_t sample = distribution(generator);
emitters_samples_[0](data_[sample]);
}
emitters_samples_[0].Close();
std::vector<ValueType> splitters;
splitters.reserve(context_.number_worker() - 1);
if (context_.rank() == 0) {
//Get samples
std::vector<ValueType> samples;
samples.reserve(samplesize * context_.number_worker());
auto it = context_.data_manager().
template GetIterator<ValueType>(channel_id_samples_);
do {
it.WaitForMore();
while (it.HasNext()) {
samples.push_back(it.Next());
}
} while (!it.IsFinished());
//Find splitters
std::sort(samples.begin(), samples.end(), compare_function_);
size_t splitting_size = samples.size() / context_.number_worker();
//Send splitters to other workers
for (size_t i = 1; i < context_.number_worker(); i++) {
splitters.push_back(samples[i * splitting_size]);
for (size_t j = 1; j < context_.number_worker(); j++) {
emitters_samples_[j](samples[i * splitting_size]);
}
}
for (size_t j = 1; j < context_.number_worker(); j++) {
emitters_samples_[j].Close();
}
} else {
//Close unused emitters
for (size_t j = 1; j < context_.number_worker(); j++) {
emitters_samples_[j].Close();
}
auto it = context_.data_manager().
template GetIterator<ValueType>(channel_id_samples_);
do {
it.WaitForMore();
while (it.HasNext()) {
splitters.push_back(it.Next());
}
} while (!it.IsFinished());
}
for (ValueType ele : data_) {
bool sent = false;
for (size_t i = 0; i < splitters.size() && !sent; i++) {
if (compare_function_(ele, splitters[i])) {
emitters_data_[i](ele);
sent = true;
break;
}
}
if (!sent) {
emitters_data_[splitters.size()](ele);
}
}
for (size_t i = 0; i < emitters_data_.size(); i++) {
emitters_data_[i].Close();
}
data_.clear();
auto it = context_.data_manager().
template GetIterator<ValueType>(channel_id_data_);
do {
it.WaitForMore();
while (it.HasNext()) {
data_.push_back(it.Next());
}
} while (!it.IsFinished());
std::sort(data_.begin(), data_.end(), compare_function_);
for (size_t i = 0; i < data_.size(); i++) {
for (auto func : DIANode<ValueType>::callbacks_) {
func(data_[i]);
}
}
std::vector<ValueType>().swap(data_);
}
void PostOp() { }
};
template <typename ValueType, typename Stack>
template <typename CompareFunction>
auto DIARef<ValueType, Stack>::Sort(const CompareFunction & compare_function) const {
using SortResultNode
= SortNode<ValueType, Stack, CompareFunction>;
static_assert(
std::is_same<
typename common::FunctionTraits<CompareFunction>::template arg<0>,
ValueType>::value ||
std::is_same<CompareFunction, common::LessThan<ValueType> >::value,
"CompareFunction has the wrong input type");
static_assert(
std::is_same<
typename common::FunctionTraits<CompareFunction>::template arg<1>,
ValueType>::value ||
std::is_same<CompareFunction, common::LessThan<ValueType> >::value,
"CompareFunction has the wrong input type");
static_assert(
std::is_same<
typename common::FunctionTraits<CompareFunction>::result_type,
ValueType>::value ||
std::is_same<CompareFunction, common::LessThan<ValueType> >::value,
"CompareFunction has the wrong input type");
auto shared_node
= std::make_shared<SortResultNode>(node_->context(),
node_,
stack_,
compare_function);
auto sort_stack = shared_node->ProduceStack();
return DIARef<ValueType, decltype(sort_stack)>(
std::move(shared_node), sort_stack);
}
} // namespace api
} // namespace c7a
#endif // !C7A_API_SORT_NODE_HEADER
/******************************************************************************/
<commit_msg>Uncrustify.<commit_after>/*******************************************************************************
* c7a/api/sort.hpp
*
* Part of Project c7a.
*
* Copyright (C) 2015 Alexander Noe <aleexnoe@gmail.com>
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#pragma once
#ifndef C7A_API_SORT_HEADER
#define C7A_API_SORT_HEADER
#include <c7a/api/function_stack.hpp>
#include <c7a/api/dia.hpp>
#include <c7a/api/context.hpp>
#include <c7a/net/group.hpp>
#include <c7a/net/collective_communication.hpp>
#include <c7a/net/flow_control_channel.hpp>
#include <c7a/net/flow_control_manager.hpp>
#include <c7a/common/logger.hpp>
#include <cmath>
namespace c7a {
namespace api {
template <typename ValueType, typename ParentStack, typename CompareFunction>
class SortNode : public DOpNode<ValueType>
{
static const bool debug = true;
using Super = DOpNode<ValueType>;
using Super::context_;
using Super::data_id_;
using ParentInput = typename ParentStack::Input;
public:
SortNode(Context& ctx,
std::shared_ptr<DIANode<ParentInput> > parent,
const ParentStack& parent_stack,
CompareFunction compare_function)
: DOpNode<ValueType>(ctx, { parent }),
compare_function_(compare_function),
channel_id_samples_(ctx.data_manager().AllocateNetworkChannel()),
emitters_samples_(ctx.data_manager().
template GetNetworkEmitters<ValueType>(channel_id_samples_)),
channel_id_data_(ctx.data_manager().AllocateNetworkChannel()),
emitters_data_(ctx.data_manager().
template GetNetworkEmitters<ValueType>(channel_id_data_))
{
// Hook PreOp(s)
auto pre_op_fn = [ = ](const ValueType& input) {
PreOp(input);
};
auto lop_chain = parent_stack.push(pre_op_fn).emit();
parent->RegisterChild(lop_chain);
}
virtual ~SortNode() { }
//! Executes the sum operation.
void Execute() override {
MainOp();
}
/*!
* Produces an 'empty' function stack, which only contains the identity
* emitter function.
*
* \return Empty function stack
*/
auto ProduceStack() {
// Hook Identity
auto id_fn = [ = ](ValueType t, auto emit_func) {
return emit_func(t);
};
return MakeFunctionStack<ValueType>(id_fn);
}
/*!
* Returns "[SortNode]" as a string.
* \return "[SortNode]"
*/
std::string ToString() override {
return "[PrefixSumNode] Id:" + data_id_.ToString();
}
private:
//! The sum function which is applied to two elements.
CompareFunction compare_function_;
//! Local data
std::vector<ValueType> data_;
//!Emitter to send samples to process 0
data::ChannelId channel_id_samples_;
std::vector<data::Emitter<ValueType> > emitters_samples_;
//!Emitters to send data to other workers specified by splitters.
data::ChannelId channel_id_data_;
std::vector<data::Emitter<ValueType> > emitters_data_;
//epsilon
double desired_imbalance = 0.25;
void PreOp(ValueType input) {
//LOG << "Input: " << input;
data_.push_back(input);
}
void MainOp() {
//LOG << "MainOp processing";
size_t samplesize = std::ceil(log2((double)data_.size()) *
(1 / (desired_imbalance * desired_imbalance)));
std::random_device random_device;
std::default_random_engine generator(random_device());
std::uniform_int_distribution<int> distribution(0, data_.size() - 1);
//Send samples to worker 0
for (size_t i = 0; i < samplesize; i++) {
size_t sample = distribution(generator);
emitters_samples_[0](data_[sample]);
}
emitters_samples_[0].Close();
std::vector<ValueType> splitters;
splitters.reserve(context_.number_worker() - 1);
if (context_.rank() == 0) {
//Get samples
std::vector<ValueType> samples;
samples.reserve(samplesize * context_.number_worker());
auto it = context_.data_manager().
template GetIterator<ValueType>(channel_id_samples_);
do {
it.WaitForMore();
while (it.HasNext()) {
samples.push_back(it.Next());
}
} while (!it.IsFinished());
//Find splitters
std::sort(samples.begin(), samples.end(), compare_function_);
size_t splitting_size = samples.size() / context_.number_worker();
//Send splitters to other workers
for (size_t i = 1; i < context_.number_worker(); i++) {
splitters.push_back(samples[i * splitting_size]);
for (size_t j = 1; j < context_.number_worker(); j++) {
emitters_samples_[j](samples[i * splitting_size]);
}
}
for (size_t j = 1; j < context_.number_worker(); j++) {
emitters_samples_[j].Close();
}
}
else {
//Close unused emitters
for (size_t j = 1; j < context_.number_worker(); j++) {
emitters_samples_[j].Close();
}
auto it = context_.data_manager().
template GetIterator<ValueType>(channel_id_samples_);
do {
it.WaitForMore();
while (it.HasNext()) {
splitters.push_back(it.Next());
}
} while (!it.IsFinished());
}
for (ValueType ele : data_) {
bool sent = false;
for (size_t i = 0; i < splitters.size() && !sent; i++) {
if (compare_function_(ele, splitters[i])) {
emitters_data_[i](ele);
sent = true;
break;
}
}
if (!sent) {
emitters_data_[splitters.size()](ele);
}
}
for (size_t i = 0; i < emitters_data_.size(); i++) {
emitters_data_[i].Close();
}
data_.clear();
auto it = context_.data_manager().
template GetIterator<ValueType>(channel_id_data_);
do {
it.WaitForMore();
while (it.HasNext()) {
data_.push_back(it.Next());
}
} while (!it.IsFinished());
std::sort(data_.begin(), data_.end(), compare_function_);
for (size_t i = 0; i < data_.size(); i++) {
for (auto func : DIANode<ValueType>::callbacks_) {
func(data_[i]);
}
}
std::vector<ValueType>().swap(data_);
}
void PostOp() { }
};
template <typename ValueType, typename Stack>
template <typename CompareFunction>
auto DIARef<ValueType, Stack>::Sort(const CompareFunction &compare_function) const {
using SortResultNode
= SortNode<ValueType, Stack, CompareFunction>;
static_assert(
std::is_same<
typename common::FunctionTraits<CompareFunction>::template arg<0>,
ValueType>::value ||
std::is_same<CompareFunction, common::LessThan<ValueType> >::value,
"CompareFunction has the wrong input type");
static_assert(
std::is_same<
typename common::FunctionTraits<CompareFunction>::template arg<1>,
ValueType>::value ||
std::is_same<CompareFunction, common::LessThan<ValueType> >::value,
"CompareFunction has the wrong input type");
static_assert(
std::is_same<
typename common::FunctionTraits<CompareFunction>::result_type,
ValueType>::value ||
std::is_same<CompareFunction, common::LessThan<ValueType> >::value,
"CompareFunction has the wrong input type");
auto shared_node
= std::make_shared<SortResultNode>(node_->context(),
node_,
stack_,
compare_function);
auto sort_stack = shared_node->ProduceStack();
return DIARef<ValueType, decltype(sort_stack)>(
std::move(shared_node), sort_stack);
}
} // namespace api
} // namespace c7a
#endif // !C7A_API_SORT_NODE_HEADER
/******************************************************************************/
<|endoftext|> |
<commit_before>/**
* @file
*/
#pragma once
#include "bi/io/bih_ostream.hpp"
#include <list>
namespace bi {
/**
* Output stream for Markdown files.
*
* @ingroup compiler_io
*/
class md_ostream: public bih_ostream {
public:
md_ostream(std::ostream& base);
using bih_ostream::visit;
virtual void visit(const Package* o);
virtual void visit(const Name* o);
virtual void visit(const Parameter* o);
virtual void visit(const GlobalVariable* o);
virtual void visit(const MemberVariable* o);
virtual void visit(const Function* o);
virtual void visit(const Fiber* o);
virtual void visit(const Program* o);
virtual void visit(const MemberFunction* o);
virtual void visit(const MemberFiber* o);
virtual void visit(const BinaryOperator* o);
virtual void visit(const UnaryOperator* o);
virtual void visit(const AssignmentOperator* o);
virtual void visit(const ConversionOperator* o);
virtual void visit(const Class* o);
virtual void visit(const ListType* o);
virtual void visit(const ClassType* o);
virtual void visit(const BasicType* o);
virtual void visit(const AliasType* o);
virtual void visit(const IdentifierType* o);
virtual void visit(const ArrayType* o);
virtual void visit(const ParenthesesType* o);
virtual void visit(const FunctionType* o);
virtual void visit(const FiberType* o);
virtual void visit(const OptionalType* o);
private:
void genHead(const std::string& name);
template<class ObjectType, class RootType>
void genBrief(const std::string& name, const RootType* root);
template<class ObjectType, class RootType>
void genOneLine(const std::string& name, const RootType* root);
template<class ObjectType, class RootType>
void genDetailed(const std::string& name, const RootType* root);
template<class ObjectType, class RootType>
void genSections(const std::string& name, const RootType* root);
/**
* Current section depth.
*/
int depth;
};
}
#include "bi/visitor/Gatherer.hpp"
#include "bi/primitive/encode.hpp"
template<class ObjectType, class RootType>
void bi::md_ostream::genBrief(const std::string& name, const RootType* root) {
Gatherer<ObjectType> gatherer;
root->accept(&gatherer);
if (gatherer.size() > 0) {
genHead(name);
line("| --- | --- |");
++depth;
for (auto o : gatherer) {
line("| *" << o << "* | " << brief(o->loc->doc) << " |");
}
line("");
--depth;
}
}
template<class ObjectType, class RootType>
void bi::md_ostream::genOneLine(const std::string& name,
const RootType* root) {
Gatherer<ObjectType> gatherer;
root->accept(&gatherer);
if (gatherer.size() > 0) {
genHead(name);
line("| --- | --- |");
++depth;
for (auto o : gatherer) {
line("| *" << o << "* | " << one_line(o->loc->doc) << " |");
}
line("");
--depth;
}
}
template<class ObjectType, class RootType>
void bi::md_ostream::genDetailed(const std::string& name,
const RootType* root) {
Gatherer<ObjectType> gatherer([](const ObjectType* o) {
return !detailed(o->loc->doc).empty();
});
root->accept(&gatherer);
if (gatherer.size() > 0) {
genHead(name);
++depth;
for (auto o : gatherer) {
std::string desc = detailed(o->loc->doc);
line("*" << o << "*\n");
line(desc << "\n");
}
--depth;
}
}
template<class ObjectType, class RootType>
void bi::md_ostream::genSections(const std::string& name,
const RootType* root) {
Gatherer<ObjectType> gatherer([](const ObjectType* o) {
return !detailed(o->loc->doc).empty();
});
root->accept(&gatherer);
if (gatherer.size() > 0) {
genHead(name);
++depth;
for (auto o : gatherer) {
genHead(o->name->str());
*this << o;
}
--depth;
}
}
<commit_msg>Added alphabetical sorting of function details.<commit_after>/**
* @file
*/
#pragma once
#include "bi/io/bih_ostream.hpp"
#include <list>
#include <vector>
#include <algorithm>
namespace bi {
/**
* Output stream for Markdown files.
*
* @ingroup compiler_io
*/
class md_ostream: public bih_ostream {
public:
md_ostream(std::ostream& base);
using bih_ostream::visit;
virtual void visit(const Package* o);
virtual void visit(const Name* o);
virtual void visit(const Parameter* o);
virtual void visit(const GlobalVariable* o);
virtual void visit(const MemberVariable* o);
virtual void visit(const Function* o);
virtual void visit(const Fiber* o);
virtual void visit(const Program* o);
virtual void visit(const MemberFunction* o);
virtual void visit(const MemberFiber* o);
virtual void visit(const BinaryOperator* o);
virtual void visit(const UnaryOperator* o);
virtual void visit(const AssignmentOperator* o);
virtual void visit(const ConversionOperator* o);
virtual void visit(const Class* o);
virtual void visit(const ListType* o);
virtual void visit(const ClassType* o);
virtual void visit(const BasicType* o);
virtual void visit(const AliasType* o);
virtual void visit(const IdentifierType* o);
virtual void visit(const ArrayType* o);
virtual void visit(const ParenthesesType* o);
virtual void visit(const FunctionType* o);
virtual void visit(const FiberType* o);
virtual void visit(const OptionalType* o);
private:
void genHead(const std::string& name);
template<class ObjectType, class RootType>
void genBrief(const std::string& name, const RootType* root);
template<class ObjectType, class RootType>
void genOneLine(const std::string& name, const RootType* root);
template<class ObjectType, class RootType>
void genDetailed(const std::string& name, const RootType* root);
template<class ObjectType, class RootType>
void genSections(const std::string& name, const RootType* root);
/**
* Current section depth.
*/
int depth;
};
}
#include "bi/visitor/Gatherer.hpp"
#include "bi/primitive/encode.hpp"
template<class ObjectType, class RootType>
void bi::md_ostream::genBrief(const std::string& name, const RootType* root) {
Gatherer<ObjectType> gatherer;
root->accept(&gatherer);
if (gatherer.size() > 0) {
genHead(name);
line("| --- | --- |");
++depth;
for (auto o : gatherer) {
line("| *" << o << "* | " << brief(o->loc->doc) << " |");
}
line("");
--depth;
}
}
template<class ObjectType, class RootType>
void bi::md_ostream::genOneLine(const std::string& name,
const RootType* root) {
Gatherer<ObjectType> gatherer;
root->accept(&gatherer);
if (gatherer.size() > 0) {
genHead(name);
line("| --- | --- |");
++depth;
for (auto o : gatherer) {
line("| *" << o << "* | " << one_line(o->loc->doc) << " |");
}
line("");
--depth;
}
}
template<class ObjectType, class RootType>
void bi::md_ostream::genDetailed(const std::string& name,
const RootType* root) {
Gatherer<ObjectType> gatherer([](const ObjectType* o) {
return !detailed(o->loc->doc).empty();
});
root->accept(&gatherer);
std::vector<ObjectType*> sorted(gatherer.size());
std::copy(gatherer.begin(), gatherer.end(), sorted.begin());
std::stable_sort(sorted.begin(), sorted.end(),
[](const ObjectType* o1, const ObjectType* o2) {
return o1->name->str() < o2->name->str();
});
if (sorted.size() > 0) {
genHead(name);
++depth;
for (auto o : sorted) {
std::string desc = detailed(o->loc->doc);
line("*" << o << "*\n");
line(desc << "\n");
}
--depth;
}
}
template<class ObjectType, class RootType>
void bi::md_ostream::genSections(const std::string& name,
const RootType* root) {
Gatherer<ObjectType> gatherer([](const ObjectType* o) {
return !detailed(o->loc->doc).empty();
});
root->accept(&gatherer);
if (gatherer.size() > 0) {
genHead(name);
++depth;
for (auto o : gatherer) {
genHead(o->name->str());
*this << o;
}
--depth;
}
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <sstream>
#include <cstring>
#include <cassert>
#include <set>
#include <string>
#include <queue>
#include <iostream>
#include "CallGraph.h"
#include "CodeGen_Bash.h"
#include "Parser.h"
#include "IRVisitor.h"
const std::string BISH_VERSION = "0.1";
const std::string BISH_URL = "https://github.com/tdenniston/bish";
const std::string STDLIB_PATH = "src/StdLib.bish";
class FindFunctionCalls : public Bish::IRVisitor {
public:
FindFunctionCalls(const std::set<std::string> &n) {
to_find.insert(n.begin(), n.end());
}
std::set<std::string> names() { return names_; }
virtual void visit(Bish::FunctionCall *call) {
for (std::vector<Bish::IRNode *>::const_iterator I = call->args.begin(),
E = call->args.end(); I != E; ++I) {
(*I)->accept(this);
}
if (to_find.count(call->function->name)) {
names_.insert(call->function->name);
}
}
private:
std::set<std::string> to_find;
std::set<std::string> names_;
};
// Add necessary stdlib functions to the given module.
void link_stdlib(Bish::Module *m) {
Bish::Parser p;
Bish::Module *stdlib = p.parse(STDLIB_PATH);
std::set<std::string> stdlib_functions;
for (std::vector<Bish::Function *>::iterator I = stdlib->functions.begin(),
E = stdlib->functions.end(); I != E; ++I) {
Bish::Function *f = *I;
if (f->name.compare("main") == 0) continue;
stdlib_functions.insert(f->name);
}
FindFunctionCalls find(stdlib_functions);
m->accept(&find);
Bish::CallGraphBuilder cgb;
Bish::CallGraph cg = cgb.build(stdlib);
std::set<std::string> to_link = find.names();
for (std::set<std::string>::iterator I = to_link.begin(), E = to_link.end(); I != E; ++I) {
Bish::Function *f = stdlib->get_function(*I);
assert(f);
if (f->name.compare("main") == 0) continue;
m->add_function(f);
std::vector<Bish::Function *> calls = cg.transitive_calls(f);
for (std::vector<Bish::Function *>::iterator II = calls.begin(), EE = calls.end(); II != EE; ++II) {
m->add_function(stdlib->get_function((*II)->name));
}
}
}
void compile_to_bash(std::ostream &os, Bish::Module *m) {
link_stdlib(m);
os << "#!/bin/bash\n";
os << "# Autogenerated script, compiled from the Bish language.\n";
os << "# Bish version " << BISH_VERSION << "\n";
os << "# Please see " << BISH_URL << " for more information about Bish.\n\n";
Bish::CodeGen_Bash compile(os);
m->accept(&compile);
}
void run_on_bash(std::istream &is) {
FILE *bash = popen("bash", "w");
char buf[4096];
while (is.read(buf, sizeof(buf))) {
fwrite(buf, 1, is.gcount(), bash);
}
fwrite(buf, 1, is.gcount(), bash);
fflush(bash);
pclose(bash);
}
int main(int argc, char **argv) {
if (argc < 2) {
std::cerr << "USAGE: " << argv[0] << " [-r] <INPUT>\n";
std::cerr << " Compiles Bish file <INPUT> to bash.\n";
std::cerr << "\nOPTIONS:\n";
std::cerr << " -r compiles and runs the file.\n";
return 1;
}
if (strcmp(argv[1], "-r") == 0) {
if (argc != 3) {
std::cerr << "-r needs a filename\n";
return 1;
}
std::string path(argv[2]);
Bish::Parser p;
Bish::Module *m = p.parse(path);
std::stringstream s;
compile_to_bash(s, m);
run_on_bash(s);
} else {
std::string path(argv[1]);
Bish::Parser p;
Bish::Module *m = p.parse(path);
compile_to_bash(std::cout, m);
}
return 0;
}
<commit_msg>Use a do-while loop to DRY up the stream reading<commit_after>#include <stdio.h>
#include <sstream>
#include <cstring>
#include <cassert>
#include <set>
#include <string>
#include <queue>
#include <iostream>
#include "CallGraph.h"
#include "CodeGen_Bash.h"
#include "Parser.h"
#include "IRVisitor.h"
const std::string BISH_VERSION = "0.1";
const std::string BISH_URL = "https://github.com/tdenniston/bish";
const std::string STDLIB_PATH = "src/StdLib.bish";
class FindFunctionCalls : public Bish::IRVisitor {
public:
FindFunctionCalls(const std::set<std::string> &n) {
to_find.insert(n.begin(), n.end());
}
std::set<std::string> names() { return names_; }
virtual void visit(Bish::FunctionCall *call) {
for (std::vector<Bish::IRNode *>::const_iterator I = call->args.begin(),
E = call->args.end(); I != E; ++I) {
(*I)->accept(this);
}
if (to_find.count(call->function->name)) {
names_.insert(call->function->name);
}
}
private:
std::set<std::string> to_find;
std::set<std::string> names_;
};
// Add necessary stdlib functions to the given module.
void link_stdlib(Bish::Module *m) {
Bish::Parser p;
Bish::Module *stdlib = p.parse(STDLIB_PATH);
std::set<std::string> stdlib_functions;
for (std::vector<Bish::Function *>::iterator I = stdlib->functions.begin(),
E = stdlib->functions.end(); I != E; ++I) {
Bish::Function *f = *I;
if (f->name.compare("main") == 0) continue;
stdlib_functions.insert(f->name);
}
FindFunctionCalls find(stdlib_functions);
m->accept(&find);
Bish::CallGraphBuilder cgb;
Bish::CallGraph cg = cgb.build(stdlib);
std::set<std::string> to_link = find.names();
for (std::set<std::string>::iterator I = to_link.begin(), E = to_link.end(); I != E; ++I) {
Bish::Function *f = stdlib->get_function(*I);
assert(f);
if (f->name.compare("main") == 0) continue;
m->add_function(f);
std::vector<Bish::Function *> calls = cg.transitive_calls(f);
for (std::vector<Bish::Function *>::iterator II = calls.begin(), EE = calls.end(); II != EE; ++II) {
m->add_function(stdlib->get_function((*II)->name));
}
}
}
void compile_to_bash(std::ostream &os, Bish::Module *m) {
link_stdlib(m);
os << "#!/bin/bash\n";
os << "# Autogenerated script, compiled from the Bish language.\n";
os << "# Bish version " << BISH_VERSION << "\n";
os << "# Please see " << BISH_URL << " for more information about Bish.\n\n";
Bish::CodeGen_Bash compile(os);
m->accept(&compile);
}
void run_on_bash(std::istream &is) {
FILE *bash = popen("bash", "w");
char buf[4096];
do {
is.read(buf, sizeof(buf));
fwrite(buf, 1, is.gcount(), bash);
} while (is.gcount() > 0);
fflush(bash);
pclose(bash);
}
int main(int argc, char **argv) {
if (argc < 2) {
std::cerr << "USAGE: " << argv[0] << " [-r] <INPUT>\n";
std::cerr << " Compiles Bish file <INPUT> to bash.\n";
std::cerr << "\nOPTIONS:\n";
std::cerr << " -r compiles and runs the file.\n";
return 1;
}
if (strcmp(argv[1], "-r") == 0) {
if (argc != 3) {
std::cerr << "-r needs a filename\n";
return 1;
}
std::string path(argv[2]);
Bish::Parser p;
Bish::Module *m = p.parse(path);
std::stringstream s;
compile_to_bash(s, m);
run_on_bash(s);
} else {
std::string path(argv[1]);
Bish::Parser p;
Bish::Module *m = p.parse(path);
compile_to_bash(std::cout, m);
}
return 0;
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <stdlib.h>
using namespace std;
#define uint unsigned int
int main(int argc, char* argv[])
{
return 0;
}
<commit_msg>Update c++ template to print a newline<commit_after>#include <stdio.h>
#include <stdlib.h>
using namespace std;
#define uint unsigned int
int main(int argc, char* argv[])
{
printf("\n");
return 0;
}
<|endoftext|> |
<commit_before>#include <vector>
#include <ostream>
#include "BST.h"
/*
namespace Graph
{
template <typename Key, typename Value> class BST
{//A Binary Search Tree.
private:
Node<Key, Value> root;
Value get( Node subtreeNode, Key getKey );//Returns the value of the node with a specified key that is within the subtree rooted at subtreeNode. Returns null if the node isn't found.
Node put( Node rootNode, Key newKey, Value newValue );
Node min( Node minNode );
Key floor( Node rootNode, Key key );
public:
int size() const;//Returns the size of the tree.
int size(Node node) const;//Returns the size at node node.
Value get( Key getKey );//Returns the value of the node with a specified key.
void put( Key newKey, Value newValue );
Key min();
Key floor( Key key );
};
}
*/
namespace Graph
{
template <typename Key, typename Value> int BST<Key, Value>::size() const
{//Returns the size of the tree.
return size( root );
}
template <typename Key, typename Value> int size(Node node) const
{//Returns the size at node node.
if( node == null )
{
return 0;
}
else
{
return node.N;
}
}
template <typename Key, typename Value> Value BST<Key, Value>::get( Key getKey )
{//Returns the value of the node with a specified key.
return get( root, key );
}
template <typename Key, typename Value> Value Node<Key, Value>::get( Node subtreeNode, Key getKey )
{//Returns the value of the node with a specified key that is within the subtree rooted at subtreeNode. Returns null if the node isn't found.
if( subtreeNode == null )
{
return null;
}
int compare = getKey.compareTo( subtreeNode.key );
if( compare < 0 )
{
return get( subtreeNode.left, getKey );
}
else if( compare > 0 )
{
return get( subtreeNode.right, getKey );
}
else
{
return subtreeNode.value;
}
}
template <typename Key, typename Value> void BST<Key, Value>::put( Key newKey, Value newValue )
{//Search for the key. If there is a node with the key, update the value. If not, add it to the tree.
root = put(root, newKey, newValue);
}
template <typename Key, typename Value> Node BST<Key, Value>::put( Node rootNode, Key newKey, Value newValue )
{//If a node with newKey exists in the tree rooted at rootNode, change the value of the node. If not, add it to the tree.
if( newKey == null )
{
return new Node( newKey, newValue, 1 );
}
int compare = newKey.compareTo( rootNode.key );
if( compare < 0 )
{
rootNode.left = put( rootNode.left, newKey, newValue );
}
else if( compare > 0 )
{
rootNode.right = put( rootNode.right, newKey, newValue );
}
else
{
rootNode.value = newValue;
}
rootNode.N = size(rootNode.left) + size(rootNode.right) + 1;
return rootNode;
}
template <typename Key, typename Value> Key BST<Key, Value>::min()
{
return min(root).key;
}
template <typename Key, typename Value> void BST<Key, Value>::min( Node rootNode )
{
if( rootNode.left == null )
{
return rootNode;
}
else
{
return min( rootNode.left );
}
}
template <typename Key, typename Value> Key BST<Key, Value>::floor( Node rootNode, Key key )
{
if( rootNode == null )
{
return null;
}
int compare = key.compareTo( rootNode.key );
if( compare == 0 )
{
return rootNode;
}
else if( compare < 0 )
{
return floor( rootNode.left, key );
}
Node t = floor( rootNode.right, key );
if( t != null )
{
return t;
}
else
{
return rootNode;
}
}
template <typename Key, typename Value> BST<Key, Value>::Key floor( Key key )
{
Node rootNode = floor( root, key );
if( rootNode == null )
{
return null;
}
else
{
return rootNode.key;
}
}
template <typename Key, typename Value> BST<Key, Value>::Key select( int n )
{
}
}
<commit_msg>Added a comment.<commit_after>#include <vector>
#include <ostream>
#include "BST.h"
/*
namespace Graph
{
template <typename Key, typename Value> class BST
{//A Binary Search Tree.
private:
Node<Key, Value> root;
Value get( Node subtreeNode, Key getKey );//Returns the value of the node with a specified key that is within the subtree rooted at subtreeNode. Returns null if the node isn't found.
Node put( Node rootNode, Key newKey, Value newValue );
Node min( Node minNode );
Key floor( Node rootNode, Key key );
Key select( int n );
public:
int size() const;//Returns the size of the tree.
int size(Node node) const;//Returns the size at node node.
Value get( Key getKey );//Returns the value of the node with a specified key.
void put( Key newKey, Value newValue );
Key min();
Key floor( Key key );
};
}
*/
namespace Graph
{
template <typename Key, typename Value> int BST<Key, Value>::size() const
{//Returns the size of the tree.
return size( root );
}
template <typename Key, typename Value> int size(Node node) const
{//Returns the size at node node.
if( node == null )
{
return 0;
}
else
{
return node.N;
}
}
template <typename Key, typename Value> Value BST<Key, Value>::get( Key getKey )
{//Returns the value of the node with a specified key.
return get( root, key );
}
template <typename Key, typename Value> Value Node<Key, Value>::get( Node subtreeNode, Key getKey )
{//Returns the value of the node with a specified key that is within the subtree rooted at subtreeNode. Returns null if the node isn't found.
if( subtreeNode == null )
{
return null;
}
int compare = getKey.compareTo( subtreeNode.key );
if( compare < 0 )
{
return get( subtreeNode.left, getKey );
}
else if( compare > 0 )
{
return get( subtreeNode.right, getKey );
}
else
{
return subtreeNode.value;
}
}
template <typename Key, typename Value> void BST<Key, Value>::put( Key newKey, Value newValue )
{//Search for the key. If there is a node with the key, update the value. If not, add it to the tree.
root = put(root, newKey, newValue);
}
template <typename Key, typename Value> Node BST<Key, Value>::put( Node rootNode, Key newKey, Value newValue )
{//If a node with newKey exists in the tree rooted at rootNode, change the value of the node. If not, add it to the tree.
if( newKey == null )
{
return new Node( newKey, newValue, 1 );
}
int compare = newKey.compareTo( rootNode.key );
if( compare < 0 )
{
rootNode.left = put( rootNode.left, newKey, newValue );
}
else if( compare > 0 )
{
rootNode.right = put( rootNode.right, newKey, newValue );
}
else
{
rootNode.value = newValue;
}
rootNode.N = size(rootNode.left) + size(rootNode.right) + 1;
return rootNode;
}
template <typename Key, typename Value> Key BST<Key, Value>::min()
{
return min(root).key;
}
template <typename Key, typename Value> void BST<Key, Value>::min( Node rootNode )
{
if( rootNode.left == null )
{
return rootNode;
}
else
{
return min( rootNode.left );
}
}
template <typename Key, typename Value> Key BST<Key, Value>::floor( Node rootNode, Key key )
{
if( rootNode == null )
{
return null;
}
int compare = key.compareTo( rootNode.key );
if( compare == 0 )
{
return rootNode;
}
else if( compare < 0 )
{
return floor( rootNode.left, key );
}
Node t = floor( rootNode.right, key );
if( t != null )
{
return t;
}
else
{
return rootNode;
}
}
template <typename Key, typename Value> BST<Key, Value>::Key floor( Key key )
{
Node rootNode = floor( root, key );
if( rootNode == null )
{
return null;
}
else
{
return rootNode.key;
}
}
template <typename Key, typename Value> BST<Key, Value>::Key select( int n )
{
}
}
<|endoftext|> |
<commit_before>#pragma once
#include "imgui.h"
void drawIGSLogo(
const ImVec2& pos,
const double time );
/** Show an info about window with animated IGS logo.
Usage example:
if( about_window_visible &&
aboutWindow(
ICON_FA_INFO_CIRCLE " About",
"My fancy tools\n"
"Abla bli blub ....\n",
ImVec2( 400, 155 ),
time ) )
about_window_visible = false;
*/
bool aboutWindow(
const char* title,
const char* text,
const ImVec2& size,
double time );
<commit_msg>adjust comment<commit_after>#pragma once
#include "imgui.h"
void drawIGSLogo(
const ImVec2& pos,
const double time );
/** Show an info about window with animated IGS logo.
* \param time in secs.
*/
bool aboutWindow(
const char* title,
const char* text,
const ImVec2& size,
double time );
<|endoftext|> |
<commit_before>#include "NMEAParser.cpp"
#include "gtest/gtest.h"
#include <cmath>
namespace NMEA {
TEST(ParseFloat, Valid_Float) {
const std::string String = "3.0";
const float Expected = 3.0f;
EXPECT_EQ(Expected, ParseFloat(String));
}
TEST(ParseFloat, Invalid_Float) {
const std::string String = "ASDF";
EXPECT_TRUE(isnan(ParseFloat(String)));
}
TEST(ParseFloat, Invalid_Empty_Float) {
const std::string String = "";
const float Expected = NAN;
EXPECT_TRUE(isnan(ParseFloat(String)));
}
}
<commit_msg>Add ParseFloat_Test file comment<commit_after>/**
* File: ParseFloat_Test.cpp
* Description: Unit tests for
* Parse(const std::string &String)
*/
#include "NMEAParser.cpp"
#include "gtest/gtest.h"
#include <cmath>
namespace NMEA {
TEST(ParseFloat, Valid_Float) {
const std::string String = "3.0";
const float Expected = 3.0f;
EXPECT_EQ(Expected, ParseFloat(String));
}
TEST(ParseFloat, Invalid_Float) {
const std::string String = "ASDF";
EXPECT_TRUE(isnan(ParseFloat(String)));
}
TEST(ParseFloat, Invalid_Empty_Float) {
const std::string String = "";
const float Expected = NAN;
EXPECT_TRUE(isnan(ParseFloat(String)));
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef itkOnePlusOneEvolutionaryOptimizerv4_hxx
#define itkOnePlusOneEvolutionaryOptimizerv4_hxx
#include "itkMath.h"
#include "itkOnePlusOneEvolutionaryOptimizerv4.h"
#include "vnl/vnl_matrix.h"
namespace itk
{
template<typename TInternalComputationValueType>
OnePlusOneEvolutionaryOptimizerv4<TInternalComputationValueType>
::OnePlusOneEvolutionaryOptimizerv4()
{
m_CatchGetValueException = false;
m_MetricWorstPossibleValue = 0;
m_Epsilon = (double)1.5e-4;
m_RandomGenerator = ITK_NULLPTR;
m_Initialized = false;
m_GrowthFactor = 1.05;
m_ShrinkFactor = std::pow(m_GrowthFactor, -0.25);
m_InitialRadius = 1.01;
m_MaximumIteration = 100;
m_Stop = false;
m_StopConditionDescription.str("");
m_CurrentCost = 0;
m_FrobeniusNorm = 0.0;
}
template<typename TInternalComputationValueType>
OnePlusOneEvolutionaryOptimizerv4<TInternalComputationValueType>
::~OnePlusOneEvolutionaryOptimizerv4()
{}
template<typename TInternalComputationValueType>
void
OnePlusOneEvolutionaryOptimizerv4<TInternalComputationValueType>
::SetNormalVariateGenerator(NormalVariateGeneratorType *generator)
{
if ( m_RandomGenerator != generator )
{
m_RandomGenerator = generator;
this->Modified();
}
}
template<typename TInternalComputationValueType>
void
OnePlusOneEvolutionaryOptimizerv4<TInternalComputationValueType>
::Initialize(double initialRadius, double grow, double shrink)
{
m_InitialRadius = initialRadius;
if ( Math::AlmostEquals( grow, -1 ) )
{
m_GrowthFactor = 1.05;
}
else
{
m_GrowthFactor = grow;
}
if ( Math::AlmostEquals( shrink, -1 ) )
{
m_ShrinkFactor = std::pow(m_GrowthFactor, -0.25);
}
else
{
m_ShrinkFactor = shrink;
}
}
template<typename TInternalComputationValueType>
void
OnePlusOneEvolutionaryOptimizerv4<TInternalComputationValueType>
::StartOptimization(bool /* doOnlyInitialization */)
{
if ( this->m_Metric.IsNull() )
{
return;
}
Superclass::StartOptimization();
this->InvokeEvent( StartEvent() );
m_Stop = false;
unsigned int spaceDimension = this->m_Metric->GetNumberOfParameters();
vnl_matrix< double > A(spaceDimension, spaceDimension);
vnl_vector< double > parent( this->m_Metric->GetParameters() );
vnl_vector< double > f_norm(spaceDimension);
vnl_vector< double > child(spaceDimension);
vnl_vector< double > delta(spaceDimension);
ParametersType parentPosition(spaceDimension);
ParametersType childPosition(spaceDimension);
for ( unsigned int i = 0; i < spaceDimension; i++ )
{
parentPosition[i] = parent[i];
}
this->m_Metric->SetParameters( parentPosition );
double pvalue = m_MetricWorstPossibleValue;
try
{
pvalue = this->m_Metric->GetValue();
}
catch ( ... )
{
if ( m_CatchGetValueException )
{
pvalue = m_MetricWorstPossibleValue;
}
else
{
throw;
}
}
itkDebugMacro(<< ": initial position: " << parentPosition);
itkDebugMacro(<< ": initial fitness: " << pvalue);
this->m_Metric->SetParameters(parentPosition);
const ScalesType & scales = this->GetScales();
// Make sure the scales have been set properly
if ( scales.size() != spaceDimension )
{
itkExceptionMacro(<< "The size of Scales is "
<< scales.size()
<< ", but the NumberOfParameters for the CostFunction is "
<< spaceDimension
<< ".");
}
A.set_identity();
for ( unsigned int i = 0; i < spaceDimension; i++ )
{
A(i, i) = m_InitialRadius / scales[i];
}
this->m_CurrentIteration = 0;
for ( unsigned int iter = 0; iter < m_MaximumIteration; iter++ )
{
if ( m_Stop )
{
m_StopConditionDescription.str("");
m_StopConditionDescription << this->GetNameOfClass() << ": ";
m_StopConditionDescription << "StopOptimization() called";
break;
}
++this->m_CurrentIteration;
for ( unsigned int i = 0; i < spaceDimension; i++ )
{
if ( !m_RandomGenerator )
{
itkExceptionMacro(<< "Random Generator is not set!");
}
f_norm[i] = m_RandomGenerator->GetVariate();
}
delta = A * f_norm;
child = parent + delta;
for ( unsigned int i = 0; i < spaceDimension; i++ )
{
childPosition[i] = child[i];
}
// Update the metric so we can check the metric value in childPosition
this->m_Metric->SetParameters( childPosition );
double cvalue = m_MetricWorstPossibleValue;
try
{
cvalue = this->m_Metric->GetValue();
// While we got the metric value in childPosition,
// the metric paramteres are set back to parentPosition
this->m_Metric->SetParameters( parentPosition );
}
catch ( ... )
{
if ( m_CatchGetValueException )
{
cvalue = m_MetricWorstPossibleValue;
}
else
{
throw;
}
}
itkDebugMacro(<< "iter: " << iter << ": parent position: "
<< parentPosition);
itkDebugMacro(<< "iter: " << iter << ": parent fitness: "
<< pvalue);
itkDebugMacro(<< "iter: " << iter << ": random vector: " << f_norm);
itkDebugMacro(<< "iter: " << iter << ": A: " << std::endl << A);
itkDebugMacro(<< "iter: " << iter << ": delta: " << delta);
itkDebugMacro(<< "iter: " << iter << ": child position: "
<< childPosition);
itkDebugMacro(<< "iter: " << iter << ": child fitness: "
<< cvalue);
double adjust = m_ShrinkFactor;
if ( cvalue < pvalue )
{
itkDebugMacro(<< "iter: " << iter << ": increasing search radius");
pvalue = cvalue;
parent.swap(child);
adjust = m_GrowthFactor;
for ( unsigned int i = 0; i < spaceDimension; i++ )
{
parentPosition[i] = parent[i];
}
this->m_Metric->SetParameters(parentPosition);
}
else
{
itkDebugMacro(<< "iter: " << iter << ": decreasing search radius");
}
m_CurrentCost = pvalue;
// convergence criterion: f-norm of A < epsilon_A
// Compute double precision sum of absolute values of
// a single precision vector
m_FrobeniusNorm = A.fro_norm();
itkDebugMacro(<< "A f-norm:" << m_FrobeniusNorm);
if ( m_FrobeniusNorm <= m_Epsilon )
{
itkDebugMacro(<< "converges at iteration = " << iter);
m_StopConditionDescription.str("");
m_StopConditionDescription << this->GetNameOfClass() << ": ";
m_StopConditionDescription << "Fnorm (" << m_FrobeniusNorm
<< ") is less than Epsilon (" << m_Epsilon
<< " at iteration #" << iter;
this->InvokeEvent( EndEvent() );
return;
}
// A += (adjust - 1)/ (f_norm * f_norm) * A * f_norm * f_norm;
// Blas_R1_Update(A, A * f_norm, f_norm,
// ((adjust - 1) / Blas_Dot_Prod(f_norm, f_norm)));
// = DGER(Fortran)
// performs the rank 1 operation
// A := alpha*x*y' + A,
// where y' = transpose(y)
// where alpha is a scalar, x is an m element vector, y is an n element
// vector and A is an m by n matrix.
// x = A * f_norm , y = f_norm, alpha = (adjust - 1) / Blas_Dot_Prod(
// f_norm, f_norm)
//A = A + (adjust - 1.0) * A;
double alpha = ( ( adjust - 1.0 ) / dot_product(f_norm, f_norm) );
for ( unsigned int c = 0; c < spaceDimension; c++ )
{
for ( unsigned int r = 0; r < spaceDimension; r++ )
{
A(r, c) += alpha * delta[r] * f_norm[c];
}
}
this->InvokeEvent( IterationEvent() );
itkDebugMacro( << "Current position: " << this->GetCurrentPosition() );
}
m_StopConditionDescription.str("");
m_StopConditionDescription << this->GetNameOfClass() << ": ";
m_StopConditionDescription << "Maximum number of iterations ("
<< m_MaximumIteration
<< ") exceeded. ";
this->InvokeEvent( EndEvent() );
}
template<typename TInternalComputationValueType>
const std::string
OnePlusOneEvolutionaryOptimizerv4<TInternalComputationValueType>
::GetStopConditionDescription() const
{
return m_StopConditionDescription.str();
}
template<typename TInternalComputationValueType>
const typename OnePlusOneEvolutionaryOptimizerv4<TInternalComputationValueType>::MeasureType &
OnePlusOneEvolutionaryOptimizerv4<TInternalComputationValueType>
::GetValue() const
{
return this->GetCurrentCost();
}
template<typename TInternalComputationValueType>
void
OnePlusOneEvolutionaryOptimizerv4<TInternalComputationValueType>
::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
if ( m_RandomGenerator )
{
os << indent << "Random Generator " << m_RandomGenerator.GetPointer() << std::endl;
}
else
{
os << indent << "Random Generator " << "(none)" << std::endl;
}
os << indent << "Maximum Iteration " << GetMaximumIteration() << std::endl;
os << indent << "Epsilon " << GetEpsilon() << std::endl;
os << indent << "Initial Radius " << GetInitialRadius() << std::endl;
os << indent << "Growth Fractor " << GetGrowthFactor() << std::endl;
os << indent << "Shrink Fractor " << GetShrinkFactor() << std::endl;
os << indent << "Initialized " << GetInitialized() << std::endl;
os << indent << "Current Cost " << GetCurrentCost() << std::endl;
os << indent << "Frobenius Norm " << GetFrobeniusNorm() << std::endl;
os << indent << "CatchGetValueException " << GetCatchGetValueException()
<< std::endl;
os << indent << "MetricWorstPossibleValue " << GetMetricWorstPossibleValue()
<< std::endl;
}
} // end of namespace itk
#endif
<commit_msg>BUG: First IterationEvent is at CurrentIteration==0<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef itkOnePlusOneEvolutionaryOptimizerv4_hxx
#define itkOnePlusOneEvolutionaryOptimizerv4_hxx
#include "itkMath.h"
#include "itkOnePlusOneEvolutionaryOptimizerv4.h"
#include "vnl/vnl_matrix.h"
namespace itk
{
template<typename TInternalComputationValueType>
OnePlusOneEvolutionaryOptimizerv4<TInternalComputationValueType>
::OnePlusOneEvolutionaryOptimizerv4()
{
m_CatchGetValueException = false;
m_MetricWorstPossibleValue = 0;
m_Epsilon = (double)1.5e-4;
m_RandomGenerator = ITK_NULLPTR;
m_Initialized = false;
m_GrowthFactor = 1.05;
m_ShrinkFactor = std::pow(m_GrowthFactor, -0.25);
m_InitialRadius = 1.01;
m_MaximumIteration = 100;
m_Stop = false;
m_StopConditionDescription.str("");
m_CurrentCost = 0;
m_FrobeniusNorm = 0.0;
}
template<typename TInternalComputationValueType>
OnePlusOneEvolutionaryOptimizerv4<TInternalComputationValueType>
::~OnePlusOneEvolutionaryOptimizerv4()
{}
template<typename TInternalComputationValueType>
void
OnePlusOneEvolutionaryOptimizerv4<TInternalComputationValueType>
::SetNormalVariateGenerator(NormalVariateGeneratorType *generator)
{
if ( m_RandomGenerator != generator )
{
m_RandomGenerator = generator;
this->Modified();
}
}
template<typename TInternalComputationValueType>
void
OnePlusOneEvolutionaryOptimizerv4<TInternalComputationValueType>
::Initialize(double initialRadius, double grow, double shrink)
{
m_InitialRadius = initialRadius;
if ( Math::AlmostEquals( grow, -1 ) )
{
m_GrowthFactor = 1.05;
}
else
{
m_GrowthFactor = grow;
}
if ( Math::AlmostEquals( shrink, -1 ) )
{
m_ShrinkFactor = std::pow(m_GrowthFactor, -0.25);
}
else
{
m_ShrinkFactor = shrink;
}
}
template<typename TInternalComputationValueType>
void
OnePlusOneEvolutionaryOptimizerv4<TInternalComputationValueType>
::StartOptimization(bool /* doOnlyInitialization */)
{
if ( this->m_Metric.IsNull() )
{
return;
}
Superclass::StartOptimization();
this->InvokeEvent( StartEvent() );
m_Stop = false;
unsigned int spaceDimension = this->m_Metric->GetNumberOfParameters();
vnl_matrix< double > A(spaceDimension, spaceDimension);
vnl_vector< double > parent( this->m_Metric->GetParameters() );
vnl_vector< double > f_norm(spaceDimension);
vnl_vector< double > child(spaceDimension);
vnl_vector< double > delta(spaceDimension);
ParametersType parentPosition(spaceDimension);
ParametersType childPosition(spaceDimension);
for ( unsigned int i = 0; i < spaceDimension; i++ )
{
parentPosition[i] = parent[i];
}
this->m_Metric->SetParameters( parentPosition );
double pvalue = m_MetricWorstPossibleValue;
try
{
pvalue = this->m_Metric->GetValue();
}
catch ( ... )
{
if ( m_CatchGetValueException )
{
pvalue = m_MetricWorstPossibleValue;
}
else
{
throw;
}
}
itkDebugMacro(<< ": initial position: " << parentPosition);
itkDebugMacro(<< ": initial fitness: " << pvalue);
this->m_Metric->SetParameters(parentPosition);
const ScalesType & scales = this->GetScales();
// Make sure the scales have been set properly
if ( scales.size() != spaceDimension )
{
itkExceptionMacro(<< "The size of Scales is "
<< scales.size()
<< ", but the NumberOfParameters for the CostFunction is "
<< spaceDimension
<< ".");
}
A.set_identity();
for ( unsigned int i = 0; i < spaceDimension; i++ )
{
A(i, i) = m_InitialRadius / scales[i];
}
for ( this->m_CurrentIteration = 0;
this->m_CurrentIteration < m_MaximumIteration;
this->m_CurrentIteration++ )
{
if ( m_Stop )
{
m_StopConditionDescription.str("");
m_StopConditionDescription << this->GetNameOfClass() << ": ";
m_StopConditionDescription << "StopOptimization() called";
break;
}
for ( unsigned int i = 0; i < spaceDimension; i++ )
{
if ( !m_RandomGenerator )
{
itkExceptionMacro(<< "Random Generator is not set!");
}
f_norm[i] = m_RandomGenerator->GetVariate();
}
delta = A * f_norm;
child = parent + delta;
for ( unsigned int i = 0; i < spaceDimension; i++ )
{
childPosition[i] = child[i];
}
// Update the metric so we can check the metric value in childPosition
this->m_Metric->SetParameters( childPosition );
double cvalue = m_MetricWorstPossibleValue;
try
{
cvalue = this->m_Metric->GetValue();
// While we got the metric value in childPosition,
// the metric paramteres are set back to parentPosition
this->m_Metric->SetParameters( parentPosition );
}
catch ( ... )
{
if ( m_CatchGetValueException )
{
cvalue = m_MetricWorstPossibleValue;
}
else
{
throw;
}
}
itkDebugMacro(<< "iter: " << this->m_CurrentIteration << ": parent position: "
<< parentPosition);
itkDebugMacro(<< "iter: " << this->m_CurrentIteration << ": parent fitness: "
<< pvalue);
itkDebugMacro(<< "iter: " << this->m_CurrentIteration << ": random vector: " << f_norm);
itkDebugMacro(<< "iter: " << this->m_CurrentIteration << ": A: " << std::endl << A);
itkDebugMacro(<< "iter: " << this->m_CurrentIteration << ": delta: " << delta);
itkDebugMacro(<< "iter: " << this->m_CurrentIteration << ": child position: "
<< childPosition);
itkDebugMacro(<< "iter: " << this->m_CurrentIteration << ": child fitness: "
<< cvalue);
double adjust = m_ShrinkFactor;
if ( cvalue < pvalue )
{
itkDebugMacro(<< "iter: " << this->m_CurrentIteration << ": increasing search radius");
pvalue = cvalue;
parent.swap(child);
adjust = m_GrowthFactor;
for ( unsigned int i = 0; i < spaceDimension; i++ )
{
parentPosition[i] = parent[i];
}
this->m_Metric->SetParameters(parentPosition);
}
else
{
itkDebugMacro(<< "iter: " << this->m_CurrentIteration << ": decreasing search radius");
}
m_CurrentCost = pvalue;
// convergence criterion: f-norm of A < epsilon_A
// Compute double precision sum of absolute values of
// a single precision vector
m_FrobeniusNorm = A.fro_norm();
itkDebugMacro(<< "A f-norm:" << m_FrobeniusNorm);
if ( m_FrobeniusNorm <= m_Epsilon )
{
itkDebugMacro(<< "converges at iteration = " << this->m_CurrentIteration);
m_StopConditionDescription.str("");
m_StopConditionDescription << this->GetNameOfClass() << ": ";
m_StopConditionDescription << "Fnorm (" << m_FrobeniusNorm
<< ") is less than Epsilon (" << m_Epsilon
<< " at iteration #" << this->m_CurrentIteration;
this->InvokeEvent( EndEvent() );
return;
}
// A += (adjust - 1)/ (f_norm * f_norm) * A * f_norm * f_norm;
// Blas_R1_Update(A, A * f_norm, f_norm,
// ((adjust - 1) / Blas_Dot_Prod(f_norm, f_norm)));
// = DGER(Fortran)
// performs the rank 1 operation
// A := alpha*x*y' + A,
// where y' = transpose(y)
// where alpha is a scalar, x is an m element vector, y is an n element
// vector and A is an m by n matrix.
// x = A * f_norm , y = f_norm, alpha = (adjust - 1) / Blas_Dot_Prod(
// f_norm, f_norm)
//A = A + (adjust - 1.0) * A;
double alpha = ( ( adjust - 1.0 ) / dot_product(f_norm, f_norm) );
for ( unsigned int c = 0; c < spaceDimension; c++ )
{
for ( unsigned int r = 0; r < spaceDimension; r++ )
{
A(r, c) += alpha * delta[r] * f_norm[c];
}
}
this->InvokeEvent( IterationEvent() );
itkDebugMacro( << "Current position: " << this->GetCurrentPosition() );
}
m_StopConditionDescription.str("");
m_StopConditionDescription << this->GetNameOfClass() << ": ";
m_StopConditionDescription << "Maximum number of iterations ("
<< m_MaximumIteration
<< ") exceeded. ";
this->InvokeEvent( EndEvent() );
}
template<typename TInternalComputationValueType>
const std::string
OnePlusOneEvolutionaryOptimizerv4<TInternalComputationValueType>
::GetStopConditionDescription() const
{
return m_StopConditionDescription.str();
}
template<typename TInternalComputationValueType>
const typename OnePlusOneEvolutionaryOptimizerv4<TInternalComputationValueType>::MeasureType &
OnePlusOneEvolutionaryOptimizerv4<TInternalComputationValueType>
::GetValue() const
{
return this->GetCurrentCost();
}
template<typename TInternalComputationValueType>
void
OnePlusOneEvolutionaryOptimizerv4<TInternalComputationValueType>
::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
if ( m_RandomGenerator )
{
os << indent << "Random Generator " << m_RandomGenerator.GetPointer() << std::endl;
}
else
{
os << indent << "Random Generator " << "(none)" << std::endl;
}
os << indent << "Maximum Iteration " << GetMaximumIteration() << std::endl;
os << indent << "Epsilon " << GetEpsilon() << std::endl;
os << indent << "Initial Radius " << GetInitialRadius() << std::endl;
os << indent << "Growth Fractor " << GetGrowthFactor() << std::endl;
os << indent << "Shrink Fractor " << GetShrinkFactor() << std::endl;
os << indent << "Initialized " << GetInitialized() << std::endl;
os << indent << "Current Cost " << GetCurrentCost() << std::endl;
os << indent << "Frobenius Norm " << GetFrobeniusNorm() << std::endl;
os << indent << "CatchGetValueException " << GetCatchGetValueException()
<< std::endl;
os << indent << "MetricWorstPossibleValue " << GetMetricWorstPossibleValue()
<< std::endl;
}
} // end of namespace itk
#endif
<|endoftext|> |
<commit_before>//---------------------------------------------------------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 2009, 2010, 2012, 2013 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------------------------------------------------------
// check ConstraintMatrix.distribute() for a petsc vector
//
// we do this by creating a vector where each processor has 100
// elements but no ghost elements. then we add constraints on each
// processor that constrain elements within each processor's local
// range to ones outside. these have to be added on all
// processors. then call distribute() and verify that the result is
// true.
//
// we use constraints of the form x_i = x_j with sequentially growing
// x_j's so that we can verify the correctness analytically
//
// compared to the _01 test, here the ConstraintMatrix object acts on an index
// set that only includes the locally owned vector elements, without any
// overlap. this verifies that we really only need to know about the *sources*
// of constraints locally, not the *targets*.
#include "../tests.h"
#include <deal.II/base/logstream.h>
#include <deal.II/lac/petsc_parallel_vector.h>
#include <deal.II/lac/constraint_matrix.h>
#include <fstream>
#include <sstream>
void test()
{
const unsigned int myid = Utilities::MPI::this_mpi_process (MPI_COMM_WORLD);
const unsigned int n_processes = Utilities::MPI::n_mpi_processes (MPI_COMM_WORLD);
// create a vector that consists of elements indexed from 0 to n
PETScWrappers::MPI::Vector vec (MPI_COMM_WORLD, 100 * n_processes, 100);
Assert (vec.local_size() == 100, ExcInternalError());
Assert (vec.local_range().first == 100*myid, ExcInternalError());
Assert (vec.local_range().second == 100*myid+100, ExcInternalError());
for (unsigned int i=vec.local_range().first; i<vec.local_range().second; ++i)
vec(i) = i;
vec.compress();
// verify correctness so far
{
double exact_l1 = 0;
for (unsigned int i=0; i<vec.size(); ++i)
exact_l1 += i;
Assert (vec.l1_norm() == exact_l1, ExcInternalError());
}
// create a ConstraintMatrix with a range that only includes locally active
// DoFs
IndexSet locally_relevant_range (vec.size());
locally_relevant_range.add_range (100*myid,
100*myid+100);
ConstraintMatrix cm (locally_relevant_range);
// add constraints that constrain an element in the middle of the
// local range of each processor against an element outside, both in
// the ghost range before and after
//
// note that we tell each processor about all constraints, but most
// of them will throw away this information since it is not for a
// DoF inside the locally relevant range
for (unsigned int p=0; p<n_processes; ++p)
{
if ((p != 0) && locally_relevant_range.is_element (p*100+10))
{
cm.add_line (p*100+10);
cm.add_entry (p*100+10,
p*100-25,
1);
}
if ((p != n_processes-1) && locally_relevant_range.is_element (p*100+90))
{
cm.add_line (p*100+90);
cm.add_entry (p*100+90,
p*100+105,
1);
}
}
cm.close ();
// now distribute these constraints
cm.distribute (vec);
// verify correctness
vec.compress ();
if (myid != 0)
Assert (vec(vec.local_range().first+10) == vec.local_range().first-25,
ExcInternalError());
if (myid != n_processes-1)
Assert (vec(vec.local_range().first+90) == vec.local_range().first+105,
ExcInternalError());
for (unsigned int i=vec.local_range().first; i<vec.local_range().second; ++i)
{
if ((i != vec.local_range().first+10)
&&
(i != vec.local_range().first+90))
{
double val = vec(i);
Assert (std::fabs(val - i) <= 1e-6, ExcInternalError());
}
}
{
double exact_l1 = 0;
// add up original values of vector entries
for (unsigned int i=0; i<vec.size(); ++i)
exact_l1 += i;
// but then correct for the constrained values
for (unsigned int p=0; p<n_processes; ++p)
{
if (p != 0)
exact_l1 = exact_l1 - (p*100+10) + (p*100-25);
if (p != n_processes-1)
exact_l1 = exact_l1 - (p*100+90) + (p*100+105);
}
Assert (vec.l1_norm() == exact_l1, ExcInternalError());
if (myid == 0)
deallog << "Norm = " << vec.l1_norm() << std::endl;
}
}
int main(int argc, char *argv[])
{
Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1);
unsigned int myid = Utilities::MPI::this_mpi_process (MPI_COMM_WORLD);
deallog.push(Utilities::int_to_string(myid));
if (myid == 0)
{
std::ofstream logfile(output_file_for_mpi("petsc_condense_02").c_str());
deallog.attach(logfile);
deallog.depth_console(0);
deallog.threshold_double(1.e-10);
test();
}
else
test();
}
<commit_msg>Augment text.<commit_after>//---------------------------------------------------------------------------
// $Id$
// Version: $Name$
//
// Copyright (C) 2009, 2010, 2012, 2013 by the deal.II authors
//
// This file is subject to QPL and may not be distributed
// without copyright and license information. Please refer
// to the file deal.II/doc/license.html for the text and
// further information on this license.
//
//---------------------------------------------------------------------------
// check ConstraintMatrix.distribute() for a petsc vector
//
// we do this by creating a vector where each processor has 100
// elements but no ghost elements. then we add constraints on each
// processor that constrain elements within each processor's local
// range to ones outside. these have to be added on all
// processors. then call distribute() and verify that the result is
// true.
//
// we use constraints of the form x_i = x_j with sequentially growing
// x_j's so that we can verify the correctness analytically
//
// compared to the _01 test, here the ConstraintMatrix object acts on an index
// set that only includes the locally owned vector elements, without any
// overlap. this verifies that we really only need to know about the *targets*
// of constraints locally, not the *sources*. (at the time of writing this
// test, ConstraintMatrix::distribute for PETSc distributed vectors actively
// imported the source vector elements for those target elements we locally
// own.)
#include "../tests.h"
#include <deal.II/base/logstream.h>
#include <deal.II/lac/petsc_parallel_vector.h>
#include <deal.II/lac/constraint_matrix.h>
#include <fstream>
#include <sstream>
void test()
{
const unsigned int myid = Utilities::MPI::this_mpi_process (MPI_COMM_WORLD);
const unsigned int n_processes = Utilities::MPI::n_mpi_processes (MPI_COMM_WORLD);
// create a vector that consists of elements indexed from 0 to n
PETScWrappers::MPI::Vector vec (MPI_COMM_WORLD, 100 * n_processes, 100);
Assert (vec.local_size() == 100, ExcInternalError());
Assert (vec.local_range().first == 100*myid, ExcInternalError());
Assert (vec.local_range().second == 100*myid+100, ExcInternalError());
for (unsigned int i=vec.local_range().first; i<vec.local_range().second; ++i)
vec(i) = i;
vec.compress();
// verify correctness so far
{
double exact_l1 = 0;
for (unsigned int i=0; i<vec.size(); ++i)
exact_l1 += i;
Assert (vec.l1_norm() == exact_l1, ExcInternalError());
}
// create a ConstraintMatrix with a range that only includes locally owned
// DoFs
IndexSet locally_owned_range (vec.size());
locally_owned_range.add_range (100*myid,
100*myid+100);
ConstraintMatrix cm (locally_owned_range);
// add constraints that constrain an element in the middle of the
// local range of each processor against an element outside, both in
// the ghost range before and after
//
// note that we tell each processor about all constraints, but most
// of them will throw away this information since it is not for a
// DoF inside the locally relevant range
for (unsigned int p=0; p<n_processes; ++p)
{
if ((p != 0) && locally_owned_range.is_element (p*100+10))
{
cm.add_line (p*100+10);
cm.add_entry (p*100+10,
p*100-25,
1);
}
if ((p != n_processes-1) && locally_owned_range.is_element (p*100+90))
{
cm.add_line (p*100+90);
cm.add_entry (p*100+90,
p*100+105,
1);
}
}
cm.close ();
// now distribute these constraints
cm.distribute (vec);
// verify correctness
vec.compress ();
if (myid != 0)
Assert (vec(vec.local_range().first+10) == vec.local_range().first-25,
ExcInternalError());
if (myid != n_processes-1)
Assert (vec(vec.local_range().first+90) == vec.local_range().first+105,
ExcInternalError());
for (unsigned int i=vec.local_range().first; i<vec.local_range().second; ++i)
{
if ((i != vec.local_range().first+10)
&&
(i != vec.local_range().first+90))
{
double val = vec(i);
Assert (std::fabs(val - i) <= 1e-6, ExcInternalError());
}
}
{
double exact_l1 = 0;
// add up original values of vector entries
for (unsigned int i=0; i<vec.size(); ++i)
exact_l1 += i;
// but then correct for the constrained values
for (unsigned int p=0; p<n_processes; ++p)
{
if (p != 0)
exact_l1 = exact_l1 - (p*100+10) + (p*100-25);
if (p != n_processes-1)
exact_l1 = exact_l1 - (p*100+90) + (p*100+105);
}
Assert (vec.l1_norm() == exact_l1, ExcInternalError());
if (myid == 0)
deallog << "Norm = " << vec.l1_norm() << std::endl;
}
}
int main(int argc, char *argv[])
{
Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1);
unsigned int myid = Utilities::MPI::this_mpi_process (MPI_COMM_WORLD);
deallog.push(Utilities::int_to_string(myid));
if (myid == 0)
{
std::ofstream logfile(output_file_for_mpi("petsc_condense_02").c_str());
deallog.attach(logfile);
deallog.depth_console(0);
deallog.threshold_double(1.e-10);
test();
}
else
test();
}
<|endoftext|> |
<commit_before>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "build.h"
#include <stdio.h>
#include <sys/time.h>
#include "build_log.h"
#include "graph.h"
#include "ninja.h"
#include "subprocess.h"
struct BuildStatus {
BuildStatus();
void PlanHasTotalEdges(int total);
void BuildEdgeStarted(Edge* edge);
// Returns the time the edge took, in ms.
int BuildEdgeFinished(Edge* edge);
void PrintStatus(Edge* edge);
time_t last_update_;
int finished_edges_, total_edges_;
typedef map<Edge*, timeval> RunningEdgeMap;
RunningEdgeMap running_edges_;
BuildConfig::Verbosity verbosity_;
// Whether we can do fancy terminal control codes.
bool smart_terminal_;
};
BuildStatus::BuildStatus()
: last_update_(time(NULL)), finished_edges_(0), total_edges_(0),
verbosity_(BuildConfig::NORMAL) {
const char* term = getenv("TERM");
smart_terminal_ = isatty(1) && term && string(term) != "dumb";
}
void BuildStatus::PlanHasTotalEdges(int total) {
total_edges_ = total;
}
void BuildStatus::BuildEdgeStarted(Edge* edge) {
timeval now;
gettimeofday(&now, NULL);
running_edges_.insert(make_pair(edge, now));
PrintStatus(edge);
}
int BuildStatus::BuildEdgeFinished(Edge* edge) {
timeval now;
gettimeofday(&now, NULL);
++finished_edges_;
if (verbosity_ != BuildConfig::QUIET) {
if (smart_terminal_ && verbosity_ == BuildConfig::NORMAL) {
PrintStatus(edge);
if (finished_edges_ == total_edges_)
printf("\n");
} else {
if (now.tv_sec - last_update_ > 5) {
printf("%.1f%% %d/%d\n", finished_edges_ * 100 / (float)total_edges_,
finished_edges_, total_edges_);
last_update_ = now.tv_sec;
}
}
}
RunningEdgeMap::iterator i = running_edges_.find(edge);
timeval delta;
timersub(&now, &i->second, &delta);
int ms = (delta.tv_sec * 1000) + (delta.tv_usec / 1000);
running_edges_.erase(i);
return ms;
}
void BuildStatus::PrintStatus(Edge* edge) {
switch (verbosity_) {
case BuildConfig::QUIET:
return;
case BuildConfig::VERBOSE:
printf("%s\n", edge->EvaluateCommand().c_str());
break;
default: {
string to_print = edge->GetDescription();
if (to_print.empty() || verbosity_ == BuildConfig::VERBOSE)
to_print = edge->EvaluateCommand();
if (smart_terminal_) {
printf("\r[%d/%d] %s\e[K", finished_edges_, total_edges_,
to_print.c_str());
fflush(stdout);
} else {
printf("%s\n", to_print.c_str());
}
}
}
}
Plan::Plan() : command_edges_(0) {}
bool Plan::AddTarget(Node* node, string* err) {
vector<Node*> stack;
return AddSubTarget(node, &stack, err);
}
bool Plan::AddSubTarget(Node* node, vector<Node*>* stack, string* err) {
Edge* edge = node->in_edge_;
if (!edge) { // Leaf node.
if (node->dirty_) {
string referenced;
if (!stack->empty())
referenced = ", needed by '" + stack->back()->file_->path_ + "',";
*err = "'" + node->file_->path_ + "'" + referenced + " missing "
"and no known rule to make it";
}
return false;
}
assert(edge);
if (CheckDependencyCycle(node, stack, err))
return false;
if (!node->dirty())
return false; // Don't need to do anything.
if (want_.find(edge) != want_.end())
return true; // We've already enqueued it.
want_.insert(edge);
if (!edge->is_phony())
++command_edges_;
stack->push_back(node);
bool awaiting_inputs = false;
for (vector<Node*>::iterator i = edge->inputs_.begin();
i != edge->inputs_.end(); ++i) {
if (!edge->is_implicit(i - edge->inputs_.begin()) &&
AddSubTarget(*i, stack, err)) {
awaiting_inputs = true;
} else if (!err->empty()) {
return false;
}
}
assert(stack->back() == node);
stack->pop_back();
if (!awaiting_inputs)
ready_.insert(edge);
return true;
}
bool Plan::CheckDependencyCycle(Node* node, vector<Node*>* stack, string* err) {
vector<Node*>::reverse_iterator ri =
find(stack->rbegin(), stack->rend(), node);
if (ri == stack->rend())
return false;
// Add this node onto the stack to make it clearer where the loop
// is.
stack->push_back(node);
vector<Node*>::iterator start = find(stack->begin(), stack->end(), node);
*err = "dependency cycle: ";
for (vector<Node*>::iterator i = start; i != stack->end(); ++i) {
if (i != start)
err->append(" -> ");
err->append((*i)->file_->path_);
}
return true;
}
Edge* Plan::FindWork() {
if (ready_.empty())
return NULL;
set<Edge*>::iterator i = ready_.begin();
Edge* edge = *i;
ready_.erase(i);
return edge;
}
void Plan::EdgeFinished(Edge* edge) {
want_.erase(edge);
// Check off any nodes we were waiting for with this edge.
for (vector<Node*>::iterator i = edge->outputs_.begin();
i != edge->outputs_.end(); ++i) {
NodeFinished(*i);
}
}
void Plan::NodeFinished(Node* node) {
// See if we we want any edges from this node.
for (vector<Edge*>::iterator i = node->out_edges_.begin();
i != node->out_edges_.end(); ++i) {
if (want_.find(*i) != want_.end()) {
// See if the edge is now ready.
bool ready = true;
for (vector<Node*>::iterator j = (*i)->inputs_.begin();
j != (*i)->inputs_.end(); ++j) {
if ((*j)->dirty()) {
ready = false;
break;
}
}
if (ready)
ready_.insert(*i);
}
}
}
void Plan::Dump() {
printf("pending: %d\n", (int)want_.size());
for (set<Edge*>::iterator i = want_.begin(); i != want_.end(); ++i) {
(*i)->Dump();
}
printf("ready: %d\n", (int)ready_.size());
}
struct RealCommandRunner : public CommandRunner {
RealCommandRunner(const BuildConfig& config) : config_(config) {}
virtual ~RealCommandRunner() {}
virtual bool CanRunMore();
virtual bool StartCommand(Edge* edge);
virtual bool WaitForCommands();
virtual Edge* NextFinishedCommand(bool* success);
const BuildConfig& config_;
SubprocessSet subprocs_;
map<Subprocess*, Edge*> subproc_to_edge_;
};
bool RealCommandRunner::CanRunMore() {
return ((int)subprocs_.running_.size()) < config_.parallelism;
}
bool RealCommandRunner::StartCommand(Edge* edge) {
string command = edge->EvaluateCommand();
Subprocess* subproc = new Subprocess;
subproc_to_edge_.insert(make_pair(subproc, edge));
if (!subproc->Start(command))
return false;
subprocs_.Add(subproc);
return true;
}
bool RealCommandRunner::WaitForCommands() {
if (subprocs_.running_.empty())
return false;
while (subprocs_.finished_.empty()) {
subprocs_.DoWork();
}
return true;
}
Edge* RealCommandRunner::NextFinishedCommand(bool* success) {
Subprocess* subproc = subprocs_.NextFinished();
if (!subproc)
return NULL;
*success = subproc->Finish();
map<Subprocess*, Edge*>::iterator i = subproc_to_edge_.find(subproc);
Edge* edge = i->second;
subproc_to_edge_.erase(i);
if (!*success ||
!subproc->stdout_.buf_.empty() ||
!subproc->stderr_.buf_.empty()) {
// Print the command that is spewing before printing its output.
// Print the full command when it failed, otherwise the short name if
// available.
string to_print = edge->GetDescription();
if (to_print.empty() ||
config_.verbosity == BuildConfig::VERBOSE ||
!*success) {
to_print = edge->EvaluateCommand();
}
printf("\n%s%s\n", *success ? "" : "FAILED: ", to_print.c_str());
if (!subproc->stdout_.buf_.empty())
printf("%s\n", subproc->stdout_.buf_.c_str());
if (!subproc->stderr_.buf_.empty())
printf("%s\n", subproc->stderr_.buf_.c_str());
}
delete subproc;
return edge;
}
struct DryRunCommandRunner : public CommandRunner {
virtual ~DryRunCommandRunner() {}
virtual bool CanRunMore() {
return true;
}
virtual bool StartCommand(Edge* edge) {
finished_.push(edge);
return true;
}
virtual bool WaitForCommands() {
return true;
}
virtual Edge* NextFinishedCommand(bool* success) {
if (finished_.empty())
return NULL;
*success = true;
Edge* edge = finished_.front();
finished_.pop();
return edge;
}
queue<Edge*> finished_;
};
Builder::Builder(State* state, const BuildConfig& config)
: state_(state) {
disk_interface_ = new RealDiskInterface;
if (config.dry_run)
command_runner_ = new DryRunCommandRunner;
else
command_runner_ = new RealCommandRunner(config);
status_ = new BuildStatus;
status_->verbosity_ = config.verbosity;
log_ = state->build_log_;
}
Node* Builder::AddTarget(const string& name, string* err) {
Node* node = state_->LookupNode(name);
if (!node) {
*err = "unknown target: '" + name + "'";
return NULL;
}
node->file_->StatIfNecessary(disk_interface_);
if (node->in_edge_) {
if (!node->in_edge_->RecomputeDirty(state_, disk_interface_, err))
return NULL;
}
if (!node->dirty_)
return NULL; // Intentionally no error.
if (!plan_.AddTarget(node, err))
return NULL;
return node;
}
bool Builder::Build(string* err) {
if (!plan_.more_to_do()) {
*err = "no work to do";
return true;
}
status_->PlanHasTotalEdges(plan_.command_edge_count());
while (plan_.more_to_do()) {
while (command_runner_->CanRunMore()) {
Edge* edge = plan_.FindWork();
if (!edge)
break;
if (!StartEdge(edge, err))
return false;
if (edge->is_phony())
FinishEdge(edge);
}
if (!plan_.more_to_do())
break;
bool success;
if (Edge* edge = command_runner_->NextFinishedCommand(&success)) {
if (!success) {
*err = "subcommand failed";
return false;
}
FinishEdge(edge);
} else {
if (!command_runner_->WaitForCommands()) {
*err = "stuck [this is a bug]";
return false;
}
}
}
return true;
}
bool Builder::StartEdge(Edge* edge, string* err) {
if (edge->is_phony())
return true;
status_->BuildEdgeStarted(edge);
// Create directories necessary for outputs.
// XXX: this will block; do we care?
for (vector<Node*>::iterator i = edge->outputs_.begin();
i != edge->outputs_.end(); ++i) {
if (!disk_interface_->MakeDirs((*i)->file_->path_))
return false;
}
// Compute command and start it.
string command = edge->EvaluateCommand();
if (!command_runner_->StartCommand(edge)) {
err->assign("command '" + command + "' failed.");
return false;
}
return true;
}
void Builder::FinishEdge(Edge* edge) {
for (vector<Node*>::iterator i = edge->outputs_.begin();
i != edge->outputs_.end(); ++i) {
// XXX check that the output actually changed
// XXX just notify node and have it propagate?
(*i)->dirty_ = false;
}
plan_.EdgeFinished(edge);
if (edge->is_phony())
return;
int ms = status_->BuildEdgeFinished(edge);
if (log_)
log_->RecordCommand(edge, ms);
}
<commit_msg>limit output width to prevent line-wrapping<commit_after>// Copyright 2011 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "build.h"
#include <stdio.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <sys/termios.h>
#include "build_log.h"
#include "graph.h"
#include "ninja.h"
#include "subprocess.h"
struct BuildStatus {
BuildStatus();
void PlanHasTotalEdges(int total);
void BuildEdgeStarted(Edge* edge);
// Returns the time the edge took, in ms.
int BuildEdgeFinished(Edge* edge);
void PrintStatus(Edge* edge);
time_t last_update_;
int finished_edges_, total_edges_;
typedef map<Edge*, timeval> RunningEdgeMap;
RunningEdgeMap running_edges_;
BuildConfig::Verbosity verbosity_;
// Whether we can do fancy terminal control codes.
bool smart_terminal_;
};
BuildStatus::BuildStatus()
: last_update_(time(NULL)), finished_edges_(0), total_edges_(0),
verbosity_(BuildConfig::NORMAL) {
const char* term = getenv("TERM");
smart_terminal_ = isatty(1) && term && string(term) != "dumb";
}
void BuildStatus::PlanHasTotalEdges(int total) {
total_edges_ = total;
}
void BuildStatus::BuildEdgeStarted(Edge* edge) {
timeval now;
gettimeofday(&now, NULL);
running_edges_.insert(make_pair(edge, now));
PrintStatus(edge);
}
int BuildStatus::BuildEdgeFinished(Edge* edge) {
timeval now;
gettimeofday(&now, NULL);
++finished_edges_;
if (verbosity_ != BuildConfig::QUIET) {
if (smart_terminal_ && verbosity_ == BuildConfig::NORMAL) {
PrintStatus(edge);
if (finished_edges_ == total_edges_)
printf("\n");
} else {
if (now.tv_sec - last_update_ > 5) {
printf("%.1f%% %d/%d\n", finished_edges_ * 100 / (float)total_edges_,
finished_edges_, total_edges_);
last_update_ = now.tv_sec;
}
}
}
RunningEdgeMap::iterator i = running_edges_.find(edge);
timeval delta;
timersub(&now, &i->second, &delta);
int ms = (delta.tv_sec * 1000) + (delta.tv_usec / 1000);
running_edges_.erase(i);
return ms;
}
void BuildStatus::PrintStatus(Edge* edge) {
switch (verbosity_) {
case BuildConfig::QUIET:
return;
case BuildConfig::VERBOSE:
printf("%s\n", edge->EvaluateCommand().c_str());
break;
default: {
string to_print = edge->GetDescription();
if (to_print.empty() || verbosity_ == BuildConfig::VERBOSE)
to_print = edge->EvaluateCommand();
if (smart_terminal_) {
// Limit output to width of the terminal so we don't cause line-wrapping.
winsize size;
if (ioctl(0, TIOCGWINSZ, &size) == 0) {
const int kMargin = 15; // Space for [xxx/yyy] and "...".
if (to_print.size() + kMargin > size.ws_col) {
int substr = to_print.size() + kMargin - size.ws_col;
to_print = "..." + to_print.substr(substr);
}
}
printf("\r[%d/%d] %s\e[K", finished_edges_, total_edges_,
to_print.c_str());
fflush(stdout);
} else {
printf("%s\n", to_print.c_str());
}
}
}
}
Plan::Plan() : command_edges_(0) {}
bool Plan::AddTarget(Node* node, string* err) {
vector<Node*> stack;
return AddSubTarget(node, &stack, err);
}
bool Plan::AddSubTarget(Node* node, vector<Node*>* stack, string* err) {
Edge* edge = node->in_edge_;
if (!edge) { // Leaf node.
if (node->dirty_) {
string referenced;
if (!stack->empty())
referenced = ", needed by '" + stack->back()->file_->path_ + "',";
*err = "'" + node->file_->path_ + "'" + referenced + " missing "
"and no known rule to make it";
}
return false;
}
assert(edge);
if (CheckDependencyCycle(node, stack, err))
return false;
if (!node->dirty())
return false; // Don't need to do anything.
if (want_.find(edge) != want_.end())
return true; // We've already enqueued it.
want_.insert(edge);
if (!edge->is_phony())
++command_edges_;
stack->push_back(node);
bool awaiting_inputs = false;
for (vector<Node*>::iterator i = edge->inputs_.begin();
i != edge->inputs_.end(); ++i) {
if (!edge->is_implicit(i - edge->inputs_.begin()) &&
AddSubTarget(*i, stack, err)) {
awaiting_inputs = true;
} else if (!err->empty()) {
return false;
}
}
assert(stack->back() == node);
stack->pop_back();
if (!awaiting_inputs)
ready_.insert(edge);
return true;
}
bool Plan::CheckDependencyCycle(Node* node, vector<Node*>* stack, string* err) {
vector<Node*>::reverse_iterator ri =
find(stack->rbegin(), stack->rend(), node);
if (ri == stack->rend())
return false;
// Add this node onto the stack to make it clearer where the loop
// is.
stack->push_back(node);
vector<Node*>::iterator start = find(stack->begin(), stack->end(), node);
*err = "dependency cycle: ";
for (vector<Node*>::iterator i = start; i != stack->end(); ++i) {
if (i != start)
err->append(" -> ");
err->append((*i)->file_->path_);
}
return true;
}
Edge* Plan::FindWork() {
if (ready_.empty())
return NULL;
set<Edge*>::iterator i = ready_.begin();
Edge* edge = *i;
ready_.erase(i);
return edge;
}
void Plan::EdgeFinished(Edge* edge) {
want_.erase(edge);
// Check off any nodes we were waiting for with this edge.
for (vector<Node*>::iterator i = edge->outputs_.begin();
i != edge->outputs_.end(); ++i) {
NodeFinished(*i);
}
}
void Plan::NodeFinished(Node* node) {
// See if we we want any edges from this node.
for (vector<Edge*>::iterator i = node->out_edges_.begin();
i != node->out_edges_.end(); ++i) {
if (want_.find(*i) != want_.end()) {
// See if the edge is now ready.
bool ready = true;
for (vector<Node*>::iterator j = (*i)->inputs_.begin();
j != (*i)->inputs_.end(); ++j) {
if ((*j)->dirty()) {
ready = false;
break;
}
}
if (ready)
ready_.insert(*i);
}
}
}
void Plan::Dump() {
printf("pending: %d\n", (int)want_.size());
for (set<Edge*>::iterator i = want_.begin(); i != want_.end(); ++i) {
(*i)->Dump();
}
printf("ready: %d\n", (int)ready_.size());
}
struct RealCommandRunner : public CommandRunner {
RealCommandRunner(const BuildConfig& config) : config_(config) {}
virtual ~RealCommandRunner() {}
virtual bool CanRunMore();
virtual bool StartCommand(Edge* edge);
virtual bool WaitForCommands();
virtual Edge* NextFinishedCommand(bool* success);
const BuildConfig& config_;
SubprocessSet subprocs_;
map<Subprocess*, Edge*> subproc_to_edge_;
};
bool RealCommandRunner::CanRunMore() {
return ((int)subprocs_.running_.size()) < config_.parallelism;
}
bool RealCommandRunner::StartCommand(Edge* edge) {
string command = edge->EvaluateCommand();
Subprocess* subproc = new Subprocess;
subproc_to_edge_.insert(make_pair(subproc, edge));
if (!subproc->Start(command))
return false;
subprocs_.Add(subproc);
return true;
}
bool RealCommandRunner::WaitForCommands() {
if (subprocs_.running_.empty())
return false;
while (subprocs_.finished_.empty()) {
subprocs_.DoWork();
}
return true;
}
Edge* RealCommandRunner::NextFinishedCommand(bool* success) {
Subprocess* subproc = subprocs_.NextFinished();
if (!subproc)
return NULL;
*success = subproc->Finish();
map<Subprocess*, Edge*>::iterator i = subproc_to_edge_.find(subproc);
Edge* edge = i->second;
subproc_to_edge_.erase(i);
if (!*success ||
!subproc->stdout_.buf_.empty() ||
!subproc->stderr_.buf_.empty()) {
// Print the command that is spewing before printing its output.
// Print the full command when it failed, otherwise the short name if
// available.
string to_print = edge->GetDescription();
if (to_print.empty() ||
config_.verbosity == BuildConfig::VERBOSE ||
!*success) {
to_print = edge->EvaluateCommand();
}
printf("\n%s%s\n", *success ? "" : "FAILED: ", to_print.c_str());
if (!subproc->stdout_.buf_.empty())
printf("%s\n", subproc->stdout_.buf_.c_str());
if (!subproc->stderr_.buf_.empty())
printf("%s\n", subproc->stderr_.buf_.c_str());
}
delete subproc;
return edge;
}
struct DryRunCommandRunner : public CommandRunner {
virtual ~DryRunCommandRunner() {}
virtual bool CanRunMore() {
return true;
}
virtual bool StartCommand(Edge* edge) {
finished_.push(edge);
return true;
}
virtual bool WaitForCommands() {
return true;
}
virtual Edge* NextFinishedCommand(bool* success) {
if (finished_.empty())
return NULL;
*success = true;
Edge* edge = finished_.front();
finished_.pop();
return edge;
}
queue<Edge*> finished_;
};
Builder::Builder(State* state, const BuildConfig& config)
: state_(state) {
disk_interface_ = new RealDiskInterface;
if (config.dry_run)
command_runner_ = new DryRunCommandRunner;
else
command_runner_ = new RealCommandRunner(config);
status_ = new BuildStatus;
status_->verbosity_ = config.verbosity;
log_ = state->build_log_;
}
Node* Builder::AddTarget(const string& name, string* err) {
Node* node = state_->LookupNode(name);
if (!node) {
*err = "unknown target: '" + name + "'";
return NULL;
}
node->file_->StatIfNecessary(disk_interface_);
if (node->in_edge_) {
if (!node->in_edge_->RecomputeDirty(state_, disk_interface_, err))
return NULL;
}
if (!node->dirty_)
return NULL; // Intentionally no error.
if (!plan_.AddTarget(node, err))
return NULL;
return node;
}
bool Builder::Build(string* err) {
if (!plan_.more_to_do()) {
*err = "no work to do";
return true;
}
status_->PlanHasTotalEdges(plan_.command_edge_count());
while (plan_.more_to_do()) {
while (command_runner_->CanRunMore()) {
Edge* edge = plan_.FindWork();
if (!edge)
break;
if (!StartEdge(edge, err))
return false;
if (edge->is_phony())
FinishEdge(edge);
}
if (!plan_.more_to_do())
break;
bool success;
if (Edge* edge = command_runner_->NextFinishedCommand(&success)) {
if (!success) {
*err = "subcommand failed";
return false;
}
FinishEdge(edge);
} else {
if (!command_runner_->WaitForCommands()) {
*err = "stuck [this is a bug]";
return false;
}
}
}
return true;
}
bool Builder::StartEdge(Edge* edge, string* err) {
if (edge->is_phony())
return true;
status_->BuildEdgeStarted(edge);
// Create directories necessary for outputs.
// XXX: this will block; do we care?
for (vector<Node*>::iterator i = edge->outputs_.begin();
i != edge->outputs_.end(); ++i) {
if (!disk_interface_->MakeDirs((*i)->file_->path_))
return false;
}
// Compute command and start it.
string command = edge->EvaluateCommand();
if (!command_runner_->StartCommand(edge)) {
err->assign("command '" + command + "' failed.");
return false;
}
return true;
}
void Builder::FinishEdge(Edge* edge) {
for (vector<Node*>::iterator i = edge->outputs_.begin();
i != edge->outputs_.end(); ++i) {
// XXX check that the output actually changed
// XXX just notify node and have it propagate?
(*i)->dirty_ = false;
}
plan_.EdgeFinished(edge);
if (edge->is_phony())
return;
int ms = status_->BuildEdgeFinished(edge);
if (log_)
log_->RecordCommand(edge, ms);
}
<|endoftext|> |
<commit_before>//
// Screen_HX8353E.cpp
// Library C++ code
// ----------------------------------
// Developed with embedXcode
// http://embedXcode.weebly.com
//
// Project new_screen_HX8353
//
// Created by Rei VILO, mars 07, 2013 09:21
// embedXcode.weebly.com
//
// Apr 25, 2014
// Support for new LaunchPads with
// . MSP430F5529
// . LM4F120H5QR TM4C123GH6PM
// . TM4C1294NCPDT TM4C1294XNCZAD
//
//
// Copyright © Rei VILO, 2013-2014
// License CC = BY NC SA
//
// See Screen_HX8353E.h and ReadMe.txt for references
//
// Library header
#include "Screen_HX8353E.h"
///
#define HX8353E_WIDTH 128
#define HX8353E_HEIGHT 128
#define HX8353E_MADCTL_MY 0x80
#define HX8353E_MADCTL_MX 0x40
#define HX8353E_MADCTL_MV 0x20
#define HX8353E_MADCTL_ML 0x10
#define HX8353E_MADCTL_RGB 0x08
#define HX8353E_MADCTL_MH 0x04
#define HX8353E_NOP 0x00
#define HX8353E_SWRESET 0x01
#define HX8353E_RDDID 0x04
#define HX8353E_RDDST 0x09
#define HX8353E_SLPIN 0x10
#define HX8353E_SLPOUT 0x11
#define HX8353E_PTLON 0x12
#define HX8353E_NORON 0x13
#define HX8353E_INVOFF 0x20
#define HX8353E_INVON 0x21
#define HX8353E_GAMSET 0x26
#define HX8353E_DISPOFF 0x28
#define HX8353E_DISPON 0x29
#define HX8353E_CASET 0x2A
#define HX8353E_RASET 0x2B
#define HX8353E_RAMWR 0x2C
#define HX8353E_RGBSET 0x2d
#define HX8353E_RAMRD 0x2E
#define HX8353E_PTLAR 0x30
#define HX8353E_MADCTL 0x36
#define HX8353E_COLMOD 0x3A
#define HX8353E_SETPWCTR 0xB1
#define HX8353E_SETDISPL 0xB2
#define HX8353E_FRMCTR3 0xB3
#define HX8353E_SETCYC 0xB4
#define HX8353E_SETBGP 0xb5
#define HX8353E_SETVCOM 0xB6
#define HX8353E_SETSTBA 0xC0
#define HX8353E_SETID 0xC3
#define HX8353E_GETHID 0xd0
#define HX8353E_SETGAMMA 0xE0
Screen_HX8353E::Screen_HX8353E() {
#if defined(__LM4F120H5QR__) || defined(__MSP430F5529__) || defined(__TM4C123GH6PM__) || defined(__TM4C1294NCPDT__) || defined(__TM4C1294XNCZAD__)
_pinReset = 17;
_pinDataCommand = 31;
_pinChipSelect = 13;
_pinBacklight = NULL;
#else
#error Platform not supported
#endif
}
Screen_HX8353E::Screen_HX8353E(uint8_t resetPin, uint8_t dataCommandPin, uint8_t chipSelectPin, uint8_t backlightPin)
{
_pinReset = resetPin;
_pinDataCommand = dataCommandPin;
_pinChipSelect = chipSelectPin;
_pinBacklight = backlightPin;
};
void Screen_HX8353E::begin()
{
#if defined(__LM4F120H5QR__)
SPI.setModule(2);
#endif
SPI.begin();
SPI.setClockDivider(SPI_CLOCK_DIV2);
SPI.setBitOrder(MSBFIRST);
SPI.setDataMode(SPI_MODE0);
if (_pinReset!=NULL) pinMode(_pinReset, OUTPUT);
if (_pinBacklight!=NULL) pinMode(_pinBacklight, OUTPUT);
pinMode(_pinDataCommand, OUTPUT);
pinMode(_pinChipSelect, OUTPUT);
if (_pinBacklight!=NULL) digitalWrite(_pinBacklight, HIGH);
if (_pinReset!=NULL) digitalWrite(_pinReset, 1);
delay(100);
if (_pinReset!=NULL) digitalWrite(_pinReset, 0);
delay(50);
if (_pinReset!=NULL) digitalWrite(_pinReset, 1);
delay(120);
_writeCommand(HX8353E_SWRESET);
delay(150);
_writeCommand(HX8353E_SLPOUT);
delay(200);
_writeRegister(HX8353E_GAMSET, 0x04);
_writeCommand(HX8353E_SETPWCTR);
_writeData88(0x0A, 0x14);
_writeCommand(HX8353E_SETSTBA);
_writeData88(0x0A, 0x00);
_writeRegister(HX8353E_COLMOD, 0x05);
delay(10);
_writeRegister(HX8353E_MADCTL, HX8353E_MADCTL_RGB);
_writeCommand(HX8353E_CASET);
_writeData8888(0x00, 0x00, 0x00, 0x79);
_writeCommand(HX8353E_RASET);
_writeData8888(0x00, 0x00, 0x00, 0x79);
_writeCommand(HX8353E_NORON);
delay(10);
_writeCommand(HX8353E_DISPON);
delay(120);
_writeCommand(HX8353E_RAMWR);
setBacklight(true);
setOrientation(0);
_screenWidth = HX8353E_WIDTH;
_screenHeigth = HX8353E_HEIGHT;
_penSolid = false;
_fontSolid = true;
_flagRead = false;
_touchTrim = 0;
clear();
}
String Screen_HX8353E::WhoAmI()
{
return "LCD MKII BoosterPack";
}
void Screen_HX8353E::invert(boolean flag)
{
_writeCommand(flag ? HX8353E_INVON : HX8353E_INVOFF);
}
void Screen_HX8353E::setBacklight(boolean flag)
{
if (_pinBacklight!=NULL) digitalWrite(_pinBacklight, flag);
}
void Screen_HX8353E::setDisplay(boolean flag)
{
if (_pinBacklight!=NULL) setBacklight(flag);
}
void Screen_HX8353E::setOrientation(uint8_t orientation)
{
_orientation = orientation % 4;
_writeCommand(HX8353E_MADCTL);
switch (_orientation) {
case 0:
_writeData(HX8353E_MADCTL_MX | HX8353E_MADCTL_MY | HX8353E_MADCTL_RGB);
break;
case 1:
_writeData(HX8353E_MADCTL_MY | HX8353E_MADCTL_MV | HX8353E_MADCTL_RGB);
break;
case 2:
_writeData(HX8353E_MADCTL_RGB);
break;
case 3:
_writeData(HX8353E_MADCTL_MX | HX8353E_MADCTL_MV | HX8353E_MADCTL_RGB);
break;
}
}
void Screen_HX8353E::_fastFill(uint16_t x1, uint16_t y1, uint16_t x2, uint16_t y2, uint16_t colour)
{
if (x1 > x2) _swap(x1, x2);
if (y1 > y2) _swap(y1, y2);
_setWindow(x1, y1, x2, y2);
digitalWrite(_pinDataCommand, HIGH);
digitalWrite(_pinChipSelect, LOW);
uint8_t hi = highByte(colour);
uint8_t lo = lowByte(colour);
for (uint32_t t=(uint32_t)(y2-y1+1)*(x2-x1+1); t>0; t--) {
SPI.transfer(hi);
SPI.transfer(lo);
}
digitalWrite(_pinChipSelect, HIGH);
}
void Screen_HX8353E::_setPoint(uint16_t x1, uint16_t y1, uint16_t colour)
{
if( (x1 < 0) || (x1 >= screenSizeX()) || (y1 < 0) || (y1 >= screenSizeY()) ) return;
_setWindow(x1, y1, x1+1, y1+1);
_writeData16(colour);
}
void Screen_HX8353E::_setWindow(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1)
{
switch (_orientation) {
case 0:
x0 += 2;
y0 += 3;
x1 += 2;
y1 += 3;
break;
case 1:
x0 += 3;
y0 += 2;
x1 += 3;
y1 += 2;
break;
case 2:
x0 += 2;
y0 += 1;
x1 += 2;
y1 += 1;
break;
case 3:
x0 += 1;
y0 += 2;
x1 += 1;
y1 += 2;
break;
default:
break;
}
_writeCommand(HX8353E_CASET);
_writeData16(x0);
_writeData16(x1);
_writeCommand(HX8353E_RASET);
_writeData16(y0);
_writeData16(y1);
_writeCommand(HX8353E_RAMWR);
}
void Screen_HX8353E::_writeRegister(uint8_t command8, uint8_t data8)
{
_writeCommand(command8);
_writeData(data8);
}
void Screen_HX8353E::_writeCommand(uint8_t command8)
{
digitalWrite(_pinDataCommand, LOW);
digitalWrite(_pinChipSelect, LOW);
SPI.transfer(command8);
digitalWrite(_pinChipSelect, HIGH);
}
void Screen_HX8353E::_writeData(uint8_t data8)
{
digitalWrite(_pinDataCommand, HIGH);
digitalWrite(_pinChipSelect, LOW);
SPI.transfer(data8);
digitalWrite(_pinChipSelect, HIGH);
}
void Screen_HX8353E::_writeData16(uint16_t data16)
{
digitalWrite(_pinDataCommand, HIGH);
digitalWrite(_pinChipSelect, LOW);
SPI.transfer(highByte(data16));
SPI.transfer(lowByte(data16));
digitalWrite(_pinChipSelect, HIGH);
}
void Screen_HX8353E::_writeData88(uint8_t dataHigh8, uint8_t dataLow8)
{
digitalWrite(_pinDataCommand, HIGH);
digitalWrite(_pinChipSelect, LOW);
SPI.transfer(dataHigh8);
SPI.transfer(dataLow8);
digitalWrite(_pinChipSelect, HIGH);
}
void Screen_HX8353E::_writeData8888(uint8_t dataHigh8, uint8_t dataLow8, uint8_t data8_3, uint8_t data8_4)
{
_writeData(dataHigh8);
_writeData(dataLow8);
_writeData(data8_3);
_writeData(data8_4);
}
void Screen_HX8353E::_getRawTouch(uint16_t &x0, uint16_t &y0, uint16_t &z0)
{
x0 = 0;
y0 = 0;
z0 = 0;
}
<commit_msg>Fix compilation errors for EduBPMKII_Screen<commit_after>//
// Screen_HX8353E.cpp
// Library C++ code
// ----------------------------------
// Developed with embedXcode
// http://embedXcode.weebly.com
//
// Project new_screen_HX8353
//
// Created by Rei VILO, mars 07, 2013 09:21
// embedXcode.weebly.com
//
// Apr 25, 2014
// Support for new LaunchPads with
// . MSP430F5529
// . LM4F120H5QR TM4C123GH6PM
// . TM4C1294NCPDT TM4C1294XNCZAD
//
//
// Copyright © Rei VILO, 2013-2014
// License CC = BY NC SA
//
// See Screen_HX8353E.h and ReadMe.txt for references
//
// Library header
#include "Screen_HX8353E.h"
///
#define HX8353E_WIDTH 128
#define HX8353E_HEIGHT 128
#define HX8353E_MADCTL_MY 0x80
#define HX8353E_MADCTL_MX 0x40
#define HX8353E_MADCTL_MV 0x20
#define HX8353E_MADCTL_ML 0x10
#define HX8353E_MADCTL_RGB 0x08
#define HX8353E_MADCTL_MH 0x04
#define HX8353E_NOP 0x00
#define HX8353E_SWRESET 0x01
#define HX8353E_RDDID 0x04
#define HX8353E_RDDST 0x09
#define HX8353E_SLPIN 0x10
#define HX8353E_SLPOUT 0x11
#define HX8353E_PTLON 0x12
#define HX8353E_NORON 0x13
#define HX8353E_INVOFF 0x20
#define HX8353E_INVON 0x21
#define HX8353E_GAMSET 0x26
#define HX8353E_DISPOFF 0x28
#define HX8353E_DISPON 0x29
#define HX8353E_CASET 0x2A
#define HX8353E_RASET 0x2B
#define HX8353E_RAMWR 0x2C
#define HX8353E_RGBSET 0x2d
#define HX8353E_RAMRD 0x2E
#define HX8353E_PTLAR 0x30
#define HX8353E_MADCTL 0x36
#define HX8353E_COLMOD 0x3A
#define HX8353E_SETPWCTR 0xB1
#define HX8353E_SETDISPL 0xB2
#define HX8353E_FRMCTR3 0xB3
#define HX8353E_SETCYC 0xB4
#define HX8353E_SETBGP 0xb5
#define HX8353E_SETVCOM 0xB6
#define HX8353E_SETSTBA 0xC0
#define HX8353E_SETID 0xC3
#define HX8353E_GETHID 0xd0
#define HX8353E_SETGAMMA 0xE0
Screen_HX8353E::Screen_HX8353E() {
#if defined(__MSP432P401R__) || defined(__LM4F120H5QR__) || defined(__MSP430F5529__) || defined(__TM4C123GH6PM__) || defined(__TM4C1294NCPDT__) || defined(__TM4C1294XNCZAD__)
_pinReset = 17;
_pinDataCommand = 31;
_pinChipSelect = 13;
_pinBacklight = 0;
#else
#error Platform not supported
#endif
}
Screen_HX8353E::Screen_HX8353E(uint8_t resetPin, uint8_t dataCommandPin, uint8_t chipSelectPin, uint8_t backlightPin)
{
_pinReset = resetPin;
_pinDataCommand = dataCommandPin;
_pinChipSelect = chipSelectPin;
_pinBacklight = backlightPin;
};
void Screen_HX8353E::begin()
{
#if defined(__LM4F120H5QR__)
SPI.setModule(2);
#endif
SPI.begin();
SPI.setClockDivider(SPI_CLOCK_DIV2);
SPI.setBitOrder(MSBFIRST);
SPI.setDataMode(SPI_MODE0);
if (_pinReset!=0) pinMode(_pinReset, OUTPUT);
if (_pinBacklight!=0) pinMode(_pinBacklight, OUTPUT);
pinMode(_pinDataCommand, OUTPUT);
pinMode(_pinChipSelect, OUTPUT);
if (_pinBacklight!=0) digitalWrite(_pinBacklight, HIGH);
if (_pinReset!=0) digitalWrite(_pinReset, 1);
delay(100);
if (_pinReset!=0) digitalWrite(_pinReset, 0);
delay(50);
if (_pinReset!=0) digitalWrite(_pinReset, 1);
delay(120);
_writeCommand(HX8353E_SWRESET);
delay(150);
_writeCommand(HX8353E_SLPOUT);
delay(200);
_writeRegister(HX8353E_GAMSET, 0x04);
_writeCommand(HX8353E_SETPWCTR);
_writeData88(0x0A, 0x14);
_writeCommand(HX8353E_SETSTBA);
_writeData88(0x0A, 0x00);
_writeRegister(HX8353E_COLMOD, 0x05);
delay(10);
_writeRegister(HX8353E_MADCTL, HX8353E_MADCTL_RGB);
_writeCommand(HX8353E_CASET);
_writeData8888(0x00, 0x00, 0x00, 0x79);
_writeCommand(HX8353E_RASET);
_writeData8888(0x00, 0x00, 0x00, 0x79);
_writeCommand(HX8353E_NORON);
delay(10);
_writeCommand(HX8353E_DISPON);
delay(120);
_writeCommand(HX8353E_RAMWR);
setBacklight(true);
setOrientation(0);
_screenWidth = HX8353E_WIDTH;
_screenHeigth = HX8353E_HEIGHT;
_penSolid = false;
_fontSolid = true;
_flagRead = false;
_touchTrim = 0;
clear();
}
String Screen_HX8353E::WhoAmI()
{
return "LCD MKII BoosterPack";
}
void Screen_HX8353E::invert(boolean flag)
{
_writeCommand(flag ? HX8353E_INVON : HX8353E_INVOFF);
}
void Screen_HX8353E::setBacklight(boolean flag)
{
if (_pinBacklight!=0) digitalWrite(_pinBacklight, flag);
}
void Screen_HX8353E::setDisplay(boolean flag)
{
if (_pinBacklight!=0) setBacklight(flag);
}
void Screen_HX8353E::setOrientation(uint8_t orientation)
{
_orientation = orientation % 4;
_writeCommand(HX8353E_MADCTL);
switch (_orientation) {
case 0:
_writeData(HX8353E_MADCTL_MX | HX8353E_MADCTL_MY | HX8353E_MADCTL_RGB);
break;
case 1:
_writeData(HX8353E_MADCTL_MY | HX8353E_MADCTL_MV | HX8353E_MADCTL_RGB);
break;
case 2:
_writeData(HX8353E_MADCTL_RGB);
break;
case 3:
_writeData(HX8353E_MADCTL_MX | HX8353E_MADCTL_MV | HX8353E_MADCTL_RGB);
break;
}
}
void Screen_HX8353E::_fastFill(uint16_t x1, uint16_t y1, uint16_t x2, uint16_t y2, uint16_t colour)
{
if (x1 > x2) _swap(x1, x2);
if (y1 > y2) _swap(y1, y2);
_setWindow(x1, y1, x2, y2);
digitalWrite(_pinDataCommand, HIGH);
digitalWrite(_pinChipSelect, LOW);
uint8_t hi = highByte(colour);
uint8_t lo = lowByte(colour);
for (uint32_t t=(uint32_t)(y2-y1+1)*(x2-x1+1); t>0; t--) {
SPI.transfer(hi);
SPI.transfer(lo);
}
digitalWrite(_pinChipSelect, HIGH);
}
void Screen_HX8353E::_setPoint(uint16_t x1, uint16_t y1, uint16_t colour)
{
if( (x1 < 0) || (x1 >= screenSizeX()) || (y1 < 0) || (y1 >= screenSizeY()) ) return;
_setWindow(x1, y1, x1+1, y1+1);
_writeData16(colour);
}
void Screen_HX8353E::_setWindow(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1)
{
switch (_orientation) {
case 0:
x0 += 2;
y0 += 3;
x1 += 2;
y1 += 3;
break;
case 1:
x0 += 3;
y0 += 2;
x1 += 3;
y1 += 2;
break;
case 2:
x0 += 2;
y0 += 1;
x1 += 2;
y1 += 1;
break;
case 3:
x0 += 1;
y0 += 2;
x1 += 1;
y1 += 2;
break;
default:
break;
}
_writeCommand(HX8353E_CASET);
_writeData16(x0);
_writeData16(x1);
_writeCommand(HX8353E_RASET);
_writeData16(y0);
_writeData16(y1);
_writeCommand(HX8353E_RAMWR);
}
void Screen_HX8353E::_writeRegister(uint8_t command8, uint8_t data8)
{
_writeCommand(command8);
_writeData(data8);
}
void Screen_HX8353E::_writeCommand(uint8_t command8)
{
digitalWrite(_pinDataCommand, LOW);
digitalWrite(_pinChipSelect, LOW);
SPI.transfer(command8);
digitalWrite(_pinChipSelect, HIGH);
}
void Screen_HX8353E::_writeData(uint8_t data8)
{
digitalWrite(_pinDataCommand, HIGH);
digitalWrite(_pinChipSelect, LOW);
SPI.transfer(data8);
digitalWrite(_pinChipSelect, HIGH);
}
void Screen_HX8353E::_writeData16(uint16_t data16)
{
digitalWrite(_pinDataCommand, HIGH);
digitalWrite(_pinChipSelect, LOW);
SPI.transfer(highByte(data16));
SPI.transfer(lowByte(data16));
digitalWrite(_pinChipSelect, HIGH);
}
void Screen_HX8353E::_writeData88(uint8_t dataHigh8, uint8_t dataLow8)
{
digitalWrite(_pinDataCommand, HIGH);
digitalWrite(_pinChipSelect, LOW);
SPI.transfer(dataHigh8);
SPI.transfer(dataLow8);
digitalWrite(_pinChipSelect, HIGH);
}
void Screen_HX8353E::_writeData8888(uint8_t dataHigh8, uint8_t dataLow8, uint8_t data8_3, uint8_t data8_4)
{
_writeData(dataHigh8);
_writeData(dataLow8);
_writeData(data8_3);
_writeData(data8_4);
}
void Screen_HX8353E::_getRawTouch(uint16_t &x0, uint16_t &y0, uint16_t &z0)
{
x0 = 0;
y0 = 0;
z0 = 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: indexentrysupplier_ja_phonetic.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: obo $Date$
*
* 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): _______________________________________
*
*
************************************************************************/
#define INDEXENTRYSUPPLIER_ja_phonetic
#include <indexentrysupplier_asian.hxx>
#include <data/indexdata_ja_phonetic.h>
#include <string.h>
namespace com { namespace sun { namespace star { namespace i18n {
rtl::OUString SAL_CALL IndexEntrySupplier_ja_phonetic::getIndexCharacter( const rtl::OUString& rIndexEntry,
const lang::Locale& rLocale, const rtl::OUString& rSortAlgorithm )
throw (com::sun::star::uno::RuntimeException)
{
return IndexEntrySupplier_CJK::getIndexString(rIndexEntry.toChar(), idx,
strstr(implementationName, "syllable") ? syllable : consonant);
}
rtl::OUString SAL_CALL IndexEntrySupplier_ja_phonetic::getIndexKey( const rtl::OUString& IndexEntry,
const rtl::OUString& PhoneticEntry, const lang::Locale& rLocale )
throw (com::sun::star::uno::RuntimeException)
{
return IndexEntrySupplier_CJK::getIndexString(
PhoneticEntry.getLength() > 0 ? PhoneticEntry.toChar() : IndexEntry.toChar(), idx,
strstr(implementationName, "syllable") ? syllable : consonant);
}
sal_Int16 SAL_CALL IndexEntrySupplier_ja_phonetic::compareIndexEntry(
const rtl::OUString& IndexEntry1, const rtl::OUString& PhoneticEntry1, const lang::Locale& rLocale1,
const rtl::OUString& IndexEntry2, const rtl::OUString& PhoneticEntry2, const lang::Locale& rLocale2 )
throw (com::sun::star::uno::RuntimeException)
{
sal_Int16 result = collator->compareString(
IndexEntrySupplier_ja_phonetic::getIndexKey(IndexEntry1, PhoneticEntry1, rLocale1),
IndexEntrySupplier_ja_phonetic::getIndexKey(IndexEntry2, PhoneticEntry2, rLocale2));
if (result == 0)
return IndexEntrySupplier_Common::compareIndexEntry(
IndexEntry1, PhoneticEntry1, rLocale1,
IndexEntry2, PhoneticEntry2, rLocale2);
return result;
}
static sal_Char first[] = "ja_phonetic (alphanumeric first)";
sal_Bool SAL_CALL IndexEntrySupplier_ja_phonetic_alphanumeric_first_by_syllable::loadAlgorithm(
const com::sun::star::lang::Locale& rLocale, const rtl::OUString& SortAlgorithm,
sal_Int32 collatorOptions ) throw (com::sun::star::uno::RuntimeException)
{
aLocale = rLocale;
return collator->loadCollatorAlgorithm(rtl::OUString::createFromAscii(first), rLocale, collatorOptions) == 0;
}
sal_Bool SAL_CALL IndexEntrySupplier_ja_phonetic_alphanumeric_first_by_consonant::loadAlgorithm(
const com::sun::star::lang::Locale& rLocale, const rtl::OUString& SortAlgorithm,
sal_Int32 collatorOptions ) throw (com::sun::star::uno::RuntimeException)
{
aLocale = rLocale;
return collator->loadCollatorAlgorithm(rtl::OUString::createFromAscii(first), rLocale, collatorOptions) == 0;
}
static sal_Char last[] = "ja_phonetic (alphanumeric last)";
sal_Bool SAL_CALL IndexEntrySupplier_ja_phonetic_alphanumeric_last_by_syllable::loadAlgorithm(
const com::sun::star::lang::Locale& rLocale, const rtl::OUString& SortAlgorithm,
sal_Int32 collatorOptions ) throw (com::sun::star::uno::RuntimeException)
{
aLocale = rLocale;
return collator->loadCollatorAlgorithm(rtl::OUString::createFromAscii(last), rLocale, collatorOptions) == 0;
}
sal_Bool SAL_CALL IndexEntrySupplier_ja_phonetic_alphanumeric_last_by_consonant::loadAlgorithm(
const com::sun::star::lang::Locale& rLocale, const rtl::OUString& SortAlgorithm,
sal_Int32 collatorOptions ) throw (com::sun::star::uno::RuntimeException)
{
aLocale = rLocale;
return collator->loadCollatorAlgorithm(rtl::OUString::createFromAscii(last), rLocale, collatorOptions) == 0;
}
} } } }
<commit_msg>INTEGRATION: CWS ooo19126 (1.7.66); FILE MERGED 2005/09/05 17:47:38 rt 1.7.66.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: indexentrysupplier_ja_phonetic.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2005-09-07 17:10:14 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#define INDEXENTRYSUPPLIER_ja_phonetic
#include <indexentrysupplier_asian.hxx>
#include <data/indexdata_ja_phonetic.h>
#include <string.h>
namespace com { namespace sun { namespace star { namespace i18n {
rtl::OUString SAL_CALL IndexEntrySupplier_ja_phonetic::getIndexCharacter( const rtl::OUString& rIndexEntry,
const lang::Locale& rLocale, const rtl::OUString& rSortAlgorithm )
throw (com::sun::star::uno::RuntimeException)
{
return IndexEntrySupplier_CJK::getIndexString(rIndexEntry.toChar(), idx,
strstr(implementationName, "syllable") ? syllable : consonant);
}
rtl::OUString SAL_CALL IndexEntrySupplier_ja_phonetic::getIndexKey( const rtl::OUString& IndexEntry,
const rtl::OUString& PhoneticEntry, const lang::Locale& rLocale )
throw (com::sun::star::uno::RuntimeException)
{
return IndexEntrySupplier_CJK::getIndexString(
PhoneticEntry.getLength() > 0 ? PhoneticEntry.toChar() : IndexEntry.toChar(), idx,
strstr(implementationName, "syllable") ? syllable : consonant);
}
sal_Int16 SAL_CALL IndexEntrySupplier_ja_phonetic::compareIndexEntry(
const rtl::OUString& IndexEntry1, const rtl::OUString& PhoneticEntry1, const lang::Locale& rLocale1,
const rtl::OUString& IndexEntry2, const rtl::OUString& PhoneticEntry2, const lang::Locale& rLocale2 )
throw (com::sun::star::uno::RuntimeException)
{
sal_Int16 result = collator->compareString(
IndexEntrySupplier_ja_phonetic::getIndexKey(IndexEntry1, PhoneticEntry1, rLocale1),
IndexEntrySupplier_ja_phonetic::getIndexKey(IndexEntry2, PhoneticEntry2, rLocale2));
if (result == 0)
return IndexEntrySupplier_Common::compareIndexEntry(
IndexEntry1, PhoneticEntry1, rLocale1,
IndexEntry2, PhoneticEntry2, rLocale2);
return result;
}
static sal_Char first[] = "ja_phonetic (alphanumeric first)";
sal_Bool SAL_CALL IndexEntrySupplier_ja_phonetic_alphanumeric_first_by_syllable::loadAlgorithm(
const com::sun::star::lang::Locale& rLocale, const rtl::OUString& SortAlgorithm,
sal_Int32 collatorOptions ) throw (com::sun::star::uno::RuntimeException)
{
aLocale = rLocale;
return collator->loadCollatorAlgorithm(rtl::OUString::createFromAscii(first), rLocale, collatorOptions) == 0;
}
sal_Bool SAL_CALL IndexEntrySupplier_ja_phonetic_alphanumeric_first_by_consonant::loadAlgorithm(
const com::sun::star::lang::Locale& rLocale, const rtl::OUString& SortAlgorithm,
sal_Int32 collatorOptions ) throw (com::sun::star::uno::RuntimeException)
{
aLocale = rLocale;
return collator->loadCollatorAlgorithm(rtl::OUString::createFromAscii(first), rLocale, collatorOptions) == 0;
}
static sal_Char last[] = "ja_phonetic (alphanumeric last)";
sal_Bool SAL_CALL IndexEntrySupplier_ja_phonetic_alphanumeric_last_by_syllable::loadAlgorithm(
const com::sun::star::lang::Locale& rLocale, const rtl::OUString& SortAlgorithm,
sal_Int32 collatorOptions ) throw (com::sun::star::uno::RuntimeException)
{
aLocale = rLocale;
return collator->loadCollatorAlgorithm(rtl::OUString::createFromAscii(last), rLocale, collatorOptions) == 0;
}
sal_Bool SAL_CALL IndexEntrySupplier_ja_phonetic_alphanumeric_last_by_consonant::loadAlgorithm(
const com::sun::star::lang::Locale& rLocale, const rtl::OUString& SortAlgorithm,
sal_Int32 collatorOptions ) throw (com::sun::star::uno::RuntimeException)
{
aLocale = rLocale;
return collator->loadCollatorAlgorithm(rtl::OUString::createFromAscii(last), rLocale, collatorOptions) == 0;
}
} } } }
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <spikehw.h>
SpikeHw *spikeHw;
int main(int argc, const char **argv)
{
spikeHw = new SpikeHw();
// not needed yet
//spikeHw->setupDma(memfd);
// query mmcm and interrupt status
spikeHw->status();
// read boot rom
uint32_t firstword;
spikeHw->read(0x000000 + 0x000, (uint8_t *)&firstword);
fprintf(stderr, "First word of boot ROM %08x (expected %08x)\n", firstword, 0x00001137);
// read ethernet identification register
uint32_t id;
spikeHw->read(0x180000 + 0x4f8, (uint8_t *)&id);
fprintf(stderr, "AXI Ethernet Identification %08x (expected %08x)\n", id, 0x09000000);
// put flash in query mode
spikeHw->setFlashParameters(50); // divides clock by 50
uint32_t values[4] = { 0x98 };
spikeHw->writeFlash(0x00aa, (uint8_t *)&values[0]);
spikeHw->readFlash(0x0040, (uint8_t *)&values[1]);
spikeHw->readFlash(0x0042, (uint8_t *)&values[2]);
spikeHw->readFlash(0x0044, (uint8_t *)&values[3]);
fprintf(stderr, "Query flash %02x.%02x.%02x %c%c%c (expected QRY)\n", values[1], values[2], values[3], values[1], values[2], values[3]);
return 0;
}
<commit_msg>use the by-16 rather than by-32 CFI addresses<commit_after>#include <stdio.h>
#include <spikehw.h>
SpikeHw *spikeHw;
int main(int argc, const char **argv)
{
spikeHw = new SpikeHw();
// not needed yet
//spikeHw->setupDma(memfd);
// query mmcm and interrupt status
spikeHw->status();
// read boot rom
uint32_t firstword;
spikeHw->read(0x000000 + 0x000, (uint8_t *)&firstword);
fprintf(stderr, "First word of boot ROM %08x (expected %08x)\n", firstword, 0x00001137);
// read ethernet identification register
uint32_t id;
spikeHw->read(0x180000 + 0x4f8, (uint8_t *)&id);
fprintf(stderr, "AXI Ethernet Identification %08x (expected %08x)\n", id, 0x09000000);
// put flash in query mode
spikeHw->setFlashParameters(50); // divides clock by 50
uint32_t values[4] = { 0x98 };
spikeHw->writeFlash(0x00aa, (uint8_t *)&values[0]);
spikeHw->readFlash(0x0020, (uint8_t *)&values[1]);
spikeHw->readFlash(0x0022, (uint8_t *)&values[2]);
spikeHw->readFlash(0x0024, (uint8_t *)&values[3]);
fprintf(stderr, "Query flash %02x.%02x.%02x %c%c%c (expected QRY)\n", values[1], values[2], values[3], values[1], values[2], values[3]);
return 0;
}
<|endoftext|> |
<commit_before>#pragma once
#include "acmacs-base/string.hh"
#include "acmacs-base/fmt.hh"
#include "acmacs-base/to-string.hh"
#include "acmacs-base/float.hh"
#include "acmacs-base/range.hh"
// Simplified version of https://github.com/joboccara/NamedType
// Also see https://github.com/Enhex/phantom_type
// ----------------------------------------------------------------------
namespace acmacs
{
template <typename T, typename Tag> class named_t
{
public:
using value_type = T;
explicit constexpr named_t() = default;
template <typename T2> explicit constexpr named_t(T2&& value) : value_(std::forward<T2>(value)) {}
// template <typename T2, typename = std::enable_if_t<std::is_same_v<T, size_t>>>
// explicit constexpr named_t(T2 value) : value_(static_cast<T>(value)) {}
// template <typename TT> using is_not_reference_t = typename std::enable_if<!std::is_reference<TT>::value, void>::type;
// explicit constexpr named_t(const T& value) : value_(value) {}
// explicit constexpr named_t(T&& value) : value_(std::move(value)) {}
// template <typename T2 = T, typename = is_not_reference_t<T2>> explicit constexpr named_t(T2&& value) : value_(std::move(value)) {}
constexpr T& get() noexcept { return value_; }
constexpr const T& get() const noexcept { return value_; }
constexpr T& operator*() noexcept { return value_; }
constexpr const T& operator*() const noexcept { return value_; }
constexpr const T* operator->() const noexcept { return &value_; }
explicit constexpr operator T&() noexcept { return value_; }
explicit constexpr operator const T&() const noexcept { return value_; }
private:
T value_;
};
template <typename T, typename Tag> constexpr bool operator==(const named_t<T, Tag>& lhs, const named_t<T, Tag>& rhs) noexcept { return lhs.get() == rhs.get(); }
template <typename T, typename Tag> constexpr bool operator!=(const named_t<T, Tag>& lhs, const named_t<T, Tag>& rhs) noexcept { return !operator==(lhs, rhs); }
template <typename T, typename Tag> inline std::string to_string(const named_t<T, Tag>& nt) { return acmacs::to_string(nt.get()); }
// ----------------------------------------------------------------------
template <typename T, typename Tag> class named_number_t : public named_t<T, Tag>
{
public:
template <typename TT> explicit constexpr named_number_t(TT&& value) : named_t<T, Tag>(static_cast<T>(std::forward<TT>(value))) {}
constexpr auto& operator++()
{
++this->get();
return *this;
}
constexpr auto& operator--()
{
--this->get();
return *this;
}
};
template <typename T, typename Tag> constexpr bool operator<(const named_number_t<T, Tag>& lhs, const named_number_t<T, Tag>& rhs) noexcept { return lhs.get() < rhs.get(); }
template <typename T, typename Tag> constexpr bool operator<=(const named_number_t<T, Tag>& lhs, const named_number_t<T, Tag>& rhs) noexcept { return lhs.get() <= rhs.get(); }
template <typename T, typename Tag> constexpr bool operator>(const named_number_t<T, Tag>& lhs, const named_number_t<T, Tag>& rhs) noexcept { return lhs.get() > rhs.get(); }
template <typename T, typename Tag> constexpr bool operator>=(const named_number_t<T, Tag>& lhs, const named_number_t<T, Tag>& rhs) noexcept { return lhs.get() >= rhs.get(); }
template <typename T, typename Tag> constexpr named_number_t<T, Tag> operator+(const named_number_t<T, Tag>& lhs, const named_number_t<T, Tag>& rhs) noexcept { return named_number_t<T, Tag>{lhs.get() + rhs.get()}; }
template <typename T, typename Tag> constexpr named_number_t<T, Tag> operator-(const named_number_t<T, Tag>& lhs, const named_number_t<T, Tag>& rhs) noexcept { return named_number_t<T, Tag>{lhs.get() - rhs.get()}; }
template <typename T, typename Tag> constexpr named_number_t<T, Tag> operator*(const named_number_t<T, Tag>& lhs, const named_number_t<T, Tag>& rhs) noexcept { return named_number_t<T, Tag>{lhs.get() * rhs.get()}; }
// no operator/
// ----------------------------------------------------------------------
template <typename Tag> class named_size_t : public named_number_t<size_t, Tag>
{
public:
using named_number_t<size_t, Tag>::named_number_t;
};
template <typename Tag> constexpr bool operator==(const named_size_t<Tag>& lhs, const named_size_t<Tag>& rhs) noexcept { return lhs.get() == rhs.get(); }
template <typename Tag> constexpr bool operator!=(const named_size_t<Tag>& lhs, const named_size_t<Tag>& rhs) noexcept { return !operator==(lhs, rhs); }
template <typename Tag> range(int, named_size_t<Tag>)->range<named_size_t<Tag>>;
template <typename Tag> range(size_t, named_size_t<Tag>)->range<named_size_t<Tag>>;
template <typename Tag> range(named_size_t<Tag>)->range<named_size_t<Tag>>;
template <typename Tag> range(named_size_t<Tag>, named_size_t<Tag>)->range<named_size_t<Tag>>;
// ----------------------------------------------------------------------
template <typename Tag> class named_double_t : public named_number_t<double, Tag>
{
public:
using named_number_t<double, Tag>::named_number_t;
};
template <typename Tag> constexpr bool operator==(const named_double_t<Tag>& lhs, const named_double_t<Tag>& rhs) noexcept { return float_equal(lhs.get(), rhs.get()); }
template <typename Tag> constexpr bool operator!=(const named_double_t<Tag>& lhs, const named_double_t<Tag>& rhs) noexcept { return !operator==(lhs, rhs); }
// ----------------------------------------------------------------------
template <typename Tag> class named_string_t : public named_t<std::string, Tag>
{
public:
using named_t<std::string, Tag>::named_t;
bool empty() const noexcept { return this->get().empty(); }
size_t size() const noexcept { return this->get().size(); }
char operator[](size_t pos) const { return this->get()[pos]; }
size_t find(const char* s, size_t pos = 0) const noexcept { return this->get().find(s, pos); }
size_t find(char ch, size_t pos = 0) const noexcept { return this->get().find(ch, pos); }
constexpr operator std::string_view() const noexcept { return this->get(); }
int compare(const named_string_t<Tag>& rhs) const { return ::string::compare(this->get(), rhs.get()); }
void assign(std::string_view source) { this->get().assign(source); }
};
template <typename T> constexpr bool operator==(const named_string_t<T>& lhs, const named_string_t<T>& rhs) noexcept { return lhs.get() == rhs.get(); }
template <typename T> constexpr bool operator==(const named_string_t<T>& lhs, const std::string& rhs) noexcept { return lhs.get() == rhs; }
template <typename T> constexpr bool operator==(const named_string_t<T>& lhs, const char* rhs) noexcept { return lhs.get() == rhs; }
template <typename T> constexpr bool operator==(const named_string_t<T>& lhs, std::string_view rhs) noexcept { return lhs.get() == rhs; }
template <typename T, typename R> constexpr bool operator!=(const named_string_t<T>& lhs, R&& rhs) noexcept { return !operator==(lhs, std::forward<R>(rhs)); }
template <typename T> constexpr bool operator<(const named_string_t<T>& lhs, const named_string_t<T>& rhs) noexcept { return lhs.get() < rhs.get(); }
// ----------------------------------------------------------------------
template <typename T, typename Tag> class named_vector_t : public named_t<std::vector<T>, Tag>
{
public:
using value_type = T;
using named_t<std::vector<T>, Tag>::named_t;
constexpr auto begin() const { return this->get().begin(); }
constexpr auto end() const { return this->get().end(); }
constexpr auto begin() { return this->get().begin(); }
constexpr auto end() { return this->get().end(); }
constexpr auto rbegin() { return this->get().rbegin(); }
constexpr auto rend() { return this->get().rend(); }
constexpr auto empty() const { return this->get().empty(); }
constexpr auto size() const { return this->get().size(); }
constexpr auto operator[](size_t index) const { return this->get()[index]; }
constexpr auto& operator[](size_t index) { return this->get()[index]; }
// for std::back_inserter
constexpr void push_back(const T& val) { this->get().push_back(val); }
constexpr void push_back(T&& val) { this->get().push_back(std::forward<T>(val)); }
void remove(const T& val)
{
if (const auto found = std::find(begin(), end(), val); found != end())
this->get().erase(found);
}
// set like
bool exists(const T& val) const { return std::find(begin(), end(), val) != end(); }
void insert_if_not_present(const T& val)
{
if (!exists(val))
push_back(val);
}
void insert_if_not_present(T&& val)
{
if (!exist(val))
push_back(std::forward<T>(val));
}
void merge_in(const named_vector_t<T, Tag>& another)
{
for (const auto& val : another)
insert_if_not_present(val);
}
};
template <typename Tag> constexpr bool operator<(const named_vector_t<std::string, Tag>& lhs, const named_vector_t<std::string, Tag>& rhs) noexcept
{
const auto sz = std::min(lhs.size(), rhs.size());
for (size_t i = 0; i < sz; ++i) {
if (!(lhs[i] == rhs[i]))
return lhs[i] < rhs[i];
}
if (lhs.size() < rhs.size())
return true;
return false;
}
} // namespace acmacs
// ----------------------------------------------------------------------
// template <typename T, typename Tag> struct fmt::formatter<acmacs::named_t<T, Tag>> : fmt::formatter<T> {
// template <typename FormatCtx> auto format(const acmacs::named_t<T, Tag>& nt, FormatCtx& ctx) { return fmt::formatter<T>::format(nt.get(), ctx); }
// };
template <typename Tag> struct fmt::formatter<acmacs::named_size_t<Tag>> : fmt::formatter<size_t> {
template <typename FormatCtx> auto format(const acmacs::named_size_t<Tag>& nt, FormatCtx& ctx) { return fmt::formatter<size_t>::format(nt.get(), ctx); }
};
template <typename Tag> struct fmt::formatter<acmacs::named_double_t<Tag>> : fmt::formatter<double> {
template <typename FormatCtx> auto format(const acmacs::named_double_t<Tag>& nt, FormatCtx& ctx) { return fmt::formatter<double>::format(nt.get(), ctx); }
};
template <typename Tag> struct fmt::formatter<acmacs::named_string_t<Tag>> : fmt::formatter<std::string> {
template <typename FormatCtx> auto format(const acmacs::named_string_t<Tag>& nt, FormatCtx& ctx) { return fmt::formatter<std::string>::format(nt.get(), ctx); }
};
template <typename T, typename Tag> struct fmt::formatter<acmacs::named_vector_t<T, Tag>> : fmt::formatter<std::vector<T>> {
template <typename FormatCtx> auto format(const acmacs::named_vector_t<T, Tag>& vec, FormatCtx& ctx) { return fmt::formatter<std::vector<T>>::format(vec.get(), ctx); }
};
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>named_number_from_string_t<commit_after>#pragma once
#include <variant>
#include "acmacs-base/string.hh"
#include "acmacs-base/fmt.hh"
#include "acmacs-base/to-string.hh"
#include "acmacs-base/float.hh"
#include "acmacs-base/range.hh"
// Simplified version of https://github.com/joboccara/NamedType
// Also see https://github.com/Enhex/phantom_type
// ----------------------------------------------------------------------
namespace acmacs
{
template <typename T, typename Tag> class named_t
{
public:
using value_type = T;
explicit constexpr named_t() = default;
template <typename T2> explicit constexpr named_t(T2&& value) : value_(std::forward<T2>(value)) {}
// template <typename T2, typename = std::enable_if_t<std::is_same_v<T, size_t>>>
// explicit constexpr named_t(T2 value) : value_(static_cast<T>(value)) {}
// template <typename TT> using is_not_reference_t = typename std::enable_if<!std::is_reference<TT>::value, void>::type;
// explicit constexpr named_t(const T& value) : value_(value) {}
// explicit constexpr named_t(T&& value) : value_(std::move(value)) {}
// template <typename T2 = T, typename = is_not_reference_t<T2>> explicit constexpr named_t(T2&& value) : value_(std::move(value)) {}
constexpr T& get() noexcept { return value_; }
constexpr const T& get() const noexcept { return value_; }
constexpr T& operator*() noexcept { return value_; }
constexpr const T& operator*() const noexcept { return value_; }
constexpr const T* operator->() const noexcept { return &value_; }
explicit constexpr operator T&() noexcept { return value_; }
explicit constexpr operator const T&() const noexcept { return value_; }
private:
T value_;
};
template <typename T, typename Tag> constexpr bool operator==(const named_t<T, Tag>& lhs, const named_t<T, Tag>& rhs) noexcept { return lhs.get() == rhs.get(); }
template <typename T, typename Tag> constexpr bool operator!=(const named_t<T, Tag>& lhs, const named_t<T, Tag>& rhs) noexcept { return !operator==(lhs, rhs); }
template <typename T, typename Tag> inline std::string to_string(const named_t<T, Tag>& nt) { return acmacs::to_string(nt.get()); }
// ----------------------------------------------------------------------
template <typename Number, typename Tag> class named_number_t : public named_t<Number, Tag>
{
public:
template <typename TT> explicit constexpr named_number_t(TT&& value) : named_t<Number, Tag>(static_cast<Number>(std::forward<TT>(value))) {}
constexpr auto& operator++()
{
++this->get();
return *this;
}
constexpr auto& operator--()
{
--this->get();
return *this;
}
};
template <typename Number, typename Tag> constexpr bool operator<(const named_number_t<Number, Tag>& lhs, const named_number_t<Number, Tag>& rhs) noexcept { return lhs.get() < rhs.get(); }
template <typename Number, typename Tag> constexpr bool operator<=(const named_number_t<Number, Tag>& lhs, const named_number_t<Number, Tag>& rhs) noexcept { return lhs.get() <= rhs.get(); }
template <typename Number, typename Tag> constexpr bool operator>(const named_number_t<Number, Tag>& lhs, const named_number_t<Number, Tag>& rhs) noexcept { return lhs.get() > rhs.get(); }
template <typename Number, typename Tag> constexpr bool operator>=(const named_number_t<Number, Tag>& lhs, const named_number_t<Number, Tag>& rhs) noexcept { return lhs.get() >= rhs.get(); }
template <typename Number, typename Tag> constexpr named_number_t<Number, Tag> operator+(const named_number_t<Number, Tag>& lhs, const named_number_t<Number, Tag>& rhs) noexcept { return named_number_t<Number, Tag>{lhs.get() + rhs.get()}; }
template <typename Number, typename Tag> constexpr named_number_t<Number, Tag> operator-(const named_number_t<Number, Tag>& lhs, const named_number_t<Number, Tag>& rhs) noexcept { return named_number_t<Number, Tag>{lhs.get() - rhs.get()}; }
template <typename Number, typename Tag> constexpr named_number_t<Number, Tag> operator*(const named_number_t<Number, Tag>& lhs, const named_number_t<Number, Tag>& rhs) noexcept { return named_number_t<Number, Tag>{lhs.get() * rhs.get()}; }
// no operator/
// ----------------------------------------------------------------------
template <typename Tag> class named_size_t : public named_number_t<size_t, Tag>
{
public:
using named_number_t<size_t, Tag>::named_number_t;
};
template <typename Tag> constexpr bool operator==(const named_size_t<Tag>& lhs, const named_size_t<Tag>& rhs) noexcept { return lhs.get() == rhs.get(); }
template <typename Tag> constexpr bool operator!=(const named_size_t<Tag>& lhs, const named_size_t<Tag>& rhs) noexcept { return !operator==(lhs, rhs); }
template <typename Tag> range(int, named_size_t<Tag>)->range<named_size_t<Tag>>;
template <typename Tag> range(size_t, named_size_t<Tag>)->range<named_size_t<Tag>>;
template <typename Tag> range(named_size_t<Tag>)->range<named_size_t<Tag>>;
template <typename Tag> range(named_size_t<Tag>, named_size_t<Tag>)->range<named_size_t<Tag>>;
// ----------------------------------------------------------------------
template <typename Tag> class named_double_t : public named_number_t<double, Tag>
{
public:
using named_number_t<double, Tag>::named_number_t;
};
template <typename Tag> constexpr bool operator==(const named_double_t<Tag>& lhs, const named_double_t<Tag>& rhs) noexcept { return float_equal(lhs.get(), rhs.get()); }
template <typename Tag> constexpr bool operator!=(const named_double_t<Tag>& lhs, const named_double_t<Tag>& rhs) noexcept { return !operator==(lhs, rhs); }
// ----------------------------------------------------------------------
template <typename Number, typename Tag> class named_number_from_string_t : public named_t<std::variant<Number, std::string_view>, Tag>
{
public:
using base_t = named_t<std::variant<Number, std::string_view>, Tag>;
template <typename TT> explicit constexpr named_number_from_string_t(TT&& value) : base_t(std::forward<TT>(value)) {}
Number as_number() const
{
return std::visit(
[]<typename Repr>(Repr content) -> Number {
if constexpr (std::is_same_v<Repr, Number>)
return content;
else
return string::from_chars<Number>(content);
},
base_t::get());
}
std::string as_string() const
{
return std::visit(
[]<typename Repr>(Repr content) -> std::string {
if constexpr (std::is_same_v<Repr, Number>)
return acmacs::to_string(content);
else
return std::string{content};
},
base_t::get());
}
};
template <typename Tag> class named_size_t_from_string_t : public named_number_from_string_t<size_t, Tag>
{
public:
using named_number_from_string_t<size_t, Tag>::named_number_from_string_t;
};
template <typename Tag> class named_double_from_string_t : public named_number_from_string_t<double, Tag>
{
public:
using named_number_from_string_t<double, Tag>::named_number_from_string_t;
};
// ----------------------------------------------------------------------
template <typename Tag> class named_string_t : public named_t<std::string, Tag>
{
public:
using named_t<std::string, Tag>::named_t;
bool empty() const noexcept { return this->get().empty(); }
size_t size() const noexcept { return this->get().size(); }
char operator[](size_t pos) const { return this->get()[pos]; }
size_t find(const char* s, size_t pos = 0) const noexcept { return this->get().find(s, pos); }
size_t find(char ch, size_t pos = 0) const noexcept { return this->get().find(ch, pos); }
constexpr operator std::string_view() const noexcept { return this->get(); }
int compare(const named_string_t<Tag>& rhs) const { return ::string::compare(this->get(), rhs.get()); }
void assign(std::string_view source) { this->get().assign(source); }
};
template <typename T> constexpr bool operator==(const named_string_t<T>& lhs, const named_string_t<T>& rhs) noexcept { return lhs.get() == rhs.get(); }
template <typename T> constexpr bool operator==(const named_string_t<T>& lhs, const std::string& rhs) noexcept { return lhs.get() == rhs; }
template <typename T> constexpr bool operator==(const named_string_t<T>& lhs, const char* rhs) noexcept { return lhs.get() == rhs; }
template <typename T> constexpr bool operator==(const named_string_t<T>& lhs, std::string_view rhs) noexcept { return lhs.get() == rhs; }
template <typename T, typename R> constexpr bool operator!=(const named_string_t<T>& lhs, R&& rhs) noexcept { return !operator==(lhs, std::forward<R>(rhs)); }
template <typename T> constexpr bool operator<(const named_string_t<T>& lhs, const named_string_t<T>& rhs) noexcept { return lhs.get() < rhs.get(); }
// ----------------------------------------------------------------------
template <typename T, typename Tag> class named_vector_t : public named_t<std::vector<T>, Tag>
{
public:
using value_type = T;
using named_t<std::vector<T>, Tag>::named_t;
constexpr auto begin() const { return this->get().begin(); }
constexpr auto end() const { return this->get().end(); }
constexpr auto begin() { return this->get().begin(); }
constexpr auto end() { return this->get().end(); }
constexpr auto rbegin() { return this->get().rbegin(); }
constexpr auto rend() { return this->get().rend(); }
constexpr auto empty() const { return this->get().empty(); }
constexpr auto size() const { return this->get().size(); }
constexpr auto operator[](size_t index) const { return this->get()[index]; }
constexpr auto& operator[](size_t index) { return this->get()[index]; }
// for std::back_inserter
constexpr void push_back(const T& val) { this->get().push_back(val); }
constexpr void push_back(T&& val) { this->get().push_back(std::forward<T>(val)); }
void remove(const T& val)
{
if (const auto found = std::find(begin(), end(), val); found != end())
this->get().erase(found);
}
// set like
bool exists(const T& val) const { return std::find(begin(), end(), val) != end(); }
void insert_if_not_present(const T& val)
{
if (!exists(val))
push_back(val);
}
void insert_if_not_present(T&& val)
{
if (!exist(val))
push_back(std::forward<T>(val));
}
void merge_in(const named_vector_t<T, Tag>& another)
{
for (const auto& val : another)
insert_if_not_present(val);
}
};
template <typename Tag> constexpr bool operator<(const named_vector_t<std::string, Tag>& lhs, const named_vector_t<std::string, Tag>& rhs) noexcept
{
const auto sz = std::min(lhs.size(), rhs.size());
for (size_t i = 0; i < sz; ++i) {
if (!(lhs[i] == rhs[i]))
return lhs[i] < rhs[i];
}
if (lhs.size() < rhs.size())
return true;
return false;
}
} // namespace acmacs
// ----------------------------------------------------------------------
// template <typename T, typename Tag> struct fmt::formatter<acmacs::named_t<T, Tag>> : fmt::formatter<T> {
// template <typename FormatCtx> auto format(const acmacs::named_t<T, Tag>& nt, FormatCtx& ctx) { return fmt::formatter<T>::format(nt.get(), ctx); }
// };
template <typename Tag> struct fmt::formatter<acmacs::named_size_t<Tag>> : fmt::formatter<size_t> {
template <typename FormatCtx> auto format(const acmacs::named_size_t<Tag>& nt, FormatCtx& ctx) { return fmt::formatter<size_t>::format(nt.get(), ctx); }
};
template <typename Tag> struct fmt::formatter<acmacs::named_double_t<Tag>> : fmt::formatter<double> {
template <typename FormatCtx> auto format(const acmacs::named_double_t<Tag>& nt, FormatCtx& ctx) { return fmt::formatter<double>::format(nt.get(), ctx); }
};
template <typename Tag> struct fmt::formatter<acmacs::named_string_t<Tag>> : fmt::formatter<std::string> {
template <typename FormatCtx> auto format(const acmacs::named_string_t<Tag>& nt, FormatCtx& ctx) { return fmt::formatter<std::string>::format(nt.get(), ctx); }
};
template <typename T, typename Tag> struct fmt::formatter<acmacs::named_vector_t<T, Tag>> : fmt::formatter<std::vector<T>> {
template <typename FormatCtx> auto format(const acmacs::named_vector_t<T, Tag>& vec, FormatCtx& ctx) { return fmt::formatter<std::vector<T>>::format(vec.get(), ctx); }
};
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|> |
<commit_before>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_HOOFS_CXX_OPTIONAL_INL
#define IOX_HOOFS_CXX_OPTIONAL_INL
#include "iceoryx_hoofs/cxx/attributes.hpp"
#include "iceoryx_hoofs/cxx/optional.hpp"
namespace iox
{
namespace cxx
{
// m_data is not initialized since this is a constructor for an optional with no value; an access of the value would
// lead to the application's termination
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init, hicpp-member-init)
template <typename T>
inline optional<T>::optional(const nullopt_t& noVal IOX_MAYBE_UNUSED) noexcept
{
}
// m_data is not initialized since this is a constructor for an optional with no value; an access of the value would
// lead to the application's termination
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init, hicpp-member-init)
template <typename T>
inline optional<T>::optional() noexcept
: optional(nullopt_t())
{
}
// m_data is set inside construct_value
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init, hicpp-member-init)
template <typename T>
inline optional<T>::optional(T&& value) noexcept
{
construct_value(std::forward<T>(value));
}
// m_data is set inside construct_value
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init, hicpp-member-init)
template <typename T>
inline optional<T>::optional(const T& value) noexcept
{
construct_value(value);
}
// if rhs has a value m_data is set inside construct_value, otherwise this stays an optional with has no value
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init, hicpp-member-init)
template <typename T>
inline optional<T>::optional(const optional& rhs) noexcept
{
if (rhs.m_hasValue)
{
construct_value(rhs.value());
}
}
// if rhs has a value m_data is set inside construct_value, otherwise this stays an optional with has no value
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init, hicpp-member-init)
template <typename T>
inline optional<T>::optional(optional&& rhs) noexcept
{
if (rhs.m_hasValue)
{
construct_value(std::move(rhs.value()));
rhs.destruct_value();
}
}
// m_data is set inside construct_value
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init, hicpp-member-init)
template <typename T>
template <typename... Targs>
// NOLINTNEXTLINE(readability-named-parameter, hicpp-named-parameter) justification in header
inline optional<T>::optional(in_place_t, Targs&&... args) noexcept
{
construct_value(std::forward<Targs>(args)...);
}
template <typename T>
inline optional<T>& optional<T>::operator=(const optional& rhs) noexcept
{
if (this != &rhs)
{
if (!rhs.m_hasValue && m_hasValue)
{
destruct_value();
}
else if (rhs.m_hasValue && m_hasValue)
{
value() = rhs.value();
}
else if (rhs.m_hasValue && !m_hasValue)
{
construct_value(rhs.value());
}
}
return *this;
}
template <typename T>
inline optional<T>& optional<T>::operator=(optional&& rhs) noexcept
{
if (this != &rhs)
{
if (!rhs.m_hasValue && m_hasValue)
{
destruct_value();
}
else if (rhs.m_hasValue && m_hasValue)
{
value() = std::move(rhs.value());
}
else if (rhs.m_hasValue && !m_hasValue)
{
construct_value(std::move(rhs.value()));
}
if (rhs.m_hasValue)
{
rhs.destruct_value();
}
}
return *this;
}
template <typename T>
inline optional<T>::~optional() noexcept
{
if (m_hasValue)
{
destruct_value();
}
}
// NOLINTNEXTLINE(cppcoreguidelines-c-copy-assignment-signature) justification in header
template <typename T>
template <typename U>
inline typename std::enable_if<!std::is_same<U, optional<T>&>::value, optional<T>>::type&
optional<T>::operator=(U&& newValue) noexcept
{
if (m_hasValue)
{
/// @todo broken msvc compiler, see:
/// https://developercommunity.visualstudio.com/content/problem/858688/stdforward-none-of-these-2-overloads-could-convert.html
/// remove this as soon as it is fixed;
#ifdef _WIN32
value() = newValue;
#else
value() = std::forward<T>(newValue);
#endif
}
else
{
/// @todo again broken msvc compiler
#ifdef _WIN32
construct_value(newValue);
#else
construct_value(std::forward<T>(newValue));
#endif
}
return *this;
}
template <typename T>
constexpr inline bool optional<T>::operator==(const optional<T>& rhs) const noexcept
{
return (!m_hasValue && !rhs.m_hasValue) || ((m_hasValue && rhs.m_hasValue) && (value() == rhs.value()));
}
template <typename T>
constexpr inline bool optional<T>::operator==(const nullopt_t& rhs IOX_MAYBE_UNUSED) const noexcept
{
return !m_hasValue;
}
template <typename T>
constexpr inline bool optional<T>::operator!=(const optional<T>& rhs) const noexcept
{
return !(*this == rhs);
}
template <typename T>
constexpr inline bool optional<T>::operator!=(const nullopt_t& rhs) const noexcept
{
return !(*this == rhs);
}
template <typename T>
inline const T* optional<T>::operator->() const noexcept
{
return &value();
}
template <typename T>
inline const T& optional<T>::operator*() const noexcept
{
return value();
}
template <typename T>
inline T* optional<T>::operator->() noexcept
{
return &value();
}
template <typename T>
inline T& optional<T>::operator*() noexcept
{
return value();
}
template <typename T>
inline constexpr optional<T>::operator bool() const noexcept
{
return m_hasValue;
}
template <typename T>
template <typename... Targs>
inline T& optional<T>::emplace(Targs&&... args) noexcept
{
if (m_hasValue)
{
destruct_value();
}
construct_value(std::forward<Targs>(args)...);
return value();
}
template <typename T>
inline constexpr bool optional<T>::has_value() const noexcept
{
return m_hasValue;
}
template <typename T>
inline void optional<T>::reset() noexcept
{
if (m_hasValue)
{
destruct_value();
}
}
template <typename T>
inline T& optional<T>::value() & noexcept
{
Expects(has_value());
return *static_cast<T*>(static_cast<void*>(m_data));
}
template <typename T>
inline const T& optional<T>::value() const& noexcept
{
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) const_cast to avoid code duplication
return const_cast<optional<T>*>(this)->value();
}
template <typename T>
inline T&& optional<T>::value() && noexcept
{
Expects(has_value());
return std::move(*static_cast<T*>(static_cast<void*>(m_data)));
}
template <typename T>
inline const T&& optional<T>::value() const&& noexcept
{
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) const_cast to avoid code duplication
return std::move(*const_cast<optional<T>*>(this)->value());
}
template <typename T>
template <typename... Targs>
inline void optional<T>::construct_value(Targs&&... args) noexcept
{
new (static_cast<T*>(static_cast<void*>(m_data))) T(std::forward<Targs>(args)...);
m_hasValue = true;
}
template <typename T>
inline void optional<T>::destruct_value() noexcept
{
value().~T();
m_hasValue = false;
}
template <typename OptionalBaseType, typename... Targs>
inline optional<OptionalBaseType> make_optional(Targs&&... args) noexcept
{
optional<OptionalBaseType> returnValue = nullopt_t();
returnValue.emplace(std::forward<Targs>(args)...);
return returnValue;
}
} // namespace cxx
} // namespace iox
#endif // IOX_HOOFS_CXX_OPTIONAL_INL
<commit_msg>iox-#1638 Correct access of m_data in optional<commit_after>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2021 - 2022 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_HOOFS_CXX_OPTIONAL_INL
#define IOX_HOOFS_CXX_OPTIONAL_INL
#include "iceoryx_hoofs/cxx/attributes.hpp"
#include "iceoryx_hoofs/cxx/optional.hpp"
namespace iox
{
namespace cxx
{
// m_data is not initialized since this is a constructor for an optional with no value; an access of the value would
// lead to the application's termination
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init, hicpp-member-init)
template <typename T>
inline optional<T>::optional(const nullopt_t& noVal IOX_MAYBE_UNUSED) noexcept
{
}
// m_data is not initialized since this is a constructor for an optional with no value; an access of the value would
// lead to the application's termination
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init, hicpp-member-init)
template <typename T>
inline optional<T>::optional() noexcept
: optional(nullopt_t())
{
}
// m_data is set inside construct_value
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init, hicpp-member-init)
template <typename T>
inline optional<T>::optional(T&& value) noexcept
{
construct_value(std::forward<T>(value));
}
// m_data is set inside construct_value
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init, hicpp-member-init)
template <typename T>
inline optional<T>::optional(const T& value) noexcept
{
construct_value(value);
}
// if rhs has a value m_data is set inside construct_value, otherwise this stays an optional with has no value
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init, hicpp-member-init)
template <typename T>
inline optional<T>::optional(const optional& rhs) noexcept
{
if (rhs.m_hasValue)
{
construct_value(rhs.value());
}
}
// if rhs has a value m_data is set inside construct_value, otherwise this stays an optional with has no value
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init, hicpp-member-init)
template <typename T>
inline optional<T>::optional(optional&& rhs) noexcept
{
if (rhs.m_hasValue)
{
construct_value(std::move(rhs.value()));
rhs.destruct_value();
}
}
// m_data is set inside construct_value
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init, hicpp-member-init)
template <typename T>
template <typename... Targs>
// NOLINTNEXTLINE(readability-named-parameter, hicpp-named-parameter) justification in header
inline optional<T>::optional(in_place_t, Targs&&... args) noexcept
{
construct_value(std::forward<Targs>(args)...);
}
template <typename T>
inline optional<T>& optional<T>::operator=(const optional& rhs) noexcept
{
if (this != &rhs)
{
if (!rhs.m_hasValue && m_hasValue)
{
destruct_value();
}
else if (rhs.m_hasValue && m_hasValue)
{
value() = rhs.value();
}
else if (rhs.m_hasValue && !m_hasValue)
{
construct_value(rhs.value());
}
}
return *this;
}
template <typename T>
inline optional<T>& optional<T>::operator=(optional&& rhs) noexcept
{
if (this != &rhs)
{
if (!rhs.m_hasValue && m_hasValue)
{
destruct_value();
}
else if (rhs.m_hasValue && m_hasValue)
{
value() = std::move(rhs.value());
}
else if (rhs.m_hasValue && !m_hasValue)
{
construct_value(std::move(rhs.value()));
}
if (rhs.m_hasValue)
{
rhs.destruct_value();
}
}
return *this;
}
template <typename T>
inline optional<T>::~optional() noexcept
{
if (m_hasValue)
{
destruct_value();
}
}
// NOLINTNEXTLINE(cppcoreguidelines-c-copy-assignment-signature) justification in header
template <typename T>
template <typename U>
inline typename std::enable_if<!std::is_same<U, optional<T>&>::value, optional<T>>::type&
optional<T>::operator=(U&& newValue) noexcept
{
if (m_hasValue)
{
/// @todo broken msvc compiler, see:
/// https://developercommunity.visualstudio.com/content/problem/858688/stdforward-none-of-these-2-overloads-could-convert.html
/// remove this as soon as it is fixed;
#ifdef _WIN32
value() = newValue;
#else
value() = std::forward<T>(newValue);
#endif
}
else
{
/// @todo again broken msvc compiler
#ifdef _WIN32
construct_value(newValue);
#else
construct_value(std::forward<T>(newValue));
#endif
}
return *this;
}
template <typename T>
constexpr inline bool optional<T>::operator==(const optional<T>& rhs) const noexcept
{
return (!m_hasValue && !rhs.m_hasValue) || ((m_hasValue && rhs.m_hasValue) && (value() == rhs.value()));
}
template <typename T>
constexpr inline bool optional<T>::operator==(const nullopt_t& rhs IOX_MAYBE_UNUSED) const noexcept
{
return !m_hasValue;
}
template <typename T>
constexpr inline bool optional<T>::operator!=(const optional<T>& rhs) const noexcept
{
return !(*this == rhs);
}
template <typename T>
constexpr inline bool optional<T>::operator!=(const nullopt_t& rhs) const noexcept
{
return !(*this == rhs);
}
template <typename T>
inline const T* optional<T>::operator->() const noexcept
{
return &value();
}
template <typename T>
inline const T& optional<T>::operator*() const noexcept
{
return value();
}
template <typename T>
inline T* optional<T>::operator->() noexcept
{
return &value();
}
template <typename T>
inline T& optional<T>::operator*() noexcept
{
return value();
}
template <typename T>
inline constexpr optional<T>::operator bool() const noexcept
{
return m_hasValue;
}
template <typename T>
template <typename... Targs>
inline T& optional<T>::emplace(Targs&&... args) noexcept
{
if (m_hasValue)
{
destruct_value();
}
construct_value(std::forward<Targs>(args)...);
return value();
}
template <typename T>
inline constexpr bool optional<T>::has_value() const noexcept
{
return m_hasValue;
}
template <typename T>
inline void optional<T>::reset() noexcept
{
if (m_hasValue)
{
destruct_value();
}
}
template <typename T>
inline T& optional<T>::value() & noexcept
{
Expects(has_value());
return *static_cast<T*>(static_cast<void*>(&m_data));
}
template <typename T>
inline const T& optional<T>::value() const& noexcept
{
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) const_cast to avoid code duplication
return const_cast<optional<T>*>(this)->value();
}
template <typename T>
inline T&& optional<T>::value() && noexcept
{
Expects(has_value());
return std::move(*static_cast<T*>(static_cast<void*>(&m_data)));
}
template <typename T>
inline const T&& optional<T>::value() const&& noexcept
{
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) const_cast to avoid code duplication
return std::move(*const_cast<optional<T>*>(this)->value());
}
template <typename T>
template <typename... Targs>
inline void optional<T>::construct_value(Targs&&... args) noexcept
{
new (static_cast<T*>(static_cast<void*>(&m_data))) T(std::forward<Targs>(args)...);
m_hasValue = true;
}
template <typename T>
inline void optional<T>::destruct_value() noexcept
{
value().~T();
m_hasValue = false;
}
template <typename OptionalBaseType, typename... Targs>
inline optional<OptionalBaseType> make_optional(Targs&&... args) noexcept
{
optional<OptionalBaseType> returnValue = nullopt_t();
returnValue.emplace(std::forward<Targs>(args)...);
return returnValue;
}
} // namespace cxx
} // namespace iox
#endif // IOX_HOOFS_CXX_OPTIONAL_INL
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <spikehw.h>
SpikeHw *spikeHw;
int main(int argc, const char **argv)
{
spikeHw = new SpikeHw();
// not needed yet
//spikeHw->setupDma(memfd);
// query mmcm and interrupt status
spikeHw->status();
// read boot rom
uint32_t firstword;
spikeHw->read(0x000000 + 0x000, (uint8_t *)&firstword);
fprintf(stderr, "First word of boot ROM %08x (expected %08x)\n", firstword, 0x00001137);
// read ethernet identification register
uint32_t id;
spikeHw->read(0x180000 + 0x4f8, (uint8_t *)&id);
fprintf(stderr, "AXI Ethernet Identification %08x (expected %08x)\n", id, 0x09000000);
// put flash in query mode
spikeHw->setFlashParameters(50); // divides clock by 50
uint32_t values[4] = { 0x98 };
spikeHw->writeFlash(0x00aa, (uint8_t *)&values[0]);
spikeHw->readFlash(0x0020, (uint8_t *)&values[1]);
spikeHw->readFlash(0x0022, (uint8_t *)&values[2]);
spikeHw->readFlash(0x0024, (uint8_t *)&values[3]);
fprintf(stderr, "Query flash %02x.%02x.%02x %c%c%c (expected QRY)\n", values[1], values[2], values[3], values[1], values[2], values[3]);
return 0;
}
<commit_msg>read and verify 8 32-bit words of boot ROM<commit_after>#include <stdio.h>
#include <spikehw.h>
SpikeHw *spikeHw;
int main(int argc, const char **argv)
{
spikeHw = new SpikeHw();
// not needed yet
//spikeHw->setupDma(memfd);
// query mmcm and interrupt status
spikeHw->status();
// read boot rom
uint32_t word = 0;
uint32_t expected[] = {
0x00001137,
0x010000ef,
0x20000513,
0x00050067,
0x0000006f,
0x040007b7,
0x40078793,
0xfc0005b7
};
for (int i = 0; i < 8; i++){
spikeHw->read(0x000000 + i*4, (uint8_t *)&word);
fprintf(stderr, "word %04x of boot ROM %08x (expected %08x)\n", i*4, word, expected[i]);
}
// read ethernet identification register
uint32_t id;
spikeHw->read(0x180000 + 0x4f8, (uint8_t *)&id);
fprintf(stderr, "AXI Ethernet Identification %08x (expected %08x)\n", id, 0x09000000);
// put flash in query mode
spikeHw->setFlashParameters(50); // divides clock by 50
uint32_t values[4] = { 0x98 };
spikeHw->writeFlash(0x00aa, (uint8_t *)&values[0]);
spikeHw->readFlash(0x0020, (uint8_t *)&values[1]);
spikeHw->readFlash(0x0022, (uint8_t *)&values[2]);
spikeHw->readFlash(0x0024, (uint8_t *)&values[3]);
fprintf(stderr, "Query flash %02x.%02x.%02x %c%c%c (expected QRY)\n", values[1], values[2], values[3], values[1], values[2], values[3]);
return 0;
}
<|endoftext|> |
<commit_before>/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
#include "colormap_editor.h"
#include "ui_colormap_editor.h"
#include "PlotJuggler/svg_util.h"
#include <QSettings>
#include <QInputDialog>
#include <QMessageBox>
#include "stylesheet.h"
#include "color_map.h"
ColorMapEditor::ColorMapEditor(QWidget *parent) :
QDialog(parent),
ui(new Ui::colormap_editor)
{
ui->setupUi(this);
QSettings settings;
ui->functionText->setHighlighter( new QLuaHighlighter );
ui->functionText->setCompleter(new QLuaCompleter);
auto theme = settings.value("StyleSheet::theme", "light").toString();
on_stylesheetChanged(theme);
for(const auto& it: ColorMapLibrary())
{
ui->listWidget->addItem(it.first);
}
}
ColorMapEditor::~ColorMapEditor()
{
SaveColorMapToSettings();
delete ui;
}
void ColorMapEditor::on_stylesheetChanged(QString theme)
{
ui->buttonDelete->setIcon(LoadSvg(":/resources/svg/trash.svg", theme));
ui->functionText->setSyntaxStyle( GetLuaSyntaxStyle(theme) );
}
void ColorMapEditor::on_buttonSave_clicked()
{
bool ok;
auto colormap = std::make_shared<ColorMap>();
auto res = colormap->setScrip(ui->functionText->toPlainText());
if (!res.valid())
{
QMessageBox::warning(this, "Error in the Lua Script", colormap->getError(res), QMessageBox::Cancel);
return;
}
QString default_name;
auto selected = ui->listWidget->selectedItems();
if( selected.size() == 1 )
{
default_name = selected.front()->text();
}
QString name = QInputDialog::getText(this, tr("ColorMap Name"),
tr("Name of the function:"), QLineEdit::Normal,
default_name, &ok);
if (!ok || name.isEmpty())
{
return;
}
bool overwrite = false;
if( !ui->listWidget->findItems(name, Qt::MatchExactly).empty() )
{
auto reply = QMessageBox::question(this, "Confirm overwrite",
"A ColorMap with the same name exist already. "
"Do you want to ovewrite it?",
QMessageBox::Yes|QMessageBox::No);
if (reply == QMessageBox::No)
{
return;
}
overwrite = true;
}
ColorMapLibrary()[name] = colormap;
if( !overwrite )
{
ui->listWidget->addItem(name);
selectRow(ui->listWidget->count() - 1);
}
}
void ColorMapEditor::on_buttonDelete_clicked()
{
for(auto item: ui->listWidget->selectedItems())
{
auto it = ColorMapLibrary().find(item->text());
if( it != ColorMapLibrary().end() )
{
if( !it->second->script().isEmpty() )
{
auto reply = QMessageBox::question(this, "Delete ColorMap", "Are you sure?",
QMessageBox::Yes|QMessageBox::No);
if (reply == QMessageBox::No)
{
return;
}
}
ColorMapLibrary().erase( it );
}
delete ui->listWidget->takeItem( ui->listWidget->row( item ) );
}
}
void ColorMapEditor::selectRow(int row)
{
ui->listWidget->clearSelection();
ui->listWidget->selectionModel()->setCurrentIndex(ui->listWidget->model()->index(row,0),
QItemSelectionModel::SelectionFlag::Select );
}
void ColorMapEditor::on_listWidget_itemDoubleClicked(QListWidgetItem *item)
{
auto it = ColorMapLibrary().find(item->text());
if( it != ColorMapLibrary().end() )
{
auto colormap = it->second;
ui->functionText->setText( colormap->script() );
}
}
<commit_msg>Fix typo in ColorMap warning (#693)<commit_after>/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
#include "colormap_editor.h"
#include "ui_colormap_editor.h"
#include "PlotJuggler/svg_util.h"
#include <QSettings>
#include <QInputDialog>
#include <QMessageBox>
#include "stylesheet.h"
#include "color_map.h"
ColorMapEditor::ColorMapEditor(QWidget *parent) :
QDialog(parent),
ui(new Ui::colormap_editor)
{
ui->setupUi(this);
QSettings settings;
ui->functionText->setHighlighter( new QLuaHighlighter );
ui->functionText->setCompleter(new QLuaCompleter);
auto theme = settings.value("StyleSheet::theme", "light").toString();
on_stylesheetChanged(theme);
for(const auto& it: ColorMapLibrary())
{
ui->listWidget->addItem(it.first);
}
}
ColorMapEditor::~ColorMapEditor()
{
SaveColorMapToSettings();
delete ui;
}
void ColorMapEditor::on_stylesheetChanged(QString theme)
{
ui->buttonDelete->setIcon(LoadSvg(":/resources/svg/trash.svg", theme));
ui->functionText->setSyntaxStyle( GetLuaSyntaxStyle(theme) );
}
void ColorMapEditor::on_buttonSave_clicked()
{
bool ok;
auto colormap = std::make_shared<ColorMap>();
auto res = colormap->setScrip(ui->functionText->toPlainText());
if (!res.valid())
{
QMessageBox::warning(this, "Error in the Lua Script", colormap->getError(res), QMessageBox::Cancel);
return;
}
QString default_name;
auto selected = ui->listWidget->selectedItems();
if( selected.size() == 1 )
{
default_name = selected.front()->text();
}
QString name = QInputDialog::getText(this, tr("ColorMap Name"),
tr("Name of the function:"), QLineEdit::Normal,
default_name, &ok);
if (!ok || name.isEmpty())
{
return;
}
bool overwrite = false;
if( !ui->listWidget->findItems(name, Qt::MatchExactly).empty() )
{
auto reply = QMessageBox::question(this, "Confirm overwrite",
"A ColorMap with the same name exist already. "
"Do you want to overwrite it?",
QMessageBox::Yes|QMessageBox::No);
if (reply == QMessageBox::No)
{
return;
}
overwrite = true;
}
ColorMapLibrary()[name] = colormap;
if( !overwrite )
{
ui->listWidget->addItem(name);
selectRow(ui->listWidget->count() - 1);
}
}
void ColorMapEditor::on_buttonDelete_clicked()
{
for(auto item: ui->listWidget->selectedItems())
{
auto it = ColorMapLibrary().find(item->text());
if( it != ColorMapLibrary().end() )
{
if( !it->second->script().isEmpty() )
{
auto reply = QMessageBox::question(this, "Delete ColorMap", "Are you sure?",
QMessageBox::Yes|QMessageBox::No);
if (reply == QMessageBox::No)
{
return;
}
}
ColorMapLibrary().erase( it );
}
delete ui->listWidget->takeItem( ui->listWidget->row( item ) );
}
}
void ColorMapEditor::selectRow(int row)
{
ui->listWidget->clearSelection();
ui->listWidget->selectionModel()->setCurrentIndex(ui->listWidget->model()->index(row,0),
QItemSelectionModel::SelectionFlag::Select );
}
void ColorMapEditor::on_listWidget_itemDoubleClicked(QListWidgetItem *item)
{
auto it = ColorMapLibrary().find(item->text());
if( it != ColorMapLibrary().end() )
{
auto colormap = it->second;
ui->functionText->setText( colormap->script() );
}
}
<|endoftext|> |
<commit_before>// http://redd.it/29od55
// Challenge 169-Intermediate - Home-row Spell Check
// Usage: aliensp
// Spell check and correct alien input.
// aliensp < file.in
// Built using g++: g++ -std=c++0x -Wall -o alien_trans chal169.cpp
//
#include <iostream>
#include "alien_translator.h"
#include "string_utils.h"
int main() {
// For each word, check if it's a real word as opposed to gooblygook. If
// it's a real word, print it. Otherwise try to guess what the word could
// be and print the guesses. If there are no guesses, then print the
// original gooblygook.
Alien_translator translator;
std::istream_iterator<std::string> word_iter(std::cin);
std::istream_iterator<std::string> end_iter;
for(; word_iter != end_iter; ++word_iter) {
std::string word = string_utils::remove_punctuation(*word_iter);
if(translator.is_gooblygook(word)) {
auto guesses = translator.guess(word);
if(guesses.size() > 0)
std::cout << '{' << string_utils::fmt_as_list(guesses) << "} ";
else
std::cout << word << ' ';
}
else
std::cout << word << ' ';
}
return 0;
}
<commit_msg>Correct usage comment<commit_after>// http://redd.it/29od55
// Challenge 169-Intermediate - Home-row Spell Check
// Usage: alien_trans
// Spell check and correct alien input.
// alien_trans < file.in
// Built using g++: g++ -std=c++0x -Wall -o alien_trans chal169.cpp
//
#include <iostream>
#include "alien_translator.h"
#include "string_utils.h"
int main() {
// For each word, check if it's a real word as opposed to gooblygook. If
// it's a real word, print it. Otherwise try to guess what the word could
// be and print the guesses. If there are no guesses, then print the
// original gooblygook.
Alien_translator translator;
std::istream_iterator<std::string> word_iter(std::cin);
std::istream_iterator<std::string> end_iter;
for(; word_iter != end_iter; ++word_iter) {
std::string word = string_utils::remove_punctuation(*word_iter);
if(translator.is_gooblygook(word)) {
auto guesses = translator.guess(word);
if(guesses.size() > 0)
std::cout << '{' << string_utils::fmt_as_list(guesses) << "} ";
else
std::cout << word << ' ';
}
else
std::cout << word << ' ';
}
return 0;
}
<|endoftext|> |
<commit_before>
#include <pcap.h>
#include <stdio.h>
#include <poll.h>
#include <vector>
#include <queue>
#include <algorithm>
#include <slankdev/util.h>
#include <slankdev/ncurses.h>
#include <slankdev/exception.h>
#include <slankdev/net/protocol.h>
class Packet {
public:
uint8_t buf[2000];
size_t len;
uint64_t time;
size_t number;
Packet(const void* p, size_t l, uint64_t t, size_t n) :
len(l), time(t), number(n)
{
memcpy(buf, p, len);
}
std::string line()
{
using namespace slankdev;
std::string source;
std::string dest;
std::string proto;
ether* eth = reinterpret_cast<ether*>(buf);
char str[1000];
sprintf(str, "%5zd %-13ld %-20s %-20s %6s %5zd %-10s" , number, time,
eth->src.to_string().c_str(),
eth->dst.to_string().c_str(),
"protocol", len, "summry");
return str;
}
};
class pane {
protected:
size_t current_x;
size_t current_y;
slankdev::ncurses& screen;
public:
const size_t x;
const size_t y;
const size_t w;
const size_t h;
pane(size_t ix, size_t iy, size_t iw, size_t ih, slankdev::ncurses& scr) :
x(ix), y(iy), w(iw), h(ih), current_x(ix), current_y(iy), screen(scr) {}
template <class... Arg>
void println(const char* fmt, Arg... arg)
{
screen.mvprintw(current_y++, current_x, fmt, arg...);
current_x = x;
}
template <class... Arg>
void println_hl(const char* fmt, Arg... arg)
{
attron(A_REVERSE);
screen.mvprintw(current_y++, current_x, fmt, arg...);
current_x = x;
attroff(A_REVERSE);
}
template <class... Arg>
void print(const char* fmt, Arg... arg)
{
char str[1000];
sprintf(str, fmt, arg...);
size_t len = strlen(str);
screen.mvprintw(current_y, current_x+=len, fmt, arg...);
}
void putc(char c)
{
if (c == '\n') {
current_y ++ ;
current_x = x;
} else {
screen.mvprintw(current_y, current_x++, "%c", c);
}
}
};
class Pane_list : public pane {
ssize_t cursor_index;
size_t list_start_index;
public:
std::vector<Packet> packets;
ssize_t get_cursor() { return cursor_index; }
void dec_cursor()
{
if (cursor_index-1 < list_start_index) scroll_up();
if (get_cursor()-1 >= 0) cursor_index--;
}
void inc_cursor()
{
if (cursor_index+1-list_start_index >= h) scroll_down();
if (get_cursor()+1 < packets.size()) cursor_index++;
}
void scroll_up() { list_start_index --; }
void scroll_down() { list_start_index ++; }
Pane_list(size_t ix, size_t iy, size_t iw, size_t ih,
slankdev::ncurses& scr) : pane(ix, iy, iw, ih, scr),
cursor_index(0), list_start_index(0) {}
void push_packet(const void* packet, struct pcap_pkthdr* hdr)
{
static int number = 0;
packets.emplace_back(packet, hdr->len, hdr->ts.tv_sec, number++);
}
void refresh()
{
current_x = x;
current_y = y;
println("%-5s %-13s %-20s %-20s %-6s %-5s %-10s",
"No.", "Time", "Source", "Destination",
"Protocol", "Len", "Info");
size_t start_idx = list_start_index;
for (size_t i=start_idx, c=0; i<packets.size() && c<h; i++, c++) {
if (i == get_cursor())
println_hl(packets[i].line().c_str());
else
println(packets[i].line().c_str());
}
}
};
class Pane_detail : public pane {
public:
Pane_detail(size_t ix, size_t iy, size_t iw, size_t ih,
slankdev::ncurses& scr) : pane(ix, iy, iw, ih, scr) {}
void print_packet_detail(Packet* packet)
{
current_x = x;
current_y = y;
println("Packet Detail");
println(" + number : %zd ", packet->number);
println(" + pointer: %p", packet->buf);
println(" + length : %zd", packet->len);
println(" + time : %ld", packet->time);
}
void refresh() {}
};
class Pane_binary : public pane {
ssize_t cursor_index;
size_t list_start_index;
public:
std::vector<std::string> lines;
ssize_t get_cursor() { return cursor_index; }
void dec_cursor()
{
if (cursor_index-1 < list_start_index) scroll_up();
if (get_cursor()-1 >= 0) cursor_index--;
}
void inc_cursor()
{
if (cursor_index+1-list_start_index >= h) scroll_down();
if (get_cursor()+1 < lines.size()) cursor_index++;
}
void scroll_up() { list_start_index --; }
void scroll_down() { list_start_index ++; }
Pane_binary(size_t ix, size_t iy, size_t iw, size_t ih,
slankdev::ncurses& scr) : pane(ix, iy, iw, ih, scr) {}
void hex(Packet* packet)
{
lines.clear();
const void* buffer = packet->buf;
size_t bufferlen = packet->len;
char str[1000];
const uint8_t *data = reinterpret_cast<const uint8_t*>(buffer);
size_t row = 0;
std::string line;
while (bufferlen > 0) {
line.clear();
sprintf(str, " %04zx: ", row);
line += str;
size_t n;
if (bufferlen < 16) n = bufferlen;
else n = 16;
for (size_t i = 0; i < n; i++) {
if (i == 8) { line += " "; }
sprintf(str, " %02x", data[i]);
line += str;
}
for (size_t i = n; i < 16; i++) { line += " "; }
line += " ";
for (size_t i = 0; i < n; i++) {
if (i == 8) { line += " "; }
uint8_t c = data[i];
if (!(0x20 <= c && c <= 0x7e)) c = '.';
sprintf(str, "%c", c);
line += str;
}
println("");
lines.push_back(line);
bufferlen -= n;
data += n;
row += n;
}
}
void refresh()
{
current_x = x;
current_y = y;
for (size_t i=0, c=0; i<lines.size() && c<h; i++, c++) {
if (i == get_cursor())
println_hl("%s", lines[i].c_str());
else
println("%s", lines[i].c_str());
}
for (size_t i=0; i<h-lines.size(); i++) {
for (size_t c=0; c<w; c++) print(" ");
println("");
}
}
};
enum cursor_state {
LIST,
DETAIL,
BINARY,
};
class Statusline {
const size_t x;
const size_t y;
const size_t w;
const cursor_state& state;
public:
Statusline(size_t ix, size_t iy, size_t iw, cursor_state& c)
: x(ix), y(iy), w(iw), state(c) {}
const char* state2str(cursor_state s)
{
switch (s) {
case LIST: return "LIST ";
case DETAIL: return "DETAIL ";
case BINARY: return "BINARY ";
default : return "UNKNOWN";
}
}
void refresh()
{
mvprintw(y, x, "[CUISHARK] pane=%s", state2str(state));
}
};
size_t a(size_t h) { return (h-1) % 3; }
size_t m(size_t h) { return ((h-1)-((h-1)%3))/3; }
#define H screen.geth()
class display {
slankdev::ncurses screen;
pcap_t *handle;
cursor_state cstate;
public:
Pane_list pane_list;
Pane_detail pane_detail;
Pane_binary pane_binary;
Statusline statusline;
display() :
cstate(LIST),
pane_list (0, 0 , screen.getw(), a(H)+m(H), screen),
pane_detail(0, a(H)+m(H) , screen.getw(), m(H) , screen),
pane_binary(0, a(H)+2*m(H), screen.getw(), m(H) , screen),
statusline (0, a(H)+3*m(H), screen.getw(), cstate)
{
char errbuf[PCAP_ERRBUF_SIZE];
handle = pcap_open_live("lo", BUFSIZ, 0, 0, errbuf);
// handle = pcap_open_offline("in.pcap", errbuf);
if (handle == NULL) {
throw slankdev::exception("pcap_open_live");
}
noecho();
screen.refresh();
}
~display() { pcap_close(handle); }
void charnge_cstate()
{
switch (cstate) {
case LIST:
cstate = DETAIL;
break;
case DETAIL:
cstate = BINARY;
break;
case BINARY:
cstate = LIST;
break;
default :
throw slankdev::exception("UNKNOWN state");
break;
}
}
void press_j()
{
switch (cstate) {
case LIST:
pane_list.inc_cursor();
break;
case DETAIL:
break;
case BINARY:
pane_binary.inc_cursor();
break;
defaut:
throw slankdev::exception("UNknown state");
break;
}
}
void press_k()
{
switch (cstate) {
case LIST:
pane_list.dec_cursor();
break;
case DETAIL:
break;
case BINARY:
pane_binary.dec_cursor();
break;
defaut:
throw slankdev::exception("UNknown state");
break;
}
}
void press_enter()
{
switch (cstate) {
case LIST:
{
if (pane_list.packets.empty()) return;
Packet* pack = &pane_list.packets[pane_list.get_cursor()];
pane_detail.print_packet_detail(pack);
pane_binary.hex(pack);
break;
}
case DETAIL:
break;
case BINARY:
break;
defaut:
throw slankdev::exception("UNknown state");
break;
}
}
void view_help()
{
size_t x = 0;
size_t y = 0;
screen.mvprintw(y++, x, " ");
screen.mvprintw(y++, x, " CuiShark version 0.0 ");
screen.mvprintw(y++, x, " Copyright 2017-2020 Hiroki SHIROKURA. ");
screen.mvprintw(y++, x, " ");
screen.mvprintw(y++, x, " Avalable Keyboard commands are below. ");
screen.mvprintw(y++, x, " These are Vi-like key-bind because I'm vimmer. ");
screen.mvprintw(y++, x, " ");
screen.mvprintw(y++, x, " Commands ");
screen.mvprintw(y++, x, " j : down ");
screen.mvprintw(y++, x, " k : up ");
screen.mvprintw(y++, x, " tab : switch pane ");
screen.mvprintw(y++, x, " enter : select ");
screen.mvprintw(y++, x, " ? : view help ");
screen.mvprintw(y++, x, " C-c : exit ");
screen.mvprintw(y++, x, " ");
screen.getchar();
}
void dispatch()
{
struct pollfd fds[2];
fds[0].fd = pcap_get_selectable_fd(handle);
fds[0].events = POLLIN;
fds[1].fd = fileno(stdin);
fds[1].events = POLLIN;
while (1) {
if (poll(fds, 2, 100)) {
if (fds[0].revents & POLLIN) {
struct pcap_pkthdr header;
const u_char *packet;
packet = pcap_next(handle, &header);
pane_list.push_packet(packet, &header);
}
if (fds[1].revents & POLLIN) {
int c = screen.getchar();
switch (c) {
case 'j':
press_j();
break;
case 'k':
press_k();
break;
case '\t':
charnge_cstate();
break;
case '\n':
press_enter();
break;
case '?':
view_help();
break;
}
}
}
refresh();
}
}
void refresh()
{
pane_list.refresh();
pane_detail.refresh();
pane_binary.refresh();
statusline.refresh();
screen.refresh();
}
};
int main(int argc, char *argv[])
{
display dsp0;
dsp0.dispatch();
}
<commit_msg>Support: scroll on detail-pane<commit_after>
#include <pcap.h>
#include <stdio.h>
#include <poll.h>
#include <vector>
#include <queue>
#include <algorithm>
#include <slankdev/util.h>
#include <slankdev/ncurses.h>
#include <slankdev/exception.h>
#include <slankdev/net/protocol.h>
class Packet {
public:
uint8_t buf[2000];
size_t len;
uint64_t time;
size_t number;
Packet(const void* p, size_t l, uint64_t t, size_t n) :
len(l), time(t), number(n)
{
memcpy(buf, p, len);
}
std::string line()
{
using namespace slankdev;
std::string source;
std::string dest;
std::string proto;
ether* eth = reinterpret_cast<ether*>(buf);
char str[1000];
sprintf(str, "%5zd %-13ld %-20s %-20s %6s %5zd %-10s" , number, time,
eth->src.to_string().c_str(),
eth->dst.to_string().c_str(),
"protocol", len, "summry");
return str;
}
};
class pane {
protected:
size_t current_x;
size_t current_y;
slankdev::ncurses& screen;
public:
const size_t x;
const size_t y;
const size_t w;
const size_t h;
pane(size_t ix, size_t iy, size_t iw, size_t ih, slankdev::ncurses& scr) :
x(ix), y(iy), w(iw), h(ih), current_x(ix), current_y(iy), screen(scr) {}
template <class... Arg>
void println(const char* fmt, Arg... arg)
{
screen.mvprintw(current_y++, current_x, fmt, arg...);
current_x = x;
}
template <class... Arg>
void println_hl(const char* fmt, Arg... arg)
{
attron(A_REVERSE);
screen.mvprintw(current_y++, current_x, fmt, arg...);
current_x = x;
attroff(A_REVERSE);
}
template <class... Arg>
void print(const char* fmt, Arg... arg)
{
char str[1000];
sprintf(str, fmt, arg...);
size_t len = strlen(str);
screen.mvprintw(current_y, current_x+=len, fmt, arg...);
}
void putc(char c)
{
if (c == '\n') {
current_y ++ ;
current_x = x;
} else {
screen.mvprintw(current_y, current_x++, "%c", c);
}
}
};
class Pane_list : public pane {
ssize_t cursor_index;
size_t list_start_index;
public:
std::vector<Packet> packets;
ssize_t get_cursor() { return cursor_index; }
void dec_cursor()
{
if (cursor_index-1 < list_start_index) scroll_up();
if (get_cursor()-1 >= 0) cursor_index--;
}
void inc_cursor()
{
if (cursor_index+1-list_start_index >= h) scroll_down();
if (get_cursor()+1 < packets.size()) cursor_index++;
}
void scroll_up() { list_start_index --; }
void scroll_down() { list_start_index ++; }
Pane_list(size_t ix, size_t iy, size_t iw, size_t ih,
slankdev::ncurses& scr) : pane(ix, iy, iw, ih, scr),
cursor_index(0), list_start_index(0) {}
void push_packet(const void* packet, struct pcap_pkthdr* hdr)
{
static int number = 0;
packets.emplace_back(packet, hdr->len, hdr->ts.tv_sec, number++);
}
void refresh()
{
current_x = x;
current_y = y;
println("%-5s %-13s %-20s %-20s %-6s %-5s %-10s",
"No.", "Time", "Source", "Destination",
"Protocol", "Len", "Info");
size_t start_idx = list_start_index;
for (size_t i=start_idx, c=0; i<packets.size() && c<h; i++, c++) {
if (i == get_cursor())
println_hl(packets[i].line().c_str());
else
println(packets[i].line().c_str());
}
}
};
class Pane_detail : public pane {
ssize_t cursor_index;
size_t list_start_index;
public:
std::vector<std::string> lines;
ssize_t get_cursor() { return cursor_index; }
void dec_cursor()
{
if (cursor_index-1 < list_start_index) scroll_up();
if (get_cursor()-1 >= 0) cursor_index--;
}
void inc_cursor()
{
if (cursor_index+1-list_start_index >= h) scroll_down();
if (get_cursor()+1 < lines.size()) cursor_index++;
}
void scroll_up() { list_start_index --; }
void scroll_down() { list_start_index ++; }
Pane_detail(size_t ix, size_t iy, size_t iw, size_t ih,
slankdev::ncurses& scr) : pane(ix, iy, iw, ih, scr) {}
void print_packet_detail(Packet* packet)
{
char str[1000];
sprintf(str, "Packet Detail");
lines.push_back(str);
sprintf(str, " + number : %zd ", packet->number);
lines.push_back(str);
sprintf(str, " + pointer: %p", packet->buf);
lines.push_back(str);
sprintf(str, " + length : %zd", packet->len);
lines.push_back(str);
sprintf(str, " + time : %ld", packet->time);
lines.push_back(str);
}
void refresh()
{
current_x = x;
current_y = y;
println("Detail pane");
for (size_t i=0, c=0; i<lines.size() && c<h; i++, c++) {
if (i == get_cursor())
println_hl("%s", lines[i].c_str());
else
println("%s", lines[i].c_str());
}
for (size_t i=0; i<h-lines.size(); i++) {
for (size_t c=0; c<w; c++) print(" ");
println("");
}
}
};
class Pane_binary : public pane {
ssize_t cursor_index;
size_t list_start_index;
public:
std::vector<std::string> lines;
ssize_t get_cursor() { return cursor_index; }
void dec_cursor()
{
if (cursor_index-1 < list_start_index) scroll_up();
if (get_cursor()-1 >= 0) cursor_index--;
}
void inc_cursor()
{
if (cursor_index+1-list_start_index >= h) scroll_down();
if (get_cursor()+1 < lines.size()) cursor_index++;
}
void scroll_up() { list_start_index --; }
void scroll_down() { list_start_index ++; }
Pane_binary(size_t ix, size_t iy, size_t iw, size_t ih,
slankdev::ncurses& scr) : pane(ix, iy, iw, ih, scr) {}
void hex(Packet* packet)
{
lines.clear();
const void* buffer = packet->buf;
size_t bufferlen = packet->len;
char str[1000];
const uint8_t *data = reinterpret_cast<const uint8_t*>(buffer);
size_t row = 0;
std::string line;
while (bufferlen > 0) {
line.clear();
sprintf(str, " %04zx: ", row);
line += str;
size_t n;
if (bufferlen < 16) n = bufferlen;
else n = 16;
for (size_t i = 0; i < n; i++) {
if (i == 8) { line += " "; }
sprintf(str, " %02x", data[i]);
line += str;
}
for (size_t i = n; i < 16; i++) { line += " "; }
line += " ";
for (size_t i = 0; i < n; i++) {
if (i == 8) { line += " "; }
uint8_t c = data[i];
if (!(0x20 <= c && c <= 0x7e)) c = '.';
sprintf(str, "%c", c);
line += str;
}
println("");
lines.push_back(line);
bufferlen -= n;
data += n;
row += n;
}
}
void refresh()
{
current_x = x;
current_y = y;
for (size_t i=0, c=0; i<lines.size() && c<h; i++, c++) {
if (i == get_cursor())
println_hl("%s", lines[i].c_str());
else
println("%s", lines[i].c_str());
}
for (size_t i=0; i<h-lines.size(); i++) {
for (size_t c=0; c<w; c++) print(" ");
println("");
}
}
};
enum cursor_state {
LIST,
DETAIL,
BINARY,
};
class Statusline {
const size_t x;
const size_t y;
const size_t w;
const cursor_state& state;
public:
Statusline(size_t ix, size_t iy, size_t iw, cursor_state& c)
: x(ix), y(iy), w(iw), state(c) {}
const char* state2str(cursor_state s)
{
switch (s) {
case LIST: return "LIST ";
case DETAIL: return "DETAIL ";
case BINARY: return "BINARY ";
default : return "UNKNOWN";
}
}
void refresh()
{
mvprintw(y, x, "[CUISHARK] pane=%s", state2str(state));
}
};
size_t a(size_t h) { return (h-1) % 3; }
size_t m(size_t h) { return ((h-1)-((h-1)%3))/3; }
#define H screen.geth()
class display {
slankdev::ncurses screen;
pcap_t *handle;
cursor_state cstate;
public:
Pane_list pane_list;
Pane_detail pane_detail;
Pane_binary pane_binary;
Statusline statusline;
display() :
cstate(LIST),
pane_list (0, 0 , screen.getw(), a(H)+m(H), screen),
pane_detail(0, a(H)+m(H) , screen.getw(), m(H) , screen),
pane_binary(0, a(H)+2*m(H), screen.getw(), m(H) , screen),
statusline (0, a(H)+3*m(H), screen.getw(), cstate)
{
char errbuf[PCAP_ERRBUF_SIZE];
handle = pcap_open_live("lo", BUFSIZ, 0, 0, errbuf);
// handle = pcap_open_offline("in.pcap", errbuf);
if (handle == NULL) {
throw slankdev::exception("pcap_open_live");
}
noecho();
screen.refresh();
}
~display() { pcap_close(handle); }
void charnge_cstate()
{
switch (cstate) {
case LIST : cstate = DETAIL; break;
case DETAIL: cstate = BINARY; break;
case BINARY: cstate = LIST ; break;
default : throw slankdev::exception("UNKNOWN state");
}
}
void press_j()
{
switch (cstate) {
case LIST : pane_list.inc_cursor() ; break;
case DETAIL: pane_detail.inc_cursor(); break;
case BINARY: pane_binary.inc_cursor(); break;
defaut: throw slankdev::exception("UNknown state");
}
}
void press_k()
{
switch (cstate) {
case LIST : pane_list.dec_cursor() ; break;
case DETAIL: pane_detail.dec_cursor(); break;
case BINARY: pane_binary.dec_cursor(); break;
defaut: throw slankdev::exception("UNknown state");
}
}
void press_enter()
{
switch (cstate) {
case LIST:
{
if (pane_list.packets.empty()) return;
Packet* pack = &pane_list.packets[pane_list.get_cursor()];
pane_detail.print_packet_detail(pack);
pane_binary.hex(pack);
break;
}
case DETAIL:
break;
case BINARY:
break;
defaut:
throw slankdev::exception("UNknown state");
break;
}
}
void view_help()
{
size_t x = 0;
size_t y = 0;
screen.mvprintw(y++, x, " ");
screen.mvprintw(y++, x, " CuiShark version 0.0 ");
screen.mvprintw(y++, x, " Copyright 2017-2020 Hiroki SHIROKURA. ");
screen.mvprintw(y++, x, " ");
screen.mvprintw(y++, x, " Avalable Keyboard commands are below. ");
screen.mvprintw(y++, x, " These are Vi-like key-bind because I'm vimmer. ");
screen.mvprintw(y++, x, " ");
screen.mvprintw(y++, x, " Commands ");
screen.mvprintw(y++, x, " j : down ");
screen.mvprintw(y++, x, " k : up ");
screen.mvprintw(y++, x, " tab : switch pane ");
screen.mvprintw(y++, x, " enter : select ");
screen.mvprintw(y++, x, " ? : view help ");
screen.mvprintw(y++, x, " C-c : exit ");
screen.mvprintw(y++, x, " ");
screen.getchar();
}
void dispatch()
{
struct pollfd fds[2];
fds[0].fd = pcap_get_selectable_fd(handle);
fds[0].events = POLLIN;
fds[1].fd = fileno(stdin);
fds[1].events = POLLIN;
while (1) {
if (poll(fds, 2, 100)) {
if (fds[0].revents & POLLIN) {
struct pcap_pkthdr header;
const u_char *packet;
packet = pcap_next(handle, &header);
pane_list.push_packet(packet, &header);
}
if (fds[1].revents & POLLIN) {
int c = screen.getchar();
switch (c) {
case 'j':
press_j();
break;
case 'k':
press_k();
break;
case '\t':
charnge_cstate();
break;
case '\n':
press_enter();
break;
case '?':
view_help();
break;
}
}
}
refresh();
}
}
void refresh()
{
pane_list.refresh();
pane_detail.refresh();
pane_binary.refresh();
statusline.refresh();
screen.refresh();
}
};
int main(int argc, char *argv[])
{
display dsp0;
dsp0.dispatch();
}
<|endoftext|> |
<commit_before>#include <cstdlib>
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include "fasta_parser.h"
#include "sa_is.h"
struct suffix {
unsigned int index;
std::string suffix_string;
};
bool compare(suffix i, suffix j) {
return i.suffix_string < j.suffix_string ;
}
// Creates a sufix array for the given string using a simple and slow method
void suffix_array(std::string str, std::vector<int> &sa) {
std::vector<suffix> suffixes;
for (unsigned int i = 0; i < str.size(); ++i) {
suffix *s = new suffix;
s->index = i;
s->suffix_string = str.substr(i);
suffixes.push_back(*s);
delete s;
}
std::sort(suffixes.begin(), suffixes.end(), compare);
for (unsigned int i = 0; i < suffixes.size(); ++i) {
sa.push_back(suffixes[i].index);
}
}
int main(int argc, char *argv[]) {
if(argc != 5) {
std::cerr << "Usage: " << argv[1] << " <file containing reference string>" << std::endl;
std::cerr << "Usage: " << argv[2] << " <file containing query string>" << std::endl;
std::cerr << "Usage: " << argv[3] << " <index level of sparseSA, K-SA>" << std::endl;
std::cerr << "Usage: " << argv[4] << " <size of minimal match>" << std::endl;
exit(-1);
}
std::ifstream ref_file(argv[1]);
std::ifstream query_file(argv[2]);
if(!ref_file.is_open()) {
std::cerr << "There was a problem openning the file \"" << argv[1] << "\"!\nAborting." << std::endl;
exit(-2);
}
if(!query_file.is_open()) {
std::cerr << "There was a problem openning the file \"" << argv[2] << "\"!\nAborting." << std::endl;
exit(-2);
}
std::string ref_string;
std::vector<string> refdescr;
std::vector<long> startpos;
fasta_parser(argv[1], ref_string, refdescr, startpos);
std::int K = atoi(argv[3]);
std::int L = atoi(argv[4]);
std::int N = ref_string;
std::string query_string;
std::getline(query_file, query_string);
std::cout << "Query: " << query_string << std::endl;
std::vector<int> sa;
sa.reserve(ref_string.size());
bool *types = new bool[ref_string.size()];
suffix_array(ref_string, sa);
type_array(ref_string.c_str(), types, ref_string.size(), sizeof(char));
for (unsigned int i = 0; i < sa.size(); ++i) {
std::cout << "[" << i << "]\t" << sa[i] << (types[sa[i]] ? "\tS\t" : "\tL\t")
<< ref_string.substr(sa[i]) << std::endl;
}
int *SA = new int[N];
int *sparseSA = new int[N / K];
int *ISA = new int[N];
// Creates Suffix Array using SA_IS algorithm
sa_is(ref_string.c_str(), SA, N, 256, sizeof(char));
// Create
// Creates Invese SA
for ( int i = 0; i < N; ++i) {;}
for (int i = 0; i < N); ++i) {
printf("%d ", SA[i]);
if (SA[i] != sa[i]) {
std::cout << "<-!!! ";
}
}
printf("\n");
return 0;
}
<commit_msg>ISA, LCP, SSA<commit_after>#include <cstdlib>
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include "fasta_parser.h"
#include "sa_is.h"
struct suffix {
unsigned int index;
std::string suffix_string;
};
bool compare(suffix i, suffix j) {
return i.suffix_string < j.suffix_string ;
}
// Creates a sufix array for the given string using a simple and slow method
void suffix_array(std::string str, std::vector<int> &sa) {
std::vector<suffix> suffixes;
for (unsigned int i = 0; i < str.size(); ++i) {
suffix *s = new suffix;
s->index = i;
s->suffix_string = str.substr(i);
suffixes.push_back(*s);
delete s;
}
std::sort(suffixes.begin(), suffixes.end(), compare);
for (unsigned int i = 0; i < suffixes.size(); ++i) {
sa.push_back(suffixes[i].index);
}
}
int main(int argc, char *argv[]) {
if(argc != 5) {
std::cerr << "Usage: " << argv[1] << " <file containing reference string>" << std::endl;
std::cerr << "Usage: " << argv[2] << " <file containing query string>" << std::endl;
std::cerr << "Usage: " << argv[3] << " <index level of sparseSA, K-SA>" << std::endl;
std::cerr << "Usage: " << argv[4] << " <size of minimal match>" << std::endl;
exit(-1);
}
std::ifstream ref_file(argv[1]);
std::ifstream query_file(argv[2]);
if(!ref_file.is_open()) {
std::cerr << "There was a problem openning the file \"" << argv[1] << "\"!\nAborting." << std::endl;
exit(-2);
}
if(!query_file.is_open()) {
std::cerr << "There was a problem openning the file \"" << argv[2] << "\"!\nAborting." << std::endl;
exit(-2);
}
std::string ref_string;
std::vector<string> refdescr;
std::vector<long> startpos;
fasta_parser(argv[1], ref_string, refdescr, startpos);
int K = atoi(argv[3]);
int L = atoi(argv[4]);
int N = ref_string.length();
std::string query_string;
std::getline(query_file, query_string);
std::cout << "Query: " << query_string << std::endl;
std::vector<int> sa;
sa.reserve(ref_string.size());
bool *types = new bool[ref_string.size()];
suffix_array(ref_string, sa);
type_array(ref_string.c_str(), types, ref_string.size(), sizeof(char));
for (unsigned int i = 0; i < sa.size(); ++i) {
std::cout << "[" << i << "]\t" << sa[i] << (types[sa[i]] ? "\tS\t" : "\tL\t")
<< ref_string.substr(sa[i]) << std::endl;
}
int *SA = new int[N];
int *sparseSA = new int[N / K];
int *ISA = new int[N];
int *LCP = new int[N / K];
// Creates Suffix Array using SA_IS algorithm
sa_is(ref_string.c_str(), SA, N, 256, sizeof(char));
// Generate Sparse Suffix Array
for (int i = 0; i < N / K; ++i) {
sparseSA[i] = SA[i * K];
}
// Generate ISA
for(long i = 0; i < N/K; i++) {
ISA[SA[i]/K] = i;
}
int h = 0;
for(int i = 0; i < N; i+=K) {
int m = ISA[i/K];
if(m==0) {
LCP[m] = 0;
}
else {
int j = SA[m-1];
while(i+h < N && j+h < N && ref_string[i+h] == ref_string[j+h]) {
h++;
}
LCP[m] = h;
}
h = std::max(0, h - K);
}
for (int i = 0; i < N; ++i) {
printf("%d ", SA[i]);
if (SA[i] != sa[i]) {
std::cout << "<-!!! ";
}
}
printf("\n");
return 0;
}
<|endoftext|> |
<commit_before>#include <stdint.h>
#include <stddef.h>
#include <stdarg.h>
#include <stdbool.h>
#include <new>
typedef uint64_t u64;
typedef uint32_t u32;
typedef uint16_t u16;
typedef uint8_t u8;
typedef uintptr_t size_t;
typedef unsigned int uint;
extern "C" void start64() __attribute__((noreturn));
#define STRING_INL_LINKAGE static
#include "string.c"
#define S_(X) #X
#define S(X) S_(X)
#define assert(X) \
do { if (!(X)) { assert_failed(__FILE__ ":" S(__LINE__), #X); } } while (0)
namespace {
void assert_failed(const char* file, const char* line, const char* msg) __attribute__((noreturn));
static const intptr_t kernel_base = -(1 << 30);
static constexpr void* PhysAddr(uintptr_t phys) {
return (void*)(phys + kernel_base);
}
static void memset16(u16* dest, u16 value, size_t n) {
if (/* constant(value) && */ (value >> 8) == (value & 0xff)) {
memset(dest, value, n * 2);
} else {
// rep movsw
while (n--) *dest++ = value;
}
}
namespace Console {
static u16* const buffer = (u16*)PhysAddr(0xb80a0);
static u16 pos;
static const u8 width = 80, height = 24;
void clear() {
pos = 0;
memset16(buffer, 0, width * height);
}
void write(char c) {
if (c == '\n') {
u8 fill = width - (pos % width);
while(fill--) write(' ');
} else {
buffer[pos++] = 0x0700 | c;
}
}
void write(const char *s) {
while (char c = *s++) write(c);
}
};
void assert_failed(const char* fileline, const char* msg) {
using Console::write;
write(fileline); write(": ASSERT FAILED: "); write(msg);
for(;;);
}
} // namespace
using Console::write;
void start64() {
write("Hello world\n");
assert(!"Testing the assert");
for(;;);
}
<commit_msg>Add support for qemu/bochs debug console<commit_after>#include <stdint.h>
#include <stddef.h>
#include <stdarg.h>
#include <stdbool.h>
#include <new>
typedef uint64_t u64;
typedef uint32_t u32;
typedef uint16_t u16;
typedef uint8_t u8;
typedef uintptr_t size_t;
typedef unsigned int uint;
extern "C" void start64() __attribute__((noreturn));
#define DEBUGCON 1
#define STRING_INL_LINKAGE static
#include "string.c"
#define S_(X) #X
#define S(X) S_(X)
#define assert(X) \
do { if (!(X)) { assert_failed(__FILE__ ":" S(__LINE__), #X "\n"); } } while (0)
namespace {
void assert_failed(const char* file, const char* line, const char* msg) __attribute__((noreturn));
static const intptr_t kernel_base = -(1 << 30);
static constexpr void* PhysAddr(uintptr_t phys) {
return (void*)(phys + kernel_base);
}
static void memset16(u16* dest, u16 value, size_t n) {
if (/* constant(value) && */ (value >> 8) == (value & 0xff)) {
memset(dest, value, n * 2);
} else {
// rep movsw
while (n--) *dest++ = value;
}
}
static void debugcon_putc(char c) {
#if DEBUGCON
asm("outb %0,%1"::"a"(c),"d"((u16)0xe9));
#endif
}
namespace Console {
static u16* const buffer = (u16*)PhysAddr(0xb80a0);
static u16 pos;
static const u8 width = 80, height = 24;
void clear() {
pos = 0;
memset16(buffer, 0, width * height);
}
void write(char c) {
if (c == '\n') {
u8 fill = width - (pos % width);
while(fill--) buffer[pos++] = 0;
} else {
buffer[pos++] = 0x0700 | c;
}
debugcon_putc(c);
}
void write(const char *s) {
while (char c = *s++) write(c);
}
};
void assert_failed(const char* fileline, const char* msg) {
using Console::write;
write(fileline); write(": ASSERT FAILED: "); write(msg);
for(;;);
}
} // namespace
using Console::write;
void start64() {
write("Hello world\n");
assert(!"Testing the assert");
for(;;);
}
<|endoftext|> |
<commit_before>#include <GL/glew.h>
#define GLM_SWIZZLE
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>
#include "SDL.h"
#undef main
#include <list>
#include <algorithm>
#include <functional>
#include "RenderingContext.h"
#include "scene/GraphNode.h"
#include "scene/Skybox.h"
#include "scene/Terrain.h"
#include "scene/Mech.h"
#include "animations/Animation.h"
static SDL_Window *win;
static SDL_GLContext context;
bool conf_enable_msaa;
GraphNode *scene = NULL;
RenderingContext *rc;
std::list<Animation*> animations;
int move_forward = 0;
class TestSceneRotation : public Animation
{
private:
GraphNode* subject;
public:
TestSceneRotation(GraphNode* subject) : subject(subject)
{
rotation = 0;
y = 0;
};
virtual void update(float timestep)
{
glm::vec4 cam_pos =
subject->getWorldCoordinates(
glm::rotate(rotation, glm::vec3(0.0f, 1.0f, 0.0f)) *
glm::vec4(0.0f, y, 3.0f, 1.0f));
rc->setCamera(cam_pos.xyz(), subject);
while (rotation > 360.0f) rotation -= 360.0f;
};
float y;
float rotation;
} *scene_rot;
class MechWalk : public Animation
{
private:
Mech* subject;
Terrain* terrain;
float leg_bend;
int leg_state;
public:
MechWalk(Mech* subject, Terrain* terrain) : subject(subject), terrain(terrain)
{
leg_state = 0;
leg_bend = 90.0f;
};
virtual void update(float timestep)
{
if (move_forward) {
subject->bendLeg(0, 35.0f + leg_bend);
subject->bendLeg(1, 95.0f - leg_bend);
subject->bendLeg(2, 35.0f + leg_bend);
subject->bendLeg(3, 95.0f - leg_bend);
if (leg_state) {
leg_bend--;
if (leg_bend <= 0.0f) leg_state = 0;
} else {
leg_bend++;
if (leg_bend >= 60.0f) leg_state = 1;
}
}
glm::vec4 current_pos = subject->getWorldCoordinates();
current_pos.z += move_forward * timestep;
glm::vec3 new_pos(current_pos.x, terrain->getHeight(current_pos.x, current_pos.z) + subject->getDistanceToGround(), current_pos.z);
subject->setPosition(new_pos.x, new_pos.y, new_pos.z);
}
};
void reshape(int width, int height)
{
glViewport(0, 0, (GLint) width, (GLint) height);
rc->reshape(width, height);
}
/// Sets up rendering and creates the initial scene graph.
void init_scene()
{
static GLfloat pos[4] =
{3000.0, 1000.0, -3000.0, 0.0};
glLightfv(GL_LIGHT0, GL_POSITION, pos);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_NORMALIZE);
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glEnable(GL_TEXTURE_2D);
//glEnable(GL_MULTISAMPLE);
scene = new GraphNode;
scene->addMember(new Skybox);
Mech *mech = new Mech();
scene->addMember(mech);
//mech->setVisibility(false);
Terrain *terrain = new Terrain("textures/heightmap.bmp", 20.0f);
scene->addMember(terrain);
rc = new RenderingContext(scene);
rc->setCamera(glm::vec3(0.0f, 1.0f, -3.0f), mech);
scene_rot = new TestSceneRotation(mech);
animations.push_back(scene_rot);
animations.push_back(new MechWalk(mech, terrain));
}
/// Sets up a new frame and renders the scene.
void draw_scene()
{
rc->update();
GLenum error = glGetError();
if (error != GL_NO_ERROR)
puts((const char*)gluErrorString(error));
glFlush();
SDL_GL_SwapWindow(win);
}
/// Updates scene state
void update_scene(float timestep)
{
std::for_each(
animations.begin(),
animations.end(),
std::bind2nd(std::mem_fun(&Animation::update), timestep));
}
int main(int argc, char const *argv[])
{
#ifdef WIN32
conf_enable_msaa = true;
#else
conf_enable_msaa = false;
#endif
while(*++argv) {
if (!strcmp(*argv, "--enable-msaa"))
conf_enable_msaa = true;
else if (!strcmp(*argv, "--disable-msaa"))
conf_enable_msaa = false;
}
Uint8 *keys;
int w = 800, h = 600;
printf("Hello!\n");
if (0 != SDL_Init(SDL_INIT_EVERYTHING)) return 1;
// Set up an OpenGL window
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
if (conf_enable_msaa) {
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);
}
win = SDL_CreateWindow("Mech",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
w, h,
SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);
if ( ! win ) {
puts(SDL_GetError());
SDL_Quit();
exit(2);
}
context = SDL_GL_CreateContext(win);
GLenum err = glewInit();
if (GLEW_OK != err)
{
printf("glewInit error: %s\n", glewGetErrorString(err));
}
printf("Using GLEW %s\n", glewGetString(GLEW_VERSION));
printf("OpenGL version: %s\n", glGetString(GL_VERSION));
init_scene();
reshape(w, h);
Uint32 previous_ticks = SDL_GetTicks();
Uint32 fps_prev_t = previous_ticks, frames = 0;
int done = 0;
SDL_Event event;
while (!done) {
while (SDL_PollEvent(&event)) {
switch(event.type) {
case SDL_WINDOWEVENT:
if (event.window.event == SDL_WINDOWEVENT_RESIZED) {
w = event.window.data1;
h = event.window.data2;
reshape(w,h);
}
break;
case SDL_MOUSEMOTION:
scene_rot->y = 4.0f * (float)(event.motion.y) / (float)(h) - 2.0f;
scene_rot->rotation = -360.0f * (float)(event.motion.x) / (float)(w);
break;
case SDL_QUIT:
done = 1;
break;
}
}
keys = SDL_GetKeyboardState(NULL);
if (keys[SDL_SCANCODE_ESCAPE]) {
done = 1;
}
if (keys[SDL_SCANCODE_W])
move_forward = 1;
else if (keys[SDL_SCANCODE_S])
move_forward = -1;
else
move_forward = 0;
// update
Uint32 t = SDL_GetTicks();
update_scene((float)(t - previous_ticks) / 1000.0f);
previous_ticks = t;
// count FPS
frames++;
if (fps_prev_t + 5000 < t) {
printf("FPS: %f\n", (float)frames / ((float)(t - fps_prev_t) / 1000.0f));
fps_prev_t = t;
frames = 0;
}
// render
draw_scene();
}
SDL_Quit();
delete scene;
return 0;
}
<commit_msg>Change the beginning of the walk animation.<commit_after>#include <GL/glew.h>
#define GLM_SWIZZLE
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>
#include "SDL.h"
#undef main
#include <list>
#include <algorithm>
#include <functional>
#include "RenderingContext.h"
#include "scene/GraphNode.h"
#include "scene/Skybox.h"
#include "scene/Terrain.h"
#include "scene/Mech.h"
#include "animations/Animation.h"
static SDL_Window *win;
static SDL_GLContext context;
bool conf_enable_msaa;
GraphNode *scene = NULL;
RenderingContext *rc;
std::list<Animation*> animations;
int move_forward = 0;
class TestSceneRotation : public Animation
{
private:
GraphNode* subject;
public:
TestSceneRotation(GraphNode* subject) : subject(subject)
{
rotation = 0;
y = 0;
};
virtual void update(float timestep)
{
glm::vec4 cam_pos =
subject->getWorldCoordinates(
glm::rotate(rotation, glm::vec3(0.0f, 1.0f, 0.0f)) *
glm::vec4(0.0f, y, 3.0f, 1.0f));
rc->setCamera(cam_pos.xyz(), subject);
while (rotation > 360.0f) rotation -= 360.0f;
};
float y;
float rotation;
} *scene_rot;
class MechWalk : public Animation
{
private:
Mech* subject;
Terrain* terrain;
float leg_bend;
int leg_state;
public:
MechWalk(Mech* subject, Terrain* terrain) : subject(subject), terrain(terrain)
{
leg_state = 0;
leg_bend = 30.0f;
};
virtual void update(float timestep)
{
subject->bendLeg(0, 35.0f + leg_bend);
subject->bendLeg(1, 95.0f - leg_bend);
subject->bendLeg(2, 35.0f + leg_bend);
subject->bendLeg(3, 95.0f - leg_bend);
if (move_forward) {
if (leg_state) {
leg_bend--;
if (leg_bend <= 0.0f) leg_state = 0;
} else {
leg_bend++;
if (leg_bend >= 60.0f) leg_state = 1;
}
} else {
leg_state = 0;
leg_bend = 30.0f;
}
glm::vec4 current_pos = subject->getWorldCoordinates();
current_pos.z += move_forward * timestep;
glm::vec3 new_pos(current_pos.x, terrain->getHeight(current_pos.x, current_pos.z) + subject->getDistanceToGround(), current_pos.z);
subject->setPosition(new_pos.x, new_pos.y, new_pos.z);
}
};
void reshape(int width, int height)
{
glViewport(0, 0, (GLint) width, (GLint) height);
rc->reshape(width, height);
}
/// Sets up rendering and creates the initial scene graph.
void init_scene()
{
static GLfloat pos[4] =
{3000.0, 1000.0, -3000.0, 0.0};
glLightfv(GL_LIGHT0, GL_POSITION, pos);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_NORMALIZE);
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glEnable(GL_TEXTURE_2D);
//glEnable(GL_MULTISAMPLE);
scene = new GraphNode;
scene->addMember(new Skybox);
Mech *mech = new Mech();
scene->addMember(mech);
//mech->setVisibility(false);
Terrain *terrain = new Terrain("textures/heightmap.bmp", 20.0f);
scene->addMember(terrain);
rc = new RenderingContext(scene);
rc->setCamera(glm::vec3(0.0f, 1.0f, -3.0f), mech);
scene_rot = new TestSceneRotation(mech);
animations.push_back(scene_rot);
animations.push_back(new MechWalk(mech, terrain));
}
/// Sets up a new frame and renders the scene.
void draw_scene()
{
rc->update();
GLenum error = glGetError();
if (error != GL_NO_ERROR)
puts((const char*)gluErrorString(error));
glFlush();
SDL_GL_SwapWindow(win);
}
/// Updates scene state
void update_scene(float timestep)
{
std::for_each(
animations.begin(),
animations.end(),
std::bind2nd(std::mem_fun(&Animation::update), timestep));
}
int main(int argc, char const *argv[])
{
#ifdef WIN32
conf_enable_msaa = true;
#else
conf_enable_msaa = false;
#endif
while(*++argv) {
if (!strcmp(*argv, "--enable-msaa"))
conf_enable_msaa = true;
else if (!strcmp(*argv, "--disable-msaa"))
conf_enable_msaa = false;
}
Uint8 *keys;
int w = 800, h = 600;
printf("Hello!\n");
if (0 != SDL_Init(SDL_INIT_EVERYTHING)) return 1;
// Set up an OpenGL window
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
if (conf_enable_msaa) {
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);
}
win = SDL_CreateWindow("Mech",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
w, h,
SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);
if ( ! win ) {
puts(SDL_GetError());
SDL_Quit();
exit(2);
}
context = SDL_GL_CreateContext(win);
GLenum err = glewInit();
if (GLEW_OK != err)
{
printf("glewInit error: %s\n", glewGetErrorString(err));
}
printf("Using GLEW %s\n", glewGetString(GLEW_VERSION));
printf("OpenGL version: %s\n", glGetString(GL_VERSION));
init_scene();
reshape(w, h);
Uint32 previous_ticks = SDL_GetTicks();
Uint32 fps_prev_t = previous_ticks, frames = 0;
int done = 0;
SDL_Event event;
while (!done) {
while (SDL_PollEvent(&event)) {
switch(event.type) {
case SDL_WINDOWEVENT:
if (event.window.event == SDL_WINDOWEVENT_RESIZED) {
w = event.window.data1;
h = event.window.data2;
reshape(w,h);
}
break;
case SDL_MOUSEMOTION:
scene_rot->y = 4.0f * (float)(event.motion.y) / (float)(h) - 2.0f;
scene_rot->rotation = -360.0f * (float)(event.motion.x) / (float)(w);
break;
case SDL_QUIT:
done = 1;
break;
}
}
keys = SDL_GetKeyboardState(NULL);
if (keys[SDL_SCANCODE_ESCAPE]) {
done = 1;
}
if (keys[SDL_SCANCODE_W])
move_forward = 1;
else if (keys[SDL_SCANCODE_S])
move_forward = -1;
else
move_forward = 0;
// update
Uint32 t = SDL_GetTicks();
update_scene((float)(t - previous_ticks) / 1000.0f);
previous_ticks = t;
// count FPS
frames++;
if (fps_prev_t + 5000 < t) {
printf("FPS: %f\n", (float)frames / ((float)(t - fps_prev_t) / 1000.0f));
fps_prev_t = t;
frames = 0;
}
// render
draw_scene();
}
SDL_Quit();
delete scene;
return 0;
}
<|endoftext|> |
<commit_before>/** @file
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "slice.h"
#include "Config.h"
#include "Data.h"
#include "HttpHeader.h"
#include "intercept.h"
#include "ts/remap.h"
#include "ts/ts.h"
#include <netinet/in.h>
namespace
{
Config globalConfig;
bool
read_request(TSHttpTxn txnp, Config *const config)
{
DEBUG_LOG("slice read_request");
TxnHdrMgr hdrmgr;
hdrmgr.populateFrom(txnp, TSHttpTxnClientReqGet);
HttpHeader const header(hdrmgr.m_buffer, hdrmgr.m_lochdr);
if (TS_HTTP_METHOD_GET == header.method()) {
static int const SLICER_MIME_LEN_INFO = strlen(SLICER_MIME_FIELD_INFO);
if (!header.hasKey(SLICER_MIME_FIELD_INFO, SLICER_MIME_LEN_INFO)) {
// turn off any and all transaction caching (shouldn't matter)
TSHttpTxnServerRespNoStoreSet(txnp, 1);
TSHttpTxnRespCacheableSet(txnp, 0);
TSHttpTxnReqCacheableSet(txnp, 0);
DEBUG_LOG("slice accepting and slicing");
// connection back into ATS
sockaddr const *const ip = TSHttpTxnClientAddrGet(txnp);
if (nullptr == ip) {
return false;
}
TSAssert(nullptr != config);
Data *const data = new Data(config);
// set up feedback connect
if (AF_INET == ip->sa_family) {
memcpy(&data->m_client_ip, ip, sizeof(sockaddr_in));
} else if (AF_INET6 == ip->sa_family) {
memcpy(&data->m_client_ip, ip, sizeof(sockaddr_in6));
} else {
delete data;
return false;
}
// need to reset the HOST field for global plugin
data->m_hostlen = sizeof(data->m_hostname) - 1;
if (!header.valueForKey(TS_MIME_FIELD_HOST, TS_MIME_LEN_HOST, data->m_hostname, &data->m_hostlen)) {
DEBUG_LOG("Unable to get hostname from header");
delete data;
return false;
}
// is the plugin configured to use a remap host?
std::string const &newhost = config->m_remaphost;
if (newhost.empty()) {
TSMBuffer urlbuf;
TSMLoc urlloc;
TSReturnCode rcode = TSHttpTxnPristineUrlGet(txnp, &urlbuf, &urlloc);
if (TS_SUCCESS == rcode) {
TSMBuffer const newbuf = TSMBufferCreate();
TSMLoc newloc = nullptr;
rcode = TSUrlClone(newbuf, urlbuf, urlloc, &newloc);
TSHandleMLocRelease(urlbuf, TS_NULL_MLOC, urlloc);
if (TS_SUCCESS != rcode) {
ERROR_LOG("Error cloning pristine url");
TSMBufferDestroy(newbuf);
delete data;
return false;
}
data->m_urlbuf = newbuf;
data->m_urlloc = newloc;
}
} else { // grab the effective url, swap out the host and zero the port
int len = 0;
char *const effstr = TSHttpTxnEffectiveUrlStringGet(txnp, &len);
if (nullptr != effstr) {
TSMBuffer const newbuf = TSMBufferCreate();
TSMLoc newloc = nullptr;
bool okay = false;
if (TS_SUCCESS == TSUrlCreate(newbuf, &newloc)) {
char const *start = effstr;
if (TS_PARSE_DONE == TSUrlParse(newbuf, newloc, &start, start + len)) {
if (TS_SUCCESS == TSUrlHostSet(newbuf, newloc, newhost.c_str(), newhost.size()) &&
TS_SUCCESS == TSUrlPortSet(newbuf, newloc, 0)) {
okay = true;
}
}
}
TSfree(effstr);
if (!okay) {
ERROR_LOG("Error cloning effective url");
if (nullptr != newloc) {
TSHandleMLocRelease(newbuf, nullptr, newloc);
}
TSMBufferDestroy(newbuf);
delete data;
return false;
}
data->m_urlbuf = newbuf;
data->m_urlloc = newloc;
}
}
if (TSIsDebugTagSet(PLUGIN_NAME)) {
int len = 0;
char *const urlstr = TSUrlStringGet(data->m_urlbuf, data->m_urlloc, &len);
DEBUG_LOG("slice url: %.*s", len, urlstr);
TSfree(urlstr);
}
// we'll intercept this GET and do it ourselves
TSCont const icontp(TSContCreate(intercept_hook, TSMutexCreate()));
TSContDataSet(icontp, (void *)data);
TSHttpTxnIntercept(icontp, txnp);
return true;
} else {
DEBUG_LOG("slice passing GET request through to next plugin");
}
}
return false;
}
int
global_read_request_hook(TSCont // contp
,
TSEvent // event
,
void *edata)
{
TSHttpTxn const txnp = static_cast<TSHttpTxn>(edata);
read_request(txnp, &globalConfig);
TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);
return 0;
}
} // namespace
///// remap plugin engine
SLICE_EXPORT
TSRemapStatus
TSRemapDoRemap(void *ih, TSHttpTxn txnp, TSRemapRequestInfo *rri)
{
Config *const config = static_cast<Config *>(ih);
if (read_request(txnp, config)) {
return TSREMAP_DID_REMAP_STOP;
} else {
return TSREMAP_NO_REMAP;
}
}
///// remap plugin setup and teardown
SLICE_EXPORT
void
TSRemapOSResponse(void *ih, TSHttpTxn rh, int os_response_type)
{
}
SLICE_EXPORT
TSReturnCode
TSRemapNewInstance(int argc, char *argv[], void **ih, char * /* errbuf */, int /* errbuf_size */)
{
Config *const config = new Config;
if (2 < argc) {
config->fromArgs(argc - 2, argv + 2);
}
*ih = static_cast<void *>(config);
return TS_SUCCESS;
}
SLICE_EXPORT
void
TSRemapDeleteInstance(void *ih)
{
if (nullptr != ih) {
Config *const config = static_cast<Config *>(ih);
delete config;
}
}
SLICE_EXPORT
TSReturnCode
TSRemapInit(TSRemapInterface *api_info, char *errbug, int errbuf_size)
{
DEBUG_LOG("slice remap is successfully initialized.");
return TS_SUCCESS;
}
///// global plugin
SLICE_EXPORT
void
TSPluginInit(int argc, char const *argv[])
{
TSPluginRegistrationInfo info;
info.plugin_name = (char *)PLUGIN_NAME;
info.vendor_name = (char *)"Apache Software Foundation";
info.support_email = (char *)"dev@trafficserver.apache.org";
if (TS_SUCCESS != TSPluginRegister(&info)) {
ERROR_LOG("Plugin registration failed.\n");
ERROR_LOG("Unable to initialize plugin (disabled).");
return;
}
if (1 < argc) {
globalConfig.fromArgs(argc - 1, argv + 1);
}
TSCont const contp(TSContCreate(global_read_request_hook, nullptr));
// Called immediately after the request header is read from the client
TSHttpHookAdd(TS_HTTP_READ_REQUEST_HDR_HOOK, contp);
}
<commit_msg>if transaction status nonzero, bypass the slice plugin (#6417)<commit_after>/** @file
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "slice.h"
#include "Config.h"
#include "Data.h"
#include "HttpHeader.h"
#include "intercept.h"
#include "ts/remap.h"
#include "ts/ts.h"
#include <netinet/in.h>
namespace
{
Config globalConfig;
bool
read_request(TSHttpTxn txnp, Config *const config)
{
DEBUG_LOG("slice read_request");
TxnHdrMgr hdrmgr;
hdrmgr.populateFrom(txnp, TSHttpTxnClientReqGet);
HttpHeader const header(hdrmgr.m_buffer, hdrmgr.m_lochdr);
if (TS_HTTP_METHOD_GET == header.method()) {
static int const SLICER_MIME_LEN_INFO = strlen(SLICER_MIME_FIELD_INFO);
if (!header.hasKey(SLICER_MIME_FIELD_INFO, SLICER_MIME_LEN_INFO)) {
// check if any previous plugin has monkeyed with the transaction status
TSHttpStatus const txnstat = TSHttpTxnStatusGet(txnp);
if (0 != (int)txnstat) {
DEBUG_LOG("slice: txn status change detected (%d), skipping plugin\n", (int)txnstat);
return false;
}
// turn off any and all transaction caching (shouldn't matter)
TSHttpTxnServerRespNoStoreSet(txnp, 1);
TSHttpTxnRespCacheableSet(txnp, 0);
TSHttpTxnReqCacheableSet(txnp, 0);
DEBUG_LOG("slice accepting and slicing");
// connection back into ATS
sockaddr const *const ip = TSHttpTxnClientAddrGet(txnp);
if (nullptr == ip) {
return false;
}
TSAssert(nullptr != config);
Data *const data = new Data(config);
// set up feedback connect
if (AF_INET == ip->sa_family) {
memcpy(&data->m_client_ip, ip, sizeof(sockaddr_in));
} else if (AF_INET6 == ip->sa_family) {
memcpy(&data->m_client_ip, ip, sizeof(sockaddr_in6));
} else {
delete data;
return false;
}
// need to reset the HOST field for global plugin
data->m_hostlen = sizeof(data->m_hostname) - 1;
if (!header.valueForKey(TS_MIME_FIELD_HOST, TS_MIME_LEN_HOST, data->m_hostname, &data->m_hostlen)) {
DEBUG_LOG("Unable to get hostname from header");
delete data;
return false;
}
// is the plugin configured to use a remap host?
std::string const &newhost = config->m_remaphost;
if (newhost.empty()) {
TSMBuffer urlbuf;
TSMLoc urlloc;
TSReturnCode rcode = TSHttpTxnPristineUrlGet(txnp, &urlbuf, &urlloc);
if (TS_SUCCESS == rcode) {
TSMBuffer const newbuf = TSMBufferCreate();
TSMLoc newloc = nullptr;
rcode = TSUrlClone(newbuf, urlbuf, urlloc, &newloc);
TSHandleMLocRelease(urlbuf, TS_NULL_MLOC, urlloc);
if (TS_SUCCESS != rcode) {
ERROR_LOG("Error cloning pristine url");
TSMBufferDestroy(newbuf);
delete data;
return false;
}
data->m_urlbuf = newbuf;
data->m_urlloc = newloc;
}
} else { // grab the effective url, swap out the host and zero the port
int len = 0;
char *const effstr = TSHttpTxnEffectiveUrlStringGet(txnp, &len);
if (nullptr != effstr) {
TSMBuffer const newbuf = TSMBufferCreate();
TSMLoc newloc = nullptr;
bool okay = false;
if (TS_SUCCESS == TSUrlCreate(newbuf, &newloc)) {
char const *start = effstr;
if (TS_PARSE_DONE == TSUrlParse(newbuf, newloc, &start, start + len)) {
if (TS_SUCCESS == TSUrlHostSet(newbuf, newloc, newhost.c_str(), newhost.size()) &&
TS_SUCCESS == TSUrlPortSet(newbuf, newloc, 0)) {
okay = true;
}
}
}
TSfree(effstr);
if (!okay) {
ERROR_LOG("Error cloning effective url");
if (nullptr != newloc) {
TSHandleMLocRelease(newbuf, nullptr, newloc);
}
TSMBufferDestroy(newbuf);
delete data;
return false;
}
data->m_urlbuf = newbuf;
data->m_urlloc = newloc;
}
}
if (TSIsDebugTagSet(PLUGIN_NAME)) {
int len = 0;
char *const urlstr = TSUrlStringGet(data->m_urlbuf, data->m_urlloc, &len);
DEBUG_LOG("slice url: %.*s", len, urlstr);
TSfree(urlstr);
}
// we'll intercept this GET and do it ourselves
TSCont const icontp(TSContCreate(intercept_hook, TSMutexCreate()));
TSContDataSet(icontp, (void *)data);
TSHttpTxnIntercept(icontp, txnp);
return true;
} else {
DEBUG_LOG("slice passing GET request through to next plugin");
}
}
return false;
}
int
global_read_request_hook(TSCont // contp
,
TSEvent // event
,
void *edata)
{
TSHttpTxn const txnp = static_cast<TSHttpTxn>(edata);
read_request(txnp, &globalConfig);
TSHttpTxnReenable(txnp, TS_EVENT_HTTP_CONTINUE);
return 0;
}
} // namespace
///// remap plugin engine
SLICE_EXPORT
TSRemapStatus
TSRemapDoRemap(void *ih, TSHttpTxn txnp, TSRemapRequestInfo *rri)
{
Config *const config = static_cast<Config *>(ih);
if (read_request(txnp, config)) {
return TSREMAP_DID_REMAP_STOP;
} else {
return TSREMAP_NO_REMAP;
}
}
///// remap plugin setup and teardown
SLICE_EXPORT
void
TSRemapOSResponse(void *ih, TSHttpTxn rh, int os_response_type)
{
}
SLICE_EXPORT
TSReturnCode
TSRemapNewInstance(int argc, char *argv[], void **ih, char * /* errbuf */, int /* errbuf_size */)
{
Config *const config = new Config;
if (2 < argc) {
config->fromArgs(argc - 2, argv + 2);
}
*ih = static_cast<void *>(config);
return TS_SUCCESS;
}
SLICE_EXPORT
void
TSRemapDeleteInstance(void *ih)
{
if (nullptr != ih) {
Config *const config = static_cast<Config *>(ih);
delete config;
}
}
SLICE_EXPORT
TSReturnCode
TSRemapInit(TSRemapInterface *api_info, char *errbug, int errbuf_size)
{
DEBUG_LOG("slice remap is successfully initialized.");
return TS_SUCCESS;
}
///// global plugin
SLICE_EXPORT
void
TSPluginInit(int argc, char const *argv[])
{
TSPluginRegistrationInfo info;
info.plugin_name = (char *)PLUGIN_NAME;
info.vendor_name = (char *)"Apache Software Foundation";
info.support_email = (char *)"dev@trafficserver.apache.org";
if (TS_SUCCESS != TSPluginRegister(&info)) {
ERROR_LOG("Plugin registration failed.\n");
ERROR_LOG("Unable to initialize plugin (disabled).");
return;
}
if (1 < argc) {
globalConfig.fromArgs(argc - 1, argv + 1);
}
TSCont const contp(TSContCreate(global_read_request_hook, nullptr));
// Called immediately after the request header is read from the client
TSHttpHookAdd(TS_HTTP_READ_REQUEST_HDR_HOOK, contp);
}
<|endoftext|> |
<commit_before>/* This file is part of Ingen.
* Copyright (C) 2007 Dave Robillard <http://drobilla.net>
*
* Ingen is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* Ingen 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 General Public License for details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include CONFIG_H_PATH
#include <cstdlib>
#include <pthread.h>
#include <dirent.h>
#include <float.h>
#include <cmath>
#include "module/World.hpp"
#include "NodeFactory.hpp"
#include "ThreadManager.hpp"
#include "MidiNoteNode.hpp"
#include "MidiTriggerNode.hpp"
#include "MidiControlNode.hpp"
#include "TransportNode.hpp"
#include "PatchImpl.hpp"
#include "InternalPlugin.hpp"
#ifdef HAVE_LADSPA
#include "LADSPANode.hpp"
#include "LADSPAPlugin.hpp"
#endif
#ifdef HAVE_SLV2
#include <slv2/slv2.h>
#include "LV2Plugin.hpp"
#include "LV2Node.hpp"
#endif
using namespace std;
namespace Ingen {
NodeFactory::NodeFactory(Ingen::Shared::World* world)
: _world(world)
, _has_loaded(false)
#ifdef HAVE_SLV2
, _lv2_info(new LV2Info(world->slv2_world))
#endif
{
}
NodeFactory::~NodeFactory()
{
for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i)
if (i->second->type() != Plugin::Internal)
delete i->second;
_plugins.clear();
}
PluginImpl*
NodeFactory::plugin(const string& uri)
{
const Plugins::const_iterator i = _plugins.find(uri);
return ((i != _plugins.end()) ? i->second : NULL);
}
/** DEPRECATED: Find a plugin by type, lib, label.
*
* Slow. Evil. Do not use.
*/
PluginImpl*
NodeFactory::plugin(const string& type, const string& lib, const string& label)
{
if (type != "LADSPA" || lib == "" || label == "")
return NULL;
for (Plugins::const_iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
LADSPAPlugin* lp = dynamic_cast<LADSPAPlugin*>(i->second);
if (lp && lp->type_string() == type
&& lp->library_name() == lib
&& lp->label() == label)
return lp;
}
cerr << "ERROR: Failed to find " << type << " plugin " << lib << " / " << label << endl;
return NULL;
}
void
NodeFactory::load_plugins()
{
assert(ThreadManager::current_thread_id() == THREAD_PRE_PROCESS);
// Only load if we havn't already, so every client connecting doesn't cause
// this (expensive!) stuff to happen. Not the best solution - would be nice
// if clients could refresh plugins list for whatever reason :/
if (!_has_loaded) {
_plugins.clear(); // FIXME: assert empty?
load_internal_plugins();
#ifdef HAVE_SLV2
load_lv2_plugins();
#endif
#ifdef HAVE_LADSPA
load_ladspa_plugins();
#endif
_has_loaded = true;
}
#if 0
for (Plugins::const_iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
assert(Path::is_valid_name(i->second->symbol()));
cerr << "PLUGIN: " << i->second->uri() << " - " << i->second->symbol()
<< " (" << i->second->name() << ")" << endl;
PatchImpl* parent = new PatchImpl(*_world->local_engine, "dummy", 1, NULL, 1, 1, 1);
NodeImpl* node = i->second->instantiate("foo", 0, parent, 48000, 512);
if (node)
for (uint32_t i=0; i < node->num_ports(); ++i) {
cerr << "\t" << node->port(i)->name() << endl;
}
cerr << endl;
}
#endif
//cerr << "[NodeFactory] # Plugins: " << _plugins.size() << endl;
}
void
NodeFactory::load_internal_plugins()
{
// This is a touch gross...
PatchImpl* parent = new PatchImpl(*_world->local_engine, "dummy", 1, NULL, 1, 1, 1);
NodeImpl* n = NULL;
n = new MidiNoteNode("foo", 1, parent, 1, 1);
_plugins.insert(make_pair(n->plugin_impl()->uri(), n->plugin_impl()));
delete n;
n = new MidiTriggerNode("foo", 1, parent, 1, 1);
_plugins.insert(make_pair(n->plugin_impl()->uri(), n->plugin_impl()));
delete n;
n = new MidiControlNode("foo", 1, parent, 1, 1);
_plugins.insert(make_pair(n->plugin_impl()->uri(), n->plugin_impl()));
delete n;
n = new TransportNode("foo", 1, parent, 1, 1);
_plugins.insert(make_pair(n->plugin_impl()->uri(), n->plugin_impl()));
delete n;
delete parent;
}
#ifdef HAVE_SLV2
/** Loads information about all LV2 plugins into internal plugin database.
*/
void
NodeFactory::load_lv2_plugins()
{
SLV2Plugins plugins = slv2_world_get_all_plugins(_world->slv2_world);
//cerr << "[NodeFactory] Found " << slv2_plugins_size(plugins) << " LV2 plugins:" << endl;
for (unsigned i=0; i < slv2_plugins_size(plugins); ++i) {
SLV2Plugin lv2_plug = slv2_plugins_get_at(plugins, i);
const string uri(slv2_value_as_uri(slv2_plugin_get_uri(lv2_plug)));
#ifndef NDEBUG
assert(_plugins.find(uri) == _plugins.end());
#endif
LV2Plugin* const plugin = new LV2Plugin(_lv2_info, uri);
plugin->slv2_plugin(lv2_plug);
plugin->library_path(slv2_uri_to_path(slv2_value_as_uri(
slv2_plugin_get_library_uri(lv2_plug))));
_plugins.insert(make_pair(uri, plugin));
}
slv2_plugins_free(_world->slv2_world, plugins);
}
#endif // HAVE_SLV2
#ifdef HAVE_LADSPA
/** Loads information about all LADSPA plugins into internal plugin database.
*/
void
NodeFactory::load_ladspa_plugins()
{
char* env_ladspa_path = getenv("LADSPA_PATH");
string ladspa_path;
if (!env_ladspa_path) {
cerr << "[NodeFactory] LADSPA_PATH is empty. Assuming /usr/lib/ladspa:/usr/local/lib/ladspa:~/.ladspa" << endl;
ladspa_path = string("/usr/lib/ladspa:/usr/local/lib/ladspa:").append(
getenv("HOME")).append("/.ladspa");
} else {
ladspa_path = env_ladspa_path;
}
// Yep, this should use an sstream alright..
while (ladspa_path != "") {
const string dir = ladspa_path.substr(0, ladspa_path.find(':'));
if (ladspa_path.find(':') != string::npos)
ladspa_path = ladspa_path.substr(ladspa_path.find(':')+1);
else
ladspa_path = "";
DIR* pdir = opendir(dir.c_str());
if (pdir == NULL) {
//cerr << "[NodeFactory] Unreadable directory in LADSPA_PATH: " << dir.c_str() << endl;
continue;
}
struct dirent* pfile;
while ((pfile = readdir(pdir))) {
LADSPA_Descriptor_Function df = NULL;
LADSPA_Descriptor* descriptor = NULL;
if (!strcmp(pfile->d_name, ".") || !strcmp(pfile->d_name, ".."))
continue;
const string lib_path = dir +"/"+ pfile->d_name;
// Ignore stupid libtool files. Kludge alert.
if (lib_path.substr(lib_path.length()-3) == ".la") {
//cerr << "WARNING: Skipping stupid libtool file " << pfile->d_name << endl;
continue;
}
Glib::Module* plugin_library = new Glib::Module(lib_path, Glib::MODULE_BIND_LOCAL);
if (!plugin_library || !(*plugin_library)) {
cerr << "WARNING: Failed to load LADSPA library " << lib_path << endl;
continue;
}
bool found = plugin_library->get_symbol("ladspa_descriptor", (void*&)df);
if (!found || !df) {
cerr << "WARNING: Non-LADSPA library found in LADSPA path: " <<
lib_path << endl;
// Not a LADSPA plugin library
delete plugin_library;
continue;
}
for (unsigned long i=0; (descriptor = (LADSPA_Descriptor*)df(i)) != NULL; ++i) {
char id_str[11];
snprintf(id_str, 11, "%lu", descriptor->UniqueID);
const string uri = string("ladspa:").append(id_str);
const Plugins::const_iterator i = _plugins.find(uri);
if (i == _plugins.end()) {
LADSPAPlugin* plugin = new LADSPAPlugin(lib_path, uri,
descriptor->UniqueID,
descriptor->Label,
descriptor->Name);
_plugins.insert(make_pair(uri, plugin));
} else {
cerr << "Warning: Duplicate LADSPA plugin " << uri << " found." << endl;
cerr << "\tUsing " << i->second->library_path() << " over " << lib_path << endl;
}
}
delete plugin_library;
}
closedir(pdir);
}
}
#endif // HAVE_LADSPA
} // namespace Ingen
<commit_msg>Fix building w/o LADSPA.<commit_after>/* This file is part of Ingen.
* Copyright (C) 2007 Dave Robillard <http://drobilla.net>
*
* Ingen is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* Ingen 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 General Public License for details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include CONFIG_H_PATH
#include <cstdlib>
#include <pthread.h>
#include <dirent.h>
#include <float.h>
#include <cmath>
#include "module/World.hpp"
#include "NodeFactory.hpp"
#include "ThreadManager.hpp"
#include "MidiNoteNode.hpp"
#include "MidiTriggerNode.hpp"
#include "MidiControlNode.hpp"
#include "TransportNode.hpp"
#include "PatchImpl.hpp"
#include "InternalPlugin.hpp"
#ifdef HAVE_LADSPA
#include "LADSPANode.hpp"
#include "LADSPAPlugin.hpp"
#endif
#ifdef HAVE_SLV2
#include <slv2/slv2.h>
#include "LV2Plugin.hpp"
#include "LV2Node.hpp"
#endif
using namespace std;
namespace Ingen {
NodeFactory::NodeFactory(Ingen::Shared::World* world)
: _world(world)
, _has_loaded(false)
#ifdef HAVE_SLV2
, _lv2_info(new LV2Info(world->slv2_world))
#endif
{
}
NodeFactory::~NodeFactory()
{
for (Plugins::iterator i = _plugins.begin(); i != _plugins.end(); ++i)
if (i->second->type() != Plugin::Internal)
delete i->second;
_plugins.clear();
}
PluginImpl*
NodeFactory::plugin(const string& uri)
{
const Plugins::const_iterator i = _plugins.find(uri);
return ((i != _plugins.end()) ? i->second : NULL);
}
/** DEPRECATED: Find a plugin by type, lib, label.
*
* Slow. Evil. Do not use.
*/
PluginImpl*
NodeFactory::plugin(const string& type, const string& lib, const string& label)
{
if (type != "LADSPA" || lib == "" || label == "")
return NULL;
#ifdef HAVE_LADSPA
for (Plugins::const_iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
LADSPAPlugin* lp = dynamic_cast<LADSPAPlugin*>(i->second);
if (lp && lp->type_string() == type
&& lp->library_name() == lib
&& lp->label() == label)
return lp;
}
#endif
cerr << "ERROR: Failed to find " << type << " plugin " << lib << " / " << label << endl;
return NULL;
}
void
NodeFactory::load_plugins()
{
assert(ThreadManager::current_thread_id() == THREAD_PRE_PROCESS);
// Only load if we havn't already, so every client connecting doesn't cause
// this (expensive!) stuff to happen. Not the best solution - would be nice
// if clients could refresh plugins list for whatever reason :/
if (!_has_loaded) {
_plugins.clear(); // FIXME: assert empty?
load_internal_plugins();
#ifdef HAVE_SLV2
load_lv2_plugins();
#endif
#ifdef HAVE_LADSPA
load_ladspa_plugins();
#endif
_has_loaded = true;
}
#if 0
for (Plugins::const_iterator i = _plugins.begin(); i != _plugins.end(); ++i) {
assert(Path::is_valid_name(i->second->symbol()));
cerr << "PLUGIN: " << i->second->uri() << " - " << i->second->symbol()
<< " (" << i->second->name() << ")" << endl;
PatchImpl* parent = new PatchImpl(*_world->local_engine, "dummy", 1, NULL, 1, 1, 1);
NodeImpl* node = i->second->instantiate("foo", 0, parent, 48000, 512);
if (node)
for (uint32_t i=0; i < node->num_ports(); ++i) {
cerr << "\t" << node->port(i)->name() << endl;
}
cerr << endl;
}
#endif
//cerr << "[NodeFactory] # Plugins: " << _plugins.size() << endl;
}
void
NodeFactory::load_internal_plugins()
{
// This is a touch gross...
PatchImpl* parent = new PatchImpl(*_world->local_engine, "dummy", 1, NULL, 1, 1, 1);
NodeImpl* n = NULL;
n = new MidiNoteNode("foo", 1, parent, 1, 1);
_plugins.insert(make_pair(n->plugin_impl()->uri(), n->plugin_impl()));
delete n;
n = new MidiTriggerNode("foo", 1, parent, 1, 1);
_plugins.insert(make_pair(n->plugin_impl()->uri(), n->plugin_impl()));
delete n;
n = new MidiControlNode("foo", 1, parent, 1, 1);
_plugins.insert(make_pair(n->plugin_impl()->uri(), n->plugin_impl()));
delete n;
n = new TransportNode("foo", 1, parent, 1, 1);
_plugins.insert(make_pair(n->plugin_impl()->uri(), n->plugin_impl()));
delete n;
delete parent;
}
#ifdef HAVE_SLV2
/** Loads information about all LV2 plugins into internal plugin database.
*/
void
NodeFactory::load_lv2_plugins()
{
SLV2Plugins plugins = slv2_world_get_all_plugins(_world->slv2_world);
//cerr << "[NodeFactory] Found " << slv2_plugins_size(plugins) << " LV2 plugins:" << endl;
for (unsigned i=0; i < slv2_plugins_size(plugins); ++i) {
SLV2Plugin lv2_plug = slv2_plugins_get_at(plugins, i);
const string uri(slv2_value_as_uri(slv2_plugin_get_uri(lv2_plug)));
#ifndef NDEBUG
assert(_plugins.find(uri) == _plugins.end());
#endif
LV2Plugin* const plugin = new LV2Plugin(_lv2_info, uri);
plugin->slv2_plugin(lv2_plug);
plugin->library_path(slv2_uri_to_path(slv2_value_as_uri(
slv2_plugin_get_library_uri(lv2_plug))));
_plugins.insert(make_pair(uri, plugin));
}
slv2_plugins_free(_world->slv2_world, plugins);
}
#endif // HAVE_SLV2
#ifdef HAVE_LADSPA
/** Loads information about all LADSPA plugins into internal plugin database.
*/
void
NodeFactory::load_ladspa_plugins()
{
char* env_ladspa_path = getenv("LADSPA_PATH");
string ladspa_path;
if (!env_ladspa_path) {
cerr << "[NodeFactory] LADSPA_PATH is empty. Assuming /usr/lib/ladspa:/usr/local/lib/ladspa:~/.ladspa" << endl;
ladspa_path = string("/usr/lib/ladspa:/usr/local/lib/ladspa:").append(
getenv("HOME")).append("/.ladspa");
} else {
ladspa_path = env_ladspa_path;
}
// Yep, this should use an sstream alright..
while (ladspa_path != "") {
const string dir = ladspa_path.substr(0, ladspa_path.find(':'));
if (ladspa_path.find(':') != string::npos)
ladspa_path = ladspa_path.substr(ladspa_path.find(':')+1);
else
ladspa_path = "";
DIR* pdir = opendir(dir.c_str());
if (pdir == NULL) {
//cerr << "[NodeFactory] Unreadable directory in LADSPA_PATH: " << dir.c_str() << endl;
continue;
}
struct dirent* pfile;
while ((pfile = readdir(pdir))) {
LADSPA_Descriptor_Function df = NULL;
LADSPA_Descriptor* descriptor = NULL;
if (!strcmp(pfile->d_name, ".") || !strcmp(pfile->d_name, ".."))
continue;
const string lib_path = dir +"/"+ pfile->d_name;
// Ignore stupid libtool files. Kludge alert.
if (lib_path.substr(lib_path.length()-3) == ".la") {
//cerr << "WARNING: Skipping stupid libtool file " << pfile->d_name << endl;
continue;
}
Glib::Module* plugin_library = new Glib::Module(lib_path, Glib::MODULE_BIND_LOCAL);
if (!plugin_library || !(*plugin_library)) {
cerr << "WARNING: Failed to load LADSPA library " << lib_path << endl;
continue;
}
bool found = plugin_library->get_symbol("ladspa_descriptor", (void*&)df);
if (!found || !df) {
cerr << "WARNING: Non-LADSPA library found in LADSPA path: " <<
lib_path << endl;
// Not a LADSPA plugin library
delete plugin_library;
continue;
}
for (unsigned long i=0; (descriptor = (LADSPA_Descriptor*)df(i)) != NULL; ++i) {
char id_str[11];
snprintf(id_str, 11, "%lu", descriptor->UniqueID);
const string uri = string("ladspa:").append(id_str);
const Plugins::const_iterator i = _plugins.find(uri);
if (i == _plugins.end()) {
LADSPAPlugin* plugin = new LADSPAPlugin(lib_path, uri,
descriptor->UniqueID,
descriptor->Label,
descriptor->Name);
_plugins.insert(make_pair(uri, plugin));
} else {
cerr << "Warning: Duplicate LADSPA plugin " << uri << " found." << endl;
cerr << "\tUsing " << i->second->library_path() << " over " << lib_path << endl;
}
}
delete plugin_library;
}
closedir(pdir);
}
}
#endif // HAVE_LADSPA
} // namespace Ingen
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkFollower.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-1996 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include <stdlib.h>
#include <math.h>
#include "vtkMath.h"
#include "vtkFollower.h"
#include "vtkCamera.h"
// Description:
// Creates a follower with no camera set
vtkFollower::vtkFollower()
{
this->Camera = NULL;
this->Device = vtkActor::New();
}
vtkFollower::~vtkFollower()
{
this->Device->Delete();
}
// Description:
// Copy the follower's composite 4x4 matrix into the matrix provided.
void vtkFollower::GetMatrix(vtkMatrix4x4& result)
{
float *pos;
vtkMatrix4x4 matrix;
this->GetOrientation();
this->Transform.Push();
this->Transform.Identity();
this->Transform.PreMultiply();
// apply user defined matrix last if there is one
if (this->UserMatrix)
{
this->Transform.Concatenate(*this->UserMatrix);
}
// first translate
this->Transform.Translate(this->Position[0],
this->Position[1],
this->Position[2]);
// shift to origin
this->Transform.Translate(this->Origin[0],
this->Origin[1],
this->Origin[2]);
// add the rotation to follow the camera
if (this->Camera)
{
float distance, distance_old;
float *vup;
float twist = 0;
float v1[3], v2[3], y_axis[3];
double theta, dot, mag;
double cosang;
float vn[3];
// calc the direction
pos = this->Camera->GetPosition();
vup = this->Camera->GetViewUp();
// first rotate y
distance = sqrt((this->Position[0]-pos[0])*(this->Position[0]-pos[0]) +
(this->Position[2]-pos[2])*(this->Position[2]-pos[2]));
vn[0] = (pos[0] - this->Position[0])/distance;
vn[1] = (pos[1] - this->Position[1])/distance;
vn[2] = (pos[2] - this->Position[2])/distance;
// rotate y
if (distance > 0.0)
{
matrix[0][0] = (this->Position[2]-pos[2])/distance;
matrix[0][2] = -1.0*(pos[0] - this->Position[0])/distance;
}
else
{
if (this->Position[1] < pos[1])
{
matrix[0][0] = -1.0;
}
else
{
matrix[0][0] = 1.0;
}
matrix[0][2] = 0.0;
}
matrix[0][1] = matrix[0][3] = 0.0;
matrix[1][1] = 1.0;
matrix[1][0] = matrix[1][2] = matrix[1][3] = 0.0;
matrix[2][0] = -1.0*matrix[0][2];
matrix[2][2] = matrix[0][0];
matrix[2][3] = 0.0;
matrix[2][1] = 0.0;
matrix[3][3] = 1.0;
matrix[3][0] = matrix[3][1] = matrix[3][2] = 0.0;
this->Transform.Concatenate(matrix);
// now rotate x
distance_old = distance;
distance = sqrt((this->Position[0]-pos[0])*(this->Position[0]-pos[0]) +
(this->Position[1]-pos[1])*(this->Position[1]-pos[1]) +
(this->Position[2]-pos[2])*(this->Position[2]-pos[2]));
matrix[0][0] = 1.0;
matrix[0][1] = matrix[0][2] = matrix[0][3] = 0.0;
matrix[1][1] = distance_old/distance;
matrix[1][2] = (this->Position[1] - pos[1])/distance;
matrix[1][0] = matrix[1][3] = 0.0;
matrix[2][1] = -1.0*matrix[1][2];
matrix[2][2] = matrix[1][1];
matrix[2][3] = 0.0;
matrix[2][0] = 0.0;
matrix[3][3] = 1.0;
matrix[3][0] = matrix[3][1] = matrix[3][2] = 0.0;
this->Transform.Concatenate(matrix);
// calc the twist
// compute: vn X ( vup X vn)
// and: vn X ( y-axis X vn)
// then find the angle between the two projected vectors
//
y_axis[0] = y_axis[2] = 0.0; y_axis[1] = 1.0;
// bump the view normal if it is parallel to the y-axis
//
if ((vn[0] == 0.0) && (vn[2] == 0.0))
vn[2] = 0.01*vn[1];
// first project the view_up onto the view_plane
//
vtkMath::Cross(vup, vn, v1);
vtkMath::Cross(vn, v1, v1);
// then project the y-axis onto the view plane
//
vtkMath::Cross(y_axis, vn, v2);
vtkMath::Cross(vn, v2, v2);
// then find the angle between the two projected vectors
//
dot = v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2];
mag = sqrt((double)(v1[0]*v1[0] + v1[1]*v1[1] + v1[2]*v1[2]));
mag *= sqrt((double)(v2[0]*v2[0] + v2[1]*v2[1] + v2[2]*v2[2]));
// make sure we dont divide by 0
if (mag != 0.0)
{
cosang = dot / mag;
if (cosang < -1.0) cosang = -1.0;
if (cosang > 1.0) cosang = 1.0;
theta = acos(cosang);
}
else
theta = 0.0;
// now see if the angle is positive or negative
//
vtkMath::Cross(v1, v2, v1);
dot = v1[0]*vn[0] + v1[1]*vn[1] + v1[2]*vn[2];
twist = (theta);
if (dot < 0.0)
twist = -twist;
// now rotate z (twist)
matrix[0][0] = cos(-twist);
matrix[0][1] = sin(-twist);
matrix[0][2] = matrix[0][3] = 0.0;
matrix[1][0] = -1.0*matrix[0][1];
matrix[1][1] = matrix[0][0];
matrix[1][2] = matrix[1][3] = 0.0;
matrix[2][1] = 0.0;
matrix[2][2] = 1.0;
matrix[2][3] = 0.0;
matrix[2][0] = 0.0;
matrix[3][3] = 1.0;
matrix[3][0] = matrix[3][1] = matrix[3][2] = 0.0;
this->Transform.Concatenate(matrix);
// rotate y by 180 to get the positive zaxis instead of negative
this->Transform.RotateY(180);
}
// rotate
this->Transform.RotateZ(this->Orientation[2]);
this->Transform.RotateX(this->Orientation[0]);
this->Transform.RotateY(this->Orientation[1]);
// scale
this->Transform.Scale(this->Scale[0],
this->Scale[1],
this->Scale[2]);
// shift back from origin
this->Transform.Translate(-this->Origin[0],
-this->Origin[1],
-this->Origin[2]);
result = this->Transform.GetMatrix();
this->Transform.Pop();
}
void vtkFollower::PrintSelf(ostream& os, vtkIndent indent)
{
vtkActor::PrintSelf(os,indent);
if ( this->Camera )
{
os << indent << "Camera:\n";
this->Camera->PrintSelf(os,indent.GetNextIndent());
}
else
{
os << indent << "Camera: (none)\n";
}
}
// Description:
// This causes the actor to be rendered. It, in turn, will render the actor's
// property and then mapper.
void vtkFollower::Render(vtkRenderer *ren)
{
vtkMatrix4x4 *matrix = vtkMatrix4x4::New();
/* render the property */
if (!this->Property)
{
// force creation of a property
this->GetProperty();
}
this->Property->Render(this, ren);
/* render the texture */
if (this->Texture) this->Texture->Render(ren);
// make sure the device has the same matrix
this->GetMatrix(*matrix);
this->Device->SetUserMatrix(matrix);
this->Device->Render(ren,this->Mapper);
delete matrix;
}
<commit_msg>ERR: Follower not handling property properly.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkFollower.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-1996 Ken Martin, Will Schroeder, Bill Lorensen.
This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.
The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.
IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
=========================================================================*/
#include <stdlib.h>
#include <math.h>
#include "vtkMath.h"
#include "vtkFollower.h"
#include "vtkCamera.h"
// Description:
// Creates a follower with no camera set
vtkFollower::vtkFollower()
{
this->Camera = NULL;
this->Device = vtkActor::New();
}
vtkFollower::~vtkFollower()
{
this->Device->Delete();
}
// Description:
// Copy the follower's composite 4x4 matrix into the matrix provided.
void vtkFollower::GetMatrix(vtkMatrix4x4& result)
{
float *pos;
vtkMatrix4x4 matrix;
this->GetOrientation();
this->Transform.Push();
this->Transform.Identity();
this->Transform.PreMultiply();
// apply user defined matrix last if there is one
if (this->UserMatrix)
{
this->Transform.Concatenate(*this->UserMatrix);
}
// first translate
this->Transform.Translate(this->Position[0],
this->Position[1],
this->Position[2]);
// shift to origin
this->Transform.Translate(this->Origin[0],
this->Origin[1],
this->Origin[2]);
// add the rotation to follow the camera
if (this->Camera)
{
float distance, distance_old;
float *vup;
float twist = 0;
float v1[3], v2[3], y_axis[3];
double theta, dot, mag;
double cosang;
float vn[3];
// calc the direction
pos = this->Camera->GetPosition();
vup = this->Camera->GetViewUp();
// first rotate y
distance = sqrt((this->Position[0]-pos[0])*(this->Position[0]-pos[0]) +
(this->Position[2]-pos[2])*(this->Position[2]-pos[2]));
vn[0] = (pos[0] - this->Position[0])/distance;
vn[1] = (pos[1] - this->Position[1])/distance;
vn[2] = (pos[2] - this->Position[2])/distance;
// rotate y
if (distance > 0.0)
{
matrix[0][0] = (this->Position[2]-pos[2])/distance;
matrix[0][2] = -1.0*(pos[0] - this->Position[0])/distance;
}
else
{
if (this->Position[1] < pos[1])
{
matrix[0][0] = -1.0;
}
else
{
matrix[0][0] = 1.0;
}
matrix[0][2] = 0.0;
}
matrix[0][1] = matrix[0][3] = 0.0;
matrix[1][1] = 1.0;
matrix[1][0] = matrix[1][2] = matrix[1][3] = 0.0;
matrix[2][0] = -1.0*matrix[0][2];
matrix[2][2] = matrix[0][0];
matrix[2][3] = 0.0;
matrix[2][1] = 0.0;
matrix[3][3] = 1.0;
matrix[3][0] = matrix[3][1] = matrix[3][2] = 0.0;
this->Transform.Concatenate(matrix);
// now rotate x
distance_old = distance;
distance = sqrt((this->Position[0]-pos[0])*(this->Position[0]-pos[0]) +
(this->Position[1]-pos[1])*(this->Position[1]-pos[1]) +
(this->Position[2]-pos[2])*(this->Position[2]-pos[2]));
matrix[0][0] = 1.0;
matrix[0][1] = matrix[0][2] = matrix[0][3] = 0.0;
matrix[1][1] = distance_old/distance;
matrix[1][2] = (this->Position[1] - pos[1])/distance;
matrix[1][0] = matrix[1][3] = 0.0;
matrix[2][1] = -1.0*matrix[1][2];
matrix[2][2] = matrix[1][1];
matrix[2][3] = 0.0;
matrix[2][0] = 0.0;
matrix[3][3] = 1.0;
matrix[3][0] = matrix[3][1] = matrix[3][2] = 0.0;
this->Transform.Concatenate(matrix);
// calc the twist
// compute: vn X ( vup X vn)
// and: vn X ( y-axis X vn)
// then find the angle between the two projected vectors
//
y_axis[0] = y_axis[2] = 0.0; y_axis[1] = 1.0;
// bump the view normal if it is parallel to the y-axis
//
if ((vn[0] == 0.0) && (vn[2] == 0.0))
vn[2] = 0.01*vn[1];
// first project the view_up onto the view_plane
//
vtkMath::Cross(vup, vn, v1);
vtkMath::Cross(vn, v1, v1);
// then project the y-axis onto the view plane
//
vtkMath::Cross(y_axis, vn, v2);
vtkMath::Cross(vn, v2, v2);
// then find the angle between the two projected vectors
//
dot = v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2];
mag = sqrt((double)(v1[0]*v1[0] + v1[1]*v1[1] + v1[2]*v1[2]));
mag *= sqrt((double)(v2[0]*v2[0] + v2[1]*v2[1] + v2[2]*v2[2]));
// make sure we dont divide by 0
if (mag != 0.0)
{
cosang = dot / mag;
if (cosang < -1.0) cosang = -1.0;
if (cosang > 1.0) cosang = 1.0;
theta = acos(cosang);
}
else
theta = 0.0;
// now see if the angle is positive or negative
//
vtkMath::Cross(v1, v2, v1);
dot = v1[0]*vn[0] + v1[1]*vn[1] + v1[2]*vn[2];
twist = (theta);
if (dot < 0.0)
twist = -twist;
// now rotate z (twist)
matrix[0][0] = cos(-twist);
matrix[0][1] = sin(-twist);
matrix[0][2] = matrix[0][3] = 0.0;
matrix[1][0] = -1.0*matrix[0][1];
matrix[1][1] = matrix[0][0];
matrix[1][2] = matrix[1][3] = 0.0;
matrix[2][1] = 0.0;
matrix[2][2] = 1.0;
matrix[2][3] = 0.0;
matrix[2][0] = 0.0;
matrix[3][3] = 1.0;
matrix[3][0] = matrix[3][1] = matrix[3][2] = 0.0;
this->Transform.Concatenate(matrix);
// rotate y by 180 to get the positive zaxis instead of negative
this->Transform.RotateY(180);
}
// rotate
this->Transform.RotateZ(this->Orientation[2]);
this->Transform.RotateX(this->Orientation[0]);
this->Transform.RotateY(this->Orientation[1]);
// scale
this->Transform.Scale(this->Scale[0],
this->Scale[1],
this->Scale[2]);
// shift back from origin
this->Transform.Translate(-this->Origin[0],
-this->Origin[1],
-this->Origin[2]);
result = this->Transform.GetMatrix();
this->Transform.Pop();
}
void vtkFollower::PrintSelf(ostream& os, vtkIndent indent)
{
vtkActor::PrintSelf(os,indent);
if ( this->Camera )
{
os << indent << "Camera:\n";
this->Camera->PrintSelf(os,indent.GetNextIndent());
}
else
{
os << indent << "Camera: (none)\n";
}
}
// Description:
// This causes the actor to be rendered. It, in turn, will render the actor's
// property and then mapper.
void vtkFollower::Render(vtkRenderer *ren)
{
vtkMatrix4x4 *matrix = vtkMatrix4x4::New();
/* render the property */
if (!this->Property)
{
// force creation of a property
this->GetProperty();
}
this->Device->SetProperty (this->Property);
this->Property->Render(this, ren);
/* render the texture */
if (this->Texture) this->Texture->Render(ren);
// make sure the device has the same matrix
this->GetMatrix(*matrix);
this->Device->SetUserMatrix(matrix);
this->Device->Render(ren,this->Mapper);
delete matrix;
}
<|endoftext|> |
<commit_before>#include "HeaderModifier.hpp"
#include "../Core/Core.hpp"
namespace
{
NETStringList& _getProperBankBy(NECodeType::CodeType codetype)
{
NEScriptEditor::Banks& banks = Editor::getInstance().getScriptEditor().getBanks();
switch(codetype)
{
case NECodeType::NAME: return banks.getNameBank();
case NECodeType::SCRIPT: return banks.getScriptBank();
case NECodeType::GROUP: return banks.getGroupBank();
case NECodeType::PRIORITY: return banks.getPriorityBank();
}
NETStringList* nullpointer = 0x00;
return *nullpointer;
}
const NETStringList& _getProperBankBy(int index)
{
const NEScriptEditor::Banks& banks = Editor::getInstance().getScriptEditor().getBanks();
switch(index)
{
case 0: return banks.getNameBank();
case 1: return banks.getScriptBank();
case 2: return banks.getGroupBank();
case 3: return banks.getPriorityBank();
}
NETStringList* nullpointer = 0x00;
return *nullpointer;
}
}
void HeaderModifier::CodePopUpMenu::onItemChoosed(type_index index, const NEString& chosen_content)
{
if( _codetype < NECodeType::NAME ||
_codetype > NECodeType::PRIORITY)
{
::Core::pushMessage("ERROR: ߸ CodeTypeԴϴ.");
delete_me = true;
return;
}
NEScriptEditor& ed = Editor::getInstance().getScriptEditor();
switch(index)
{
case 0:
// ο ڵ :
if(_codetype == NECodeType::SCRIPT)
_onModifyCodeName();
else
_onAddNewCode();
break;
case 1: // ̸ ϱ
_onModifyCodeName();
break;
case 2: // ڵ ϱ
_onRemoveCode();
break;
default:
::Core::pushMessage("ERROR: ϴ.");
return;
}
}
void HeaderModifier::CodePopUpMenu::_onModifyCodeName()
{
NETStringList& bank = _getProperBankBy(_codetype);
call(StringInputWindow(bank[_code]));
delete_me = true;
}
void HeaderModifier::CodePopUpMenu::_onAddNewCode()
{
if( ! _code)
{
::Core::pushMessage("ERROR: 0 ڵ ⺻ ڵԴϴ. ߰ / Ұմϴ.");
return;
}
NEScriptEditor& ed = Editor::getInstance().getScriptEditor();
type_result result = 0;
switch(_codetype)
{
case NECodeType::NAME: result = ed.insertNameCode(_code); break;
case NECodeType::GROUP: result = ed.insertGroupCode(_code); break;
case NECodeType::PRIORITY: result = ed.insertPriorityCode(_code); break;
}
if( ! NEResult::hasError(result))
_onModifyCodeName();
}
void HeaderModifier::CodePopUpMenu::_onRemoveCode()
{
if( ! _code)
{
::Core::pushMessage("ERROR: 0 ڵ ⺻ ڵԴϴ. ߰ / Ұմϴ.");
return;
}
NEScriptEditor& ed = Editor::getInstance().getScriptEditor();
switch(_codetype)
{
case NECodeType::NAME: ed.removeNameCode(_code); break;
case NECodeType::GROUP: ed.removeGroupCode(_code); break;
case NECodeType::PRIORITY: ed.removePriorityCode(_code); break;
}
delete_me = true;
}
void HeaderModifier::onItemChoosed(type_index index, const NEString& chosen_content)
{
NEScriptManager::ScriptHeader& h = Editor::getInstance().getScriptEditor().getScriptHeader();
NECodeType::CodeType ct = NECodeType::UNDEFINED;
switch(index)
{
case 0: // ̸ ϱ
call( StringInputWindow(h.getName()));
break;
case 1:
call( StringInputWindow(h.getDeveloper()));
break;
case 2:
::Core::pushMessage("Revision ڵ ˴ϴ.");
break;
case 3:
call( StringInputWindow(h.getReleaseDate()));
break;
case 4:
call( StringInputWindow(h.getComment()));
break;
case 5:
call( StringInputWindow(h.getContact()));
break;
case 6: // Bank ý
ct = NECodeType::NAME;
case 7:
if(ct == NECodeType::UNDEFINED)
ct = NECodeType::SCRIPT;
case 8:
if(ct == NECodeType::UNDEFINED)
ct = NECodeType::GROUP;
case 9:
if(ct == NECodeType::UNDEFINED)
ct = NECodeType::PRIORITY;
{
type_code code = codes_display_indexes[index-6];
if(code != -1)
call(CodePopUpMenu(ct, code));
}
break;
}
}
void HeaderModifier::_pushCodeLists()
{
const NEScriptEditor::Banks& banks = Editor::getInstance().getScriptEditor().getBanks();
for(int code_type_n=0; code_type_n < codes_display_indexes.getLength(); code_type_n++)
{
NEString to_show = (list.choosed == code_type_n + 6) ? "<-" : " ";
switch(code_type_n)
{
case 0: to_show += "[NAME] "; break;
case 1: to_show += "[SCRI] "; break;
case 2: to_show += "[GROU] "; break;
case 3: to_show += "[PRIO] "; break;
}
int index = codes_display_indexes[code_type_n];
switch(index)
{
case -2:
to_show += "NEW";
break;
case -1:
to_show += _generateCodeListNames(code_type_n);
break;
default:
{
to_show += NEString(index) + "th: ";
if(index >= 0)
to_show += _getProperBankBy(code_type_n)[index];
}
}
if(list.choosed == code_type_n + 6)
to_show += "->";
list.items.push(to_show);
}
}
NE::NEString HeaderModifier::_generateCodeListNames(int index)
{
NEString to_show = "CODES: ";
const NETStringList& bank = _getProperBankBy(index);
int n=0;
for(const NETStringList::Iterator* i = bank.getIterator(0); i ;i = i->getNext())
{
to_show += i->getValue().extract(0, 4) + "[" + n++ + "] "; // 5ھ
if(to_show.getLength() > 23) // ִ 20ڱ
break;
}
return to_show;
}
void HeaderModifier::onKeyPressed(char inputed)
{
int codetype = list.choosed - 6;
if(codetype >= 0 && codetype <= 3)
{
const NETStringList& bank = _getProperBankBy(codetype);
switch(inputed)
{
case LEFT:
if(codes_display_indexes[codetype] > -2)
codes_display_indexes[codetype]--;
break;
case RIGHT:
if(codes_display_indexes[codetype] < bank.getLengthLastIndex())
codes_display_indexes[codetype]++;
break;
}
}
ListWindow::onKeyPressed(inputed);
onUpdateData();
}<commit_msg>FIX: HeaderModifier의 Code 전체보기가 짤리는 UI 개선<commit_after>#include "HeaderModifier.hpp"
#include "../Core/Core.hpp"
namespace
{
NETStringList& _getProperBankBy(NECodeType::CodeType codetype)
{
NEScriptEditor::Banks& banks = Editor::getInstance().getScriptEditor().getBanks();
switch(codetype)
{
case NECodeType::NAME: return banks.getNameBank();
case NECodeType::SCRIPT: return banks.getScriptBank();
case NECodeType::GROUP: return banks.getGroupBank();
case NECodeType::PRIORITY: return banks.getPriorityBank();
}
NETStringList* nullpointer = 0x00;
return *nullpointer;
}
const NETStringList& _getProperBankBy(int index)
{
const NEScriptEditor::Banks& banks = Editor::getInstance().getScriptEditor().getBanks();
switch(index)
{
case 0: return banks.getNameBank();
case 1: return banks.getScriptBank();
case 2: return banks.getGroupBank();
case 3: return banks.getPriorityBank();
}
NETStringList* nullpointer = 0x00;
return *nullpointer;
}
}
void HeaderModifier::CodePopUpMenu::onItemChoosed(type_index index, const NEString& chosen_content)
{
if( _codetype < NECodeType::NAME ||
_codetype > NECodeType::PRIORITY)
{
::Core::pushMessage("ERROR: ߸ CodeTypeԴϴ.");
delete_me = true;
return;
}
NEScriptEditor& ed = Editor::getInstance().getScriptEditor();
switch(index)
{
case 0:
// ο ڵ :
if(_codetype == NECodeType::SCRIPT)
_onModifyCodeName();
else
_onAddNewCode();
break;
case 1: // ̸ ϱ
_onModifyCodeName();
break;
case 2: // ڵ ϱ
_onRemoveCode();
break;
default:
::Core::pushMessage("ERROR: ϴ.");
return;
}
}
void HeaderModifier::CodePopUpMenu::_onModifyCodeName()
{
NETStringList& bank = _getProperBankBy(_codetype);
call(StringInputWindow(bank[_code]));
delete_me = true;
}
void HeaderModifier::CodePopUpMenu::_onAddNewCode()
{
if( ! _code)
{
::Core::pushMessage("ERROR: 0 ڵ ⺻ ڵԴϴ. ߰ / Ұմϴ.");
return;
}
NEScriptEditor& ed = Editor::getInstance().getScriptEditor();
type_result result = 0;
switch(_codetype)
{
case NECodeType::NAME: result = ed.insertNameCode(_code); break;
case NECodeType::GROUP: result = ed.insertGroupCode(_code); break;
case NECodeType::PRIORITY: result = ed.insertPriorityCode(_code); break;
}
if( ! NEResult::hasError(result))
_onModifyCodeName();
}
void HeaderModifier::CodePopUpMenu::_onRemoveCode()
{
if( ! _code)
{
::Core::pushMessage("ERROR: 0 ڵ ⺻ ڵԴϴ. ߰ / Ұմϴ.");
return;
}
NEScriptEditor& ed = Editor::getInstance().getScriptEditor();
switch(_codetype)
{
case NECodeType::NAME: ed.removeNameCode(_code); break;
case NECodeType::GROUP: ed.removeGroupCode(_code); break;
case NECodeType::PRIORITY: ed.removePriorityCode(_code); break;
}
delete_me = true;
}
void HeaderModifier::onItemChoosed(type_index index, const NEString& chosen_content)
{
NEScriptManager::ScriptHeader& h = Editor::getInstance().getScriptEditor().getScriptHeader();
NECodeType::CodeType ct = NECodeType::UNDEFINED;
switch(index)
{
case 0: // ̸ ϱ
call( StringInputWindow(h.getName()));
break;
case 1:
call( StringInputWindow(h.getDeveloper()));
break;
case 2:
::Core::pushMessage("Revision ڵ ˴ϴ.");
break;
case 3:
call( StringInputWindow(h.getReleaseDate()));
break;
case 4:
call( StringInputWindow(h.getComment()));
break;
case 5:
call( StringInputWindow(h.getContact()));
break;
case 6: // Bank ý
ct = NECodeType::NAME;
case 7:
if(ct == NECodeType::UNDEFINED)
ct = NECodeType::SCRIPT;
case 8:
if(ct == NECodeType::UNDEFINED)
ct = NECodeType::GROUP;
case 9:
if(ct == NECodeType::UNDEFINED)
ct = NECodeType::PRIORITY;
{
type_code code = codes_display_indexes[index-6];
if(code != -1)
call(CodePopUpMenu(ct, code));
}
break;
}
}
void HeaderModifier::_pushCodeLists()
{
const NEScriptEditor::Banks& banks = Editor::getInstance().getScriptEditor().getBanks();
for(int code_type_n=0; code_type_n < codes_display_indexes.getLength(); code_type_n++)
{
NEString to_show = (list.choosed == code_type_n + 6) ? "<-" : " ";
switch(code_type_n)
{
case 0: to_show += "[NAME] "; break;
case 1: to_show += "[SCRI] "; break;
case 2: to_show += "[GROU] "; break;
case 3: to_show += "[PRIO] "; break;
}
int index = codes_display_indexes[code_type_n];
switch(index)
{
case -2:
to_show += "NEW";
break;
case -1:
to_show += _generateCodeListNames(code_type_n);
break;
default:
{
to_show += NEString(index) + "th: ";
if(index >= 0)
to_show += _getProperBankBy(code_type_n)[index];
}
}
if(list.choosed == code_type_n + 6)
to_show += "->";
list.items.push(to_show);
}
}
NE::NEString HeaderModifier::_generateCodeListNames(int index)
{
NEString to_show = "CODES: ";
const NETStringList& bank = _getProperBankBy(index);
int n=0;
for(const NETStringList::Iterator* i = bank.getIterator(0); i ;i = i->getNext())
{
to_show += i->getValue().extract(0, 4) + "[" + n++ + "] "; // 5ھ
if(to_show.getLength() > 40)
{
to_show += "...";
break;
}
}
return to_show;
}
void HeaderModifier::onKeyPressed(char inputed)
{
int codetype = list.choosed - 6;
if(codetype >= 0 && codetype <= 3)
{
const NETStringList& bank = _getProperBankBy(codetype);
switch(inputed)
{
case LEFT:
if(codes_display_indexes[codetype] > -2)
codes_display_indexes[codetype]--;
break;
case RIGHT:
if(codes_display_indexes[codetype] < bank.getLengthLastIndex())
codes_display_indexes[codetype]++;
break;
}
}
ListWindow::onKeyPressed(inputed);
onUpdateData();
}<|endoftext|> |
<commit_before>// Scintilla source code edit control
/** @file ContractionState.cxx
** Manages visibility of lines for folding and wrapping.
**/
// Copyright 1998-2007 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <string.h>
#include "Platform.h"
#include "SplitVector.h"
#include "Partitioning.h"
#include "RunStyles.h"
#include "ContractionState.h"
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
ContractionState::ContractionState() : visible(0), expanded(0), heights(0), displayLines(0), linesInDocument(1) {
//InsertLine(0);
}
ContractionState::~ContractionState() {
Clear();
}
void ContractionState::EnsureData() {
if (OneToOne()) {
visible = new RunStyles();
expanded = new RunStyles();
heights = new RunStyles();
displayLines = new Partitioning(4);
InsertLines(0, linesInDocument);
}
}
void ContractionState::Clear() {
delete visible;
visible = 0;
delete expanded;
expanded = 0;
delete heights;
heights = 0;
delete displayLines;
displayLines = 0;
linesInDocument = 1;
}
int ContractionState::LinesInDoc() const {
if (OneToOne()) {
return linesInDocument;
} else {
return displayLines->Partitions() - 1;
}
}
int ContractionState::LinesDisplayed() const {
if (OneToOne()) {
return linesInDocument;
} else {
return displayLines->PositionFromPartition(LinesInDoc());
}
}
int ContractionState::DisplayFromDoc(int lineDoc) const {
if (OneToOne()) {
return lineDoc;
} else {
if (lineDoc > displayLines->Partitions())
lineDoc = displayLines->Partitions();
return displayLines->PositionFromPartition(lineDoc);
}
}
int ContractionState::DocFromDisplay(int lineDisplay) const {
if (OneToOne()) {
return lineDisplay;
} else {
if (lineDisplay <= 0) {
return 0;
}
if (lineDisplay > LinesDisplayed()) {
return displayLines->PartitionFromPosition(LinesDisplayed());
}
int lineDoc = displayLines->PartitionFromPosition(lineDisplay);
PLATFORM_ASSERT(GetVisible(lineDoc));
return lineDoc;
}
}
void ContractionState::InsertLine(int lineDoc) {
if (OneToOne()) {
linesInDocument++;
} else {
visible->InsertSpace(lineDoc, 1);
visible->SetValueAt(lineDoc, 1);
expanded->InsertSpace(lineDoc, 1);
expanded->SetValueAt(lineDoc, 1);
heights->InsertSpace(lineDoc, 1);
heights->SetValueAt(lineDoc, 1);
int lineDisplay = DisplayFromDoc(lineDoc);
displayLines->InsertPartition(lineDoc, lineDisplay);
displayLines->InsertText(lineDoc, 1);
}
}
void ContractionState::InsertLines(int lineDoc, int lineCount) {
for (int l = 0; l < lineCount; l++) {
InsertLine(lineDoc + l);
}
Check();
}
void ContractionState::DeleteLine(int lineDoc) {
if (OneToOne()) {
linesInDocument--;
} else {
if (GetVisible(lineDoc)) {
displayLines->InsertText(lineDoc, -heights->ValueAt(lineDoc));
}
displayLines->RemovePartition(lineDoc);
visible->DeleteRange(lineDoc, 1);
expanded->DeleteRange(lineDoc, 1);
heights->DeleteRange(lineDoc, 1);
}
}
void ContractionState::DeleteLines(int lineDoc, int lineCount) {
for (int l = 0; l < lineCount; l++) {
DeleteLine(lineDoc);
}
Check();
}
bool ContractionState::GetVisible(int lineDoc) const {
if (OneToOne()) {
return true;
} else {
if (lineDoc >= visible->Length())
return true;
return visible->ValueAt(lineDoc) == 1;
}
}
bool ContractionState::SetVisible(int lineDocStart, int lineDocEnd, bool visible_) {
if (OneToOne() && visible_) {
return false;
} else {
EnsureData();
int delta = 0;
Check();
if ((lineDocStart <= lineDocEnd) && (lineDocStart >= 0) && (lineDocEnd < LinesInDoc())) {
for (int line = lineDocStart; line <= lineDocEnd; line++) {
if (GetVisible(line) != visible_) {
int difference = visible_ ? heights->ValueAt(line) : -heights->ValueAt(line);
visible->SetValueAt(line, visible_ ? 1 : 0);
displayLines->InsertText(line, difference);
delta += difference;
}
}
} else {
return false;
}
Check();
return delta != 0;
}
}
bool ContractionState::GetExpanded(int lineDoc) const {
if (OneToOne()) {
return true;
} else {
Check();
return expanded->ValueAt(lineDoc) == 1;
}
}
bool ContractionState::SetExpanded(int lineDoc, bool expanded_) {
if (OneToOne() && expanded_) {
return false;
} else {
EnsureData();
if (expanded_ != (expanded->ValueAt(lineDoc) == 1)) {
expanded->SetValueAt(lineDoc, expanded_ ? 1 : 0);
Check();
return true;
} else {
Check();
return false;
}
}
}
int ContractionState::GetHeight(int lineDoc) const {
if (OneToOne()) {
return 1;
} else {
return heights->ValueAt(lineDoc);
}
}
// Set the number of display lines needed for this line.
// Return true if this is a change.
bool ContractionState::SetHeight(int lineDoc, int height) {
if (OneToOne() && (height == 1)) {
return false;
} else {
EnsureData();
if (GetHeight(lineDoc) != height) {
if (GetVisible(lineDoc)) {
displayLines->InsertText(lineDoc, height - GetHeight(lineDoc));
}
heights->SetValueAt(lineDoc, height);
Check();
return true;
} else {
Check();
return false;
}
}
}
void ContractionState::ShowAll() {
Clear();
}
// Debugging checks
void ContractionState::Check() const {
#ifdef CHECK_CORRECTNESS
for (int vline = 0;vline < LinesDisplayed(); vline++) {
const int lineDoc = DocFromDisplay(vline);
PLATFORM_ASSERT(GetVisible(lineDoc));
}
for (int lineDoc = 0;lineDoc < LinesInDoc(); lineDoc++) {
const int displayThis = DisplayFromDoc(lineDoc);
const int displayNext = DisplayFromDoc(lineDoc + 1);
const int height = displayNext - displayThis;
PLATFORM_ASSERT(height >= 0);
if (GetVisible(lineDoc)) {
PLATFORM_ASSERT(GetHeight(lineDoc) == height);
} else {
PLATFORM_ASSERT(0 == height);
}
}
#endif
}
<commit_msg>Fixed bug when ShowAll called where linesInDocument was always reset to 1 which hid most of the file.<commit_after>// Scintilla source code edit control
/** @file ContractionState.cxx
** Manages visibility of lines for folding and wrapping.
**/
// Copyright 1998-2007 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
#include <string.h>
#include "Platform.h"
#include "SplitVector.h"
#include "Partitioning.h"
#include "RunStyles.h"
#include "ContractionState.h"
#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif
ContractionState::ContractionState() : visible(0), expanded(0), heights(0), displayLines(0), linesInDocument(1) {
//InsertLine(0);
}
ContractionState::~ContractionState() {
Clear();
}
void ContractionState::EnsureData() {
if (OneToOne()) {
visible = new RunStyles();
expanded = new RunStyles();
heights = new RunStyles();
displayLines = new Partitioning(4);
InsertLines(0, linesInDocument);
}
}
void ContractionState::Clear() {
delete visible;
visible = 0;
delete expanded;
expanded = 0;
delete heights;
heights = 0;
delete displayLines;
displayLines = 0;
}
int ContractionState::LinesInDoc() const {
if (OneToOne()) {
return linesInDocument;
} else {
return displayLines->Partitions() - 1;
}
}
int ContractionState::LinesDisplayed() const {
if (OneToOne()) {
return linesInDocument;
} else {
return displayLines->PositionFromPartition(LinesInDoc());
}
}
int ContractionState::DisplayFromDoc(int lineDoc) const {
if (OneToOne()) {
return lineDoc;
} else {
if (lineDoc > displayLines->Partitions())
lineDoc = displayLines->Partitions();
return displayLines->PositionFromPartition(lineDoc);
}
}
int ContractionState::DocFromDisplay(int lineDisplay) const {
if (OneToOne()) {
return lineDisplay;
} else {
if (lineDisplay <= 0) {
return 0;
}
if (lineDisplay > LinesDisplayed()) {
return displayLines->PartitionFromPosition(LinesDisplayed());
}
int lineDoc = displayLines->PartitionFromPosition(lineDisplay);
PLATFORM_ASSERT(GetVisible(lineDoc));
return lineDoc;
}
}
void ContractionState::InsertLine(int lineDoc) {
if (OneToOne()) {
linesInDocument++;
} else {
visible->InsertSpace(lineDoc, 1);
visible->SetValueAt(lineDoc, 1);
expanded->InsertSpace(lineDoc, 1);
expanded->SetValueAt(lineDoc, 1);
heights->InsertSpace(lineDoc, 1);
heights->SetValueAt(lineDoc, 1);
int lineDisplay = DisplayFromDoc(lineDoc);
displayLines->InsertPartition(lineDoc, lineDisplay);
displayLines->InsertText(lineDoc, 1);
}
}
void ContractionState::InsertLines(int lineDoc, int lineCount) {
for (int l = 0; l < lineCount; l++) {
InsertLine(lineDoc + l);
}
Check();
}
void ContractionState::DeleteLine(int lineDoc) {
if (OneToOne()) {
linesInDocument--;
} else {
if (GetVisible(lineDoc)) {
displayLines->InsertText(lineDoc, -heights->ValueAt(lineDoc));
}
displayLines->RemovePartition(lineDoc);
visible->DeleteRange(lineDoc, 1);
expanded->DeleteRange(lineDoc, 1);
heights->DeleteRange(lineDoc, 1);
}
}
void ContractionState::DeleteLines(int lineDoc, int lineCount) {
for (int l = 0; l < lineCount; l++) {
DeleteLine(lineDoc);
}
Check();
}
bool ContractionState::GetVisible(int lineDoc) const {
if (OneToOne()) {
return true;
} else {
if (lineDoc >= visible->Length())
return true;
return visible->ValueAt(lineDoc) == 1;
}
}
bool ContractionState::SetVisible(int lineDocStart, int lineDocEnd, bool visible_) {
if (OneToOne() && visible_) {
return false;
} else {
EnsureData();
int delta = 0;
Check();
if ((lineDocStart <= lineDocEnd) && (lineDocStart >= 0) && (lineDocEnd < LinesInDoc())) {
for (int line = lineDocStart; line <= lineDocEnd; line++) {
if (GetVisible(line) != visible_) {
int difference = visible_ ? heights->ValueAt(line) : -heights->ValueAt(line);
visible->SetValueAt(line, visible_ ? 1 : 0);
displayLines->InsertText(line, difference);
delta += difference;
}
}
} else {
return false;
}
Check();
return delta != 0;
}
}
bool ContractionState::GetExpanded(int lineDoc) const {
if (OneToOne()) {
return true;
} else {
Check();
return expanded->ValueAt(lineDoc) == 1;
}
}
bool ContractionState::SetExpanded(int lineDoc, bool expanded_) {
if (OneToOne() && expanded_) {
return false;
} else {
EnsureData();
if (expanded_ != (expanded->ValueAt(lineDoc) == 1)) {
expanded->SetValueAt(lineDoc, expanded_ ? 1 : 0);
Check();
return true;
} else {
Check();
return false;
}
}
}
int ContractionState::GetHeight(int lineDoc) const {
if (OneToOne()) {
return 1;
} else {
return heights->ValueAt(lineDoc);
}
}
// Set the number of display lines needed for this line.
// Return true if this is a change.
bool ContractionState::SetHeight(int lineDoc, int height) {
if (OneToOne() && (height == 1)) {
return false;
} else {
EnsureData();
if (GetHeight(lineDoc) != height) {
if (GetVisible(lineDoc)) {
displayLines->InsertText(lineDoc, height - GetHeight(lineDoc));
}
heights->SetValueAt(lineDoc, height);
Check();
return true;
} else {
Check();
return false;
}
}
}
void ContractionState::ShowAll() {
int lines = LinesInDoc();
Clear();
linesInDocument = lines;
}
// Debugging checks
void ContractionState::Check() const {
#ifdef CHECK_CORRECTNESS
for (int vline = 0;vline < LinesDisplayed(); vline++) {
const int lineDoc = DocFromDisplay(vline);
PLATFORM_ASSERT(GetVisible(lineDoc));
}
for (int lineDoc = 0;lineDoc < LinesInDoc(); lineDoc++) {
const int displayThis = DisplayFromDoc(lineDoc);
const int displayNext = DisplayFromDoc(lineDoc + 1);
const int height = displayNext - displayThis;
PLATFORM_ASSERT(height >= 0);
if (GetVisible(lineDoc)) {
PLATFORM_ASSERT(GetHeight(lineDoc) == height);
} else {
PLATFORM_ASSERT(0 == height);
}
}
#endif
}
<|endoftext|> |
<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/c/experimental/gradients/math_grad.h"
#include "tensorflow/c/eager/c_api_test_util.h"
#include "tensorflow/c/eager/c_api_unified_experimental_internal.h"
#include "tensorflow/c/eager/unified_api_testutil.h"
#include "tensorflow/c/experimental/gradients/grad_test_helper.h"
#include "tensorflow/c/experimental/gradients/tape/tape_context.h"
#include "tensorflow/c/experimental/ops/math_ops.h"
#include "tensorflow/c/tf_status_helper.h"
#include "tensorflow/core/platform/test.h"
namespace tensorflow {
namespace gradients {
namespace internal {
namespace {
using tensorflow::TF_StatusPtr;
Status AddModel(AbstractContext* ctx,
absl::Span<AbstractTensorHandle* const> inputs,
absl::Span<AbstractTensorHandle*> outputs) {
return ops::Add(ctx, inputs, outputs, "Add");
}
Status AddGradModel(AbstractContext* ctx,
absl::Span<AbstractTensorHandle* const> inputs,
absl::Span<AbstractTensorHandle*> outputs) {
GradientRegistry registry;
TF_RETURN_IF_ERROR(registry.Register("AddV2", AddRegisterer));
Tape tape(/*persistent=*/false);
tape.Watch(inputs[0]);
tape.Watch(inputs[1]);
std::vector<AbstractTensorHandle*> temp_outputs(1);
AbstractContextPtr tape_ctx(new TapeContext(ctx, &tape, registry));
TF_RETURN_IF_ERROR(ops::Add(tape_ctx.get(), inputs,
absl::MakeSpan(temp_outputs), "AddGrad"));
TF_RETURN_IF_ERROR(tape.ComputeGradient(ctx, /*targets=*/temp_outputs,
/*sources=*/inputs,
/*output_gradients=*/{}, outputs));
for (auto temp_output : temp_outputs) {
temp_output->Unref();
}
return Status::OK();
}
class CppGradients
: public ::testing::TestWithParam<std::tuple<const char*, bool, bool>> {
protected:
void SetUp() override {
TF_StatusPtr status(TF_NewStatus());
TF_SetTracingImplementation(std::get<0>(GetParam()), status.get());
Status s = StatusFromTF_Status(status.get());
ASSERT_EQ(errors::OK, s.code()) << s.error_message();
{
AbstractContext* ctx_raw = nullptr;
Status s =
BuildImmediateExecutionContext(std::get<1>(GetParam()), &ctx_raw);
ASSERT_EQ(errors::OK, s.code()) << s.error_message();
ctx_.reset(ctx_raw);
}
}
AbstractContextPtr ctx_;
public:
bool UseMlir() const { return strcmp(std::get<0>(GetParam()), "mlir") == 0; }
bool UseFunction() const { return std::get<2>(GetParam()); }
};
TEST_P(CppGradients, TestAddGrad) {
AbstractTensorHandlePtr x;
{
AbstractTensorHandle* x_raw = nullptr;
Status s = TestScalarTensorHandle(ctx_.get(), 2.0f, &x_raw);
ASSERT_EQ(errors::OK, s.code()) << s.error_message();
x.reset(x_raw);
}
AbstractTensorHandlePtr y;
{
AbstractTensorHandle* y_raw = nullptr;
Status s = TestScalarTensorHandle(ctx_.get(), 2.0f, &y_raw);
ASSERT_EQ(errors::OK, s.code()) << s.error_message();
y.reset(y_raw);
}
ASSERT_NO_FATAL_FAILURE(CompareNumericalAndAutodiffGradients(
AddModel, AddGradModel, ctx_.get(), {x.get(), y.get()}, UseFunction()));
}
#ifdef PLATFORM_GOOGLE
INSTANTIATE_TEST_SUITE_P(
UnifiedCAPI, CppGradients,
::testing::Combine(::testing::Values("graphdef", "mlir"),
/*tfrt*/ ::testing::Values(false),
/*use_function*/ ::testing::Values(true, false)));
#else
INSTANTIATE_TEST_SUITE_P(
UnifiedCAPI, CppGradients,
::testing::Combine(::testing::Values("graphdef", "mlir"),
/*tfrt*/ ::testing::Values(false),
/*use_function*/ ::testing::Values(true, false)));
#endif
} // namespace
} // namespace internal
} // namespace gradients
} // namespace tensorflow
<commit_msg>add `TestExpGrad` to `math_grad_test`<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/c/experimental/gradients/math_grad.h"
#include "tensorflow/c/eager/c_api_test_util.h"
#include "tensorflow/c/eager/c_api_unified_experimental_internal.h"
#include "tensorflow/c/eager/unified_api_testutil.h"
#include "tensorflow/c/experimental/gradients/grad_test_helper.h"
#include "tensorflow/c/experimental/gradients/tape/tape_context.h"
#include "tensorflow/c/experimental/ops/math_ops.h"
#include "tensorflow/c/tf_status_helper.h"
#include "tensorflow/core/platform/test.h"
namespace tensorflow {
namespace gradients {
namespace internal {
namespace {
using tensorflow::TF_StatusPtr;
Status AddModel(AbstractContext* ctx,
absl::Span<AbstractTensorHandle* const> inputs,
absl::Span<AbstractTensorHandle*> outputs) {
return ops::Add(ctx, inputs, outputs, "Add");
}
Status AddGradModel(AbstractContext* ctx,
absl::Span<AbstractTensorHandle* const> inputs,
absl::Span<AbstractTensorHandle*> outputs) {
GradientRegistry registry;
TF_RETURN_IF_ERROR(registry.Register("AddV2", AddRegisterer));
Tape tape(/*persistent=*/false);
tape.Watch(inputs[0]);
tape.Watch(inputs[1]);
std::vector<AbstractTensorHandle*> temp_outputs(1);
AbstractContextPtr tape_ctx(new TapeContext(ctx, &tape, registry));
TF_RETURN_IF_ERROR(ops::Add(tape_ctx.get(), inputs,
absl::MakeSpan(temp_outputs), "AddGrad"));
TF_RETURN_IF_ERROR(tape.ComputeGradient(ctx, /*targets=*/temp_outputs,
/*sources=*/inputs,
/*output_gradients=*/{}, outputs));
for (auto temp_output : temp_outputs) {
temp_output->Unref();
}
return Status::OK();
}
Status ExpModel(AbstractContext* ctx,
absl::Span<AbstractTensorHandle* const> inputs,
absl::Span<AbstractTensorHandle*> outputs) {
return ops::Exp(ctx, inputs, outputs, "Exp");
}
Status ExpGradModel(AbstractContext* ctx,
absl::Span<AbstractTensorHandle* const> inputs,
absl::Span<AbstractTensorHandle*> outputs) {
GradientRegistry registry;
TF_RETURN_IF_ERROR(registry.Register("Exp", ExpRegisterer));
Tape tape(/*persistent=*/false);
tape.Watch(inputs[0]);
std::vector<AbstractTensorHandle*> temp_outputs(1);
AbstractContextPtr tape_ctx(new TapeContext(ctx, &tape, registry));
TF_RETURN_IF_ERROR(ops::Exp(tape_ctx.get(), inputs,
absl::MakeSpan(temp_outputs), "ExpGrad"));
TF_RETURN_IF_ERROR(tape.ComputeGradient(ctx, /*targets=*/temp_outputs,
/*sources=*/inputs,
/*output_gradients=*/{}, outputs));
for (auto temp_output : temp_outputs) {
temp_output->Unref();
}
return Status::OK();
}
class CppGradients
: public ::testing::TestWithParam<std::tuple<const char*, bool, bool>> {
protected:
void SetUp() override {
TF_StatusPtr status(TF_NewStatus());
TF_SetTracingImplementation(std::get<0>(GetParam()), status.get());
Status s = StatusFromTF_Status(status.get());
ASSERT_EQ(errors::OK, s.code()) << s.error_message();
{
AbstractContext* ctx_raw = nullptr;
Status s =
BuildImmediateExecutionContext(std::get<1>(GetParam()), &ctx_raw);
ASSERT_EQ(errors::OK, s.code()) << s.error_message();
ctx_.reset(ctx_raw);
}
}
AbstractContextPtr ctx_;
public:
bool UseMlir() const { return strcmp(std::get<0>(GetParam()), "mlir") == 0; }
bool UseFunction() const { return std::get<2>(GetParam()); }
};
TEST_P(CppGradients, TestAddGrad) {
AbstractTensorHandlePtr x;
{
AbstractTensorHandle* x_raw = nullptr;
Status s = TestScalarTensorHandle(ctx_.get(), 2.0f, &x_raw);
ASSERT_EQ(errors::OK, s.code()) << s.error_message();
x.reset(x_raw);
}
AbstractTensorHandlePtr y;
{
AbstractTensorHandle* y_raw = nullptr;
Status s = TestScalarTensorHandle(ctx_.get(), 2.0f, &y_raw);
ASSERT_EQ(errors::OK, s.code()) << s.error_message();
y.reset(y_raw);
}
ASSERT_NO_FATAL_FAILURE(CompareNumericalAndAutodiffGradients(
AddModel, AddGradModel, ctx_.get(), {x.get(), y.get()}, UseFunction()));
}
TEST_P(CppGradients, TestExpGrad) {
AbstractTensorHandlePtr x;
{
AbstractTensorHandle* x_raw = nullptr;
Status s = TestScalarTensorHandle(ctx_.get(), 2.0f, &x_raw);
ASSERT_EQ(errors::OK, s.code()) << s.error_message();
x.reset(x_raw);
}
ASSERT_NO_FATAL_FAILURE(CompareNumericalAndAutodiffGradients(
ExpModel, ExpGradModel, ctx_.get(), {x.get()}, UseFunction()));
}
#ifdef PLATFORM_GOOGLE
INSTANTIATE_TEST_SUITE_P(
UnifiedCAPI, CppGradients,
::testing::Combine(::testing::Values("graphdef", "mlir"),
/*tfrt*/ ::testing::Values(false),
/*use_function*/ ::testing::Values(true, false)));
#else
INSTANTIATE_TEST_SUITE_P(
UnifiedCAPI, CppGradients,
::testing::Combine(::testing::Values("graphdef", "mlir"),
/*tfrt*/ ::testing::Values(false),
/*use_function*/ ::testing::Values(true, false)));
#endif
} // namespace
} // namespace internal
} // namespace gradients
} // namespace tensorflow
<|endoftext|> |
<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM 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) version 2.1 dated February 1999.
//
#include "mfem.hpp"
#include "catch.hpp"
#include <cmath>
using namespace mfem;
TEST_CASE("First order ODE methods",
"[ODE1]")
{
double tol = 0.1;
/** Class for simple linear first order ODE.
*
* du/dt + a u = 0
*
*/
class ODE : public TimeDependentOperator
{
protected:
DenseMatrix A;
public:
ODE(double a00,double a01,double a10,double a11) : TimeDependentOperator(2, 0.0)
{
A.SetSize(2,2);
A(0,0) = a00;
A(0,1) = a01;
A(1,0) = a10;
A(1,1) = a11;
};
virtual void Mult(const Vector &u, Vector &dudt) const
{
A.Mult(u,dudt);
dudt.Neg();
}
virtual void ImplicitSolve(const double dt, const Vector &u, Vector &dudt)
{
DenseMatrix I(2,2),T(2,2);
I = 0.0;
I(0,0) = I(1,1) = 1.0;
Add(I,A,dt,T);
T.Invert();
Vector r(2);
A.Mult(u,r);
r.Neg();
T.Mult(r,dudt);
}
virtual ~ODE() {};
};
/** Class for checking order of convergence of first order ODE.
*/
class CheckODE
{
protected:
int ti_steps,levels;
Vector u0;
double t_final,dt;
ODE *oper;
public:
CheckODE()
{
oper = new ODE(0.0, 1.0, -1.0, 0.0);
ti_steps = 100;
levels = 6;
u0.SetSize(2);
u0 = 1.0;
t_final = M_PI;
dt = t_final/double(ti_steps);
};
double order(ODESolver* ode_solver)
{
ode_solver->Init(*oper);
double dt,t;
Vector u(2);
Vector err(levels);
int steps = ti_steps;
t = 0.0;
dt = t_final/double(steps);
u = u0;
for (int ti = 0; ti< steps; ti++)
{
ode_solver->Step(u, t, dt);
}
u +=u0;
err[0] = u.Norml2();
std::cout<<std::setw(12)<<"Error"
<<std::setw(12)<<"Ratio"
<<std::setw(12)<<"Order"<<std::endl;
std::cout<<std::setw(12)<<err[0]<<std::endl;
for (int l = 1; l< levels; l++)
{
t = 0.0;
steps *=2;
dt = t_final/double(steps);
u = u0;
for (int ti = 0; ti< steps; ti++)
{
ode_solver->Step(u, t, dt);
}
u +=u0;
err[l] = u.Norml2();
std::cout<<std::setw(12)<<err[l]
<<std::setw(12)<<err[l-1]/err[l]
<<std::setw(12)<<log(err[l-1]/err[l])/log(2) <<std::endl;
}
delete ode_solver;
return log(err[levels-2]/err[levels-1])/log(2);
}
virtual ~CheckODE() {delete oper;};
};
CheckODE check;
// Implicit L-stable methods
SECTION("BackwardEuler")
{
std::cout <<"\nTesting BackwardEuler" << std::endl;
REQUIRE(check.order(new BackwardEulerSolver) + tol > 1.0 );
}
SECTION("SDIRK23Solver(2)")
{
std::cout <<"\nTesting SDIRK23Solver(2)" << std::endl;
REQUIRE(check.order(new SDIRK23Solver(2)) + tol > 2.0 );
}
SECTION("SDIRK33Solver")
{
std::cout <<"\nTesting SDIRK33Solver" << std::endl;
REQUIRE(check.order(new SDIRK33Solver) + tol > 3.0 );
}
SECTION("ForwardEulerSolver")
{
std::cout <<"\nTesting ForwardEulerSolver" << std::endl;
REQUIRE(check.order(new ForwardEulerSolver) + tol > 1.0 );
}
SECTION("RK2Solver(0.5)")
{
std::cout <<"\nTesting RK2Solver(0.5)" << std::endl;
REQUIRE(check.order(new RK2Solver(0.5))+ tol > 2.0 );
}
SECTION("RK3SSPSolver")
{
std::cout <<"\nTesting RK3SSPSolver" << std::endl;
REQUIRE(check.order(new RK3SSPSolver) + tol > 3.0 );
}
SECTION("RK4Solver")
{
std::cout <<"\nTesting RK4Solver" << std::endl;
REQUIRE(check.order(new RK4Solver) + tol > 4.0 );
}
SECTION("ImplicitMidpointSolver")
{
std::cout <<"\nTesting ImplicitMidpointSolver" << std::endl;
REQUIRE(check.order(new ImplicitMidpointSolver) + tol > 2.0 );
}
SECTION("SDIRK23Solver")
{
std::cout <<"\nTesting SDIRK23Solver" << std::endl;
REQUIRE(check.order(new SDIRK23Solver) + tol > 3.0 );
}
SECTION("SDIRK34Solver")
{
std::cout <<"\nTesting SDIRK34Solver" << std::endl;
REQUIRE(check.order(new SDIRK34Solver) + tol > 4.0 );
}
/*SECTION("GeneralizedAlphaSolver(0.0)")
{
std::cout <<"\nTesting GeneralizedAlphaSolver(0.0)" << std::endl;
REQUIRE(check.order(new GeneralizedAlphaSolver(0.0)) + tol > 2.0 );
}*/
/* SECTION("GeneralizedAlphaSolver(0.5)")
{
std::cout <<"\nTesting GeneralizedAlphaSolver(0.5)" << std::endl;
REQUIRE(check.order(new GeneralizedAlphaSolver(0.5)) + tol > 2.0 );
}*/
SECTION("GeneralizedAlphaSolver(1.0)")
{
std::cout <<"\nTesting GeneralizedAlphaSolver(1.0)" << std::endl;
REQUIRE(check.order(new GeneralizedAlphaSolver(1.0)) + tol > 2.0 );
}
SECTION("AdamsBashforthSolver(1)")
{
std::cout <<"\nTesting AdamsBashforthSolver(1)" << std::endl;
REQUIRE(check.order(new AdamsBashforthSolver(1)) + tol > 1.0 );
}
SECTION("AdamsBashforthSolver(2)")
{
std::cout <<"\nTesting AdamsBashforthSolver(2)" << std::endl;
REQUIRE(check.order(new AdamsBashforthSolver(2)) + tol > 2.0 );
}
SECTION("AdamsBashforthSolver(3)")
{
std::cout <<"\nTesting AdamsBashforthSolver(3)" << std::endl;
REQUIRE(check.order(new AdamsBashforthSolver(3)) + tol > 3.0 );
}
SECTION("AdamsBashforthSolver(4)")
{
std::cout <<"\nTesting AdamsBashforthSolver(4)" << std::endl;
REQUIRE(check.order(new AdamsBashforthSolver(4)) + tol > 4.0 );
}
SECTION("AdamsBashforthSolver(5)")
{
std::cout <<"\nTesting AdamsBashforthSolver(5)" << std::endl;
REQUIRE(check.order(new AdamsBashforthSolver(5)) + tol > 5.0 );
}
SECTION("AdamsMoultonSolver(1)")
{
std::cout <<"\nTesting AdamsMoultonSolver(1)" << std::endl;
REQUIRE(check.order(new AdamsMoultonSolver(1)) + tol > 1.0 );
}
SECTION("AdamsMoultonSolver(2)")
{
std::cout <<"\nTesting AdamsMoultonSolver(2)" << std::endl;
REQUIRE(check.order(new AdamsMoultonSolver(2)) + tol > 2.0 );
}
SECTION("AdamsMoultonSolver(3)")
{
std::cout <<"\nTesting AdamsMoultonSolver(3)" << std::endl;
REQUIRE(check.order(new AdamsMoultonSolver(3)) + tol > 3.0 );
}
SECTION("AdamsMoultonSolver(4)")
{
std::cout <<"\nTesting AdamsMoultonSolver(4)" << std::endl;
REQUIRE(check.order(new AdamsMoultonSolver(4)) + tol > 4.0 );
}
}
<commit_msg>Small corrections to unit test<commit_after>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at
// the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights
// reserved. See file COPYRIGHT for details.
//
// This file is part of the MFEM library. For more information and source code
// availability see http://mfem.org.
//
// MFEM 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) version 2.1 dated February 1999.
//
#include "mfem.hpp"
#include "catch.hpp"
#include <cmath>
using namespace mfem;
TEST_CASE("First order ODE methods",
"[ODE1]")
{
double tol = 0.1;
/** Class for simple linear first order ODE.
*
* du/dt + a u = 0
*
*/
class ODE : public TimeDependentOperator
{
protected:
DenseMatrix A,I,T;
Vector r;
public:
ODE(double a00,double a01,double a10,double a11) : TimeDependentOperator(2, 0.0)
{
A.SetSize(2,2);
I.SetSize(2,2);
T.SetSize(2,2);
r.SetSize(2);
A(0,0) = a00;
A(0,1) = a01;
A(1,0) = a10;
A(1,1) = a11;
I = 0.0;
I(0,0) = I(1,1) = 1.0;
};
virtual void Mult(const Vector &u, Vector &dudt) const
{
A.Mult(u,dudt);
dudt.Neg();
}
virtual void ImplicitSolve(const double dt, const Vector &u, Vector &dudt)
{
// Residual
A.Mult(u,r);
r.Neg();
// Jacobian
Add(I,A,dt,T);
// Solve
T.Invert();
T.Mult(r,dudt);
}
virtual ~ODE() {};
};
/** Class for checking order of convergence of first order ODE.
*/
class CheckODE
{
protected:
int ti_steps,levels;
Vector u0;
double t_final,dt;
ODE *oper;
public:
CheckODE()
{
oper = new ODE(0.0, 1.0, -1.0, 0.0);
ti_steps = 2;
levels = 6;
u0.SetSize(2);
u0 = 1.0;
t_final = M_PI;
dt = t_final/double(ti_steps);
};
double order(ODESolver* ode_solver)
{
double dt,t;
Vector u(2);
Vector err(levels);
int steps = ti_steps;
t = 0.0;
dt = t_final/double(steps);
u = u0;
ode_solver->Init(*oper);
for (int ti = 0; ti< steps; ti++)
{
ode_solver->Step(u, t, dt);
}
u +=u0;
err[0] = u.Norml2();
std::cout<<std::setw(12)<<"Error"
<<std::setw(12)<<"Ratio"
<<std::setw(12)<<"Order"<<std::endl;
std::cout<<std::setw(12)<<err[0]<<std::endl;
for (int l = 1; l< levels; l++)
{
t = 0.0;
steps *=2;
dt = t_final/double(steps);
u = u0;
ode_solver->Init(*oper);
for (int ti = 0; ti< steps; ti++)
{
ode_solver->Step(u, t, dt);
}
u +=u0;
err[l] = u.Norml2();
std::cout<<std::setw(12)<<err[l]
<<std::setw(12)<<err[l-1]/err[l]
<<std::setw(12)<<log(err[l-1]/err[l])/log(2) <<std::endl;
}
delete ode_solver;
return log(err[levels-2]/err[levels-1])/log(2);
}
virtual ~CheckODE() {delete oper;};
};
CheckODE check;
// Implicit L-stable methods
SECTION("BackwardEuler")
{
std::cout <<"\nTesting BackwardEuler" << std::endl;
REQUIRE(check.order(new BackwardEulerSolver) + tol > 1.0 );
}
SECTION("SDIRK23Solver(2)")
{
std::cout <<"\nTesting SDIRK23Solver(2)" << std::endl;
REQUIRE(check.order(new SDIRK23Solver(2)) + tol > 2.0 );
}
SECTION("SDIRK33Solver")
{
std::cout <<"\nTesting SDIRK33Solver" << std::endl;
REQUIRE(check.order(new SDIRK33Solver) + tol > 3.0 );
}
SECTION("ForwardEulerSolver")
{
std::cout <<"\nTesting ForwardEulerSolver" << std::endl;
REQUIRE(check.order(new ForwardEulerSolver) + tol > 1.0 );
}
SECTION("RK2Solver(0.5)")
{
std::cout <<"\nTesting RK2Solver(0.5)" << std::endl;
REQUIRE(check.order(new RK2Solver(0.5))+ tol > 2.0 );
}
SECTION("RK3SSPSolver")
{
std::cout <<"\nTesting RK3SSPSolver" << std::endl;
REQUIRE(check.order(new RK3SSPSolver) + tol > 3.0 );
}
SECTION("RK4Solver")
{
std::cout <<"\nTesting RK4Solver" << std::endl;
REQUIRE(check.order(new RK4Solver) + tol > 4.0 );
}
SECTION("ImplicitMidpointSolver")
{
std::cout <<"\nTesting ImplicitMidpointSolver" << std::endl;
REQUIRE(check.order(new ImplicitMidpointSolver) + tol > 2.0 );
}
SECTION("SDIRK23Solver")
{
std::cout <<"\nTesting SDIRK23Solver" << std::endl;
REQUIRE(check.order(new SDIRK23Solver) + tol > 3.0 );
}
SECTION("SDIRK34Solver")
{
std::cout <<"\nTesting SDIRK34Solver" << std::endl;
REQUIRE(check.order(new SDIRK34Solver) + tol > 4.0 );
}
// Generalized-alpha
SECTION("GeneralizedAlphaSolver(1.0)")
{
std::cout <<"\nTesting GeneralizedAlphaSolver(1.0)" << std::endl;
REQUIRE(check.order(new GeneralizedAlphaSolver(1.0)) + tol > 2.0 );
}
SECTION("GeneralizedAlphaSolver(0.5)")
{
std::cout <<"\nTesting GeneralizedAlphaSolver(0.5)" << std::endl;
REQUIRE(check.order(new GeneralizedAlphaSolver(0.5)) + tol > 2.0 );
}
SECTION("GeneralizedAlphaSolver(0.0)")
{
std::cout <<"\nTesting GeneralizedAlphaSolver(0.0)" << std::endl;
REQUIRE(check.order(new GeneralizedAlphaSolver(0.0)) + tol > 2.0 );
}
// Adams-Bashforth
/* SECTION("AdamsBashforthSolver(1)")
{
std::cout <<"\nTesting AdamsBashforthSolver(1)" << std::endl;
REQUIRE(check.order(new AdamsBashforthSolver(1)) + tol > 1.0 );
}
SECTION("AdamsBashforthSolver(2)")
{
std::cout <<"\nTesting AdamsBashforthSolver(2)" << std::endl;
REQUIRE(check.order(new AdamsBashforthSolver(2)) + tol > 2.0 );
}
SECTION("AdamsBashforthSolver(3)")
{
std::cout <<"\nTesting AdamsBashforthSolver(3)" << std::endl;
REQUIRE(check.order(new AdamsBashforthSolver(3)) + tol > 3.0 );
}
SECTION("AdamsBashforthSolver(4)")
{
std::cout <<"\nTesting AdamsBashforthSolver(4)" << std::endl;
REQUIRE(check.order(new AdamsBashforthSolver(4)) + tol > 4.0 );
}
SECTION("AdamsBashforthSolver(5)")
{
std::cout <<"\nTesting AdamsBashforthSolver(5)" << std::endl;
REQUIRE(check.order(new AdamsBashforthSolver(5)) + tol > 5.0 );
}*/
/* //AdamsMoulton
SECTION("AdamsMoultonSolver(0)")
{
std::cout <<"\nTesting AdamsMoultonSolver(0)" << std::endl;
REQUIRE(check.order(new AdamsMoultonSolver(0)) + tol > 1.0 );
}
SECTION("AdamsMoultonSolver(1)")
{
std::cout <<"\nTesting AdamsMoultonSolver(1)" << std::endl;
REQUIRE(check.order(new AdamsMoultonSolver(1)) + tol > 2.0 );
}
SECTION("AdamsMoultonSolver(2)")
{
std::cout <<"\nTesting AdamsMoultonSolver(2)" << std::endl;
REQUIRE(check.order(new AdamsMoultonSolver(2)) + tol > 3.0 );
}
SECTION("AdamsMoultonSolver(3)")
{
std::cout <<"\nTesting AdamsMoultonSolver(3)" << std::endl;
REQUIRE(check.order(new AdamsMoultonSolver(3)) + tol > 4.0 );
}
SECTION("AdamsMoultonSolver(4)")
{
std::cout <<"\nTesting AdamsMoultonSolver(4)" << std::endl;
REQUIRE(check.order(new AdamsMoultonSolver(4)) + tol > 5.0 );
}*/
}
<|endoftext|> |
<commit_before>/*********************************************************************************
* Copyright (c) 2014 David D. Marshall <ddmarsha@calpoly.edu>
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* David D. Marshall - initial code and implementation
********************************************************************************/
#ifndef eli_geom_surface_piecewise_body_of_revolution_creator_hpp
#define eli_geom_surface_piecewise_body_of_revolution_creator_hpp
#include <list>
#include <iterator>
#include "eli/code_eli.hpp"
#include "eli/util/tolerance.hpp"
#include "eli/geom/curve/bezier.hpp"
#include "eli/geom/curve/piecewise.hpp"
#include "eli/geom/surface/bezier.hpp"
#include "eli/geom/surface/piecewise.hpp"
namespace eli
{
namespace geom
{
namespace surface
{
template<typename data__, unsigned short dim__, typename tol__>
class capped_surface_creator : public piecewise_creator_base<data__, dim__, tol__>
{
public:
enum edge_split_identifier
{
SPLIT_NONE,
SPLIT_UMIN,
SPLIT_UMAX,
SPLIT_VMIN,
SPLIT_VMAX
};
typedef piecewise_creator_base<data__, dim__, tol__> base_class_type;
typedef typename base_class_type::data_type data_type;
typedef typename base_class_type::point_type point_type;
typedef typename base_class_type::index_type index_type;
typedef typename base_class_type::tolerance_type tolerance_type;
typedef typename base_class_type::piecewise_surface_type piecewise_surface_type;
capped_surface_creator()
: piecewise_creator_base<data__, dim__, tol__>(0, 0), split_param(0), edge_to_split(SPLIT_NONE)
{
}
capped_surface_creator(const data_type &uu0, const data_type &sp, edge_split_identifier esi)
: piecewise_creator_base<data__, dim__, tol__>(0, 0), edge_curve
{
}
capped_surface_creator(const general_skinning_surface_creator<data_type, dim__, tolerance_type> & gs)
: piecewise_creator_base<data_type, dim__, tolerance_type>(gs), ribs(gs.ribs),
max_degree(gs.max_degree), closed(gs.closed)
{
}
virtual ~capped_surface_creator()
{
}
bool set_conditions(const piecewise_curve_type &rbs, const std::vector<index_type> &maxd, bool cl=false)
{
}
virtual bool create(piecewise_surface_type &ps) const
{
typedef typename eli::geom::curve::piecewise<eli::geom::curve::bezier, data_type, dim__, tolerance_type> piecewise_curve_type;
// need to implement
assert(false);
return false;
}
#if 0
{
typedef piecewise<bezier, data_type, dim__, tolerance_type> piecewise_surface_type;
typedef typename piecewise_surface_type::surface_type surface_type;
index_type nribs(this->get_number_u_segments()+1), i, j;
std::vector<index_type> seg_degree(nribs-1);
std::vector<rib_data_type> rib_states(ribs);
tolerance_type tol;
// FIX: Should be able to handle closed surfaces
assert(!closed);
// FIX: Need to be able to handle v-direction discontinuous fu and fuu specifications
// reset the incoming piecewise surface
ps.clear();
// split ribs so have same number of curves (with same joint parameters) for all ribs and get degree
index_type njoints(this->get_number_v_segments()+1);
std::vector<data_type> joints(njoints);
std::vector<index_type> max_jdegs(njoints-1,0);
joints[0]=this->get_v0();
for (j=0; j<(njoints-1); ++j)
{
joints[j+1]=joints[j]+this->get_segment_dv(j);
}
for (i=0; i<nribs; ++i)
{
std::vector<index_type> jdegs;
rib_states[i].split(joints.begin(), joints.end(), std::back_inserter(jdegs));
for (j=0; j<(njoints-1); ++j)
{
if (jdegs[j]>max_jdegs[j])
{
max_jdegs[j]=jdegs[j];
}
}
}
// set degree in u-direction for each rib segment strip
for (i=0; i<nribs; ++i)
{
rib_states[i].promote(max_jdegs.begin(), max_jdegs.end());
}
// resize the piecewise surface
index_type u, v, nu(nribs-1), nv(njoints-1);
ps.init_uv(this->du_begin(), this->du_end(), this->dv_begin(), this->dv_end(), this->get_u0(), this->get_v0());
// build segments based on rib information
// here should have everything to make an nribs x njoints piecewise surface with all
// of the j-degrees matching in the u-direction so that can use general curve creator
// techniques to create control points
for (v=0; v<nv; ++v)
{
typedef eli::geom::curve::piecewise_general_creator<data_type, dim__, tolerance_type> piecewise_curve_creator_type;
typedef eli::geom::curve::piecewise<eli::geom::curve::bezier, data_type, dim__, tolerance_type> piecewise_curve_type;
typedef typename piecewise_curve_type::curve_type curve_type;
std::vector<typename piecewise_curve_creator_type::joint_data> joints(nu+1);
piecewise_curve_creator_type gc;
piecewise_curve_type c;
std::vector<surface_type> surfs(nu);
for (j=0; j<=max_jdegs[v]; ++j)
{
// cycle through each rib to set corresponding joint info
for (u=0; u<=nu; ++u)
{
curve_type jcrv;
joints[u].set_continuity(static_cast<typename piecewise_curve_creator_type::joint_continuity>(rib_states[u].get_continuity()));
rib_states[u].get_f().get(jcrv, v);
joints[u].set_f(jcrv.get_control_point(j));
if (rib_states[u].use_left_fp())
{
rib_states[u].get_left_fp().get(jcrv, v);
joints[u].set_left_fp(jcrv.get_control_point(j));
}
if (rib_states[u].use_right_fp())
{
rib_states[u].get_right_fp().get(jcrv, v);
joints[u].set_right_fp(jcrv.get_control_point(j));
}
if (rib_states[u].use_left_fpp())
{
rib_states[u].get_left_fpp().get(jcrv, v);
joints[u].set_left_fpp(jcrv.get_control_point(j));
}
if (rib_states[u].use_right_fpp())
{
rib_states[u].get_right_fpp().get(jcrv, v);
joints[u].set_right_fpp(jcrv.get_control_point(j));
}
}
// set the conditions for the curve creator
bool rtn_flag(gc.set_conditions(joints, max_degree, closed));
if (!rtn_flag)
{
return false;
}
// set the parameterizations and create curve
gc.set_t0(this->get_u0());
for (u=0; u<nu; ++u)
{
gc.set_segment_dt(this->get_segment_du(u), u);
}
rtn_flag=gc.create(c);
if (!rtn_flag)
{
return false;
}
// extract the control points from piecewise curve and set the surface control points
for (u=0; u<nu; ++u)
{
curve_type crv;
c.get(crv, u);
// resize the temp surface
if (j==0)
{
surfs[u].resize(crv.degree(), max_jdegs[v]);
}
for (i=0; i<=crv.degree(); ++i)
{
surfs[u].set_control_point(crv.get_control_point(i), i, j);
}
}
}
// put these surfaces into piecewise surface
typename piecewise_surface_type::error_code ec;
for (u=0; u<nu; ++u)
{
ec=ps.set(surfs[u], u, v);
if (ec!=piecewise_surface_type::NO_ERRORS)
{
assert(false);
return false;
}
}
}
return true;
}
#endif
private:
piecewise_surface_type orig_surface;
data_type split_param;
edge_split_identifier edge_to_split;
};
}
}
}
#endif
<commit_msg>Cleaned up naming and other code issues.<commit_after>/*********************************************************************************
* Copyright (c) 2014 David D. Marshall <ddmarsha@calpoly.edu>
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* David D. Marshall - initial code and implementation
********************************************************************************/
#ifndef eli_geom_surface_piecewise_capped_surface_creator_hpp
#define eli_geom_surface_piecewise_capped_surface_creator_hpp
#include <list>
#include <iterator>
#include "eli/code_eli.hpp"
#include "eli/util/tolerance.hpp"
#include "eli/geom/curve/bezier.hpp"
#include "eli/geom/curve/piecewise.hpp"
#include "eli/geom/surface/bezier.hpp"
#include "eli/geom/surface/piecewise.hpp"
namespace eli
{
namespace geom
{
namespace surface
{
template<typename data__, unsigned short dim__, typename tol__>
class piecewise_capped_surface_creator : public piecewise_creator_base<data__, dim__, tol__>
{
public:
enum edge_split_identifier
{
SPLIT_NONE,
SPLIT_UMIN,
SPLIT_UMAX,
SPLIT_VMIN,
SPLIT_VMAX
};
typedef piecewise_creator_base<data__, dim__, tol__> base_class_type;
typedef typename base_class_type::data_type data_type;
typedef typename base_class_type::point_type point_type;
typedef typename base_class_type::index_type index_type;
typedef typename base_class_type::tolerance_type tolerance_type;
typedef typename base_class_type::piecewise_surface_type piecewise_surface_type;
piecewise_capped_surface_creator()
: piecewise_creator_base<data__, dim__, tol__>(0, 0), split_param(0), edge_to_split(SPLIT_NONE)
{
}
piecewise_capped_surface_creator(const piecewise_surface_type &os, const data_type &sp, edge_split_identifier esi)
: piecewise_creator_base<data__, dim__, tol__>(0, 0), orig_surface(os), split_param(sp), edge_to_split(esi)
{
}
piecewise_capped_surface_creator(const piecewise_capped_surface_creator<data_type, dim__, tolerance_type> & gs)
: piecewise_creator_base<data_type, dim__, tolerance_type>(gs), orig_surface(gs.orig_surface),
split_param(gs.split_param), edge_to_split(gs.edge_to_split)
{
}
virtual ~piecewise_capped_surface_creator()
{
}
bool set_conditions(const piecewise_surface_type &os, const data_type &sp, edge_split_identifier esi)
{
// before setting things, make sure that the split parameter is within the edges min and max
orig_surface = os;
split_param = sp;
edge_to_split = esi;
}
virtual bool create(piecewise_surface_type &ps) const
{
typedef typename eli::geom::curve::piecewise<eli::geom::curve::bezier, data_type, dim__, tolerance_type> piecewise_curve_type;
// need to implement
assert(false);
return false;
}
#if 0
{
typedef piecewise<bezier, data_type, dim__, tolerance_type> piecewise_surface_type;
typedef typename piecewise_surface_type::surface_type surface_type;
index_type nribs(this->get_number_u_segments()+1), i, j;
std::vector<index_type> seg_degree(nribs-1);
std::vector<rib_data_type> rib_states(ribs);
tolerance_type tol;
// FIX: Should be able to handle closed surfaces
assert(!closed);
// FIX: Need to be able to handle v-direction discontinuous fu and fuu specifications
// reset the incoming piecewise surface
ps.clear();
// split ribs so have same number of curves (with same joint parameters) for all ribs and get degree
index_type njoints(this->get_number_v_segments()+1);
std::vector<data_type> joints(njoints);
std::vector<index_type> max_jdegs(njoints-1,0);
joints[0]=this->get_v0();
for (j=0; j<(njoints-1); ++j)
{
joints[j+1]=joints[j]+this->get_segment_dv(j);
}
for (i=0; i<nribs; ++i)
{
std::vector<index_type> jdegs;
rib_states[i].split(joints.begin(), joints.end(), std::back_inserter(jdegs));
for (j=0; j<(njoints-1); ++j)
{
if (jdegs[j]>max_jdegs[j])
{
max_jdegs[j]=jdegs[j];
}
}
}
// set degree in u-direction for each rib segment strip
for (i=0; i<nribs; ++i)
{
rib_states[i].promote(max_jdegs.begin(), max_jdegs.end());
}
// resize the piecewise surface
index_type u, v, nu(nribs-1), nv(njoints-1);
ps.init_uv(this->du_begin(), this->du_end(), this->dv_begin(), this->dv_end(), this->get_u0(), this->get_v0());
// build segments based on rib information
// here should have everything to make an nribs x njoints piecewise surface with all
// of the j-degrees matching in the u-direction so that can use general curve creator
// techniques to create control points
for (v=0; v<nv; ++v)
{
typedef eli::geom::curve::piecewise_general_creator<data_type, dim__, tolerance_type> piecewise_curve_creator_type;
typedef eli::geom::curve::piecewise<eli::geom::curve::bezier, data_type, dim__, tolerance_type> piecewise_curve_type;
typedef typename piecewise_curve_type::curve_type curve_type;
std::vector<typename piecewise_curve_creator_type::joint_data> joints(nu+1);
piecewise_curve_creator_type gc;
piecewise_curve_type c;
std::vector<surface_type> surfs(nu);
for (j=0; j<=max_jdegs[v]; ++j)
{
// cycle through each rib to set corresponding joint info
for (u=0; u<=nu; ++u)
{
curve_type jcrv;
joints[u].set_continuity(static_cast<typename piecewise_curve_creator_type::joint_continuity>(rib_states[u].get_continuity()));
rib_states[u].get_f().get(jcrv, v);
joints[u].set_f(jcrv.get_control_point(j));
if (rib_states[u].use_left_fp())
{
rib_states[u].get_left_fp().get(jcrv, v);
joints[u].set_left_fp(jcrv.get_control_point(j));
}
if (rib_states[u].use_right_fp())
{
rib_states[u].get_right_fp().get(jcrv, v);
joints[u].set_right_fp(jcrv.get_control_point(j));
}
if (rib_states[u].use_left_fpp())
{
rib_states[u].get_left_fpp().get(jcrv, v);
joints[u].set_left_fpp(jcrv.get_control_point(j));
}
if (rib_states[u].use_right_fpp())
{
rib_states[u].get_right_fpp().get(jcrv, v);
joints[u].set_right_fpp(jcrv.get_control_point(j));
}
}
// set the conditions for the curve creator
bool rtn_flag(gc.set_conditions(joints, max_degree, closed));
if (!rtn_flag)
{
return false;
}
// set the parameterizations and create curve
gc.set_t0(this->get_u0());
for (u=0; u<nu; ++u)
{
gc.set_segment_dt(this->get_segment_du(u), u);
}
rtn_flag=gc.create(c);
if (!rtn_flag)
{
return false;
}
// extract the control points from piecewise curve and set the surface control points
for (u=0; u<nu; ++u)
{
curve_type crv;
c.get(crv, u);
// resize the temp surface
if (j==0)
{
surfs[u].resize(crv.degree(), max_jdegs[v]);
}
for (i=0; i<=crv.degree(); ++i)
{
surfs[u].set_control_point(crv.get_control_point(i), i, j);
}
}
}
// put these surfaces into piecewise surface
typename piecewise_surface_type::error_code ec;
for (u=0; u<nu; ++u)
{
ec=ps.set(surfs[u], u, v);
if (ec!=piecewise_surface_type::NO_ERRORS)
{
assert(false);
return false;
}
}
}
return true;
}
#endif
private:
piecewise_surface_type orig_surface;
data_type split_param;
edge_split_identifier edge_to_split;
};
}
}
}
#endif
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.