<commit_before>    /*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: jobresult.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 11:23:37 $
 *
 *  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
 *
 ************************************************************************/

//________________________________
//  my own includes

#ifndef __FRAMEWORK_JOBS_JOBRESULT_HXX_
#include <jobs/jobresult.hxx>
#endif

#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_
#include <threadhelp/readguard.hxx>
#endif

#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_
#include <threadhelp/writeguard.hxx>
#endif

#ifndef __FRAMEWORK_GENERAL_H_
#include <general.h>
#endif

#ifndef __FRAMEWORK_SERVICES_H_
#include <services.h>
#endif

//________________________________
//  interface includes

//________________________________
//  includes of other projects

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

//________________________________
//  namespace

namespace framework{

//________________________________
//  non exported const

//________________________________
//  non exported definitions

//________________________________
//  declarations

//________________________________
/**
    @short      standard dtor
    @descr      It does nothing else ...
                but it marks this new instance as non valid!
*/
JobResult::JobResult()
    : ThreadHelpBase(&Application::GetSolarMutex())
{
    // reset the flag mask!
    // It will reset the accessible state of this object.
    // That can be usefull if something will fail here ...
    m_eParts = E_NOPART;
}

//________________________________
/**
    @short      special ctor
    @descr      It initialize this new instance with a pure job execution result
                and analyze it. Doing so, we actualize our other members.

                It's a list of named values, packed inside this any.
                Following protocol is used:

                        "SaveArguments" [sequence< css.beans.NamedValue >]

                        The returned list of (for this generic implementation unknown!)
                        properties, will be written directly to the configuration and replace
                        any old values there. There will no check for changes and we doesn't
                        support any mege feature here. They are written only. The job has
                        to modify this list.

                        "SendDispatchResult" [css.frame.DispatchResultEvent]

                        The given event is send to all current registered listener.
                        But it's not guaranteed. In case no listener are available or
                        this job isn't part of the dispatch environment (because it was used
                        by the css..task.XJobExecutor->trigger() implementation) this option
                        will be ignored.

                        "Deactivate" [boolean]

                        The job whish to be disabled. But note: There is no way, to enable it later
                        again by using this implementation. It can be done by using the configuration
                        only. (Means to register this job again.)
                        If a job knows, that there exist some status or result listener, it must use
                        the options "SendDispatchStatus" and "SendDispatchResult" (see before) too, to
                        inform it about the deactivation of this service.

    @param      aResult
                    the job result
*/
JobResult::JobResult( /*IN*/ const css::uno::Any& aResult )
    : ThreadHelpBase(&Application::GetSolarMutex())
{
    // safe the pure result
    // May someone need it later ...
    m_aPureResult = aResult;

    // reset the flag mask!
    // It will reset the accessible state of this object.
    // That can be usefull if something will fail here ...
    m_eParts = E_NOPART;

    // analyze the result and actualize our other members
    css::uno::Sequence< css::beans::NamedValue > lProtocol;
    if (!(aResult >>= lProtocol))
        return;

    sal_Int32 nCount = lProtocol.getLength();
    for( sal_Int32 i=0; i<nCount; ++i )
    {
        if (
            (lProtocol[i].Name.equalsIgnoreAsciiCaseAsciiL("Deactivate",10)) &&
            (lProtocol[i].Value >>= m_bDeactivate                          )
           )
        {
            if ( m_bDeactivate )
                m_eParts |= E_DEACTIVATE;
        }
        else
        if (
            (lProtocol[i].Name.equalsIgnoreAsciiCaseAsciiL("SaveArguments",13)) &&
            (lProtocol[i].Value >>= m_lArguments                              )
           )
        {
            m_eParts |= E_ARGUMENTS;
        }
        else
        if (
            (lProtocol[i].Name.equalsIgnoreAsciiCaseAsciiL("SendDispatchResult",18)) &&
            (lProtocol[i].Value >>= m_aDispatchResult                              )
           )
        {
            m_eParts |= E_DISPATCHRESULT;
        }
    }
}

//________________________________
/**
    @short      copy dtor
    @descr      -
*/
JobResult::JobResult( const JobResult& rCopy )
    : ThreadHelpBase(&Application::GetSolarMutex())
{
    m_aPureResult     = rCopy.m_aPureResult     ;
    m_eParts          = rCopy.m_eParts          ;
    m_lArguments      = rCopy.m_lArguments      ;
    m_bDeactivate     = rCopy.m_bDeactivate     ;
    m_aDispatchResult = rCopy.m_aDispatchResult ;
}

//________________________________
/**
    @short      standard dtor
    @descr      Free all internaly used ressources at the end of living.
*/
JobResult::~JobResult()
{
    // Nothing realy to do here.
}

//________________________________
/**
    @short      =operator
    @descr      Must be implemented to overwrite this instance with another one.

    @param      rCopy
                    reference to the other instance, which should be used for copying.
*/
void JobResult::operator=( const JobResult& rCopy )
{
    /* SAFE { */
    WriteGuard aWriteLock(m_aLock);
    m_aPureResult     = rCopy.m_aPureResult     ;
    m_eParts          = rCopy.m_eParts          ;
    m_lArguments      = rCopy.m_lArguments      ;
    m_bDeactivate     = rCopy.m_bDeactivate     ;
    m_aDispatchResult = rCopy.m_aDispatchResult ;
    aWriteLock.unlock();
    /* } SAFE */
}

//________________________________
/**
    @short      checks for existing parts of the analyzed result
    @descr      The internal flag mask was set after analyzing of the pure result.
                An user of us can check here, if the required part was realy part
                of this result. Otherwhise it would use invalid informations ...
                by using our other members!

    @param      eParts
                    a flag mask too, which will be compared with our internaly set one.

    @return     We return true only, if any set flag of the given mask match.
*/
sal_Bool JobResult::existPart( sal_uInt32 eParts ) const
{
    /* SAFE { */
    ReadGuard aReadLock(m_aLock);
    return ((m_eParts & eParts) == eParts);
    /* } SAFE */
}

//________________________________
/**
    @short      provides access to our internal members
    @descr      The return value will be valid only in case a call of
                existPart(E_...) before returned true!

    @return     It returns the state of the internal member
                without any checks!
*/
css::uno::Sequence< css::beans::NamedValue > JobResult::getArguments() const
{
    /* SAFE { */
    ReadGuard aReadLock(m_aLock);
    return m_lArguments;
    /* } SAFE */
}

//________________________________

sal_Bool JobResult::getDeactivate() const
{
    /* SAFE { */
    ReadGuard aReadLock(m_aLock);
    return m_bDeactivate;
    /* } SAFE */
}

//________________________________

css::frame::DispatchResultEvent JobResult::getDispatchResult() const
{
    /* SAFE { */
    ReadGuard aReadLock(m_aLock);
    return m_aDispatchResult;
    /* } SAFE */
}

} // namespace framework
<commit_msg>INTEGRATION: CWS pchfix02 (1.5.52); FILE MERGED 2006/09/01 17:29:14 kaib 1.5.52.1: #i68856# Added header markers and pch files<commit_after>    /*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: jobresult.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 14:04:24 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_framework.hxx"

//________________________________
//  my own includes

#ifndef __FRAMEWORK_JOBS_JOBRESULT_HXX_
#include <jobs/jobresult.hxx>
#endif

#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_
#include <threadhelp/readguard.hxx>
#endif

#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_
#include <threadhelp/writeguard.hxx>
#endif

#ifndef __FRAMEWORK_GENERAL_H_
#include <general.h>
#endif

#ifndef __FRAMEWORK_SERVICES_H_
#include <services.h>
#endif

//________________________________
//  interface includes

//________________________________
//  includes of other projects

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

//________________________________
//  namespace

namespace framework{

//________________________________
//  non exported const

//________________________________
//  non exported definitions

//________________________________
//  declarations

//________________________________
/**
    @short      standard dtor
    @descr      It does nothing else ...
                but it marks this new instance as non valid!
*/
JobResult::JobResult()
    : ThreadHelpBase(&Application::GetSolarMutex())
{
    // reset the flag mask!
    // It will reset the accessible state of this object.
    // That can be usefull if something will fail here ...
    m_eParts = E_NOPART;
}

//________________________________
/**
    @short      special ctor
    @descr      It initialize this new instance with a pure job execution result
                and analyze it. Doing so, we actualize our other members.

                It's a list of named values, packed inside this any.
                Following protocol is used:

                        "SaveArguments" [sequence< css.beans.NamedValue >]

                        The returned list of (for this generic implementation unknown!)
                        properties, will be written directly to the configuration and replace
                        any old values there. There will no check for changes and we doesn't
                        support any mege feature here. They are written only. The job has
                        to modify this list.

                        "SendDispatchResult" [css.frame.DispatchResultEvent]

                        The given event is send to all current registered listener.
                        But it's not guaranteed. In case no listener are available or
                        this job isn't part of the dispatch environment (because it was used
                        by the css..task.XJobExecutor->trigger() implementation) this option
                        will be ignored.

                        "Deactivate" [boolean]

                        The job whish to be disabled. But note: There is no way, to enable it later
                        again by using this implementation. It can be done by using the configuration
                        only. (Means to register this job again.)
                        If a job knows, that there exist some status or result listener, it must use
                        the options "SendDispatchStatus" and "SendDispatchResult" (see before) too, to
                        inform it about the deactivation of this service.

    @param      aResult
                    the job result
*/
JobResult::JobResult( /*IN*/ const css::uno::Any& aResult )
    : ThreadHelpBase(&Application::GetSolarMutex())
{
    // safe the pure result
    // May someone need it later ...
    m_aPureResult = aResult;

    // reset the flag mask!
    // It will reset the accessible state of this object.
    // That can be usefull if something will fail here ...
    m_eParts = E_NOPART;

    // analyze the result and actualize our other members
    css::uno::Sequence< css::beans::NamedValue > lProtocol;
    if (!(aResult >>= lProtocol))
        return;

    sal_Int32 nCount = lProtocol.getLength();
    for( sal_Int32 i=0; i<nCount; ++i )
    {
        if (
            (lProtocol[i].Name.equalsIgnoreAsciiCaseAsciiL("Deactivate",10)) &&
            (lProtocol[i].Value >>= m_bDeactivate                          )
           )
        {
            if ( m_bDeactivate )
                m_eParts |= E_DEACTIVATE;
        }
        else
        if (
            (lProtocol[i].Name.equalsIgnoreAsciiCaseAsciiL("SaveArguments",13)) &&
            (lProtocol[i].Value >>= m_lArguments                              )
           )
        {
            m_eParts |= E_ARGUMENTS;
        }
        else
        if (
            (lProtocol[i].Name.equalsIgnoreAsciiCaseAsciiL("SendDispatchResult",18)) &&
            (lProtocol[i].Value >>= m_aDispatchResult                              )
           )
        {
            m_eParts |= E_DISPATCHRESULT;
        }
    }
}

//________________________________
/**
    @short      copy dtor
    @descr      -
*/
JobResult::JobResult( const JobResult& rCopy )
    : ThreadHelpBase(&Application::GetSolarMutex())
{
    m_aPureResult     = rCopy.m_aPureResult     ;
    m_eParts          = rCopy.m_eParts          ;
    m_lArguments      = rCopy.m_lArguments      ;
    m_bDeactivate     = rCopy.m_bDeactivate     ;
    m_aDispatchResult = rCopy.m_aDispatchResult ;
}

//________________________________
/**
    @short      standard dtor
    @descr      Free all internaly used ressources at the end of living.
*/
JobResult::~JobResult()
{
    // Nothing realy to do here.
}

//________________________________
/**
    @short      =operator
    @descr      Must be implemented to overwrite this instance with another one.

    @param      rCopy
                    reference to the other instance, which should be used for copying.
*/
void JobResult::operator=( const JobResult& rCopy )
{
    /* SAFE { */
    WriteGuard aWriteLock(m_aLock);
    m_aPureResult     = rCopy.m_aPureResult     ;
    m_eParts          = rCopy.m_eParts          ;
    m_lArguments      = rCopy.m_lArguments      ;
    m_bDeactivate     = rCopy.m_bDeactivate     ;
    m_aDispatchResult = rCopy.m_aDispatchResult ;
    aWriteLock.unlock();
    /* } SAFE */
}

//________________________________
/**
    @short      checks for existing parts of the analyzed result
    @descr      The internal flag mask was set after analyzing of the pure result.
                An user of us can check here, if the required part was realy part
                of this result. Otherwhise it would use invalid informations ...
                by using our other members!

    @param      eParts
                    a flag mask too, which will be compared with our internaly set one.

    @return     We return true only, if any set flag of the given mask match.
*/
sal_Bool JobResult::existPart( sal_uInt32 eParts ) const
{
    /* SAFE { */
    ReadGuard aReadLock(m_aLock);
    return ((m_eParts & eParts) == eParts);
    /* } SAFE */
}

//________________________________
/**
    @short      provides access to our internal members
    @descr      The return value will be valid only in case a call of
                existPart(E_...) before returned true!

    @return     It returns the state of the internal member
                without any checks!
*/
css::uno::Sequence< css::beans::NamedValue > JobResult::getArguments() const
{
    /* SAFE { */
    ReadGuard aReadLock(m_aLock);
    return m_lArguments;
    /* } SAFE */
}

//________________________________

sal_Bool JobResult::getDeactivate() const
{
    /* SAFE { */
    ReadGuard aReadLock(m_aLock);
    return m_bDeactivate;
    /* } SAFE */
}

//________________________________

css::frame::DispatchResultEvent JobResult::getDispatchResult() const
{
    /* SAFE { */
    ReadGuard aReadLock(m_aLock);
    return m_aDispatchResult;
    /* } SAFE */
}

} // namespace framework
<|endoftext|>


<commit_before>#include "../src/utility.h"
#include "../src/HDD/HardDrive.h"

void unittest(){
    const size_t emptyOff = 0x80120;

    HDD first(1,true);
    first.init();

    int data[1000];
    for(int i = 0 ; i < 1000 ; ++i){
        data[i] = i;
    }
    first.writeaddr(emptyOff,&data,4*1000);
    int res;
    first.readaddr(emptyOff + 4 *42,&res,4);
    printf("%d\n",res);
    first.readaddr(emptyOff + 4 *999,&res,4);
    printf("%d\n",res);
    res = 45;
    first.writeaddr(emptyOff + 4 *537,&res,4);
    first.readaddr(emptyOff + 4 *753,&res,4);
    printf("%d\n",res);
    first.readaddr(emptyOff + 4 *537,&res,4);
    printf("%d\n",res);
}
<commit_msg>Fix compilation error in HDD's unittest<commit_after>#include "../src/utility.h"
#include "../src/HDD/HardDrive.h"

void unittest(){
    const size_t emptyOff = 0x80120;

    HDD::HDD first(1,true);
    first.init();

    int data[1000];
    for(int i = 0 ; i < 1000 ; ++i){
        data[i] = i;
    }
    first.writeaddr(emptyOff,&data,4*1000);
    int res;
    first.readaddr(emptyOff + 4 *42,&res,4);
    printf("%d\n",res);
    first.readaddr(emptyOff + 4 *999,&res,4);
    printf("%d\n",res);
    res = 45;
    first.writeaddr(emptyOff + 4 *537,&res,4);
    first.readaddr(emptyOff + 4 *753,&res,4);
    printf("%d\n",res);
    first.readaddr(emptyOff + 4 *537,&res,4);
    printf("%d\n",res);
}
<|endoftext|>


<commit_before>// RuledSurface.cpp
// Copyright (c) 2009, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.

#include "stdafx.h"
#include "RuledSurface.h"
#include "Wire.h"
#include "Face.h"
#include "ConversionTools.h"
#include "MarkedList.h"
#include "HeeksConfig.h"
#include "../interface/DoubleInput.h"
#include "../interface/PropertyCheck.h"

void PickCreateRuledSurface()
{
	if(wxGetApp().m_marked_list->size() == 0)
	{
		wxGetApp().PickObjects(_("pick some sketches"));
	}

	if(wxGetApp().m_marked_list->size() > 0)
	{
		std::list<TopoDS_Wire> wire_list;

		std::list<HeeksObj*> sketches_to_delete;

		for(std::list<HeeksObj *>::const_iterator It = wxGetApp().m_marked_list->list().begin(); It != wxGetApp().m_marked_list->list().end(); It++)
		{
			HeeksObj* object = *It;
			if(object->GetType() == SketchType)
			{
				std::list<HeeksObj*> list;
				list.push_back(object);
				TopoDS_Wire wire;
				if(ConvertLineArcsToWire2(list, wire))
				{
					wire_list.push_back(wire);
					if(wxGetApp().m_loft_removes_sketches)sketches_to_delete.push_back(object);
				}
			}
		}

		wxGetApp().Remove(sketches_to_delete);

		TopoDS_Shape shape;
		if(CreateRuledSurface(wire_list, shape, true))
		{
			HeeksObj* new_object = CShape::MakeObject(shape, _("Ruled Surface"), SOLID_TYPE_UNKNOWN, HeeksColor(51, 45, 51));
			wxGetApp().Add(new_object, NULL);
			wxGetApp().Repaint();
		}

	}
}

HeeksObj* CreateExtrusionOrRevolution(std::list<HeeksObj*> list, double height_or_angle, bool solid_if_possible, bool revolution_not_extrusion, bool add_new_objects)
{
	std::list<TopoDS_Shape> faces_or_wires;

	std::list<HeeksObj*> sketches_or_faces_to_delete;

	for(std::list<HeeksObj *>::const_iterator It = list.begin(); It != list.end(); It++)
	{
		HeeksObj* object = *It;
		switch(object->GetType())
		{
		case SketchType:
		case CircleType:
			{
				if(ConvertSketchToFaceOrWire(object, faces_or_wires, solid_if_possible))
				{
					if(wxGetApp().m_extrude_removes_sketches)sketches_or_faces_to_delete.push_back(object);
				}
			}
			break;

		case FaceType:
			faces_or_wires.push_back(((CFace*)object)->Face());
			if(wxGetApp().m_extrude_removes_sketches)sketches_or_faces_to_delete.push_back(object);
			break;

		default:
			break;
		}
	}

	wxGetApp().Remove(sketches_or_faces_to_delete);

	std::list<TopoDS_Shape> new_shapes;
	gp_Trsf trsf = wxGetApp().GetDrawMatrix(false);
	if(revolution_not_extrusion)
	{
		CreateRevolutions(faces_or_wires, new_shapes, gp_Ax1(gp_Pnt(0, 0, 0).Transformed(trsf), gp_Vec(0, 0, 1).Transformed(trsf)), height_or_angle);
	}
	else
	{
		CreateExtrusions(faces_or_wires, new_shapes, gp_Vec(0, 0, height_or_angle).Transformed(trsf));
	}
	HeeksObj* new_object = 0;
	if(new_shapes.size() > 0)
	{
		for(std::list<TopoDS_Shape>::iterator It = new_shapes.begin(); It != new_shapes.end(); It++){
			TopoDS_Shape& shape = *It;
			new_object = CShape::MakeObject(shape, revolution_not_extrusion ? _("Revolved Solid") : _("Extruded Solid"), SOLID_TYPE_UNKNOWN, wxGetApp().current_color);
			if(add_new_objects)
				wxGetApp().Add(new_object, NULL);
			else
				break;
		}
		wxGetApp().Repaint();
	}
	return new_object;
}

HeeksObj* CreatePipeFromProfile(HeeksObj* spine, HeeksObj* profile)
{
	const TopoDS_Wire wire = ((CWire*)spine)->Wire();
	std::list<TopoDS_Shape> faces;
	std::list<HeeksObj*> pipe_shapes;
	if(ConvertSketchToFaceOrWire(profile, faces, true))
	{
		for(std::list<TopoDS_Shape>::iterator It2 = faces.begin(); It2 != faces.end(); It2++)
		{
			TopoDS_Shape& face = *It2;

			try
			{
				// pipe profile algong spine
				BRepOffsetAPI_MakePipe makePipe(wire, face);
				makePipe.Build();
				TopoDS_Shape shape = makePipe.Shape();

				HeeksObj* new_object = CShape::MakeObject(shape, _("Pipe"), SOLID_TYPE_UNKNOWN, wxGetApp().current_color);
				if(new_object)pipe_shapes.push_back(new_object);
			}
			catch (Standard_Failure) {
				Handle_Standard_Failure e = Standard_Failure::Caught();
				wxMessageBox(wxString(_("Error making pipe")) + _T(": ") + Ctt(e->GetMessageString()));
			}
		}
		if(pipe_shapes.size() > 0)
		{
			wxGetApp().CreateUndoPoint();
			for(std::list<HeeksObj*>::iterator It = pipe_shapes.begin(); It != pipe_shapes.end(); It++)
			{
				HeeksObj* object = *It;
				wxGetApp().Add(object, NULL);
			}
			wxGetApp().Remove(profile);
			wxGetApp().Changed();
			return pipe_shapes.front();
		}
	}

	return NULL;
}

HeeksObj* CreateRuledFromSketches(std::list<HeeksObj*> list, bool make_solid)
{
	std::list<TopoDS_Wire> wire_list;
	for(std::list<HeeksObj *>::iterator It = list.begin(); It != list.end(); It++)
	{
		HeeksObj* object = *It;
		if(object->GetType() == SketchType)
		{
			std::list<HeeksObj*> s;
			s.push_back(object);
			TopoDS_Wire wire;
			if(ConvertLineArcsToWire2(s, wire))
			{
				wire_list.push_back(wire);
			}
		}
	}

	TopoDS_Shape shape;
	if(CreateRuledSurface(wire_list, shape, make_solid))
	{
		return CShape::MakeObject(shape, _("Ruled Surface"), SOLID_TYPE_UNKNOWN, HeeksColor(51, 45, 51));
	}
	return NULL;
}

static void on_extrude_to_solid(bool onoff, HeeksObj* object)
{
	wxGetApp().m_extrude_to_solid = onoff;
	HeeksConfig config;
	config.Write(_T("ExtrudeToSolid"), wxGetApp().m_extrude_to_solid);
}

class CExtrusionInput:public CLengthInput
{
public:
	CExtrusionInput(double &value):CLengthInput(_("Input extrusion height"), _("height"), value){}

	// virtual functions for InputMode
	void GetProperties(std::list<Property *> *list)
	{
		CLengthInput::GetProperties(list);
		list->push_back(new PropertyCheck(_("Extrude makes a solid"), wxGetApp().m_extrude_to_solid, NULL, on_extrude_to_solid));
	}
};

bool InputExtrusionHeight(double &value)
{
	CInputMode* save_mode = wxGetApp().input_mode_object;
	CExtrusionInput extrusion_input(value);
	wxGetApp().SetInputMode(&extrusion_input);

	wxGetApp().OnRun();

	wxGetApp().SetInputMode(save_mode);

	if(CLengthInput::m_success)value = extrusion_input.m_value;

	return CLengthInput::m_success;
}

void PickCreateExtrusion()
{
	if(wxGetApp().m_marked_list->size() == 0)
	{
		wxGetApp().PickObjects(_("pick sketches, faces or circles"), MARKING_FILTER_CIRCLE | MARKING_FILTER_SKETCH | MARKING_FILTER_FACE);
	}

	double height = 10; // to do, this should get written to config file

	if(InputExtrusionHeight(height))
	{
		if(wxGetApp().m_marked_list->size() > 0)
		{
			CreateExtrusionOrRevolution(wxGetApp().m_marked_list->list(),height, wxGetApp().m_extrude_to_solid, false);
		}
	}
}

class CRevolutionInput:public CDoubleInput
{
public:
	CRevolutionInput(double &value):CDoubleInput(_("Input revolution angle"), _("angle"), value){}

	// virtual functions for InputMode
	void GetProperties(std::list<Property *> *list)
	{
		CDoubleInput::GetProperties(list);
		list->push_back(new PropertyCheck(_("Extrude makes a solid"), wxGetApp().m_extrude_to_solid, NULL, on_extrude_to_solid));
	}
};

void PickCreateRevolution()
{
	if(wxGetApp().m_marked_list->size() == 0)
	{
		wxGetApp().PickObjects(_("pick sketches, faces or circles"), MARKING_FILTER_CIRCLE | MARKING_FILTER_SKETCH | MARKING_FILTER_FACE);
	}

	double angle = 360.0; // to do, this should get written to config file

	if(wxGetApp().InputDouble(_("Input revolution angle"), _("angle"), angle))
	{
		if(wxGetApp().m_marked_list->size() > 0)
		{
			CreateExtrusionOrRevolution(wxGetApp().m_marked_list->list(), angle, true, true);
		}
	}
}

bool CreateRuledSurface(const std::list<TopoDS_Wire> &wire_list, TopoDS_Shape& shape, bool make_solid)
{
	if(wire_list.size() > 0)
	{
			BRepOffsetAPI_ThruSections generator( make_solid ? Standard_True : Standard_False, Standard_False );
			for(std::list<TopoDS_Wire>::const_iterator It = wire_list.begin(); It != wire_list.end(); It++)
			{
				const TopoDS_Wire &wire = *It;
				generator.AddWire(wire);
			}

		try{
			generator.Build();
			shape = generator.Shape();
		}
		catch (Standard_Failure) {
			Handle_Standard_Failure e = Standard_Failure::Caught();
			wxMessageBox(wxString(_("Error making ruled solid")) + _T(": ") + Ctt(e->GetMessageString()));
			return false;
		}
		catch(...)
		{
			wxMessageBox(_("Fatal error making ruled solid"));
			return false;
		}

		return true;
	}
	return false;
}

void CreateExtrusions(const std::list<TopoDS_Shape> &faces_or_wires, std::list<TopoDS_Shape>& new_shapes, const gp_Vec& extrude_vector)
{
	try{
		for(std::list<TopoDS_Shape>::const_iterator It = faces_or_wires.begin(); It != faces_or_wires.end(); It++)
		{
			const TopoDS_Shape& face_or_wire = *It;
			BRepPrimAPI_MakePrism generator( face_or_wire, extrude_vector );
			generator.Build();
			new_shapes.push_back(generator.Shape());
		}
	}
	catch (Standard_Failure) {
		Handle_Standard_Failure e = Standard_Failure::Caught();
		wxMessageBox(wxString(_("Error making extruded solid")) + _T(": ") + Ctt(e->GetMessageString()));
	}
	catch(...)
	{
		wxMessageBox(_("Fatal error making extruded solid"));
	}

}

void CreateRevolutions(const std::list<TopoDS_Shape> &faces_or_wires, std::list<TopoDS_Shape>& new_shapes, const gp_Ax1& axis, double angle)
{
	try{
		for(std::list<TopoDS_Shape>::const_iterator It = faces_or_wires.begin(); It != faces_or_wires.end(); It++)
		{
			const TopoDS_Shape& face_or_wire = *It;
			if(fabs(angle - 360.0) < 0.00001)
			{
				BRepPrimAPI_MakeRevol generator( face_or_wire, axis );
				generator.Build();
				new_shapes.push_back(generator.Shape());
			}
			else
			{
				BRepPrimAPI_MakeRevol generator( face_or_wire, axis, angle * Pi/180 );
				generator.Build();
				new_shapes.push_back(generator.Shape());
			}
		}
	}
	catch (Standard_Failure) {
		Handle_Standard_Failure e = Standard_Failure::Caught();
		wxMessageBox(wxString(_("Error making revolved solid")) + _T(": ") + Ctt(e->GetMessageString()));
	}
	catch(...)
	{
		wxMessageBox(_("Fatal error making revolved solid"));
	}

}

<commit_msg>Changed default axis of revolution to vector along X axis, because I'm lazy :)<commit_after>// RuledSurface.cpp
// Copyright (c) 2009, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.

#include "stdafx.h"
#include "RuledSurface.h"
#include "Wire.h"
#include "Face.h"
#include "ConversionTools.h"
#include "MarkedList.h"
#include "HeeksConfig.h"
#include "../interface/DoubleInput.h"
#include "../interface/PropertyCheck.h"

void PickCreateRuledSurface()
{
	if(wxGetApp().m_marked_list->size() == 0)
	{
		wxGetApp().PickObjects(_("pick some sketches"));
	}

	if(wxGetApp().m_marked_list->size() > 0)
	{
		std::list<TopoDS_Wire> wire_list;

		std::list<HeeksObj*> sketches_to_delete;

		for(std::list<HeeksObj *>::const_iterator It = wxGetApp().m_marked_list->list().begin(); It != wxGetApp().m_marked_list->list().end(); It++)
		{
			HeeksObj* object = *It;
			if(object->GetType() == SketchType)
			{
				std::list<HeeksObj*> list;
				list.push_back(object);
				TopoDS_Wire wire;
				if(ConvertLineArcsToWire2(list, wire))
				{
					wire_list.push_back(wire);
					if(wxGetApp().m_loft_removes_sketches)sketches_to_delete.push_back(object);
				}
			}
		}

		wxGetApp().Remove(sketches_to_delete);

		TopoDS_Shape shape;
		if(CreateRuledSurface(wire_list, shape, true))
		{
			HeeksObj* new_object = CShape::MakeObject(shape, _("Ruled Surface"), SOLID_TYPE_UNKNOWN, HeeksColor(51, 45, 51));
			wxGetApp().Add(new_object, NULL);
			wxGetApp().Repaint();
		}

	}
}

HeeksObj* CreateExtrusionOrRevolution(std::list<HeeksObj*> list, double height_or_angle, bool solid_if_possible, bool revolution_not_extrusion, bool add_new_objects)
{
	std::list<TopoDS_Shape> faces_or_wires;

	std::list<HeeksObj*> sketches_or_faces_to_delete;

	for(std::list<HeeksObj *>::const_iterator It = list.begin(); It != list.end(); It++)
	{
		HeeksObj* object = *It;
		switch(object->GetType())
		{
		case SketchType:
		case CircleType:
			{
				if(ConvertSketchToFaceOrWire(object, faces_or_wires, solid_if_possible))
				{
					if(wxGetApp().m_extrude_removes_sketches)sketches_or_faces_to_delete.push_back(object);
				}
			}
			break;

		case FaceType:
			faces_or_wires.push_back(((CFace*)object)->Face());
			if(wxGetApp().m_extrude_removes_sketches)sketches_or_faces_to_delete.push_back(object);
			break;

		default:
			break;
		}
	}

	wxGetApp().Remove(sketches_or_faces_to_delete);

	std::list<TopoDS_Shape> new_shapes;
	gp_Trsf trsf = wxGetApp().GetDrawMatrix(false);
	if(revolution_not_extrusion)
	{
		CreateRevolutions(faces_or_wires, new_shapes, gp_Ax1(gp_Pnt(0, 0, 0).Transformed(trsf), gp_Vec(1, 0, 0).Transformed(trsf)), height_or_angle);
	}
	else
	{
		CreateExtrusions(faces_or_wires, new_shapes, gp_Vec(0, 0, height_or_angle).Transformed(trsf));
	}
	HeeksObj* new_object = 0;
	if(new_shapes.size() > 0)
	{
		for(std::list<TopoDS_Shape>::iterator It = new_shapes.begin(); It != new_shapes.end(); It++){
			TopoDS_Shape& shape = *It;
			new_object = CShape::MakeObject(shape, revolution_not_extrusion ? _("Revolved Solid") : _("Extruded Solid"), SOLID_TYPE_UNKNOWN, wxGetApp().current_color);
			if(add_new_objects)
				wxGetApp().Add(new_object, NULL);
			else
				break;
		}
		wxGetApp().Repaint();
	}
	return new_object;
}

HeeksObj* CreatePipeFromProfile(HeeksObj* spine, HeeksObj* profile)
{
	const TopoDS_Wire wire = ((CWire*)spine)->Wire();
	std::list<TopoDS_Shape> faces;
	std::list<HeeksObj*> pipe_shapes;
	if(ConvertSketchToFaceOrWire(profile, faces, true))
	{
		for(std::list<TopoDS_Shape>::iterator It2 = faces.begin(); It2 != faces.end(); It2++)
		{
			TopoDS_Shape& face = *It2;

			try
			{
				// pipe profile algong spine
				BRepOffsetAPI_MakePipe makePipe(wire, face);
				makePipe.Build();
				TopoDS_Shape shape = makePipe.Shape();

				HeeksObj* new_object = CShape::MakeObject(shape, _("Pipe"), SOLID_TYPE_UNKNOWN, wxGetApp().current_color);
				if(new_object)pipe_shapes.push_back(new_object);
			}
			catch (Standard_Failure) {
				Handle_Standard_Failure e = Standard_Failure::Caught();
				wxMessageBox(wxString(_("Error making pipe")) + _T(": ") + Ctt(e->GetMessageString()));
			}
		}
		if(pipe_shapes.size() > 0)
		{
			wxGetApp().CreateUndoPoint();
			for(std::list<HeeksObj*>::iterator It = pipe_shapes.begin(); It != pipe_shapes.end(); It++)
			{
				HeeksObj* object = *It;
				wxGetApp().Add(object, NULL);
			}
			wxGetApp().Remove(profile);
			wxGetApp().Changed();
			return pipe_shapes.front();
		}
	}

	return NULL;
}

HeeksObj* CreateRuledFromSketches(std::list<HeeksObj*> list, bool make_solid)
{
	std::list<TopoDS_Wire> wire_list;
	for(std::list<HeeksObj *>::iterator It = list.begin(); It != list.end(); It++)
	{
		HeeksObj* object = *It;
		if(object->GetType() == SketchType)
		{
			std::list<HeeksObj*> s;
			s.push_back(object);
			TopoDS_Wire wire;
			if(ConvertLineArcsToWire2(s, wire))
			{
				wire_list.push_back(wire);
			}
		}
	}

	TopoDS_Shape shape;
	if(CreateRuledSurface(wire_list, shape, make_solid))
	{
		return CShape::MakeObject(shape, _("Ruled Surface"), SOLID_TYPE_UNKNOWN, HeeksColor(51, 45, 51));
	}
	return NULL;
}

static void on_extrude_to_solid(bool onoff, HeeksObj* object)
{
	wxGetApp().m_extrude_to_solid = onoff;
	HeeksConfig config;
	config.Write(_T("ExtrudeToSolid"), wxGetApp().m_extrude_to_solid);
}

class CExtrusionInput:public CLengthInput
{
public:
	CExtrusionInput(double &value):CLengthInput(_("Input extrusion height"), _("height"), value){}

	// virtual functions for InputMode
	void GetProperties(std::list<Property *> *list)
	{
		CLengthInput::GetProperties(list);
		list->push_back(new PropertyCheck(_("Extrude makes a solid"), wxGetApp().m_extrude_to_solid, NULL, on_extrude_to_solid));
	}
};

bool InputExtrusionHeight(double &value)
{
	CInputMode* save_mode = wxGetApp().input_mode_object;
	CExtrusionInput extrusion_input(value);
	wxGetApp().SetInputMode(&extrusion_input);

	wxGetApp().OnRun();

	wxGetApp().SetInputMode(save_mode);

	if(CLengthInput::m_success)value = extrusion_input.m_value;

	return CLengthInput::m_success;
}

void PickCreateExtrusion()
{
	if(wxGetApp().m_marked_list->size() == 0)
	{
		wxGetApp().PickObjects(_("pick sketches, faces or circles"), MARKING_FILTER_CIRCLE | MARKING_FILTER_SKETCH | MARKING_FILTER_FACE);
	}

	double height = 10; // to do, this should get written to config file

	if(InputExtrusionHeight(height))
	{
		if(wxGetApp().m_marked_list->size() > 0)
		{
			CreateExtrusionOrRevolution(wxGetApp().m_marked_list->list(),height, wxGetApp().m_extrude_to_solid, false);
		}
	}
}

class CRevolutionInput:public CDoubleInput
{
public:
	CRevolutionInput(double &value):CDoubleInput(_("Input revolution angle"), _("angle"), value){}

	// virtual functions for InputMode
	void GetProperties(std::list<Property *> *list)
	{
		CDoubleInput::GetProperties(list);
		list->push_back(new PropertyCheck(_("Extrude makes a solid"), wxGetApp().m_extrude_to_solid, NULL, on_extrude_to_solid));
	}
};

void PickCreateRevolution()
{
	if(wxGetApp().m_marked_list->size() == 0)
	{
		wxGetApp().PickObjects(_("pick sketches, faces or circles"), MARKING_FILTER_CIRCLE | MARKING_FILTER_SKETCH | MARKING_FILTER_FACE);
	}

	double angle = 360.0; // to do, this should get written to config file

	if(wxGetApp().InputDouble(_("Input revolution angle"), _("angle"), angle))
	{
		if(wxGetApp().m_marked_list->size() > 0)
		{
			CreateExtrusionOrRevolution(wxGetApp().m_marked_list->list(), angle, true, true);
		}
	}
}

bool CreateRuledSurface(const std::list<TopoDS_Wire> &wire_list, TopoDS_Shape& shape, bool make_solid)
{
	if(wire_list.size() > 0)
	{
			BRepOffsetAPI_ThruSections generator( make_solid ? Standard_True : Standard_False, Standard_False );
			for(std::list<TopoDS_Wire>::const_iterator It = wire_list.begin(); It != wire_list.end(); It++)
			{
				const TopoDS_Wire &wire = *It;
				generator.AddWire(wire);
			}

		try{
			generator.Build();
			shape = generator.Shape();
		}
		catch (Standard_Failure) {
			Handle_Standard_Failure e = Standard_Failure::Caught();
			wxMessageBox(wxString(_("Error making ruled solid")) + _T(": ") + Ctt(e->GetMessageString()));
			return false;
		}
		catch(...)
		{
			wxMessageBox(_("Fatal error making ruled solid"));
			return false;
		}

		return true;
	}
	return false;
}

void CreateExtrusions(const std::list<TopoDS_Shape> &faces_or_wires, std::list<TopoDS_Shape>& new_shapes, const gp_Vec& extrude_vector)
{
	try{
		for(std::list<TopoDS_Shape>::const_iterator It = faces_or_wires.begin(); It != faces_or_wires.end(); It++)
		{
			const TopoDS_Shape& face_or_wire = *It;
			BRepPrimAPI_MakePrism generator( face_or_wire, extrude_vector );
			generator.Build();
			new_shapes.push_back(generator.Shape());
		}
	}
	catch (Standard_Failure) {
		Handle_Standard_Failure e = Standard_Failure::Caught();
		wxMessageBox(wxString(_("Error making extruded solid")) + _T(": ") + Ctt(e->GetMessageString()));
	}
	catch(...)
	{
		wxMessageBox(_("Fatal error making extruded solid"));
	}

}

void CreateRevolutions(const std::list<TopoDS_Shape> &faces_or_wires, std::list<TopoDS_Shape>& new_shapes, const gp_Ax1& axis, double angle)
{
	try{
		for(std::list<TopoDS_Shape>::const_iterator It = faces_or_wires.begin(); It != faces_or_wires.end(); It++)
		{
			const TopoDS_Shape& face_or_wire = *It;
			if(fabs(angle - 360.0) < 0.00001)
			{
				BRepPrimAPI_MakeRevol generator( face_or_wire, axis );
				generator.Build();
				new_shapes.push_back(generator.Shape());
			}
			else
			{
				BRepPrimAPI_MakeRevol generator( face_or_wire, axis, angle * Pi/180 );
				generator.Build();
				new_shapes.push_back(generator.Shape());
			}
		}
	}
	catch (Standard_Failure) {
		Handle_Standard_Failure e = Standard_Failure::Caught();
		wxMessageBox(wxString(_("Error making revolved solid")) + _T(": ") + Ctt(e->GetMessageString()));
	}
	catch(...)
	{
		wxMessageBox(_("Fatal error making revolved solid"));
	}

}

<|endoftext|>


<commit_before>// Licence 2

#include <cstring>
#include <stdlib.h>
#include <sstream>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include "include/dart_api.h"
#include "include/dart_native_api.h"

Dart_Handle NewDartExceptionWithMessage(const char* library_url,
                                        const char* exception_name,
                                        const char* message);
/*
Called the first time a native function with a given name is called,
 to resolve the Dart name of the native function into a C function pointer.
*/
Dart_NativeFunction ResolveName(Dart_Handle name, int argc);

Dart_Handle HandleError(Dart_Handle handle);

enum METHOD_CODE {
  OPEN = 1,
  CLOSE = 2,
  READ = 3,
  WRITE = 4
};

int selectBaudrate(int baudrate_speed){
  switch(baudrate_speed){
    // TODO baudrate 0 ? B0
    case 50: return B50; break;
    case 75: return B75; break;
    case 110: return B110; break;
    case 134: return B134; break;
    case 150: return B150; break;
    case 200: return B200; break;
    case 300: return B300; break;
    case 600: return B600; break;
    case 1200: return B1200; break;
    case 1800: return B1800; break;
    case 2400: return B2400; break;
    case 4800: return B4800; break;
    case 9600: return B9600; break;
    case 19200: return B19200; break;
    case 38400: return B38400; break;
    case 57600: return B57600; break;
    case 115200: return B115200; break;
    case 230400: return B230400; break;
    #ifdef B460800
    case 460800: return B460800;break;
    #endif
    #ifdef B500000
    case 500000: return B500000; break;
    #endif
    #ifdef B576000
    case 576000: return B576000; break;
    #endif
    #ifdef B921600
    case 921600: return B921600; break;
    #endif
    #ifdef B1000000
    case 1000000: return B1000000; break;
    #endif
    #ifdef B1152000
    case 1152000: return B1152000; break;
    #endif
    #ifdef B1500000
    case 1500000: return B1500000; break;
    #endif
    #ifdef B2000000
    case 2000000: return B2000000; break;
    #endif
    #ifdef B2500000
    case 2500000: return B2500000; break;
    #endif
    #ifdef B3000000
    case 3000000: return B3000000; break;
    #endif
    #ifdef B3500000
    case 3500000: return B3500000; break;
    #endif
    #ifdef B4000000
    case 4000000: return B4000000; break;
    #endif
    #ifdef B7200
    case 7200: return B7200; break;
    #endif
    #ifdef B14400
    case 14400: return B14400; break;
    #endif
    #ifdef B28800
    case 28800: return B28800; break;
    #endif
    #ifdef B76800
    case 76800: return B76800; break;
    #endif
    default: return -1;
  }
}

int selectDataBits(int dataBits) {
  switch (dataBits) {
    case 5: return CS5;
    case 6: return CS6;
    case 7: return CS7;
    case 8: return CS8;
    default: return -1;
  }
}

int64_t openAsync(const char* portname, speed_t baudrate, int databits){
  // Open serial port
  struct termios tio;
  memset(&tio, 0, sizeof(tio));
  tio.c_iflag=0;
  tio.c_oflag= IGNPAR;
  tio.c_cflag= databits | CREAD | CLOCAL | HUPCL;
  tio.c_lflag=0;
  tio.c_cc[VMIN]=1;
  tio.c_cc[VTIME]=0;

  int tty_fd = open(portname, O_RDWR | O_NOCTTY | O_NONBLOCK);
  if(tty_fd > 0) {
    cfsetospeed(&tio, baudrate);
    cfsetispeed(&tio, baudrate);
    tcflush(tty_fd, TCIFLUSH);
    tcsetattr(tty_fd, TCSANOW, &tio);
  }
  return tty_fd;
}

int closeAsync(int64_t tty_fd){
  return close(tty_fd);
}

int sendAsync(int64_t tty_fd, const char* data){
  return write(tty_fd, data, strlen(data));
}

// TODO maybe check type
//   result.type = Dart_CObject_kNull;
void wrappedSerialPortServicePort(Dart_Port send_port_id, Dart_CObject* message){
 Dart_Port reply_port_id = message->value.as_array.values[0]->value.as_send_port;

 Dart_CObject result;
 result.type = Dart_CObject_kArray;
 result.value.as_array.length = 2;

 Dart_CObject* error_message = (Dart_CObject*) malloc(sizeof(Dart_CObject_kString));
 error_message->type = Dart_CObject_kString;
 error_message->value.as_string =  (char*) "";
 result.value.as_array.values[1] = error_message;

 Dart_CObject dart_null;
 dart_null.type = Dart_CObject_kNull;

 int argc = message->value.as_array.length - 1;
 Dart_CObject** argv = message->value.as_array.values + 1;
 int64_t method_code = (int) argv[0]->value.as_int64;
 argv++;
 argc--;
 // TODO return a array : [result, "message"]
 // TODO replace by switch
 // TODO check args nb
 // TODO method return a Dart_CObject result
 // TODO switch
 if(method_code == OPEN) {
   //Dart_CObject* param0 = message->value.as_array.values[0];
   //Dart_CObject* param1 = message->value.as_array.values[1];
   const char* portname = argv[0]->value.as_string;
   int64_t baudrate_speed = argv[1]->value.as_int64;
   int64_t databits_nb = argv[2]->value.as_int64;
   int baudrate = selectBaudrate(baudrate_speed);
   int databits = selectDataBits(databits_nb);

   if(baudrate == -1){
     result.value.as_array.values[0] = &dart_null;
     error_message->value.as_string = (char*) "Invalid baudrate";
   } else if(databits == -1) {
     result.value.as_array.values[0] = &dart_null;
     error_message->value.as_string = (char*) "Invalid databits";
   } else {
     int64_t tty_fd = openAsync(portname, baudrate, databits);
     if(tty_fd < 0){
       // TODO errno
       result.value.as_array.values[0] = &dart_null;
       error_message->value.as_string = (char*) "Invalid access";
     } else {
       Dart_CObject dart_result;
       dart_result.type = Dart_CObject_kInt64;
       dart_result.value.as_int64 = tty_fd;
       result.value.as_array.values[0] = &dart_result;
     }

   }
  } else if(method_code == CLOSE) {
   int64_t tty_fd = argv[0]->value.as_int64;

   // TODO code close
   closeAsync(tty_fd);

   Dart_CObject dart_result;
   dart_result.type = Dart_CObject_kBool;
   dart_result.value.as_bool = true;
   result.value.as_array.values[0] = &dart_result;

  } else if(method_code == WRITE) {
   int64_t tty_fd = argv[0]->value.as_int64;

   // TODO int[]
   const char* data = argv[1]->value.as_string;

   int value = sendAsync(tty_fd, data);

   Dart_CObject dart_result;
   dart_result.type = Dart_CObject_kInt64;
   dart_result.value.as_int64 = value;
   result.value.as_array.values[0] = &dart_result;

  } else if(method_code == READ) {
   int64_t tty_fd = argv[0]->value.as_int64;
   int buffer_size = (int) argv[1]->value.as_int64;
   int8_t buffer[buffer_size];
   fd_set readfs;
   FD_ZERO(&readfs);
   FD_SET(tty_fd, &readfs);
   select(tty_fd+1, &readfs, NULL, NULL, NULL);
   int n =  read(tty_fd, &buffer, sizeof(buffer));
   if(n > 0){

     Dart_CObject dart_result;
     dart_result.type = Dart_CObject_kArray;
     dart_result.value.as_array.length = n;

     for(int i=0; i<n; i++){
       // TODO without pointer ?
       Dart_CObject* v = (Dart_CObject*) malloc(sizeof(Dart_CObject_kInt32));
       v->type = Dart_CObject_kInt32;
       v->value.as_int32 = buffer[i];
       dart_result.value.as_array.values[i] = v;
     }

     result.value.as_array.values[0] = &dart_result;

    } else {
      result.type = Dart_CObject_kNull;
    }
  } else {
    result.value.as_array.values[0] = &dart_null;
    error_message->value.as_string = (char*) "Unknow method";
  }
  Dart_PostCObject(reply_port_id, &result);
}

void serialPortServicePort(Dart_NativeArguments arguments) {
  Dart_EnterScope();
  Dart_SetReturnValue(arguments, Dart_Null());
  Dart_Port service_port = Dart_NewNativePort("SerialPortServicePort", wrappedSerialPortServicePort, true);
  if (service_port != ILLEGAL_PORT) {
    Dart_Handle send_port = HandleError(Dart_NewSendPort(service_port));
    Dart_SetReturnValue(arguments, send_port);
  }
  Dart_ExitScope();
}

DART_EXPORT Dart_Handle serial_port_Init(Dart_Handle parent_library) {
  if (Dart_IsError(parent_library)) { return parent_library; }

  Dart_Handle result_code = Dart_SetNativeResolver(parent_library, ResolveName);
  if (Dart_IsError(result_code)) return result_code;

  return Dart_Null();
}

Dart_NativeFunction ResolveName(Dart_Handle name, int argc) {
  // If we fail, we return NULL, and Dart throws an exception.
  if (!Dart_IsString(name)) return NULL;
  Dart_NativeFunction result = NULL;
  Dart_EnterScope();
  const char* cname;
  HandleError(Dart_StringToCString(name, &cname));

  if (strcmp("serialPortServicePort", cname) == 0) result = serialPortServicePort;

  Dart_ExitScope();
  return result;
}

Dart_Handle HandleError(Dart_Handle handle) {
  if (Dart_IsError(handle)) Dart_PropagateError(handle);
  return handle;
}

Dart_Handle NewDartExceptionWithMessage(const char* library_url,
                                        const char* exception_name,
                                        const char* message) {
  // Create a Dart Exception object with a message.
  Dart_Handle type = Dart_GetType(Dart_LookupLibrary(
      Dart_NewStringFromCString(library_url)),
      Dart_NewStringFromCString(exception_name), 0, NULL);

  if (Dart_IsError(type)) {
    Dart_PropagateError(type);
  }
  if (message != NULL) {
    Dart_Handle args[1];
    args[0] = Dart_NewStringFromCString(message);
    if (Dart_IsError(args[0])) {
      Dart_PropagateError(args[0]);
    }
    return Dart_New(type, Dart_Null(), 1, args);
  } else {
    return Dart_New(type, Dart_Null(), 0, NULL);
  }

}
<commit_msg>write<commit_after>// Licence 2

#include <cstring>
#include <stdlib.h>
#include <sstream>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include "include/dart_api.h"
#include "include/dart_native_api.h"

Dart_Handle NewDartExceptionWithMessage(const char* library_url,
                                        const char* exception_name,
                                        const char* message);
/*
Called the first time a native function with a given name is called,
 to resolve the Dart name of the native function into a C function pointer.
*/
Dart_NativeFunction ResolveName(Dart_Handle name, int argc);

Dart_Handle HandleError(Dart_Handle handle);

enum METHOD_CODE {
  OPEN = 1,
  CLOSE = 2,
  READ = 3,
  WRITE = 4
};

int selectBaudrate(int baudrate_speed){
  switch(baudrate_speed){
    // TODO baudrate 0 ? B0
    case 50: return B50; break;
    case 75: return B75; break;
    case 110: return B110; break;
    case 134: return B134; break;
    case 150: return B150; break;
    case 200: return B200; break;
    case 300: return B300; break;
    case 600: return B600; break;
    case 1200: return B1200; break;
    case 1800: return B1800; break;
    case 2400: return B2400; break;
    case 4800: return B4800; break;
    case 9600: return B9600; break;
    case 19200: return B19200; break;
    case 38400: return B38400; break;
    case 57600: return B57600; break;
    case 115200: return B115200; break;
    case 230400: return B230400; break;
    #ifdef B460800
    case 460800: return B460800;break;
    #endif
    #ifdef B500000
    case 500000: return B500000; break;
    #endif
    #ifdef B576000
    case 576000: return B576000; break;
    #endif
    #ifdef B921600
    case 921600: return B921600; break;
    #endif
    #ifdef B1000000
    case 1000000: return B1000000; break;
    #endif
    #ifdef B1152000
    case 1152000: return B1152000; break;
    #endif
    #ifdef B1500000
    case 1500000: return B1500000; break;
    #endif
    #ifdef B2000000
    case 2000000: return B2000000; break;
    #endif
    #ifdef B2500000
    case 2500000: return B2500000; break;
    #endif
    #ifdef B3000000
    case 3000000: return B3000000; break;
    #endif
    #ifdef B3500000
    case 3500000: return B3500000; break;
    #endif
    #ifdef B4000000
    case 4000000: return B4000000; break;
    #endif
    #ifdef B7200
    case 7200: return B7200; break;
    #endif
    #ifdef B14400
    case 14400: return B14400; break;
    #endif
    #ifdef B28800
    case 28800: return B28800; break;
    #endif
    #ifdef B76800
    case 76800: return B76800; break;
    #endif
    default: return -1;
  }
}

int selectDataBits(int dataBits) {
  switch (dataBits) {
    case 5: return CS5;
    case 6: return CS6;
    case 7: return CS7;
    case 8: return CS8;
    default: return -1;
  }
}

int64_t openAsync(const char* portname, speed_t baudrate, int databits){
  // Open serial port
  struct termios tio;
  memset(&tio, 0, sizeof(tio));
  tio.c_iflag=0;
  tio.c_oflag= IGNPAR;
  tio.c_cflag= databits | CREAD | CLOCAL | HUPCL;
  tio.c_lflag=0;
  tio.c_cc[VMIN]=1;
  tio.c_cc[VTIME]=0;

  int tty_fd = open(portname, O_RDWR | O_NOCTTY | O_NONBLOCK);
  if(tty_fd > 0) {
    cfsetospeed(&tio, baudrate);
    cfsetispeed(&tio, baudrate);
    tcflush(tty_fd, TCIFLUSH);
    tcsetattr(tty_fd, TCSANOW, &tio);
  }
  return tty_fd;
}

int closeAsync(int64_t tty_fd){
  return close(tty_fd);
}

int sendAsync(int64_t tty_fd, const char* data){
  return write(tty_fd, data, strlen(data));
}

// TODO maybe check type
//   result.type = Dart_CObject_kNull;
void wrappedSerialPortServicePort(Dart_Port send_port_id, Dart_CObject* message){
 Dart_Port reply_port_id = message->value.as_array.values[0]->value.as_send_port;

 Dart_CObject result;
 result.type = Dart_CObject_kArray;
 result.value.as_array.length = 2;

 Dart_CObject* error_message = (Dart_CObject*) malloc(sizeof(Dart_CObject_kString));
 error_message->type = Dart_CObject_kString;
 error_message->value.as_string =  (char*) "";
 result.value.as_array.values[1] = error_message;

 Dart_CObject dart_null;
 dart_null.type = Dart_CObject_kNull;

 int argc = message->value.as_array.length - 1;
 Dart_CObject** argv = message->value.as_array.values + 1;
 int64_t method_code = (int) argv[0]->value.as_int64;
 argv++;
 argc--;
 // TODO return a array : [result, "message"]
 // TODO replace by switch
 // TODO check args nb
 // TODO method return a Dart_CObject result
 // TODO switch
 if(method_code == OPEN) {
   //Dart_CObject* param0 = message->value.as_array.values[0];
   //Dart_CObject* param1 = message->value.as_array.values[1];
   const char* portname = argv[0]->value.as_string;
   int64_t baudrate_speed = argv[1]->value.as_int64;
   int64_t databits_nb = argv[2]->value.as_int64;
   int baudrate = selectBaudrate(baudrate_speed);
   int databits = selectDataBits(databits_nb);

   if(baudrate == -1){
     result.value.as_array.values[0] = &dart_null;
     error_message->value.as_string = (char*) "Invalid baudrate";
   } else if(databits == -1) {
     result.value.as_array.values[0] = &dart_null;
     error_message->value.as_string = (char*) "Invalid databits";
   } else {
     int64_t tty_fd = openAsync(portname, baudrate, databits);
     if(tty_fd < 0){
       // TODO errno
       result.value.as_array.values[0] = &dart_null;
       error_message->value.as_string = (char*) "Invalid access";
     } else {
       Dart_CObject dart_result;
       dart_result.type = Dart_CObject_kInt64;
       dart_result.value.as_int64 = tty_fd;
       result.value.as_array.values[0] = &dart_result;
     }

   }
  } else if(method_code == CLOSE) {
   int64_t tty_fd = argv[0]->value.as_int64;

   // TODO code close
   closeAsync(tty_fd);

   Dart_CObject dart_result;
   dart_result.type = Dart_CObject_kBool;
   dart_result.value.as_bool = true;
   result.value.as_array.values[0] = &dart_result;

  } else if(method_code == WRITE) {
   int64_t tty_fd = argv[0]->value.as_int64;

   // TODO int[]
   const char* data = argv[1]->value.as_string;

   int value = sendAsync(tty_fd, data);

   Dart_CObject dart_result;
   dart_result.type = Dart_CObject_kInt64;
   dart_result.value.as_int64 = value;
   result.value.as_array.values[0] = &dart_result;

  } else if(method_code == READ) {
   int64_t tty_fd = argv[0]->value.as_int64;
   int buffer_size = (int) argv[1]->value.as_int64;
   int8_t buffer[buffer_size];
   fd_set readfs;
   FD_ZERO(&readfs);
   FD_SET(tty_fd, &readfs);
   select(tty_fd+1, &readfs, NULL, NULL, NULL);
   int n =  read(tty_fd, &buffer, sizeof(buffer));
   if(n > 0){

     result.type = Dart_CObject_kArray;
     result.value.as_array.length = n;

     for(int i=0; i<n; i++){
       Dart_CObject* byte = (Dart_CObject*) malloc(sizeof(Dart_CObject_kInt32));
       byte->type = Dart_CObject_kInt32;
       byte->value.as_int32 = buffer[i];
       result.value.as_array.values[i] = byte;
     }

    } else {
      result.type = Dart_CObject_kNull;
    }
  } else {
    result.value.as_array.values[0] = &dart_null;
    error_message->value.as_string = (char*) "Unknow method";
  }
  Dart_PostCObject(reply_port_id, &result);
}

void serialPortServicePort(Dart_NativeArguments arguments) {
  Dart_EnterScope();
  Dart_SetReturnValue(arguments, Dart_Null());
  Dart_Port service_port = Dart_NewNativePort("SerialPortServicePort", wrappedSerialPortServicePort, true);
  if (service_port != ILLEGAL_PORT) {
    Dart_Handle send_port = HandleError(Dart_NewSendPort(service_port));
    Dart_SetReturnValue(arguments, send_port);
  }
  Dart_ExitScope();
}

DART_EXPORT Dart_Handle serial_port_Init(Dart_Handle parent_library) {
  if (Dart_IsError(parent_library)) { return parent_library; }

  Dart_Handle result_code = Dart_SetNativeResolver(parent_library, ResolveName);
  if (Dart_IsError(result_code)) return result_code;

  return Dart_Null();
}

Dart_NativeFunction ResolveName(Dart_Handle name, int argc) {
  // If we fail, we return NULL, and Dart throws an exception.
  if (!Dart_IsString(name)) return NULL;
  Dart_NativeFunction result = NULL;
  Dart_EnterScope();
  const char* cname;
  HandleError(Dart_StringToCString(name, &cname));

  if (strcmp("serialPortServicePort", cname) == 0) result = serialPortServicePort;

  Dart_ExitScope();
  return result;
}

Dart_Handle HandleError(Dart_Handle handle) {
  if (Dart_IsError(handle)) Dart_PropagateError(handle);
  return handle;
}

Dart_Handle NewDartExceptionWithMessage(const char* library_url,
                                        const char* exception_name,
                                        const char* message) {
  // Create a Dart Exception object with a message.
  Dart_Handle type = Dart_GetType(Dart_LookupLibrary(
      Dart_NewStringFromCString(library_url)),
      Dart_NewStringFromCString(exception_name), 0, NULL);

  if (Dart_IsError(type)) {
    Dart_PropagateError(type);
  }
  if (message != NULL) {
    Dart_Handle args[1];
    args[0] = Dart_NewStringFromCString(message);
    if (Dart_IsError(args[0])) {
      Dart_PropagateError(args[0]);
    }
    return Dart_New(type, Dart_Null(), 1, args);
  } else {
    return Dart_New(type, Dart_Null(), 0, NULL);
  }

}
<|endoftext|>


<commit_before>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2012-2015 Inviwo Foundation
 * 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 <warn/push>
#include <warn/ignore/all>
#include <QFile>
#include <warn/pop>
#include <inviwo/qt/widgets/inviwoapplicationqt.h>
#include <inviwo/core/common/defaulttohighperformancegpu.h>
#include <inviwo/core/util/commandlineparser.h>
#include <inviwo/core/util/filesystem.h>
#include <inviwo/core/util/logcentral.h>
#include <inviwo/qt/editor/inviwomainwindow.h>
#include "inviwosplashscreen.h"
#include <moduleregistration.h>

int main(int argc, char** argv) {
    std::string basePath = inviwo::filesystem::findBasePath();

    inviwo::LogCentral::init();
    inviwo::LogCentral::getPtr()->registerLogger(new inviwo::FileLogger(basePath));
    inviwo::InviwoApplicationQt inviwoApp("Inviwo v" + IVW_VERSION, argc, argv);
    inviwoApp.setWindowIcon(QIcon(":/icons/inviwo_light.png"));
    inviwoApp.setAttribute(Qt::AA_NativeWindows);
    QFile styleSheetFile(":/stylesheets/inviwo.qss");
    styleSheetFile.open(QFile::ReadOnly);
    QString styleSheet = QString::fromUtf8(styleSheetFile.readAll());
    inviwoApp.setStyleSheet(styleSheet);
    styleSheetFile.close();

    auto& clp = inviwoApp.getCommandLineParser();

    inviwo::InviwoMainWindow mainWin(&inviwoApp);
    // setup core application
    inviwoApp.setMainWindow(&mainWin);
    // initialize and show splash screen
    inviwo::InviwoSplashScreen splashScreen(&mainWin, clp.getShowSplashScreen());
    inviwoApp.setProgressCallback([&splashScreen](std::string s) { splashScreen.showMessage(s); });

    splashScreen.show();
    splashScreen.showMessage("Loading application...");

    // Initialize application and register modules
    splashScreen.showMessage("Initializing modules...");
    inviwoApp.registerModules(&inviwo::registerAllModules);
    inviwoApp.processEvents();

    // Do this after registerModules if some arguments were added
    clp.parse(inviwo::CommandLineParser::Mode::Normal);

    // setup main window
    mainWin.initialize();
    inviwoApp.processEvents();
    splashScreen.showMessage("Loading workspace...");
    inviwoApp.processEvents();
    mainWin.showWindow();
    inviwoApp.processEvents();  // Make sure the gui is done loading before loading workspace

    mainWin.openLastWorkspace(clp.getWorkspacePath());  // open last workspace
    splashScreen.finish(&mainWin);

    inviwoApp.processEvents();
    clp.processCallbacks(); // run any command line callbacks from modules.
    inviwoApp.processEvents();

    // process last arguments
    if (!clp.getQuitApplicationAfterStartup()) {
        return inviwoApp.exec();
    } else {
        mainWin.exitInviwo(false);
        return 0;
    }
}
<commit_msg>apps: fixed crash on exit due to processor widget ownership<commit_after>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2012-2015 Inviwo Foundation
 * 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 <warn/push>
#include <warn/ignore/all>
#include <QFile>
#include <warn/pop>
#include <inviwo/qt/widgets/inviwoapplicationqt.h>
#include <inviwo/core/common/defaulttohighperformancegpu.h>
#include <inviwo/core/util/commandlineparser.h>
#include <inviwo/core/util/filesystem.h>
#include <inviwo/core/util/logcentral.h>
#include <inviwo/core/util/raiiutils.h>
#include <inviwo/core/network/processornetwork.h>
#include <inviwo/qt/editor/inviwomainwindow.h>
#include "inviwosplashscreen.h"
#include <moduleregistration.h>

int main(int argc, char** argv) {
    std::string basePath = inviwo::filesystem::findBasePath();

    inviwo::LogCentral::init();
    inviwo::LogCentral::getPtr()->registerLogger(new inviwo::FileLogger(basePath));
    inviwo::InviwoApplicationQt inviwoApp("Inviwo v" + IVW_VERSION, argc, argv);
    inviwoApp.setWindowIcon(QIcon(":/icons/inviwo_light.png"));
    inviwoApp.setAttribute(Qt::AA_NativeWindows);
    QFile styleSheetFile(":/stylesheets/inviwo.qss");
    styleSheetFile.open(QFile::ReadOnly);
    QString styleSheet = QString::fromUtf8(styleSheetFile.readAll());
    inviwoApp.setStyleSheet(styleSheet);
    styleSheetFile.close();

    auto& clp = inviwoApp.getCommandLineParser();

    inviwo::InviwoMainWindow mainWin(&inviwoApp);
    // setup core application
    inviwoApp.setMainWindow(&mainWin);
    // initialize and show splash screen
    inviwo::InviwoSplashScreen splashScreen(&mainWin, clp.getShowSplashScreen());
    inviwoApp.setProgressCallback([&splashScreen](std::string s) { splashScreen.showMessage(s); });

    splashScreen.show();
    splashScreen.showMessage("Loading application...");

    // Initialize application and register modules
    splashScreen.showMessage("Initializing modules...");
    inviwoApp.registerModules(&inviwo::registerAllModules);
    inviwoApp.processEvents();

    // Do this after registerModules if some arguments were added
    clp.parse(inviwo::CommandLineParser::Mode::Normal);

    // setup main window
    mainWin.initialize();
    inviwoApp.processEvents();
    splashScreen.showMessage("Loading workspace...");
    inviwoApp.processEvents();
    mainWin.showWindow();
    inviwoApp.processEvents();  // Make sure the gui is done loading before loading workspace

    mainWin.openLastWorkspace(clp.getWorkspacePath());  // open last workspace
    splashScreen.finish(&mainWin);

    inviwoApp.processEvents();
    clp.processCallbacks(); // run any command line callbacks from modules.
    inviwoApp.processEvents();

    inviwo::util::OnScopeExit clearNetwork([&](){
        inviwoApp.getProcessorNetwork()->clear();
    });

    // process last arguments
    if (!clp.getQuitApplicationAfterStartup()) {
        return inviwoApp.exec();
    }
    else {
        mainWin.exitInviwo(false);
        return 0;
    }
}
<|endoftext|>


<commit_before>#include "SoundManager.hpp"

//Mix_Chunk *SoundManager::effect;
//x_Chunk *SoundManager::bgmusic;
//int SoundManager::audio_channels, SoundManager::audio_rate,
// SoundManager::audio_buffers;
//Uint16 SoundManager::audio_format;
SoundManager *SoundManager::s = NULL;

SoundManager::SoundManager(void){
  audio_rate = 44100;
  audio_format = MIX_DEFAULT_FORMAT;
  audio_channels = 2;
  Mix_AllocateChannels(8);
  audio_buffers = 4096;
  bgmusic = NULL;
  //effect = NULL;
  if(Mix_OpenAudio(audio_rate, audio_format,
		   audio_channels, audio_buffers)){
    std::cerr<<"unable to initiate Sound"<<std::endl;
  }
  LoadSound(DOT, "resources/sounds/bubble.wav");
  LoadSound(POWERUP, "resources/sounds/powerup.wav");
  LoadSound(GHOST, "resources/sounds/munch.wav");
  LoadSound(GAMEOVER, "resources/sounds/gameover.wav");
  LoadSound(BONUS, "resources/sounds/blibli.wav");
  // one more ghost
}

SoundManager *SoundManager::Singleton(void){
  //s.bgmusic = NULL;
  //inits
  if(!s)
    s=new SoundManager();
  return s;
}

//Playing main background music
// -1 for infinite repeats
void SoundManager::Play(int channel, char *file, int repeats){
  bgmusic = Mix_LoadWAV(file);
  Mix_FadeInChannel(channel, bgmusic, repeats, 3000);
  Mix_VolumeChunk(bgmusic, 0);
}

void SoundManager::MuteChannel(int channelnum){
  Mix_VolumeChunk(Mix_GetChunk(channelnum),0);
}

void SoundManager::lolChannel(int channelnum, int volume){
  Mix_VolumeChunk(Mix_GetChunk(channelnum),0 );
}

void SoundManager::Stop(){
  //stops the music

   Mix_FreeChunk(bgmusic);
  //freeing the pointer
  //Mix_FreeMusic(bgmusic);
  bgmusic = NULL;
}

void SoundManager::ChangeState(){
  if(Mix_PausedMusic())
    Mix_ResumeMusic();
  else
    Mix_PauseMusic();
}
void SoundManager::LoadSound(sound_t _sound, char *file){
  effect[_sound] = Mix_LoadWAV(file);
}

void SoundManager::PlayEffect(int channel, sound_t _sound){
  if(effect[_sound])
    Mix_PlayChannel(channel, effect[_sound], 0);
}

void SoundManager::StopEffect(){
  for(int i=0;i<CHUNKS;++i)
    Mix_FreeChunk(effect[i]);
}
<commit_msg>hahahah<commit_after>#include "SoundManager.hpp"

//Mix_Chunk *SoundManager::effect;
//x_Chunk *SoundManager::bgmusic;
//int SoundManager::audio_channels, SoundManager::audio_rate,
// SoundManager::audio_buffers;
//Uint16 SoundManager::audio_format;
SoundManager *SoundManager::s = NULL;

SoundManager::SoundManager(void){
  audio_rate = 44100;
  audio_format = MIX_DEFAULT_FORMAT;
  audio_channels = 2;
  Mix_AllocateChannels(8);
  audio_buffers = 4096;
  bgmusic = NULL;
  //effect = NULL;
  if(Mix_OpenAudio(audio_rate, audio_format,
		   audio_channels, audio_buffers)){
    std::cerr<<"unable to initiate Sound"<<std::endl;
  }
  LoadSound(DOT, "resources/sounds/bubble.wav");
  LoadSound(POWERUP, "resources/sounds/powerup.wav");
  LoadSound(GHOST, "resources/sounds/munch.wav");
  LoadSound(GAMEOVER, "resources/sounds/gameover.wav");
  LoadSound(BONUS, "resources/sounds/blibli.wav");
  // one more ghost
}

SoundManager *SoundManager::Singleton(void){
  //s.bgmusic = NULL;
  //inits
  if(!s)
    s=new SoundManager();
  return s;
}

//Playing main background music
// -1 for infinite repeats
void SoundManager::Play(int channel, char *file, int repeats){
  bgmusic = Mix_LoadWAV(file);
  Mix_FadeInChannel(channel, bgmusic, repeats, 3000);
  Mix_VolumeChunk(bgmusic, 64);
}

void SoundManager::MuteChannel(int channelnum){
  Mix_VolumeChunk(Mix_GetChunk(channelnum),0);
}

void SoundManager::lolChannel(int channelnum, int volume){
  Mix_VolumeChunk(Mix_GetChunk(channelnum),64 );
}

void SoundManager::Stop(){
  //stops the music

   Mix_FreeChunk(bgmusic);
  //freeing the pointer
  //Mix_FreeMusic(bgmusic);
  bgmusic = NULL;
}

void SoundManager::ChangeState(){
  if(Mix_PausedMusic())
    Mix_ResumeMusic();
  else
    Mix_PauseMusic();
}
void SoundManager::LoadSound(sound_t _sound, char *file){
  effect[_sound] = Mix_LoadWAV(file);
}

void SoundManager::PlayEffect(int channel, sound_t _sound){
  if(effect[_sound])
    Mix_PlayChannel(channel, effect[_sound], 0);
}

void SoundManager::StopEffect(){
  for(int i=0;i<CHUNKS;++i)
    Mix_FreeChunk(effect[i]);
}
<|endoftext|>


<commit_before>// Copyright 2016 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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 <vector>
#include <iostream>
#include <exception>
#include <iomanip>
#include <random>
#include <algorithm>

#include <configuration.hpp>

#include <ArgumentList.hpp>
#include <InitializeOpenCL.hpp>
#include <Kernel.hpp>
#include <Stencil.hpp>
#include <utils.hpp>
#include <Timer.hpp>
#include <Stats.hpp>

void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< inputDataType > * input, cl::Buffer * input_d, cl::Buffer * output_d, const unsigned int outputSize);

int main(int argc, char * argv[]) {
  bool reInit = true;
  unsigned int nrIterations = 0;
  unsigned int samplingFactor = 100;
  unsigned int clPlatformID = 0;
  unsigned int clDeviceID = 0;
  unsigned int vectorSize = 0;
  unsigned int maxThreads = 0;
  unsigned int maxItems = 0;
  unsigned int matrixWidth = 0;
  unsigned int padding = 0;
  // Random number generation
  std::random_device randomDevice;
  std::default_random_engine randomEngine(randomDevice());
  std::uniform_int_distribution<unsigned int> uniformDistribution(0, magicValue);

  try {
    isa::utils::ArgumentList args(argc, argv);

    clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform");
    clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device");
    if ( args.getSwitch("-sampling") ) {
      samplingFactor = args.getSwitchArgument< unsigned int >("-factor");
    }
    nrIterations = args.getSwitchArgument< unsigned int >("-iterations");
    vectorSize = args.getSwitchArgument< unsigned int >("-vector");
    padding = args.getSwitchArgument< unsigned int >("-padding");
    maxThreads = args.getSwitchArgument< unsigned int >("-max_threads");
    maxItems = args.getSwitchArgument< unsigned int >("-max_items");
    matrixWidth = args.getSwitchArgument< unsigned int >("-matrix_width");
  } catch ( isa::utils::EmptyCommandLine & err ) {
    std::cerr << argv[0] << " -opencl_platform ... -opencl_device ... [-sampling -factor ...] -iterations ... -vector ... -padding ... -max_threads ... -max_items ... -matrix_width ..." << std::endl;
    return 1;
  } catch ( std::exception & err ) {
    std::cerr << err.what() << std::endl;
    return 1;
  }

  cl::Context clContext;
  std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >();
  std::vector< cl::Device > * clDevices = new std::vector< cl::Device >();
  std::vector< std::vector< cl::CommandQueue > > * clQueues = 0;

  // Allocate host memory
  std::vector< inputDataType > input((matrixWidth + 2) * isa::utils::pad(matrixWidth + 2, padding)), output(matrixWidth * isa::utils::pad(matrixWidth, padding)), output_c;
  cl::Buffer input_d, output_d;

  for ( unsigned int y = 0; y < matrixWidth + 2; y++ ) {
    for ( unsigned int x = 0; x < matrixWidth + 2; x++ ) {
      if ( y == 0 || y == (matrixWidth - 1) ) {
        input[(y * isa::utils::pad(matrixWidth + 2, padding)) + x] = 0;
      } else if ( x == 0 || x == (matrixWidth - 1) ) {
        input[(y * isa::utils::pad(matrixWidth + 2, padding)) + x] = 0;
      } else {
        input[(y * isa::utils::pad(matrixWidth + 2, padding)) + x] = uniformDistribution(randomEngine);
      }
    }
  }
  output_c.resize(output.size());

  // Run the control
  TuneBench::stencil2D(input, output_c, matrixWidth, padding);

  // Generate tuning configurations
  std::vector<TuneBench::Stencil2DConf> configurations;
  for ( unsigned int threadsD0 = vectorSize; threadsD0 <= maxThreads; threadsD0 += vectorSize) {
    for ( unsigned int threadsD1 = 1; threadsD0 * threadsD1 <= maxThreads; threadsD1++ ) {
      for ( unsigned int itemsD0 = 1; itemsD0 <= maxItems; itemsD0++ ) {
        if ( matrixWidth % (threadsD0 * itemsD0) != 0 ) {
          continue;
        }
        for ( unsigned int itemsD1 = 1; itemsD0 * itemsD1 <= maxItems; itemsD1++ ) {
          if ( matrixWidth % (threadsD1 * itemsD1) != 0 ) {
            continue;
          }
          for ( unsigned int local = 0; local < 2; local++ ) {
            TuneBench::Stencil2DConf configuration;
            configuration.setLocalMemory(static_cast<bool>(local));
            configuration.setNrThreadsD0(threadsD0);
            configuration.setNrThreadsD1(threadsD1);
            configuration.setNrItemsD0(itemsD0);
            configuration.setNrItemsD1(itemsD1);
            configurations.push_back(configuration);
          }
        }
      }
    }
  }
  if ( samplingFactor < 100 ) {
    unsigned int newSize = static_cast<unsigned int>((configurations.size() * samplingFactor) / 100.0);
    std::shuffle(configurations.begin(), configurations.end(), randomEngine);
    configurations.resize(newSize);
  }

  std::cout << std::fixed << std::endl;
  std::cout << "# matrixWidth *configuration* GFLOP/s time stdDeviation COV" << std::endl << std::endl;

  for ( auto configuration = configurations.begin(); configuration != configurations.end(); ++configuration ) {
    // Generate kernel
    double gflops = isa::utils::giga(static_cast< uint64_t >(matrixWidth) * matrixWidth * 18.0);
    cl::Event clEvent;
    cl::Kernel * kernel;
    isa::utils::Timer timer;
    std::string * code = TuneBench::getStencil2DOpenCL(*configuration, inputDataName, matrixWidth, padding);

    if ( reInit ) {
      delete clQueues;
      clQueues = new std::vector< std::vector< cl::CommandQueue > >();
      isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues);
      try {
        initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), &input, &input_d, &output_d, output.size());
      } catch ( cl::Error & err ) {
        return -1;
      }
      reInit = false;
    }
    try {
      kernel = isa::OpenCL::compile("stencil2D", *code, "-cl-mad-enable -Werror", clContext, clDevices->at(clDeviceID));
    } catch ( isa::OpenCL::OpenCLError & err ) {
      std::cerr << err.what() << std::endl;
      delete code;
      break;
    }
    delete code;

    cl::NDRange global(matrixWidth / (*configuration).getNrItemsD0(), matrixWidth / (*configuration).getNrItemsD1());
    cl::NDRange local((*configuration).getNrThreadsD0(), (*configuration).getNrThreadsD1());

    kernel->setArg(0, input_d);
    kernel->setArg(1, output_d);

    try {
      // Warm-up run
      clQueues->at(clDeviceID)[0].finish();
      clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &clEvent);
      clEvent.wait();
      // Tuning runs
      for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) {
        timer.start();
        clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &clEvent);
        clEvent.wait();
        timer.stop();
      }
      clQueues->at(clDeviceID)[0].enqueueReadBuffer(output_d, CL_TRUE, 0, output.size() * sizeof(inputDataType), reinterpret_cast< void * >(output.data()), 0, &clEvent);
      clEvent.wait();
    } catch ( cl::Error & err ) {
      reInit = true;
      std::cerr << "OpenCL kernel execution error (";
      std::cerr << (*configuration).print();
      std::cerr << "): ";
      std::cerr << isa::utils::toString(err.err()) << std::endl;
      delete kernel;
      if ( err.err() == -4 || err.err() == -61 ) {
        return -1;
      }
      continue;
    }
    delete kernel;

    bool error = false;
    for ( unsigned int y = 0; y < matrixWidth; y++ ) {
      for ( unsigned int x = 0; x < matrixWidth; x++ ) {
        if ( !isa::utils::same(output[(y * isa::utils::pad(matrixWidth, padding)) + x], output_c[(y * isa::utils::pad(matrixWidth, padding)) + x]) ) {
          std::cerr << "Output error (" << (*configuration).print() << ")." << std::endl;
          error = true;
          continue;
        }
      }
      if ( error ) {
        continue;
      }
    }
    if ( error ) {
      continue;
    }

    std::cout << matrixWidth << " ";
    std::cout << (*configuration).print() << " ";
    std::cout << std::setprecision(3);
    std::cout << gflops / timer.getAverageTime() << " ";
    std::cout << std::setprecision(6);
    std::cout << timer.getAverageTime() << " " << timer.getStandardDeviation() << " " << timer.getCoefficientOfVariation() << std::endl;
  }
  std::cout << std::endl;

  return 0;
}

void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< inputDataType > * input, cl::Buffer * input_d, cl::Buffer * output_d, const unsigned int outputSize) {
  try {
    *input_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, input->size() * sizeof(inputDataType), 0, 0);
    *output_d = cl::Buffer(clContext, CL_MEM_WRITE_ONLY, outputSize * sizeof(inputDataType), 0, 0);
    clQueue->enqueueWriteBuffer(*input_d, CL_FALSE, 0, input->size() * sizeof(inputDataType), reinterpret_cast< void * >(input->data()));
    clQueue->finish();
  } catch ( cl::Error & err ) {
    std::cerr << "OpenCL error (memory initialization): " << isa::utils::toString(err.err()) << "." << std::endl;
    throw;
  }
}

<commit_msg>During the output check I need to break.<commit_after>// Copyright 2016 Alessio Sclocco <a.sclocco@vu.nl>
//
// 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 <vector>
#include <iostream>
#include <exception>
#include <iomanip>
#include <random>
#include <algorithm>

#include <configuration.hpp>

#include <ArgumentList.hpp>
#include <InitializeOpenCL.hpp>
#include <Kernel.hpp>
#include <Stencil.hpp>
#include <utils.hpp>
#include <Timer.hpp>
#include <Stats.hpp>

void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< inputDataType > * input, cl::Buffer * input_d, cl::Buffer * output_d, const unsigned int outputSize);

int main(int argc, char * argv[]) {
  bool reInit = true;
  unsigned int nrIterations = 0;
  unsigned int samplingFactor = 100;
  unsigned int clPlatformID = 0;
  unsigned int clDeviceID = 0;
  unsigned int vectorSize = 0;
  unsigned int maxThreads = 0;
  unsigned int maxItems = 0;
  unsigned int matrixWidth = 0;
  unsigned int padding = 0;
  // Random number generation
  std::random_device randomDevice;
  std::default_random_engine randomEngine(randomDevice());
  std::uniform_int_distribution<unsigned int> uniformDistribution(0, magicValue);

  try {
    isa::utils::ArgumentList args(argc, argv);

    clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform");
    clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device");
    if ( args.getSwitch("-sampling") ) {
      samplingFactor = args.getSwitchArgument< unsigned int >("-factor");
    }
    nrIterations = args.getSwitchArgument< unsigned int >("-iterations");
    vectorSize = args.getSwitchArgument< unsigned int >("-vector");
    padding = args.getSwitchArgument< unsigned int >("-padding");
    maxThreads = args.getSwitchArgument< unsigned int >("-max_threads");
    maxItems = args.getSwitchArgument< unsigned int >("-max_items");
    matrixWidth = args.getSwitchArgument< unsigned int >("-matrix_width");
  } catch ( isa::utils::EmptyCommandLine & err ) {
    std::cerr << argv[0] << " -opencl_platform ... -opencl_device ... [-sampling -factor ...] -iterations ... -vector ... -padding ... -max_threads ... -max_items ... -matrix_width ..." << std::endl;
    return 1;
  } catch ( std::exception & err ) {
    std::cerr << err.what() << std::endl;
    return 1;
  }

  cl::Context clContext;
  std::vector< cl::Platform > * clPlatforms = new std::vector< cl::Platform >();
  std::vector< cl::Device > * clDevices = new std::vector< cl::Device >();
  std::vector< std::vector< cl::CommandQueue > > * clQueues = 0;

  // Allocate host memory
  std::vector< inputDataType > input((matrixWidth + 2) * isa::utils::pad(matrixWidth + 2, padding)), output(matrixWidth * isa::utils::pad(matrixWidth, padding)), output_c;
  cl::Buffer input_d, output_d;

  for ( unsigned int y = 0; y < matrixWidth + 2; y++ ) {
    for ( unsigned int x = 0; x < matrixWidth + 2; x++ ) {
      if ( y == 0 || y == (matrixWidth - 1) ) {
        input[(y * isa::utils::pad(matrixWidth + 2, padding)) + x] = 0;
      } else if ( x == 0 || x == (matrixWidth - 1) ) {
        input[(y * isa::utils::pad(matrixWidth + 2, padding)) + x] = 0;
      } else {
        input[(y * isa::utils::pad(matrixWidth + 2, padding)) + x] = uniformDistribution(randomEngine);
      }
    }
  }
  output_c.resize(output.size());

  // Run the control
  TuneBench::stencil2D(input, output_c, matrixWidth, padding);

  // Generate tuning configurations
  std::vector<TuneBench::Stencil2DConf> configurations;
  for ( unsigned int threadsD0 = vectorSize; threadsD0 <= maxThreads; threadsD0 += vectorSize) {
    for ( unsigned int threadsD1 = 1; threadsD0 * threadsD1 <= maxThreads; threadsD1++ ) {
      for ( unsigned int itemsD0 = 1; itemsD0 <= maxItems; itemsD0++ ) {
        if ( matrixWidth % (threadsD0 * itemsD0) != 0 ) {
          continue;
        }
        for ( unsigned int itemsD1 = 1; itemsD0 * itemsD1 <= maxItems; itemsD1++ ) {
          if ( matrixWidth % (threadsD1 * itemsD1) != 0 ) {
            continue;
          }
          for ( unsigned int local = 0; local < 2; local++ ) {
            TuneBench::Stencil2DConf configuration;
            configuration.setLocalMemory(static_cast<bool>(local));
            configuration.setNrThreadsD0(threadsD0);
            configuration.setNrThreadsD1(threadsD1);
            configuration.setNrItemsD0(itemsD0);
            configuration.setNrItemsD1(itemsD1);
            configurations.push_back(configuration);
          }
        }
      }
    }
  }
  if ( samplingFactor < 100 ) {
    unsigned int newSize = static_cast<unsigned int>((configurations.size() * samplingFactor) / 100.0);
    std::shuffle(configurations.begin(), configurations.end(), randomEngine);
    configurations.resize(newSize);
  }

  std::cout << std::fixed << std::endl;
  std::cout << "# matrixWidth *configuration* GFLOP/s time stdDeviation COV" << std::endl << std::endl;

  for ( auto configuration = configurations.begin(); configuration != configurations.end(); ++configuration ) {
    // Generate kernel
    double gflops = isa::utils::giga(static_cast< uint64_t >(matrixWidth) * matrixWidth * 18.0);
    cl::Event clEvent;
    cl::Kernel * kernel;
    isa::utils::Timer timer;
    std::string * code = TuneBench::getStencil2DOpenCL(*configuration, inputDataName, matrixWidth, padding);

    if ( reInit ) {
      delete clQueues;
      clQueues = new std::vector< std::vector< cl::CommandQueue > >();
      isa::OpenCL::initializeOpenCL(clPlatformID, 1, clPlatforms, &clContext, clDevices, clQueues);
      try {
        initializeDeviceMemory(clContext, &(clQueues->at(clDeviceID)[0]), &input, &input_d, &output_d, output.size());
      } catch ( cl::Error & err ) {
        return -1;
      }
      reInit = false;
    }
    try {
      kernel = isa::OpenCL::compile("stencil2D", *code, "-cl-mad-enable -Werror", clContext, clDevices->at(clDeviceID));
    } catch ( isa::OpenCL::OpenCLError & err ) {
      std::cerr << err.what() << std::endl;
      delete code;
      break;
    }
    delete code;

    cl::NDRange global(matrixWidth / (*configuration).getNrItemsD0(), matrixWidth / (*configuration).getNrItemsD1());
    cl::NDRange local((*configuration).getNrThreadsD0(), (*configuration).getNrThreadsD1());

    kernel->setArg(0, input_d);
    kernel->setArg(1, output_d);

    try {
      // Warm-up run
      clQueues->at(clDeviceID)[0].finish();
      clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &clEvent);
      clEvent.wait();
      // Tuning runs
      for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) {
        timer.start();
        clQueues->at(clDeviceID)[0].enqueueNDRangeKernel(*kernel, cl::NullRange, global, local, 0, &clEvent);
        clEvent.wait();
        timer.stop();
      }
      clQueues->at(clDeviceID)[0].enqueueReadBuffer(output_d, CL_TRUE, 0, output.size() * sizeof(inputDataType), reinterpret_cast< void * >(output.data()), 0, &clEvent);
      clEvent.wait();
    } catch ( cl::Error & err ) {
      reInit = true;
      std::cerr << "OpenCL kernel execution error (";
      std::cerr << (*configuration).print();
      std::cerr << "): ";
      std::cerr << isa::utils::toString(err.err()) << std::endl;
      delete kernel;
      if ( err.err() == -4 || err.err() == -61 ) {
        return -1;
      }
      continue;
    }
    delete kernel;

    bool error = false;
    for ( unsigned int y = 0; y < matrixWidth; y++ ) {
      for ( unsigned int x = 0; x < matrixWidth; x++ ) {
        if ( !isa::utils::same(output[(y * isa::utils::pad(matrixWidth, padding)) + x], output_c[(y * isa::utils::pad(matrixWidth, padding)) + x]) ) {
          std::cerr << "Output error (" << (*configuration).print() << ")." << std::endl;
          error = true;
          break;
        }
      }
      if ( error ) {
        break;
      }
    }
    if ( error ) {
      continue;
    }

    std::cout << matrixWidth << " ";
    std::cout << (*configuration).print() << " ";
    std::cout << std::setprecision(3);
    std::cout << gflops / timer.getAverageTime() << " ";
    std::cout << std::setprecision(6);
    std::cout << timer.getAverageTime() << " " << timer.getStandardDeviation() << " " << timer.getCoefficientOfVariation() << std::endl;
  }
  std::cout << std::endl;

  return 0;
}

void initializeDeviceMemory(cl::Context & clContext, cl::CommandQueue * clQueue, std::vector< inputDataType > * input, cl::Buffer * input_d, cl::Buffer * output_d, const unsigned int outputSize) {
  try {
    *input_d = cl::Buffer(clContext, CL_MEM_READ_ONLY, input->size() * sizeof(inputDataType), 0, 0);
    *output_d = cl::Buffer(clContext, CL_MEM_WRITE_ONLY, outputSize * sizeof(inputDataType), 0, 0);
    clQueue->enqueueWriteBuffer(*input_d, CL_FALSE, 0, input->size() * sizeof(inputDataType), reinterpret_cast< void * >(input->data()));
    clQueue->finish();
  } catch ( cl::Error & err ) {
    std::cerr << "OpenCL error (memory initialization): " << isa::utils::toString(err.err()) << "." << std::endl;
    throw;
  }
}

<|endoftext|>


<commit_before>

#include "stdfileio.h"

// For lack of better place to put it...
InputStatus::~InputStatus()
{
}

StdFileInput::StdFileInput(FILE* aFile,InputStatus& aStatus)
    : LispInput(aStatus)
{
    iFile = aFile;
}
StdFileInput::StdFileInput(LispLocalFile& aFile,InputStatus& aStatus)
    : LispInput(aStatus)
{
    iFile = aFile.iFile;
}

LispChar StdFileInput::Next()
{
    LispChar c;
    c=fgetc(iFile);
    if (c == '\n')
        iStatus.NextLine();
    return c;
}

LispChar StdFileInput::Peek()
{
    LispChar c = fgetc(iFile);
    ungetc(c,iFile);
    return c;
}

void StdFileInput::Rewind()
{
    fseek(iFile,0,SEEK_SET);
}

LispBoolean StdFileInput::EndOfStream()
{
    return feof(iFile);
}

LispCharPtr StdFileInput::StartPtr()
{
    LISPASSERT(0);
    return NULL;
}
LispInt StdFileInput::Position()
{
    LISPASSERT(0);
    return 0;
}

StdFileOutput::StdFileOutput(FILE* aFile) : iFile(aFile) { }
StdFileOutput::StdFileOutput(LispLocalFile& aFile) : iFile(aFile.iFile) { }

void StdFileOutput::PutChar(LispChar aChar)
{
    fputc(aChar, iFile);
}

CachedStdFileInput::~CachedStdFileInput()
{
    PlatFree(iBuffer);
}

CachedStdFileInput::CachedStdFileInput(LispLocalFile& aFile,InputStatus& aStatus) : StdFileInput(aFile,aStatus)
{
    // Get size of file
    fseek(iFile,0,SEEK_END);
    iNrBytes = ftell(iFile);
    fseek(iFile,0,SEEK_SET);
    // Read in the full buffer
    iBuffer = PlatAlloc(iNrBytes+1);
    Check(iBuffer!=NULL,KLispErrNotEnoughMemory);
    iCurrentPos = 0;
    fread(iBuffer,iNrBytes,1,iFile);
    iBuffer[iNrBytes] = '\0';
};

LispChar CachedStdFileInput::Next()
{
    LispChar c;
    LISPASSERT(iCurrentPos < iNrBytes);
    c = iBuffer[iCurrentPos++];

    if (c == '\n')
    {
        iStatus.NextLine();
    }
    return c;
}

LispChar CachedStdFileInput::Peek()
{
    LISPASSERT(iCurrentPos < iNrBytes);
    return iBuffer[iCurrentPos];
}

void CachedStdFileInput::Rewind()
{
	iCurrentPos = 0;
}

LispBoolean CachedStdFileInput::EndOfStream()
{
    return (iCurrentPos >= iNrBytes);
}

LispCharPtr CachedStdFileInput::StartPtr()
{
    return iBuffer;
}
LispInt CachedStdFileInput::Position()
{
    return iCurrentPos;
}

void InternalFindFile(LispCharPtr aFileName, InputDirectories& aInputDirectories,
                     LispCharPtr aFoundFile)
{
    strcpy(aFoundFile,aFileName);
    FILE* file = fopen(aFileName,"r");
    LispInt i=0;
    while (file == NULL && i<aInputDirectories.NrItems())
    {
        strcpy(aFoundFile,aInputDirectories[i]->String());
        strcat(aFoundFile,aFileName);
        file = fopen(aFoundFile,"r");
        i++;
    }
    if (file != NULL)
    {
        fclose(file);
    }
    else
    {
        aFoundFile[0] = '\0';
    }
}

LispLocalFile::LispLocalFile(LispEnvironment& aEnvironment,
                             LispCharPtr aFileName, LispBoolean aRead,
                             InputDirectories& aInputDirectories)
: iEnvironment(aEnvironment)
{
    if (aRead)
    {
        LispChar othername[1024];//TODO
        strcpy(othername,aFileName);
        iFile = fopen(aFileName,"r");
        LispInt i=0;
        while (iFile == NULL && i<aInputDirectories.NrItems())
        {
            strcpy(othername,aInputDirectories[i]->String());
            strcat(othername,aFileName);
            iFile = fopen(othername,"r");
            i++;
        }
    }
    else
        iFile = fopen(aFileName,"w");

    if (iFile == NULL)
        iOpened=0;
    else
        iOpened=1;

    SAFEPUSH(iEnvironment,*this);
}

//aRead is for opening in read mode (otherwise opened in write mode)
LispLocalFile::~LispLocalFile()
{
    SAFEPOP(iEnvironment);
    Delete();
}

void LispLocalFile::Delete()
{
    if (iFile)
        fclose(iFile);
    iFile = NULL;
}

CachedStdUserInput::CachedStdUserInput(InputStatus& aStatus) :
StdUserInput(aStatus)
{
//printf("CachedStdUserInput:construct\n");
    Rewind();
};
LispChar CachedStdUserInput::Next()
{
//printf("CachedStdUserInput:Next\n");
    LispChar c = Peek();
    iCurrentPos++;
    printf("%c",c);
    return c;
}

LispChar CachedStdUserInput::Peek()
{
    if (iCurrentPos == iBuffer.NrItems())
    {
        iBuffer.Append(fgetc(iFile));
    }
    return iBuffer[iCurrentPos];
}

LispBoolean CachedStdUserInput::EndOfStream()
{
    return LispFalse;
}

void CachedStdUserInput::Rewind()
{
    // Make sure there is a buffer to point to.
    iBuffer.GrowTo(10);
    iBuffer.SetNrItems(0);
    iCurrentPos=0;
}

LispCharPtr CachedStdUserInput::StartPtr()
{
    if (iBuffer.NrItems() == 0)
        Peek();
    return &iBuffer[0];
}

LispInt CachedStdUserInput::Position()
{
    return iCurrentPos;
}

<commit_msg>Fixed Windows file reading bug (I think).<commit_after>

#include "stdfileio.h"

// For lack of better place to put it...
InputStatus::~InputStatus()
{
}

StdFileInput::StdFileInput(FILE* aFile,InputStatus& aStatus)
    : LispInput(aStatus)
{
    iFile = aFile;
}
StdFileInput::StdFileInput(LispLocalFile& aFile,InputStatus& aStatus)
    : LispInput(aStatus)
{
    iFile = aFile.iFile;
}

LispChar StdFileInput::Next()
{
    LispChar c;
    c=fgetc(iFile);
    if (c == '\n')
        iStatus.NextLine();
    return c;
}

LispChar StdFileInput::Peek()
{
    LispChar c = fgetc(iFile);
    ungetc(c,iFile);
    return c;
}

void StdFileInput::Rewind()
{
    fseek(iFile,0,SEEK_SET);
}

LispBoolean StdFileInput::EndOfStream()
{
    return feof(iFile);
}

LispCharPtr StdFileInput::StartPtr()
{
    LISPASSERT(0);
    return NULL;
}
LispInt StdFileInput::Position()
{
    LISPASSERT(0);
    return 0;
}

StdFileOutput::StdFileOutput(FILE* aFile) : iFile(aFile) { }
StdFileOutput::StdFileOutput(LispLocalFile& aFile) : iFile(aFile.iFile) { }

void StdFileOutput::PutChar(LispChar aChar)
{
    fputc(aChar, iFile);
}

CachedStdFileInput::~CachedStdFileInput()
{
    PlatFree(iBuffer);
}

CachedStdFileInput::CachedStdFileInput(LispLocalFile& aFile,InputStatus& aStatus) : StdFileInput(aFile,aStatus)
{
    // Get size of file
    fseek(iFile,0,SEEK_END);
    iNrBytes = ftell(iFile);
    fseek(iFile,0,SEEK_SET);
    // Read in the full buffer
    iBuffer = PlatAlloc(iNrBytes+1);
    Check(iBuffer!=NULL,KLispErrNotEnoughMemory);
    iCurrentPos = 0;
    fread(iBuffer,iNrBytes,1,iFile);
    iBuffer[iNrBytes] = '\0';
};

LispChar CachedStdFileInput::Next()
{
    LispChar c;
    LISPASSERT(iCurrentPos < iNrBytes);
    c = iBuffer[iCurrentPos++];

    if (c == '\n')
    {
        iStatus.NextLine();
    }
    return c;
}

LispChar CachedStdFileInput::Peek()
{
    LISPASSERT(iCurrentPos < iNrBytes);
    return iBuffer[iCurrentPos];
}

void CachedStdFileInput::Rewind()
{
	iCurrentPos = 0;
}

LispBoolean CachedStdFileInput::EndOfStream()
{
    return (iCurrentPos >= iNrBytes);
}

LispCharPtr CachedStdFileInput::StartPtr()
{
    return iBuffer;
}
LispInt CachedStdFileInput::Position()
{
    return iCurrentPos;
}

void InternalFindFile(LispCharPtr aFileName, InputDirectories& aInputDirectories,
                     LispCharPtr aFoundFile)
{
    strcpy(aFoundFile,aFileName);
    FILE* file = fopen(aFileName,"rb");
    LispInt i=0;
    while (file == NULL && i<aInputDirectories.NrItems())
    {
        strcpy(aFoundFile,aInputDirectories[i]->String());
        strcat(aFoundFile,aFileName);
        file = fopen(aFoundFile,"rb");
        i++;
    }
    if (file != NULL)
    {
        fclose(file);
    }
    else
    {
        aFoundFile[0] = '\0';
    }
}

LispLocalFile::LispLocalFile(LispEnvironment& aEnvironment,
                             LispCharPtr aFileName, LispBoolean aRead,
                             InputDirectories& aInputDirectories)
: iEnvironment(aEnvironment)
{
    if (aRead)
    {
        LispChar othername[1024];//TODO
        strcpy(othername,aFileName);
        iFile = fopen(aFileName,"rb");
        LispInt i=0;
        while (iFile == NULL && i<aInputDirectories.NrItems())
        {
            strcpy(othername,aInputDirectories[i]->String());
            strcat(othername,aFileName);
            iFile = fopen(othername,"rb");
            i++;
        }
    }
    else
        iFile = fopen(aFileName,"w");

    if (iFile == NULL)
        iOpened=0;
    else
        iOpened=1;

    SAFEPUSH(iEnvironment,*this);
}

//aRead is for opening in read mode (otherwise opened in write mode)
LispLocalFile::~LispLocalFile()
{
    SAFEPOP(iEnvironment);
    Delete();
}

void LispLocalFile::Delete()
{
    if (iFile)
        fclose(iFile);
    iFile = NULL;
}

CachedStdUserInput::CachedStdUserInput(InputStatus& aStatus) :
StdUserInput(aStatus)
{
//printf("CachedStdUserInput:construct\n");
    Rewind();
};
LispChar CachedStdUserInput::Next()
{
//printf("CachedStdUserInput:Next\n");
    LispChar c = Peek();
    iCurrentPos++;
    printf("%c",c);
    return c;
}

LispChar CachedStdUserInput::Peek()
{
    if (iCurrentPos == iBuffer.NrItems())
    {
        iBuffer.Append(fgetc(iFile));
    }
    return iBuffer[iCurrentPos];
}

LispBoolean CachedStdUserInput::EndOfStream()
{
    return LispFalse;
}

void CachedStdUserInput::Rewind()
{
    // Make sure there is a buffer to point to.
    iBuffer.GrowTo(10);
    iBuffer.SetNrItems(0);
    iCurrentPos=0;
}

LispCharPtr CachedStdUserInput::StartPtr()
{
    if (iBuffer.NrItems() == 0)
        Peek();
    return &iBuffer[0];
}

LispInt CachedStdUserInput::Position()
{
    return iCurrentPos;
}

<|endoftext|>